input
stringlengths
2.65k
237k
output
stringclasses
1 value
""" Defines the basic objects for CORE emulation: the PyCoreObj base class, along with PyCoreNode, PyCoreNet, and PyCoreNetIf. """ import os import shutil import socket import threading from socket import AF_INET from socket import AF_INET6 from core.data import NodeData, LinkData from core.enumerations import LinkTypes from core.misc import ipaddress class Position(object): """ Helper class for Cartesian coordinate position """ def __init__(self, x=None, y=None, z=None): """ Creates a Position instance. :param x: x position :param y: y position :param z: z position :return: """ self.x = x self.y = y self.z = z def set(self, x=None, y=None, z=None): """ Returns True if the position has actually changed. :param float x: x position :param float y: y position :param float z: z position :return: True if position changed, False otherwise :rtype: bool """ if self.x == x and self.y == y and self.z == z: return False self.x = x self.y = y self.z = z return True def get(self): """ Retrieve x,y,z position. :return: x,y,z position tuple :rtype: tuple """ return self.x, self.y, self.z class PyCoreObj(object): """ Base class for CORE objects (nodes and networks) """ apitype = None # TODO: appears start has no usage, verify and remove def __init__(self, session, objid=None, name=None, start=True): """ Creates a PyCoreObj instance. :param core.session.Session session: CORE session object :param int objid: object id :param str name: object name :param bool start: start value :return: """ self.session = session if objid is None: objid = session.get_object_id() self.objid = objid if name is None: name = "o%s" % self.objid self.name = name self.type = None self.server = None self.services = None # ifindex is key, PyCoreNetIf instance is value self._netif = {} self.ifindex = 0 self.canvas = None self.icon = None self.opaque = None self.position = Position() def startup(self): """ Each object implements its own startup method. :return: nothing """ raise NotImplementedError def shutdown(self): """ Each object implements its own shutdown method. :return: nothing """ raise NotImplementedError def setposition(self, x=None, y=None, z=None): """ Set the (x,y,z) position of the object. :param float x: x position :param float y: y position :param float z: z position :return: True if position changed, False otherwise :rtype: bool """ return self.position.set(x=x, y=y, z=z) def getposition(self): """ Return an (x,y,z) tuple representing this object's position. :return: x,y,z position tuple :rtype: tuple """ return self.position.get() def ifname(self, ifindex): """ Retrieve interface name for index. :param int ifindex: interface index :return: interface name :rtype: str """ return self._netif[ifindex].name def netifs(self, sort=False): """ Retrieve network interfaces, sorted if desired. :param bool sort: boolean used to determine if interfaces should be sorted :return: network interfaces :rtype: list """ if sort: return map(lambda k: self._netif[k], sorted(self._netif.keys())) else: return self._netif.itervalues() def numnetif(self): """ Return the attached interface count. :return: number of network interfaces :rtype: int """ return len(self._netif) def getifindex(self, netif): """ Retrieve index for an interface. :param PyCoreNetIf netif: interface to get index for :return: interface index if found, -1 otherwise :rtype: int """ for ifindex in self._netif: if self._netif[ifindex] is netif: return ifindex return -1 def newifindex(self): """ Create a new interface index. :return: interface index :rtype: int """ while self.ifindex in self._netif: self.ifindex += 1 ifindex = self.ifindex self.ifindex += 1 return ifindex def data(self, message_type, lat=None, lon=None, alt=None): """ Build a data object for this node. :param message_type: purpose for the data object we are creating :param str lat: latitude :param str lon: longitude :param str alt: altitude :return: node data object :rtype: core.data.NodeData """ if self.apitype is None: return None x, y, _ = self.getposition() model = self.type emulation_server = self.server services = self.services if services is not None: services = "|".join([service.name for service in services]) node_data = NodeData( message_type=message_type, id=self.objid, node_type=self.apitype, name=self.name, emulation_id=self.objid, canvas=self.canvas, icon=self.icon, opaque=self.opaque, x_position=x, y_position=y, latitude=lat, longitude=lon, altitude=alt, model=model, emulation_server=emulation_server, services=services ) return node_data def all_link_data(self, flags): """ Build CORE Link data for this object. There is no default method for PyCoreObjs as PyCoreNodes do not implement this but PyCoreNets do. :param flags: message flags :return: list of link data :rtype: core.data.LinkData """ return [] class PyCoreNode(PyCoreObj): """ Base class for CORE nodes. """ def __init__(self, session, objid=None, name=None, start=True): """ Create a PyCoreNode instance. :param core.session.Session session: CORE session object :param int objid: object id :param str name: object name :param bool start: boolean for starting """ super(PyCoreNode, self).__init__(session, objid, name, start=start) self.services = [] self.nodedir = None self.tmpnodedir = False def addservice(self, service): """ Add a services to the service list. :param core.service.CoreService service: service to add :return: nothing """ if service is not None: self.services.append(service) def makenodedir(self): """ Create the node directory. :return: nothing """ if self.nodedir is None: self.nodedir = os.path.join(self.session.session_dir, self.name + ".conf") os.makedirs(self.nodedir) self.tmpnodedir = True else: self.tmpnodedir = False def rmnodedir(self): """ Remove the node directory, unless preserve directory has been set. :return: nothing """ preserve = self.session.options.get_config("preservedir") == "1" if preserve: return if self.tmpnodedir: shutil.rmtree(self.nodedir, ignore_errors=True) def addnetif(self, netif, ifindex): """ Add network interface to node and set the network interface index if successful. :param PyCoreNetIf netif: network interface to add :param int ifindex: interface index :return: nothing """ if ifindex in self._netif: raise ValueError("ifindex %s already exists" % ifindex) self._netif[ifindex] = netif # TODO: this should have probably been set ahead, seems bad to me, check for failure and fix netif.netindex = ifindex def delnetif(self, ifindex): """ Delete a network interface :param int ifindex: interface index to delete :return: nothing """ if ifindex not in self._netif: raise ValueError("ifindex %s does not exist" % ifindex) netif = self._netif.pop(ifindex) netif.shutdown() del netif # TODO: net parameter is not used, remove def netif(self, ifindex, net=None): """ Retrieve network interface. :param int ifindex: index of interface to retrieve :param PyCoreNetIf net: network node :return: network interface, or None if not found :rtype: PyCoreNetIf """ if ifindex in self._netif: return self._netif[ifindex] else: return None def attachnet(self, ifindex, net): """ Attach a network. :param int ifindex: interface of index to attach :param PyCoreNetIf net: network to attach :return: """ if ifindex not in self._netif: raise ValueError("ifindex %s does not exist" % ifindex) self._netif[ifindex].attachnet(net) def detachnet(self, ifindex): """ Detach network interface. :param int ifindex: interface index to detach :return: nothing """ if ifindex not in self._netif: raise ValueError("ifindex %s does not exist" % ifindex) self._netif[ifindex].detachnet() def setposition(self, x=None, y=None, z=None): """ Set position. :param x: x position :param y: y position :param z: z position :return: nothing """ changed = super(PyCoreNode, self).setposition(x, y, z) if changed: for netif in self.netifs(sort=True): netif.setposition(x, y, z) def commonnets(self, obj, want_ctrl=False): """ Given another node or net object, return common networks between this node and that object. A list of tuples is returned, with each tuple consisting of (network, interface1, interface2). :param obj: object to get common network with :param want_ctrl: flag set to determine if control network are wanted :return: tuples of common networks :rtype: list """ common = [] for netif1 in self.netifs(): if not want_ctrl and hasattr(netif1, "control"): continue for netif2 in obj.netifs(): if netif1.net == netif2.net: common.append((netif1.net, netif1, netif2)) return common def check_cmd(self, args): """ Runs shell command on node. :param list[str]|str args: command to run :return: combined stdout and stderr :rtype: str :raises CoreCommandError: when a non-zero exit status occurs """ raise NotImplementedError def cmd(self, args, wait=True): """ Runs shell command on node, with option to not wait for a result. :param list[str]|str args: command to run :param bool wait: wait for command to exit, defaults to True :return: exit status for command :rtype: int """ raise NotImplementedError def cmd_output(self, args): """ Runs shell command on node and get exit status and output. :param list[str]|str args: command to run :return: exit status and combined stdout and stderr :rtype: tuple[int, str] """ raise NotImplementedError def termcmdstring(self, sh): """ Create a terminal command string. :param str sh: shell to execute command in :return: str """ raise NotImplementedError class PyCoreNet(PyCoreObj): """ Base class for
import asyncio import logging import time from pathlib import Path from typing import List, Optional, Tuple, Dict, Callable from src.util.byte_types import hexstr_to_bytes from src.util.keychain import ( generate_mnemonic, bytes_to_mnemonic, ) from src.util.path import path_from_root from src.util.ws_message import create_payload from src.cmds.init import check_keys from src.server.outbound_message import NodeType, OutboundMessage, Message, Delivery from src.simulator.simulator_protocol import FarmNewBlockProtocol from src.util.ints import uint64, uint32 from src.wallet.trade_record import TradeRecord from src.wallet.util.cc_utils import trade_record_to_dict from src.wallet.util.wallet_types import WalletType from src.wallet.rl_wallet.rl_wallet import RLWallet from src.wallet.cc_wallet.cc_wallet import CCWallet from src.wallet.wallet_info import WalletInfo from src.wallet.wallet_node import WalletNode from src.types.mempool_inclusion_status import MempoolInclusionStatus # Timeout for response from wallet/full node for sending a transaction TIMEOUT = 30 log = logging.getLogger(__name__) class WalletRpcApi: def __init__(self, wallet_node: WalletNode): self.service = wallet_node self.service_name = "chia-wallet" def get_routes(self) -> Dict[str, Callable]: return { "/get_wallet_balance": self.get_wallet_balance, "/send_transaction": self.send_transaction, "/get_next_puzzle_hash": self.get_next_puzzle_hash, "/get_transactions": self.get_transactions, "/farm_block": self.farm_block, "/get_sync_status": self.get_sync_status, "/get_height_info": self.get_height_info, "/create_new_wallet": self.create_new_wallet, "/get_wallets": self.get_wallets, "/rl_set_admin_info": self.rl_set_admin_info, "/rl_set_user_info": self.rl_set_user_info, "/cc_set_name": self.cc_set_name, "/cc_get_name": self.cc_get_name, "/cc_spend": self.cc_spend, "/cc_get_colour": self.cc_get_colour, "/create_offer_for_ids": self.create_offer_for_ids, "/get_discrepancies_for_offer": self.get_discrepancies_for_offer, "/respond_to_offer": self.respond_to_offer, "/get_wallet_summaries": self.get_wallet_summaries, "/get_public_keys": self.get_public_keys, "/generate_mnemonic": self.generate_mnemonic, "/log_in": self.log_in, "/add_key": self.add_key, "/delete_key": self.delete_key, "/delete_all_keys": self.delete_all_keys, "/get_private_key": self.get_private_key, "/get_trade": self.get_trade, "/get_all_trades": self.get_all_trades, "/cancel_trade": self.cancel_trade, } async def get_trade(self, request: Dict): if self.service is None: return {"success": False} if self.service.wallet_state_manager is None: return {"success": False} trade_mgr = self.service.wallet_state_manager.trade_manager trade_id = request["trade_id"] trade: Optional[TradeRecord] = await trade_mgr.get_trade_by_id(trade_id) if trade is None: response = { "success": False, "error": f"No trade with trade id: {trade_id}", } return response result = trade_record_to_dict(trade) response = {"success": True, "trade": result} return response async def get_all_trades(self, request: Dict): if self.service is None: return {"success": False} if self.service.wallet_state_manager is None: return {"success": False} trade_mgr = self.service.wallet_state_manager.trade_manager all_trades = await trade_mgr.get_all_trades() result = [] for trade in all_trades: result.append(trade_record_to_dict(trade)) response = {"success": True, "trades": result} return response async def cancel_trade(self, request: Dict): if self.service is None: return {"success": False} if self.service.wallet_state_manager is None: return {"success": False} wsm = self.service.wallet_state_manager secure = request["secure"] trade_id = hexstr_to_bytes(request["trade_id"]) if secure: await wsm.trade_manager.cancel_pending_offer_safely(trade_id) else: await wsm.trade_manager.cancel_pending_offer(trade_id) response = {"success": True} return response async def _state_changed(self, *args) -> List[str]: if len(args) < 2: return [] change = args[0] wallet_id = args[1] data = { "state": change, } if wallet_id is not None: data["wallet_id"] = wallet_id return [create_payload("state_changed", data, "chia-wallet", "wallet_ui")] async def get_next_puzzle_hash(self, request: Dict) -> Dict: """ Returns a new puzzlehash """ if self.service is None: return {"success": False} wallet_id = uint32(int(request["wallet_id"])) if self.service.wallet_state_manager is None: return {"success": False} wallet = self.service.wallet_state_manager.wallets[wallet_id] if wallet.wallet_info.type == WalletType.STANDARD_WALLET: puzzle_hash = (await wallet.get_new_puzzlehash()).hex() elif wallet.wallet_info.type == WalletType.COLOURED_COIN: puzzle_hash = await wallet.get_new_inner_hash() response = { "wallet_id": wallet_id, "puzzle_hash": puzzle_hash, } return response async def send_transaction(self, request): wallet_id = int(request["wallet_id"]) wallet = self.service.wallet_state_manager.wallets[wallet_id] try: tx = await wallet.generate_signed_transaction_dict(request) except Exception as e: data = { "status": "FAILED", "reason": f"Failed to generate signed transaction {e}", } return data if tx is None: data = { "status": "FAILED", "reason": "Failed to generate signed transaction", } return data try: await wallet.push_transaction(tx) except Exception as e: data = { "status": "FAILED", "reason": f"Failed to push transaction {e}", } return data sent = False start = time.time() while time.time() - start < TIMEOUT: sent_to: List[ Tuple[str, MempoolInclusionStatus, Optional[str]] ] = await self.service.wallet_state_manager.get_transaction_status( tx.name() ) if len(sent_to) == 0: await asyncio.sleep(1) continue status, err = sent_to[0][1], sent_to[0][2] if status == MempoolInclusionStatus.SUCCESS: data = {"status": "SUCCESS"} sent = True break elif status == MempoolInclusionStatus.PENDING: assert err is not None data = {"status": "PENDING", "reason": err} sent = True break elif status == MempoolInclusionStatus.FAILED: assert err is not None data = {"status": "FAILED", "reason": err} sent = True break if not sent: data = { "status": "FAILED", "reason": "Timed out. Transaction may or may not have been sent.", } return data async def get_transactions(self, request): wallet_id = int(request["wallet_id"]) transactions = await self.service.wallet_state_manager.get_all_transactions( wallet_id ) response = {"success": True, "txs": transactions, "wallet_id": wallet_id} return response async def farm_block(self, request): puzzle_hash = bytes.fromhex(request["puzzle_hash"]) request = FarmNewBlockProtocol(puzzle_hash) msg = OutboundMessage( NodeType.FULL_NODE, Message("farm_new_block", request), Delivery.BROADCAST, ) self.service.server.push_message(msg) return {"success": True} async def get_wallet_balance(self, request: Dict): if self.service.wallet_state_manager is None: return {"success": False} wallet_id = uint32(int(request["wallet_id"])) wallet = self.service.wallet_state_manager.wallets[wallet_id] balance = await wallet.get_confirmed_balance() pending_balance = await wallet.get_unconfirmed_balance() spendable_balance = await wallet.get_spendable_balance() pending_change = await wallet.get_pending_change_balance() if wallet.wallet_info.type == WalletType.COLOURED_COIN: frozen_balance = 0 else: frozen_balance = await wallet.get_frozen_amount() response = { "wallet_id": wallet_id, "success": True, "confirmed_wallet_balance": balance, "unconfirmed_wallet_balance": pending_balance, "spendable_balance": spendable_balance, "frozen_balance": frozen_balance, "pending_change": pending_change, } return response async def get_sync_status(self, request: Dict): if self.service.wallet_state_manager is None: return {"success": False} syncing = self.service.wallet_state_manager.sync_mode return {"success": True, "syncing": syncing} async def get_height_info(self, request: Dict): if self.service.wallet_state_manager is None: return {"success": False} lca = self.service.wallet_state_manager.lca height = self.service.wallet_state_manager.block_records[lca].height response = {"success": True, "height": height} return response async def create_new_wallet(self, request): config, wallet_state_manager, main_wallet = self.get_wallet_config() if request["wallet_type"] == "cc_wallet": if request["mode"] == "new": try: cc_wallet: CCWallet = await CCWallet.create_new_cc( wallet_state_manager, main_wallet, request["amount"] ) return {"success": True, "type": cc_wallet.wallet_info.type.name} except Exception as e: log.error("FAILED {e}") return {"success": False, "reason": str(e)} elif request["mode"] == "existing": try: cc_wallet = await CCWallet.create_wallet_for_cc( wallet_state_manager, main_wallet, request["colour"] ) return {"success": True, "type": cc_wallet.wallet_info.type.name} except Exception as e: log.error("FAILED2 {e}") return {"success": False, "reason": str(e)} def get_wallet_config(self): return ( self.service.config, self.service.wallet_state_manager, self.service.wallet_state_manager.main_wallet, ) async def get_wallets(self, request: Dict): if self.service.wallet_state_manager is None: return {"success": False} wallets: List[ WalletInfo ] = await self.service.wallet_state_manager.get_all_wallets() response = {"wallets": wallets, "success": True} return response async def rl_set_admin_info(self, request): wallet_id = int(request["wallet_id"]) wallet: RLWallet = self.service.wallet_state_manager.wallets[wallet_id] user_pubkey = request["user_pubkey"] limit = uint64(int(request["limit"])) interval = uint64(int(request["interval"])) amount = uint64(int(request["amount"])) success = await wallet.admin_create_coin(interval, limit, user_pubkey, amount) response = {"success": success} return response async def rl_set_user_info(self, request): wallet_id = int(request["wallet_id"]) wallet: RLWallet = self.service.wallet_state_manager.wallets[wallet_id] admin_pubkey = request["admin_pubkey"] limit = uint64(int(request["limit"])) interval = uint64(int(request["interval"])) origin_id = request["origin_id"] success = await wallet.set_user_info(interval, limit, origin_id, admin_pubkey) response = {"success": success} return response async def cc_set_name(self, request): wallet_id = int(request["wallet_id"]) wallet: CCWallet = self.service.wallet_state_manager.wallets[wallet_id] await wallet.set_name(str(request["name"])) response = {"wallet_id": wallet_id, "success": True} return response async def cc_get_name(self, request): wallet_id = int(request["wallet_id"]) wallet: CCWallet = self.service.wallet_state_manager.wallets[wallet_id] name: str = await wallet.get_name() response = {"wallet_id": wallet_id, "name": name} return response async def cc_spend(self, request): wallet_id = int(request["wallet_id"]) wallet: CCWallet = self.service.wallet_state_manager.wallets[wallet_id] puzzle_hash = hexstr_to_bytes(request["innerpuzhash"]) try: tx = await wallet.generate_signed_transaction( request["amount"], puzzle_hash ) except Exception as e: data = { "status": "FAILED", "reason": f"{e}", } return data if tx is None: data = { "status": "FAILED", "reason": "Failed to generate signed transaction", } return data try: await wallet.wallet_state_manager.add_pending_transaction(tx) except Exception as e: data = { "status": "FAILED", "reason": f"Failed to push transaction {e}", } return data sent = False start = time.time() while time.time() - start < TIMEOUT: sent_to: List[ Tuple[str, MempoolInclusionStatus, Optional[str]] ] = await self.service.wallet_state_manager.get_transaction_status( tx.name() ) if len(sent_to) == 0: await asyncio.sleep(0.1) continue status, err = sent_to[0][1], sent_to[0][2] if status == MempoolInclusionStatus.SUCCESS: data = {"status": "SUCCESS"} sent = True break elif status == MempoolInclusionStatus.PENDING: assert err is not None data = {"status": "PENDING", "reason": err} sent = True break elif status == MempoolInclusionStatus.FAILED: assert err is not None data = {"status": "FAILED", "reason": err} sent = True break if not sent: data = { "status": "FAILED", "reason": "Timed out. Transaction may or may not have been sent.", } return data async def cc_get_colour(self, request): wallet_id = int(request["wallet_id"]) wallet: CCWallet = self.service.wallet_state_manager.wallets[wallet_id] colour: str = await wallet.get_colour() response = {"colour": colour, "wallet_id": wallet_id} return response async def get_wallet_summaries(self, request: Dict): if self.service.wallet_state_manager is None: return {"success": False} response = {} for wallet_id in self.service.wallet_state_manager.wallets: wallet = self.service.wallet_state_manager.wallets[wallet_id] balance = await wallet.get_confirmed_balance() type = wallet.wallet_info.type if type == WalletType.COLOURED_COIN: name = wallet.cc_info.my_colour_name colour = await wallet.get_colour() response[wallet_id] = { "type": type, "balance": balance, "name": name, "colour": colour, } else: response[wallet_id] = {"type": type, "balance": balance} return response async def get_discrepancies_for_offer(self, request): file_name = request["filename"] file_path = Path(file_name) ( success, discrepancies, error, ) = await self.service.wallet_state_manager.trade_manager.get_discrepancies_for_offer( file_path ) if success: response = {"success": True, "discrepancies": discrepancies} else: response = {"success": False, "error": error} return response async def create_offer_for_ids(self, request): offer = request["ids"] file_name = request["filename"] ( success, spend_bundle, error, ) = await
"""Library implementing various Lasagne layers. """ import lasagne import numpy as np import theano import theano.tensor as T from lasagne.layers import Conv1DLayer from lasagne.layers.dnn import Conv2DDNNLayer from theano.sandbox.cuda import dnn import theano_printer import utils class MuLogSigmaErfLayer(lasagne.layers.Layer): def get_output_shape_for(self, input_shape): return (input_shape[0], 600) def get_output_for(self, input, **kwargs): eps = 1e-7 x_axis = theano.shared(np.arange(0, 600, dtype='float32')).dimshuffle('x',0) # This needs to be clipped to avoid NaN's! sigma = T.exp(T.clip(input[:,1].dimshuffle(0,'x'), -10, 10)) #theano_printer.print_me_this("sigma", sigma) x = (x_axis - input[:,0].dimshuffle(0,'x')) / (sigma * np.sqrt(2).astype('float32')) return (T.erf(x) + 1)/2 class MuSigmaErfLayer(lasagne.layers.Layer): def get_output_shape_for(self, input_shape): return (input_shape[0], 600) def get_output_for(self, input, eps=1e-7, **kwargs): x_axis = theano.shared(np.arange(0, 600, dtype='float32')).dimshuffle('x',0) sigma = input[:,1].dimshuffle(0,'x') x = (x_axis - input[:,0].dimshuffle(0,'x')) / (sigma * np.sqrt(2).astype('float32')) return (T.erf(x) + 1.0)/2.0 class MuConstantSigmaErfLayer(lasagne.layers.Layer): def __init__(self, incoming, sigma=0.0, **kwargs): super(MuConstantSigmaErfLayer, self).__init__(incoming, **kwargs) eps = 1e-7 if sigma>=eps: self.sigma = theano.shared(np.float32(sigma)).dimshuffle('x', 'x') else: self.sigma = theano.shared(np.float32(eps)).dimshuffle('x', 'x') def get_output_shape_for(self, input_shape): return (input_shape[0], 600) def get_output_for(self, input, **kwargs): x_axis = theano.shared(np.arange(0, 600, dtype='float32')).dimshuffle('x', 0) x = (x_axis - input[:,0].dimshuffle(0, 'x')) / (self.sigma * np.sqrt(2).astype('float32')) return (T.erf(x) + 1)/2 class CumSumLayer(lasagne.layers.Layer): def __init__(self, incoming, axis=1, **kwargs): super(CumSumLayer, self).__init__(incoming, **kwargs) self.axis = axis def get_output_shape_for(self, input_shape): return input_shape def get_output_for(self, input, **kwargs): result = T.extra_ops.cumsum(input, axis=self.axis) # theano_printer.print_me_this("result", result) return result class ScaleLayer(lasagne.layers.MergeLayer): def __init__(self, input, scale, **kwargs): incomings = [input, scale] super(ScaleLayer, self).__init__(incomings, **kwargs) def get_output_shape_for(self, input_shapes): return input_shapes[0] def get_output_for(self, inputs, **kwargs): # take the minimal working slice size, and use that one. return inputs[0] * T.shape_padright(inputs[1], n_ones=inputs[0].ndim-inputs[1].ndim) class LogicalNotLayer(lasagne.layers.Layer): def __init__(self, incoming, **kwargs): super(LogicalNotLayer, self).__init__(incoming, **kwargs) def get_output_shape_for(self, input_shape): return input_shape def get_output_for(self, input, **kwargs): # take the minimal working slice size, and use that one. return 1 - input class NormalisationLayer(lasagne.layers.Layer): """Layer which normalises the input over the first axis. Normalisation is achieved by simply dividing by the sum. """ def __init__(self, incoming, norm_sum=1.0, allow_negative=False, **kwargs): super(NormalisationLayer, self).__init__(incoming, **kwargs) self.norm_sum = norm_sum self.allow_negative = allow_negative def get_output_for(self, input, **kwargs): # take the minimal working slice size, and use that one. if self.allow_negative: inp_low_zero = input - T.min(input, axis=1).dimshuffle(0, 'x') else: inp_low_zero = input return inp_low_zero / T.sum(inp_low_zero, axis=1).dimshuffle(0, 'x') * self.norm_sum class WideConv2DDNNLayer(Conv2DDNNLayer): def __init__(self, incoming, num_filters, filter_size, skip=0, **kwargs): super(WideConv2DDNNLayer, self).__init__(incoming, num_filters, filter_size=filter_size, **kwargs) self.skip = skip def convolve(self, input, **kwargs): # by default we assume 'cross', consistent with corrmm. conv_mode = 'conv' if self.flip_filters else 'cross' border_mode = self.pad if border_mode == 'same': border_mode = tuple(s // 2 for s in self.filter_size) else: raise NotImplementedError("Only border_mode 'same' has been implemented") target_shape = self.input_shape[:2] + (self.input_shape[2]//self.skip, self.skip,) \ + (self.input_shape[3]//self.skip, self.skip,) input = input.reshape(target_shape).dimshuffle(0,3,5,1,2,4) target_shape = (self.input_shape[0]*self.skip**2, self.input_shape[1], self.input_shape[2]//self.skip, self.input_shape[3]//self.skip) input = input.reshape(target_shape) conved = dnn.dnn_conv(img=input, kerns=self.W, subsample=self.stride, border_mode=border_mode, conv_mode=conv_mode ) target_shape = (self.input_shape[0], self.skip, self.skip, self.num_filters, self.input_shape[2]//self.skip, self.input_shape[3]//self.skip) conved = conved.reshape(target_shape).dimshuffle(0,3,4,1,5,2) target_shape = (self.input_shape[0], self.num_filters, self.input_shape[2], self.input_shape[3]) conved = conved.reshape(target_shape) return conved class JeroenLayer(lasagne.layers.MergeLayer): """This layer doesn't overfit; it already knows what to do. Estimates the volume between slices using a truncated cone approximation. incomings = [mu_area, sigma_area, is_not_padded, slicelocs] output = N x 2 array, with mu = output[:, 0] and sigma = output[:, 1] """ def __init__(self, incomings, rescale_input=1.0, **kwargs): super(JeroenLayer, self).__init__(incomings, **kwargs) self.rescale_input = rescale_input def get_output_shape_for(self, input_shapes): return (input_shapes[0][0], 2) def get_output_for(self, inputs, **kwargs): mu_area, sigma_area, is_not_padded, slicelocs = inputs # Rescale input mu_area = mu_area / self.rescale_input sigma_area = sigma_area / self.rescale_input # For each slice pair, compute if both of them are valid is_pair_not_padded = is_not_padded[:, :-1] + is_not_padded[:, 1:] > 1.5 # Compute the distance between slices h = abs(slicelocs[:, :-1] - slicelocs[:, 1:]) # Compute mu for each slice pair m1 = mu_area[:, :-1] m2 = mu_area[:, 1:] eps = 1e-2 mu_volumes = (m1 + m2 + T.sqrt(T.clip(m1*m2, eps, utils.maxfloat))) * h / 3.0 mu_volumes = mu_volumes * is_pair_not_padded # Compute sigma for each slice pair s1 = sigma_area[:, :-1] s2 = sigma_area[:, 1:] sigma_volumes = h*(s1 + s2) / 3.0 sigma_volumes = sigma_volumes * is_pair_not_padded # Compute mu and sigma per patient mu_volume_patient = T.sum(mu_volumes, axis=1) sigma_volume_patient = T.sqrt(T.clip(T.sum(sigma_volumes**2, axis=1), eps, utils.maxfloat)) # Concat and return return T.concatenate([ mu_volume_patient.dimshuffle(0, 'x'), sigma_volume_patient.dimshuffle(0, 'x')], axis=1) class JeroenLayerDists(lasagne.layers.MergeLayer): """JeroenLayer using better distances. This layer expects the distances between slices as an input, so computing or estimating the distances offloaded to other modules. This allows exploration of alternative ways to compute slice distances. """ def __init__(self, incomings, rescale_input=1.0, **kwargs): super(JeroenLayerDists, self).__init__(incomings, **kwargs) self.rescale_input = rescale_input def get_output_shape_for(self, input_shapes): return (input_shapes[0][0], 2) def get_output_for(self, inputs, **kwargs): mu_area, sigma_area, is_not_padded, slicedists = inputs # Rescale input mu_area = mu_area / self.rescale_input sigma_area = sigma_area / self.rescale_input # For each slice pair, compute if both of them are valid is_pair_not_padded = is_not_padded[:, :-1] + is_not_padded[:, 1:] > 1.5 # Compute the distance between slices h = slicedists[:, :-1] # Compute mu for each slice pair m1 = mu_area[:, :-1] m2 = mu_area[:, 1:] eps = 1e-2 mu_volumes = (m1 + m2 + T.sqrt(T.clip(m1*m2, eps, utils.maxfloat))) * h / 3.0 mu_volumes = mu_volumes * is_pair_not_padded # Compute sigma for each slice pair s1 = sigma_area[:, :-1] s2 = sigma_area[:, 1:] sigma_volumes = h*(s1 + s2) / 3.0 sigma_volumes = sigma_volumes * is_pair_not_padded # Compute mu and sigma per patient mu_volume_patient = T.sum(mu_volumes, axis=1) sigma_volume_patient = T.sqrt(T.clip(T.sum(sigma_volumes**2, axis=1), eps, utils.maxfloat)) # Concat and return return T.concatenate([ mu_volume_patient.dimshuffle(0, 'x'), sigma_volume_patient.dimshuffle(0, 'x')], axis=1) class JeroenLayerDiscs(lasagne.layers.MergeLayer): """JeroenLayers using discs instead of truncated cones. """ def __init__(self, incomings, rescale_input=1.0, **kwargs): super(JeroenLayerDiscs, self).__init__(incomings, **kwargs) self.rescale_input = rescale_input def get_output_shape_for(self, input_shapes): return (input_shapes[0][0], 2) def get_output_for(self, inputs, **kwargs): mu_area, sigma_area, is_not_padded, slicedists = inputs # Rescale input mu_area = mu_area / self.rescale_input sigma_area = sigma_area / self.rescale_input # For each slice pair, compute if both of them are valid is_pair_not_padded = is_not_padded[:, :-1] + is_not_padded[:, 1:] > 1.5 # Compute the distance between slices h = slicedists[:, :-1] # Compute mu for each slice pair m1 = mu_area[:, :-1] m2 = mu_area[:, 1:] eps = 1e-2 mu_volumes = (m1 + m2) * h / 2.0 mu_volumes = mu_volumes * is_pair_not_padded # Compute sigma for each slice pair s1 = sigma_area[:, :-1] s2 = sigma_area[:, 1:] sigma_volumes = h * T.sqrt(s1**2 + s2**2 + eps) / 2.0 sigma_volumes = sigma_volumes * is_pair_not_padded # Compute mu and sigma per patient mu_volume_patient = T.sum(mu_volumes, axis=1) sigma_volume_patient = T.sqrt(T.clip(T.sum(sigma_volumes**2, axis=1), eps, utils.maxfloat)) # Concat and return return T.concatenate([ mu_volume_patient.dimshuffle(0, 'x'), sigma_volume_patient.dimshuffle(0, 'x')], axis=1) class WeightedMeanLayer(lasagne.layers.MergeLayer): def __init__(self, weights, incomings, **kwargs): super(WeightedMeanLayer, self).__init__([weights]+incomings, **kwargs) def get_output_shape_for(self, input_shapes): return input_shapes[1] def get_output_for(self, inputs, **kwargs): conc = T.concatenate([i.dimshuffle(0,1,'x') for i in inputs[1:]], axis=2) weights = T.nnet.softmax(inputs[0]) r = conc * weights.dimshuffle(0,'x',1) result = T.sum(r, axis=2) return result class IncreaseCertaintyLayer(lasagne.layers.MergeLayer): def __init__(self, weight, incoming, **kwargs): super(IncreaseCertaintyLayer, self).__init__([weight,incoming], **kwargs) def get_output_shape_for(self, input_shapes): return input_shapes[1] def get_output_for(self, inputs, **kwargs): """ :param inputs[0]: (batch, 600) :param inputs[1]: (batch, 1) :return: """ result = (T.erf( T.erfinv( T.clip(inputs[1].dimshuffle(0,'x',1)*2-1, -1+3e-8, 1-3e-8) ) * inputs[0].dimshuffle(0,1,'x') )+1)/2 return result[:,0,:] class TrainableScaleLayer(lasagne.layers.Layer): def __init__(self, incoming, scale=lasagne.init.Constant(1), trainable=True, **kwargs): super(TrainableScaleLayer, self).__init__(incoming, **kwargs) # create scales parameter, ignoring all dimensions in shared_axes shape = [] self.scale = self.add_param( scale, shape, 'scale', regularizable=False, trainable=trainable) def get_output_for(self, input, **kwargs): return input * self.scale.dimshuffle('x', 'x') class RelativeLocationLayer(lasagne.layers.Layer): """Layer implementing a function mapping outermost values to 1 and innermost values to 0. """ def __init__(self, slicelocations, **kwargs): super(RelativeLocationLayer, self).__init__(slicelocations, **kwargs) def get_output_for(self, slicelocations, **kwargs): x = slicelocations - T.min(slicelocations, axis=1).dimshuffle(0, 'x') return abs(x * 2.0 / T.max(x, axis=1).dimshuffle(0, 'x') - 1.0) class RepeatLayer(lasagne.layers.Layer): def __init__(self, incoming, repeats, axis=0, **kwargs): super(RepeatLayer, self).__init__(incoming, **kwargs) self.repeats = repeats self.axis = axis def get_output_shape_for(self, input_shape): output_shape = list(input_shape) output_shape.insert(self.axis, self.repeats) return tuple(output_shape) def get_output_for(self, input, **kwargs): return repeat(input, self.repeats, self.axis) def repeat(input, repeats, axis): shape_ones = [1]*input.ndim shape_ones.insert(axis, repeats) ones = T.ones(tuple(shape_ones), dtype=input.dtype) pattern = list(range(input.ndim)) pattern.insert(axis, "x") # print shape_ones, pattern return ones * input.dimshuffle(*pattern) class IraLayer(lasagne.layers.MergeLayer): """Layer estimating the volume of the heart using 2CH and 4CH images. The volume is estimated by stacking elliptical discs. For each 'row' in the 2ch and 4ch image, it
<reponame>rixx/twitter-to-sqlite<gh_stars>100-1000 import datetime import hashlib import json import os import pathlib import time import click from twitter_to_sqlite import archive from twitter_to_sqlite import utils def add_identifier_options(subcommand): for decorator in reversed( ( click.argument("identifiers", type=str, nargs=-1), click.option( "--attach", type=click.Path( file_okay=True, dir_okay=False, allow_dash=False, exists=True ), multiple=True, help="Additional database file to attach", ), click.option("--sql", help="SQL query to fetch identifiers to use"), ) ): subcommand = decorator(subcommand) return subcommand @click.group() @click.version_option() def cli(): "Save data from Twitter to a SQLite database" @cli.command() @click.argument("url") @click.option( "-a", "--auth", type=click.Path(file_okay=True, dir_okay=False, allow_dash=True, exists=True), default="auth.json", help="Path to auth.json token file", ) def fetch(url, auth): "Make an authenticated request to the Twitter API" auth = json.load(open(auth)) session = utils.session_for_auth(auth) click.echo(json.dumps(session.get(url).json(), indent=4)) @cli.command() @click.option( "-a", "--auth", type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), default="auth.json", help="Path to save tokens to, defaults to auth.json", ) def auth(auth): "Save authentication credentials to a JSON file" click.echo("Create an app here: https://developer.twitter.com/en/apps") click.echo("Then navigate to 'Keys and tokens' and paste in the following:") click.echo() api_key = click.prompt("API key") api_secret_key = click.prompt("API secret key") access_token = click.prompt("Access token") access_token_secret = click.prompt("Access token secret") open(auth, "w").write( json.dumps( { "api_key": api_key, "api_secret_key": api_secret_key, "access_token": access_token, "access_token_secret": access_token_secret, }, indent=4, ) + "\n" ) @cli.command() @click.argument( "db_path", type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), required=True, ) @add_identifier_options @click.option( "-a", "--auth", type=click.Path(file_okay=True, dir_okay=False, allow_dash=True, exists=True), default="auth.json", help="Path to auth.json token file", ) @click.option("--ids", is_flag=True, help="Treat input as user IDs, not screen names") @click.option("--silent", is_flag=True, help="Disable progress bar") def followers(db_path, identifiers, attach, sql, auth, ids, silent): "Save followers for specified users (defaults to authenticated user)" _shared_friends_followers( db_path, identifiers, attach, sql, auth, ids, silent, "followers" ) def _shared_friends_followers( db_path, identifiers, attach, sql, auth, ids, silent, noun ): assert noun in ("friends", "followers") auth = json.load(open(auth)) session = utils.session_for_auth(auth) db = utils.open_database(db_path) identifiers = utils.resolve_identifiers(db, identifiers, attach, sql) if not identifiers: profile = utils.get_profile(db, session) identifiers = [profile["screen_name"]] for identifier in identifiers: if ids: kwargs = {"user_id": identifier} else: kwargs = {"screen_name": identifier} fetched = [] # Get the follower count, so we can have a progress bar count = 0 profile = utils.get_profile(db, session, **kwargs) screen_name = profile["screen_name"] user_id = profile["id"] save_users_kwargs = {} if noun == "followers": save_users_kwargs["followed_id"] = user_id elif noun == "friends": save_users_kwargs["follower_id"] = user_id def go(update): for users_chunk in utils.fetch_user_list_chunks( session, user_id, screen_name, noun=noun ): fetched.extend(users_chunk) utils.save_users(db, users_chunk, **save_users_kwargs) update(len(users_chunk)) if not silent: count = profile["{}_count".format(noun)] with click.progressbar( length=count, label="Importing {:,} {} for @{}".format(count, noun, screen_name), ) as bar: go(bar.update) else: go(lambda x: None) @cli.command() @click.argument( "db_path", type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), required=True, ) @add_identifier_options @click.option( "-a", "--auth", type=click.Path(file_okay=True, dir_okay=False, allow_dash=True, exists=True), default="auth.json", help="Path to auth.json token file", ) @click.option("--ids", is_flag=True, help="Treat input as user IDs, not screen names") @click.option("--silent", is_flag=True, help="Disable progress bar") def friends(db_path, identifiers, attach, sql, auth, ids, silent): "Save friends for specified users (defaults to authenticated user)" _shared_friends_followers( db_path, identifiers, attach, sql, auth, ids, silent, "friends" ) @cli.command() @click.argument( "db_path", type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), required=True, ) @click.option( "-a", "--auth", type=click.Path(file_okay=True, dir_okay=False, allow_dash=True, exists=True), default="auth.json", help="Path to auth.json token file", ) @click.option("--user_id", help="Numeric user ID") @click.option("--screen_name", help="Screen name") @click.option("--stop_after", type=int, help="Stop after this many") def favorites(db_path, auth, user_id, screen_name, stop_after): "Save tweets favorited by specified user" auth = json.load(open(auth)) session = utils.session_for_auth(auth) db = utils.open_database(db_path) profile = utils.get_profile(db, session, user_id, screen_name) with click.progressbar( utils.fetch_favorites(session, db, user_id, screen_name, stop_after), label="Importing favorites", show_pos=True, ) as bar: utils.save_tweets(db, bar, favorited_by=profile["id"]) @cli.command(name="user-timeline") @click.argument( "db_path", type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), required=True, ) @add_identifier_options @click.option( "-a", "--auth", type=click.Path(file_okay=True, dir_okay=False, allow_dash=True, exists=True), default="auth.json", help="Path to auth.json token file", ) @click.option("--ids", is_flag=True, help="Treat input as user IDs, not screen names") @click.option("--stop_after", type=int, help="Only pull this number of recent tweets") @click.option("--user_id", help="Numeric user ID", hidden=True) @click.option("--screen_name", help="Screen name", hidden=True) @click.option( "--since", is_flag=True, help="Pull tweets since last retrieved tweet", ) @click.option("--since_id", type=str, help="Pull tweets since this Tweet ID") def user_timeline( db_path, identifiers, attach, sql, auth, ids, stop_after, user_id, screen_name, since, since_id, ): "Save tweets posted by specified user" auth = json.load(open(auth)) session = utils.session_for_auth(auth) db = utils.open_database(db_path) identifiers = utils.resolve_identifiers(db, identifiers, attach, sql) # Backwards compatible support for old --user_id and --screen_name options if screen_name: if ids: raise click.ClickException("Cannot use --screen_name with --ids") identifiers.append(screen_name) if user_id: if not identifiers: identifiers = [user_id] else: if not ids: raise click.ClickException("Use --user_id with --ids") identifiers.append(user_id) # If identifiers is empty, fetch the authenticated user fetch_profiles = True if not identifiers: fetch_profiles = False profile = utils.get_profile(db, session, user_id, screen_name) identifiers = [profile["screen_name"]] ids = False format_string = ( "@{:" + str(max(len(str(identifier)) for identifier in identifiers)) + "}" ) for identifier in identifiers: kwargs = {} if ids: kwargs["user_id"] = identifier else: kwargs["screen_name"] = identifier if fetch_profiles: profile = utils.get_profile(db, session, **kwargs) else: profile = db["users"].get(profile["id"]) expected_length = profile["statuses_count"] if since or since_id: expected_length = None with click.progressbar( utils.fetch_user_timeline( session, db, stop_after=stop_after, since_id=since_id, since=since, **kwargs ), length=expected_length, label=format_string.format(profile["screen_name"]), show_pos=True, ) as bar: # Save them 100 at a time chunk = [] for tweet in bar: chunk.append(tweet) if len(chunk) >= 100: utils.save_tweets(db, chunk) chunk = [] if chunk: utils.save_tweets(db, chunk) @cli.command(name="home-timeline") @click.argument( "db_path", type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), required=True, ) @click.option( "-a", "--auth", type=click.Path(file_okay=True, dir_okay=False, allow_dash=True, exists=True), default="auth.json", help="Path to auth.json token file", ) @click.option( "--since", is_flag=True, help="Pull tweets since last retrieved tweet", ) @click.option("--since_id", type=str, help="Pull tweets since this Tweet ID") def home_timeline(db_path, auth, since, since_id): "Save tweets from timeline for authenticated user" _shared_timeline( db_path, auth, since, since_id, table="timeline_tweets", api_url="https://api.twitter.com/1.1/statuses/home_timeline.json", since_type="home", ) @cli.command(name="mentions-timeline") @click.argument( "db_path", type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), required=True, ) @click.option( "-a", "--auth", type=click.Path(file_okay=True, dir_okay=False, allow_dash=True, exists=True), default="auth.json", help="Path to auth.json token file", ) @click.option( "--since", is_flag=True, help="Pull tweets since last retrieved mention", ) @click.option("--since_id", type=str, help="Pull mentions since this Tweet ID") def mentions_timeline(db_path, auth, since, since_id): "Save tweets that mention the authenticated user" _shared_timeline( db_path, auth, since, since_id, table="mentions_tweets", api_url="https://api.twitter.com/1.1/statuses/mentions_timeline.json", sleep=10, since_type="mentions", ) def _shared_timeline( db_path, auth, since, since_id, table, api_url, sleep=1, since_type=None ): auth = json.load(open(auth)) session = utils.session_for_auth(auth) db = utils.open_database(db_path) profile = utils.get_profile(db, session) expected_length = 800 since_key = profile["id"] with click.progressbar( utils.fetch_timeline( session, api_url, db, sleep=sleep, since=since, since_id=since_id, since_type=since_type, since_key=since_key, ), length=expected_length, label="Importing tweets", show_pos=True, ) as bar: # Save them 100 at a time def save_chunk(db, chunk): utils.save_tweets(db, chunk) # Record who's timeline they came from db[table].insert_all( [{"user": profile["id"], "tweet": tweet["id"]} for tweet in chunk], pk=("user", "tweet"), foreign_keys=("user", "tweet"), replace=True, ) chunk = [] for tweet in bar: chunk.append(tweet) if len(chunk) >= 100: save_chunk(db, chunk) chunk = [] if chunk: save_chunk(db, chunk) @cli.command(name="users-lookup") @click.argument( "db_path", type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), required=True, ) @add_identifier_options @click.option( "-a", "--auth", type=click.Path(file_okay=True, dir_okay=False, allow_dash=True, exists=True), default="auth.json", help="Path to auth.json token file", ) @click.option("--ids", is_flag=True, help="Treat input as user IDs, not screen names") def users_lookup(db_path, identifiers, attach, sql, auth, ids): "Fetch user accounts" auth = json.load(open(auth)) session = utils.session_for_auth(auth) db = utils.open_database(db_path) identifiers = utils.resolve_identifiers(db, identifiers, attach, sql) for batch in utils.fetch_user_batches(session, identifiers, ids): utils.save_users(db, batch) @cli.command(name="statuses-lookup") @click.argument( "db_path", type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), required=True, ) @add_identifier_options @click.option( "-a", "--auth", type=click.Path(file_okay=True, dir_okay=False, allow_dash=True, exists=True), default="auth.json", help="Path to auth.json token file", ) @click.option( "--skip-existing", is_flag=True, help="Skip tweets that are already in the DB" ) @click.option("--silent", is_flag=True, help="Disable progress bar") def statuses_lookup(db_path, identifiers, attach, sql, auth, skip_existing, silent): "Fetch tweets by their IDs" auth = json.load(open(auth)) session = utils.session_for_auth(auth) db = utils.open_database(db_path) identifiers = utils.resolve_identifiers(db, identifiers, attach, sql) if skip_existing: existing_ids = set( r[0] for r in db.conn.execute("select id from tweets").fetchall() ) identifiers = [i for i in identifiers if int(i) not in existing_ids] if silent: for batch in utils.fetch_status_batches(session, identifiers): utils.save_tweets(db, batch) else: # Do it with a progress bar count = len(identifiers) with click.progressbar( length=count, label="Importing {:,} tweet{}".format(count, "" if count == 1 else "s"), ) as bar: for batch in utils.fetch_status_batches(session, identifiers): utils.save_tweets(db, batch) bar.update(len(batch)) @cli.command(name="lists") @click.argument( "db_path", type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), required=True, ) @add_identifier_options @click.option( "-a", "--auth", type=click.Path(file_okay=True, dir_okay=False, allow_dash=True, exists=True), default="auth.json", help="Path to auth.json token file", ) @click.option("--ids", is_flag=True, help="Treat input as user IDs, not screen_names") @click.option("--members", is_flag=True, help="Retrieve members for each list") def lists(db_path, identifiers, attach, sql, auth, ids, members): "Fetch lists belonging to specified users" auth = json.load(open(auth)) session = utils.session_for_auth(auth) db = utils.open_database(db_path) identifiers = utils.resolve_identifiers(db, identifiers, attach, sql) # Make sure we have saved these users to the database for batch in utils.fetch_user_batches(session, identifiers, ids): utils.save_users(db, batch) first = True for identifier in identifiers: if ids: kwargs = {"user_id": identifier} else: kwargs = {"screen_name": identifier} fetched_lists = utils.fetch_lists(db, session, **kwargs) if members: for new_list in fetched_lists: utils.fetch_and_save_list( db, session, new_list["full_name"].rstrip("@") ) if not first: # Rate limit is one per minute first = False time.sleep(60) @cli.command(name="list-members") @click.argument( "db_path", type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), required=True, ) @click.argument("identifiers", type=str, nargs=-1) @click.option( "-a", "--auth", type=click.Path(file_okay=True, dir_okay=False, allow_dash=True, exists=True), default="auth.json", help="Path to auth.json token file", ) @click.option( "--ids", is_flag=True,
None, 4, None, None, "SenderFlags"), 0x401b: (0x0003, None, None, 4, None, None, "ReceivedByFlags"), 0x401c: (0x0003, None, None, 4, None, None, "ReceivedRepresentingFlags"), 0x401d: (0x0003, None, None, 4, None, None, "OriginalSenderFlags"), 0x401e: (0x0003, None, None, 4, None, None, "OriginalSentRepresentingFlags"), 0x401f: (0x0003, None, None, 4, None, None, "ReportFlags"), 0x4020: (0x0003, None, None, 4, None, None, "ReadReceiptFlags"), 0x4021: (0x0102, None, None, 4, None, None, "SoftDeletes"), 0x4022: (0x001f, None, None, 4, None, None, "CreatorAddressType"), 0x4023: (0x001f, None, None, 4, None, None, "CreatorEmailAddress"), 0x4024: (0x001f, None, None, 4, None, None, "LastModifierAddressType"), 0x4025: (0x001f, None, None, 4, None, None, "LastModifierEmailAddress"), 0x4026: (0x001f, None, None, 4, None, None, "ReportAddressType"), 0x4027: (0x001f, None, None, 4, None, None, "ReportEmailAddress"), 0x4028: (0x001f, None, None, 4, None, None, "ReportDisplayName"), 0x402d: (0x0102, None, None, 4, None, None, "IdsetRead"), 0x402e: (0x0102, None, None, 4, None, None, "IdsetUnread"), 0x402f: (0x0003, None, None, 4, None, None, "IncrSyncRead"), 0x4037: (0x001f, None, None, 4, None, None, "ReportSimpleDisplayName"), 0x4038: (0x001f, None, None, 4, None, None, "CreatorSimpleDisplayName"), 0x4039: (0x001f, None, None, 4, None, None, "LastModifierSimpleDisplayName"), 0x403a: (0x0003, None, None, 4, None, None, "IncrSyncStateBegin"), 0x403b: (0x0003, None, None, 4, None, None, "IncrSyncStateEnd"), 0x403c: (0x0003, None, None, 4, None, None, "IncrSyncImailStream"), 0x403f: (0x001f, None, None, 4, None, None, "SenderOriginalAddressType"), 0x4040: (0x001f, None, None, 4, None, None, "SenderOriginalEmailAddress"), 0x4041: (0x001f, None, None, 4, None, None, "SentRepresentingOriginalAddressType"), 0x4042: (0x001f, None, None, 4, None, None, "SentRepresentingOriginalEmailAddress"), 0x4043: (0x001f, None, None, 4, None, None, "OriginalSenderOriginalAddressType"), 0x4044: (0x001f, None, None, 4, None, None, "OriginalSenderOriginalEmailAddress"), 0x4045: (0x001f, None, None, 4, None, None, "OriginalSentRepresentingOriginalAddressType"), 0x4046: (0x001f, None, None, 4, None, None, "OriginalSentRepresentingOriginalEmailAddress"), 0x4047: (0x001f, None, None, 4, None, None, "ReceivedByOriginalAddressType"), 0x4048: (0x001f, None, None, 4, None, None, "ReceivedByOriginalEmailAddress"), 0x4049: (0x001f, None, None, 4, None, None, "ReceivedRepresentingOriginalAddressType"), 0x404a: (0x001f, None, None, 4, None, None, "ReceivedRepresentingOriginalEmailAddress"), 0x404b: (0x001f, None, None, 4, None, None, "ReadReceiptOriginalAddressType"), 0x404c: (0x001f, None, None, 4, None, None, "ReadReceiptOriginalEmailAddress"), 0x404d: (0x001f, None, None, 4, None, None, "ReportOriginalAddressType"), 0x404e: (0x001f, None, None, 4, None, None, "ReportOriginalEmailAddress"), 0x404f: (0x001f, None, None, 4, None, None, "CreatorOriginalAddressType"), 0x4050: (0x001f, None, None, 4, None, None, "CreatorOriginalEmailAddress"), 0x4051: (0x001f, None, None, 4, None, None, "LastModifierOriginalAddressType"), 0x4052: (0x001f, None, None, 4, None, None, "LastModifierOriginalEmailAddress"), 0x4053: (0x001f, None, None, 4, None, None, "OriginatorOriginalAddressType"), 0x4054: (0x001f, None, None, 4, None, None, "OriginatorOriginalEmailAddress"), 0x4055: (0x001f, None, None, 4, None, None, "ReportDestinationOriginalAddressType"), 0x4056: (0x001f, None, None, 4, None, None, "ReportDestinationOriginalEmailAddress"), 0x4057: (0x001f, None, None, 4, None, None, "OriginalAuthorOriginalAddressType"), 0x4058: (0x001f, None, None, 4, None, None, "OriginalAuthorOriginalEmailAddress"), 0x4059: (0x0003, None, None, 4, None, None, "CreatorFlags"), 0x405a: (0x0003, None, None, 4, None, None, "LastModifierFlags"), 0x405b: (0x0003, None, None, 4, None, None, "OriginatorFlags"), 0x405c: (0x0003, None, None, 4, None, None, "ReportDestinationFlags"), 0x405d: (0x0003, None, None, 4, None, None, "OriginalAuthorFlags"), 0x405e: (0x001f, None, None, 4, None, None, "OriginatorSimpleDisplayName"), 0x405f: (0x001f, None, None, 4, None, None, "ReportDestinationSimpleDisplayName"), 0x4061: (0x0102, None, None, 4, None, None, "OriginatorSearchKey"), 0x4062: (0x001f, None, None, 4, None, None, "ReportDestinationAddressType"), 0x4063: (0x001f, None, None, 4, None, None, "ReportDestinationEmailAddress"), 0x4064: (0x0102, None, None, 4, None, None, "ReportDestinationSearchKey"), 0x4066: (0x0003, None, None, 4, None, None, "IncrSyncImailStreamContinue"), 0x4067: (0x0003, None, None, 4, None, None, "IncrSyncImailStreamCancel"), 0x4071: (0x0003, None, None, 4, None, None, "IncrSyncImailStream2Continue"), 0x4074: (0x000b, None, None, 4, None, None, "IncrSyncProgressMode"), 0x4075: (0x000b, None, None, 4, None, None, "SyncProgressPerMsg"), 0x407a: (0x0003, None, None, 4, None, None, "IncrSyncMsgPartial"), 0x407b: (0x0003, None, None, 4, None, None, "IncrSyncGroupInfo"), 0x407c: (0x0003, None, None, 4, None, None, "IncrSyncGroupId"), 0x407d: (0x0003, None, None, 4, None, None, "IncrSyncChangePartial"), 0x4084: (0x0003, None, None, 4, None, None, "ContentFilterPCL"), 0x4085: (0x0040, None, None, 4, None, None, "PeopleInsightsLastAccessTime"), 0x4086: (0x0040, None, None, 4, None, None, "EmailUsageLastActivityTime"), 0x4087: (0x0003, None, None, 4, None, None, "PdpProfileDataMigrationFlags"), 0x4088: (0x0102, None, None, 4, None, None, "ControlDataForPdpDataMigrationAssistant"), 0x5500: (0x000b, None, None, 4, None, None, "IsInterestingForFileExtraction"), 0x5d03: (0x001f, None, None, 4, None, None, "OriginalSenderSMTPAddress"), 0x5d04: (0x001f, None, None, 4, None, None, "OriginalSentRepresentingSMTPAddress"), 0x5d06: (0x001f, None, None, 4, None, None, "OriginalAuthorSMTPAddress"), 0x5d09: (0x0102, None, None, 4, None, None, "MessageUsageData"), 0x5d0a: (0x001f, None, None, 4, None, None, "CreatorSMTPAddress"), 0x5d0b: (0x001f, None, None, 4, None, None, "LastModifierSMTPAddress"), 0x5d0c: (0x001f, None, None, 4, None, None, "ReportSMTPAddress"), 0x5d0d: (0x001f, None, None, 4, None, None, "OriginatorSMTPAddress"), 0x5d0e: (0x001f, None, None, 4, None, None, "ReportDestinationSMTPAddress"), 0x5fe5: (0x001f, None, None, 4, None, None, "RecipientSipUri"), 0x6000: (0x0003, None, None, 4, None, None, "RssServerLockStartTime"), 0x6001: (0x001f, None, None, 4, None, None, "DotStuffState"), 0x6002: (0x001f, None, None, 4, None, None, "RssServerLockClientName"), 0x61af: (0x0102, None, None, 4, None, None, "ScheduleData"), 0x65ef: (0x0102, None, None, 4, None, None, "RuleMsgActions"), 0x65f0: (0x0102, None, None, 4, None, None, "RuleMsgCondition"), 0x65f1: (0x0003, None, None, 4, None, None, "RuleMsgConditionLCID"), 0x65f4: (0x000b, None, None, 4, None, None, "PreventMsgCreate"), 0x65f9: (0x0102, None, None, 4, None, None, "LISSD"), 0x65fa: (0x101f, None, None, 4, None, None, "IMAPUnsubscribeList"), 0x6607: (0x001f, None, None, 4, None, None, "ProfileUnresolvedName"), 0x660d: (0x0003, None, None, 4, None, None, "ProfileMaxRestrict"), 0x660e: (0x001f, None, None, 4, None, None, "ProfileABFilesPath"), 0x660f: (0x001f, None, None, 4, None, None, "ProfileFavFolderDisplayName"), 0x6613: (0x101f, None, None, 4, None, None, "ProfileHomeServerAddrs"), 0x662b: (0x0102, None, None, 4, None, None, "TestLineSpeed"), 0x6630: (0x0102, None, None, 4, None, None, "LegacyShortcutsFolderEntryId"), 0x6635: (0x001f, None, None, 4, None, None, "FavoritesDefaultName"), 0x6641: (0x0003, None, None, 4, None, None, "DeletedFolderCount"), 0x6643: (0x0003, None, None, 4, None, None, "DeletedAssociatedMessageCount32"), 0x6644: (0x001f, None, None, 4, None, None, "ReplicaServer"), 0x664c: (0x0102, None, None, 4, None, None, "FidMid"), 0x6652: (0x0102, None, None, 4, None, None, "ActiveUserEntryId"), 0x6655: (0x0102, None, None, 4, None, None, "ICSChangeKey"), 0x6657: (0x0102, None, None, 4, None, None, "SetPropsCondition"), 0x6659: (0x0102, None, None, 4, None, None, "InternetContent"), 0x665b: (0x001f, None, None, 4, None, None, "OriginatorName"), 0x665c: (0x001f, None, None, 4, None, None, "OriginatorEmailAddress"), 0x665d: (0x001f, None, None, 4, None, None, "OriginatorAddressType"), 0x665e: (0x0102, None, None, 4, None, None, "OriginatorEntryId"), 0x6662: (0x0003, None, None, 4, None, None, "RecipientNumber"), 0x6664: (0x001f, None, None, 4, None, None, "ReportDestinationName"), 0x6665: (0x0102, None, None, 4, None, None, "ReportDestinationEntryId"), 0x6692: (0x0003, None, None, 4, None, None, "ReplicationMsgPriority"), 0x6697: (0x0003, None, None, 4, None, None, "WorkerProcessId"), 0x669a: (0x0003, None, None, 4, None, None, "CurrentDatabaseSchemaVersion"), 0x669e: (0x000b, None, None, 4, None, None, "SecureInSite"), 0x66a7: (0x0003, None, None, 4, None, None, "MailboxFlags"), 0x66ab: (0x0003, None, None, 4, None, None, "MailboxMessagesPerFolderCountWarningQuota"), 0x66ac: (0x0003, None, None, 4, None, None, "MailboxMessagesPerFolderCountReceiveQuota"), 0x66ad: (0x0003, None, None, 4, None, None, "NormalMessagesWithAttachmentsCount32"), 0x66ae: (0x0003, None, None, 4, None, None, "AssociatedMessagesWithAttachmentsCount32"), 0x66af: (0x0003, None, None, 4, None, None, "FolderHierarchyChildrenCountWarningQuota"), 0x66b0: (0x0003, None, None, 4, None, None, "FolderHierarchyChildrenCountReceiveQuota"), 0x66b1: (0x0003, None, None, 4, None, None, "AttachmentsOnNormalMessagesCount32"), 0x66b2: (0x0003, None, None, 4, None, None, "AttachmentsOnAssociatedMessagesCount32"), 0x66b3: (0x0014, None, None, 4, None, None, "NormalMessageSize64"), 0x66e0: (0x001f, None, None, 4, None, None, "ServerDN"), 0x66e1: (0x0003, None, None, 4, None, None, "BackfillRanking"), 0x66e2: (0x0003, None, None, 4, None, None, "LastTransmissionTime"), 0x66e3: (0x0040, None, None, 4, None, None, "StatusSendTime"), 0x66e4: (0x0003, None, None, 4, None, None, "BackfillEntryCount"), 0x66e5: (0x0040, None, None, 4, None, None, "NextBroadcastTime"), 0x66e6: (0x0040, None, None, 4, None, None, "NextBackfillTime"), 0x66e7: (0x0102, None, None, 4, None, None, "LastCNBroadcast"), 0x66eb: (0x0102, None, None, 4, None, None, "BackfillId"), 0x66f4: (0x0102, None, None, 4, None, None, "LastShortCNBroadcast"), 0x66fb: (0x0040, None, None, 4, None, None, "AverageTransmissionTime"), 0x66fc: (0x0014, None, None, 4, None, None, "ReplicationStatus"), 0x66fd: (0x0040, None, None, 4, None, None, "LastDataReceivalTime"), 0x670c: (0x1048, None, None, 4, None, None, "AutoReset"), 0x6712: (0x0102, None, None, 4, None, None, "ScopeFIDs"), 0x671e: (0x000b, None, None, 4, None, None, "PFPlatinumHomeMdb"), 0x673f: (0x0102, None, None, 4, None, None, "ReadCnNewExport"), 0x6745: (0x0102, None, None, 4, None, None, "LocallyDelivered"), 0x6746: (0x0014, None, None, 4, None, None, "MimeSize"), 0x6747: (0x0014, None, None, 4, None, None, "FileSize"), 0x674b: (0x0014, None, None, 4, None, None, "CategID"), 0x674c: (0x0014, None, None, 4, None, None, "ParentCategID"), 0x6750: (0x0002, None, None, 4, None, None, "ChangeType"), 0x6753: (0x000b, None, None, 4, None, None, "Not822Renderable"), 0x6758: (0x0102, None, None, 4, None, None, "LTID"), 0x6759: (0x0102, None, None, 4, None, None, "CnExport"), 0x675a: (0x0102, None, None, 4, None, None, "PclExport"), 0x675b: (0x0102, None,
+ " [extra note in the script]") for s, w in symsname[c]: if w: continue # Weak symbols never conflict with others in different libraries if s in ( '_init', '_fini', '__bss_start', '__bss_start__', '__bss_end__', '_bss_end__', '__data_start', '_edata', '_end', '__end__'): continue # Always allow those symbols [TODO: check if OK] if s in symbols: # Check for resemblances between symbols[s] and filename # if filename.startswith(symbols[s][:-12]) or symbols[s].startswith(filename[:-12]): # # Probably OK # continue # Manual incompatible libs detection match = lambda l, r: (filename[7:-10], symbols[s][7:-10]) in [(l, r), (r, l)] if match("gdkx112", "gdk3") \ or match("gtkx112", "gtk3") \ or match("libjpeg", "libjpeg62") \ or match("libncurses", "libncurses6") \ or match("libncurses", "libncursesw") \ or match("libncurses6", "libncursesw") \ or match("libtinfo6", "libtinfo") \ or match("png12", "png16") \ or match("sdl1", "sdl2") \ or match("sdl1image", "sdl2image") \ or match("sdl1mixer", "sdl2mixer") \ or match("sdl1net", "sdl2net") \ or match("sdl1ttf", "sdl2ttf") \ or match("smpeg", "smpeg2") \ or match("udev0", "udev1") \ or match("gstinterfaces010","gstvideo")\ or match("gstinterfaces010","gstaudio")\ or match("gstreamer010","gstreamer") \ \ or match("libc", "tcmallocminimal") \ or match("libc", "ldlinux") \ : # libc and ldlinux have some "__libc_" data symbols in common... TODO check if ok continue # Note: this test is very (too) simple. If it ever raises, comment # `need_halt = True` and open an issue. print("The symbol {0} is declared in multiple files ({1}/{2})" .format(s, symbols[s], filename) + " [extra note in the script]", file=sys.stderr) need_halt = True symbols[s] = filename else: symname = symname.strip() if symname == "": raise ValueError("This symbol name (\"\") is suspicious... ({0})".format(filename)) l = len(dependants.defines) already_pst = any(s == symname for s, _ in symsname[""]) if l == 1: symsname.setdefault(str(dependants), []) already_pst = already_pst or any(s == symname for s, _ in symsname[str(dependants)]) if already_pst: print("The symbol {0} is duplicated! ({1})".format(symname, filename), file=sys.stderr) need_halt = True return if l == 1: s = str(dependants.defines[0].inverted()) if (s in symsname) and ((symname, weak) in symsname[s]): symsname[s].remove((symname, weak)) symsname[""].append((symname, weak)) elif (s in symsname) and ((symname, not weak) in symsname[s]): print("The symbol {0} doesn't have the same 'weakness' in different conditions! ({1})" .format(symname, filename), file=sys.stderr) need_halt = True else: symsname[str(dependants)].append((symname, weak)) elif l == 0: symsname[""].append((symname, weak)) with open(filepath, 'r') as file: for line in file: ln = line.strip() try: # If the line is a `#' line (#ifdef LD80BITS/#ifndef LD80BITS/header) if ln.startswith("#"): preproc_cmd = ln[1:].strip() if preproc_cmd.startswith("if defined(GO)"): continue #if defined(GO) && defined(GOM)... elif preproc_cmd.startswith("if !(defined(GO)"): continue #if !(defined(GO) && defined(GOM)...) elif preproc_cmd.startswith("error"): continue #error meh! elif preproc_cmd.startswith("include"): continue #inherit other library elif preproc_cmd.startswith("endif"): dependants.pop_last() elif preproc_cmd.startswith("ifdef"): dependants.append(Define(DefineType(preproc_cmd[5:].strip()), False)) elif preproc_cmd.startswith("ifndef"): dependants.append(Define(DefineType(preproc_cmd[6:].strip()), True)) elif preproc_cmd.startswith("else"): dependants.invert_last() else: raise NotImplementedError("Unknown preprocessor directive: {0}".format(preproc_cmd.split(" ")[0])) # If the line is a `GO...' line (GO/GOM/GO2/...)... elif ln.startswith("GO"): # ... then look at the second parameter of the line try: gotype = ln.split("(")[0].strip() funname = ln.split(",")[0].split("(")[1].strip() ln = ln.split(",")[1].split(")")[0].strip() except IndexError: raise NotImplementedError("Invalid GO command") fun = Function(funname, FunctionType(ln, filespec), gotype, filespec, filename, line) if not filename.endswith("_genvate.h"): add_symbol_name(fun.name, fun.isweak) if hasattr(fun, 'invalid'): need_halt = True continue if fun.type.redirect or fun.type.usestruct: redirects[dependants.copy()].append(fun) else: gbls[dependants.copy()].append(fun) # If the line is a structure metadata information... elif ln.startswith("//%S"): metadata = [e for e in ln.split() if e] if len(metadata) != 4: # If you need an empty replacement, please open a PR raise NotImplementedError("Invalid structure metadata supply (too many/not enough fields)") if metadata[0] != "//%S": raise NotImplementedError("Invalid structure metadata supply (invalid signature)") filespec.registerStruct(metadata[1], metadata[2], metadata[3]) # If the line contains any symbol name... elif ("GO" in ln) or ("DATA" in ln): if filename.endswith("_genvate.h"): continue # Probably "//GO(..., " or "DATA(...," at least try: symname = ln.split('(')[1].split(',')[0].strip() add_symbol_name(symname) except IndexError: # Oops, it wasn't... pass except Exception as e: raise NotImplementedError("{0}:{1}".format(filename, line[:-1])) from e if filename.endswith("_genvate.h"): del filespecs[filename[:-10]] add_symbol_name(None) FunctionType.getSingletons().clear() if need_halt: raise ValueError("Fix all previous errors before proceeding") return gbls, redirects, filespecs def sortArrays(gbl_funcs: JumbledFunctions, red_funcs: JumbledFunctions, filespecs: FilesSpecific) \ -> Tuple[SortedGlobals, SortedRedirects]: # First sort file specific stuff for fn in filespecs: filespecs[fn].typedefs.sort(key=_BareFunctionType.splitchar) for funtype in filespecs[fn].typedefs: filespecs[fn].typedefs[funtype].sort(key=lambda f: f.name) filespecs[fn].structs.sort() filespecs[fn].structsuses.sort(key=FunctionType.splitchar) # Now, take all function types, and make a new table gbl_vals # This table contains all #if conditions for when a function type needs to # be generated. def add_to_vals(vals: Dict[FunctionType, Clauses], t: FunctionType, clause: Clause) -> None: vals.setdefault(t, Clauses()) if clause in vals[t].clauses: return vals[t].add(clause) gbl_vals: Dict[FunctionType, Clauses] = {} for clause in gbl_funcs: for f in gbl_funcs[clause]: add_to_vals(gbl_vals, f.type, clause) for clause in red_funcs: for f in red_funcs[clause]: assert(f.type.redirected is not None) add_to_vals(gbl_vals, f.type.redirected, clause) # Remove duplicate/useless conditions (and sort) for t in gbl_vals: gbl_vals[t].reduce() # Now create a new gbls # gbls will contain the final version of gbls (without duplicates, based on # gbl_vals), meaning, a dict from clauses to function types to implement gbls: SortedGlobals = CustOrderedDictList() for funtype in gbl_vals: gbls[gbl_vals[funtype]].append(funtype) # Sort the #if clauses as defined in `splitdef` gbls.sort(key=Clauses.splitdef) # Sort the function types as defined in `splitchar` for clauses in gbls: gbls[clauses].sort(key=FunctionType.splitchar) # This map will contain all additional function types that are "redirected" # to an already defined type (with some remapping). red_vals: Dict[FunctionType, Clauses] = {} for clause in red_funcs: for f in red_funcs[clause]: if isinstance(f.type, StructFunctionType): continue assert(f.type.redirected is not None) add_to_vals(red_vals, f.type, clause) # Also do the same sorting as before (it also helps keep the order # in the file deterministic) for t in red_vals: red_vals[t].reduce() redirects: SortedRedirects = CustOrderedDictList() for funtype in red_vals: redirects[red_vals[funtype]].append(funtype) redirects.sort(key=Clauses.splitdef) def fail(): assert(False) for clauses in redirects: redirects[clauses].sort(key=lambda v: fail() if v.redirected is None else v.splitchar() + v.redirected.splitchar()) return gbls, redirects def checkRun(root: str, gbls: SortedGlobals, redirects: SortedRedirects, filesspec: FilesSpecific) -> Optional[str]: # Check if there was any new functions compared to last run functions_list: str = "" for clauses in gbls: for v in gbls[clauses]: functions_list = functions_list + "#" + str(clauses) + " " + v.orig + "\n" for clauses in redirects: for v in redirects[clauses]: assert(v.redirected is not None) functions_list = functions_list + "#" + str(clauses) + " " + v.orig + " -> " + v.redirected.orig + "\n" for filename in sorted(filesspec.keys()): functions_list = functions_list + filename + ":\n" for st in filesspec[filename].structs: struct = filesspec[filename].structs[st] functions_list = functions_list + \ "% " + st + " " + struct.name + " " + struct.repl + "\n" for _bare in filesspec[filename].typedefs: functions_list = functions_list + "- " + _bare.orig + ":\n" for fn in filesspec[filename].typedefs[_bare]: if fn.no_dlsym: continue functions_list = functions_list + " - " + fn.name + "\n" for funtype in filesspec[filename].structsuses: assert(funtype.redirected is not None) functions_list = functions_list + "% " + funtype.orig + " -> " + funtype.redirected.orig + "\n" # functions_list is a unique string, compare it with the last run try: last_run = "" with open(os.path.join(root, "src", "wrapped", "generated", "functions_list.txt"), 'r') as file: last_run = file.read() if last_run == functions_list: # Mark as OK for CMake with open(os.path.join(root, "src", "wrapped", "generated", "functions_list.txt"), 'w') as file: file.write(functions_list) return None except IOError: # The file does not exist yet, first run pass return functions_list def generate_files(root: str, files: Iterable[str], ver: str, gbls: SortedGlobals, redirects: SortedRedirects, \ filespecs: FilesSpecific) -> None: # Files header and guard files_header = { "wrapper.c": """ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "wrapper.h" #include "emu/x86emu_private.h" #include "emu/x87emu_private.h" #include "regs.h" #include "x86emu.h" typedef union ui64_s {lbr} int64_t i; uint64_t u; uint32_t d[2]; {rbr} ui64_t; typedef struct _2uint_struct_s {lbr} uint32_t a; uint32_t b; {rbr} _2uint_struct_t; extern void* my__IO_2_1_stderr_; extern void* my__IO_2_1_stdin_ ; extern void* my__IO_2_1_stdout_; static void* io_convert(void* v) {lbr} if(!v) return v; if(v==my__IO_2_1_stderr_) return stderr; if(v==my__IO_2_1_stdin_) return stdin; if(v==my__IO_2_1_stdout_) return stdout; return v; {rbr} typedef struct my_GValue_s {lbr} int g_type; union {lbr} int v_int; int64_t v_int64; uint64_t v_uint64; float v_float; double v_double; void* v_pointer; {rbr} data[2]; {rbr} my_GValue_t; static void alignGValue(my_GValue_t* v, void* value) {lbr} v->g_type = *(int*)value; memcpy(v->data, value+4, 2*sizeof(double)); {rbr} static void unalignGValue(void* value, my_GValue_t* v) {lbr} *(int*)value = v->g_type; memcpy(value+4, v->data, 2*sizeof(double)); {rbr} void* VulkanFromx86(void* src, void** save); void VulkanTox86(void* src, void* save); #define ST0val ST0.d int of_convert(int); """, "wrapper.h": """ #ifndef __WRAPPER_H_ #define __WRAPPER_H_ #include <stdint.h> #include <string.h> typedef struct x86emu_s x86emu_t; // the generic wrapper pointer functions typedef void (*wrapper_t)(x86emu_t* emu, uintptr_t fnc); // list of defined wrappers // E = current x86emu struct // v = void // C = unsigned byte c = char // W = unsigned short w = short // u = uint32, i = int32 // U = uint64, I = int64 // L = unsigned long, l = signed long (long is an int with the size of a pointer) // p = pointer // f = float, d = double, D = long double, K = fake long double // V = vaargs, s = address on the stack (doesn't move forward the pointer) // O = libc O_ flags bitfield // o = stdout // S = _IO_2_1_stdXXX_ pointer (or FILE*) // 2 = struct of 2 uint // N = ... automatically sending 1 arg // M = ... automatically sending 2 args // P = Vulkan struct pointer, G = a single GValue pointer """, "fntypes.h": """ #ifndef __{filename}TYPES_H_ #define __{filename}TYPES_H_ #ifndef LIBNAME #error You should only #include this file inside a wrapped*.c file #endif #ifndef ADDED_FUNCTIONS #define ADDED_FUNCTIONS() #endif """, "fndefs.h": """ #ifndef __{filename}DEFS_H_ #define __{filename}DEFS_H_ """, "fnundefs.h": """ #ifndef __{filename}UNDEFS_H_ #define __{filename}UNDEFS_H_ """ } files_guard = { "wrapper.c": """ """, "wrapper.h": """ #endif // __WRAPPER_H_ """, "fntypes.h": """ #endif // __{filename}TYPES_H_ """, "fndefs.h": """ #endif // __{filename}DEFS_H_ """, "fnundefs.h": """ #endif // __{filename}UNDEFS_H_ """ } banner = "/********************************************************" + ('*'*len(ver)) + "***\n" \ " * File automatically generated by rebuild_wrappers.py (v" + ver + ") *\n" \ " ********************************************************" + ('*'*len(ver)) + "***/\n" trim: Callable[[str], str] = lambda string: '\n'.join(line[2:] for line in string.splitlines())[1:] # Yes, the for loops are inverted. This is because both dicts should have the same keys. for fhdr
<reponame>c64cryptoboy/ChiptuneSAK<filename>tests/emulatorTests/tests.py # This program runs <NAME>' C64 test suite (2002, public domain) # This standard set of tests for C64 emulators can take a LONG time to run # For now, I'm mostly ignoring C64-specific tests, and focusing on 6502 # instruction tests # # Also runs <NAME>'s ADC/SBC BCD tests (public domain) # # to run: python -m unittest -v tests import unittest import string from parameterized import parameterized from chiptunesak import emulator_6502 from chiptunesak import thin_c64_emulator from chiptunesak.byte_util import read_binary_file from chiptunesak.constants import project_to_absolute_path # translate alphabet from mixed-case (mode) petscii to ascii # TODO: This method is only complete enough for these tests, it's not yet general # Someday, all petscii tools will live in one place and be general # We'll need ascii<->petscii upper case and ascii<->petscii mixed case converters def mixed_case_petscii_to_ascii(petscii_string): result = [] for c in petscii_string: c = ord(c) # only doing letter conversions if 193 <= c <= 218: c -= 96 # convert lowercase letters elif 65 <= c <= 90: c += 32 # convert uppercase letters elif chr(c) == '\r': c = ord('\n') elif chr(c) not in string.printable: c = ord('?') result.append(chr(c)) return ''.join(result) # psuedo-op docs reference http://www.ffd2.com/fridge/docs/6502-NMOS.extra.opcodes binary_file_tests = [ # ADC tests ("adca", "adc absolute"), ("adcax", "adc absolute,x"), ("adcay", "adc absolute,y"), ("adcb", "adc immediate"), ("adcix", "adc (indirect,x)"), ("adciy", "adc (indirect),y"), ("adcz", "adc zeropage"), ("adczx", "adc zeropage,x"), # illegal op not yet supported in our emulator # # ALR *** # This opcode ANDs the contents of the A register with an immediate value and # then LSRs the result. # One supported mode: # ALR #ab ;4B ab ;No. Cycles= 2 # Example: # ALR #$FE ;4B FE # Equivalent instructions: # AND #$FE # LSR A # # ("alrb", "alr immediate"), # illegal op not yet supported in our emulator # # ANC *** # ANC ANDs the contents of the A register with an immediate value and then # moves bit 7 of A into the Carry flag. This opcode works basically # identically to AND #immed. except that the Carry flag is set to the same # state that the Negative flag is set to. # One supported mode: # ANC #ab ;2B ab ;No. Cycles= 2 # ANC #ab ;0B ab # # ("ancb", "anc immediate"), # AND tests ("anda", "and absolute"), ("andax", "and absolute,x"), ("anday", "and absolute,y"), ("andb", "and immediate"), ("andix", "and (indirect,x)"), ("andiy", "and (indirect),y"), ("andz", "and zeropage"), ("andzx", "and zeropage,x"), # illegal op not yet supported in our emulator # Note: the aneb test fails repeatedly in VICE, which I trust more # # XAA *** # XAA transfers the contents of the X register to the A register and then # ANDs the A register with an immediate value. # One supported mode: # XAA #ab ;8B ab ;No. Cycles= 2 # # ("aneb", "xaa (aka ane) immediate"), # illegal op not yet supported in our emulator # # ARR *** # This opcode ANDs the contents of the A register with an immediate value and # then RORs the result. # One supported mode: # ARR #ab ;6B ab ;No. Cycles= 2 # Here's an example of how you might write it in a program. # ARR #$7F ;6B 7F # Here's the same code using equivalent instructions. # AND #$7F # ROR A # # ("arrb", "arr immediate"), # test shifting (ASL, LSR) ("asla", "asl absolute"), ("aslax", "asl absolute,x"), ("asln", "asl"), ("aslz", "asl zeropage"), ("aslzx", "asl zeropage,x"), ("lsra", "lsr absolute"), ("lsrax", "lsr absolute,x"), ("lsrn", "lsr"), ("lsrz", "lsr zeropage"), ("lsrzx", "lsr zeropage,x"), # illegal op not yet supported in our emulator # # ASO *** (aka SLO) # This opcode ASLs the contents of a memory location and then ORs the result # with the accumulator. # Supported modes: # ASO abcd ;0F cd ab ;No. Cycles= 6 # ASO abcd,X ;1F cd ab ; 7 # ASO abcd,Y ;1B cd ab ; 7 # ASO ab ;07 ab ; 5 # ASO ab,X ;17 ab ; 6 # ASO (ab,X) ;03 ab ; 8 # ASO (ab),Y ;13 ab ; 8 # (Sub-instructions: ORA, ASL) # Here is an example of how you might use this opcode: # ASO $C010 ;0F 10 C0 # Here is the same code using equivalent instructions. # ASL $C010 # ORA $C010 # # ("asoa", "aso absolute"), # ("asoax", "aso absolute,x"), # ("asoay", "aso absolute,y"), # ("asoix", "aso (indirect,x)"), # ("asoiy", "aso (indirect),y"), # ("asoz", "aso zeropage"), # ("asozx", "aso zeropage,x"), # illegal op not yet supported in our emulator # # AXS *** (aka SAX) # AXS ANDs the contents of the A and X registers (without changing the # contents of either register) and stores the result in memory. # AXS does not affect any flags in the processor status register. # Supported modes: # AXS abcd ;8F cd ab ;No. Cycles= 4 # AXS ab ;87 ab ; 3 # AXS ab,Y ;97 ab ; 4 # AXS (ab,X) ;83 ab ; 6 # (Sub-instructions: STA, STX) # Example: # AXS $FE ;87 FE # Here's the same code using equivalent instructions. # STX $FE # PHA # AND $FE # STA $FE # PLA # # ("axsa", "axs absolute"), # ("axsix", "axs (indirect,x)"), # ("axsz", "axs zeropage"), # ("axszy", "axs zeropage,y"), # branch tests ("bccr", "bcc relative"), ("bcsr", "bcs relative"), ("beqr", "beq relative"), ("bmir", "bmi relative"), ("bner", "bne relative"), ("bplr", "bpl relative"), ("bvcr", "bvc relative"), ("bvsr", "bvs relative"), ("branchwrap", "branchwrap"), # BRK tests # Test fills memory from $1100 to $1200 with BRKs, and JMPs to each in turn ("brkn", "brk"), # Going to skip these CIA tests for now, perhaps revisit them later # ("cia1pb6", "cia1pb6"), # ("cia1pb7", "cia1pb7"), # ("cia1ta", "cia1ta"), # ("cia1tab", "cia1tab"), # ("cia1tb", "cia1tb"), # ("cia1tb123", "cia1tb123"), # ("cia2pb6", "cia2pb6"), # ("cia2pb7", "cia2pb7"), # ("cia2ta", "cia2ta"), # ("cia2tb", "cia2tb"), # ("cia2tb123", "cia2tb123"), # ("cntdef", "cntdef"), # ("cnto2", "cnto2"), # ("flipos", "flipos"), # ("icr01", "icr01"), # ("imr", "imr"), # ("irq", "irq"), # ("loadth", "loadth"), # ("nmi", "nmi"), # ("oneshot", "oneshot"), # clear flag instruction tests ("clcn", "clc"), ("cldn", "cld"), ("clin", "cli"), ("clvn", "clv"), # compare tests (BIT, CMP, CPX, CPY) ("bita", "bit absolute"), ("bitz", "bit zeropage"), ("cmpa", "cmp absolute"), ("cmpax", "cmp absolute,x"), ("cmpay", "cmp absolute,y"), ("cmpb", "cmp immediate"), ("cmpix", "cmp (indirect,x)"), ("cmpiy", "cmp (indirect),y"), ("cmpz", "cmp zeropage"), ("cmpzx", "cmp zeropage,x"), ("cpxa", "cpx absolute"), ("cpxb", "cpx immediate"), ("cpxz", "cpx zeropage"), ("cpya", "cpy absolute"), ("cpyb", "cpy immediate"), ("cpyz", "cpy zeropage"), # Test 6510 ports at mem loc 0 and 1 # Skipping this for now # # ("cpuport", "cpuport test, bits 0-7"), # ("mmu", "mmu test, bits 0-2"), # ("mmufetch", "mmufetch"), # Test various cycles consumed. If there's a problem, you'll see this: # xx command byte # clocks #measured # right #2 # #1 #2 command or addressing mode # -------------------------------------- # 2 2 n # 2 2 b # 3 3 Rz/Wz # 5 5 Mz # 4 8 Rzx/Rzy/Wzx/Wzy # 6 10 Mzx/Mzy # 4 4 Ra/Wa # 6 6 Ma # 4 8 Rax/Ray (same page) # 5 9 Rax/Ray (different page) # 5 9 Wax/Way # 7 11 Max/May # 6 8 Rix/Wix # 8 10 Mix/Miy # 5 7 Riy (same page) # 6 8 Riy (different page) # 6 8 Wiy # 8 10 Miy # 2 18 r+00 same page not taken # 3 19 r+00 same page taken # 3 19 r+7F same page taken # 4 20 r+01 different page taken # 4 20 r+7F different page taken # 3 19 r-03 same page taken # 3 19 r-80 same page taken # 4 20 r-03 different page taken # 4 20 r-80 different page taken # 7 7 BRKn # 3 3 PHAn/PHPn # 4 4 PLAn/PLPn # 3 3 JMPw # 5 5 JMPi
import glob import json import os import queue import random import threading import time from ctypes import * import cv2 import matplotlib as mpl import matplotlib.cm as cm import numpy as np import PIL.Image as pil import torch from torchvision import transforms import camera_parameters as params import darknet.darknet as darknet import monodepth2.networks as networks from camera_parameters import * from deep_sort import build_tracker from deep_sort.parser import get_config from kalman_filter import KalmanFilter from monodepth2.layers import disp_to_depth if torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu") print("CUDA NOT AVALIABLE") def gstreamer_pipeline( capture_width=1280, capture_height=720, display_width=1280, display_height=720, framerate=10, flip_method=0, ): return ( "nvarguscamerasrc ! " "video/x-raw(memory:NVMM), " "width=(int)%d, height=(int)%d, " "format=(string)NV12, framerate=(fraction)%d/1 ! " "nvvidconv flip-method=%d ! " "video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! " "videoconvert ! " "video/x-raw, format=(string)BGR ! appsink" % ( capture_width, capture_height, framerate, flip_method, display_width, display_height, ) ) class CameraCapture(cv2.VideoCapture): """Bufferless & Distorted VideoCapture""" def __init__(self, original_options: tuple, intrinsic_matrix, dist_coeffs): super().__init__(*original_options) # self._queue = queue.SimpleQueue() self._queue = queue.Queue() read_camera_thread = threading.Thread(target=self._reader) read_camera_thread.daemon = True read_camera_thread.start() self._intrinsic_matrix = intrinsic_matrix.cpu().numpy() self._dist_coeffs = np.array(dist_coeffs) frame = self._queue.get() self._new_intrinsic_matrix, self._new_xywh = cv2.getOptimalNewCameraMatrix( self._intrinsic_matrix, self._dist_coeffs, frame.shape[:2], 0) self.intrinsic_matrix = torch.tensor( self._new_intrinsic_matrix).to(device) # read frames as soon as they are available, keeping only most recent one def _reader(self): while True: self._success, frame = super().read() if not self._success: break while True: try: self._queue.get_nowait() # discard previous (unprocessed) frame except queue.Empty: break self._queue.put(frame) def _distort_img(self, img): distorted_img = cv2.undistort(img, self._intrinsic_matrix, self._dist_coeffs, None, self._new_intrinsic_matrix) x, y, w, h = self._new_xywh distorted_img = distorted_img[x:x+w, y:y+h] return distorted_img def read(self): return self._success, self._distort_img(self._queue.get()) class FileCapture(): def __init__(self, file_path: str, ext="jpg") -> None: images_list = glob.glob(f'{file_path}/*.{ext}') images_list.sort(key=lambda x: int(x[len(file_path)+1:-len(ext)-1])) self.images = iter(images_list) self.intrinsic_matrix = torch.FloatTensor( [[785.26446533, 0., 627.50964355], [0., 785.27935791, 340.54248047], [0., 0., 1.]]).to(device) def release(self): pass def read(self): success_flag = False try: fname = next(self.images) frame = cv2.imread(fname) success_flag = True except: frame = None pass return success_flag, frame class Trajectory(): def __init__(self, max_age=50, max_error=0.1): self.max_age = max_age self.max_error = max_error self.objects = dict() self.index = 0 def __delete_out_dated(self): to_be_deleted = [] for obj_id, coords_dict in self.objects.items(): last_index = max([key for key in coords_dict.keys()]) if self.index-last_index > self.max_age: to_be_deleted.append(obj_id) for index in to_be_deleted: self.objects.pop(index) def update(self, coords, ids): self.__delete_out_dated() for i, id in enumerate(ids): if id not in self.objects.keys(): self.objects[id] = {self.index: coords[i]} else: if self.index-1 in self.objects[id]: self.objects[id][self.index] = coords[i] else: last_index = max([key for key in self.objects[id].keys()]) for index in range(last_index+1, self.index+1): last_coord = self.objects[id][last_index] current_coord = coords[i] self.objects[id][index] = [last_coord[coord]+(current_coord[coord]-last_coord[coord])*( index-last_index)/(self.index-last_index) for coord in range(len(coords[i]))] self.index += 1 def get_nearest(self, distance) -> dict: distance_dict = dict() min_delta = float("inf") for obj_id, coords_dict in self.objects.items(): last_index = max([key for key in coords_dict.keys()]) current_coord = coords_dict[last_index] current_distance = (sum(x**2 for x in current_coord))**.5 distance_dict[obj_id] = current_distance for obj_id, obj_distance in distance_dict.items(): if abs(obj_distance-distance) < min_delta: min_delta = abs(obj_distance-distance) best_match = obj_id if min_delta < self.max_error: return self.objects[best_match] return None def init_monodepth_model(model_name): """Function to predict for a single image or folder of images """ model_path = os.path.join("./monodepth2/models", model_name) print("-> Loading model from ", model_path) encoder_path = os.path.join(model_path, "encoder.pth") depth_decoder_path = os.path.join(model_path, "depth.pth") # LOADING PRETRAINED MODEL print(" Loading pretrained encoder") encoder = networks.ResnetEncoder(18, False) loaded_dict_enc = torch.load(encoder_path, map_location=device) # extract the height and width of image that this model was trained with feed_height = loaded_dict_enc['height'] feed_width = loaded_dict_enc['width'] filtered_dict_enc = { k: v for k, v in loaded_dict_enc.items() if k in encoder.state_dict()} encoder.load_state_dict(filtered_dict_enc) encoder.to(device) encoder.eval() print(" Loading pretrained decoder") depth_decoder = networks.DepthDecoder( num_ch_enc=encoder.num_ch_enc, scales=range(4)) loaded_dict = torch.load(depth_decoder_path, map_location=device) depth_decoder.load_state_dict(loaded_dict) depth_decoder.to(device) depth_decoder.eval() return feed_height, feed_width, encoder, depth_decoder def get_relative_depth(frame, feed_height, feed_width, encoder, depth_decoder): input_image = pil.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) # PREDICTING ON EACH IMAGE IN TURN with torch.no_grad(): # Load image and preprocess original_width, original_height = input_image.size input_image = input_image.resize( (feed_width, feed_height), pil.LANCZOS) input_image = transforms.ToTensor()(input_image).unsqueeze(0) # PREDICTION input_image = input_image.to(device) features = encoder(input_image) outputs = depth_decoder(features) disp = outputs[("disp", 0)] disp_resized = torch.nn.functional.interpolate( disp, (original_height, original_width), mode="bilinear", align_corners=False) # 插值成源图像大小 _, depth = disp_to_depth(disp_resized, 0.1, 100) return depth def pixelcoord_to_worldcoord(depth_matrix, intrinsic_matrix, inv_extrinsics_matrix, pixel_indexs): cx = intrinsic_matrix[0, 2] cy = intrinsic_matrix[1, 2] fx = intrinsic_matrix[0, 0] fy = intrinsic_matrix[1, 1] v = pixel_indexs[0, :] u = pixel_indexs[1, :] depth_vector = depth_matrix.view(-1) v = (v-cy)*depth_vector/fy u = (u-cx)*depth_vector/fx ones = torch.ones(depth_vector.size()).to(device) P_cam = torch.stack((u, v, depth_vector, ones), dim=0) # [x: crosswise ,y: -lengthwise, z: vertical, 1] P_w = torch.mm(inv_extrinsics_matrix, P_cam) # np.savetxt('P_cam.txt', P_cam.cpu().numpy()[:, :10]) # np.savetxt('P_w.txt', P_w.cpu().numpy()[:, :10]) return P_w def get_mask(x_left, y_top, x_right, y_bottom, to_size, portion=1): """Edges all included""" if portion > 0 and portion < 1: mask = torch.bernoulli( torch.ones(y_bottom-y_top+1, x_right-x_left+1)*portion) else: mask = torch.ones(y_bottom-y_top+1, x_right-x_left+1) padding = ( x_left, # padding in left to_size[1]-x_right-1, # padding in right y_top, # padding in top to_size[0]-y_bottom-1 # padding in bottom ) mask = torch.nn.functional.pad( mask, padding, mode="constant", value=0).type(torch.bool).to(device) return mask def find_diff(last_frame, current_frame, threshold=10): diff = cv2.absdiff(last_frame, current_frame) diff = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) static_points = torch.from_numpy((diff < threshold)).to(device) return static_points def get_scale(relative_disp: torch.tensor, intrinsic_matrix: torch.tensor, inv_extrinsics_matrix: torch.tensor, camera_height: float, pixel_indexs, current_frame, last_frame, last_true_disp, portion=1): mask = get_mask(relative_disp.size()[1]*3//8, relative_disp.size()[0]*27//40, relative_disp.size()[1]*5//8, relative_disp.size()[0]*37//40, relative_disp.size(), portion=portion) road_points = relative_disp*mask P_w = pixelcoord_to_worldcoord(road_points, intrinsic_matrix, inv_extrinsics_matrix, pixel_indexs) rel_heights = torch.masked_select(P_w[2, :], mask.view(-1)) # 选取z坐标 std = torch.std(rel_heights) mean = torch.mean(rel_heights) threshold_mask = torch.lt(torch.abs(rel_heights-mean), std) rel_heights = torch.masked_select(rel_heights, threshold_mask.view(-1)) scale_camera_height_based = camera_height / \ (rel_heights.sum()/rel_heights.shape[0]) if last_frame is not None and last_true_disp is not None: static_points = find_diff(last_frame, current_frame) scale_static_points_based = torch.sum(last_true_disp*static_points.reshape_as(last_true_disp)) /\ torch.sum(relative_disp*static_points.reshape_as(relative_disp)) scale = .1*scale_camera_height_based+0.9*scale_static_points_based # print(torch.sum(static_points) / last_true_disp.numel()) else: scale = scale_camera_height_based return scale def init_darknet_network(config_file: str, data_file: str, weights_file: str,): network, class_names, class_colors = darknet.load_network( config_file, data_file, weights_file, batch_size=1) return network, class_names, class_colors def detection(darknet_network, class_names, class_colors, frame, confidence_thresh=0.25): original_height = frame.shape[0] original_width = frame.shape[1] network_width = darknet.network_width(darknet_network) network_height = darknet.network_height(darknet_network) frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame_resized = cv2.resize(frame_rgb, (network_width, network_height), interpolation=cv2.INTER_LINEAR) img_for_detect = darknet.make_image(network_width, network_height, 3) darknet.copy_image_from_bytes(img_for_detect, frame_resized.tobytes()) detections = darknet.detect_image( darknet_network, class_names, img_for_detect, thresh=confidence_thresh) darknet.free_image(img_for_detect) detections_resized = [] for label, confidence, bbox in detections: x, y, w, h = bbox bbox = (x*original_width/network_width, y*original_height/network_height, w*original_width/network_width, h*original_height/network_height,) detections_resized.append((label, confidence, bbox)) return detections_resized def get_coordinates(P_w, outputs, frame): measurement_list = [] id_list = [] for output in outputs: x1, y1, x2, y2, id = output # mask = get_mask(x1+(x2-x1)//10, y1+(y2-y1)//10, # x2-(x2-x1)//10, y2-(y2-y1)//10, frame.shape) mask = get_mask(x1, y1, x2, y2, frame.shape) x_coords = torch.masked_select(P_w[0, :], mask.view(-1)) y_coords = torch.masked_select(P_w[1, :], mask.view(-1)) z_coords = torch.masked_select(P_w[2, :], mask.view(-1)) coords = torch.stack((x_coords, y_coords, z_coords), dim=0) distance_w = torch.norm(coords, p=2, dim=0) min_distance = torch.min(distance_w) index = (distance_w == min_distance).nonzero().flatten()[0] x_distance = float(coords[0, index]) y_distance = float(coords[1, index]) z_distance = float(coords[2, index]) measurement_list.append([x_distance, y_distance, z_distance]) id_list.append(id) return measurement_list, id_list # @profile def main(): # # read form camera # intrinsic_matrix = params.intrinsic_matrix # camera = CameraCapture((0,), intrinsic_matrix, dist_coeffs) # camera = CameraCapture( # (gstreamer_pipeline(), cv2.CAP_GSTREAMER), intrinsic_matrix, dist_coeffs) # read form file camera = FileCapture("./img") intrinsic_matrix = camera.intrinsic_matrix # cv2.namedWindow("Test camera") # cv2.namedWindow("Result") # cv2.namedWindow("MultiTracker") # choices = ["mono_640x192", # "stereo_640x192", # "mono+stereo_640x192", # "mono_no_pt_640x192", # "stereo_no_pt_640x192", # "mono+stereo_no_pt_640x192", # "mono_1024x320", # "stereo_1024x320", # "mono+stereo_1024x320"] # initiate monodepth feed_height, feed_width, encoder, depth_decoder = init_monodepth_model( "mono_640x192") # initiate yolo darknet_network, class_names, class_colors = init_darknet_network(config_file="./darknet/yolo-obj.cfg", data_file="./darknet/data/obj.data", weights_file="./darknet/yolo-obj.weights") # initiate deep track cfg = get_config() cfg.merge_from_file("deep_sort/configs/deep_sort.yaml") deepsort = build_tracker(cfg, use_cuda=torch.cuda.is_available()) # initiate Kalman filter measurement_matrix = np.array( [[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0]], np.float32) transition_matrix = np.array( [[1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 1], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]], np.float32) process_noise_cov = np.eye(6, dtype=np.float32) * 1e-3 measurement_noise_cov = np.eye(3, dtype=np.float32) * 1e-1 kalman_filter = KalmanFilter(6, 3, measurement_matrix, transition_matrix, process_noise_cov, measurement_noise_cov) # initiate trajectory recorder trajectory_recorder = Trajectory() success, frame = camera.read() pixel_indexs = torch.tensor([[v, u] for v in range(frame.shape[0]) for u in range(frame.shape[1])]).t().to(device) last_frame = None last_true_disp = None last_y = dict() time_serial_index = 0 while success: last_run_time = time.time() # key = cv2.waitKey(1) # # if key == 27 or not success or\ # # cv2.getWindowProperty("Test camera", cv2.WND_PROP_AUTOSIZE) < 1 or\ # # cv2.getWindowProperty("Result", cv2.WND_PROP_AUTOSIZE) < 1 or\ # # cv2.getWindowProperty("MultiTracker", cv2.WND_PROP_AUTOSIZE) < 1:
natural. The value of logawidth sets the width of the Gauss in ln(agrain), so for logawidth<<1 this give a real width of logawidth*agraincm. wfact : float Grid width of na sampling points in units of logawidth. The Gauss distribution of grain sizes is cut off at agrain * exp(wfact*logawidth) and agrain * exp(-wfact*logawidth). Default = 3 na : int Number of size sampling points (if logawidth set, default=20) chopforward : float If >0 this gives the angle (in degrees from forward) within which the scattering phase function should be kept constant, essentially removing the strongly peaked forward scattering. This is useful for large grains (large ratio 2*pi*agraincm/lamcm) where the forward scattering peak is extremely strong, yet extremely narrow. If we are not interested in very forward-peaked scattering (e.g. only relevant when modeling e.g. the halo around the moon on a cold winter night), this will remove this component and allow a lower angular grid resolution for the theta grid. errtol : float Tolerance of the relative difference between kscat and the integral over the zscat Z11 element over angle. If this tolerance is exceeded, a warning is given. verbose : bool If set to True, the code will give some feedback so that one knows what it is doing if it becomes slow. extrapolate : bool If set to True, then if the wavelength grid lamcm goes out of the range of the wavelength grid of the optical constants file, then it will make a suitable extrapolation: keeping the optical constants constant for lamcm < minimum, and extrapolating log-log for lamcm > maximum. Returns ------- A dictionary with the following keys: * kabs : ndarray Absorption opacity kappa_abs_nu (a numpy array) in units of cm^2/gram * ksca : ndarray Scattering opacity kappa_abs_nu (a numpy array) in units of cm^2/gram * gsca : ndarray The <cos(theta)> g-factor of scattering * theta : ndarray (optional, only if theta is given at input) The theta grid itself (just a copy of what was given) * zscat : ndarray (optional, only if theta is given at input) The components of the scattering Mueller matrix Z_ij for each wavelength and each scattering angel. The normalization of Z is such that kscat can be reproduced (as can be checked) by the integral: 2*pi*int_{-1}^{+1}Z11(mu)dmu=kappa_scat. For symmetry reasons only 6 elements of the Z matrix are returned: Z11, Z12, Z22, Z33, Z34, Z44. Note that Z21 = Z12 and Z43 = -Z34. The scattering matrix is normalized such that if a plane wave with Stokes flux Fin = (Fin_I,Fin_Q,Fin_U,Fin_V) hits a dust grain (which has mass mgrain), then the scattered flux Fout = (Fout_I,Fout_Q,Fout_U,Fout_V) at distance r from the grain at angle theta is given by Fout(theta) = (mgrain/r^2) * Zscat . Fin where . is the matrix-vector multiplication. Note that the Stokes components must be such that the horizontal axis in the "image" is pointing in the scattering plane. This means that radiation with Fin_Q < 0 is scattered well, because it is vertically polarized (along the scattering angle axis), while radiation with Fin_Q > 0 is scatterd less well because it is horizontally polarized (along the scattering plane). * kscat_from_z11 : ndarray (optional, only if theta is given at input) The kscat computed from the (above mentioned) integral of Z11 over all angles. This should be nearly identical to kscat if the angular grid is sufficiently fine. If there are strong differences, this is an indication that the angular gridding (the theta grid) is not fine enough. But you should have then automatically gotten a warning message as well (see errtol). * wavmic : ndarray (optional, only if extrapolate is set to True) The original wavelength grid from the optical constants file, with possibly an added extrapolated * ncoef : ndarray (optional, only if extrapolate is set to True) The optical constant n at that grid * kcoef : ndarray (optional, only if extrapolate is set to True) The optical constant k at that grid * agr : ndarray (optional, only if logawidth is not None) Grain sizes * wgt : ndarray (optional, only if logawidth is not None) The averaging weights of these grain (not the masses!) The sum of wgt.sum() must be 1. * zscat_nochop : ndarray (optional, only if chopforward > 0) The zscat before the forward scattering was chopped off * kscat_nochop : ndarray (optional, only if chopforward > 0) The kscat originally from the bhmie code """ # # Load the optical constants # if matdens is None: msg = "Unknown material density matdens" raise ValueError(msg) if agraincm is None: msg = "Unknown grain size agraincm" raise ValueError(msg) if lamcm is None: msg = "Unknown wavelength grid lamcm" raise ValueError(msg) if theta is None: angles = np.array([0., 90., 180.]) # Minimalistic angular s if chopforward != 0.: warnings.warn("Chopping disabled. Chopping is only possible if theta grid is given. ", RuntimeWarning) else: angles = theta # # Check that the theta array goes from 0 to 180 or # 180 to 0, and store which is 0 and which is 180 # if angles[0] != 0: msg = "First element of the angular grid array is not 0. Scattering angle grid must extend from 0 to 180 " \ "degrees." raise ValueError(msg) if angles[-1] != 180: msg = "Last element of the angular grid array is not 180. Scattering angle grid must extend from 0 to 180 " \ "degrees." raise ValueError(msg) nang = angles.shape[0] # # Load the optical constants # data = np.loadtxt(fname) wavmic, ncoef, kcoef = data.T if wavmic.size <= 1: msg = "Optical constants file must have at least two rows with two different wavelengths" raise ValueError(msg) if wavmic[1] == wavmic[0]: msg = "Optical constants file must have at least two rows with two different wavelengths" raise ValueError(msg) # # Check range, and if needed and requested, extrapolate the # optical constants to longer or shorter wavelengths # if extrapolate: wmin = np.min(lamcm)*1e4 * 0.999 wmax = np.max(lamcm)*1e4 * 1.001 if wmin < np.min(wavmic): if wavmic[0] < wavmic[1]: ncoef = np.append([ncoef[0]], ncoef) kcoef = np.append([kcoef[0]], kcoef) wavmic = np.append([wmin], wavmic) else: ncoef = np.append(ncoef, [ncoef[-1]]) kcoef = np.append(kcoef, [kcoef[-1]]) wavmic = np.append(wavmic, [wmin]) if wmax > np.max(wavmic): if wavmic[0] < wavmic[1]: ncoef = np.append(ncoef, [ncoef[-1] * np.exp((np.log(wmax) - np.log(wavmic[-1])) * (np.log(ncoef[-1]) - np.log(ncoef[-2])) / (np.log(wavmic[-1]) - np.log(wavmic[-2])))]) kcoef = np.append(kcoef, [kcoef[-1]*np.exp((np.log(wmax) - np.log(wavmic[-1])) * (np.log(kcoef[-1]) - np.log(kcoef[-2])) / (np.log(wavmic[-1]) - np.log(wavmic[-2])))]) wavmic = np.append(wavmic, [wmax]) else: ncoef = np.append(ncoef, [ncoef[0]*np.exp((np.log(wmax)-np.log(wavmic[0])) * (np.log(ncoef[0]) - np.log(ncoef[1])) / (np.log(wavmic[0]) - np.log(wavmic[1])))]) kcoef = np.append(kcoef, [kcoef[0]*np.exp((np.log(wmax) - np.log(wavmic[0])) * (np.log(kcoef[0]) - np.log(kcoef[1])) / (np.log(wavmic[0]) - np.log(wavmic[1])))]) wavmic = np.append([wmax], wavmic) else: if lamcm.min() < wavmic.min()*1e-4: print(lamcm.min(), wavmic.min()*1e4) raise ValueError("Wavelength range out of range of the optical constants file") if lamcm.max() > wavmic.max()*1e-4: print(lamcm.min(), wavmic.min()*1e4) raise ValueError("Wavelength range out of range of the optical constants file") # Interpolate # Note: Must be within range, otherwise stop # f = interp1d(np.log(wavmic*1e-4), np.log(ncoef)) ncoefi = np.exp(f(np.log(lamcm))) f = interp1d(np.log(wavmic*1e-4), np.log(kcoef)) kcoefi = np.exp(f(np.log(lamcm))) # # Make the complex index of refraction # refidx = ncoefi + kcoefi*1j # # Make a size distribution for the grains # If width is not set, then take just one size # if logawidth is None: agr = np.array([agraincm]) wgt = np.array([1.0]) else: if logawidth != 0.0: agr = np.exp(np.linspace(np.log(agraincm) - wfact * logawidth, np.log(agraincm) + wfact * logawidth, na)) wgt = np.exp(-0.5*((np.log(agr / agraincm)) / logawidth)**2) wgt = wgt / wgt.sum() else: agr = np.array([agraincm]) wgt = np.array([1.0]) # # Get the true number of grain sizes # nagr = agr.size # # Compute the geometric cross sections # siggeom = np.pi*agr*agr # # Compute the mass of the grain # mgrain = (4*np.pi/3.0)*matdens*agr*agr*agr # # Now prepare
<gh_stars>0 # -*- coding: utf-8 -*- # Copyright 2011, <NAME>, <NAME>, JRL, CNRS/AIST from __future__ import print_function import sys import pinocchio from dynamic_graph import plug from dynamic_graph.sot.core.derivator import Derivator_of_Vector from dynamic_graph.sot.core.op_point_modifier import OpPointModifier from dynamic_graph.sot.core.robot_simu import RobotSimu from dynamic_graph.tools import addTrace from dynamic_graph.tracer_real_time import TracerRealTime if sys.version_info.major == 2: from abc import ABCMeta, abstractmethod class ABC: __metaclass__ = ABCMeta else: from abc import ABC, abstractmethod class AbstractRobot(ABC): """ This class instantiates all the entities required to get a consistent representation of a robot, mainly: - device : to integrate velocities into angular control, - dynamic: to compute forward geometry and kinematics, - zmpFromForces: to compute ZMP force foot force sensors, - stabilizer: to stabilize balanced motions Operational points are stored into 'OperationalPoints' list. Some of them are also accessible directly as attributes: - leftWrist, - rightWrist, - leftAnkle, - rightAnkle, - Gaze. Operational points are mapped to the actual joints in the robot model via 'OperationalPointsMap' dictionary. This attribute *must* be defined in the subclasses Other attributes require to be defined: - halfSitting: half-sitting position is the robot initial pose. This attribute *must* be defined in subclasses. - dynamic: The robot dynamic model. - device: The device that integrates the dynamic equation, namely the real robot or a simulator - dimension: The configuration size. """ def _initialize(self): self.OperationalPoints = [] """ Operational points are specific interesting points of the robot used to control it. When an operational point is defined, signals corresponding to the point position and jacobian are created. For instance if creating an operational point for the left-wrist, the associated signals will be called "left-wrist" and "Jleft-wrist" for respectively the position and the jacobian. """ self.AdditionalFrames = [] """ Additional frames are frames which are defined w.r.t an operational point and provides an interesting transformation. It can be used, for instance, to store the sensor location. The contained elements must be triplets matching: - additional frame name, - transformation w.r.t to the operational point, - operational point file. """ self.frames = dict() """ Additional frames defined by using OpPointModifier. """ # FIXME: the following options are /not/ independent. # zmp requires acceleration which requires velocity. """ Enable velocity computation. """ self.enableVelocityDerivator = False """ Enable acceleration computation. """ self.enableAccelerationDerivator = False """ Enable ZMP computation """ self.enableZmpComputation = False """ Tracer used to log data. """ self.tracer = None """ How much data will be logged. """ self.tracerSize = 2**20 """ Automatically recomputed signals through the use of device.after. This list is maintained in order to clean the signal list device.after before exiting. """ self.autoRecomputedSignals = [] """ Which signals should be traced. """ self.tracedSignals = { 'dynamic': ["com", "zmp", "angularmomentum", "position", "velocity", "acceleration"], 'device': ['zmp', 'control', 'state'] } def help(self): print(AbstractHumanoidRobot.__doc__) def _removeMimicJoints(self, urdfFile=None, urdfString=None): """ Parse the URDF, extract the mimic joints and call removeJoints. """ # get mimic joints import xml.etree.ElementTree as ET if urdfFile is not None: assert urdfString is None, "One and only one of input argument should be provided" root = ET.parse(urdfFile) else: assert urdfString is not None, "One and only one of input argument should be provided" root = ET.fromstring(urdfString) mimicJoints = list() for e in root.iter('joint'): if 'name' in e.attrib: name = e.attrib['name'] for c in e: if hasattr(c, 'tag') and c.tag == 'mimic': mimicJoints.append(name) self.removeJoints(mimicJoints) def removeJoints(self, joints): """ - param joints: a list of joint names to be removed from the self.pinocchioModel """ jointIds = list() for j in joints: if self.pinocchioModel.existJointName(j): jointIds.append(self.pinocchioModel.getJointId(j)) if len(jointIds) > 0: q = pinocchio.neutral(self.pinocchioModel) self.pinocchioModel = pinocchio.buildReducedModel(self.pinocchioModel, jointIds, q) self.pinocchioData = pinocchio.Data(self.pinocchioModel) def loadModelFromString(self, urdfString, rootJointType=pinocchio.JointModelFreeFlyer, removeMimicJoints=True): """ Load a URDF model contained in a string - param rootJointType: the root joint type. None for no root joint. - param removeMimicJoints: if True, all the mimic joints found in the model are removed. """ if rootJointType is None: self.pinocchioModel = pinocchio.buildModelFromXML(urdfString) else: self.pinocchioModel = pinocchio.buildModelFromXML(urdfString, rootJointType()) self.pinocchioData = pinocchio.Data(self.pinocchioModel) if removeMimicJoints: self._removeMimicJoints(urdfString=urdfString) def loadModelFromUrdf(self, urdfPath, urdfDir=None, rootJointType=pinocchio.JointModelFreeFlyer, removeMimicJoints=True): """ Load a model using the pinocchio urdf parser. This parser looks for urdf files in which kinematics and dynamics information have been added. - param urdfPath: a path to the URDF file. - param urdfDir: A list of directories. If None, will use ROS_PACKAGE_PATH. """ if urdfPath.startswith("package://"): from os import path n1 = 10 # len("package://") n2 = urdfPath.index(path.sep, n1) pkg = urdfPath[n1:n2] relpath = urdfPath[n2 + 1:] import rospkg rospack = rospkg.RosPack() abspkg = rospack.get_path(pkg) urdfFile = path.join(abspkg, relpath) else: urdfFile = urdfPath if urdfDir is None: import os urdfDir = os.environ["ROS_PACKAGE_PATH"].split(':') if rootJointType is None: self.pinocchioModel = pinocchio.buildModelFromUrdf(urdfFile) else: self.pinocchioModel = pinocchio.buildModelFromUrdf(urdfFile, rootJointType()) self.pinocchioData = pinocchio.Data(self.pinocchioModel) if removeMimicJoints: self._removeMimicJoints(urdfFile=urdfFile) def initializeOpPoints(self): for op in self.OperationalPoints: self.dynamic.createOpPoint(op, self.OperationalPointsMap[op]) def createFrame(self, frameName, transformation, operationalPoint): frame = OpPointModifier(frameName) frame.setTransformation(transformation) plug(self.dynamic.signal(operationalPoint), frame.positionIN) plug(self.dynamic.signal("J{0}".format(operationalPoint)), frame.jacobianIN) frame.position.recompute(frame.position.time + 1) frame.jacobian.recompute(frame.jacobian.time + 1) return frame def setJointValueInConfig(self, q, jointNames, jointValues): """ q: configuration to update jointNames: list of existing joint names in self.pinocchioModel jointValues: corresponding joint values. """ model = self.pinocchioModel for jn, jv in zip(jointNames, jointValues): assert model.existJointName(jn) joint = model.joints[model.getJointId(jn)] q[joint.idx_q] = jv @abstractmethod def defineHalfSitting(self, q): """ Define half sitting configuration using the pinocchio Model (i.e. with quaternions and not with euler angles). method setJointValueInConfig may be usefull to implement this function. """ pass def initializeRobot(self): """ If the robot model is correctly loaded, this method will then initialize the operational points, set the position to half-sitting with null velocity/acceleration. To finish, different tasks are initialized: - the center of mass task used to keep the robot stability - one task per operational point to ease robot control """ if not hasattr(self, 'dynamic'): raise RuntimeError("Dynamic robot model must be initialized first") if not hasattr(self, 'device') or self.device is None: # raise RuntimeError("A device is already defined.") self.device = RobotSimu(self.name + '_device') self.device.resize(self.dynamic.getDimension()) """ Robot timestep """ self.timeStep = self.device.getTimeStep() # Compute half sitting configuration import numpy """ Half sitting configuration. """ self.halfSitting = numpy.asarray(pinocchio.neutral(self.pinocchioModel)).flatten().tolist() self.defineHalfSitting(self.halfSitting) self.halfSitting[3:7] = [0., 0., 0.] # Replace quaternion by RPY. # Set the device limits. def get(s): s.recompute(0) return s.value def opposite(v): return [-x for x in v] self.device.setPositionBounds(get(self.dynamic.lowerJl), get(self.dynamic.upperJl)) self.device.setVelocityBounds(opposite(get(self.dynamic.upperVl)), get(self.dynamic.upperVl)) self.device.setTorqueBounds(opposite(get(self.dynamic.upperTl)), get(self.dynamic.upperTl)) # Freeflyer reference frame should be the same as global # frame so that operational point positions correspond to # position in freeflyer frame. self.device.set(self.halfSitting) plug(self.device.state, self.dynamic.position) if self.enableVelocityDerivator: self.velocityDerivator = Derivator_of_Vector('velocityDerivator') self.velocityDerivator.dt.value = self.timeStep plug(self.device.state, self.velocityDerivator.sin) plug(self.velocityDerivator.sout, self.dynamic.velocity) else: self.dynamic.velocity.value = self.dimension * (0., ) if self.enableAccelerationDerivator: self.accelerationDerivator = \ Derivator_of_Vector('accelerationDerivator') self.accelerationDerivator.dt.value = self.timeStep plug(self.velocityDerivator.sout, self.accelerationDerivator.sin) plug(self.accelerationDerivator.sout, self.dynamic.acceleration) else: self.dynamic.acceleration.value = self.dimension * (0., ) def addTrace(self, entityName, signalName): if self.tracer: self.autoRecomputedSignals.append('{0}.{1}'.format(entityName, signalName)) addTrace(self, self.tracer, entityName, signalName) def initializeTracer(self): if not self.tracer: self.tracer = TracerRealTime('trace') self.tracer.setBufferSize(self.tracerSize) self.tracer.open('/tmp/', 'dg_', '.dat') # Recompute trace.triger at each iteration to enable tracing. self.device.after.addSignal('{0}.triger'.format(self.tracer.name)) def traceDefaultSignals(self): # Geometry / operational points for s in self.OperationalPoints + self.tracedSignals['dynamic']: self.addTrace(self.dynamic.name, s) # Geometry / frames for (frameName, _, _) in self.AdditionalFrames: for s in ['position', 'jacobian']: self.addTrace(self.frames[frameName].name, s) # Device for s in self.tracedSignals['device']: self.addTrace(self.device.name, s) if type(self.device) != RobotSimu: self.addTrace(self.device.name, 'robotState') # Misc if self.enableVelocityDerivator: self.addTrace(self.velocityDerivator.name, 'sout') if self.enableAccelerationDerivator: self.addTrace(self.accelerationDerivator.name, 'sout') def __init__(self, name, tracer=None): self._initialize() self.name = name # Initialize tracer if necessary. if tracer: self.tracer = tracer def __del__(self): if self.tracer: self.stopTracer() def startTracer(self): """ Start the tracer if it does not already been stopped. """ if self.tracer: self.tracer.start() def stopTracer(self): """ Stop and destroy tracer. """ if self.tracer: self.tracer.dump() self.tracer.stop() self.tracer.close() self.tracer.clear() for s in self.autoRecomputedSignals: self.device.after.rmSignal(s) self.tracer = None def reset(self, posture=None): """ Restart the control from another position. This method has not been extensively tested and should be used carefully. In particular, tasks should be removed from the solver before attempting a reset. """ if not posture: posture = self.halfSitting self.device.set(posture) self.dynamic.com.recompute(self.device.state.time + 1) self.dynamic.Jcom.recompute(self.device.state.time + 1) for op in self.OperationalPoints: self.dynamic.signal(self.OperationalPointsMap[op]).recompute(self.device.state.time + 1) self.dynamic.signal('J' + self.OperationalPointsMap[op]).recompute(self.device.state.time + 1) class AbstractHumanoidRobot(AbstractRobot):
'health_at_a_glance': health = {} for key, val in data[category]: if key not in health: health[key] = val else: health[key].update(val) data[category] = health continue elif isinstance(data[category], list) and data[category]: for tag in ('label', 'location'): if tag in data[category][0]: data[category] = dict([(x[tag], x) for x in data[category]]) break elif data[category] in ['', []]: data[category] = None return data return self._info_tag('SERVER_INFO', 'GET_EMBEDDED_HEALTH', 'GET_EMBEDDED_HEALTH_DATA', process=process) # Ok, special XML structures. Yay. def _parse_get_embedded_health_data_drives(self, element): ret = [] for bp in element: if bp.tag != 'BACKPLANE': raise IloError("Unexpected data returned: %s" % bp.tag) backplane = obj = {'drive_bays': {}} ret.append(backplane) for elt in bp: if elt.tag == 'DRIVE_BAY': obj = {} backplane['drive_bays'][int(elt.get('VALUE'))] = obj else: obj[elt.tag.lower()] = elt.get('VALUE') return {'drives_backplanes': ret} def _parse_get_embedded_health_data_memory(self, element): ret = {} for elt in element: fname = '_parse_%s_%s' % (element.tag.lower(), elt.tag.lower()) if hasattr(self, fname): ret.update(getattr(self, fname)(elt)) continue ret[elt.tag.lower()] = self._element_children_to_dict(elt) return {element.tag.lower(): ret} _parse_memory_memory_details_summary = _parse_get_embedded_health_data_memory def _parse_memory_memory_details(self, element): ret = {} for elt in element: if elt.tag not in ret: ret[elt.tag] = {} data = self._element_children_to_dict(elt) ret[elt.tag]["socket %d" % data["socket"]] = data return {element.tag.lower(): ret} def _parse_get_embedded_health_data_nic_information(self, element): return {'nic_information': [self._element_children_to_dict(elt) for elt in element]} # Can you notice the misspelling?Yes, this is an actual bug in the HP firmware, seen in at least ilo3 1.70 _parse_get_embedded_health_data_nic_infomation = _parse_get_embedded_health_data_nic_information def _parse_get_embedded_health_data_firmware_information(self, element): ret = {} for elt in element: data = self._element_children_to_dict(elt) ret[data['firmware_name']] = data['firmware_version'] return {element.tag.lower(): ret} def _parse_get_embedded_health_data_storage(self, element): key = element.tag.lower() ret = {key: []} for ctrl in element: if ctrl.tag == 'DISCOVERY_STATUS': ret['%s_%s' % (key, ctrl.tag.lower())] = self._element_children_to_dict(ctrl)['status'] continue data = {} for elt in ctrl: tag = elt.tag.lower() if tag in ('drive_enclosure', 'logical_drive'): tag += 's' if tag not in data: data[tag] = [] if tag == 'drive_enclosures': data[tag].append(self._element_children_to_dict(elt)) else: data[tag].append(self._parse_logical_drive(elt)) else: data[tag] = elt.get('VALUE') ret[key].append(data) return ret def _parse_logical_drive(self, element): data = {} for elt in element: tag = elt.tag.lower() if tag == 'physical_drive': tag += 's' if tag not in data: data[tag] = [] data[tag].append(self._element_children_to_dict(elt)) else: data[tag] = elt.get('VALUE') return data def _parse_get_embedded_health_data_power_supplies(self, element): key = element.tag.lower() ret = {key: {}} for elt in element: data = self._element_children_to_dict(elt) if 'label' in data: ret[key][data['label']] = data else: ret[elt.tag.lower()] = data return ret def get_enclosure_ip_settings(self): """Get the enclosure bay static IP settings""" return self._info_tag('RACK_INFO', 'GET_ENCLOSURE_IP_SETTINGS') def get_encrypt_settings(self): """Get the iLO encryption settings""" return self._info_tag('RIB_INFO', 'GET_ENCRYPT_SETTINGS') def get_ers_settings(self): """Get the ERS Insight Remote Support settings""" return self._info_tag('RIB_INFO', 'GET_ERS_SETTINGS') def get_federation_all_groups(self): """Get all federation group names""" def process(data): if isinstance(data, dict): data = data.values() return data return self._info_tag('RIB_INFO', 'GET_FEDERATION_ALL_GROUPS', process=process) def get_federation_all_groups_info(self): """Get all federation group names and associated privileges""" def process(data): if isinstance(data, dict): data = data.values() data = [dict([(key, {'yes': True, 'no': False}.get(val['value'].lower(), val['value'])) for (key, val) in group]) for group in data] return dict([(x['group_name'], x) for x in data]) return self._info_tag('RIB_INFO', 'GET_FEDERATION_ALL_GROUPS_INFO', process=process) def get_federation_group(self, group_name): """Get privileges for a specific federation group""" def process(data): return dict([(key, {'yes': True, 'no': False}.get(val['value'].lower(), val['value'])) for (key, val) in data.values()[0]]) return self._info_tag('RIB_INFO', 'GET_FEDERATION_GROUP', attrib={'GROUP_NAME': group_name}, process=process) def get_federation_multicast(self): """Get the iLO federation mulicast settings""" return self._info_tag('RIB_INFO', 'GET_FEDERATION_MULTICAST') def get_fips_status(self): """Is the FIPS-mandated AES/3DESencryption enforcement in place""" return self._info_tag('RIB_INFO', 'GET_FIPS_STATUS') def get_fw_version(self): """Get the iLO type and firmware version, use get_product_name to get the server model""" return self._info_tag('RIB_INFO', 'GET_FW_VERSION') def get_global_settings(self): """Get global iLO settings""" return self._info_tag('RIB_INFO', 'GET_GLOBAL_SETTINGS') def get_host_data(self, decoded_only=True): """Get SMBIOS records that describe the host. By default only the ones where human readable information is available are returned. To get all records pass :attr:`decoded_only=False` """ def process(data): if decoded_only: data = [x for x in data if len(x) > 2] return data return self._info_tag('SERVER_INFO', 'GET_HOST_DATA', process=process) def get_host_power_reg_info(self): """Get power regulator information""" return self._control_tag('SERVER_INFO', 'GET_HOST_POWER_REG_INFO') def get_host_power_saver_status(self): """Get the configuration of the ProLiant power regulator""" return self._info_tag('SERVER_INFO', 'GET_HOST_POWER_SAVER_STATUS', 'GET_HOST_POWER_SAVER') def get_host_power_status(self): """Whether the server is powered on or not""" return self._info_tag('SERVER_INFO', 'GET_HOST_POWER_STATUS', 'GET_HOST_POWER', process=lambda data: data['host_power']) def get_host_pwr_micro_ver(self): """Get the version of the power micro firmware""" return self._info_tag('SERVER_INFO', 'GET_HOST_PWR_MICRO_VER', process=lambda data: data['pwr_micro']['version']) def get_ilo_event_log(self): """Get the full iLO event log""" def process(data): if isinstance(data, dict) and 'event' in data: return [data['event']] return data return self._info_tag('RIB_INFO', 'GET_EVENT_LOG', 'EVENT_LOG', process=process) def get_language(self): """Get the default language set""" return self._info_tag('RIB_INFO', 'GET_LANGUAGE') def get_all_languages(self): """Get the list of installed languages - broken because iLO returns invalid XML""" return self._info_tag('RIB_INFO', 'GET_ALL_LANGUAGES') def get_all_licenses(self): """Get a list of all license types and licenses""" def process(data): if not isinstance(data, list): data = data.values() return [dict([(x[0], x[1]['value']) for x in row]) for row in data] return self._info_tag('RIB_INFO', 'GET_ALL_LICENSES', process=process) def get_hotkey_config(self): """Retrieve hotkeys available for use in remote console sessions""" return self._info_tag('RIB_INFO', 'GET_HOTKEY_CONFIG') def get_network_settings(self): """Get the iLO network settings""" return self._info_tag('RIB_INFO', 'GET_NETWORK_SETTINGS') def get_oa_info(self): """Get information about the Onboard Administrator of the enclosing chassis""" return self._info_tag('BLADESYSTEM_INFO', 'GET_OA_INFO') def get_one_time_boot(self): """Get the one time boot state of the host""" # Inconsistency between iLO 2 and 3, let's fix that def process(data): if 'device' in data['boot_type']: data['boot_type'] = data['boot_type']['device'] return data['boot_type'].lower() return self._info_tag('SERVER_INFO', 'GET_ONE_TIME_BOOT', ('ONE_TIME_BOOT', 'GET_ONE_TIME_BOOT'), process=process) def get_pending_boot_mode(self): """Get the pending boot mode (legaci or uefi)""" return self._info_tag('SERVER_INFO', 'GET_PENDING_BOOT_MODE', process=lambda data: data['boot_mode']) def get_persistent_boot(self): """Get the boot order of the host. For uEFI hosts (gen9+), this returns a list of tuples (name, description. For older host it returns a list of names""" def process(data): if isinstance(data, dict): data = list(data.items()) data.sort(key=lambda x: x[1]) return [x[0].lower() for x in data] elif isinstance(data[0], tuple): return data return [x.lower() for x in data] return self._info_tag('SERVER_INFO', 'GET_PERSISTENT_BOOT', ('PERSISTENT_BOOT', 'GET_PERSISTENT_BOOT'), process=process) def get_pers_mouse_keyboard_enabled(self): """Returns whether persistent mouse and keyboard are enabled""" return self._info_tag('SERVER_INFO', 'GET_PERS_MOUSE_KEYBOARD_ENABLED', process=lambda data: data['persmouse_enabled']) def get_power_cap(self): """Get the power cap setting""" return self._info_tag('SERVER_INFO', 'GET_POWER_CAP', process=lambda data: data['power_cap']) def get_power_readings(self): """Get current, min, max and average power readings""" return self._info_tag('SERVER_INFO', 'GET_POWER_READINGS') def get_product_name(self): """Get the model name of the server, use get_fw_version to get the iLO model""" return self._info_tag('SERVER_INFO', 'GET_PRODUCT_NAME', process=lambda data: data['product_name']) def get_pwreg(self): """Get the power and power alert threshold settings""" return self._info_tag('SERVER_INFO', 'GET_PWREG') def get_rack_settings(self): """Get the rack settings for an iLO""" return self._info_tag('RACK_INFO', 'GET_RACK_SETTINGS') def get_sdcard_status(self): """Get whether an SD card is connected to the server""" return self._info_tag('SERVER_INFO', 'GET_SDCARD_STATUS') def get_security_msg(self): """Retrieve the security message that is displayed on the login screen""" return self._info_tag('RIB_INFO', 'GET_SECURITY_MSG') def get_server_auto_pwr(self): """Get the automatic power on delay setting""" return self._info_tag('SERVER_INFO', 'GET_SERVER_AUTO_PWR', process=lambda data: data['server_auto_pwr']) def get_server_event_log(self): """Get the IML log of the server""" def process(data): if isinstance(data, dict) and 'event' in data: return [data['event']] return data return self._info_tag('SERVER_INFO', 'GET_EVENT_LOG', 'EVENT_LOG', process=process) def get_server_fqdn(self): """Get the fqdn of the server this iLO is managing""" return self._info_tag('SERVER_INFO', 'GET_SERVER_FQDN', 'SERVER_FQDN', process=lambda fqdn: fqdn['value']) def get_server_name(self): """Get the name of the server this iLO is managing""" return self._info_tag('SERVER_INFO', 'GET_SERVER_NAME', 'SERVER_NAME', process=lambda name: name['value']) def get_server_power_on_time(self): """How many minutes ago has the server been powered on""" return self._info_tag('SERVER_INFO', 'GET_SERVER_POWER_ON_TIME', 'SERVER_POWER_ON_MINUTES', process=lambda data: int(data['value'])) def get_smh_fqdn(self): """Get the fqdn of the HP System Management Homepage""" return self._info_tag('SERVER_INFO', 'GET_SMH_FQDN', 'SMH_FQDN', process=lambda fqdn: fqdn['value']) def get_snmp_im_settings(self): """Where does the iLO send SNMP traps to and which traps does it send""" return self._info_tag('RIB_INFO', 'GET_SNMP_IM_SETTINGS') def get_spatial(self): """Get location information""" return self._info_tag('SERVER_INFO', 'GET_SPATIAL', 'SPATIAL') def get_sso_settings(self): """Get the HP SIM Single Sign-On settings""" return self._info_tag('SSO_INFO', 'GET_SSO_SETTINGS') def get_supported_boot_mode(self): return self._info_tag('SERVER_INFO', 'GET_SUPPORTED_BOOT_MODE', process=lambda data: data['supported_boot_mode']) def get_topology(self): """Get rack topology information""" return self._info_tag('RACK_INFO', 'GET_TOPOLOGY') def get_tpm_status(self): """Get the status of the Trusted Platform Module""" return self._info_tag('SERVER_INFO', 'GET_TPM_STATUS') def get_twofactor_settings(self): """Get two-factor authentication settings""" return self._info_tag('RIB_INFO', 'GET_TWOFACTOR_SETTINGS') def get_uid_status(self): """Get the status of the UID light""" return self._info_tag('SERVER_INFO', 'GET_UID_STATUS', process=lambda data: data['uid']) def get_user(self, user_login): """Get user info about a specific user""" return self._info_tag('USER_INFO', 'GET_USER', attrib={'USER_LOGIN': user_login}) def get_vm_status(self, device="CDROM"): """Get the status of virtual media devices. Valid devices are FLOPPY and CDROM""" return self._info_tag('RIB_INFO', 'GET_VM_STATUS', attrib={'DEVICE': device}) def hotkey_config(self, ctrl_t=None, ctrl_u=None, ctrl_v=None, ctrl_w=None, ctrl_x=None, ctrl_y=None): """Change remote console hotkeys""" vars = locals() del vars['self'] elements
# -*- coding: utf-8 -*- {} import matplotlib.pyplot as plt import numpy as np import scipy import os import math from mpmath import * mp.dps = 25 mp.pretty = True # part 1:gif_splitfile to txt # 新建文件夹txt,用于存储原文件的分解文件集。 os.mkdir("C://george//PhD//papers//BHE_sc//result//txt") # os.chdir(path) 方法用于改变当前工作目录到指定的路径。此处创建路径到新建文件夹txt os.chdir("C://george//PhD//papers//BHE_sc//result//txt") txtfiles = os.getcwd() # 获得当前运行脚本所在目录作为文件储存地址 # define the path of the data file str_tec_file_path = "C://george//PhD//papers//BHE_sc//result//tec_0_5m.tec" data_num = 0 with open(str_tec_file_path, "r") as f_in: i = -1 # 此处写-1是因为要使输出文件名第一个必须是以0结尾,不然和part2的文件读入循环对不上。必须要对上是因为\n # part2数组值从0位开始储存的。 for line in f_in: if "=" not in line: txtfiles.write(line) # 读出单位文件中有多少行数据,存入变量data_num data_num = data_num + 1 elif "ZONE" in line: # 从关键词ZONE开始读取行 data_num = 0 i = i + 1 txtfiles = open("txtfile{}.txt".format(i), "w") # 格式化命名文件名存储 # 记录总共的分出文件数目,用于part 2 numfile = i + 1 # 关闭并完整文件释放内存 txtfiles.close() # plotting T_in T_out curves,建立作图文件夹及及改变工作路径 os.mkdir("C://george//PhD//papers//BHE_sc//result//png") os.chdir("C://george//PhD//papers//BHE_sc//result//png") pngfiles = os.getcwd() # 建立source term坐标矩阵,用以计算各热源对referece point的温度影响矩阵 po_x = np.array([40, 40, 40, 40, 40], dtype=float).reshape(-1, 1) + np.arange(0, 25, 5) po_y = np.arange(60, 35, -5).reshape(-1, 1) + np.zeros(5) po_dist_to_referencepo = np.zeros([5, 5]) Temp_po_to_referencepo = np.zeros([5, 5]) # 解析解1基础数据项,q是timestep变化量 q1 = -35 q2 = 35 q3 = 0 time_trans = 120 * 24 * 60 * 60 # 3个月一输出数据 T0 = 10 T = T0 poro = 10e-20 lamda_f = 0.5984 density_f = 998.2032 cp_f = 4182.0 lamda_sp = 2.0 density_sp = 1950.0 cp_sp = 1500.0 alpha_f = lamda_f / (density_f * cp_f) alpha_sp = lamda_sp / (density_sp * cp_sp) lamda_med = (1 - poro) * lamda_sp + poro * lamda_f alpha_med = (1 - poro) * alpha_sp + poro * alpha_f # 解析解2基础数据项: qq = np.array([-35, 0, 0, -35, 0, 0, -35, 0, 0, -35, 0]).reshape(1, -1) qq_all = np.repeat(qq, data_num, axis=0) expandedloads = np.array(qq) numtimesteps = 11 numbhe = 25 ppo_x = np.array([40, 40, 40, 40, 40], dtype=float).reshape(-1, 1) + np.arange(0, 25, 5) ppo_y = np.arange(60, 35, -5).reshape(-1, 1) + np.zeros(5) ppo_x_re = np.reshape(po_x, (-1, 1)) ppo_y_re = np.reshape(po_y, (-1, 1)) # 建立动态变量名 createVar = locals() # 建立月份名字表,因为数据记录从1月1日有一组数据,所以多出一个月数据。 month = [ " Temperature after 0 months ", " Temperature after 4 months", " Temperature after 8 months", " Temperature after 12 months", " Temperature after 16 months", " Temperature after 20 months", " Temperature after 24 months", " Temperature after 28 months", " Temperature after 32 months", " Temperature after 36 months", " Temperature after 40 months", " Temperature after 44 months", ] # 解析解2项: txtpath2 = f"C://george//PhD//papers//BHE_sc//result//txt//txtfile0.txt" # f格式化字符串 dist_arrayy = 0.0 with open(txtpath2, "r") as f_in_txt: for line in f_in_txt: # split line data_line = line.split(" ") # maxsplit # time_double = 0.0 dist_double2 = float(data_line[0]) cordinate2 = math.sqrt(dist_double2 ** 2 / 2) # put into the list dist_arrayy = np.vstack((dist_arrayy, cordinate2)) dist_arrayy_new = np.delete(dist_arrayy, 0, 0) numtemppoints = len(dist_arrayy_new) T2 = np.zeros([numtemppoints, numtimesteps]) coeff_all = np.zeros([numtemppoints, numtimesteps]) for currstep in range(0, numtimesteps): Temp_po_to_referencepo = np.zeros([numtemppoints, numbhe]) po_dist_to_referencepo = np.zeros([numtemppoints, numbhe]) localcoeff_all = np.zeros([numtemppoints, 1]) localcoeff = np.zeros([numtemppoints, numbhe]) localcoeff1 = np.zeros([numtemppoints, numbhe]) for i in range(0, numbhe): if time_trans * (currstep + 1) - time_trans * 0 > 0: for j in range(0, numtemppoints): po_dist_to_referencepo[j, i] = ( abs(ppo_x_re[i] - (dist_arrayy_new[j] + 1)) ** 2 + abs(ppo_y_re[i] - dist_arrayy_new[j]) ** 2 ) exp = po_dist_to_referencepo[j, i] / ( 4 * alpha_med * time_trans * (currstep + 1) ) n = e1(exp) localcoeff[j, i] = 1 / (4 * math.pi * lamda_med) * n if time_trans * (currstep + 1) - time_trans * 1 > 0: for j in range(0, numtemppoints): po_dist_to_referencepo[j, i] = ( abs(ppo_x_re[i] - (dist_arrayy_new[j] + 1)) ** 2 + abs(ppo_y_re[i] - dist_arrayy_new[j]) ** 2 ) exp1 = po_dist_to_referencepo[j, i] / ( 4 * alpha_med * time_trans * currstep ) n1 = e1(exp1) localcoeff[j, i] = ( localcoeff[j, i] - 1 / (4 * math.pi * lamda_med) * n1 ) localcoeff_all = np.sum(localcoeff, axis=1).reshape(-1, 1) coeff_all[:, 1:] = coeff_all[:, : numtimesteps - 1] coeff_all[:, :1] = localcoeff_all for currstep in range(0, numtimesteps): T2[:, currstep] = ( np.sum( coeff_all[:, numtimesteps - 1 - currstep :] * qq_all[:, : currstep + 1], axis=1, ) + 10 ) # loop over for m in range(0, numfile): # 文件读取路径 txtpath = f"C://george//PhD//papers//BHE_sc//result//txt//txtfile{m}.txt" # f格式化字符串 txtpath_ogs6 = f"C://george//PhD//papers//BHE_sc//result//txt_ogs6//txtfile{m}.txt" # 动态变量名每组赋初值0.0 createVar["dist_array" + str(m)] = 0.0 createVar["temperature_array_ogs5" + str(m)] = 0.0 createVar["temperature_array_ana" + str(m)] = 0.0 createVar["dist_array2" + str(m)] = 0.0 createVar["temperature_array_ana2" + str(m)] = 0.0 createVar["dist_array_ogs6" + str(m)] = 0.0 createVar["temperature_array_ogs6" + str(m)] = 0.0 # 解析解1: # if m == 0 or m ==2 or m ==3 or m ==5 or m ==6 or m ==8 or m ==9 or m ==10: # q = q2 # elif m == 1 or m ==4 or m ==7: # q = q1 if m == 0: with open(txtpath, "r") as f_in_txt: for line in f_in_txt: # split line data_line = line.split(" ") # maxsplit # time_double = 0.0 dist_double = float(data_line[0]) cordinate = math.sqrt(dist_double ** 2 / 2) temperature = float(data_line[1]) # 解析解数据项 time = time_trans + 10e-6 for i in range(0, 5): for j in range(0, 5): po_dist_to_referencepo[i, j] = ( abs(po_x[i, j] - (cordinate + 1)) ** 2 + abs(po_y[i, j] - cordinate) ** 2 ) for i in range(0, 5): for j in range(0, 5): exp = po_dist_to_referencepo[i, j] / (4 * alpha_med * time) n1 = e1(exp) Temp_po_to_referencepo[i, j] = ( q3 / (4 * math.pi * lamda_med) * n1 ) T = np.sum(Temp_po_to_referencepo) + T0 # put into the list createVar["dist_array" + str(m)] = np.vstack( (createVar["dist_array" + str(m)], cordinate) ) createVar["temperature_array_ogs5" + str(m)] = np.vstack( (createVar["temperature_array_ogs5" + str(m)], temperature) ) createVar["temperature_array_ana" + str(m)] = np.vstack( (createVar["temperature_array_ana" + str(m)], T) ) f_in_txt.close() # end of loop # 去除21和22行的0.0值,因为此值被带入了dist_array的list第一行,可查看variable explorer temperature_array观察。 # 目的是去除做图时的第一个数据0值。 dist_array_new = np.delete(createVar["dist_array" + str(m)], 0, 0) temperature_array_ogs5_new = np.delete( createVar["temperature_array_ogs5" + str(m)], 0, 0 ) temperature_array_ana_new = np.delete( createVar["temperature_array_ana" + str(m)], 0, 0 ) with open(txtpath_ogs6, "r") as f_in_txt: for line in f_in_txt: # split line data_line = line.split(" ") # maxsplit # time_double = 0.0 dist_double = float(data_line[0]) cordinate = math.sqrt(dist_double ** 2 / 2) temperature = float(data_line[1]) createVar["dist_array_ogs6" + str(m)] = np.vstack( (createVar["dist_array_ogs6" + str(m)], cordinate) ) createVar["temperature_array_ogs6" + str(m)] = np.vstack( (createVar["temperature_array_ogs6" + str(m)], temperature) ) f_in_txt.close() dist_array_new_ogs6 = np.delete(createVar["dist_array_ogs6" + str(m)], 0, 0) temperature_array_ogs6_new = np.delete( createVar["temperature_array_ogs6" + str(m)], 0, 0 ) # plotting plt.figure() plt.plot( scipy.dot(dist_array_new, 1.0), scipy.dot(temperature_array_ogs5_new, 1.0), color="r", ls=":", lw=1, marker="^", markersize=1.5, label="OGS5", ) plt.plot( scipy.dot(dist_array_new_ogs6, 1.0), scipy.dot(temperature_array_ogs6_new, 1.0), c="g", ls=":", lw=1, marker="o", markersize=1, label="OGS6", ) # plt.plot(scipy.dot(dist_array_new,1.0),scipy.dot(temperature_array_ana_new,1.0), color = 'g',label= 'ana1' + months[m]) plt.plot( scipy.dot(dist_array_new, 1.0), scipy.dot(temperature_array_ana_new, 1.0), "b", label="Analytical", ) plt.xlim([0, 100]) plt.ylim([-10, 20]) plt.ylabel("Temperature [$^\circ$C]") plt.xlabel("x [m]") plt.legend(loc="best", fontsize=8) plt.title(month[m], fontsize=12) # plt.show() plt.savefig("pngfile{}.png".format(m), dpi=300, transparent=False) else: # 解析解数据项,实际是温度场斜三角矩阵相加 T = np.zeros([12]) with open(txtpath, "r") as f_in_txt: for line in f_in_txt: # split line data_line = line.split(" ") # maxsplit # time_double = 0.0 dist_double = float(data_line[0]) cordinate = math.sqrt(dist_double ** 2 / 2) i1 = m + 1 for m1 in range(1, m + 1): i1 = i1 - 1 # 时间变量,timestep温度随时间叠加矩阵每行重新设为0 time = time_trans * i1 + 10e-6 if m1 == 2 or m1 == 5 or m1 == 8 or m1 == 11: q = q2 elif m1 == 1 or m1 == 4 or m1 == 7 or m1 == 10: q = q1 elif m1 == 3 or m1 == 6 or m1 == 9: q = q3 for i in range(0, 5): for j in range(0, 5): po_dist_to_referencepo[i, j] = ( abs(po_x[i, j] - (cordinate + 1)) ** 2 + abs(po_y[i, j] - cordinate) ** 2 ) for i in range(0, 5): for j in range(0, 5): exp = po_dist_to_referencepo[i, j] / (4 * alpha_med * time) n1 = e1(exp) Temp_po_to_referencepo[i, j] = ( q / (4 * math.pi * lamda_med) * n1 ) T[m1] = np.sum(Temp_po_to_referencepo) T_sum = np.sum(T) + T0 createVar["temperature_array_ana" + str(m)] = np.vstack( (createVar["temperature_array_ana" + str(m)], T_sum) ) f_in_txt.close() # ogs5项: with open(txtpath, "r") as f_in_txt: for line in f_in_txt: # split line data_line = line.split(" ") # maxsplit # time_double = 0.0 dist_double = float(data_line[0]) cordinate = math.sqrt(dist_double ** 2 / 2) temperature = float(data_line[1]) # put into the list createVar["dist_array" + str(m)] = np.vstack( (createVar["dist_array" + str(m)], cordinate) ) createVar["temperature_array_ogs5" + str(m)] = np.vstack( (createVar["temperature_array_ogs5" + str(m)], temperature) ) f_in_txt.close() # 去除21和22行的0.0值,因为此值被带入了dist_array的list第一行,可查看variable
118800), (255, 90, 3, 1, 55440), (256, 91, 3, 1, 332640), (257, 42, 4, 13, 6652800), (258, 43, 4, 67, 5702400), (259, 44, 4, 163, 6652800), (260, 45, 4, 37, 1774080), (261, 46, 4, 19, 2851200), (262, 47, 4, 1, 1900800), (263, 48, 4, 1, 2217600), (264, 49, 4, 7, 237600), (265, 50, 4, 47, 443520), (266, 51, 4, 5, 44352), (267, 52, 4, 277, 6652800), (268, 53, 4, 1, 118800), (269, 54, 4, 43, 665280), (270, 55, 4, 31, 443520), (271, 56, 4, -43, 2217600), (272, 57, 4, 1, 73920), (273, 58, 4, 13, 443520), (274, 59, 4, 29, 2661120), (275, 60, 4, -61, 13305600), (276, 61, 4, 1, 147840), (277, 62, 4, -59, 1330560), (278, 42, 5, 89, 19958400), (279, 43, 5, 41, 1900800), (280, 44, 5, 61, 2217600), (281, 45, 5, -23, 3193344), (282, 46, 5, -67, 2217600), (283, 47, 5, -31, 1900800), (284, 48, 5, -19, 8553600), (285, 49, 5, 67, 950400), (286, 50, 5, 59, 295680), (287, 51, 5, 157, 1330560), (288, 52, 5, -13, 739200), (289, 53, 5, -53, 6652800), (290, 54, 5, 17, 95040), (291, 55, 5, 1, 5280), (292, 56, 5, 23, 1108800), (293, 57, 5, 59, 887040), (294, 58, 5, 167, 1330560), (295, 59, 5, 811, 13305600), (296, 60, 5, 17, 739200), (297, 61, 5, 17, 221760), (298, 62, 5, -97, 1663200), (299, 63, 5, 19, 380160), (300, 64, 5, 1, 55440), (301, 65, 5, -403, 6652800), (302, 66, 5, -29, 2661120), (303, 67, 5, 17, 221760), (304, 68, 5, 1, 831600), (305, 24, 6, 7, 2851200), (306, 25, 6, 31, 2851200), (307, 26, 6, 59, 3991680), (308, 27, 6, 31, 3991680), (309, 28, 6, 97, 19958400), (310, 29, 6, 1, 316800), (311, 30, 6, 1, 57024), (312, 31, 6, 13, 498960), (313, 32, 6, -1, 95040), (314, 33, 6, -23, 2494800), (315, 34, 6, -1, 73920), (316, 35, 6, -17, 221760), (317, 36, 6, 1, 199584), (318, 37, 6, -1, 55440), (319, 38, 6, -23, 665280), (320, 39, 6, 31, 1995840), (321, 40, 6, -1, 88704), (322, 41, 6, 13, 6652800), (323, 24, 7, 53, 5702400), (324, 25, 7, 163, 4435200), (325, 26, 7, 107, 2661120), (326, 27, 7, 13, 1596672), (327, 28, 7, -1, 887040), (328, 29, 7, 7, 1900800), (329, 30, 7, 31, 380160), (330, 31, 7, 29, 190080), (331, 32, 7, 7, 126720), (332, 33, 7, 1, 49280), (333, 34, 7, 1, 29568), (334, 35, 7, -1, 12320), (335, 36, 7, 53, 1330560), (336, 37, 7, 1, 126720), (337, 38, 7, -163, 4435200), (338, 39, 7, 53, 665280), (339, 40, 7, 1, 24640), (340, 41, 7, 67, 1108800), (341, 24, 8, 7, 950400), (342, 25, 8, 107, 6652800), (343, 26, 8, -13, 798336), (344, 27, 8, -193, 3991680), (345, 28, 8, -1, 35200), (346, 29, 8, -29, 8553600), (347, 30, 8, 173, 2661120), (348, 31, 8, 1, 17820), (349, 32, 8, -53, 1330560), (350, 33, 8, -13, 1663200), (351, 34, 8, 67, 1330560), (352, 35, 8, -17, 3326400), (353, 36, 8, 53, 1330560), (354, 37, 8, 53, 1663200), (355, 38, 8, 1, 49280), (356, 39, 8, -23, 3991680), (357, 40, 8, -229, 2217600), (358, 41, 8, -19, 3326400), (359, 15, 9, 1, 887040), (360, 16, 9, 13, 15966720), (361, 17, 9, -1, 190080), (362, 18, 9, -17, 5322240), (363, 19, 9, 23, 7983360), (364, 20, 9, -1, 124740), (365, 21, 9, -13, 266112), (366, 22, 9, -13, 266112), (367, 23, 9, -47, 1330560), (368, 15, 10, 167, 19958400), (369, 16, 10, 7, 380160), (370, 17, 10, 13, 1995840), (371, 18, 10, 107, 7983360), (372, 19, 10, 13, 739200), (373, 20, 10, 13, 1995840), (374, 21, 10, -19, 266112), (375, 22, 10, -73, 1330560), (376, 23, 10, -37, 443520), (377, 15, 11, 89, 6652800), (378, 16, 11, 19, 887040), (379, 17, 11, -19, 1995840), (380, 18, 11, -1, 380160), (381, 19, 11, 31, 2217600), (382, 20, 11, 19, 443520), (383, 21, 11, -1, 83160), (384, 22, 11, 17, 1330560), (385, 23, 11, -1, 23100), (386, 15, 12, 7, 1900800), (387, 16, 12, -179, 15966720), (388, 17, 12, -23, 570240), (389, 18, 12, -29, 1064448), (390, 19, 12, -43, 23950080), (391, 20, 12, 37, 3991680), (392, 21, 12, -1, 33264), (393, 22, 12, -1, 887040), (394, 23, 12, 1, 133056), (395, 15, 13, 61, 3326400), (396, 16, 13, 167, 2661120), (397, 17, 13, 79, 1330560), (398, 18, 13, 59, 2661120), (399, 19, 13, 1, 110880), (400, 20, 13, 1, 14784), (401, 21, 13, 13, 443520), (402, 22, 13, -31, 443520), (403, 23, 13, -13, 147840), (404, 15, 14, 1, 23100), (405, 16, 14, 23, 177408), (406, 17, 14, 13, 142560), (407, 18, 14, 1, 332640), (408, 19, 14, -1, 554400), (409, 20, 14, 29, 133056), (410, 21, 14, 1, 4158), (411, 22, 14, 37, 1663200), (412, 23, 14, -13, 277200), (413, 227, 1, 0, 1), (414, 227, 2, 1, 95800320), (415, 228, 2, 1, 9580032), (416, 229, 2, 139, 319334400), (417, 230, 2, 13, 13305600), (418, 231, 2, 61, 47900160), (419, 232, 2, 13, 13305600), (420, 233, 2, 139, 319334400), (421, 234, 2, 1, 9580032), (422, 235, 2, 1, 95800320), (423, 236, 2, 0, 1), (424, 128, 3, 0, 1), (425, 129, 3, 1, 2128896), (426, 130, 3, 139, 39916800), (427, 131, 3, 13, 1267200), (428, 132, 3, 61, 3991680), (429, 133, 3, 13, 1064448), (430, 134, 3, 139, 26611200), (431, 135, 3, 1, 912384), (432, 136, 3, 1, 11975040), (433, 137, 3, 0, 1), (434, 138, 3, 1, 178200), (435, 139, 3, 53, 1900800), (436, 140, 3, 23, 456192), (437, 141, 3, 1, 24640), (438, 142, 3, 127, 8870400), (439, 143, 3, 5, 3193344), (440, 144, 3, 0, 1), (441, 145, 3, 7, 380160), (442, 146, 3, 13, 266112), (443, 147, 3, 1, 27720), (444, 148, 3, 67, 13305600), (445, 149, 3, 0, 1), (446, 150, 3, 1, 110880), (447, 151, 3, 1, 665280), (448, 72, 4, 0, 1), (449, 73, 4, 13, 13305600), (450, 74, 4, 67, 11404800), (451, 75, 4, 359, 26611200), (452, 76, 4, 17, 1140480), (453, 77, 4, 331, 39916800), (454, 78, 4, 113, 53222400), (455, 79, 4, 1, 6386688), (456, 80, 4, 0, 1), (457, 81, 4, 7, 475200), (458, 82, 4, 47, 887040), (459, 83, 4, 247, 3991680), (460, 84, 4, 83, 3326400), (461, 85, 4, 1, 13305600), (462, 86, 4, 0, 1), (463, 87, 4, 43, 1330560), (464, 88, 4, 31, 887040), (465, 89, 4, -23, 1663200), (466, 90, 4, 0, 1), (467, 91, 4, -1, 110880), (468, 92, 4, 0, 1), (469, 93, 4, 1, 147840), (470, 94, 4, 13, 887040), (471, 95, 4, 29, 5322240), (472, 96, 4, -29, 6652800), (473, 97, 4, 0, 1), (474, 98, 4, 1, 295680), (475, 99, 4, -59, 2661120), (476, 100, 4, -1, 295680), (477, 72, 5, 1, 2128896), (478, 73, 5, 19, 3326400), (479, 74, 5, 131, 5702400), (480, 75, 5, 677, 15966720), (481, 76, 5, 19, 483840), (482, 77, 5, 211, 11404800), (483, 78, 5, 23, 5702400), (484, 79, 5, 1, 3548160), (485, 80, 5, 1, 89100), (486, 81, 5, 173, 1900800), (487, 82, 5, 79, 354816), (488, 83, 5, 97, 443520), (489, 84, 5, 211, 2419200), (490, 85, 5, 7, 760320), (491, 86, 5, 7, 126720), (492, 87, 5, 157, 665280), (493, 88, 5, 101, 443520), (494, 89, 5, 197, 6652800), (495, 90, 5, 1, 27720), (496, 91, 5, 1, 221760), (497, 92, 5, 7, 475200), (498, 93, 5, 17, 197120), (499, 94, 5, 361, 2661120), (500, 95, 5, 5, 76032), (501, 96, 5, -1, 483840), (502, 97, 5, 43, 665280), (503, 98, 5, 1, 9240), (504, 99, 5, -61, 831600), (505, 100, 5, -17, 443520), (506, 101, 5, 67, 1900800), (507, 102, 5, 1, 6336), (508, 103, 5, 283, 1330560), (509, 104, 5, 1, 9856), (510, 105, 5, 19,
# -*- coding: utf-8 -*- """ Created on Mon Feb 24 16:42:34 2020 @author: <NAME> Additional credit to <NAME> for help with delay & midi, and <NAME> for wavetable positions! """ # MySQL connection from sql_kit import SQL_Kit import mysql.connector # import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import signal from datetime import datetime from scipy.signal import butter, lfilter, freqz from sklearn.preprocessing import MinMaxScaler import soundfile as sf import IPython.display as ipd import os import sys import warnings from pathlib import Path import getpass # default style plt.style.use('seaborn-dark-palette') class MusicCode: def __init__(self,bpm): """ User Settings """ # set file path to your music-code program files location self.program_files_location = 'C:/Users/wesle/Desktop/Code Portfolio/music-code-master_v16/program files/' # Connect and update MySQL database self.database_connect=False self.userID = None self.password=<PASSWORD> # sound settings self.Fs = 44100 self.bpm = bpm self.time_mode = 'relative' """ Music-Code Setup """ # import clean chords dataset chords_blueprint_path = Path(self.program_files_location+'datasets/chords_blueprint.csv') chords_blueprint = pd.read_csv(chords_blueprint_path, encoding='latin1') #chords_blueprint = pd.read_excel(self.home_directory+"Program Files\\datasets"+'\\'+'chords_blueprint_v3.xlsx') self.chords_blueprint = chords_blueprint self.all_chords = list(chords_blueprint['chord']) # Music Note --> Frequency # create dictionary to convert between musical notes and frequencies notes_freqs_path = Path(self.program_files_location+'datasets/frequency_musical notes.csv') notes_freqs = pd.read_csv(notes_freqs_path, encoding='latin1') # Sharps self.note_freq_table_sharp = dict(zip(list(notes_freqs['sharps']), list(notes_freqs['frequency']))) self.freq_note_table_sharp = dict(zip(list(notes_freqs['frequency']), list(notes_freqs['sharps']))) # Flats self.note_freq_table_flat = dict(zip(list(notes_freqs['flats']), list(notes_freqs['frequency']))) self.freq_note_table_flat = dict(zip(list(notes_freqs['frequency']), list(notes_freqs['flats']))) # SET UP SAMPLE LIBRARY self.kick = os.listdir(Path(self.program_files_location+'samples/kick')) self.kick.sort() self.snare = os.listdir(Path(self.program_files_location+'samples/snare')) self.snare.sort() self.clap = os.listdir(Path(self.program_files_location+'samples/clap')) self.clap.sort() self.hihat = os.listdir(Path(self.program_files_location+'samples/hihat')) self.hihat.sort() self.perc = os.listdir(Path(self.program_files_location+'samples/perc')) self.perc.sort() self.cymbal = os.listdir(Path(self.program_files_location+'samples/cymbal')) self.cymbal.sort() self.bass = os.listdir(Path(self.program_files_location+'samples/bass')) self.bass.sort() self.fx = os.listdir(Path(self.program_files_location+'samples/fx')) self.fx.sort() self.user = os.listdir(Path(self.program_files_location+'samples/user')) self.user.sort() # set up archive library self.archive = os.listdir(Path(self.program_files_location+'archive')) # GETTERS def get_bpm(self): return self.bpm def get_time_mode(self): return self.time_mode def get_database_connect(self): return self.database_connect # SETTERS def set_bpm(self, new_bpm): self.bpm = new_bpm def set_time_mode(self, time_mode): self.time_mode = time_mode def connect(self): self.database_connect = True self.userID = input('User ID: ') self.password = <PASSWORD>('Password: ') # Sound Wave Generator def create_wave(self, note_labels, wave_type, duration, wt_pos=1, wave_context="create_wave"): """ create_wave Required Parameters note_labels: list of strings and/or integers. Strings are musical note labels i.e. ['C2','Ab4','G#2'] and integer values are frequencies measured in Hertz (Hz) i.e. [440, 220, 110] wave_type: string value representing the waveform shape in abbreviated form. Here are all the avaiable waveform shapes: 'sine', 'tri', 'saw1', 'saw2', 'square'. You can blend shapes like 'saw-tri'. duration: float or integer value representing the waveform duration in measures. For example 1/8 is an eighth note, based on the set BPM. 1 is a full measure/bar. 4 is 4 measures and so on Optional Parameters wt_pos: integer value defining the wavetable position. This parameter adjusts the tone & timbre of the sound """ if self.time_mode == 'relative': rhythm_duration = (60/self.bpm)*4*(duration) else: rhythm_duration = duration final_waveform=np.array([0]) # for each note in note_label for note_label in note_labels: if isinstance(note_label, int) or isinstance(note_label, float): freq = note_label else: try: freq = self.note_freq_table_sharp[note_label] # frequency except: freq = self.note_freq_table_flat[note_label] # frequency # number of samples in total file sample = self.Fs*rhythm_duration # create wave x = np.arange(sample) # waveform types if wave_type == 'sine': waveform = (np.sin(2 * np.pi * freq * x / self.Fs)**wt_pos)*0.5 elif wave_type == 'tri': waveform = (signal.sawtooth(t=2 * np.pi * freq * x / self.Fs,width=.5)**wt_pos)*0.5 elif wave_type == 'saw1': waveform = (signal.sawtooth(t=2 * np.pi * freq * x / self.Fs,width=1)**wt_pos)*.2 elif wave_type == 'saw2': waveform = (signal.sawtooth(t=2 * np.pi * freq * x / self.Fs,width=0)**wt_pos)*.2 elif wave_type == 'square': waveform = (signal.square(t=2 * np.pi * freq * x / self.Fs)**wt_pos)*.2 elif wave_type == 'sine-tri' or wave_type == 'tri-sine': waveform = (np.sin(2 * np.pi * freq * x / self.Fs)**wt_pos)*0.21 + (signal.sawtooth(t=2 * np.pi * freq * x / self.Fs,width=.5)**wt_pos)*0.21 elif wave_type == 'sine-saw'or wave_type == 'saw-sine': waveform = (np.sin(2 * np.pi * freq * x / self.Fs)**wt_pos)*0.21 + (signal.sawtooth(t=2 * np.pi * freq * x / self.Fs,width=1)**wt_pos)*.1 elif wave_type == 'sine-square'or wave_type == 'square-sine': waveform = (np.sin(2 * np.pi * freq * x / self.Fs)**wt_pos)*0.21 + (signal.square(t=2 * np.pi * freq * x / self.Fs)**wt_pos)*.1 elif wave_type == 'saw-square'or wave_type == 'square-saw': waveform = (signal.sawtooth(t=2 * np.pi * freq * x / self.Fs,width=1)**wt_pos)*.1 + (signal.square(t=2 * np.pi * freq * x / self.Fs)**wt_pos)*.1 elif wave_type == 'tri-saw'or wave_type == 'saw-tri': waveform = (signal.sawtooth(t=2 * np.pi * freq * x / self.Fs,width=.5)**wt_pos)*0.21 + (signal.sawtooth(t=2 * np.pi * freq * x / self.Fs,width=1)**wt_pos)*.1 elif wave_type == 'tri-square'or wave_type == 'square-tri': waveform = (signal.sawtooth(t=2 * np.pi * freq * x / self.Fs,width=.5)**wt_pos)*0.21 + (signal.square(t=2 * np.pi * freq * x / self.Fs)**wt_pos)*.1 # sum current waveform and new waveform, then move to next note in note_labels list final_waveform=final_waveform+waveform # while volume is quiet, gradually make louser until threshold is reached while abs(final_waveform).max() < .5: final_waveform = final_waveform*1.25 # while volume is clipping, make quiter while abs(final_waveform).max() > 1: final_waveform = final_waveform*.75 # convert to wave object self.waveform = Wave(final_waveform, self.bpm, self.time_mode, self.program_files_location, self.database_connect, self.userID, self.password) # subtle fade in to avoid audible clicks and pops self.waveform = self.waveform.fade(fade_in=1/128,fade_out=1/128) # update MySQL database if self.database_connect == True and wave_context=='create_wave': db = SQL_Kit(userID=self.userID, password=<PASSWORD>, database='musiccode') db.createwave_table(note_labels, wave_type, wt_pos, duration, self.get_bpm(), self.get_time_mode()) # if no database connection, pass else: pass return self.waveform # Wave Sequencer def sequence(self, note_labels, wave_type, rhythm, duration, wt_pos=1, arp_type = 'up', fade_in=1/128, fade_out = 1/128, in_curve = False, out_curve=False, wave_context='sequence'): """ sequence Required Parameters note_labels: list of strings and/or integers. Strings are musical note labels i.e. ['C2','Ab4','G#2'] and integer values are frequencies measured in Hertz (Hz) i.e. [440, 220, 110] wave_type: string value representing the waveform shape in abbreviated form. Here are all the avaiable waveform shapes: 'sine', 'tri', 'saw1', 'saw2', 'square'. You can blend shapes like 'saw-tri'. duration: float or integer value representing the waveform duration in measures. For example 1/8 is an eighth note, based on the set BPM. 1 is a full measure/bar. 4 is 4 measures and so on Optional Parameters wt_pos: integer value defining the wavetable position. This parameter adjusts the tone & timbre of the sound """ # rhythm & duration rhythm_duration = ((60/self.bpm)*4)*(rhythm) total_duration = ((60/self.bpm)*4)*(duration) total_samples = int(round(total_duration*44100)) # sample rate for WAV audio sample_rate=self.Fs # container for master waveform master_wave = np.zeros(1) # iterate through all items in note_labels for note in note_labels: # if note is wave type if type(note).__name__ == 'Wave': waveform = note # if note is float type elif isinstance(note, float) or isinstance(note, int): waveform = self.create_wave([note], wave_type, rhythm, wt_pos, wave_context).fade(fade_in,in_curve,fade_out,out_curve) # if note is string type elif isinstance(note, str): if note== 'rest': waveform = self.rest(rhythm) else: # generate waveform for note in note list waveform = self.create_wave([note], wave_type, rhythm, wt_pos, wave_context).fade(fade_in,in_curve,fade_out,out_curve) # concatenate new waveform to master_waveform master_wave=self.join_waves((master_wave,waveform),wave_context) if arp_type == 'up': # single loop through each note in note_labels one_loop = master_wave # concatenate master_wave until it reaches full duration while master_wave.shape[0] < total_samples: master_wave = self.join_waves((master_wave,one_loop),wave_context) elif arp_type == 'down': # flip waveform to get descending order master_wave = np.flip(master_wave) one_loop = master_wave # concatenate master_wave until it reaches full duration while master_wave.shape[0] < total_samples: master_wave = self.join_waves((master_wave,one_loop),wave_context) elif arp_type == 'up-down': # flip waveform to get descending order master_wave = self.join_waves((master_wave,np.flip(master_wave)),wave_context) one_loop = master_wave # concatenate master_wave until it reaches full duration while master_wave.shape[0] < total_samples: master_wave = self.join_waves((master_wave,one_loop),wave_context) elif arp_type == 'down-up': # flip waveform to get descending order master_wave = self.join_waves((np.flip(master_wave),master_wave),wave_context) one_loop = master_wave # concatenate master_wave until it reaches full duration while master_wave.shape[0] < total_samples: master_wave = self.join_waves((master_wave,one_loop),wave_context) master_wave = master_wave[:total_samples] self.waveform = Wave(master_wave, self.bpm, self.time_mode, self.program_files_location, self.database_connect, self.userID, self.password) # update MySQL database if self.database_connect == True and wave_context=='sequence': db
np.array([-1]) else: return np.ones(shape=(n_clusters, 1)) * -1, np.ones(shape=(n_clusters, 1)) * -1 def random_sample_pixels(image, sample_ratio=0, mode="row-col"): """ Randomly sample an amount of pixels from an image based on the given sampled ratio. Two sampling mode are available. row-col: sampling first across the row and then across the column on each sampled row The output sampled image is still 2D and keep same aspect ratio as the input image, which can be used to visualize the sampling effect on the image. flat: sampling across the flat input image. The shape and aspect ratio of the input image are not preserved due to the flatten process, but it sample the pixels much faster than 'row-col' mode. The distribution of the sampling result is similar to that from the 'row-col' :param image: Input 2D image. Either a multi-channel color image or a single channel greyscale image \ Expected shape==height x width x (channels) :type image: numpy.ndarray :param sample_ratio: The amount of pixels sampled from the image. in range [0, 1] :type sample_ratio: float :param mode: two sampling mode are available. \ 1) 'row-col' sampling mode \ 2) 'flat' sampling mode :type mode: str :return: If mode="flat", return the resampled array of pixels (1-d flat array of data points) \ If mode="row-col", return the resampled image :rtype: numpy.ndarray """ assert 0 <= sample_ratio <= 1, "The sample ratio is in the range of [0, 1]" if sample_ratio == 1: return image elif sample_ratio == 0: return np.array([]).astype(image.dtype) if mode == "row-col": # To keep the aspect ratio of the input image, sample equal ratio on the columns and rows ratio = (sample_ratio) ** (1 / 2) # Number of row to sample row_size = int(image.shape[0] * ratio) # Number of column to sample col_size = int(image.shape[1] * ratio) # Sample the row first random_row_indices = np.sort(np.random.choice(np.arange(image.shape[0]), row_size, replace=False)) random_row = image[random_row_indices] random_pixels = [] # Then, in each row, sampled a number of pixels/columns for row in random_row: random_col_indices = np.sort(np.random.choice(np.arange(image.shape[1]), col_size, replace=False)) random_pixels.append(row[random_col_indices]) random_pixels = np.array(random_pixels) elif mode == "flat": # Flatten the image flat_img = flatten_image(image) # Generate the possible indices indices = np.arange(flat_img.shape[0]) # Generate the sampled indices sampled_indices = np.random.choice(indices, int(sample_ratio * flat_img.shape[0]), replace=False) # Sampled the flat image using the sampled indices random_pixels = flat_img[sampled_indices] else: # If none of two modes is specified print("Invalid sampling mode. Two sampling options are 'row-col' and 'flat'") return return np.array(random_pixels) def watershed_segmentation(image, minimum_segment_size=0.0004, base_ratio=0.5, denoise_disk_size=5, gradiant_disk_size=5, marker_disk_size=15): """ Label the connected regions in an image. Use edge detection approach with watershed algorithm. adjust the critical gradient (edge gradient) with the distribution of the input image's intensity gradient . :param image: The input color image for region segmentation using gradient-based watershed :type image: numpy.ndarray :param minimum_segment_size: The minimum size of the segments in the segmented image in percentage \ (size is the relative ratio of the image) The segmented regions smaller than the minimum size will be merged \ to its neighboring larger segmented components :type minimum_segment_size: float :param base_ratio: Amount of regions at least in the image. The image in watershed transformation is \ differentiated into two parts regions + boundaries. The base ratio is the ratio between the least amount of \ pixels that are regions and the total amount of pixels in the image. :type base_ratio: float :param denoise_disk_size: the kernel size of the denoise median filter :type denoise_disk_size: int :param gradiant_disk_size: the kernel size of the gradient filter that is used for determining the amount of \ boundaries :type gradiant_disk_size: int :param marker_disk_size: the kernel size of the gradient filter that is used for generating transformation \ marker :type marker_disk_size: int :return: the segmented image, where shape==input_image.shape. and regions are labeled from 0 to n-1, where \ n is the number of regions in the labeled image. Functions also return the greyscale image corresponding to \ the original image :rtype: (numpy.ndarray, numpy.ndarray) """ assert 0 <= minimum_segment_size < 1, "The minimum size of the segments (in percentage ratio) is in range [0, 1)" # Gray Scale image grey_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # denoise image denoised = rank.median(grey_image, disk(denoise_disk_size)) num_of_pixels = image.shape[0] * image.shape[1] # local gradient gradient = rank.gradient(denoised, disk(gradiant_disk_size)) critical = np.sort(gradient, axis=None) # Use std to adjust the ratio of the regions in the image criteria = np.std(gradient) # A high std of the image's intensity gradient means the intensities of image are changed more rapidly # and frequently, so there are more boundaries but less regions. A low std of the image's intensity # gradients means the changes across the image are more smooth. Such coherence indicate a larger ratio # of regions in the image # Divide adjust ratio by the std of the gradient distribution adjust_ratio = 0.25 * 25 / (criteria + 1e6) if (adjust_ratio > 0.45): adjust_ratio = 0.45 # Assume at least 50% of an image is the content (at most 50% of an image # is edge), and at most 95% of an image is the content (at least 5% of an # image is edge) # Critical is the critical threshold of intensity gradient that separate the regions and boundaries # Pixels with gradients larger than critical are considered as boundaries # Pixels with gradients smaller than critical are considered as regions critical = critical[int(num_of_pixels * (base_ratio + adjust_ratio))] # Minimum size of a segment # Segments under the minimum size will be joined into larger segments segment_min_size = int(num_of_pixels * minimum_segment_size) # find continuous region which marked by gradient lower than critical gradient markers = rank.gradient(denoised, disk(marker_disk_size)) < critical markers = ndimage.label(remove_small_objects(markers, segment_min_size))[0] # process the watershed transformation regions = watershed(gradient, markers) # Return the labeled image and the corresponding greyscale image return regions, grey_image def get_rag(gray_image, labels): """ Get the region adjacency graph using the labeled image and corresponding the edge map generated by greyscale image with sobel filter :param gray_image: The greyscale image corresponding to the labeled image :type gray_image: numpy.ndarray :param labels: a labeled segmented image, where the pixels in the image are labeled with index of the \ segmented regions. :type labels: numpy.ndarray :return: The region adjacency graph in dictionary \ see https://scikit-image.org/docs/stable/auto_examples/segmentation/plot_rag_boundary.html for more \ references :rtype: skimage.future.graph.RAG """ # Get rag of the labeled image edge_map = sobel(gray_image) rag = graph.rag_boundary(labels, edge_map) return rag def rag_to_matrix(rag, num_regions): """ Transfer the region adjacency dictionary to a more accessible region adjacency matrix where in the matrix, 1 means the region of corresponding column index is adjacent to the region of corresponding row index/ e.g. 0,1 1,0 means region 0 and region 1 are adjacent :param rag: region adjacency dictionary :type rag: skimage.future.graph.RAG :param num_regions: number of regions in the region adjacency graph :type num_regions: int :return: An binary adjacency matrix with shape==num_regions x num_regions :rtype: numpy.ndarray """ matrix = np.zeros((num_regions, num_regions), dtype=np.int8) for i in range(1, num_regions + 1): elements = rag[i] adict = dict(elements) adj_list = adict.keys() for keys in adj_list: matrix[i - 1][keys - 1] = 1 return matrix def color_of_regions(labels, original_image): """ Compute average color and brightest color of the regions and record the relative size of the regions as a ratio with respect to the size of whole image. :param labels: The labeled image. Expected shape==height x width. Integer labels :type labels: numpy.ndarray :param original_image: The original color image corresponding to the label image :type original_image: numpy.ndarray :return: A list of average color of the regions, a list of brightest color of the regions, and \ a list of sizes of the regions. The order of the regions in list is the same as they are in \ labeled image :rtype: (list, list, list) """ # Average Color of the region avg_colors_list = [] # Brightest Color of the region brightest_colors_list = [] # Sizes of
{"store_history": True, "title": "Reconstructed Augmented iSEG After Normalization"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Augmented Input iSEG Image", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True, "title": "Reconstructed Augmented Input iSEG Image"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Input MRBrainS Image", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True, "title": "Reconstructed Input MRBrainS Image"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Normalized MRBrainS Image", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True, "title": "Reconstructed Normalized MRBrainS Image"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Segmented MRBrainS Image", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True, "title": "Reconstructed Segmented MRBrainS Image"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Ground Truth MRBrainS Image", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True, "title": "Reconstructed Ground Truth MRBrainS Image"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Initial Noise MRBrainS Image", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True, "title": "Reconstructed Initial Noise MRBrainS Image"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Augmented MRBrainS After Normalization", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True, "title": "Reconstructed Augmented MRBrainS After Normalization"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Augmented Input MRBrainS Image", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True, "title": "Reconstructed Augmented Input MRBrainS Image"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Input ABIDE Image", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True, "title": "Reconstructed Input ABIDE Image"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Normalized ABIDE Image", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True, "title": "Reconstructed Normalized ABIDE Image"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Ground Truth ABIDE Image", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True, "title": "Reconstructed Ground Truth ABIDE Image"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Segmented ABIDE Image", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True, "title": "Reconstructed Segmented ABIDE Image"}}, every=10), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Conv1 FM", PlotType.IMAGES_PLOT, params={"nrow": 8, "opts": {"store_history": True, "title": "Conv1 FM"}}, every=500), Event.ON_TRAIN_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Layer1 FM", PlotType.IMAGES_PLOT, params={"nrow": 8, "opts": {"store_history": True, "title": "Layer1 FM"}}, every=500), Event.ON_TRAIN_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Layer2 FM", PlotType.IMAGES_PLOT, params={"nrow": 12, "opts": {"store_history": True, "title": "Layer2 FM"}}, every=500), Event.ON_TRAIN_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Layer3 FM", PlotType.IMAGES_PLOT, params={"nrow": 16, "opts": {"store_history": True, "title": "Layer3 FM"}}, every=500), Event.ON_TRAIN_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Per-Dataset Histograms", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Reconstructed Images Histograms", PlotType.IMAGE_PLOT, params={"opts": {"store_history": True}}, every=5), Event.ON_TEST_EPOCH_END) \ .with_event_handler(PlotAvgGradientPerLayer(visdom_logger, every=25), Event.ON_TRAIN_BATCH_END) return trainer elif self._trainer == TrainerType.LSGAN: trainer = LSGANTrainer(training_config, model_trainers, dataloaders[0], dataloaders[1], dataloaders[2], reconstruction_datasets, normalized_reconstructor, input_reconstructor, segmentation_reconstructor, augmented_input_reconstructor, gt_reconstructor, run_config, dataset_configs, save_folder) \ .with_event_handler(PrintTrainingStatus(every=25), Event.ON_BATCH_END) \ .with_event_handler(PrintMonitors(every=25), Event.ON_BATCH_END) \ .with_event_handler(PlotMonitors(visdom_logger), Event.ON_EPOCH_END) \ .with_event_handler(PlotLR(visdom_logger), Event.ON_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Training Generated Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Training Generated Patches Process {}".format( run_config.local_rank)}}, every=500), Event.ON_TRAIN_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Validation Generated Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Validation Generated Patches Process {}".format( run_config.local_rank)}}, every=100), Event.ON_VALID_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Test Generated Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Test Generated Patches Process {}".format( run_config.local_rank)}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Training Input Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Training Input Patches Process {}".format( run_config.local_rank)}}, every=500), Event.ON_TRAIN_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Validation Input Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Validation Input Patches Process {}".format( run_config.local_rank)}}, every=100), Event.ON_VALID_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Test Input Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Test Input Patches Process {}".format( run_config.local_rank)}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Training Segmented Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Segmented Patches Process {}".format( run_config.local_rank)}}, every=500), Event.ON_TRAIN_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Validation Segmented Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Validation Segmented Patches Process {}".format( run_config.local_rank)}}, every=100), Event.ON_VALID_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Test Segmented Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Test Segmented Patches Process {}".format( run_config.local_rank)}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Training Segmentation Ground Truth Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Training Ground Truth Patches Process {}".format( run_config.local_rank)}}, every=500), Event.ON_TRAIN_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Validation Segmentation Ground Truth Batch Process {}".format( run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Validation Ground Truth Patches Process {}".format( run_config.local_rank)}}, every=100), Event.ON_VALID_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Test Segmentation Ground Truth Batch Process {}".format( run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Test Ground Truth Patches Process {}".format( run_config.local_rank)}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Training Label Map Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Training Label Map Patches Process {}".format( run_config.local_rank)}}, every=500), Event.ON_TRAIN_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Validation Label Map Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Validation Label Map Patches Process {}".format( run_config.local_rank)}}, every=100), Event.ON_VALID_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Test Label Map Batch Process {}".format(run_config.local_rank), PlotType.IMAGES_PLOT, params={"nrow": 4, "opts": {"store_history": True, "title": "Test Label Map Patches Process {}".format( run_config.local_rank)}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Generated Intensity Histogram", PlotType.HISTOGRAM_PLOT, params={"opts": {"title": "Generated Intensity Histogram", "store_history": True, "numbins": 128}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Background Generated Intensity Histogram", PlotType.HISTOGRAM_PLOT, params={"opts": {"title": "Background Generated Intensity Histogram", "store_history": True, "numbins": 128}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "CSF Generated Intensity Histogram", PlotType.HISTOGRAM_PLOT, params={"opts": {"title": "CSF Generated Intensity Histogram", "store_history": True, "numbins": 128}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "GM Generated Intensity Histogram", PlotType.HISTOGRAM_PLOT, params={"opts": {"title": "GM Generated Intensity Histogram", "store_history": True, "numbins": 128}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "WM Generated Intensity Histogram", PlotType.HISTOGRAM_PLOT, params={"opts": {"title": "WM Generated Intensity Histogram", "store_history": True, "numbins": 128}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Input Intensity Histogram", PlotType.HISTOGRAM_PLOT, params={"opts": {"title": "Inputs Intensity Histogram", "store_history": True, "numbins": 128}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Background Input Intensity Histogram", PlotType.HISTOGRAM_PLOT, params={"opts": {"title": "Background Input Intensity Histogram", "store_history": True, "numbins": 128}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "CSF Input Intensity Histogram", PlotType.HISTOGRAM_PLOT, params={"opts": {"title": "CSF Input Intensity Histogram", "store_history": True, "numbins": 128}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "GM Input Intensity Histogram", PlotType.HISTOGRAM_PLOT, params={"opts": {"title": "GM Input Intensity Histogram", "store_history": True, "numbins": 128}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "WM Input Intensity Histogram", PlotType.HISTOGRAM_PLOT, params={"opts": {"title": "WM Input Intensity Histogram", "store_history": True, "numbins": 128}}, every=100), Event.ON_TEST_BATCH_END) \ .with_event_handler(PlotCustomVariables(visdom_logger, "Pie Plot", PlotType.PIE_PLOT, params={"opts": {"title": "Classification hit per classes", "legend": list(map(lambda key: key, dataset_configs.keys())) + [ "Fake Class"]}}, every=25), Event.ON_TRAIN_BATCH_END) \ .with_event_handler(PlotCustomVariables(visdom_logger, "Pie Plot True", PlotType.PIE_PLOT, params={"opts": {"title": "Batch data distribution", "legend": list(map(lambda key: key, dataset_configs.keys())) + [ "Fake Class"]}}, every=25), Event.ON_TRAIN_BATCH_END) \ .with_event_handler(PlotCustomVariables(visdom_logger, "Mean Hausdorff Distance", PlotType.LINE_PLOT, params={"opts": {"title": "Mean Hausdorff Distance", "legend": ["Test"]}}, every=1), Event.ON_TEST_EPOCH_END) \ .with_event_handler(PlotCustomVariables(visdom_logger, "Metric Table", PlotType.TEXT_PLOT, params={"opts": {"title": "Metric Table"}}, every=1), Event.ON_TEST_EPOCH_END) \ .with_event_handler(PlotCustomVariables(visdom_logger, "Per-Dataset Metric Table", PlotType.TEXT_PLOT, params={"opts": {"title": "Per-Dataset Metric Table"}}, every=1), Event.ON_TEST_EPOCH_END) \ .with_event_handler(PlotCustomVariables(visdom_logger, "Jensen-Shannon Table", PlotType.TEXT_PLOT, params={"opts": {"title": "Jensen-Shannon Divergence"}}, every=1), Event.ON_TEST_EPOCH_END) \ .with_event_handler(PlotCustomVariables(visdom_logger, "Confusion Matrix", PlotType.HEATMAP_PLOT, params={ "opts": {"columnnames": ["VM", "GM", "CSF", "Background"], "rownames": ["Background", "CSF", "GM", "WM"], "title": "Confusion Matrix"}}, every=1), Event.ON_TEST_EPOCH_END) \ .with_event_handler(PlotCustomVariables(visdom_logger, "iSEG Confusion Matrix", PlotType.HEATMAP_PLOT, params={ "opts": {"columnnames": ["VM", "GM", "CSF", "Background"], "rownames": ["Background", "CSF", "GM", "WM"], "title": "iSEG Confusion Matrix"}}, every=1), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "MRBrainS Confusion Matrix", PlotType.HEATMAP_PLOT, params={"opts": {"columnnames": ["VM", "GM", "CSF", "Background"], "rownames": ["Background", "CSF", "GM", "WM"], "title": "MRBrainS Confusion Matrix"}}, every=1), Event.ON_TEST_EPOCH_END) \ .with_event_handler(PlotCustomVariables(visdom_logger, "ABIDE Confusion Matrix", PlotType.HEATMAP_PLOT, params={ "opts": {"columnnames": ["VM", "GM", "CSF", "Background"], "rownames": ["Background", "CSF", "GM", "WM"], "title": "ABIDE Confusion Matrix"}}, every=1), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Discriminator Confusion Matrix", PlotType.HEATMAP_PLOT, params={"opts": { "columnnames": ["Generated"] + list(reversed(list(dataset_configs.keys()))), "rownames": list(dataset_configs.keys()) + ["Generated"], "title": "Discriminator Confusion Matrix"}}, every=1), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomVariables(visdom_logger, "Discriminator Confusion Matrix Training", PlotType.HEATMAP_PLOT, params={"opts": { "columnnames": ["Generated"] + list(reversed(list(dataset_configs.keys()))), "rownames": list(dataset_configs.keys()) + ["Generated"], "title": "Discriminator Confusion Matrix Training"}}, every=1), Event.ON_TRAIN_EPOCH_END) \ .with_event_handler(PlotCustomVariables(visdom_logger, "Runtime", PlotType.TEXT_PLOT, params={"opts": {"title": "Runtime"}}, every=1), Event.ON_TEST_EPOCH_END) \ .with_event_handler(PlotCustomLoss(visdom_logger, "Discriminator Loss", every=1), Event.ON_EPOCH_END) \ .with_event_handler(PlotCustomLoss(visdom_logger, "Total Loss", every=1), Event.ON_EPOCH_END) \ .with_event_handler( PlotCustomLinePlotWithLegend(visdom_logger, "Jensen-Shannon Divergence", every=1, params={"title": "Jensen-Shannon Divergence on test data per Epoch", "legend": ["Inputs", "Normalized"]}), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomLinePlotWithLegend(visdom_logger, "Dice score per class per epoch", every=1, params={"title": "Dice score on test patches per class per epoch", "legend": ["CSF", "GM", "WM"]}), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomLinePlotWithLegend(visdom_logger, "Per Dataset Mean Hausdorff Distance", every=1, params={"title": "Per Dataset Mean Hausdorff Distance", "legend": list(dataset_configs.keys())}), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomLinePlotWithLegend(visdom_logger, "Hausdorff Distance per class per epoch on reconstructed iSEG image", every=1, params={ "title": "Hausdorff Distance per class per epoch on reconstructed iSEG image", "legend": ["CSF", "GM", "WM"]}), Event.ON_TEST_EPOCH_END) \ .with_event_handler( PlotCustomLinePlotWithLegend(visdom_logger, "Hausdorff Distance per class per epoch on reconstructed
"dog"] res << a.delete_at(99) #=> nil return res """) assert self.unwrap(space, w_res) == ["cat", ["ant", "bat", "dog"], None] def test_first(self, space): assert space.int_w(space.execute("return [1, 2, 3].first")) == 1 assert space.execute("return [].first") == space.w_nil def test_last(self, space): assert space.int_w(space.execute("return [1, 2, 3].last")) == 3 assert space.execute("return [].last") == space.w_nil def test_shift(self, space): w_res = space.execute("return [].shift") assert w_res is space.w_nil w_res = space.execute(""" a = [1, 2] return [a.shift, a] """) assert self.unwrap(space, w_res) == [1, [2]] w_res = space.execute(""" a = [1, 2, 3, 4, 5] return [a.shift(2), a] """) assert self.unwrap(space, w_res) == [[1, 2], [3, 4, 5]] with self.raises(space, "ArgumentError"): space.execute("[].shift(-2)") def test_push(self, space): w_res = space.execute("return [].push(2, 3)") assert self.unwrap(space, w_res) == [2, 3] def test_insert(self, space): w_res = space.execute("return [1,2,3].insert(0, 4, 5)") assert self.unwrap(space, w_res) == [4, 5, 1, 2, 3] w_res = space.execute("return [1,2,3].insert(-1, 4, 5)") assert self.unwrap(space, w_res) == [1, 2, 3, 4, 5] w_res = space.execute("return [1,2,3].insert(-2, 4, 5)") assert self.unwrap(space, w_res) == [1, 2, 4, 5, 3] w_res = space.execute("return [1,2,3].insert(5, 4, 5)") assert self.unwrap(space, w_res) == [1, 2, 3, None, None, 4, 5] with self.raises(space, "IndexError", "index -6 too small for array; minimum: -3"): space.execute("return [1,2,3].insert(-7, 4, 5)") def test_eq(self, space): w_res = space.execute(""" x = [] return [ [] == :abc, [] == [], [:abc] == [:abc], x == (x << 2), [1, 2, 3] == [1, 2, 4], [1] == [1, 2], ] """) assert self.unwrap(space, w_res) == [False, True, True, True, False, False] def test_eqlp(self, space): w_res = space.execute("return [].eql? 2") assert w_res is space.w_false w_res = space.execute("return [0].eql? [0.0]") assert w_res is space.w_false w_res = space.execute("return [0].eql? [0]") assert w_res is space.w_true def test_clear(self, space): w_res = space.execute(""" a = [1, 2, 3] a.clear return a """) assert self.unwrap(space, w_res) == [] def test_hashability(self, space): w_res = space.execute("return {[] => 2}[[]]") assert space.int_w(w_res) == 2 w_res = space.execute("return {[1] => 5}[[1]]") assert space.int_w(w_res) == 5 w_res = space.execute("return {[1, 2, 3] => 5}[[1, 2]]") assert w_res is space.w_nil def test_sort(self, space): w_res = space.execute(""" a = [3, 2, 1] b = a.sort return a.object_id == b.object_id, a, b """) assert self.unwrap(space, w_res) == [False, [3, 2, 1], [1, 2, 3]] w_res = space.execute(""" a = [3, 2, 1] b = a.sort! return a.object_id == b.object_id, a, b """) assert self.unwrap(space, w_res) == [True, [1, 2, 3], [1, 2, 3]] w_res = space.execute(""" a = [1, 2, 3] b = a.sort { |a, b| -a <=> -b } return a.object_id == b.object_id, a, b """) assert self.unwrap(space, w_res) == [False, [1, 2, 3], [3, 2, 1]] w_res = space.execute(""" a = [1, 2, 3] b = a.sort! { |a, b| -a <=> -b } return a.object_id == b.object_id, a, b """) assert self.unwrap(space, w_res) == [True, [3, 2, 1], [3, 2, 1]] with self.raises(space, "NoMethodError"): space.execute("[0, 1].sort{ |n, m| BasicObject.new }") with self.raises(space, "ArgumentError", "comparison of Array with Object failed"): space.execute("[Object.new, []].sort") def test_multiply(self, space): w_res = space.execute("return [ 1, 2, 3 ] * 3") assert self.unwrap(space, w_res) == [1, 2, 3, 1, 2, 3, 1, 2, 3] w_res = space.execute("return [ 1, 2, 3 ] * ','") assert self.unwrap(space, w_res) == "1,2,3" def test_flatten(self, space): w_res = space.execute(""" s = [ 1, 2, 3 ] t = [ 4, 5, 6, [7, 8] ] a = [ s, t, 9, 10 ] return a.flatten """) assert self.unwrap(space, w_res) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] w_res = space.execute("return [ 1, 2, [3, [4, 5] ] ].flatten(1)") assert self.unwrap(space, w_res) == [1, 2, 3, [4, 5]] with self.raises(space, "ArgumentError", "tried to flatten recursive array"): space.execute(""" a = [0, 1, 2, 3] a[0] = a a.flatten """) class TestArrayPack(BaseTopazTest): def test_garbage_format(self, space): assert space.str_w(space.execute("return [].pack ''")) == "" assert space.str_w(space.execute("return [].pack 'yy'")) == "" assert space.str_w(space.execute("return [1, 2].pack 'y3'")) == "" def test_padding(self, space): assert space.str_w(space.execute("return [].pack 'xx'")) == "\0\0" assert space.str_w(space.execute("return [].pack 'x2'")) == "\0\0" def test_moving(self, space): assert space.str_w(space.execute("return [].pack '@2'")) == "\0\0" assert space.str_w(space.execute("return [].pack 'xx@2'")) == "\0\0" def test_backing_up(self, space): assert space.str_w(space.execute("return [].pack 'xxXX'")) == "" with self.raises(space, "ArgumentError", "X outside of string"): space.execute("[].pack 'X'") def test_char(self, space): assert space.str_w(space.execute("return [-10, 10].pack 'cc'")) == struct.pack("bb", -10, 10) assert space.str_w(space.execute("return [255].pack 'C'")) == struct.pack("B", 255) assert space.str_w(space.execute("return [256].pack 'C'")) == struct.pack("B", 256 % 256) assert space.str_w(space.execute("return [-255].pack 'C'")) == struct.pack("B", -255 % 256) with self.raises(space, "ArgumentError", "> allowed only after types SsIiLlQq"): space.execute("[-255].pack 'C>'") with self.raises(space, "ArgumentError", "! allowed only after types SsIiLl"): space.execute("[-255].pack 'C!'") with self.raises(space, "ArgumentError", "< allowed only after types SsIiLlQq"): space.execute("[-255].pack 'C<'") def test_short(self, space): assert space.str_w(space.execute("return [-255].pack 'S'")) == struct.pack("H", -255 % 2 ** 16) assert space.str_w(space.execute("return [12].pack 's'")) == struct.pack("h", 12) assert space.str_w(space.execute("return [12].pack 'S!'")) == struct.pack("@h", 12) assert space.str_w(space.execute("return [12].pack 'S_'")) == struct.pack("@h", 12) assert space.str_w(space.execute("return [12].pack 'S_!_'")) == struct.pack("@h", 12) with self.raises(space, "RangeError", "Can't use both '<' and '>'"): space.execute("[2].pack 'S><'") def test_long(self, space): assert space.str_w(space.execute("return [-255].pack 'I'")) == struct.pack("I", -255 % 2 ** 32) assert space.str_w(space.execute("return [12].pack 'i'")) == struct.pack("i", 12) assert space.str_w(space.execute("return [-255].pack 'L'")) == struct.pack("I", -255 % 2 ** 32) assert space.str_w(space.execute("return [12].pack 'l'")) == struct.pack("i", 12) def test_longlong(self, space): assert space.str_w(space.execute("return [-255].pack 'Q'")) == struct.pack("Q", -255 % 2 ** 64) assert space.str_w(space.execute("return [12].pack 'q'")) == struct.pack("q", 12) def test_float(self, space): assert space.str_w(space.execute("return [-255].pack 'f'")) == struct.pack("f", -255) assert space.str_w(space.execute("return [-255].pack 'F'")) == struct.pack("f", -255) assert space.str_w(space.execute("return [-255.42].pack 'F'")) == struct.pack("f", -255.42) def test_double(self, space): assert space.str_w(space.execute("return [-255].pack 'd'")) == struct.pack("d", -255) assert space.str_w(space.execute("return [-255].pack 'D'")) == struct.pack("d", -255) assert space.str_w(space.execute("return [-255.42].pack 'D'")) == struct.pack("d", -255.42) def test_strings(self, space): string = "abö" assert space.str_w(space.execute("return ['%s'].pack 'a'" % string)) == string[0] assert space.str_w(space.execute("return ['%s'].pack 'A6'" % string)) == string + " " assert space.str_w(space.execute("return ['abö'].pack 'a6'")) == string + "\0\0" assert space.str_w(space.execute("return ['abö'].pack 'Z6'")) == string + "\0\0" assert space.str_w(space.execute("return ['abö'].pack 'Z*'")) == string + "\0" def test_endianess(self, space): assert space.str_w(space.execute("return [42].pack 's<'")) == struct.pack("<h", 42) assert space.str_w(space.execute("return [42].pack 's>'")) == struct.pack(">h", 42) assert space.str_w(space.execute("return [42].pack 'S<'")) == struct.pack("<H", 42) assert space.str_w(space.execute("return [42].pack 'S>'")) == struct.pack(">H", 42) assert space.str_w(space.execute("return [42].pack 'i<'")) == struct.pack("<i", 42) assert space.str_w(space.execute("return [42].pack 'i>'")) == struct.pack(">i", 42) assert space.str_w(space.execute("return [42].pack 'I<'")) == struct.pack("<I", 42) assert space.str_w(space.execute("return [42].pack 'I>'")) == struct.pack(">I", 42) assert space.str_w(space.execute("return [42].pack 'q<'")) == struct.pack("<q", 42) assert space.str_w(space.execute("return [42].pack 'q>'")) == struct.pack(">q", 42) assert space.str_w(space.execute("return [42].pack 'Q<'")) == struct.pack("<Q", 42) assert space.str_w(space.execute("return [42].pack 'Q>'")) == struct.pack(">Q", 42) assert space.str_w(space.execute("return [42].pack 'v'")) == struct.pack("<H", 42) assert space.str_w(space.execute("return [42].pack 'V'")) == struct.pack("<I", 42) assert space.str_w(space.execute("return [42].pack 'n'")) == struct.pack(">H", 42) assert space.str_w(space.execute("return [42].pack 'N'")) == struct.pack(">I", 42) assert space.str_w(space.execute("return [4.2].pack 'e'")) == struct.pack("<f", 4.2) assert space.str_w(space.execute("return [4.2].pack 'g'")) == struct.pack(">f", 4.2) assert space.str_w(space.execute("return [4.2].pack 'E'")) == struct.pack("<d", 4.2) assert space.str_w(space.execute("return [4.2].pack 'G'")) == struct.pack(">d", 4.2) def test_complex(self, space): w_res = space.execute(""" return [65, 66, 5, 5, 4.2, 4.2, "hello"].pack 'c02s<s>egg0Z*' """) expected = (struct.pack("2b", 65, 66) + struct.pack("<h", 5) + struct.pack(">h", 5) + struct.pack("<f", 4.2) + struct.pack(">f", 4.2) + "hello\0") assert space.str_w(w_res) == expected def test_pointers(self, space): pointerlen = struct.calcsize("P") w_res = space.execute("return [''].pack 'P'") assert space.str_w(w_res) == "\0" * pointerlen w_res = space.execute("return [''].pack 'p'") assert space.str_w(w_res) == "\0" * pointerlen def test_errors(self, space): with self.raises(space, "ArgumentError", "too few arguments"): space.execute("[].pack 'P'") with self.raises(space, "ArgumentError", "too few arguments"): space.execute("[].pack 'a'") with self.raises(space, "ArgumentError", "too few arguments"): space.execute("[].pack 'c'") with self.raises(space, "ArgumentError", "too few arguments"): space.execute("[].pack 'f'") with self.raises(space, "RangeError", "pack length too big"): space.execute("[].pack 'a18446744073709551617'") def test_max(self, space): w_res = space.execute(""" a = %w(albatross dog horse) return a.max """) assert self.unwrap(space, w_res) == "horse" w_res = space.execute(""" a = %w(albatross dog horse) return a.max { |a, b| a.length <=> b.length } """) assert self.unwrap(space, w_res) == "albatross" assert space.execute("[].max") is space.w_nil def test_singleton_subscript(self, space): w_res = space.execute("return Array[6, -1]") assert self.unwrap(space, w_res) == [6, -1] def test_each(self, space):
if line.lstrip().find('!') == 0 and tokens[0] != '!Ver': continue if line.lstrip(' ').find('#') == 0: #sys.stderr.write('allowed_section_names = ' + # str(allowed_section_names) + '\n') if (tokens[0] in allowed_section_names): section_name = tokens[0] section_is_auto = tokens[-1].endswith('_auto') tokens_after_section_name = tokens[1:] sys.stderr.write(' encountered section \"'+tokens[0]+'\"\n') continue elif (not tokens[0] in ('#version','#define')): raise InputError('Error: Line# '+str(iline) +'\n' ' Unrecognized section name:\n' ' \"' + tokens[0] + '\"\n') elif (len(tokens) > 8) and (section_name == '#torsion_1'): if line.lstrip().find('!') == 0: continue atom_names = SortByEnds(map(EncodeAName, tokens[2:6])) dihedral_name = EncodeInteractionName(atom_names, section_is_auto) dihedral2ver[dihedral_name] = tokens[0] dihedral2ref[dihedral_name] = tokens[1] dihedral2priority_or[dihedral_name] = \ DetermineNumericPriority(section_is_auto, tokens[2:6], float(dihedral2ver[dihedral_name])) dihedral_is_secondary_or[dihedral_name] = False dihedral2priority[dihedral_name] = \ (section_is_auto, dihedral_is_secondary_or[dihedral_name], dihedral2priority_or[dihedral_name]) K = tokens[6] n = tokens[7] d = tokens[8] w = '0.0' #ignore: this is only used by the CHARMM force field if (dihedral_styles_selected & set(['charmm','torsion_1'])): dihedral_styles.add('charmm') dihedral2style[dihedral_name] = 'charmm' #dihedral2params_or[dihedral_name] = [K,n,d,w] dihedral2params[dihedral_name] = (K+' '+n+' '+d+' '+w) elif (dihedral_styles_selected & set(['class2','torsion_3'])): # Then this is a special case of the class2 angle # lacking the higher terms in the Fourier series dihedral_styles.add('class2') dihedral2style[dihedral_name] = 'class2' dihedral2params_or[dihedral_name] = [K,d,0,0,0,0] elif ((len(tokens) > 7) and (section_name == '#torsion_3') and (dihedral_styles_selected & set(['class2','torsion_3']))): if line.lstrip().find('!') == 0: continue dihedral_styles.add('class2') atom_names = SortByEnds(map(EncodeAName, tokens[2:6])) dih_name_orig = EncodeInteractionName(atom_names, section_is_auto) version = tokens[0] reference = tokens[1] dihedral2priority_or[dih_name_orig] = \ DetermineNumericPriority(section_is_auto, tokens[2:6], float(version)) dihedral_is_secondary_or[dih_name_orig] = False #dihedral2priority[dih_name_orig] = \ # (section_is_auto, # dihedral_is_secondary_or[dih_name_orig], # dihedral2priority_or[dih_name_orig]) V1 = tokens[6] phi0_1 = tokens[7] V2 = phi0_2 = V3 = phi0_3 = '0.0' if len(tokens) > 9: V2 = tokens[8] phi0_2 = tokens[9] if len(tokens) > 11: V3 = tokens[10] phi0_3 = tokens[11] dihedral2style_or[dih_name_orig] = 'class2' dihedral2ver_or[dih_name_orig] = version dihedral2ref_or[dih_name_orig] = reference dihedral2params_or[dih_name_orig] = [V1, phi0_1, V2, phi0_2, V3, phi0_3] # default values for cross terms: if not dih_name_orig in dihedral2class2_mbt_or: dihedral2class2_mbt_or[dih_name_orig] = ['0.0','0.0','0.0'] # default value dihedral2ver_mbt_or[dih_name_orig] = version dihedral2ref_mbt_or[dih_name_orig] = reference if not dih_name_orig in dihedral2class2_ebt_or: dihedral2class2_ebt_or[dih_name_orig] = [['0.0','0.0','0.0'],['0.0','0.0','0.0']] # default value dihedral2ver_ebt_or[dih_name_orig] = version dihedral2ref_ebt_or[dih_name_orig] = reference if not dih_name_orig in dihedral2class2_bb13_or: dihedral2class2_bb13_or[dih_name_orig] = '0.0' # default value dihedral2ver_bb13_or[dih_name_orig] = version dihedral2ref_bb13_or[dih_name_orig] = reference if not dih_name_orig in dihedral2class2_at_or: dihedral2class2_at_or[dih_name_orig] = [['0.0','0.0','0.0'],['0.0','0.0','0.0']] # default value dihedral2ver_at_or[dih_name_orig] = version dihedral2ref_at_or[dih_name_orig] = reference if not dih_name_orig in dihedral2class2_aat_or: dihedral2class2_aat_or[dih_name_orig] = '0.0' # default value dihedral2ver_aat_or[dih_name_orig] = version dihedral2ref_aat_or[dih_name_orig] = reference elif ((len(tokens) > 6) and (section_name == '#middle_bond-torsion_3') and (dihedral_styles_selected & set(['class2','torsion_3']))): if line.lstrip().find('!') == 0: continue dihedral_styles.add('class2') version = tokens[0] reference = tokens[1] if line.lstrip().find('!') == 0: continue aorig = [a for a in map(EncodeAName, tokens[2:6])] atom_names = SortByEnds(aorig) Fmbt = [tokens[6], '0.0', '0.0'] if len(tokens) > 7: Fmbt[1] = tokens[7] if len(tokens) > 8: Fmbt[2] = tokens[8] dih_name_orig = EncodeInteractionName(atom_names, section_is_auto) #sys.stderr.write('DEBUG: (a2,a3) = '+str((a2,a3))+', ' # ' (b1,b2) = '+str(batoms)+'\n') dihedral2style[dih_name_orig] = 'class2' dihedral2class2_mbt_or[dih_name_orig] = [F for F in Fmbt] dihedral2ver_mbt_or[dih_name_orig] = version dihedral2ref_mbt_or[dih_name_orig] = reference if not dih_name_orig in dihedral2params_or: dihedral_is_secondary_or[dih_name_orig] = True #only cross terms have been defined so far dihedral2params_or[dih_name_orig] = ['0.0', '0.0', '0.0', '0.0', '0.0', '0.0'] dihedral2ver_or[dih_name_orig] = version dihedral2ref_or[dih_name_orig] = reference dihedral2priority_or[dih_name_orig] = 0.0 elif ((len(tokens) > 6) and (section_name in ('#end_bond-torsion_3', '#bond-bond_1_3')) and (dihedral_styles_selected & set(['class2', 'torsion_3']))): if line.lstrip().find('!') == 0: continue dihedral_styles.add('class2') version = tokens[0] reference = tokens[1] if line.lstrip().find('!') == 0: continue aorig = [a for a in map(EncodeAName, tokens[2:6])] atom_names = SortByEnds(aorig) dih_name_orig = EncodeInteractionName(atom_names, section_is_auto) dihedral2style[dih_name_orig] = 'class2' if section_name == '#end_bond-torsion_3': Febt = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] Febt[0][0] = tokens[6] if len(tokens) > 7: Febt[0][1] = tokens[7] if len(tokens) > 8: Febt[0][2] = tokens[8] Febt[1][0] = Febt[0][0] Febt[1][1] = Febt[0][1] Febt[1][2] = Febt[0][2] if len(tokens) > 9: Febt[1][0] = tokens[9] if len(tokens) > 10: Febt[1][1] = tokens[10] if len(tokens) > 11: Febt[1][2] = tokens[11] order_reversed = aorig[0] > aorig[-1] if order_reversed: Febt.reverse() dihedral2class2_ebt_or[dih_name_orig] = [ [F_ij for F_ij in F_i] for F_i in Febt] #deep copy of Febt[][] dihedral2ver_ebt_or[dih_name_orig] = version dihedral2ref_ebt_or[dih_name_orig] = reference elif section_name == '#bond-bond_1_3': Kbb13 = tokens[6] #dihedral2ver_bb13[dih_name_orig] = version dihedral2class2_bb13_or[dih_name_orig] = Kbb13 dihedral2ver_bb13_or[dih_name_orig] = version dihedral2ref_bb13_or[dih_name_orig] = reference else: assert(False) if not dih_name_orig in dihedral2params_or: dihedral_is_secondary_or[dih_name_orig] = True #only cross terms have been defined so far dihedral2params_or[dih_name_orig] = ['0.0', '0.0', '0.0', '0.0', '0.0', '0.0'] dihedral2ver_or[dih_name_orig] = version dihedral2ref_or[dih_name_orig] = reference dihedral2priority_or[dih_name_orig] = 0.0 elif ((len(tokens) > 6) and (section_name in ('#angle-torsion_3', '#angle-angle-torsion_1')) and (dihedral_styles_selected & set(['class2', 'torsion_3']))): if line.lstrip().find('!') == 0: continue dihedral_styles.add('class2') version = tokens[0] reference = tokens[1] if line.lstrip().find('!') == 0: continue aorig = [a for a in map(EncodeAName, tokens[2:6])] atom_names = SortByEnds(aorig) dih_name_orig = EncodeInteractionName(atom_names, section_is_auto) dihedral2style[dih_name_orig] = 'class2' if section_name == '#angle-torsion_3': Fat = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] Fat[0][0] = tokens[6] if len(tokens) > 7: Fat[0][1] = tokens[7] if len(tokens) > 8: Fat[0][2] = tokens[8] Fat[1][0] = Fat[0][0] Fat[1][1] = Fat[0][1] Fat[1][2] = Fat[0][2] if len(tokens) > 9: Fat[1][0] = tokens[9] if len(tokens) > 10: Fat[1][1] = tokens[10] if len(tokens) > 11: Fat[1][2] = tokens[11] order_reversed = aorig[0] > aorig[-1] if order_reversed: Fat.reverse() Fat[0].reverse() Fat[1].reverse() dihedral2class2_at_or[dih_name_orig] = [ [F_ij for F_ij in F_i] for F_i in Fat] #deep copy of Fat dihedral2ver_at_or[dih_name_orig] = version dihedral2ref_at_or[dih_name_orig] = reference elif section_name == '#angle-angle-torsion_1': Kaat = tokens[6] dihedral2class2_aat_or[dih_name_orig] = Kaat dihedral2ver_aat_or[dih_name_orig] = version dihedral2ref_aat_or[dih_name_orig] = reference else: assert(False) if not dih_name_orig in dihedral2params_or: dihedral_is_secondary_or[dih_name_orig] = True #only cross terms have been defined so far dihedral2params_or[dih_name_orig] = ['0.0', '0.0', '0.0', '0.0', '0.0', '0.0'] # default value dihedral2ver_or[dih_name_orig] = version dihedral2ref_or[dih_name_orig] = reference dihedral2priority_or[dih_name_orig] = 0.0 elif ((len(tokens) > 8) and (section_name == '#out_of_plane') and (improper_styles_selected & set(['cvff','out_of_plane']))): if line.lstrip().find('!') == 0: continue improper_styles.add('cvff') aorig = [a for a in map(EncodeAName, tokens[2:6])] atom_names,_ignore = OOPImproperNameSort(tokens[2:6]) improper_name = EncodeInteractionName(atom_names, section_is_auto) imsym = improper_symmetry_subgraph[improper_name] = 'cenJflipIL' subgraph2impname['cenJflipIL'].add(improper_name) CONTINUEHERE improper2ver[imsym][improper_name] = tokens[0] improper2ref[imsym][improper_name] = tokens[1] improper2priority_or[imsym][improper_name] = \ DetermineNumericPriority(section_is_auto, tokens[2:6], float(improper2ver[imsym][improper_name])) improper_is_secondary_or[imsym][imp_name_orig] = False improper2priority[imsym][improper_name] = \ (section_is_auto, improper_is_secondary_or[imsym][imp_name_orig], improper2priority_or[imsym][improper_name]) K = tokens[6] n = tokens[7] chi0 = tokens[8] improper2style[imsym][improper_name] = 'cvff' improper2params[imsym][improper_name] = (Kchi+' '+n+' '+chi0) #if improper_style_name == 'cvff': # improper2params[improper_name] = (Kchi+' '+n+' '+chi0) # improper_symmetry_subgraph[improper_name] = 'cenJswapIL' elif ((len(tokens) > 7) and (section_name == '#wilson_out_of_plane') and (improper_styles_selected and set(['class2','wilson_out_of_plane']))): if line.lstrip().find('!') == 0: continue improper_styles.add('class2') sys.stderr.write('tokens = ' + str(tokens) + '\n') version = tokens[0] reference = tokens[1] aorig = [a for a in map(EncodeAName, tokens[2:6])] # To avoid redundancy, it is necessary to order the atoms # in the interaction so that two equivalent ways of ordering # the atoms in an improper interaction do not get misinterpreted # as two different types of improper interactions. So we sort # the 3 "leaf" atoms surrounding the central "hub" by name. atom_names, permutation = Class2ImproperNameSort(tokens[2:6]) # This will effect the formula for the energy. # (specifically the "chi0" parameter) # When we lookup the various cross-term interactions for that # same improper interaction, we will be sure to sort them # in the same way to make sure those interactions are # associated with the same improper interaction. imp_name_orig = EncodeInteractionName(atom_names, section_is_auto) #improper_symmetry_subgraph_or[improper_name] = 'dihedrals_nosym' (<--no) imsym = improper_symmetry_subgraph_or[imp_name_orig] = 'cenJsortIKL' improper2ver_or[imsym][imp_name_orig] = version improper2ref_or[imsym][imp_name_orig] = reference improper2priority_or[imsym][imp_name_orig] = \ DetermineNumericPriority(section_is_auto, tokens[2:6], float(improper2ver_or[imp_name_orig])) improper_is_secondary_or[imsym][imp_name_orig] = False #improper2priority[imp_name_orig] = \ # (section_is_auto, # improper_is_secondary_or[imp_name_orig], # improper2priority_or[imp_name_orig]) K = tokens[6] chi0 = tokens[7] if Parity(permutation) != 0: # Each time the order of a pair of atoms is swapped in # the interaction, all 3 of the "X" (chi) angles change sign # The formula for the ordinary term in the improper # interaction is Ei = K*((Xijkl + Xkjli + Xljik)/3 - chi0)^2 # This formula is invariant if we change the sign of all # Xijkl, Xkjli, Xljik, chi0 # Hence, we can account for a change in atom order by # changing the sign of the "chi0" parameter. # We calculate the "Parity" of the permutation (ie whether # the permutation has an even or odd number of swaps) # and multiply chi0 by -1 for each swap. # It's
""" Support mudule for EPICS Input/Output Controllers (IOCs) Implements the server side of the Channel Access (CA) protocol, version 4.11. Author: <NAME> Date created: 2009-10-31 Date last modified: 2019-11-08 based on: 'Channel Access Protocol Specification', version 4.11 http://epics.cosylab.com/cosyjava/JCA-Common/Documentation/CAproto.html Object-Oriented Interface 1 PV class object: recommended for application that export a single process variable. def getT(): return float(serial_port.query("SET:TEMP?")) def setT(T): serial_port.write("SET:TEMP %s" % T) pv = PV("14IDB:TemperatureController.T",get=getT,set=setT) Object-Oriented Interface 2 Use "register" object to export properties of a Python class object as EPICS PVs. class Temperature(object): def get_value(self): return float(serial_port.query("SET:TEMP?")) def set_value(self,value): serial_port.write("SET:TEMP %s" % value) value = property(get_value,set_value) T = Temperature() register_object(T,prefix="14IDB:TemperatureController.") Procedural Interface casput ("14IDB:MyInstrument.VAL",1.234) Creates a process variable named "14IDB:MyInstrument.VAL" Subsequent calls to with difference value cause update events to besent to connected clients. casget ("14IDB:MyInstrument.VAL") Reads back the current value of the "14IDB:MyInstrument.VAL", which may have been modified be a client since the last casput. casmonitor("14IDB:MyInstrument.VAL",callback=procedure) The function "procedure" is called when a client modifies a the process variable with three arguments: - the name of the process variable - the new value - the new value as string """ from logging import debug, info, warning, error __version__ = "1.7.4" # bug fix: isstring DEBUG = False # Generate debug messages? registered_object_list = [] def register_object(object, name=""): """Export object as PV under the given name""" global registered_object_list start_server() unregister_object(name=name) registered_object_list += [(object, name)] casregister = CAServer_register = register_object # alias names def unregister_object(object=None, name=None): """Undo 'register_object'""" global registered_object_list if name is None: for (o, n) in registered_object_list: if o is object: name = n if name is not None: for PV_name in list(PVs): if PV_name.startswith(name): delete_PV(PV_name) if object is not None: for (o,n) in registered_object_list: if o is object: name = n for PV_name in list(PVs): if PV_name.startswith(name): delete_PV(PV_name) registered_object_list = [ (o, n) for (o, n) in registered_object_list if not o is object ] if name is not None: registered_object_list = [(o, n) for (o, n) in registered_object_list if not n == name] def registered_objects(): """List of Python object instances""" return [object for (object,name) in registered_object_list] registered_properties = {} def register_property(object, property_name, PV_name): """Export object as PV under the given name""" global registered_properties start_server() unregister_property(PV_name=PV_name) registered_properties[PV_name] = (object, property_name) def unregister_property(object=None, property_name=None, PV_name=None): """Undo 'register_object'""" global registered_properties if object is not None and property_name is not None and PV_name is not None: if PV_name in registered_properties: if registered_properties[PV_name] == (object, property_name): del registered_properties[PV_name] elif PV_name is not None: if PV_name in registered_properties: del registered_properties[PV_name] elif object is not None and property_name is not None: for key in list(registered_properties): if registered_properties[key] == (object, property_name): del registered_properties[key] def casdel(name): """Undo 'casput'""" for PV_name in list(PVs): if PV_name.startswith(name): delete_PV(PV_name) class PV(object): """Process Variable. Override the 'set_value' and 'get_value' methods in subclasses""" instances = [] def __init__(self, name): """name: common prefix for all process variables, e.g. '14IDB:MyInstrument.'""" self.__name__ = name self.instances += [self] start_server() def get_value(self): return getattr(self, "__value__", None) def set_value(self, value): self.__value__ = value value = property(get_value, set_value) def get_connected(self): return PV_connected(self.__name__) connected = property(get_connected) def __setattr__(self, attr, value): """Called when x.attr = value is executed.""" ##if DEBUG: debug("PV.__setattr__(%r,%r)" % (attr,value)) object.__setattr__(self, attr, value) if attr == "value": notify_subscribers_if_changed(self.__name__, value) def __getattr__(self, attr): """Called when x.attr is evaluated.""" ##if DEBUG: debug("PV.__getattr__(%r)" % attr) value = object.__getattr__(self, attr) if attr == "value": notify_subscribers_if_changed(self.__name__, value) return value def casput(PV_name, value, update=True): """Create a new process variable with thte given name, or update an existing one. update: send an updaate to the clients even if the value has not changed. """ if DEBUG: debug("casput(%r,%r)" % (PV_name, value)) start_server() if not PV_name in PVs: PVs[PV_name] = PV_info() PV = PVs[PV_name] if not CA_equal(PV_value(PV_name), value) or update: PV_set_value(PV_name, value, keep_type=False) CAServer_put = casput def casget(PV_name): """Current value of a process variable""" start_server() return PV_value(PV_name) CAServer_get = casget def casmonitor(PV_name, writer=None, callback=None): """Call a function every time a PV changes value. writer: function that will be passed a formatted string: "<PB_name> <date> <time> <value>" E.g. "14IDB:SAMPLEZ.RBV 2013-11-02 18:25:13.555540 4.3290" f=file("PV.log","w"); camonitor("14IDB:SAMPLEZ.RBV",f.write) callback: function that will be passed three arguments: the PV name, its new value, and its new value as string. E.g. def callback(PV_name,value,char_value): def callback(pvname,value,char_value): print pvname,value,char_value """ start_server() if not PV_name in PVs: PVs[PV_name] = PV_info() PV = PVs[PV_name] if callback is None and writer is None: # By default, if not argument are given, just print update messages. import sys writer = sys.stdout.write if callback is not None: if not callback in PV.callbacks: PV.callbacks += [callback] if writer is not None: if not writer in PV.writers: PV.writers += [writer] CAServer_monitor = casmonitor class PV_info: """State information for each process variable""" def __init__(self): self.value = None # current value in Python format self.subscribers = {} # subscriber_info objects, indexed by (address,port) self.channel_SID = ( self.new_channel_SID() ) # server-assigned session identity number self.last_updated = 0 # timestamp of value self.callbacks = [] # for "casmonitor" self.writers = [] # for "casmonitor" @staticmethod def new_channel_SID(): """Interger starting with 1""" with PV_info.lock: PV_info.last_channel_SID += 1 return PV_info.last_channel_SID from threading import Lock lock = Lock() last_channel_SID = 0 def __repr__(self): return "PV_info(channel_SID=%r)" % self.channel_SID PVs = {} # Active process variables, indexed by name class subscriber_info: """State information for each active connection to a process variable""" def __init__(self, subscription_ID=None, data_type=None, data_count=None): """subscription_ID: client-assigned number for EVENT_ADD updates""" self.subscription_ID = subscription_ID self.data_type = data_type # DOUBLE,LONG,STRING,... self.data_count = data_count # 1 if a scalar, >1 if an array cache = {} # values of PVs cache_timeout = 1.0 class cache_entry: def __init__(self, value, time): self.value = value self.time = time def __repr__(self): return "(%r,%s)" % (self.value, date_string(self.time)) def PV_exists(PV_name): """Has a process variable with the given name been defined?""" ##return PV_name in PVs or PV_value(PV_name) is not None return PV_value(PV_name) is not None def PV_value(PV_name, cached=True): """The value of a process variable as Python data type. If the process variable has not been define return None.""" from time import time if cached and PV_name in cache: if time() <= cache[PV_name].time + cache_timeout: ##if DEBUG: debug("%s in cache" % PV_name) return cache[PV_name].value ##if DEBUG: debug("%s expired from cache" % PV_name) value = PV_current_value(PV_name) cache[PV_name] = cache_entry(value, time()) return value def PV_current_value(PV_name): """The current value of a process variable as Python data type. If the process variable has not been define return None.""" from time import time t0 = time() value = PV_value_or_object(PV_name) # Is value is an object, use the PV name instead. if isobject(value): value = "<record: %s>" % ", ".join(members(value)) ##if DEBUG: debug("%s: current value %r (%.3f s)" % (PV_name,value,time()-t0)) return value def PV_value_or_object(PV_name): """The current value of a process variable as Python data type. If the process variable has not been define return None.""" for object, name in registered_object_list: if PV_name.startswith(name): attribute = PV_name[len(name) :] ##try: return eval("object"+attribute+".value") ##except: pass try: return eval("object" + attribute) except: pass if PV_name in registered_properties: object, property_name = registered_properties[PV_name] try: return getattr(object, property_name) except Exception as msg: error("%s: %r.%s: %s" % (PV_name, object, property_name, msg)) record = object_instance(PV_name) if record: return getattr(record, object_property(PV_name)) if PV_name in PVs: return PVs[PV_name].value return None def isobject(x): """Is x a class object?""" if hasattr(x, "__len__"): return False # array if hasattr(x, "__dict__"): return True return False def members(x): """x: class object Return value: list of strings""" function = type(lambda: 0) members = [] for name in dir(x): if name.startswith("__") and name.endswith("__"): continue ##if type(getattr(x,name)) == function: continue members += [name] return members def PV_set_value(PV_name, value, keep_type=True): """Modify the local value of a process variable (The value retreived by 'PV_value')""" if DEBUG: debug("set %s = %r" % (PV_name, value)) if keep_type: value = convert(PV_name, value) for object, name in registered_object_list: if PV_name.startswith(name + "."): attribute = PV_name[len(name + ".") :] PV_object_name = "object." + attribute try: PV_object = eval(PV_object_name) except Exception as exception: if DEBUG: debug("%s: %s" % (PV_object_name, exception)) continue if hasattr(PV_object, "value"): code = "object.%s.value = %r" % (attribute, value) from numpy import nan, inf # needed for exec try: exec(code) if DEBUG: debug("Tried %s: OK" % code.replace("object", name)) continue except Exception as exception: if DEBUG: debug("Tried %s: failed: %s" % (code, exception)) else: if not ("." in attribute or "[" in attribute): try: setattr(object, attribute, value) if
# -*- coding: UTF-8 -*- """ 1. Category words Input : {"tea", "eat", "ate", "run","urn","cool","school"} Output : {{"tea", "eat", "ate"},{"run","urn"}} """ # set and list are unhashable def category(words): table = {} result = [] for word in words: # Sort the string as list, and use string as hash key chars = str(sorted(list(word))) if chars in table: table[chars].append(word) else: table[chars] = [word] for word_list in table.values(): if len(word_list) > 1: result.append(word_list) return result words = ["tea", "eat", "ate", "run","urn","cool","school"] print category(words) """ 2. Copy a list input: ----------- | | A---->B--->C---->D---->E | ^ | | ------------ output: ------------ | | A'---->B'--->C'---->D'---->E'' | ^ | | ------------ struct node { node * next; node * jump; int val } """ # Ask question: # 1. Any loop? (A.jump = B, B.jump = A) # 2. Duplicates values? def copy_list(a): # this only works when there is no loop b = Node(a) heada = a headb = b # Copy this list without jump pointer while a.next: b.next = Node(a.next.val) a = a.next b = b.next a = heada b = headb while a: if a.jump: table[a.jump.val] = b if b.val in table: table[b.val].jump = b a = a.next b = b.next return headb # This works for list with loop def copyRandomList2(self, head): if not head: return None table = {} dummy = RandomListNode(0) b = RandomListNode(0) a = head pre = dummy dummy.next = b while a: if a in table: b = table[a] else: b = RandomListNode(a.label) table[a] = b pre.next = b if a.random: if a.random in table: b.random = table[a.random] else: b.random = RandomListNode(a.random.label) table[a.random] = b.random pre = pre.next a = a.next return dummy.next """ 3. Clone graph Return a deep copy of graph """ """ 4. Continuous sequence with the largest sum Example: input[2,-8,3,-2,4,-10] -> output: 5 (from the continuous sequence 3,-2,4). """ # 如果相加<0, 记作0,否则一直加下去 """ 5. shortest path to Good point. gave a matrix, (B means cannot go through) 000 BGG G00 calculate the shortest path between each 0 to G, so result will be 211 BGG G11 """ # 从G开始把周围元素加1,再从所有1开始把1周围的所有元素加1,一个队列就行了 import Queue def shortest(ma): m = len(ma) n = len(ma[0]) for i in range(m): ma[i] = list(ma[i]) print ma for i in range(m): for j in range(n): if ma[i][j] == 'G': if valid(i-1, j, m, n, ma): ma[i-1][j] = 1 if valid(i+1, j, m, n, ma): ma[i+1][j] = 1 if valid(i, j-1, m, n, ma): ma[i][j-1] = 1 if valid(i, j+1, m, n, ma): ma[i][j+1] = 1 if ma[i][j] == '0': ma[i][j] = 0 q = Queue.Queue() for i in range(m): for j in range(n): if ma[i][j] == 1: q.put((i,j)) while q.qsize() > 1: i, j = q.get() if valid(i-1, j, m, n, ma): enqueue(i-1, j, i, j, ma, q) if valid(i+1, j, m, n, ma): enqueue(i+1, j, i, j, ma, q) if valid(i, j-1, m, n, ma): enqueue(i, j-1, i, j, ma, q) if valid(i, j+1, m, n, ma): enqueue(i, j+1, i, j, ma, q) return ma def valid(i, j, m, n, ma): if 0 <= i < m and 0 <= j < n: if ma[i][j] != 'B' and ma[i][j] != 'G': return True return False def enqueue(i, j, x, y, ma, q): if ma[i][j] == 0: ma[i][j] = ma[x][y]+1 q.put((i, j)) else: if ma[x][y]+1 < ma[i][j]: ma[i][j] = ma[x][y]+1 q.put((i, j)) matrix = ["000", "BGG", "G00" ] #print shortest(matrix) """ 6. Sum of two linked list 7->8 + 2->2 = 1->0->0 """ class ListNode(object): def __init__(self, x): self.val = x self.next = None # reverse two linked lists, sum them up and reverse back def list_sum(a1, b1): a = reverse(a1) b = reverse(b1) dummy = c = ListNode(0) carry = 0 while a or b or carry: if a: carry += a.val a = a.next if b: carry += b.val b = b.next carry, val = divmod(carry, 10) c.next = ListNode(val) c = c.next return reverse(dummy.next) def reverse(a): pre = None cur = a while cur: nex = cur.next cur.next = pre pre = cur cur = nex return pre #a = ListNode(1) #a.next = ListNode(2) #a.next.next = ListNode(9) #b = ListNode(2) #b.next = ListNode(1) # #nh = list_sum(a, b) #while nh: # print nh.val # nh = nh.next """ 7. check parentheses is balanced """ # Remember if all are right parentheses # stack will still be empty at last stack = [] if not stack: return not input """ 8. Wildcard Matching '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") → false isMatch("aa","aa") → true isMatch("aaa","aa") → false isMatch("aa", "*") → true isMatch("aa", "a*") → true isMatch("ab", "?*") → true isMatch("aab", "c*a*b") → false """ def isMatch(self, s, p): si, pi, match = 0, 0, 0 stari = -1 while si<len(s): # advancing both pointers if pi<len(p) and (p[pi] == '?' or s[si] == p[pi]): si += 1 pi += 1 # * found, only advancing pattern pointer elif pi < len(p) and p[pi] == '*': stari = pi match = si pi += 1 # current pattern pointer is not star, last pattern pointer was not * # characters do not match elif stari != -1: pi = stari + 1 match += 1 si = match else: return False while pi < len(p) and p[pi] == '*': pi += 1 return pi == len(p) """ 9. Longest Substring Without Repeating Characters """ def lengthOfLongestSubstring(self, s): if not s: return 0 re = s[0] m = 1 for i in xrange(1, len(s)): if s[i] not in re: re += s[i] else: j = re.index(s[i]) re = re[j+1:] + s[i] if len(re) > m: m = len(re) return m """ 10. Create class which stores big integers (of any length) and implement addition operation. Store the number in array with a reversed way """ class BigInt(): def __init__(self, num_str): if num_str[0] != '-': self.positive = True self.intlist = [int(d) for d in num_str] else: self.positive = False self.intlist = [int(d) for d in num_str[1:]] self.intlist.reverse() # reverse() has NO return value!!! def add(self, bigint): if self.abs_bigger(bigint): a = self.intlist b = bigint.intlist positive = self.positive else: a = bigint.intlist b = self.intlist positive = bigint.positive if self.positive != bigint.positive: return self.sub(a, b, positive) m = len(a) n = len(b) carry = 0 for i in range(m): if i < n: carry, val = divmod(a[i]+b[i]+carry, 10) else: carry, val = divmod(a[i]+carry, 10) a[i] = val if carry > 0: a.append(1) return positive, a def sub(self, a, b, positive): m = len(a) n = len(b) carry = 0 for i in range(m): if i < n: if a[i] + carry >= b[i]: a[i] -= b[i] carry = 0 else: a[i] = a[i] + 10 - b[i] carry = -1 else: if a[i] + carry >= 0: a[i] += carry carry = 0 else: a[i] = a[i] + 10 + carry carry = -1 if a[-1] == 0: if len(a) != 1: a = a[:-1] return positive, a def abs_bigger(self, bigint): if len(self.intlist) > len(bigint.intlist): return True elif len(self.intlist) == len(bigint.intlist): for i in range(len(self.intlist)): if self.intlist[i] > bigint.intlist[i]: return True elif self.intlist[i] < bigint.intlist[i]: return False return True else: return False # test cases: print BigInt('0').add(BigInt('0')) print BigInt('0').add(BigInt('1')) print BigInt('1').add(BigInt('99')) print BigInt('100').add(BigInt('-1')) print BigInt('1').add(BigInt('-1')) print BigInt('-1').add(BigInt('-100')) print BigInt('-1').add(BigInt('100000')) """ 11. Print all items on k-th level of a binary tree. Use recursive way (DFS) """ def klevel(root, k): result = [] if not root: return result dfs(root, result, 1, k) return result def dfs(node, result, cur_level, max_level): if not node or cur_level > max_level: return if cur_level == max_level: result.append(node) return dfs(node.left, result, cur_level+1, max_level) dfs(node.right, result, cur_level+1, max_level) """ 12. Implement pow(x, n). X to the power of N 1.Most naive method, simply multiply x n times: The time complecity is O(n), but will cause(stack overflow)error 2.Do division before recursive: x^n = x^n/2 * x^n/2 * x^n%2 Time complexity is O(logN) NOTE: 1. n might be positive or negetive 2. 0^0 = 1, 0^positive = 0, 0^negetive nonsence """ # @param x, a float # @param n, a integer # @return a float # Recursive def myPow(self, x, n): if n == 0: return 1 if n < 0: return 1 / self.myPow(x, -n) if n % 2 == 1: return x * self.myPow(x, n-1) return self.myPow(x*x, n/2) # Iterative def pow2(self, x, n): if n == 0: return 1 if n < 0: x =
['--segmentation-id', '--segmentation_id']: self.run_command('share-network-list %s 1234' % command) self.assert_called( 'GET', '/share-networks/detail?segmentation_id=1234', ) cliutils.print_list.assert_called_with( mock.ANY, fields=['id', 'name']) @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_share_network_list_ip_version_aliases(self): for command in ['--ip-version', '--ip_version']: self.run_command('share-network-list %s 4' % command) self.assert_called( 'GET', '/share-networks/detail?ip_version=4', ) cliutils.print_list.assert_called_with( mock.ANY, fields=['id', 'name']) @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_share_network_list_all_filters(self): filters = { 'name': 'fake-name', 'project-id': '1234', 'created-since': '2001-01-01', 'created-before': '2002-02-02', 'neutron-net-id': 'fake-net', 'neutron-subnet-id': 'fake-subnet', 'network-type': 'local', 'segmentation-id': '5678', 'cidr': 'fake-cidr', 'ip-version': '4', 'offset': 10, 'limit': 20, } command_str = 'share-network-list' for key, value in filters.items(): command_str += ' --%(key)s=%(value)s' % {'key': key, 'value': value} self.run_command(command_str) query = utils.safe_urlencode(sorted([(k.replace('-', '_'), v) for (k, v) in filters.items()])) self.assert_called( 'GET', '/share-networks/detail?%s' % query, ) cliutils.print_list.assert_called_once_with( mock.ANY, fields=['id', 'name']) def test_share_network_list_filter_by_inexact_name(self): for separator in self.separators: self.run_command('share-network-list --name~' + separator + 'fake_name') self.assert_called( 'GET', '/share-networks/detail?name~=fake_name') def test_share_network_list_filter_by_inexact_description(self): for separator in self.separators: self.run_command('share-network-list --description~' + separator + 'fake_description') self.assert_called( 'GET', '/share-networks/detail?description~=fake_description') def test_share_network_list_filter_by_inexact_unicode_name(self): for separator in self.separators: self.run_command('share-network-list --name~' + separator + u'ффф') self.assert_called( 'GET', '/share-networks/detail?name~=%D1%84%D1%84%D1%84') def test_share_network_list_filter_by_inexact_unicode_description(self): for separator in self.separators: self.run_command('share-network-list --description~' + separator + u'ффф') self.assert_called( 'GET', '/share-networks/detail?description~=%D1%84%D1%84%D1%84') def test_share_network_security_service_add(self): self.run_command('share-network-security-service-add fake_share_nw ' 'fake_security_service') self.assert_called( 'POST', '/share-networks/1234/action', ) def test_share_network_security_service_remove(self): self.run_command('share-network-security-service-remove fake_share_nw ' 'fake_security_service') self.assert_called( 'POST', '/share-networks/1234/action', ) @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_share_network_security_service_list_select_column(self): self.run_command('share-network-security-service-list ' 'fake_share_nw --column id,name') self.assert_called( 'GET', '/security-services/detail?share_network_id=1234', ) cliutils.print_list.assert_called_once_with( mock.ANY, fields=['Id', 'Name']) def test_share_network_security_service_list_by_name(self): self.run_command('share-network-security-service-list fake_share_nw') self.assert_called( 'GET', '/security-services/detail?share_network_id=1234', ) def test_share_network_security_service_list_by_name_not_found(self): self.assertRaises( exceptions.CommandError, self.run_command, 'share-network-security-service-list inexistent_share_nw', ) def test_share_network_security_service_list_by_name_multiple(self): self.assertRaises( exceptions.CommandError, self.run_command, 'share-network-security-service-list duplicated_name', ) def test_share_network_security_service_list_by_id(self): self.run_command('share-network-security-service-list 1111') self.assert_called( 'GET', '/security-services/detail?share_network_id=1111', ) @ddt.data( {}, {'--neutron_net_id': 'fake_neutron_net_id', '--neutron_subnet_id': 'fake_neutron_subnet_id'}, {'--availability-zone': 'fake_availability_zone_id'}, {'--neutron_net_id': 'fake_neutron_net_id', '--neutron_subnet_id': 'fake_neutron_subnet_id', '--availability-zone': 'fake_availability_zone_id'}) def test_share_network_subnet_add(self, data): fake_share_network = type( 'FakeShareNetwork', (object,), {'id': '1234'}) self.mock_object( shell_v2, '_find_share_network', mock.Mock(return_value=fake_share_network)) cmd = 'share-network-subnet-create' for k, v in data.items(): cmd += ' ' + k + ' ' + v cmd += ' ' + fake_share_network.id self.run_command(cmd) shell_v2._find_share_network.assert_called_once_with( mock.ANY, fake_share_network.id) self.assert_called('POST', '/share-networks/1234/subnets') @ddt.data( {'--neutron_net_id': 'fake_neutron_net_id'}, {'--neutron_subnet_id': 'fake_neutron_subnet_id'}, {'--neutron_net_id': 'fake_neutron_net_id', '--availability-zone': 'fake_availability_zone_id'}, {'--neutron_subnet_id': 'fake_neutron_subnet_id', '--availability-zone': 'fake_availability_zone_id'}) def test_share_network_subnet_add_invalid_param(self, data): cmd = 'share-network-subnet-create' for k, v in data.items(): cmd += ' ' + k + ' ' + v cmd += ' fake_network_id' self.assertRaises( exceptions.CommandError, self.run_command, cmd) def test_share_network_subnet_add_invalid_share_network(self): cmd = 'share-network-subnet-create not-found-id' self.assertRaises( exceptions.CommandError, self.run_command, cmd) @ddt.data(('fake_subnet1', ), ('fake_subnet1', 'fake_subnet2')) def test_share_network_subnet_delete(self, subnet_ids): fake_share_network = type( 'FakeShareNetwork', (object,), {'id': '1234'}) self.mock_object( shell_v2, '_find_share_network', mock.Mock(return_value=fake_share_network)) fake_share_network_subnets = [ share_network_subnets.ShareNetworkSubnet( 'fake', {'id': subnet_id}, True) for subnet_id in subnet_ids ] self.run_command( 'share-network-subnet-delete %(network_id)s %(subnet_ids)s' % { 'network_id': fake_share_network.id, 'subnet_ids': ' '.join(subnet_ids) }) shell_v2._find_share_network.assert_called_once_with( mock.ANY, fake_share_network.id) for subnet in fake_share_network_subnets: self.assert_called_anytime( 'DELETE', '/share-networks/1234/subnets/%s' % subnet.id, clear_callstack=False) def test_share_network_subnet_delete_invalid_share_network(self): command = 'share-network-subnet-delete %(net_id)s %(subnet_id)s' % { 'net_id': 'not-found-id', 'subnet_id': '1234', } self.assertRaises( exceptions.CommandError, self.run_command, command) def test_share_network_subnet_delete_invalid_share_network_subnet(self): fake_share_network = type( 'FakeShareNetwork', (object,), {'id': '1234'}) self.mock_object( shell_v2, '_find_share_network', mock.Mock(return_value=fake_share_network)) command = 'share-network-subnet-delete %(net_id)s %(subnet_id)s' % { 'net_id': fake_share_network.id, 'subnet_id': 'not-found-id', } self.assertRaises( exceptions.CommandError, self.run_command, command) @mock.patch.object(cliutils, 'print_dict', mock.Mock()) def test_share_network_subnet_show(self): fake_share_network = type( 'FakeShareNetwork', (object,), {'id': '1234'}) self.mock_object( shell_v2, '_find_share_network', mock.Mock(return_value=fake_share_network)) args = { 'share_net_id': fake_share_network.id, 'subnet_id': 'fake_subnet_id', } self.run_command( 'share-network-subnet-show %(share_net_id)s %(subnet_id)s' % args) self.assert_called( 'GET', '/share-networks/%(share_net_id)s/subnets/%(subnet_id)s' % args, ) cliutils.print_dict.assert_called_once_with(mock.ANY) def test_share_network_subnet_show_invalid_share_network(self): command = 'share-network-subnet-show %(net_id)s %(subnet_id)s' % { 'net_id': 'not-found-id', 'subnet_id': 1234, } self.assertRaises( exceptions.CommandError, self.run_command, command) @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_share_server_list_select_column(self): self.run_command('share-server-list --columns id,host,status') self.assert_called('GET', '/share-servers') cliutils.print_list.assert_called_once_with( mock.ANY, fields=['Id', 'Host', 'Status']) def test_create_share(self): # Use only required fields self.run_command("create nfs 1") self.assert_called("POST", "/shares", body=self.create_share_body) def test_create_public_share(self): expected = self.create_share_body.copy() expected['share']['is_public'] = True self.run_command("create --public nfs 1") self.assert_called("POST", "/shares", body=expected) def test_create_with_share_network(self): # Except required fields added share network sn = "fake-share-network" with mock.patch.object(shell_v2, "_find_share_network", mock.Mock(return_value=sn)): self.run_command("create nfs 1 --share-network %s" % sn) expected = self.create_share_body.copy() expected['share']['share_network_id'] = sn self.assert_called("POST", "/shares", body=expected) shell_v2._find_share_network.assert_called_once_with(mock.ANY, sn) def test_create_with_metadata(self): # Except required fields added metadata self.run_command("create nfs 1 --metadata key1=value1 key2=value2") expected = self.create_share_body.copy() expected['share']['metadata'] = {"key1": "value1", "key2": "value2"} self.assert_called("POST", "/shares", body=expected) def test_allow_access_cert(self): self.run_command("access-allow 1234 cert client.example.com") expected = { "allow_access": { "access_type": "cert", "access_to": "client.example.com", } } self.assert_called("POST", "/shares/1234/action", body=expected) def test_allow_access_cert_error_gt64(self): common_name = 'x' * 65 self.assertRaises(exceptions.CommandError, self.run_command, ("access-allow 1234 cert %s" % common_name)) def test_allow_access_cert_error_zero(self): cmd = mock.Mock() cmd.split = mock.Mock(side_effect=lambda: ['access-allow', '1234', 'cert', '']) self.assertRaises(exceptions.CommandError, self.run_command, cmd) cmd.split.assert_called_once_with() def test_allow_access_cert_error_whitespace(self): cmd = mock.Mock() cmd.split = mock.Mock(side_effect=lambda: ['access-allow', '1234', 'cert', ' ']) self.assertRaises(exceptions.CommandError, self.run_command, cmd) cmd.split.assert_called_once_with() def test_allow_access_with_access_level(self): aliases = ['--access_level', '--access-level'] expected = { "allow_access": { "access_type": "ip", "access_to": "10.0.0.6", "access_level": "ro", } } for alias in aliases: for s in self.separators: self.run_command( "access-allow " + alias + s + "ro 1111 ip 10.0.0.6") self.assert_called("POST", "/shares/1111/action", body=expected) def test_allow_access_with_valid_access_levels(self): expected = { "allow_access": { "access_type": "ip", "access_to": "10.0.0.6", } } for level in ['rw', 'ro']: expected["allow_access"]['access_level'] = level self.run_command( "access-allow --access-level " + level + " 1111 ip 10.0.0.6") self.assert_called("POST", "/shares/1111/action", body=expected) def test_allow_access_with_invalid_access_level(self): self.assertRaises(SystemExit, self.run_command, "access-allow --access-level fake 1111 ip 10.0.0.6") def test_allow_access_with_metadata(self): expected = { "allow_access": { "access_type": "ip", "access_to": "10.0.0.6", "metadata": {"key1": "v1", "key2": "v2"}, } } self.run_command( "access-allow 2222 ip 10.0.0.6 --metadata key1=v1 key2=v2", version="2.45") self.assert_called("POST", "/shares/2222/action", body=expected) def test_set_access_metadata(self): expected = { "metadata": { "key1": "v1", "key2": "v2", } } self.run_command( "access-metadata 9999 set key1=v1 key2=v2", version="2.45") self.assert_called("PUT", "/share-access-rules/9999/metadata", body=expected) def test_unset_access_metadata(self): self.run_command( "access-metadata 9999 unset key1", version="2.45") self.assert_called("DELETE", "/share-access-rules/9999/metadata/key1") @ddt.data("1.0", "2.0", "2.44") def test_allow_access_with_metadata_not_support_version(self, version): self.assertRaises( exceptions.CommandError, self.run_command, "access-allow 2222 ip 10.0.0.6 --metadata key1=v1", version=version, ) @mock.patch.object(cliutils, 'print_list', mock.Mock()) @ddt.data(*set(["2.44", "2.45", api_versions.MAX_VERSION])) def test_access_list(self, version): self.run_command("access-list 1111", version=version) version = api_versions.APIVersion(version) cliutils.print_list.assert_called_with( mock.ANY, ['id', 'access_type', 'access_to', 'access_level', 'state', 'access_key', 'created_at', 'updated_at']) @mock.patch.object(cliutils, 'print_list', mock.Mock()) @ddt.data(*set(["2.44", "2.45", api_versions.MAX_VERSION])) def test_access_list_select_column(self, version): self.run_command("access-list 1111 --columns id,access_type", version=version) cliutils.print_list.assert_called_with( mock.ANY, ['Id', 'Access_Type']) @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_snapshot_access_list(self): self.run_command("snapshot-access-list 1234") self.assert_called('GET', '/snapshots/1234/access-list') cliutils.print_list.assert_called_with( mock.ANY, ['id', 'access_type', 'access_to', 'state']) @mock.patch.object(cliutils, 'print_dict', mock.Mock()) def test_snapshot_access_allow(self): self.run_command("snapshot-access-allow 1234 ip 1.1.1.1") self.assert_called('POST', '/snapshots/1234/action') cliutils.print_dict.assert_called_with( {'access_type': 'ip', 'access_to': '1.1.1.1'}) def test_snapshot_access_deny(self): self.run_command("snapshot-access-deny 1234 fake_id") self.assert_called('POST', '/snapshots/1234/action') @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_snapshot_export_location_list(self): self.run_command('snapshot-export-location-list 1234') self.assert_called( 'GET', '/snapshots/1234/export-locations') @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_snapshot_instance_export_location_list(self): self.run_command('snapshot-instance-export-location-list 1234') self.assert_called( 'GET', '/snapshot-instances/1234/export-locations') @mock.patch.object(cliutils, 'print_dict', mock.Mock()) def test_snapshot_instance_export_location_show(self): self.run_command('snapshot-instance-export-location-show 1234 ' 'fake_el_id') self.assert_called( 'GET', '/snapshot-instances/1234/export-locations/fake_el_id') cliutils.print_dict.assert_called_once_with( {'path': '/fake_path', 'id': 'fake_id'}) @mock.patch.object(cliutils, 'print_dict', mock.Mock()) def test_snapshot_export_location_show(self): self.run_command('snapshot-export-location-show 1234 fake_el_id') self.assert_called('GET', '/snapshots/1234/export-locations/fake_el_id') cliutils.print_dict.assert_called_once_with( {'path': '/fake_path', 'id': 'fake_id'}) @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_security_service_list(self): self.run_command('security-service-list') self.assert_called( 'GET', '/security-services', ) cliutils.print_list.assert_called_once_with( mock.ANY, fields=['id', 'name', 'status', 'type']) @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_security_service_list_select_column(self): self.run_command('security-service-list --columns name,type') self.assert_called( 'GET', '/security-services', ) cliutils.print_list.assert_called_once_with( mock.ANY, fields=['Name', 'Type']) @mock.patch.object(cliutils, 'print_list', mock.Mock()) @mock.patch.object(shell_v2, '_find_share_network', mock.Mock()) def test_security_service_list_filter_share_network(self): class FakeShareNetwork(object): id = 'fake-sn-id' sn = FakeShareNetwork() shell_v2._find_share_network.return_value = sn for command in ['--share-network', '--share_network']: self.run_command('security-service-list %(command)s %(sn_id)s' % {'command': command, 'sn_id': sn.id}) self.assert_called( 'GET', '/security-services?share_network_id=%s' % sn.id, ) shell_v2._find_share_network.assert_called_with(mock.ANY, sn.id) cliutils.print_list.assert_called_with( mock.ANY, fields=['id', 'name', 'status', 'type']) @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_security_service_list_detailed(self): self.run_command('security-service-list --detailed') self.assert_called( 'GET', '/security-services/detail', ) cliutils.print_list.assert_called_once_with( mock.ANY, fields=['id', 'name', 'status', 'type', 'share_networks']) @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_security_service_list_all_tenants(self): self.run_command('security-service-list --all-tenants') self.assert_called( 'GET', '/security-services?all_tenants=1', ) cliutils.print_list.assert_called_once_with( mock.ANY, fields=['id', 'name', 'status', 'type']) @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_security_service_list_all_filters(self): filters = { 'status': 'new', 'name': 'fake-name', 'type': 'ldap', 'user': 'fake-user', 'dns-ip': '1.1.1.1', 'ou': 'fake-ou', 'server': 'fake-server', 'domain': 'fake-domain', 'offset': 10, 'limit': 20, } command_str = 'security-service-list' for key, value in filters.items(): command_str += ' --%(key)s=%(value)s' % {'key': key, 'value': value} self.run_command(command_str) self.assert_called( 'GET', '/security-services?dns_ip=1.1.1.1&domain=fake-domain&limit=20' '&name=fake-name&offset=10&ou=fake-ou&server=fake-server' '&status=new&type=ldap&user=fake-user', ) cliutils.print_list.assert_called_once_with( mock.ANY, fields=['id', 'name', 'status', 'type']) @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_security_service_list_filter_by_dns_ip_alias(self): self.run_command('security-service-list --dns_ip 1.1.1.1') self.assert_called( 'GET', '/security-services?dns_ip=1.1.1.1', ) cliutils.print_list.assert_called_once_with( mock.ANY, fields=['id', 'name', 'status', 'type']) @mock.patch.object(cliutils, 'print_list', mock.Mock()) def test_security_service_list_filter_by_ou_alias(self): self.run_command('security-service-list --ou fake-ou') self.assert_called( 'GET', '/security-services?ou=fake-ou', ) cliutils.print_list.assert_called_once_with( mock.ANY, fields=['id', 'name', 'status', 'type']) @ddt.data( {'--name': 'fake_name'}, {'--description': 'fake_description'}, {'--dns-ip': 'fake_dns_ip'}, {'--ou': 'fake_ou'}, {'--domain': 'fake_domain'}, {'--server': 'fake_server'}, {'--user': 'fake_user'}, {'--password': '<PASSWORD>'}, {'--name': 'fake_name', '--description': 'fake_description', '--dns-ip': 'fake_dns_ip', '--ou': 'fake_ou', '--domain': 'fake_domain', '--server': 'fake_server', '--user': 'fake_user', '--password': '<PASSWORD>'}, {'--name': '""'}, {'--description': '""'}, {'--dns-ip': '""'}, {'--ou': '""'}, {'--domain': '""'}, {'--server': '""'}, {'--user': '""'}, {'--password': '""'}, {'--name': '""', '--description': '""', '--dns-ip': '""', '--ou': '""', '--domain': '""', '--server': '""', '--user': '""', '--password': '""'},) def test_security_service_update(self, data): cmd = 'security-service-update 1111' expected = dict() for k, v in data.items(): cmd += ' ' + k + ' ' + v expected[k[2:].replace('-',
""" Module with function for running in parallel and doing cleanups after runs etc. BE AWARE: This module is not completely safe for use on multiple computers with shared file system. In particular, it's not safe to start init or cleanup at the same time as anything else. @author = Joel """ import numpy as np import warnings import shutil import os from os.path import join, isfile, isdir from multiprocessing import Pool from time import perf_counter, sleep from datetime import datetime from uuid import getnode as get_mac from pathlib import Path from core import data from constants import ROOT_DIR max_num_workers = os.cpu_count() base_dir = join(ROOT_DIR, 'data_ignore') mac = get_mac() class Wrap: """ Class for wrapping simulate (need pickable object for multiprocess Pool) """ def __init__(self, simulate, debug=False): self.simulate = simulate self.debug = debug def __call__(self, x): # Use a broad try-except to not crash if we don't have to try: return x[0], self.simulate(*x[0], *x[1]) except Exception as e: # This will be saved in the metadata file. if self.debug: raise e return x[0], e class Bookkeeper: """ Class for keeping track of what's been done and only assign new tasks. """ def __init__(self, iterator, book, output_calc=None, bounds=None): """ :param iterator: Iterable :param set book: Set of identifiers corresponding to previously completed tasks. :param output_calc: List of functions :param bounds: Bounds of elements to return from iterator """ if output_calc is None: output_calc = {} if bounds is None: bounds = [0, np.inf] self.iterator = iterator self.book = book self.output_calc = output_calc self.bounds = bounds self.count = -1 # to start from 0 (see += 1 below) def __iter__(self): return self def __next__(self): while True: x = self.iterator.__next__() self.count += 1 if self.count >= self.bounds[1]: raise StopIteration if x not in self.book and self.count >= self.bounds[0]: output = [] for i in range(len(x) + 1): if i in self.output_calc: output.extend(self.output_calc[i]( *[y for j, y in enumerate(x) if j < i])) return x, output def script_input(args): """ Parse script inputs to parallel.run :param args: Input sys.argv :return: kwargs to parallel.run """ # Handle cleanup and init if len(args) == 2 and args[1] in ['init', 'cleanup', 'debug']: print(f'\nStarting {args[1]}.\n') return {args[1]: True} # Input number of workers if len(args) <= 1: num_workers = max_num_workers else: try: num_workers = int(args[1]) except ValueError: num_workers = max_num_workers warnings.warn(f'Could not parse input parameter 1 num_workers.') # Input start of range if len(args) <= 2: start_range = 0 else: try: start_range = int(args[2]) except ValueError: start_range = 0 warnings.warn(f'Could not parse input parameter 2 start_range.') # Input end of range if len(args) <= 3: stop_range = np.inf else: try: stop_range = int(args[3]) except ValueError: stop_range = np.inf warnings.warn(f'Could not parse input parameter 3 stop_range.') print(f'\nStarting simulation with num_workers = {num_workers}, and range =' f' [{start_range}, {stop_range})\n') return {'num_workers': num_workers, 'start_range': start_range, 'stop_range': stop_range} def run(simulate, identifier_generator, input_functions, directory, version, script_file, file_from_id, metadata_from_id, num_workers=max_num_workers, start_range=0, stop_range=np.inf, max_task=1, chunksize=1, restart=True, delay=5, init=False, cleanup=False, debug=False): """ Run simulations, metadata initialization or cleanup. # TODO: param doc :param simulate: :param identifier_generator: :param input_functions: :param directory: :param version: :param script_file: :param file_from_id: :param metadata_from_id: :param num_workers: :param start_range: :param stop_range: :param max_task: :param chunksize: :param restart: :param delay: :param init: :param cleanup: :param debug: :return: """ directory = join(directory, f'v{version}') task = 'run'*(not init and not cleanup) \ + 'cleanup'*(not init and cleanup) \ + 'init'*init _mark_running(directory, task) try: if init: if _is_running(directory, ('run', 'cleanup', 'init')): raise RuntimeError("Can't run init when anyone else is " "running.") _init_metadata(identifier_generator(), directory, script_file) elif cleanup: if _is_running(directory, ('run', 'cleanup', 'init')): raise RuntimeError("Can't run cleanup when anyone else is " "running.") _cleanup_big(identifier_generator(), directory, script_file) else: if _is_running(directory, ('cleanup', 'init')): raise RuntimeError("Can't run simulation when someone else is " "initializing metadata or cleaning up.") while restart and _run_internal( simulate, identifier_generator(), input_functions, directory, script_file, file_from_id, metadata_from_id, num_workers, start_range, stop_range, max_task, chunksize, debug ): print(f'\nRestarting in {delay} s.\n') sleep(delay) finally: _mark_not_running(directory, task) def _run_internal(simulate, identifier_generator, input_functions, directory, script_file, file_from_id, metadata_from_id, num_workers, start_range, stop_range, max_task, chunksize, debug): """ Internal parallel run. :return: number of remaining tasks. """ # Files and paths directory_nomac = directory directory = join(directory, str(mac)) path_metadata = join(directory, 'metadata') try: # Try to load the file (will raise FileNotFoundError if not existing) metadata, metametadata = data.load(path_metadata, base_dir=base_dir) except FileNotFoundError: metadata = _get_metadata(directory_nomac)[0] metametadata = { 'description': "File that keeps track of what's been done " "previously in this script " f"({script_file}).", 'run_time': [], 'num_workers': [], 'num_tasks_completed': [], 'success_rate': [], 'created_from': script_file} data.save(file=path_metadata, data=metadata, metadata=metametadata, extract=True, base_dir=base_dir) # Extract identifiers to previously completed simulations ids = set() for id_, value in metadata: if value is True: if id_ in ids: raise KeyError('Multiple entries for same id in metadata.') ids.add(id_) # Cleanup (metadata can contain thousands of Exception objects) del metadata, metametadata # Wrap simulate to get expected input/output and handle exceptions wrap = Wrap(simulate, debug=debug) # Generator for pool generator = Bookkeeper(identifier_generator, ids, input_functions, [start_range, stop_range]) # Counters and such files = set() success = 0 fail = 0 start_time = perf_counter() # Actual run try: with Pool(num_workers, maxtasksperchild=max_task) as p: result_generator = p.imap_unordered(wrap, generator, chunksize=chunksize) for identifier, result in result_generator: # Handle exceptions: if isinstance(result, Exception): fail += 1 # Save the error data.append(path_metadata, [identifier, result], base_dir=base_dir) else: success += 1 file = file_from_id(identifier) if file not in files: files.add(file) if not isfile(join(base_dir, directory, file + '.pkl')): # Create file metadata = metadata_from_id(identifier) data.save(join(directory, file), [], metadata, extract=True, base_dir=base_dir) data.append(join(directory, file), [identifier, result], base_dir=base_dir) # Mark the task as completed (last in the else, # after saving result) data.append(path_metadata, [identifier, True], base_dir=base_dir) except Exception as e: if debug: raise e finally: stop_time = perf_counter() total = success + fail if total == 0: total = 1 # To avoid division by zero # Post simulation. metadata, metametadata = data.load(path_metadata, base_dir=base_dir) metadata = _cleanup_small(metadata) metametadata['run_time'].append(stop_time - start_time) metametadata['num_workers'].append((num_workers, max_num_workers)) metametadata['num_tasks_completed'].append(success) metametadata['success_rate'].append(success / total) data.save(file=path_metadata, data=metadata, metadata=metametadata, extract=True, base_dir=base_dir) # Print some stats print('\nSimulation completed.') print(f'Total number of tasks this far: {len(metadata)}') print(f'Completed tasks this run: {success}') print(f'Success rate this run: {success / total}') remaining = len(metadata) - sum(x[1] for x in metadata if x[1] is True) print(f'Minimum number of tasks remaining for this run: {fail}') print(f'Total number of tasks remaining: {remaining}') # No success and no fail => no restart if not debug: return success + fail def _init_metadata(identifier_generator, directory, script_file, force=False): """ Initialize metadata. :param identifier_generator: id generator :param directory: directory :param script_file: name of script :param force: if False raise RuntimeError if metadata is already existing. :return: """ if not force and _get_metadata(directory, warn=False) != ([], {}): raise RuntimeError('Metadata has already been initialized.') start_time = perf_counter() # Try to load from data/directory metadata, metametadata = _get_metadata(directory, False, data.BASE_DIR) # Fix directory and path path_metadata = join(directory, 'total', 'metadata') if (metadata, metametadata) == ([], {}): # Initialize from scratch # Save metadata file metadata = [] metametadata = { 'description': "File that keeps track of what's been done " "previously in this script " f"({script_file}).", 'created_from': script_file} data.save(file=path_metadata, data=metadata, metadata=metametadata, extract=True, base_dir=base_dir) # Add identifiers count = 0 for identifier in identifier_generator: count += 1 if count % 1e4 == 0: print(f'{count} identifiers saved.') data.append(path_metadata, [identifier, False], base_dir=base_dir) else: print(f'Initializing metadata from {join(data.BASE_DIR, directory)}.') count = len(metadata) data.save(file=path_metadata, data=metadata, metadata=metametadata, extract=True, base_dir=base_dir) stop_time = perf_counter() print(f'\nMetadata initialization completed in' f'{stop_time - start_time: .1f} s with {count} identifiers.\n') def _cleanup_big(identifier_generator, directory, script_file): """ Cleanup directory by going trough all subdirectories, collect results and fix metadata. :param directory: Directory of cleanup. :return: """ # TODO: collect metadata regarding time, success rate, etc. from # mac-subdirs to total/metadata, save as dict with mac as key(?) start_time = perf_counter() # Get total/metadata metadata, metametadata = _get_metadata(directory, warn=False) if (metadata, metametadata) == ([], {}): _init_metadata(identifier_generator, directory, script_file) # Try again metadata, metametadata = _get_metadata(directory, warn=False) if (metadata, metametadata) == ([], {}): raise ValueError("_init_metadata doesn't work") # Convert metadata to dict meta_dict = {} for x in metadata: # Keep only the last
# Tests of the quasiisothermaldf module from __future__ import print_function, division import numpy #fiducial setup uses these from galpy.potential import MWPotential, vcirc, omegac, epifreq, verticalfreq from galpy.actionAngle import actionAngleAdiabatic, actionAngleStaeckel from galpy.df import quasiisothermaldf aAA= actionAngleAdiabatic(pot=MWPotential,c=True) aAS= actionAngleStaeckel(pot=MWPotential,c=True,delta=0.5) def test_pvRvT_adiabatic(): qdf= quasiisothermaldf(1./4.,0.2,0.1,1.,1., pot=MWPotential,aA=aAA,cutcounter=True) R,z= 0.8, 0.1 vRs= numpy.linspace(-1.,1.,21) vTs= numpy.linspace(0.,1.5,51) pvRvT= numpy.array([[qdf.pvRvT(vr,vt,R,z) for vt in vTs] for vr in vRs]) tvR= numpy.tile(vRs,(len(vTs),1)).T tvT= numpy.tile(vTs,(len(vRs),1)) mvR= numpy.sum(tvR*pvRvT)/numpy.sum(pvRvT) mvT= numpy.sum(tvT*pvRvT)/numpy.sum(pvRvT) svR= numpy.sqrt(numpy.sum(tvR**2.*pvRvT)/numpy.sum(pvRvT)-mvR**2.) svT= numpy.sqrt(numpy.sum(tvT**2.*pvRvT)/numpy.sum(pvRvT)-mvT**2.) svRvT= (numpy.sum(tvR*tvT*pvRvT)/numpy.sum(pvRvT)-mvR*mvT)/svR/svT assert numpy.fabs(mvR) < 0.01, 'mean vR calculated from pvRvT not equal to zero for adiabatic actions' assert numpy.fabs(mvT-qdf.meanvT(R,z)) < 0.01, 'mean vT calculated from pvRvT not equal to zero for adiabatic actions' assert numpy.fabs(numpy.log(svR)-0.5*numpy.log(qdf.sigmaR2(R,z))) < 0.01, 'sigma vR calculated from pvRvT not equal to that from sigmaR2 for adiabatic actions' assert numpy.fabs(numpy.log(svT)-0.5*numpy.log(qdf.sigmaT2(R,z))) < 0.01, 'sigma vT calculated from pvRvT not equal to that from sigmaT2 for adiabatic actions' assert numpy.fabs(svRvT) < 0.01, 'correlation between vR and vT calculated from pvRvT not equal to zero for adiabatic actions' return None def test_pvRvT_staeckel(): qdf= quasiisothermaldf(1./4.,0.2,0.1,1.,1., pot=MWPotential,aA=aAS,cutcounter=True) R,z= 0.8, 0.1 vRs= numpy.linspace(-1.,1.,21) vTs= numpy.linspace(0.,1.5,51) pvRvT= numpy.array([[qdf.pvRvT(vr,vt,R,z) for vt in vTs] for vr in vRs]) tvR= numpy.tile(vRs,(len(vTs),1)).T tvT= numpy.tile(vTs,(len(vRs),1)) mvR= numpy.sum(tvR*pvRvT)/numpy.sum(pvRvT) mvT= numpy.sum(tvT*pvRvT)/numpy.sum(pvRvT) svR= numpy.sqrt(numpy.sum(tvR**2.*pvRvT)/numpy.sum(pvRvT)-mvR**2.) svT= numpy.sqrt(numpy.sum(tvT**2.*pvRvT)/numpy.sum(pvRvT)-mvT**2.) svRvT= (numpy.sum(tvR*tvT*pvRvT)/numpy.sum(pvRvT)-mvR*mvT)/svR/svT assert numpy.fabs(mvR) < 0.01, 'mean vR calculated from pvRvT not equal to zero for staeckel actions' assert numpy.fabs(mvT-qdf.meanvT(R,z)) < 0.01, 'mean vT calculated from pvRvT not equal to zero for staeckel actions' assert numpy.fabs(numpy.log(svR)-0.5*numpy.log(qdf.sigmaR2(R,z))) < 0.01, 'sigma vR calculated from pvRvT not equal to that from sigmaR2 for staeckel actions' assert numpy.fabs(numpy.log(svT)-0.5*numpy.log(qdf.sigmaT2(R,z))) < 0.01, 'sigma vT calculated from pvRvT not equal to that from sigmaT2 for staeckel actions' assert numpy.fabs(svRvT) < 0.01, 'correlation between vR and vT calculated from pvRvT not equal to zero for staeckel actions' return None def test_pvRvT_staeckel_diffngl(): qdf= quasiisothermaldf(1./4.,0.2,0.1,1.,1., pot=MWPotential,aA=aAS,cutcounter=True) R,z= 0.8, 0.1 vRs= numpy.linspace(-1.,1.,21) vTs= numpy.linspace(0.,1.5,51) #ngl=10 pvRvT= numpy.array([[qdf.pvRvT(vr,vt,R,z,ngl=10) for vt in vTs] for vr in vRs]) tvR= numpy.tile(vRs,(len(vTs),1)).T tvT= numpy.tile(vTs,(len(vRs),1)) mvR= numpy.sum(tvR*pvRvT)/numpy.sum(pvRvT) mvT= numpy.sum(tvT*pvRvT)/numpy.sum(pvRvT) svR= numpy.sqrt(numpy.sum(tvR**2.*pvRvT)/numpy.sum(pvRvT)-mvR**2.) svT= numpy.sqrt(numpy.sum(tvT**2.*pvRvT)/numpy.sum(pvRvT)-mvT**2.) svRvT= (numpy.sum(tvR*tvT*pvRvT)/numpy.sum(pvRvT)-mvR*mvT)/svR/svT assert numpy.fabs(mvR) < 0.01, 'mean vR calculated from pvRvT not equal to zero for staeckel actions' assert numpy.fabs(mvT-qdf.meanvT(R,z)) < 0.01, 'mean vT calculated from pvRvT not equal to zero for staeckel actions' assert numpy.fabs(numpy.log(svR)-0.5*numpy.log(qdf.sigmaR2(R,z))) < 0.01, 'sigma vR calculated from pvRvT not equal to that from sigmaR2 for staeckel actions' assert numpy.fabs(numpy.log(svT)-0.5*numpy.log(qdf.sigmaT2(R,z))) < 0.01, 'sigma vT calculated from pvRvT not equal to that from sigmaT2 for staeckel actions' assert numpy.fabs(svRvT) < 0.01, 'correlation between vR and vT calculated from pvRvT not equal to zero for staeckel actions' #ngl=24 pvRvT= numpy.array([[qdf.pvRvT(vr,vt,R,z,ngl=40) for vt in vTs] for vr in vRs]) mvR= numpy.sum(tvR*pvRvT)/numpy.sum(pvRvT) mvT= numpy.sum(tvT*pvRvT)/numpy.sum(pvRvT) svR= numpy.sqrt(numpy.sum(tvR**2.*pvRvT)/numpy.sum(pvRvT)-mvR**2.) svT= numpy.sqrt(numpy.sum(tvT**2.*pvRvT)/numpy.sum(pvRvT)-mvT**2.) svRvT= (numpy.sum(tvR*tvT*pvRvT)/numpy.sum(pvRvT)-mvR*mvT)/svR/svT assert numpy.fabs(mvR) < 0.01, 'mean vR calculated from pvRvT not equal to zero for staeckel actions' assert numpy.fabs(mvT-qdf.meanvT(R,z)) < 0.01, 'mean vT calculated from pvRvT not equal to zero for staeckel actions' assert numpy.fabs(numpy.log(svR)-0.5*numpy.log(qdf.sigmaR2(R,z))) < 0.01, 'sigma vR calculated from pvRvT not equal to that from sigmaR2 for staeckel actions' assert numpy.fabs(numpy.log(svT)-0.5*numpy.log(qdf.sigmaT2(R,z))) < 0.01, 'sigma vT calculated from pvRvT not equal to that from sigmaT2 for staeckel actions' assert numpy.fabs(svRvT) < 0.01, 'correlation between vR and vT calculated from pvRvT not equal to zero for staeckel actions' #ngl=11, shouldn't work try: pvRvT= numpy.array([[qdf.pvRvT(vr,vt,R,z,ngl=11) for vt in vTs] for vr in vRs]) except ValueError: pass else: raise AssertionError('pvz w/ ngl=odd did not raise ValueError') return None def test_pvTvz_adiabatic(): qdf= quasiisothermaldf(1./4.,0.2,0.1,1.,1., pot=MWPotential,aA=aAA,cutcounter=True) R,z= 0.8, 0.1 vTs= numpy.linspace(0.,1.5,51) vzs= numpy.linspace(-1.,1.,21) pvTvz= numpy.array([[qdf.pvTvz(vt,vz,R,z) for vt in vTs] for vz in vzs]) tvT= numpy.tile(vTs,(len(vzs),1)) tvz= numpy.tile(vzs,(len(vTs),1)).T mvz= numpy.sum(tvz*pvTvz)/numpy.sum(pvTvz) mvT= numpy.sum(tvT*pvTvz)/numpy.sum(pvTvz) svz= numpy.sqrt(numpy.sum(tvz**2.*pvTvz)/numpy.sum(pvTvz)-mvz**2.) svT= numpy.sqrt(numpy.sum(tvT**2.*pvTvz)/numpy.sum(pvTvz)-mvT**2.) svTvz= (numpy.sum(tvz*tvT*pvTvz)/numpy.sum(pvTvz)-mvz*mvT)/svz/svT assert numpy.fabs(mvz) < 0.01, 'mean vz calculated from pvTvz not equal to zero for adiabatic actions' assert numpy.fabs(mvT-qdf.meanvT(R,z)) < 0.01, 'mean vT calculated from pvTvz not equal to zero for adiabatic actions' assert numpy.fabs(numpy.log(svz)-0.5*numpy.log(qdf.sigmaz2(R,z))) < 0.01, 'sigma vz calculated from pvTvz not equal to that from sigmaz2 for adiabatic actions' assert numpy.fabs(numpy.log(svT)-0.5*numpy.log(qdf.sigmaT2(R,z))) < 0.01, 'sigma vT calculated from pvTvz not equal to that from sigmaT2 for adiabatic actions' assert numpy.fabs(svTvz) < 0.01, 'correlation between vz and vT calculated from pvTvz not equal to zero for adiabatic actions' return None def test_pvTvz_staeckel(): qdf= quasiisothermaldf(1./4.,0.2,0.1,1.,1., pot=MWPotential,aA=aAS,cutcounter=True) R,z= 0.8, 0.1 vzs= numpy.linspace(-1.,1.,21) vTs= numpy.linspace(0.,1.5,51) pvTvz= numpy.array([[qdf.pvTvz(vt,vz,R,z) for vt in vTs] for vz in vzs]) tvz= numpy.tile(vzs,(len(vTs),1)).T tvT= numpy.tile(vTs,(len(vzs),1)) mvz= numpy.sum(tvz*pvTvz)/numpy.sum(pvTvz) mvT= numpy.sum(tvT*pvTvz)/numpy.sum(pvTvz) svz= numpy.sqrt(numpy.sum(tvz**2.*pvTvz)/numpy.sum(pvTvz)-mvz**2.) svT= numpy.sqrt(numpy.sum(tvT**2.*pvTvz)/numpy.sum(pvTvz)-mvT**2.) svTvz= (numpy.sum(tvz*tvT*pvTvz)/numpy.sum(pvTvz)-mvz*mvT)/svz/svT assert numpy.fabs(mvz) < 0.01, 'mean vz calculated from pvTvz not equal to zero for staeckel actions' assert numpy.fabs(mvT-qdf.meanvT(R,z)) < 0.01, 'mean vT calculated from pvTvz not equal to zero for staeckel actions' assert numpy.fabs(numpy.log(svz)-0.5*numpy.log(qdf.sigmaz2(R,z))) < 0.01, 'sigma vz calculated from pvTvz not equal to that from sigmaz2 for staeckel actions' assert numpy.fabs(numpy.log(svT)-0.5*numpy.log(qdf.sigmaT2(R,z))) < 0.01, 'sigma vT calculated from pvTvz not equal to that from sigmaT2 for staeckel actions' assert numpy.fabs(svTvz) < 0.01, 'correlation between vz and vT calculated from pvTvz not equal to zero for staeckel actions' return None def test_pvTvz_staeckel_diffngl(): qdf= quasiisothermaldf(1./4.,0.2,0.1,1.,1., pot=MWPotential,aA=aAS,cutcounter=True) R,z= 0.8, 0.1 vzs= numpy.linspace(-1.,1.,21) vTs= numpy.linspace(0.,1.5,51) #ngl=10 pvTvz= numpy.array([[qdf.pvTvz(vt,vz,R,z,ngl=10) for vt in vTs] for vz in vzs]) tvz= numpy.tile(vzs,(len(vTs),1)).T tvT= numpy.tile(vTs,(len(vzs),1)) mvz= numpy.sum(tvz*pvTvz)/numpy.sum(pvTvz) mvT= numpy.sum(tvT*pvTvz)/numpy.sum(pvTvz) svz= numpy.sqrt(numpy.sum(tvz**2.*pvTvz)/numpy.sum(pvTvz)-mvz**2.) svT= numpy.sqrt(numpy.sum(tvT**2.*pvTvz)/numpy.sum(pvTvz)-mvT**2.) svTvz= (numpy.sum(tvz*tvT*pvTvz)/numpy.sum(pvTvz)-mvz*mvT)/svz/svT assert numpy.fabs(mvz) < 0.01, 'mean vz calculated from pvTvz not equal to zero for staeckel actions' assert numpy.fabs(mvT-qdf.meanvT(R,z)) < 0.01, 'mean vT calculated from pvTvz not equal to zero for staeckel actions' assert numpy.fabs(numpy.log(svz)-0.5*numpy.log(qdf.sigmaz2(R,z))) < 0.01, 'sigma vz calculated from pvTvz not equal to that from sigmaz2 for staeckel actions' assert numpy.fabs(numpy.log(svT)-0.5*numpy.log(qdf.sigmaT2(R,z))) < 0.01, 'sigma vT calculated from pvTvz not equal to that from sigmaT2 for staeckel actions' assert numpy.fabs(svTvz) < 0.01, 'correlation between vz and vT calculated from pvTvz not equal to zero for staeckel actions' #ngl=24 pvTvz= numpy.array([[qdf.pvTvz(vt,vz,R,z,ngl=40) for vt in vTs] for vz in vzs]) mvz= numpy.sum(tvz*pvTvz)/numpy.sum(pvTvz) mvT= numpy.sum(tvT*pvTvz)/numpy.sum(pvTvz) svz= numpy.sqrt(numpy.sum(tvz**2.*pvTvz)/numpy.sum(pvTvz)-mvz**2.) svT= numpy.sqrt(numpy.sum(tvT**2.*pvTvz)/numpy.sum(pvTvz)-mvT**2.) svTvz= (numpy.sum(tvz*tvT*pvTvz)/numpy.sum(pvTvz)-mvz*mvT)/svz/svT assert numpy.fabs(mvz) < 0.01, 'mean vz calculated from pvTvz not equal to zero for staeckel actions' assert numpy.fabs(mvT-qdf.meanvT(R,z)) < 0.01, 'mean vT calculated from pvTvz not equal to zero for staeckel actions' assert numpy.fabs(numpy.log(svz)-0.5*numpy.log(qdf.sigmaz2(R,z))) < 0.01, 'sigma vz calculated from pvTvz not equal to that from sigmaz2 for staeckel actions' assert numpy.fabs(numpy.log(svT)-0.5*numpy.log(qdf.sigmaT2(R,z))) < 0.01, 'sigma vT calculated from pvTvz not equal to that from sigmaT2 for staeckel actions' assert numpy.fabs(svTvz) < 0.01, 'correlation between vz and vT calculated from pvTvz not equal to zero for staeckel actions' #ngl=11, shouldn't work try: pvTvz= numpy.array([[qdf.pvTvz(vt,vz,R,z,ngl=11) for vt in vTs] for vz in vzs]) except ValueError: pass else: raise AssertionError('pvz w/ ngl=odd did not raise ValueError') return None def test_pvRvz_adiabatic(): qdf= quasiisothermaldf(1./4.,0.2,0.1,1.,1., pot=MWPotential,aA=aAA,cutcounter=True) R,z= 0.8, 0.1 vRs= numpy.linspace(-1.,1.,21) vzs= numpy.linspace(-1.,1.,21) pvRvz= numpy.array([[qdf.pvRvz(vr,vz,R,z) for vz in vzs] for vr in vRs]) tvR= numpy.tile(vRs,(len(vzs),1)).T tvz= numpy.tile(vzs,(len(vRs),1)) mvR= numpy.sum(tvR*pvRvz)/numpy.sum(pvRvz) mvz= numpy.sum(tvz*pvRvz)/numpy.sum(pvRvz) svR= numpy.sqrt(numpy.sum(tvR**2.*pvRvz)/numpy.sum(pvRvz)-mvR**2.) svz= numpy.sqrt(numpy.sum(tvz**2.*pvRvz)/numpy.sum(pvRvz)-mvz**2.) svRvz= (numpy.sum(tvR*tvz*pvRvz)/numpy.sum(pvRvz)-mvR*mvz)/svR/svz sR2= qdf.sigmaR2(R,z) #direct calculation sz2= qdf.sigmaz2(R,z) assert numpy.fabs(mvR) < 0.01, 'mean vR calculated from pvRvz not equal to zero for adiabatic actions' assert numpy.fabs(mvz) < 0.01, 'mean vz calculated from pvRvz not equal to zero for adiabatic actions' assert numpy.fabs(numpy.log(svR)-0.5*numpy.log(sR2)) < 0.01, 'sigma vR calculated from pvRvz not equal to that from sigmaR2 for adiabatic actions' assert numpy.fabs(numpy.log(svz)-0.5*numpy.log(sz2)) < 0.01, 'sigma vz calculated from pvRvz not equal to that from sigmaz2 for adiabatic actions' assert numpy.fabs(svRvz-qdf.sigmaRz(R,z)/numpy.sqrt(sR2*sz2)) < 0.01, 'correlation between vR and vz calculated from pvRvz not equal to zero for adiabatic actions' return None def test_pvRvz_staeckel(): qdf= quasiisothermaldf(1./4.,0.2,0.1,1.,1., pot=MWPotential,aA=aAS,cutcounter=True) R,z= 0.8, 0.1 vRs= numpy.linspace(-1.,1.,21) vzs= numpy.linspace(-1.,1.,21) pvRvz= numpy.array([[qdf.pvRvz(vr,vz,R,z) for vz in vzs] for vr in vRs]) tvR= numpy.tile(vRs,(len(vzs),1)).T tvz= numpy.tile(vzs,(len(vRs),1)) mvR= numpy.sum(tvR*pvRvz)/numpy.sum(pvRvz) mvz= numpy.sum(tvz*pvRvz)/numpy.sum(pvRvz) svR= numpy.sqrt(numpy.sum(tvR**2.*pvRvz)/numpy.sum(pvRvz)-mvR**2.) svz= numpy.sqrt(numpy.sum(tvz**2.*pvRvz)/numpy.sum(pvRvz)-mvz**2.) svRvz= (numpy.sum(tvR*tvz*pvRvz)/numpy.sum(pvRvz)-mvR*mvz)/svR/svz sR2= qdf.sigmaR2(R,z) #direct calculation sz2= qdf.sigmaz2(R,z) assert numpy.fabs(mvR) < 0.01, 'mean vR calculated from pvRvz not equal to zero for staeckel actions' assert numpy.fabs(mvz) < 0.01, 'mean vz calculated from pvRvz not equal to zero for staeckel actions' assert numpy.fabs(numpy.log(svR)-0.5*numpy.log(sR2)) < 0.01, 'sigma vR calculated from pvRvz not equal to that from sigmaR2 for staeckel actions' assert numpy.fabs(numpy.log(svz)-0.5*numpy.log(sz2)) < 0.01, 'sigma vz calculated from pvRvz not equal to that from sigmaz2
<reponame>jpazdera/PazdKaha22<filename>Experiment/ltpFR3_MTurk/ListGen/ltpFR3_listgen.py<gh_stars>0 #!/usr/bin/env python2 import random import itertools import numpy import sys import json import copy def make_bins_ltpFR3(semArray): """ Creates four equal-width bins of WAS scores, identical to those used in ltpFR2. Then combine the middle two to give three bins: low similarity, medium similarity, and high similarity. A coordinate in semRows[i][j] and semCols[i][j] is the index of the jth word pair in semArray that falls in the ith similarity bin. """ semArray_nondiag = semArray[numpy.where(semArray != 1)] # Find lowest and highest similarity min_sim = semArray_nondiag.min() max_sim = semArray_nondiag.max() # Split up the semantic space into four equal segments semBins = list(numpy.linspace(min_sim, max_sim, 4)) # Combine the two middle bins by removing the bin boundary between them # semBins = semBins[:2] + semBins[3:] # Create bounds for the bins semBins = zip(*[semBins[i:] + semBins[-1:i] for i in range(2)]) # For word pairs within the bounds of each bin, append the indices to semRows and semCols semRows = [] semCols = [] for bin in semBins: (i, j) = ((semArray > bin[0]) & (semArray < bin[1])).nonzero() semRows.append(i) semCols.append(j) return semRows, semCols def randomize_conditions_ltpFR3(config): """ Randomize the conditions for all sessions. :param config: The imported configuration file, containing all parameters for the experiment :return: A list of lists, where sublist n contains the ordering of list conditions for the nth session. cond[x][y][0] defines the length of session x, list y; cond[x][y][1] defines the presentation rate of session x, list y; cond[x][y][2] defines whether session x, list y uses visual or auditory presentation; cond[x][y][3] defines the duration of the pre-list distractor task for session x, list y. """ options = [c for c in itertools.product(config.listLength, config.presRate, config.modality, config.distDur)] cond = [] for i in range(config.nSessions): sess = [] for j in range(config.reps): random.shuffle(options) sess += options[:] cond.append(sess) return cond def choose_pairs_ltpFR3(wp_tot, cond, config, semRows, semCols): """ Selects word pairs to use in each list of each session. :param wp_tot: A list containing all the words of the word pool. The order of the words is expected to correspond to the indices used by semRows and semCols. :param cond: A list of lists, where sublist n contains the ordering of list conditions for the nth session. :param config: The imported configuration file, containing all parameters for the experiment. :param semRows: See make_bins_ltpFR3() :param semCols: See make_bins_ltpFR3() :return: pairs - pairs[x][y][z] is the zth word pair in session x, list y :return: pair_dicts - a list of dictionaries, where each dictionary contains all word pairs from a given session :return: practice_lists - A list containing two practice lists, each with 18 words """ # pairs[x][y][z] will be the zth pair of words in the yth list on session x pairs = [] # points to the other word in the pair for a given session pair_dicts = [] # Deep copy the full word pool into full_wp_allowed, so it can be shuffled for each session without altering wp_tot full_wp = wp_tot[:] # Make word pairs for each session session_num = 0 while session_num < config.nSessions: #print 'Making session', session_num, ':', #sys.stdout.flush() # Shuffle the order of the word pool; I believe this is technically only necessary for the first session, in # order to randomize which words are selected for the practice lists. All other lists have their items randomly # chosen anyway ''' IMPORTANT NOTE!!!: Lists containing more than 2080 elements should not be randomized with shuffle, as explained here: http://stackoverflow.com/questions/3062741/maximal-length-of-list-to-shuffle-with-python-random-shuffle The full word pool contains 1638 words, so this is only a concern if the word pool is ever expanded. ''' random.shuffle(full_wp) # The first session has two 18-word practice lists if session_num == 0: practice_lists = [full_wp[:18], full_wp[18:36]] sess_wp_allowed = full_wp[36:] else: sess_wp_allowed = full_wp[:] # sess_pairs[x][y] will be the yth pair in the xth list on the current session sess_pairs = [] # Track number of attempts to create the lists for the current session sess_tries = 0 # Track whether the session completed successfully goodSess = True # Make word pairs for each list in the current session list_num = 0 while list_num < len(cond[session_num]): #print list_num, #sys.stdout.flush() # list_pairs[x] will be the xth pair in the current list on the current session list_pairs = [] # Track number of attempts to create the current list list_tries = 0 # Track whether the list completed successfully goodList = True # Retrieve the list length condition for the current list by looking in cond listLength = cond[session_num][list_num][0] # Length 12 lists have 2 pairs per bin, length 24 list have 4 pairs per bin pairs_per_bin = 2 if listLength == 12 else 4 # Select two or four word pairs from each bin (based on list length) for sem_i in range(len(semRows)): # The pair for each semantic bin gets placed twice pair_i = 0 while pair_i < pairs_per_bin: # Get the indices (within the full word pool) of the words chosen for the current session available_indices = [wp_tot.index(word) for word in sess_wp_allowed] # Randomly choose indices/words from those in the current session until one is found that has one # or more pairs in the current bin index_word1 = random.choice(available_indices) while index_word1 not in semRows[sem_i]: index_word1 = random.choice(available_indices) # Get the indices of all words whose pairing with the chosen word falls into the correct bin good_second_indices = semCols[sem_i][semRows[sem_i] == index_word1] # Eliminate the words that are not available in the session good_second_indices = [i for i in good_second_indices if wp_tot[i] in sess_wp_allowed] # Ensure that a word cannot be accidentally paired with itself if index_word1 in good_second_indices: del good_second_indices[good_second_indices.index(index_word1)] # If there are no good words to choose from, restart if len(good_second_indices) == 0: list_tries += 1 if list_tries > 10: goodList = False break else: continue # Choose the second word randomly index_word2 = random.choice(good_second_indices) # Add the pairs to list_pairs, delete them from the pool of allowed words list_pairs.append([wp_tot[index_word1], wp_tot[index_word2]]) del sess_wp_allowed[sess_wp_allowed.index(wp_tot[index_word1])] del sess_wp_allowed[sess_wp_allowed.index(wp_tot[index_word2])] pair_i += 1 # If the list is bad, add the words back to the pool of allowed words if not goodList: sess_wp_allowed.extend([x[0] for x in list_pairs] + [x[1] for x in list_pairs]) break # If the list is good, add the list_pairs to sess_pairs, if goodList: sess_pairs.append(list_pairs) list_num += 1 else: # Otherwise, try the session again (up to 50 times), then restart list_pairs = [] sess_tries += 1 if sess_tries > 50: goodSess = False break # If the whole session went successfully if goodSess: # Get the pairs from the lists, add them backwards and forwards to sess_pair_dict sess_pair_dict = dict(itertools.chain(*sess_pairs)) sess_pair_dict.update(dict(zip(sess_pair_dict.values(), sess_pair_dict.keys()))) pair_dicts.append(sess_pair_dict) pairs.append(sess_pairs) session_num += 1 else: # If the session did not go well, try again. sess_pairs = [] print '' return pairs, pair_dicts, practice_lists def place_pairs_ltpFR3(pairs, cond): """ :param pairs: :param cond: :param config: :return: """ # Load all valid list compositions for 12-item lists (small lists are too restrictive to use trial and error) with open('valid12.json', 'r') as f: valid12 = json.load(f)['3bin-valid12'] # Loop through sessions subj_wo = [] for (n, sess_pairs) in enumerate(pairs): sess_wo = [] #print '\nPlacing session', n, ':', #sys.stdout.flush() # Loop through lists within each session for (m, list_pairs) in enumerate(sess_pairs): #print m, #sys.stdout.flush() # Create pairs of word pairs from the same bin -- one pair will have adjacent presentation, one distant grouped_pairs = [list(group) for group in zip([list_pairs[i] for i in range(len(list_pairs)) if i % 2 == 0], [list_pairs[i] for i in range(len(list_pairs)) if i % 2 == 1])] # Retrieve list length for the current list list_length = cond[n][m][0] # For 12-item lists, select a random solution template and assign word pairs to the variables in the # template, such that one pair from each bin has adjacent presentation and one pair from each bin has # distant presentation if list_length == 12: # Randomize the ordering of the grouped pairs,
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2019/5/15 @Author : AnNing """ from __future__ import print_function import os import sys import numpy as np from initialize import load_yaml_file from load import ReadAhiL1 TEST = True def ndsi(in_file_l1, in_file_geo, in_file_cloud): # ------------------------------------------------------------------------- # SolarZenith_MAX : MAXIMUM SOLAR ZENITH ANGLE, *1.0 DEGREE # solar_zenith_max = None # ------------------------------------------------------------------------- # Date and Time # i_year = None # i_month = None # i_day = None # i_minute = None # n_year = None # n_month = None # n_day = None # n_hour = None # n_minute = None # n_second = None # ------------------------------------------------------------------------- # out data # r4_rt = np.array([]) # r4_info = np.array([]) # i2_cm = np.array([]) # r4_test = np.array([]) # ------------------------------------------------------------------------- # swath sum # i_swath_valid = None # i_sum_valid = None # ------------------------------------------------------------------------- # dim_x = None # dim_y = None # dim_z = None # ------------------------------------------------------------------------- # r_lats = None # LATITUDE # r_lons = None # LONGITUDE # a_satz = None # SATELLITE ZENITH ANGLE # a_sata = None # SATELLITE AZIMUTH # a_sunz = None # SOLAR ZENITH ANGLE # a_suna = None # SOLAR AZIMUTH # r_dems = None # DEM MASK # i_mask = None # LANDCOVER MASK # i_cm = None # Cloud MASK # ------------------------------------------------------------------------- # cossl = None # SOLAR-ZENITH-ANGLE-COSINE # glint = None # SUN GLINT # lsm = None # Mask For Water & Land # i_avalible = None # Mask For Data to be used # ------------------------------------------------------------------------- # ref_01 = None # 0.645 um : Ref, NDVI # ref_02 = None # 0.865 um : Ref, NDVI # ref_03 = None # 0.470 um : Ref, NDVI # ref_04 = None # 0.555 um : Ref, NDVI # ref_05 = None # 1.640 um : Ref, NDVI # ref_06 = None # 1.640 um : Ref, NDSI # ref_07 = None # 2.130 um : Ref, NDSI # ref_19 = None # 0.940 um : Ref, Vapour # ref_26 = None # 1.375 um : Ref, Cirrus # tbb_20 = None # 3.750 um : TBB, Temperature # tbb_31 = None # 11.030 um : TBB, Temperature # tbb_32 = None # 12.020 um : TBB, Temperature # ------------------------------------------------------------------------- # ndvis = None # R2-R1/R2+R1: R0.86,R0.65 # ndsi_6 = None # R4-R6/R4+R6: R0.55,R1.64 # ndsi_7 = None # R4-R7/R4+R7: R0.55,R2.13 # # dr_16 = None # R1-R6: R0.86,R1.64 # dr_17 = None # R1-0.5*R7: R0.86,R2.13 # # dt_01 = None # T20-T31: T3.75-T11.0 # dt_02 = None # T20-T32: T3.75-T12.0 # dt_12 = None # T31-T32: T11.0-T12.0 # # rr_21 = None # R2/R1: R0.86,R0.65 # rr_46 = None # R4/R6: R0.55,R1.64 # rr_47 = None # R4/R7: R0.55,R2.13 # # dt_34 = None # T20-T23: T3.75-T4.05 # dt_81 = None # T29-T31: T8.55-T11.0 # dt_38 = None # T20-T29: T3.75-T8.55 # ------------------------------------------------------------------------- # Used for Masking Over-Estimation for snow by monthly snow pack lines. # LookUpTable For Monthly CHN-SnowPackLine (ZhengZJ, 2006) # Line: Longitude from 65.0 to 145.0 (Step is 0.1 deg.) # Column: Month from Jan to Dec (Step is month) # Value: Latitude (Unit is deg.) # r_mon_snow_line = np.array([]) # Monthly CHN-SnowPackLine # Used for judging low or water cloud by BT difference. # LookUpTable For T11-T12 (Saunders and Kriebel, 1988) # Line: T11 from 250.0K to 310.0K (Step is 1.0K) # Column: Secant-SZA from 1.00 to 2.50 (Step is 0.01) # Value: T11-T12 (Unit is K) # delta_bt_lut = np.array([]) # LookUpTable for BT11-BT12 # Used for judging snow in forest by NDSI and NDVI. # LookUpTable For Snow in Forest , by NDVI-NDSI (Klein et al., 1998) # Line: NDVI from 0.010 to 1.000 (Step is 0.01) # Column: NDSI from 0.01000 to 1.00000 (Step is 0.00001) # Value: NDSI (Unit is null) # y_ndsi_x_ndvi = np.array([]) # LookUpTable for NDSI-NDVI # !!!!! Four Variables below should be USED TOGETHER. # !! R138R164LUT,R164T11_LUT,R164R138LUT,T11mT12R164LUT # !! LookUpTable For FreshSnow&WaterIceCloud (ZhengZJ, 2006) # !! (1)Line-R164T11_LUT: T11 from 225.0 to 280.0 (Step is 0.1K) # !! Column--R164T11_LUT: R164 from 0.00000 to 0.24000 (No Step) # !! (2)Line-T11mT12R164LUT: R164 from 0.100 to 0.250 (Step is 0.001) # !! Column-T11mT12R164LUT: T11mT12 from -40 to 130 (No Step) # !! (3)Line-R138R164LUT: R164 from 0.010 to 0.260 (Step is 0.001) # !! Column-R138R164LUT: R138 from 0.0020 to 0.3000 (No Step) # !! (4)Line-R164R138LUT: R138 from 0.000 to 0.550 (Step is 0.001) # !! Column-R164R138LUT: R164 from 0.1500 to 0.3000 (No Step) # y_r164_x_t11 = np.array([]) # LookUpTable For R164T11 # y_t11_m_t12_x_r164 = np.array([]) # LookUpTable For T11mT12R164 # y_r138_x_r164 = np.array([]) # LookUpTable For R138R164 # y_r164_x_r138 = np.array([]) # LookUpTable For R164R138 # ------------------------------------------------------------------------- # Used for Reference of 11um Minimum Brightness Temperature. # ref_bt11um = None # ref_bt11um_slope_n = None # ref_bt11um_slope_s = None # ref_bt11um_offset_n = None # ref_bt11um_offset_s = None # a_low_t_lat = None # Referential Latitude for BT11 LowThreshold # a_low_bt11 = None # Referential Temp for BT11 LowThreshold # delta_t_low = None # Referential Temporal Delta-Temp for BT11_Low # b_hai_t_lat = None # Referential Latitude for BT11 HaiThreshold # b_hai_bt11 = None # Referential Temp for BT11 HaiThreshold # delta_t_hai = None # Referential Temporal Delta-Temp for BT11_Hai # # a_low_bt11_n = None # a_low_bt11_s = None # b_hai_bt11_n = None # b_hai_bt11_s = None # ------------------------------------------------------------------------- # Used for Calculate and Store Xun number from 1 to 36 in a year. # f_xun_n = None # f_xun_s = None # i2_xun_num = None # ------------------------------------------------------------------------- # i_step = np.array([]) # TEST-STEP # i_mark = np.array([]) # SNOW MAP # !!!! VALUE = 255 : Fill Data--no Data expected For pixel # !!!! VALUE = 254 : Saturated MODIS sensor detector # !!!! VALUE = 240 : NATIONAL OR PROVINCIAL BOUNDARIES # !!!! VALUE = 200 : Snow # !!!! VALUE = 100 : Snow-Covered Lake Ice # !!!! VALUE = 50 : Cloud Obscured # !!!! VALUE = 39 : Ocean # !!!! VALUE = 37 : Inland Water # !!!! VALUE = 25 : Land--no snow detected # !!!! VALUE = 11 : Darkness, terminator or polar # !!!! VALUE = 1 : No Decision # !!!! VALUE = 0 : Sensor Data Missing # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- print('Program : Make SNC') # ------------------------------------------------------------------------- path = os.path.abspath(os.path.dirname(__file__)) name_list_swath_snc = os.path.join(path, 'ndsi_cfg.yaml') print('Config file : {}'.format(name_list_swath_snc)) a = load_yaml_file(name_list_swath_snc) solar_zenith_max = float(a['SolarZenith_MAX']) inn_put_para_path = a['InnPut_ParaPath'] inn_put_root_l01 = a['InnPut_Root_L01'] inn_put_root_l02 = a['InnPut_Root_L02'] inn_put_root_l03 = a['InnPut_Root_L03'] # inn_put_root_l11 = a['InnPut_Root_L11'] # inn_put_root_l12 = a['InnPut_Root_L12'] # inn_put_root_l13 = a['InnPut_Root_L13'] # inn_put_root_l14 = a['InnPut_Root_L14'] inn_put_file_l01 = os.path.join(path, inn_put_para_path, inn_put_root_l01) inn_put_file_l02 = os.path.join(path, inn_put_para_path, inn_put_root_l02) inn_put_file_l03 = os.path.join(path, inn_put_para_path, inn_put_root_l03) # inn_put_file_l11 = os.path.join(path, inn_put_para_path, inn_put_root_l11) # inn_put_file_l12 = os.path.join(path, inn_put_para_path, inn_put_root_l12) # inn_put_file_l13 = os.path.join(path, inn_put_para_path, inn_put_root_l13) # inn_put_file_l14 = os.path.join(path, inn_put_para_path, inn_put_root_l14) delta_bt_lut = np.loadtxt(inn_put_file_l01, skiprows=1)[:, 1:] r_mon_snow_line_temp = np.loadtxt(inn_put_file_l02, skiprows=1)[:, 1:] r_mon_snow_line = np.zeros((3601, 12, 2)) r_mon_snow_line[:, :, 0] = r_mon_snow_line_temp[:, 0:24:2] r_mon_snow_line[:, :, 1] = r_mon_snow_line_temp[:, 1:24:2] y_ndsi_x_ndvi = np.loadtxt(inn_put_file_l03, skiprows=1)[:] # y_r138_x_r164 = np.loadtxt(inn_put_file_l11, skiprows=1)[:] # y_r164_x_t11 = np.loadtxt(inn_put_file_l12, skiprows=1)[:] # y_r164_x_r138 = np.loadtxt(inn_put_file_l13, skiprows=1)[:] # y_t11_m_t12_x_r164 = np.loadtxt(inn_put_file_l14, skiprows=1)[:] # ------------------------------------------------------------------------- # Set Date Information year_min = 2000 year_max = 2048 month_min = 1 month_max = 12 date_min = 1 data_max = 31 hour_min = 0 hour_max = 23 read_ahi = ReadAhiL1(in_file_l1, geo_file=in_file_geo, cloud_file=in_file_cloud) ymd = read_ahi.ymd hms = read_ahi.hms j_year = int(ymd[0:4]) j_month = int(ymd[4:6]) j_date = int(ymd[6:8]) j_hour = int(hms[0:2]) if (not year_min <= j_year <= year_max) or (not month_min <= j_month <= month_max) or \ (not date_min <= j_date <= data_max) or (not hour_min <= j_hour <= hour_max): raise ValueError('Wrongly Time Setting. Please Retry ......') # ------------------------------------------------------------------------- # Calculating the Number of Xun (means ten day). if j_date <= 10: i2_xun_num = 3 *
@pulumi.getter def requested(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "requested") @requested.setter def requested(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "requested", value) @property @pulumi.getter(name="resourceId") def resource_id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "resource_id") @resource_id.setter def resource_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "resource_id", value) @property @pulumi.getter(name="specHash") def spec_hash(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "spec_hash") @spec_hash.setter def spec_hash(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "spec_hash", value) @property @pulumi.getter def state(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "state") @state.setter def state(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "state", value) @pulumi.input_type class AppInsightsApiKeySpecArgs: def __init__(__self__, *, app_insights: pulumi.Input[str], resource_group: pulumi.Input[str], auth_sdk_control_channel: Optional[pulumi.Input[bool]] = None, read_telemetry: Optional[pulumi.Input[bool]] = None, write_annotations: Optional[pulumi.Input[bool]] = None): """ AppInsightsApiKeySpec defines the desired state of AppInsightsApiKey """ pulumi.set(__self__, "app_insights", app_insights) pulumi.set(__self__, "resource_group", resource_group) if auth_sdk_control_channel is not None: pulumi.set(__self__, "auth_sdk_control_channel", auth_sdk_control_channel) if read_telemetry is not None: pulumi.set(__self__, "read_telemetry", read_telemetry) if write_annotations is not None: pulumi.set(__self__, "write_annotations", write_annotations) @property @pulumi.getter(name="appInsights") def app_insights(self) -> pulumi.Input[str]: return pulumi.get(self, "app_insights") @app_insights.setter def app_insights(self, value: pulumi.Input[str]): pulumi.set(self, "app_insights", value) @property @pulumi.getter(name="resourceGroup") def resource_group(self) -> pulumi.Input[str]: return pulumi.get(self, "resource_group") @resource_group.setter def resource_group(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group", value) @property @pulumi.getter(name="authSDKControlChannel") def auth_sdk_control_channel(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "auth_sdk_control_channel") @auth_sdk_control_channel.setter def auth_sdk_control_channel(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "auth_sdk_control_channel", value) @property @pulumi.getter(name="readTelemetry") def read_telemetry(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "read_telemetry") @read_telemetry.setter def read_telemetry(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "read_telemetry", value) @property @pulumi.getter(name="writeAnnotations") def write_annotations(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "write_annotations") @write_annotations.setter def write_annotations(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "write_annotations", value) @pulumi.input_type class AppInsightsApiKeyStatusArgs: def __init__(__self__, *, completed: Optional[pulumi.Input[str]] = None, contains_update: Optional[pulumi.Input[bool]] = None, failed_provisioning: Optional[pulumi.Input[bool]] = None, flattened_secrets: Optional[pulumi.Input[bool]] = None, message: Optional[pulumi.Input[str]] = None, output: Optional[pulumi.Input[str]] = None, polling_url: Optional[pulumi.Input[str]] = None, provisioned: Optional[pulumi.Input[bool]] = None, provisioning: Optional[pulumi.Input[bool]] = None, requested: Optional[pulumi.Input[str]] = None, resource_id: Optional[pulumi.Input[str]] = None, spec_hash: Optional[pulumi.Input[str]] = None, state: Optional[pulumi.Input[str]] = None): """ ASOStatus (AzureServiceOperatorsStatus) defines the observed state of resource actions """ if completed is not None: pulumi.set(__self__, "completed", completed) if contains_update is not None: pulumi.set(__self__, "contains_update", contains_update) if failed_provisioning is not None: pulumi.set(__self__, "failed_provisioning", failed_provisioning) if flattened_secrets is not None: pulumi.set(__self__, "flattened_secrets", flattened_secrets) if message is not None: pulumi.set(__self__, "message", message) if output is not None: pulumi.set(__self__, "output", output) if polling_url is not None: pulumi.set(__self__, "polling_url", polling_url) if provisioned is not None: pulumi.set(__self__, "provisioned", provisioned) if provisioning is not None: pulumi.set(__self__, "provisioning", provisioning) if requested is not None: pulumi.set(__self__, "requested", requested) if resource_id is not None: pulumi.set(__self__, "resource_id", resource_id) if spec_hash is not None: pulumi.set(__self__, "spec_hash", spec_hash) if state is not None: pulumi.set(__self__, "state", state) @property @pulumi.getter def completed(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "completed") @completed.setter def completed(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "completed", value) @property @pulumi.getter(name="containsUpdate") def contains_update(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "contains_update") @contains_update.setter def contains_update(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "contains_update", value) @property @pulumi.getter(name="failedProvisioning") def failed_provisioning(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "failed_provisioning") @failed_provisioning.setter def failed_provisioning(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "failed_provisioning", value) @property @pulumi.getter(name="flattenedSecrets") def flattened_secrets(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "flattened_secrets") @flattened_secrets.setter def flattened_secrets(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "flattened_secrets", value) @property @pulumi.getter def message(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "message") @message.setter def message(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "message", value) @property @pulumi.getter def output(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "output") @output.setter def output(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "output", value) @property @pulumi.getter(name="pollingUrl") def polling_url(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "polling_url") @polling_url.setter def polling_url(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "polling_url", value) @property @pulumi.getter def provisioned(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "provisioned") @provisioned.setter def provisioned(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "provisioned", value) @property @pulumi.getter def provisioning(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "provisioning") @provisioning.setter def provisioning(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "provisioning", value) @property @pulumi.getter def requested(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "requested") @requested.setter def requested(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "requested", value) @property @pulumi.getter(name="resourceId") def resource_id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "resource_id") @resource_id.setter def resource_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "resource_id", value) @property @pulumi.getter(name="specHash") def spec_hash(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "spec_hash") @spec_hash.setter def spec_hash(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "spec_hash", value) @property @pulumi.getter def state(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "state") @state.setter def state(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "state", value) @pulumi.input_type class AppInsightsSpecArgs: def __init__(__self__, *, application_type: pulumi.Input[str], kind: pulumi.Input[str], location: pulumi.Input[str], resource_group: pulumi.Input[str], key_vault_to_store_secrets: Optional[pulumi.Input[str]] = None): """ AppInsightsSpec defines the desired state of AppInsights """ pulumi.set(__self__, "application_type", application_type) pulumi.set(__self__, "kind", kind) pulumi.set(__self__, "location", location) pulumi.set(__self__, "resource_group", resource_group) if key_vault_to_store_secrets is not None: pulumi.set(__self__, "key_vault_to_store_secrets", key_vault_to_store_secrets) @property @pulumi.getter(name="applicationType") def application_type(self) -> pulumi.Input[str]: return pulumi.get(self, "application_type") @application_type.setter def application_type(self, value: pulumi.Input[str]): pulumi.set(self, "application_type", value) @property @pulumi.getter def kind(self) -> pulumi.Input[str]: return pulumi.get(self, "kind") @kind.setter def kind(self, value: pulumi.Input[str]): pulumi.set(self, "kind", value) @property @pulumi.getter def location(self) -> pulumi.Input[str]: return pulumi.get(self, "location") @location.setter def location(self, value: pulumi.Input[str]): pulumi.set(self, "location", value) @property @pulumi.getter(name="resourceGroup") def resource_group(self) -> pulumi.Input[str]: return pulumi.get(self, "resource_group") @resource_group.setter def resource_group(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group", value) @property @pulumi.getter(name="keyVaultToStoreSecrets") def key_vault_to_store_secrets(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "key_vault_to_store_secrets") @key_vault_to_store_secrets.setter def key_vault_to_store_secrets(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "key_vault_to_store_secrets", value) @pulumi.input_type class AppInsightsStatusArgs: def __init__(__self__, *, completed: Optional[pulumi.Input[str]] = None, contains_update: Optional[pulumi.Input[bool]] = None, failed_provisioning: Optional[pulumi.Input[bool]] = None, flattened_secrets: Optional[pulumi.Input[bool]] = None, message: Optional[pulumi.Input[str]] = None, output: Optional[pulumi.Input[str]] = None, polling_url: Optional[pulumi.Input[str]] = None, provisioned: Optional[pulumi.Input[bool]] = None, provisioning: Optional[pulumi.Input[bool]] = None, requested: Optional[pulumi.Input[str]] = None, resource_id: Optional[pulumi.Input[str]] = None, spec_hash: Optional[pulumi.Input[str]] = None, state: Optional[pulumi.Input[str]] = None): """ ASOStatus (AzureServiceOperatorsStatus) defines the observed state of resource actions """ if completed is not None: pulumi.set(__self__, "completed", completed) if contains_update is not None: pulumi.set(__self__, "contains_update", contains_update) if failed_provisioning is not None: pulumi.set(__self__, "failed_provisioning", failed_provisioning) if flattened_secrets is not None: pulumi.set(__self__, "flattened_secrets", flattened_secrets) if message is not None: pulumi.set(__self__, "message", message) if output is not None: pulumi.set(__self__, "output", output) if polling_url is not None: pulumi.set(__self__, "polling_url", polling_url) if provisioned is not None: pulumi.set(__self__, "provisioned", provisioned) if provisioning is not None: pulumi.set(__self__, "provisioning", provisioning) if requested is not None: pulumi.set(__self__, "requested", requested) if resource_id is not None: pulumi.set(__self__, "resource_id", resource_id) if spec_hash is not None: pulumi.set(__self__, "spec_hash", spec_hash) if state is not None: pulumi.set(__self__, "state", state) @property @pulumi.getter def completed(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "completed") @completed.setter def completed(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "completed", value) @property @pulumi.getter(name="containsUpdate") def contains_update(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "contains_update") @contains_update.setter def contains_update(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "contains_update", value) @property @pulumi.getter(name="failedProvisioning") def failed_provisioning(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "failed_provisioning") @failed_provisioning.setter def failed_provisioning(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "failed_provisioning", value) @property @pulumi.getter(name="flattenedSecrets") def flattened_secrets(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "flattened_secrets") @flattened_secrets.setter def flattened_secrets(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "flattened_secrets", value) @property @pulumi.getter def message(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "message") @message.setter def message(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "message", value) @property @pulumi.getter def output(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "output") @output.setter def output(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "output", value) @property @pulumi.getter(name="pollingUrl") def polling_url(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "polling_url") @polling_url.setter def polling_url(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "polling_url", value) @property @pulumi.getter def provisioned(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "provisioned") @provisioned.setter def provisioned(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "provisioned", value) @property @pulumi.getter def provisioning(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "provisioning") @provisioning.setter def provisioning(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "provisioning", value) @property @pulumi.getter def requested(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "requested") @requested.setter def requested(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "requested", value) @property @pulumi.getter(name="resourceId") def resource_id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "resource_id") @resource_id.setter def resource_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "resource_id", value) @property @pulumi.getter(name="specHash") def spec_hash(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "spec_hash") @spec_hash.setter def spec_hash(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "spec_hash", value) @property @pulumi.getter def state(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "state") @state.setter def state(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "state", value) @pulumi.input_type class AzureLoadBalancerSpecArgs: def __init__(__self__, *, backend_address_pool_name: pulumi.Input[str], backend_port: pulumi.Input[int], frontend_port_range_end: pulumi.Input[int], frontend_port_range_start: pulumi.Input[int], inbound_nat_pool_name: pulumi.Input[str], location: pulumi.Input[str], public_ip_address_name: pulumi.Input[str], resource_group: pulumi.Input[str]): """ AzureLoadBalancerSpec defines the desired state of AzureLoadBalancer :param pulumi.Input[str] location: INSERT ADDITIONAL SPEC FIELDS - desired state of cluster Important: Run "make" to regenerate code after modifying this file """ pulumi.set(__self__, "backend_address_pool_name", backend_address_pool_name) pulumi.set(__self__, "backend_port", backend_port) pulumi.set(__self__, "frontend_port_range_end", frontend_port_range_end) pulumi.set(__self__, "frontend_port_range_start", frontend_port_range_start) pulumi.set(__self__, "inbound_nat_pool_name", inbound_nat_pool_name) pulumi.set(__self__, "location", location) pulumi.set(__self__, "public_ip_address_name", public_ip_address_name) pulumi.set(__self__, "resource_group", resource_group) @property @pulumi.getter(name="backendAddressPoolName") def backend_address_pool_name(self) -> pulumi.Input[str]: return pulumi.get(self, "backend_address_pool_name") @backend_address_pool_name.setter def backend_address_pool_name(self, value: pulumi.Input[str]): pulumi.set(self, "backend_address_pool_name", value) @property @pulumi.getter(name="backendPort") def backend_port(self) -> pulumi.Input[int]: return pulumi.get(self, "backend_port") @backend_port.setter def backend_port(self, value: pulumi.Input[int]): pulumi.set(self, "backend_port", value) @property @pulumi.getter(name="frontendPortRangeEnd") def frontend_port_range_end(self) -> pulumi.Input[int]: return pulumi.get(self, "frontend_port_range_end") @frontend_port_range_end.setter def frontend_port_range_end(self, value: pulumi.Input[int]): pulumi.set(self, "frontend_port_range_end", value) @property @pulumi.getter(name="frontendPortRangeStart") def frontend_port_range_start(self) -> pulumi.Input[int]: return pulumi.get(self, "frontend_port_range_start") @frontend_port_range_start.setter def frontend_port_range_start(self, value: pulumi.Input[int]): pulumi.set(self, "frontend_port_range_start", value) @property @pulumi.getter(name="inboundNatPoolName") def inbound_nat_pool_name(self) -> pulumi.Input[str]: return pulumi.get(self, "inbound_nat_pool_name") @inbound_nat_pool_name.setter def inbound_nat_pool_name(self,
else: ws_conn_string = "wss://%s/bokeh/sub" % split.netloc f_dict = dict( docid = sess.docid, ws_conn_string = ws_conn_string, docapikey = sess.apikey, root_url = base_url, modelid = modelid, modeltype = typename, script_url = base_url + "/bokeh/embed.js") e_str = '''<script src="%(script_url)s" bokeh_plottype="serverconn" bokeh_docid="%(docid)s" bokeh_ws_conn_string="%(ws_conn_string)s" bokeh_docapikey="%(docapikey)s" bokeh_root_url="%(root_url)s" bokeh_modelid="%(modelid)s" bokeh_modeltype="%(modeltype)s" async="true"></script> ''' return "", e_str % f_dict def _build_static_embed_snippet(self, static_path, embed_base_url): embed_filename = "%s.embed.js" % self._id full_embed_path = embed_base_url + embed_filename js_str = self._session.embed_js(self._id, static_path) sess = self._session modelid = self._id typename = self.__view_model__ embed_filename = full_embed_path f_dict = dict(modelid = modelid, modeltype = typename, embed_filename=embed_filename) e_str = '''<script src="%(embed_filename)s" bokeh_plottype="embeddata" bokeh_modelid="%(modelid)s" bokeh_modeltype="%(modeltype)s" async="true"></script> ''' return js_str, e_str % f_dict class DataSource(PlotObject): """ Base class for data sources """ # List of names of the fields of each tuple in self.data # ordering is incoporated here column_names = List() selected = List() #index of selected points def columns(self, *columns): """ Returns a ColumnsRef object that points to a column or set of columns on this data source """ return ColumnsRef(source=self, columns=list(columns)) class ColumnsRef(HasProps): source = Instance(DataSource, has_ref=True) columns = List(String) class ColumnDataSource(DataSource): # Maps names of columns to sequences or arrays data = Dict() # Maps field/column name to a DataRange or FactorRange object. If the # field is not in the dict, then a range is created automatically. cont_ranges = Dict() discrete_ranges = Dict() def __init__(self, *args, **kw): """ Modify the basic DataSource/PlotObj constructor so that if we are called with a single argument that is a dict, then we treat that implicitly as our "data" attribute. """ if len(args) == 1 and "data" not in kw: kw["data"] = args[0] raw_data = kw.get("data", {}) if not isinstance(raw_data, dict): import pandas as pd if isinstance(raw_data, pd.DataFrame): new_data = {} for colname in raw_data: new_data[colname] = raw_data[colname].tolist() raw_data = new_data for name, data in raw_data.items(): self.add(data, name) super(ColumnDataSource, self).__init__(**kw) def add(self, data, name=None): """ Appends the data to the list of columns. Returns the name that was inserted. """ if name is None: n = len(self.data) while "Series %d"%n in self.data: n += 1 name = "Series %d"%n self.column_names.append(name) self.data[name] = data return name def remove(self, name): try: self.column_names.remove(name) del self.data[name] except (ValueError, KeyError): warnings.warn("Unable to find column '%s' in datasource" % name) class PandasDataSource(DataSource): """ Represents serverside data. This gets stored into the plot server's database, but it does not have any client side representation. Instead, a PandasPlotSource needs to be created and pointed at it. """ data = Dict() class Range1d(PlotObject): start = Float() end = Float() class DataRange(PlotObject): sources = List(ColumnsRef, has_ref=True) def vm_serialize(self): props = self.vm_props(withvalues=True) props['id'] = self._id sources = props.pop("sources") props["sources"] = [{"ref":cr.source, "columns":cr.columns} for cr in sources] return props def finalize(self, models): super(DataRange, self).finalize(models) for idx, source in enumerate(self.sources): if isinstance(source, dict): self.sources[idx] = ColumnsRef( source=source['ref'], columns=source['columns']) def references(self): return [x.source for x in self.sources] class DataRange1d(DataRange): """ Represents a range in a scalar dimension """ sources = List(ColumnsRef, has_ref=True) rangepadding = Float(0.1) start = Float end = Float class FactorRange(PlotObject): """ Represents a range in a categorical dimension """ factors = List class Glyph(PlotObject): plot = Instance(has_ref=True) data_source = Instance(DataSource, has_ref=True) xdata_range = Instance(DataRange1d, has_ref=True) ydata_range = Instance(DataRange1d, has_ref=True) # How to intepret the values in the data_source units = Enum("screen", "data") # Instance of bokeh.glyphs.Glyph; not declaring it explicitly below # because of circular imports. The renderers should get moved out # into another module... glyph = Instance() # glyph used when data is unselected. optional nonselection_glyph = Instance() # glyph used when data is selected. optional selection_glyph = Instance() def vm_serialize(self): # Glyphs need to serialize their state a little differently, # because the internal glyph instance is turned into a glyphspec data = {"id" : self._id, "data_source": self.data_source, "xdata_range": self.xdata_range, "ydata_range": self.ydata_range, "glyphspec": self.glyph.to_glyphspec() } if self.selection_glyph: data['selection_glyphspec'] = self.selection_glyph.to_glyphspec() if self.nonselection_glyph: data['nonselection_glyphspec'] = self.nonselection_glyph.to_glyphspec() return data def finalize(self, models): super(Glyph, self).finalize(models) ## FIXME: we shouldn't have to do this i think.. if hasattr(self, 'glyphspec'): glyphspec = self.glyphspec del self.glyphspec self.glyph = PlotObject.get_class(glyphspec['type'])(**glyphspec) else: self.glyph = None if hasattr(self, 'selection_glyphspec'): selection_glyphspec = self.selection_glyphspec del self.selection_glyphspec temp = PlotObject.get_class(selection_glyphspec['type']) self.selection_glyph = temp(**selection_glyphspec) else: self.selection_glyph = None if hasattr(self, 'nonselection_glyphspec'): nonselection_glyphspec = self.nonselection_glyphspec del self.nonselection_glyphspec temp = PlotObject.get_class(nonselection_glyphspec['type']) self.nonselection_glyph = temp(**nonselection_glyphspec) else: self.nonselection_glyph = None class Plot(PlotObject): """ Object representing a plot, containing glyphs, guides, annotations. """ data_sources = List title = String("Bokeh Plot") x_range = Instance(DataRange1d, has_ref=True) y_range = Instance(DataRange1d, has_ref=True) png = String('') title = String('') outline_props = Include(LineProps, prefix="outline") # A list of all renderers on this plot; this includes guides as well # as glyph renderers renderers = List(has_ref=True) tools = List(has_ref=True) # TODO: These don't appear in the CS source, but are created by mpl.py, so # I'm leaving them here for initial compatibility testing. axes = List(has_ref=True) # TODO: How do we want to handle syncing of the different layers? # image = List # underlay = List # glyph = List # # annotation = List height = Int(600) width = Int(600) background_fill = Color("white") border_fill = Color("white") canvas_width = Int(400) canvas_height = Int(400) outer_width = Int(400) outer_height = Int(400) min_border_top = Int(50) min_border_bottom = Int(50) min_border_left = Int(50) min_border_right = Int(50) min_border = Int(50) script_inject_snippet = String("") def _get_script_inject_snippet(self): from .session import HTMLFileSession if isinstance(self._session, HTMLFileSession): self.script_inject_snippet return "" else: return self.create_html_snippet(server=True) def vm_props(self, *args, **kw): # FIXME: We need to duplicate the height and width into canvas and # outer height/width. This is a quick fix for the gorpiness, but this # needs to be fixed more structurally on the JS side, and then this # should be revisited on the Python side. if hasattr(self.session, "root_url"): self.script_inject_snippet = self.create_html_snippet(server=True) if "canvas_width" not in self._changed_vars: self.canvas_width = self.width if "outer_width" not in self._changed_vars: self.outer_width = self.width if "canvas_height" not in self._changed_vars: self.canvas_height = self.height if "outer_height" not in self._changed_vars: self.outer_height = self.height return super(Plot, self).vm_props(*args, **kw) class GMapPlot(PlotObject): center_lat = Float center_lng = Float zoom_level = Int(12) data_sources = List title = String("Bokeh Plot") png = String('') title = String('') # A list of all renderers on this plot; this includes guides as well # as glyph renderers renderers = List(has_ref=True) tools = List(has_ref=True) # TODO: These don't appear in the CS source, but are created by mpl.py, so # I'm leaving them here for initial compatibility testing. axes = List(has_ref=True) x_range = Instance(Range1d, has_ref=True) y_range = Instance(Range1d, has_ref=True) # TODO: How do we want to handle syncing of the different layers? # image = List # underlay = List # glyph = List # # annotation = List height = Int(800) width = Int(800) border_fill = Color("white") border_symmetry = String("h") canvas_width = Int(800) canvas_height = Int(800) outer_width = Int(800) outer_height = Int(800) min_border_top = Int(50) min_border_bottom = Int(50) min_border_left = Int(50) min_border_right = Int(50) min_border = Int(50) def vm_serialize(self): # Glyphs need to serialize their state a little differently, # because the internal glyph instance is turned into a glyphspec data = super(GMapPlot, self).vm_serialize() data.pop('center_lat', None) data.pop('center_lng', None) data.pop('zoom_level', None) data["map_options"] = { 'lat': self.center_lat, 'lng': self.center_lng, 'zoom': self.zoom_level } self._session.raw_js_snippets(self) return data @classmethod def load_json(cls, attrs, instance=None): """Loads all json into a instance of cls, EXCEPT any references which are handled in finalize """ inst = super(GMapPlot, cls).load_json(attrs, instance=instance) if hasattr(inst, 'map_options'): mo = inst.map_options del inst.map_options inst.center_lat = mo['lat'] inst.center_lng = mo['lng'] inst.zoom_level = mo['zoom'] return inst def get_raw_js(self): return '<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>' def vm_props(self, *args, **kw): # FIXME: We need to duplicate the height and width into canvas and # outer height/width. This is a quick fix for the gorpiness, but this # needs to be fixed more structurally on the JS side, and then this # should be revisited on the Python side. if "canvas_width" not in self._changed_vars: self.canvas_width = self.width if "outer_width" not in self._changed_vars: self.outer_width = self.width if "canvas_height" not in self._changed_vars: self.canvas_height = self.height if
params[0] return np.array([[1, 0], [0, cmath.exp(1j * phi)]]) @staticmethod def decomposition(phi, wires): return [PhaseShift(phi, wires=wires)] def adjoint(self): return U1(-self.data[0], wires=self.wires) class U2(Operation): r"""U2(phi, lambda, wires) U2 gate. .. math:: U_2(\phi, \lambda) = \frac{1}{\sqrt{2}}\begin{bmatrix} 1 & -\exp(i \lambda) \\ \exp(i \phi) & \exp(i (\phi + \lambda)) \end{bmatrix} The :math:`U_2` gate is related to the single-qubit rotation :math:`R` (:class:`Rot`) and the :math:`R_\phi` (:class:`PhaseShift`) gates via the following relation: .. math:: U_2(\phi, \lambda) = R_\phi(\phi+\lambda) R(\lambda,\pi/2,-\lambda) .. note:: If the ``U2`` gate is not supported on the targeted device, PennyLane will attempt to decompose the gate into :class:`~.Rot` and :class:`~.PhaseShift` gates. **Details:** * Number of wires: 1 * Number of parameters: 2 * Gradient recipe: :math:`\frac{d}{d\phi}f(U_2(\phi, \lambda)) = \frac{1}{2}\left[f(U_2(\phi+\pi/2, \lambda)) - f(U_2(\phi-\pi/2, \lambda))\right]` where :math:`f` is an expectation value depending on :math:`U_2(\phi, \lambda)`. This gradient recipe applies for each angle argument :math:`\{\phi, \lambda\}`. Args: phi (float): azimuthal angle :math:`\phi` lambda (float): quantum phase :math:`\lambda` wires (Sequence[int] or int): the subsystem the gate acts on """ num_params = 2 num_wires = 1 par_domain = "R" grad_method = "A" @classmethod def _matrix(cls, *params): phi, lam = params return INV_SQRT2 * np.array( [[1, -cmath.exp(1j * lam)], [cmath.exp(1j * phi), cmath.exp(1j * (phi + lam))]] ) @staticmethod def decomposition(phi, lam, wires): decomp_ops = [ Rot(lam, np.pi / 2, -lam, wires=wires), PhaseShift(lam, wires=wires), PhaseShift(phi, wires=wires), ] return decomp_ops def adjoint(self): phi, lam = self.parameters new_lam = (np.pi - phi) % (2 * np.pi) new_phi = (np.pi - lam) % (2 * np.pi) return U2(new_phi, new_lam, wires=self.wires) class U3(Operation): r"""U3(theta, phi, lambda, wires) Arbitrary single qubit unitary. .. math:: U_3(\theta, \phi, \lambda) = \begin{bmatrix} \cos(\theta/2) & -\exp(i \lambda)\sin(\theta/2) \\ \exp(i \phi)\sin(\theta/2) & \exp(i (\phi + \lambda))\cos(\theta/2) \end{bmatrix} The :math:`U_3` gate is related to the single-qubit rotation :math:`R` (:class:`Rot`) and the :math:`R_\phi` (:class:`PhaseShift`) gates via the following relation: .. math:: U_3(\theta, \phi, \lambda) = R_\phi(\phi+\lambda) R(\lambda,\theta,-\lambda) .. note:: If the ``U3`` gate is not supported on the targeted device, PennyLane will attempt to decompose the gate into :class:`~.PhaseShift` and :class:`~.Rot` gates. **Details:** * Number of wires: 1 * Number of parameters: 3 * Gradient recipe: :math:`\frac{d}{d\phi}f(U_3(\theta, \phi, \lambda)) = \frac{1}{2}\left[f(U_3(\theta+\pi/2, \phi, \lambda)) - f(U_3(\theta-\pi/2, \phi, \lambda))\right]` where :math:`f` is an expectation value depending on :math:`U_3(\theta, \phi, \lambda)`. This gradient recipe applies for each angle argument :math:`\{\theta, \phi, \lambda\}`. Args: theta (float): polar angle :math:`\theta` phi (float): azimuthal angle :math:`\phi` lambda (float): quantum phase :math:`\lambda` wires (Sequence[int] or int): the subsystem the gate acts on """ num_params = 3 num_wires = 1 par_domain = "R" grad_method = "A" @classmethod def _matrix(cls, *params): theta, phi, lam = params c = math.cos(theta / 2) s = math.sin(theta / 2) return np.array( [ [c, -s * cmath.exp(1j * lam)], [s * cmath.exp(1j * phi), c * cmath.exp(1j * (phi + lam))], ] ) @staticmethod def decomposition(theta, phi, lam, wires): decomp_ops = [ Rot(lam, theta, -lam, wires=wires), PhaseShift(lam, wires=wires), PhaseShift(phi, wires=wires), ] return decomp_ops def adjoint(self): theta, phi, lam = self.parameters new_lam = (np.pi - phi) % (2 * np.pi) new_phi = (np.pi - lam) % (2 * np.pi) return U3(theta, new_phi, new_lam, wires=self.wires) class IsingXX(Operation): r"""IsingXX(phi, wires) Ising XX coupling gate .. math:: XX(\phi) = \begin{bmatrix} \cos(\phi / 2) & 0 & 0 & -i \sin(\phi / 2) \\ 0 & \cos(\phi / 2) & -i \sin(\phi / 2) & 0 \\ 0 & -i \sin(\phi / 2) & \cos(\phi / 2) & 0 \\ -i \sin(\phi / 2) & 0 & 0 & \cos(\phi / 2) \end{bmatrix}. **Details:** * Number of wires: 2 * Number of parameters: 1 * Gradient recipe: :math:`\frac{d}{d\phi}f(XX(\phi)) = \frac{1}{2}\left[f(XX(\phi +\pi/2)) - f(XX(\phi-\pi/2))\right]` where :math:`f` is an expectation value depending on :math:`XX(\phi)`. Args: phi (float): the phase angle wires (int): the subsystem the gate acts on """ num_params = 1 num_wires = 2 par_domain = "R" grad_method = "A" @classmethod def _matrix(cls, *params): phi = params[0] c = math.cos(phi / 2) s = math.sin(phi / 2) return np.array( [[c, 0, 0, -1j * s], [0, c, -1j * s, 0], [0, -1j * s, c, 0], [-1j * s, 0, 0, c]] ) @staticmethod def decomposition(phi, wires): decomp_ops = [ CNOT(wires=wires), RX(phi, wires=[wires[0]]), CNOT(wires=wires), ] return decomp_ops def adjoint(self): (phi,) = self.parameters return IsingXX(-phi, wires=self.wires) class IsingZZ(Operation): r""" IsingZZ(phi, wires) Ising ZZ coupling gate .. math:: ZZ(\phi) = \begin{bmatrix} e^{-i \phi / 2} & 0 & 0 & 0 \\ 0 & e^{i \phi / 2} & 0 & 0 \\ 0 & 0 & e^{i \phi / 2} & 0 \\ 0 & 0 & 0 & e^{-i \phi / 2} \end{bmatrix}. **Details:** * Number of wires: 2 * Number of parameters: 1 * Gradient recipe: :math:`\frac{d}{d\phi}f(ZZ(\phi)) = \frac{1}{2}\left[f(ZZ(\phi +\pi/2)) - f(ZZ(\phi-\pi/2))\right]` where :math:`f` is an expectation value depending on :math:`ZZ(\theta)`. Args: phi (float): the phase angle wires (int): the subsystem the gate acts on """ num_params = 1 num_wires = 2 par_domain = "R" grad_method = "A" @staticmethod def decomposition(phi, wires): return [ qml.CNOT(wires=wires), qml.RZ(phi, wires=[wires[1]]), qml.CNOT(wires=wires), ] @classmethod def _matrix(cls, *params): phi = params[0] pos_phase = np.exp(1.0j * phi / 2) neg_phase = np.exp(-1.0j * phi / 2) return np.diag([neg_phase, pos_phase, pos_phase, neg_phase]) def adjoint(self): (phi,) = self.parameters return IsingZZ(-phi, wires=self.wires) # ============================================================================= # Quantum chemistry # ============================================================================= class SingleExcitation(Operation): r"""SingleExcitation(phi, wires) Single excitation rotation. .. math:: U(\phi) = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos(\phi/2) & -\sin(\phi/2) & 0 \\ 0 & \sin(\phi/2) & \cos(\phi/2) & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}. This operation performs a rotation in the two-dimensional subspace :math:`\{|01\rangle, |10\rangle\}`. The name originates from the occupation-number representation of fermionic wavefunctions, where the transformation from :math:`|10\rangle` to :math:`|01\rangle` is interpreted as "exciting" a particle from the first qubit to the second. **Details:** * Number of wires: 2 * Number of parameters: 1 * Gradient recipe: The ``SingleExcitation`` operator satisfies a four-term parameter-shift rule (see Appendix F, https://arxiv.org/abs/2104.05695) Args: phi (float): rotation angle :math:`\phi` wires (Sequence[int]): the wires the operation acts on **Example** The following circuit performs the transformation :math:`|10\rangle\rightarrow \cos( \phi/2)|10\rangle -\sin(\phi/2)|01\rangle`: .. code-block:: dev = qml.device('default.qubit', wires=2) @qml.qnode(dev) def circuit(phi): qml.PauliX(wires=0) qml.SingleExcitation(phi, wires=[0, 1]) return qml.state() circuit(0.1) """ num_params = 1 num_wires = 2 par_domain = "R" grad_method = "A" grad_recipe = four_term_grad_recipe generator = [np.array([[0, 0, 0, 0], [0, 0, -1j, 0], [0, 1j, 0, 0], [0, 0, 0, 0]]), -1 / 2] @classmethod def _matrix(cls, *params): theta = params[0] c = math.cos(theta / 2) s = math.sin(theta / 2) return np.array([[1, 0, 0, 0], [0, c, -s, 0], [0, s, c, 0], [0, 0, 0, 1]]) @staticmethod def decomposition(theta, wires): decomp_ops = [ qml.CNOT(wires=[wires[0], wires[1]]), qml.CRY(theta, wires=[wires[1], wires[0]]), qml.CNOT(wires=[wires[0], wires[1]]), ] return decomp_ops def adjoint(self): (phi,) = self.parameters return SingleExcitation(-phi, wires=self.wires) class SingleExcitationMinus(Operation): r"""SingleExcitationMinus(phi, wires) Single excitation rotation with negative phase-shift outside the rotation subspace. .. math:: U_-(\phi) = \begin{bmatrix} e^{-i\phi/2} & 0 & 0 & 0 \\ 0 & \cos(\phi/2) & -\sin(\phi/2) & 0 \\ 0 & \sin(\phi/2) & \cos(\phi/2) & 0 \\ 0 & 0 & 0 & e^{-i\phi/2} \end{bmatrix}. **Details:** * Number of wires: 2 * Number of parameters: 1 * Gradient recipe: :math:`\frac{d}{d\phi}f(U_-(\phi)) = \frac{1}{2}\left[f(U_-(\phi+\pi/2)) - f(U_-(\phi-\pi/2))\right]` where :math:`f` is an expectation value depending on :math:`U_-(\phi)`. Args: phi (float): rotation angle :math:`\phi` wires (Sequence[int] or int): the wires the operation acts on """ num_params = 1 num_wires = 2 par_domain = "R" grad_method = "A" generator = [np.array([[1, 0, 0, 0], [0, 0, -1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1]]), -1 / 2] @classmethod def _matrix(cls, *params): theta = params[0] c = math.cos(theta / 2) s = math.sin(theta / 2) e = cmath.exp(-1j * theta / 2) return np.array([[e, 0, 0, 0], [0, c, -s, 0], [0, s, c, 0], [0, 0, 0, e]]) @staticmethod def decomposition(theta, wires): decomp_ops = [ qml.PauliX(wires=wires[0]), qml.PauliX(wires=wires[1]),
<filename>libdarknet/Bridge.py '''Darknet_zed auxillary code developed for 3D object detection by Reachy. Developed by :- <NAME> Supervisors :- <NAME>, <NAME> This package contains code developed for the ZED Camera 2 running on Jetson tx2.''' import io import math import random import socket import statistics import time # from skimage.measure import compare_ssim import numpy as np import cv2 from PIL import Image, ImageChops def socket_server_status(detections, point_cloud_data): '''The Detection data is transmitted via a socket connection to OverLord.py via TCP or UDP protocol, to be viewed by the primary user of the program. The import function was compromised between darknet_zed & Overlord, meaning the text - input command from Overlord was initiated every time darknet_zed ran and the sequential structure execution in python meant that the detection algorithm would only start once the input was given to print detected function. The socket method kept both code independent from each other, allowing us to detect the objects and at the same time see it in a seperate window. Parallel Processing libraries such as threading and multiprocessing were tried but this method gave a favourable outcome. UDP was chosen over TCP due to it's independence from the necessity of a listening client, thus irrespective of whether or not, there was a listening client the server keeps on transmitting data and the client only prints out the real-time data once the user needs it otherwise, the data can get overwritten.''' # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # SOCK_DGRAM stands for datagram which is UDP's method of data transmission server_address = ('localhost', 10000) # the local host address and port number. If you run into an error try changing, # as the port might be occupied by some other process message = detections + "//" + point_cloud_data # the detected data separated by a separator '//' from the point # cloud location data of x, y, z value of the bounding box for # location estimation of the object in the environment try: # Send data in a try block to prevent the presence of an error sent = sock.sendto(message.encode(), server_address) finally: sock.close() # once the data has been sent, the socket can be closed def socket_server_detected_objects(detected_objects): '''The detected objects list is transmitted via a socket connection to OverLord.py via TCP or UDP protocol, to be viewed by the primary user of the program. The import function was compromised between darknet_zed & Overlord, meaning the text - input command from Overlord was initiated every time darknet_zed ran and the sequential structure execution in python meant that the detection algorithm would only start once the input was given to print detected function. The socket method kept both code independent from ech other, allowing us to detect the objects and at the same time see it in a seperate window. Parallel Processing libraries such as threading and multiprocessing were tried but this method gave a favourable outcome. UDP was chosen over TCP due to it's independence from the necessity of a listning client, thus irrespective of whether or not, there was a listening client the server keeps on transmitting data and the client only prints out the real-time data once the user needs it otherwise, the data can get overwritten''' # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # SOCK_DGRAM stands for datagram which is UDP's method of data transmission server_address = ('localhost', 20000) # the local host address and port number. If you run into an error try changing, as the port might be occupied by some other process message = detected_objects # the detected data separated by a separator '//' from the point cloud location data of x, y, z value of the bounding box for location estimation of the object in the environment try: # Send data in a try block to prevent the presence of an error sent = sock.sendto(message.encode(), server_address) finally: sock.close() # once the data has been sent, the socket can be closed def socket_client_control(): '''A remote control which needs to be refreshed but can be used to control the image output ZED camera, though the detection data will still flow into detected objects.''' sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_address = ('localhost', 30000) # the local host address and port number. If you run into an error try changing, as the port might be occupied by some other process sock.bind(server_address) # client binding statement to the port try: # Receive response from the server data, server = sock.recvfrom(4096) # receiving data from the socket which tells if the camera window "ZED" should show and image output or a blank mask detection_data = str(data) finally: sock.close() # closing the socket once all the data has been transmitted or received. return detection_data def opfileprint(detection): '''An alternate method of displaying data to the socket method. They are both similar in their mechanism, with this method printing the detected data in a file called "YOLO_OUTPUT.txt". It's easier to implement method out of the 2 and is kept as an alternate if needed. The Receiving end needs to just read the file and print out the data. The receiving end is present in Overlord.py''' Fileman = open('YOLO_OUTPUT', 'w') # creating and opening file in the write configuration for i in detection: Fileman.write('\n') Fileman.write(i) # writing the detection into the file def image_segmentation_depth(y_extent, x_extent, y_coord, x_coord, depth, image, median_max, avg_median, grasp_y_delay, shallow_cluster_y, x_centroid, x_centroid_marker): '''Perform image segmentation based on depth information received by ZED camera's point cloud data. The depth of the pixels in the bounding box are added to a flattened array and after averaging their depth, the mean depth of the object is received and the depth of the pixels is once again compared to analyse if the target pixel is greater or lesser than the mean depth of the object's bounding box. If it is lesser than the mean depth, the pixel is highlighted. Grasping points - an additional method which may be used in addition to the image segmentation mask is to identify, the ideal grasping points of the object with respect to the object geometry. The present primary method to acheive, grasping points on the object is done by storing all the y-axis pixels which are lesser than the median depth and then finding the median values from the pixel to locate the center of the object in terms of y-axis values. Once, the central y-axis coordinates have been narrowed down, it's respective x-axis values are at the edge of the segmentation mask are highlighted using a green circle marker.''' median_depth = [] # initialising an array to store the depth of all pixels in the bounding box grasp_array_y = [] # initialising an array to store the pixels in the bounding box lesser than the median depth grasp_array_x = [] # initialising an array to store the depth of all pixels on the x-axis for grasping point # min_object_depth = [] # initialising an array to store the minimum depth of bounding box for grasping technique shallow_grasp_x = [] # initialising an array to store the depth of all pixels on x-axis for grasping points corresponding to shallowest point on the object shallow_grasp_y = [] # initialising an array to store the depth of all pixels on y-axis for grasping points corresponding to shallowest point on the object x_marker = {} # dictionary to store all x-axis coordinates belonging to the object for every y-axis coordinate geometrical_centroid_x = [] # registering coordinates on the x-axis line for the y-axis marker which has the most x-axis coordinates height = 0 '''FOR loop that calculates the median depth of the bounding box by storing the pixel depth data from the point cloud data in an array - median_depth.''' for i in range(y_extent): # element by element multiplication of the height of the bounding box y_val = y_coord + (i - 1)
use_only=False) model.set_all_beta(2, use_only=False) elif args.init_to_smallest: model.set_all_alpha(er=3, k=3, se=0.25 if args.force_se else 0, use_only=False) model.set_all_beta(2, use_only=False) elif args.init_to_biggest: model.set_last_alpha(use_only=False) model.set_last_beta(use_only=False) elif args.init_to_biggest_alpha: model.set_all_alpha(er=6, k=5, se=0.25 if args.force_se else 0, use_only=False) model.set_all_beta(2, use_only=False) else: model.set_uniform_alpha() model.set_uniform_beta(stage=1) if args.local_rank == 0: logging.info('Model %s created, param count: %d' % (args.model, sum([m.numel() for m in model.parameters()]))) data_config = resolve_data_config(vars(args), model=model, verbose=False) model.eval() num_aug_splits = 0 if args.aug_splits > 0: assert args.aug_splits > 1, 'A split of 1 makes no sense' num_aug_splits = args.aug_splits if args.split_bn: assert num_aug_splits > 1 or args.resplit model = convert_splitbn_model(model, max(num_aug_splits, 2)) use_amp = None if args.amp: # For backwards compat, `--amp` arg tries apex before native amp if has_apex: args.apex_amp = True elif has_native_amp: args.native_amp = True if args.apex_amp and has_apex: use_amp = 'apex' elif args.native_amp and has_native_amp: use_amp = 'native' elif args.apex_amp or args.native_amp: logging.warning("Neither APEX or native Torch AMP is available, using float32. " "Install NVIDA apex or upgrade to PyTorch 1.6") if args.num_gpu > 1: if use_amp == 'apex': logging.warning( 'Apex AMP does not work well with nn.DataParallel, disabling. Use DDP or Torch AMP.') use_amp = None model = nn.DataParallel(model, device_ids=list(range(args.num_gpu))).cuda() assert not args.channels_last, "Channels last not supported with DP, use DDP." else: model.cuda() model.train() if args.channels_last: model = model.to(memory_format=torch.channels_last) model.cuda() model.train() optim = None list_alphas = None fixed_latency = 0 if args.search_elastic_model: model.set_hard_backprop(False) model.eval() with torch.no_grad(): x = torch.rand(64, 3, 224, 224).cuda() out = model(x) del out, x gc.collect() torch.cuda.empty_cache() list_alphas, fixed_latency = extract_structure_param_list(model, file_name=args.lut_filename, batch_size=args.lut_measure_batch_size, repeat_measure=args.repeat_measure, target_device=args.target_device) fixed_latency = args.latency_corrective_slope * fixed_latency + args.latency_corrective_intercept optim = create_optimizer_alpha(args, list_alphas, args.lr_alphas) if hasattr(optim, 'fixed_latency'): optim.fixed_latency = fixed_latency # Optionally resume from a checkpoint resume_state = {} if args.resume: resume_state, resume_epoch = resume_checkpoint(model, args.resume) if resume_state and not args.no_resume_opt: if use_amp and 'amp' in resume_state and 'load_state_dict' in amp.__dict__: if args.local_rank == 0: logging.info('Restoring NVIDIA AMP state from checkpoint') amp.load_state_dict(resume_state['amp']) del resume_state if args.distributed: if args.sync_bn: assert not args.split_bn try: if has_apex: model = convert_syncbn_model(model) else: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) if args.local_rank == 0: logging.info( 'Converted model to use Synchronized BatchNorm. WARNING: You may have issues if using ' 'zero initialized BN layers (enabled by default for ResNets) while sync-bn enabled.') except Exception as e: logging.error('Failed to enable Synchronized BatchNorm. Install Apex or Torch >= 1.1') if has_apex and use_amp != 'native': # Apex DDP preferred unless native amp is activated if args.local_rank == 0: logging.info("Using NVIDIA APEX DistributedDataParallel.") model = ApexDDP(model, delay_allreduce=True) else: if args.local_rank == 0: logging.info("Using native Torch DistributedDataParallel.") # NOTE: EMA model does not need to be wrapped by DDP model = NativeDDP(model, device_ids=[args.local_rank], find_unused_parameters=True) if args.eval_child_model: loader_eval = create_loader( dataset_eval, input_size=data_config['input_size'], batch_size=args.validation_batch_size_multiplier * args.batch_size, is_training=False, use_prefetcher=args.prefetcher, interpolation=data_config['interpolation'], mean=data_config['mean'], std=data_config['std'], num_workers=args.workers, distributed=args.distributed, crop_pct=data_config['crop_pct'], pin_memory=args.pin_mem, squish=args.squish, ) if args.jsd: assert num_aug_splits > 1 # JSD only valid with aug splits set validate_loss_fn = nn.CrossEntropyLoss().cuda() elif args.mixup > 0.: # smoothing is handled with mixup label transform validate_loss_fn = nn.CrossEntropyLoss().cuda() elif args.smoothing: validate_loss_fn = nn.CrossEntropyLoss().cuda() else: train_loss_fn = nn.CrossEntropyLoss().cuda() validate_loss_fn = train_loss_fn eval_metric = args.eval_metric best_metric = None best_epoch = None saver = None output_dir = '' if args.local_rank == 0: output_base = args.output if args.output else './output' exp_name = '-'.join([ datetime.now().strftime("%Y%m%d-%H%M%S"), args.model, str(data_config['input_size'][-1]) ]) output_dir = get_outdir(output_base, 'train', exp_name) decreasing = True if eval_metric == 'loss' else False saver = CheckpointSaver(checkpoint_dir=output_dir, decreasing=decreasing) with open(os.path.join(output_dir, 'args.yaml'), 'w') as f: f.write(args_text) torch.cuda.empty_cache() alpha_attention_vec, _, alpha_grad_vec, alpha_blocks, beta_attention_vec, beta_grad_vec, beta_blocks = \ flatten_attention_latency_grad_alpha_beta_blocks(list_alphas) alphas = len(alpha_attention_vec) betas = len(beta_attention_vec) predictor = construct_predictors(args.predictor_type, alphas, betas) predictor.load_state_dict(torch.load(args.predictor_ckpt_filename)) print(f'Loaded {args.predictor_ckpt_filename}') alpha_attention_vec, latency_vec, _, alpha_blocks, beta_attention_vec, _, beta_blocks = \ flatten_attention_latency_grad_alpha_beta_blocks(list_alphas) _, _ = optim._latency_constraint(alpha_blocks, beta_blocks, latency_vec, alpha_vec=alpha_attention_vec, beta_vec=beta_attention_vec) if args.test_accuracy_lut_filename is not None: print('----------------------- Ranking Correlation with Supernet --------------------------------') with open(args.test_accuracy_lut_filename, 'rb') as f: test_accuracy_dict = pickle.load(f) xs, ys, xs_oh = [], [], [] for i, record in enumerate(test_accuracy_dict.values()): record['logits'] = record['logits'] ys.append(torch.tensor(record['accuracy']).unsqueeze(dim=0)) xs.append(torch.tensor(record['logits'])) x_oh = [] for entry, argmax in zip(list_alphas, record['logits']): key = 'beta' if 'beta' in entry else 'alpha' if key == 'beta': continue logits = entry['module'].alpha if key == 'alpha' else entry[key] one_hot = [0 for _ in range(len(logits.data))] one_hot[argmax] = 1 x_oh += one_hot for entry, argmax in zip(list_alphas, record['logits']): key = 'beta' if 'beta' in entry else 'alpha' if key == 'alpha': continue logits = entry['module'].alpha if key == 'alpha' else entry[key] one_hot = [0 for _ in range(len(logits.data))] one_hot[argmax] = 1 x_oh += one_hot xs_oh.append(torch.tensor(x_oh)) X, Y = xs_oh, ys predictor.model.cuda() y = predict(predictor, X) x = np.array([y.item() for y in Y], dtype=y.dtype) kt_str = 'Kendall-tau: {0:0.2f}'.format(stats.kendalltau(x, y)[0]) sp_str = 'Spearman: {0:0.2f}'.format(stats.spearmanr(x, y)[0]) ps_str = 'Pearson: {0:0.2f}'.format(stats.pearsonr(x, y)[0]) mse_str = 'MSE: {0:0.2f}'.format(np.mean(np.square(x - y))) print('{} | {} | {} | {}'.format(kt_str, sp_str, ps_str, mse_str)) if args.test_figure_filename is not None: plt.figure() plt.scatter(x, y) plt.title('{} | {} | {} | {}'.format(kt_str, sp_str, ps_str, mse_str)) plt.xlabel('Oneshot Accuracy') plt.ylabel('Predicted Accuracy') xmin, xmax, ymin, ymax = plt.axis() plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)), color='yellow') plt.plot([xmin, xmax], [ymin, ymax], color='green', linestyle='dashed') plt.savefig(args.test_figure_filename) search(args, model, list_alphas, optim, saver, predictor, args.verbose_search) alpha_attention_vec, _, _, _, beta_attention_vec, _, _ = \ flatten_attention_latency_grad_alpha_beta_blocks(list_alphas) x = np.concatenate((alpha_attention_vec, beta_attention_vec)) X = [torch.tensor(x)] predictor.model.cuda() predicted_accuracy = predict(predictor, X) print(f'Predicted Accuracy: {predicted_accuracy}') if not args.eval_child_model: return # Evaluate child model child_model, string_model = transform_model_to_mobilenet(model) if args.num_gpu > 1: child_model = torch.nn.DataParallel(child_model, device_ids=list(range(args.num_gpu))) child_model.cuda() validate(child_model, loader_eval, validate_loss_fn, args, log_suffix=' child model') if saver is not None: saver.save_checkpoint(child_model, optim, args, epoch=2, metric=2) model.eval() child_model.eval() print(f"Computing latency for {string_model}") unwrapped_model = model if hasattr(model, 'extract_expected_latency') else model.module latency_predicted = unwrapped_model.extract_expected_latency(file_name=args.lut_filename, batch_size=args.lut_measure_batch_size, iterations=args.repeat_measure, target=args.target_device) latency_measured = measure_time(child_model) diff = latency_measured - latency_predicted print(f"Latency_predicted={latency_predicted}, Latency_measured={latency_measured}, Diff={diff}") def search(args, model, list_alphas, optim, saver, predictor, verbose=False): print('------------------------ Search -------------------------------') if hasattr(optim, 'qcp'): alpha_attention_vec, _, _, _, beta_attention_vec, _, _ = \ flatten_attention_latency_grad_alpha_beta_blocks(list_alphas) alphas = len(alpha_attention_vec) betas = len(beta_attention_vec) optim.Q_acc = np.array(predictor.model.bilinear.weight.squeeze().detach().cpu(), dtype=np.double) p_acc = np.array(predictor.model.linear.weight.detach().cpu()[0], dtype=np.double) optim.p_acc_a = p_acc[:alphas] optim.p_acc_b = p_acc[-betas:] optim.qcp(np.zeros(alphas), np.zeros(betas), linear=False) elif hasattr(optim, 'evo'): optim.set_predictor(predictor) optim.evo() else: # model.set_all_alpha(er=3, k=3, se=0.25 if args.force_se else 0, use_only=False) # model.set_all_beta(2, use_only=False) alpha_attn, beta_attn = optimize_diff_predictor(predictor, optim, args.bcfw_steps) update_attentions_inplace(list_alphas, alpha_attention_vec=alpha_attn.detach().numpy(), beta_attention_vec=beta_attn.detach().numpy()) if verbose: print_solution(list_alphas, optim, args) # print('------------------------ Sparsify -------------------------------') optim.sparsify() if verbose: print_solution(list_alphas, optim, args) if saver is not None: saver.save_checkpoint(model, optim, args, epoch=0, metric=1) # Set alpha and beta to argmax model.set_argmax_alpha_beta() if hasattr(model, 'set_argmax_alpha_beta') else model.module.set_argmax_alpha_beta() if verbose: print_solution(list_alphas, optim, args) if saver is not None: saver.save_checkpoint(model, optim, args, epoch=1, metric=5) def optimize_diff_predictor(predictor, optimizer, steps): predictor.model.to(device='cpu') predictor.eval() predictor.requires_grad = False alpha_attn, beta_attn = smallest_sol(*generate_cnames(optimizer.alpha_blocks, optimizer.beta_blocks)) alpha_attn = torch.tensor(alpha_attn, requires_grad=True, device=next(predictor.model.parameters()).device) beta_attn = torch.tensor(beta_attn, requires_grad=True, device=next(predictor.model.parameters()).device) bar = tqdm(range(steps)) if DistributedManager.local_rank == 0 else range(steps) for _ in bar: alpha_attn.grad = torch.zeros_like(alpha_attn) beta_attn.grad = torch.zeros_like(beta_attn) x = torch.cat([alpha_attn, beta_attn]) criterion = -predictor(x) criterion.backward() with torch.no_grad(): bcfw_step(alpha_attn, beta_attn, optimizer) return alpha_attn, beta_attn def smallest_sol(anames, bnames): avals = [1.0 if name[0] == 'a' and name.split('_')[-1] == '0' else 0.0 for name in anames] bvals = [1.0 if name[0] == 'b' and name.split('_')[-1] == '1' else 0.0 for name in bnames] return avals, bvals def generate_cnames(alpha_blocks, beta_blocks): aname, bname = [], [] alpha_offset = 0 for beta_block, beta_block_size in enumerate(beta_blocks): aname += [f'a_{beta_block}_0_{c}' for c in range(alpha_blocks[alpha_offset])] alpha_offset += 1 for b in range(1, beta_block_size + 1): bname.append(f'b_{beta_block}_{b}') aname += [f'a_{beta_block}_{b}_{c}' for c in range(alpha_blocks[alpha_offset])] alpha_offset += 1 assert alpha_offset == len(alpha_blocks) return aname, bname def bcfw_step(alpha_attn, beta_attn, bcfw_opt): prob = np.random.random() if prob < 0.5 and bcfw_opt.k > 1: alpha_attn.data = bcfw_opt.alpha_lp(alpha_attn, bcfw_opt.alpha_blocks, bcfw_opt.latency_vec, alpha_attn.grad, beta_attn, bcfw_opt.beta_blocks) else: beta_attn.data = bcfw_opt.beta_lp(alpha_attn, bcfw_opt.latency_vec, bcfw_opt.alpha_blocks, beta_attn, beta_attn.grad, bcfw_opt.beta_blocks) def print_solution(list_alphas, optim, args, alpha_attn=None, beta_attn=None): alpha_attention_vec, _, alpha_grad_vec, alpha_blocks, beta_attention_vec, beta_grad_vec, beta_blocks = \ flatten_attention_latency_grad_alpha_beta_blocks(list_alphas) alpha_attention_vec = alpha_attn if alpha_attn is not None else alpha_attention_vec beta_attention_vec = beta_attn if beta_attn is not None else beta_attention_vec if args.local_rank != 0: return print('alpha:') reshaped = np.reshape(alpha_attention_vec, (len(alpha_blocks), -1)).copy() print(reshaped) print('beta:') reshaped = np.reshape(beta_attention_vec, (len(beta_blocks), -1)).copy() print(reshaped) check_rounding_constraint(optim, alpha_attention_vec, beta_attention_vec, alpha_blocks, beta_blocks) def check_rounding_constraint(optim, alpha, beta, alpha_blocks, beta_blocks): latency = optim.latency_formula(alpha, beta, optim.fixed_latency) print('constraint: {} <= {}'.format(latency, optim.T)) alpha =
<reponame>fruch/pbs #=============================================================================== # Copyright (C) 2011-2012 by <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #=============================================================================== import subprocess as subp import sys import traceback import os import re from glob import glob from types import ModuleType from functools import partial __version__ = "0.104" __project_url__ = "https://github.com/amoffat/pbs" IS_PY3 = sys.version_info[0] == 3 if IS_PY3: raw_input = input unicode = str else: pass config = {} config["DEFAULT_ENCODING"] = None if os.name == "nt": config["DEFAULT_ENCODING"] = "mbcs" if os.name == "posix": config["DEFAULT_ENCODING"] = "utf8" ''' default encoding could be changed like this pbs.set_default_encoding("utf16") ''' def set_default_encoding(new_encoding): config["DEFAULT_ENCODING"] = new_encoding class ErrorReturnCode(Exception): truncate_cap = 200 def __init__(self, full_cmd, stdout, stderr): self.full_cmd = full_cmd self.stdout = stdout self.stderr = stderr if self.stdout is None: tstdout = "<redirected>" else: tstdout = self.stdout[:self.truncate_cap] out_delta = len(self.stdout) - len(tstdout) if out_delta: tstdout += "... (%d more, please see e.stdout)" % out_delta if self.stderr is None: tstderr = "<redirected>" else: tstderr = self.stderr[:self.truncate_cap] err_delta = len(self.stderr) - len(tstderr) if err_delta: tstderr += "... (%d more, please see e.stderr)" % err_delta msg = "\n\nRan: %r\n\nSTDOUT:\n\n %s\n\nSTDERR:\n\n %s" %\ (full_cmd, tstdout, tstderr) super(ErrorReturnCode, self).__init__(msg) class CommandNotFound(Exception): pass rc_exc_regex = re.compile("ErrorReturnCode_(\d+)") rc_exc_cache = {} def get_rc_exc(rc): rc = int(rc) try: return rc_exc_cache[rc] except KeyError: pass name = "ErrorReturnCode_%d" % rc exc = type(name, (ErrorReturnCode,), {}) rc_exc_cache[rc] = exc return exc def which(program): def is_exe(fpath): return os.path.exists(fpath) and os.access(fpath, os.X_OK) def ext_candidates(fpath): yield fpath for ext in os.environ.get("PATHEXT", "").split(os.pathsep): yield fpath + ext fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) for candidate in ext_candidates(exe_file): if is_exe(candidate): return candidate return None def resolve_program(program): path = which(program) if not path: # our actual command might have a dash in it, but we can't call # that from python (we have to use underscores), so we'll check # if a dash version of our underscore command exists and use that # if it does if "_" in program: path = which(program.replace("_", "-")) if not path: return None return path class RunningCommand(object): def __init__(self, command_ran, process, call_args, stdin=None): self.command_ran = command_ran self.process = process self._stdout = None self._stderr = None self.call_args = call_args # we're running in the background, return self and let us lazily # evaluate if self.call_args["bg"]: return # we're running this command as a with context, don't do anything # because nothing was started to run from Command.__call__ if self.call_args["with"]: return # run and block if stdin: stdin.encode(config["DEFAULT_ENCODING"]) self._stdout, self._stderr = self.process.communicate(stdin) self._handle_exit_code(self.process.wait()) def __enter__(self): # we don't actually do anything here because anything that should # have been done would have been done in the Command.__call__ call. # essentially all that has to happen is the comand be pushed on # the prepend stack. pass def __exit__(self, typ, value, traceback): if self.call_args["with"] and Command._prepend_stack: Command._prepend_stack.pop() def __str__(self): if IS_PY3: return self.__unicode__() else: return unicode(self).encode(config["DEFAULT_ENCODING"]) def __unicode__(self): if self.process: if self.call_args["bg"]: self.wait() if self._stdout: return self.stdout else: return "" def __eq__(self, other): return unicode(self) == unicode(other) def __contains__(self, item): return item in str(self) def __getattr__(self, p): # let these three attributes pass through to the Popen object if p in ("send_signal", "terminate", "kill"): if self.process: return getattr(self.process, p) else: raise AttributeError return getattr(unicode(self), p) def __repr__(self): return "<RunningCommand %r, pid:%d, special_args:%r" % ( self.command_ran, self.process.pid, self.call_args) def __long__(self): return long(str(self).strip()) def __float__(self): return float(str(self).strip()) def __int__(self): return int(str(self).strip()) @property def stdout(self): if self.call_args["bg"]: self.wait() return self._stdout.decode(config["DEFAULT_ENCODING"], "replace") @property def stderr(self): if self.call_args["bg"]: self.wait() return self._stderr.decode(config["DEFAULT_ENCODING"], "replace") def wait(self): if self.process.returncode is not None: return self._stdout, self._stderr = self.process.communicate() self._handle_exit_code(self.process.wait()) return str(self) def _handle_exit_code(self, rc): if rc not in self.call_args["ok_code"]: raise get_rc_exc(rc)(self.command_ran, self._stdout, self._stderr) def __len__(self): return len(str(self)) class Command(object): _prepend_stack = [] call_args = { "fg": False, # run command in foreground "bg": False, # run command in background "with": False, # prepend the command to every command after it "out": None, # redirect STDOUT "err": None, # redirect STDERR "err_to_out": None, # redirect STDERR to STDOUT "env": os.environ, # this is for commands that may have a different exit status than the # normal 0. this can either be an integer or a list/tuple of ints "ok_code": 0, } @classmethod def _create(cls, program): path = resolve_program(program) if not path: # handle nt internal commands if os.name == 'nt' and program.lower() in nt_internal_command: return getattr(cls("cmd.exe").bake("/s", "/c"), program) else: raise CommandNotFound(program) return cls(path) def __init__(self, path): self._path = path self._partial = False self._partial_baked_args = [] self._partial_call_args = {} def __getattribute__(self, name): # convenience getattr = partial(object.__getattribute__, self) if name.startswith("_"): return getattr(name) if name == "bake": return getattr("bake") return getattr("bake")(name) @staticmethod def _extract_call_args(kwargs): kwargs = kwargs.copy() call_args = Command.call_args.copy() for parg, default in call_args.items(): key = "_" + parg if key in kwargs: call_args[parg] = kwargs[key] del kwargs[key] return call_args, kwargs def _format_arg(self, arg): if IS_PY3: arg = str(arg) else: arg = unicode(arg).encode(config["DEFAULT_ENCODING"]) return arg def _compile_args(self, args, kwargs): processed_args = [] # aggregate positional args for arg in args: if isinstance(arg, (list, tuple)): for sub_arg in arg: processed_args.append(self._format_arg(sub_arg)) else: processed_args.append(self._format_arg(arg)) # aggregate the keyword arguments for k,v in kwargs.items(): # we're passing a short arg as a kwarg, example: # cut(d="\t") if len(k) == 1: processed_args.append("-"+k) if v is not True: processed_args.append(self._format_arg(v)) # we're doing a long arg else: k = k.replace("_", "-") if v is True: processed_args.append("--"+k) else: processed_args.append('--%s="%s"' % (k, self._format_arg(v))) return processed_args def bake(self, *args, **kwargs): fn = Command(self._path) fn._partial = True call_args, kwargs = self._extract_call_args(kwargs) pruned_call_args = call_args for k,v in Command.call_args.items(): try: if pruned_call_args[k] == v: del pruned_call_args[k] except KeyError: continue fn._partial_call_args.update(self._partial_call_args) fn._partial_call_args.update(pruned_call_args) fn._partial_baked_args.extend(self._partial_baked_args) fn._partial_baked_args.extend(self._compile_args(args, kwargs)) return fn def __str__(self): if IS_PY3: return self.__unicode__() else: return unicode(self).encode(config["DEFAULT_ENCODING"]) def __repr__(self): return str(self) def __unicode__(self): baked_args = " ".join(self._partial_baked_args) if baked_args: baked_args = " " + baked_args return self._path + baked_args def __eq__(self, other): try: return str(self) == str(other) except: return False def __enter__(self): Command._prepend_stack.append([self._path]) def __exit__(self, typ, value, traceback): Command._prepend_stack.pop() def __call__(self, *args, **kwargs): kwargs = kwargs.copy() args = list(args) cmd = [] # aggregate any with contexts for prepend in self._prepend_stack: cmd.extend(prepend) cmd.append(self._path) call_args, kwargs = self._extract_call_args(kwargs) call_args.update(self._partial_call_args) # here we normalize the ok_code to be something we can do # "if return_code in call_args["ok_code"]" on if not isinstance(call_args["ok_code"], (tuple, list)): call_args["ok_code"] = [call_args["ok_code"]] # set pipe to None if we're outputting straight to CLI pipe = None if call_args["fg"] else subp.PIPE # check if we're piping via composition stdin = pipe actual_stdin = None if args: first_arg = args.pop(0) if isinstance(first_arg, RunningCommand): # it makes sense that if the input pipe of a command is running # in the background, then this command should run in the # background as well if first_arg.call_args["bg"]: call_args["bg"] = True stdin = first_arg.process.stdout else: actual_stdin = first_arg.stdout else: args.insert(0, first_arg) processed_args = self._compile_args(args, kwargs)
(source and os.path.exists(source)): logger.error("Source file or directory does not exist: {}".format(source)) sys.exit(-1) if source.endswith("/") or source.endswith("\\"): suite_name = get_file_name(get_file_path(source)) else: suite_name = get_file_name(source) if os.path.isdir(source): files = get_dir_files(source) else: files = [source, ] suite_dict = copy.deepcopy(self.suite_tpl) suite_dict['config']['name'] = suite_name logger.info("Start to parse cases from source files: {}".format(source)) for _file in files: if _file.lower().endswith('.har'): one_case = self.har_to_case(_file, target, include, exclude, validate_include, validate_exclude, auto_extract, suite_name) # elif _file.lower().endswith('.trace'): # self.charles_trace_to_case() # elif _file.lower().endswith('.txt'): # self.fiddler_txt_to_case() else: logger.warning("Unsupported file extension: {}, ignore".format(_file)) continue # add case into suite suite_dict['test_cases'].append(one_case) logger.info("Parse finished.") self.__generate_case(suite_dict, target) return suite_dict # parse har file and generate test cases def har_to_case(self, source, target="ParrotProject", include=None, exclude=None, validate_include=None, validate_exclude=None, auto_extract=False, suite_name=None): """parse source har file and generate test cases :param source: source file :param target: target directory for case output :param include: list, not matched url would be ignored in recording :param exclude: list, matched url would be ignored in recording :param validate_include: list, not matched response would be ignored in validating :param validate_exclude: list, matched response would be ignored in validating :param auto_extract: bool, for automatic identification of interface dependencies :param suite_name: specified suite, new a suite as default :return suite dict """ if not (source and os.path.exists(source)): logger.error("Source file does not exist: {}".format(source)) return False if not source.lower().endswith('.har'): logger.error("The source is not a har file: {}".format(source)) return False logger.info("Start to parse source file: {}".format(source)) content = self.__read_file(source) try: har_dict = json.loads(content)['log']['entries'] except TypeError: logger.error("HAR file content error: {}".format(source)) except KeyError: logger.error("HAR file content error: {}".format(source)) return False case_dict = copy.deepcopy(self.case_tpl) case_dict['config']['name'] = get_file_name(file=source) for entry_dict in har_dict: step_dict = copy.deepcopy(self.step_tpl) self.__har_times(entry=entry_dict, step_dict=step_dict) if not self.__har_request(entry=entry_dict, step_dict=step_dict, include=include, exclude=exclude, auto_extract=auto_extract): continue if not self.__har_response(entry=entry_dict, step_dict=step_dict, include=validate_include, exclude=validate_exclude, auto_extract=auto_extract): continue logger.debug("test_step: {}".format(json.dumps(step_dict, ensure_ascii=False))) # add step into case case_dict['test_steps'].append(step_dict) if suite_name: return case_dict else: suite_dict = copy.deepcopy(self.suite_tpl) # add case into suite suite_dict['test_cases'].append(case_dict) suite_dict['config']['name'] = get_file_name(file=source) logger.info("Parse finished.") self.__generate_case(suite_dict, target) return suite_dict @staticmethod def __read_file(name): try: with open(file=name, mode="r", encoding='utf-8') as f: content = f.read() # solve problem caused by BOM head if content.startswith(u'\ufeff'): content = content.encode('utf-8')[3:].decode('utf-8') return content except IOError: logger.error("Failed to open file: {}".format(name)) sys.exit(-1) def __generate_case(self, suite, target="ParrotProject"): logger.info("Start to generate test yamls") # generate test data _d_path = "{}/environments".format(target) _d_yaml = "{}/{}_env.yml".format(_d_path, suite['config']['name']) r_d_yaml = "../environments/{}_env.yml".format(suite['config']['name']) make_dir(_d_path) with open(file=_d_yaml, mode='w', encoding='utf-8') as f: yaml.dump(data=self.env_tpl, stream=f, encoding='utf-8', allow_unicode=True) logger.debug(" - environments: {}".format(_d_yaml)) _e_path = "{}/test_suites".format(target) _e_yaml = "{}/{}.yml".format(_e_path, suite['config']['name']) make_dir(_e_path) suite['config']['import'] = r_d_yaml _t_sid = 0 # count total steps in a suite for _cid, _case in enumerate(suite['test_cases']): # generate test steps for _sid, _step in enumerate(_case['test_steps']): _t_sid += 1 # remove 'response' for a clear view # _step['response'] = {'extract': {}} _s_resp = copy.deepcopy(_step['response']) for _k, _v in _s_resp.items(): if _k == 'extract': for _ex_k, _ex_v in _s_resp['extract'].items(): if _ex_k in self.variables.keys() and self.variables[_ex_k]['flag']: _step['response']['extract'][_ex_v] = _ex_v del _step['response']['extract'][_ex_k] elif _k != 'time.spent': del _step['response'][_k] _s_id = "{}{}".format('0'*(4-len(str(_t_sid))), _t_sid) # step id _s_path = "{}/test_steps/{}".format(target, '/'.join(_step['config']['name'].split('/')[1:-1])) _s_yaml = "{}/{}_{}.yml".format(_s_path, _s_id, _step['config']['name'].split('/')[-1]) r_s_yaml = "../test_steps/{}/{}_{}.yml".format( '/'.join(_step['config']['name'].split('/')[1:-1]), _s_id, _step['config']['name'].split('/')[-1]) if len(_step['config']['name'].split('/')) > 1: _step['config']['import'] = "{}environments/{}_env.yml".format('../'*(len(_step['config']['name'].split('/'))-1), suite['config']['name']) else: _step['config']['import'] = "../environments/{}_env.yml".format(suite['config']['name']) make_dir(_s_path) with open(file=_s_yaml, mode='w', encoding='utf-8') as f: # use allow_unicode=True to solve Chinese display problem yaml.dump(data=_step, stream=f, encoding='utf-8', allow_unicode=True) _case['test_steps'][_sid] = r_s_yaml logger.debug(" - test step: {}".format(_s_yaml)) # generate test cases _c_path = "{}/test_cases".format(target) _c_yaml = "{}/{}.yml".format(_c_path, _case['config']['name']) r_c_yaml = "../test_cases/{}.yml".format(_case['config']['name']) _case['config']['import'] = r_d_yaml make_dir(_c_path) with open(file=_c_yaml, mode='w', encoding='utf-8') as f: yaml.dump(data=_case, stream=f, encoding='utf-8', allow_unicode=True) logger.debug(" - test case: {}".format(_c_yaml)) suite['test_cases'][_cid] = r_c_yaml # generate test suite with open(file=_e_yaml, mode='w', encoding='utf-8') as f: yaml.dump(data=suite, stream=f, encoding='utf-8', allow_unicode=True) logger.debug(" - test suite: {}".format(_e_yaml)) logger.info("Done. You could get them in {}".format(target)) # parse request block and filter unneeded urls def __har_request(self, entry, step_dict, include, exclude, auto_extract=False): if not ('request' in entry.keys() and entry['request']): logger.warning(" * There is no request in this entry: {}".format(json.dumps(entry, ensure_ascii=False))) return False _req = entry['request'] # get method step_dict['request']['method'] = _req.get('method', 'GET') # get url: protocol, host, url path _url = _req.get('url', "") # logger.info(" Get a {} request: {}".format(step_dict['request']['method'], _url)) try: ( _whole_url, step_dict['request']['protocol'], step_dict['request']['host'], step_dict['request']['url'], _ ) = re.findall(r"((http\w*)://([\w.:]+)([^?]+))\??(.*)", _url)[0] step_dict['config']['name'] = step_dict['request']['url'] logger.debug(" - protocol: {} host: {} url: {}".format( step_dict['request']['protocol'], step_dict['request']['host'], step_dict['request']['url'])) logger.info(" Get a {} request: {}".format(step_dict['request']['method'], step_dict['request']['url'])) except IndexError: logger.warning(" * Invalid url: {}".format(_url)) return False # filter with include and exclude options logger.debug(" - include: {} exclude: {}".format(include, exclude)) if not self.__if_include(_whole_url, include) or self.__if_exclude(_whole_url, exclude): logger.info(" According to include/exclude options, ignore it") return False # get parameters # it may have both queryString and postData in an unusual post request step_dict['request']['params'] = {} step_dict['request']['data'] = {} _param = _req.get('queryString', []) _data = _req.get('postData', []) if _data: if 'params' in _req.get('postData'): _data = _req.get('postData').get('params') else: _data = _req.get('postData').get('text') # if 'mimeType' in _req.get('postData') and _req.get('postData').get('mimeType') == 'application/json': # _tmp = json.loads(_data) # _data = [] # for _tk, _tv in _tmp.items(): # _data.append({'name': _tk, 'value': _tv}) logger.debug(" - params: {}".format(_param)) logger.debug(" - data: {}".format(_data)) # extract all parameter values into variables, and keep {value} in parameters if isinstance(_param, (list, tuple, set)): for _item in _param: self.__har_extract(step_dict, _item['name'], _item['value'], 'params', auto_extract) else: # step_dict['request']['params'] = _param self.__har_extract(step_dict, '', _param, 'params', auto_extract) if isinstance(_data, (list, tuple, set)): for _item in _data: self.__har_extract(step_dict, _item['name'], _item['value'], 'data', auto_extract) else: # step_dict['request']['data'] = _data self.__har_extract(step_dict, '', _data, 'data', auto_extract) logger.debug(" - self.variables: {}".format(json.dumps(self.variables, ensure_ascii=False))) # get headers step_dict['request']['headers'] = {} self.__har_headers(_req.get('headers'), step_dict['request']['headers'], RECORD_HEADERS, auto_extract) logger.debug(" - headers: {}".format(json.dumps(step_dict['request']['headers'], ensure_ascii=False))) # get cookies step_dict['request']['cookies'] = {} self.__har_cookies(_req.get('cookies'), step_dict['request']['cookies'], auto_extract) logger.debug(" - cookies: {}".format(json.dumps(step_dict['request']['cookies'], ensure_ascii=False))) return True def __har_extract(self, step_dict, i_name, i_value, i_type, auto_extract=False): _value = i_value if format(_value) == _value and _value.startswith('{') and _value.endswith('}'): try: _value = json.loads(_value) if not isinstance(_value, dict): _value = i_value except json.decoder.JSONDecodeError: pass if isinstance(_value, dict): for _k, _v in _value.items(): if auto_extract and format(_v) in self.variables.keys(): if i_name: step_dict['config']['variables']["{}.{}".format(i_name, _k)] = '${' + self.variables[_v]['key'] + '}' else: step_dict['config']['variables']["{}".format(_k)] = '${' + self.variables[_v]['key'] + '}' self.variables[format(_v)]['flag'] = 1 else: if i_name: step_dict['config']['variables']["{}.{}".format(i_name, _k)] = _v else: step_dict['config']['variables']["{}".format(_k)] = _v if i_name: _value[_k] = '${' + "{}.{}".format(i_name, _k) + '}' else: _value[_k] = '${' + "{}".format(_k) + '}' if i_name: step_dict['request'][i_type][i_name] = json.dumps(_value, ensure_ascii=False) else: step_dict['request'][i_type] = json.dumps(_value, ensure_ascii=False) else: if auto_extract and format(_value) in self.variables.keys(): if i_name: step_dict['config']['variables'][i_name] = '${' + self.variables[_value]['key'] + '}' self.variables[_value]['flag'] = 1 else: if i_name: step_dict['config']['variables'][i_name] = _value if i_name: step_dict['request'][i_type][i_name] = '${' + "{}".format(i_name) + '}' # parse response block and make validations def __har_response(self, entry, step_dict, include, exclude, auto_extract=False): if not ('response' in entry.keys() and entry['response']): logger.warning(" * There is no response in this entry: {}".format(json.dumps(entry, ensure_ascii=False))) return False _rsp = entry['response'] # get status step_dict['response']['status'] = _rsp.get('status', 200) step_dict['validations'].append({"eq": {'status.code': step_dict['response']['status']}}) # get headers step_dict['response']['headers'] = {} self.__har_headers(_rsp.get('headers'), step_dict['response']['headers'], VALIDATE_HEADERS) __headers = get_all_kv_pairs(item=step_dict['response']['headers'], prefix='headers') _vin = get_matched_keys(key=include, keys=list(__headers.keys()), fuzzy=1) _vex = get_matched_keys(key=exclude, keys=list(__headers.keys()), fuzzy=1) if exclude else [] for _k, _v in step_dict['response']['headers'].items(): _k = "headers.{}".format(_k) # Extracting temporary variables for automatic identification of interface dependencies if auto_extract and isinstance(_v, str) and len(_v) >= IDENTIFY_LEN: if _v not in self.variables.keys(): self.variables[_v] = { 'key': _k, 'flag': 0 } step_dict['response']['extract'][_v] = _k if _k in _vin and _k not in _vex: step_dict['validations'].append({"eq": {_k: _v}}) logger.debug(" - self.variables: {}".format(json.dumps(self.variables, ensure_ascii=False))) # get cookies step_dict['response']['cookies'] = {} self.__har_cookies(_rsp.get('cookies'), step_dict['response']['cookies']) # get content try: _text = _rsp.get('content').get('text', '') _mime = _rsp.get('content').get('mimeType') or '' _code = _rsp.get('content').get('encoding') except AttributeError: logger.warning(" * Invalid response content: {}".format(_rsp.get('content'))) return False if _code and _code == 'base64': try: _text = base64.b64decode(_text).decode('utf-8') except UnicodeDecodeError as e: logger.warning(" * Decode error: {}".format(e)) elif _code: logger.warning(" * Unsupported encoding method: {}".format(_code)) return False logger.debug(" - mimeType: {}, encoding: {}".format(_mime, _code)) logger.debug(" - content text: {}".format(_text)) if _mime.startswith('application/json'): # json => dict try: step_dict['response']['content'] = json.loads(_text) # extract all content values into validations logger.debug(" - validation include: {}, exclude: {}".format(include, exclude)) _pairs = get_all_kv_pairs(item=json.loads(_text), prefix='content')
<filename>tefla/core/eval_metrices.py<gh_stars>10-100 """ Evaluation API for evaluation matrices and plots, supports classification and regression both. """ import math from ast import literal_eval from collections import defaultdict, Counter from statistics import mean import numpy as np import pandas as pd from sklearn import metrics from sklearn.preprocessing import MultiLabelBinarizer from bokeh.models import BasicTicker, ColorBar, LinearColorMapper, ColumnDataSource, Whisker from bokeh.plotting import figure from bokeh.transform import factor_cmap from tefla.utils import quadratic_weighted_kappa as qwk def calc_acc(true_pos, true_neg, false_pos, false_neg): """ function to calculate accuracy. Args: true_pos: Number of true positives true_neg: Number of true negatives false_pos: Number of false positives false_neg: Number of false negatives Returns: None """ try: acc = (true_pos + true_neg) / \ float(true_pos + true_neg + false_neg + false_pos) return round(acc, 3) except BaseException: return None def calc_recall(true_pos, false_neg): """ function to calculate recall/sensitivity/true positive rate Args: true_pos: Number of true positives false_pos: Number of false positives Returns: None """ try: recall = true_pos / float(true_pos + false_neg) return round(recall, 3) except BaseException: return None def calc_precision(true_pos, false_pos): """ function to calculate precision Args: true_pos: Number of true positives false_pos: Number of false positives Returns: None """ try: prec = true_pos / float(true_pos + false_pos) return round(prec, 3) except BaseException: return None def calc_specificity(true_neg, false_pos): """ function to calculate specificity/true negative rate Args: true_neg: Number of true negatives false_pos: Number of false positives Returns: None """ try: spec = true_neg / float(true_neg + false_pos) return round(spec, 3) except BaseException: return None def calc_f1score(true_pos, false_pos, false_neg): """ function to calculate f1_score Args: true_pos: Number of true positives false_pos: Number of false positives false_neg: Number of false negatives Returns: None """ try: f1score = (2 * true_pos) / float(2 * true_pos + false_neg + false_pos) return round(f1score, 3) except BaseException: return None def calc_npv(true_neg, false_neg): """ function to calculate negative predictive value Args: true_neg: Number of true negatives false_neg: Number of false negatives Returns: None """ try: npv = true_neg / float(true_neg + false_neg) return round(npv, 3) except BaseException: return None def calc_fnr(false_neg, true_pos): """ function to calculate false negative rate Args: true_pos: Number of true positives false_neg: Number of false negatives Returns: None """ try: fnr = false_neg / float(true_pos + false_neg) return round(fnr, 3) except BaseException: return None def calc_fpr(false_pos, true_neg): """ function to calculate false positve rate Args: true_neg: Number of true negatives false_pos: Number of false positives Returns: None """ try: fpr = false_pos / float(true_neg + false_pos) return round(fpr, 3) except BaseException: return None def calc_fdr(true_pos, false_pos): """ function to calculate false discovery rate Args: true_pos: Number of true positives false_pos: Number of false positives Returns: None """ try: fdr = false_pos / float(true_pos + false_pos) return round(fdr, 3) except BaseException: return None def calc_for(false_neg, true_neg): """ function to calculate false positve rate Args: true_neg: Number of true negatives false_neg: Number of false negatives Returns: None """ try: fomr = false_neg / float(false_neg + true_neg) return round(fomr, 3) except BaseException: return None def calc_mcc(true_pos, true_neg, false_pos, false_neg): """ funcrtion to calculate matthews correlation coefficient Args: true_pos: Number of true positives true_neg: Number of true negatives false_pos: Number of false positives false_neg: Number of false negatives Returns: None """ try: temp_var1 = (true_pos * true_neg - false_pos * false_neg) temp_var2 = math.sqrt((true_pos + false_pos) * (true_pos + false_neg) * (true_neg + false_pos) * (true_neg + false_neg)) mcc = temp_var1 / float(temp_var2) return round(mcc, 3) except BaseException: return None def calc_kappa(truth, pred): """ funcrtion to calculate cohen's kappa coefficient Args: truth: Collections of truth labels pred: Collections of prediction labels Returns: None """ try: kappa = qwk.calculate_kappa(truth, pred) return round(kappa, 3) except BaseException: return None def calc_mae(truth, pred): """ function to calculate mean absolute error Args: truth: Collections of truth labels pred: Collections of prediction labels Returns: None """ try: mae = mean([abs(truth[i] - pred[i]) for i in range(0, len(truth))]) return round(mae, 3) except BaseException: return None def calc_mse(truth, pred): """ function to calculate mean squared error Args: truth: Collections of truth labels pred: Collections of prediction labels Returns: None """ try: mse = mean([pow(truth[i] - pred[i], 2) for i in range(0, len(truth))]) return round(mse, 3) except BaseException: return None def calc_rmse(truth, pred): """ function to calculate mean squared error Args: truth: Collections of truth labels pred: Collections of prediction labels Returns: None """ try: rmse = pow(mean([pow(truth[i] - pred[i], 2) for i in range(0, len(truth))]), 0.5) return round(rmse, 3) except BaseException: return None def plot_conf_mat(conf_mat, classes): """ This method plots confusion matrix. Args: conf_mat: Cnfusion matrix array classes: Class list Returns: bokeh plot object """ mapper = LinearColorMapper(palette='Blues9', low=conf_mat.min(), high=conf_mat.max()) fig = figure( title="confusion matrix", x_axis_label="predicted", y_axis_label="Actual", x_range=[str(cls) for cls in classes], y_range=[str(cls) for cls in classes], tooltips=[("value", "@image")]) fig.image(image=[conf_mat], x=0, y=0, dw=len(classes), dh=len(classes), palette='Blues9') color_bar = ColorBar( color_mapper=mapper, location=(0, 0), ticker=BasicTicker(desired_num_ticks=9)) fig.add_layout(color_bar, 'right') return fig class Evaluation(): """ This is a base class for evaluation. """ # pylint: disable=too-many-instance-attributes def __init__(self): self.eval_result = {} self.ids = [] self.pred = [] self.truth = [] self.pred_max = self.pred self.ensemble = False self.multilabel = False self.eval_plots = [] self.classes = [] def read_data(self, truth_file, pred_files): """ This method reads the data from provided csv files for truth and predication. Args: truth_file: A file containing ids and truth annotations. pred_files: A list of files containing ids and prediction annotations. Raises: At least 2 columns are required, if number of columns in the provided csv file are less then 2. Return: None. """ self.ensemble = len(pred_files) > 1 file_data = pd.read_csv(truth_file) if len(file_data.columns) < 2: raise ValueError("At least 2 columns are required") for i in pred_files: pred_data = pd.read_csv(i) if len(pred_data.columns) < 2: raise ValueError("At least 2 columns are required") if len(pred_data.columns) > 2: self.classes = pred_data.columns[1:].tolist() pred_data['Pred'] = pred_data[pred_data.columns[1:]].replace( '', 0).stack().groupby(level=0).apply(list) pred_data = pred_data[[pred_data.columns[0], 'Pred']] file_data = file_data.merge(pred_data, on=file_data.columns[0], how="inner") if len(file_data.columns) > 3: self.pred = np.array([file_data.iloc[:, i] for i in range(2, len(file_data.columns))]) else: self.pred = np.array(file_data.iloc[:, 2].tolist()) self.truth = np.array(file_data.iloc[:, 1]) self.ids = np.array(file_data.iloc[:, 0]) if isinstance(self.truth[0], type("str")) and '[' in self.truth[0]: self.multilabel = True else: self.multilabel = False # pylint: disable-msg=too-many-arguments # pylint: disable-msg=too-many-locals # pylint: disable-msg=too-many-statements # pylint: disable-msg=too-many-branches def eval_classification(self, truth_file, pred_files, eval_list, plot_list, over_all=False, ensemble_voting="soft", ensemble_weights=None, class_names=None, convert_binary=False, binary_threshold=None): """ This function calculates the evaluation measures required by the user for classification problems. Args: truth_file: A csv file containing ids and truth annotations. pred_files: A list of csv files containing ids and prediction annotations. eval_list: A list of evaluation measures. plot_list: A list of evaluation plots. over_all: if class wise results are required or overall result, in case of multiclass classification, default false. ensemble_voting: Type of voting in case of multiple prediction(soft/hard) default soft. ensemble_weights: Weights for each class in case of ensemble, default None. calss_names: An array containing class names, default None. convert_binary: If multiclass predictions should be evaluated as binary problem (normal vs abnormal)first value should represent probability of normal class. binary_threshold: threshold to be used in case of multiclass to binary conversion. Returns: A dictionary containing evaluation result. Raises: "Invalid evaluation term" if a term is not present in supported list. """ self.eval_result = {} self.classes = None self.eval_plots = [] self.read_data(truth_file, pred_files) eval_list = [element.strip().lower() for element in eval_list] if self.ensemble: self.eval_ensemble(ensemble_voting, ensemble_weights) if self.multilabel: self.truth = np.array([literal_eval(p) for p in self.truth]) self.pred = np.array([literal_eval(p) for p in self.pred]) classes = self.classes if class_names: classes = class_names if isinstance(self.truth[0], type("str")): self.truth = np.array([classes.index(tval) for tval in self.truth]) if not self.multilabel: if len(self.pred.shape) > 1 and convert_binary and binary_threshold: self.pred_max = np.array([0 if prd_n[0] >= binary_threshold else 1 for prd_n in self.pred]) self.truth = np.array([1 if truth_n != 0 else truth_n for truth_n in self.truth]) classes = [self.classes[0], '!' + self.classes[0]] elif len(self.pred.shape) > 1: self.pred_max = np.argmax(self.pred, axis=1) else: self.pred_max = self.pred conf_matrix = metrics.confusion_matrix(self.truth, self.pred_max) true_pos = [0] * len(classes) false_pos = [0] * len(classes) false_neg = [0] * len(classes) true_neg = [0] * len(classes) col_sum = np.sum(conf_matrix, axis=0) row_sum = np.sum(conf_matrix, axis=1) cum_sum = np.sum(conf_matrix) for k in range(0, len(classes)): true_pos[k] += conf_matrix[k, k] false_pos[k] += col_sum[k]
# coding: utf-8 """ cloudFPGA Resource Manager API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 0.8 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from swagger_client.api_client import ApiClient class DebugApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def cf_manager_rest_api_delete_debug_connection(self, username, password, instance_id, **kwargs): # noqa: E501 """Deletes an existing connection to the `hw_server` of this instance # noqa: E501 This deletes the *connection to the* `hw_server`. This **does not imply** that the `hw_server` itself is stopped too. The `hw_server` is only stopped if there is no other open debug connection to the connected JTAG probe (some probes are connected to a JTAG chain). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.cf_manager_rest_api_delete_debug_connection(username, password, instance_id, async_req=True) >>> result = thread.get() :param async_req bool :param str username: OpenStack username (required) :param str password: OpenStack password (required) :param str instance_id: ROLE instance unique identifier (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.cf_manager_rest_api_delete_debug_connection_with_http_info(username, password, instance_id, **kwargs) # noqa: E501 else: (data) = self.cf_manager_rest_api_delete_debug_connection_with_http_info(username, password, instance_id, **kwargs) # noqa: E501 return data def cf_manager_rest_api_delete_debug_connection_with_http_info(self, username, password, instance_id, **kwargs): # noqa: E501 """Deletes an existing connection to the `hw_server` of this instance # noqa: E501 This deletes the *connection to the* `hw_server`. This **does not imply** that the `hw_server` itself is stopped too. The `hw_server` is only stopped if there is no other open debug connection to the connected JTAG probe (some probes are connected to a JTAG chain). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.cf_manager_rest_api_delete_debug_connection_with_http_info(username, password, instance_id, async_req=True) >>> result = thread.get() :param async_req bool :param str username: OpenStack username (required) :param str password: OpenStack password (required) :param str instance_id: ROLE instance unique identifier (required) :return: None If the method is called asynchronously, returns the request thread. """ all_params = ['username', 'password', 'instance_id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method cf_manager_rest_api_delete_debug_connection" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'username' is set if ('username' not in params or params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `cf_manager_rest_api_delete_debug_connection`") # noqa: E501 # verify the required parameter 'password' is set if ('password' not in params or params['password'] is None): raise ValueError("Missing the required parameter `password` when calling `cf_manager_rest_api_delete_debug_connection`") # noqa: E501 # verify the required parameter 'instance_id' is set if ('instance_id' not in params or params['instance_id'] is None): raise ValueError("Missing the required parameter `instance_id` when calling `cf_manager_rest_api_delete_debug_connection`") # noqa: E501 collection_formats = {} path_params = {} if 'instance_id' in params: path_params['instance_id'] = params['instance_id'] # noqa: E501 query_params = [] if 'username' in params: query_params.append(('username', params['username'])) # noqa: E501 if 'password' in params: query_params.append(('password', params['password'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/debug/ila_connection/{instance_id}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def cf_manager_rest_api_get_all_debug_connections(self, username, password, **kwargs): # noqa: E501 """Requests a list of running `hw_server`s on all instances (admin only) # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.cf_manager_rest_api_get_all_debug_connections(username, password, async_req=True) >>> result = thread.get() :param async_req bool :param str username: OpenStack username (required) :param str password: OpenStack password (required) :return: list[InlineResponse2003] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.cf_manager_rest_api_get_all_debug_connections_with_http_info(username, password, **kwargs) # noqa: E501 else: (data) = self.cf_manager_rest_api_get_all_debug_connections_with_http_info(username, password, **kwargs) # noqa: E501 return data def cf_manager_rest_api_get_all_debug_connections_with_http_info(self, username, password, **kwargs): # noqa: E501 """Requests a list of running `hw_server`s on all instances (admin only) # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.cf_manager_rest_api_get_all_debug_connections_with_http_info(username, password, async_req=True) >>> result = thread.get() :param async_req bool :param str username: OpenStack username (required) :param str password: OpenStack password (required) :return: list[InlineResponse2003] If the method is called asynchronously, returns the request thread. """ all_params = ['username', 'password'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method cf_manager_rest_api_get_all_debug_connections" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'username' is set if ('username' not in params or params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `cf_manager_rest_api_get_all_debug_connections`") # noqa: E501 # verify the required parameter 'password' is set if ('password' not in params or params['password'] is None): raise ValueError("Missing the required parameter `password` when calling `cf_manager_rest_api_get_all_debug_connections`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] if 'username' in params: query_params.append(('username', params['username'])) # noqa: E501 if 'password' in params: query_params.append(('password', params['password'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/debug/open_ila_connections', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[InlineResponse2003]', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def cf_manager_rest_api_get_all_debug_connections_of_user(self, username, password, **kwargs): # noqa: E501 """Returns all open `hw_server` of a user # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.cf_manager_rest_api_get_all_debug_connections_of_user(username, password, async_req=True) >>> result = thread.get() :param async_req bool :param str username: OpenStack username (required) :param str password: OpenStack password (required) :return: list[InlineResponse2003] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.cf_manager_rest_api_get_all_debug_connections_of_user_with_http_info(username, password, **kwargs) # noqa: E501 else: (data) = self.cf_manager_rest_api_get_all_debug_connections_of_user_with_http_info(username, password, **kwargs) # noqa: E501 return data def cf_manager_rest_api_get_all_debug_connections_of_user_with_http_info(self, username, password, **kwargs): # noqa: E501 """Returns all open `hw_server` of a user # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.cf_manager_rest_api_get_all_debug_connections_of_user_with_http_info(username, password, async_req=True) >>> result = thread.get() :param async_req bool :param str username: OpenStack username (required) :param str password: OpenStack password (required) :return: list[InlineResponse2003] If the method is called asynchronously, returns the request thread. """ all_params = ['username', 'password'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method cf_manager_rest_api_get_all_debug_connections_of_user" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'username' is set if ('username' not in params or params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `cf_manager_rest_api_get_all_debug_connections_of_user`") # noqa: E501 # verify the required parameter 'password' is set if ('password' not in params or params['password'] is None): raise ValueError("Missing the required parameter `password` when calling `cf_manager_rest_api_get_all_debug_connections_of_user`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] if 'username' in params: query_params.append(('username', params['username'])) # noqa: E501 if 'password' in params: query_params.append(('password', params['password'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/debug/ila_connections', 'GET',
<filename>workflows/segmine/library.py ''' Segmine library. @author: <NAME> <<EMAIL>> ''' from biomine import BiomineSearch from segs import Segs import logging # # Visualization widgets: # def segmine_rank_plotter(input_dict): return {} def segmine_biomine_visualizer(input_dict): return {'graph' : input_dict.get('graph', None)} # # Interactions widgets: # def segmine_rule_browser(input_dict): return {'node_list' : []} def segmine_rule_browser_finished(postdata, input_dict, output_dict): rules = input_dict['rules'] widget_id = postdata.get('widget_id')[0] selectedCell = postdata.get('selectedCell')[0] node_list = [] if selectedCell: key, _, idx = selectedCell.split('_') rule = rules[int(idx)] if key == 'terms': terms = rule['description']['terms'] + \ rule['description']['interactingTerms'] node_list.extend([term['termID'] for term in terms]) elif key in ['coveredGenes', 'coveredTopGenes']: genes = ['EntrezGene:%s' % gene for gene in rule[key]] node_list.extend(genes) return {'node_list' : node_list} def segmine_fc_gene_filter_finished(postdata, input_dict, output_dict): from orngBioinformatics import obiExpression as rankers import orange dataset = input_dict['dataset'] widget_id = postdata.get('widget_id')[0] fc_threshold = float(postdata.get('fc_threshold%s' % widget_id)[0]) targets = map(str, postdata.get('target%s' % widget_id)) ranker = rankers.ExpressionSignificance_FoldChange(dataset, False) ranks = ranker(target=targets if len(targets)>1 else targets[0]) new_domain = orange.Domain([att for att, fc in ranks if fc >= fc_threshold], dataset.domain.classVar) reduced_dataset = orange.ExampleTable(new_domain, dataset) return {'dataset' : reduced_dataset} def segmine_ttest_gene_filter_finished(postdata, input_dict, output_dict): from orngBioinformatics import obiExpression as rankers import orange dataset = input_dict['dataset'] widget_id = postdata.get('widget_id')[0] pvalue_threshold = float(postdata.get('pvalue_threshold%s' % widget_id)[0]) targets = map(str, postdata.get('target%s' % widget_id)) ranker = rankers.ExpressionSignificance_TTest(dataset, False) ranks = ranker(target=targets if len(targets)>1 else targets[0]) filter_atts = [att for att, (t, pval) in ranks if pval <= pvalue_threshold] new_domain = orange.Domain(filter_atts, dataset.domain.classVar) reduced_dataset = orange.ExampleTable(new_domain, dataset) return {'dataset' : reduced_dataset} # # Regular widgets: # def segmine_ttest_gene_filter(input_dict): return {'dataset' : None} def segmine_fc_gene_filter(input_dict): return {'dataset' : None} def segmine_gene_ranker(input_dict, widget): import orange from numpy import mean, var from math import sqrt, floor CONTROL_GROUP_KEY = 'control group' DATA_GROUP_KEY = 'data group' CLASS_ATRR_NAME = 'group' table = input_dict['microarrayTable'] k = int(input_dict['k']) m = int(input_dict['m']) if m == 0: # special value m= -1 # all examples ranks = [] # ReliefF parameters: # - number of neighbours: 10 # - number of reference examples: all (-1) # - checksum computation: none (the data do not change) ranker = orange.MeasureAttribute_relief(k=k, m=m, checkCachedData=False) for attr in table.domain.attributes: ranks.append((ranker(attr, table), attr.name)) # tuples are sorted according to the first element, # here, this is attribute's quality ranks.sort(reverse=True) # reverse order inside sorted tuples list in result geneRanks = [(elt[1], elt[0]) for elt in ranks] tScores = {} control = table.selectref({CLASS_ATRR_NAME:CONTROL_GROUP_KEY}) data = table.selectref({CLASS_ATRR_NAME:DATA_GROUP_KEY}) nerrors = 0 widget.progress = 0 widget.save() for i, attr in enumerate(table.domain.attributes): geneID = attr.name controlValues = [float(example[attr]) for example in control] dataValues = [float(example[attr]) for example in data] try: average = mean(dataValues) - mean(controlValues) variance = var(controlValues)/len(controlValues) + \ var(dataValues)/len(dataValues) score = average/sqrt(variance) tScores[geneID] = score except ZeroDivisionError: tScores[geneID] = 0.0 if (i + 1)%100 == 0: widget.progress = floor((i + 1)/float(len(table.domain.attributes))*100) widget.save() widget.progress = 100 widget.save() sortedTScores = sorted(tScores.items(), reverse=True, key=lambda x: x[1]) return {'geneRanks': geneRanks, 'tScores': sortedTScores} def segmine_segs(input_dict, widget): segs = Segs(input_dict['wsdl']) results = segs.run(input_dict, widget=widget) return {'rules_fisher' : results.get('rules_fisher', None), 'rules_PAGE' : results.get('rules_PAGE', None), 'rules_GSEA' : results.get('rules_GSEA', None), 'rules_combined' : results.get('rules_combined', None)} def segmine_segs_stu(input_dict, widget): segs = Segs(input_dict['wsdl']) results = segs.run_STU(input_dict, widget=widget) return {'rules_fisher': results.get('rules_fisher', None), 'rules_PAGE': results.get('rules_PAGE', None), 'rules_GSEA': results.get('rules_GSEA', None), 'rules_combined': results.get('rules_combined', None)} def segmine_segs_ath(input_dict, widget): segs = Segs(input_dict['wsdl']) results = segs.run_ATH(input_dict, widget=widget) return {'rules_fisher': results.get('rules_fisher', None), 'rules_PAGE': results.get('rules_PAGE', None), 'rules_GSEA': results.get('rules_GSEA', None), 'rules_combined': results.get('rules_combined', None)} def segmine_resolve_gene_synonyms(input_dict): from .data import mappings gene_ranks = input_dict['gene_ranks'] unknown = 0 ndup = 0 mapped = [] genes = {} for (i, (geneID, rank)) in enumerate(gene_ranks): # gene name can also be symbolic or synonym geneID = geneID.lower() try: entrezID = int(geneID) except ValueError: if geneID in mappings.symbol2entrez: entrezID = mappings.symbol2entrez[geneID] elif geneID in mappings.synonyms2entrez: entrezID = mappings.synonyms2entrez[geneID] else: unknown += 1 continue if entrezID in genes: ndup += 1 continue else: mapped.append((str(entrezID), rank)) genes[entrezID] = None return {'gene_ranks': mapped} def segmine_biomine_neighbourhood(input_dict): groupNodes = input_dict.get('groupNodes', False) singleComponent = input_dict.get('singleComponent', False) maxNodes = int(input_dict.get('maxNodes', 0)) startNodes = input_dict.get('startNodes', None) databaseVersion = input_dict.get('databaseVersion') search = BiomineSearch(groupNodes=groupNodes, singleComponent=singleComponent, maxNodes=maxNodes, startNodes=startNodes, databaseVersion=databaseVersion) result, bestPath = search.invokeBiomine() return {'result' : result, 'bestPath' : bestPath} def segmine_biomine_connection(input_dict): groupNodes = input_dict.get('groupNodes', False) singleComponent = input_dict.get('singleComponent', False) maxNodes = int(input_dict.get('maxNodes', 0)) startNodes = input_dict.get('startNodes', None) endNodes = input_dict.get('endNodes', None) databaseVersion = input_dict.get('databaseVersion') search = BiomineSearch(groupNodes=groupNodes, singleComponent=singleComponent, maxNodes=maxNodes, startNodes=startNodes, endNodes=endNodes, databaseVersion=databaseVersion) result, bestPath = search.invokeBiomine() return {'result' : result, 'bestPath' : bestPath} def segmine_biomine_medoid(input_dict): groupNodes = input_dict.get('groupNodes', False) singleComponent = input_dict.get('singleComponent', False) maxNodes = int(input_dict.get('maxNodes', 0)) startNodes = input_dict.get('startNodes', None) databaseVersion = input_dict.get('databaseVersion') search = BiomineSearch(groupNodes=groupNodes, singleComponent=singleComponent, maxNodes=maxNodes, medoids=True, startNodes=startNodes, databaseVersion=databaseVersion) result, bestPath = search.invokeBiomine() return {'result' : result, 'bestPath' : bestPath} def segmine_mirna_to_gene_tarbase(input_dict): import cPickle from os.path import normpath, join, dirname mirna_ranks = input_dict['mirna_ranks'] mirna2gene = cPickle.load(open(normpath(join(dirname(__file__), 'data/mirna2gene_tarbase')),'rb')) result = {} unknown = 0 for (rna, rank) in mirna_ranks: rna = rna.lower() if rna not in mirna2gene: unknown += 1 continue for gene in mirna2gene[rna]: if gene not in result: result[gene] = rank else: result[gene] += rank #end # if unknown: # self.warning('%d unknown miRNA were found and ignored!' % unknown) result = sorted([(pair[1], pair[0]) for pair in result.items()], reverse=True) result = [(str(pair[1]), pair[0]) for pair in result] return {'gene_ranks': result} #end def segmine_mirna_to_gene_targetscan(input_dict): import cPickle from os.path import normpath, join, dirname mirna_ranks = input_dict['mirna_ranks'] mirna2gene = cPickle.load(open(normpath(join(dirname(__file__), 'data/mirna2gene_targetscan')),'rb')) result = {} unknown = 0 for (rna, rank) in mirna_ranks: rna = rna.lower() if rna not in mirna2gene: unknown += 1 continue for gene in mirna2gene[rna]: if gene not in result: result[gene] = rank else: result[gene] += rank #end # if unknown: # self.warning('%d unknown miRNA were found and ignored!' % unknown) result = sorted([(pair[1], pair[0]) for pair in result.items()], reverse=True) result = [(str(pair[1]), pair[0]) for pair in result] return {'gene_ranks': result} #end def __makeExampleTable(namesDict, data): import orange from constants import CLASS_ATRR_NAME, CONTROL_GROUP_KEY, DATA_GROUP_KEY geneIDs = sorted(data.keys()) attrList = [orange.FloatVariable(name=str(geneID)) for geneID in geneIDs] classAttr = orange.EnumVariable(name=CLASS_ATRR_NAME, values = [CONTROL_GROUP_KEY, DATA_GROUP_KEY]) domain = orange.Domain(attrList, classAttr) table = orange.ExampleTable(domain) # first half: group 1 for attrName in namesDict[CONTROL_GROUP_KEY].keys(): exampleValues = [data[geneID][CONTROL_GROUP_KEY][attrName] for geneID in geneIDs] + [CONTROL_GROUP_KEY] example = orange.Example(domain, exampleValues) table.append(example) # second half: group 2 for attrName in namesDict[DATA_GROUP_KEY].keys(): exampleValues = [data[geneID][DATA_GROUP_KEY][attrName] for geneID in geneIDs] + [DATA_GROUP_KEY] example = orange.Example(domain, exampleValues) table.append(example) return table #end def segmine_read_microarray_data(input_dict): from numpy import mean import math from constants import CLASS_ATRR_NAME, CONTROL_GROUP_KEY, DATA_GROUP_KEY, DEFAULT_CONTROL_GROUP_ID data = open(input_dict['file']).read() dataFormat = 'linear' if int(input_dict['idf']) == 1 else 'log2' calcMethod = 'ratio' if int(input_dict['cm']) == 1 else 'difference' lines = [x.replace(',', ' ').split() for x in data.splitlines()] names = lines[0][1:] # skip name of gene column # find the prefix of the data channel (the first group prefix is fixed in advance) pfs = set() for name in names: pfs.add(name[0]) if len(pfs) != 2: raise ValueError('Invalid data header: more than two prefixes found: %s' % str(list(pfs))) # if the data do not obey the default rule, the first character of the first column # is the identifier of the first group if DEFAULT_CONTROL_GROUP_ID not in pfs: CONTROL_GROUP_ID = names[0][0] else: CONTROL_GROUP_ID = DEFAULT_CONTROL_GROUP_ID pfs.remove(CONTROL_GROUP_ID) DATA_GROUP_ID = list(pfs)[0] # collect positions of column names for both groups firstGroupNames = [] secondGroupNames = [] for name in names: if name.startswith(CONTROL_GROUP_ID): firstGroupNames.append(name) elif name.startswith(DATA_GROUP_ID): secondGroupNames.append(name) #end controlGroupNames = firstGroupNames dataGroupNames = secondGroupNames # collect positions of column names for both groups controlGroupNames = dict.fromkeys(controlGroupNames) dataGroupNames = dict.fromkeys(dataGroupNames) for name in controlGroupNames: controlGroupNames[name] = names.index(name) for name in dataGroupNames: dataGroupNames[name] = names.index(name) # parse and store the actual data # read values data = {} ndup = 0 ln = 0 #refresh = (len(self.lines)-1) / 10 #self.progressBar = ProgressBar(self, iterations=25) for elts in lines[1:]: ln += 1 #if ln%refresh == 0: #self.progressBar.advance() if len(elts) != len(names)+1: # EntrezID is the first value raise ValueError('Wrong number of values, line: %d' % ln) try: geneID = str(elts[0]) vals = [float(x) for x in elts[1:]] except Exception, e: raise ValueError('Error while reading values, line: %d' % ln) else: if data.has_key(geneID): ndup += 1 else: # init storage data[geneID] = {} data[geneID][CONTROL_GROUP_KEY] = {} data[geneID][DATA_GROUP_KEY] = {} for atrName in controlGroupNames.keys(): data[geneID][CONTROL_GROUP_KEY][atrName] = [] for atrName in dataGroupNames.keys(): data[geneID][DATA_GROUP_KEY][atrName] = [] # get values for first group
for distance, meters/second for speed etc if not isinstance(reference_speed, speed_type): reference_speed = reference_speed * speed if not isinstance(reference_height, distance_type): reference_height = reference_height * distance if not isinstance(aerodynamic_roughness, distance_type): aerodynamic_roughness = aerodynamic_roughness * distance if debug: print(reference_speed) print(reference_height) print(aerodynamic_roughness) u_star = (reference_speed * k) / (np.log((reference_height + aerodynamic_roughness) / aerodynamic_roughness)) if return_without_units: u_star = np.array(u_star) return u_star def i_eurocode(unit, height, aerodynamic_roughness, return_without_units=True, debug=False): ''' Take reference values, return wind speeds at given height(s). Parameters ---------- height : float or np.array().astype(float64) or pint.quantity.build_quantity_class.<locals>.Quantity The heights in which to return the velocity results at, this can be an array, or a single value. If no dimenson is supplied we assume meters. aerodynamic_roughness : float or pint.quantity.build_quantity_class.<locals>.Quantity The aerodynamic roughness of the AbL profile. return_without_units : bool. True returns the numpy array as a numpy array without units assuming the unit is default SI, this makes it harder to convert if using other units. debug : bool, optional Returns more detail in the command line, more functionality to be added later. The default is False. Returns ------- i : np.array().astype(float64) or pint.quantity.build_quantity_class.<locals>.Quantity The intensity at specified height or heights. ''' # return expected dimensional unit types distance = 1 * unit.meter distance_type = type(distance) # Check if the inputs have units, if not, assume the units are # default SI units, i.e. meters for distance, meters/second for speed etc if not isinstance(aerodynamic_roughness, distance_type): aerodynamic_roughness = aerodynamic_roughness * distance if not isinstance(height, distance_type): height = height * distance if debug: print(aerodynamic_roughness) print(height) i = 1 / np.log(height / aerodynamic_roughness) zmin = get_eurocode_minimum_height(unit, aerodynamic_roughness) i[height < zmin] = 1 / np.log(zmin / aerodynamic_roughness) # If a raw numpy array is needed, we can simply ask for the same array # stripped of its units if return_without_units: i = np.array(i) return i def tke_derived(unit, u, intensity, return_without_units=True, debug=False): ''' Take reference values, return TKE at given height(s). Parameters ---------- u : np.array().astype(float64) or pint.quantity.build_quantity_class.<locals>.Quantity The height dependent streamwise wind speed. intensity : np.array().astype(float64) or pint.quantity.build_quantity_class.<locals>.Quantity The height dependent turbulent intensity. return_without_units : bool. True returns the numpy array as a numpy array without units assuming the unit is default SI, this makes it harder to convert if using other units. debug : bool, optional Returns more detail in the command line, more functionality to be added later. The default is False. Returns ------- tke : np.array().astype(float64) or pint.quantity.build_quantity_class.<locals>.Quantity The turbulent kinetic energy as a function of height. ''' # check there is data if u.size == 0: raise OrderError("set_tke", "Error: define the wind speed profile first using set_streamwise_speed(method)") if intensity.size == 0: raise OrderError("set_tke", "Error: define the intensity profile first using set_streamwise_speed(method)") # return expected dimensional unit types speed = 1 * unit.meter / unit.second speed_type = type(speed) dimensionless = 1 * unit.meter / unit.meter dimensionless_type = type(dimensionless) # Check if the inputs have units, if not, assume the units are # default SI units, i.e. meters for distance, meters/second for speed etc if not isinstance(u, speed_type): u = u * speed if not isinstance(intensity, dimensionless_type): intensity = intensity * dimensionless_type if debug: print(u) print(intensity) tke = (3 / 2) * (u * intensity) ** 2 # If a raw numpy array is needed, we can simply ask for the same array # stripped of its units if return_without_units: tke = np.array(tke) return tke def tke_uniform(unit, height, tke, return_without_units=True, debug=False): ''' Take reference values, return TKE at given height(s). Parameters ---------- height : np.array().astype(float64) or pint.quantity.build_quantity_class.<locals>.Quantity The heights in which to return the velocity results at, this can be an array, or a single value. If no dimenson is supplied we assume meters. tke : float or pint.quantity.build_quantity_class.<locals>.Quantity A value of TKE for the uniform velocity profile. return_without_units : bool, optional True returns the numpy array as a numpy array without units assuming the unit is default SI, this makes it harder to convert if using other units.. The default is True. debug : bool, optional Returns more detail in the command line, more functionality to be added later. The default is False.. The default is False. Returns ------- tke : np.array().astype(float64) or pint.quantity.build_quantity_class.<locals>.Quantity The turbulent kinetic energy as a function of height. ''' # return expected dimensional unit types distance = 1 * unit.meter distance_type = type(distance) energy = 1 * unit.meter ** 2 / unit.second ** 2 tke_type = type(energy) if not isinstance(height, distance_type): height = height * distance if not isinstance(tke, tke_type): tke = tke * tke_type if debug: print(height) ones = np.ones(len(height)) tke = (ones * tke) # If a raw numpy array is needed, we can simply ask for the same array # stripped of its units if return_without_units: tke = np.array(tke) return tke def tke_YGCJ(unit, reference_speed, reference_height, height, aerodynamic_roughness, c1, c2, return_without_units=True, debug=False): ''' Take reference values, return TKE at given heights. Expression generalisations to allow height variation for turbulence quantities (tag:YGCJ): <NAME>., <NAME>., <NAME>., & <NAME>. (2009). New inflow boundary conditions for modelling the neutral equilibrium atmospheric boundary layer in computational wind engineering. J. of Wind Engineering and Industrial Aerodynamics, 97(2), 88-95. DOI:10.1016/j.jweia.2008.12.001 Parameters ---------- reference_speed : float or pint.quantity.build_quantity_class.<locals>.Quantity The reference speed taken at the reference height, usually taken to be 10m in SimScale. If no dimenson is supplied we assume meters per second. reference_height : float or pint.quantity.build_quantity_class.<locals>.Quantity The height in which we measure the reference speed, usually taken to be 10m/s in SimScale. If no dimenson is supplied we assume meters. height : float or np.array().astype(float64) or pint.quantity.build_quantity_class.<locals>.Quantity The heights in which to return the velocity results at, this can be an array, or a single value. If no dimenson is supplied we assume meters. aerodynamic_roughness : float or pint.quantity.build_quantity_class.<locals>.Quantity The aerodynamic roughness of the AbL profile. c1 : float fitting coefficient 1 c2 : float fitting coefficient 2 return_without_units : bool. True returns the numpy array as a numpy array without units assuming the unit is default SI, this makes it harder to convert if using other units. debug : bool, optional Returns more detail in the command line, more functionality to be added later. The default is False. Returns ------- u : np.array().astype(float64) or pint.quantity.build_quantity_class.<locals>.Quantity the velocity at specified height or heights. ''' # return expected dimensional unit types distance = 1 * unit.meter distance_type = type(distance) speed = 1 * unit.meter / unit.second speed_type = type(speed) # Check if the inputs have units, if not, assume the units are # default SI units, i.e. meters for distance, meters/second for speed etc if not isinstance(reference_speed, speed_type): reference_speed = reference_speed * speed if not isinstance(reference_height, distance_type): reference_height = reference_height * distance if not isinstance(aerodynamic_roughness, distance_type): aerodynamic_roughness = aerodynamic_roughness * distance if not isinstance(height, distance_type): height = height * distance if debug: print(reference_speed) print(reference_height) print(aerodynamic_roughness) print(height) u_star = calulate_u_star(unit, reference_speed, reference_height, aerodynamic_roughness, return_without_units=False) cmu = 0.09 tke = (u_star ** 2 / cmu ** 0.5) * ( (c1 * np.log((height + aerodynamic_roughness) / aerodynamic_roughness)) + c2) ** 0.5 # If a raw numpy array is needed, we can simply ask for the same array # stripped of its units if return_without_units: tke = np.array(tke) return tke def omega_YGCJ( unit, reference_speed, reference_height, height, aerodynamic_roughness, return_without_units=True, debug=False ): ''' Take reference values, return TKE at given heights. Expression generalisations to allow height variation for turbulence quantities (tag:YGCJ): <NAME>., <NAME>., <NAME>., & <NAME>. (2009). New inflow boundary conditions for modelling the neutral equilibrium atmospheric boundary layer in computational wind engineering. J. of Wind Engineering and Industrial Aerodynamics, 97(2), 88-95. DOI:10.1016/j.jweia.2008.12.001 Parameters ---------- reference_speed : float or pint.quantity.build_quantity_class.<locals>.Quantity The reference speed taken at the reference height, usually taken to be 10m in SimScale. If no
<reponame>zhafen/linefinder #!/usr/bin/env python '''Testing for classify.py @author: <NAME> @contact: <EMAIL> @status: Development ''' import h5py from mock import patch, PropertyMock import numpy as np import numpy.testing as npt import os import pandas as pd import pdb import unittest import galaxy_dive.read_data.ahf as read_ahf from linefinder import classify import linefinder.analyze_data.worldlines as analyze_worldlines ######################################################################## # Global Variables Useful for Testing ######################################################################## default_kwargs = { 'halo_data_dir': './tests/data/ahf_test_data', 'out_dir': './tests/data/tracking_output', 'tag': 'test_classify', 'neg': 1, 'wind_cut': 2., 'absolute_wind_cut': 15., 't_pro': 100., 't_m': 500., 'velocity_scale': 'Vc(Rvir)', 'min_gal_density': None, 'pp_classifications_to_save': [], } default_ptrack = { 'mt_gal_id': np.array([ [ 0, 0, 2, -2, -2, ], # Merger, except in early snapshots [ 0, 0, 0, 0, 0, ], # Always part of main galaxy [ -2, 0, -2, -2, -2, ], # CGM -> main galaxy -> CGM ]), 'gal_id': np.array([ [ 0, 2, 2, -2, -2, ], # Merger, except in early snapshots [ 0, 0, 0, 0, 10, ], # Always part of main galaxy [ -2, 0, -2, -2, -2, ], # CGM -> main galaxy -> CGM ]), 'PType': np.array([ [ 4, 4, 0, 0, 0, ], # Merger, except in early snapshots [ 4, 0, 0, 0, 0, ], # Always part of main galaxy [ 0, 0, 0, 0, 0, ], # CGM -> main galaxy -> CGM ]), 'P': np.array([ [ [ 41792.1633 , 44131.2309735 , 46267.67030708 ], # Merger, except in early snapshots [ 38198.04856455, 42852.63974461, 43220.86278364 ], [ 34972.28497249, 39095.17772698, 39446.83170768 ], [ 0., 0., 0. ], [ 0., 0., 0. ], ], [ [ 41792.1633 , 44131.2309735 , 46267.67030708 ], # Always part of main galaxy [ 39109.18846174, 41182.20608191, 43161.6788352 ], [ 35829.91969126, 37586.13659658, 39375.69670048 ], [ 32543.5697382 , 33981.19081307, 35583.36876478 ], [ 3245.25202392, 3136.94192456, 3317.2277023 ], ], [ [ 0., 0., 0. ], # CGM -> main galaxy -> CGM [ 39109.18846174, 41182.20608191, 43161.6788352 ], [ 0., 0., 0. ], [ 0., 0., 0. ], [ 0., 0., 0. ], ], ]), 'V': np.array([ [ [-48.53, 72.1 , 96.12], # Merger, except in early snapshots [-23.75, 91.13, 80.57], [-20.92, 92.55, 75.86], [-17.9 , 92.69, 70.54], [ 0., 0., 0., ], ], [ [-48.53, 72.1 , 96.12], # Always part of main galaxy [-49.05, 72.73, 96.86], [-48.89, 73.77, 97.25], [-49.75, 75.68, 96.52], [-12.43, 39.47, 13. ], ], [ [-48.53 + 100., 72.1 , 96.12], # CGM -> main galaxy -> CGM [-49.05, 72.73, 96.86], [-48.89, 73.77, 97.25], [-49.75, 75.68, 96.52], [-12.43, 39.47, 13. ], ], ]), 'snum': np.array([ 600, 550, 500, 450, 10 ]), 'redshift': np.array([ 0. , 0.06984665, 0.16946003, 0.28952773953090749, 12.310917860336163 ]), } default_ptrack_attrs = { 'main_mt_halo_id': 0, 'hubble': 0.70199999999999996, 'omega_lambda': 0.72799999999999998, 'omega_matter': 0.27200000000000002, } ######################################################################## # Test Cases ######################################################################## class TestReadPTrack( unittest.TestCase ): def setUp( self ): self.classifier = classify.Classifier( **default_kwargs ) ######################################################################## def test_basic( self ): self.classifier.read_data_files() expected = 1.700689e-08 actual = self.classifier.ptrack['Den'][0,0] npt.assert_allclose( expected, actual ) ######################################################################## ######################################################################## class TestDerivedFunctions( unittest.TestCase ): def setUp( self ): self.classifier = classify.Classifier( **default_kwargs ) ######################################################################## def test_get_radial_velocity( self ): self.classifier.read_data_files() # Set the second particle at snapshot 550 to be at the center of the main halo at that redshift # Also set the velocity of the second particle at snapshot 550 to the velocity of the main halo at that redshift # This should result in an identically 0 radial velocity self.classifier.ptrack[ 'P' ][ 1, 1 ] = np.array([ 29372.26565053, 30929.16894187, 32415.81701217 ]) self.classifier.ptrack[ 'P' ][ 1, 1 ] *= 1./(1. + self.classifier.ptrack['redshift'][ 1 ])/self.classifier.ptrack_attrs['hubble'] self.classifier.ptrack[ 'V' ][ 1, 1 ] = np.array([ -49.05, 72.73, 96.86 ]) # Get the result result = self.classifier.get_radial_velocity() # Make sure we have the right shape. assert result.shape == self.classifier.ptrack[ 'Den' ].shape # Make sure that we have 0 radial velocity when we should npt.assert_allclose( result[ 1, 1 ], 0., atol=1e-3 ) ######################################################################## def test_get_circular_velocity( self ): self.classifier.read_data_files() # What our actual circular velocity is result = self.classifier.get_circular_velocity() # Make sure we have the right dimensions assert result.shape == ( 3, ) # We expect the circular velocity of a 1e12 Msun galaxy to be roughly ~100 km/s expected = 100. actual = result[600] npt.assert_allclose( expected, actual, rtol=0.5 ) ######################################################################## def test_get_time_difference( self ): self.classifier.read_data_files() result = self.classifier.get_time_difference() # Expected difference in time, from NED's cosmology calculator. travel_time_at_snum_550 = 0.927 # In Gyr travel_time_at_snum_600 = 2.104 # In Gyr expected_0 = travel_time_at_snum_550 expected_1 = travel_time_at_snum_600 - travel_time_at_snum_550 npt.assert_allclose( expected_0, result[0][0], 1e-3) npt.assert_allclose( expected_1, result[1][1], 1e-3) ######################################################################## ######################################################################## class TestIdentifyAccrectionEjectionAndMergers( unittest.TestCase ): def setUp( self ): self.classifier = classify.Classifier( **default_kwargs ) # Emulate the loading data phase self.classifier.ptrack = default_ptrack self.classifier.ptrack_attrs = default_ptrack_attrs # Put in the number of snapshots and particles so that the function works correctly. self.classifier.n_snap = default_ptrack['gal_id'].shape[1] self.classifier.n_particle = default_ptrack['gal_id'].shape[0] # Force the first valid snapshot to be snapshot 10, to ensure compatibility with # previous tests. self.classifier._main_mt_halo_first_snap = 10 ######################################################################## def test_identify_is_in_other_gal( self ): self.classifier.ahf_reader = read_ahf.AHFReader( default_kwargs['halo_data_dir'] ) self.classifier.ahf_reader.get_mtree_halos( 'snum' ) expected = np.array([ [ 0, 1, 1, 0, 0, ], # Merger, except in early snapshots [ 0, 0, 0, 0, 0, ], # Always part of main galaxy [ 0, 0, 0, 0, 0, ], # CGM -> main galaxy -> CGM ]).astype( bool ) # Run the function actual = self.classifier.identify_is_in_other_gal() npt.assert_allclose( expected, actual ) ######################################################################## def test_identify_is_in_other_gal_density_criterion( self ): '''Test we can identify when a particle is in another galaxy, including some minimum density criterion for gas. ''' # Change parameters self.classifier.min_gal_density = 0.1 # Setup Test Data self.classifier.ahf_reader = read_ahf.AHFReader( default_kwargs['halo_data_dir'] ) self.classifier.ahf_reader.get_mtree_halos( 'snum' ) self.classifier.ptrack['Den'] = np.array([ [ 0, 0.01, 10., 0, 0, ], # Merger, except in early snapshots [ 0, 0, 0, 0, 0, ], # Always part of main galaxy [ 0, 0, 0, 0, 0, ], # CGM -> main galaxy -> CGM ]) self.classifier.ptrack['PType'] = np.array([ [ 0, 0, 0, 0, 0, ], # Merger, except in early snapshots [ 0, 0, 0, 0, 0, ], # Always part of main galaxy [ 0, 0, 0, 0, 0, ], # CGM -> main galaxy -> CGM ]) expected = np.array([ [ 0, 0, 1, 0, 0, ], # Merger, except in early snapshots [ 0, 0, 0, 0, 0, ], # Always part of main galaxy [ 0, 0, 0, 0, 0, ], # CGM -> main galaxy -> CGM ]).astype( bool ) # Run the function actual = self.classifier.identify_is_in_other_gal() npt.assert_allclose( expected, actual ) ######################################################################## def test_identify_is_in_other_gal_density_criterion_ptype( self ): '''Test we can identify when a particle is in another galaxy, including some minimum density criterion for gas. Also make sure that PType is considered. ''' # Change parameters self.classifier.min_gal_density = 0.1 # Setup Test Data self.classifier.ahf_reader = read_ahf.AHFReader( default_kwargs['halo_data_dir'] ) self.classifier.ahf_reader.get_mtree_halos( 'snum' ) self.classifier.ptrack['Den'] = np.array([ [ 0, 0.01, 10., 0, 0, ], # Merger, except in early snapshots [ 0, 0, 0, 0, 0, ], # Always part of main galaxy [ 0, 0, 0, 0, 0, ], # CGM -> main galaxy -> CGM ]) self.classifier.ptrack['PType'] = np.array([ [ 0, 4, 4, 0, 0, ], # Merger, except in early snapshots [ 0, 0, 0, 0, 0, ], # Always part of main galaxy [ 0, 0, 0, 0, 0, ], # CGM -> main galaxy -> CGM ]) expected = np.array([ [ 0, 1, 1, 0, 0, ], # Merger, except in early snapshots [ 0, 0, 0, 0, 0, ], # Always part of main galaxy [ 0, 0, 0, 0, 0, ], # CGM -> main galaxy -> CGM ]).astype( bool ) # Run the function actual = self.classifier.identify_is_in_other_gal() npt.assert_allclose( expected, actual ) ######################################################################## def test_identify_is_in_main_gal( self ): # Prerequisites self.classifier.is_in_other_gal = np.array([ [ 0, 1, 1, 0, 0, ], # Merger, except in early snapshots [ 0, 0, 0, 0, 0, ], # Always part of main galaxy [ 0, 0, 0, 0, 0, ], # CGM -> main galaxy -> CGM ]).astype( bool ) expected = np.array([ [ 1, 0, 0, 0, 0, ], # Merger, except in early snapshots [
not in biom_types: raise ValueError( 'The observable could not be found in the observable column.') # Get dose information mask = data[dose_key].notnull() dose_data = data[mask][[time_key, dose_key, dose_duration_key]] # Mask data for observable mask = data[obs_key] == observable data = data[mask][[time_key, value_key]] # Set axis labels to dataframe keys self.set_axis_labels(time_key, obs_key, dose_key) # Add samples as scatter plot if no bulk probabilites are provided, and # terminate method if bulk_probs is None: times = data[time_key] samples = data[value_key] self._add_prediction_scatter_trace(times, samples) return None # Not more than 7 bulk probabilities are allowed (Purely aesthetic # criterion) if len(bulk_probs) > 7: raise ValueError( 'At most 7 different bulk probabilities can be illustrated at ' 'the same time.') # Make sure that bulk probabilities are between 0 and 1 bulk_probs = [float(probability) for probability in bulk_probs] for probability in bulk_probs: if (probability < 0) or (probability > 1): raise ValueError( 'The provided bulk probabilities have to between 0 and 1.') # Define colour scheme shift = 2 colors = plotly.colors.sequential.Blues[shift:] # Create scatter plot of dose events self._add_dose_trace( _id=None, times=dose_data[time_key], doses=dose_data[dose_key], durations=dose_data[dose_duration_key], color=colors[0], is_prediction=True) # Add bulk probabilities to figure percentile_df = self._compute_bulk_probs( data, bulk_probs, time_key, value_key) self._add_prediction_bulk_prob_trace(percentile_df, colors) def set_axis_labels(self, time_label, biom_label, dose_label): """ Sets the label of the time axis, the biomarker axis, and the dose axis. """ self._fig.update_xaxes(title=time_label, row=2) self._fig.update_yaxes(title=dose_label, row=1) self._fig.update_yaxes(title=biom_label, row=2) class PDTimeSeriesPlot(plots.SingleFigure): """ A figure class that visualises measurements of a pharmacodynamic observables across multiple individuals. Measurements of a pharmacodynamic observables over time are visualised as a scatter plot. Extends :class:`SingleFigure`. Parameters ---------- updatemenu Boolean flag that enables or disables interactive buttons, such as a logarithmic scale switch for the y-axis. """ def __init__(self, updatemenu=True): super(PDTimeSeriesPlot, self).__init__(updatemenu) def _add_data_trace(self, _id, times, measurements, color): """ Adds scatter plot of an indiviudals pharamcodynamics to figure. """ self._fig.add_trace( go.Scatter( x=times, y=measurements, name="ID: %d" % _id, showlegend=True, mode="markers", marker=dict( symbol='circle', color=color, opacity=0.7, line=dict(color='black', width=1)))) def _add_simulation_trace(self, times, biomarker): """ Adds scatter plot of an indiviudals pharamcodynamics to figure. """ self._fig.add_trace( go.Scatter( x=times, y=biomarker, name="Model", showlegend=True, mode="lines", line=dict(color='black'))) def add_data( self, data, observable=None, id_key='ID', time_key='Time', obs_key='Observable', value_key='Value'): """ Adds pharmacodynamic time series data of (multiple) individuals to the figure. Expects a :class:`pandas.DataFrame` with an ID, a time, an observable and a value column, and adds a scatter plot of the measuremed time series to the figure. Each individual receives a unique colour. Parameters ---------- data A :class:`pandas.DataFrame` with the time series PD data in form of an ID, time, and observable column. observable The measured bimoarker. This argument is used to determine the relevant rows in the dataframe. If ``None``, the first observable in the observable column is selected. id_key Key label of the :class:`DataFrame` which specifies the ID column. The ID refers to the identity of an individual. Defaults to ``'ID'``. time_key Key label of the :class:`DataFrame` which specifies the time column. Defaults to ``'Time'``. obs_key Key label of the :class:`DataFrame` which specifies the observable column. Defaults to ``'Observable'``. value_key Key label of the :class:`DataFrame` which specifies the column of the measured values. Defaults to ``'Value'``. """ # Check input format if not isinstance(data, pd.DataFrame): raise TypeError( 'Data has to be pandas.DataFrame.') for key in [id_key, time_key, obs_key, value_key]: if key not in data.keys(): raise ValueError( 'Data does not have the key <' + str(key) + '>.') # Default to first bimoarker, if observable is not specified biom_types = data[obs_key].dropna().unique() if observable is None: observable = biom_types[0] if observable not in biom_types: raise ValueError( 'The observable could not be found in the observable column.') # Mask data for observable mask = data[obs_key] == observable data = data[mask] # Get a colour scheme colors = plotly.colors.qualitative.Plotly n_colors = len(colors) # Fill figure with scatter plots of individual data ids = data[id_key].unique() for index, _id in enumerate(ids): # Get individual data mask = data[id_key] == _id times = data[time_key][mask] measurements = data[value_key][mask] color = colors[index % n_colors] # Create Scatter plot self._add_data_trace(_id, times, measurements, color) def add_simulation(self, data, time_key='Time', value_key='Value'): """ Adds a pharmacodynamic time series simulation to the figure. Expects a :class:`pandas.DataFrame` with a time and a value column, and adds a line plot of the simulated time series to the figure. Parameters ---------- data A :class:`pandas.DataFrame` with the time series PD simulation in form of a time and value column. time_key Key label of the :class:`DataFrame` which specifies the time column. Defaults to ``'Time'``. value_key Key label of the :class:`DataFrame` which specifies the value column. Defaults to ``'Value'``. """ # Check input format if not isinstance(data, pd.DataFrame): raise TypeError( 'Data has to be pandas.DataFrame.') for key in [time_key, value_key]: if key not in data.keys(): raise ValueError( 'Data does not have the key <' + str(key) + '>.') times = data[time_key] values = data[value_key] self._add_simulation_trace(times, values) class PKTimeSeriesPlot(plots.SingleSubplotFigure): """ A figure class that visualises measurements of a pharmacokinetic observable across multiple individuals. Measurements of a pharmacokinetic observable over time are visualised as a scatter plot. Extends :class:`SingleSubplotFigure`. Parameters ---------- updatemenu Boolean flag that enables or disables interactive buttons, such as a logarithmic scale switch for the y-axis. """ def __init__(self, updatemenu=True): super(PKTimeSeriesPlot, self).__init__() self._create_template_figure( rows=2, cols=1, shared_x=True, row_heights=[0.2, 0.8]) if updatemenu: self._add_updatemenu() def _add_dose_trace(self, _id, times, doses, durations, color): """ Adds scatter plot of an indiviudals pharamcodynamics to figure. """ # Convert durations to strings durations = [ 'Dose duration: ' + str(duration) for duration in durations] # Add scatter plot of dose events self._fig.add_trace( go.Scatter( x=times, y=doses, name="ID: %s" % str(_id), legendgroup="ID: %s" % str(_id), showlegend=False, mode="markers", text=durations, hoverinfo='text', marker=dict( symbol='circle', color=color, opacity=0.7, line=dict(color='black', width=1))), row=1, col=1) def _add_biom_trace(self, _id, times, measurements, color): """ Adds scatter plot of an indiviudals pharamcodynamics to figure. """ self._fig.add_trace( go.Scatter( x=times, y=measurements, name="ID: %s" % str(_id), legendgroup="ID: %s" % str(_id), showlegend=True, mode="markers", marker=dict( symbol='circle', color=color, opacity=0.7, line=dict(color='black', width=1))), row=2, col=1) def _add_updatemenu(self): """ Adds a button to the figure that switches the biomarker scale from linear to logarithmic. """ self._fig.update_layout( updatemenus=[ dict( type="buttons", direction="left", buttons=list([ dict( args=[{"yaxis2.type": "linear"}], label="Linear y-scale", method="relayout" ), dict( args=[{"yaxis2.type": "log"}], label="Log y-scale", method="relayout" ) ]), pad={"r": 0, "t": -10}, showactive=True, x=0.0, xanchor="left", y=1.15, yanchor="top" ) ] ) def add_data( self, data, observable=None, id_key='ID', time_key='Time', obs_key='Observable', value_key='Value', dose_key='Dose', dose_duration_key='Duration'): """ Adds pharmacokinetic time series data of (multiple) individuals to the figure. Expects a :class:`pandas.DataFrame` with an ID, a time, an observable and a value column, and adds a scatter plot of the measuremed time series to the figure. The dataframe is also expected to have information about the administered dose via a dose and a dose duration column. Each individual receives a unique colour. Parameters ---------- data A :class:`pandas.DataFrame` with the time series PD data in form of an ID, time, observable and value column. observable The measured bimoarker. This argument is used to determine the relevant rows in the dataframe. If ``None``, the first observable in the observable column is selected. id_key Key label of the :class:`DataFrame` which specifies the ID column. The ID refers to the identity of an individual. Defaults to ``'ID'``. time_key Key label of the :class:`DataFrame` which specifies the time column. Defaults to ``'Time'``. obs_key Key label of the :class:`DataFrame` which specifies the observable column. Defaults to ``'Observable'``. value_key Key label of the :class:`DataFrame` which specifies the column of the measured values. Defaults to ``'Value'``. dose_key Key label of the :class:`DataFrame` which specifies the dose column. Defaults to ``'Dose'``. dose_duration_key Key label of the :class:`DataFrame` which specifies the dose duration column. Defaults to ``'Duration'``. """ # Check input format if not isinstance(data, pd.DataFrame): raise TypeError( 'Data has to be pandas.DataFrame.') keys = [ id_key, time_key, obs_key, value_key, dose_key, dose_duration_key] for key in keys: if key not in data.keys(): raise ValueError( 'Data does not have the key <' + str(key) + '>.') # Default to first bimoarker, if observable is
"""Text transitions used for segment displays.""" import abc from typing import Optional, List from mpf.core.placeholder_manager import TextTemplate from mpf.core.rgb_color import RGBColor from mpf.devices.segment_display.segment_display_text import SegmentDisplayText, UncoloredSegmentDisplayText STEP_OUT_OF_RANGE_ERROR = "Step is out of range" TRANSITION_DIRECTION_UNKNOWN_ERROR = "Transition uses an unknown direction value" class TransitionBase(metaclass=abc.ABCMeta): """Base class for text transitions in segment displays.""" __slots__ = ["output_length", "config", "collapse_dots", "collapse_commas"] def __init__(self, output_length: int, collapse_dots: bool, collapse_commas: bool, config: dict) -> None: """Initialize the transition.""" self.output_length = output_length self.config = config self.collapse_dots = collapse_dots self.collapse_commas = collapse_commas for key, value in config.items(): if hasattr(self, key): setattr(self, key, value) @abc.abstractmethod def get_step_count(self): """Return the total number of steps required for the transition.""" raise NotImplementedError # pylint: disable=too-many-arguments @abc.abstractmethod def get_transition_step(self, step: int, current_text: str, new_text: str, current_colors: Optional[List[RGBColor]] = None, new_colors: Optional[List[RGBColor]] = None) -> SegmentDisplayText: """Calculate all the steps in the transition.""" raise NotImplementedError class TransitionRunner: """Class to run/execute transitions using an iterator.""" __slots__ = ["_transition", "_step", "_current_placeholder", "_new_placeholder", "_current_colors", "_new_colors"] # pylint: disable=too-many-arguments def __init__(self, machine, transition: TransitionBase, current_text: str, new_text: str, current_colors: Optional[List[RGBColor]] = None, new_colors: Optional[List[RGBColor]] = None) -> None: """Class initializer.""" self._transition = transition self._step = 0 self._current_placeholder = TextTemplate(machine, current_text) self._new_placeholder = TextTemplate(machine, new_text) self._current_colors = current_colors self._new_colors = new_colors def __iter__(self): """Return the iterator.""" return self def __next__(self): """Evaluate and return the next transition step.""" if self._step >= self._transition.get_step_count(): raise StopIteration transition_step = self._transition.get_transition_step(self._step, self._current_placeholder.evaluate({}), self._new_placeholder.evaluate({}), self._current_colors, self._new_colors) self._step += 1 return transition_step class NoTransition(TransitionBase): """Segment display no transition effect.""" def get_step_count(self): """Return the total number of steps required for the transition.""" return 1 # pylint: disable=too-many-arguments def get_transition_step(self, step: int, current_text: str, new_text: str, current_colors: Optional[List[RGBColor]] = None, new_colors: Optional[List[RGBColor]] = None) -> SegmentDisplayText: """Calculate all the steps in the transition.""" if step < 0 or step >= self.get_step_count(): raise AssertionError(STEP_OUT_OF_RANGE_ERROR) return SegmentDisplayText.from_str(new_text, self.output_length, self.collapse_dots, self.collapse_commas, new_colors) class PushTransition(TransitionBase): """Segment display push transition effect.""" def __init__(self, output_length: int, collapse_dots: bool, collapse_commas: bool, config: dict) -> None: """Class initializer.""" self.direction = 'right' self.text = None self.text_color = None super().__init__(output_length, collapse_dots, collapse_commas, config) if self.text is None: self.text = '' def get_step_count(self): """Return the total number of steps required for the transition.""" return self.output_length + len(self.text) # pylint: disable=too-many-arguments def get_transition_step(self, step: int, current_text: str, new_text: str, current_colors: Optional[List[RGBColor]] = None, new_colors: Optional[List[RGBColor]] = None) -> SegmentDisplayText: """Calculate all the steps in the transition.""" if step < 0 or step >= self.get_step_count(): raise AssertionError(STEP_OUT_OF_RANGE_ERROR) current_display_text = SegmentDisplayText.from_str(current_text, self.output_length, self.collapse_dots, self.collapse_commas, current_colors) new_display_text = SegmentDisplayText.from_str(new_text, self.output_length, self.collapse_dots, self.collapse_commas, new_colors) if self.text: if new_colors and not self.text_color: text_color = [new_colors[0]] else: text_color = self.text_color transition_text = SegmentDisplayText.from_str(self.text, len(self.text), self.collapse_dots, self.collapse_commas, text_color) else: transition_text = UncoloredSegmentDisplayText([], self.collapse_dots, self.collapse_commas) if self.direction == 'right': temp_list = new_display_text temp_list.extend(transition_text) temp_list.extend(current_display_text) return temp_list[ self.output_length + len(self.text) - (step + 1):2 * self.output_length + len( self.text) - (step + 1)] if self.direction == 'left': temp_list = current_display_text temp_list.extend(transition_text) temp_list.extend(new_display_text) return temp_list[step + 1:step + 1 + self.output_length] raise AssertionError(TRANSITION_DIRECTION_UNKNOWN_ERROR) class CoverTransition(TransitionBase): """Segment display cover transition effect.""" def __init__(self, output_length: int, collapse_dots: bool, collapse_commas: bool, config: dict) -> None: """Class initializer.""" self.direction = 'right' self.text = None self.text_color = None super().__init__(output_length, collapse_dots, collapse_commas, config) if self.text is None: self.text = '' def get_step_count(self): """Return the total number of steps required for the transition.""" return self.output_length + len(self.text) # pylint: disable=too-many-arguments def get_transition_step(self, step: int, current_text: str, new_text: str, current_colors: Optional[List[RGBColor]] = None, new_colors: Optional[List[RGBColor]] = None) -> SegmentDisplayText: """Calculate all the steps in the transition.""" if step < 0 or step >= self.get_step_count(): raise AssertionError(STEP_OUT_OF_RANGE_ERROR) current_display_text = SegmentDisplayText.from_str(current_text, self.output_length, self.collapse_dots, self.collapse_commas, current_colors) new_display_text = SegmentDisplayText.from_str(new_text, self.output_length, self.collapse_dots, self.collapse_commas, new_colors) if self.text: if new_colors and not self.text_color: text_color = [new_colors[0]] else: text_color = self.text_color transition_text = SegmentDisplayText.from_str(self.text, len(self.text), self.collapse_dots, self.collapse_commas, text_color) else: transition_text = UncoloredSegmentDisplayText([], self.collapse_dots, self.collapse_commas) if self.direction == 'right': new_extended_display_text = new_display_text new_extended_display_text.extend(transition_text) if step < self.output_length: temp_text = new_extended_display_text[-(step + 1):] temp_text.extend(current_display_text[step + 1:]) else: temp_text = new_display_text[-(step + 1):-(step + 1) + self.output_length] return temp_text if self.direction == 'left': new_extended_display_text = transition_text new_extended_display_text.extend(new_display_text) if step < self.output_length: temp_text = current_display_text[:self.output_length - (step + 1)] temp_text.extend(new_extended_display_text[:step + 1]) else: temp_text = new_extended_display_text[step - self.output_length + 1:step + 1] return temp_text raise AssertionError(TRANSITION_DIRECTION_UNKNOWN_ERROR) class UncoverTransition(TransitionBase): """Segment display uncover transition effect.""" def __init__(self, output_length: int, collapse_dots: bool, collapse_commas: bool, config: dict) -> None: """Class initializer.""" self.direction = 'right' self.text = None self.text_color = None super().__init__(output_length, collapse_dots, collapse_commas, config) if self.text is None: self.text = '' def get_step_count(self): """Return the total number of steps required for the transition.""" return self.output_length + len(self.text) # pylint: disable=too-many-arguments def get_transition_step(self, step: int, current_text: str, new_text: str, current_colors: Optional[List[RGBColor]] = None, new_colors: Optional[List[RGBColor]] = None) -> SegmentDisplayText: """Calculate all the steps in the transition.""" if step < 0 or step >= self.get_step_count(): raise AssertionError(STEP_OUT_OF_RANGE_ERROR) current_display_text = SegmentDisplayText.from_str(current_text, self.output_length, self.collapse_dots, self.collapse_commas, current_colors) new_display_text = SegmentDisplayText.from_str(new_text, self.output_length, self.collapse_dots, self.collapse_commas, new_colors) if self.text: if new_colors and not self.text_color: text_color = [new_colors[0]] else: text_color = self.text_color transition_text = SegmentDisplayText.from_str(self.text, len(self.text), self.collapse_dots, self.collapse_commas, text_color) else: transition_text = UncoloredSegmentDisplayText([], self.collapse_dots, self.collapse_commas) if self.direction == 'right': current_extended_display_text = transition_text current_extended_display_text.extend(current_display_text) if step < len(self.text): temp_text = current_extended_display_text[ len(self.text) - step - 1:len(self.text) - step - 1 + self.output_length] else: temp_text = new_display_text[:step - len(self.text) + 1] temp_text.extend(current_extended_display_text[:self.output_length - len(temp_text)]) return temp_text if self.direction == 'left': current_extended_display_text = current_display_text current_extended_display_text.extend(transition_text) if step < len(self.text): temp_text = current_extended_display_text[step + 1:step + 1 + self.output_length] else: temp_text = current_display_text[step + 1:] temp_text.extend(new_display_text[-(self.output_length - len(temp_text)):]) return temp_text raise AssertionError(TRANSITION_DIRECTION_UNKNOWN_ERROR) class WipeTransition(TransitionBase): """Segment display wipe transition effect.""" def __init__(self, output_length: int, collapse_dots: bool, collapse_commas: bool, config: dict) -> None: """Class initializer.""" self.direction = 'right' self.text = None self.text_color = None super().__init__(output_length, collapse_dots, collapse_commas, config) if self.text is None: self.text = '' def get_step_count(self): """Return the total number of steps required for the transition.""" return self.output_length + len(self.text) # pylint: disable=too-many-arguments,too-many-branches,too-many-return-statements def get_transition_step(self, step: int, current_text: str, new_text: str, current_colors: Optional[List[RGBColor]] = None, new_colors: Optional[List[RGBColor]] = None) -> SegmentDisplayText: """Calculate all the steps in the transition.""" if step < 0 or step >= self.get_step_count(): raise AssertionError(STEP_OUT_OF_RANGE_ERROR) current_display_text = SegmentDisplayText.from_str(current_text, self.output_length, self.collapse_dots, self.collapse_commas, current_colors) new_display_text = SegmentDisplayText.from_str(new_text, self.output_length, self.collapse_dots, self.collapse_commas, new_colors) if self.text: if new_colors and not self.text_color: text_color = [new_colors[0]] else: text_color = self.text_color transition_text = SegmentDisplayText.from_str(self.text, len(self.text), self.collapse_dots, self.collapse_commas, text_color) else: transition_text = UncoloredSegmentDisplayText([], self.collapse_dots, self.collapse_commas) if self.direction == 'right': if step < len(self.text): temp_text = transition_text[-(step + 1):] temp_text.extend(current_display_text[step + 1:]) elif step < self.output_length: temp_text = new_display_text[:step - len(self.text) + 1] temp_text.extend(transition_text) temp_text.extend(current_display_text[len(temp_text):]) else: temp_text = new_display_text[:step - len(self.text) + 1] temp_text.extend(transition_text[:self.output_length - len(temp_text)]) return temp_text if self.direction == 'left': if step < len(self.text): temp_text = current_display_text[:self.output_length - (step + 1)] temp_text.extend(transition_text[:step + 1]) elif step < self.output_length: temp_text = current_display_text[:self.output_length - (step + 1)] temp_text.extend(transition_text) temp_text.extend(new_display_text[len(temp_text):]) elif step < self.output_length + len(self.text) - 1: temp_text = transition_text[step - (self.output_length + len(self.text)) + 1:] temp_text.extend(new_display_text[-(self.output_length - len(temp_text)):]) else: temp_text = new_display_text return temp_text raise AssertionError(TRANSITION_DIRECTION_UNKNOWN_ERROR) class SplitTransition(TransitionBase): """Segment display split transition effect.""" def __init__(self, output_length: int, collapse_dots: bool, collapse_commas: bool, config: dict) -> None: """Class initializer.""" self.direction = 'out' self.mode = 'push' super().__init__(output_length, collapse_dots, collapse_commas, config) def get_step_count(self): """Return the total number of steps required for the transition.""" return int((self.output_length + 1) / 2) # pylint: disable=too-many-arguments,too-many-branches,too-many-return-statements def get_transition_step(self, step: int, current_text: str, new_text: str, current_colors: Optional[List[RGBColor]] = None, new_colors: Optional[List[RGBColor]] = None) -> SegmentDisplayText: """Calculate all the steps in the transition.""" if step < 0 or step >= self.get_step_count(): raise AssertionError(STEP_OUT_OF_RANGE_ERROR) current_display_text = SegmentDisplayText.from_str(current_text, self.output_length, self.collapse_dots, self.collapse_commas, current_colors) new_display_text = SegmentDisplayText.from_str(new_text, self.output_length, self.collapse_dots, self.collapse_commas, new_colors) if self.mode == 'push': if self.direction == 'out': if step == self.get_step_count() - 1: return new_display_text characters = int(self.output_length / 2) split_point = characters if characters * 2 == self.output_length: characters -= 1 else: split_point += 1 characters -= step temp_text = current_display_text[split_point - characters:split_point] temp_text.extend(new_display_text[characters:characters + (self.output_length - 2 * characters)]) temp_text.extend(current_display_text[split_point:split_point + characters]) return temp_text if self.direction == 'in':
<reponame>shivgarg/ai_game<gh_stars>0 import socket, sys, time from Tkinter import * from math import floor from GameStack import GameStack import Helpers as h from sys import argv from time import sleep from threading import Thread from threading import Timer import time import select # TODO - print graph socket_list = [] #Accepting incoming connections WON1=0 WON2=0 winners=0 el=1 class TkBoard(): # CONSTANTS SQUARE_SIZE = 50 PLAYER_SIZE = SQUARE_SIZE * 0.8 SQUARE_SPACING = 10 MARGIN = 20 is_redo_m=False PANEL_WIDTH = 200 ICON_MARGIN = 55 BUTTON_Y_START = 125 BUTTON_WIDTH = 100 BUTTON_HEIGHT = 30 BUTTON_MARGIN = 10 LABEL_Y_START = 330 LABEL_FONT_SIZE = 26 LABEL_SPACING = 10 LABEL_TEXT = lambda s, n, c: ("%-"+str(n+7)+"s") % ("walls: "+"I"*c) # lambda c: "Walls: {0}".format(c) DEFAULT_COLORS = {'bg': '#FFFFFF', 'square': '#333333', 'wall': '#DD6611', 'wall-error': '#CC1111', 'panel': '#333333', 'button': '#555555',#'#AA5303', 'text': '#000000', 'players': ['#11CC11', '#CC11CC', '#CC1111', '#11CCCC'] } # CLASS VARIABLES - DRAWING tk_root = None tk_canv = None players = [] player_ghost = None icon = None ai_label = None squares = [[0]*9]*9 wall_labels = [] grid = None canvas_dims = (0,0) buttons = [] # will contain bbox and callback as tuple for each button walls = {} # will be dictionary of name => id. all will exist, transparency toggled, colors changed for errors active_wall = "" active_move = "" recent_x = 0 recent_y = 0 # GAME-INTERACTION VARIABLES gs = None moveType = "move" game_over = False # CONTROL VARIABLES THREAD_SLEEP = 0.1 def set_default_colors(new_colors_dict={}): """update default colors with given dictionary of new color scheme Given colors don't need to be complete - only updates those given""" for k in new_colors_dict.keys(): if k in self.DEFAULT_COLORS.keys(): self.DEFAULT_COLORS[k] = new_colors_dict[k] def new_game(self, np=2, nai=0): """Destroy old board, draw new board, update object state with new board """ if self.tk_root: self.tk_root.destroy() self.tk_root = Tk() self.tk_root.bind("<Escape>", lambda e: self.handle_quit()) self.tk_root.bind("<Motion>", lambda e: self.handle_mouse_motion(e.x, e.y)) self.thread_kill = False self.time_stats = [] # margin - space/2 - square - space - square - ... - square - space/2 - margin - panel total_height = 9*self.SQUARE_SIZE + 9*self.SQUARE_SPACING + 2*self.MARGIN total_width = total_height + self.PANEL_WIDTH self.canvas_dims = (total_width, total_height) self.tk_canv = Canvas(self.tk_root, width=total_width, height=total_height, background=self.DEFAULT_COLORS['bg']) self.tk_canv.pack() self.draw_squares() self.generate_walls() self.game_stack = GameStack(np, nai) self.update_gs() self.players = [(None, None)]*len(self.gs.players) self.max_walls = self.gs.current_player.num_walls self.wall_labels = [None]*len(self.gs.players) self.draw_panel() self.refresh(False) th = Thread(target = lambda : self.background_loop()) th.start() self.tk_root.mainloop() def update_gs(self): self.gs = self.game_stack.current def background_loop(self): global WON1 global WON2 global winners global el turn = 0 timeout=60.0 trackTime1=60.0 trackTime2=60.0 global message global message2 for player in socket_list: player.settimeout(timeout) while True: if turn==0: try: start=time.time() message = socket_list[0].recv(1024) end=time.time() trackTime1=trackTime1-(end-start) print trackTime1 msg=map(int,message.split(' ')) if WON1==1: if msg[1]==0 or (msg[2]==0 and msg[0]==0): message2=str(trackTime1) socket_list[0].send(message2+" 31") socket_list[1].send("0 0 0 31") print "Player 1 passes. SUCCESS" turn =1 success=self.handle_click(msg[0],msg[1],msg[2]) continue message2=str(trackTime1) if trackTime1<0: raise socket.timeout except socket.timeout: if WON1==1: print "Timed out" socket_list[0].send(message2+" 1") socket_list[1].send(message+" 2") print "Player 1 timed out, But player 1 wins" socket_list[0].close() socket_list[1].close() sys.exit(0) break else: print "Timed out" socket_list[0].send(message2+" 2") socket_list[1].send(message+" 1") print "Player 1 timed out, Player 2 wins" socket_list[0].close() socket_list[1].close() sys.exit(0) break else: try: start=time.time() message = socket_list[1].recv(1024) end=time.time() trackTime2=trackTime2-(end-start) print trackTime2 msg=map(int,message.split(' ')) if WON2==1: if msg[1]==0 or (msg[2]==0 and msg[0]==0): message2=str(trackTime2) socket_list[1].send(message2+" 32") socket_list[0].send("0 0 0 32") print "Player 2 passes. SUCCESS" turn =0 success=self.handle_click(msg[0],msg[1],msg[2]) continue message2=str(trackTime2) if trackTime2<0: raise socket.timeout except socket.timeout: if WON2: print "Timed out" socket_list[1].send(message2+" 1") socket_list[0].send(message+" 2") print "Player 2 timed out, but Player 2 wins" socket_list[0].close() socket_list[1].close() sys.exit(0) break else: print "Timed out" socket_list[1].send(message2+" 2") socket_list[0].send(message+" 1") print "Player 2 timed out, Player 1 wins" socket_list[0].close() socket_list[1].close() sys.exit(0) break success=self.handle_click(msg[0],msg[1],msg[2]) if success==0: if turn==0 and WON1==1: socket_list[0].send(message2+" 1") socket_list[1].send(message+" 2") print "Player 1 made invalid move, But, Player 1 wins" elif turn==0 and WON1==0: socket_list[0].send(message2+" 2") socket_list[1].send(message+" 1") print "Player 1 made invalid move, Player 2 wins" elif turn==1 and WON2==1: socket_list[1].send(message2+" 1") socket_list[0].send(message+" 2") print "Player 2 made invalid move, But, Player 2 wins" elif turn==1 and WON2==0: socket_list[1].send(message2+" 2") socket_list[0].send(message+" 1") print "Player 2 made invalid move, Player 1 wins" socket_list[0].close() socket_list[1].close() sys.exit(0) break if success==2: if WON1==1: if turn==0: socket_list[0].send(message2+" 1") socket_list[1].send(message+" 2") print "Player 1 wins" if turn==1: socket_list[0].send(message+" 1") socket_list[1].send(message2+" 2") print "Player 1 wins" if WON2==1: if turn==1: socket_list[1].send(message2+" 1") socket_list[0].send(message+" 2") print "Player 2 wins" if turn==0: socket_list[1].send(message+" 1") socket_list[0].send(message2+" 2") print "Player 2 wins" socket_list[0].close() socket_list[1].close() sys.exit(0) break if success==1: if turn==0 : socket_list[0].send(message2+" 3") socket_list[1].send(message+" 3") if turn == 1: socket_list[1].send(message2+" 3") socket_list[0].send(message+" 3") if success==31: if turn==0 : socket_list[0].send(message2+" 31") socket_list[1].send(message+" 31") if turn == 1: socket_list[1].send(message2+" 31") socket_list[0].send(message+" 31") if success==32: if turn==0 : socket_list[0].send(message2+" 32") socket_list[1].send(message+" 32") if turn == 1: socket_list[1].send(message2+" 32") socket_list[0].send(message+" 32") print "here: ",success if self.thread_kill: break turn = 1-turn for player in socket_list: player.close() print "--- END BACKGROUND LOOP ---" def handle_quit(self): self.thread_kill = True for p in self.gs.players: if p.ai: p.ai.kill_thread() self.tk_root.destroy() def refresh(self, check_ai=True): self.update_gs() self.clear_ghost() self.handle_mouse_motion(self.recent_x, self.recent_y) self.active_wall = "" self.active_move = "" self.draw_players() self.redraw_walls(False) self.draw_current_player_icon() self.draw_wall_counts() if check_ai: self.get_ai_move() def get_ai_move(self, verbose=True): ai = self.gs.current_player.ai if ai: if verbose: print "ai exists for player", self.gs.current_player_num, if ai.thread_started: if verbose: print "and thread", turn, time = ai.get_threaded_move() if turn: self.time_stats.append(time) if verbose: print "is done!" if not self.exec_wrapper(turn, True): print "\n################" print "### AI ERROR ###" print "################\n" self.handle_quit() else: self.refresh() elif verbose: print "has started but hasn't finished yet" else: if verbose: print "but thread hasn't started. starting now." ai.get_move_thread_start(self.game_stack.duplicate()) def draw_current_player_icon(self): width, height = self.canvas_dims midx = width - self.PANEL_WIDTH/2 radius = self.PLAYER_SIZE/2 x0, x1 = midx - radius, midx + radius y0, y1 = self.ICON_MARGIN - radius, self.ICON_MARGIN + radius c = self.DEFAULT_COLORS['players'][self.gs.current_player_num -1] oval = self.tk_canv.create_oval(x0, y0, x1, y1, fill=c, outline="") if self.icon: self.tk_canv.delete(self.icon) self.icon = oval text = None if self.gs.current_player.ai: text = self.tk_canv.create_text((midx, self.ICON_MARGIN), text="AI", font=("Arial", 14, "bold")) if self.ai_label: self.tk_canv.delete(self.ai_label) self.ai_label = text def new_rect_button(self, text, fill, x0, y0, x1, y1, callback): hover_lighten = TkBoard.alpha_hax(fill, "#FFFFFF", 0.25) self.tk_canv.create_rectangle(x0, y0, x1, y1, fill=fill, activefill=hover_lighten, outline="") midx = (x0 + x1) / 2 midy = (y0 + y1) / 2 self.tk_canv.create_text((midx, midy), text=text, font=("Arial", 14, "bold")) self.buttons.append(((x0, y0, x1, y1), callback)) def set_movetype(self, type): self.moveType = type self.refresh() def toggle_movetype(self): if self.moveType == "wall": self.set_movetype("move") elif self.moveType == "move": self.set_movetype("wall") self.refresh() def draw_panel(self): # panel bg width, height = self.canvas_dims midx = width-self.PANEL_WIDTH/2 c = self.DEFAULT_COLORS['panel'] self.tk_canv.create_rectangle(width-self.PANEL_WIDTH, 0, width, height, fill=c) # current-player icon @ top self.draw_current_player_icon() # buttons! c = self.DEFAULT_COLORS['button'] x0, x1 = midx-self.BUTTON_WIDTH/2, midx+self.BUTTON_WIDTH/2 y0, y1 = self.BUTTON_Y_START, self.BUTTON_Y_START + self.BUTTON_HEIGHT self.new_rect_button("Move", c, x0, y0, x1, y1, lambda: self.set_movetype("move")) yshift = self.BUTTON_HEIGHT + self.BUTTON_MARGIN y0 += yshift y1 += yshift self.new_rect_button("Wall", c, x0, y0, x1, y1, lambda: self.set_movetype("wall")) y0 += yshift y1 += yshift self.new_rect_button("undo", c, x0, y0, x1, y1, lambda: self.undo()) y0 += yshift y1 += yshift self.new_rect_button("redo", c, x0, y0, x1, y1, lambda: self.redo()) # "walls: IIII" text self.draw_wall_counts() def undo(self): self.game_stack.undo() self.refresh(False) self.game_over = False def redo(self): self.game_stack.redo() self.refresh() def draw_wall_counts(self): width, height = self.canvas_dims midx = width - self.PANEL_WIDTH/2 y = self.LABEL_Y_START for i in range(len(self.gs.players)): p = self.gs.players[i] text = self.LABEL_TEXT(self.max_walls, p.num_walls) c = self.DEFAULT_COLORS['players'][i] l = self.wall_labels[i] if not l: l = self.tk_canv.create_text((midx, y), text=text, font=("Arial", self.LABEL_FONT_SIZE, "bold"), fill=c) self.wall_labels[i] = l else: self.tk_canv.itemconfigure(l, text=text) y += self.LABEL_SPACING + self.LABEL_FONT_SIZE def handle_mouse_motion(self, x, y): if self.game_over or self.gs.current_player.ai: return self.recent_x = x self.recent_y = y grid = self.point_to_grid((x,y)) if grid and self.moveType == "move": move_str = h.point_to_notation(grid) if move_str != self.active_move: self.active_move = move_str if self.gs.turn_is_valid(move_str, "move"): self.draw_player(grid, self.gs.current_player_num-1, True) elif self.player_ghost: self.tk_canv.delete(self.player_ghost) self.player_ghost = None elif grid and self.moveType == "wall": orient, topleft = self.xy_to_wall_spec(grid, x, y) pos = h.point_to_notation(topleft) wall_str = orient+pos if wall_str != self.active_wall: self.active_wall = wall_str active_error = not self.gs.turn_is_valid(wall_str, "wall") self.redraw_walls(active_error) def handle_click(self,m,xi,yi): x=10 y=20 print self.gs.current_player.position[0] for b in self.buttons: (x0, y0, x1, y1), callback = b if (x0 <= x <= x1) and (y0 <= y <= y1): callback() return if self.game_over or self.gs.current_player.ai: return print self.moveType # check for turn execution global is_redo_m is_redo_m=False if WON1==1 and self.gs.current_player_num==1 and m==0: grid=self.gs.current_player.position is_redo_m=True elif WON2==1 and self.gs.current_player_num==2 and m==0: grid=self.gs.current_player.position is_redo_m=True else: grid=(xi,yi) if m == 1 : self.moveType="wall" elif m == 2 : self.moveType="wall" else : self.moveType="move" if grid and self.moveType == "move": move_str = h.point_to_notation(grid) success = self.exec_wrapper(move_str) elif grid and self.moveType == "wall": orient, topleft = self.xy_to_wall_spec(grid, x, y) if m == 1: orient='H' if m == 2: orient='V' pos = h.point_to_notation(topleft) wall_str = orient+pos success = self.exec_wrapper(wall_str) print success if success: self.refresh() return success def handle_keypress(self, key): (cr, cc) = self.gs.current_player.position if key == "L": cc -= 1 elif key == "R": cc += 1 elif key == "U": cr -= 1 elif key == "D": cr += 1 move_str = h.point_to_notation((cr, cc)) success = self.exec_wrapper(move_str) if success: self.refresh() def wall_on(self, wall_str,
from __future__ import division import collections import re import time R_C_thres = 0.999 # file = codecs.open('out2.txt', 'r','utf-8') # for original utf with diacritics, does not help much file = open('out2.txt', 'r') texts = file.readlines() file.close() # taken from winLen.xls -- the numbers of documents for the individual days # sum(ocNum) must match with len(texts) # docNumDecJan=[7366,6591,6780,6640,6094,3542,3405,6405,6352,6586,6537,6166,3290,3335,6531,6227,6547,6873,6060,3276,3110,5582,4824,2704,2692,2878,2922,2947,5052,4750,3887,3123,4821,3291,3293,6550,6636,6599,6601,6410,3862,3759,6684,6589,6446,6498,6193,3416,3459,6626,6615,6625,6869,6544,3709,3701,6870,6586,6838,6765,6657,3882] docNum = [3002, 5442, 5559, 3059, 3163, 6089, 6013, 6284, 5918, 5916, 3221, 3304, 6139, 5978, 6293, 6103, 5821, 3463, 3204, 6128, 6018, 6328, 6168, 3855, 4847, 3269, 6252, 5989, 6343, 6036, 6197, 3343, 3408, 6258, 6279, 6202, 6215, 5798, 3359, 3105, 6224, 6093, 6253, 6349, 5975, 3064, 3141, 6076, 6227, 6242, 6218, 5804, 3568, 3347, 6333, 6121, 6330, 6105, 6325, 3208, 3639, 6385, 6519, 6415, 6335, 5821, 3426, 3443, 6195, 6296, 6378, 6174, 6011, 3433, 3532, 6273, 6384, 6586, 6127, 6119, 3455, 3438, 6253, 6226, 6263, 6353, 6008, 3328, 2974, 6422, 6433, 6560, 6508, 6079, 3310, 3431, 6286, 6334, 6347, 6622, 5988, 3394, 3299, 6598, 6345, 6336, 6226, 5369, 3143, 2932, 3239, 6237, 6257, 6273, 6226, 3682, 3633, 6615, 6567, 6414, 4094, 5606, 3542, 3498, 6439, 6212, 6532, 3746, 5586, 3480, 3573, 6698, 6478, 6588, 6460, 5848, 3501, 3500, 6223, 6117, 6078, 6221, 5811, 3580, 3519, 6497, 6129, 6309, 6007, 5854, 3467, 3552, 6302, 6291, 6056, 6167, 5794, 3086, 3110, 6212, 6283, 6076, 6144, 5758, 3424, 3317, 6046, 6195, 5829, 5952, 5833, 3236, 2997, 5972, 5900, 6206, 6119, 5674, 3163, 2971, 5907, 5944, 5801, 5673, 5313, 3264, 2986, 5499, 3084, 7636, 5650, 5517, 3220, 3117, 5617, 5928, 5554, 5687, 5503, 3015, 2939, 5960, 5690, 5750, 6016, 5453, 3265, 3062, 5786, 6213, 5902, 5906, 5292, 3097, 3029, 5688, 5817, 5718, 5755, 5373, 2999, 2959, 5664, 5743, 5712, 5755, 5426, 3304, 3120, 5666, 5738, 5493, 5816, 5246, 3228, 3283, 5638, 5857, 5782, 5922, 5649, 3288, 3343, 6299, 6107, 6193, 6435, 5837, 3263, 3378, 6344, 6024, 6240, 6013, 5627, 3333, 3367, 6133, 6114, 6012, 6287, 6180, 3409, 3432, 6161, 6206, 6350, 6112, 6197, 3555, 3442, 6275, 6370, 6770, 6689, 6552, 3376, 3489, 6772, 6748, 6659, 6754, 6493, 3982, 3719, 6749, 6517, 6597, 6524, 6395, 3747, 3187, 6858, 6354, 6434, 3409, 8686, 3330, 3294, 5740, 3959, 6280, 6623, 6327, 3526, 3469, 6440, 6381, 6443, 6408, 6119, 3565, 3392, 6555, 6257, 6706, 6222, 6264, 3407, 3183, 3826, 6424, 6658, 6568, 6065, 3427, 3466, 6558, 6653, 6452, 6501, 6111, 3463, 3570, 7366, 6591, 6780, 6640, 6094, 3542, 3405, 6405, 6352, 6586, 6537, 6166, 3290, 3335, 6531, 6227, 6547, 6873, 6060, 3276, 3110, 5582, 4824, 2704, 2692, 2878, 2922, 2947, 5052, 4750, 3887, 3123, 4821, 3291, 3293, 6550, 6636, 6599, 6601, 6410, 3862, 3759, 6684, 6589, 6446, 6498, 6193, 3416, 3459, 6626, 6615, 6625, 6869, 6544, 3709, 3701, 6870, 6586, 6838, 6765, 6657, 3882] N = round(sum(docNum) / len(docNum)) # set N to normalize the window sizes docScale = [x / N for x in docNum] print(texts[1].decode('string_escape')) # pouziti pro nacteni bez codecs, zobrazuje ceske znaky # pomala varianta pres collections # cte ve formatu: texts = ['John likes to watch movies. Mary likes too.','John also likes to watch football games.'] bagsofwords = [collections.Counter(re.findall(r'\w+', txt)) for txt in texts] bagsofwords[0] # get the document sums for the individual days, measue time start = time.time() sumbags = sum(bagsofwords[501:1000], collections.Counter()) # time consuming, 500 docs takes 76s end = time.time() print(end - start) # rychlejsi varianta pres sparse matrices from sklearn.feature_extraction.text import CountVectorizer import numpy as np c = CountVectorizer(min_df=30, max_df=100000) # ignore all the words that appear in fewer than min_df docs # 2 months ... takes less than 1min, size 328468x450642, 30740640 stored elements for min_df=1, about 1/3 of the words # for min_df=3, for the annual data and min_df=20 shape 2090635 x 157556 bow_matrix = c.fit_transform(texts).astype(bool) # bow_matrix = c.fit_transform(texts[0:7366]) # sparse numpy int64 matrix originates, scipy.sparse.coo_matrix # c.vocabulary_ # get mapping between words and column indices, for complete data extremely large to print c.vocabulary_['rebel'] # index 127576 c.vocabulary_.keys()[127576] # list of keys but not the same order as in coo matrix print(c.vocabulary_.keys()[c.vocabulary_.values().index(127576)]) # this works inv_vocabulary = {v: k for k, v in c.vocabulary_.items()} # general vocabulary transpose inv_vocabulary[127576] # rebel inv_vocabulary[183107] # rebel def annot_list(ind): return [inv_vocabulary[k] for k in ind] bow_matrix.sum(1) # total word counts in each document, fast word_sums = bow_matrix.sum(0) # the counts of each word in all documents, slower but still works bow_matrix.sum(0).shape # get the counts for the individual days offset = 0 sum_matrix = np.empty([len(docNum), bow_matrix.shape[1]], dtype=int) offset_store = [0] for i in range(len(docNum)): sum_matrix[i] = bow_matrix[offset:offset + docNum[i]].sum(0) offset += docNum[i] offset_store.append(offset) # dfidf ad He et al.: Analyzing feature trajectories for event detection # idf ... word importance, more frequent words are less important idf = np.log(sum(docNum) / sum_matrix.sum(0)) dfidf = sum_matrix / np.tile(docNum, [sum_matrix.shape[1], 1]).T * np.tile(idf, [len(docNum), 1]) # normalize to uniform N, round to simplify e.g. future computations of binomial coeffiecients sum_matrix_norm = (np.round(sum_matrix / np.tile(docScale, [sum_matrix.shape[1], 1]).T)).astype(int) # the final check, the sum of window counts must be the total sum # the last window has to be +1 to make it work check = sum_matrix.sum(0) - word_sums check.sum() from scipy.special import binom from scipy.stats import binom as binm from scipy.stats import logistic # turn frequencies into probs p_o = sum_matrix / np.tile(docNum, [sum_matrix.shape[1], 1]).T # observed word probs, check that "from __future__ import division" was called p_o_norm = np.divide(sum_matrix, N) # observed word probs for normalized sum_matrix # p_j = p_o.mean(0) # mean word observed prob vector, rewrite, zero probs do not count def get_pj_slow(obs): pj = np.empty(obs.shape[1]) for i in range(len(pj)): pj[i] = obs[:, i][obs[:, i] > 0].mean() return pj def get_pj(obs): obs[obs == 0] = np.nan return np.nanmean(obs, 0) p_j = get_pj(p_o) # for normalized sum_matrix only, docNum replaced by N, faster but approximate probs only # robust towards high binom coefficients, log approach taken def get_p_g_norm_robust(N, sum_matrix, p_j): # precompute binom coefs up to max number in sum_matrix def mylogbc(max): mylogbc = np.zeros(max + 1) for i in range(max): mylogbc[i + 1] = mylogbc[i] + np.log(N - i) - np.log(i + 1) return mylogbc def mylogbin(n, p): return preclogbin[n] + n * np.log(p) + (N - n) * np.log(1 - p) mylogbin = np.vectorize(mylogbin) preclogbin = mylogbc(np.max(sum_matrix)) p_g = np.empty(sum_matrix.shape) for words in range(p_g.shape[1]): p_g[:, words] = mylogbin(sum_matrix[:, words], p_j[words]) return np.exp(p_g) # for normalized sum_matrix only, docNum replaced by N, faster but approximate probs only # fails for word counts and thus overflow binom coefficients!!! def get_p_g_norm(N, sum_matrix, p_j): def mybin(n, p): return binom(N, n) * p ** n * (1 - p) ** (N - n) mybin = np.vectorize(mybin) p_g = np.empty(sum_matrix.shape) for words in range(p_g.shape[1]): p_g[:, words] = mybin(sum_matrix[:, words], p_j[words]) return p_g # for normalized sum_matrix only, docNum replaced by N, faster but approximate probs only def get_r_c_thres_norm(N, sum_matrix, p_j): r_c_thres = np.empty(sum_matrix.shape[1]) for words in range(sum_matrix.shape[1]): r_c_thres[words] = binm.ppf(R_C_thres, N, p_j[words]) return r_c_thres # at the moment, the most time consuming part # can be made faster by normalizing to the same window size -- use docScale np.mean(p_o, axis=0) # p_o.mean(0) changes p_o, places nans there p_g = np.empty([len(docNum), bow_matrix.shape[ 1]]) # prob that the given number of words is observed in the given day purely randomly r_c_thres = np.empty(p_g.shape) for days in range(len(docNum)): for words in range(len(p_j)): p_g[days, words] = binom(docNum[days], sum_matrix[days, words]) * p_j[words] ** sum_matrix[days, words] * (1 - p_j[ words]) ** ( docNum[ days] - sum_matrix[ days, words]) # find the border of R_C region r_c_thres[days, words] = binm.ppf(R_C_thres, docNum[days], p_j[words]) p_g_norm = get_p_g_norm_robust(N, sum_matrix_norm, p_j) r_c_thres_norm = get_r_c_thres_norm(N, sum_matrix_norm, p_j) # construct bursty features, start with the individual ones p_b = np.zeros(p_o.shape) # p_b[p_o>np.tile(p_j,[p_o.shape[0],1])]=1 # the initial necessary condition, not in R_A region # p_b[sum_matrix>r_c_thres]=1 # the sufficient condition, in R_C region p_b[sum_matrix_norm > np.tile(r_c_thres_norm, [sum_matrix_norm.shape[0], 1])] = 1 # the sufficient condition, in R_C region # sigmoid function for R_B region # p_b[np.logical_and(sum_matrix<r_c_thres,p_o>np.tile(p_j,[p_o.shape[0],1]))]=... for days in range(len(docNum)): for words in range(len(p_j)): # if sum_matrix[days,words]<r_c_thres[days,words] and p_o[days,words]>p_j[words]: # p_b[days,words] = logistic.cdf(sum_matrix[days,words]-(r_c_thres[days,words]+p_j[words]*docNum[days])/2) if sum_matrix_norm[days, words] < r_c_thres_norm[words] and p_o[days, words] > p_j[words]: p_b[days, words] = logistic.cdf(sum_matrix_norm[days, words] - (r_c_thres_norm[words] + p_j[words] * N) / 2) # find the most striking bursts # there are many features with at least one non-zero burst signal ..., get their indeces [j for (i, j) in zip(sum(p_b), range(p_b.shape[1]))
per_split is False, num_splits=1 for the 'sqrt_covariance' only. """ assert imap.ndim in range(2, 6) imap = atleast_nd(imap, 5) num_arrays, num_splits, num_pol = imap.shape[:-2] if mode == 'fft': # get the power -- since filtering maps by their own power, only need diagonal. # also apply mask correction kmap = enmap.fft(imap*mask_est, normalize='phys', nthread=nthread) w2 = np.mean(mask_est**2) smap = (kmap * np.conj(kmap)).real / w2 if not per_split: smap = smap.mean(axis=-4, keepdims=True).real # bin the 2D power into ledges and take the square-root modlmap = smap.modlmap().astype(imap.dtype) # modlmap is np.float64 always... smap = radial_bin(smap, modlmap, ledges, weights=weights) ** 0.5 sqrt_cls = [] lfuncs = [] for i in range(num_arrays): for j in range(num_splits): # there is only one "filter split" if not per_split jfilt = j if not per_split: jfilt = 0 for k in range(num_pol): # interpolate to the center of the bins. lfunc, y = interp1d_bins(ledges, smap[i, jfilt, k], return_vals=True, kind='cubic', bounds_error=False) sqrt_cls.append(y) lfuncs.append(lfunc) # Re-do the FFT for the map masked with the bigger mask. kmap[:] = enmap.fft(imap*mask_observed, normalize='phys', nthread=nthread) # Apply the filter to the maps. for i in range(num_arrays): for j in range(num_splits): jfilt = j if not per_split else 0 for k in range(num_pol): flat_idx = np.ravel_multi_index((i, j, k), (num_arrays, num_splits, num_pol)) lfilter = 1/lfuncs[flat_idx](modlmap) assert np.all(np.isfinite(lfilter)), f'{i,jfilt,k}' assert np.all(lfilter > 0) kmap[i,j,k] *= lfilter sqrt_cls = np.array(sqrt_cls).reshape(num_arrays, num_splits, num_pol, -1) if return_sqrt_cov: return enmap.ifft(kmap, normalize='phys', nthread=nthread).real, sqrt_cls else: return enmap.ifft(kmap, normalize='phys', nthread=nthread).real elif mode == 'curvedsky': if lmax is None: lmax = lmax_from_wcs(imap.wcs) if ainfo is None: ainfo = sharp.alm_info(lmax) # since filtering maps by their own power only need diagonal alm = map2alm(imap*mask_est, ainfo=ainfo, lmax=lmax) cl = curvedsky.alm2cl(alm, ainfo=ainfo) if not per_split: cl = cl.mean(axis=-3, keepdims=True) # apply correction and take sqrt. # the filter is 1/sqrt pmap = enmap.pixsizemap(mask_est.shape, mask_est.wcs) w2 = np.sum((mask_est**2)*pmap) / np.pi / 4. sqrt_cl = (cl / w2)**0.5 lfilter = np.zeros_like(sqrt_cl) np.divide(1, sqrt_cl, where=sqrt_cl!=0, out=lfilter) # alm_c_utils.lmul cannot blindly broadcast filters and alms lfilter = np.broadcast_to(lfilter, (*imap.shape[:-2], lfilter.shape[-1])) # Re-do the SHT for the map masked with the bigger mask. alm = map2alm(imap*mask_observed, alm=alm, ainfo=ainfo, lmax=lmax) for preidx in np.ndindex(imap.shape[:-2]): assert alm[preidx].ndim == 1 assert lfilter[preidx].ndim == 1 alm[preidx] = alm_c_utils.lmul( alm[preidx], lfilter[preidx], ainfo ) # finally go back to map space omap = alm2map(alm, shape=imap.shape, wcs=imap.wcs, dtype=imap.dtype, ainfo=ainfo) if return_sqrt_cov: return omap, sqrt_cl else: return omap else: raise NotImplementedError('Only implemented modes are fft and curvedsky') def map2alm(imap, alm=None, ainfo=None, lmax=None, **kwargs): """A wrapper around pixell.curvedsky.map2alm that performs proper looping over array 'pre-dimensions'. Always performs a spin[0,2] transform if imap.ndim >= 3; therefore, 'pre-dimensions' are those at axes <= -4. Parameters ---------- imap : ndmap Map to transform. alm : arr, optional Array to write result into, by default None. If None, will be built based off other kwargs. ainfo : sharp.alm_info, optional An alm_info object, by default None. lmax : int, optional Transform bandlimit, by default None. Returns ------- ndarray The alms of the transformed map. """ if alm is None: alm, _ = curvedsky.prepare_alm( alm=alm, ainfo=ainfo, lmax=lmax, pre=imap.shape[:-2], dtype=imap.dtype ) for preidx in np.ndindex(imap.shape[:-3]): # map2alm, alm2map doesn't work well for other dims beyond pol component assert imap[preidx].ndim in [2, 3] curvedsky.map2alm( imap[preidx], alm=alm[preidx], ainfo=ainfo, lmax=lmax, **kwargs ) return alm def alm2map(alm, omap=None, shape=None, wcs=None, dtype=None, ainfo=None, **kwargs): """A wrapper around pixell.curvedsky.alm2map that performs proper looping over array 'pre-dimensions'. Always performs a spin[0,2] transform if imap.ndim >= 3; therefore, 'pre-dimensions' are those at axes <= -4. Parameters ---------- alm : arr The alms to transform. omap : ndmap, optional The output map into which the alms are transformed, by default None. If None, will be allocated according to shape, wcs, and dtype kwargs. shape : iterable, optional The sky-shape of the output map, by default None. Only the last two axes are used. Only used if omap is None. wcs : astropy.wcs.WCS, optional The wcs information of the output map, by default None. Only used if omap is None. dtype : np.dtype, optional The data type of the output map, by default None. Only used if omap is None. If omap is None and dtype is None, will be set to alm.real.dtype. ainfo : sharp.alm_info, optional An alm_info object, by default None. Returns ------- ndmap The (inverse)-transformed map. """ if omap is None: if dtype is None: dtype = alm.real.dtype omap = enmap.empty((*alm.shape[:-1], *shape[-2:]), wcs=wcs, dtype=dtype) for preidx in np.ndindex(alm.shape[:-2]): # map2alm, alm2map doesn't work well for other dims beyond pol component assert omap[preidx].ndim in [2, 3] omap[preidx] = curvedsky.alm2map( alm[preidx], omap[preidx], ainfo=ainfo, **kwargs ) return omap def downgrade_geometry_cc_quad(shape, wcs, dg): """Get downgraded geometry that adheres to Clenshaw-Curtis quadrature. Parameters ---------- shape : tuple Shape of map geometry to be downgraded. wcs : astropy.wcs.WCS Wcs of map geometry to be downgraded dg : int or float Downgrade factor. Returns ------- (tuple, astropy.wcs.WCS) The shape and wcs of the downgraded geometry. If dg <= 1, the geometry of the input map. Notes ----- Works by generating a fullsky geometry at downgraded resolution and slicing out coordinates of original map. """ if dg <= 1: return shape[-2:], wcs else: # get the shape, wcs corresponding to the sliced fullsky geometry, with resolution # downgraded vs. imap resolution by factor dg, containg sky footprint of imap res = np.deg2rad(np.abs(wcs.wcs.cdelt)) * dg full_dshape, full_dwcs = enmap.fullsky_geometry(res=res) full_dpixbox = enmap.skybox2pixbox( full_dshape, full_dwcs, enmap.corners(shape, wcs, corner=False), corner=False ) # we need to round this to an exact integer in order to guarantee that # the sliced geometry is still clenshaw-curtis compatible. we use # np.round here (as opposed to np.floor) since we want pixel centers, # see enmap.sky2pix documemtation full_dpixbox = np.round(full_dpixbox).astype(int) slice_dshape, slice_dwcs = slice_geometry_by_pixbox( full_dshape, full_dwcs, full_dpixbox ) return slice_dshape, slice_dwcs def empty_downgrade_cc_quad(imap, dg): """Get an empty enmap to hold the Clenshaw-Curtis-preserving downgraded map.""" oshape, owcs = downgrade_geometry_cc_quad(imap.shape, imap.wcs, dg) oshape = (*imap.shape[:-2], *oshape) omap = enmap.empty(oshape, owcs, dtype=imap.dtype) return omap def harmonic_downgrade_cc_quad(imap, dg, area_pow=0., dtype=None): """Downgrade a map by harmonic resampling into a geometry that adheres to Clenshaw-Curtis quadrature. This will bandlimit the input signal in harmonic space which may introduce ringing around bright objects, but will not introduce a pixel-window nor aliasing. Parameters ---------- imap : ndmap Map to be downgraded. dg : int or float Downgrade factor. area_pow : int or float, optional The area scaling of the downgraded signal, by default 0. Output map is multiplied by dg^(2*area_pow). dtype : np.dtype, optional If not None, cast the input map to this data type, by default None. Useful for allowing boolean masks to be "interpolated." Returns ------- ndmap The downgraded map. The unchanged input if dg <= 1. """ if dg <= 1: return imap else: # cast imap to dtype so now omap has omap dtype if dtype is not None: imap = imap.astype(dtype, copy=False) omap = empty_downgrade_cc_quad(imap, dg) lmax = lmax_from_wcs(imap.wcs) // dg # new bandlimit ainfo = sharp.alm_info(lmax) alm = map2alm(imap, ainfo=ainfo, lmax=lmax) # scale values by area factor, e.g. dg^2 if ivar maps mult = dg ** (2*area_pow) return mult * alm2map(alm, omap=omap, ainfo=ainfo) # inspired by optweight.map_utils.gauss2guass def interpol_downgrade_cc_quad(imap, dg, area_pow=0., dtype=None, negative_cdelt_ra=True, order=1, preconvolve=True): """Downgrade a map by spline interpolating into a geometry that adheres to Clenshaw-Curtis quadrature. This will bandlimit the input signal, but operates only in pixel space: there will be no ringing around bright sources, but this will introduce a pixel-window and aliasing. Parameters ---------- imap : ndmap Map to be downgraded. dg : int or float Downgrade factor. area_pow : int or float, optional The area scaling of the downgraded signal, by default 0. Output map is multiplied by dg^(2*area_pow). dtype : np.dtype, optional If not None, cast the input map to this data type, by default None. Useful for allowing boolean
features # MACCS feature: 130 atomic_mapping = MACCSFeaturizer.maccs_count_features_mapping(maccs_idx, substructures, num_atoms, atomic_mapping, feature_idx1=124, feature_idx2=130) # MACCS feature: 127 atomic_mapping = MACCSFeaturizer.maccs_count_features_mapping(maccs_idx, substructures, num_atoms, atomic_mapping, feature_idx1=143, feature_idx2=127) # MACCS feature: 138: atomic_mapping = MACCSFeaturizer.maccs_count_features_mapping(maccs_idx, substructures, num_atoms, atomic_mapping, feature_idx1=153, feature_idx2=138) # MACCS features: 140, 146, 159 ## 159 if maccs_idx == 164 and len(substructures) > 1: mapping_submol = [[] for _ in range(num_atoms)] count_atoms = 0 for atom_idx in range(num_atoms): for structure in substructures: if atom_idx in structure: mapping_submol[atom_idx].append(159) count_atoms += 1 count_atoms = 1 if count_atoms == 0 else count_atoms for i in range(num_atoms): if len(mapping_submol[i]) > 0: for _feature_idx in mapping_submol[i]: atomic_mapping[i].append((_feature_idx, count_atoms)) ## 146 if len(substructures) > 2: mapping_submol = [[] for _ in range(num_atoms)] count_atoms = 0 for atom_idx in range(num_atoms): for structure in substructures: if atom_idx in structure: mapping_submol[atom_idx].append(146) count_atoms += 1 count_atoms = 1 if count_atoms == 0 else count_atoms for i in range(num_atoms): if len(mapping_submol[i]) > 0: for _feature_idx in mapping_submol[i]: atomic_mapping[i].append((_feature_idx, count_atoms)) ## 140 if len(substructures) > 3: mapping_submol = [[] for _ in range(num_atoms)] count_atoms = 0 for atom_idx in range(num_atoms): for structure in substructures: if atom_idx in structure: mapping_submol[atom_idx].append(140) count_atoms += 1 count_atoms = 1 if count_atoms == 0 else count_atoms for i in range(num_atoms): if len(mapping_submol[i]) > 0: for _feature_idx in mapping_submol[i]: atomic_mapping[i].append((_feature_idx, count_atoms)) # MACCS feature 142 atomic_mapping = MACCSFeaturizer.maccs_count_features_mapping(maccs_idx, substructures, num_atoms, atomic_mapping, feature_idx1=161, feature_idx2=142) # MACCS feature 145 atomic_mapping = MACCSFeaturizer.maccs_count_features_mapping(maccs_idx, substructures, num_atoms, atomic_mapping, feature_idx1=163, feature_idx2=145) # MACCS feature 149 atomic_mapping = MACCSFeaturizer.maccs_count_features_mapping(maccs_idx, substructures, num_atoms, atomic_mapping, feature_idx1=160, feature_idx2=149) # Atomic number features for idx_maccs_atomnumb in idx_maccs_atomnumbs: maccs_feature = MACCSFeaturizer.SMARTS_ATOMIC_NUMBER[idx_maccs_atomnumb] feature_idx = idx_maccs_atomnumb mapping_submol = [[] for _ in range(num_atoms)] count_atoms = 0 for atom_idx in range(num_atoms): if atom_idx in maccs_feature: mapping_submol[atom_idx].append(feature_idx) count_atoms += 1 count_atoms = 1 if count_atoms == 0 else count_atoms for i in range(num_atoms): if len(mapping_submol[i]) > 0: for _feature_idx in mapping_submol[i]: atomic_mapping[i].append((_feature_idx, count_atoms)) # MACCS 125: Aromatic rings atomic_mapping = MACCSFeaturizer.maccs_125_aromaticrings_mapping(mol, num_atoms, atomic_mapping) # MACCS 166: Fragments atomic_mapping = MACCSFeaturizer.maccs_166_fragments_mapping(mol, num_atoms, atomic_mapping) return atomic_mapping def _atomic_attribution(self, molecule: Union[str, Mol, bytes], feature_attribution: np.ndarray, num_atoms: Optional[int] = None) -> np.ndarray: """adapted/based on the implementation by <NAME>""" mol = _init_molecule(molecule) num_atoms = mol.GetNumAtoms() if not num_atoms else num_atoms idx_maccs = list(MACCSFeaturizer.SMARTS_SUBSTR.keys()) idx_maccs_atomnumbs = list(MACCSFeaturizer.SMARTS_ATOMIC_NUMBER.keys()) atomic_attribution = np.zeros(num_atoms) for maccs_idx in idx_maccs: # Substructure features pattern = MACCSFeaturizer.SMARTS_SUBSTR[maccs_idx] attribution_value = feature_attribution[maccs_idx] substructures = mol.GetSubstructMatches(pattern) attribution_submol = np.zeros(num_atoms) count_atoms = 0 for atom_idx in range(num_atoms): for structure in substructures: if atom_idx in structure: attribution_submol[atom_idx] += attribution_value count_atoms += 1 if count_atoms != 0: attribution_submol = attribution_submol / count_atoms atomic_attribution += attribution_submol # Count features # MACCS feature: 130 atomic_attribution = MACCSFeaturizer.maccs_count_features(maccs_idx, substructures, feature_attribution, num_atoms, atomic_attribution, feature_idx1=124, feature_idx2=130) # MACCS feature: 127 atomic_attribution = MACCSFeaturizer.maccs_count_features(maccs_idx, substructures, feature_attribution, num_atoms, atomic_attribution, feature_idx1=143, feature_idx2=127) # MACCS feature: 138: atomic_attribution = MACCSFeaturizer.maccs_count_features(maccs_idx, substructures, feature_attribution, num_atoms, atomic_attribution, feature_idx1=153, feature_idx2=138) # MACCS features: 140, 146, 159 ## 159 if maccs_idx == 164 and len(substructures) > 1: attribution_value = feature_attribution[159] attribution_submol = np.zeros(num_atoms) count_atoms = 0 for atom_idx in range(num_atoms): for structure in substructures: if atom_idx in structure: attribution_submol[atom_idx] += attribution_value count_atoms += 1 if count_atoms != 0: attribution_submol = attribution_submol / count_atoms atomic_attribution += attribution_submol ## 146 if len(substructures) > 2: attribution_value = feature_attribution[146] attribution_submol = np.zeros(num_atoms) count_atoms = 0 for atom_idx in range(num_atoms): for structure in substructures: if atom_idx in structure: attribution_submol[atom_idx] += attribution_value count_atoms += 1 if count_atoms != 0: attribution_submol = attribution_submol / count_atoms atomic_attribution += attribution_submol ## 140 if len(substructures) > 3: attribution_value = feature_attribution[140] attribution_submol = np.zeros(num_atoms) count_atoms = 0 for atom_idx in range(num_atoms): for structure in substructures: if atom_idx in structure: attribution_submol[atom_idx] += attribution_value count_atoms += 1 if count_atoms != 0: attribution_submol = attribution_submol / count_atoms atomic_attribution += attribution_submol # MACCS feature 142 atomic_attribution = MACCSFeaturizer.maccs_count_features(maccs_idx, substructures, feature_attribution, num_atoms, atomic_attribution, feature_idx1=161, feature_idx2=142) # MACCS feature 145 atomic_attribution = MACCSFeaturizer.maccs_count_features(maccs_idx, substructures, feature_attribution, num_atoms, atomic_attribution, feature_idx1=163, feature_idx2=145) # MACCS feature 149 atomic_attribution = MACCSFeaturizer.maccs_count_features(maccs_idx, substructures, feature_attribution, num_atoms, atomic_attribution, feature_idx1=160, feature_idx2=149) # Atomic number features for idx_maccs_atomnumb in idx_maccs_atomnumbs: maccs_feature = MACCSFeaturizer.SMARTS_ATOMIC_NUMBER[idx_maccs_atomnumb] attribution_value = feature_attribution[idx_maccs_atomnumb] attribution_submol = np.zeros(num_atoms) count_atoms = 0 for atom_idx in range(num_atoms): if atom_idx in maccs_feature: attribution_submol[atom_idx] += attribution_value count_atoms += 1 if count_atoms != 0: attribution_submol = attribution_submol / count_atoms atomic_attribution += attribution_submol # MACCS 125: Aromatic rings atomic_attribution = MACCSFeaturizer.maccs_125_aromaticrings(mol, feature_attribution, num_atoms, atomic_attribution) # MACCS 166: Fragments atomic_attribution = MACCSFeaturizer.maccs_166_fragments(mol, feature_attribution, num_atoms, atomic_attribution) return atomic_attribution def atomic_mappings(self, smiles: List[str]) -> List[List[List[Tuple[int, int]]]]: _, mols = self._maccs(smiles) _mols = [m.ToBinary() for m in mols if m] if self.n_jobs > 1: atomic_mappings = process_map(self._atomic_mapping, _mols, chunksize=(len(smiles) // self.n_jobs) + 1 if self.chunksize is None else self.chunksize, # chunksize=1, max_workers=self.n_jobs, desc="_maccs_atomic_mappings", mp_context=mp.get_context(self.mp_context)) else: atomic_mappings = list( map(self._atomic_mapping, tqdm(_mols, total=len(smiles), desc="_maccs_atomic_mappings"))) return atomic_mappings def atomic_attributions(self, smiles: List[str], feature_attributions: np.ndarray) -> List[np.ndarray]: assert len(smiles) == len( feature_attributions), f"provided number of smiles {len(smiles)} does not match number of features {len(feature_attributions)}" _, mols = self._maccs(smiles) _mols = [m.ToBinary() for m in mols if m] if self.n_jobs > 1: atomic_attributions = process_map(self._atomic_attribution, _mols, feature_attributions, chunksize=(len(smiles) // self.n_jobs) + 1 if self.chunksize is None else self.chunksize, # chunksize=1, max_workers=self.n_jobs, desc="_maccs_atomic_attributions", mp_context=mp.get_context(self.mp_context)) else: atomic_attributions = list( map(self._atomic_attribution, tqdm(_mols, total=len(smiles), desc="_maccs_atomic_attributions"), feature_attributions)) return atomic_attributions @staticmethod def maccs_count_features_mapping(maccs_idx: int, substructures, num_atoms: int, atomic_mapping: List[List[Tuple[int, int]]], feature_idx1: int, feature_idx2: int ) -> List[List[Tuple[int, int]]]: if maccs_idx == feature_idx1 and len(substructures) > 1: mapping_submol = [[] for _ in range(num_atoms)] count_atoms = 0 for atom_idx in range(num_atoms): for structure in substructures: if atom_idx in structure: mapping_submol[atom_idx].append(feature_idx2) count_atoms += 1 count_atoms = 1 if count_atoms == 0 else count_atoms for i in range(num_atoms): if len(mapping_submol[i]) > 0: for _feature_idx in mapping_submol[i]: atomic_mapping[i].append((_feature_idx, count_atoms)) return atomic_mapping @staticmethod def maccs_count_features(maccs_idx: int, substructures, feature_attribution: np.ndarray, num_atoms: int, atomic_attribution: np.ndarray, feature_idx1: int, feature_idx2: int) -> np.ndarray: """based on the implementation by <NAME>""" if maccs_idx == feature_idx1 and len(substructures) > 1: attribution_value = feature_attribution[feature_idx2] weights_submol = np.zeros(num_atoms) count_atoms = 0 for atom_idx in range(num_atoms): for structure in substructures: if atom_idx in structure: weights_submol[atom_idx] += attribution_value count_atoms += 1 if count_atoms != 0: weights_submol = weights_submol / count_atoms atomic_attribution += weights_submol return atomic_attribution @staticmethod def isRingAromatic(mol: Mol, ringbond: Tuple[int, ...]) -> bool: """based on the implementation by <NAME>""" for id in ringbond: if not mol.GetBondWithIdx(id).GetIsAromatic(): return False return True @staticmethod def maccs_125_aromaticrings_mapping(mol: Mol, num_atoms: int, atomic_mapping: List[List[Tuple[int, int]]]): substructure = list() ri = mol.GetRingInfo() ringcount = ri.NumRings() rings = ri.AtomRings() ringbonds = ri.BondRings() if ringcount > 1: for ring_idx in range(ringcount): ring = rings[ring_idx] ringbond = ringbonds[ring_idx] is_aromatic = MACCSFeaturizer.isRingAromatic(mol, ringbond) if is_aromatic == True: substructure.append(ring) mapping_submol = [[] for _ in range(num_atoms)] count_atoms = 0 for atom_idx in range(num_atoms): for structure in substructure: if atom_idx in structure: mapping_submol[atom_idx].append(125) count_atoms += 1 count_atoms = 1 if count_atoms == 0 else count_atoms for i in range(num_atoms): if len(mapping_submol[i]) > 0: for _feature_idx in mapping_submol[i]: atomic_mapping[i].append((_feature_idx, count_atoms)) return atomic_mapping @staticmethod def maccs_125_aromaticrings(mol: Mol, feature_attribution: np.ndarray, num_atoms: int, atomic_attribution: np.ndarray) -> np.ndarray: """based on the implementation by <NAME>""" attribution_value = feature_attribution[125] substructure = list() ri = mol.GetRingInfo() ringcount = ri.NumRings() rings = ri.AtomRings() ringbonds = ri.BondRings() if ringcount > 1: for ring_idx in range(ringcount): ring = rings[ring_idx] ringbond = ringbonds[ring_idx] is_aromatic = MACCSFeaturizer.isRingAromatic(mol, ringbond) if is_aromatic == True: substructure.append(ring) weights_submol = np.zeros(num_atoms) count_atoms = 0 for atom_idx in range(num_atoms): for structure in substructure: if atom_idx in structure: weights_submol[atom_idx] += attribution_value count_atoms += 1 if count_atoms != 0: weights_submol = weights_submol / count_atoms atomic_attribution += weights_submol return atomic_attribution @staticmethod def maccs_166_fragments_mapping(mol: Mol, num_atoms: int, atomic_mapping: List[List[Tuple[int, int]]]) -> List[ List[Tuple[int, int]]]: frags = Chem.GetMolFrags(mol) if len(frags) > 1: mapping_submol = [[] for _ in range(num_atoms)] count_atoms = 0 for atom_idx in range(num_atoms): for structure in frags: if atom_idx in structure: mapping_submol[atom_idx].append(166) count_atoms += 1 count_atoms = 1 if count_atoms == 0 else count_atoms for i in range(num_atoms): if len(mapping_submol[i]) > 0: for _feature_idx in mapping_submol[i]:
<reponame>GruDev325/graphql-python-api from typing import List, Optional from ..error import GraphQLSyntaxError from .ast import Token from .block_string import dedent_block_string_value from .source import Source from .token_kind import TokenKind __all__ = ["Lexer", "is_punctuator_token_kind"] _punctuator_token_kinds = frozenset( [ TokenKind.BANG, TokenKind.DOLLAR, TokenKind.AMP, TokenKind.PAREN_L, TokenKind.PAREN_R, TokenKind.SPREAD, TokenKind.COLON, TokenKind.EQUALS, TokenKind.AT, TokenKind.BRACKET_L, TokenKind.BRACKET_R, TokenKind.BRACE_L, TokenKind.PIPE, TokenKind.BRACE_R, ] ) def is_punctuator_token_kind(kind: TokenKind) -> bool: """Check whether the given token kind corresponds to a punctuator. For internal use only. """ return kind in _punctuator_token_kinds def print_char(char: str) -> str: return repr(char) if char else TokenKind.EOF.value _KIND_FOR_PUNCT = { "!": TokenKind.BANG, "$": TokenKind.DOLLAR, "&": TokenKind.AMP, "(": TokenKind.PAREN_L, ")": TokenKind.PAREN_R, ":": TokenKind.COLON, "=": TokenKind.EQUALS, "@": TokenKind.AT, "[": TokenKind.BRACKET_L, "]": TokenKind.BRACKET_R, "{": TokenKind.BRACE_L, "}": TokenKind.BRACE_R, "|": TokenKind.PIPE, } class Lexer: """GraphQL Lexer A Lexer is a stateful stream generator in that every time it is advanced, it returns the next token in the Source. Assuming the source lexes, the final Token emitted by the lexer will be of kind EOF, after which the lexer will repeatedly return the same EOF token whenever called. """ def __init__(self, source: Source): """Given a Source object, initialize a Lexer for that source.""" self.source = source self.token = self.last_token = Token(TokenKind.SOF, 0, 0, 0, 0) self.line, self.line_start = 1, 0 def advance(self) -> Token: """Advance the token stream to the next non-ignored token.""" self.last_token = self.token token = self.token = self.lookahead() return token def lookahead(self) -> Token: """Look ahead and return the next non-ignored token, but do not change state.""" token = self.token if token.kind != TokenKind.EOF: while True: if not token.next: token.next = self.read_token(token) token = token.next if token.kind != TokenKind.COMMENT: break return token def read_token(self, prev: Token) -> Token: """Get the next token from the source starting at the given position. This skips over whitespace until it finds the next lexable token, then lexes punctuators immediately or calls the appropriate helper function for more complicated tokens. """ source = self.source body = source.body body_length = len(body) pos = prev.end while pos < body_length: char = body[pos] # SourceCharacter if char in " \t,\ufeff": pos += 1 continue elif char == "\n": pos += 1 self.line += 1 self.line_start = pos continue elif char == "\r": if body[pos + 1 : pos + 2] == "\n": pos += 2 else: pos += 1 self.line += 1 self.line_start = pos continue line = self.line col = 1 + pos - self.line_start kind = _KIND_FOR_PUNCT.get(char) if kind: return Token(kind, pos, pos + 1, line, col, prev) if "A" <= char <= "Z" or "a" <= char <= "z" or char == "_": return self.read_name(pos, line, col, prev) if "0" <= char <= "9" or char == "-": return self.read_number(pos, char, line, col, prev) if char == "#": return self.read_comment(pos, line, col, prev) if char == '"': if body[pos + 1 : pos + 3] == '""': return self.read_block_string(pos, line, col, prev) return self.read_string(pos, line, col, prev) if char == ".": if body[pos + 1 : pos + 3] == "..": return Token(TokenKind.SPREAD, pos, pos + 3, line, col, prev) raise GraphQLSyntaxError(source, pos, unexpected_character_message(char)) line = self.line col = 1 + pos - self.line_start return Token(TokenKind.EOF, body_length, body_length, line, col, prev) def read_comment( self, start: int, line: int, col: int, prev: Optional[Token] ) -> Token: """Read a comment token from the source file.""" body = self.source.body body_length = len(body) position = start while True: position += 1 if position >= body_length: break char = body[position] if char < " " and char != "\t": break return Token( TokenKind.COMMENT, start, position, line, col, prev, body[start + 1 : position], ) def read_number( self, start: int, char: str, line: int, col: int, prev: Optional[Token] ) -> Token: """Reads a number token from the source file. Either a float or an int depending on whether a decimal point appears. """ source = self.source body = source.body position = start is_float = False if char == "-": position += 1 char = body[position : position + 1] if char == "0": position += 1 char = body[position : position + 1] if "0" <= char <= "9": raise GraphQLSyntaxError( source, position, f"Invalid number, unexpected digit after 0: {print_char(char)}.", ) else: position = self.read_digits(position, char) char = body[position : position + 1] if char == ".": is_float = True position += 1 char = body[position : position + 1] position = self.read_digits(position, char) char = body[position : position + 1] if char and char in "Ee": is_float = True position += 1 char = body[position : position + 1] if char and char in "+-": position += 1 char = body[position : position + 1] position = self.read_digits(position, char) char = body[position : position + 1] # Numbers cannot be followed by . or NameStart if char and (char == "." or is_name_start(char)): raise GraphQLSyntaxError( source, position, f"Invalid number, expected digit but got: {print_char(char)}.", ) return Token( TokenKind.FLOAT if is_float else TokenKind.INT, start, position, line, col, prev, body[start:position], ) def read_digits(self, start: int, char: str) -> int: """Return the new position in the source after reading digits.""" source = self.source body = source.body position = start while "0" <= char <= "9": position += 1 char = body[position : position + 1] if position == start: raise GraphQLSyntaxError( source, position, f"Invalid number, expected digit but got: {print_char(char)}.", ) return position def read_string( self, start: int, line: int, col: int, prev: Optional[Token] ) -> Token: """Read a string token from the source file.""" source = self.source body = source.body body_length = len(body) position = start + 1 chunk_start = position value: List[str] = [] append = value.append while position < body_length: char = body[position] if char in "\n\r": break if char == '"': append(body[chunk_start:position]) return Token( TokenKind.STRING, start, position + 1, line, col, prev, "".join(value), ) if char < " " and char != "\t": raise GraphQLSyntaxError( source, position, f"Invalid character within String: {print_char(char)}.", ) position += 1 if char == "\\": append(body[chunk_start : position - 1]) char = body[position : position + 1] escaped = _ESCAPED_CHARS.get(char) if escaped: value.append(escaped) elif char == "u" and position + 4 < body_length: code = uni_char_code(*body[position + 1 : position + 5]) if code < 0: escape = repr(body[position : position + 5]) escape = escape[:1] + "\\" + escape[1:] raise GraphQLSyntaxError( source, position, f"Invalid character escape sequence: {escape}.", ) append(chr(code)) position += 4 else: escape = repr(char) escape = escape[:1] + "\\" + escape[1:] raise GraphQLSyntaxError( source, position, f"Invalid character escape sequence: {escape}.", ) position += 1 chunk_start = position raise GraphQLSyntaxError(source, position, "Unterminated string.") def read_block_string( self, start: int, line: int, col: int, prev: Optional[Token] ) -> Token: source = self.source body = source.body body_length = len(body) position = start + 3 chunk_start = position raw_value = "" while position < body_length: char = body[position] if char == '"' and body[position + 1 : position + 3] == '""': raw_value += body[chunk_start:position] return Token( TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, dedent_block_string_value(raw_value), ) if char < " " and char not in "\t\n\r": raise GraphQLSyntaxError( source, position, f"Invalid character within String: {print_char(char)}.", ) if char == "\n": position += 1 self.line += 1 self.line_start = position elif char == "\r": if body[position + 1 : position + 2] == "\n": position += 2 else: position += 1 self.line += 1 self.line_start = position elif char == "\\" and body[position + 1 : position + 4] == '"""': raw_value += body[chunk_start:position] + '"""' position += 4 chunk_start = position else: position += 1 raise GraphQLSyntaxError(source, position, "Unterminated string.") def read_name( self, start: int, line: int, col: int, prev: Optional[Token] ) -> Token: """Read an alphanumeric + underscore name from the source.""" body = self.source.body body_length = len(body) position = start + 1 while position < body_length: char = body[position] if not ( char == "_" or "0" <= char <= "9"
i2] = [alti1, alti2] w[i2, i1] = [0, 1] other[i2, i1] = [alti2, alti1] elif symetrize: w[i1, i2] = [0.5, 0.5] other[i1, i2] = [i1 + mp, i2 - mp] w[i2, i1] = [0.5, 0.5] other[i2, i1] = [i2 - mp, i1 + mp] elif i1 >= mt + me: # BB if P_track_T: w[i1, i2] = [0, 1] other[i1, i2] = [alti1, alti2] w[i2, i1] = [0, 1] other[i2, i1] = [alti2, alti1] agrp.create_dataset("other", data=nm.array( other.flat[:], dtype=nm.int)) agrp.create_dataset("w", data=nm.array(w.flat[:], dtype=nm.double)) setnames(agrp, names) return agrp return None def add_icalTP_component(lkl_grp, names, calib_order, P_track_T, symetrize, position=-1): typ = "icalTP" im = [] dnames = get_dnames(lkl_grp) for i, n in enumerate(names): if "calib" in n: det = re.findall("calib_(.+)", n)[0] idx = dnames.index(det) im += [idx] if len(im): agrp = add_component(lkl_grp, typ, position) agrp.create_dataset("im", data=nm.array(im, dtype=nm.int)) hascl = lkl_grp.attrs["has_cl"] mt = lkl_grp.attrs["m_channel_T"] mp = lkl_grp.attrs["m_channel_P"] me = lkl_grp.attrs["m_channel_P"] * hascl[1] mb = lkl_grp.attrs["m_channel_P"] * hascl[2] m = mt + me + mb t_order = calib_order[:mt] p_order = calib_order[mt:] w = nm.zeros((m, m, 2), dtype=nm.double) other = nm.zeros((m, m, 2), dtype=nm.int) for i1 in range(m): alti1 = i1 if i1 >= mt and i1 < mt + me and p_order[i1 - mt] in t_order: alti1 = t_order.index(p_order[i1 - mt]) elif i1 >= mt + me and p_order[i1 - mt - me] in t_order: alti1 = t_order.index(p_order[i1 - mt - me]) for i2 in range(i1, m): alti2 = i2 if i2 >= mt and i2 < mt + me and p_order[i2 - mt] in t_order: alti2 = t_order.index(p_order[i2 - mt]) elif i2 >= mt + me and p_order[i2 - mt - me] in t_order: alti2 = t_order.index(p_order[i2 - mt - me]) # general case, nothing to do w[i1, i2] = [1, 0] other[i1, i2] = [i1, i2] w[i2, i1] = [1, 0] other[i2, i1] = [i2, i1] if i1 < mt and i2 >= mt and i2 < mt + me: # TE if P_track_T and p_order[i2 - mt] in t_order: w[i1, i2] = [0, 1] other[i1, i2] = [i1, alti2] w[i2, i1] = [0, 1] other[i2, i1] = [alti2, i1] elif symetrize and p_order[i2 - mt] in t_order and t_order[i1] in p_order: w[i1, i2] = [0.5, 0.5] other[i1, i2] = [p_order.index( t_order[i1]) + mt, alti2] w[i2, i1] = [0.5, 0.5] other[i2, i1] = [ alti2, p_order.index(t_order[i1]) + mt] elif i1 < mt and i2 >= mt + me: # TB if P_track_T and p_order[i2 - mt - me] in t_order: w[i1, i2] = [0, 1] other[i1, i2] = [i1, alti2] w[i2, i1] = [0, 1] other[i2, i1] = [alti2, i1] elif symetrize and p_order[i2 - mt - me] in t_order and t_order[i1] in p_order: w[i1, i2] = [0.5, 0.5] other[i1, i2] = [p_order.index( t_order[i1]) + mt + me, alti2] w[i2, i1] = [0.5, 0.5] other[i2, i1] = [ alti2, p_order.index(t_order[i1]) + mt + me] elif i1 >= mt and i1 < mt + me and i2 < mt + me: # EE if P_track_T: w[i1, i2] = [0, 1] other[i1, i2] = [alti1, alti2] w[i2, i1] = [0, 1] other[i2, i1] = [alti2, alti1] elif i1 >= mt and i1 < mt + me and i2 >= mt + me: # EB if P_track_T: w[i1, i2] = [0, 1] other[i1, i2] = [alti1, alti2] w[i2, i1] = [0, 1] other[i2, i1] = [alti2, alti1] elif symetrize: w[i1, i2] = [0.5, 0.5] other[i1, i2] = [i1 + mp, i2 - mp] w[i2, i1] = [0.5, 0.5] other[i2, i1] = [i2 - mp, i1 + mp] elif i1 >= mt + me: # BB if P_track_T: w[i1, i2] = [0, 1] other[i1, i2] = [alti1, alti2] w[i2, i1] = [0, 1] other[i2, i1] = [alti2, alti1] agrp.create_dataset("other", data=nm.array( other.flat[:], dtype=nm.int)) agrp.create_dataset("w", data=nm.array(w.flat[:], dtype=nm.double)) setnames(agrp, names) return agrp return None def add_gcal2_component(lkl_grp, names, tpl, position=-1): typ = "gcal2" agrp = add_component(lkl_grp, typ, position) im = [] jm = [] tpls = [] dnames = get_dnames(lkl_grp) # compute nq here for i, n in enumerate(names): if "beammode_" in n: det1, det2, mode = re.findall("beammode_(.+)_(.+)_(\d+)", n)[0] idx1 = dnames.index(det1) idx2 = dnames.index(det2) im += [idx1] jm += [idx2] tpls += [tpl[i]] agrp.create_dataset("im", data=nm.array(im, dtype=nm.int)) agrp.create_dataset("jm", data=nm.array(jm, dtype=nm.int)) agrp.create_dataset("tpl", data=nm.array( nm.concatenate(tpls), dtype=nm.double)) setnames(agrp, names) return agrp def read_gcal_data(pars, lkl_grp): return read_gcal_data_(pars.str_array.datacal, pars.float_array.ngcal, pars.int_array(default=[-1]).lmax_tpl, lkl_grp) def read_gcal_data_(datacal, ngcal, lmax_tpl, lkl_grp): # returns the dtemplate data lmin = lkl_grp.attrs["lmin"] lmax = lkl_grp.attrs["lmax"] if len(datacal) == 1: dat = nm.loadtxt(datacal[0]).flat[:] else: assert len(datacal) == len(ngcal) dat = () i = 0 if len(lmax_tpl) == 1: lmax_tpl = list(lmax_tpl) * len(ngcal) assert len(ngcal) == len(lmax_tpl) for ff, lm in zip(datacal, lmax_tpl): assert lm >= lmax idat = nm.loadtxt(ff).flat[:] if lm != -1: idat.shape = (-1, lm + 1) idat = idat[:ngcal[i], lmin:lmax + 1] idat = idat.flat[:] dat = nm.concatenate((dat, idat)) return dat def add_gcal_component_pars(lkl_grp, pars): typ = pars.str.type ngcal = pars.float_array.ngcal gcaltpl = read_gcal_data(pars, lkl_grp) names = [] if "name" in pars: names = pars.str_array.name assert len(names) == nm.sum(ngcal) binned = bool(pars.int(default=0).binned != 0) return add_gcal_component(lkl_grp, typ, ngcal, galtpl, binned, names) def setnames(agrp, names): agrp.attrs["names"] = php.pack256(*names) def add_egfs_component(lkl_grp, vpars, defaults, values, lmin, lmax, template_names, tpls, cib_decor_clustering, position=-1): from . import egfs agrp = add_component(lkl_grp, "egfs", position) egfs.add_xxx(agrp, vpars, defaults, values, lmin, lmax, template_names, tpls, cib_decor_clustering) agrp.attrs["A_cmb"] = lkl_grp.attrs["A_cmb"] return agrp def add_from_pars(lkl_grp, parfile): from . import miniparse pars = miniparse.miniparse(parfile) typ = pars.str.ctype return globals()["add_%s_component_pars"](lkl_grp, pars) def add_parametric_component(lkl_grp, name, dets, vpars, lmin, lmax, defaults={}, color=None, rename={}, voidmask="", data=None, position=-1): import os from . import parametric import os.path as osp # parametric.register_all(parametric.__dict__,False) # initialize parameters prclass = getattr(parametric, name) nT = lkl_grp.attrs["m_channel_T"] nP = lkl_grp.attrs["m_channel_P"] if issubclass(prclass, parametric.parametric_pol): has_cl = lkl_grp.attrs["has_cl"] pm = prclass(dets[:nT], dets[nT:], has_cl, vpars, lmin, lmax, defaults, color=color, rename=rename, voidmask=voidmask) else: dets = dets[:nT] if color != None: color = color[:nT] pm = prclass(dets, vpars, lmin, lmax, defaults, color=color, rename=rename, voidmask=voidmask) # filter them out npars = [vp for vp in vpars if pm.has_parameter(vp)] agrp = add_component(lkl_grp, pm.name, position) agrp.attrs["ndim"] = len(npars) agrp.attrs["keys"] = php.pack256(*npars) nefaults = pm.defaults agrp.attrs["ndef"] = len(nefaults) defkey = list(nefaults.keys()) defval = [nefaults[k] for k in defkey] agrp.attrs["defaults"] = php.pack256(*defkey) agrp.attrs["values"] = php.pack256(*defval) agrp.attrs["lmin"] = lmin agrp.attrs["lmax"] = lmax agrp.attrs["dfreq"] = [float(d) for d in dets] agrp.attrs["A_cmb"] = lkl_grp.attrs["A_cmb"] voidmask = pm.voidmask if voidmask: _voidlist = [i for i in range( len(voidmask)) if not bool(int(voidmask[i]))] nvoid = len(_voidlist) if nvoid != 0: agrp.attrs["nvoid"] = nvoid agrp.attrs["voidlist"] = _voidlist if color is not None: agrp.create_dataset("color", data=color.flat[:]) template = pm.get_template() if template is None: pass else: if data is None: agrp.create_dataset("template", data=nm.array( template, dtype=nm.double).flat[:]) else: agrp.create_dataset("template", data=nm.array( data, dtype=nm.double).flat[:]) rename = pm.rename if rename: rename_from = list(rename.keys()) rename_to = [rename[k] for k in rename_from] agrp.attrs["rename_from"] = php.pack256(*rename_from) agrp.attrs["rename_to"] = php.pack256(*rename_to) agrp.attrs["nrename"] = len(rename_from) return agrp import numpy as nm def set_criterion(lkl_grp, typ, **extra): if typ.lower() == "classic": lkl_grp.attrs["criterion"] = "classic" return if typ.lower() == "eig": lkl_grp.attrs["criterion"] = "eig" if "eig_norm" in extra: lkl_grp["criterion_eig_norm"] = extra["eig_nrm"] else: import numpy.linalg as la import numpy as nm rqh = lkl_grp["Rq_hat"][:] nq = len(lkl_grp["wq"][:]) m = lkl_grp.attrs["m_channel_T"] + lkl_grp.attrs["m_channel_P"] rqh.shape = (nq, m, m) nrm = nm.array([.5 * (nm.log(nm.abs(la.det(rqh[i]))) + m) for i in range(nq)]) lkl_grp["criterion_eig_norm"] = nrm return if typ.lower() == "gauss": import numpy.linalg as la import numpy as nm if "mask" in extra: lkl_grp["criterion_gauss_mask"] = extra["mask"].flat[:] if "ordering" in extra: lkl_grp["criterion_gauss_ordering"] = extra["ordering"].flat[:] lkl_grp["criterion_gauss_mat"] = extra["mat"].flat[:] lkl_grp.attrs["criterion"] = "gauss" return if typ.lower() == "quad": import numpy as nm if "fid" in extra: if "mask" in extra: lkl_grp["criterion_quad_mask"] = extra["mask"].flat[:] mask = extra["mask"].flat[:] rq = extra["fid"] * 1. n = int(nm.sqrt(mask.size)) rq.shape = (-1, n, n) mask.shape = (n, n) sn = int(nm.sum(nm.triu(mask))) fq = nm.zeros((len(rq), sn, sn)) for i in range(len(rq)): ifq = build_tensormat(rq[i], mask) fq[i] = nm.linalg.inv(ifq) lkl_grp["criterion_quad_mat"] = fq.flat[:] else: lkl_grp["criterion_quad_mat"] = extra["fid"].flat[:] lkl_grp.attrs["criterion"] = "quad" return def build_tensormat(rq, mask=None): n = len(rq) if mask == None: mask = nm.ones((n, n))
<filename>pyfda/tree_builder.py<gh_stars>1-10 # -*- coding: utf-8 -*- # # This file is part of the pyFDA project hosted at https://github.com/chipmuenk/pyfda # # Copyright © pyFDA Project Contributors # Licensed under the terms of the MIT License # (see file LICENSE in root directory for details) """ Create the tree dictionaries containing information about filters, filter implementations, widgets etc. in hierarchical form """ from __future__ import print_function, division, unicode_literals, absolute_import import os, sys, six from pprint import pformat import importlib if sys.version_info > (3,): # True for Python 3 import configparser else: import ConfigParser as configparser import logging logger = logging.getLogger(__name__) import pyfda.filterbroker as fb import pyfda.filter_factory as ff import pyfda.pyfda_dirs as dirs from .frozendict import freeze_hierarchical #-------------------------------------------------------------------------- def merge_dicts(d1, d2, path=None, mode='keep1'): """ Merge the multi-level dictionaries d1 and d2. The ``mode`` flag determines the behaviour when the same key is present in both dictionaries: * :keep1: keep the entry from dict1 * :keep2: keep the entry from dict2 * :add1: merge the entries, putting the values from dict2 first (important for lists) * :add2: merge the entries, putting the values from dict1 first ( " ) The parameter ``path`` is only used for keeping track of the hierarchical structure for error messages, it should not be set when calling the function. dict1 is modified in place and returned, if this is not intended call the function using ``new_dict = merge_dicts(dict(d1), d2)``. Example ------- >>> merge_dicts(fil_tree, fil_tree_add, mode='add1') Notes ----- If you need to merge more than two dicts use: >>> from functools import reduce # only for py3 >>> reduce(merge, [d1, d2, d3...]) # add / merge all other dicts into d1 Taken with some modifications from: http://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge """ if not(isinstance(d1, dict) and isinstance(d2, dict)): # at least one of the arguments is not a dict -> don't do anything return d1 if path is None: path = "" for key in d2: if key in d1: if isinstance(d1[key], dict) and isinstance(d2[key], dict): # both entries are dicts, recurse one level deeper: merge_dicts(d1[key], d2[key], path = path + str(key), mode=mode) #TODO: elif <either d1[key] OR d2[key] is not a dict> -> exception elif d1[key] == d2[key] or mode == 'keep1': pass # keep item in dict1, discard item with same key in dict1 elif mode == 'keep2': d1[key] = d2[key] # replace item in dict1 by item in dict2 else: try: if mode == 'add2': if (isinstance(d1[key], tuple) and isinstance(d2[key], tuple)): d1[key] = (d2[key][0], d2[key][1] + d1[key][1]) else: d1[key] = d2[key] + d1[key] elif mode == 'add1': if (isinstance(d1[key], tuple) and isinstance(d2[key], tuple)): d1[key] = (d1[key][0], d1[key][1] + d2[key][1]) else: d1[key] = d1[key] + d2[key] else: logger.warning("Unknown merge mode {0}.".format(mode)) except Exception as e: logger.warning("Merge conflict at {0}: {1}".format(path + str(key), e )) else: d1[key] = d2[key] # add new entry to dict1 return d1 class ParseError(Exception): pass class Tree_Builder(object): """ Read the config file and construct dictionary trees with - all filter combinations - valid combinations of filter designs and fixpoint implementations """ def __init__(self): logger.debug("Config file: {0:s}\n".format(dirs.USER_CONF_DIR_FILE)) self.init_filters() #============================================================================== def init_filters(self): """ Run at startup to populate global dictionaries and lists: - :func:`parse_conf_file()`: Parse the configuration file ``pyfda.conf`` (specified in ``dirs.USER_CONF_DIR_FILE``), writing classes and file paths to lists for the individual sections, a.o. to ``fb.filter_designs_list`` for the filter design algorithms. - :func:`dyn_filt_import()` : Try to import all filter modules and classes from ``fb.filter_designs_list`` and store successful imports in the dict ``fb.fil_classes`` as {filterName:filterModule}: - Read attributes (`ft`, `rt`, `fo`) from all valid filter classes (`fc`) in the global dict ``fb.fil_classes`` and store them in the filter tree dict ``fil_tree`` with the hierarchy **rt-ft-fc-fo-subwidget:params** . Parameters ---------- None Returns ------- None, but populates the following global attributes: - ``fb.fil_tree``: - """ self.parse_conf_file() self.dyn_filt_import() fil_tree = {} for fc in fb.fil_classes: # iterate over all previously found filter classes fc # instantiate a global instance ff.fil_inst() of filter class fc err_code = ff.fil_factory.create_fil_inst(fc) if err_code > 0: logger.warning('Skipping filter class "{0:s}" due to import error {1:d}'.format(fc, err_code)) continue # continue with next entry in fb.fil_classes # add attributes from dict to fil_tree for filter class fc fil_tree = self.build_fil_tree(fc, ff.fil_inst.rt_dict, fil_tree) # merge additional rt_dict (optional) into filter tree if hasattr(ff.fil_inst, 'rt_dict_add'): fil_tree_add = self.build_fil_tree(fc, ff.fil_inst.rt_dict_add) merge_dicts(fil_tree, fil_tree_add, mode='add1') # Make the dictionary and all sub-dictionaries read-only ("FrozenDict"): fb.fil_tree = freeze_hierarchical(fil_tree) # Test Immutatbility # fil_tree_ref = fb.fil_tree['LP']['FIR']['Equiripple']['min'] # fil_tree_ref.update({'msg':("hallo",)}) # this changes fb.fil_tree !! # fb.fil_tree['LP']['FIR']['Equiripple']['min']['par'] = ("A_1","F_1") # print(type(fb.fil_tree['LP']['FIR']['Equiripple'])) logger.debug("\nfb.fil_tree =\n%s", pformat(fb.fil_tree)) #============================================================================== def parse_conf_file(self): """ Parse the file ``dirs.USER_CONF_DIR_FILE`` with the following sections :[Dirs1] and [Dirs2]: Try to find user directories and store them in ``dirs.USER_DIRS`` and ``dirs.USER_DIR_LABEL``. For the other sections, a list of tuples is returned with the elements ``(class, dir)`` where "class" is the class name of the widget and "dir" specifies the directory for user widgets and None for standard widgets: :[Input Widgets]: Store a list of tuples of (user) input widgets in ``fb.input_widgets_list`` :[Plot Widgets]: Store a list of tuples of (user) plot widgets in ``fb.plot_widgets_list`` :[Filter Designs]: Store a list of tuples of (user) filter designs in ``fb.filter_designs_list`` :[Fixpoint Widgets]: Store a list of tuples of (user) fixpoint widgets in ``fb.fixpoint_widgets_list`` Parameters ---------- None Returns ------- None """ try: # Test whether user config file is readable, this is necessary as # configParser quietly fails when the file doesn't exist if not os.access(dirs.USER_CONF_DIR_FILE, os.R_OK): raise IOError('Config file "{0}" cannot be read.'.format(dirs.USER_CONF_DIR_FILE)) # setup an instance of config parser, allow keys without value conf = configparser.ConfigParser(allow_no_value=True) # preserve case of parsed options by overriding optionxform(): # Set it to function str() conf.optionxform = str # Allow interpolation across sections, ${Dirs:dir1} # conf._interpolation = configparser.ExtendedInterpolation() # PY3 only conf.read(dirs.USER_CONF_DIR_FILE) logger.info('Parsing config file\n\t"{0}"\n\t\twith sections:\n\t{1}' .format(dirs.USER_CONF_DIR_FILE, str(conf.sections()))) # ----------------------------------------------------------------- # Parsing [Common] #------------------------------------------------------------------ try: commons = {} items_list = conf.items('Common') # list of entries from section [Common] except configparser.NoSectionError: logger.critical("No section '[Common]' in\n" "'{0:s}'\n" "You can either edit the file or delete it, in this case " "a new configuration file will be created at restart."\ .format(dirs.USER_CONF_DIR_FILE)) sys.exit() if len(items_list) > 0: for i in items_list: commons.update({i[0]:i[1]}) # standard widget, no dir specified if not 'version' in commons or int(commons['version']) < 1: logger.critical("Version {2} of 'pyfda.conf' < {0} or no option 'version' in\n" "'{1:s}'\n" "Please delete the file and restart pyfdax, " "a new configuration file will be created.".format(1, dirs.USER_CONF_DIR_FILE, commons['version'])) sys.exit() logger.info("commons: {0}\n".format(commons)) # ----------------------------------------------------------------- # Parsing directories [Dirs] #------------------------------------------------------------------ #dirs.USER_DIR_LABEL = None # last valid user label entry (legacy) #dirs.USER_DIR = None # last valid user dir (legacy) dirs.USER_DIRS = {} # dict with user label : user_dir pairs for section in ['Dirs1','Dirs2']: try: for d in conf.items(section): user_dir = os.path.normpath(d[1]) if os.path.exists(user_dir): try: dirs.USER_DIRS.update({d[0]:user_dir}) #dirs.USER_DIR_LABEL = d[0] #dirs.USER_DIR = user_dir except TypeError: logger.warning('Unsuitable key - value pair\n"{0}" - "{1}".' .format(d[0],d[1])) except (AttributeError, KeyError): logger.info("No user directory specified.") except configparser.NoSectionError: logger.info("No section [{0:s}] found.".format(section)) if dirs.USER_DIRS: # use last found directory logger.info("User directory(s):\n{0}".format(dirs.USER_DIRS)) else: logger.warning('No valid user directory found in "{0}.' .format(dirs.USER_CONF_DIR_FILE)) # ----------------------------------------------------------------- # Parsing [Input Widgets] #------------------------------------------------------------------ fb.input_widgets_list = self.parse_conf_section(conf, "Input Widgets") # ----------------------------------------------------------------- # Parsing [Plot Widgets] #------------------------------------------------------------------ fb.plot_widgets_list = self.parse_conf_section(conf, "Plot Widgets") # ----------------------------------------------------------------- # Parsing [Filter Designs] #------------------------------------------------------------------ fb.filter_designs_list = self.parse_conf_section(conf, "Filter Designs") # ----------------------------------------------------------------- # Parsing [Fixpoint Filters] #------------------------------------------------------------------ fb.fixpoint_widgets_list = self.parse_conf_section(conf, "Fixpoint Widgets") # ----- Exceptions ---------------------- except configparser.ParsingError as e: logger.critical('Parsing Error in config file "{0}:\n{1}".' .format(dirs.USER_CONF_DIR_FILE,e)) sys.exit() except configparser.NoSectionError as e: logger.critical('{0} in config file "{1}".'.format(e, dirs.USER_CONF_DIR_FILE)) sys.exit() # configparser.NoOptionError except configparser.DuplicateSectionError as e: logger.warning('{0} in config file "{1}".'.format(e, dirs.USER_CONF_DIR_FILE)) except configparser.Error as e: logger.critical('{0} in config file "{1}".'.format(e, dirs.USER_CONF_DIR_FILE)) sys.exit() # Py3 only? # except configparser.DuplicateOptionError as e: # logger.warning('{0} in config file "{1}".'.format(e, dirs.USER_CONF_DIR_FILE)) except IOError as e: logger.critical('{0}'.format(e)) sys.exit() #============================================================================== def parse_conf_section(self, conf, section, req=True): """ Parse ``section`` in ``dirs.USER_CONF_DIR_FILE`` and return a list of tuples with the elements ``(class, dir)`` where "class" is the class name of the widget
item by id for imageFolders. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.portals_id_image_folders_fk_put(id, fk, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: Portal id (required) :param str fk: Foreign key for imageFolders (required) :param ImageFolder data: :return: ImageFolder If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.portals_id_image_folders_fk_put_with_http_info(id, fk, **kwargs) else: (data) = self.portals_id_image_folders_fk_put_with_http_info(id, fk, **kwargs) return data def portals_id_image_folders_fk_put_with_http_info(self, id, fk, **kwargs): """ Update a related item by id for imageFolders. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.portals_id_image_folders_fk_put_with_http_info(id, fk, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: Portal id (required) :param str fk: Foreign key for imageFolders (required) :param ImageFolder data: :return: ImageFolder If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'fk', 'data'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method portals_id_image_folders_fk_put" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params) or (params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `portals_id_image_folders_fk_put`") # verify the required parameter 'fk' is set if ('fk' not in params) or (params['fk'] is None): raise ValueError("Missing the required parameter `fk` when calling `portals_id_image_folders_fk_put`") collection_formats = {} resource_path = '/Portals/{id}/imageFolders/{fk}'.replace('{format}', 'json') path_params = {} if 'id' in params: path_params['id'] = params['id'] if 'fk' in params: path_params['fk'] = params['fk'] query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None if 'data' in params: body_params = params['data'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml']) # Authentication setting auth_settings = ['access_token'] return self.api_client.call_api(resource_path, 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ImageFolder', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), collection_formats=collection_formats) def portals_id_image_folders_get(self, id, **kwargs): """ Queries imageFolders of Portal. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.portals_id_image_folders_get(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: Portal id (required) :param str filter: :return: list[ImageFolder] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.portals_id_image_folders_get_with_http_info(id, **kwargs) else: (data) = self.portals_id_image_folders_get_with_http_info(id, **kwargs) return data def portals_id_image_folders_get_with_http_info(self, id, **kwargs): """ Queries imageFolders of Portal. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.portals_id_image_folders_get_with_http_info(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: Portal id (required) :param str filter: :return: list[ImageFolder] If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'filter'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method portals_id_image_folders_get" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params) or (params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `portals_id_image_folders_get`") collection_formats = {} resource_path = '/Portals/{id}/imageFolders'.replace('{format}', 'json') path_params = {} if 'id' in params: path_params['id'] = params['id'] query_params = {} if 'filter' in params: query_params['filter'] = params['filter'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml']) # Authentication setting auth_settings = ['access_token'] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[ImageFolder]', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), collection_formats=collection_formats) def portals_id_image_folders_post(self, id, **kwargs): """ Creates a new instance in imageFolders of this model. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.portals_id_image_folders_post(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: Portal id (required) :param ImageFolder data: :return: ImageFolder If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.portals_id_image_folders_post_with_http_info(id, **kwargs) else: (data) = self.portals_id_image_folders_post_with_http_info(id, **kwargs) return data def portals_id_image_folders_post_with_http_info(self, id, **kwargs): """ Creates a new instance in imageFolders of this model. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.portals_id_image_folders_post_with_http_info(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: Portal id (required) :param ImageFolder data: :return: ImageFolder If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'data'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method portals_id_image_folders_post" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params) or (params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `portals_id_image_folders_post`") collection_formats = {} resource_path = '/Portals/{id}/imageFolders'.replace('{format}', 'json') path_params = {} if 'id' in params: path_params['id'] = params['id'] query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None if 'data' in params: body_params = params['data'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml']) # Authentication setting auth_settings = ['access_token'] return self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ImageFolder', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), collection_formats=collection_formats) def portals_id_image_folders_rel_fk_delete(self, id, fk, **kwargs): """ Remove the imageFolders relation to an item by id. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.portals_id_image_folders_rel_fk_delete(id, fk, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: Portal id (required) :param str fk: Foreign key for imageFolders (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.portals_id_image_folders_rel_fk_delete_with_http_info(id, fk, **kwargs) else: (data) = self.portals_id_image_folders_rel_fk_delete_with_http_info(id, fk, **kwargs) return data def portals_id_image_folders_rel_fk_delete_with_http_info(self, id, fk, **kwargs): """ Remove the imageFolders relation to an item by id. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.portals_id_image_folders_rel_fk_delete_with_http_info(id, fk, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: Portal id (required) :param str fk: Foreign key for imageFolders (required) :return: None If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'fk'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'"
<filename>cogs/verify.py """ MIT License Copyright (c) 2020 BobDotCom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import discord, humanize, aiosqlite_pool, datetime, time, string, io, random, asyncio from discord.ext import commands import extensions.verification as verification from claptcha import Claptcha async def captcha(bot, member): for i in range(5): captcha_embed = discord.Embed(title='Captcha', description=f'Please send the text seen in this image. Once you send the correct text, you will pass the captcha. (case insensitive, letters and numbers)').set_footer(text=f'Attempt {i + 1}/5') s = string.ascii_uppercase + string.ascii_lowercase + string.digits rand_str = ''.join(random.choices(s, k=6)) c = Claptcha(rand_str, "extensions/Courier.dfont") text, byte = c.bytes await member.send(content='Hey! I just need to make sure you are human.', embed=captcha_embed,file=discord.File(byte, 'image.png')) def check(message): if message.author == member and not message.guild: return True try: msg = await bot.wait_for('message',check=check,timeout=60) if msg.content.lower() == text.lower(): await member.send(f'Correct!') return i + 1 else: await member.send('Incorrect!') continue except asyncio.TimeoutError: await member.send('Time is up! Try again.') return False return False class Verify(commands.Cog): def __init__(self,bot): """Verify new members""" self.bot = bot self.bot.verify_pool = aiosqlite_pool.Pool("./storage/verify.db",max_connection=5) self.pending_verification = [] @commands.Cog.listener() async def on_ready(self): """Setup the databases""" async with self.bot.verify_pool.acquire(timeout=5) as connection: async with connection.cursor() as cursor: await cursor.execute('CREATE TABLE IF NOT EXISTS guilds (id INTEGER PRIMARY KEY, enabled BOOL, time INTEGER, captcha INTEGER, roleid INTEGER, channelid INTEGER, messageid INTEGER, logid INTEGER, modid INTEGER, notifid INTEGER, ping BOOL)') await connection.commit() @commands.Cog.listener() async def on_raw_reaction_add(self, payload): if str(payload.emoji) != '\U00002705': return # we dont need to do anything async with self.bot.verify_pool.acquire(timeout=5) as connection: async with connection.cursor() as cursor: await cursor.execute('SELECT * FROM guilds WHERE id = ?',(payload.guild_id,)) data = await cursor.fetchone() if not data: # not set yet return if not bool(data[1]): # not enabled return if not (payload.message_id == data[6] and payload.channel_id == data[5]): return guild = self.bot.get_guild(payload.guild_id) channel = guild.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) await message.remove_reaction(payload.emoji,payload.member) if not payload.member.id in self.pending_verification: self.pending_verification.append(payload.member.id) else: return payload.member.send('You are already pending verification') result = verification.VerifyMember(self.bot, payload, data) # this is blocking but it takes < 1ms so its fine if result.moderator_approval: ping = guild.get_role(data[8]).mention if bool(data[10]) else '' channel = guild.get_channel(data[9]) await channel.send(f'{payload.member.mention} is waiting for approval {ping}') role = guild.get_role(data[4]) if role in payload.member.roles: self.pending_verification.remove(payload.member.id) return await payload.member.send('You are already verified') if result.failed and not result.moderator_approval: if result.needs_captcha: await payload.member.send(f'Please complete this captcha before joining **{guild.name}**.') x = await captcha(self.bot, payload.member) if x: await payload.member.add_roles(role) result = verification.VerifyMember(self.bot, payload, data, override='Passed Captcha', failed=False) await payload.member.send(f'You have been verified in **{guild.name}**') else: result = verification.VerifyMember(self.bot, payload, data, override="Failed Captcha", result=False) else: await payload.member.send(result.failed) elif not result.moderator_approval: await payload.member.add_roles(role) try: await payload.member.send(f'Successfully verified in **{guild.name}**') except: pass if data[7] != 0 and result.embed: logs = guild.get_channel(data[7]) await logs.send(embed=result.embed) self.pending_verification.remove(payload.member.id) async def verify_embed(self, ctx: commands.Context, data: tuple) -> discord.Embed: embed = discord.Embed(title='Guild Join Verification',description='Here are your current settings',timestamp=ctx.message.created_at) embed.add_field(name='Enabled',value=bool(data[1])) time = humanize.precisedelta(datetime.timedelta(seconds=data[2])) embed.add_field(name='Time before verification is allowed',value=time) captcha_settings = 'Always' if data[3] == 2 else 'Sometimes' if data[3] == 1 else 'Disabled' embed.add_field(name='Captcha Required',value=captcha_settings) role = None if data[4] == 0 else ctx.guild.get_role(data[4]) embed.add_field(name='Verified Role',value=role.mention if role else role) message_link = f'[Click Here](https://discord.com/channels/{ctx.guild.id}/{data[5]}/{data[6]})' if data[5] and data[6] else 'Not set' embed.add_field(name='Reaction Message',value=message_link) channel = None if data[7] == 0 else ctx.guild.get_channel(data[7]) embed.add_field(name='Log Channel',value=channel.mention if channel else channel) role = None if data[8] == 0 else ctx.guild.get_role(data[8]) embed.add_field(name='Manual Verification Role',value=role.mention if role else role) channel = None if data[9] == 0 else ctx.guild.get_channel(data[9]) embed.add_field(name='Manual Notification Channel',value=channel.mention if channel else channel) embed.add_field(name='Manual Verification Ping',value=bool(data[10])) return embed @commands.group(invoke_without_command=True) async def verify(self, ctx, member: discord.Member = None): """The command group for verification. Running this command will show you your current settings, if you specify a member, it will manually verify them. To run a subcommand, the syntax is `B.verify <subcommand> [arguments]`""" if member: command = self.bot.get_command('verify member') await ctx.invoke(command,member=member) else: command = self.bot.get_command('verify settings') await ctx.invoke(command) @verify.command() async def member(self, ctx, member: discord.Member): """Manually verify a member. Members with the Manual Verification role or the Kick Members permission can run this command""" async with self.bot.verify_pool.acquire(timeout=5) as connection: async with connection.cursor() as cursor: await cursor.execute('SELECT * FROM guilds WHERE id = ?',(ctx.guild.id,)) data = await cursor.fetchone() mod_role = None if data[8] == 0 else ctx.guild.get_role(data[8]) if mod_role in ctx.author.roles or ctx.author.guild_permissions.kick_members: role = None if data[4] == 0 else ctx.guild.get_role(data[4]) if role: await member.add_roles(role) try: await member.send(f'You have been manually verified in **{ctx.guild.name}**') except: pass await ctx.send(f'Successfully verified {member.mention}') else: await ctx.send('You do not have permissions to do that') @verify.command() @commands.has_guild_permissions(manage_guild=True) @commands.bot_has_guild_permissions(manage_guild=True) async def toggle(self, ctx, toggle: bool = None): """Toggle the verification system""" async with ctx.typing(): async with self.bot.verify_pool.acquire(timeout=5) as connection: async with connection.cursor() as cursor: await cursor.execute('SELECT * FROM guilds WHERE id = ?',(ctx.guild.id,)) data = await cursor.fetchone() if not data: data = (ctx.guild.id, True, 0, 1, 0, 0, 0, 0, 0, 0, 0,) await cursor.execute('INSERT INTO guilds (id, enabled, time, captcha, roleid, channelid, messageid, logid, modid, notifid, ping) VALUES (?,?,?,?,?,?,?,?,?,?,?)',data) else: data = list(data) if toggle == None: toggle = not bool(data[1]) data[1] = toggle await cursor.execute('UPDATE guilds SET enabled = ? WHERE id = ?',(data[1], ctx.guild.id,)) await connection.commit() embed = await self.verify_embed(ctx,data) await ctx.send('Success!',embed=embed) @verify.command() @commands.has_guild_permissions(manage_guild=True) @commands.bot_has_guild_permissions(manage_guild=True) async def captcha(self, ctx, toggle = 'sometimes'): """Toggle whether the captcha is always, sometimes, or never on. **Always:** Users will always have to complete a captcha, if their account is highly suspicious they will require manual verification **Sometimes:** Users will have to complete a captcha if their account is suspicious, if their account is highly suspicious they will require manual verification **Never:** Users will never have to complete a captcha, if their account is suspicious they will require manual verification""" toggle = 2 if toggle.lower() == 'always' else 1 if toggle.lower() == 'sometimes' else 0 if toggle.lower() == 'never' else None if toggle is None: return await ctx.send('Valid options are: always, sometimes, and never') async with ctx.typing(): async with self.bot.verify_pool.acquire(timeout=5) as connection: async with connection.cursor() as cursor: await cursor.execute('SELECT * FROM guilds WHERE id = ?',(ctx.guild.id,)) data = await cursor.fetchone() if not data: data = (ctx.guild.id, True, 0, toggle, 0, 0, 0, 0, 0, 0, 0,) await cursor.execute('INSERT INTO guilds (id, enabled, time, captcha, roleid, channelid, messageid, logid, modid, notifid, ping) VALUES (?,?,?,?,?,?,?,?,?,?,?)',data) else: data = list(data) data[3] = toggle await cursor.execute('UPDATE guilds SET captcha = ? WHERE id = ?',(data[3], ctx.guild.id,)) await connection.commit() embed = await self.verify_embed(ctx,data) await ctx.send('Success!',embed=embed) @verify.command() @commands.has_guild_permissions(manage_guild=True) @commands.bot_has_guild_permissions(manage_guild=True) async def channel(self, ctx, channel: discord.TextChannel = None, *, quote = 'Click here to verify'): """Pick a channel to start verification in, defaults to the current channel. You may also set a quote to display in the embed. The bot will send a message to that channel and people who react to it will be checked for verification""" async with ctx.typing(): channel = channel or ctx.channel embed = discord.Embed(title='Verify',description=quote) embed.set_footer(text='React with \U00002705 to verify. Your DMs must be open!') try: message = await channel.send(embed=embed) await message.add_reaction('\U00002705') except: return await ctx.send("Please make sure I can send messages, add reactions, and manage messages in that channel!") async with self.bot.verify_pool.acquire(timeout=5) as connection: async with connection.cursor() as cursor: await cursor.execute('SELECT *
UnequipItemsSetMacro(): _unequip_itemsset_macro() def Undress(): tmp = [] client_version_int = GetClientVersionInt() if client_version_int < 7007400: delay = GetDressSpeed() char = Self() backpack = Backpack() for layer in _wearable_layers: item = ObjAtLayerEx(layer, char) if item: tmp.append(MoveItem(item, 1, backpack, 0, 0, 0)) Wait(delay) else: UnequipItemsSetMacro() tmp.append(True) # no need to wait - all this done inside return all(tmp) _set_dress = _ScriptMethod(238) # SetDress def SetDress(): _set_dress() _equip_item_set_macro = _ScriptMethod(357) # SCEquipItemsSetMacro def EquipItemsSetMacro(): _equip_item_set_macro() _get_dress_set = _ScriptMethod(239) # GetDressSet _get_dress_set.restype = _buffer # TLayersObjectsList def EquipDressSet(): res = [] client_version_int = GetClientVersionInt() if client_version_int < 7007400: delay = GetDressSpeed() data = _get_dress_set() count = _struct.unpack('B', data[:1])[0] data = data[1:] offset = 0 for i in range(count): layer, item = _struct.unpack_from('<BI', data, offset) offset += 5 if item: res.append(Equip(layer, item)) Wait(delay) else: EquipItemsSetMacro() res.append(True) # no need to wait - all this done inside return all(res) def DressSavedSet(): EquipDressSet() def Count(ObjType): FindType(ObjType, Backpack()) return FindFullQuantity() def CountGround(ObjType): FindType(ObjType, Ground()) return FindFullQuantity() def CountEx(ObjType, Color, Container): FindTypeEx(ObjType, Color, Container, False) return FindFullQuantity() def BP(): return 0X0F7A def BM(): return 0x0F7B def GA(): return 0x0F84 def GS(): return 0x0F85 def MR(): return 0x0F86 def NS(): return 0x0F88 def SA(): return 0x0F8C def SS(): return 0x0F8D def BPCount(): FindTypeEx(BP(), 0, Backpack(), True) return FindFullQuantity() def BMCount(): FindTypeEx(BM(), 0, Backpack(), True) return FindFullQuantity() def GACount(): FindTypeEx(GA(), 0, Backpack(), True) return FindFullQuantity() def GSCount(): FindTypeEx(GS(), 0, Backpack(), True) return FindFullQuantity() def MRCount(): FindTypeEx(MR(), 0, Backpack(), True) return FindFullQuantity() def NSCount(): FindTypeEx(NS(), 0, Backpack(), True) return FindFullQuantity() def SACount(): FindTypeEx(SA(), 0, Backpack(), True) return FindFullQuantity() def SSCount(): FindTypeEx(SS(), 0, Backpack(), True) return FindFullQuantity() _auto_buy = _ScriptMethod(240) # AutoBuy _auto_buy.argtypes = [_ushort, # ItemType _ushort, # ItemColor _ushort] # Quantity def AutoBuy(ItemType, ItemColor, Quantity): _auto_buy(ItemType, ItemColor, Quantity) _get_shop_list = _ScriptMethod(241) # GetShopList _get_shop_list.restype = _str def GetShopList(): return _get_shop_list() _clear_shop_list = _ScriptMethod(242) # ClearShopList def ClearShopList(): _clear_shop_list() _auto_buy_extended = _ScriptMethod(243) # AutoBuyEx _auto_buy_extended.argtypes = [_ushort, # ItemType _ushort, # ItemColor _ushort, # Quantity _uint, # Price _str] # ItemName def AutoBuyEx(ItemType, ItemColor, Quantity, Price, ItemName): _auto_buy_extended(ItemType, ItemColor, Quantity, Price, ItemName) _get_auto_buy_delay = _ScriptMethod(244) # GetAutoBuyDelay _get_auto_buy_delay.restype = _ushort def GetAutoBuyDelay(): return _get_auto_buy_delay() _set_auto_buy_delay = _ScriptMethod(245) # SetAutoBuyDelay _set_auto_buy_delay.argtypes = [_ushort] # Value def SetAutoBuyDelay(Value): _set_auto_buy_delay(Value) _get_auto_sell_delay = _ScriptMethod(246) # GetAutoSellDelay _get_auto_sell_delay.restype = _ushort def GetAutoSellDelay(): return _get_auto_sell_delay() _set_auto_sell_delay = _ScriptMethod(247) # SetAutoSellDelay _set_auto_sell_delay.argtypes = [_ushort] # Value def SetAutoSellDelay(Value): _set_auto_sell_delay(Value) _auto_sell = _ScriptMethod(248) # AutoSell _auto_sell.argtypes = [_ushort, # ItemType _ushort, # ItemColor _ushort] # Quantity def AutoSell(ItemType, ItemColor, Quantity): _auto_sell(ItemType, ItemColor, Quantity) _request_stats = _ScriptMethod(249) # RequestStats _request_stats.argtypes = [_uint] # ObjID def RequestStats(ObjID): _request_stats(ObjID) _help_request = _ScriptMethod(250) # HelpRequest def HelpRequest(): _help_request() _quest_request = _ScriptMethod(251) # QuestRequest def QuestRequest(): _quest_request() _rename_mobile = _ScriptMethod(252) # RenameMobile _rename_mobile.argtypes = [_uint, # Mob_ID _str] # NewName def RenameMobile(Mob_ID, NewName): _rename_mobile(Mob_ID, NewName) _mobile_can_be_renamed = _ScriptMethod(253) # MobileCanBeRenamed _mobile_can_be_renamed.restype = _bool _mobile_can_be_renamed.argtypes = [_uint] # Mob_ID def MobileCanBeRenamed(Mob_ID): return _mobile_can_be_renamed(Mob_ID) _lock_stat = _ScriptMethod(254) # ChangeStatLockState _lock_stat.argtypes = [_ubyte, # statNum _ubyte] # statState def SetStatState(statNum, statState): _lock_stat(statNum, statState) _get_static_art_bitmap = _ScriptMethod(255) # GetStaticArtBitmap _get_static_art_bitmap.restype = _buffer # Bitmap file in bytes _get_static_art_bitmap.argtypes = [_uint, # Id _ushort] # Hue def GetStaticArtBitmap(Id, Hue): return _get_static_art_bitmap(Id, Hue) _print_script_methods = _ScriptMethod(256) # PrintScriptMethodsList _print_script_methods.argtypes = [_str, # FileName _bool] # SortedList def PrintScriptMethodsList(FileName, SortedList): _print_script_methods(FileName, SortedList) _alarm = _ScriptMethod(257) # SetAlarm def Alarm(): _alarm() _uo_say = _ScriptMethod(308) # SendTextToUO _uo_say.argtypes = [_str] # Text def UOSay(Text): _uo_say(Text) _uo_say_color = _ScriptMethod(309) # SendTextToUOColor _uo_say_color.argtypes = [_str, # Text _ushort] # Color def UOSayColor(Text, Color): _uo_say_color(Text, Color) _reg_stealth = 0, '0', 'reg_stealth', 'stealth' _reg_char = 1, '1', 'reg_char', 'char' _set_global = _ScriptMethod(310) # SetGlobal _set_global.argtypes = [_ubyte, # GlobalRegion _str, # VarName _str] # VarValue def SetGlobal(GlobalRegion, VarName, VarValue): if isinstance(GlobalRegion, str): GlobalRegion = GlobalRegion.lower() for region in _reg_stealth, _reg_char: if GlobalRegion in region: _set_global(region[0], VarName, VarValue) break else: raise ValueError('GlobalRegion must be "stealth" or "char".') _get_global = _ScriptMethod(311) _get_global.restype = _str _get_global.argtypes = [_ubyte, # GlobalRegion _str] # VarName def GetGlobal(GlobalRegion, VarName): if isinstance(GlobalRegion, str): GlobalRegion = GlobalRegion.lower() for region in _reg_stealth, _reg_char: if GlobalRegion in region: return _get_global(region[0], VarName) else: raise ValueError('GlobalRegion must be "stealth" or "char".') _console_entry_reply = _ScriptMethod(312) _console_entry_reply.argtypes = [_str] # Text def ConsoleEntryReply(Text): _console_entry_reply(Text) _console_entry_unicode_reply = _ScriptMethod(313) # ConsoleEntryUnicodeReply _console_entry_unicode_reply.argtypes = [_str] # Text def ConsoleEntryUnicodeReply(Text): _console_entry_unicode_reply(Text) _game_server_ip_string = _ScriptMethod(341) # GameServerIPString _game_server_ip_string.restype = _str def GameServerIPString(): return _game_server_ip_string() _easyuo_sub_key = 'Software\\EasyUO' def SetEasyUO(num, Regvalue): if b'' == '': # py2 import _winreg as winreg else: import winreg key = winreg.HKEY_CURRENT_USER access = winreg.KEY_WRITE with winreg.OpenKey(key, _easyuo_sub_key, 0, access) as easyuo_key: winreg.SetValueEx(easyuo_key, '*' + str(num), 0, winreg.REG_SZ, Regvalue) def GetEasyUO(num): if b'' == '': # py2 import _winreg as winreg else: import winreg key = winreg.HKEY_CURRENT_USER access = winreg.KEY_READ with winreg.OpenKey(key, _easyuo_sub_key, 0, access) as easyuo_key: type_, data = winreg.QueryValueEx(easyuo_key, '*' + str(num)) return data def EUO2StealthType(EUO): # TODO: 2 and 3 compatible code: int(codecs.encode(b'A', 'hex'), 16) res = 0 multi = 1 for char in EUO: if b'' == '': # py2 tmp = int(char.encode('hex'), 16) else: tmp = int.from_bytes(char.encode(), 'little') res += multi * (tmp - 65) multi *= 26 res = (res - 7) ^ 0x0045 return 0 if res > 0xFFFF else res def EUO2StealthID(EUO): # TODO: 2 and 3 compatible code: int(codecs.encode(b'A', 'hex'), 16) res = 0 multi = 1 for char in EUO: if b'' == '': # py2 tmp = int(char.encode('hex'), 16) else: tmp = int.from_bytes(char.encode(), 'little') res += multi * (tmp - 65) multi *= 26 return (res - 7) ^ 0x0045 _http_get = _ScriptMethod(258) # HTTP_Get _http_get.argtypes = [_str] # URL def HTTP_Get(URL): _http_get(URL) _http_post = _ScriptMethod(259) # HTTP_Post _http_post.restype = _str _http_post.argtypes = [_str, # URL _str] # PostData def HTTP_Post(URL, PostData): return _http_post(URL, PostData) _http_body = _ScriptMethod(260) # HTTP_Body _http_body.restype = _str def HTTP_Body(): return _http_body() _http_header = _ScriptMethod(261) # HTTP_Header _http_header.restype = _str def HTTP_Header(): return _http_header() _party_invite = _ScriptMethod(262) # InviteToParty _party_invite.argtypes = [_uint] # ID def InviteToParty(ID): _party_invite(ID) _party_kick = _ScriptMethod(263) # RemoveFromParty _party_kick.argtypes = [_uint] # ID def RemoveFromParty(ID): _party_kick(ID) _party_msg_to = _ScriptMethod(264) # PartyMessageTo _party_msg_to.argtypes = [_uint, # ID _str] # Msg def PartyMessageTo(ID, Msg): _party_msg_to(ID, Msg) _party_msg = _ScriptMethod(265) # PartySay _party_msg.argtypes = [_str] # Msg def PartySay(Msg): _party_msg(Msg) _party_can_loot = _ScriptMethod(266) # PartyCanLootMe _party_can_loot.argtypes = [_bool] # Value def PartyCanLootMe(Value): _party_can_loot(Value) _party_accept = _ScriptMethod(267) # PartyAcceptInvite def PartyAcceptInvite(): _party_accept() _party_reject = _ScriptMethod(268) # PartyDeclineInvite def PartyDeclineInvite(): _party_reject() _party_leave = _ScriptMethod(269) # PartyLeave def PartyLeave(): _party_leave() _is_in_party = _ScriptMethod(271) # InParty _is_in_party.restype = _bool def InParty(): return _is_in_party() _get_party_members = _ScriptMethod(270) # PartyMembersList _get_party_members.restype = _buffer # Array of Cardinal def PartyMembersList(): result = [] data = _get_party_members() if data: fmt = 'I' * (len(data) // 4) result.extend(_struct.unpack(fmt, data)) return result _get_icq_connection_state = _ScriptMethod(272) # GetConnectedStatus _get_icq_connection_state.restype = _bool def ICQConnected(): return _get_icq_connection_state() _icq_connect = _ScriptMethod(273) # ICQ_Connect _icq_connect.argtypes = [_uint, # UIN _str] # Password def ICQConnect(UIN, Password): _icq_connect(UIN, Password) _icq_disconnect = _ScriptMethod(274) # ICQ_Disconnect def ICQDisconnect(): _icq_disconnect() _icq_set_status = _ScriptMethod(275) # ICQ_SetStatus _icq_set_status.argtypes = [_ubyte] # Num def ICQSetStatus(Num): _icq_set_status(Num) _icq_set_x_status = _ScriptMethod(276) # ICQ_SetXStatus _icq_set_x_status.argtypes = [_ubyte] # Num def ICQSetXStatus(Num): _icq_set_x_status(Num) _icq_send_message = _ScriptMethod(277) # ICQ_SendText _icq_send_message.argtypes = [_uint, # DestinationUIN _str] # Text def ICQSendText(DestinationUIN, Text): _icq_send_message(DestinationUIN, Text) _messengers = {0: 1, # default - telegram 1: 1, 'Telegram': 1, 'telegram': 1, 2: 2, 'Viber': 2, 'viber': 2, 3: 3, 'Discord': 3, 'discord': 3} _messenger_get_connected = _ScriptMethod(501) # Messenger_GetConnected _messenger_get_connected.restype = _bool _messenger_get_connected.argtypes = [_ubyte] # MesID def MessengerGetConnected(MesID): if MesID not in _messengers.keys(): error = 'MessengerGetConnected: MesID must be "Telegram", "Viber" or "Discord"' raise ValueError(error) return _messenger_get_connected(_messengers[MesID]) _messenger_set_connected = _ScriptMethod(502) # Messenger_SetConnected _messenger_set_connected.argtypes = [_ubyte, # MesID _bool] # Value def MessengerSetConnected(MesID, Value): if MesID not in _messengers.keys(): error = 'MessengerGetConnected: MesID must be "Telegram", "Viber" or "Discord"' raise ValueError(error) _messenger_set_connected(_messengers[MesID], Value) _messenger_get_token = _ScriptMethod(503) # Messenger_GetToken _messenger_get_token.restype = _str _messenger_get_token.argtypes = [_ubyte] # MesID def MessengerGetToken(MesID): if MesID not in _messengers.keys(): error = 'MessengerGetConnected: MesID must be "Telegram", "Viber" or "Discord"' raise ValueError(error) return _messenger_get_token(_messengers[MesID]) _messenger_set_token = _ScriptMethod(504) # Messenger_SetToken _messenger_set_token.argtypes = [_ubyte, # MesID _str] # Value def MessengerSetToken(MesID, Value): if MesID not in _messengers.keys(): error = 'MessengerGetConnected: MesID must be "Telegram", "Viber" or "Discord"' raise ValueError(error) _messenger_set_token(_messengers[MesID], Value) _messenger_get_name = _ScriptMethod(505) # Messenger_GetName _messenger_get_name.restype = _str _messenger_get_name.argtypes = [_ubyte] # MesID def MessengerGetName(MesID): if MesID not in _messengers.keys(): error = 'MessengerGetConnected: MesID must be "Telegram", "Viber" or "Discord"' raise ValueError(error) return _messenger_get_name(_messengers[MesID]) _messenger_send_message = _ScriptMethod(506) # Messenger_SendMessage _messenger_send_message.argtypes = [_ubyte, # MesID _str, # Msg _str] # UserID def MessengerSendMessage(MesID, Msg, UserID): if MesID not in _messengers.keys(): error = 'MessengerGetConnected: MesID must be "Telegram", "Viber" or "Discord"' raise ValueError(error) _messenger_send_message(_messengers[MesID], Msg, UserID) _tile_groups = {0: 0, 'tfLand': 0, 'tfland': 0, 'Land': 0, 'land': 0, 1: 1, 'tfStatic': 1, 'tfstatic': 1, 'Static': 1, 'static': 1} _get_tile_flags = _ScriptMethod(278) # GetTileFlags _get_tile_flags.restype = _uint _get_tile_flags.argtypes = [_ubyte, # TileGroup _ushort] # Tile def GetTileFlags(TileGroup, Tile): if TileGroup not in _tile_groups.keys(): raise ValueError('GetTileFlags:
from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.db import connection from django.db import IntegrityError from django.utils.text import slugify from build.management.commands.base_build import Command as BaseBuild from mutation.models import * from common.views import AbsTargetSelection from common.views import AbsSegmentSelection from common.tools import fetch_from_cache, save_to_cache, fetch_from_web_api from residue.models import Residue from protein.models import Protein from ligand.models import Ligand, LigandProperities, LigandRole, LigandType from ligand.functions import get_or_make_ligand from common.models import WebLink, WebResource, Publication import json import yaml import logging import os import re from datetime import datetime from collections import OrderedDict from urllib.request import urlopen, quote import math import xlrd import operator import traceback import time ## FOR VIGNIR ORDERED DICT YAML IMPORT/DUMP _mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG def dict_constructor(loader, node): return OrderedDict(loader.construct_pairs(node)) def represent_ordereddict(dumper, data): value = [] for item_key, item_value in data.items(): node_key = dumper.represent_data(item_key) node_value = dumper.represent_data(item_value) value.append((node_key, node_value)) return yaml.nodes.MappingNode(u'tag:yaml.org,2002:map', value) class Command(BaseBuild): help = 'Reads source data and creates pdb structure records' def add_arguments(self, parser): parser.add_argument('-p', '--proc', type=int, action='store', dest='proc', default=1, help='Number of processes to run') parser.add_argument('-f', '--filename', action='append', dest='filename', help='Filename to import. Can be used multiple times') parser.add_argument('-u', '--purge', action='store_true', dest='purge', default=False, help='Purge existing mutations records') parser.add_argument('--test_run', action='store_true', help='Skip this during a test run', default=False) logger = logging.getLogger(__name__) # source file directory structure_data_dir = os.sep.join([settings.DATA_DIR, 'mutant_data']) publication_cache = {} ligand_cache = {} ref_ligand_cache = {} data_all = [] def handle(self, *args, **options): if options['test_run']: print('Skipping in test run') return # delete any existing structure data if options['purge']: try: self.purge_mutants() except Exception as msg: print(msg) self.logger.error(msg) # import the structure data try: #self.create_mutant_data(options['filename']) self.logger.info('CREATING MUTANT DATA') self.prepare_all_data(options['filename']) import random random.shuffle(self.data_all) # self.data_all = random.shuffle(self.data_all) # split into 10 runs to average out slow ones #n = 5 #for d in [ self.data_all[i::n] for i in range(n) ]: # self.data = d self.prepare_input(options['proc'], self.data_all) self.logger.info('COMPLETED CREATING MUTANTS') except Exception as msg: print(msg) traceback.print_exc() self.logger.error(msg) def purge_mutants(self): Mutation.objects.all().delete() MutationRaw.objects.all().delete() MutationExperiment.objects.all().delete() def loaddatafromexcel(self,excelpath): workbook = xlrd.open_workbook(excelpath) worksheets = workbook.sheet_names() temp = [] old = 0 for worksheet_name in worksheets: worksheet = workbook.sheet_by_name(worksheet_name) try: if worksheet.cell_value(0, 0) == "REFERENCE \nDOI (or PMID)": #old format FIXME pass elif worksheet.cell_value(0, 0) == "REFERENCE \nDOI or PMID": #new format pass old = 1 elif worksheet.cell_value(0, 0) == "REFERENCE \nDOI or PMID (original)": #newest format pass elif worksheet.cell_value(0, 1) == "REFERENCE \nDOI or PMID (original)": #newest format pass else: #skip non-matching xls files continue except: continue num_rows = worksheet.nrows - 1 num_cells = worksheet.ncols - 1 curr_row = 0 #skip first, otherwise -1 while curr_row < num_rows: curr_row += 1 row = worksheet.row(curr_row) curr_cell = -1 temprow = [] if not old and worksheet.cell_value(curr_row, 1) == '': #if empty reference continue elif old and worksheet.cell_value(curr_row, 0) == '': #if empty reference continue while curr_cell < num_cells: curr_cell += 1 cell_type = worksheet.cell_type(curr_row, curr_cell) cell_value = worksheet.cell_value(curr_row, curr_cell) # fix wrong spaced cells if cell_value==" ": cell_value = "" temprow.append(cell_value) temp.append(temprow) #if curr_row>10: break return [temp, old] def analyse_rows(self,rows,source_file, old): # Analyse the rows from excel and assign the right headers temp = [] for i,r in enumerate(rows,1): d = {} if not old and r[9]!='': # if multi mutant group skip it self.logger.info('Skipped row due to being a multi group ' + source_file + "_" + str(i)) continue if old: if r[6] !='': continue d['reference'] = r[0] d['protein'] = r[2].replace("__","_").lower() d['mutation_pos'] = r[3] d['mutation_from'] = r[4] d['mutation_to'] = r[5] #r[6] is new double multi mutant group #FIXME FOR LATER d['ligand_name'] = r[7] d['ligand_type'] = r[8] d['ligand_id'] = r[9] d['ligand_class'] = r[10] #r[10] is new reference ligand #FIXME FOR LATER d['exp_type'] = r[12] d['exp_func'] = r[13] d['exp_wt_value'] = float(r[14]) if r[14] else 0 d['exp_wt_unit'] = r[15] d['exp_mu_effect_sign'] = r[16] d['exp_mu_value_raw'] = float(r[17]) if r[17] else 0 d['fold_effect'] = float(r[18]) if r[18] else 0 d['exp_mu_effect_qual'] = r[19] d['exp_mu_effect_ligand_prop'] = '' #removed d['exp_mu_ligand_ref'] = r[11] #check if correct d['review'] ='' d['submitting_group'] ='' d['data_container'] ='' d['data_container_number'] = '' d['opt_receptor_expression'] = 0 d['opt_basal_activity'] = 0 d['opt_gain_of_activity'] = 0 d['opt_ligand_emax'] = 0 d['opt_agonist'] = 0 else: d['submitting_group'] = r[0] d['reference'] = r[1] d['data_container'] = r[2] d['data_container_number'] = r[3] d['review'] = r[4] d['protein'] = r[5].replace("__","_").lower() d['mutation_pos'] = r[6] d['mutation_from'] = r[7] d['mutation_to'] = r[8] #r[9] is new double multi mutant group #FIXME FOR LATER d['ligand_name'] = r[10] d['ligand_type'] = r[11] d['ligand_id'] = r[12] d['ligand_class'] = r[13] d['exp_mu_ligand_ref'] = r[14] #check if correct? #r[10] is new reference ligand #FIXME FOR LATER d['exp_type'] = r[15] d['exp_func'] = r[16] d['exp_wt_value'] = float(r[17]) if r[17] else 0 d['exp_wt_unit'] = r[18] d['exp_mu_effect_sign'] = r[19] d['exp_mu_value_raw'] = float(r[20]) if r[20] else 0 d['fold_effect'] = float(r[21]) if r[21] else 0 d['exp_mu_effect_qual'] = r[22] d['exp_mu_effect_ligand_prop'] = '' #removed d['opt_receptor_expression'] = float(r[23]) if r[23] else 0 d['opt_basal_activity'] = float(r[24]) if r[24] else 0 d['opt_gain_of_activity'] = r[25] d['opt_ligand_emax'] = float(r[26]) if r[26] else 0 d['opt_agonist'] = r[27] # d['opt_type'] = r[20] # d['opt_wt'] = float(r[21]) if r[21] else 0 # d['opt_mu'] = float(r[23]) if r[23] else 0 # d['opt_sign'] = r[22] # d['opt_percentage'] = float(r[24]) if r[24] else 0 # d['opt_qual'] = r[25] # d['opt_agonist'] = r[26] d['source_file'] = source_file + "_" + str(i) if len(d['mutation_to'])>1 or len(d['mutation_from'])>1: #if something is off with amino acid continue if isinstance(d['ligand_id'], float): d['ligand_id'] = int(d['ligand_id']) if isinstance(d['mutation_pos'], float): d['mutation_pos'] = int(d['mutation_pos']) temp.append(d) return temp def insert_raw(self,r): obj = MutationRaw( reference=r['reference'], review=r['review'], submitting_group = r['submitting_group'], data_container = r['data_container'], data_container_number = r['data_container_number'], protein=r['protein'], mutation_pos=r['mutation_pos'], mutation_from=r['mutation_from'], mutation_to=r['mutation_to'], ligand_name=r['ligand_name'], ligand_idtype=r['ligand_type'], ligand_id=r['ligand_id'], ligand_class=r['ligand_class'], exp_type=r['exp_type'], exp_func=r['exp_func'], exp_wt_value=r['exp_wt_value'], exp_wt_unit=r['exp_wt_unit'], exp_fold_change=r['fold_effect'], exp_mu_effect_sign=r['exp_mu_effect_sign'], exp_mu_effect_value=r['exp_mu_value_raw'], exp_mu_effect_qual=r['exp_mu_effect_qual'], exp_mu_effect_ligand_prop=r['exp_mu_effect_ligand_prop'], exp_mu_ligand_ref=r['exp_mu_ligand_ref'], opt_receptor_expression=r['opt_receptor_expression'], opt_basal_activity=r['opt_basal_activity'], opt_gain_of_activity=r['opt_gain_of_activity'], opt_ligand_emax=r['opt_ligand_emax'], opt_agonist=r['opt_agonist'], # opt_type=r['opt_type'], # opt_wt=r['opt_wt'], # opt_mu=r['opt_mu'], # opt_sign=r['opt_sign'], # opt_percentage=r['opt_percentage'], # opt_qual=r['opt_qual'], # opt_agonist=r['opt_agonist'], added_by='munk', added_date=datetime.now() ) raw_id = obj return raw_id def load_mutant_from_yaml(self,filename): pass def prepare_all_data(self, filenames): if not filenames: filenames = os.listdir(self.structure_data_dir) for source_file in filenames: source_file_path = os.sep.join([self.structure_data_dir, source_file]) if os.path.isfile(source_file_path) and source_file[0] != '.': self.logger.info('Reading file {}'.format(source_file_path)) print('Reading file {}'.format(source_file_path)) # read the yaml file rows = [] if source_file[-4:]=='xlsx' or source_file[-3:]=='xls': if "~$" in source_file: # ignore open excel files continue rows, old = self.loaddatafromexcel(source_file_path) rows = self.analyse_rows(rows,source_file, old) elif source_file[-4:]=='yaml': rows = yaml.load(open(source_file_path, 'r'), Loader=yaml.FullLoader) temp = [] for i,r in enumerate(rows): d = {} d['reference'] = r['pubmed'] d['submitting_group'] = '' d['data_container'] = '' d['data_container_number'] = '' d['review'] = '' d['protein'] = r['entry_name'].replace("__","_").lower() d['mutation_pos'] = r['seq'] d['mutation_from'] = r['from_res'] d['mutation_to'] = r['to_res'] d['ligand_name'] = '' d['ligand_type'] = '' d['ligand_id'] = '' d['ligand_class'] = '' d['exp_type'] = '' d['exp_func'] = '' d['exp_wt_value'] = 0 d['exp_wt_unit'] = '' d['exp_mu_effect_sign'] = '' d['exp_mu_value_raw'] = 0 d['fold_effect'] = 0 d['exp_mu_effect_qual'] = '' d['exp_mu_effect_ligand_prop'] = '' d['exp_mu_ligand_ref'] = '' d['opt_receptor_expression'] = 0 d['opt_basal_activity'] = 0 d['opt_gain_of_activity'] = '' d['opt_ligand_emax'] = 0 d['opt_agonist'] = '' d['source_file'] = source_file + "_" + str(i) if len(d['mutation_to'])>1 or len(d['mutation_from'])>1: #if something is off with amino acid continue temp.append(d) rows = temp else: self.logger.info('unknown format'.source_file) continue self.data_all += rows print(len(self.data_all)," total data points") #def create_mutant_data(self, filenames): def main_func(self, positions, iteration,count,lock): # filenames # if not positions[1]: # rows = self.data[positions[0]:] # else: # rows = self.data[positions[0]:positions[1]] missing_proteins = {} mutants_for_proteins = {} wrong_uniport_ids = {} c = 0 skipped = 0 inserted = 0 bulk_m = [] bulk_r = [] current_sheet = time.time() rows = self.data_all while count.value<len(rows): with lock: r = rows[count.value] count.value +=1 # for r in rows: # print(r['source_file'],c) # PRINT IF ERRORS OCCUR #self.logger.info('File '+str(r['source_file'])+' number '+str(c)) current = time.time() c += 1 # if c%100==0: # self.logger.info('Parsed '+str(c)+' mutant data entries') try: # publication try: #fix if it thinks it's float. float(r['reference']) r['reference'] = str(int(r['reference'])) float(r['review']) r['review'] = str(int(r['review'])) except ValueError: pass if r['reference'].isdigit(): #assume pubmed pub_type = 'pubmed' else: #assume doi pub_type = 'doi' if r['reference'] not in self.publication_cache and len(r['reference']) > 0: if pub_type == 'doi': pub = Publication.get_or_create_from_doi(r['reference']) elif pub_type == 'pubmed': pub = Publication.get_or_create_from_pubmed(r['reference']) if not pub: self.logger.error('error with reference ' + str(r['reference']) + ' ' + pub_type) continue #if something off with publication, skip. self.publication_cache[r['reference']] = pub else: pub = self.publication_cache[r['reference']] # print(r['review'],r['reference']) if r['review'].isdigit(): #assume pubmed pub_type = 'pubmed' elif r['review'].startswith('http'): pub_type = 'raw_link' else: #assume doi pub_type = 'doi'
was the last accessed date. """ print("= Method 2g: Get substring with ...") print(" re.findall(r'[\"](.*?)[\"]', string).") # Enumerate all the test strings. for current_test_string in my_strings: for values in re.findall(r'["](.*?)["]', current_test_string): my_substrings.append(values) #print("values are:",values,"=") print(" my_substrings are:",my_substrings,"=") my_substrings = [] print(" > stores empty strings embedded within quotation marks.") print(" > Method works.") """ References: + [Lundberg2012] - <NAME>, Answer to ``Python Regex to find a string in double quotes within a string'', Stack Exchange, Inc., New York, NY, March 1, 2012. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/9519934/1531728 and https://stackoverflow.com/questions/9519734/python-regex-to-find-a-string-in-double-quotes-within-a-string/9519934#9519934; November 6, 2021 was the last accessed date. + [Avinash2021] - <NAME>, Answer to ``Extract text between quotation using regex python'', Stack Exchange, Inc., New York, NY, October 12, 2021. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/69543129/1531728 and https://stackoverflow.com/questions/69542978/extract-text-between-quotation-using-regex-python/69543129#69543129; November 8, 2021 was the last accessed date. """ print("= Method 2h(i): Get substring with ...") print(" re.findall(r'\\\"(.+?)\\\"', string).") # Enumerate all the test strings. for current_test_string in my_strings: for values in re.findall(r'\"(.+?)\"', current_test_string): my_substrings.append(values) #print("values are:",values,"=") print(" my_substrings are:",my_substrings,"=") my_substrings = [] print(" > Fails with empty strings embedded within quotation marks.") print(" > Method FAILS!!!") # Replace ".+" (one or more empty strings) wit ".*" (zero or more empty strings) print("= Method 2h(ii): Get substring with ...") print(" re.findall(r'\\\"(.*?)\\\"', string).") # Enumerate all the test strings. for current_test_string in my_strings: for values in re.findall(r'\"(.*?)\"', current_test_string): my_substrings.append(values) #print("values are:",values,"=") print(" my_substrings are:",my_substrings,"=") my_substrings = [] print(" > stores empty strings embedded within quotation marks.") print(" > Method works.") """ References: + [Shelvington2020] - <NAME>, Answer to ``Extracting only words out of a mixed string in Python [duplicate]'', Stack Exchange, Inc., New York, NY, January 5, 2020. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/59598630/1531728 and https://stackoverflow.com/questions/59598565/extracting-only-words-out-of-a-mixed-string-in-python/59598630#59598630; November 6, 2021 was the last accessed date. + [w3resourceContributors2021] w3resource contributors, "Python: Extract values between quotation marks of a string", from w3resource: Backend tutorials: Python Tutorial: Python Exercises, Practice, Solution: Python Regular Expression - Exercises, Practice, Solution, or from w3resource: Exercises with online editor: Python Tutorial: Python Exercises, Practice, Solution: Python Regular Expression - Exercises, Practice, Solution, DataSoft, Khosbagan, Bardhaman, Purba Bardhaman, West Bengal, India, October 25, 2021. Available from w3resource: Backend tutorials: Python Tutorial: Python Exercises, Practice, Solution: Python Regular Expression - Exercises, Practice, Solution, or from w3resource: Exercises with online editor: Python Tutorial: Python Exercises, Practice, Solution: Python Regular Expression - Exercises, Practice, Solution at: https://www.w3resource.com/python-exercises/re/python-re-exercise-38.php; last accessed on November 10, 2021. """ print("= Method 2i: Get substring with ...") print(" re.findall('\"(.*?)\"', string).") # Enumerate all the test strings. for current_test_string in my_strings: for values in re.findall('"(.*?)"', current_test_string): my_substrings.append(values) #print("values are:",values,"=") print(" my_substrings are:",my_substrings,"=") my_substrings = [] print(" > stores empty strings embedded within quotation marks.") print(" > Method works.") """ Use the regular expression from [Avinash2021], without the suggested re.search() method. References: + [Avinash2021] - <NAME>, Answer to ``Extract text between quotation using regex python'', Stack Exchange, Inc., New York, NY, October 12, 2021. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/69543129/1531728 and https://stackoverflow.com/questions/69542978/extract-text-between-quotation-using-regex-python/69543129#69543129; November 8, 2021 was the last accessed date. + [user17405772021] - user1740577, Answer to ``Extract text between quotation using regex python'', Stack Exchange, Inc., New York, NY, October 12, 2021. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/69543030/1531728 and https://stackoverflow.com/questions/69542978/extract-text-between-quotation-using-regex-python/69543030#69543030; November 8, 2021 was the last accessed date. """ print("= Method 2j: Get substring with ...") print(" re.findall('\"(.+?)\"', string).") # Enumerate all the test strings. for current_test_string in my_strings: for values in re.findall('"(.+?)"', current_test_string): my_substrings.append(values) #print("values are:",values,"=") print(" my_substrings are:",my_substrings,"=") my_substrings = [] print(" > stores empty strings embedded within quotation marks.") print(" > Method FAILS!!!") #print("= Method 2k: Get substring with ...") #print(" re.search('\"(.+?)\"', string).") """ Enumerate all the test strings. Use the method in [Avinash2021] based on regular expression objects, specifically 're.Match' object. However, it only finds the first/only substring embedded within quotation marks, double quotes in this case. [KiteStaff20XY] uses the re.search().group(1) method that returns only the first substring embedded within the specified markers. """ # for current_test_string in my_strings: #values = re.search('"(.+?)"', current_test_string) # values = re.findall('"(.+?)"', current_test_string) #values = re.compile('"(.+?)"', current_test_string) #values = re.match('"(.+?)"', current_test_string) #values = re.fullmatch('"(.+?)"', current_test_string) # """ # if values: # print("values are:",values,"=") # #print(" my_substrings are:",my_substrings,"=") # my_substrings = [] # """ #for v in values: #print("values are:",values.group(1),"=") #print(" my_substrings are:",my_substrings,"=") # print("values are:",values,"=") #print("values are:",values.span(),"=") #print("values are:",values.string,"=") # print("values are:",values.group(),"=") #print("values are:",values.group(0),"=") #print("values are:",values.group(1),"=") #print("values are:",values.group(2),"=") #my_substrings = [] """ Combining the my_string.split() method [Roman2010][Koledoye2016] with the loop/enumeration approach [Booboo2020]. References: + [Roman2010] + [Koledoye2016] """ print("= Method 2k: Get substring with ...") print(" my_string.split() method.") # Enumerate all the test strings. for current_test_string in my_strings: #values = current_test_string.split("'") #for x in values: for x in current_test_string.split("\""): if x.strip(): my_substrings.append(x) #print("x is:",x,"=") print(" my_substrings are:",my_substrings,"=") my_substrings = [] print(" !!!Approach works for strings with targeted") print(" substrings embedded in patterns!!!") print(" > Method FAILS!!!") """ References: + [devnull2013] - devnull, Answer to `Extracting strings in Python in either single or double quotes', Stack Exchange, Inc., New York, NY, October 30, 2013. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/19675957/1531728 and https://stackoverflow.com/questions/19675760/extracting-strings-in-python-in-either-single-or-double-quotes/19675957#19675957; November 11, 2021 was the last accessed date. """ print("= Method 2l: Get substring with ...") print(" re.findall(r\"['\\\"](.*?)['\\\"]\", string).") # Enumerate all the test strings. for current_test_string in my_strings: for values in re.findall(r"['\"](.*?)['\"]", current_test_string): my_substrings.append(values) #print("values are:",values,"=") print(" my_substrings are:",my_substrings,"=") my_substrings = [] print(" > stores empty strings embedded within quotation marks.") print(" > Method works.") """ References: + [devnull2013] - devnull, Answer to `Extracting strings in Python in either single or double quotes', Stack Exchange, Inc., New York, NY, October 30, 2013. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/19675957/1531728 and https://stackoverflow.com/questions/19675760/extracting-strings-in-python-in-either-single-or-double-quotes/19675957#19675957; November 11, 2021 was the last accessed date. + [devnull2013a] - tripleee, Comment about an answer to `Extracting strings in Python in either single or double quotes', Stack Exchange, Inc., New York, NY, October 30, 2013. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/questions/19675760/extracting-strings-in-python-in-either-single-or-double-quotes#comment29222674_19675957; November 11, 2021 was the last accessed date. + [WikipediaContributors2019i] - Wikipedia contributors, "CAR and CDR", Wikimedia Foundation, San Francisco, CA, August 28, 2019. Available online from Wikipedia, The Free Encyclopedia: Lisp (programming language) at: https://en.wikipedia.org/wiki/CAR_and_CDR; February 19, 2020 was the last accessed date. """ print("= Method 2m: Get substring with ...") print(" re.findall(r\"(['\\\"])(.*?)['\\\"]\", string).") # Enumerate all the test strings. for current_test_string in my_strings: for values in re.findall(r"(['\"])(.*?)['\"]", current_test_string): my_substrings.append(values) #print("values are:",values,"=") print(" my_substrings are:",my_substrings,"=") my_substrings = [] print(" > stores empty strings embedded within quotation marks.") print(" > Store result in tuples, as cdr for the cons (car, cdr).") #print(" > Method FAILS!!!") print(" > Method works.") """ References: + [devnull2013] - devnull, Answer to `Extracting strings in Python in either single or double quotes', Stack Exchange, Inc., New York, NY, October 30, 2013. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/19675957/1531728 and https://stackoverflow.com/questions/19675760/extracting-strings-in-python-in-either-single-or-double-quotes/19675957#19675957; November 11, 2021 was the last accessed date. + [tripleee2013] - tripleee, Comment about an answer to `Extracting strings in Python in either single or double quotes', Stack Exchange, Inc., New York, NY, October 30, 2013. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/questions/19675760/extracting-strings-in-python-in-either-single-or-double-quotes#comment29224831_19675957; November 11, 2021 was the last accessed date. + [WikipediaContributors2019i] - Wikipedia contributors, "CAR and CDR", Wikimedia Foundation, San Francisco, CA, August 28, 2019. Available online from Wikipedia, The Free Encyclopedia: Lisp (programming language) at: https://en.wikipedia.org/wiki/CAR_and_CDR; February 19, 2020 was the last accessed date. """ print("= Method 2n: Get substring with ...") print(" re.findall(r\"(['\\\"])(.*?)\\1\", string).") # Enumerate all the test strings. for current_test_string in my_strings: for values in re.findall(r"(['\"])(.*?)\1", current_test_string): my_substrings.append(values) #print("values are:",values,"=") print(" my_substrings are:",my_substrings,"=") my_substrings = [] print(" > stores empty strings embedded within quotation marks.") print(" > Store result in tuples, as cdr for the cons (car, cdr).") #print(" > Method FAILS!!!") print(" > Method works.") """ References: + [Feldman2021] - Alex 'af3ld' Feldman and Shaido, Answer to `How do I find quotes in strings - Python', Stack Exchange, Inc., New York, NY, February 26, 2021. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/38444540/1531728 and https://stackoverflow.com/questions/38444389/how-do-i-find-quotes-in-strings-python/38444540#38444540; November 11, 2021 was the last accessed date. + [Paluter2016] - Paluter, Answer to "How do I find quotes in strings - Python", Stack Exchange, Inc., New York, NY, July 18, 2016. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/38444653/1531728 and https://stackoverflow.com/questions/38444389/how-do-i-find-quotes-in-strings-python/38444653#38444653; November 11, 2021 was the last accessed date. """ print("= Method 2o: Get substring with ...") print(" my_string.find(pattern, string_positional_index).") my_substrings = [] # Enumerate all the test strings. for current_test_string in my_strings: """ for values in re.findall(r"(['\"])(.*?)\1", current_test_string): my_substrings.append(values) #print("values are:",values,"=") print(" my_substrings are:",my_substrings,"=") """ start = current_test_string.find('"') while -1 != start: end = current_test_string.find('"', start+1) if -1 != end: substring = current_test_string[start+1:end] #print(" > substring of current_test_string is:",substring,"=") my_substrings.append(substring) start = current_test_string.find('"', end+1) print(" my_substrings are:",my_substrings,"=") my_substrings = [] print(" > stores empty strings embedded within quotation marks.") #print(" > Method FAILS!!!") print(" > Method works.") """ Testing methods for non-capturing groups and non-consuming groups. References: + [Tisnek2015] - <NAME> and Kenly, Answer to `How do I find quotes in strings - Python', Stack Exchange, Inc., New York, NY, December 17, 2015. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/34155315/1531728 and https://stackoverflow.com/questions/34155110/python-find-text-in-file-between-quotation-marks/34155315#34155315; November 11, 2021 was the last accessed date. """ print("= Method 2p: Get substring with ...") print(" re.findall('(?:\")([^\"]*)(?:\")', current_test_string).") my_substrings = [] """ Enumerate all the test strings. Test methods for non-capturing groups. """ for current_test_string in my_strings: for values in re.findall('(?:")([^"]*)(?:")', current_test_string): my_substrings.append(values) #print("values are:",values,"=") print(" my_substrings are:",my_substrings,"=") my_substrings
<reponame>marses/tiltx """ Created on Thu May 16 18:53:46 2019 @author: seslija """ import numpy import matplotlib.pyplot as plt from scipy.signal import savgol_filter from scipy import integrate def detect_cusum(x, threshold=1, drift=0, ending=False): """Cumulative sum algorithm (CUSUM) to detect abrupt changes in data. Parameters ---------- x : 1D array_like data. threshold : positive number, optional (default = 1) amplitude threshold for the change in the data. drift : positive number, optional (default = 0) drift term that prevents any change in the absence of change. ending : bool, optional (default = False) True (1) to estimate when the change ends; False (0) otherwise. Returns ------- ta : 1D array_like [indi, indf], int alarm time (index of when the change was detected). tai : 1D array_like, int index of when the change started. taf : 1D array_like, int index of when the change ended (if `ending` is True). amp : 1D array_like, float amplitude of changes (if `ending` is True). Notes ----- Tuning of the CUSUM algorithm according to Gustafsson (2000)[1]_: Start with a very large `threshold`. Choose `drift` to one half of the expected change, or adjust `drift` such that `g` = 0 more than 50% of the time. Then set the `threshold` so the required number of false alarms (this can be done automatically) or delay for detection is obtained. If faster detection is sought, try to decrease `drift`. If fewer false alarms are wanted, try to increase `drift`. If there is a subset of the change times that does not make sense, try to increase `drift`. Note that by default repeated sequential changes, i.e., changes that have the same beginning (`tai`) are not deleted because the changes were detected by the alarm (`ta`) at different instants. This is how the classical CUSUM algorithm operates. If you want to delete the repeated sequential changes and keep only the beginning of the first sequential change, set the parameter `ending` to True. In this case, the index of the ending of the change (`taf`) and the amplitude of the change (or of the total amplitude for a repeated sequential change) are calculated and only the first change of the repeated sequential changes is kept. In this case, it is likely that `ta`, `tai`, and `taf` will have less values than when `ending` was set to False. The cumsum algorithm is taken from (with minor modifications): https://github.com/BMClab/BMC/blob/master/functions/detect_cusum.py <NAME>., <NAME>. (2018) Notes on Scientific Computing for Biomechanics and Motor Control. GitHub repository, https://github.com/bmclab/BMC """ x = numpy.atleast_1d(x).astype('float64') gp, gn = numpy.zeros(x.size), numpy.zeros(x.size) ta, tai, taf = numpy.array([[], [], []], dtype=int) tap, tan = 0, 0 amp = numpy.array([]) a = -0.0001 # Find changes (online form) for i in range(1, x.size): s = x[i] - x[i-1] gp[i] = gp[i-1] + s - drift # cumulative sum for + change gn[i] = gn[i-1] - s - drift # cumulative sum for - change if gp[i] < a: gp[i], tap = 0, i if gn[i] < a: gn[i], tan = 0, i if gp[i] > threshold or gn[i] > threshold: # change detected! ta = numpy.append(ta, i) # alarm index tai = numpy.append(tai, tap if gp[i] > threshold else tan) # start gp[i], gn[i] = 0, 0 # reset alarm # THE CLASSICAL CUSUM ALGORITHM ENDS HERE # Estimation of when the change ends (offline form) if tai.size and ending: _, tai2, _, _ = detect_cusum(x[::-1], threshold, drift) taf = x.size - tai2[::-1] - 1 # Eliminate repeated changes, changes that have the same beginning tai, ind = numpy.unique(tai, return_index=True) ta = ta[ind] # taf = numpy.unique(taf, return_index=False) # corect later if tai.size != taf.size: if tai.size < taf.size: taf = taf[[numpy.argmax(taf >= i) for i in ta]] else: ind = [numpy.argmax(i >= ta[::-1])-1 for i in taf] ta = ta[ind] tai = tai[ind] # Delete intercalated changes (the ending of the change is after # the beginning of the next change) ind = taf[:-1] - tai[1:] > 0 if ind.any(): ta = ta[~numpy.append(False, ind)] tai = tai[~numpy.append(False, ind)] taf = taf[~numpy.append(ind, False)] # Amplitude of changes amp = x[taf] - x[tai] return ta, tai, taf, amp def last_stationary_point(y,t): """ Finds stationary points in the signal. :param y: the array representing a time series :type y: list or array :param t: the array representing time component :type t: list or array """ finite_difference_1 = numpy.gradient(y, t) is_peak = [finite_difference_1[i] * finite_difference_1[i + 1] <= -0*0.0001 for i in range(len(finite_difference_1) - 1)] peak_indices = [i for i, b in enumerate(is_peak) if b] if len(peak_indices) == 0: return [],[] return peak_indices[-1] def CUMSUM_flip(y,t): """ Iterative cumsum algorithm for change point detection in the time series y. The algorithm normalizes the input gradient and feeds it to the standard cumsum algorithm with decreasing treshold. The algorithm does not stop untill the change point is detected. If no change point is detected, it uses a last stationary point as the output. If there is no statinary point, the algorithm gives the last point of y as the output. :param y: the array representing a time series :type y: list or array :param t: the array representing time component :type t: list or array """ # compute gradinet of y grad = numpy.gradient(y, t) # if time series shortar than 12 samples, report the last index if (t[-1]-t[0])< 0.120: return len(y)-1 # grad_f is filtered gradient # l_filter = 5 # grad_f = savgol_filter(grad, l_filter, 3) # no filtration applied grad_f = grad # normalize the input to repeated cumsum grad_norm = (grad_f-grad_f.min())/(grad_f.max()-grad_f.min()) for k in range(0,15): ta_k, tai_k, taf_k, amp_k = detect_cusum( numpy.flip(grad_norm), 0.85-0.05*k, 0.01, True) if len(taf_k) > 0: taf = taf_k[0] ind = len(grad_norm) - int(taf) if t[taf] - t[ind] < 120: ta_k_aux, tai_k_aux, taf_k_aux, amp_k_aux = detect_cusum( numpy.flip(grad_norm)[taf_k[0]:], 0.85-0.05*k, 0.005, True) if len(taf_k_aux) > 0: taf = taf_k_aux[0] ind = len(grad_norm) - int(taf)-taf_k[0] # 170 ms as an exclusion treshold if t[ind]-t[0] > 0.170: return ind else: # could not find a reaction point stationary_points = last_stationary_point(y,t) if len(stationary_points[0]) > 0: stationary_index, _ = stationary_points if stationary_index[-1] >= 12: return stationary_index[-1] else: return len(y)-1 else: return len(y)-1 def number_of_flips(y,t): """ Finds the number of flips in a signal y defined on t. That is, the function computes a number of turning points in the time series y. :param y: the array representing a time series :type y: list or array :param t: the array representing time component :type t: list or array """ finite_difference_1 = numpy.gradient(y, t) is_peak = [finite_difference_1[i] * finite_difference_1[i + 1] <= 0 for i in range(len(finite_difference_1) - 1)] peak_indices = [i for i, b in enumerate(is_peak) if b] if len(peak_indices) == 0: return 0 return len(peak_indices) def SampEn(U, m, r): """ This function calculates the sample entropy of the time series U. For a given embedding dimension m, tolerance r and number of data points N, SampEn is the negative logarithm of the probability that if two sets of simultaneous data points of length m have distance smaller than r then two sets of simultaneous data points of length m+1 also have smaller than r. For more information see, e.g., https://en.wikipedia.org/wiki/Sample_entropy :param U: the array representing a time series :type U: list or array :param m: embedding dimension :type m: integer :param r: tolerance :type r: float """ def _maxdist(x_i, x_j): result = max([abs(ua - va) for ua, va in zip(x_i, x_j)]) return result def _phi(m): x = [[U[j] for j in range(i, i + m - 1 + 1)] for i in range(N - m + 1)] C = 1.*numpy.array([len([1 for j in range(len(x)) if i != j and _maxdist(x[i], x[j]) <= r]) for i in range(len(x))]) return sum(C) N = len(U)
<reponame>23doors/pulumi-gcp # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class InstanceTemplate(pulumi.CustomResource): can_ip_forward: pulumi.Output[bool] """ Whether to allow sending and receiving of packets with non-matching source or destination IPs. This defaults to false. """ description: pulumi.Output[str] """ A brief description of this resource. """ disks: pulumi.Output[list] """ Disks to attach to instances created from this template. This can be specified multiple times for multiple disks. Structure is documented below. * `autoDelete` (`bool`) * `boot` (`bool`) * `device_name` (`str`) * `disk_encryption_key` (`dict`) * `kmsKeySelfLink` (`str`) * `diskName` (`str`) * `disk_size_gb` (`float`) * `diskType` (`str`) * `interface` (`str`) * `labels` (`dict`) - A set of key/value label pairs to assign to instances created from this template, * `mode` (`str`) * `source` (`str`) * `sourceImage` (`str`) * `type` (`str`) """ enable_display: pulumi.Output[bool] """ Enable [Virtual Displays](https://cloud.google.com/compute/docs/instances/enable-instance-virtual-display#verify_display_driver) on this instance. **Note**: `allow_stopping_for_update` must be set to true in order to update this field. """ guest_accelerators: pulumi.Output[list] """ List of the type and count of accelerator cards attached to the instance. Structure documented below. * `count` (`float`) * `type` (`str`) """ instance_description: pulumi.Output[str] """ A brief description to use for instances created from this template. """ labels: pulumi.Output[dict] """ A set of key/value label pairs to assign to instances created from this template, """ machine_type: pulumi.Output[str] """ The machine type to create. """ metadata: pulumi.Output[dict] """ Metadata key/value pairs to make available from within instances created from this template. """ metadata_fingerprint: pulumi.Output[str] """ The unique fingerprint of the metadata. """ metadata_startup_script: pulumi.Output[str] """ An alternative to using the startup-script metadata key, mostly to match the compute_instance resource. This replaces the startup-script metadata key on the created instance and thus the two mechanisms are not allowed to be used simultaneously. """ min_cpu_platform: pulumi.Output[str] """ Specifies a minimum CPU platform. Applicable values are the friendly names of CPU platforms, such as `Intel Haswell` or `Intel Skylake`. See the complete list [here](https://cloud.google.com/compute/docs/instances/specify-min-cpu-platform). """ name: pulumi.Output[str] """ The name of the instance template. If you leave this blank, this provider will auto-generate a unique name. """ name_prefix: pulumi.Output[str] """ Creates a unique name beginning with the specified prefix. Conflicts with `name`. """ network_interfaces: pulumi.Output[list] """ Networks to attach to instances created from this template. This can be specified multiple times for multiple networks. Structure is documented below. * `accessConfigs` (`list`) * `natIp` (`str`) * `network_tier` (`str`) * `aliasIpRanges` (`list`) * `ip_cidr_range` (`str`) * `subnetworkRangeName` (`str`) * `network` (`str`) * `networkIp` (`str`) * `subnetwork` (`str`) * `subnetworkProject` (`str`) """ project: pulumi.Output[str] """ The ID of the project in which the resource belongs. If it is not provided, the provider project is used. """ region: pulumi.Output[str] """ An instance template is a global resource that is not bound to a zone or a region. However, you can still specify some regional resources in an instance template, which restricts the template to the region where that resource resides. For example, a custom `subnetwork` resource is tied to a specific region. Defaults to the region of the Provider if no value is given. """ scheduling: pulumi.Output[dict] """ The scheduling strategy to use. More details about this configuration option are detailed below. * `automaticRestart` (`bool`) * `nodeAffinities` (`list`) * `key` (`str`) * `operator` (`str`) * `values` (`list`) * `onHostMaintenance` (`str`) * `preemptible` (`bool`) """ self_link: pulumi.Output[str] """ The URI of the created resource. """ service_account: pulumi.Output[dict] """ Service account to attach to the instance. Structure is documented below. * `email` (`str`) * `scopes` (`list`) """ shielded_instance_config: pulumi.Output[dict] """ Enable [Shielded VM](https://cloud.google.com/security/shielded-cloud/shielded-vm) on this instance. Shielded VM provides verifiable integrity to prevent against malware and rootkits. Defaults to disabled. Structure is documented below. **Note**: `shielded_instance_config` can only be used with boot images with shielded vm support. See the complete list [here](https://cloud.google.com/compute/docs/images#shielded-images). * `enableIntegrityMonitoring` (`bool`) * `enableSecureBoot` (`bool`) * `enableVtpm` (`bool`) """ tags: pulumi.Output[list] """ Tags to attach to the instance. """ tags_fingerprint: pulumi.Output[str] """ The unique fingerprint of the tags. """ def __init__(__self__, resource_name, opts=None, can_ip_forward=None, description=None, disks=None, enable_display=None, guest_accelerators=None, instance_description=None, labels=None, machine_type=None, metadata=None, metadata_startup_script=None, min_cpu_platform=None, name=None, name_prefix=None, network_interfaces=None, project=None, region=None, scheduling=None, service_account=None, shielded_instance_config=None, tags=None, __props__=None, __name__=None, __opts__=None): """ Manages a VM instance template resource within GCE. For more information see [the official documentation](https://cloud.google.com/compute/docs/instance-templates) and [API](https://cloud.google.com/compute/docs/reference/latest/instanceTemplates). :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[bool] can_ip_forward: Whether to allow sending and receiving of packets with non-matching source or destination IPs. This defaults to false. :param pulumi.Input[str] description: A brief description of this resource. :param pulumi.Input[list] disks: Disks to attach to instances created from this template. This can be specified multiple times for multiple disks. Structure is documented below. :param pulumi.Input[bool] enable_display: Enable [Virtual Displays](https://cloud.google.com/compute/docs/instances/enable-instance-virtual-display#verify_display_driver) on this instance. **Note**: `allow_stopping_for_update` must be set to true in order to update this field. :param pulumi.Input[list] guest_accelerators: List of the type and count of accelerator cards attached to the instance. Structure documented below. :param pulumi.Input[str] instance_description: A brief description to use for instances created from this template. :param pulumi.Input[dict] labels: A set of key/value label pairs to assign to instances created from this template, :param pulumi.Input[str] machine_type: The machine type to create. :param pulumi.Input[dict] metadata: Metadata key/value pairs to make available from within instances created from this template. :param pulumi.Input[str] metadata_startup_script: An alternative to using the startup-script metadata key, mostly to match the compute_instance resource. This replaces the startup-script metadata key on the created instance and thus the two mechanisms are not allowed to be used simultaneously. :param pulumi.Input[str] min_cpu_platform: Specifies a minimum CPU platform. Applicable values are the friendly names of CPU platforms, such as `Intel Haswell` or `Intel Skylake`. See the complete list [here](https://cloud.google.com/compute/docs/instances/specify-min-cpu-platform). :param pulumi.Input[str] name: The name of the instance template. If you leave this blank, this provider will auto-generate a unique name. :param pulumi.Input[str] name_prefix: Creates a unique name beginning with the specified prefix. Conflicts with `name`. :param pulumi.Input[list] network_interfaces: Networks to attach to instances created from this template. This can be specified multiple times for multiple networks. Structure is documented below. :param pulumi.Input[str] project: The ID of the project in which the resource belongs. If it is not provided, the provider project is used. :param pulumi.Input[str] region: An instance template is a global resource that is not bound to a zone or a region. However, you can still specify some regional resources in an instance template, which restricts the template to the region where that resource resides. For example, a custom `subnetwork` resource is tied to a specific region. Defaults to the region of the Provider if no value is given. :param pulumi.Input[dict] scheduling: The scheduling strategy to use. More details about this configuration option are detailed below. :param pulumi.Input[dict] service_account: Service account to attach to the instance. Structure is documented below. :param pulumi.Input[dict] shielded_instance_config: Enable [Shielded VM](https://cloud.google.com/security/shielded-cloud/shielded-vm) on this instance. Shielded VM provides verifiable integrity to prevent against malware and rootkits. Defaults to disabled. Structure is documented below. **Note**: `shielded_instance_config` can only be used with boot images with shielded vm support. See the complete list [here](https://cloud.google.com/compute/docs/images#shielded-images). :param pulumi.Input[list] tags: Tags to attach to the instance. The **disks** object supports the following: * `autoDelete` (`pulumi.Input[bool]`) * `boot` (`pulumi.Input[bool]`) * `device_name` (`pulumi.Input[str]`) * `disk_encryption_key` (`pulumi.Input[dict]`) * `kmsKeySelfLink` (`pulumi.Input[str]`) * `diskName` (`pulumi.Input[str]`) * `disk_size_gb` (`pulumi.Input[float]`) * `diskType` (`pulumi.Input[str]`) * `interface` (`pulumi.Input[str]`) * `labels` (`pulumi.Input[dict]`) - A set of key/value label pairs to assign to instances created from this template, * `mode` (`pulumi.Input[str]`) * `source` (`pulumi.Input[str]`) * `sourceImage` (`pulumi.Input[str]`) * `type` (`pulumi.Input[str]`) The **guest_accelerators** object supports
""" Basic linear algebra operations as defined on the parameter sets of entire models. We can think of these list as a single vectors consisting of all the individual parameter values. The functions in this module implement basic linear algebra operations on such lists. The operations defined in the module follow the PyTorch convention of appending the '__' suffix to the name of in-place operations. """ import copy import math import numpy as np import torch import torch.nn class ModelParameters: """ A ModelParameters object is an abstract view of a model's optimizable parameters as a tensor. This class enables the parameters of models of the same 'shape' (architecture) to be operated on as if they were 'real' tensors. A ModelParameters object cannot be converted to a true tensor as it is potentially irregularly shaped. TODO: ENFORCE GPU OR CPU DEVICE """ def __init__(self, parameters: list): if not isinstance(parameters, list) and all(isinstance(p, torch.Tensor) for p in parameters): raise AttributeError('Argument to ModelParameter is not a list of torch.Tensor objects.') self.parameters = parameters def __len__(self) -> int: """ Returns the number of model layers within the parameter tensor. :return: number of layer tensors """ return len(self.parameters) def numel(self) -> int: """ Returns the number of elements (i.e. individual parameters) within the tensor. Note that this refers to individual parameters, not layers. :return: number of elements in tensor """ return sum(p.numel() for p in self.parameters) def __getitem__(self, index) -> torch.nn.Parameter: """ Returns the tensor of the layer at the given index. :param index: layer index :return: tensor of layer """ return self.parameters[index] def __eq__(self, other: 'ModelParameters') -> bool: """ Compares this parameter tensor for equality with the argument tensor, using the == operator. :param other: the object to compare to :return: true if equal """ if not isinstance(other, ModelParameters) or len(self) != len(other): return False else: return all(torch.equal(p_self, p_other) for p_self, p_other in zip(self.parameters, other.parameters)) def __add__(self, other: 'ModelParameters') -> 'ModelParameters': """ Constructively returns the result of addition between this tensor and another. :param other: other to add :return: self + other """ return ModelParameters([self[idx] + other[idx] for idx in range(len(self))]) def __radd__(self, other: 'ModelParameters') -> 'ModelParameters': """ Constructively returns the result of addition between this tensor and another. :param other: model parameters to add :return: other + self """ return self.__add__(other) def add_(self, other: 'ModelParameters'): """ In-place addition between this tensor and another. :param other: model parameters to add :return: none """ for idx in range(len(self)): self.parameters[idx] += other[idx].cuda() # TODO: change def __sub__(self, other: 'ModelParameters') -> 'ModelParameters': """ Constructively returns the result of subtracting another tensor from this one. :param other: model parameters to subtract :return: self - other """ return ModelParameters([self[idx] - other[idx] for idx in range(len(self))]) def __rsub__(self, other: 'ModelParameters') -> 'ModelParameters': """ Constructively returns the result of subtracting this tensor from another one. :param other: other to subtract from :return: other - self """ return self.__sub__(other) def sub_(self, vector: 'ModelParameters'): """ In-place subtraction of another tensor from this one. :param vector: other to subtract :return: none """ for idx in range(len(self)): self.parameters[idx] -= vector[idx].cuda() # TODO: change def __mul__(self, scalar) -> 'ModelParameters': """ Constructively returns the result of multiplying this tensor by a scalar. :param scalar: scalar to multiply by :return: self * scalar """ return ModelParameters([self[idx] * scalar for idx in range(len(self))]) def __rmul__(self, scalar) -> 'ModelParameters': """ Constructively returns the result of multiplying this tensor by a scalar. :param scalar: scalar to multiply by :return: scalar * self """ return self.__mul__(scalar) def mul_(self, scalar): """ In-place multiplication of this tensor by a scalar. :param scalar: scalar to multiply by :return: none """ for idx in range(len(self)): self.parameters[idx] *= scalar def __truediv__(self, scalar) -> 'ModelParameters': """ Constructively returns the result of true-dividing this tensor by a scalar. :param scalar: scalar to divide by :return: scalar / self """ return ModelParameters([self[idx] / scalar for idx in range(len(self))]) def truediv_(self, scalar): """ In-place true-division of this tensor by a scalar. :param scalar: scalar to divide by :return: none """ for idx in range(len(self)): self.parameters[idx] /= scalar def __floordiv__(self, scalar) -> 'ModelParameters': """ Constructively returns the result of floor-dividing this tensor by a scalar. :param scalar: scalar to divide by :return: scalar // self """ return ModelParameters([self[idx] // scalar for idx in range(len(self))]) def floordiv_(self, scalar): """ In-place floor-division of this tensor by a scalar. :param scalar: scalar to divide by :return: none """ for idx in range(len(self)): self.parameters[idx] //= scalar def __matmul__(self, other: 'ModelParameters') -> 'ModelParameters': """ Constructively returns the result of tensor-multiplication of this tensor by another tensor. :param other: other tensor :return: self @ tensor """ raise NotImplementedError() def dot(self, other: 'ModelParameters') -> float: """ Returns the vector dot product of this ModelParameters vector and the given other vector. :param other: other ModelParameters vector :return: dot product of self and other """ param_products = [] for idx in range(len(self.parameters)): param_products.append((self.parameters[idx] * other.parameters[idx]).sum().item()) return sum(param_products) def model_normalize_(self, ref_point: 'ModelParameters', order=2): """ In-place model-wise normalization of the tensor. :param ref_point: use this model's norm, if given :param order: norm order, e.g. 2 for L2 norm :return: none """ for parameter in self.parameters: parameter *= (ref_point.model_norm(order) / self.model_norm()) def layer_normalize_(self, ref_point: 'ModelParameters', order=2): """ In-place layer-wise normalization of the tensor. :param ref_point: use this model's layer norms, if given :param order: norm order, e.g. 2 for L2 norm :return: none """ # in-place normalize each parameter for layer_idx, parameter in enumerate(self.parameters, 0): parameter *= (ref_point.layer_norm(layer_idx, order) / self.layer_norm(layer_idx, order)) def filter_normalize_(self, ref_point: 'ModelParameters', order=2): """ In-place filter-wise normalization of the tensor. :param ref_point: use this model's filter norms, if given :param order: norm order, e.g. 2 for L2 norm :return: none """ for l in range(len(self.parameters)): # normalize one-dimensional bias vectors if len(self.parameters[l].size()) == 1: self.parameters[l] *= (ref_point.parameters[l].norm(order) / self.parameters[l].norm(order)) # normalize two-dimensional weight vectors for f in range(len(self.parameters[l])): self.parameters[l][f] *= ref_point.filter_norm((l, f), order) / (self.filter_norm((l, f), order)) def model_norm(self, order=2) -> float: """ Returns the model-wise L-norm of the tensor. :param order: norm order, e.g. 2 for L2 norm :return: L-norm of tensor """ # L-n norm of model where we treat the model as a flat other return math.pow(sum([ torch.pow(layer, order).sum().item() for layer in self.parameters ]), 1.0 / order) def layer_norm(self, index, order=2) -> float: """ Returns a list of layer-wise L-norms of the tensor. :param order: norm order, e.g. 2 for L2 norm :param index: layer index :return: list of L-norms of layers """ # L-n norms of layer where we treat each layer as a flat other return math.pow(torch.pow(self.parameters[index], order).sum().item(), 1.0 / order) def filter_norm(self, index, order=2) -> float: """ Returns a 2D list of filter-wise L-norms of the tensor. :param order: norm order, e.g. 2 for L2 norm :param index: tuple with layer index and filter index :return: list of L-norms of filters """ # L-n norm of each filter where we treat each layer as a flat other return math.pow(torch.pow(self.parameters[index[0]][index[1]], order).sum().item(), 1.0 / order) def as_numpy(self) -> np.ndarray: """ Returns the tensor as a flat numpy array. :return: a numpy array """ return np.concatenate([p.numpy().flatten() for p in self.parameters]) def _get_parameters(self) -> list: """ Returns a reference to the internal parameter data in whatever format used by the source model. :return: reference to internal parameter data """ return self.parameters def rand_u_like(example_vector: ModelParameters, return_vector=False) -> ModelParameters: """ Create a new ModelParameters object of size and shape compatible with the given example vector, such that the values in the ModelParameter are uniformly distributed in the range [0,1]. :param example_vector: defines by example the size and shape the new vector will have :return: new vector with uniformly distributed values """ new_vector = [] ''' example_vector --- current model parameters ''' for param in example_vector: new_vector.append(torch.rand(size=param.size(), dtype=example_vector[0].dtype)) if return_vector: return ModelParameters(new_vector), new_vector return ModelParameters(new_vector) def rand_n_like(example_vector: ModelParameters) -> ModelParameters: """ Create a new ModelParameters object of size and shape compatible with the given example
:return: AmendmentPagedMetadata If the method is called asynchronously, returns the request thread. """ all_params = ['lower_threshold', 'upper_threshold', 'organizations', 'offset', 'records', 'order_by', 'order'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_amendments_by_created_date" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'lower_threshold' is set if ('lower_threshold' not in params) or (params['lower_threshold'] is None): raise ValueError("Missing the required parameter `lower_threshold` when calling `get_amendments_by_created_date`") # verify the required parameter 'upper_threshold' is set if ('upper_threshold' not in params) or (params['upper_threshold'] is None): raise ValueError("Missing the required parameter `upper_threshold` when calling `get_amendments_by_created_date`") resource_path = '/amendments/created/{lower-threshold}/{upper-threshold}'.replace('{format}', 'json') path_params = {} if 'lower_threshold' in params: path_params['lower-threshold'] = params['lower_threshold'] if 'upper_threshold' in params: path_params['upper-threshold'] = params['upper_threshold'] query_params = {} if 'organizations' in params: query_params['organizations'] = params['organizations'] if 'offset' in params: query_params['offset'] = params['offset'] if 'records' in params: query_params['records'] = params['records'] if 'order_by' in params: query_params['order_by'] = params['order_by'] if 'order' in params: query_params['order'] = params['order'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type([]) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AmendmentPagedMetadata', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only')) def get_amendments_by_updated_date(self, lower_threshold, upper_threshold, **kwargs): """ Returns a collection of amendment objects with updated times within the period specified by the lower-threshold and upper-threshold parameters. By default 10 values are returned. Records are returned in natural order. {\"nickname\":\"Retrieve by updated\",\"response\":\"getAmendmentByUpdated.html\"} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_amendments_by_updated_date(lower_threshold, upper_threshold, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str lower_threshold: The UTC DateTime specifying the start of the result period. (required) :param str upper_threshold: The UTC DateTime specifying the end of the result period. (required) :param list[str] organizations: A list of organization-IDs used to restrict the scope of API calls. :param int offset: The offset from the first amendment to return. :param int records: The maximum number of amendments to return. :param str order_by: Specify a field used to order the result set. :param str order: Ihe direction of any ordering, either ASC or DESC. :return: AmendmentPagedMetadata If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_amendments_by_updated_date_with_http_info(lower_threshold, upper_threshold, **kwargs) else: (data) = self.get_amendments_by_updated_date_with_http_info(lower_threshold, upper_threshold, **kwargs) return data def get_amendments_by_updated_date_with_http_info(self, lower_threshold, upper_threshold, **kwargs): """ Returns a collection of amendment objects with updated times within the period specified by the lower-threshold and upper-threshold parameters. By default 10 values are returned. Records are returned in natural order. {\"nickname\":\"Retrieve by updated\",\"response\":\"getAmendmentByUpdated.html\"} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_amendments_by_updated_date_with_http_info(lower_threshold, upper_threshold, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str lower_threshold: The UTC DateTime specifying the start of the result period. (required) :param str upper_threshold: The UTC DateTime specifying the end of the result period. (required) :param list[str] organizations: A list of organization-IDs used to restrict the scope of API calls. :param int offset: The offset from the first amendment to return. :param int records: The maximum number of amendments to return. :param str order_by: Specify a field used to order the result set. :param str order: Ihe direction of any ordering, either ASC or DESC. :return: AmendmentPagedMetadata If the method is called asynchronously, returns the request thread. """ all_params = ['lower_threshold', 'upper_threshold', 'organizations', 'offset', 'records', 'order_by', 'order'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_amendments_by_updated_date" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'lower_threshold' is set if ('lower_threshold' not in params) or (params['lower_threshold'] is None): raise ValueError("Missing the required parameter `lower_threshold` when calling `get_amendments_by_updated_date`") # verify the required parameter 'upper_threshold' is set if ('upper_threshold' not in params) or (params['upper_threshold'] is None): raise ValueError("Missing the required parameter `upper_threshold` when calling `get_amendments_by_updated_date`") resource_path = '/amendments/updated/{lower-threshold}/{upper-threshold}'.replace('{format}', 'json') path_params = {} if 'lower_threshold' in params: path_params['lower-threshold'] = params['lower_threshold'] if 'upper_threshold' in params: path_params['upper-threshold'] = params['upper_threshold'] query_params = {} if 'organizations' in params: query_params['organizations'] = params['organizations'] if 'offset' in params: query_params['offset'] = params['offset'] if 'records' in params: query_params['records'] = params['records'] if 'order_by' in params: query_params['order_by'] = params['order_by'] if 'order' in params: query_params['order'] = params['order'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type([]) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AmendmentPagedMetadata', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only')) def retire_amendment(self, amendment_id, organizations, **kwargs): """ Retires the amendment specified by the amendment-ID parameter. Retiring a amendment causes it to cancel based on the specificed retirement settings for the product. {\"nickname\":\"Delete an amendment\",\"response\":\"deleteAmendment.html\"} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.retire_amendment(amendment_id, organizations, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str amendment_id: ID of the amendment. (required) :param list[str] organizations: A list of organization-IDs used to restrict the scope of API calls. (required) :return: AmendmentPagedMetadata If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.retire_amendment_with_http_info(amendment_id, organizations, **kwargs) else: (data) = self.retire_amendment_with_http_info(amendment_id, organizations, **kwargs) return data def retire_amendment_with_http_info(self, amendment_id, organizations, **kwargs): """ Retires the amendment specified by the amendment-ID parameter. Retiring a amendment causes it to cancel based on the specificed retirement settings for the product. {\"nickname\":\"Delete an amendment\",\"response\":\"deleteAmendment.html\"} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.retire_amendment_with_http_info(amendment_id, organizations, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str amendment_id: ID of the amendment. (required) :param list[str] organizations: A list of organization-IDs used to restrict the scope of API calls. (required) :return: AmendmentPagedMetadata If the method is called asynchronously, returns the request thread. """ all_params = ['amendment_id', 'organizations'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method retire_amendment" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'amendment_id' is set if ('amendment_id' not in params) or (params['amendment_id'] is None): raise ValueError("Missing the required parameter `amendment_id` when calling `retire_amendment`") # verify the required parameter 'organizations' is set if ('organizations' not in params) or (params['organizations'] is None): raise ValueError("Missing the required parameter `organizations` when calling `retire_amendment`") resource_path = '/amendments/{amendment-ID}'.replace('{format}', 'json') path_params = {} if 'amendment_id' in params: path_params['amendment-ID'] = params['amendment_id'] query_params = {} if 'organizations' in params: query_params['organizations'] = params['organizations'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['text/plain']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AmendmentPagedMetadata', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only')) def update_amendment(self, amendment, **kwargs): """ Update an amendment. {\"nickname\":\"Update an amendment\",\"request\":\"updateAmendmentRequest.html\",\"response\":\"updateAmendmentResponse.html\" } This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be
import json import os from nose.tools import * from lxml import etree as ET from mets_dnx import factory as mdf CURRENT_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__))) mets_dnx_nsmap = { 'mets': 'http://www.loc.gov/METS/', 'dnx': 'http://www.exlibrisgroup.com/dps/dnx' } def test_mets_dnx(): """Test basic construction of METS DNX""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_mets( ie_dmd_dict=ie_dc_dict, pres_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm'), modified_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'mm'), input_dir=os.path.join(os.path.dirname( os.path.realpath(__file__)), 'data', 'test_batch_1'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], ) print(ET.tounicode(mets, pretty_print=True)) def test_mets_dnx_with_digital_original_details(): """Test big fix where true/false value was being populated with uppercase inital letter, when translating True or False booleans to strings. """ ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_mets( ie_dmd_dict=ie_dc_dict, pres_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm'), modified_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'mm'), input_dir=os.path.join(os.path.dirname( os.path.realpath(__file__)), 'data', 'test_batch_1'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], digital_original=True ) digital_original_el = mets.xpath('.//key[@id="DigitalOriginal"]')[0] assert(digital_original_el.text == "true") def test_mets_dnx_single_file(): """Test basic construction of METS DNX for single file""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_single_file_mets( ie_dmd_dict=ie_dc_dict, filepath=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm', 'presmaster.jpg'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], ) print(ET.tounicode(mets, pretty_print=True)) def test_all_amdsec_subsections_have_dnx_element(): """Make sure that all amdsec have at least a DNX stub element""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_single_file_mets( ie_dmd_dict=ie_dc_dict, filepath=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm', 'presmaster.jpg'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], ) # print(ET.tounicode(mets, pretty_print=True)) amd_sections = mets.findall("{http://www.loc.gov/METS/}amdSec") for section in amd_sections: for tag in ('techMD', 'rightsMD', 'sourceMD', 'digiprovMD'): subsection = section.find("{http://www.loc.gov/METS/}%s" % tag) dnx = subsection.find(".//dnx") assert(dnx != None) def test_structmap_has_version_in_rep_id_for_single_file_sip(): """test to confirm that a rep's physical structmap has the "-1" at the end of it""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_single_file_mets( ie_dmd_dict=ie_dc_dict, filepath=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm', 'presmaster.jpg'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], ) # print(ET.tounicode(mets, pretty_print=True)) structmap = mets.findall("{http://www.loc.gov/METS/}structMap")[0] # print(structmap.tag) assert(structmap.attrib["ID"][-2:] == "-1") def test_structmap_has_version_in_rep_id_for_multi_file_sip(): """test to confirm that a rep's physical structmap has the "-1" at the end of it""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_mets( ie_dmd_dict=ie_dc_dict, pres_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm'), modified_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'mm'), input_dir=os.path.join(os.path.dirname( os.path.realpath(__file__)), 'data', 'test_batch_1'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], digital_original=True ) structmap = mets.findall("{http://www.loc.gov/METS/}structMap")[0] # print(structmap.tag) assert(structmap.attrib["ID"][-2:] == "-1") def test_mets_dnx_with_cms(): """Test basic construction of METS DNX, with CMS details""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_mets( ie_dmd_dict=ie_dc_dict, cms=[{'recordId': '55515', 'system': 'emu'}], pres_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm'), modified_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'mm'), input_dir=os.path.join(os.path.dirname( os.path.realpath(__file__)), 'data', 'test_batch_1'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], ) print(ET.tounicode(mets, pretty_print=True)) cms_id = mets.findall('.//dnx/section[@id="CMS"]/record/key[@id="recordId"]') # print(cms_id[0].tag) # cms_id = mets.find('.//{http://www.exlibrisgroup.com/dps/dnx}section[@ID="CMS"]/{http://www.exlibrisgroup.com/dps/dnx}record/{http://www.exlibrisgroup.com/dps/dnx}key[@recordId]') assert(cms_id[0].text == '55515') def test_filesec_has_use_attrib_for_single_file_sip(): """test to confirm that a filesec has the USE="VIEW" attribute""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_single_file_mets( ie_dmd_dict=ie_dc_dict, cms=[{'recordId': '55515', 'system': 'emu'}], filepath=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm', 'presmaster.jpg'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], ) filegrp = mets.findall(".//{http://www.loc.gov/METS/}fileGrp")[0] assert(filegrp.attrib["USE"] == "VIEW") def test_structmap_for_single_file_mets_has_upper_case_type(): ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_single_file_mets( ie_dmd_dict=ie_dc_dict, cms=[{'recordId': '55515', 'system': 'emu'}], filepath=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm', 'presmaster.jpg'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], ) structmap = mets.findall(".//{http://www.loc.gov/METS/}structMap")[0] # filegrp = mets.findall(".//{http://www.loc.gov/METS/}fileGrp")[0] # assert(filegrp.attrib["USE"] == "VIEW") assert(structmap.attrib["TYPE"] == "PHYSICAL") print(structmap.attrib["TYPE"]) assert(structmap.attrib["TYPE"] != "Physical") def test_mets_dnx_with_for_single_rep(): """ """ ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_mets( ie_dmd_dict=ie_dc_dict, pres_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm'), input_dir=os.path.join(os.path.dirname( os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], digital_original=True ) digital_original_el = mets.xpath('.//key[@id="DigitalOriginal"]')[0] assert(digital_original_el.text == "true") def test_mets_dnx_with_json_for_admid_in_filesec_files(): """For testing new function for building SIP with JSON documents describing the structure and metadata of files. Specifically testing that all files in the filesec have an ADMID attrib.""" ie_dc_dict = {"dc:title": "test title"} pm_json = """[ {"fileOriginalName": "img1.jpg", "fileOriginalPath": "path/to/files/img1.jpg", "MD5": "aff64bf1391ac627edb3234a422f9a77", "fileCreationDate": "1st of January, 1601", "fileModificationDate": "1st of January, 1601", "label": "Image One", "note": "This is a note for image 1"}, {"fileOriginalName": "img2.jpg", "fileOriginalPath": "path/to/files/img2.jpg", "MD5": "9d09f20ab8e37e5d32cdd1508b49f0a9", "fileCreationDate": "1st of January, 1601", "fileModificationDate": "1st of January, 1601", "label": "Image Two", "note": "This is a note for image 2"} ]""" mets = mdf.build_mets_from_json( ie_dmd_dict=ie_dc_dict, pres_master_json = pm_json, input_dir=os.path.join(CURRENT_DIR, 'data', 'test_batch_2'), digital_original=True) print(ET.tounicode(mets, pretty_print=True)) files_list = mets.findall(".//{http://www.loc.gov/METS/}fileSec" "/{http://www.loc.gov/METS/}fileGrp/{http://www.loc.gov/METS/}file") for file in files_list: assert("ADMID" in file.attrib) assert(file.attrib['ADMID'].endswith('-amd')) amdsec_list = mets.findall(".//{http://www.loc.gov/METS/}amdSec") for amdsec in amdsec_list: assert("ID" in amdsec.attrib) assert(amdsec.attrib["ID"].endswith("-amd")) def test_mets_dnx_deriv_copy_gets_preservationType(): """Test basic construction of METS DNX, but assigning an access derivative (using the mm dir for efficiency's sake)""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_mets( ie_dmd_dict=ie_dc_dict, pres_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm'), access_derivative_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'mm'), input_dir=os.path.join(os.path.dirname( os.path.realpath(__file__)), 'data', 'test_batch_1'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], ) print(ET.tounicode(mets, pretty_print=True)) ad_pres_type = mets.findall('./{http://www.loc.gov/METS/}amdSec[@ID="rep2-amd"]' '/{http://www.loc.gov/METS/}techMD/{http://www.loc.gov/METS/}mdWrap/{http://www.loc.gov/METS/}xmlData' '/dnx/section[@id="generalRepCharacteristics"]/record/key[@id="preservationType"]' )[0] assert (ad_pres_type.text == "DERIVATIVE_COPY") # print(ad_pres_type) def test_file_original_path_exists(): """Test to make sure the fileOriginalPath is added to the generalFileCharacteristics sections""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_mets( ie_dmd_dict=ie_dc_dict, pres_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm'), modified_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'mm'), input_dir=os.path.join(os.path.dirname( os.path.realpath(__file__)), 'data', 'test_batch_1'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], ) file_gen_chars_list = mets.findall('.//section[@id="generalFileCharacteristics"]') for el in file_gen_chars_list: fop = el.findall('./record/key[@id="fileOriginalName"]') assert(fop[0].text in ('presmaster.jpg', 'modifiedmaster.jpg')) def test_gfc_file_label_exists(): """Test to make sure the label is added to the generalFileCharacteristics sections, and that it onlye includes the filename up to the extension.""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_mets( ie_dmd_dict=ie_dc_dict, pres_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm'), modified_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'mm'), input_dir=os.path.join(os.path.dirname( os.path.realpath(__file__)), 'data', 'test_batch_1'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], ) file_gen_chars_list = mets.findall('.//section[@id="generalFileCharacteristics"]') for el in file_gen_chars_list: fop = el.findall('./record/key[@id="label"]') assert(fop[0].text in ('presmaster', 'modifiedmaster')) print(ET.tounicode(mets, pretty_print=True)) def test_structmap_file_label_exists(): """Test to make sure the label is added to the structMap file-level divs, and that it only includes the filename up to the extension.""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_mets( ie_dmd_dict=ie_dc_dict, pres_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm'), modified_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'mm'), input_dir=os.path.join(os.path.dirname( os.path.realpath(__file__)), 'data', 'test_batch_1'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], ) struct_maps = mets.findall('./{http://www.loc.gov/METS/}structMap') for struct_map in struct_maps: file_divs = struct_map.findall('.//{http://www.loc.gov/METS/}div[@TYPE="FILE"]') for file_div in file_divs: assert(file_div.attrib['LABEL'] in ('presmaster', 'modifiedmaster')) print(ET.tounicode(mets, pretty_print=True)) def test_labels_in_mets_dnx_single_file(): """Test that labels are added to generalFileCharactierists secion and structMap, and that they are populated with the filenames (sans extensions)""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_single_file_mets( ie_dmd_dict=ie_dc_dict, filepath=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm', 'presmaster.jpg'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], ) gfc = mets.findall('.//section[@id="generalFileCharacteristics"]/record')[0] # since we're doing this, let's also test the FileOriginalName key file_original_name = gfc.findall('./key[@id="fileOriginalName"]')[0] assert(file_original_name.text == 'presmaster.jpg') label = gfc.findall('./key[@id="label"]')[0] assert(label.text == 'presmaster') struct_map = mets.findall('./{http://www.loc.gov/METS/}structMap')[0] file_div = struct_map.findall('.//{http://www.loc.gov/METS/}div[@TYPE="FILE"]')[0] assert(file_div.attrib['LABEL'] == 'presmaster') # assert(gfc_file_original_name == 'presmaster.jpg') # print(ET.tounicode(mets, pretty_print=True)) def test_digtial_original_dnx(): """Test that the digitalOriginal value is being properly translated from a boolean input to a lower-case string of 'true' or 'false'""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_mets( ie_dmd_dict=ie_dc_dict, pres_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm'), modified_master_dir=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'mm'), input_dir=os.path.join(os.path.dirname( os.path.realpath(__file__)), 'data', 'test_batch_1'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], digital_original=True ) grc = mets.findall('.//section[@id="generalRepCharacteristics"]')[0] # print(ET.tounicode(grc[0], pretty_print=True)) do = grc.findall('.//key[@id="DigitalOriginal"]')[0] assert (do.text == 'true') # for grc in general_rep_characteristics: # assert(grc.text == 'true') def test_digtial_original_dnx_single_file(): """Test that the digitalOriginal value is being properly translated from a boolean input to a lower-case string of 'true' or 'false' for a single-file METS""" ie_dc_dict = {"dc:title": "test title"} mets = mdf.build_single_file_mets( ie_dmd_dict=ie_dc_dict, filepath=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'test_batch_1', 'pm', 'presmaster.jpg'), generalIECharacteristics=[{ 'submissionReason': 'bornDigitalContent', 'IEEntityType': 'periodicIE'}], digital_original=True ) grc = mets.findall('.//section[@id="generalRepCharacteristics"]')[0] # print(ET.tounicode(grc[0], pretty_print=True)) do = grc.findall('.//key[@id="DigitalOriginal"]')[0] assert (do.text == 'true') # for grc in general_rep_characteristics: # assert(grc.text == 'true') print(ET.tounicode(mets, pretty_print=True)) # 2017-08-01: Removed "ORDER" attribute, so the following test is no longer # required # def test_structmap_order_attrib_single_file(): # """Test for order to be included in single file METS structmaps # At both div levels""" # ie_dc_dict = {"dc:title": "test title"} # mets = mdf.build_single_file_mets( # ie_dmd_dict=ie_dc_dict, # filepath=os.path.join( # os.path.dirname(os.path.realpath(__file__)), # 'data', # 'test_batch_1', # 'pm', # 'presmaster.jpg'), # generalIECharacteristics=[{ # 'submissionReason': 'bornDigitalContent', # 'IEEntityType': 'periodicIE'}], # digital_original=True # ) # structmap_divs = mets.findall('.//{http://www.loc.gov/METS/}structMap/{http://www.loc.gov/METS/}div') # for div in structmap_divs: # print(div.attrib["ORDER"]) # assert("ORDER" in div.attrib.keys()) # grc = mets.findall('.//section[@id="generalRepCharacteristics"]')[0] # print(ET.tounicode(grc[0], pretty_print=True)) # do = grc.findall('.//key[@id="DigitalOriginal"]')[0] # assert (do.text == 'true') # for grc in general_rep_characteristics: # assert(grc.text == 'true') # print(ET.tounicode(mets, pretty_print=True)) # 2017-07-20: Removed "ORDER" attribute, so the following test is no longer # required # def test_structmap_order_attrib(): # """Test for order to be included in single file METS structmaps divs where TYPE="FILE" """ # ie_dc_dict = {"dc:title": "test title"} # mets = mdf.build_mets( # ie_dmd_dict=ie_dc_dict, # pres_master_dir=os.path.join( # os.path.dirname(os.path.realpath(__file__)), # 'data', # 'test_batch_1', # 'pm'), # modified_master_dir=os.path.join( # os.path.dirname(os.path.realpath(__file__)), # 'data', # 'test_batch_1', # 'mm'), # input_dir=os.path.join(os.path.dirname( # os.path.realpath(__file__)), # 'data', # 'test_batch_1'), # generalIECharacteristics=[{ # 'submissionReason': 'bornDigitalContent', # 'IEEntityType': 'periodicIE'}], # digital_original=True # ) # print(ET.tounicode(mets, pretty_print=True)) # structmap_divs = mets.findall('.//{http://www.loc.gov/METS/}structMap/{http://www.loc.gov/METS/}div') # for div in structmap_divs: # if "TYPE" in div.attrib
# -*- coding: utf-8 -*- """ Created on Fri Jun 15 15:02:49 2018 @author: <NAME> """ # Last modified: 03.07.2018 00:08:28 Yuanyuan Wang # Improved logging and exit code # Last modified: 09.07.2018 12:01:00 Jingliang Hu # update function 'getTiffExtent' to get EPSG code from tiff ROI # Last modified: 10.07.2018 14:09:35 Yuanyuan Wang # added multi thread in gdalwarp import os import glob import subprocess import numpy as np import xml.etree.ElementTree as et from osgeo import ogr,osr,gdal unfiltStringList = ['geocoded_subset_unfilt_dat','_Orb_Cal_Deb_TC_SUB.tif','mosaic_unfilt_dat'] leefilStringList = ['geocoded_subset_dat','_Orb_Cal_Deb_Spk_TC_SUB.tif','mosaic_dat'] def createGPTTemplate(inputZip, template, geoRegion, region, procFlag, projFlag, projection=0): # This function updates the gpt preprocessing xml template for each downloaded data and starts the preprocessing # Input: # -- inputZip - downloaded sentinel-1 data in zip # -- template - path to gpt xml template # -- geoRegion - the coordinate of ROI # -- region - pixel-wise extent of ROI # -- procFlag - processing flag: 1: no filtering, 2: lee filtering, 3: water mask, 4: range azimuth complex form, 5: range azimuth covariance matrix (boxcar filtered) # -- projFlag - projection flag: 1: WGS longitude, latitude, 2: UTM # # Output: # -- template - write the updated template # -- data - save processed data # # Example input: # inputZip = '/media/sf_So2Sat/data/massive_downloading/0378_index_0033_Adelaide/original_dat/201706/S1A_IW_SLC__1SDV_20170607T200453_20170607T200519_016932_01C2E2_7E63.zip' # template = '/media/sf_So2Sat/sentinel1_data_processing/ma_data_proc_leeflt_2.0/gpt_template_preprocessing_lee.xml' # geoRegion = 'POLYGON ((138.47500610351562 -35.087501525878906, 138.75 -35.087501525878906, 138.75 -34.775001525878906, 138.47500610351562 -34.775001525878906, 138.47500610351562 -35.087501525878906, 138.47500610351562 -35.087501525878906))' # region = '0,0,25234,17679' try: gptdir = os.environ['gpt'] except: print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") print("ERROR: Directory to ESA SNAP TOOLBOX GPT not found in environment variables") print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") return 0 city = inputZip.split('/')[-4] time = inputZip.split('/')[-2] if procFlag == 1: outputData = inputZip.replace('original_dat',unfiltStringList[0]) outputData = outputData.replace('.zip',unfiltStringList[1]) elif procFlag == 2: outputData = inputZip.replace('original_dat',leefilStringList[0]) outputData = outputData.replace('.zip',leefilStringList[1]) elif procFlag == 3: outputData = inputZip.replace('original_dat','water_mask') outputData = outputData.replace('.zip','_water_mask.tif') elif procFlag == 4: outputData = inputZip.replace('original_dat','rangeAzimuth_dat') outputData = outputData.replace('.zip','_Orb_Cal_Deb_Sub.dim') elif procFlag == 5: outputData = inputZip.replace('original_dat','rangeAzimuth_nlm_dat') outputData = outputData.replace('.zip','_Orb_Cal_Deb_Spk_Sub.dim') else: print("ERROR: INDICATED PROCESSING (procFlag) IS NOT YET SUPPORTED") exit(1) outputPath = '/'.join(outputData.split('/')[:-1]) tree = et.parse(template) root = tree.getroot() for node in root.findall('node'): if node[0].text == 'Read': node[2][0].text = inputZip elif node[0].text == 'Write': node[2][0].text = outputData elif node[0].text == 'Subset': node[2][1].text = region node[2][2].text = geoRegion elif node[0].text == 'Terrain-Correction' and projection != 0: node[2][9].text = projection # XML File configure if not os.path.exists(outputPath): os.makedirs(outputPath) if procFlag == 1: xmldir = outputPath + "/Preprocessing_Orb_Cal_Deb_TC_SUB.xml" print(" ") print("#############################################################") print("INFO: Data of the city "+city+" at the time of "+time) print("INFO: Apply orbit file, calibration, deburst, terrain correction, subset: ") elif procFlag == 2: xmldir = outputPath + "/Preprocessing_Orb_Cal_Deb_Spk_TC_SUB.xml" print(" ") print("#############################################################") print("INFO: Data of the city "+city+" at the time of "+time) print("INFO: Apply orbit file, calibration, deburst, Lee filtering, terrain correction, subset: ") elif procFlag == 3: xmldir = outputPath + "/_water_mask.xml" print(" ") print("#############################################################") print("INFO: Water mask for data of the city "+city+" at the time of "+time) print("INFO: Apply orbit file, calibration, deburst, filtering, terrain correction, subset: ") elif procFlag == 4: xmldir = outputPath + "/Preprocessing_Orb_Cal_Deb_Sub.xml" print(" ") print("#############################################################") print("INFO: range azimuth data in complex form of the city "+city+" at the time of "+time) print("INFO: Apply orbit file, calibration, deburst, subset: ") elif procFlag == 5: xmldir = outputPath + "/Preprocessing_Orb_Cal_Deb_Spk_Sub.xml" print(" ") print("#############################################################") print("INFO: range azimuth data in covariance matrix form of the city "+city+" at the time of "+time) print("INFO: Apply orbit file, calibration, deburst, filtering, subset: ") # write the graph xml tree.write(xmldir) if os.path.exists(outputData): print('INFO: Output file exist') print("#############################################################") print(" ") subprocess.call([gptdir,xmldir]) return 2, outputData else: subprocess.call([gptdir,xmldir]) print('INFO: process done') print("#############################################################") print(" ") return 1, outputData def getGeoRegion(cpath,kmlCityList): # This function read the unique index of city for data indicated by cpath, and then find the coordinates of the corresponding ROI # Input # -- cpath - path to the file of city, where data saved # -- kmlCityList - path to the ROI kml file # # Output # -- geoRegion - WKT format coordinate of ROI in longitude and latitude # -- centerPoint - longitude and latitude of the center point to the ROI # read the unique index of city temp = cpath.split('/')[-1].split('_') # print cpath # print temp idx = int(temp[1]) # find the ROI coordinate of the city tree = et.parse(kmlCityList) for item in tree.findall('.//{http://www.opengis.net/kml/2.2}Placemark'): if item[1][0][3].text == str(idx): found = item break # convert the text coordinate into WKT coordinate coordText = found[2][0][0][0].text temp = coordText.split(' ') x = np.zeros([5,1]) y = np.zeros([5,1]) for i in range(0,len(temp)): a,b = temp[i].split(',') x[i] = np.double(a) y[i] = np.double(b) xmin = np.min(x) xmax = np.max(x) ymin = np.min(y) ymax = np.max(y) centerPoint = np.array([np.float32(xmin+xmax)/2,np.float32(ymin+ymax)/2]) # create a polygon ring = ogr.Geometry(ogr.wkbLinearRing) ring.AddPoint(xmin,ymin) ring.AddPoint(xmax,ymin) ring.AddPoint(xmax,ymax) ring.AddPoint(xmin,ymax) ring.AddPoint(xmin,ymin) poly = ogr.Geometry(ogr.wkbPolygon) poly.AddGeometry(ring) geoRegion = poly.ExportToWkt() return geoRegion, centerPoint def getROIPoints(cpath,kmlCityList): # This function finds the WGS coordinates of ROI for one city # Input # -- cpath - path to the file of city, where data saved # -- kmlCityList - path to the ROI kml file # # Output # -- points - a 3 by 2 array, # - 1st column is longitude, 2nd column is latitude # - 1st row: center point, 2nd row: upper-left cornor, 3rd row: bottom-right cornor # read the unique index of city temp = cpath.split('/')[-1].split('_') # print cpath # print temp idx = int(temp[1]) # find the ROI coordinate of the city tree = et.parse(kmlCityList) for item in tree.findall('.//{http://www.opengis.net/kml/2.2}Placemark'): if item[1][0][3].text == str(idx): found = item break coordText = found[2][0][0][0].text temp = coordText.split(' ') x = np.zeros([5,1]) y = np.zeros([5,1]) for i in range(0,len(temp)): a,b = temp[i].split(',') x[i] = np.double(a) y[i] = np.double(b) xmin = np.min(x) xmax = np.max(x) ymin = np.min(y) ymax = np.max(y) points = np.array([[np.float32(xmin+xmax)/2,np.float32(ymin+ymax)/2],[xmin,ymax],[xmax,ymin]]) return points def roiLatlon2UTM(WGSPoint,outputEPSG=0): # This function transfers geographical coordinate (lon-lat) into WGS 84 / UTM zone coordinate using GDAL # Input: # -- WGSPoint - A N by M array of lon-lat coordinate; N is number of points, 1st col is longitude, 2nd col is latitude # -- outputEPSG - targeting UTM zone code # # Output: # -- UTMPoints - A N by M array of WGS 84 /UTM zone coordinate; N is number of points, 1st col is X, 2nd col is Y # -- outputEPSG - A UTM EPSG code calculated from the center of ROI # -- utmProjInfo - A string contains comprehensive utm projection information # WGSPoint = np.array(WGSPoint).astype(np.float64) if len(WGSPoint.shape)==1: WGSPoint = np.stack((WGSPoint,WGSPoint),axis=0) nb,dim = np.shape(WGSPoint) elif len(WGSPoint.shape)==2: # number of WGSPoint nb,dim = np.shape(WGSPoint) elif len(WGSPoint.shape)==3: print('ERROR: DIMENSION OF POINTS SHOULD NO MORE THAN TWO') # geographic coordinate (lat-lon) WGS84 inputEPSG = 4326 # WGS 84 / UTM zone if outputEPSG==0: if WGSPoint[0][1]<0: outputEPSG = 32700 else: outputEPSG = 32600 outputEPSG = int(outputEPSG + np.floor((WGSPoint[0][0]+180)/6) + 1) # create coordinate transformation inSpatialRef = osr.SpatialReference() inSpatialRef.ImportFromEPSG(inputEPSG) outSpatialRef = osr.SpatialReference() outSpatialRef.ImportFromEPSG(outputEPSG) utmProjInfo = outSpatialRef.ExportToWkt() coordTransform = osr.CoordinateTransformation(inSpatialRef, outSpatialRef) # transform point UTMPoints = np.zeros(WGSPoint.shape) for i in range(0,np.size(WGSPoint,axis=0)): p = ogr.Geometry(ogr.wkbPoint) p.AddPoint(WGSPoint[i][1], WGSPoint[i][0]) p.Transform(coordTransform) UTMPoints[i][0] = p.GetX() UTMPoints[i][1] = p.GetY() return UTMPoints, outputEPSG, utmProjInfo def latlon2utm(points): # This function transfers geographical coordinate (lon-lat) into WGS 84 / UTM zone coordinate using GDAL # Input: # -- points - A N by M array of lon-lat coordinate; N is number of points, 1st col is longitude, 2nd col is latitude # # Output: # -- points - A N by M array of WGS 84 /UTM zone coordinate; N is number of points, 1st col is X, 2nd col is Y # points = np.array(points) if len(points.shape)==1: points = np.stack((points,points),axis=0) nb,dim = np.shape(points) elif len(points.shape)==2: # number of points nb,dim = np.shape(points) elif len(points.shape)==3: print('ERROR: DIMENSION OF POINTS SHOULD NO MORE THAN TWO') # geographic coordinate (lat-lon) WGS84 inputEPSG = 4326 # WGS 84 / UTM zone if points[0][1]<0: outputEPSG = 32700 else:
<reponame>asabyr/LensTools<filename>lenstools/image/shear.py """ .. module:: shear :platform: Unix :synopsis: This module implements a set of operations which are usually performed on weak lensing shear maps .. moduleauthor:: <NAME> <<EMAIL>> """ from __future__ import division from ..extern import _topology from .convergence import ConvergenceMap import numpy as np #FFT engine from ..utils.fft import NUMPYFFTPack fftengine = NUMPYFFTPack() #Units from astropy.units import deg,rad,arcsec,quantity #I/O from .io import loadFITS,saveFITS try: import matplotlib import matplotlib.pyplot as plt from matplotlib.colors import LogNorm matplotlib = matplotlib except ImportError: matplotlib = False ########################################## ########Spin1 class####################### ########################################## class Spin1(object): def __init__(self,data,angle,**kwargs): #Sanity check assert angle.unit.physical_type in ["angle","length"] assert data.shape[1]==data.shape[2],"The map must be a square!!" self.data = data self.side_angle = angle self.resolution = self.side_angle / self.data.shape[1] if self.side_angle.unit.physical_type=="angle": self.resolution = self.resolution.to(arcsec) self.lmin = 2.0*np.pi/self.side_angle.to(rad).value self.lmax = np.sqrt(2)*np.pi/self.resolution.to(rad).value self._extra_attributes = kwargs.keys() for key in kwargs: setattr(self,key,kwargs[key]) @property def info(self): """ Displays some of the information stored in the map (mainly resolution) """ print("Pixels on a side: {0}".format(self.data.shape[1])) print("Pixel size: {0}".format(self.resolution)) print("Total angular size: {0}".format(self.side_angle)) print("lmin={0:.1e} ; lmax={1:.1e}".format(self.lmin,self.lmax)) #Multipole values in real FFT space def getEll(self): """ Get the values of the multipoles in real FFT space :returns: ell array with real FFT shape :rtype: array. """ ellx = fftengine.fftfreq(self.data.shape[1])*2.0*np.pi / self.resolution.to(u.rad).value elly = fftengine.rfftfreq(self.data.shape[1])*2.0*np.pi / self.resolution.to(u.rad).value return np.sqrt(ellx[:,None]**2 + elly[None,:]**2) ############################################################################################### ############################################################################################### @classmethod def load(cls,filename,format=None,**kwargs): """ This class method allows to read the map from a data file, in various formats :param filename: name of the file in which the map is saved :type filename: str. :param format: the format of the file in which the map is saved (can be a callable too); if None, it's detected automatically from the filename :type format: str. or callable :param kwargs: the keyword arguments are passed to the format (if callable) :type kwargs: dict. :returns: Spin1 instance with the loaded map """ if format is None: extension = filename.split(".")[-1] if extension in ["fit","fits"]: format="fits" else: raise IOError("File format not recognized from extension '{0}', please specify it manually".format(extension)) if format=="fits": return loadFITS(cls,filename) else: angle,data = format(filename,**kwargs) return cls(data,angle) def save(self,filename,format=None,double_precision=False): """ Saves the map to an external file, of which the format can be specified (only fits implemented so far) :param filename: name of the file on which to save the plane :type filename: str. :param format: format of the file, only FITS implemented so far; if None, it's detected automatically from the filename :type format: str. :param double_precision: if True saves the Plane in double precision :type double_precision: bool. """ if format is None: extension = filename.split(".")[-1] if extension in ["fit","fits"]: format="fits" else: raise IOError("File format not recognized from extension '{0}', please specify it manually".format(extension)) if format=="fits": saveFITS(self,filename,double_precision) else: raise ValueError("Format {0} not implemented yet!!".format(format)) def setAngularUnits(self,unit): """ Convert the angular units of the map to the desired unit :param unit: astropy unit instance to which to perform the conversion :type unit: astropy units """ #Sanity check assert unit.physical_type=="angle" self.side_angle = self.side_angle.to(unit) def gradient(self,x=None,y=None): """ Computes the gradient of the components of the spin1 field at each point :param x: optional, x positions at which to evaluate the gradient :type x: array with units :param y: optional, y positions at which to evaluate the gradient :type y: array with units :returns: the gradient of the spin1 field in array form, of shape (4,:,:) where the four components are, respectively, 1x,1y,2x,2y; the units for the finite difference are pixels """ if self.data.shape[0] > 2: raise ValueError("Gradients are nor defined yet for spin>1 fields!!") if (x is not None) and (y is not None): assert x.shape==y.shape,"x and y must have the same shape!" #x coordinates if type(x)==quantity.Quantity: assert x.unit.physical_type=="angle" j = np.mod(((x / self.resolution).decompose().value).astype(np.int32),self.data.shape[1]) else: j = np.mod((x / self.resolution.to(rad).value).astype(np.int32),self.data.shape[1]) #y coordinates if type(y)==quantity.Quantity: assert y.unit.physical_type=="angle" i = np.mod(((y / self.resolution).decompose().value).astype(np.int32),self.data.shape[1]) else: i = np.mod((y / self.resolution.to(rad).value).astype(np.int32),self.data.shape[1]) else: i = None j = None #Call the C backend grad1x,grad1y = _topology.gradient(self.data[0],j,i) grad2x,grad2y = _topology.gradient(self.data[1],j,i) #Return if (x is not None) and (y is not None): return np.array([grad1x.reshape(x.shape),grad1y.reshape(y.shape),grad2x.reshape(x.shape),grad2y.reshape(y.shape)]) else: return np.array([grad1x,grad1y,grad2x,grad2y]) def getValues(self,x,y): """ Extract the map values at the requested (x,y) positions; this is implemented using the numpy fast indexing routines, so the formats of x and y must follow the numpy advanced indexing rules. Periodic boundary conditions are enforced :param x: x coordinates at which to extract the map values (if unitless these are interpreted as radians) :type x: numpy array or quantity :param y: y coordinates at which to extract the map values (if unitless these are interpreted as radians) :type y: numpy array or quantity :returns: numpy array with the map values at the specified positions, with shape (N,shape x) where N is the number of components of the map field :raises: IndexError if the formats of x and y are not the proper ones """ assert isinstance(x,np.ndarray) and isinstance(y,np.ndarray) #x coordinates if type(x)==quantity.Quantity: assert x.unit.physical_type=="angle" j = np.mod(((x / self.resolution).decompose().value).astype(np.int32),self.data.shape[2]) else: j = np.mod((x / self.resolution.to(rad).value).astype(np.int32),self.data.shape[2]) #y coordinates if type(y)==quantity.Quantity: assert y.unit.physical_type=="angle" i = np.mod(((y / self.resolution).decompose().value).astype(np.int32),self.data.shape[1]) else: i = np.mod((y / self.resolution.to(rad).value).astype(np.int32),self.data.shape[1]) #Return the map values at the specified coordinates return self.data[:,i,j] def visualize(self,fig=None,ax=None,component_labels=(r"$\gamma_1$",r"$\gamma_2$"),colorbar=False,cmap="viridis",cbar_label=None,**kwargs): """ Visualize the shear map; the kwargs are passed to imshow """ if not matplotlib: raise ImportError("matplotlib is not installed, cannot visualize!") #Instantiate figure if (fig is None) or (ax is None): self.fig,self.ax = plt.subplots(1,self.data.shape[0],figsize=(16,8)) else: self.fig = fig self.ax = ax #Build the color map if isinstance(cmap,matplotlib.colors.Colormap): cmap = cmap else: cmap = plt.get_cmap(cmap) #Plot the map if colorbar: for i in range(self.data.shape[0]): plt.colorbar(self.ax[i].imshow(self.data[i],origin="lower",interpolation="nearest",extent=[0,self.side_angle.value,0,self.side_angle.value],cmap=cmap,**kwargs),ax=self.ax[i]) self.ax[i].grid(b=False) else: for i in range(self.data.shape[0]): self.ax[i].imshow(self.data[i],origin="lower",interpolation="nearest",extent=[0,self.side_angle.value,0,self.side_angle.value],cmap=cmap,**kwargs) self.ax[i].grid(b=False) #Axes labels for i in range(self.data.shape[0]): self.ax[i].set_xlabel(r"$x$({0})".format(self.side_angle.unit.to_string()),fontsize=18) self.ax[i].set_ylabel(r"$y$({0})".format(self.side_angle.unit.to_string()),fontsize=18) self.ax[i].set_title(component_labels[i],fontsize=18) def savefig(self,filename): """ Saves the map visualization to an external file :param filename: name of the file on which to save the map :type filename: str. """ self.fig.savefig(filename) ########################################## ########Spin2 class####################### ########################################## class Spin2(Spin1): @classmethod def fromEBmodes(cls,fourier_E,fourier_B,angle=3.14*deg): """ This class method allows to build a shear map specifying its E and B mode components :param fourier_E: E mode of the shear map in fourier space :type fourier_E: numpy 2D array, must be of type np.complex128 and must have a shape that is appropriate for a real fourier transform, i.e. (N,N/2 + 1); N should be a power of 2 :param fourier_B: B mode of the shear map in fourier space :type fourier_B: numpy 2D array, must be of type np.complex128 and must have a shape that is appropriate for a real fourier transform, i.e. (N,N/2 + 1); N should be a power of 2 :param angle: Side angle of the real space map in degrees :type angle: float. :returns: the corresponding ShearMap instance :raises: AssertionErrors for inappropriate inputs """ assert fourier_E.dtype == np.complex128 and fourier_B.dtype == np.complex128 assert fourier_E.shape[1] == fourier_E.shape[0]/2 + 1 assert fourier_B.shape[1] == fourier_B.shape[0]/2 + 1 assert fourier_E.shape == fourier_B.shape #Compute frequencies lx = fftengine.rfftfreq(fourier_E.shape[0]) ly = fftengine.fftfreq(fourier_E.shape[0]) #Safety check assert len(lx)==fourier_E.shape[1] assert len(ly)==fourier_E.shape[0] #Compute sines and cosines of rotation angles l_squared = lx[np.newaxis,:]**2 + ly[:,np.newaxis]**2 l_squared[0,0] = 1.0 sin_2_phi = 2.0 * lx[np.newaxis,:] * ly[:,np.newaxis] / l_squared cos_2_phi = (lx[np.newaxis,:]**2 - ly[:,np.newaxis]**2) / l_squared sin_2_phi[0,0] = 0.0 cos_2_phi[0,0] = 0.0 #Invert E/B modes and find the components of the shear ft_data1 = cos_2_phi * fourier_E - sin_2_phi * fourier_B ft_data2 = sin_2_phi * fourier_E + cos_2_phi * fourier_B #Invert Fourier transforms data1 = fftengine.irfft2(ft_data1) data2 = fftengine.irfft2(ft_data2) #Instantiate new shear map class new = cls(np.array([data1,data2]),angle) setattr(new,"fourier_E",fourier_E) setattr(new,"fourier_B",fourier_B) return new def sticks(self,fig=None,ax=None,pixel_step=10,multiplier=1.0): """ Draw the ellipticity map using the shear components :param ax: ax on which to draw the ellipticity field :type ax: matplotlib ax object :param pixel_step: One arrow will be drawn every pixel_step pixels to avoid arrow overplotting :type pixel_step: int. :param multiplier: Multiplies the stick length by a factor :type multiplier: float. :returns: ax -- the matplotlib ax object on which the stick field was drawn >>> import matplotlib.pyplot as plt >>> test = ShearMap.load("shear.fit",loader=load_fits_default_shear) >>> fig,ax = plt.subplots() >>> test.sticks(ax,pixel_step=50) """ if not(matplotlib): raise ImportError("matplotlib is not installed, cannot visualize!") #Instantiate fig,ax objects if (fig is None) or (ax is None): self.fig,self.ax = plt.subplots() else: self.fig = fig self.ax = ax x,y = np.meshgrid(np.arange(0,self.data.shape[2],pixel_step),np.arange(0,self.data.shape[1],pixel_step)) #Translate shear components into sines and cosines cos_2_phi = self.data[0] / np.sqrt(self.data[0]**2 + self.data[1]**2) sin_2_phi = self.data[1] / np.sqrt(self.data[0]**2 + self.data[1]**2) #Compute stick directions cos_phi = np.sqrt(0.5*(1.0 + cos_2_phi)) * np.sign(sin_2_phi) sin_phi = np.sqrt(0.5*(1.0 - cos_2_phi)) #Fix ambiguity when sin_2_phi = 0 cos_phi[sin_2_phi==0] = np.sqrt(0.5*(1.0 + cos_2_phi[sin_2_phi==0])) #Draw map using matplotlib quiver self.ax.quiver((x+0.5)*self.side_angle.value/self.data.shape[2],(y+0.5)*self.side_angle.value/self.data.shape[1],cos_phi[y,x],sin_phi[y,x],headwidth=0,units="height",scale=x.shape[0]/multiplier) #Axes labels self.ax.set_xlabel(r"$x$({0})".format(self.side_angle.unit.to_string())) self.ax.set_ylabel(r"$y$({0})".format(self.side_angle.unit.to_string())) def fourierEB(self): """ Computes E and B modes of the shear map in Fourier space :returns: (E,B) map :rtype: tuple. """ #Perform Fourier transforms ft_data1 = fftengine.rfft2(self.data[0]) ft_data2 = fftengine.rfft2(self.data[1]) #Compute frequencies lx = fftengine.rfftfreq(ft_data1.shape[0]) ly = fftengine.fftfreq(ft_data1.shape[0]) #Safety check assert len(lx)==ft_data1.shape[1] assert len(ly)==ft_data1.shape[0] #Compute sines and cosines of rotation angles l_squared = lx[np.newaxis,:]**2 + ly[:,np.newaxis]**2 l_squared[0,0] = 1.0 sin_2_phi = 2.0 * lx[np.newaxis,:] * ly[:,np.newaxis] / l_squared cos_2_phi = (lx[np.newaxis,:]**2 - ly[:,np.newaxis]**2) / l_squared #Compute E and B components ft_E = cos_2_phi * ft_data1 + sin_2_phi * ft_data2 ft_B = -1.0 * sin_2_phi * ft_data1 + cos_2_phi * ft_data2 ft_E[0,0] = 0.0 ft_B[0,0] = 0.0 assert ft_E.shape == ft_B.shape assert ft_E.shape == ft_data1.shape #Return return ft_E,ft_B def eb_power_spectrum(self,l_edges,scale=None): """ Decomposes the shear map into its E and B modes components and returns the respective power spectral densities at the specified multipole moments :param l_edges: Multipole bin edges :type l_edges: array :param scale: scaling to apply to the Fourier coefficients before harmonic azimuthal averaging. Must be a function that takes the array of multipole magnitudes as an input and returns a real numbers :type scale: callable :returns: (l -- array,P_EE,P_BB,P_EB -- arrays) = (multipole moments, EE,BB power spectra and EB cross power) :rtype: tuple. >>> test_map = ShearMap.load("shear.fit",format=load_fits_default_shear) >>> l_edges = np.arange(300.0,5000.0,200.0) >>> l,EE,BB,EB = test_map.eb_power_spectrum(l_edges) """ #Compute the E,B modes in Fourier space ft_E,ft_B = self.fourierEB() #Scaling of Fourier
file for a custom model is limited to 10 MB. * Use a *parallel corpus* when you want your custom model to learn from general translation patterns in parallel sentences in your samples. What your model learns from a parallel corpus can improve translation results for input text that the model has not been trained on. You can upload multiple parallel corpora files with a request. To successfully train with parallel corpora, the corpora files must contain a cumulative total of at least 5000 parallel sentences. The cumulative size of all uploaded corpus files for a custom model is limited to 250 MB. Depending on the type of customization and the size of the uploaded files, training time can range from minutes for a glossary to several hours for a large parallel corpus. To create a model that is customized with a parallel corpus and a forced glossary, customize the model with a parallel corpus first and then customize the resulting model with a forced glossary. You can create a maximum of 10 custom models per language pair. For more information about customizing a translation model, including the formatting and character restrictions for data files, see [Customizing your model](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing). #### Supported file formats You can provide your training data for customization in the following document formats: * **TMX** (`.tmx`) - Translation Memory eXchange (TMX) is an XML specification for the exchange of translation memories. * **XLIFF** (`.xliff`) - XML Localization Interchange File Format (XLIFF) is an XML specification for the exchange of translation memories. * **CSV** (`.csv`) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code. * **TSV** (`.tsv` or `.tab`) - Tab-separated values (TSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code. * **JSON** (`.json`) - Custom JSON format for specifying aligned sentences and phrases. * **Microsoft Excel** (`.xls` or `.xlsx`) - Excel file with the first two columns for aligned sentences and phrases. The first row contains the language code. You must encode all text data in UTF-8 format. For more information, see [Supported document formats for training data](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing#supported-document-formats-for-training-data). #### Specifying file formats You can indicate the format of a file by including the file extension with the file name. Use the file extensions shown in **Supported file formats**. Alternatively, you can omit the file extension and specify one of the following `content-type` specifications for the file: * **TMX** - `application/x-tmx+xml` * **XLIFF** - `application/xliff+xml` * **CSV** - `text/csv` * **TSV** - `text/tab-separated-values` * **JSON** - `application/json` * **Microsoft Excel** - `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` For example, with `curl`, use the following `content-type` specification to indicate the format of a CSV file named **glossary**: `--form "forced_glossary=@glossary;type=text/csv"`. :param str base_model_id: The ID of the translation model to use as the base for customization. To see available models and IDs, use the `List models` method. Most models that are provided with the service are customizable. In addition, all models that you create with parallel corpora customization can be further customized with a forced glossary. :param BinaryIO forced_glossary: (optional) A file with forced glossary terms for the source and target languages. The customizations in the file completely overwrite the domain translation data, including high frequency or high confidence phrase translations. You can upload only one glossary file for a custom model, and the glossary can have a maximum size of 10 MB. A forced glossary must contain single words or short phrases. For more information, see **Supported file formats** in the method description. *With `curl`, use `--form forced_glossary=@{filename}`.*. :param BinaryIO parallel_corpus: (optional) A file with parallel sentences for the source and target languages. You can upload multiple parallel corpus files in one request by repeating the parameter. All uploaded parallel corpus files combined must contain at least 5000 parallel sentences to train successfully. You can provide a maximum of 500,000 parallel sentences across all corpora. A single entry in a corpus file can contain a maximum of 80 words. All corpora files for a custom model can have a cumulative maximum size of 250 MB. For more information, see **Supported file formats** in the method description. *With `curl`, use `--form parallel_corpus=@{filename}`.*. :param str name: (optional) An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces, and apostrophes. The maximum length of the name is 32 characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object """ if base_model_id is None: raise ValueError('base_model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='create_model') headers.update(sdk_headers) params = { 'version': self.version, 'base_model_id': base_model_id, 'name': name } form_data = [] if forced_glossary: form_data.append(('forced_glossary', (None, forced_glossary, 'application/octet-stream'))) if parallel_corpus: form_data.append(('parallel_corpus', (None, parallel_corpus, 'application/octet-stream'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers['Accept'] = 'application/json' url = '/v3/models' request = self.prepare_request(method='POST', url=url, headers=headers, params=params, files=form_data) response = self.send(request) return response def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: """ Delete model. Deletes a custom translation model. :param str model_id: Model ID of the model to delete. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `DeleteModelResult` object """ if model_id is None: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='delete_model') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers['Accept'] = 'application/json' path_param_keys = ['model_id'] path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v3/models/{model_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, params=params) response = self.send(request) return response def get_model(self, model_id: str, **kwargs) -> DetailedResponse: """ Get model details. Gets information about a translation model, including training status for custom models. Use this API call to poll the status of your customization request. A successfully completed training has a status of `available`. :param str model_id: Model ID of the model to get. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object """ if model_id is None: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='get_model') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers['Accept'] = 'application/json' path_param_keys = ['model_id'] path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v3/models/{model_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, params=params) response = self.send(request) return response ######################### # Document translation ######################### def list_documents(self, **kwargs) -> DetailedResponse: """ List documents. Lists documents that have been submitted for translation. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `DocumentList` object """ headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='list_documents') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers['Accept'] = 'application/json' url = '/v3/documents' request = self.prepare_request(method='GET', url=url, headers=headers, params=params) response = self.send(request) return response def translate_document(self, file: BinaryIO, *, filename: str = None, file_content_type: str = None, model_id: str = None, source: str = None, target: str = None, document_id: str = None, **kwargs) -> DetailedResponse: """ Translate document. Submit a document for translation. You can submit the document contents in the `file` parameter, or you can reference a previously submitted document by document ID. The maximum file size for document translation is * 20 MB for service instances on the Standard, Advanced, and
import logging import copy import re import avi.migrationtools.f5_converter.converter_constants as conv_const from avi.migrationtools.f5_converter.conversion_util import F5Util from avi.migrationtools.avi_migration_utils import update_count LOG = logging.getLogger(__name__) # Creating f5 object for util library. conv_utils = F5Util() class PoolConfigConv(object): @classmethod def get_instance(cls, version, f5_pool_attributes, prefix): """ :param version: f5 version :param f5_pool_attributes: location of yaml file for supported attributes :param prefix: prefix for objects :return: """ if version == '10': return PoolConfigConvV10(f5_pool_attributes, prefix) if version in ['11', '12']: return PoolConfigConvV11(f5_pool_attributes, prefix) def convert_pool(self, pool_name, f5_config, avi_config, user_ignore, tenant_ref, cloud_ref, merge_object_mapping, sys_dict, vrf=None, segroup=None): pass def convert(self, f5_config, avi_config, user_ignore, tenant_ref, cloud_name, merge_object_mapping, sys_dict, vrf=None, segroup=None): """ :param f5_config: parsed f5 config dict :param avi_config: dict for avi conversion :param user_ignore: Ignore config defined by user :param tenant_ref: tenant for which config need to be converted :param cloud_name: cloud for which config need to be converted :param merge_object_mapping: flag for merge object :param sys_dict: baseline profile dict :return: """ pool_list = [] pool_config = f5_config.get('pool', {}) user_ignore = user_ignore.get('pool', {}) avi_config['VrfContext'] = [] avi_config['PoolGroup'] = [] avi_config['PriorityLabels'] = {} # Initialize Global vrf context object vrf_context = { "name": 'global', "system_default": True, "tenant_ref": conv_utils.get_object_ref('admin', 'tenant'), "cloud_ref": conv_utils.get_object_ref(cloud_name, 'cloud'), "static_routes": [] } avi_config['VrfContext'].append(vrf_context) total_size = len(pool_config.keys()) # Added variable to get total object count. progressbar_count = 0 print "Converting Pools..." for pool_name in pool_config.keys(): progressbar_count += 1 LOG.debug("Converting Pool: %s" % pool_name) f5_pool = pool_config[pool_name] if not f5_pool: msg = "Empty pool skipped for conversion :%s" % pool_name LOG.debug(msg) conv_utils.add_status_row('pool', None, pool_name, conv_const.STATUS_SKIPPED, msg) continue if 'gateway-failsafe-device' in f5_pool: msg = ("Not supported gateway-failsafe-device, pool skipped " "for conversion :%s" % pool_name) LOG.debug(msg) conv_utils.add_status_row('pool', None, pool_name, conv_const.STATUS_SKIPPED, msg) continue try: converted_objs = self.convert_pool( pool_name, f5_config, avi_config, user_ignore, tenant_ref, cloud_name, merge_object_mapping, sys_dict, vrf, segroup) pool_list += converted_objs['pools'] if 'pg_obj' in converted_objs: avi_config['PoolGroup'].extend(converted_objs['pg_obj']) LOG.debug("Conversion successful for Pool: %s" % pool_name) except: update_count('error') LOG.error("Failed to convert pool: %s" % pool_name, exc_info=True) conv_utils.add_status_row('pool', None, pool_name, conv_const.STATUS_ERROR) # Added call to check progress. msg = "Pool and PoolGroup conversion started..." conv_utils.print_progress_bar(progressbar_count, total_size, msg, prefix='Progress', suffix='') avi_config['Pool'] = pool_list LOG.debug("Converted %s pools" % len(pool_list)) f5_config.pop('pool', {}) def get_monitor_refs(self, monitor_names, monitor_config_list, pool_name, tenant_ref, merge_object_mapping, sys_mon): """ :param monitor_names: name of monitor :param monitor_config_list: parsed dict of monitor_config_list :param pool_name: name of pool :param tenant_ref: tenant which need to be converted :param merge_object_mapping: flag for object merge :param sys_mon: baseline profile dict :return: """ skipped_monitors = [] monitors = monitor_names.split(" ") monitor_refs = [] garbage_val = ["and", "all", "min", "of", "{", "}", "none"] for monitor in monitors: monitor = monitor.strip() if not monitor or monitor in garbage_val or \ monitor.isdigit(): continue if self.prefix: monitor = '%s-%s' % (self.prefix, monitor) tenant, monitor = conv_utils.get_tenant_ref(monitor) monitor_obj = [ob for ob in sys_mon if ob['name'] == merge_object_mapping['health_monitor'].get(monitor)] \ or [obj for obj in monitor_config_list if ( obj["name"] == monitor or monitor in obj.get("dup_of", []))] if monitor_obj: tenant = conv_utils.get_name( monitor_obj[0]['tenant_ref']) monitor_refs.append(conv_utils.get_object_ref(monitor_obj[0]['name'], 'healthmonitor', tenant=tenant)) else: LOG.warning("Monitor not found: %s for pool %s" % (monitor, pool_name)) skipped_monitors.append(monitor) return skipped_monitors, monitor_refs def create_pool_object(self, name, desc, servers, pd_action, algo, ramp_time, limits, tenant_ref, cloud_ref): """ :param name: name of pool :param desc: description of pool :param servers: servers list in pool :param pd_action: action on avi pool :param algo: algorithm used for pool :param tenant_ref: tenant of which output to be converted :param cloud_ref: cloud of which output to be converted :return: pool_obj """ tenant, name = conv_utils.get_tenant_ref(name) # Added prefix for objects if self.prefix: name = self.prefix + '-' + name pool_obj = { 'name': name, 'description': desc, 'servers': servers, 'fail_action': pd_action, 'lb_algorithm': algo, 'cloud_ref': conv_utils.get_object_ref(cloud_ref, 'cloud') } if not tenant_ref == 'admin': tenant = tenant_ref pool_obj['tenant_ref'] = conv_utils.get_object_ref(tenant, 'tenant') if ramp_time: pool_obj['connection_ramp_duration'] = ramp_time if limits.get('connection_limit', 0) > 0: pool_obj['max_concurrent_connections_per_server'] = \ limits['connection_limit'] if limits.get('rate_limit', 0) > 0: pool_obj['max_conn_rate_per_server'] = { 'count': limits['rate_limit'] } return pool_obj def check_for_pool_group(self, servers): """ Check if the priority group for the server exist :param servers: List of servers to check server priority :return: if priority exist returns true and priority wise dict of servers """ is_pool_group = False for server in servers: if 'priority' in server: is_pool_group = True break if not is_pool_group: return is_pool_group, None pg_dict = dict() for server in servers: priority = server.get('priority', None) if not priority: is_pool_group = False break else: del server['priority'] priority_list = pg_dict.get(priority, []) priority_list.append(server) pg_dict[priority] = priority_list return is_pool_group, pg_dict def add_status(self, name, skipped_attr, member_skipped, skipped_monitors, converted_objs, user_ignore, skipped_servers): skipped = [] conv_status = dict() conv_status['user_ignore'] = [] if skipped_attr: p_ignore = user_ignore.get('pool', []) conv_status['user_ignore'] = [val for val in skipped_attr if val in p_ignore] skipped_attr = [attr for attr in skipped_attr if attr not in p_ignore] if skipped_attr: skipped.append(skipped_attr) if member_skipped: m_ignore = user_ignore.get('members', []) if m_ignore: ms_new = [] um_list = [] for obj in member_skipped: um_skipped = dict() um_skipped[obj.keys()[0]] = \ [val for val in obj[obj.keys()[0]] if val in m_ignore] temp = [val for val in obj[obj.keys()[0]] if val not in m_ignore] if um_skipped[um_skipped.keys()[0]]: um_list.append(um_skipped) if temp: ms_new.append({obj.keys()[0]: temp}) conv_status['user_ignore'].append(um_list) if ms_new: skipped.append(ms_new) else: skipped.append(member_skipped) if skipped_monitors and not user_ignore.get('monitor', None): skipped.append({"monitor": skipped_monitors}) if skipped_servers: skipped.append({"server": skipped_servers}) conv_status['skipped'] = skipped status = conv_const.STATUS_SUCCESSFUL if skipped: status = conv_const.STATUS_PARTIAL conv_status['status'] = status conv_utils.add_conv_status('pool', None, name, conv_status, converted_objs) def convert_for_pg(self, pg_dict, pool_obj, name, tenant, avi_config, cloud_ref): """ Creates a pool group object :param pg_dict: priority wise sorted dict of pools :param pool_obj: Converted f5 pool object :param name: name of the pool :param tenant: tenant name for tenant reference :param avi_config: Avi config to add temporary labels :return: """ pg_members = [] pools = [] for priority in pg_dict: priority_pool = copy.deepcopy(pool_obj) priority_pool['servers'] = pg_dict[priority] priority_pool_ref = '%s-%s' % (name, priority) # Added prefix for objects if self.prefix: priority_pool_ref = self.prefix + '-' + priority_pool_ref priority_pool['name'] = priority_pool_ref pools.append(priority_pool) if priority_pool_ref: member = { 'pool_ref': conv_utils.get_object_ref( priority_pool_ref, 'pool', tenant=tenant, cloud_name=cloud_ref), 'priority_label': priority } pg_members.append(member) # Added prefix for objects if self.prefix: name = self.prefix + "-" + name pg_obj = { 'name': name, 'members': pg_members, 'cloud_ref': conv_utils.get_object_ref(cloud_ref, 'cloud') } pg_obj['tenant_ref'] = conv_utils.get_object_ref(tenant, 'tenant') converted_objs = { 'pools': pools, 'pg_obj': [pg_obj] } return converted_objs class PoolConfigConvV11(PoolConfigConv): def __init__(self, f5_pool_attributes, prefix): """ :param f5_pool_attributes: f5 pool attributes from yaml file :param prefix: prefix for objects """ self.supported_attr = f5_pool_attributes['Pool_supported_attr'] self.supported_attributes = f5_pool_attributes[ 'Pool_supported_attr_convert_servers_config'] self.ignore_for_val = f5_pool_attributes['Pool_ignore_val'] # Added prefix for objects self.prefix = prefix def convert_pool(self, pool_name, f5_config, avi_config, user_ignore, tenant_ref, cloud_ref, merge_object_mapping, sys_dict, vrf=None, segroup=None): """ :param pool_name: name of the pool :param f5_config: parsed f5 config dict :param avi_config: dict for avi conversion :param user_ignore: Ignore config defined by user :param tenant_ref: tenant of which output to converted :param cloud_ref: cloud of which output to converted :param merge_object_mapping: flag for merge object :param sys_dict: baseline dict :return: """ converted_objs = {} nodes = f5_config.get("node", {}) f5_pool = f5_config['pool'][pool_name] monitor_config = avi_config['HealthMonitor'] servers, member_skipped_config, limits, skipped_servers = \ self.convert_servers_config(f5_pool.get("members", {}), nodes, avi_config, cloud_ref) sd_action = f5_pool.get("service-down-action", "") pd_action = conv_utils.get_avi_pool_down_action(sd_action) lb_method = f5_pool.get("load-balancing-mode", None) lb_algorithm = self.get_avi_lb_algorithm(lb_method) desc = f5_pool.get('description', None) ramp_time = f5_pool.get('slow-ramp-time', None) pool_obj = super(PoolConfigConvV11, self).create_pool_object( pool_name, desc, servers, pd_action, lb_algorithm, ramp_time, limits, tenant_ref, cloud_ref) # if length of servers > 400 take only 400 servers status_flag = False if len(servers) > 400: servers = servers[0:400] status_flag = True tenant, name = conv_utils.get_tenant_ref(pool_name) tenant_name = tenant if not tenant_ref == 'admin': tenant = tenant_ref num_retries = f5_pool.get('reselect-tries', None) if num_retries: server_reselect = { "retry_nonidempotent": False, "svr_resp_code": { "resp_code_block": ["HTTP_RSP_4XX", "HTTP_RSP_5XX"] }, "num_retries": num_retries, "enabled": True } pool_obj['server_reselect'] = server_reselect monitor_names = f5_pool.get("monitor", None) skipped_monitors = [] if monitor_names: skipped_monitors, monitor_refs = super( PoolConfigConvV11, self).get_monitor_refs( monitor_names, monitor_config, pool_name, tenant, merge_object_mapping, sys_dict['HealthMonitor']) pool_obj["health_monitor_refs"] = list(set(monitor_refs)) # Adding vrf context ref to pool obj vrf_config = avi_config['VrfContext'] members = f5_pool.get('members') address = (isinstance(members, dict) and members.get(members.keys()[ 0]) and isinstance(members[members.keys()[0]], dict)) and \ members[members.keys()[0]].get('address') or isinstance( members, str) and members.split(' ')[0] or None if members \ else None if
<filename>lib/rucio/tests/temp_factories.py # -*- coding: utf-8 -*- # Copyright 2021-2022 CERN # # 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. # # Authors: # - <NAME> <<EMAIL>>, 2021-2022 # - <NAME> <<EMAIL>>, 2021 # - <NAME> <<EMAIL>>, 2021 # - <NAME> <<EMAIL>>, 2021 import os import shutil import tempfile from itertools import chain from pathlib import Path from random import choice from string import ascii_uppercase from rucio.client.client import Client from rucio.client.uploadclient import UploadClient from rucio.common.types import InternalScope from rucio.common.utils import execute, generate_uuid from rucio.core import replica as replica_core from rucio.core import rse as rse_core from rucio.core import rule as rule_core from rucio.db.sqla import models from rucio.db.sqla.constants import DIDType from rucio.db.sqla.session import transactional_session from rucio.tests.common import file_generator, rse_name_generator from six import PY3 from sqlalchemy import and_, or_ class TemporaryRSEFactory: """ Factory which keeps track of created RSEs and cleans up everything related to these RSEs at the end """ def __init__(self, vo, **kwargs): self.vo = vo self.created_rses = [] def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.cleanup() def cleanup(self): if not self.created_rses: return rules_to_remove = self.__get_rules_to_remove() self.__cleanup_transfers() self.__cleanup_locks_and_rules(rules_to_remove) self.__cleanup_replicas() self.__cleanup_rse_attributes() @transactional_session def __get_rules_to_remove(self, session=None): # Retrieve the list of rules to be cleaned up rules_from_requests = session.query(models.ReplicationRule.id). \ join(models.Request, models.ReplicationRule.id == models.Request.rule_id). \ filter(or_(models.Request.dest_rse_id.in_(self.created_rses), models.Request.source_rse_id.in_(self.created_rses))) rules_from_locks = session.query(models.ReplicationRule.id). \ join(models.ReplicaLock, models.ReplicationRule.id == models.ReplicaLock.rule_id). \ filter(models.ReplicaLock.rse_id.in_(self.created_rses)) return list(rules_from_requests.union(rules_from_locks).distinct()) @transactional_session def __cleanup_transfers(self, session=None): # Cleanup Transfers session.query(models.Source).filter(or_(models.Source.dest_rse_id.in_(self.created_rses), models.Source.rse_id.in_(self.created_rses))).delete(synchronize_session=False) requests = list(chain.from_iterable( session.query(models.Request.id).filter(or_(models.Request.dest_rse_id.in_(self.created_rses), models.Request.source_rse_id.in_(self.created_rses))).distinct() )) session.query(models.TransferHop).filter(or_(models.TransferHop.request_id.in_(requests), models.TransferHop.initial_request_id.in_(requests)) ).delete(synchronize_session=False) session.query(models.Request).filter(or_(models.Request.dest_rse_id.in_(self.created_rses), models.Request.source_rse_id.in_(self.created_rses))).delete(synchronize_session=False) @transactional_session def __cleanup_locks_and_rules(self, rules_to_remove, session=None): for rule_id, in rules_to_remove: rule_core.delete_rule(rule_id, session=session, ignore_rule_lock=True) @transactional_session def __cleanup_replicas(self, session=None): # Cleanup Replicas and Parent Datasets query = session.query(models.RSEFileAssociation.scope, models.RSEFileAssociation.name, models.RSEFileAssociation.rse_id). \ filter(models.RSEFileAssociation.rse_id.in_(self.created_rses)) dids_by_rse = {} for scope, name, rse_id in query: dids_by_rse.setdefault(rse_id, []).append({'scope': scope, 'name': name}) for rse_id, dids in dids_by_rse.items(): replica_core.delete_replicas(rse_id=rse_id, files=dids, session=session) # Cleanup BadReplicas session.query(models.BadReplicas).filter(models.BadReplicas.rse_id.in_(self.created_rses)).delete(synchronize_session=False) @transactional_session def __cleanup_rse_attributes(self, session=None): for model in (models.RSEAttrAssociation, models.RSEProtocols, models.UpdatedRSECounter, models.RSEUsage, models.RSELimit, models.RSETransferLimit, models.RSEQoSAssociation): session.query(model).filter(model.rse_id.in_(self.created_rses)).delete(synchronize_session=False) session.query(models.Distance).filter(or_(models.Distance.src_rse_id.in_(self.created_rses), models.Distance.dest_rse_id.in_(self.created_rses))).delete(synchronize_session=False) def __cleanup_rses(self): for rse_id in self.created_rses: # Only archive RSE instead of deleting. Account handling code doesn't expect RSEs to ever be deleted. # So running test in parallel results in some tests failing on foreign key errors. rse_core.del_rse(rse_id) def _make_rse(self, scheme, protocol_impl, parameters=None, add_rse_kwargs=None): rse_name = rse_name_generator() if add_rse_kwargs and 'vo' in add_rse_kwargs: rse_id = rse_core.add_rse(rse_name, **add_rse_kwargs) else: rse_id = rse_core.add_rse(rse_name, vo=self.vo, **(add_rse_kwargs or {})) if scheme and protocol_impl: protocol_parameters = { 'scheme': scheme, 'hostname': '%s.cern.ch' % rse_id, 'port': 0, 'prefix': '/test/', 'impl': protocol_impl, 'domains': { 'wan': { 'read': 1, 'write': 1, 'delete': 1, 'third_party_copy': 1 } } } protocol_parameters.update(parameters or {}) rse_core.add_protocol(rse_id=rse_id, parameter=protocol_parameters) self.created_rses.append(rse_id) return rse_name, rse_id def make_rse(self, scheme=None, protocol_impl=None, **kwargs): return self._make_rse(scheme=scheme, protocol_impl=protocol_impl, add_rse_kwargs=kwargs) def make_posix_rse(self, **kwargs): return self._make_rse(scheme='file', protocol_impl='rucio.rse.protocols.posix.Default', add_rse_kwargs=kwargs) def make_mock_rse(self, **kwargs): return self._make_rse(scheme='MOCK', protocol_impl='rucio.rse.protocols.mock.Default', add_rse_kwargs=kwargs) def make_xroot_rse(self, **kwargs): return self._make_rse(scheme='root', protocol_impl='rucio.rse.protocols.xrootd.Default', add_rse_kwargs=kwargs) def make_srm_rse(self, **kwargs): parameters = { "extended_attributes": {"web_service_path": "/srm/managerv2?SFN=", "space_token": "<PASSWORD>"}, } return self._make_rse(scheme='srm', protocol_impl='rucio.rse.protocols.srm.Default', parameters=parameters, add_rse_kwargs=kwargs) class TemporaryDidFactory: """ Factory which keeps track of created dids and cleans up everything related to these dids at the end. All files related to the same test will have the same uuid in the name for easier debugging. """ def __init__(self, default_scope, vo): self.default_scope = default_scope self.vo = vo self.base_uuid = generate_uuid() self._client = None self._upload_client = None self.created_dids = [] def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.cleanup() @property def client(self): if not self._client: self._client = Client(vo=self.vo) return self._client @property def upload_client(self): if not self._upload_client: self._upload_client = UploadClient(self.client) return self._upload_client def cleanup(self): if not self.created_dids: return self.__cleanup_transfers() self.__cleanup_locks_and_rules() self.__cleanup_replicas() @transactional_session def __cleanup_transfers(self, session=None): # Cleanup Transfers session.query(models.Source).filter(or_(and_(models.Source.scope == did['scope'], models.Source.name == did['name']) for did in self.created_dids)).delete(synchronize_session=False) requests = list(chain.from_iterable( session.query(models.Request.id).filter(or_(and_(models.Request.scope == did['scope'], models.Request.name == did['name']) for did in self.created_dids)).distinct() )) session.query(models.TransferHop).filter(or_(models.TransferHop.request_id.in_(requests), models.TransferHop.initial_request_id.in_(requests)) ).delete(synchronize_session=False) session.query(models.Request).filter(or_(and_(models.Request.scope == did['scope'], models.Request.name == did['name']) for did in self.created_dids)).delete(synchronize_session=False) @transactional_session def __cleanup_locks_and_rules(self, session=None): query = session.query(models.ReplicationRule.id).filter(or_(and_(models.ReplicationRule.scope == did['scope'], models.ReplicationRule.name == did['name']) for did in self.created_dids)) for rule_id, in query: rule_core.delete_rule(rule_id, session=session, ignore_rule_lock=True) @transactional_session def __cleanup_replicas(self, session=None): query = session.query(models.RSEFileAssociation.scope, models.RSEFileAssociation.name, models.RSEFileAssociation.rse_id). \ filter(or_(and_(models.RSEFileAssociation.scope == did['scope'], models.RSEFileAssociation.name == did['name']) for did in self.created_dids)) dids_by_rse = {} for scope, name, rse_id in query: dids_by_rse.setdefault(rse_id, []).append({'scope': scope, 'name': name}) for rse_id, dids in dids_by_rse.items(): replica_core.delete_replicas(rse_id=rse_id, files=dids, session=session) # Cleanup BadReplicas session.query(models.BadReplicas).filter(or_(and_(models.BadReplicas.scope == did['scope'], models.BadReplicas.name == did['name']) for did in self.created_dids)).delete(synchronize_session=False) def register_dids(self, dids): """ Register the provided dids to be cleaned up on teardown """ self.created_dids.extend(dids) def _sanitize_or_set_scope(self, scope): if not scope: scope = self.default_scope elif isinstance(scope, str): scope = InternalScope(scope, vo=self.vo) return scope def _random_did(self, scope, name_prefix, name_suffix=''): scope = self._sanitize_or_set_scope(scope) if not name_prefix: name_prefix = 'lfn' name = '%s_%s_%s%s' % (name_prefix, self.base_uuid, len(self.created_dids), name_suffix) did = {'scope': scope, 'name': name} self.created_dids.append(did) return did def random_did(self, scope=None, name_prefix=None, name_suffix=''): did = self._random_did(scope=scope, name_prefix=name_prefix, name_suffix=name_suffix) return did def make_dataset(self, scope=None): did = self._random_did(scope=scope, name_prefix='dataset') self.client.add_did(scope=did['scope'].external, name=did['name'], did_type=DIDType.DATASET) return did def make_container(self, scope=None): did = self._random_did(scope=scope, name_prefix='container') self.client.add_container(scope=did['scope'].external, name=did['name']) return did def upload_test_file(self, rse_name, scope=None, name=None, path=None, size=2, return_full_item=False): scope = self._sanitize_or_set_scope(scope) if not path: path = file_generator(size=size) if not name: name = os.path.basename(path) item = { 'path': path, 'rse': rse_name, 'did_scope': str(scope), 'did_name': name, 'guid': generate_uuid(), } self.upload_client.upload([item]) did = {'scope': scope, 'name': name} self.created_dids.append(did) return item if return_full_item else did def upload_test_dataset(self, rse_name, scope=None, size=2, nb_files=2): scope = self._sanitize_or_set_scope(scope) dataset = self.make_dataset(scope=scope) did = {'scope': scope, 'name': dataset['name']} self.created_dids.append(did) items = list() for _ in range(0, nb_files): path = file_generator(size=size) name = os.path.basename(path) items.append({ 'path': path, 'rse': rse_name, 'dataset_scope': str(scope), 'dataset_name': dataset['name'], 'did_scope': str(scope), 'did_name': name, 'guid': generate_uuid(), }) did = {'scope': scope, 'name': name} self.created_dids.append(did) self.upload_client.upload(items) return items class TemporaryFileFactory: """ Factory which keeps track of creation and cleanup of created local test files and directories. If initialized with tmp_path_factory fixture, the basedir is managed by pytest. Otherwise, the basedir is handled by this factory itself. """ def __init__(self, pytest_path_factory=None) -> None: self.pytest_path_factory = pytest_path_factory self.base_uuid = generate_uuid() self._base_dir = None self.non_basedir_files = [] def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if self.pytest_path_factory is None: shutil.rmtree(self.base_dir) self.cleanup() @property def base_dir(self): if not self._base_dir: if self.pytest_path_factory is not None: self._base_dir = self.pytest_path_factory.mktemp(basename=self.base_uuid, numbered=True) else: tmp_dir = tempfile.mkdtemp(prefix=self.base_uuid) self._base_dir = Path(tmp_dir) return self._base_dir def _make_temp_file(self, data, size, namelen, use_basedir, path): fn = ''.join(choice(ascii_uppercase) for x in range(namelen)) if use_basedir: fp = self.base_dir / path / fn if path is not None else self.base_dir / fn else: fp = Path(tempfile.gettempdir()) / path / fn if path is not None else Path(tempfile.gettempdir()) / fn self.non_basedir_files.append(fp) if data is not None: if PY3: with open(fp, 'w', encoding='utf-8') as f: f.write(data) else: with open(fp, 'w') as f: f.write(data) else: execute('dd if=/dev/urandom of={0} count={1} bs=1'.format(fp, size)) return fp def _make_temp_folder(self, namelen, use_basedir, path): fn = ''.join(choice(ascii_uppercase) for x in range(namelen)) if use_basedir: fp = self.base_dir / path / fn if path is not None else self.base_dir / fn else: fp = Path(tempfile.gettempdir()) / path / fn if path is not None else Path(tempfile.gettempdir()) / fn self.non_basedir_files.append(fp) os.makedirs(fp, exist_ok=True) return fp def file_generator(self, data=None, size=2, namelen=10, use_basedir=False, path=None): """ Creates a temporary file :param data : The content to be written in the file. If provided, the size parameter is ignored. :param size : The size of random bytes to be written in the file :param namelen : The length of filename :param use_basedir : If True, the file is created under the base_dir for this TemporaryFileFactory instance. :param path : Relative path of the file, can be under basedir (if use_basedir True) or from the temp dir :returns: The absolute path of the generated file """ return self._make_temp_file(data, size, namelen, use_basedir, path) def folder_generator(self, namelen=10, use_basedir=False, path=None): """ Creates an empty temporary folder :param namelen
"sgn-CH-DE" regular = "art-lojban" ; these tags match the 'langtag' / "cel-gaulish" ; production, but their subtags / "no-bok" ; are not extended language / "no-nyn" ; or variant subtags: their meaning / "zh-guoyu" ; is defined by their registration / "zh-hakka" ; and all of these are deprecated / "zh-min" ; in favor of a more modern / "zh-min-nan" ; subtag or sequence of subtags / "zh-xiang" alphanum = (ALPHA / DIGIT) ; letters and numbers ------------- Most tests use examples from https://tools.ietf.org/search/bcp47 and https://github.com/unicode-org/cldr/blob/main/tools/cldr-code /src/main/resources/org/unicode/cldr/util/data/langtagTest.txt Exemplōrum gratiā (et Python doctest, id est, testum automata): (run with python3 -m doctest myscript.py) >>> bcp47_langtag('pt-Latn-BR', 'language') 'pt' >>> bcp47_langtag('pt-Latn-BR', 'script') 'Latn' >>> bcp47_langtag('pt-Latn-BR', 'region') 'BR' >>> bcp47_langtag('de-CH-1996', 'variant') ['1996'] >>> bcp47_langtag('x-fr-CH', ['language', 'region', 'privateuse']) {'language': None, 'region': None, 'privateuse': ['fr', 'CH']} >>> bcp47_langtag('i-klingon', 'grandfathered') 'i-klingon' >>> bcp47_langtag('zh-min-nan', 'language') 'zh' >>> bcp47_langtag('zh-min-nan', 'variant') ['min-nan'] >>> bcp47_langtag('es-419', 'region') '419' >>> bcp47_langtag('en-oxendict', 'variant') # Oxford English Dictionary ['oxendict'] >>> bcp47_langtag('zh-pinyin', 'variant') # Pinyin romanization ['pinyin'] >>> bcp47_langtag('zh-pinyin', 'script') # Limitation: cannot infer Latn >>> bcp47_langtag('en-a-bbb-x-a-ccc', 'privateuse') ['a', 'ccc'] >>> bcp47_langtag('en-a-bbb-x-a-ccc', 'extension') {'a': 'bbb'} >>> bcp47_langtag('tlh-a-b-foo', '_error') Traceback (most recent call last): ... ValueError: Errors for [tlh-a-b-foo]: extension [a] empty >>> bcp47_langtag('tlh-a-b-foo', '_error', False) ['extension [a] empty'] >>> bcp47_langtag( ... 'zh-Latn-CN-variant1-a-extend1-x-wadegile-private1', ... ['variant', 'extension', 'privateuse']) {'variant': ['variant1'], 'extension': {'a': 'extend1'}, \ 'privateuse': ['wadegile', 'private1']} >>> bcp47_langtag( ... 'en-Latn-US-lojban-gaulish-a-12345678-ABCD-b-ABCDEFGH-x-a-b-c-12345678') {'Language-Tag': \ 'en-Latn-US-lojban-gaulish-a-12345678-ABCD-b-ABCDEFGH-x-a-b-c-12345678', \ 'Language-Tag_normalized': \ 'en-Latn-US-lojban-gaulish-a-12345678-ABCD-b-ABCDEFGH-x-a-b-c-12345678', \ 'language': 'en', 'script': 'Latn', 'region': 'US', \ 'variant': ['lojban', 'gaulish'], \ 'extension': {'a': '12345678-ABCD', 'b': 'ABCDEFGH'}, \ 'privateuse': ['a', 'b', 'c', '12345678'], \ 'grandfathered': None, '_unknown': [], '_error': []} # BCP47: "Example: The language tag "en-a-aaa-b-ccc-bbb-x-xyz" is in # canonical form, while "en-b-ccc-bbb-a-aaa-X-xyz" is well-formed (...) >>> bcp47_langtag( ... 'en-b-ccc-bbb-a-aaa-X-xyz') {'Language-Tag': 'en-b-ccc-bbb-a-aaa-X-xyz', \ 'Language-Tag_normalized': 'en-a-aaa-b-ccc-bbb-x-xyz', \ 'language': 'en', 'script': None, 'region': None, 'variant': [], \ 'extension': {'a': 'aaa', 'b': 'ccc-bbb'}, 'privateuse': ['xyz'], \ 'grandfathered': None, '_unknown': [], '_error': []} """ # For sake of copy-and-paste portability, we ignore a few pylints: # pylint: disable=too-many-branches,too-many-statements,too-many-locals result = { # The input Language-Tag, _as it is_ 'Language-Tag': rem, # The Language-Tag normalized syntax, if no errors 'Language-Tag_normalized': None, 'language': None, 'script': None, 'region': None, 'variant': [], 'extension': {}, # Example {'a': ['bbb', 'ccc'], 'd': True} 'privateuse': [], # Example: ['wadegile', 'private1'] 'grandfathered': None, '_unknown': [], '_error': [], } skip = 0 if not isinstance(rem, str) or len(rem) == 0: result['_error'].append('Empty/wrong type') skip = 1 else: rem = rem.replace('_', '-').strip() # The weird tags first: grandfathered/irregular if rem in [ 'en-GB-oed', 'i-ami', 'i-bnn', 'i-default', 'i-enochian', 'i-hak', 'i-klingon', 'i-lux', 'i-ming', 'i-navajo', 'i-pwn', 'i-tao', 'i-tay', 'i-tsu', 'sgn-BE-FR', 'sgn-BE-NL', 'sgn-CH-DE']: # result['langtag'] = None result['language'] = rem.lower() result['grandfathered'] = rem skip = 1 # The weird tags first: grandfathered/regular if rem in [ 'art-lojban', 'cel-gaulish', 'no-bok', 'no-nyn', 'zh-guoyu', 'zh-hakka', 'zh-min', 'zh-min-nan', 'zh-xiang']: parts_r = rem.split('-') # result['langtag'] = None result['language'] = parts_r.pop(0).lower() result['variant'].append('-'.join(parts_r).lower()) result['grandfathered'] = rem skip = 1 parts = rem.split('-') leftover = [] deep = 0 while len(parts) > 0 and skip == 0 and deep < 100: deep = deep + 1 # BCP47 can start with private tag, without language at all if parts[0].lower() == 'x': parts.pop(0) while len(parts) > 0: result['privateuse'].append(parts.pop(0)) break # BCP47 extensions start with one US-ASCII letter. if len(parts[0]) == 1 and parts[0].isalpha(): if parts[0].isalpha() == 'i': result['_error'].append('Only grandfathered can use i-') extension_key = parts.pop(0).lower() if len(parts) == 0 or len(parts[0]) == 1: # BCP47 2.2.6. : "Each singleton MUST be followed by at least # one extension subtag (...) # result['extension'][extension_key] = [None] result['extension'][extension_key] = {} result['_error'].append( 'extension [' + extension_key + '] empty') continue result['extension'][extension_key] = '' while len(parts) > 0 and len(parts[0]) != 1: # Extensions may have more strict rules than -x- # @see https://datatracker.ietf.org/doc/html/rfc6497 (-t-) # @see https://datatracker.ietf.org/doc/html/rfc6067 (-u-) # Let's avoid atempt to lowercase extensions, since this is not # not explicity on BCP47 for unknow extensions # result['extension'][extension_key] = \ # result['extension'][extension_key] + \ # '-' + parts.pop(0).lower() result['extension'][extension_key] = \ result['extension'][extension_key] + \ '-' + parts.pop(0) result['extension'][extension_key] = \ result['extension'][extension_key].strip('-') continue # for part in parts: if result['language'] is None: if parts[0].isalnum() and len(parts[0]) == 2 or len(parts[0]) == 3: result['language'] = parts[0].lower() else: result['language'] = False result['_error'].append('language?') parts.pop(0) continue # Edge case to test for numeric in 4 (not 3): 'de-CH-1996' if len(parts[0]) == 4 and parts[0].isalpha() \ and result['script'] is None: # if parts[0].isalpha() and result['script'] is None: if parts[0].isalpha(): if result['region'] is None and len(result['privateuse']) == 0: result['script'] = parts[0].capitalize() else: result['script'] = False result['_error'].append('script after region/privateuse') else: result['script'] = False result['_error'].append('script?') parts.pop(0) continue # Regions, such as ISO 3661-1, like BR if len(parts[0]) == 2 and result['region'] is None: if parts[0].isalpha(): result['region'] = parts[0].upper() else: result['region'] = False result['_error'].append('region?') parts.pop(0) continue # Regions, such as ISO 3661-1, like 076 if len(parts[0]) == 3 and result['region'] is None: if parts[0].isnumeric(): result['region'] = parts.pop(0) else: result['region'] = False result['_error'].append('region?') parts.pop(0) continue if len(result['extension']) == 0 and len(result['privateuse']) == 0: # 2.2.5. Variant Subtags # 4.1 "Variant subtags that begin with a (US-ASCII)* letter # (a-z, A-Z) MUST be at least five characters long." # 4.2 "Variant subtags that begin with a digit (0-9) MUST be at # least four characters long." if parts[0][0].isalpha() and len(parts[0]) >= 5: result['variant'].append(parts.pop(0)) continue if parts[0][0].isnumeric() and len(parts[0]) >= 4: result['variant'].append(parts.pop(0)) continue leftover.append(parts.pop(0)) result['_unknown'] = leftover # @TODO: maybe re-implement only for know extensions, like -t-, -u-, -h- # if len(result['extension']) > 0: # extension_norm = {} # # keys # keys_sorted = sorted(result['extension']) # # values # for key in keys_sorted: # extension_norm[key] = sorted(result['extension'][key]) # result['extension'] = extension_norm # Language-Tag_normalized if len(result['_error']) == 0: if result['grandfathered']: result['Language-Tag_normalized'] = result['grandfathered'] else: norm = [] if result['language']: norm.append(result['language']) if result['script']: norm.append(result['script']) if result['region']: norm.append(result['region']) if len(result['variant']) > 0: norm.append('-'.join(result['variant'])) if len(result['extension']) > 0: # TODO: maybe re-implement only for know extensions, # like -t-, -u-, -h-. For now we're not trying to # normalize ordering of unknow future extensions, BUT # we sort key from different extensions sorted_extension = {} for key in sorted(result['extension']): sorted_extension[key] = result['extension'][key] result['extension'] = sorted_extension for key in result['extension']: if result['extension'][key][0] is None: norm.append(key) else: norm.append(key) # norm.extend(result['extension'][key]) norm.append(result['extension'][key]) if len(result['privateuse']) > 0: norm.append('x-' + '-'.join(result['privateuse'])) result['Language-Tag_normalized'] = '-'.join(norm) if strictum and len(result['_error']) > 0: raise ValueError( 'Errors for [' + rem + ']: ' + ', '.join(result['_error'])) if clavem is not None: if isinstance(clavem, str): return result[clavem] if isinstance(clavem, list): result_partial = {} for item in clavem: result_partial[item] = result[item] return result_partial raise TypeError( 'clavem [' + str(type(clavem)) + '] != [str, list]') return result def numerordinatio_neo_separatum( numerordinatio: str, separatum: str = "_") -> str: resultatum = '' resultatum = numerordinatio.replace('_', separatum) resultatum = resultatum.replace('/', separatum) resultatum = resultatum.replace(':', separatum) # TODO: add more as need return resultatum def numerordinatio_ordo(numerordinatio: str) -> int: normale = numerordinatio_neo_separatum(numerordinatio, '_') return (normale.count('_') + 1) def numerordinatio_progenitori( numerordinatio: str, separatum: str = "_") -> int: # prōgenitōrī, s, m, dativus, https://en.wiktionary.org/wiki/progenitor normale = numerordinatio_neo_separatum(numerordinatio, separatum) _parts = normale.split(separatum) _parts = _parts[:-1] if len(_parts) == 0: return "0" return separatum.join(_parts) def numerordinatio_lineam_hxml5_details(rem: dict, title: str = None) -> str: # codex = rem['#item+conceptum+codicem'] title = title if title else rem['#item+conceptum+codicem'] resultatum = '<details><summary>🔎' + \ title + '🔍</summary>' + "\n" resultatum += ' <dl>' + "\n" for clavem, item in rem.items(): if item: resultatum += ' <dt>' + clavem + '</dt>' + "\n" resultatum += ' <dd>' + item + '</dd>' + "\n" # print(item) resultatum += ' </dl>' + "\n" resultatum += '</details>' + "\n" return resultatum def numerordinatio_summary(rem: dict, title: str = None) -> str: # codex = rem['#item+conceptum+codicem'] # TODO: maybe remove this? # title = title if title else rem['#item+conceptum+codicem'] resultatum = [] # status_definitionem = qhxl(rem, '#status+conceptum+definitionem') # if status_definitionem: # resultatum.append( # "<progress value='{0}' max='100' title='definitionem: " # "{0}/100'>{0}/100</progress>".format( # status_definitionem)) # status_codicem = qhxl(rem, '#status+conceptum+codicem') # if status_codicem: # resultatum.append( # "<progress
options = dict( verbose=True, model_extensions=[ 'h2o.model.extensions.ScoringHistoryTrees', 'h2o.model.extensions.VariableImportance', 'h2o.model.extensions.FeatureInteraction', 'h2o.model.extensions.Trees', 'h2o.model.extensions.HStatistic', ], ) def update_param(name, param): if name == 'distribution': param['values'].remove('ordinal') return param return None # param untouched doc = dict( __class__=""" Builds gradient boosted trees on a parsed data set, for regression or classification. The default distribution function will guess the model type based on the response column type. Otherwise, the response column must be an enum for "bernoulli" or "multinomial", and numeric for all other distributions. """ ) examples = dict( training_frame=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> train, valid = cars.split_frame(ratios=[.8], seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.auc(valid=True) """, validation_frame=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> train, valid = cars.split_frame(ratios=[.8], seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.auc(valid=True) """, nfolds=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> folds = 5 >>> cars_gbm = H2OGradientBoostingEstimator(nfolds=folds, ... seed=1234 >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=cars) >>> cars_gbm.auc() """, keep_cross_validation_models=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> folds = 5 >>> train, valid = cars.split_frame(ratios=[.8], seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(keep_cross_validation_models=True, ... nfolds=5, ... seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.auc() """, keep_cross_validation_predictions=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> folds = 5 >>> train, valid = cars.split_frame(ratios=[.8], seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(keep_cross_validation_predictions=True, ... nfolds=5, ... seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.auc() """, keep_cross_validation_fold_assignment=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> folds = 5 >>> train, valid = cars.split_frame(ratios=[.8], seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(keep_cross_validation_fold_assignment=True, ... nfolds=5, ... seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.auc() """, score_each_iteration=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> train, valid = cars.split_frame(ratios=[.8], ... seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(score_each_iteration=True, ... ntrees=55, ... seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.scoring_history() """, score_tree_interval=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> train, valid = cars.split_frame(ratios=[.8], ... seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(score_tree_interval=True, ... ntrees=55, ... seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.scoring_history() """, fold_assignment=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> assignment_type = "Random" >>> cars_gbm = H2OGradientBoostingEstimator(fold_assignment=assignment_type, ... nfolds=5, ... seed=1234) >>> cars_gbm.train(x=predictors, y=response, training_frame=cars) >>> cars_gbm.auc(xval=True) """, fold_column=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> fold_numbers = cars.kfold_column(n_folds=5, ... seed=1234) >>> fold_numbers.set_names(["fold_numbers"]) >>> cars = cars.cbind(fold_numbers) >>> cars_gbm = H2OGradientBoostingEstimator(seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=cars, ... fold_column="fold_numbers") >>> cars_gbm.auc(xval=True) """, ignore_const_cols=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> cars["const_1"] = 6 >>> cars["const_2"] = 7 >>> train, valid = cars.split_frame(ratios=[.8], seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(seed=1234, ... ignore_const_cols=True) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.auc(valid=True) """, offset_column=""" >>> boston = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/gbm_test/BostonHousing.csv") >>> predictors = boston.columns[:-1] >>> response = "medv" >>> boston['chas'] = boston['chas'].asfactor() >>> boston["offset"] = boston["medv"].log() >>> train, valid = boston.split_frame(ratios=[.8], seed=1234) >>> boston_gbm = H2OGradientBoostingEstimator(offset_column="offset", ... seed=1234) >>> boston_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> boston_gbm.mse(valid=True) """, weights_column=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> train, valid = cars.split_frame(ratios=[.8], seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid, ... weights_column="weight") >>> cars_gbm.auc(valid=True) """, balance_classes=""" >>> covtype = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/covtype/covtype.20k.data") >>> covtype[54] = covtype[54].asfactor() >>> predictors = covtype.columns[0:54] >>> response = 'C55' >>> train, valid = covtype.split_frame(ratios=[.8], seed=1234) >>> cov_gbm = H2OGradientBoostingEstimator(balance_classes=True, ... seed=1234) >>> cov_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cov_gbm.logloss(valid=True) """, class_sampling_factors=""" >>> covtype = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/covtype/covtype.20k.data") >>> covtype[54] = covtype[54].asfactor() >>> predictors = covtype.columns[0:54] >>> response = 'C55' >>> train, valid = covtype.split_frame(ratios=[.8], seed=1234) >>> sample_factors = [1., 0.5, 1., 1., 1., 1., 1.] >>> cov_gbm = H2OGradientBoostingEstimator(balance_classes=True, ... class_sampling_factors=sample_factors, ... seed=1234) >>> cov_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cov_gbm.logloss(valid=True) """, max_after_balance_size=""" >>> covtype = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/covtype/covtype.20k.data") >>> covtype[54] = covtype[54].asfactor() >>> predictors = covtype.columns[0:54] >>> response = 'C55' >>> train, valid = covtype.split_frame(ratios=[.8], seed=1234) >>> max = .85 >>> cov_gbm = H2OGradientBoostingEstimator(balance_classes=True, ... max_after_balance_size=max, ... seed=1234) >>> cov_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cov_gbm.logloss(valid=True) """, ntrees=""" >>> titanic = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/gbm_test/titanic.csv") >>> titanic['survived'] = titanic['survived'].asfactor() >>> predictors = titanic.columns >>> del predictors[1:3] >>> response = 'survived' >>> train, valid = titanic.split_frame(ratios=[.8], seed=1234) >>> tree_num = [20, 50, 80, 110, 140, 170, 200] >>> label = ["20", "50", "80", "110", "140", "170", "200"] >>> for key, num in enumerate(tree_num): ... titanic_gbm = H2OGradientBoostingEstimator(ntrees=num, ... seed=1234) ... titanic_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) ... print(label[key], 'training score', titanic_gbm.auc(train=True)) ... print(label[key], 'validation score', titanic_gbm.auc(valid=True)) """, max_depth=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> train, valid = cars.split_frame(ratios=[.8], seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(ntrees=100, ... max_depth=2, ... seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.auc(valid=True) """, min_rows=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> train, valid = cars.split_frame(ratios=[.8], seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(min_rows=16, ... seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.auc(valid=True) """, nbins=""" >>> eeg = h2o.import_file("https://h2o-public-test-data.s3.amazonaws.com/smalldata/eeg/eeg_eyestate.csv") >>> eeg['eyeDetection'] = eeg['eyeDetection'].asfactor() >>> predictors = eeg.columns[:-1] >>> response = 'eyeDetection' >>> train, valid = eeg.split_frame(ratios=[.8], seed=1234) >>> bin_num = [16, 32, 64, 128, 256, 512] >>> label = ["16", "32", "64", "128", "256", "512"] >>> for key, num in enumerate(bin_num): ... eeg_gbm = H2OGradientBoostingEstimator(nbins=num, seed=1234) ... eeg_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) ... print(label[key], 'training score', eeg_gbm.auc(train=True)) ... print(label[key], 'validation score', eeg_gbm.auc(valid=True)) """, nbins_top_level=""" >>> eeg = h2o.import_file("https://h2o-public-test-data.s3.amazonaws.com/smalldata/eeg/eeg_eyestate.csv") >>> eeg['eyeDetection'] = eeg['eyeDetection'].asfactor() >>> predictors = eeg.columns[:-1] >>> response = 'eyeDetection' >>> train, valid = eeg.split_frame(ratios=[.8], seed=1234) >>> bin_num = [32, 64, 128, 256, 512, 1024, 2048, 4096] >>> label = ["32", "64", "128", "256", "512", "1024", "2048", "4096"] >>> for key, num in enumerate(bin_num): ... eeg_gbm = H2OGradientBoostingEstimator(nbins_top_level=num, seed=1234) ... eeg_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) ... print(label[key], 'training score', eeg_gbm.auc(train=True)) ... print(label[key], 'validation score', eeg_gbm.auc(valid=True)) """, nbins_cats=""" >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip") >>> airlines["Year"] = airlines["Year"].asfactor() >>> airlines["Month"] = airlines["Month"].asfactor() >>> airlines["DayOfWeek"] = airlines["DayOfWeek"].asfactor() >>> airlines["Cancelled"] = airlines["Cancelled"].asfactor() >>> airlines['FlightNum'] = airlines['FlightNum'].asfactor() >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier", ... "DayOfWeek", "Month", "Distance", "FlightNum"] >>> response = "IsDepDelayed" >>> train, valid = airlines.split_frame(ratios=[.8], seed=1234) >>> bin_num = [8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096] >>> label = ["8", "16", "32", "64", "128", "256", "512", "1024", "2048", "4096"] >>> for key, num in enumerate(bin_num): ... airlines_gbm = H2OGradientBoostingEstimator(nbins_cats=num, seed=1234) ... airlines_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) ... print(label[key], 'training score', airlines_gbm.auc(train=True)) ... print(label[key], 'validation score', airlines_gbm.auc(valid=True)) """, stopping_rounds=""" >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip") >>> airlines["Year"] = airlines["Year"].asfactor() >>> airlines["Month"] = airlines["Month"].asfactor() >>> airlines["DayOfWeek"] = airlines["DayOfWeek"].asfactor() >>> airlines["Cancelled"] = airlines["Cancelled"].asfactor() >>> airlines['FlightNum'] = airlines['FlightNum'].asfactor() >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier", ... "DayOfWeek", "Month", "Distance", "FlightNum"] >>> response = "IsDepDelayed" >>> train, valid = airlines.split_frame(ratios=[.8], seed=1234) >>> airlines_gbm = H2OGradientBoostingEstimator(stopping_metric="auc", ... stopping_rounds=3, ... stopping_tolerance=1e-2, ... seed=1234) >>> airlines_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> airlines_gbm.auc(valid=True) """, stopping_metric=""" >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip") >>> airlines["Year"] = airlines["Year"].asfactor() >>> airlines["Month"] = airlines["Month"].asfactor() >>> airlines["DayOfWeek"] = airlines["DayOfWeek"].asfactor() >>> airlines["Cancelled"] = airlines["Cancelled"].asfactor() >>> airlines['FlightNum'] = airlines['FlightNum'].asfactor() >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier", ... "DayOfWeek", "Month", "Distance", "FlightNum"] >>> response = "IsDepDelayed" >>> train, valid = airlines.split_frame(ratios=[.8], seed=1234) >>> airlines_gbm = H2OGradientBoostingEstimator(stopping_metric="auc", ... stopping_rounds=3, ... stopping_tolerance=1e-2, ... seed=1234) >>> airlines_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> airlines_gbm.auc(valid=True) """, stopping_tolerance=""" >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip") >>> airlines["Year"] = airlines["Year"].asfactor() >>> airlines["Month"] = airlines["Month"].asfactor() >>> airlines["DayOfWeek"] = airlines["DayOfWeek"].asfactor() >>> airlines["Cancelled"] = airlines["Cancelled"].asfactor() >>> airlines['FlightNum'] = airlines['FlightNum'].asfactor() >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier", ... "DayOfWeek", "Month", "Distance", "FlightNum"] >>> response = "IsDepDelayed" >>> train, valid= airlines.split_frame(ratios=[.8], seed=1234) >>> airlines_gbm = H2OGradientBoostingEstimator(stopping_metric="auc", ... stopping_rounds=3, ... stopping_tolerance=1e-2, ... seed=1234) >>> airlines_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> airlines_gbm.auc(valid=True) """, max_runtime_secs=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> train, valid = cars.split_frame(ratios=[.8], seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(max_runtime_secs=10, ... ntrees=10000, ... max_depth=10, ... seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.auc(valid=True) """, seed=""" >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip") >>> airlines["Year"] = airlines["Year"].asfactor() >>> airlines["Month"] = airlines["Month"].asfactor() >>> airlines["DayOfWeek"] = airlines["DayOfWeek"].asfactor() >>> airlines["Cancelled"] = airlines["Cancelled"].asfactor() >>> airlines['FlightNum'] = airlines['FlightNum'].asfactor() >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier", ... "DayOfWeek", "Month", "Distance", "FlightNum"] >>> response = "IsDepDelayed" >>> train, valid = airlines.split_frame(ratios=[.8], seed=1234) >>> gbm_w_seed_1 = H2OGradientBoostingEstimator(col_sample_rate=.7, ... seed=1234) >>> gbm_w_seed_1.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> print('auc for the 1st model built with a seed:', gbm_w_seed_1.auc(valid=True)) """, build_tree_one_node=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"] = cars["economy_20mpg"].asfactor() >>> predictors = ["displacement","power","weight","acceleration","year"] >>> response = "economy_20mpg" >>> train, valid = cars.split_frame(ratios=[.8], seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(build_tree_one_node=True, ... seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.auc(valid=True) """, learn_rate=""" >>> titanic = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/gbm_test/titanic.csv") >>> titanic['survived'] = titanic['survived'].asfactor() >>> predictors = titanic.columns >>> del predictors[1:3] >>> response = 'survived' >>> train, valid = titanic.split_frame(ratios=[.8], seed=1234) >>> titanic_gbm = H2OGradientBoostingEstimator(ntrees=10000, ... learn_rate=0.01, ... stopping_rounds=5, ... stopping_metric="AUC", ... stopping_tolerance=1e-4, ... seed=1234) >>> titanic_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> titanic_gbm.auc(valid=True) """, learn_rate_annealing=""" >>> titanic = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/gbm_test/titanic.csv") >>> titanic['survived'] = titanic['survived'].asfactor() >>> predictors = titanic.columns >>> del predictors[1:3] >>> response = 'survived' >>> train, valid = titanic.split_frame(ratios=[.8], seed=1234) >>> titanic_gbm = H2OGradientBoostingEstimator(ntrees=10000, ... learn_rate=0.05, ... learn_rate_annealing=.9, ... stopping_rounds=5, ... stopping_metric="AUC", ... stopping_tolerance=1e-4, ... seed=1234) >>> titanic_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> titanic_gbm.auc(valid=True) """, distribution=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> response = "cylinders" >>> train, valid = cars.split_frame(ratios=[.8], seed=1234) >>> cars_gbm = H2OGradientBoostingEstimator(distribution="poisson", ... seed=1234) >>> cars_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> cars_gbm.mse(valid=True) """, quantile_alpha=""" >>> boston = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/gbm_test/BostonHousing.csv") >>> predictors = boston.columns[:-1] >>> response = "medv" >>> boston['chas'] = boston['chas'].asfactor() >>> train, valid = boston.split_frame(ratios=[.8], seed=1234) >>> boston_gbm = H2OGradientBoostingEstimator(distribution="quantile", ... quantile_alpha=.8, ... seed=1234) >>> boston_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> boston_gbm.mse(valid=True) """, tweedie_power=""" >>> insurance = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/glm_test/insurance.csv") >>> predictors = insurance.columns[0:4] >>> response = 'Claims' >>> insurance['Group'] = insurance['Group'].asfactor() >>> insurance['Age'] = insurance['Age'].asfactor() >>> train, valid = insurance.split_frame(ratios=[.8], seed=1234) >>> insurance_gbm = H2OGradientBoostingEstimator(distribution="tweedie", ... tweedie_power=1.2, ... seed=1234) >>> insurance_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> insurance_gbm.mse(valid=True) """, huber_alpha=""" >>> insurance = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/glm_test/insurance.csv") >>> predictors = insurance.columns[0:4] >>> response = 'Claims' >>> insurance['Group'] = insurance['Group'].asfactor() >>> insurance['Age'] = insurance['Age'].asfactor() >>> train, valid = insurance.split_frame(ratios=[.8], seed=1234) >>> insurance_gbm = H2OGradientBoostingEstimator(distribution="huber", ... huber_alpha=0.9, ... seed=1234) >>> insurance_gbm.train(x=predictors, ... y=response, ... training_frame=train, ... validation_frame=valid) >>> insurance_gbm.mse(valid=True) """, checkpoint=""" >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv") >>> cars["economy_20mpg"]
= self.elements["_eteam"] if len(myteam.get_active_members(camp)) < 1: self.obj.win(camp, 100) class BAM_DefeatTheBandits(Plot): LABEL = BAMO_DEFEAT_THE_BANDITS active = True scope = "LOCALE" def custom_init(self, nart): myscene = self.elements["LOCALE"] myfac = self.elements.get("ENEMY_FACTION") roomtype = self.elements["ARCHITECTURE"].get_a_room() self.register_element("ROOM", roomtype(15, 15, anchor=pbge.randmaps.anchors.middle), dident="LOCALE") team2 = self.register_element("_eteam", teams.Team(enemies=(myscene.player_team,)), dident="ROOM") if myfac: mynpc = self.seek_element(nart, "_commander", self._npc_is_good, must_find=False, lock=True) else: mynpc = None if mynpc: unit_size = 120 if mynpc.renown > self.rank: unit_size = max(unit_size + self.rank - mynpc.renown, 50) plotutility.CharacterMover(self, mynpc, myscene, team2) myunit = gears.selector.RandomMechaUnit(self.rank, unit_size, myfac, myscene.environment, add_commander=False) else: myunit = gears.selector.RandomMechaUnit(self.rank, 150, myfac, myscene.environment, add_commander=True) self.register_element("_commander", myunit.commander) team2.contents += myunit.mecha_list self.obj = adventureseed.MissionObjective("Defeat the bandits".format(myfac), MAIN_OBJECTIVE_VALUE) self.adv.objectives.append(self.obj) self.intro_ready = True return True def _npc_is_good(self, nart, candidate): return isinstance(candidate, gears.base.Character) and candidate.combatant and candidate.faction == \ self.elements["ENEMY_FACTION"] and candidate not in nart.camp.party def _eteam_ACTIVATETEAM(self, camp): if self.intro_ready: npc = self.elements["_commander"] ghdialogue.start_conversation(camp, camp.pc, npc, cue=ghdialogue.ATTACK_STARTER) self.intro_ready = False def _commander_offers(self, camp): mylist = list() mylist.append(Offer("[CHALLENGE]", context=ContextTag([context.CHALLENGE, ]))) return mylist def t_ENDCOMBAT(self, camp): myteam = self.elements["_eteam"] if len(myteam.get_active_members(camp)) < 1: self.obj.win(camp, 100) class BAM_DefeatTheBandits_NoCommander(Plot): LABEL = BAMO_DEFEAT_THE_BANDITS active = True scope = "LOCALE" def custom_init(self, nart): myscene = self.elements["LOCALE"] myfac = self.elements.get("ENEMY_FACTION") roomtype = self.elements["ARCHITECTURE"].get_a_room() self.register_element("ROOM", roomtype(15, 15, anchor=pbge.randmaps.anchors.middle), dident="LOCALE") team2 = self.register_element("_eteam", teams.Team(enemies=(myscene.player_team,)), dident="ROOM") myunit = gears.selector.RandomMechaUnit(self.rank, 150, myfac, myscene.environment, add_commander=False) team2.contents += myunit.mecha_list self.obj = adventureseed.MissionObjective("Defeat the bandits".format(myfac), MAIN_OBJECTIVE_VALUE) self.adv.objectives.append(self.obj) self.intro_ready = True return True def t_ENDCOMBAT(self, camp): myteam = self.elements["_eteam"] if len(myteam.get_active_members(camp)) < 1: self.obj.win(camp, 100) class BAM_DestroyArtillery(Plot): LABEL = BAMO_DESTROY_ARTILLERY active = True scope = "LOCALE" def custom_init(self, nart): myscene = self.elements["LOCALE"] myfac = self.elements.get("ENEMY_FACTION") roomtype = self.elements["ARCHITECTURE"].get_a_room() self.register_element("ROOM", roomtype(15, 15, anchor=pbge.randmaps.anchors.middle), dident="LOCALE") team2 = self.register_element("_eteam", teams.Team(enemies=(myscene.player_team,)), dident="ROOM") mynpc = self.seek_element(nart, "_commander", self._npc_is_good, must_find=False, lock=True) if mynpc: plotutility.CharacterMover(self, mynpc, myscene, team2) myunit = gears.selector.RandomMechaUnit(self.rank, 70, myfac, myscene.environment, add_commander=False) else: myunit = gears.selector.RandomMechaUnit(self.rank, 100, myfac, myscene.environment, add_commander=True) self.register_element("_commander", myunit.commander) team2.contents += myunit.mecha_list myfac = self.elements.get("ENEMY_FACTION") if myfac: colors = myfac.mecha_colors else: colors = gears.color.random_mecha_colors() for t in range(random.randint(1, 2) + max(self.rank // 20, 0)): team2.contents.append(gears.selector.get_design_by_full_name("HAL-82 Artillery")) team2.contents[-1].colors = colors self.obj = adventureseed.MissionObjective("Destroy enemy artillery", MAIN_OBJECTIVE_VALUE * 2) self.adv.objectives.append(self.obj) self.intro_ready = True return True def _npc_is_good(self, nart, candidate): return isinstance(candidate, gears.base.Character) and candidate.combatant and candidate.faction == \ self.elements["ENEMY_FACTION"] and candidate not in nart.camp.party def _eteam_ACTIVATETEAM(self, camp): if self.intro_ready: npc = self.elements["_commander"] ghdialogue.start_conversation(camp, camp.pc, npc, cue=ghdialogue.ATTACK_STARTER) self.intro_ready = False def _commander_offers(self, camp): mylist = list() mylist.append(Offer("[CHALLENGE]", context=ContextTag([context.CHALLENGE, ]))) return mylist def t_ENDCOMBAT(self, camp): myteam = self.elements["_eteam"] if len(myteam.get_active_members(camp)) < 1: self.obj.win(camp, 100) class BAM_ExtractAllies(Plot): LABEL = BAMO_EXTRACT_ALLIED_FORCES active = True scope = "LOCALE" def custom_init(self, nart): myscene = self.elements["LOCALE"] roomtype = self.elements["ARCHITECTURE"].get_a_room() myroom = self.register_element("ROOM", roomtype(10, 10), dident="LOCALE") team2 = self.register_element("_eteam", teams.Team(enemies=(myscene.player_team,)), dident="ROOM") team3 = self.register_element("_ateam", teams.Team(enemies=(team2,), allies=(myscene.player_team,)), dident="ROOM") myunit = gears.selector.RandomMechaUnit(self.rank, 200, self.elements.get("ENEMY_FACTION"), myscene.environment, add_commander=False) team2.contents += myunit.mecha_list mynpc = self.seek_element(nart, "PILOT", self._npc_is_good, must_find=False, lock=True) if mynpc: plotutility.CharacterMover(self, mynpc, myscene, team3) mek = mynpc.get_root() self.register_element("SURVIVOR", mek) else: mysurvivor = self.register_element("SURVIVOR", gears.selector.generate_ace(self.rank, self.elements.get( "ALLIED_FACTION"), myscene.environment)) self.register_element("PILOT", mysurvivor.get_pilot()) team3.contents.append(mysurvivor) self.obj = adventureseed.MissionObjective("Extract allied pilot {}".format(self.elements["PILOT"]), MAIN_OBJECTIVE_VALUE, can_reset=False) self.adv.objectives.append(self.obj) self.intro_ready = True self.eteam_activated = False self.eteam_defeated = False self.pilot_fled = False return True def _npc_is_good(self, nart, candidate): return isinstance(candidate, gears.base.Character) and candidate.combatant and candidate.faction == \ self.elements["ALLIED_FACTION"] and candidate not in nart.camp.party def _eteam_ACTIVATETEAM(self, camp): if self.intro_ready: self.eteam_activated = True if not self.pilot_fled: npc = self.elements["PILOT"] ghdialogue.start_conversation(camp, camp.pc, npc, cue=ghdialogue.HELLO_STARTER) camp.fight.active.append(self.elements["SURVIVOR"]) self.intro_ready = False def PILOT_offers(self, camp): mylist = list() if self.eteam_defeated: mylist.append(Offer("[THANKS_FOR_MECHA_COMBAT_HELP] I better get back to base.", dead_end=True, context=ContextTag([ghdialogue.context.HELLO, ]), effect=self.pilot_leaves_combat)) else: myoffer = Offer("[HELP_ME_VS_MECHA_COMBAT]", dead_end=True, context=ContextTag([ghdialogue.context.HELLO, ])) if not self.eteam_activated: myoffer.replies.append(Reply("Get out of here, I can handle this.", destination=Offer("[THANK_YOU] I need to get back to base.", effect=self.pilot_leaves_before_combat, dead_end=True))) mylist.append(myoffer) return mylist def pilot_leaves_before_combat(self, camp): self.obj.win(camp, 105) self.pilot_leaves_combat(camp) def pilot_leaves_combat(self, camp): if not self.pilot_fled: npc = self.elements["PILOT"] npc.relationship.reaction_mod += 10 camp.scene.contents.remove(self.elements["SURVIVOR"]) self.pilot_fled = True def t_ENDCOMBAT(self, camp): if self.eteam_activated and not self.pilot_fled: myteam = self.elements["_ateam"] eteam = self.elements["_eteam"] if len(myteam.get_active_members(camp)) < 1: self.obj.failed = True elif len(myteam.get_active_members(camp)) > 0 and len(eteam.get_active_members(camp)) < 1: self.eteam_defeated = True self.obj.win(camp, 100 - self.elements["SURVIVOR"].get_percent_damage_over_health()) npc = self.elements["PILOT"] ghdialogue.start_conversation(camp, camp.pc, npc, cue=ghdialogue.HELLO_STARTER) class BAM_LocateEnemyForces(Plot): LABEL = BAMO_LOCATE_ENEMY_FORCES active = True scope = "LOCALE" def custom_init(self, nart): myscene = self.elements["LOCALE"] myfac = self.elements.get("ENEMY_FACTION") roomtype = self.elements["ARCHITECTURE"].get_a_room() self.register_element("ROOM", roomtype(15, 15), dident="LOCALE") self.register_element("DUD_ROOM", pbge.randmaps.rooms.FuzzyRoom(5, 5), dident="LOCALE") team2 = self.register_element("_eteam", teams.Team(enemies=(myscene.player_team,)), dident="ROOM") myunit = gears.selector.RandomMechaUnit(self.rank, 100, myfac, myscene.environment, add_commander=True) team2.contents += myunit.mecha_list self.register_element("_commander", myunit.commander) if myfac: self.obj = adventureseed.MissionObjective("Locate {} forces".format(myfac), MAIN_OBJECTIVE_VALUE) else: self.obj = adventureseed.MissionObjective("Locate enemy forces", MAIN_OBJECTIVE_VALUE) self.adv.objectives.append(self.obj) self.intro_ready = True return True def _eteam_ACTIVATETEAM(self, camp): if self.intro_ready: npc = self.elements["_commander"] ghdialogue.start_conversation(camp, camp.pc, npc, cue=ghdialogue.ATTACK_STARTER) self.intro_ready = False def _commander_offers(self, camp): mylist = list() mylist.append(Offer("[CHALLENGE]", context=ContextTag([context.CHALLENGE, ]))) return mylist def t_ENDCOMBAT(self, camp): myteam = self.elements["_eteam"] if len(myteam.get_active_members(camp)) < 1: self.obj.win(camp, 100) class BAM_NeutralizeAllDrones(Plot): LABEL = BAMO_NEUTRALIZE_ALL_DRONES active = True scope = "LOCALE" def custom_init(self, nart): myscene = self.elements["LOCALE"] myfac = self.elements.get("ENEMY_FACTION") if myfac: colors = myfac.mecha_colors else: colors = gears.color.random_mecha_colors() roomtype = self.elements["ARCHITECTURE"].get_a_room() self.register_element("ROOM", roomtype(8, 8), dident="LOCALE") team2 = self.register_element("_eteam", teams.Team(enemies=(myscene.player_team,)), dident="ROOM") for t in range(random.randint(3, 4)): mydrone = gears.selector.get_design_by_full_name("DZD-01 Sentry Drone") mydrone.colors = colors team2.contents.append(mydrone) self.obj = adventureseed.MissionObjective("Neutralize all security drones".format(myfac), MAIN_OBJECTIVE_VALUE) self.adv.objectives.append(self.obj) return True def t_ENDCOMBAT(self, camp): myteam = self.elements["_eteam"] if len(myteam.get_active_members(camp)) < 1: self.obj.win(camp, 100) class BAM_RecoverCargo(Plot): LABEL = BAMO_RECOVER_CARGO active = True scope = "LOCALE" def custom_init(self, nart): myscene = self.elements["LOCALE"] roomtype = self.elements["ARCHITECTURE"].get_a_room() myroom = self.register_element("ROOM", roomtype(10, 10), dident="LOCALE") team2 = self.register_element("_eteam", teams.Team(enemies=(myscene.player_team,)), dident="ROOM") myunit = gears.selector.RandomMechaUnit(self.rank, 100, self.elements.get("ENEMY_FACTION"), myscene.environment, add_commander=True) team2.contents += myunit.mecha_list team3 = self.register_element("_cargoteam", teams.Team(), dident="ROOM") team3.contents += game.content.plotutility.CargoContainer.generate_cargo_fleet(self.rank) # Oh yeah, when using PyCharm, why not use ludicrously long variable names? self.starting_number_of_containers = len(team3.contents) self.obj = adventureseed.MissionObjective("Recover missing cargo", MAIN_OBJECTIVE_VALUE) self.adv.objectives.append(self.obj) self.combat_entered = False self.combat_finished = False return True def _eteam_ACTIVATETEAM(self, camp): if not self.combat_entered: self.combat_entered = True def t_ENDCOMBAT(self, camp): myteam = self.elements["_eteam"] cargoteam = self.elements["_cargoteam"] if len(cargoteam.get_active_members(camp)) < 1: self.obj.failed = True elif len(myteam.get_active_members(camp)) < 1: self.obj.win(camp, (sum([(100 - c.get_percent_damage_over_health()) for c in cargoteam.get_active_members(camp)])) // self.starting_number_of_containers) if not self.combat_finished: pbge.alert("The missing cargo has been secured.") self.combat_finished = True class BAM_RespondToDistressCall(Plot): LABEL = BAMO_RESPOND_TO_DISTRESS_CALL active = True scope = "LOCALE" def custom_init(self, nart): myscene = self.elements["LOCALE"] roomtype = self.elements["ARCHITECTURE"].get_a_room() myroom = self.register_element("ROOM", roomtype(10, 10), dident="LOCALE") team2 = self.register_element("_eteam", teams.Team(enemies=(myscene.player_team,)), dident="ROOM") myunit = gears.selector.RandomMechaUnit(self.rank, 120, self.elements.get("ENEMY_FACTION"), myscene.environment, add_commander=False) team2.contents += myunit.mecha_list team3 = self.register_element("_cargoteam", teams.Team(), dident="ROOM") team3.contents += game.content.plotutility.CargoContainer.generate_cargo_fleet(self.rank) # Oh yeah, when using PyCharm, why not use ludicrously long variable names? self.starting_number_of_containers = len(team3.contents) self.obj = adventureseed.MissionObjective("Respond to convoy distress call", MAIN_OBJECTIVE_VALUE) self.adv.objectives.append(self.obj) self.combat_entered = False self.combat_finished = False return True def _eteam_ACTIVATETEAM(self, camp): if not self.combat_entered: self.combat_entered = True def t_ENDCOMBAT(self, camp): myteam = self.elements["_eteam"] cargoteam = self.elements["_cargoteam"] if len(cargoteam.get_active_members(camp)) < 1: self.obj.failed = True elif len(myteam.get_active_members(camp)) < 1: self.obj.win(camp, (sum([(100 - c.get_percent_damage_over_health()) for c in cargoteam.get_active_members(camp)])) // self.starting_number_of_containers) if not self.combat_finished: pbge.alert("The missing cargo has been secured.") self.combat_finished = True class BAM_StormTheCastle(Plot): LABEL = BAMO_STORM_THE_CASTLE active = True scope = "LOCALE" def custom_init(self, nart): myscene = self.elements["LOCALE"] myfac = self.elements.get("ENEMY_FACTION") roomtype = self.elements["ARCHITECTURE"].get_a_room() self.register_element("ROOM", roomtype(10, 10), dident="LOCALE") team2 = self.register_element("_eteam", teams.Team(enemies=(myscene.player_team,)), dident="ROOM") myunit = gears.selector.RandomMechaUnit(self.rank, 150, myfac, myscene.environment, add_commander=True) team2.contents += myunit.mecha_list self.register_element("_commander", myunit.commander) self.starting_guards = len(team2.contents) myfort = self.register_element("_FORT", gears.selector.generate_fortification(self.rank, myfac, myscene.environment)) team2.contents.append(myfort) self.obj1 = adventureseed.MissionObjective("Destroy {} command center".format(myfac), MAIN_OBJECTIVE_VALUE * 3) self.adv.objectives.append(self.obj1) self.obj2 = adventureseed.MissionObjective("Defeat command center guards".format(myunit.commander), MAIN_OBJECTIVE_VALUE) self.adv.objectives.append(self.obj2) self.intro_ready = True return True def _eteam_ACTIVATETEAM(self, camp): if self.intro_ready: npc = self.elements["_commander"] ghdialogue.start_conversation(camp, camp.pc, npc, cue=ghdialogue.ATTACK_STARTER) self.intro_ready = False def _commander_offers(self, camp): mylist = list() mylist.append(Offer("[CHALLENGE]", context=ContextTag([context.CHALLENGE, ]))) return mylist def t_ENDCOMBAT(self, camp): myteam = self.elements["_eteam"] myboss = self.elements["_FORT"] myguards = [npc for npc in myteam.get_active_members(camp) if npc is not myboss] if len(myguards) < self.starting_guards: self.obj2.win(camp, 100 * (self.starting_guards - len(myguards)) // self.starting_guards) if not myboss.is_operational(): self.obj1.win(camp, 100) class BAM_SurviveTheAmbush(Plot): LABEL = BAMO_SURVIVE_THE_AMBUSH active = True scope = "LOCALE" def custom_init(self, nart): myscene = self.elements["LOCALE"] myfac = self.elements.get("ENEMY_FACTION") team2 = self.register_element("_eteam", teams.Team(enemies=(myscene.player_team,)), dident="ENTRANCE_ROOM") myunit = gears.selector.RandomMechaUnit(self.rank, 100, myfac, myscene.environment, add_commander=False) team2.contents += myunit.mecha_list self.obj = adventureseed.MissionObjective("Survive the ambush".format(myfac), MAIN_OBJECTIVE_VALUE) self.adv.objectives.append(self.obj) self.intro_ready = True return True def t_START(self, camp): if
<reponame>rajeevratan84/siamese_network_laser<filename>db.py import os import pandas as pd import numpy as np import matplotlib.pyplot as plt from os import listdir from pathlib import Path from os.path import isfile, join from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.model_selection import train_test_split from pyts.image import GramianAngularField import cv2 import random from io import BytesIO import base64 import matplotlib.pyplot as plt import glob from tensorflow.keras.models import load_model from tensorflow import keras from imutils.paths import list_images from sklearn import preprocessing from pathlib import Path first_x_colums = 360 first_col = pd.DataFrame(range(first_x_colums)) def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=None, normalize=True): """ A prettier confusion matrix """ import matplotlib.pyplot as plt import numpy as np import itertools img = BytesIO() accuracy = np.trace(cm) / np.sum(cm).astype('float') misclass = 1 - accuracy if cmap is None: cmap = plt.get_cmap('Blues') plt.figure(figsize=(12, 12)) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() if target_names is not None: tick_marks = np.arange(len(target_names)) plt.xticks(tick_marks, target_names, rotation=45) plt.yticks(tick_marks, target_names) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] thresh = cm.max() / 1.5 if normalize else cm.max() / 2 for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): if normalize: plt.text(j, i, "{:0.2f}".format(cm[i, j]), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") else: plt.text(j, i, "{:,}".format(cm[i, j]), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass)) #plt.show() plt.savefig(img, format='png') #plt.savefig('new_plot.png') plt.close() img.seek(0) plot_url = base64.b64encode(img.getvalue()).decode('utf8') return plot_url def processResults(df_summary_a): df_summary_a['Reading'] = df_summary_a['Ground Truth'].apply(lambda x: x.split('_')[0].split('/')[2]) print(df_summary_a) df_agg = df_summary_a.groupby(['Ground Truth', 'Compared With']).agg({'Similarity':sum}) print('df_agg') print(df_agg) g = df_agg['Similarity'].groupby('Ground Truth', group_keys=False) res = g.apply(lambda x: x.sort_values().head(3)) print('res') print(res) res = res.reset_index() res['Sample'] = res['Ground Truth'].apply(lambda x: x.split('/')[2].split('.')[0]) res['Prediction'] = res['Compared With'].apply(lambda x: x.split('/')[1].split('.')[0]) print('res2') print(res) #res = res[res['Similarity'] <= 0.3] res = res.groupby(['Sample', 'Prediction']).agg({'Similarity':'mean'}).reset_index().sort_values(by='Similarity') res['Sample'] = res['Sample'].apply(lambda x: x.split('_')[0]) res['Prediction'] = res['Prediction'].apply(lambda x: x.split('_')[0]) res = res.groupby(['Sample','Prediction']).mean().reset_index().sort_values(by = ['Sample','Similarity']) return res def processResultsC(df_summary_a): df_summary_a['Reading'] = df_summary_a['Sample'].apply(lambda x: x.split('_')[0]) #df_summary_a = df_summary_a[df_summary_a['Confidence'] >= 0.3] df_agg = df_summary_a.groupby(['Reading', 'Prediction']).agg({'Confidence':'mean'}).reset_index() df_agg = df_agg.sort_values(by = ['Reading','Confidence'], ascending=False) df_agg['Confidence'] = df_agg['Confidence'] * 100 df_agg['Confidence'] = df_agg['Confidence'].map('{:,.3f}%'.format) return df_agg def getPredictions(): args = { "input": "examples", "test": "image/train", "train": "images/train", "avg": "image_averaged" } print("[INFO] loading siamese model...") model = load_model('model/contrastive_siamese_model/', compile=False) ImagePathsTest = list(list_images(args["test"])) ImagePathsAvg = list(list_images(args["avg"])) GTsa = [] CWa = [] PRa = [] print(ImagePathsTest) print(ImagePathsAvg) # loop over all image pairs for (i, pathA) in enumerate(ImagePathsTest): # load both the images and convert them to grayscale for (j, pathB) in enumerate(ImagePathsAvg): imageA = cv2.imread(pathA, 0) imageB = cv2.imread(pathB, 0) # add channel a dimension to both the images imageA = np.expand_dims(imageA, axis=-1) imageB = np.expand_dims(imageB, axis=-1) # add a batch dimension to both images imageA = np.expand_dims(imageA, axis=0) imageB = np.expand_dims(imageB, axis=0) # scale the pixel values to the range of [0, 1] imageA = imageA / 255.0 imageB = imageB / 255.0 # use our siamese model to make predictions on the image pair, # indicating whether or not the images belong to the same class preds = model.predict([imageA, imageB]) proba = preds[0][0] ground_truth = pathA.split('_')[0].split('/')[2] #compared_with = int(pathB.split('_')[0].split('/')[1]) compared_with = pathB.split('/')[1] #if j % 200: print(f'{j}-{i} - {pathA}, {pathB}, {ground_truth}, {compared_with}, {proba}') GTsa.append(pathA) CWa.append(pathB) PRa.append(proba) return pd.DataFrame( {'Ground Truth': GTsa, 'Compared With': CWa, 'Similarity': PRa }) def getPredictionsConfusionMatrix(): args = { "input": "examples", "test": "image/train", "train": "images/train", "avg": "image_averaged_db/train" } label_dict = { 0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J', 10: 'K', 11: 'L', 12: 'M', 13: 'N', 14: 'O', 15: 'P', 16: 'Q', 17: 'R', 18: 'S', 19: 'T', 20: 'U', 21: 'V', 22: 'W', 23: 'X'} print("[INFO] loading model...") model = keras.models.load_model('model/classifier_model/CNN_20220310_190832.h5') #model = keras.models.load_model('model/classifier_model/data_aug_1_25.h5') ImagePathsTest = "image/train/" filenames = listdir(ImagePathsTest) image_file_names = [filename for filename in filenames if filename.endswith(".jpg")] image_file_names.sort() preds = [] for f in image_file_names: image = cv2.imread(ImagePathsTest+f, 0) #image = cv2.imread(ImagePathsTest+f) image = image / 255.0 # We need to add a 4th dimension to the first axis input_im = image.reshape(1,256,256,1) #input_im = image.reshape(3,256,256,1) # We now get the predictions for that single image #pred = np.argmax(model.predict(input_im), axis=-1)[0] probs = model.predict(input_im) prediction = np.argmax(probs) print(prediction) preds.append(np.argmax(probs)) return preds def getClassifications(): args = { "input": "examples", "test": "image/train", "train": "images/train", "avg": "image_averaged_db/train" } label_dict = { 0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J', 10: 'K', 11: 'L', 12: 'M', 13: 'N', 14: 'O', 15: 'P', 16: 'Q', 17: 'R', 18: 'S', 19: 'T', 20: 'U', 21: 'V', 22: 'W', 23: 'X', 24: 'AB', 25: 'CB', 26: 'DB', 27: 'EB', 28: 'PB', 29: 'RB', 30: 'SB', 31: 'UB', 32: 'VB', 33: 'WB', 34: 'XB'} print("[INFO] loading siamese model...") #model = keras.models.load_model('model/classifier_model/Feb_28.h5') #model = keras.models.load_model('model/classifier_model/CNN_20220308_172743.h5') model = keras.models.load_model('model/classifier_model/CNN_20220310_190832.h5') #model = keras.models.load_model('model/classifier_model/data_aug_1_25.h5') ImagePathsTest = "image/train/" filenames = listdir(ImagePathsTest) image_file_names = [filename for filename in filenames if filename.endswith(".jpg")] image_file_names.sort() data_frames = [] for f in image_file_names: image = cv2.imread(ImagePathsTest+f, 0) #image = cv2.imread(ImagePathsTest+f) image = image / 255.0 # We need to add a 4th dimension to the first axis input_im = image.reshape(1,256,256,1) #input_im = image.reshape(3,256,256,1) # We now get the predictions for that single image #pred = np.argmax(model.predict(input_im), axis=-1)[0] n = 5 probs = model.predict(input_im) y_preds = np.flip(np.argsort(probs, axis=1)[:,-n:]) label_names = [] for y in list(y_preds[0]): label_names.append(label_dict[int(y)]) top_3_prob = [probs[0][int(y_preds[0][0])], probs[0][int(y_preds[0][1])], probs[0][int(y_preds[0][2])], probs[0][int(y_preds[0][3])], probs[0][int(y_preds[0][4])]] df = pd.DataFrame(data=zip(label_names,top_3_prob),columns=['Prediction','Confidence']) print(f) df['Sample'] = f.split('.')[0] new_order = [2,1,0] df = df[df.columns[new_order]] #df['Confidence'] = df['Confidence'] * 100 #df['Confidence'] = df['Confidence'].map('{:,.3f}%'.format) data_frames.append(df) return pd.concat(data_frames) def preprocess_excel_files(filterno, path, start=0, end=360, data_sets = '1,2,3', differentiate = True, differentiate_2 = False, normalize_a = False, normalize_b = True, train=True): filenames = listdir(path) onlyfiles = [filename for filename in filenames if filename.endswith(".xlsx")] onlyfiles.sort() all_data = [] # training_sets = data_sets.split(',') # onlyfiles = ["Set " + f + '.csv' for f in training_sets] print(onlyfiles) for (i,file) in enumerate(onlyfiles): df_orig = pd.read_excel(path+'/'+file) df_orig = df_orig.iloc[start:end, : ] first_col = pd.DataFrame(range(start,end)) df_orig.insert(0, 'Index', first_col) df = df_orig.copy() labels = df.iloc[:,0] df = df.T new_header = labels #grab the first row for the header df = df[1:] #take the data less the header row df.columns = new_header #set the header row as the df header df['labels'] = df.index df['orignal_labels'] = df['labels'] if train: ind = 0 try: df['labels'] = df['labels'].str.split(pat="_", expand=True).iloc[:,ind] except: df['labels'] = df['labels'].str.split(pat="-", expand=True).iloc[:,ind] else: ind = 0 df['labels'] = df['labels'].str.split(pat="-", expand=True).iloc[:,ind] all_data.append(df) print(f'[INFO] Processed {file}, {i+1} out of {len(onlyfiles)} {len(df)}') all_data = pd.concat(all_data) #print('ALL DATA') #print(all_data) #all_data.to_csv('data.csv') unique_list = list(all_data['labels'].unique()) key_hash = dict(zip(unique_list, range(len(unique_list)))) all_data = all_data.replace({"labels": key_hash}) cols = all_data.columns.tolist() cols.insert(0, cols.pop(cols.index('labels'))) all_data = all_data.reindex(columns= cols) all_data_labels = all_data['labels'] orig_data_labels = all_data['orignal_labels'] data = all_data[all_data.columns[1:len(all_data.columns)]] data.reset_index(drop=True, inplace=True) all_data_labels.reset_index(drop=True, inplace=True) #data = data.iloc[start:end, : ] data = data.drop(columns=data.columns[-1]) print('DATA') print(data) if normalize_b: data = preprocessing.normalize(data.values, axis=1, norm='max') # min_max_scaler_a = MinMaxScaler() # x = data.values # data = min_max_scaler_a.fit_transform(x) data = pd.DataFrame(data) if differentiate: print('Differentiating...') x = data.values #returns a numpy array x = pd.DataFrame(x) x = x.iloc[:, :-1] x = x.apply(pd.to_numeric) x = x.diff(axis=1) x = x.clip(lower = 0) x = np.array(x) data = pd.DataFrame(x) del data[0] if differentiate_2: x = pd.DataFrame(x) x = x.iloc[:, :-1] x = x.apply(pd.to_numeric) x = x.diff(axis=1) x = x.clip(lower = 0) x = np.array(x) data = pd.DataFrame(x) del data[0] else: #del data["orignal_labels"] data = pd.DataFrame(data) if normalize_a: min_max_scaler = MinMaxScaler() x = data.values data = min_max_scaler.fit_transform(x) data = pd.DataFrame(data) print('fINAL DATA') print(data) return data, all_data_labels, orig_data_labels, key_hash # def preprocess_excel_files(filter_x_cols, path, train=True): # print("[INFO] Loading and pre-processing data...") # filenames = listdir(path) # onlyfiles = [filename for filename in filenames if filename.endswith(".xlsx")] # onlyfiles.sort() # all_data = [] # for (i,file) in enumerate(onlyfiles): # df_orig = pd.read_excel(path+'/'+file) # #df_orig = df_orig.iloc[48:549,] # print(df_orig) # #del df_orig['Unnamed: 0'] # #df_orig = df_orig.drop(df_orig.columns[[0]], axis=1) # df_orig.insert(0, 'Index', first_col) # df = df_orig.copy() # labels = df.iloc[:,0] # df = df.T # print(df) # new_header = labels #grab the first row for the header # #df = df[1:] #take the data less the header row # df.columns = new_header #set the header row as the df header # df['labels'] = df.index # print(df['labels']) # df['orignal_labels'] = df['labels'] # ind
# # Contains the OpenCL transformation module # import json from functools import reduce import orio.main.util.globals as g import orio.module.loop.ast_lib.common_lib import orio.module.loop.ast_lib.forloop_lib from orio.module.loop.ast import * INCLUDES = r''' #ifdef __APPLE__ #include <OpenCL/opencl.h> #else #include <CL/cl.h> #endif ''' #---------------------------------------------------------------------------------------------------------------------- # globals to note 'only-once' events for efficiency warpkern32 = None warpkern64 = None #---------------------------------------------------------------------------------------------------------------------- class Transformation(object): '''Code transformation''' # ----------------------------------------------------------------------------------------------------------------- def __init__(self, stmt, devProps, targs, tinfo=None): '''Instantiate a code transformation object''' self.stmt = stmt self.devProps = devProps self.platform = targs['platform'] self.device = targs['device'] self.cacheBlocks = targs['cacheBlocks'] self.workGroups = targs['workGroups'] self.streamCount = targs['streamCount'] self.workItemsPerGroup = targs['workItemsPerGroup'] self.unrollInner = targs['unrollInner'] self.clFlags = targs['clFlags'] self.vecHint = targs['vecHint'] self.sizeHint = targs['sizeHint'] self.threadCount = self.workItemsPerGroup self.blockCount = self.workGroups self.globalSize = self.workGroups * self.workItemsPerGroup self.localSize = self.workItemsPerGroup platform_props = self.devProps[self.platform] device_props = platform_props['devices'][self.device] for pname, pval in platform_props.items(): if pname != 'devices': g.Globals().metadata[pname] = pval g.Globals().metadata.update(device_props) self.tinfo = tinfo if self.tinfo is not None and self.streamCount > 1: ivarLists = [x for x in tinfo.ivar_decls if len(x[3])>0] ivarListLengths = set(reduce(lambda acc,item: acc+item[3], ivarLists, [])) if len(ivarListLengths) > 1: raise Exception(('orio.module.loop.submodule.opencl.transformation: streaming for different-length arrays is not supported')) # --------------------------------------------------------------------- # analysis results; initial values are at defaults self.model = { 'inputsize': IdentExp('n'), 'isReduction': False, 'idents': [], 'scalars': [], 'arrays': [], 'rhs_arrays': [], 'lhss': [], 'intscalars': [], 'intarrays': [], 'lbound': None } # tracks various state variables used during transformations self.state = { 'calc_offset': [], 'calc_boffset': [], 'dev_kernel_name': '', 'dev_redkern_name': '' } # frequently used constants self.cs = { 'nthreads': IdentExp('nthreads'), 'nstreams': IdentExp('nstreams'), 'nbytes': IdentExp('nbytes'), 'soffset': IdentExp('soffset'), 'boffset': IdentExp('boffset'), 'chunklen': IdentExp('chunklen'), 'chunkrem': IdentExp('chunkrem'), 'istream': IdentExp('istream'), 'blks4chunk': IdentExp('blks4chunk'), 'blks4chunks': IdentExp('blks4chunks'), 'int0': NumLitExp(0, NumLitExp.INT), 'int1': NumLitExp(1, NumLitExp.INT), 'int2': NumLitExp(2, NumLitExp.INT), 'int3': NumLitExp(3, NumLitExp.INT), 'sizeofDbl': FunCallExp(IdentExp('sizeof'), [IdentExp('double')]), 'prefix': 'orcl_', 'dev': 'dev_', 'q': IdentExp('orcl_command_queue'), 'ctx': IdentExp('orcl_context'), 'st': IdentExp('orcl_status'), 'null': IdentExp('NULL'), 'devs': IdentExp('orcl_devices'), 'false': IdentExp('CL_FALSE'), 'true': IdentExp('CL_TRUE'), 'globalSize': IdentExp('orcl_global_work_size'), 'localSize': IdentExp('orcl_local_work_size'), } # transformation results/components self.newstmts = { 'openclInitialization': [], 'hostDecls': [], 'deviceDims': [], 'streamAllocs': [], 'streamDeallocs': [], 'mallocs': [], 'deallocs': [], 'h2dcopys': [], 'd2hcopys': [], 'kernel_calls': [], 'timerStart': [], 'timerStop': [], 'testNewOutput': [], 'openclFinalization': [], } def checkStatus(self, place): return IfStmt(BinOpExp(self.cs['st'], IdentExp('CL_SUCCESS'), BinOpExp.NE), CompStmt([ExpStmt(FunCallExp(IdentExp('fprintf'),[IdentExp('stderr'), StringLitExp('OpenCL Error: %d in %s\\\\n'), self.cs['st'], StringLitExp(place)])), ExpStmt(FunCallExp(IdentExp('exit'),[IdentExp('EXIT_FAILURE')]))])) # ----------------------------------------------------------------------------------------------------------------- def initializeOpenCL(self): null = IdentExp('NULL') zero = self.cs['int0'] np = IdentExp('orcl_num_platforms') st = IdentExp('orcl_status') pl = IdentExp('orcl_platforms') malloc = IdentExp('malloc') sizeofPlatform = FunCallExp(IdentExp('sizeof'), [IdentExp('cl_platform_id')]) sizeofDevice = FunCallExp(IdentExp('sizeof'), [IdentExp('cl_device_id')]) nd = IdentExp('orcl_num_devices') dev = IdentExp('orcl_devices') ctx = IdentExp('orcl_context') q = self.cs['q'] init = [] init += [Comment('initialize OpenCL'), Comment('get number of platforms'), VarDecl('cl_int', [st]), VarDecl('cl_uint', [np]), VarDecl('cl_platform_id *', [pl]), ExpStmt(BinOpExp( st, FunCallExp(IdentExp('clGetPlatformIDs'), [zero, null, UnaryExp(np, UnaryExp.ADDRESSOF)]), BinOpExp.EQ_ASGN)), self.checkStatus('clGetPlatformIDs for number'), Comment('get platforms'), ExpStmt(BinOpExp( pl, FunCallExp(malloc, [BinOpExp(np, sizeofPlatform, BinOpExp.MUL)]), BinOpExp.EQ_ASGN)), ExpStmt(BinOpExp( st, FunCallExp(IdentExp('clGetPlatformIDs'), [np, pl, null]), BinOpExp.EQ_ASGN)), self.checkStatus('clGetPlatformIDs for platforms'), Comment('get number of devices for chosen platform'), VarDecl('cl_uint', [nd]), VarDecl('cl_device_id *', [dev]), ExpStmt(BinOpExp( st, FunCallExp(IdentExp('clGetDeviceIDs'), [ArrayRefExp(pl, NumLitExp(self.platform, NumLitExp.INT)), IdentExp('CL_DEVICE_TYPE_ALL'), zero, null, UnaryExp(nd, UnaryExp.ADDRESSOF)]), BinOpExp.EQ_ASGN)), self.checkStatus('clGetDeviceIDs for number'), Comment('get devices for chosen platform'), ExpStmt(BinOpExp( dev, FunCallExp(malloc, [BinOpExp(nd, sizeofDevice, BinOpExp.MUL)]), BinOpExp.EQ_ASGN)), ExpStmt(BinOpExp( st, FunCallExp(IdentExp('clGetDeviceIDs'), [ArrayRefExp(pl, NumLitExp(self.platform, NumLitExp.INT)), IdentExp('CL_DEVICE_TYPE_ALL'), nd, dev, null]), BinOpExp.EQ_ASGN)), self.checkStatus('clGetDeviceIDs for devices'), Comment('create OpenCL context'), VarDecl('cl_context', [ctx]), ExpStmt(BinOpExp( ctx, FunCallExp(IdentExp('clCreateContext'), [null, nd, dev, null, null, UnaryExp(st, UnaryExp.ADDRESSOF) ]), BinOpExp.EQ_ASGN)), self.checkStatus('clCreateContext'), Comment('create OpenCL command queue'), VarDecl('cl_command_queue', [q]), ExpStmt(BinOpExp( q, FunCallExp(IdentExp('clCreateCommandQueue'), [ctx, ArrayRefExp(dev, NumLitExp(self.device, NumLitExp.INT)), IdentExp('CL_QUEUE_PROFILING_ENABLE'), UnaryExp(st, UnaryExp.ADDRESSOF) ]), BinOpExp.EQ_ASGN)), self.checkStatus('clCreateCommandQueue'), ] final = [] final += [Comment('free OpenCL data structures'), ExpStmt(FunCallExp(IdentExp('TAU_PROFILER_STOP'),[IdentExp('execute_profiler')])), ExpStmt(FunCallExp(IdentExp('clReleaseCommandQueue'), [q])), ExpStmt(FunCallExp(IdentExp('clReleaseContext'), [ctx])), ExpStmt(FunCallExp(IdentExp('free'), [dev])), ExpStmt(FunCallExp(IdentExp('free'), [pl])) ] self.newstmts['openclInitialization'] += init self.newstmts['openclFinalization'] += final # ----------------------------------------------------------------------------------------------------------------- def createDVarDecls(self): '''Create declarations of device-side variables corresponding to host-side variables''' intarrays = self.model['intarrays'] hostDecls = [ExpStmt(FunCallExp(IdentExp('clFinish'), [self.cs['q']]))] hostDecls += [ Comment('declare variables'), VarDecl('cl_mem', [x[1] for x in self.model['idents']]) ] if len(intarrays)>0: hostDecls += [VarDecl('cl_mem', [x[1] for x in intarrays])] hostDecls += [ VarDeclInit('int', self.cs['nthreads'], NumLitExp(self.threadCount, NumLitExp.INT)) ] if self.streamCount > 1: hostDecls += [VarDeclInit('int', self.cs['nstreams'], NumLitExp(self.streamCount, NumLitExp.INT))] self.newstmts['hostDecls'] = hostDecls # free allocated memory and resources deallocs = [Comment('free allocated memory')] for _,dvar in self.model['idents']: deallocs += [ExpStmt(FunCallExp(IdentExp('clReleaseMemObject'), [IdentExp(dvar)]))] for _,dvar in self.model['intarrays']: deallocs += [ExpStmt(FunCallExp(IdentExp('clReleaseMemObject'), [IdentExp(dvar)]))] self.newstmts['deallocs'] = deallocs # ----------------------------------------------------------------------------------------------------------------- def calcDims(self): '''Calculate device dimensions''' self.newstmts['deviceDims'] = [ Comment('calculate device dimensions'), VarDecl('size_t', ['orcl_global_work_size[1]', 'orcl_local_work_size[1]']), ExpStmt(BinOpExp(IdentExp('orcl_global_work_size[0]'), NumLitExp(self.globalSize, NumLitExp.INT), BinOpExp.EQ_ASGN)), ExpStmt(BinOpExp(IdentExp('orcl_local_work_size[0]'), NumLitExp(self.localSize, NumLitExp.INT), BinOpExp.EQ_ASGN)) ] # ----------------------------------------------------------------------------------------------------------------- def createStreamDecls(self): '''Create stream declarations''' # TODO: streams raise Exception("streams not yet implemented") # # self.state['calc_offset'] = [ # ExpStmt(BinOpExp(self.cs['soffset'], # BinOpExp(self.cs['istream'], self.cs['chunklen'], BinOpExp.MUL), # BinOpExp.EQ_ASGN)) # ] # self.state['calc_boffset'] = [ # ExpStmt(BinOpExp(self.cs['boffset'], # BinOpExp(self.cs['istream'], self.cs['blks4chunk'], BinOpExp.MUL), # BinOpExp.EQ_ASGN)) # ] # # self.newstmts['streamAllocs'] = [ # Comment('create streams'), # VarDecl('int', [self.cs['istream'], self.cs['soffset']] + ([self.cs['boffset']] if self.model['isReduction'] else [])), # VarDecl('cudaStream_t', ['stream[nstreams+1]']), # ForStmt(BinOpExp(self.cs['istream'], self.cs['int0'], BinOpExp.EQ_ASGN), # BinOpExp(self.cs['istream'], self.cs['nstreams'], BinOpExp.LE), # UnaryExp(self.cs['istream'], UnaryExp.POST_INC), # ExpStmt(FunCallExp(IdentExp('cudaStreamCreate'), # [UnaryExp(ArrayRefExp(IdentExp('stream'), self.cs['istream']), UnaryExp.ADDRESSOF)]))), # VarDeclInit('int', self.cs['chunklen'], BinOpExp(self.model['inputsize'], self.cs['nstreams'], BinOpExp.DIV)), # VarDeclInit('int', self.cs['chunkrem'], BinOpExp(self.model['inputsize'], self.cs['nstreams'], BinOpExp.MOD)), # ] # # # destroy streams # deallocs = [ # ForStmt(BinOpExp(self.cs['istream'], self.cs['int0'], BinOpExp.EQ_ASGN), # BinOpExp(self.cs['istream'], self.cs['nstreams'], BinOpExp.LE), # UnaryExp(self.cs['istream'], UnaryExp.POST_INC), # ExpStmt(FunCallExp(IdentExp('cudaStreamDestroy'), [ArrayRefExp(IdentExp('stream'), self.cs['istream'])])))] # self.newstmts['streamDeallocs'] = deallocs # ----------------------------------------------------------------------------------------------------------------- def createMallocs(self): '''Create device-side mallocs''' readWrite = IdentExp('CL_MEM_READ_WRITE') copyHost = IdentExp('CL_MEM_COPY_HOST_PTR') rwCopy = BinOpExp(readWrite, copyHost, BinOpExp.BOR) mallocs = [ Comment('allocate device memory'), ] if self.tinfo is None: # inference mode mallocs += [VarDeclInit('int', self.cs['nbytes'], BinOpExp(self.model['inputsize'], self.cs['sizeofDbl'], BinOpExp.MUL))] h2dcopys = [Comment('copy data from host to device')] h2dasyncs = [] h2dasyncsrem = [] # ------------------------------------------------- pinnedIdents = [] for aid,daid in self.model['arrays']: if self.tinfo is None: aidbytes = self.cs['nbytes'] else: aidtinfo = [x for x in self.tinfo.ivar_decls if x[2] == aid] if len(aidtinfo) == 0: raise Exception('orio.module.loop.submodule.opencl.transformation: %s: unknown input variable argument: "%s"' % aid) else: aidtinfo = aidtinfo[0] aidbytes = BinOpExp(IdentExp(aidtinfo[3][0]), FunCallExp(IdentExp('sizeof'), [IdentExp(aidtinfo[1])]), BinOpExp.MUL) mallocs += [ ExpStmt(BinOpExp(IdentExp(daid), FunCallExp(IdentExp('clCreateBuffer'), [self.cs['ctx'], readWrite, aidbytes, self.cs['null'], UnaryExp(self.cs['st'], UnaryExp.ADDRESSOF), ]), BinOpExp.EQ_ASGN)), self.checkStatus('clCreateCommandQueue') ] # memcopy rhs arrays device to host if aid in self.model['rhs_arrays']: if self.streamCount > 1: # TODO: streams raise Exception("multiple streams not supported yet") # mallocs += [ # ExpStmt(FunCallExp(IdentExp('cudaHostRegister'), # [IdentExp(aid), # aidbytes, # IdentExp('cudaHostRegisterPortable') # ])) # ] # pinnedIdents += [aid] # remember to unregister at the end # h2dasyncs += [ # ExpStmt(FunCallExp(IdentExp('cudaMemcpyAsync'), # [BinOpExp(IdentExp(daid), self.cs['soffset'], BinOpExp.ADD), # BinOpExp(IdentExp(aid), self.cs['soffset'], BinOpExp.ADD), # BinOpExp(self.cs['chunklen'], self.cs['sizeofDbl'], BinOpExp.MUL), # IdentExp('cudaMemcpyHostToDevice'), # ArrayRefExp(IdentExp('stream'), self.cs['istream']) ])) # ] # h2dasyncsrem += [ # ExpStmt(FunCallExp(IdentExp('cudaMemcpyAsync'), # [BinOpExp(IdentExp(daid), self.cs['soffset'], BinOpExp.ADD), # BinOpExp(IdentExp(aid), self.cs['soffset'], BinOpExp.ADD), # BinOpExp(self.cs['chunkrem'], self.cs['sizeofDbl'], BinOpExp.MUL), # IdentExp('cudaMemcpyHostToDevice'), # ArrayRefExp(IdentExp('stream'), self.cs['istream']) ])) # ] else: h2dcopys += [ ExpStmt(BinOpExp(self.cs['st'],FunCallExp(IdentExp('clEnqueueWriteBuffer'), [self.cs['q'], IdentExp(daid), self.cs['false'], self.cs['int0'], aidbytes, IdentExp(aid), self.cs['int0'], self.cs['int0'], self.cs['null'] ]),BinOpExp.EQ_ASGN)), self.checkStatus('clEnqueueWriteBuffer for ' + daid) ] # for-loop over streams to do async copies # if self.streamCount > 1: # h2dcopys += [ # ForStmt(BinOpExp(self.cs['istream'], self.cs['int0'], BinOpExp.EQ_ASGN), # BinOpExp(self.cs['istream'], self.cs['nstreams'], BinOpExp.LT), # UnaryExp(self.cs['istream'], UnaryExp.POST_INC), # CompStmt(self.state['calc_offset'] + h2dasyncs)), # # copy the remainder in the last/reserve stream # IfStmt(BinOpExp(self.cs['chunkrem'], self.cs['int0'], BinOpExp.NE), # CompStmt(self.state['calc_offset'] + h2dasyncsrem)) # ] for aid,daid in self.model['intarrays']: if self.tinfo is None: aidbytes = FunCallExp(IdentExp('sizeof'), [IdentExp(aid)]) else: aidtinfo = [x for x in self.tinfo.ivar_decls if x[2] == aid] if len(aidtinfo) == 0: raise Exception('orio.module.loop.submodule.opencl.transformation: %s: unknown input variable argument: "%s"' % aid) else: aidtinfo = aidtinfo[0] aidbytes = BinOpExp(IdentExp(aidtinfo[3][0]), FunCallExp(IdentExp('sizeof'), [IdentExp(aidtinfo[1])]), BinOpExp.MUL) mallocs += [ ExpStmt(BinOpExp(IdentExp(daid), FunCallExp(IdentExp('clCreateBuffer'), [self.cs['ctx'], readWrite, aidbytes, self.cs['null'], UnaryExp(self.cs['st'], UnaryExp.ADDRESSOF), ]), BinOpExp.EQ_ASGN)), self.checkStatus('clCreateBuffer for ' + daid) ] # memcopy rhs arrays device to host if aid in self.model['rhs_arrays']: h2dcopys += [ ExpStmt(BinOpExp(self.cs['st'],FunCallExp(IdentExp('clEnqueueReadBuffer'), [self.cs['q'], IdentExp(daid), self.cs['false'], self.cs['int0'], aidbytes, IdentExp(aid), self.cs['int0'], self.cs['int0'], self.cs['null'] ])), BinOpExp.EQ_ASGN), self.checkStatus('clEnqueueReadBuffer for ' + daid) ] # ------------------------------------------------- # malloc block-level result var if self.model['isReduction']: mallocs += [ ExpStmt(BinOpExp(IdentExp(self.cs['dev'] + self.model['lhss'][0]), FunCallExp(IdentExp('clCreateBuffer'), [self.cs['ctx'], readWrite, BinOpExp(ParenthExp(BinOpExp(IdentExp('orcl_global_work_size[0]'), self.cs['int1'], BinOpExp.ADD)), self.cs['sizeofDbl'], BinOpExp.MUL), self.cs['null'], UnaryExp(self.cs['st'], UnaryExp.ADDRESSOF), ]), BinOpExp.EQ_ASGN)), self.checkStatus('clCreateBuffer for ' + (self.cs['dev'] + self.model['lhss'][0]))] # ------------------------------------------------- d2hcopys = [Comment('copy data from device to host')] d2hasyncs = [] d2hasyncsrem = [] for var in self.model['lhss']: res_scalar_ids = [x for x in self.model['scalars'] if x == var] for rsid in res_scalar_ids: d2hcopys += [ ExpStmt(BinOpExp(self.cs['st'], FunCallExp(IdentExp('clEnqueueReadBuffer'), [self.cs['q'], IdentExp(self.cs['dev'] + rsid), self.cs['true'], self.cs['int0'], self.cs['sizeofDbl'], UnaryExp(IdentExp(rsid),UnaryExp.ADDRESSOF), self.cs['int0'], self.cs['null'], self.cs['null'], ]), BinOpExp.EQ_ASGN)), self.checkStatus('clEnqueueReadBuffer for ' + self.cs['dev'] + rsid)] res_array_ids = [x for x in self.model['arrays'] if x[0] == var] for raid,draid in res_array_ids: if self.streamCount > 1: # TODO: streams raise Exception("streams not yet implemented") # d2hasyncs += [ # ExpStmt(FunCallExp(IdentExp('cudaMemcpyAsync'), # [BinOpExp(IdentExp(raid), self.cs['soffset'], BinOpExp.ADD), # BinOpExp(IdentExp(draid), self.cs['soffset'], BinOpExp.ADD), # BinOpExp(self.cs['chunklen'], self.cs['sizeofDbl'], BinOpExp.MUL), # IdentExp('cudaMemcpyDeviceToHost'), # ArrayRefExp(IdentExp('stream'), self.cs['istream']) # ]))] # d2hasyncsrem += [ # ExpStmt(FunCallExp(IdentExp('cudaMemcpyAsync'), # [BinOpExp(IdentExp(raid), self.cs['soffset'], BinOpExp.ADD), # BinOpExp(IdentExp(draid), self.cs['soffset'], BinOpExp.ADD), # BinOpExp(self.cs['chunkrem'], self.cs['sizeofDbl'], BinOpExp.MUL), # IdentExp('cudaMemcpyDeviceToHost'), # ArrayRefExp(IdentExp('stream'), self.cs['istream']) # ]))] else: if self.tinfo is None: raidbytes = self.cs['nbytes'] else: raidtinfo = [x for x in self.tinfo.ivar_decls if x[2]
:param value: Required. The parameter value of fabric setting. :type value: str """ _validation = { 'name': {'required': True}, 'value': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__( self, *, name: str, value: str, **kwargs ): super(SettingsParameterDescription, self).__init__(**kwargs) self.name = name self.value = value class SettingsSectionDescription(msrest.serialization.Model): """Describes a section in the fabric settings of the cluster. All required parameters must be populated in order to send to Azure. :param name: Required. The section name of the fabric settings. :type name: str :param parameters: Required. The collection of parameters in the section. :type parameters: list[~service_fabric_managed_clusters_management_client.models.SettingsParameterDescription] """ _validation = { 'name': {'required': True}, 'parameters': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'parameters': {'key': 'parameters', 'type': '[SettingsParameterDescription]'}, } def __init__( self, *, name: str, parameters: List["SettingsParameterDescription"], **kwargs ): super(SettingsSectionDescription, self).__init__(**kwargs) self.name = name self.parameters = parameters class SingletonPartitionScheme(Partition): """SingletonPartitionScheme. All required parameters must be populated in order to send to Azure. :param partition_scheme: Required. Specifies how the service is partitioned.Constant filled by server. Possible values include: "Singleton", "UniformInt64Range", "Named". :type partition_scheme: str or ~service_fabric_managed_clusters_management_client.models.PartitionScheme """ _validation = { 'partition_scheme': {'required': True}, } _attribute_map = { 'partition_scheme': {'key': 'partitionScheme', 'type': 'str'}, } def __init__( self, **kwargs ): super(SingletonPartitionScheme, self).__init__(**kwargs) self.partition_scheme = 'Singleton' # type: str class Sku(msrest.serialization.Model): """Service Fabric managed cluster Sku definition. All required parameters must be populated in order to send to Azure. :param name: Required. Sku Name. Possible values include: "Basic", "Standard". :type name: str or ~service_fabric_managed_clusters_management_client.models.SkuName """ _validation = { 'name': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, } def __init__( self, *, name: Union[str, "SkuName"], **kwargs ): super(Sku, self).__init__(**kwargs) self.name = name class StatefulServiceProperties(ServiceResourceProperties): """The properties of a stateful service resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param placement_constraints: The placement constraints as a string. Placement constraints are boolean expressions on node properties and allow for restricting a service to particular nodes based on the service requirements. For example, to place a service on nodes where NodeType is blue specify the following: "NodeColor == blue)". :type placement_constraints: str :param correlation_scheme: A list that describes the correlation of the service with other services. :type correlation_scheme: list[~service_fabric_managed_clusters_management_client.models.ServiceCorrelation] :param service_load_metrics: The service load metrics is given as an array of ServiceLoadMetric objects. :type service_load_metrics: list[~service_fabric_managed_clusters_management_client.models.ServiceLoadMetric] :param service_placement_policies: A list that describes the correlation of the service with other services. :type service_placement_policies: list[~service_fabric_managed_clusters_management_client.models.ServicePlacementPolicy] :param default_move_cost: Specifies the move cost for the service. Possible values include: "Zero", "Low", "Medium", "High". :type default_move_cost: str or ~service_fabric_managed_clusters_management_client.models.MoveCost :param scaling_policies: Scaling policies for this service. :type scaling_policies: list[~service_fabric_managed_clusters_management_client.models.ScalingPolicy] :ivar provisioning_state: The current deployment or provisioning state, which only appears in the response. :vartype provisioning_state: str :param service_kind: Required. The kind of service (Stateless or Stateful).Constant filled by server. Possible values include: "Stateless", "Stateful". :type service_kind: str or ~service_fabric_managed_clusters_management_client.models.ServiceKind :param service_type_name: Required. The name of the service type. :type service_type_name: str :param partition_description: Required. Describes how the service is partitioned. :type partition_description: ~service_fabric_managed_clusters_management_client.models.Partition :param service_package_activation_mode: The activation Mode of the service package. Possible values include: "SharedProcess", "ExclusiveProcess". :type service_package_activation_mode: str or ~service_fabric_managed_clusters_management_client.models.ServicePackageActivationMode :param service_dns_name: The DNS name of the service. It requires the DNS system service to be enabled in Service Fabric cluster. :type service_dns_name: str :param has_persisted_state: A flag indicating whether this is a persistent service which stores states on the local disk. If it is then the value of this property is true, if not it is false. :type has_persisted_state: bool :param target_replica_set_size: The target replica set size as a number. :type target_replica_set_size: int :param min_replica_set_size: The minimum replica set size as a number. :type min_replica_set_size: int :param replica_restart_wait_duration: The duration between when a replica goes down and when a new replica is created, represented in ISO 8601 format "hh:mm:ss". :type replica_restart_wait_duration: str :param quorum_loss_wait_duration: The maximum duration for which a partition is allowed to be in a state of quorum loss, represented in ISO 8601 format "hh:mm:ss". :type quorum_loss_wait_duration: str :param stand_by_replica_keep_duration: The definition on how long StandBy replicas should be maintained before being removed, represented in ISO 8601 format "hh:mm:ss". :type stand_by_replica_keep_duration: str :param service_placement_time_limit: The duration for which replicas can stay InBuild before reporting that build is stuck, represented in ISO 8601 format "hh:mm:ss". :type service_placement_time_limit: str :param drop_source_replica_on_move: Indicates whether to drop source Secondary replica even if the target replica has not finished build. If desired behavior is to drop it as soon as possible the value of this property is true, if not it is false. :type drop_source_replica_on_move: bool """ _validation = { 'provisioning_state': {'readonly': True}, 'service_kind': {'required': True}, 'service_type_name': {'required': True}, 'partition_description': {'required': True}, 'target_replica_set_size': {'minimum': 1}, 'min_replica_set_size': {'minimum': 1}, } _attribute_map = { 'placement_constraints': {'key': 'placementConstraints', 'type': 'str'}, 'correlation_scheme': {'key': 'correlationScheme', 'type': '[ServiceCorrelation]'}, 'service_load_metrics': {'key': 'serviceLoadMetrics', 'type': '[ServiceLoadMetric]'}, 'service_placement_policies': {'key': 'servicePlacementPolicies', 'type': '[ServicePlacementPolicy]'}, 'default_move_cost': {'key': 'defaultMoveCost', 'type': 'str'}, 'scaling_policies': {'key': 'scalingPolicies', 'type': '[ScalingPolicy]'}, 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, 'service_kind': {'key': 'serviceKind', 'type': 'str'}, 'service_type_name': {'key': 'serviceTypeName', 'type': 'str'}, 'partition_description': {'key': 'partitionDescription', 'type': 'Partition'}, 'service_package_activation_mode': {'key': 'servicePackageActivationMode', 'type': 'str'}, 'service_dns_name': {'key': 'serviceDnsName', 'type': 'str'}, 'has_persisted_state': {'key': 'hasPersistedState', 'type': 'bool'}, 'target_replica_set_size': {'key': 'targetReplicaSetSize', 'type': 'int'}, 'min_replica_set_size': {'key': 'minReplicaSetSize', 'type': 'int'}, 'replica_restart_wait_duration': {'key': 'replicaRestartWaitDuration', 'type': 'str'}, 'quorum_loss_wait_duration': {'key': 'quorumLossWaitDuration', 'type': 'str'}, 'stand_by_replica_keep_duration': {'key': 'standByReplicaKeepDuration', 'type': 'str'}, 'service_placement_time_limit': {'key': 'servicePlacementTimeLimit', 'type': 'str'}, 'drop_source_replica_on_move': {'key': 'dropSourceReplicaOnMove', 'type': 'bool'}, } def __init__( self, *, service_type_name: str, partition_description: "Partition", placement_constraints: Optional[str] = None, correlation_scheme: Optional[List["ServiceCorrelation"]] = None, service_load_metrics: Optional[List["ServiceLoadMetric"]] = None, service_placement_policies: Optional[List["ServicePlacementPolicy"]] = None, default_move_cost: Optional[Union[str, "MoveCost"]] = None, scaling_policies: Optional[List["ScalingPolicy"]] = None, service_package_activation_mode: Optional[Union[str, "ServicePackageActivationMode"]] = None, service_dns_name: Optional[str] = None, has_persisted_state: Optional[bool] = None, target_replica_set_size: Optional[int] = None, min_replica_set_size: Optional[int] = None, replica_restart_wait_duration: Optional[str] = None, quorum_loss_wait_duration: Optional[str] = None, stand_by_replica_keep_duration: Optional[str] = None, service_placement_time_limit: Optional[str] = None, drop_source_replica_on_move: Optional[bool] = None, **kwargs ): super(StatefulServiceProperties, self).__init__(placement_constraints=placement_constraints, correlation_scheme=correlation_scheme, service_load_metrics=service_load_metrics, service_placement_policies=service_placement_policies, default_move_cost=default_move_cost, scaling_policies=scaling_policies, service_type_name=service_type_name, partition_description=partition_description, service_package_activation_mode=service_package_activation_mode, service_dns_name=service_dns_name, **kwargs) self.service_kind = 'Stateful' # type: str self.has_persisted_state = has_persisted_state self.target_replica_set_size = target_replica_set_size self.min_replica_set_size = min_replica_set_size self.replica_restart_wait_duration = replica_restart_wait_duration self.quorum_loss_wait_duration = quorum_loss_wait_duration self.stand_by_replica_keep_duration = stand_by_replica_keep_duration self.service_placement_time_limit = service_placement_time_limit self.drop_source_replica_on_move = drop_source_replica_on_move class StatelessServiceProperties(ServiceResourceProperties): """The properties of a stateless service resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param placement_constraints: The placement constraints as a string. Placement constraints are boolean expressions on node properties and allow for restricting a service to particular nodes based on the service requirements. For example, to place a service on nodes where NodeType is blue specify the following: "NodeColor == blue)". :type placement_constraints: str :param correlation_scheme: A list that describes the correlation of the service with other services. :type correlation_scheme: list[~service_fabric_managed_clusters_management_client.models.ServiceCorrelation] :param service_load_metrics: The service load metrics is given as an array of ServiceLoadMetric objects. :type service_load_metrics: list[~service_fabric_managed_clusters_management_client.models.ServiceLoadMetric] :param service_placement_policies: A list that describes the correlation of the service with other services. :type service_placement_policies: list[~service_fabric_managed_clusters_management_client.models.ServicePlacementPolicy] :param default_move_cost: Specifies the move cost for the service. Possible values include: "Zero", "Low", "Medium", "High". :type default_move_cost: str or ~service_fabric_managed_clusters_management_client.models.MoveCost :param scaling_policies: Scaling policies for this service. :type scaling_policies: list[~service_fabric_managed_clusters_management_client.models.ScalingPolicy] :ivar provisioning_state: The current deployment or provisioning state, which only appears in the response. :vartype provisioning_state: str :param service_kind: Required. The kind of service (Stateless or Stateful).Constant filled by server. Possible values include: "Stateless", "Stateful". :type service_kind: str or ~service_fabric_managed_clusters_management_client.models.ServiceKind :param service_type_name: Required. The name of the service type. :type service_type_name: str :param partition_description: Required. Describes how the service is partitioned. :type partition_description: ~service_fabric_managed_clusters_management_client.models.Partition :param service_package_activation_mode: The activation Mode of the service package. Possible values include: "SharedProcess", "ExclusiveProcess". :type service_package_activation_mode: str or ~service_fabric_managed_clusters_management_client.models.ServicePackageActivationMode :param service_dns_name: The DNS name of the service. It requires the DNS system service to be enabled in Service Fabric
<filename>python-code/robot.py import numpy as np import scipy from scipy.linalg import block_diag import math import quaternion class rJoint: def __init__(self, alpha, a, theta, offset, d, type, inertia, m, r): self.alpha = alpha self.a = a self.offset = offset self.theta = theta self.d = d self.type = type self.inertia = inertia self.m = m self.r = r class cartesian: def __init__(self, x, y, z, roll, pitch, yaw): self.x = x self.y = y self.z = z self.roll = roll self.pitch = pitch self.yaw = yaw class jointTarget: def __init__(self, q0, qf): self.q0 = q0 self.qf = qf class jointspaceConfig: def __init__(self, joints): self.joints = joints class fkine: def __init__(self, T, A, Aout, transl, R, rpy, w_hat): self.T = T self.A = A self.Aout = Aout self.transl = transl self.R = R self.rpy = rpy self.w_hat = w_hat class impedanceController: def __init__(self): self.Kd = np.diag(np.array([125,125,125,1,1,1])) self.Bd = np.diag(np.array([85,85,85,165,165,165])) self.Md = np.diag(np.array([15, 15, 15, 1, 1, 1])) self.x = np.zeros(6) self.x_target = np.zeros(6) self.quat = np.quaternion(1,0,0,0) self.quat_target = np.quaternion(1,0,0,0) self.filter_params_ = 0.0005 self.cartesian_stiffness_ = np.zeros((6,6)) self.cartesian_damping_ = np.zeros((6,6)) self.nullspace_stiffness_ = 20 self.nullspace_stiffness_target_ = 20 self.zeta = np.array([1, 1, 1, 1, 1, 1]) self.F = np.zeros(6) # Controllers def output(self, x, xd, xdd, xc, xcd, F): Mdinv = np.linalg.inv(self.Md) damper = np.dot(self.Bd,(xcd - xd)) spring = np.dot(self.Kd,(xc - x)) ax = xdd - np.dot(Mdinv,(damper + spring + F)) return ax def output3(self, e, ed, xdd, F): Mdinv = np.linalg.inv(self.Md[:3,:3]) damper = np.dot(self.Bd[:3,:3],(ed[:3])) spring = np.dot(self.Kd[:3,:3],(e[:3])) ax = xdd[:3] - np.dot(Mdinv,(damper + spring + F[:3])) return ax def outputquat(self, Kd_b, Bd, e, ed, xdd, F): Mdinv = np.linalg.inv(self.Md) damper = np.dot(Bd,ed) spring = np.dot(Kd_b,e) ax = xdd - np.dot(Mdinv,(damper + spring + F)) return ax def exponential_smoothing(self): # Exponential smoothing function. self.cartesian_stiffness_ = np.dot(self.filter_params_, self.Kd) + np.dot((1.0 - self.filter_params_), self.cartesian_stiffness_) self.cartesian_damping_ = np.dot(self.filter_params_, self.Bd) + np.dot((1.0 - self.filter_params_), self.cartesian_damping_) self.nullspace_stiffness_ = np.dot(self.filter_params_, self.nullspace_stiffness_target_) + np.dot((1.0 - self.filter_params_), self.nullspace_stiffness_) self.x = np.dot( self.filter_params_, self.x_target ) + np.dot( (1.0 - self.filter_params_), self.x ) self.quat = quaternion.slerp_evaluate(self.quat, self.quat_target, self.filter_params_) def damping_dual_eigen(self, Kd, M): # Computing dynamic damping B0, Q = scipy.linalg.eigh(Kd, M) B0sqrt = np.sqrt(B0) # If the resulting eigenvalues are close to zero for i in range(6): if np.isnan(B0sqrt[i]): B0sqrt[i] = 0 Kd_B = Q.T.dot(B0.dot(Q)) Bd = 2*Q.T.dot(( np.diag( self.zeta * B0sqrt ).dot(Q)) ) return Bd, Kd_B def damping_dual_eigen2(self, Kd, M): # Computing dynamic damping B0, Q = scipy.linalg.eigh(Kd, M) B0sqrt = np.sqrt(B0) # If the resulting eigenvalues are close to zero for i in range(6): if np.isnan(B0sqrt[i]): B0sqrt[i] = 0 Kd_B = Q.T.dot(B0.dot(Q)) Bd = 2*Q.T.dot(( np.diag( np.ones(7) * B0sqrt ).dot(Q)) ) return Bd, Kd_B def damping_constant_mass(self): # Computing dynamic damping K1 = np.sqrt(self.Kd) M1 = np.sqrt(self.Md) Bd = self.zeta * (M1.dot(K1) + K1.dot(M1) ) return Bd def damping_constant_mass2(self, Kd): # Computing dynamic damping K1 = np.sqrt(Kd) M1 = np.sqrt(self.Md) Bd = self.zeta * (M1.dot(K1) + K1.dot(M1) ) return Bd class Robot: def __init__(self, dh): self.joints = 0 self.ndof = 0 self.dh = dh self.grav = np.array([0,0,9.81]) def robot_init(self): # Initial values for declaration q = np.array([0, 0, 0, 0, 0, 0, 0]) # q_off = np.array([0.1, 0.1, 0.1, -np.pi/3, 0.1, np.pi/3, np.pi/3]) q_off = np.array([0, 0, 0, 0, 0, 0, 0]) # q = np.array([0.1, 0.1, 0.1, -np.pi/3, 0.1, np.pi/3, np.pi/3]) qd = np.array([0, 0, 0, 0, 0, 0, 0]) qdd = np.array([0, 0, 0, 0, 0, 0, 0]) # Robot parameters # alpha = [(np.pi/2), (-np.pi/2), (np.pi/2), (-np.pi/2), (np.pi/2), (np.pi/2), 0] alpha = [0, (-np.pi/2), (np.pi/2), (np.pi/2), (-np.pi/2), (np.pi/2), (np.pi/2)] a = [0, 0, 0, 0.0825, -0.0825, 0, 0.088, 0] d = [0.333, 0, 0.316, 0, 0.384, 0, 0, 0.107] # m = [4.970684, 0.646926, 3.228604, 3.587895, 1.225946, 1.666555, 7.35522e-01] m = [2.34471, 2.36414, 2.38050, 2.42754, 3.49611, 1.46736, 0.45606] # r = [-(0.333/2), 0.0, -(0.316/2), 0, -(0.384/2), 0, -(0.107/2)] n_dof = 7 Ipanda = [[0.3, 0, 0],[0, 0.3, 0],[0, 0, 0.3]] Ipanda1 = np.array([[7.03370e-01, -1.39000e-04, 6.77200e-03], [-1.39000e-04, 7.06610e-01, 1.91690e-02], [6.77200e-03, 1.91690e-02, 9.11700e-03]]) Ipanda2 = np.array([[7.96200e-03, -3.92500e-03, 1.02540e-02], [-3.92500e-03, 2.81100e-02, 7.04000e-04], [1.02540e-02, 7.04000e-04, 2.59950e-02 ]]) Ipanda3 = np.array([[3.72420e-02, -4.76100e-03, -1.13960e-02], [-4.76100e-03, 3.61550e-02, -1.28050e-02], [-1.13960e-02, -1.28050e-02, 1.08300e-02 ]]) Ipanda4 = np.array([[2.58530e-02, 7.79600e-03, -1.33200e-03], [7.79600e-03, 1.95520e-02, 8.64100e-03], [-1.33200e-03, 8.64100e-03, 2.83230e-02 ]]) Ipanda5 = np.array([[3.55490e-02, -2.11700e-03, -4.03700e-03], [-2.11700e-03, 2.94740e-02, 2.29000e-04], [-4.03700e-03, 2.29000e-04, 8.62700e-03]]) Ipanda6 = np.array([[1.96400e-03, 1.09000e-04, -1.15800e-03], [1.09000e-04, 4.35400e-03, 3.41000e-04], [-1.15800e-03, 3.41000e-04, 5.43300e-03]]) Ipanda7 = np.array([[1.25160e-02, -4.28000e-04, -1.19600e-03], [-4.28000e-04, 1.00270e-02, -7.41000e-04], [-1.19600e-03, -7.41000e-04, 4.81500e-03]]) # _____________________ # Parameter order: # alpha, a, theta, d, type, inertia, m, r Joint1 = rJoint(alpha[0], a[0], q[0], q_off[0], d[0], 'R', Ipanda, m[0], np.array([[3.875e-03],[2.081e-03],[0]]) ) Joint2 = rJoint(alpha[1], a[1], q[1], q_off[1], d[1], 'R', Ipanda, m[1], np.array([[-3.141e-03],[-2.872e-02],[3.495e-03]]) ) Joint3 = rJoint(alpha[2], a[2], q[2], q_off[2], d[2], 'R', Ipanda, m[2], np.array([[2.7518e-02],[3.9252e-02],[-6.6502e-02]]) ) Joint4 = rJoint(alpha[3], a[3], q[3], q_off[3], d[3], 'R', Ipanda, m[3], np.array([[-5.317e-02],[1.04419e-01],[2.7454e-02]]) ) Joint5 = rJoint(alpha[4], a[4], q[4], q_off[4], d[4], 'R', Ipanda, m[4], np.array([[-1.1953e-02],[4.1065e-02],[-3.8437e-02]]) ) Joint6 = rJoint(alpha[5], a[5], q[5], q_off[5], d[5], 'R', Ipanda, m[5], np.array([[6.0149e-02],[-1.4117e-02],[-1.0517e-02]]) ) Joint7 = rJoint(alpha[6], a[6], q[6], q_off[6], d[6], 'R', Ipanda, m[6], np.array([[1.0517e-02],[-4.252e-03],[6.1597e-02]]) ) # Collecting joints JointCol = [Joint1, Joint2, Joint3, Joint4, Joint5, Joint6, Joint7] self.joints = JointCol self.ndof = 7 def inverseDynamics(self, qc, qcdot, qcddot, grav): qc = qc.reshape((1,self.ndof)) qcdot = qcdot.reshape((1,self.ndof)) qcddot = qcddot.reshape((1,self.ndof)) if self.dh.lower() == 'mdh': grav = grav.reshape(3) Q = np.ravel(self.mdh_invdyn(qc, qcdot, qcddot, grav)) else: grav = grav.reshape((3,1)) # May need to fix this Q = np.ravel(self.invdyn(qc, qcdot, qcddot, grav)) return Q def forwardKinematics(self, q): if self.dh.lower() == 'mdh': T,A,Aout = self.mdh_Transform(q) else: T,A,Aout = self.Transform(q) transl = self.t2transl(T) R = self.t2rot(T) r,p,y = self.r2rpy(R) rpy = [r,p,y] w_hat = self.angleRep(R) kinematics = fkine(T, A, Aout, transl, R, rpy, w_hat) return kinematics def angleRep(self, R): theta = np.arccos((R[0,0] + R[1,1] + R[2,2] - 1.0)/2.0) vec = np.array([(R[2,1] - R[1,2]),(R[0,2]-R[2,0]),(R[1,0]-R[0,1])]) w_hat = 1/(2*np.sin(theta)) * vec w_hat = np.array([theta * w_hat[0], theta * w_hat[1], theta * w_hat[2]]) return w_hat def jacobian(self, q): J = self.calcJac(q) return J def jacobianDot(self, q, qd): Jd = self.calcJacDot(q, qd) return Jd # Kinematics def mdh_Transform(rb, q): for j in range(rb.ndof): rb.joints[j].theta = q[j] A = [0 for i in range(rb.ndof)] alp = np.zeros(rb.ndof) a = np.zeros(rb.ndof) th = np.zeros(rb.ndof) d = np.zeros(rb.ndof) for i in range(rb.ndof): alp[i] = rb.joints[i].alpha a[i] = rb.joints[i].a th[i] = rb.joints[i].theta + rb.joints[i].offset d[i] = rb.joints[i].d T = np.identity(4) Aout = [] for i in range(rb.ndof): ct = np.cos(th[i]) st = np.sin(th[i]) ca = np.cos(alp[i]) sa = np.sin(alp[i]) A[i] = np.array([[ct, -st, 0, a[i]], [(st * ca), (ct * ca), -sa, (-d[i] * sa)], [(st * sa), (ct * sa), ca, (d[i] * ca)], [0, 0, 0, 1]]) Aout.append(np.dot(T, A[i])) T = np.dot(T, A[i]) return T, A, Aout def Transform(rb, q): for j in range(rb.ndof): rb.joints[j].theta = q[j] A = [0 for i in range(rb.ndof)] alp = np.zeros(rb.ndof) a = np.zeros(rb.ndof) th = np.zeros(rb.ndof) d = np.zeros(rb.ndof) # A = np.zeros(2) for i in range(rb.ndof): alp[i] = rb.joints[i].alpha a[i] = rb.joints[i].a th[i] = rb.joints[i].theta + rb.joints[i].offset d[i] = rb.joints[i].d T = np.identity(4) Aout = [] for i in range(rb.ndof): A[i] = np.array([[np.cos(th[i]), -np.sin(th[i]) * np.cos(alp[i]), np.sin(th[i]) * np.sin(alp[i]), a[i] * np.cos(th[i])], [np.sin(th[i]), np.cos(th[i]) * np.cos(alp[i]), -np.cos(th[i]) * np.sin(alp[i]), a[i] * np.sin(th[i])], [0, np.sin(alp[i]), np.cos(alp[i]), d[i]], [0, 0, 0, 1]]) Aout.append(np.dot(T, A[i])) T = np.dot(T, A[i]) return T, A, Aout def t2transl(self, T): transl = np.ravel(T[:3, 3]) return transl def t2rot(self, T): R = T[:3, :3] return R def r2eul(self, R): if (R[0,2] < np.finfo(float).eps and R[1,2] <np.finfo(float).eps): theta = 0 sp = 0 cp = 1 phi = np.arctan2(cp*R[0,2] + sp*R[1,2], R[2,2]) psi = np.arctan2(-sp*R[0,0] + cp*R[1,0], -sp*R[0,1] + cp*R[1,1]) else: # sin(theta) > 0 #theta = np.arctan2(R[2,2], np.sqrt(1 - (R[2,2]**2))) theta =
<reponame>xiaoxiaoxh/OMAD import argparse import numpy as np import os.path as osp import open3d as o3d import tqdm import copy import time import os import psutil import mmcv import torch.utils.data from matplotlib import cm import torch.multiprocessing as mp from scipy.spatial.transform import Rotation as R from dataset.dataset_omadnet import SapienDataset_OMADNet from model.omad_net import OMAD_Net from libs.utils import iou_3d, get_part_bbox_from_kp, get_part_bbox_from_corners, calc_joint_errors cate_list = ['laptop', 'eyeglasses', 'dishwasher', 'drawer', 'scissors'] def rot_diff_rad(rot1, rot2): if np.abs((np.trace(np.matmul(rot1, rot2.T)) - 1) / 2) > 1.: print('Something wrong in rotation error!') return np.arccos((np.trace(np.matmul(rot1, rot2.T)) - 1) / 2) % (2*np.pi) def rot_diff_degree(rot1, rot2): return rot_diff_rad(rot1, rot2) / np.pi * 180 class PoseEstimator(torch.nn.Module): def __init__(self, model, num_parts, num_kp, init_base_r, init_base_t, init_joint_state, init_beta, part_kp_weight, device, joint_type='revolute', reg_weight=0.0): super(PoseEstimator, self).__init__() self.model = model.to(device) self.model.eval() self.num_parts = num_parts self.num_kp = num_kp self.num_joints = num_parts - 1 self.device = device self.part_kp_weight = part_kp_weight self.joint_type = joint_type assert joint_type in ('revolute', 'prismatic') self.reg_weight = reg_weight x, y, z, w = R.from_matrix(init_base_r.cpu().numpy()).as_quat() self.base_r_quat = torch.nn.Parameter(torch.tensor( [w, x, y, z], device=device, dtype=torch.float), requires_grad=True) # q=a+bi+ci+di self.base_t = torch.nn.Parameter(init_base_t.clone().detach().to(device), requires_grad=True) self.joint_state = torch.nn.Parameter(init_joint_state.clone().detach().to(device), requires_grad=True) self.beta = torch.nn.Parameter(init_beta.clone().detach().to(device), requires_grad=True) def forward(self, pred_kp, mode='base'): assert mode in ('base', 'joint_single', 'all') norm_kp = self.model.get_norm_keypoints(self.beta)[0] # bs=1 homo_norm_kp = torch.cat([norm_kp, torch.ones(norm_kp.shape[0], norm_kp.shape[1], 1, device=norm_kp.device)], dim=-1) homo_pred_kp = torch.cat([pred_kp, torch.ones(pred_kp.shape[0], pred_kp.shape[1], 1, device=pred_kp.device)], dim=-1) base_r_quat = self.base_r_quat / torch.norm(self.base_r_quat) a, b, c, d = base_r_quat[0], base_r_quat[1], base_r_quat[2], base_r_quat[3] # q=a+bi+ci+di base_rot_matrix = torch.stack([1 - 2 * c * c - 2 * d * d, 2 * b * c - 2 * a * d, 2 * a * c + 2 * b * d, 2 * b * c + 2 * a * d, 1 - 2 * b * b - 2 * d * d, 2 * c * d - 2 * a * b, 2 * b * d - 2 * a * c, 2 * a * b + 2 * c * d, 1 - 2 * b * b - 2 * c * c]).reshape(3, 3) base_transform = torch.cat([torch.cat([base_rot_matrix, self.base_t.transpose(0, 1)], dim=1), torch.tensor([[0., 0., 0., 1.]], device=self.device)], dim=0) base_objective = torch.mean( torch.norm(base_transform.matmul(homo_norm_kp[0].T).T - homo_pred_kp[0], dim=-1) * self.part_kp_weight[0]) all_objective = base_objective norm_joint_loc_all, norm_joint_axis_all = self.model.get_norm_joint_params(self.beta) norm_joint_loc_all, norm_joint_axis_all = norm_joint_loc_all[0], norm_joint_axis_all[0] # bs=1 norm_joint_axis_all = norm_joint_axis_all / torch.norm(norm_joint_axis_all, dim=-1, keepdim=True) norm_joint_params_all = (norm_joint_loc_all.detach(), norm_joint_axis_all.detach()) new_joint_anchor_list = [] new_joint_axis_list = [] relative_transform_list = [] for joint_idx in range(self.num_joints): part_idx = joint_idx + 1 # TODO: support kinematic tree depth > 2 norm_joint_loc, norm_joint_axis = norm_joint_loc_all[joint_idx], norm_joint_axis_all[joint_idx] # bs=1 homo_joint_anchor = torch.cat([norm_joint_loc, torch.ones(1, device=self.device)]).unsqueeze(1) new_joint_anchor = base_transform.matmul(homo_joint_anchor)[:3, 0] new_joint_axis = base_rot_matrix.matmul(norm_joint_axis) a, b, c = new_joint_anchor[0], new_joint_anchor[1], new_joint_anchor[2] u, v, w = new_joint_axis[0], new_joint_axis[1], new_joint_axis[2] if self.joint_type == 'revolute': cos = torch.cos(-self.joint_state[joint_idx]) sin = torch.sin(-self.joint_state[joint_idx]) relative_transform = torch.cat([torch.stack([u*u+(v*v+w*w)*cos, u*v*(1-cos)-w*sin, u*w*(1-cos)+v*sin, (a*(v*v+w*w)-u*(b*v+c*w))*(1-cos)+(b*w-c*v)*sin, u*v*(1-cos)+w*sin, v*v+(u*u+w*w)*cos, v*w*(1-cos)-u*sin, (b*(u*u+w*w)-v*(a*u+c*w))*(1-cos)+(c*u-a*w)*sin, u*w*(1-cos)-v*sin, v*w*(1-cos)+u*sin, w*w+(u*u+v*v)*cos, (c*(u*u+v*v)-w*(a*u+b*v))*(1-cos)+(a*v-b*u)*sin]).reshape(3, 4), torch.tensor([[0., 0., 0., 1.]], device=self.device)], dim=0) elif self.joint_type == 'prismatic': relative_transform = torch.cat([torch.cat([torch.eye(3, device=self.device), (new_joint_axis*self.joint_state[joint_idx]).unsqueeze(1)], dim=1), torch.tensor([[0., 0., 0., 1.]], device=self.device)], dim=0) relative_transform_list.append(relative_transform.detach()) child_objective = torch.mean(torch.norm(relative_transform.matmul(base_transform).matmul(homo_norm_kp[part_idx].T).T - homo_pred_kp[part_idx], dim=-1) * self.part_kp_weight[part_idx]) all_objective += child_objective new_joint_anchor_list.append(new_joint_anchor.detach()) new_joint_axis_list.append(new_joint_axis.detach()) all_objective /= self.num_parts all_objective += (self.beta * self.beta).mean() * self.reg_weight # regularization loss new_joint_params_all = (torch.stack(new_joint_anchor_list, dim=0), torch.stack(new_joint_axis_list, dim=0)) relative_transform_all = torch.stack(relative_transform_list, dim=0) return all_objective, base_transform.detach(), relative_transform_all, \ new_joint_params_all, norm_joint_params_all, norm_kp.detach() def optimize_pose(estimator, pred_kp, rank=0, use_initial=False): estimator.base_r_quat.requires_grad_(True) estimator.base_t.requires_grad_(True) estimator.joint_state.requires_grad_(True) estimator.beta.requires_grad_(True) if use_initial: pass else: optimizer = torch.optim.Adam(estimator.parameters(), lr=1e-2) last_loss = 0. for iter in range(3000): # base transformation(r+t) + beta + joint state loss, _, _, _, _, _ = estimator(pred_kp.detach(), mode='all') if iter % 50 == 0: if rank == 0: print('base_r + base_t + joint state + beta: iter {}, loss={:05f}'.format(iter, loss.item())) if abs(last_loss - loss.item()) < 0.5*1e-3: break last_loss = loss.item() optimizer.zero_grad() loss.backward() optimizer.step() _, base_transform, relative_transform_all, new_joint_params_all, norm_joint_params_all, norm_kp = estimator(pred_kp.detach()) joint_state = estimator.joint_state.detach() beta = estimator.beta.detach() return base_transform, relative_transform_all, new_joint_params_all, norm_joint_params_all, norm_kp, joint_state, beta def get_new_part_kp(cloud, pred_trans_part_kp, thr=0.1, use_raw_kp=False): bs, n = cloud.size(0), cloud.size(1) num_parts, num_kp_per_part = pred_trans_part_kp.size(1), pred_trans_part_kp.size(2) num_kp = num_parts * num_kp_per_part pred_trans_kp = pred_trans_part_kp.detach().reshape(bs, 1, -1, 3) cloud_expand = cloud.detach().reshape(bs, n, 1, 3).expand(-1, -1, num_kp, -1) # (bs, n, m, 3) pred_trans_kp_expand = pred_trans_kp.expand(-1, n, -1, -1) # (bs, n, m, 3) dist_square = torch.sum((cloud_expand - pred_trans_kp_expand) ** 2, dim=-1) # (bs, n, m) min_dist_square, cloud_idxs = torch.min(dist_square, dim=1) # (bs, m) kp_weight = torch.sign(thr ** 2 - min_dist_square) * 0.5 + 0.5 # (bs, m) part_kp_weight = kp_weight.reshape(bs, num_parts, -1) # (bs, k, m/k) if use_raw_kp: new_part_kp = pred_trans_part_kp else: cloud_idxs_expand = cloud_idxs.unsqueeze(-1).expand(-1, -1, 3) # (bs, m, 3) new_kp = torch.gather(cloud.detach(), dim=1, index=cloud_idxs_expand) # (bs, m, 3) new_part_kp = new_kp.reshape(bs, num_parts, -1, 3) # (bs, k, m/k, 3) return new_part_kp, part_kp_weight def parallel_eval(pid, rank, results, model, opt, device): print() print('rank {} loading model sucessfully!'.format(rank)) print() all_eval_results = dict() pps = psutil.Process(pid=pid) if rank == 0: results = tqdm.tqdm(results) for result in results: try: if pps.status() in (psutil.STATUS_DEAD, psutil.STATUS_STOPPED): print('Parent Process {} has stopped, rank {} quit now!!'.format(pid, rank)) os._exit(0) sample_id = result['sample_id'] pred_cls = torch.from_numpy(result['pred_cls']).to(device) pred_trans_part_kp = torch.from_numpy(result['pred_trans_part_kp']).to(device) pred_base_r = torch.from_numpy(result['pred_base_r']).to(device) pred_base_t = torch.from_numpy(result['pred_base_t']).to(device) pred_joint_state = torch.from_numpy(result['pred_joint_state']).to(device) pred_beta = torch.from_numpy(result['pred_beta']).to(device) pred_norm_part_kp = torch.from_numpy(result['pred_norm_part_kp']).to(device) cloud = torch.from_numpy(result['cloud']).to(device) gt_part_r = torch.from_numpy(result['gt_part_r']).to(device) gt_part_t = torch.from_numpy(result['gt_part_t']).to(device) gt_norm_joint_loc = torch.from_numpy(result['gt_norm_joint_loc']).to(device) gt_norm_joint_axis = torch.from_numpy(result['gt_norm_joint_axis']).to(device) gt_joint_state = torch.from_numpy(result['gt_joint_state']).to(device)[1:] # ignore base joint gt_norm_part_kp = torch.from_numpy(result['gt_norm_part_kp']).to(device) gt_norm_part_corners = torch.from_numpy(result['gt_norm_part_corners']).to(device) cate = torch.from_numpy(result['cate']).to(device) urdf_id = torch.from_numpy(result['urdf_id']).to(device) new_pred_trans_part_kp, part_kp_weight = get_new_part_kp(cloud.unsqueeze(0), pred_trans_part_kp.unsqueeze(0), thr=opt.kp_thr, use_raw_kp=opt.use_raw_kp) init_part_kp_weight = part_kp_weight[0] new_pred_trans_part_kp = new_pred_trans_part_kp[0] if rank == 0: print() print('URDF id={}'.format(urdf_id)) print('{} valid keypoints!'.format(torch.sum(init_part_kp_weight).to(torch.int).item())) init_base_t = pred_base_t.unsqueeze(0) init_base_r = pred_base_r gt_trans_joint_anchor = [] gt_trans_joint_axis = [] gt_base_transform = torch.cat([torch.cat([gt_part_r[0, :, :], gt_part_t[0, :, :].transpose(0, 1)], dim=1), torch.tensor([[0., 0., 0., 1.]], device=device)], dim=0) for joint_idx in range(opt.num_parts - 1): homo_joint_anchor = torch.cat([gt_norm_joint_loc[joint_idx], torch.ones(1, device=device)]).unsqueeze(1) gt_trans_joint_anchor.append(gt_base_transform.matmul(homo_joint_anchor)[:3, 0]) gt_trans_joint_axis.append(gt_base_transform[:3, :3].matmul(gt_norm_joint_axis[joint_idx])) gt_trans_joint_anchor = torch.stack(gt_trans_joint_anchor, dim=0) gt_trans_joint_axis = torch.stack(gt_trans_joint_axis, dim=0) gt_r_list = [] gt_t_list = [] for part_idx in range(opt.num_parts): gt_r = gt_part_r[part_idx, :, :].cpu().numpy() gt_r_list.append(gt_r) gt_t = gt_part_t[part_idx, 0, :].cpu().numpy() gt_t_list.append(gt_t) gt_part_bbox = get_part_bbox_from_corners(gt_norm_part_corners) # TODO: support prismatic joints and kinematic tree depth > 2 num_joints = opt.num_parts - 1 init_joint_state = pred_joint_state joint_type = 'revolute' if opt.category != 4 else 'prismatic' if rank == 0: if joint_type == 'revolute': print('init_joint_state={} degree'.format((init_joint_state.cpu().numpy() / np.pi * 180).tolist())) else: print('init_joint_state={}'.format((init_joint_state.cpu().numpy()).tolist())) init_beta = pred_beta.unsqueeze(0) pose_estimator = PoseEstimator(model, opt.num_parts, opt.num_kp, init_base_r, init_base_t, init_joint_state, init_beta, init_part_kp_weight, device=device, joint_type=joint_type, reg_weight=opt.reg_weight) # ground-truth part-keypoint single_gt_trans_part_kp = torch.stack([gt_part_r[i, :, :].matmul(gt_norm_part_kp[i, :, :].T).T + gt_part_t[i, :, :] for i in range(opt.num_parts)], dim=0) if opt.use_gt_kp: base_transform, relative_transform_all, pred_trans_joint_params_all, pred_norm_joint_params_all, \ new_pred_norm_kp, new_pred_joint_state, new_pred_beta = optimize_pose(pose_estimator, single_gt_trans_part_kp, rank=rank, use_initial=opt.use_initial) else: base_transform, relative_transform_all, pred_trans_joint_params_all, pred_norm_joint_params_all, \ new_pred_norm_kp, new_pred_joint_state, new_pred_beta = optimize_pose(pose_estimator, new_pred_trans_part_kp, rank=rank, use_initial=opt.use_initial) pred_r_list = [base_transform[:3, :3].cpu().numpy()] + [ relative_transform_all[joint_idx].matmul(base_transform)[:3, :3].cpu().numpy() for joint_idx in range(num_joints)] pred_t_list = [base_transform[:3, -1].cpu().numpy()] + [ relative_transform_all[joint_idx].matmul(base_transform)[:3, -1].cpu().numpy() for joint_idx in range(num_joints)] pred_part_bbox = get_part_bbox_from_kp(new_pred_norm_kp) pred_norm_joint_loc, pred_norm_joint_axis = pred_norm_joint_params_all pred_trans_joint_loc, pred_trans_joint_axis = pred_trans_joint_params_all r_errs = [] t_errs = [] ious = [] for part_idx in range(opt.num_parts): r_err = rot_diff_degree(pred_r_list[part_idx], gt_r_list[part_idx]) t_err = np.linalg.norm(pred_t_list[part_idx] - gt_t_list[part_idx], axis=-1) iou = iou_3d(pred_part_bbox[part_idx], gt_part_bbox[part_idx]) if rank == 0: print('sample {}, urdf_id {}, part {}, r_error={:04f}, t_error={:04f}, iou_3d={:04f}'.format( sample_id, urdf_id, part_idx, r_err, t_err, iou)) r_errs.append(r_err) t_errs.append(t_err) ious.append(iou) joint_loc_errs = [] joint_axis_errs = [] joint_state_errs = [] for joint_idx in range(num_joints): joint_loc_err, joint_axis_err, joint_state_err = calc_joint_errors( pred_trans_joint_loc[joint_idx], pred_trans_joint_axis[joint_idx], gt_trans_joint_anchor[joint_idx], gt_trans_joint_axis[joint_idx], new_pred_joint_state[joint_idx], gt_joint_state[joint_idx], joint_type=joint_type) if rank == 0: print('sample {}, urdf_id {}, joint {}, (camera space) ' 'joint_loc_err={:4f}, joint_axis_err={:4f} degree, ' 'joint_state_err={:4f}'.format( sample_id, urdf_id, joint_idx, joint_loc_err, joint_axis_err, joint_state_err)) joint_loc_errs.append(joint_loc_err) joint_axis_errs.append(joint_axis_err) joint_state_errs.append(joint_state_err) if rank == 0 and opt.show: base_colors = np.array([(207/255, 37/255, 38/255), (28/255, 108/255, 171/255), (38/255, 148/255, 36/255), (254/255, 114/255, 16/255)] * 2) cmap = cm.get_cmap("jet", opt.num_kp) kp_colors = cmap(np.linspace(0, 1, opt.num_kp, endpoint=True))[:, :3] pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(cloud.cpu().numpy()) pcd.colors = o3d.utility.Vector3dVector(base_colors[pred_cls.numpy(), :]) pred_trans_static_kp_pcd_list = [] pred_kp_pcd_list = [] gt_kp_pcd_list = [] pred_trans_norm_kp_pcd_list = [] gt_trans_norm_kp_pcd_list = [] pred_trans_norm_kp_mesh_list = [] for part_idx in range(opt.num_parts): pred_trans_static_kp = (pred_r_list[part_idx] @ gt_norm_part_kp[part_idx, :, :].cpu().numpy().T + pred_t_list[part_idx][np.newaxis, :].T).T pred_trans_static_kp_pcd = o3d.geometry.PointCloud() pred_trans_static_kp_pcd.points = o3d.utility.Vector3dVector(pred_trans_static_kp) pred_trans_static_kp_pcd.paint_uniform_color([0, 0, 1]) pred_trans_static_kp_pcd_list.append(pred_trans_static_kp_pcd) pred_kp_pcd = o3d.geometry.PointCloud() pred_kp_pcd.points = o3d.utility.Vector3dVector( new_pred_trans_part_kp[part_idx, :,
# The 6.00 Word Game import random import string VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = "words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") # inFile: file inFile = open(WORDLIST_FILENAME, 'r') # wordList: list of strings wordList = [] for line in inFile: wordList.append(line.strip().lower()) print(" ", len(wordList), "words loaded.") return wordList def getFrequencyDict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x,0) + 1 return freq # (end of helper code) # ----------------------------------- # # Problem #1: Scoring a word # def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, PLUS 50 points if all n letters are used on the first turn. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES) word: string (lowercase letters) n: integer (HAND_SIZE; i.e., hand size required for additional points) returns: int >= 0 """ total_points = 0 for letter in word: total_points += SCRABBLE_LETTER_VALUES[letter] total_points *= len(word) if len(word) == n: total_points += 50 return total_points # # Problem #2: Make sure you understand how this function works and what it does! # def displayHand(hand): """ Displays the letters currently in the hand. For example: >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -> int) """ for letter in hand.keys(): for j in range(hand[letter]): print(letter,end=" ") # print all on the same line print() # print an empty line # # Problem #2: Make sure you understand how this function works and what it does! # def dealHand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. n: int >= 0 returns: dictionary (string -> int) """ hand={} numVowels = n // 3 for i in range(numVowels): x = VOWELS[random.randrange(0,len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(numVowels, n): x = CONSONANTS[random.randrange(0,len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand # # Problem #2: Update a hand by removing letters # def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ hand_copy = hand.copy() for letter in word: hand_copy[letter] = hand_copy.get(letter, 0) - 1 return hand_copy # # Problem #3: Test word validity # def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings """ if len(word) == 0: return False for letter in word: if word.count(letter) > hand.get(letter, 0) or word not in wordList: return False return True # # Problem #4: Playing a hand # def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ hand_len = 0 for frequency in hand.values(): hand_len += frequency return hand_len def playHand(hand, wordList, n): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word or a single period (the string ".") to indicate they're done playing * Invalid words are rejected, and a message is displayed asking the user to choose another word until they enter a valid word or "." * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters or the user inputs a "." hand: dictionary (string -> int) wordList: list of lowercase strings n: integer (HAND_SIZE; i.e., hand size required for additional points) """ acumulated_points = 0 number_of_remaining_letters = n # As long as there are still letters left in the hand: while number_of_remaining_letters > 0: # Display the hand print('Current hand: ', end='') displayHand(hand) # Ask user for input word = input('Enter word, or a "." to indicate that you are finished: ') # Otherwise (the input is not a single period): # Otherwise (the word is valid): if isValidWord(word, hand, wordList) == True: word_points = getWordScore(word, n) # Keep track of the total score acumulated_points += word_points # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line print('"{}" earned {}. Total: {} points\n'.format(word, word_points, acumulated_points)) # Update the hand hand = updateHand(hand, word) number_of_remaining_letters = calculateHandlen(hand) # End the game (break out of the loop) if number_of_remaining_letters == 0: print('Run out of letters. Total score: {} points.\n'.format(acumulated_points)) break # If the input is a single period: elif word == '.': # Game is over (user entered a '.' or ran out of letters), so tell user the total score print('Goodbye! Total score: {} points.\n'.format(acumulated_points)) break # If the word is not valid: else: # Reject invalid word (print a message followed by a blank line) print('Invalid word, please try again.\n') # # Problem #5: Playing a game # def playGame(wordList): """ Allow the user to play an arbitrary number of hands. 1) Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, tell them their input was invalid. 2) When done playing the hand, repeat from step 1 """ first_game = True while True: choice = input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ').lower().strip() if choice == 'n': hand = dealHand(HAND_SIZE) first_game = False elif choice == 'r': if first_game == True: print('You have not played a hand yet. Please play a new hand first!\n') continue elif choice == 'e': break else: print('Invalid command.') continue playHand(hand, wordList, HAND_SIZE) # # Build data structures used for entire session and
import discord import random from helpcommands import * from elo import * from datetime import datetime from random import shuffle,randint client = discord.Client() busyChannels = [] game = discord.Game(name="Perudo") diefaces = 6 #Number of faces on a die startingdice = 5 #How many dice each player starts with maxplayers = 6 #Maximum number of players @client.event async def on_ready(): print("Connected!") print("Username: " + client.user.name) print("ID: " + str(client.user.id)) await client.change_presence(activity = game) @client.event async def on_message(message): if message.author == client.user: return if message.content == "!hello": msg = "Greetings {0.author.mention}".format(message) await message.channel.send(msg) if message.content == "!perudo": if message.channel in busyChannels: await message.channel.send("Channel busy with another activity.") else: busyChannels.append(message.channel) await message.channel.send("Starting **Perudo** in `#"+message.channel.name+"`...") await perudo(client,message) busyChannels.remove(message.channel) if message.content == "!help": await helpcommand(client, message) if message.content == "!help abilities": await helpabilities(client, message) if message.content == "!rules": await rules(client, message) if message.content.startswith("!elo"): messagelist = message.content.split() if len(messagelist) > 1: messagemention = removeExclamation(messagelist[1]) else: messagemention = removeExclamation(message.author.mention) elovalue = fetchelo(messagemention) if elovalue == 0: await message.channel.send("Could not find an elo for this player.") else: await message.channel.send("{} has elo {}.".format(messagemention,elovalue)) async def perudo(client,message): #Declarations gamestate = 0 #State of game playerlist = [] #List of players freebidding = False #Can players bid freely, or are they restricted to BGA rules? calza = False #Can players call calza to gain dice? abilities = False #Do players have their special abilities? playerposition = [] #Position of each player (1 for first, 2 for second, and so on) activeplayerlist = [] #List of players who are still in playerdicenum = [] #Number of dice each player has playerdice = [] #Each player's dice playerabilities = [] #Each player's abilities (0 is not unlocked, 1 is unlocked, 2 is used) curplayer = 0 #Current player firstturn = True #Is this the first turn of the round? palifico = False #Is this a palifico round? currentbid = [] #Current bid (e.g.[5,6] means five sixes) if gamestate == 0: #Login phase gamestate,playerlist,freebidding,calza,abilities,playerposition,activeplayerlist,playerdicenum,playerabilities = await login(client,message) curplayer = 0 while gamestate == 2 or gamestate == 3: if gamestate == 2: #Rolling dice at start of round playerdice = await rolldice(client,message,activeplayerlist,playerdicenum,palifico) firstturn = True currentbid = [] gamestate = 3 if gamestate == 3: #Taking a turn gamestate,playerposition,activeplayerlist,playerdicenum,playerdice,playerabilities,curplayer,firstturn,palifico,currentbid = await taketurn(client,message,playerlist,freebidding,calza,abilities,playerposition,activeplayerlist,playerdicenum,playerdice,playerabilities,curplayer,firstturn,palifico,currentbid) if gamestate == 4: #End of game await gameend(client,message,playerlist,playerposition) #Login phase async def login(client,message): gamestate = 1 playerlist = [] freebidding = False calza = False abilities = False playerdicenum = [] playerabilities = [] await message.channel.send("```Login Phase Triggered```\nThe game of Perudo is about to begin.\n*Type !join to enter the game. (2-{} players only.)*\n".format(maxplayers)) while gamestate == 1: def channel_check(m): return m.channel == message.channel reply = await client.wait_for("message", check=channel_check) if reply.content == "!join": if len(playerlist) <= maxplayers: if reply.author not in playerlist: await message.channel.send("{} has joined the game.".format(reply.author.display_name)) playerlist.append(reply.author) else: await message.channel.send("{} is already in the game.".format(reply.author.display_name)) else: await message.channel.send("The game is full.") if reply.content == "!quit": if reply.author in playerlist: await message.channel.send("{} has left the game.".format(reply.author.display_name)) playerlist.remove(reply.author) else: await message.channel.send("{} wasn't in the game.".format(reply.author.display_name)) if reply.content == "!stop" and reply.author in playerlist: await message.channel.send("The game has been stopped.") gamestate = 0 replylist = reply.content.split() if replylist[0] == "!start" and reply.author in playerlist: if len(playerlist) < 2: await message.channel.send("Not enough players.") else: gamemodestr = "" if "freebidding" in replylist: freebidding = True gamemodestr = gamemodestr + "Free bidding, " if "calza" in replylist: calza = True gamemodestr = gamemodestr + "Calza, " if "abilities" in replylist: abilities = True gamemodestr = gamemodestr + "Special abilities, " for i in range(len(playerlist)): playerabilities.append([0,0,0]) gamemodestr = gamemodestr.rstrip(", ") if gamemodestr != "": gamemodestr = " ({})".format(gamemodestr) random.seed(datetime.now()) shuffle(playerlist) playerposition = [1] * len(playerlist) activeplayerlist = playerlist.copy() playerdicenum = [startingdice] * len(playerlist) await message.channel.send("Game started!{}".format(gamemodestr)) gamestate = 2 return gamestate,playerlist,freebidding,calza,abilities,playerposition,activeplayerlist,playerdicenum,playerabilities async def rolldice(client,message,activeplayerlist,playerdicenum,palifico): #Rolls dice and shows each player their dice playerdice = [] for i in range(len(activeplayerlist)): playerdice.append([]) for j in range(playerdicenum[i]): playerdice[i].append(randint(1,diefaces)) playerdice[i].sort() dicestr = "" for j in range(len(playerdice[i])): dicestr = dicestr + str(playerdice[i][j]) + ", " dicestr = dicestr.rstrip(", ") await activeplayerlist[i].send("You rolled:\n{}".format(dicestr)) #Displays message at start of each round messagestring = "Dice have been rolled for the start of this round.\n" for i in range(len(activeplayerlist)): messagestring = messagestring + "{} has {} dice\n".format(activeplayerlist[i].display_name,playerdicenum[i]) if palifico: messagestring = messagestring + "This is a palifico round!" await message.channel.send(messagestring) return playerdice async def taketurn(client,message,playerlist,freebidding,calza,abilities,playerposition,activeplayerlist,playerdicenum,playerdice,playerabilities,curplayer,firstturn,palifico,currentbid): def player_check(m): if m.channel == message.channel and m.author in activeplayerlist: return True return False #Function for revealing counting dice at end of round async def diecount(client,message,activeplayerlist,playerdice,palifico,currentbid): messagestring = "" numdice = [0] * diefaces for i in range(len(activeplayerlist)): playerstr = "" for j in range(len(playerdice[i])): playerstr = playerstr + str(playerdice[i][j]) + ", " numdice[playerdice[i][j]-1] += 1 playerstr = playerstr.rstrip(", ") messagestring = messagestring + "{} had {}\n".format(activeplayerlist[i].display_name,playerstr) await message.channel.send(messagestring) if currentbid[1] == 1 or palifico: numofbid = numdice[currentbid[1]-1] else: numofbid = numdice[0] + numdice[currentbid[1]-1] await message.channel.send("There were {} {}s!".format(numofbid,currentbid[1])) return numofbid await message.channel.send("It is {}'s turn.".format(activeplayerlist[curplayer].display_name)) waiting = True while waiting: command = await client.wait_for('message', check=player_check) losingplayer = 0 playerlosedie = False #Did someone lose a die? #Check for calza if command.content == "calza": if not calza: await message.channel.send("Calling calza is disabled.") continue if firstturn: await message.channel.send("You cannot call calza on the first turn.") continue if command.author == activeplayerlist[curplayer-1]: await message.channel.send("You cannot call calza on your own bid.") continue numofbid = await diecount(client,message,activeplayerlist,playerdice,palifico,currentbid) prevplayer = curplayer - 1 for i in range(len(activeplayerlist)): if command.author == activeplayerlist[i]: curplayer = i if currentbid[0] == numofbid: await message.channel.send("{} called calza successfully on {}!".format(activeplayerlist[curplayer].display_name,activeplayerlist[prevplayer].display_name)) newdicenum = playerdicenum[curplayer]+1 if newdicenum > startingdice: newdicenum = startingdice await message.channel.send("{} was at the maximum number of dice and thus has {} dice.".format(activeplayerlist[curplayer].display_name,newdicenum)) else: await message.channel.send("{} has gained a die and now has {} dice.".format(activeplayerlist[curplayer].display_name,newdicenum)) playerdicenum[curplayer] = newdicenum gamestate = 2 palifico = False break else: losingplayer = curplayer await message.channel.send("{} called calza unsuccessfully on {}!".format(activeplayerlist[curplayer].display_name,activeplayerlist[prevplayer].display_name)) playerlosedie = True if command.author != activeplayerlist[curplayer]: await message.channel.send("It is not your turn!") continue #Check for dudo if command.content == "dudo": if firstturn: await message.channel.send("You cannot call dudo on the first turn.") continue #Dudo has been called! Reveal everyone's dice numofbid = await diecount(client,message,activeplayerlist,playerdice,palifico,currentbid) prevplayer = curplayer - 1 if currentbid[0] > numofbid: losingplayer = prevplayer await message.channel.send("{} called dudo successfully on {}!".format(activeplayerlist[curplayer].display_name,activeplayerlist[prevplayer].display_name)) else: losingplayer = curplayer await message.channel.send("{} called dudo unsuccessfully on {}!".format(activeplayerlist[curplayer].display_name,activeplayerlist[prevplayer].display_name)) playerlosedie = True #If someone lost a die if playerlosedie: newdicenum = playerdicenum[losingplayer]-1 playerdicenum[losingplayer] = newdicenum await message.channel.send("{} has lost a die and now has {} dice.".format(activeplayerlist[losingplayer].display_name,newdicenum)) if newdicenum == 1: palifico = True else: palifico = False #Do they gain abilities? if abilities: if newdicenum == 3 and playerabilities[losingplayer][0] == 0: await message.channel.send("{} unlocked the ability to match the previous bid! (Type \"match\" to use.)".format(activeplayerlist[losingplayer].display_name)) playerabilities[losingplayer][0] = 1 if newdicenum == 2 and playerabilities[losingplayer][1] == 0: await message.channel.send("{} unlocked the ability to reroll their own dice! (Type \"reroll\" to use.)".format(activeplayerlist[losingplayer].display_name)) playerabilities[losingplayer][1] = 1 if newdicenum == 1 and playerabilities[losingplayer][2] == 0: await message.channel.send("{} unlocked the ability to see another player's dice! (Type \"see @playername\" to use.)".format(activeplayerlist[losingplayer].display_name)) playerabilities[losingplayer][2] = 1 curplayer = losingplayer if newdicenum == 0: await message.channel.send("{} is out of the game!".format(activeplayerlist[losingplayer].display_name)) actualplayer = 0 for i in range(len(playerlist)): if playerlist[i] == activeplayerlist[curplayer]: actualplayer = i playerposition[actualplayer] = len(activeplayerlist) activeplayerlist.pop(curplayer) playerdicenum.pop(curplayer) if abilities: playerabilities.pop(curplayer) if curplayer == len(activeplayerlist) or curplayer == -1: curplayer = 0 if len(activeplayerlist) == 1: gamestate = 4 else: gamestate = 2 break commandlist = command.content.split() #Check for use of abilities #Match bid: if command.content == "match": if not abilities: await message.channel.send("Abilities are disabled.") continue if playerabilities[curplayer][0] == 0: await message.channel.send("You have not yet unlocked this ability.") continue if playerabilities[curplayer][0] == 2: await message.channel.send("You have already used this ability.") continue if firstturn: await message.channel.send("You cannot match on the first turn.") continue await message.channel.send("{} matched the previous bid!".format(activeplayerlist[curplayer].display_name)) playerabilities[curplayer][0] = 2 gamestate = 3 firstturn = False curplayer += 1 if curplayer == len(activeplayerlist): curplayer = 0
from datetime import date, datetime, timedelta from markdown import markdown import json import time from django.core.cache import cache from django.core.mail import EmailMessage, send_mail from django.core.urlresolvers import reverse from django.db import models from django.db.models import Max, Min, Q from django.utils import timezone from django.utils.encoding import force_unicode from stdimage import StdImageField import tweepy from gcal.apiclient.errors import HttpError from event_cal.gcal_functions import get_credentials, get_authorized_http from event_cal.gcal_functions import get_service from mig_main.models import AcademicTerm, OfficerPosition, MemberProfile from mig_main.models import UserProfile from requirements.models import Requirement from migweb.settings import DEBUG, twitter_token, twitter_secret COE_EVENT_EMAIL_BODY = r'''%(salutation)s, %(intro_text)s **Contact Information** Uniqname: %(leader_uniq)s Full Name: %(leader_name)s Department: Student Organization Telephone Email Address: %(leader_email)s **Submit a new Request** Name Of Event: %(event_name)s **Event Information** Short Description: %(blurb)s Type of Event: %(event_type)s (may not be the same as for the COE calendar) If Type of Event is 'Other', specify here Event Date: %(date)s Start Time: %(start_time)s End Time: %(end_time)s Multi-Day Event? Enter Additional Dates + Times: %(mult_shift)s Location: %(location)s RSVP Link (optional): https://tbp.engin.umich.edu%(event_link)s Contact Person: Use official contact person Department/Host: Student Organization Description of Event: %(description)s More information can be found at https://tbp.engin.umich.edu%(event_link)s Regards, The Website Note: This is an automated email. Please do not reply to it as responses are not checked. ''' COE_EVENT_BODY_CANCEL = r'''%(salutation)s, The event %(event_name)s is no longer listed as needing a COE Calendar Event. The event information can be found at https://tbp.engin.umich.edu%(event_link)s Regards, The Website Note: This is an automated email. Please do not reply to it as responses are not checked. ''' # Create your models here. def default_term(): """ Returns the current term. Fixes a serialization issue that results from circular references in migrations. """ try: return AcademicTerm.get_current_term().id except: return 1 class GoogleCalendar(models.Model): """ Represents an actual calendar on google calendar. This is a mostly infrastructural model that contains the name and calendar ID attribute of a calendar that is used by the chapter (currently those managed by <EMAIL>). """ calendar_id = models.CharField(max_length=100) display_order = models.PositiveSmallIntegerField(default=0) name = models.CharField(max_length=40) def __unicode__(self): return self.name class EventClass(models.Model): """A type of event. Basically, this is a type of event that gets held semester after semester, while a CalendarEvent is the particular event that happens on a specified date/time. This is used to help group events by type of event. """ name = models.CharField(max_length=64) def __unicode__(self): return self.name class CalendarEvent(models.Model): """ An event on the TBP calendar. This class captures the essential bits of the event (without tackling the details of time and place). It details what types of requirements the event can fill, who the leaders are, whether it has been completed, how to publicize it, what term it is during, whether to restrict to members only, and more as detailed by the fairly clearly named fields. """ agenda = models.ForeignKey('history.MeetingMinutes', null=True, blank=True) allow_advance_sign_up = models.BooleanField(default=True) allow_overlapping_sign_ups = models.BooleanField(default=False) announce_start = models.DateField( verbose_name='Date to start including in announcements', default=date.today ) announce_text = models.TextField('Announcement Text') assoc_officer = models.ForeignKey('mig_main.OfficerPosition') completed = models.BooleanField( 'Event completed and progress assigned?', default=False ) description = models.TextField('Event Description') event_type = models.ForeignKey('requirements.EventCategory') event_class = models.ForeignKey( EventClass, verbose_name=('Choose the event \"class\" ' 'from the list below. If the event is ' 'not listed, leave this blank'), null=True, blank=True, ) google_cal = models.ForeignKey(GoogleCalendar) leaders = models.ManyToManyField( 'mig_main.MemberProfile', related_name="event_leader" ) members_only = models.BooleanField(default=True) min_sign_up_notice = models.PositiveSmallIntegerField( 'Block sign-up how many hours before event starts?', default=0 ) min_unsign_up_notice = models.PositiveSmallIntegerField( 'Block unsign-up how many hours before event starts?', default=12 ) mutually_exclusive_shifts = models.BooleanField(default=False) name = models.CharField('Event Name', max_length=50) needs_carpool = models.BooleanField(default=False) needs_COE_event = models.BooleanField(default=False) needs_facebook_event = models.BooleanField(default=False) needs_flyer = models.BooleanField(default=False) preferred_items = models.TextField( ('List any (nonobvious) items that attendees should ' 'bring, they will be prompted to see if they can.'), null=True, blank=True ) project_report = models.ForeignKey( 'history.ProjectReport', null=True, blank=True, on_delete=models.SET_NULL ) requires_AAPS_background_check = models.BooleanField(default=False) requires_UM_background_check = models.BooleanField(default=False) term = models.ForeignKey('mig_main.AcademicTerm', default=default_term) use_sign_in = models.BooleanField(default=False) # Static attributes. before_grace = timedelta(minutes=-30) after_grace = timedelta(hours=1) # Shift aggregations to speed querying earliest_start = models.DateTimeField(default=datetime.now) latest_end = models.DateTimeField(default=datetime.now) # To support active-status emails active_status_email_sent = models.BooleanField(default=False) @classmethod def get_current_meeting_query(cls): """ Returns a Q object for the query for meetings happening now.""" now = timezone.localtime(timezone.now()) query = ( Q(use_sign_in=True) & Q(eventshift__end_time__gte=(now-cls.after_grace)) & Q(eventshift__start_time__lte=(now-cls.before_grace)) ) return query @classmethod def get_current_term_events_alph(cls): """Returns the current term events ordered alphabetically.""" current_term = AcademicTerm.get_current_term() return cls.get_term_events_alph(current_term) @classmethod def get_current_term_events_rchron(cls): """ Returns the current term events ordered reverse-chronologically.""" current_term = AcademicTerm.get_current_term() return cls.get_term_events_rchron(current_term) @classmethod def get_events_w_o_reports(cls, term): """ Returns a queryset of events in 'term' that lack project reports. Finds all events for the given term that have been marked as completed but for which there is no project report. """ events = cls.objects.filter(term=term, project_report=None, completed=True ) return events @classmethod def get_pending_events(cls): """ Returns a queryset of uncompleted events in the past. Finds all events where all the shifts have passed but the event is not yet marked as completed. """ now = timezone.localtime(timezone.now()) evts = cls.objects.annotate(latest_shift=Max('eventshift__end_time')) return evts.filter(latest_shift__lte=now, completed=False) @classmethod def get_term_events_alph(cls, term): """Returns the provided term's events ordered alphabetically.""" return cls.objects.filter(term=term).order_by('name') @classmethod def get_term_events_rchron(cls, term): """Returns the provided term's events ordered reverse-chronologically. """ evts = cls.objects.filter(term=term) an_evts = evts.annotate(earliest_shift=Min('eventshift__start_time')) return an_evts.order_by('earliest_shift') @classmethod def get_upcoming_events(cls, reset=False): """ Returns a queryset of upcoming events. Returns all events that are upcoming or are happening now and have sign-in enabled. In this context 'upcoming' is determined by the event start time and the announcement start date. Namely if an event has a start time in the future and an announcement start date in the past (or present), it is considered upcoming. It is thus possible that some events will be incorrectly (albeit intentionally) skipped if they have announcement start dates set for after the event commences. If reset is False, it pulls the upcoming events from the cache (provided they exist in the cache). Otherwise it assembles them from the database and stores them in the cache prior to returning. """ upcoming_events = cache.get('upcoming_events', None) if upcoming_events and not reset: return upcoming_events now = timezone.localtime(timezone.now()) today = date.today() non_meeting_query = ( Q(eventshift__start_time__gte=now) & Q(announce_start__lte=today) ) meeting_query = cls.get_current_meeting_query() not_officer_meeting = ~Q(event_type__name='Officer Meetings') event_pool = cls.objects.filter( (non_meeting_query | meeting_query) & not_officer_meeting ) an_evts = event_pool.distinct().annotate( earliest_shift=Min('eventshift__start_time') ) upcoming_events = an_evts.order_by('earliest_shift') cache.set('upcoming_events', upcoming_events) return upcoming_events # Instance Methods, built-ins def save(self, *args, **kwargs): """ Saves the event. Also clears the cache entry for its ajax.""" if self.eventshift_set.exists(): shifts = self.eventshift_set.all() self.earliest_start = shifts.order_by('start_time')[0].start_time self.latest_end = shifts.order_by('-end_time')[0].end_time super(CalendarEvent, self).save(*args, **kwargs) cache.delete('EVENT_AJAX'+unicode(self.id)) def delete(self, *args, **kwargs): """ Deletes the event. Also clears the cache entry for its ajax.""" cache.delete('EVENT_AJAX'+unicode(self.id)) super(CalendarEvent, self).delete(*args, **kwargs) def __unicode__(self): """ Returns a string representation of the event. For use in the admin or in times the event is interpreted as a string. """ return self.name def get_relevant_event_type(self, status, standing): """ Returns the event type that the event satisfies. For a given status and standing, this determines the type of requirement that will be filled by attending this event. Since requirements are assumed to be hierarchical, this essentially traverses upward until it finds an event category listed in the requirements associated with that status and standing. If it finds none it assumes that this event won't fill any events and so the original event category is used. """ requirements = Requirement.objects.filter( distinction_type__status_type__name=status, distinction_type__standing_type__name=standing, term=self.term.semester_type ) ev_category = self.event_type while(not requirements.filter(event_category=ev_category).exists() and ev_category.parent_category is not None ): ev_category = ev_category.parent_category return ev_category def get_relevant_active_event_type(self): """ Returns the event type that matters for an active member. Templates don't allow methods to have arguments, so this unfortunately bakes the argument into the method name. Determines what event category should be displayed for an active member based on their requirements. This assumes that all actives have the same requirements regardless of Standing. It will break if that changes. """ return self.get_relevant_event_type('Active', 'Undergraduate') def get_relevant_ugrad_electee_event_type(self): """ Returns the event type that matters for an undergraduate electee. Templates don't allow methods to have arguments, so this unfortunately bakes the argument into the method name. Determines what event category should be displayed for an undergraduate electee based on their requirements. """ return self.get_relevant_event_type('Electee', 'Undergraduate') def get_relevant_grad_electee_event_type(self): """ Returns the event type that matters for a graduate student electee. Templates don't allow methods to have arguments, so this unfortunately bakes the argument
<filename>swift/internal/providers.bzl # Copyright 2018 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Defines Skylark providers that propagated by the Swift BUILD rules.""" SwiftInfo = provider( doc = """\ Contains information about the compiled artifacts of a Swift module. This provider contains a large number of fields and many custom rules may not need to set all of them. Instead of constructing a `SwiftInfo` provider directly, consider using the `swift_common.create_swift_info` function, which has reasonable defaults for any fields not explicitly set. """, fields = { "direct_defines": """\ `List` of `string`s. The values specified by the `defines` attribute of the library that directly propagated this provider. """, "direct_swiftdocs": """\ `List` of `File`s. The Swift documentation (`.swiftdoc`) files for the library that directly propagated this provider. """, "direct_swiftmodules": """\ `List` of `File`s. The Swift modules (`.swiftmodule`) for the library that directly propagated this provider. """, "module_name": """\ `String`. The name of the Swift module represented by the target that directly propagated this provider. This field will be equal to the explicitly assigned module name (if present); otherwise, it will be equal to the autogenerated module name. """, "swift_version": """\ `String`. The version of the Swift language that was used when compiling the propagating target; that is, the value passed via the `-swift-version` compiler flag. This will be `None` if the flag was not set. """, "transitive_defines": """\ `Depset` of `string`s. The transitive `defines` specified for the library that propagated this provider and all of its dependencies. """, "transitive_generated_headers": """\ `Depset` of `File`s. The transitive generated header files that can be used by Objective-C sources to interop with the transitive Swift libraries. """, "transitive_modulemaps": """\ `Depset` of `File`s. The transitive module map files that will be passed to Clang using the `-fmodule-map-file` option. """, "transitive_swiftdocs": """\ `Depset` of `File`s. The transitive Swift documentation (`.swiftdoc`) files emitted by the library that propagated this provider and all of its dependencies. """, "transitive_swiftinterfaces": """\ `Depset` of `File`s. The transitive Swift interface (`.swiftinterface`) files emitted by the library that propagated this provider and all of its dependencies. """, "transitive_swiftmodules": """\ `Depset` of `File`s. The transitive Swift modules (`.swiftmodule`) emitted by the library that propagated this provider and all of its dependencies. """, }, ) SwiftProtoInfo = provider( doc = "Propagates Swift-specific information about a `proto_library`.", fields = { "module_mappings": """\ `Sequence` of `struct`s. Each struct contains `module_name` and `proto_file_paths` fields that denote the transitive mappings from `.proto` files to Swift modules. This allows messages that reference messages in other libraries to import those modules in generated code. """, "pbswift_files": """\ `Depset` of `File`s. The transitive Swift source files (`.pb.swift`) generated from the `.proto` files. """, }, ) SwiftToolchainInfo = provider( doc = """ Propagates information about a Swift toolchain to compilation and linking rules that use the toolchain. """, fields = { "action_configs": """\ This field is an internal implementation detail of the build rules. """, "all_files": """\ A `depset` of `File`s containing all the Swift toolchain files (tools, libraries, and other resource files) so they can be passed as `tools` to actions using this toolchain. """, "cc_toolchain_info": """\ The `cc_common.CcToolchainInfo` provider from the Bazel C++ toolchain that this Swift toolchain depends on. """, "command_line_copts": """\ `List` of `strings`. Flags that were passed to Bazel using the `--swiftcopt` command line flag. These flags have the highest precedence; they are added to compilation command lines after the toolchain default flags (`SwiftToolchainInfo.swiftc_copts`) and after flags specified in the `copts` attributes of Swift targets. """, "cpu": """\ `String`. The CPU architecture that the toolchain is targeting. """, "linker_opts_producer": """\ Skylib `partial`. A partial function that returns the flags that should be passed to Clang to link a binary or test target with the Swift runtime libraries. The partial should be called with two arguments: * `is_static`: A `Boolean` value indicating whether to link against the static or dynamic runtime libraries. * `is_test`: A `Boolean` value indicating whether the target being linked is a test target. """, "object_format": """\ `String`. The object file format of the platform that the toolchain is targeting. The currently supported values are `"elf"` and `"macho"`. """, "optional_implicit_deps": """\ `List` of `Target`s. Library targets that should be added as implicit dependencies of any `swift_library`, `swift_binary`, or `swift_test` target that does not have the feature `swift.minimal_deps` applied. """, "requested_features": """\ `List` of `string`s. Features that should be implicitly enabled by default for targets built using this toolchain, unless overridden by the user by listing their negation in the `features` attribute of a target/package or in the `--features` command line flag. These features determine various compilation and debugging behaviors of the Swift build rules, and they are also passed to the C++ APIs used when linking (so features defined in CROSSTOOL may be used here). """, "required_implicit_deps": """\ `List` of `Target`s. Library targets that should be unconditionally added as implicit dependencies of any `swift_library`, `swift_binary`, or `swift_test` target. """, "root_dir": """\ `String`. The workspace-relative root directory of the toolchain. """, "stamp_producer": """\ Skylib `partial`. A partial function that compiles build data that should be stamped into binaries. This value may be `None` if the toolchain does not support link stamping. The `swift_binary` and `swift_test` rules call this function _whether or not_ link stamping is enabled for that target. This provides toolchains the option of still linking fixed placeholder data into the binary if desired, instead of linking nothing at all. Whether stamping is enabled can be checked by inspecting `ctx.attr.stamp` inside the partial's implementation. The rule implementation will call this partial and pass it the following four arguments: * `ctx`: The rule context of the target being built. * `cc_feature_configuration`: The C++ feature configuration to use when compiling the stamp code. * `cc_toolchain`: The C++ toolchain (`CcToolchainInfo` provider) to use when compiling the stamp code. * `binary_path`: The short path of the binary being linked. The partial should return a `CcLinkingContext` containing the data (such as object files) to be linked into the binary, or `None` if nothing should be linked into the binary. """, "supports_objc_interop": """\ `Boolean`. Indicates whether or not the toolchain supports Objective-C interop. """, "swift_worker": """\ `File`. The executable representing the worker executable used to invoke the compiler and other Swift tools (for both incremental and non-incremental compiles). """, "system_name": """\ `String`. The name of the operating system that the toolchain is targeting. """, "test_configuration": """\ `Struct` containing two fields: * `env`: A `dict` of environment variables to be set when running tests that were built with this toolchain. * `execution_requirements`: A `dict` of execution requirements for tests that were built with this toolchain. This is used, for example, with Xcode-based toolchains to ensure that the `xctest` helper and coverage tools are found in the correct developer directory when running tests. """, "tool_configs": """\ This field is an internal implementation detail of the build rules. """, "unsupported_features": """\ `List` of `string`s. Features that should be implicitly disabled by default for targets built using this toolchain, unless overridden by the user by listing them in the `features` attribute of a target/package or in the `--features` command line flag. These features determine various compilation and debugging behaviors of the Swift build rules, and they are also passed to the C++ APIs used when linking (so features defined in CROSSTOOL may be used here). """, }, ) SwiftUsageInfo = provider( doc = """\ A provider that indicates that Swift was used by a target or any target that it depends on, and specifically which toolchain was used. """, fields = { "toolchain": """\ The Swift toolchain that was used to build the targets propagating this provider. """, }, ) def create_swift_info( defines = [], generated_headers = [], modulemaps = [], module_name = None, swiftdocs = [], swiftmodules = [], swiftinterfaces = [], swift_infos = [], swift_version = None): """Creates a new `SwiftInfo` provider with the given values. This function is recommended instead of directly creating a `SwiftInfo` provider because it encodes reasonable defaults for fields that some rules may not be interested in and ensures that the direct and transitive fields are set consistently. This function can also be used to do a simple merge of `SwiftInfo` providers, by leaving all of the arguments except for `swift_infos` as their empty defaults. In that
each layer of the GraphSAGE model. The supplied graph should be a StellarGraph object with node features for all node types. Use the :meth:`flow` method supplying the nodes and (optionally) targets to get an object that can be used as a Keras data generator. The generator should be given the ``(src,dst)`` node types using * It's possible to do link prediction on a graph where that link type is completely removed from the graph (e.g., "same_as" links in ER) .. seealso:: Model using this generator: :class:`.HinSAGE`. Example using this generator: `link prediction <https://stellargraph.readthedocs.io/en/stable/demos/link-prediction/hinsage-link-prediction.html>`__. Related functionality: - :class:`.UnsupervisedSampler` for unsupervised training using random walks - :class:`.HinSAGENodeGenerator` for node classification and related tasks - :class:`.GraphSAGELinkGenerator` for homogeneous graphs - :class:`.DirectedGraphSAGELinkGenerator` for directed homogeneous graphs Args: g (StellarGraph): A machine-learning ready graph. batch_size (int): Size of batch of links to return. num_samples (list): List of number of neighbour node samples per GraphSAGE layer (hop) to take. head_node_types (list, optional): List of the types (str) of the two head nodes forming the node pair. This does not need to be specified if ``G`` has only one node type. seed (int or str, optional): Random seed for the sampling methods. Example:: G_generator = HinSAGELinkGenerator(G, 50, [10,10]) data_gen = G_generator.flow(edge_ids) """ def __init__( self, G, batch_size, num_samples, head_node_types=None, schema=None, seed=None, name=None, ): super().__init__(G, batch_size, schema) self.num_samples = num_samples self.name = name # This is a link generator and requires two nodes per query if head_node_types is None: # infer the head node types, if this is a homogeneous-node graph node_type = G.unique_node_type( "head_node_types: expected a pair of head node types because G has more than one node type, found node types: %(found)s" ) head_node_types = [node_type, node_type] self.head_node_types = head_node_types if len(self.head_node_types) != 2: raise ValueError( "The head_node_types should be of length 2 for a link generator" ) # Create sampling schema self._sampling_schema = self.schema.sampling_layout( self.head_node_types, self.num_samples ) self._type_adjacency_list = self.schema.type_adjacency_list( self.head_node_types, len(self.num_samples) ) # The sampler used to generate random samples of neighbours self.sampler = SampledHeterogeneousBreadthFirstWalk( G, graph_schema=self.schema, seed=seed ) def _get_features(self, node_samples, head_size, use_ilocs=False): """ Collect features from sampled nodes. Args: node_samples: A list of lists of node IDs head_size: The number of head nodes (typically the batch size). Returns: A list of numpy arrays that store the features for each head node. """ # Note the if there are no samples for a node a zero array is returned. # Resize features to (batch_size, n_neighbours, feature_size) # for each node type (note that we can have different feature size for each node type) batch_feats = [ self.graph.node_features(layer_nodes, nt, use_ilocs=use_ilocs) for nt, layer_nodes in node_samples ] # Resize features to (batch_size, n_neighbours, feature_size) batch_feats = [np.reshape(a, (head_size, -1, a.shape[1])) for a in batch_feats] return batch_feats def sample_features(self, head_links, batch_num): """ Sample neighbours recursively from the head nodes, collect the features of the sampled nodes, and return these as a list of feature arrays for the GraphSAGE algorithm. Args: head_links (list): An iterable of edges to perform sampling for. batch_num (int): Batch number Returns: A list of the same length as `num_samples` of collected features from the sampled nodes of shape: ``(len(head_nodes), num_sampled_at_layer, feature_size)`` where ``num_sampled_at_layer`` is the cumulative product of `num_samples` for that layer. """ nodes_by_type = [] for ii in range(2): # Extract head nodes from edges: each edge is a tuple of 2 nodes, so we are extracting 2 head nodes per edge head_nodes = [e[ii] for e in head_links] # Get sampled nodes for the subgraphs starting from the (src, dst) head nodes # nodes_samples is list of two lists: [[samples for src], [samples for dst]] node_samples = self.sampler.run( nodes=head_nodes, n=1, n_size=self.num_samples ) # Reshape node samples to the required format for the HinSAGE model # This requires grouping the sampled nodes by edge type and in order nodes_by_type.append( [ ( nt, reduce( operator.concat, (samples[ks] for samples in node_samples for ks in indices), [], ), ) for nt, indices in self._sampling_schema[ii] ] ) # Interlace the two lists, nodes_by_type[0] (for src head nodes) and nodes_by_type[1] (for dst head nodes) nodes_by_type = [ tuple((ab[0][0], reduce(operator.concat, (ab[0][1], ab[1][1])))) for ab in zip(nodes_by_type[0], nodes_by_type[1]) ] batch_feats = self._get_features(nodes_by_type, len(head_links), use_ilocs=True) return batch_feats class Attri2VecLinkGenerator(BatchedLinkGenerator): """ A data generator for context node prediction with the attri2vec model. At minimum, supply the StellarGraph and the batch size. The supplied graph should be a StellarGraph object with node features. Use the :meth:`flow` method supplying the nodes and targets, or an UnsupervisedSampler instance that generates node samples on demand, to get an object that can be used as a Keras data generator. Example:: G_generator = Attri2VecLinkGenerator(G, 50) train_data_gen = G_generator.flow(edge_ids, edge_labels) .. seealso:: Model using this generator: :class:`.Attri2Vec`. An example using this generator (see the model for more): `link prediction <https://stellargraph.readthedocs.io/en/stable/demos/link-prediction/attri2vec-link-prediction.html>`__. Related functionality: - :class:`.UnsupervisedSampler` for unsupervised training using random walks - :class:`.Attri2VecNodeGenerator` for node classification and related tasks Args: G (StellarGraph): A machine-learning ready graph. batch_size (int): Size of batch of links to return. name, optional: Name of generator. """ def __init__(self, G, batch_size, name=None): super().__init__(G, batch_size) self.name = name def sample_features(self, head_links, batch_num): """ Sample content features of the target nodes and the ids of the context nodes and return these as a list of feature arrays for the attri2vec algorithm. Args: head_links: An iterable of edges to perform sampling for. batch_num (int): Batch number Returns: A list of feature arrays, with each element being the feature of a target node and the id of the corresponding context node. """ target_ids = [head_link[0] for head_link in head_links] context_ids = [head_link[1] for head_link in head_links] target_feats = self.graph.node_features(target_ids, use_ilocs=True) context_feats = np.array(context_ids) batch_feats = [target_feats, np.array(context_feats)] return batch_feats class Node2VecLinkGenerator(BatchedLinkGenerator): """ A data generator for context node prediction with Node2Vec models. At minimum, supply the StellarGraph and the batch size. The supplied graph should be a StellarGraph object that is ready for machine learning. Currently the model does not require node features for nodes in the graph. Use the :meth:`flow` method supplying the nodes and targets, or an UnsupervisedSampler instance that generates node samples on demand, to get an object that can be used as a Keras data generator. Example:: G_generator = Node2VecLinkGenerator(G, 50) data_gen = G_generator.flow(edge_ids, edge_labels) .. seealso:: Model using this generator: :class:`.Node2Vec`. An example using this generator (see the model for more): `unsupervised representation learning <https://stellargraph.readthedocs.io/en/stable/demos/embeddings/keras-node2vec-embeddings.html>`__. Related functionality: :class:`.Node2VecNodeGenerator` for node classification and related tasks. Args: G (StellarGraph): A machine-learning ready graph. batch_size (int): Size of batch of links to return. name (str or None): Name of the generator (optional). """ def __init__(self, G, batch_size, name=None): super().__init__(G, batch_size, use_node_features=False) self.name = name def sample_features(self, head_links, batch_num): """ Sample the ids of the target and context nodes. and return these as a list of feature arrays for the Node2Vec algorithm. Args: head_links: An iterable of edges to perform sampling for. Returns: A list of feature arrays, with each element being the ids of the sampled target and context node. """ return [np.array(ids) for ids in zip(*head_links)] class DirectedGraphSAGELinkGenerator(BatchedLinkGenerator): """ A data generator for link prediction with directed Homogeneous GraphSAGE models At minimum, supply the StellarDiGraph, the batch size, and the number of node samples (separately for in-nodes and out-nodes) for each layer of the GraphSAGE model. The supplied graph should be a StellarDiGraph object with node features. Use the :meth:`flow` method supplying the nodes and (optionally) targets, or an UnsupervisedSampler instance that generates node samples on demand, to get an object that can be used as a Keras data generator. Example:: G_generator = DirectedGraphSageLinkGenerator(G, 50, [10,10], [10,10]) train_data_gen = G_generator.flow(edge_ids) .. seealso:: Model using this generator: :class:`.GraphSAGE`. Related functionality: - :class:`.UnsupervisedSampler` for unsupervised training using random walks - :class:`.DirectedGraphSAGENodeGenerator` for node classification and related tasks - :class:`.GraphSAGELinkGenerator` for undirected graphs - :class:`.HinSAGELinkGenerator` for heterogeneous graphs Args: G (StellarGraph):
-------------- 3 References ========== - http://en.wikipedia.org/wiki/Homogeneous_differential_equation - <NAME> & <NAME>, "Ordinary Differential Equations", Dover 1963, pp. 59 # indirect doctest """ x = func.args[0] f = func.func u = Dummy('u') u2 = Dummy('u2') # u2 == x/f(x) r = match # d+e*diff(f(x),x) C1 = get_numbered_constants(eq, num=1) xarg = match.get('xarg', 0) # If xarg present take xarg, else zero yarg = match.get('yarg', 0) # If yarg present take yarg, else zero int = C.Integral( simplify( (-r[r['d']]/(r[r['e']] + u2*r[r['d']])).subs({x: u2, r['y']: 1})), (u2, None, x/f(x))) sol = logcombine(Eq(log(f(x)), int + log(C1)), force=True) sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x)))) return sol # XXX: Should this function maybe go somewhere else? def homogeneous_order(eq, *symbols): r""" Returns the order `n` if `g` is homogeneous and ``None`` if it is not homogeneous. Determines if a function is homogeneous and if so of what order. A function `f(x, y, \cdots)` is homogeneous of order `n` if `f(t x, t y, \cdots) = t^n f(x, y, \cdots)`. If the function is of two variables, `F(x, y)`, then `f` being homogeneous of any order is equivalent to being able to rewrite `F(x, y)` as `G(x/y)` or `H(y/x)`. This fact is used to solve 1st order ordinary differential equations whose coefficients are homogeneous of the same order (see the docstrings of :py:meth:`~solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep` and :py:meth:`~solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`). Symbols can be functions, but every argument of the function must be a symbol, and the arguments of the function that appear in the expression must match those given in the list of symbols. If a declared function appears with different arguments than given in the list of symbols, ``None`` is returned. Examples ======== >>> from sympy import Function, homogeneous_order, sqrt >>> from sympy.abc import x, y >>> f = Function('f') >>> homogeneous_order(f(x), f(x)) is None True >>> homogeneous_order(f(x,y), f(y, x), x, y) is None True >>> homogeneous_order(f(x), f(x), x) 1 >>> homogeneous_order(x**2*f(x)/sqrt(x**2+f(x)**2), x, f(x)) 2 >>> homogeneous_order(x**2+f(x), x, f(x)) is None True """ from sympy.simplify.simplify import separatevars if not symbols: raise ValueError("homogeneous_order: no symbols were given.") symset = set(symbols) eq = sympify(eq) # The following are not supported if eq.has(Order, Derivative): return None # These are all constants if (eq.is_Number or eq.is_NumberSymbol or eq.is_number ): return S.Zero # Replace all functions with dummy variables dum = numbered_symbols(prefix='d', cls=Dummy) newsyms = set() for i in [j for j in symset if getattr(j, 'is_Function')]: iargs = set(i.args) if iargs.difference(symset): return None else: dummyvar = next(dum) eq = eq.subs(i, dummyvar) symset.remove(i) newsyms.add(dummyvar) symset.update(newsyms) if not eq.free_symbols & symset: return None # assuming order of a nested function can only be equal to zero if isinstance(eq, Function): return None if homogeneous_order( eq.args[0], *tuple(symset)) != 0 else S.Zero # make the replacement of x with x*t and see if t can be factored out t = Dummy('t', positive=True) # It is sufficient that t > 0 eqs = separatevars(eq.subs([(i, t*i) for i in symset]), [t], dict=True)[t] if eqs is S.One: return S.Zero # there was no term with only t i, d = eqs.as_independent(t, as_Add=False) b, e = d.as_base_exp() if b == t: return e def ode_1st_linear(eq, func, order, match): r""" Solves 1st order linear differential equations. These are differential equations of the form .. math:: dy/dx + P(x) y = Q(x)\text{.} These kinds of differential equations can be solved in a general way. The integrating factor `e^{\int P(x) \,dx}` will turn the equation into a separable equation. The general solution is:: >>> from sympy import Function, dsolve, Eq, pprint, diff, sin >>> from sympy.abc import x >>> f, P, Q = map(Function, ['f', 'P', 'Q']) >>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x)) >>> pprint(genform) d P(x)*f(x) + --(f(x)) = Q(x) dx >>> pprint(dsolve(genform, f(x), hint='1st_linear_Integral')) / / \ | | | | | / | / | | | | | | | | P(x) dx | - | P(x) dx | | | | | | | / | / f(x) = |C1 + | Q(x)*e dx|*e | | | \ / / Examples ======== >>> f = Function('f') >>> pprint(dsolve(Eq(x*diff(f(x), x) - f(x), x**2*sin(x)), ... f(x), '1st_linear')) f(x) = x*(C1 - cos(x)) References ========== - http://en.wikipedia.org/wiki/Linear_differential_equation#First_order_equation - <NAME> & <NAME>, "Ordinary Differential Equations", Dover 1963, pp. 92 # indirect doctest """ x = func.args[0] f = func.func r = match # a*diff(f(x),x) + b*f(x) + c C1 = get_numbered_constants(eq, num=1) t = exp(C.Integral(r[r['b']]/r[r['a']], x)) tt = C.Integral(t*(-r[r['c']]/r[r['a']]), x) f = match.get('u', f(x)) # take almost-linear u if present, else f(x) return Eq(f, (tt + C1)/t) def ode_Bernoulli(eq, func, order, match): r""" Solves Bernoulli differential equations. These are equations of the form .. math:: dy/dx + P(x) y = Q(x) y^n\text{, }n \ne 1`\text{.} The substitution `w = 1/y^{1-n}` will transform an equation of this form into one that is linear (see the docstring of :py:meth:`~sympy.solvers.ode.ode_1st_linear`). The general solution is:: >>> from sympy import Function, dsolve, Eq, pprint >>> from sympy.abc import x, n >>> f, P, Q = map(Function, ['f', 'P', 'Q']) >>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)**n) >>> pprint(genform) d n P(x)*f(x) + --(f(x)) = Q(x)*f (x) dx >>> pprint(dsolve(genform, f(x), hint='Bernoulli_Integral')) #doctest: +SKIP 1 ---- 1 - n // / \ \ || | | | || | / | / | || | | | | | || | (1 - n)* | P(x) dx | (-1 + n)* | P(x) dx| || | | | | | || | / | / | f(x) = ||C1 + (-1 + n)* | -Q(x)*e dx|*e | || | | | \\ / / / Note that the equation is separable when `n = 1` (see the docstring of :py:meth:`~sympy.solvers.ode.ode_separable`). >>> pprint(dsolve(Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)), f(x), ... hint='separable_Integral')) f(x) / | / | 1 | | - dy = C1 + | (-P(x) + Q(x)) dx | y | | / / Examples ======== >>> from sympy import Function, dsolve, Eq, pprint, log >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(Eq(x*f(x).diff(x) + f(x), log(x)*f(x)**2), ... f(x), hint='Bernoulli')) 1 f(x) = ------------------- / log(x) 1\ x*|C1 + ------ + -| \ x x/ References ========== - http://en.wikipedia.org/wiki/Bernoulli_differential_equation - <NAME> & <NAME>, "Ordinary Differential Equations", Dover 1963, pp. 95 # indirect doctest """ x = func.args[0] f = func.func r = match # a*diff(f(x),x) + b*f(x) + c*f(x)**n, n != 1 C1 = get_numbered_constants(eq, num=1) t = exp((1 - r[r['n']])*C.Integral(r[r['b']]/r[r['a']], x)) tt = (r[r['n']] - 1)*C.Integral(t*r[r['c']]/r[r['a']], x) return Eq(f(x), ((tt + C1)/t)**(1/(1 - r[r['n']]))) def ode_Riccati_special_minus2(eq, func, order, match): r""" The general Riccati equation has the form .. math:: dy/dx = f(x) y^2 + g(x) y + h(x)\text{.} While it does not have a general solution [1], the "special" form, `dy/dx = a y^2 - b x^c`, does have solutions in many cases [2]. This routine returns a solution for `a(dy/dx) = b y^2 + c y/x + d/x^2` that is obtained by using a suitable change of variables to reduce it to the special form and is valid when neither `a` nor `b` are zero and either `c` or `d` is zero. >>> from sympy.abc import x, y, a, b, c, d >>> from sympy.solvers.ode import dsolve, checkodesol >>> from sympy import pprint, Function >>> f = Function('f') >>> y = f(x) >>> genform = a*y.diff(x) - (b*y**2 + c*y/x + d/x**2) >>> sol = dsolve(genform, y) >>> pprint(sol, wrap_line=False) / / __________________ \\ | __________________ | / 2 || | / 2 | \/ 4*b*d - (a + c) *log(x)|| -|a + c - \/ 4*b*d - (a + c) *tan|C1 + ----------------------------|| \ \ 2*a // f(x) = ------------------------------------------------------------------------ 2*b*x >>> checkodesol(genform, sol, order=1)[0] True References ========== 1. http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Riccati 2. http://eqworld.ipmnet.ru/en/solutions/ode/ode0106.pdf - http://eqworld.ipmnet.ru/en/solutions/ode/ode0123.pdf """ x = func.args[0] f = func.func r = match # a2*diff(f(x),x) + b2*f(x) + c2*f(x)/x
<filename>canopygrid.py # -*- coding: utf-8 -*- """ Created on Fri Mar 24 11:01:50 2017 @author: slauniai ****************************************************************************** CanopyGrid: Gridded canopy and snow hydrology model for SpaFHy -integration Based on simple schemes for computing water flows and storages within vegetation canopy and snowpack at daily or sub-daily timesteps. (C) <NAME>, 2016- last edit: Oct 2018 / Samuli ****************************************************************************** Kersti: modifications to allow for spatially varying forcing data """ import numpy as np eps = np.finfo(float).eps epsi = 0.01 class CanopyGrid(): def __init__(self, cpara, state): """ initializes CanopyGrid -object Args: cpara - parameter dict: state - dict of initial state outputs - True saves output grids to list at each timestep Returns: self - object NOTE: Currently the initialization assumes simulation start 1st Jan, and sets self._LAI_decid and self.X equal to minimum values. Also leaf-growth & senescence parameters are intialized to zero. """ cmask = state['hc'].copy() cmask[np.isfinite(cmask)] = 1.0 self.cmask = cmask self.latitude = cpara['loc']['lat'] * cmask self.longitude = cpara['loc']['lon'] # physiology: transpi + floor evap self.physpara = cpara['physpara'] # phenology self.phenopara = cpara['phenopara'] # canopy parameters and state self.update_state(state) # senescence starts at first doy when daylength < self.phenopara['sdl'] self.phenopara['sso'] = np.ones(np.shape(self.latitude))*np.nan doy = np.arange(1, 366) for lat in np.unique(self.latitude): if np.isnan(lat): break # senescence starts at first doy when daylength < self.phenopara['sdl'] dl = daylength(lat, doy) ix = np.max(np.where(dl > self.phenopara['sdl'])) self.phenopara['sso'][self.latitude == lat] = doy[ix] # this is onset date for senescence del ix self.phenopara['sso'] = self.phenopara['sso'] * cmask self.wmax = cpara['interc']['wmax'] self.wmaxsnow = cpara['interc']['wmaxsnow'] self.Tmin = cpara['interc']['Tmin'] self.Tmax = cpara['interc']['Tmax'] self.cs = cpara['interc']['c_snow'] self.Kmelt = cpara['snow']['kmelt'] / (3600 * 24) # to mm/s self.Kfreeze = cpara['snow']['kfreeze'] / (3600 * 24) # to mm/s self.R = cpara['snow']['r'] # max fraction of liquid water in snow # --- for computing aerodynamic resistances self.zmeas = cpara['flow']['zmeas'] self.zground =cpara['flow']['zground'] # reference height above ground [m] self.zo_ground = cpara['flow']['zo_ground'] # ground roughness length [m] self.gsoil = self.physpara['gsoil'] # --- state variables self.W = np.minimum(state['w'], self.wmax*self.LAI) self.SWE = state['swe'] self.SWEi = self.SWE self.SWEl = np.zeros(np.shape(self.SWE)) # deciduous leaf growth stage # NOTE: this assumes simulations start 1st Jan each year !!! self.DDsum = self.W * 0.0 self.X = self.W * 0.0 self._growth_stage = self.W * 0.0 self._senesc_stage = self.W *0.0 def update_state(self, state): # canopy parameters and state self.hc = state['hc'] self.cf = state['cf'] self._LAIconif = np.maximum(state['lai_conif'], epsi) # m2m-2 self._LAIdecid = state['lai_decid_max'] * self.phenopara['lai_decid_min'] self.LAI = self._LAIconif + self._LAIdecid self._LAIdecid_max = state['lai_decid_max'] # m2m-2 def run_timestep(self, doy, dt, Ta, Prec, Rg, Par, VPD, U=2.0, CO2=380.0, Rew=1.0, beta=1.0, P=101300.0): """ Runs CanopyGrid instance for one timestep IN: doy - day of year dt - timestep [s] Ta - air temperature [degC], scalar or (n x m) -matrix prec - precipitatation rate [mm/s] Rg - global radiation [Wm-2], scalar or matrix Par - photos. act. radiation [Wm-2], scalar or matrix VPD - vapor pressure deficit [kPa], scalar or matrix U - mean wind speed at ref. height above canopy top [ms-1], scalar or matrix CO2 - atm. CO2 mixing ratio [ppm] Rew - fractional limit of transpiration [-], scalar or matrix beta - fractional limit of soil evaporation (Wliq/FC) [-] P - pressure [Pa], scalar or matrix OUT: dictionary of fluxes """ Rn = np.maximum(2.57 * self.LAI / (2.57 * self.LAI + 0.57) - 0.2, 0.55) * Rg # Launiainen et al. 2016 GCB, fit to Fig 2a """ --- update phenology: self.ddsum & self.X ---""" self._degreeDays(Ta, doy) fPheno = self._photoacclim(Ta) """ --- update deciduous leaf area index --- """ laifract = self._lai_dynamics(doy) """ --- aerodynamic conductances --- """ Ra, _, Ras, _, _, _ = aerodynamics( self.LAI, self.hc, U, w=0.01, zm=self.zmeas, zg=self.zground, zos=self.zo_ground) """ --- interception, evaporation and snowpack --- """ PotInf, Trfall, Evap, Interc, MBE, erate, unload, fact = self.canopy_water_snow( dt, Ta, Prec, Rn, VPD, Ra=Ra) """--- dry-canopy evapotranspiration [mm s-1] --- """ Transpi, Efloor, Gc, gs = self.dry_canopy_et( VPD, Par, Rn, Ta, Ra=Ra, Ras=Ras, CO2=CO2, Rew=Rew, beta=beta, fPheno=fPheno) Transpi = Transpi * dt Efloor = Efloor * dt results = { 'potential_infiltration': PotInf, # [mm d-1] 'interception': Interc, # [mm d-1] 'evaporation': Evap, # [mm d-1] 'forestfloor_evaporation': Efloor, # [mm d-1] 'transpiration': Transpi, # [mm d-1] 'throughfall': Trfall, #[mm d-1] 'snow_water_equivalent': self.SWE, # [mm] 'water_closure': MBE, # [mm d-1] 'phenostate': fPheno, # [-] 'leaf_area_index': self.LAI, # [m2 m-2] 'stomatal_conductance': Gc, # [m s-1] 'gs_raw': gs, # [m s-1] 'degree_day_sum': self.DDsum # [degC] } return results def _degreeDays(self, T, doy): """ Calculates and updates degree-day sum from the current mean Tair. INPUT: T - daily mean temperature (degC) doy - day of year 1...366 (integer) """ To = 5.0 # threshold temperature self.DDsum = self.DDsum + np.maximum(0.0, T - To) #reset at beginning of year self.DDsum[doy * self.cmask == 1] = 0. def _photoacclim(self, T): """ computes new stage of temperature acclimation and phenology modifier. Peltoniemi et al. 2015 Bor.Env.Res. IN: object, T = daily mean air temperature OUT: fPheno - phenology modifier [0...1], updates object state """ self.X = self.X + 1.0 / self.phenopara['tau'] * (T - self.X) # degC S = np.maximum(self.X - self.phenopara['xo'], 0.0) fPheno = np.maximum(self.phenopara['fmin'], np.minimum(S / self.phenopara['smax'], 1.0)) return fPheno def _lai_dynamics(self, doy): """ Seasonal cycle of deciduous leaf area Args: self - object doy - day of year Returns: none, updates state variables self.LAIdecid, self._growth_stage, self._senec_stage """ lai_min = self.phenopara['lai_decid_min'] ddo = self.phenopara['ddo'] ddur = self.phenopara['ddur'] sso = self.phenopara['sso'] sdur = self.phenopara['sdur'] # growth phase self._growth_stage += 1.0 / ddur f = np.minimum(1.0, lai_min + (1.0 - lai_min) * self._growth_stage) # beginning of year ix = np.where(self.DDsum <= ddo) f[ix] = lai_min self._growth_stage[ix] = 0. self._senesc_stage[ix] = 0. # senescence phase ix = np.where(doy > sso) self._growth_stage[ix] = 0. self._senesc_stage[ix] += 1.0 / sdur f[ix] = 1.0 - (1.0 - lai_min) * np.minimum(1.0, self._senesc_stage[ix]) # update self.LAIdecid and total LAI self._LAIdecid = self._LAIdecid_max * f self.LAI = self._LAIconif + self._LAIdecid return f def dry_canopy_et(self, D, Qp, AE, Ta, Ra=25.0, Ras=250.0, CO2=380.0, Rew=1.0, beta=1.0, fPheno=1.0): """ Computes ET from 2-layer canopy in absense of intercepted precipitiation, i.e. in dry-canopy conditions IN: self - object D - vpd in kPa Qp - PAR in Wm-2 AE - available energy in Wm-2 Ta - air temperature degC Ra - aerodynamic resistance (s/m) Ras - soil aerodynamic resistance (s/m) CO2 - atm. CO2 mixing ratio (ppm) Rew - relative extractable water [-] beta - relative soil conductance for evaporation [-] fPheno - phenology modifier [-] Args: Tr - transpiration rate (mm s-1) Efloor - forest floor evaporation rate (mm s-1) Gc - canopy conductance (integrated stomatal conductance) (m s-1) SOURCES: Launiainen et al. (2016). Do the energy fluxes and surface conductance of boreal coniferous forests in Europe scale with leaf area? Global Change Biol. Modified from: Leuning et al. 2008. A Simple surface conductance model to estimate regional evaporation using MODIS leaf area index and the Penman-Montheith equation. Water. Resources. Res., 44, W10419 Original idea Kelliher et al. (1995). Maximum conductances for evaporation from global vegetation types. Agric. For. Met 85, 135-147 <NAME>, Luke """ # ---Amax and g1 as LAI -weighted average of conifers and decid. rhoa = 101300.0 / (8.31 * (Ta + 273.15)) # mol m-3 Amax = 1./self.LAI * (self._LAIconif * self.physpara['amax'] + self._LAIdecid *self.physpara['amax']) # umolm-2s-1 g1 = 1./self.LAI * (self._LAIconif * self.physpara['g1_conif'] + self._LAIdecid *self.physpara['g1_decid']) kp = self.physpara['kp'] # (-) attenuation coefficient for PAR q50 = self.physpara['q50'] # Wm-2, half-sat. of leaf light response tau = np.exp(-kp * self.LAI) # fraction of Qp at ground relative to canopy top """--- canopy conductance Gc (integrated stomatal conductance)----- """ # fQ: Saugier & Katerji, 1991 Agric. For. Met., eq. 4. Leaf light response = Qp / (Qp + q50) fQ = 1./ kp * np.log((kp*Qp + q50) / (kp*Qp*np.exp(-kp * self.LAI) + q50 + eps)) # CO2 -response of canopy conductance, derived from APES-simulations # (Launiainen et al. 2016, Global Change Biology). relative to
'owner' ] name = repository_info_dict[ 'name' ] changeset_revision = repository_to_install_dict[ 'changeset_revision' ] repository_id = repository_to_install_dict[ 'repository_id' ] # We are testing deprecated repositories, because it is possible that a deprecated repository contains valid # and functionally correct tools that someone has previously installed. Deleted repositories have never been installed, # and therefore do not need to be checked. If they are undeleted, this script will then test them the next time it runs. if repository_info_dict[ 'deleted' ]: log.info( "Skipping revision %s of repository id %s (%s/%s) since the repository is deleted...", changeset_revision, repository_id, name, owner ) continue # Now merge the dict returned from /api/repository_revisions with the detailed dict we just retrieved. if latest_revision_only: if changeset_revision == repository_info_dict[ 'latest_revision' ]: detailed_repository_list.append( dict( repository_info_dict.items() + repository_to_install_dict.items() ) ) else: detailed_repository_list.append( dict( repository_info_dict.items() + repository_to_install_dict.items() ) ) repositories_tested = len( detailed_repository_list ) if latest_revision_only: skipped_previous = ' and metadata revisions that are not the most recent' else: skipped_previous = '' if testing_single_repository: log.info( 'Testing single repository with name %s and owner %s.', testing_single_repository[ 'name' ], testing_single_repository[ 'owner' ]) for repository_to_install in detailed_repository_list: if repository_to_install[ 'name' ] == testing_single_repository[ 'name' ] \ and repository_to_install[ 'owner' ] == testing_single_repository[ 'owner' ]: if testing_single_repository[ 'changeset_revision' ] is None: return [ repository_to_install ] else: if testing_single_repository[ 'changeset_revision' ] == repository_to_install[ 'changeset_revision' ]: return [ repository_to_install ] return [] log.info( 'After removing deleted repositories%s from the list, %d remain to be tested.', skipped_previous, repositories_tested ) return detailed_repository_list def get_tool_info_from_test_id( test_id ): ''' Test IDs come in the form test_tool_number (functional.test_toolbox.TestForTool_toolshed_url/repos/owner/repository_name/tool_id/tool_version) We want the tool ID and tool version. ''' parts = test_id.replace( ')', '' ).split( '/' ) tool_version = parts[ -1 ] tool_id = parts[ -2 ] return tool_id, tool_version def get_tool_test_results_from_api( tool_shed_url, metadata_revision_id ): api_path = [ 'api', 'repository_revisions', metadata_revision_id ] api_url = get_api_url( base=tool_shed_url, parts=api_path ) repository_metadata = json_from_url( api_url ) tool_test_results = repository_metadata.get( 'tool_test_results', {} ) # If, for some reason, the script that checks for functional tests has not run, tool_test_results will be None. if tool_test_results is None: return dict() return tool_test_results def is_latest_downloadable_revision( url, repository_info_dict ): latest_revision = get_latest_downloadable_changeset_revision( url, name=repository_info_dict[ 'name' ], owner=repository_info_dict[ 'owner' ] ) return str( repository_info_dict[ 'changeset_revision' ] ) == str( latest_revision ) def json_from_url( url ): url_handle = urllib.urlopen( url ) url_contents = url_handle.read() try: parsed_json = from_json_string( url_contents ) except: log.exception( 'Error parsing JSON data.' ) raise return parsed_json def parse_exclude_list( xml_filename ): ''' This method should return a list with the following structure: [ { 'reason': The default reason or the reason specified in this section, 'repositories': [ ( name, owner, changeset revision if changeset revision else None ), ( name, owner, changeset revision if changeset revision else None ) ] }, { 'reason': The default reason or the reason specified in this section, 'repositories': [ ( name, owner, changeset revision if changeset revision else None ), ( name, owner, changeset revision if changeset revision else None ) ] }, ] ''' exclude_list = [] exclude_verbose = [] xml_tree = parse_xml( xml_filename ) tool_sheds = xml_tree.findall( 'repositories' ) xml_element = [] exclude_count = 0 for tool_shed in tool_sheds: if galaxy_tool_shed_url != tool_shed.attrib[ 'tool_shed' ]: continue else: xml_element = tool_shed for reason_section in xml_element: reason_text = reason_section.find( 'text' ).text repositories = reason_section.findall( 'repository' ) exclude_dict = dict( reason=reason_text, repositories=[] ) for repository in repositories: repository_tuple = get_repository_tuple_from_elem( repository ) if repository_tuple not in exclude_dict[ 'repositories' ]: exclude_verbose.append( repository_tuple ) exclude_count += 1 exclude_dict[ 'repositories' ].append( repository_tuple ) exclude_list.append( exclude_dict ) log.debug( '%d repositories excluded from testing...', exclude_count ) if '-list_repositories' in sys.argv: for name, owner, changeset_revision in exclude_verbose: if changeset_revision: log.debug( 'Repository %s owned by %s, changeset revision %s.', name, owner, changeset_revision ) else: log.debug( 'Repository %s owned by %s, all revisions.', name, owner ) return exclude_list def register_test_result( url, metadata_id, test_results_dict, repository_info_dict, params ): ''' Update the repository metadata tool_test_results and appropriate flags using the API. ''' params[ 'tool_test_results' ] = test_results_dict if '-info_only' in sys.argv: return {} else: return update( tool_shed_api_key, '%s' % ( url_join( galaxy_tool_shed_url, 'api', 'repository_revisions', metadata_id ) ), params, return_formatted=False ) def remove_generated_tests( app ): # Delete any configured tool functional tests from the test_toolbox.__dict__, otherwise nose will find them # and try to re-run the tests after uninstalling the repository, which will cause false failure reports, # since the test data has been deleted from disk by now. tests_to_delete = [] tools_to_delete = [] global test_toolbox for key in test_toolbox.__dict__: if key.startswith( 'TestForTool_' ): log.info( 'Tool test found in test_toolbox, deleting: %s', key ) # We can't delete this test just yet, we're still iterating over __dict__. tests_to_delete.append( key ) tool_id = key.replace( 'TestForTool_', '' ) for tool in app.toolbox.tools_by_id: if tool.replace( '_', ' ' ) == tool_id.replace( '_', ' ' ): tools_to_delete.append( tool ) for key in tests_to_delete: # Now delete the tests found in the previous loop. del test_toolbox.__dict__[ key ] for tool in tools_to_delete: del app.toolbox.tools_by_id[ tool ] def run_tests( test_config ): loader = nose.loader.TestLoader( config=test_config ) test_config.plugins.addPlugin( ReportResults() ) plug_loader = test_config.plugins.prepareTestLoader( loader ) if plug_loader is not None: loader = plug_loader tests = loader.loadTestsFromNames( test_config.testNames ) test_runner = nose.core.TextTestRunner( stream=test_config.stream, verbosity=test_config.verbosity, config=test_config ) plug_runner = test_config.plugins.prepareTestRunner( test_runner ) if plug_runner is not None: test_runner = plug_runner result = test_runner.run( tests ) return result, test_config.plugins._plugins def show_summary_output( repository_info_dicts ): repositories_by_owner = dict() for repository in repository_info_dicts: if repository[ 'owner' ] not in repositories_by_owner: repositories_by_owner[ repository[ 'owner' ] ] = [] repositories_by_owner[ repository[ 'owner' ] ].append( repository ) for owner in repositories_by_owner: print "# " for repository in repositories_by_owner[ owner ]: print "# %s owned by %s, changeset revision %s" % ( repository[ 'name' ], repository[ 'owner' ], repository[ 'changeset_revision' ] ) def main(): # ---- Configuration ------------------------------------------------------ galaxy_test_host = os.environ.get( 'GALAXY_INSTALL_TEST_HOST', default_galaxy_test_host ) galaxy_test_port = os.environ.get( 'GALAXY_INSTALL_TEST_PORT', str( default_galaxy_test_port_max ) ) tool_path = os.environ.get( 'GALAXY_INSTALL_TEST_TOOL_PATH', 'tools' ) if 'HTTP_ACCEPT_LANGUAGE' not in os.environ: os.environ[ 'HTTP_ACCEPT_LANGUAGE' ] = default_galaxy_locales galaxy_test_file_dir = os.environ.get( 'GALAXY_INSTALL_TEST_FILE_DIR', default_galaxy_test_file_dir ) if not os.path.isabs( galaxy_test_file_dir ): galaxy_test_file_dir = os.path.abspath( galaxy_test_file_dir ) use_distributed_object_store = os.environ.get( 'GALAXY_INSTALL_TEST_USE_DISTRIBUTED_OBJECT_STORE', False ) if not os.path.isdir( galaxy_test_tmp_dir ): os.mkdir( galaxy_test_tmp_dir ) galaxy_test_proxy_port = None # Set up the configuration files for the Galaxy instance. shed_tool_data_table_conf_file = os.environ.get( 'GALAXY_INSTALL_TEST_SHED_TOOL_DATA_TABLE_CONF', os.path.join( galaxy_test_tmp_dir, 'test_shed_tool_data_table_conf.xml' ) ) galaxy_tool_data_table_conf_file = os.environ.get( 'GALAXY_INSTALL_TEST_TOOL_DATA_TABLE_CONF', tool_data_table_conf ) galaxy_tool_conf_file = os.environ.get( 'GALAXY_INSTALL_TEST_TOOL_CONF', os.path.join( galaxy_test_tmp_dir, 'test_tool_conf.xml' ) ) galaxy_shed_tool_conf_file = os.environ.get( 'GALAXY_INSTALL_TEST_SHED_TOOL_CONF', os.path.join( galaxy_test_tmp_dir, 'test_shed_tool_conf.xml' ) ) galaxy_migrated_tool_conf_file = os.environ.get( 'GALAXY_INSTALL_TEST_MIGRATED_TOOL_CONF', os.path.join( galaxy_test_tmp_dir, 'test_migrated_tool_conf.xml' ) ) galaxy_tool_sheds_conf_file = os.environ.get( 'GALAXY_INSTALL_TEST_TOOL_SHEDS_CONF', os.path.join( galaxy_test_tmp_dir, 'test_tool_sheds_conf.xml' ) ) galaxy_shed_tools_dict = os.environ.get( 'GALAXY_INSTALL_TEST_SHED_TOOL_DICT_FILE', os.path.join( galaxy_test_tmp_dir, 'shed_tool_dict' ) ) file( galaxy_shed_tools_dict, 'w' ).write( to_json_string( dict() ) ) if 'GALAXY_INSTALL_TEST_TOOL_DATA_PATH' in os.environ: tool_data_path = os.environ.get( 'GALAXY_INSTALL_TEST_TOOL_DATA_PATH' ) else: tool_data_path = tempfile.mkdtemp( dir=galaxy_test_tmp_dir ) os.environ[ 'GALAXY_INSTALL_TEST_TOOL_DATA_PATH' ] = tool_data_path # Configure the database connection and path. if 'GALAXY_INSTALL_TEST_DBPATH' in os.environ: galaxy_db_path = os.environ[ 'GALAXY_INSTALL_TEST_DBPATH' ] else: tempdir = tempfile.mkdtemp( dir=galaxy_test_tmp_dir ) galaxy_db_path = os.path.join( tempdir, 'database' ) # Configure the paths Galaxy needs to install and test tools. galaxy_file_path = os.path.join( galaxy_db_path, 'files' ) new_repos_path = tempfile.mkdtemp( dir=galaxy_test_tmp_dir ) galaxy_tempfiles = tempfile.mkdtemp( dir=galaxy_test_tmp_dir ) galaxy_shed_tool_path = tempfile.mkdtemp( dir=galaxy_test_tmp_dir, prefix='shed_tools' ) galaxy_migrated_tool_path = tempfile.mkdtemp( dir=galaxy_test_tmp_dir ) # Set up the tool dependency path for the Galaxy instance. tool_dependency_dir = os.environ.get( 'GALAXY_INSTALL_TEST_TOOL_DEPENDENCY_DIR', None ) if tool_dependency_dir is None: tool_dependency_dir = tempfile.mkdtemp( dir=galaxy_test_tmp_dir ) os.environ[ 'GALAXY_INSTALL_TEST_TOOL_DEPENDENCY_DIR' ] = tool_dependency_dir if 'GALAXY_INSTALL_TEST_DBURI' in os.environ: database_connection = os.environ[ 'GALAXY_INSTALL_TEST_DBURI' ] else: database_connection = 'sqlite:///' + os.path.join( galaxy_db_path, 'install_and_test_repositories.sqlite' ) kwargs = {} for dir in [ galaxy_test_tmp_dir ]: try: os.makedirs( dir ) except OSError: pass print "Database connection: ", database_connection # Generate the shed_tool_data_table_conf.xml file. file( shed_tool_data_table_conf_file, 'w' ).write( tool_data_table_conf_xml_template ) os.environ[ 'GALAXY_INSTALL_TEST_SHED_TOOL_DATA_TABLE_CONF' ] = shed_tool_data_table_conf_file # ---- Start up a Galaxy instance ------------------------------------------------------ # Generate the tool_conf.xml file. file( galaxy_tool_conf_file, 'w' ).write( tool_conf_xml ) # Generate the
#!/usr/bin/env python """ Extracts data from XNAT archive folders into a few well-known formats. Usage: dm_xnat_extract.py [options] <study> [-t <tag>]... dm_xnat_extract.py [options] <study> <session> [-t <tag>]... Arguments: <study> Nickname of the study to process <session> Fullname of the session to process Options: --blacklist FILE Table listing series to ignore override the default metadata/blacklist.csv -v --verbose Show intermediate steps -d --debug Show debug messages -q --quiet Show minimal output -n --dry-run Do nothing --server URL XNAT server to connect to, overrides the server defined in the site config file. -u --username USER XNAT username. If specified then the credentials file is ignored and you are prompted for password. --dont-update-dashboard Dont update the dashboard database -t --tag tag,... List of scan tags to download OUTPUT FOLDERS Each dicom series will be converted and placed into a subfolder of the datadir named according to the converted filetype and subject ID, e.g. data/ nifti/ SPN01_CMH_0001_01/ (all nifti acquisitions for this subject-timepoint) OUTPUT FILE NAMING Each dicom series will be and named according to the following schema: <scanid>_<tag>_<series#>_<description>.<ext> Where, <scanid> = the scan id from the file name, eg. DTI_CMH_H001_01_01 <tag> = a short code indicating the data type (e.g. T1, DTI, etc..) <series#> = the dicom series number in the exam <descr> = the dicom series description <ext> = appropriate filetype extension For example, a T1 in nifti format might be named: DTI_CMH_H001_01_01_T1_11_Sag-T1-BRAVO.nii.gz The <tag> is determined from project_settings.yml NON-DICOM DATA XNAT puts "other" (i.e. non-DICOM data) into the RESOURCES folder, defined in paths:resources. data will be copied to a subfolder of the data directory named paths:resources/<scanid>, for example: /path/to/resources/SPN01_CMH_0001_01_01/ DEPENDENCIES dcm2nii """ from datetime import datetime from glob import glob import logging import os import platform import shutil import sys import re import zipfile from docopt import docopt import pydicom as dicom import datman.dashboard as dashboard import datman.config import datman.xnat import datman.utils import datman.scan import datman.scanid import datman.exceptions logger = logging.getLogger(os.path.basename(__file__)) xnat = None cfg = None DRYRUN = False db_ignore = False # if True dont update the dashboard db wanted_tags = None def main(): global xnat global cfg global DRYRUN global wanted_tags arguments = docopt(__doc__) verbose = arguments['--verbose'] debug = arguments['--debug'] quiet = arguments['--quiet'] study = arguments['<study>'] session = arguments['<session>'] wanted_tags = arguments['--tag'] server = arguments['--server'] username = arguments['--username'] db_ignore = arguments['--dont-update-dashboard'] if arguments['--dry-run']: DRYRUN = True db_ignore = True # setup logging ch = logging.StreamHandler(sys.stdout) # setup log levels log_level = logging.WARNING if quiet: log_level = logging.ERROR if verbose: log_level = logging.INFO if debug: log_level = logging.DEBUG logger.setLevel(log_level) ch.setLevel(log_level) formatter = logging.Formatter('%(asctime)s - %(name)s - {study} - ' '%(levelname)s - %(message)s' .format(study=study)) ch.setFormatter(formatter) logger.addHandler(ch) logging.getLogger('datman.utils').addHandler(ch) logging.getLogger('datman.dashboard').addHandler(ch) # setup the config object logger.info("Loading config") cfg = datman.config.config(study=study) # get base URL link to XNAT server, authentication info server = datman.xnat.get_server(cfg, url=server) username, password = datman.xnat.get_auth(username) # initialize requests module object for XNAT REST API xnat = datman.xnat.xnat(server, username, password) # get the list of XNAT projects linked to the datman study xnat_projects = cfg.get_xnat_projects(study) if session: # if session has been provided on the command line, identify which # project it is in try: xnat_project = xnat.find_session(session, xnat_projects) except datman.exceptions.XnatException as e: raise e if not xnat_project: logger.error("Failed to find session: {} in XNAT. " "Ensure it is named correctly with timepoint and repeat." .format(session)) return sessions = [(xnat_project, session)] else: sessions = collect_sessions(xnat_projects, cfg) logger.info("Found {} sessions for study: {}" .format(len(sessions), study)) for session in sessions: process_session(session) def collect_sessions(xnat_projects, config): sessions = [] # for each XNAT project send out URL request for list of session records # then validate and add (XNAT project, subject ID ['label']) to output list for project in xnat_projects: project_sessions = xnat.get_sessions(project) for session in project_sessions: try: sub_id = datman.utils.validate_subject_id(session['label'], config) except RuntimeError as e: logger.error("Invalid ID {} in project {}. Reason: {}" .format(session['label'], project, str(e))) continue if not datman.scanid.is_phantom(session['label']) and sub_id.session is None: logger.error("Invalid ID {} in project {}. Reason: Not a " "phantom, but missing series number" .format(session['label'], project)) continue sessions.append((project, session['label'])) return sessions def process_session(session): xnat_project = session[0] session_label = session[1] logger.info("Processing session: {}".format(session_label)) # session_label should be a valid datman scanid try: ident = datman.scanid.parse(session_label) except datman.scanid.ParseException: logger.error("Invalid session: {}. Skipping".format(session_label)) return # check that the session is valid on XNAT try: xnat.get_session(xnat_project, session_label) except Exception as e: logger.error("Error while getting session {} from XNAT. " "Message: {}".format(session_label, e.message)) return # look into XNAT project and get list of experiments try: experiments = xnat.get_experiments(xnat_project, session_label) except Exception as e: logger.warning("Failed getting experiments for: {} in project: {} " "with reason: {}" .format(session_label, xnat_project, e)) return # we expect exactly 1 experiment per session if len(experiments) > 1: logger.error("Found more than one experiment for session: {} " "in study: {}. Skipping" .format(session_label, xnat_project)) return if not experiments: logger.error("Session: {} in study: {} has no experiments" .format(session_label, xnat_project)) return experiment_label = experiments[0]['label'] # experiment_label should be the same as the session_label if not experiment_label == session_label: logger.warning("Experiment label: {} doesn't match session label: {}" .format(experiment_label, session_label)) # retrieve json table from project --> session --> experiment try: experiment = xnat.get_experiment(xnat_project, session_label, experiment_label) except Exception as e: logger.error("Failed getting experiment for session: {} with reason" .format(session_label, e)) return if not experiment: logger.warning("No experiments found for session: {}" .format(session_label)) return if not db_ignore: logger.debug("Adding session {} to dashboard".format(session_label)) try: db_session = dashboard.get_session(ident, create=True) except dashboard.DashboardException as e: logger.error("Failed adding session {}. Reason: {}".format( session_label, e)) else: set_date(db_session, experiment) # experiment['children'] is a list of top level folders in XNAT # project --> session --> experiments for data in experiment['children']: if data['field'] == 'resources/resource': process_resources(xnat_project, session_label, experiment_label, data) elif data['field'] == 'scans/scan': process_scans(ident, xnat_project, session_label, experiment_label, data) else: logger.warning("Unrecognised field type: {} for experiment: {} " "in session: {} from study: {}" .format(data['field'], experiment_label, session_label, xnat_project)) def set_date(session, experiment): try: date = experiment['data_fields']['date'] except KeyError: logger.error("No scanning date found for {}, leaving blank.".format( session)) return try: date = datetime.strptime(date, '%Y-%m-%d') except ValueError: logger.error('Invalid date {} for scan session {}'.format(date, session)) return if date == session.date: return session.date = date session.save() def process_resources(xnat_project, session_label, experiment_label, data): """Export any non-dicom resources from the XNAT archive""" logger.info("Extracting {} resources from {}" .format(len(data), session_label)) base_path = os.path.join(cfg.get_path('resources'), session_label) if not os.path.isdir(base_path): logger.info("Creating resources dir: {}".format(base_path)) try: os.makedirs(base_path) except OSError: logger.error("Failed creating resources dir: {}".format(base_path)) return for item in data['items']: try: data_type = item['data_fields']['label'] except KeyError: data_type = 'MISC' target_path = os.path.join(base_path, data_type) try: target_path = datman.utils.define_folder(target_path) except OSError: logger.error("Failed creating target folder: {}" .format(target_path)) continue xnat_resource_id = item['data_fields']['xnat_abstractresource_id'] try: resources = xnat.get_resource_list(xnat_project, session_label, experiment_label, xnat_resource_id) if not resources: continue except Exception as e: logger.error("Failed getting resource: {} " "for session: {} in project: {}" .format(xnat_resource_id, session_label, e)) continue for resource in resources: resource_path = os.path.join(target_path, resource['URI']) if os.path.isfile(resource_path): logger.debug("Resource: {} found for session: {}" .format(resource['name'], session_label)) else: logger.info("Resource: {} not found for session: {}" .format(resource['name'], session_label)) get_resource(xnat_project, session_label, experiment_label, xnat_resource_id, resource['URI'], resource_path) def get_resource(xnat_project, xnat_session, xnat_experiment, xnat_resource_id, xnat_resource_uri, target_path): """ Download a single resource file from XNAT. Target path should be full path to store the file, including filename """ try: source = xnat.get_resource(xnat_project, xnat_session, xnat_experiment, xnat_resource_id, xnat_resource_uri, zipped=False) except Exception as e: logger.error("Failed downloading resource archive from: {} with " "reason: {}".format(xnat_session, e)) return # check that the target path exists target_dir = os.path.split(target_path)[0] if not os.path.exists(target_dir): try: os.makedirs(target_dir) except OSError: logger.error("Failed to create directory: {}".format(target_dir)) return # copy the downloaded file to the target location try: if not DRYRUN: shutil.copyfile(source, target_path) except: logger.error("Failed copying resource: {} to target: {}" .format(source, target_path)) # finally delete the temporary archive try: os.remove(source) except OSError: logger.error("Failed to remove temporary archive: {} on system: {}" .format(source, platform.node())) return(target_path) def process_scans(ident, xnat_project, session_label, experiment_label, scans): """ Process a set of scans in an XNAT experiment scanid is a valid datman.scanid object Scans is the json output from XNAT query representing scans in an experiment """ logger.info("Processing scans in session: {}" .format(session_label)) # load the export info from the site config files tags = cfg.get_tags(site=ident.site) exportinfo = tags.series_map if not exportinfo: logger.error("Failed to get exportinfo for
"EEB59D" }, "776" : { "number" : "776", "name" : "greenapple", "title" : u"\u9752\u308a\u3093\u3054", "sjis" : "F45E", "unicode" : "EB5A", "jis-email" : "7B3F", "sjis-email" : "EE5E", "utf-8" : "EEB59E" }, "777" : { "number" : "777", "name" : "bill", "title" : u"\u7fbd\u306e\u306f\u3048\u305f\u304a\u672d", "sjis" : "F45F", "unicode" : "EB5B", "jis-email" : "7B40", "sjis-email" : "EE5F", "utf-8" : "EEB59F" }, "778" : { "number" : "778", "name" : "sign5", "title" : u"\u76ee\u304c\u307e\u308f\u308b\u6642\u306e\u8a18\u53f7", "sjis" : "F460", "unicode" : "EB5C", "jis-email" : "7B41", "sjis-email" : "EE60", "utf-8" : "EEB5A0" }, "779" : { "number" : "779", "name" : "face26", "title" : u"\u3077\u30fc(\u304b\u308f\u3044\u304f\u6012)", "sjis" : "F461", "unicode" : "EB5D", "jis-email" : "7B42", "sjis-email" : "EE61", "utf-8" : "EEB5A1" }, "780" : { "number" : "780", "name" : "catface", "title" : u"\u3076\u30fc\uff08\u304b\u308f\u3044\u304f\u6012\uff09\uff08\u30cd\u30b3\uff09", "sjis" : "F462", "unicode" : "EB5E", "jis-email" : "7B43", "sjis-email" : "EE62", "utf-8" : "EEB5A2" }, "781" : { "number" : "781", "name" : "milkyway", "title" : u"\u5929\u306e\u5ddd", "sjis" : "F463", "unicode" : "EB5F", "jis-email" : "7B44", "sjis-email" : "EE63", "utf-8" : "EEB5A3" }, "782" : { "number" : "782", "name" : "catface2", "title" : u"\u30c1\u30e5\u30fc\uff08\u30cd\u30b3\uff09", "sjis" : "F464", "unicode" : "EB60", "jis-email" : "7B45", "sjis-email" : "EE64", "utf-8" : "EEB5A4" }, "783" : { "number" : "783", "name" : "catface3", "title" : u"\u306b\u3053(\u30cd\u30b3)", "sjis" : "F465", "unicode" : "EB61", "jis-email" : "7B46", "sjis-email" : "EE65", "utf-8" : "EEB5A5" }, "784" : { "number" : "784", "name" : "envelope4", "title" : u"\u30e1\u30fc\u30eb\u3059\u308b", "sjis" : "F466", "unicode" : "EB62", "jis-email" : "7B47", "sjis-email" : "EE66", "utf-8" : "EEB5A6" }, "785" : { "number" : "785", "name" : "catface4", "title" : u"\u6ce3\u304d\u7b11\u3044\uff08\u30cd\u30b3\uff09", "sjis" : "F467", "unicode" : "EB63", "jis-email" : "7B48", "sjis-email" : "EE67", "utf-8" : "EEB5A7" }, "786" : { "number" : "786", "name" : "face27", "title" : u"\u6ce3\u304d\u7b11\u3044", "sjis" : "F468", "unicode" : "EB64", "jis-email" : "7B49", "sjis-email" : "EE68", "utf-8" : "EEB5A8" }, "787" : { "number" : "787", "name" : "catface5", "title" : u"\u76ee\u304c\u30cf\u30fc\u30c8\uff08\u30cd\u30b3\uff09", "sjis" : "F469", "unicode" : "EB65", "jis-email" : "7B4A", "sjis-email" : "EE69", "utf-8" : "EEB5A9" }, "788" : { "number" : "788", "name" : "catface6", "title" : u"\u307b\u3048\u30fc\uff08\u30cd\u30b3\uff09", "sjis" : "F46A", "unicode" : "EB66", "jis-email" : "7B4B", "sjis-email" : "EE6A", "utf-8" : "EEB5AA" }, "789" : { "number" : "789", "name" : "face28", "title" : u"\u307b\u3048\u30fc", "sjis" : "F46B", "unicode" : "EB67", "jis-email" : "7B4C", "sjis-email" : "EE6B", "utf-8" : "EEB5AB" }, "790" : { "number" : "790", "name" : "catface7", "title" : u"\u6d99\u307d\u308d\u308a\uff08\u30cd\u30b3\uff09", "sjis" : "F46C", "unicode" : "EB68", "jis-email" : "7B4D", "sjis-email" : "EE6C", "utf-8" : "EEB5AC" }, "791" : { "number" : "791", "name" : "face29", "title" : u"\u6d99\u307d\u308d\u308a", "sjis" : "F46D", "unicode" : "EB69", "jis-email" : "7B4E", "sjis-email" : "EE6D", "utf-8" : "EEB5AD" }, "792" : { "number" : "792", "name" : "catface9", "title" : u"\u304d\u308a\u308a\uff08\u30cd\u30b3\uff09", "sjis" : "F46E", "unicode" : "EB6A", "jis-email" : "7B4F", "sjis-email" : "EE6E", "utf-8" : "EEB5AE" }, "793" : { "number" : "793", "name" : "dress", "title" : u"\u30c9\u30ec\u30b9", "sjis" : "F46F", "unicode" : "EB6B", "jis-email" : "7B50", "sjis-email" : "EE6F", "utf-8" : "EEB5AF" }, "794" : { "number" : "794", "name" : "figure", "title" : u"\u30e2\u30e4\u30a4\u8c61", "sjis" : "F470", "unicode" : "EB6C", "jis-email" : "7B51", "sjis-email" : "EE70", "utf-8" : "EEB5B0" }, "795" : { "number" : "795", "name" : "station", "title" : u"\u99c5", "sjis" : "F471", "unicode" : "EB6D", "jis-email" : "7B52", "sjis-email" : "EE71", "utf-8" : "EEB5B1" }, "796" : { "number" : "796", "name" : "japaneseplayingcards", "title" : u"\u82b1\u672d", "sjis" : "F472", "unicode" : "EB6E", "jis-email" : "7B53", "sjis-email" : "EE72", "utf-8" : "EEB5B2" }, "797" : { "number" : "797", "name" : "joker", "title" : u"\u30b8\u30e7\u30fc\u30ab\u30fc", "sjis" : "F473", "unicode" : "EB6F", "jis-email" : "7B54", "sjis-email" : "EE73", "utf-8" : "EEB5B3" }, "798" : { "number" : "798", "name" : "lobster", "title" : u"\u30a8\u30d3\u30d5\u30e9\u30a4", "sjis" : "F474", "unicode" : "EB70", "jis-email" : "7B55", "sjis-email" : "EE74", "utf-8" : "EEB5B4" }, "799" : { "number" : "799", "name" : "icon", "title" : u"e\u30e1\u30fc\u30eb\u30a2\u30a4\u30b3\u30f3", "sjis" : "F475", "unicode" : "EB71", "jis-email" : "7B56", "sjis-email" : "EE75", "utf-8" : "EEB5B5" }, "800" : { "number" : "800", "name" : "walk", "title" : u"\u6b69\u304f\u4eba", "sjis" : "F476", "unicode" : "EB72", "jis-email" : "7B57", "sjis-email" : "EE76", "utf-8" : "EEB5B6" }, "801" : { "number" : "801", "name" : "policecar2", "title" : u"\u30d1\u30c8\u30ab\u30fc\u306e\u30e9\u30f3\u30d7", "sjis" : "F477", "unicode" : "EB73", "jis-email" : "7B58", "sjis-email" : "EE77", "utf-8" : "EEB5B7" }, "802" : { "number" : "802", "name" : "ezmovie", "title" : u"ezmovie", "sjis" : "F478", "unicode" : "EB74", "jis-email" : "7B59", "sjis-email" : "EE78", "utf-8" : "EEB5B8" }, "803" : { "number" : "803", "name" : "heart8", "title" : u"\u30c9\u30ad\u30c9\u30ad\u3057\u3066\u3044\u308b\u30cf\u30fc\u30c8", "sjis" : "F479", "unicode" : "EB75", "jis-email" : "7B5A", "sjis-email" : "EE79", "utf-8" : "EEB5B9" }, "804" : { "number" : "804", "name" : "chick", "title" : u"\u6b63\u9762\u5411\u304d\u306e\u3072\u3088\u3053", "sjis" : "F47A", "unicode" : "EB76", "jis-email" : "7B5B", "sjis-email" : "EE7A", "utf-8" : "EEB5BA" }, "805" : { "number" : "805", "name" : "jeans", "title" : u"\u30b8\u30fc\u30f3\u30ba", "sjis" : "F47B", "unicode" : "EB77", "jis-email" : "7B5C", "sjis-email" : "EE7B", "utf-8" : "EEB5BB" }, "806" : { "number" : "806", "name" : "envelope3", "title" : u"\u30cf\u30fc\u30c8\u3064\u304d\u30e1\u30fc\u30eb", "sjis" : "F47C", "unicode" : "EB78", "jis-email" : "7B5D", "sjis-email" : "EE7C", "utf-8" : "EEB5BC" }, "807" : { "number" : "807", "name" : "arrow", "title" : u"\u5faa\u74b0\u77e2\u5370", "sjis" : "F47D", "unicode" : "EB79", "jis-email" : "7B5E", "sjis-email" : "EE7D", "utf-8" : "EEB5BD" }, "808" : { "number" : "808", "name" : "doubleheadedarrow", "title" : u"\u5de6\u53f3\u4e21\u65b9\u5411\u77e2\u5370", "sjis" : "F47E", "unicode" : "EB7A", "jis-email" : "7B5F", "sjis-email" : "EE7E", "utf-8" : "EEB5BE" }, "809" : { "number" : "809", "name" : "doubleheadedarrow2", "title" : u"\u4e0a\u4e0b\u4e21\u65b9\u5411\u77e2\u5370", "sjis" : "F480", "unicode" : "EB7B", "jis-email" : "7B60", "sjis-email" : "EE80", "utf-8" : "EEB680" }, "810" : { "number" : "810", "name" : "wave", "title" : u"\u8352\u6ce2", "sjis" : "F481", "unicode" : "EB7C", "jis-email" : "7B61", "sjis-email" : "EE81", "utf-8" : "EEB681" }, "811" : { "number" : "811", "name" : "bud2", "title" : u"\u53cc\u8449", "sjis" : "F482", "unicode" : "EB7D", "jis-email" : "7B62", "sjis-email" : "EE82", "utf-8" : "EEB682" }, "812" : { "number" : "812", "name" : "snail", "title" : u"\u304b\u305f\u3064\u3080\u308a", "sjis" : "F483", "unicode" : "EB7E", "jis-email" : "7B63", "sjis-email" : "EE83", "utf-8" : "EEB683" }, "813" : { "number" : "813", "name" : "catface8", "title" : u"\u3046\u3063\u3057\u3063\u3057\uff08\u30cd\u30b3\uff09", "sjis" : "F484", "unicode" : "EB7F", "jis-email" : "7B64", "sjis-email" : "EE84", "utf-8" : "EEB684" }, "814" : { "number" : "814", "name" : "face31", "title" : u"\u3046\u3063\u3057\u3063\u3057", "sjis" : "F485", "unicode" : "EB80", "jis-email" : "7B65", "sjis-email" : "EE85", "utf-8" : "EEB685" }, "815" : { "number" : "815", "name" : "icon2", "title" : u"C\u30e1\u30fc\u30eb\u30a2\u30a4\u30b3\u30f3", "sjis" : "F486", "unicode" : "EB81", "jis-email" : "7B66", "sjis-email" : "EE86", "utf-8" : "EEB686" }, "816" : { "number" : "816", "name" : "herb", "title" : u"\u30cf\u30fc\u30d6", "sjis" : "F487", "unicode" : "EB82", "jis-email" : "7B67", "sjis-email" : "EE87", "utf-8" : "EEB687" }, "817" : { "number" : "817", "name" : "closefinger", "title" : u"\u30b0\u30fc", "sjis" : "F488", "unicode" : "EB83", "jis-email" : "7B68", "sjis-email" : "EE88", "utf-8" : "EEB688" }, "818" : { "number" : "818", "name" : "sharp", "title" : u"\uff03", "sjis" : "F489", "unicode" : "EB84", "jis-email" : "7B69", "sjis-email" : "EE89", "utf-8" : "EEB689" }, "819" : { "number" : "819", "name" : "raisehand", "title" : u"\u30ad\u30e3\u30e9\u30af\u30bf\u30fc\uff08\u6319\u624b\uff09", "sjis" : "F48A", "unicode" : "EB85", "jis-email" : "7B6A", "sjis-email" : "EE8A", "utf-8" : "EEB68A" }, "820" : { "number" : "820", "name" : "character", "title" : u"\u30ad\u30e3\u30e9\u30af\u30bf\u30fc\uff08\u4e07\u6b73\uff09", "sjis" : "F48B", "unicode" : "EB86", "jis-email" : "7B6B", "sjis-email" : "EE8B", "utf-8" : "EEB68B" }, "821" : { "number" : "821", "name" : "character2", "title" : u"\u30ad\u30e3\u30e9\u30af\u30bf\u30fc\uff08\u3057\u3087\u3093\u307c\u308a\uff09", "sjis" : "F48C", "unicode" : "EB87",
<reponame>hkotaro1215/invest<filename>src/natcap/invest/coastal_blue_carbon/coastal_blue_carbon.py # -*- coding: utf-8 -*- """Coastal Blue Carbon Model.""" from __future__ import absolute_import import os import logging import math import itertools import time import re import csv import numpy from osgeo import gdal import pygeoprocessing from .. import validation from .. import utils # using largest negative 32-bit floating point number # reasons: practical limit for 32 bit floating point and most outputs should # be positive NODATA_FLOAT = -16777216 LOGGER = logging.getLogger( 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon') _INTERMEDIATE = { 'aligned_lulc_template': 'aligned_lulc_%s.tif', } _OUTPUT = { 'carbon_stock': 'carbon_stock_at_%s.tif', 'carbon_accumulation': 'carbon_accumulation_between_%s_and_%s.tif', 'cabon_emissions': 'carbon_emissions_between_%s_and_%s.tif', 'carbon_net_sequestration': 'net_carbon_sequestration_between_%s_and_%s.tif', } def execute(args): """Coastal Blue Carbon. Args: workspace_dir (str): location into which all intermediate and output files should be placed. results_suffix (str): a string to append to output filenames. lulc_lookup_uri (str): filepath to a CSV table used to convert the lulc code to a name. Also used to determine if a given lulc type is a coastal blue carbon habitat. lulc_transition_matrix_uri (str): generated by the preprocessor. This file must be edited before it can be used by the main model. The left-most column represents the source lulc class, and the top row represents the destination lulc class. carbon_pool_initial_uri (str): the provided CSV table contains information related to the initial conditions of the carbon stock within each of the three pools of a habitat. Biomass includes carbon stored above and below ground. All non-coastal blue carbon habitat lulc classes are assumed to contain no carbon. The values for 'biomass', 'soil', and 'litter' should be given in terms of Megatonnes CO2 e/ ha. carbon_pool_transient_uri (str): the provided CSV table contains information related to the transition of carbon into and out of coastal blue carbon pools. All non-coastal blue carbon habitat lulc classes are assumed to neither sequester nor emit carbon as a result of change. The 'yearly_accumulation' values should be given in terms of Megatonnes of CO2 e/ha-yr. The 'half-life' values must be given in terms of years. The 'disturbance' values must be given as a decimal (e.g. 0.5 for 50%) of stock distrubed given a transition occurs away from a lulc-class. lulc_baseline_map_uri (str): a GDAL-supported raster representing the baseline landscape/seascape. lulc_baseline_year (int): The year of the baseline snapshot. lulc_transition_maps_list (list): a list of GDAL-supported rasters representing the landscape/seascape at particular points in time. Provided in chronological order. lulc_transition_years_list (list): a list of years that respectively correspond to transition years of the rasters. Provided in chronological order. analysis_year (int): optional. Indicates how many timesteps to run the transient analysis beyond the last transition year. Must come chronologically after the last transition year if provided. Otherwise, the final timestep of the model will be set to the last transition year. do_economic_analysis (bool): boolean value indicating whether model should run economic analysis. do_price_table (bool): boolean value indicating whether a price table is included in the arguments and to be used or a price and interest rate is provided and to be used instead. price (float): the price per Megatonne CO2 e at the base year. inflation_rate (float): the interest rate on the price per Megatonne CO2e, compounded yearly. Provided as a percentage (e.g. 3.0 for 3%). price_table_uri (bool): if `args['do_price_table']` is set to `True` the provided CSV table is used in place of the initial price and interest rate inputs. The table contains the price per Megatonne CO2e sequestered for a given year, for all years from the original snapshot to the analysis year, if provided. discount_rate (float): the discount rate on future valuations of sequestered carbon, compounded yearly. Provided as a percentage (e.g. 3.0 for 3%). Example Args:: args = { 'workspace_dir': 'path/to/workspace/', 'results_suffix': '', 'lulc_lookup_uri': 'path/to/lulc_lookup_uri', 'lulc_transition_matrix_uri': 'path/to/lulc_transition_uri', 'carbon_pool_initial_uri': 'path/to/carbon_pool_initial_uri', 'carbon_pool_transient_uri': 'path/to/carbon_pool_transient_uri', 'lulc_baseline_map_uri': 'path/to/baseline_map.tif', 'lulc_baseline_year': <int>, 'lulc_transition_maps_list': [raster1_uri, raster2_uri, ...], 'lulc_transition_years_list': [2000, 2005, ...], 'analysis_year': 2100, 'do_economic_analysis': '<boolean>', 'do_price_table': '<boolean>', 'price': '<float>', 'inflation_rate': '<float>', 'price_table_uri': 'path/to/price_table', 'discount_rate': '<float>' } """ LOGGER.info("Starting Coastal Blue Carbon model run...") d = get_inputs(args) # Setup Logging num_blocks = get_num_blocks(d['C_prior_raster']) blocks_processed = 0. last_time = time.time() # Limit block size here to try to improve memory usage of the application. block_iterator = enumerate(pygeoprocessing.iterblocks( d['C_prior_raster'], largest_block=2**10)) C_nodata = pygeoprocessing.get_raster_info( d['C_prior_raster'])['nodata'][0] for block_idx, (offset_dict, C_prior) in block_iterator: current_time = time.time() blocks_processed += 1. if (current_time - last_time >= 5 or blocks_processed in [0, num_blocks-1]): LOGGER.info('Processing model, about %.2f%% complete', (blocks_processed/num_blocks) * 100) last_time = current_time # Initialization valid_mask = C_prior != C_nodata valid_C_prior = C_prior[valid_mask] timesteps = d['timesteps'] valid_shape = valid_C_prior.shape # timesteps+1 to include initial conditions stock_shape = (timesteps+1,) + valid_shape S_biomass = numpy.zeros(stock_shape, dtype=numpy.float32) # Stock S_soil = numpy.zeros(stock_shape, dtype=numpy.float32) T = numpy.zeros(stock_shape, dtype=numpy.float32) # Total Carbon Stock timestep_shape = (timesteps,) + valid_shape A_biomass = numpy.zeros(timestep_shape, dtype=numpy.float32) # Accumulation A_soil = numpy.zeros(timestep_shape, dtype=numpy.float32) E_biomass = numpy.zeros(timestep_shape, dtype=numpy.float32) # Emissions E_soil = numpy.zeros(timestep_shape, dtype=numpy.float32) # Net Sequestration N_biomass = numpy.zeros(timestep_shape, dtype=numpy.float32) N_soil = numpy.zeros(timestep_shape, dtype=numpy.float32) V = numpy.zeros(timestep_shape, dtype=numpy.float32) # Valuation snapshot_shape = (d['transitions']+1,) + valid_shape L = numpy.zeros(snapshot_shape, dtype=numpy.float32) # Litter transition_shape = (d['transitions'],) + valid_shape # Yearly Accumulation Y_biomass = numpy.zeros(transition_shape, dtype=numpy.float32) Y_soil = numpy.zeros(transition_shape, dtype=numpy.float32) # Disturbance Percentage D_biomass = numpy.zeros(transition_shape, dtype=numpy.float32) D_soil = numpy.zeros(transition_shape, dtype=numpy.float32) H_biomass = numpy.zeros(transition_shape, dtype=numpy.float32) # Half-life H_soil = numpy.zeros(transition_shape, dtype=numpy.float32) # Total Disturbed Carbon R_biomass = numpy.zeros(transition_shape, dtype=numpy.float32) R_soil = numpy.zeros(transition_shape, dtype=numpy.float32) # Set Accumulation and Disturbance Values C_r = [read_from_raster(i, offset_dict)[valid_mask] for i in d['C_r_rasters']] if C_r: # final transition out to analysis year C_list = [valid_C_prior] + C_r + [C_r[-1]] else: C_list = [valid_C_prior]*2 # allow for a final analysis for i in xrange(0, d['transitions']): D_biomass[i] = reclass_transition( C_list[i], C_list[i+1], d['lulc_trans_to_Db'], out_dtype=numpy.float32, nodata_mask=C_nodata) D_soil[i] = reclass_transition( C_list[i], C_list[i+1], d['lulc_trans_to_Ds'], out_dtype=numpy.float32, nodata_mask=C_nodata) H_biomass[i] = reclass( C_list[i], d['lulc_to_Hb'], out_dtype=numpy.float32, nodata_mask=C_nodata) H_soil[i] = reclass( C_list[i], d['lulc_to_Hs'], out_dtype=numpy.float32, nodata_mask=C_nodata) Y_biomass[i] = reclass( C_list[i+1], d['lulc_to_Yb'], out_dtype=numpy.float32, nodata_mask=C_nodata) Y_soil[i] = reclass( C_list[i+1], d['lulc_to_Ys'], out_dtype=numpy.float32, nodata_mask=C_nodata) S_biomass[0] = reclass( valid_C_prior, d['lulc_to_Sb'], out_dtype=numpy.float32, nodata_mask=C_nodata) S_soil[0] = reclass( valid_C_prior, d['lulc_to_Ss'], out_dtype=numpy.float32, nodata_mask=C_nodata) for i in xrange(0, len(C_list)): L[i] = reclass( C_list[i], d['lulc_to_L'], out_dtype=numpy.float32, nodata_mask=C_nodata) T[0] = S_biomass[0] + S_soil[0] R_biomass[0] = D_biomass[0] * S_biomass[0] R_soil[0] = D_soil[0] * S_soil[0] # Transient Analysis for i in xrange(0, timesteps): transition_idx = timestep_to_transition_idx( d['snapshot_years'], d['transitions'], i) if is_transition_year(d['snapshot_years'], d['transitions'], i): # Set disturbed stock values R_biomass[transition_idx] = \ D_biomass[transition_idx] * S_biomass[i] R_soil[transition_idx] = D_soil[transition_idx] * S_soil[i] # Accumulation A_biomass[i] = Y_biomass[transition_idx] A_soil[i] = Y_soil[transition_idx] # Emissions for transition_idx in xrange(0, timestep_to_transition_idx( d['snapshot_years'], d['transitions'], i)+1): try: j = (d['transition_years'][transition_idx] - d['transition_years'][0]) except IndexError: # When we're at the analysis year, we're out of transition # years to calculate for. Transition years represent years # for which we have LULC rasters, and the analysis year # doesn't have a transition LULC associated with it. break E_biomass[i] += R_biomass[transition_idx] * \ (0.5**(i-j) - 0.5**(i-j+1)) E_soil[i] += R_soil[transition_idx] * \ (0.5**(i-j) - 0.5**(i-j+1)) # Net Sequestration N_biomass[i] = A_biomass[i] - E_biomass[i] N_soil[i] = A_soil[i] - E_soil[i] # Next Stock S_biomass[i+1] = S_biomass[i] + N_biomass[i] S_soil[i+1] = S_soil[i] + N_soil[i] T[i+1] = S_biomass[i+1] + S_soil[i+1] # Net Present Value if d['do_economic_analysis']: V[i] = (N_biomass[i] + N_soil[0]) * d['price_t'][i] # Write outputs: T_s, A_r, E_r, N_r, NPV s_years = d['snapshot_years'] num_snapshots = len(s_years) A = A_biomass + A_soil E = E_biomass + E_soil N = N_biomass + N_soil A_r = [sum(A[s_to_timestep(s_years, i):s_to_timestep(s_years, i+1)]) for i in xrange(0, num_snapshots-1)] E_r = [sum(E[s_to_timestep(s_years, i):s_to_timestep(s_years, i+1)]) for i in xrange(0, num_snapshots-1)] N_r = [sum(N[s_to_timestep(s_years, i):s_to_timestep(s_years, i+1)]) for i in xrange(0, num_snapshots-1)] T_s = [T[s_to_timestep(s_years, i)] for i in xrange(0, num_snapshots)] # Add litter to total carbon stock if len(T_s) == len(L): T_s = map(numpy.add, T_s, L) else: T_s = map(numpy.add, T_s, L[:-1]) N_total = numpy.sum(N, axis=0) raster_tuples = [ ('T_s_rasters', T_s), ('A_r_rasters', A_r), ('E_r_rasters', E_r), ('N_r_rasters', N_r)] for key, array in raster_tuples: for i in xrange(0, len(d['File_Registry'][key])): out_array = numpy.empty_like(C_prior, dtype=numpy.float32) out_array[:] = NODATA_FLOAT out_array[valid_mask] = array[i] write_to_raster( d['File_Registry'][key][i], out_array, offset_dict['xoff'], offset_dict['yoff']) N_total_out_array = numpy.empty_like(C_prior, dtype=numpy.float32) N_total_out_array[:] = NODATA_FLOAT N_total_out_array[valid_mask] = N_total write_to_raster( d['File_Registry']['N_total_raster'], N_total_out_array, offset_dict['xoff'], offset_dict['yoff']) if d['do_economic_analysis']: NPV = numpy.sum(V, axis=0) NPV_out_array = numpy.empty_like(C_prior, dtype=numpy.float32) NPV_out_array[:] = NODATA_FLOAT NPV_out_array[valid_mask]
""" Get whether this task has been completed. :return: Whether this task has been completed. """ return self.get_complete_date() is not None def get_short_repr(self) -> typing.Optional[str]: """ Get the short representation of this task. This is can be used to reference this task across Ryver. It has the form PREFIX-ID, and is also unique across the entire organization. If the task board does not have prefixes set up, this will return None. :return: The unique short representation of this task. """ return self._data["short"] def get_position(self) -> int: """ Get the position of this task in its category or the task list. The first task has a position of 0. :return: The position of this task in its category. """ return self._data["position"] def get_comments_count(self) -> int: """ Get how many comments this task has received. :return: The number of comments this task has received. """ return self._data["commentsCount"] def get_attachments_count(self) -> int: """ Get how many attachments this task has. :return: The number of attachments this task has. """ return self._data["attachmentsCount"] def get_tags(self) -> typing.List[str]: """ Get all the tags of this task. .. note:: The tags are returned as a list of strings, not a list of ``TaskTag``s. :return: All the tags of this task, as strings. """ return self._data["tags"] async def get_task_board(self) -> TaskBoard: """ Get the task board this task is in. :return: The task board containing this task. """ return await self.get_deferred_field("board", TYPE_TASK_BOARD) async def get_task_category(self) -> TaskCategory: """ Get the category this task is in. :return: The category containing this task. """ return await self.get_deferred_field("category", TYPE_TASK_CATEGORY) async def get_assignees(self) -> typing.List[User]: """ Get the assignees of this task. :return: The assignees of this task,. """ return await self.get_deferred_field("assignees", TYPE_USER) async def set_complete_date(self, time: typing.Optional[str] = "") -> None: """ Set the complete date of this task, which also marks whether this task is complete. An optional completion time can be specified in the form of an ISO 8601 timestamp with a timezone offset. If not specified or an empty string, the current time will be used. .. tip:: You can use :py:meth:`pyryver.util.datetime_to_iso8601()` to turn datetime objects into timestamps that Ryver will accept. Note that timezone info **must** be present in the timestamp. Otherwise, this will result in a 400 Bad Request. If None is used as the time, in addition to clearing the complete date, this task will also be un-completed. .. note:: This also updates the complete date property in this object. If a time of None is given, this task will be marked as uncomplete. :param time: The completion time (optional). """ if time == "": time = datetime_to_iso8601( datetime.datetime.now(datetime.timezone.utc)) url = self.get_api_url() data = { "completeDate": time } await self._ryver._session.patch(url, json=data) self._data["completeDate"] = time async def set_due_date(self, time: typing.Optional[str]): """ Set the due date of this task. The time must be specified as an ISO 8601 timestamp with a timezone offset. It can also be None, in which case there will be no due date. .. tip:: You can use :py:meth:`pyryver.util.datetime_to_iso8601()` to turn datetime objects into timestamps that Ryver will accept. Note that timezone info **must** be present in the timestamp. Otherwise, this will result in a 400 Bad Request. .. note:: This also updates the due date property in this object. :param time: The new due date. """ url = self.get_api_url() data = { "dueDate": time } await self._ryver._session.patch(url, json=data) self._data["dueDate"] = time async def complete(self) -> None: """ Mark this task as complete. """ await self.set_complete_date() async def uncomplete(self) -> None: """ Mark this task as uncomplete. """ await self.set_complete_date(None) async def archive(self, archived: bool = True) -> None: """ Archive or un-archive this task. :param archived: Whether the task should be archived. """ url = self.get_api_url("Task.Archive()" if archived else "Task.Unarchive()") await self._ryver._session.post(url) async def unarchive(self) -> None: """ Un-archive this task. This is the same as calling :py:meth:`Task.archive()` with False. """ await self.archive(False) async def move(self, category: TaskCategory, position: int) -> None: """ Move this task to another category or to a different position in the same category. .. note:: This also updates the position property of this object. """ url = self.get_api_url( action=f"Task.Move(position={position}, category={category.get_id()})") await self._ryver._session.post(url) self._data["position"] = position async def get_checklist(self, top: int = -1, skip: int = 0) -> typing.AsyncIterator["Task"]: """ Get the checklist items of this task (subtasks). If this task has no checklist, an empty list will be returned. The checklist items are ``Task`` objects; complete or uncomplete those objects to change the checklist status. :param top: Maximum number of results; optional, if unspecified return all results. :param skip: Skip this many results (optional). :return: An async iterator for the tasks in the checklist of this task. """ url = self.get_api_url(action="subTasks") async for task in self._ryver.get_all(url, top, skip): yield Task(self._ryver, task) #NOSONAR async def get_parent(self) -> typing.Optional["Task"]: """ Get the parent task of this sub-task (checklist item). This only works if this task is an item in another task's checklist. Otherwise, this will return None. :return: The parent of this sub-task (checklist item), or None if this task is not a sub-task. """ try: return await self.get_deferred_field("parent", TYPE_TASK) except ValueError: return None async def add_to_checklist(self, items: typing.Iterable[str]) -> None: """ Add items to this task's checklist. :param items: The names of the items to add. """ # Make sure that there is at least one item to add # Otherwise the PATCH request will actually erase all existing subtasks # as the results array is empty. if not items: return data = { "subTasks": { "results": [{"subject": subject} for subject in items] } } url = self.get_api_url( format="json", select="subTasks", expand="subTasks") await self._ryver._session.patch(url, json=data) async def set_checklist(self, items: typing.Iterable["Task"]) -> None: """ Set the contents of this task's checklist. This will overwrite existing checklist items. .. note:: This method should be used for deleting checklist items only. It cannot be used to add new items as the tasks would have to be created first. To add new items, use :py:meth:`Task.add_to_checklist()`. :param items: The items in the checklist. """ # Note: The official client deletes checklist items another way # But I can't get it to work outside the browser data = { "subTasks": { "results": [{"id": item} for item in items] } } url = self.get_api_url() await self._ryver._session.patch(url, json=data) async def edit(self, subject: typing.Optional[str] = NO_CHANGE, body: typing.Optional[str] = NO_CHANGE, category: typing.Optional["TaskCategory"] = NO_CHANGE, assignees: typing.Optional[typing.Iterable[User]] = NO_CHANGE, due_date: typing.Optional[str] = NO_CHANGE, tags: typing.Optional[typing.Union[typing.List[str], typing.List[TaskTag]]] = NO_CHANGE, attachments: typing.Optional[typing.Iterable[typing.Union["Storage", "File"]]] = NO_CHANGE) -> None: """ Edit this task. .. note:: Admins can edit any task regardless of whether they created it. The file attachments (if specified) will **replace** all existing attachments. Additionally, this method also updates these properties in this object. .. note:: While a value of ``None`` for the category in :py:meth:`TaskBoard.create_task()` will result in the task being placed in the "Uncategorized" category, ``None`` is not a valid value for the category in this method, and if used will result in the category being unmodified. This method does not support editing the checklist. To edit the checklist, use :py:meth:`Task.get_checklist()`, :py:meth:`Task.set_checklist()` and :py:meth:`Task.add_to_checklist()`. If any parameters are unspecified or :py:const:`NO_CHANGE`, they will be left as-is. Passing ``None`` for parameters for which ``None`` is not a valid value will also result in the value being unchanged. .. tip:: To attach files to the task, use :py:meth:`pyryver.ryver.Ryver.upload_file()` to upload the files you wish to attach. Alternatively, use :py:meth:`pyryver.ryver.Ryver.create_link()` for link attachments. .. tip:: You can use :py:meth:`pyryver.util.datetime_to_iso8601()` to turn datetime objects into timestamps that Ryver will accept. Note that timezone info **must** be present in the timestamp. Otherwise, this will result in a 400 Bad Request. :param subject: The subject, or title of the task (optional). :param body: The body,
from functools import partial from os.path import join, dirname import pandas as pd import talib from Query import Query from bokeh.io import curdoc from bokeh.layouts import column, layout, row from bokeh.models import Button, Select, TextInput, ColumnDataSource, DataTable, TableColumn, Div, Tabs, Panel, \ CustomJS, NumeralTickFormatter, Range1d, HoverTool, CheckboxGroup, Span, RadioGroup, Spinner from bokeh.models.widgets import DatePicker from bokeh.plotting import figure from numpy import array ################### ## Plot Function ## ################### def quant_plot(df, name, signal=None, param=None): # Select the datetime format for the x axis depending on the timeframe xaxis_dt_format = '%Y/%m/%d' fig = figure(sizing_mode='stretch_both', tools="xpan,xwheel_zoom,tap,reset,box_select,save", active_drag='xpan', active_scroll='xwheel_zoom', x_axis_type='linear', x_range=Range1d(df.index[0] - .5, df.index[-1] + .5, bounds="auto"), title=name, width=1150 ) fig.yaxis[0].formatter = NumeralTickFormatter(format="5.3f") inc = df.close > df.open dec = ~inc # Colour scheme for increasing and descending candles INCREASING_COLOR = '#ff0000' DECREASING_COLOR = '#00ff00' fig.background_fill_color = '#01171f' fig.background_fill_alpha = 0.8 width = 0.5 inc_source = ColumnDataSource(data=dict( x1=df.index[inc], top1=df.open[inc], bottom1=df.close[inc], high1=df.high[inc], low1=df.low[inc], trade_date1=df.trade_date[inc] )) dec_source = ColumnDataSource(data=dict( x2=df.index[dec], top2=df.open[dec], bottom2=df.close[dec], high2=df.high[dec], low2=df.low[dec], trade_date2=df.trade_date[dec] )) # Plot candles # high and low fig.segment(x0='x1', y0='high1', x1='x1', y1='low1', source=inc_source, color=INCREASING_COLOR) fig.segment(x0='x2', y0='high2', x1='x2', y1='low2', source=dec_source, color=DECREASING_COLOR) # open and close r1 = fig.vbar(x='x1', width=width, top='top1', bottom='bottom1', source=inc_source, fill_color=INCREASING_COLOR, line_color="black") r2 = fig.vbar(x='x2', width=width, top='top2', bottom='bottom2', source=dec_source, fill_color=DECREASING_COLOR, line_color="black") # Add on extra lines (e.g. moving averages) here # fig.line(df.index, <your data>) ############ # MA lines # ############ if 'ma5' in df.columns: fig.line(df.index, df.ma5.values, line_color='white', legend_label='MA5') if 'ma10' in df.columns: fig.line(df.index, df.ma10.values, line_color='yellow', legend_label='MA10') if 'ma20' in df.columns: fig.line(df.index, df.ma20.values, line_color='purple', legend_label='MA20') if 'ma60' in df.columns: fig.line(df.index, df.ma60.values, line_color='green', legend_label='MA60') if 'ma120' in df.columns: fig.line(df.index, df.ma120.values, line_color='red', legend_label='MA120') if len(df.columns) > 6: fig.legend.background_fill_alpha = 0.5 # Add on a vertical line to indicate a trading signal here # vline = Span(location=df.index[-<your index>, dimension='height', # line_color="green", line_width=2) # fig.renderers.extend([vline]) ################ # Trade Signal # ################ cum_fig = None if signal in quant_signal_menu: fig.xgrid.grid_line_color = None fig.ygrid.grid_line_color = None if signal == 'MACD': _, holding_signal, _ = talib.MACD(array(df.close), param[0], param[1], param[2]) quick = talib.SMA(array(df.close), param[0]) slow = talib.SMA(array(df.close), param[1]) fig.line(df.index, quick, line_color='white', legend_label='MA%d' % param[0]) fig.line(df.index, slow, line_color='yellow', legend_label='MA%d' % param[1]) fig.legend.background_fill_alpha = 0.5 holding_signal = (holding_signal > 0) trade_signal = [] flag = False for i in holding_signal: if i == flag: trade_signal.append(0) else: trade_signal.append(int(i) - .5) flag = i buy = array(trade_signal) > 0 sell = array(trade_signal) < 0 elif signal == 'BBANDS': high, middle, low = talib.BBANDS(array(df.close), timeperiod=param[0], nbdevup=param[1], nbdevdn=param[2], matype=0) fig.line(df.index, high, line_color='yellow', legend_label='+%1.1f\u03C3' % param[1]) fig.line(df.index, middle, line_color='white', legend_label='MA%d' % param[0]) fig.line(df.index, low, line_color='purple', legend_label='-%1.1f\u03C3' % param[2]) fig.legend.background_fill_alpha = 0.5 flag = False holding = False buy = [] sell = [] for h, m, l in zip(high, df.close, low): if (h > m) & (m > l): flag = True if flag: if h < m: if holding: buy.append(False) else: buy.append(True) holding = True sell.append(False) flag = False continue if m < l: if holding: sell.append(True) holding = False else: sell.append(False) buy.append(False) flag = False continue buy.append(False) sell.append(False) buy = array(buy) sell = array(sell) ############### # Trade Lines # ############### buy_line = [Span(location=i, dimension='height', line_color="red", line_dash='dashed', line_width=2) for i in df.index[buy]] sell_line = [Span(location=i, dimension='height', line_color="green", line_dash='dashed', line_width=2) for i in df.index[sell]] fig.renderers.extend(buy_line + sell_line) cum_return = [] flag = False for index, pair in enumerate(zip(buy, sell)): if pair[0]: cum_return.append(0) flag = True elif pair[1]: cum_return.append(df.pct_chg[index]) flag = False else: if flag: cum_return.append(df.pct_chg[index]) else: cum_return.append(0) cum_return = (array(cum_return) / 100 + 1).cumprod() cum_fig = figure(sizing_mode='stretch_both', tools="pan,wheel_zoom,tap,reset,box_select,save", active_drag='pan', active_scroll='wheel_zoom', x_axis_type='linear', title='累计回报率', x_range=Range1d(df.index[0] - .5, df.index[-1] + .5, bounds="auto"), height=220, margin=(20, 0, 0, 0)) cum_fig.line(df.index, cum_return, color='blue') cum_fig.xaxis.major_label_overrides = { i: date.strftime(xaxis_dt_format) for i, date in enumerate(pd.to_datetime(df["trade_date"], format='%Y%m%d')) } # Add date labels to x axis fig.xaxis.major_label_overrides = { i: date.strftime(xaxis_dt_format) for i, date in enumerate(pd.to_datetime(df["trade_date"], format='%Y%m%d')) } # Set up the hover tooltip to display some useful data fig.add_tools(HoverTool( renderers=[r1], tooltips=[ ("open", "@top1"), ("high", "@high1"), ("low", "@low1"), ("close", "@bottom1"), ("trade_date", "@trade_date1"), ], formatters={ 'trade_date1': 'datetime', })) fig.add_tools(HoverTool( renderers=[r2], tooltips=[ ("open", "@top2"), ("high", "@high2"), ("low", "@low2"), ("close", "@bottom2"), ("trade_date", "@trade_date2") ], formatters={ 'trade_date2': 'datetime' })) # JavaScript callback function to automatically zoom the Y axis to # view the data properly source = ColumnDataSource({'Index': df.index, 'high': df.high, 'low': df.low}) callback = CustomJS(args={'y_range': fig.y_range, 'source': source}, code=''' clearTimeout(window._autoscale_timeout); var Index = source.data.Index, low = source.data.low, high = source.data.high, start = cb_obj.start, end = cb_obj.end, min = Infinity, max = -Infinity; for (var i=0; i < Index.length; ++i) { if (start <= Index[i] && Index[i] <= end) { max = Math.max(high[i], max); min = Math.min(low[i], min); } } var pad = (max - min) * .05; window._autoscale_timeout = setTimeout(function() { y_range.start = min - pad; y_range.end = max + pad; }); ''') # Finalise the figure fig.x_range.js_event_callbacks = {'callback': [callback]} return fig, cum_fig ###################### ## Global Variable ## ###################### # Info q = Query() info_table_dict = q.get_tables() info_menu = list(info_table_dict.values()) info_menu_dict = dict(zip(info_menu, list(info_table_dict.keys()))) # Map from Chinese labels to English names of table info_table_func = q.stock_basic info_filter = {'limit': 100, 'trade_date': (20100101, 20200531)} info_date_available = False info_div_date_func = lambda x: x[:4] + '/' + x[4:6] + '/' + x[6:] # Print date # Quant quant_filter = {'trade_date': (20200101, 20200531), 'ts_code': ['000001']} quant_columns = ['trade_date', 'high', 'low', 'open', 'close', 'pct_chg'] quant_ma = {x: y for x, y in list(enumerate(['ma5', 'ma10', 'ma20', 'ma60', 'ma120']))} quant_signal_menu = ['MACD', 'BBANDS'] ############# ## Widgets ## ############# # Info info_start_date = DatePicker(title="起始日期", min_date='2010-01-01', max_date='2020-05-31', value='2010-01-01', width=140, visible=False) info_end_date = DatePicker(title="结束日期", min_date='2010-01-01', max_date='2020-05-31', value='2020-05-31', width=140, visible=False) info_select = Select(title="请选择", value="股票列表", options=info_menu, width=150) info_confirm = Button(label="查询", button_type="success", width=100) info_text = TextInput(title="TS代码(多个代码请用英文,分隔)", width=150) info_div = Div(text='请选择筛选条件,并按「查询」按钮确认。', width=600) info_df = DataTable(source=ColumnDataSource(pd.DataFrame()), width=1150, height=500) info_download = Button(label='下载', button_type='success', width=100, visible=False) info_limit = Spinner(title='限制条数(-1为无限制)', width=150, value=100, visible=False, low=-1) info_token = TextInput(title='Token', width=150) # Quant quant_start_date = DatePicker(title="起始日期", min_date='2010-01-01', max_date='2020-05-31', value='2020-01-01', width=140) quant_end_date = DatePicker(title="结束日期", min_date='2010-01-01', max_date='2020-05-31', value='2020-05-31', width=140) quant_text = TextInput(title="TS代码", width=150, value='000001') quant_confirm = Button(label="刷新", button_type="success", width=100) quant_option = CheckboxGroup( labels=["5日均线", "10日均线", "20日均线", '60日均线', '120日均线'], width=150, margin=(20, 0, 0, 0)) quant_select = Select(title='交易指标', value='无指标', options=['无指标', 'MACD', 'BBANDS'], width=150) quant_signal = None quant_param_MACD = [26, 12, 9] quant_param_BBANDS = [5, 2, 2] quant_MACD_long = Spinner(title='快变指数移动平均天数', value=26, width=150, visible=False, low=0) quant_MACD_short = Spinner(title='慢变指数移动平均天数', value=12, width=150, visible=False, low=0) quant_MACD_DEM = Spinner(title='差离平均天数', value=9, width=150, visible=False, low=0) return_plot = figure(visible=False, height=220, margin=(20, 0, 0, 0)) quant_div = Div(text='', width=150) quant_radio = RadioGroup(labels=["股票", "场内基金"], active=0, inline=True) quant_BBANDS_timeperiod = Spinner(title='移动平均天数', value=5, width=150, visible=False, low=0) quant_BBANDS_nbdevup = Spinner(title='上轨标准差(倍)', value=2, width=150, visible=False, low=0, step=.1) quant_BBANDS_nbdevdn = Spinner(title='下轨标准差(倍)', value=2, width=150, visible=False, low=0, step=.1) ############### ## Callback ## ############### def textChange(attr, old, new: str, name): if name == 'info': info_filter['ts_code'] = new.split(',') divChange('info') elif name == 'quant': quant_filter['ts_code'] = [new] elif name == 'MACD_long': quant_param_MACD[0] = int(new) elif name == 'MACD_short': quant_param_MACD[1] = int(new) elif name == 'MACD_DEM': quant_param_MACD[2] = int(new) elif name == 'BBANDS_timeperiod': quant_param_BBANDS[0] = int(new) elif name == 'BBANDS_nbdevup': quant_param_BBANDS[1] = float(new) elif name == 'BBANDS_nbdevdn': quant_param_BBANDS[2] = float(new) def selectChange(attr, old, new: str, name=None): if name == 'info': global info_table_func, info_date_available, quant_signal info_table_func = getattr(q, info_menu_dict[new]) available_filter = list(q.search(table=info_menu_dict[new]).keys()) if 'trade_date' in available_filter: info_date_available = True info_start_date.visible = True info_end_date.visible = True else: info_date_available = False info_start_date.visible = False info_end_date.visible = False divChange('info') elif name == 'quant': quant_signal = new return_plot.visible = False quant_MACD_long.visible = False quant_MACD_short.visible = False quant_MACD_DEM.visible = False quant_BBANDS_timeperiod.visible = False quant_BBANDS_nbdevup.visible = False quant_BBANDS_nbdevdn.visible = False if quant_signal in quant_signal_menu: return_plot.visible = True if quant_signal == 'MACD': quant_MACD_long.visible = True quant_MACD_short.visible = True quant_MACD_DEM.visible = True elif quant_signal == 'BBANDS': quant_BBANDS_timeperiod.visible = True quant_BBANDS_nbdevup.visible = True quant_BBANDS_nbdevdn.visible = True def dateChange(attr, old, new, name): if name == 'info': info_filter['trade_date'] = (int(''.join(info_start_date.value.split('-'))), int(''.join(info_end_date.value.split('-')))) info_start_date.max_date = info_end_date.value info_end_date.min_date = info_start_date.value divChange('info') elif name == 'quant': quant_filter['trade_date'] = (int(''.join(quant_start_date.value.split('-'))), int(''.join(quant_end_date.value.split('-')))) quant_start_date.max_date = quant_end_date.value quant_end_date.min_date = quant_start_date.value def divChange(status, tab='info'): if tab == 'info': if status == 'info': if info_filter['limit'] == -1: info_div.text = '<b> 上限:无限制 </b>' else: info_div.text = '<b> 上限:%s条 </b>' % info_filter['limit'] if info_start_date.visible: info_div.text += '<br><b> 日期:%s至%s </b>' % (info_div_date_func(str(info_filter['trade_date'][0])), info_div_date_func(str(info_filter['trade_date'][1]))) if info_filter.get('ts_code', False): info_div.text += '<br><b> TS代码:%s </b>' % ','.join(info_filter['ts_code']) elif status == 'end': info_div.text = '<b> 查询完成! </b>' else: info_div.text = '<b> %s </b>' % status elif tab == 'quant': quant_div.text = '<b> %s </b>' % status def dfChange(): try: if (not info_date_available) & bool(info_filter.get('trade_date', 0)): info_filter_without_date = info_filter.copy() del
' % vm_str if 'msg_cat' in self._log_prefixes : line += '%s' % line_data.msg_cat missing_spaces = 8 - len( line_data.msg_cat ) line += ' ' * missing_spaces if self._log_prefixes : line += '|' line += line_data.msg_rest else : # remove the first char (a space) line += line_data.msg_rest[1:] current_item = QtGui.QListWidgetItem( line ) current_item.as_line_data = line_data #################################################################### # Find the accurate icon #################################################################### if self._show_icons : icon = None line_type = line_data.msg_content[ 'type' ] if line_type in [ 'loaded_mesh_file', 'while_loading_mesh_object' ] : icon = self.icons[ 'mesh' ] elif line_type == 'scene_bounding_box' : icon = self.icons[ 'bbox' ] elif line_type == 'scene_diameter' : icon = self.icons[ 'diameter' ] elif line_type == 'rendering_progress' : icon = self.icons[ 'progress' ] elif line_type == 'opening_texture_file' : icon = self.icons[ 'texture' ] else : icon = self.icons[ 'empty' ] if icon : current_item.setIcon( icon ) self.filtered_log_listWidget.addItem( current_item ) self.filtered_log_listWidget.setIconSize( QtCore.QSize(13, 13) ) def refresh_options_tab( self ) : options = dict() if self._current_log in self._log_datas : current_log_data = self._log_datas[ self._current_log ] options = current_log_data.render_options ######################################################################## # Frame Setting ######################################################################## frame_setting_options = dict() if 'frame_settings' in options : frame_setting_options = options[ 'frame_settings' ] label_str = 'Not found' if 'resolution' in frame_setting_options : x, y = frame_setting_options[ 'resolution' ] label_str = '%s x %s' % ( y, x ) self.frame_setting_resolution_value_label.setText( label_str ) label_str = 'Not found' if 'tile_size' in frame_setting_options : x, y = frame_setting_options[ 'tile_size' ] label_str = '%s x %s' % ( y, x ) self.frame_setting_tile_size_value_label.setText( label_str ) label_str = 'Not found' if 'pixel_format' in frame_setting_options : label_str = str( frame_setting_options[ 'pixel_format' ] ) self.frame_setting_pixel_format_value_label.setText( label_str ) label_str = 'Not found' if 'filter' in frame_setting_options : label_str = str( frame_setting_options[ 'filter' ] ) self.frame_setting_filter_value_label.setText( label_str ) label_str = 'Not found' if 'filter_size' in frame_setting_options : label_str = str( frame_setting_options[ 'filter_size' ] ) self.frame_setting_filter_size_value_label.setText( label_str ) label_str = 'Not found' if 'color_space' in frame_setting_options : label_str = str( frame_setting_options[ 'color_space' ] ) self.frame_setting_color_space_value_label.setText( label_str ) label_str = 'Not found' if 'premult_alpha' in frame_setting_options : label_str = 'on' if frame_setting_options[ 'premult_alpha' ] else 'off' self.frame_setting_premult_alpha_value_label.setText( label_str ) label_str = 'Not found' if 'clamping' in frame_setting_options : label_str = 'on' if frame_setting_options[ 'clamping' ] else 'off' self.frame_setting_clamping_value_label.setText( label_str ) label_str = 'Not found' if 'gamma_correction' in frame_setting_options : label_str = str( frame_setting_options[ 'gamma_correction' ] ) self.frame_setting_gamma_correction_value_label.setText( label_str ) label_str = 'Not found' if 'crop_window' in frame_setting_options : label_str = '%s x %s - %s x %s' % frame_setting_options[ 'crop_window' ] self.frame_setting_crop_window_value_label.setText( label_str ) def refresh_log_level_cb( self ) : state = QtCore.Qt.Checked if 'info' in self._log_levels else QtCore.Qt.Unchecked if state != self.info_cb.checkState() : self.info_cb.setCheckState( state ) state = QtCore.Qt.Checked if 'warning' in self._log_levels else QtCore.Qt.Unchecked if state != self.warning_cb.checkState() : self.warning_cb.setCheckState( state ) state = QtCore.Qt.Checked if 'error' in self._log_levels else QtCore.Qt.Unchecked if state != self.error_cb.checkState() : self.error_cb.setCheckState( state ) state = QtCore.Qt.Checked if 'fatal' in self._log_levels else QtCore.Qt.Unchecked if state != self.fatal_cb.checkState() : self.fatal_cb.setCheckState( state ) all_cb_state = self.all_cb.checkState() if self._log_levels == set( [ 'info', 'warning', 'error', 'fatal' ] ) : if all_cb_state != QtCore.Qt.Checked : self.all_cb.setCheckState( QtCore.Qt.Checked ) elif len( self._log_levels ) : if all_cb_state != QtCore.Qt.PartiallyChecked : self.all_cb.setCheckState( QtCore.Qt.PartiallyChecked ) elif all_cb_state != QtCore.Qt.Unchecked : self.all_cb.setCheckState( QtCore.Qt.Unchecked ) def refresh_log_prefix_cb( self ) : state = QtCore.Qt.Checked if self._show_icons else QtCore.Qt.Unchecked if state != self.icon_cb.checkState() : self.icon_cb.setCheckState( state ) state = QtCore.Qt.Checked if 'timestamp' in self._log_prefixes else QtCore.Qt.Unchecked if state != self.timestamp_cb.checkState() : self.timestamp_cb.setCheckState( state ) state = QtCore.Qt.Checked if 'thread_id' in self._log_prefixes else QtCore.Qt.Unchecked if state != self.thread_id_cb.checkState() : self.thread_id_cb.setCheckState( state ) state = QtCore.Qt.Checked if 'vm' in self._log_prefixes else QtCore.Qt.Unchecked if state != self.vm_cb.checkState() : self.vm_cb.setCheckState( state ) state = QtCore.Qt.Checked if 'msg_cat' in self._log_prefixes else QtCore.Qt.Unchecked if state != self.msg_cat_cb.checkState() : self.msg_cat_cb.setCheckState( state ) def cb_filtered_log_view_menu( self, pt ) : """Generate the menu for the log view.""" def short_label( text ) : """Used to shorten the action label complement.""" if len( text ) > 30 : return '"%s..."' % text[:27] else : return '"%s"' % text # Get selection selected_items = self.filtered_log_listWidget.selectedItems() menu = QtGui.QMenu( self ) if len( selected_items ) == 1 : selected_item = selected_items[0] line_data = selected_item.as_line_data # Copy visible line act = QtGui.QAction( self.icons[ 'copy' ], 'Copy' , menu ) act.triggered.connect( functools.partial( self.cb_copy, selected_item.text() ) ) menu.addAction( act ) # Copy whole line (only if user has changed the line view ) if self._log_levels != set( [ 'info', 'warning', 'error', 'fatal' ] ) or \ self._log_prefixes != set( [ 'timestamp', 'thread_id', 'vm', 'msg_cat' ] ) : act = QtGui.QAction( self.icons[ 'copy' ], 'Copy whole line' , menu ) act.triggered.connect( functools.partial( self.cb_copy, line_data.line ) ) menu.addAction( act ) if line_data.msg_content[ 'type' ] == 'loading_project_file' : project_file_path = line_data.msg_content[ 'project_file_path' ] label = 'Copy project file path: %s' % short_label( project_file_path ) act = QtGui.QAction( self.icons[ 'copy' ] , label , menu ) act.triggered.connect( functools.partial( self.cb_copy , project_file_path ) ) menu.addAction( act ) elif line_data.msg_content[ 'type' ] == 'opening_texture_file' : texture_path = line_data.msg_content[ 'texture_path' ] label = 'Copy texture file path: %s' % short_label( texture_path ) act = QtGui.QAction( self.icons[ 'copy' ] , label , menu ) act.triggered.connect( functools.partial( self.cb_copy , texture_path ) ) menu.addAction( act ) elif line_data.msg_content[ 'type' ] == 'wrote_image_file' : image_path = line_data.msg_content[ 'image_path' ] label = 'Copy image file path: %s' % short_label( image_path ) act = QtGui.QAction( self.icons[ 'copy' ] , label , menu ) act.triggered.connect( functools.partial( self.cb_copy , image_path ) ) menu.addAction( act ) elif line_data.msg_content[ 'type' ] == 'loaded_mesh_file' : mesh_path = line_data.msg_content[ 'mesh_path' ] label = 'Copy image file path: %s' % short_label( mesh_path ) act = QtGui.QAction( self.icons[ 'copy' ] , label , menu ) act.triggered.connect( functools.partial( self.cb_copy , mesh_path ) ) menu.addAction( act ) elif len( selected_items ) > 1 : raw_text = str() # The text that will be put in the clipboard for selected_item in selected_items : raw_text += '%s\n' % selected_item.text() act = QtGui.QAction( self.icons[ 'copy' ], 'Copy' , menu ) act.triggered.connect( functools.partial( self.cb_copy, raw_text ) ) menu.addAction( act ) # Copy whole lines if self._log_levels != set( [ 'info', 'warning', 'error', 'fatal' ] ) or \ self._log_prefixes != set( [ 'timestamp', 'thread_id', 'vm', 'msg_cat' ] ) : raw_str = str() for selected_item in selected_items : line_data = selected_item.as_line_data raw_str += '%s\n' % line_data.line act = QtGui.QAction( self.icons[ 'copy' ], 'Copy whole lines' , menu ) act.triggered.connect( functools.partial( self.cb_copy, raw_str ) ) menu.addAction( act ) menu.exec_( self.filtered_log_listWidget.mapToGlobal( pt ) ) def cb_recent_log_view_menu( self, pt ) : """Generate the context menu for the recent log file listWidget.""" # Get selection selected_items = self.recent_log_files_listWidget.selectedItems() menu = QtGui.QMenu( self ) if len( selected_items ) == 1 : selected_item = selected_items[0] log_file_path = selected_item.as_log_file_path # Copy log file path act = QtGui.QAction( self.icons[ 'copy' ], 'Copy file path' , menu ) act.triggered.connect( functools.partial( self.cb_copy, log_file_path ) ) menu.addAction( act ) # Copy log folder path log_dir_path = os.path.dirname( log_file_path ) act = QtGui.QAction( self.icons[ 'copy' ], 'Copy folder path' , menu ) act.triggered.connect( functools.partial( self.cb_copy, log_dir_path ) ) menu.addAction( act ) # Open in folder path log_dir_path = os.path.dirname( log_file_path ) act = QtGui.QAction( self.icons[ 'open' ], 'Open log folder' , menu ) act.triggered.connect( functools.partial( self.cb_dir_open, log_dir_path ) ) menu.addAction( act ) # Remove entry act = QtGui.QAction( self.icons[ 'remove' ], 'Remove log entry' , menu ) act.triggered.connect( functools.partial( self.remove_log_entry, log_file_path ) ) menu.addAction( act ) menu.exec_( self.recent_log_files_listWidget.mapToGlobal( pt ) ) def cb_log_level_changed( self, *args ) : log_type = args[0] state = args[1] if log_type == "ALL" : if state : self._log_levels = set( [ 'info', 'warning', 'error', 'fatal' ] ) else : self._log_levels = set() else : if state : self._log_levels.add( log_type ) else : self._log_levels.remove( log_type ) self.refresh_log_level_cb() self.refresh_filtered_log_view() def cb_log_prefix_changed( self, *args ) : prefix = args[0] state = args[1] if state : self._log_prefixes.add( prefix ) else : self._log_prefixes.remove( prefix )
pending messages in the queue have been processed. """ while self.messages_pending(): await self.do_work_async() async def send_message_async(self, messages, close_on_done=False): """Send a single message or batched message asynchronously. :param messages: A message to send. This can either be a single instance of ~uamqp.message.Message, or multiple messages wrapped in an instance of ~uamqp.message.BatchMessage. :type message: ~uamqp.message.Message :param close_on_done: Close the client once the message is sent. Default is `False`. :type close_on_done: bool :raises: ~uamqp.errors.MessageException if message fails to send after retry policy is exhausted. """ batch = messages.gather() pending_batch = [] for message in batch: message.idle_time = self._counter.get_current_ms() async with self._pending_messages_lock: self._pending_messages.append(message) pending_batch.append(message) await self.open_async() try: while any([m for m in pending_batch if m.state not in constants.DONE_STATES]): await self.do_work_async() failed = [m for m in pending_batch if m.state == constants.MessageState.SendFailed] if any(failed): details = {"total_messages": len(pending_batch), "number_failed": len(failed)} details['failed_messages'] = {} exception = None for failed_message in failed: exception = failed_message._response # pylint: disable=protected-access details['failed_messages'][failed_message] = exception raise errors.ClientMessageError(exception, info=details) finally: if close_on_done: await self.close_async() async def send_all_messages_async(self, close_on_done=True): """Send all pending messages in the queue asynchronously. This will return a list of the send result of all the pending messages so it can be determined if any messages failed to send. This function will open the client if it is not already open. :param close_on_done: Close the client once the messages are sent. Default is `True`. :type close_on_done: bool :rtype: list[~uamqp.constants.MessageState] """ await self.open_async() try: async with self._pending_messages_lock: messages = self._pending_messages[:] await self.wait_async() results = [m.state for m in messages] return results finally: if close_on_done: await self.close_async() class ReceiveClientAsync(client.ReceiveClient, AMQPClientAsync): """An AMQP client for receiving messages asynchronously. :param target: The source AMQP service endpoint. This can either be the URI as a string or a ~uamqp.address.Source object. :type target: str, bytes or ~uamqp.address.Source :param auth: Authentication for the connection. This should be one of the subclasses of uamqp.authentication.AMQPAuth. Currently this includes: - uamqp.authentication.SASLAnonymous - uamqp.authentication.SASLPlain - uamqp.authentication.SASTokenAsync If no authentication is supplied, SASLAnnoymous will be used by default. :type auth: ~uamqp.authentication.common.AMQPAuth :param client_name: The name for the client, also known as the Container ID. If no name is provided, a random GUID will be used. :type client_name: str or bytes :param loop: A user specified event loop. :type loop: ~asycnio.AbstractEventLoop :param debug: Whether to turn on network trace logs. If `True`, trace logs will be logged at INFO level. Default is `False`. :type debug: bool :param timeout: A timeout in milliseconds. The receiver will shut down if no new messages are received after the specified timeout. If set to 0, the receiver will never timeout and will continue to listen. The default is 0. :type timeout: float :param auto_complete: Whether to automatically settle message received via callback or via iterator. If the message has not been explicitly settled after processing the message will be accepted. Alternatively, when used with batch receive, this setting will determine whether the messages are pre-emptively settled during batching, or otherwise let to the user to be explicitly settled. :type auto_complete: bool :param error_policy: A policy for parsing errors on link, connection and message disposition to determine whether the error should be retryable. :type error_policy: ~uamqp.errors.ErrorPolicy :param keep_alive_interval: If set, a thread will be started to keep the connection alive during periods of user inactivity. The value will determine how long the thread will sleep (in seconds) between pinging the connection. If 0 or None, no thread will be started. :type keep_alive_interval: int :param send_settle_mode: The mode by which to settle message send operations. If set to `Unsettled`, the client will wait for a confirmation from the service that the message was successfully sent. If set to 'Settled', the client will not wait for confirmation and assume success. :type send_settle_mode: ~uamqp.constants.SenderSettleMode :param receive_settle_mode: The mode by which to settle message receive operations. If set to `PeekLock`, the receiver will lock a message once received until the client accepts or rejects the message. If set to `ReceiveAndDelete`, the service will assume successful receipt of the message and clear it from the queue. The default is `PeekLock`. :type receive_settle_mode: ~uamqp.constants.ReceiverSettleMode :param desired_capabilities: The extension capabilities desired from the peer endpoint. To create an desired_capabilities object, please do as follows: - 1. Create an array of desired capability symbols: `capabilities_symbol_array = [types.AMQPSymbol(string)]` - 2. Transform the array to AMQPValue object: `utils.data_factory(types.AMQPArray(capabilities_symbol_array))` :type desired_capabilities: ~uamqp.c_uamqp.AMQPValue :param max_message_size: The maximum allowed message size negotiated for the Link. :type max_message_size: int :param link_properties: Metadata to be sent in the Link ATTACH frame. :type link_properties: dict :param prefetch: The receiver Link credit that determines how many messages the Link will attempt to handle per connection iteration. The default is 300. :type prefetch: int :param max_frame_size: Maximum AMQP frame size. Default is 63488 bytes. :type max_frame_size: int :param channel_max: Maximum number of Session channels in the Connection. :type channel_max: int :param idle_timeout: Timeout in milliseconds after which the Connection will close if there is no further activity. :type idle_timeout: int :param properties: Connection properties. :type properties: dict :param remote_idle_timeout_empty_frame_send_ratio: Ratio of empty frames to idle time for Connections with no activity. Value must be between 0.0 and 1.0 inclusive. Default is 0.5. :type remote_idle_timeout_empty_frame_send_ratio: float :param incoming_window: The size of the allowed window for incoming messages. :type incoming_window: int :param outgoing_window: The size of the allowed window for outgoing messages. :type outgoing_window: int :param handle_max: The maximum number of concurrent link handles. :type handle_max: int :param on_attach: A callback function to be run on receipt of an ATTACH frame. The function must take 4 arguments: source, target, properties and error. :type on_attach: func[~uamqp.address.Source, ~uamqp.address.Target, dict, ~uamqp.errors.AMQPConnectionError] :param encoding: The encoding to use for parameters supplied as strings. Default is 'UTF-8' :type encoding: str """ def __init__( self, source, auth=None, client_name=None, loop=None, debug=False, timeout=0, auto_complete=True, error_policy=None, keep_alive_interval=None, **kwargs): self.loop = loop or get_running_loop() client.ReceiveClient.__init__( self, source, auth=auth, client_name=client_name, debug=debug, timeout=timeout, auto_complete=auto_complete, error_policy=error_policy, keep_alive_interval=keep_alive_interval, **kwargs) # AMQP object settings self.receiver_type = MessageReceiverAsync async def _client_ready_async(self): """Determine whether the client is ready to start receiving messages. To be ready, the connection must be open and authentication complete, The Session, Link and MessageReceiver must be open and in non-errored states. :rtype: bool :raises: ~uamqp.errors.MessageHandlerError if the MessageReceiver goes into an error state. """ # pylint: disable=protected-access if not self.message_handler: self.message_handler = self.receiver_type( self._session, self._remote_address, self._name, on_message_received=self._message_received, name='receiver-link-{}'.format(uuid.uuid4()), debug=self._debug_trace, receive_settle_mode=self._receive_settle_mode, send_settle_mode=self._send_settle_mode, prefetch=self._prefetch, max_message_size=self._max_message_size, properties=self._link_properties, error_policy=self._error_policy, encoding=self._encoding, desired_capabilities=self._desired_capabilities, executor=self._connection._executor, loop=self.loop) await asyncio.shield(self.message_handler.open_async()) return False if self.message_handler.get_state() == constants.MessageReceiverState.Error: raise errors.MessageHandlerError( "Message Receiver Client is in an error state. " "Please confirm credentials and access permissions." "\nSee debug trace for more details.") if self.message_handler.get_state() != constants.MessageReceiverState.Open: self._last_activity_timestamp = self._counter.get_current_ms() return False return True async def _client_run_async(self): """MessageReceiver Link is now open - start receiving messages. Will return True if operation successful and client can remain open for further work. :rtype: bool """ await self.message_handler.work_async() await self._connection.work_async() now = self._counter.get_current_ms() if self._last_activity_timestamp and not self._was_message_received: # If no messages are coming through, back off a little to keep CPU use low. await asyncio.sleep(0.05) if self._timeout > 0: timespan = now - self._last_activity_timestamp if timespan >= self._timeout: _logger.info("Timeout reached, closing receiver.") self._shutdown = True else: self._last_activity_timestamp = now self._was_message_received = False return True async def receive_messages_async(self, on_message_received): """Receive messages asynchronously. This function will run indefinitely, until the client closes either via timeout, error or forced interruption (e.g. keyboard interrupt). If the receive client is configured with `auto_complete=True` then the messages that have not been settled on completion of the provided callback will automatically be accepted provided it has not expired. If an error occurs or the message has expired it will be released. Alternatively if `auto_complete=False`, each message will need to be explicitly settled during the callback, otherwise it will be released. :param on_message_received: A callback to process messages as they arrive from the service. It
in arrayName: fctName, params = str2FctParams(arrayName) #print("Function : %s(%s)"%(fctName, ",".join(params))) fct = getSubAttr(obj, fctName) paramsNameFirstIdxNbFloats = list() for param in params: #print("param :", param) nameFirstIdxNbFloats = infoArray(objName, param, arrayNames2Info) if nameFirstIdxNbFloats is None: break paramsNameFirstIdxNbFloats.append(nameFirstIdxNbFloats) if len(paramsNameFirstIdxNbFloats) >= 1 : self.fctLstXY.append((fct, paramsNameFirstIdxNbFloats)) else: nameFirstIdxNbFloats = infoArray(objName, arrayName, arrayNames2Info) if nameFirstIdxNbFloats is not None: self.varLstXY.append(nameFirstIdxNbFloats) def plot(self): print("Recorder.plot()") import matplotlib.pyplot as plt nbSubplot = len(self.tPltLst) rcds = self.records[:self.recordIdx, :] ts = rcds[:, 0] minTime = 0.0 maxTime = np.amax(ts) timeRange = (minTime, maxTime) timeTicks = np.arange(minTime, maxTime+1e-9, maxTime/20) fig = plt.figure(figsize=(20, 11)) # default left=0.125,right=0.9,bottom=0.1,top=0.9,wspace=0.2,hspace=0.2 fig.subplots_adjust(top=0.96,bottom=0.03, left=0.04,right=0.98, hspace=0.4) #tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None) i = 0 for name, (unitY, rangeY, varsLst, fctsLst) in self.tPltLst.items(): i += 1 ax = fig.add_subplot(nbSubplot, 1, i) ax.set_xlim(timeRange) ax.set_xticks(timeTicks) if rangeY is not None: ax.set_ylim(rangeY) minY, maxY = rangeY deltaY = maxY - minY ax.set_yticks(np.arange(minY, maxY+deltaY*1e-6, deltaY/8)) ax.grid() for varName, firstIdx, nbFloats in varsLst: ax.plot(ts, rcds[:, firstIdx:firstIdx+nbFloats], '-') for fct, paramsNameFirstIdxNbFloats in fctsLst: params = list() for paramNameFirstIdxNbFloats in paramsNameFirstIdxNbFloats: varName, firstIdx, nbFloats = paramNameFirstIdxNbFloats param = rcds[:, firstIdx:firstIdx+nbFloats] params.append(param) print("fct :%s ; param shape"%fct.__name__, param.shape) calculated = fct(*params) print("calculated.shape", calculated.shape) ax.plot(ts, calculated, '-') plt.title(name) if 1: # XY graph fig = plt.figure(figsize=(15, 10)) varName, firstIdx, nbFloats = self.varLstXY[0] # pos xys = rcds[:, firstIdx:firstIdx+nbFloats] varName, firstIdx, nbFloats = self.varLstXY[1] # wingForce wfxys = rcds[:, firstIdx:firstIdx+nbFloats] # rapport de bras de levier varName, firstIdx, nbFloats = self.varLstXY[2] # stabForce sfxys = rcds[:, firstIdx:firstIdx+nbFloats] if 0: varName, firstIdx, nbFloats = self.varLstXY[3] dxys = rcds[:, firstIdx:firstIdx+nbFloats] varName, firstIdx, nbFloats = self.varLstXY[4] # accel axys = rcds[:, firstIdx:firstIdx+nbFloats] plt.plot(xys[:,0], xys[:, 1], '.-b') plt.quiver(xys[:,0], xys[:, 1], wfxys[:,0], wfxys[:, 1], color='r', scale=1000, width=0.002) # plt.quiver(xys[:,0], xys[:, 1], sfxys[:,0], sfxys[:, 1], color='m', scale= 200, width=0.002) # #plt.quiver(xys[:,0], xys[:, 1], dxys[:,0], dxys[:, 1], color='r', scale=10, width=0.002) # #plt.quiver(xys[:,0], xys[:, 1], axys[:,0], axys[:, 1], color='c', scale=100, width=0.002) # plt.axis('equal') plt.grid() plt.show() class Simulation(object): def __init__(self, wind=None): self.t = np.zeros((1,)) # time in sec self.objDict = dict() self.wind = wind self.recorder = Recorder(self) def add(self, obj, name): obj.simul = self self.objDict[name] = obj #def addToRecorderList(self, objName, floatArraysNames): self.recorder.addToLst(objName, floatArraysNames) def addToRecorderList(self, *args) : self.recorder.addToLst (*args) def addPlotVsTime (self, *args) : self.recorder.addPlotVsTime(*args) def addToPlot (self, *args) : self.recorder.addToPlot (*args) def addToPlotXY (self, *args) : self.recorder.addToPlotXY (*args) def plot (self, *args) : self.recorder.plot (*args) def info(self): #print(self.atm.info()) print(self.plane.info()) def step(self, t, dt): for name, obj in self.objDict.items(): obj.step(t, dt) def start(self, end_t=1.0, dt=10e-3, underSampling=1): self.dt = dt self.underSampling = underSampling self.end_t = end_t - 1e-3*self.dt for name, obj in self.objDict.items(): obj.launch() self.end_t = end_t - 1e-3*self.dt nbRecord = int(self.end_t/self.dt)//self.underSampling + 2 self.recorder.start(nbRecord=nbRecord) self.samplingCnt = 0 self.run() def run(self): self.end = 0 while self.end == 0 : if self.t >= self.end_t : print("normal stop at %6.3f s"%self.t) self.end = 1 # normal stop by time self.step(self.t, self.dt) self.t += self.dt self.samplingCnt += 1 if self.samplingCnt >= self.underSampling : self.recorder.record() self.samplingCnt = 0 print("End simulation") def info(self): print("Simulation info") class MechanicPoint(object): def __init__(self, mass=1.0, initialPos=(0.0,10.0), initialSpeed=(0.0, 0.0)): self.simul = None self.mass = mass # kg self.initialPos = initialPos # m self.initialSpeed = initialSpeed # m/s self.accel = np.zeros(vecShape) # m/s2 self.speed = np.zeros(vecShape) # m/s self.pos = np.zeros(vecShape) # m self.force = np.zeros(vecShape) # Newton def info(self): return "mass:%6.3f kg"%(self.mass) def energyKin(self, speed): # speed could be np.array #print("MechanicPoint.energyKin : speed.shape :", speed.shape) print("speed.shape :", speed.shape) n, m = speed.shape spd = np.zeros((n,1)) spd[:,0] = speed[:,0]**2 + speed[:,1]**2 print("spd.shape :", spd.shape) return 0.5 * self.mass * spd def energyPot(self, altitude): # altitude could be np.array return self.mass * g * altitude def energyTot(self, speed, altitude): ep = self.energyPot(altitude) print("ep.shape :", ep.shape) ek = self.energyKin(speed) print("ek.shape :", ek.shape) et = ek + ep print("et.shape :", et.shape) return et def launch(self): self.pos [:] = self.initialPos self.speed[:] = self.initialSpeed self.force[:] = 0.0, self.mass * -g # suppose objet stand on ground self.accel[:] = gravity[:] + self.force/self.mass def step(self, t, dt=0.1): self.accel[:] = gravity[:] + self.force/self.mass self.speed += self.accel * dt self.pos += self.speed * dt def CalculateMassInertiaCenterOfGravity(massDist): # moment of inertia / Mass*dist**2 mass, balance, inertia = 0.0, 0.0, 0.0 for m, d in massDist: mass += m balance += m * d inertia += m * d**2 centerOfGravity = balance / mass print("mass : %5.3f kg, GC: %5.3f m, inertia:%6.4f kgm2"%(mass, centerOfGravity, inertia)) return mass, centerOfGravity, inertia class MechanicObject(MechanicPoint): def __init__(self, massDist=((0.2,-0.6),(0.2,0.0),(0.6,0.2)), gCfixed=False,\ initialPos=(0.0,0.0), initialAngle=0.0, initialSpeed=(0.0, 0.0), initialRot=0.0): self.massDist = massDist # (mass, dist) from Center mass, centerOfGravity, inertia = CalculateMassInertiaCenterOfGravity(self.massDist) self.gCfixed = gCfixed # MassCenter no speed : girouette if self.gCfixed : initialSpeed = 0.0 MechanicPoint.__init__(self, mass=mass, initialPos=initialPos, initialSpeed=initialSpeed) self.Jz = inertia # kg.m2 self.initialAngle = initialAngle # rd self.initialRot = initialRot # rd/s self.d2a_dt2 = np.zeros(rotShape) # rd/s2 self.dij_dt = np.zeros(mRotShap) # /s self.repere = mRot(initialAngle) self.repereU = self.repere[0,:] self.da_dt = np.zeros(rotShape) # rd/s #self.angle = np.zeros(rotShape) # rd self.torque = np.zeros(rotShape) # N*m def angle(self, vec): a = np.arctan2(vec[:,1], vec[:,0]) print("angle() :", a[0:5]) return a*RAD2DEG def info(self): return MechanicPoint.info(self) + "; RotInertia:%6.3f kg*m2"%(self.Jz) def absPosSpeedAtInternPos(self, posInObject): pos = self.pos + posInObject @ self.repere speed = self.speed + posInObject @ self.dij_dt return pos, speed def launch(self): MechanicPoint.launch(self) self.repere[:,:] = mRot(self.initialAngle) if 1: u = self.repere[0,:] rs = np.array((u,)) a = self.angle(rs) print("initialAngle : %6.1f deg"%(a)) self.da_dt[0] = self.initialRot def step(self, t, dt=0.1): if not self.gCfixed : MechanicPoint.step(self, t, dt=dt) self.d2a_dt2[0] = self.torque/self.Jz self.da_dt[0] += self.d2a_dt2 * dt self.dij_dt[:,:] = mRotSpeed(self.da_dt) @ self.repere self.repere[:,:] = self.repere @ mRot(self.da_dt * dt) class Wind(object): def __init__(self, windGradient=None, v0=-7.0, h0=2.5, z0=0.1): #25km at 2.5m self.windGradient = windGradient self.v0 = v0 self.h0 = h0 self.z0 = z0 def step(self, t, dt=0.1): pass def speed(self, pos): h = pos[1] vec = np.zeros(vecShape) if not self.windGradient is None: # linear windSpeed = self.windGradient * h else: # exponential if h <= self.z0 : windSpeed = 0.0 else: windSpeed = self.v0 *(np.log(h/self.z0)/np.log(self.h0/self.z0)) vec[0] = windSpeed #print("Wind.speed :", vec) return vec if 0: w0 = Wind() #v0, h0, z0) w1 = Wind(windGradient=0.5) print("Wind profile:") for i in range(2, 100): h = 0.5 * i speed0 = w0.speed((0.0, h)) speed1 = w1.speed((0.0, h)) print("%5.1f m :%5.1f m/s :%5.1f m/s"%(h, speed0[0], speed1[0])) quit() class Pilote(object): def __init__(self, durationCmds=((0.1,(0.0,)),(0.7,(-0.3,)),(0.45,(-0.7,))), gain=1.0): self.ramp = 2.0/0.5 # -100% to +100% in 0.5 sec self.gain = gain self.elevCmd = np.zeros((1,)) # rd elevator neg to go up self.elevCmd[:] = durationCmds[0][1] self.durationCmds = durationCmds # [(duration, values), (duration, values) ...] self.timeOfnextChange = 0.0 def readCmds(self): if self.idx >= len(self.durationCmds): duration, cmds = 1e12, (0.0,) # zero forever else: duration, cmds = self.durationCmds[self.idx] self.idx += 1 self.timeOfnextChange += duration self.cmds = cmds print("cmds :", self.cmds) def launch(self): self.idx = 0 self.readCmds() def step(self, t, dt, alt, repere, speed): dmax = self.ramp * dt if t >= self.timeOfnextChange: self.readCmds() delta = self.cmds[0] - self.elevCmd[0] if delta < -dmax : delta = -dmax elif delta > dmax : delta = dmax self.elevCmd[0] += delta class AeroSurf(object): def __init__(self, name, span, chord, pos, angle, profil): self.name = name self.span = span # m self.chord = chord # m self.area = self.span * self.chord # m2 self.pos = pos # relative to plane GC self.angle = angle # relative to plane main axe (calage aile) self.profil = profil self.kWing = 0.5 * ro * self.area self.alpha = np.zeros(1,) self.lift = np.zeros(1,) self.drag = np.zeros(1,) self.moment = np.zeros(1,) def aeroForce(self, airSpeed, alphaPlane, incidenceCmd): # m/s, rd, rd alphaDeg = (alphaPlane + self.angle + incidenceCmd) * RAD2DEG ''' if alphaDeg > 180.0 : alphaDeg -= 360.0 elif
<filename>TopQuarkAnalysis/Configuration/test/patRefSel_muJets_cfg.py from __future__ import print_function # As of 1 Feb 2017: # This configuration appears to be already broken in more # than one way. It fails to even run only under python. # For this reason, it was not converted to use Tasks. # If it is ever fixed, it will also need to be migrated # to use Tasks. # # This file contains the Top PAG reference selection work-flow for mu + jets analysis. # as defined in # https://twiki.cern.ch/twiki/bin/view/CMS/TWikiTopRefEventSel#mu_jets_Channel # # Command line arguments: # - standard command line arguments as defined in FWCore.ParameterSet.VarParsing.VarParsing( 'standard' ) # + 'maxEvent' (int , default: -1) # - 'runOnMC' (bool, default: True ): decide if run on MC or real data # - 'runOnMiniAOD' (bool, default: True ): decide if run on miniAOD or AOD input # - 'useElecEAIsoCorr' (bool, default: True ): decide, if EA (rho) or Delta beta corrections are used for electron isolation # - 'useCalibElec' (bool, default: False): decide, if electron re-calibration using regression energies is used # - 'addTriggerMatch' (bool, default: True ): decide, if trigger objects are matched to signal muons # import sys import FWCore.ParameterSet.Config as cms # Command line parsing import FWCore.ParameterSet.VarParsing as VarParsing options = VarParsing.VarParsing ( 'standard' ) options.register( 'runOnMC' , True , VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.bool, 'decide, if run on MC or real data' ) options.register( 'runOnMiniAOD' , True , VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.bool, 'decide, if run on miniAOD or AOD input' ) options.register( 'useElecEAIsoCorr', True , VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.bool, 'decide, if EA (rho) or Delta beta corrections are used for electron isolation is used' ) options.register( 'useCalibElec' , False, VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.bool, 'decide, if electron re-calibration using regression energies is used' ) options.register( 'addTriggerMatch' , True , VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.bool, 'decide, if trigger objects are matched to signal muons' ) # parsing command line arguments if( hasattr( sys, 'argv' ) ): if( len( sys.argv ) > 2 ): print('Parsing command line arguments:') for args in sys.argv : arg = args.split(',') for val in arg: val = val.split( '=' ) if( len( val ) == 2 ): print('Setting "', val[0], '" to:', val[1]) setattr( options, val[0], val[1] ) process = cms.Process( 'USER' ) #process.Tracer = cms.Service( "Tracer" ) ### ======================================================================== ### ### ### ### Constants ### ### (user job steering) ### ### ### ### ======================================================================== ### from TopQuarkAnalysis.Configuration.patRefSel_refMuJets import * inputFiles = [] ### Selection steps # If a step is switched off here, its results will still be available in the coreespondinng TriggerResults of this process. # Event filter # This parameter defines the level, at which events will be filtered for output. # The available levels (paths) are (ordered!): # 0a. pTrigger # 0b. pEventCleaning # 0c. pGoodVertex # 1. pSignalMuon # 2. pLooseMuonVeto # 3. pElectronVeto # 4a. p1Jet # 4b. p2Jets # 4c. p3Jets # 5. p4Jets # 6. pBTags # Each level includes the former ones, but also the corresponding stand-alone selection steps are available, adding a # 'StandAlone' after the prefix 'p' (e.g. 'pLooseMuonVeto' --> 'pStandAloneLooseMuonVeto'). # All corresponding flags are available in the TriggerResults collection produced by this process later. selectEvents = 'pGoodVertex' # Step 0 #triggerSelectionData = '' #triggerSelectionMC = '' # Step 1 #muonCut = '' #signalMuonCut = '' #muonVertexMaxDZ = 0.5 # Step 2 # Step 3 useElecEAIsoCorr = options.useElecEAIsoCorr useCalibElec = options.useCalibElec #electronGsfCut = '' #electronCalibCut = '' electronCut = electronGsfCut # Step 4 #jetCut = '' # Step4a #veryTightJetCut = '' # Step4b #tightJetCut = '' # Step4c #looseJetCut = '' # Step 5 #veryLooseJetCut = '' # Step 6 bTagSrc = 'selectedJets' #bTagCut = '' minBTags = 2 # TriggerMatching addTriggerMatch = options.addTriggerMatch #triggerObjectSelectionData = 'type("TriggerMuon") && ( path("%s") )'%( triggerSelectionData ) #triggerObjectSelectionMC = 'type("TriggerMuon") && ( path("%s") )'%( triggerSelectionMC ) ### Input runOnMC = options.runOnMC runOnMiniAOD = options.runOnMiniAOD # maximum number of events maxEvents = options.maxEvents ### Conditions # GlobalTags globalTagMC = 'DEFAULT' globalTagData = 'DEFAULT' ### Output # output file outputFile = 'patRefSel_muJets.root' # event frequency of Fwk report fwkReportEvery = max( 1, int( maxEvents / 100 ) ) # switch for 'TrigReport'/'TimeReport' at job end wantSummary = True ### ======================================================================== ### ### ### ### End of constants ### ### (user job steering) ### ### ### ### ======================================================================== ### triggerSelection = triggerSelectionData triggerObjectSelection = triggerObjectSelectionData if runOnMC: triggerSelection = triggerSelectionMC triggerObjectSelection = triggerObjectSelectionMC ### ### Basic configuration ### process.load( "TopQuarkAnalysis.Configuration.patRefSel_basics_cff" ) process.MessageLogger.cerr.FwkReport.reportEvery = fwkReportEvery process.options.wantSummary = wantSummary from Configuration.AlCa.GlobalTag import GlobalTag if runOnMC: if globalTagMC == 'DEFAULT': process.GlobalTag = GlobalTag( process.GlobalTag, 'auto:run2_mc' ) else: process.GlobalTag.globaltag = globalTagMC else: if globalTagData == 'DEFAULT': process.GlobalTag = GlobalTag( process.GlobalTag, 'auto:run2_data' ) else: process.GlobalTag.globaltag = globalTagData ### ### Input configuration ### if len( inputFiles ) == 0: if runOnMiniAOD: if runOnMC: from PhysicsTools.PatAlgos.patInputFiles_cff import filesRelValTTbarPileUpMINIAODSIM inputFiles = filesRelValTTbarPileUpMINIAODSIM else: from PhysicsTools.PatAlgos.patInputFiles_cff import filesRelValSingleMuMINIAOD inputFiles = filesRelValSingleMuMINIAOD else: if runOnMC: from PhysicsTools.PatAlgos.patInputFiles_cff import filesRelValProdTTbarAODSIM inputFiles = filesRelValProdTTbarAODSIM else: from PhysicsTools.PatAlgos.patInputFiles_cff import filesSingleMuRECO # not available at CERN inputFiles = filesSingleMuRECO process.load( "TopQuarkAnalysis.Configuration.patRefSel_inputModule_cfi" ) process.source.fileNames = inputFiles process.maxEvents.input = maxEvents ### ### PAT configuration ### if not runOnMiniAOD: process.load( "PhysicsTools.PatAlgos.producersLayer1.patCandidates_cff" ) ### ### Output configuration ### process.load( "TopQuarkAnalysis.Configuration.patRefSel_outputModule_cff" ) # output file name process.out.fileName = outputFile from TopQuarkAnalysis.Configuration.patRefSel_eventContent_cff import refMuJets_eventContent process.out.outputCommands += refMuJets_eventContent if runOnMiniAOD: from TopQuarkAnalysis.Configuration.patRefSel_eventContent_cff import miniAod_eventContent process.out.outputCommands += miniAod_eventContent else: from TopQuarkAnalysis.Configuration.patRefSel_eventContent_cff import aod_eventContent process.out.outputCommands += aod_eventContent # clear event selection process.out.SelectEvents.SelectEvents = cms.vstring( selectEvents ) ### ### Selection configuration ### # Individual steps # Step 0 from TopQuarkAnalysis.Configuration.patRefSel_triggerSelection_cff import triggerResults process.triggerSelection = triggerResults.clone( triggerConditions = [ triggerSelection ] ) process.sStandAloneTrigger = cms.Sequence( process.triggerSelection ) process.pStandAloneTrigger = cms.Path( process.sStandAloneTrigger ) process.load( 'TopQuarkAnalysis.Configuration.patRefSel_eventCleaning_cff' ) process.sStandAloneEventCleaning = cms.Sequence() if runOnMiniAOD: process.sStandAloneEventCleaning += process.eventCleaningMiniAOD if runOnMC: process.sStandAloneEventCleaning += process.eventCleaningMiniAODMC else: process.sStandAloneEventCleaning += process.eventCleaningMiniAODData else: process.sStandAloneEventCleaning += process.eventCleaning if runOnMC: process.sStandAloneEventCleaning += process.eventCleaningMC else: process.sStandAloneEventCleaning += process.eventCleaningData process.pStandAloneEventCleaning = cms.Path( process.sStandAloneEventCleaning ) from CommonTools.ParticleFlow.goodOfflinePrimaryVertices_cfi import goodOfflinePrimaryVertices process.goodOfflinePrimaryVertices = goodOfflinePrimaryVertices.clone( filter = True ) if runOnMiniAOD: process.goodOfflinePrimaryVertices.src = 'offlineSlimmedPrimaryVertices' process.sStandAloneGoodVertex = cms.Sequence( process.goodOfflinePrimaryVertices ) process.pStandAloneGoodVertex = cms.Path( process.sStandAloneGoodVertex ) # Step 1 from TopQuarkAnalysis.Configuration.patRefSel_refMuJets_cfi import selectedMuons, preSignalMuons, signalMuons, standAloneSignalMuonFilter process.selectedMuons = selectedMuons.clone( cut = muonCut ) if runOnMiniAOD: process.selectedMuons.src = 'slimmedMuons' process.preSignalMuons = preSignalMuons.clone( cut = signalMuonCut ) process.signalMuons = signalMuons.clone( maxDZ = muonVertexMaxDZ ) if runOnMiniAOD: process.signalMuons.vertexSource = 'offlineSlimmedPrimaryVertices' process.standAloneSignalMuonFilter = standAloneSignalMuonFilter.clone() process.sStandAloneSignalMuon = cms.Sequence( process.standAloneSignalMuonFilter ) process.pStandAloneSignalMuon = cms.Path( process.sStandAloneSignalMuon ) # Step 2 from TopQuarkAnalysis.Configuration.patRefSel_refMuJets_cfi import standAloneLooseMuonVetoFilter process.standAloneLooseMuonVetoFilter = standAloneLooseMuonVetoFilter.clone() process.sStandAloneLooseMuonVeto = cms.Sequence( process.standAloneLooseMuonVetoFilter ) process.pStandAloneLooseMuonVeto = cms.Path( process.sStandAloneLooseMuonVeto ) # Step 3 if not runOnMiniAOD: from PhysicsTools.SelectorUtils.tools.vid_id_tools import switchOnVIDElectronIdProducer, setupAllVIDIdsInModule, setupVIDElectronSelection electron_ids = [ 'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_CSA14_50ns_V1_cff' , 'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_CSA14_PU20bx25_V0_cff' ] switchOnVIDElectronIdProducer( process ) process.electronIDValueMapProducer.ebReducedRecHitCollection = cms.InputTag( 'reducedEcalRecHitsEB' ) process.electronIDValueMapProducer.eeReducedRecHitCollection = cms.InputTag( 'reducedEcalRecHitsEE' ) process.electronIDValueMapProducer.esReducedRecHitCollection = cms.InputTag( 'reducedEcalRecHitsES' ) for idmod in electron_ids: setupAllVIDIdsInModule( process, idmod, setupVIDElectronSelection ) if useElecEAIsoCorr: from EgammaAnalysis.ElectronTools.electronIsolatorFromEffectiveArea_cfi import elPFIsoValueEA03 if runOnMiniAOD: process.patElPFIsoValueEA03 = elPFIsoValueEA03.clone( gsfElectrons = '' , pfElectrons = '' , patElectrons = cms.InputTag( 'slimmedElectrons' ) , rhoIso = cms.InputTag( 'fixedGridRhoFastjetAll' ) ) from EgammaAnalysis.ElectronTools.patElectronEAIsoCorrectionProducer_cfi import patElectronEAIso03CorrectionProducer process.electronsWithEA03Iso = patElectronEAIso03CorrectionProducer.clone( patElectrons = 'slimmedElectrons' , eaIsolator = 'patElPFIsoValueEA03' ) else: process.elPFIsoValueEA03 = elPFIsoValueEA03.clone( gsfElectrons = 'gedGsfElectrons' , pfElectrons = '' , rhoIso = cms.InputTag( 'fixedGridRhoFastjetAll' ) ) process.patElectrons.isolationValues.user = cms.VInputTag( cms.InputTag( 'elPFIsoValueEA03' ) ) else: electronGsfCut.replace( '-1.0*userIsolation("User1Iso")', '-0.5*puChargedHadronIso' ) electronCalibCut.replace( '-1.0*userIsolation("User1Iso")', '-0.5*puChargedHadronIso' ) electronCut.replace( '-1.0*userIsolation("User1Iso")', '-0.5*puChargedHadronIso' ) if useCalibElec: from TopQuarkAnalysis.Configuration.patRefSel_refMuJets_cfi import electronsWithRegression, calibratedElectrons process.electronsWithRegression = electronsWithRegression.clone() if runOnMiniAOD: if useElecEAIsoCorr: process.electronsWithRegression.inputElectronsTag = 'electronsWithEA03Iso' else: process.electronsWithRegression.inputElectronsTag = 'slimmedElectrons' process.electronsWithRegression.vertexCollection = 'offlineSlimmedPrimaryVertices' process.calibratedElectrons = calibratedElectrons.clone( isMC = runOnMC ) if runOnMC: process.calibratedElectrons.inputDataset = 'Summer12_LegacyPaper' # FIXME: Update as soon as available else: process.calibratedElectrons.inputDataset = '22Jan2013ReReco' # FIXME: Update as soon as available process.RandomNumberGeneratorService = cms.Service( "RandomNumberGeneratorService" , calibratedElectrons = cms.PSet( initialSeed = cms.untracked.uint32( 1 ) , engineName = cms.untracked.string('TRandom3') ) ) electronCut = electronCalibCut from TopQuarkAnalysis.Configuration.patRefSel_refMuJets_cfi import selectedElectrons, standAloneElectronVetoFilter process.selectedElectrons = selectedElectrons.clone( cut = electronCut ) if useCalibElec: process.selectedElectrons.src = 'calibratedElectrons' elif useElecEAIsoCorr and runOnMiniAOD: process.selectedElectrons.src = 'electronsWithEA03Iso' elif runOnMiniAOD: process.selectedElectrons.src = 'slimmedElectrons' process.standAloneElectronVetoFilter = standAloneElectronVetoFilter.clone() process.sStandAloneElectronVeto = cms.Sequence( process.standAloneElectronVetoFilter ) process.pStandAloneElectronVeto = cms.Path( process.sStandAloneElectronVeto ) # Step 4 from TopQuarkAnalysis.Configuration.patRefSel_refMuJets_cfi import selectedJets process.selectedJets = selectedJets.clone( cut = jetCut ) if runOnMiniAOD: process.selectedJets.src = 'slimmedJets' from TopQuarkAnalysis.Configuration.patRefSel_refMuJets_cfi import signalVeryTightJets, standAloneSignalVeryTightJetsFilter process.signalVeryTightJets = signalVeryTightJets.clone( cut = veryTightJetCut ) process.standAloneSignalVeryTightJetsFilter = standAloneSignalVeryTightJetsFilter.clone() process.sStandAlone1Jet = cms.Sequence( process.standAloneSignalVeryTightJetsFilter ) process.pStandAlone1Jet = cms.Path( process.sStandAlone1Jet ) from TopQuarkAnalysis.Configuration.patRefSel_refMuJets_cfi import signalTightJets, standAloneSignalTightJetsFilter process.signalTightJets = signalTightJets.clone( cut = tightJetCut ) process.standAloneSignalTightJetsFilter = standAloneSignalTightJetsFilter.clone() process.sStandAlone2Jets = cms.Sequence( process.standAloneSignalTightJetsFilter ) process.pStandAlone2Jets = cms.Path( process.sStandAlone2Jets ) from TopQuarkAnalysis.Configuration.patRefSel_refMuJets_cfi import signalLooseJets, standAloneSignalLooseJetsFilter process.signalLooseJets = signalLooseJets.clone( cut = looseJetCut ) process.standAloneSignalLooseJetsFilter = standAloneSignalLooseJetsFilter.clone() process.sStandAlone3Jets = cms.Sequence( process.standAloneSignalLooseJetsFilter ) process.pStandAlone3Jets = cms.Path( process.sStandAlone3Jets ) # Step 5 from TopQuarkAnalysis.Configuration.patRefSel_refMuJets_cfi import signalVeryLooseJets, standAloneSignalVeryLooseJetsFilter process.signalVeryLooseJets = signalVeryLooseJets.clone( cut = veryLooseJetCut ) process.standAloneSignalVeryLooseJetsFilter = standAloneSignalVeryLooseJetsFilter.clone() process.sStandAlone4Jets = cms.Sequence( process.standAloneSignalVeryLooseJetsFilter ) process.pStandAlone4Jets = cms.Path( process.sStandAlone4Jets ) # Step 6 from TopQuarkAnalysis.Configuration.patRefSel_refMuJets_cfi import selectedBTagJets, standAloneSignalBTagsFilter process.selectedBTagJets = selectedBTagJets.clone( src = bTagSrc , cut = bTagCut ) process.standAloneSignalBTagsFilter = standAloneSignalBTagsFilter.clone( minNumber = minBTags ) process.sStandAloneBTags = cms.Sequence( process.standAloneSignalBTagsFilter ) process.pStandAloneBTags = cms.Path( process.sStandAloneBTags ) # Consecutive steps process.sTrigger = cms.Sequence( process.sStandAloneTrigger ) process.sEventCleaning = cms.Sequence( process.sTrigger + process.sStandAloneEventCleaning ) process.sGoodVertex = cms.Sequence( process.sEventCleaning + process.sStandAloneGoodVertex ) process.sSignalMuon = cms.Sequence( process.sGoodVertex + process.sStandAloneSignalMuon ) process.sLooseMuonVeto = cms.Sequence( process.sSignalMuon + process.sStandAloneLooseMuonVeto ) process.sElectronVeto = cms.Sequence( process.sLooseMuonVeto + process.sStandAloneElectronVeto ) process.s1Jet = cms.Sequence( process.sElectronVeto + process.sStandAlone1Jet ) process.s2Jets = cms.Sequence( process.s1Jet + process.sStandAlone2Jets ) process.s3Jets =
<filename>det3d/models/bbox_heads/clear_mg_ohs_head.py # Copyright (c) Gorilla-Lab. All rights reserved. import logging from functools import partial from collections import defaultdict from typing import Dict, List, Optional, Sequence import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from ..losses.ohs_loss_clear import OHSLossClear from ..losses.attention_constrain_loss import AttentionConstrainedLoss from ..registry import HEADS from ..builder import build_loss from ...core.bbox import box_torch_ops from ...core.bbox.geometry import points_in_convex_polygon_torch from ...core.bbox.box_coders import BoxCoder, GroundBox3dCoderAF from ipdb import set_trace def multi_apply(func, *args, **kwargs): pfunc = partial(func, **kwargs) if kwargs else func map_results = map(pfunc, *args) return tuple(map(list, zip(*map_results))) def _get_pos_neg_loss(cls_loss, labels, label_weights): # cls_loss: [N, num_anchors, num_class] # labels: [N, num_anchors] batch_size = cls_loss.shape[0] if cls_loss.shape[-1] == 1 or len(cls_loss.shape) == 2: cls_pos_loss = (labels > 0).type_as(cls_loss) * cls_loss.view(batch_size, -1) cls_neg_loss = ((labels == 0) & (label_weights > 0)).type_as( cls_loss) * cls_loss.view(batch_size, -1) cls_pos_loss = cls_pos_loss.sum() / batch_size cls_neg_loss = cls_neg_loss.sum() / batch_size else: cls_pos_loss = cls_loss[..., 1:].sum() / batch_size cls_neg_loss = cls_loss[..., 0].sum() / batch_size return cls_pos_loss, cls_neg_loss @HEADS.register_module class OHSHeadClear(nn.Module): def __init__(self, box_coder: GroundBox3dCoderAF, num_input: int, num_pred: int, num_cls: int, header: bool = True, name: str = "", **kwargs,): super().__init__() self.box_coder = box_coder self.conv_cls = nn.Conv2d(num_input, num_cls, 1) self.mode = kwargs.get("mode", "bev") if self.box_coder.center == "direct": self.conv_xy = nn.Conv2d(num_input, 2, 1) elif self.box_coder.center == "soft_argmin": self.conv_xy = nn.Conv2d(num_input, 2 * self.box_coder.kwargs["xy_bin_num"], 1) self.loc_bins_x = torch.linspace(self.box_coder.kwargs["x_range"][0], self.box_coder.kwargs["x_range"][1], self.box_coder.kwargs["xy_bin_num"]).reshape(1, 1, -1, 1, 1) self.loc_bins_y = torch.linspace(self.box_coder.kwargs["y_range"][0], self.box_coder.kwargs["y_range"][1], self.box_coder.kwargs["xy_bin_num"]).reshape(1, 1, -1, 1, 1) self.loc_bins = torch.cat([self.loc_bins_x, self.loc_bins_y], 1) else: raise NotImplementedError if "direct" in self.box_coder.height: self.conv_z = nn.Conv2d(num_input, 1, 1) elif "soft_argmin" in self.box_coder.height: self.conv_z = nn.Conv2d(num_input, self.box_coder.kwargs["z_bin_num"], 1) self.z_loc_bins = torch.linspace(self.box_coder.kwargs["z_range"][0], self.box_coder.kwargs["z_range"][1], self.box_coder.kwargs["z_bin_num"]).reshape(1, self.box_coder.kwargs["z_bin_num"], 1, 1) else: raise NotImplementedError if "soft_argmin" in self.box_coder.dim: self.conv_dim = nn.Conv2d(num_input, 3 * self.box_coder.kwargs["dim_bin_num"], 1) self.dim_loc_bins = torch.linspace(self.box_coder.kwargs["dim_range"][0], self.box_coder.kwargs["dim_range"][1], self.box_coder.kwargs["dim_bin_num"]).reshape(1, self.box_coder.kwargs[ "dim_bin_num"], 1, 1) self.dim_bins = torch.cat([self.dim_loc_bins, self.dim_loc_bins, self.dim_loc_bins], 1) else: self.conv_dim = nn.Conv2d(num_input, 3, 1) if self.box_coder.velocity: self.conv_velo = nn.Conv2d(num_input, 2, 1) if self.box_coder.rotation == "vector": self.conv_r = nn.Conv2d(num_input, 2, 1) elif self.box_coder.rotation == "soft_argmin": self.conv_r = nn.Conv2d(num_input, self.box_coder.kwargs["r_bin_num"], 1) self.r_loc_bins = torch.linspace(-np.pi, np.pi, self.box_coder.kwargs["r_bin_num"]).reshape( 1, self.box_coder.kwargs["r_bin_num"], 1, 1) else: self.conv_r = nn.Conv2d(num_input, 1, 1) def forward(self, x, return_loss): x_bev = x ret_dict = {} cls_preds = self.conv_cls(x_bev).permute(0, 2, 3, 1).contiguous() # predict bounding box xy = self.conv_xy(x_bev) z = self.conv_z(x_bev) dim = self.conv_dim(x_bev) # encode as bounding box if self.box_coder.center == "soft_argmin": xy = xy.view( (xy.shape[0], 2, self.box_coder.kwargs["xy_bin_num"], xy.shape[2], xy.shape[3])) xy = F.softmax(xy, dim=2) xy = xy * self.loc_bins.to(xy.device) xy = torch.sum(xy, dim=2, keepdim=False) if "soft_argmin" in self.box_coder.height: z = F.softmax(z, dim=1) z = z * self.z_loc_bins.to(z.device) z = torch.sum(z, dim=1, keepdim=True) if "soft_argmin" in self.box_coder.dim: dim = dim.view( (dim.shape[0], 3, self.box_coder.kwargs["dim_bin_num"], dim.shape[2], dim.shape[3])) dim = F.softmax(dim, dim=2) dim = dim * self.dim_loc_bins.to(dim.device) dim = torch.sum(dim, dim=2, keepdim=False) xy = xy.permute(0, 2, 3, 1).contiguous() z = z.permute(0, 2, 3, 1).contiguous() dim = dim.permute(0, 2, 3, 1).contiguous() if self.box_coder.dim == "direct": dim = F.relu(dim) if self.box_coder.velocity: velo = self.conv_velo(x_bev).permute(0, 2, 3, 1).contiguous() r_preds = self.conv_r(x_bev) if self.box_coder.rotation == "vector": #import pdb; pdb.set_trace() r_preds = F.normalize(r_preds, p=2, dim=1) elif self.box_coder.rotation == "soft_argmin": r_preds = F.softmax(r_preds, dim=1) r_preds = r_preds * self.r_loc_bins.to(r_preds.device) r_preds = torch.sum(r_preds, dim=1, keepdim=True) r_preds = r_preds.permute(0, 2, 3, 1).contiguous() if self.box_coder.velocity: box_preds = torch.cat([xy, z, dim, velo, r_preds], -1) else: box_preds = torch.cat([xy, z, dim, r_preds], -1) ret_dict.update({"box_preds": box_preds, "cls_preds": cls_preds}) return ret_dict @HEADS.register_module class MultiGroupOHSHeadClear(nn.Module): def __init__(self, mode: str = "3d", in_channels: List[int] = [128, ], norm_cfg=None, tasks: List[Dict] = [], weights=[], box_coder: BoxCoder = None, with_cls: bool = True, with_reg: bool = True, encode_background_as_zeros: bool = True, use_sigmoid_score: bool = True, loss_norm: Dict = dict(type="NormByNumPositives", pos_class_weight=1.0, neg_class_weight=1.0,), loss_cls: Dict = dict(type="CrossEntropyLoss", use_sigmoid=False, loss_weight=1.0,), loss_bbox: Dict = dict(type="SmoothL1Loss", beta=1.0, loss_weight=1.0,), atten_res: Sequence[int] = None, assign_cfg: Optional[dict] = dict(), name="rpn",): super().__init__() assert with_cls or with_reg # read tasks and analysis the classes for tasks num_classes = [len(t["class_names"]) for t in tasks] self.class_names = [t["class_names"] for t in tasks] self.num_anchor_per_locs = [1] * len(num_classes) self.targets = tasks # define the essential paramters self.box_coder = box_coder self.with_cls = with_cls self.with_reg = with_reg self.in_channels = in_channels self.num_classes = num_classes self.encode_background_as_zeros = encode_background_as_zeros self.use_sigmoid_score = use_sigmoid_score self.box_n_dim = self.box_coder.n_dim self.mode = mode self.assign_cfg = assign_cfg self.pc_range = np.asarray(self.box_coder.pc_range) # [6] self.dims = self.pc_range[3:] - self.pc_range[:3] # [3] # initialize loss self.loss_norm = loss_norm self.loss_cls = build_loss(loss_cls) self.loss_reg = build_loss(loss_bbox) self.atten_res = atten_res # initialize logger logger = logging.getLogger("MultiGroupHead") self.logger = logger # check box_coder assert isinstance( box_coder, GroundBox3dCoderAF), "OHSLoss must comes with an anchor-free box coder" assert box_coder.code_size == len( loss_bbox.code_weights), "code weights does not match code size" # set multi-tasks heads # split each head num_clss = [] num_preds = [] box_code_sizes = [self.box_coder.n_dim] * len(self.num_classes) for num_c, num_a, box_cs in zip( self.num_classes, self.num_anchor_per_locs, box_code_sizes ): if self.encode_background_as_zeros: num_cls = num_a * num_c else: num_cls = num_a * (num_c + 1) num_clss.append(num_cls) num_pred = num_a * box_cs num_preds.append(num_pred) self.logger.info( f"num_classes: {self.num_classes}, num_preds: {num_preds}" ) # construct each task head self.tasks = nn.ModuleList() for task_id, (num_pred, num_cls) in enumerate(zip(num_preds, num_clss)): self.tasks.append( OHSHeadClear( self.box_coder, self.in_channels, num_pred, num_cls, header=False, mode=self.mode, ) ) def set_train_cfg(self, cfg): self.ohs_loss = [] self.atten_loss = [] for task_id, target in enumerate(self.targets): self.ohs_loss.append( OHSLossClear(self.box_coder, target.num_class, self.loss_cls, self.loss_reg, self.encode_background_as_zeros, cfg, self.loss_norm, task_id, self.mode)) self.atten_loss.append( AttentionConstrainedLoss( self.box_coder, target.num_class, task_id, self.atten_res) ) self.logger.info("Finish Attention Constrained Loss Initialization") self.logger.info("Finish MultiGroupOHSHeadClear Initialization") def forward(self, x, return_loss=False): ret_dicts = [] for task in self.tasks: ret_dicts.append(task(x, return_loss)) return ret_dicts def loss(self, example, preds_dicts, **kwargs): annos = example["annos"] batch_size_device = example["num_voxels"].shape[0] batch_labels = [anno["gt_classes"] for anno in annos] batch_boxes = [anno["gt_boxes"] for anno in annos] batch_atten_map = kwargs.get('atten_map', None) rets = [] for task_id, preds_dict in enumerate(preds_dicts): box_preds = preds_dict["box_preds"] cls_preds = preds_dict["cls_preds"] bs_per_gpu = len(cls_preds) batch_task_boxes = [batch_box[task_id] for batch_box in batch_boxes] batch_task_labels = [batch_label[task_id] for batch_label in batch_labels] attention_loss = defaultdict(list) for index, bam in enumerate(batch_atten_map): temp_attention_loss = self.atten_loss[task_id]( bam, batch_task_boxes, batch_task_labels) for ke, va in temp_attention_loss.items(): attention_loss[ke].append(va) targets = self.assign_hotspots(cls_preds, batch_task_boxes, batch_task_labels) labels, label_weights, bbox_targets, bbox_locs, num_total_pos, num_total_neg = targets # process assign targets labels = torch.stack(labels, 0).view(bs_per_gpu, -1) # [B, H*W] label_weights = torch.stack(label_weights, 0).view(bs_per_gpu, -1) # [B, H*W] kwargs = {} # calculate ohs loss for each task loc_loss, cls_loss = self.ohs_loss[task_id]( box_preds, cls_preds, labels, label_weights, bbox_targets, bbox_locs, **kwargs ) if self.loss_norm["type"] == "NormByNumExamples": normalizer = num_total_pos + num_total_neg elif self.loss_norm["type"] == "NormByNumPositives": normalizer = max(num_total_pos, 1.0) elif self.loss_norm["type"] == "NormByNumPosNeg": normalizer = self.loss_norm["pos_cls_weight"] * num_total_pos + \ self.loss_norm["neg_cls_weight"] * num_total_neg elif self.loss_norm["type"] == "dont_norm": # support ghm loss normalizer = batch_size_device else: raise ValueError(f"unknown loss norm type") loc_loss_reduced = loc_loss.sum() / normalizer loc_loss_reduced *= self.loss_reg._loss_weight cls_pos_loss, cls_neg_loss = _get_pos_neg_loss(cls_loss, labels, label_weights) cls_pos_loss /= self.loss_norm["pos_cls_weight"] cls_neg_loss /= self.loss_norm["neg_cls_weight"] cls_loss_reduced = cls_loss.sum() / normalizer cls_loss_reduced *= self.loss_cls._loss_weight loss = loc_loss_reduced + cls_loss_reduced atten_loss = 0.0 for value in attention_loss.values(): if type(value) == list: temp_loss = 0.0 norm_fac = len(value) for temp_atten_loss in value: temp_loss = temp_loss + temp_atten_loss value = temp_loss * 1.0 / norm_fac atten_loss = atten_loss + value loss = loss + atten_loss loc_loss_elem = [ loc_loss[:, :, i].sum() / num_total_pos for i in range(loc_loss.shape[-1]) ] ret = { "loss": loss, "cls_pos_loss": cls_pos_loss.detach().cpu(), "cls_neg_loss": cls_neg_loss.detach().cpu(), "cls_loss_reduced": cls_loss_reduced.detach().cpu().mean(), "loc_loss_reduced": loc_loss_reduced.detach().cpu().mean(), "loc_loss_elem": [elem.detach().cpu() for elem in loc_loss_elem], "num_pos": torch.tensor([num_total_pos]), "num_neg": torch.tensor([num_total_neg]), } for key, value in attention_loss.items(): if type(value) == list: temp_loss = 0.0 norm_fac = len(value) for temp_atten_loss in value: temp_loss = temp_loss + temp_atten_loss value = temp_loss * 1.0 / norm_fac ret.update({key: value.detach().cpu()}) rets.append(ret) rets_merged = defaultdict(list) for ret in rets: for k, v in ret.items(): rets_merged[k].append(v) return rets_merged def assign_hotspots(self, cls_scores: torch.Tensor, gt_bboxes: List[np.ndarray], gt_labels: List[np.ndarray]): """ assign hotspots(generate targets) Args: cls_scores (torch.Tensor, [B, H, W, C]): classification prediction score map gt_bboxes (List[np.ndarray], [[M, ndim], [K, ndim], ...]): ground truth bounding box for each batch gt_labels (List[np.ndarray], [[M], [K], ...]): ground truth bounding box id for each batch cls_scores (torch.Tensor, [B, H, D, C], optional): classification prediction score map for RV. Default to None. """ bs_per_gpu = len(gt_bboxes) # Get the batch size device =
""" gameEngine.py high-level tools to simplify pygame programming for Game Programming - The L-Line by <NAME>, 2006 Version 1.1 - incorporates drawTrace() method and replaces all default fonts with direct call to freesansbold.ttf (pygame's standard font.) This is done because py2exe doesn't seem to like system fonts under Windows. """ import pygame, math pygame.init() class BasicSprite(pygame.sprite.Sprite): """ use this sprite when you want to directly control the sprite with dx and dy or want to extend in another direction than DirSprite """ def __init__(self, scene): pygame.sprite.Sprite.__init__(self) self.screen = scene.screen self.image = pygame.Surface((25, 25)) self.image.fill((255, 0, 0)) self.rect = self.image.get_rect() self.x = 100 self.y = 100 self.dx = 0 self.dy = 0 def update(self): self.x += self.dx self.y += self.dy self.checkBounds() self.rect.center = (self.x, self.y) def checkBounds(self): scrWidth = self.screen.get_width() scrHeight = self.screen.get_height() if self.x > scrWidth: self.x = 0 if self.x < 0: self.x = scrWidth if self.y > scrHeight: self.y = 0 if self.y < 0: self.y = scrHeight class SuperSprite(pygame.sprite.Sprite): """ An enhanced Sprite class expects a gameEngine.Scene class as its one parameter Use methods to change image, direction, speed Will automatically travel in direction and speed indicated Automatically rotates to point in indicated direction Five kinds of boundary collision """ def __init__(self, scene): pygame.sprite.Sprite.__init__(self) self.scene = scene self.screen = scene.screen #create constants self.WRAP = 0 self.BOUNCE = 1 self.STOP = 2 self.HIDE = 3 self.CONTINUE = 4 #create a default text image as a placeholder #This will usually be changed by a setImage call self.font = pygame.font.Font("freesansbold.ttf", 30) self.imageMaster = self.font.render("TUIO", True, (0, 0,0), (0xFF, 0xFF, 0xFF)) self.image = self.imageMaster self.rect = self.image.get_rect() #create properties #most will be changed through method calls self.x = 200 self.y = 200 self.dx = 0 self.dy = 0 self.dir = 0 self.rotation = 0 self.speed = 0 self.maxSpeed = 10 self.minSpeed = -3 self.boundAction = self.WRAP self.pressed = False self.oldCenter = (100, 100) def update(self): self.oldCenter = self.rect.center self.checkEvents() self.__rotate() self.__calcVector() self.__calcPosition() self.checkBounds() self.rect.center = (self.x, self.y) def checkEvents(self): """ overwrite this method to add your own event code """ pass def __rotate(self): """ PRIVATE METHOD change visual orientation based on rotation property. automatically called in update. change rotation property directly or with rotateBy(), setAngle() methods """ oldCenter = self.rect.center self.oldCenter = oldCenter self.image = pygame.transform.rotate(self.imageMaster, self.rotation) self.rect = self.image.get_rect() self.rect.center = oldCenter def __calcVector(self): """ calculates dx and dy based on speed, dir automatically called in update """ theta = self.dir / 180.0 * math.pi self.dx = math.cos(theta) * self.speed self.dy = math.sin(theta) * self.speed self.dy *= -1 def __calcPosition(self): """ calculates the sprites position adding dx and dy to x and y. automatically called in update """ self.x += self.dx self.y += self.dy def checkBounds(self): """ checks boundary and acts based on self.BoundAction. WRAP: wrap around screen (default) BOUNCE: bounce off screen STOP: stop at edge of screen HIDE: move off stage and wait CONTINUE: keep going at present course and speed automatically called by update """ scrWidth = self.screen.get_width() scrHeight = self.screen.get_height() #create variables to simplify checking offRight = offLeft = offTop = offBottom = offScreen = False if self.x > scrWidth: offRight = True if self.x < 0: offLeft = True if self.y > scrHeight: offBottom = True if self.y < 0: offTop = True if offRight or offLeft or offTop or offBottom: offScreen = True if self.boundAction == self.WRAP: if offRight: self.x = 0 if offLeft: self.x = scrWidth if offBottom: self.y = 0 if offTop: self.y = scrHeight elif self.boundAction == self.BOUNCE: if offLeft or offRight: self.dx *= -1 if offTop or offBottom: self.dy *= -1 self.updateVector() self.rotation = self.dir elif self.boundAction == self.STOP: if offScreen: self.speed = 0 elif self.boundAction == self.HIDE: if offScreen: self.speed = 0 self.setPosition((-1000, -1000)) elif self.boundAction == self.CONTINUE: pass else: # assume it's continue - keep going forever pass def setSpeed(self, speed): """ immediately sets the objects speed to the given value. """ self.speed = speed def speedUp(self, amount): """ changes speed by the given amount Use a negative value to slow down """ self.speed += amount if self.speed < self.minSpeed: self.speed = self.minSpeed if self.speed > self.maxSpeed: self.speed = self.maxSpeed def setAngle(self, dir): """ sets both the direction of motion and visual rotation to the given angle If you want to set one or the other, set them directly. Angle measured in degrees """ self.dir = dir self.rotation = dir def turnBy (self, amt): """ turn by given number of degrees. Changes both motion and visual rotation. Positive is counter-clockwise, negative is clockwise """ self.dir += amt if self.dir > 360: self.dir = amt if self.dir < 0: self.dir = 360 - amt self.rotation = self.dir def rotateBy(self, amt): """ change visual orientation by given number of degrees. Does not change direction of travel. """ self.rotation += amt if self.rotation > 360: self.rotation = amt if self.rotation < 0: self.rotation = 360 - amt def setImage (self, image): """ loads the given file name as the master image default setting should be facing east. Image will be rotated automatically """ self.imageMaster = pygame.image.load(image) self.imageMaster = self.imageMaster.convert() def setDX(self, dx): """ changes dx value and updates vector """ self.dx = dx self.updateVector() def addDX(self, amt): """ adds amt to dx, updates vector """ self.dx += amt self.updateVector() def setDY(self, dy): """ changes dy value and updates vector """ self.dy = dy self.updateVector() def addDY(self, amt): """ adds amt to dy and updates vector """ self.dy += amt self.updateVector() def setComponents(self, components): """ expects (dx, dy) for components change speed and angle according to dx, dy values """ (self.dx, self.dy) = components self.updateVector() def setBoundAction (self, action): """ sets action for boundary. Values are self.WRAP (wrap around edge - default) self.BOUNCE (bounce off screen changing direction) self.STOP (stop at edge of screen) self.HIDE (move off-stage and stop) self.CONTINUE (move on forever) Any other value allows the sprite to move on forever """ self.boundAction = action def setPosition (self, position): """ place the sprite directly at the given position expects an (x, y) tuple """ (self.x, self.y) = position def moveBy (self, vector): """ move the sprite by the (dx, dy) values in vector automatically calls checkBounds. Doesn't change speed or angle settings. """ (dx, dy) = vector self.x += dx self.y += dy self.__checkBounds() def forward(self, amt): """ move amt pixels in the current direction of travel """ #calculate dx dy based on current direction radians = self.dir * math.pi / 180 dx = amt * math.cos(radians) dy = amt * math.sin(radians) * -1 self.x += dx self.y += dy def addForce(self, amt, angle): """ apply amt of thrust in angle. change speed and dir accordingly add a force straight down to simulate gravity in rotation direction to simulate spacecraft thrust in dir direction to accelerate forward at an angle for retro-rockets, etc. """ #calculate dx dy based on angle radians = angle * math.pi / 180 dx = amt * math.cos(radians) dy = amt * math.sin(radians) * -1 self.dx += dx self.dy += dy self.updateVector() def updateVector(self): #calculate new speed and angle based on dx, dy #call this any time you change dx or dy self.speed = math.sqrt((self.dx * self.dx) + (self.dy * self.dy)) dy = self.dy * -1 dx = self.dx radians = math.atan2(dy, dx) self.dir = radians / math.pi * 180 def setSpeedLimits(self, max, min): """ determines maximum and minimum speeds you will allow through speedUp() method. You can still directly set any speed
'x_iam_token'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method delete_healthbot_organization_site_edge_edge_by_id" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'organization_name' is set if ('organization_name' not in params or params['organization_name'] is None): raise ValueError("Missing the required parameter `organization_name` when calling `delete_healthbot_organization_site_edge_edge_by_id`") # noqa: E501 # verify the required parameter 'site_name' is set if ('site_name' not in params or params['site_name'] is None): raise ValueError("Missing the required parameter `site_name` when calling `delete_healthbot_organization_site_edge_edge_by_id`") # noqa: E501 # verify the required parameter 'edge_name' is set if ('edge_name' not in params or params['edge_name'] is None): raise ValueError("Missing the required parameter `edge_name` when calling `delete_healthbot_organization_site_edge_edge_by_id`") # noqa: E501 collection_formats = {} path_params = {} if 'organization_name' in params: path_params['organization_name'] = params['organization_name'] # noqa: E501 if 'site_name' in params: path_params['site_name'] = params['site_name'] # noqa: E501 if 'edge_name' in params: path_params['edge_name'] = params['edge_name'] # noqa: E501 query_params = [] header_params = {} if 'x_iam_token' in params: header_params['x-iam-token'] = params['x_iam_token'] # noqa: E501 form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/config/organization/{organization_name}/site/{site_name}/edge/{edge_name}/', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def delete_healthbot_organization_site_site_by_id(self, organization_name, site_name, **kwargs): # noqa: E501 """Delete site by ID # noqa: E501 Delete operation of resource: site # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_healthbot_organization_site_site_by_id(organization_name, site_name, async_req=True) >>> result = thread.get() :param async_req bool :param str organization_name: ID of organization-name (required) :param str site_name: ID of site-name (required) :param str x_iam_token: authentication header object :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.delete_healthbot_organization_site_site_by_id_with_http_info(organization_name, site_name, **kwargs) # noqa: E501 else: (data) = self.delete_healthbot_organization_site_site_by_id_with_http_info(organization_name, site_name, **kwargs) # noqa: E501 return data def delete_healthbot_organization_site_site_by_id_with_http_info(self, organization_name, site_name, **kwargs): # noqa: E501 """Delete site by ID # noqa: E501 Delete operation of resource: site # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_healthbot_organization_site_site_by_id_with_http_info(organization_name, site_name, async_req=True) >>> result = thread.get() :param async_req bool :param str organization_name: ID of organization-name (required) :param str site_name: ID of site-name (required) :param str x_iam_token: authentication header object :return: None If the method is called asynchronously, returns the request thread. """ all_params = ['organization_name', 'site_name', 'x_iam_token'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method delete_healthbot_organization_site_site_by_id" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'organization_name' is set if ('organization_name' not in params or params['organization_name'] is None): raise ValueError("Missing the required parameter `organization_name` when calling `delete_healthbot_organization_site_site_by_id`") # noqa: E501 # verify the required parameter 'site_name' is set if ('site_name' not in params or params['site_name'] is None): raise ValueError("Missing the required parameter `site_name` when calling `delete_healthbot_organization_site_site_by_id`") # noqa: E501 collection_formats = {} path_params = {} if 'organization_name' in params: path_params['organization_name'] = params['organization_name'] # noqa: E501 if 'site_name' in params: path_params['site_name'] = params['site_name'] # noqa: E501 query_params = [] header_params = {} if 'x_iam_token' in params: header_params['x-iam-token'] = params['x_iam_token'] # noqa: E501 form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/config/organization/{organization_name}/site/{site_name}/', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def retrieve_healthbot_organization_site_edge_edge_by_id(self, organization_name, site_name, edge_name, **kwargs): # noqa: E501 """Retrieve edge by ID # noqa: E501 Retrieve operation of resource: edge # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.retrieve_healthbot_organization_site_edge_edge_by_id(organization_name, site_name, edge_name, async_req=True) >>> result = thread.get() :param async_req bool :param str organization_name: ID of organization-name (required) :param str site_name: ID of site-name (required) :param str edge_name: ID of edge-name (required) :param str x_iam_token: authentication header object :param bool working: true queries undeployed configuration :return: EdgeSchema If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.retrieve_healthbot_organization_site_edge_edge_by_id_with_http_info(organization_name, site_name, edge_name, **kwargs) # noqa: E501 else: (data) = self.retrieve_healthbot_organization_site_edge_edge_by_id_with_http_info(organization_name, site_name, edge_name, **kwargs) # noqa: E501 return data def retrieve_healthbot_organization_site_edge_edge_by_id_with_http_info(self, organization_name, site_name, edge_name, **kwargs): # noqa: E501 """Retrieve edge by ID # noqa: E501 Retrieve operation of resource: edge # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.retrieve_healthbot_organization_site_edge_edge_by_id_with_http_info(organization_name, site_name, edge_name, async_req=True) >>> result = thread.get() :param async_req bool :param str organization_name: ID of organization-name (required) :param str site_name: ID of site-name (required) :param str edge_name: ID of edge-name (required) :param str x_iam_token: authentication header object :param bool working: true queries undeployed configuration :return: EdgeSchema If the method is called asynchronously, returns the request thread. """ all_params = ['organization_name', 'site_name', 'edge_name', 'x_iam_token', 'working'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method retrieve_healthbot_organization_site_edge_edge_by_id" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'organization_name' is set if ('organization_name' not in params or params['organization_name'] is None): raise ValueError("Missing the required parameter `organization_name` when calling `retrieve_healthbot_organization_site_edge_edge_by_id`") # noqa: E501 # verify the required parameter 'site_name' is set if ('site_name' not in params or params['site_name'] is None): raise ValueError("Missing the required parameter `site_name` when calling `retrieve_healthbot_organization_site_edge_edge_by_id`") # noqa: E501 # verify the required parameter 'edge_name' is set if ('edge_name' not in params or params['edge_name'] is None): raise ValueError("Missing the required parameter `edge_name` when calling `retrieve_healthbot_organization_site_edge_edge_by_id`") # noqa: E501 collection_formats = {} path_params = {} if 'organization_name' in params: path_params['organization_name'] = params['organization_name'] # noqa: E501 if 'site_name' in params: path_params['site_name'] = params['site_name'] # noqa: E501 if 'edge_name' in params: path_params['edge_name'] = params['edge_name'] # noqa: E501 query_params = [] if 'working' in params: query_params.append(('working', params['working'])) # noqa: E501 header_params = {} if 'x_iam_token' in params: header_params['x-iam-token'] = params['x_iam_token'] # noqa: E501 form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/config/organization/{organization_name}/site/{site_name}/edge/{edge_name}/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='EdgeSchema', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def retrieve_healthbot_organization_site_site_by_id(self, organization_name, site_name, **kwargs): # noqa: E501 """Retrieve site by ID # noqa: E501 Retrieve operation of resource: site # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.retrieve_healthbot_organization_site_site_by_id(organization_name, site_name, async_req=True) >>> result = thread.get() :param async_req bool :param str organization_name: ID of organization-name (required) :param str site_name: ID of site-name (required) :param str x_iam_token: authentication header object :param bool working: true queries undeployed configuration :return: SiteSchema If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.retrieve_healthbot_organization_site_site_by_id_with_http_info(organization_name, site_name, **kwargs) # noqa: E501 else: (data) = self.retrieve_healthbot_organization_site_site_by_id_with_http_info(organization_name, site_name, **kwargs) # noqa: E501 return data def retrieve_healthbot_organization_site_site_by_id_with_http_info(self, organization_name, site_name, **kwargs): # noqa: E501 """Retrieve site by ID # noqa: E501 Retrieve operation of resource: site # noqa: E501
contribution scalar multiple. avg_price_length: determines length of average of price series. avg_research_length: determines length of average of research series. """ # Splits out the price/research df to individual pandas Series. price = dataframe[PandasEnum.MID.value] research = dataframe["research"] # Calculates the averages. avg_price = price.rolling(window=avg_price_length).mean() avg_research = research.rolling(window=avg_research_length).mean() # Weights each average by the scalar coefficients. price_total = avg_price_coeff * avg_price research_total = avg_research_coeff * avg_research # Sums the contributions and normalises by the level of the price. # N.B. as summing, this approach assumes that research signal is of same dimensionality as the price. position = (price_total + research_total) / price.values dataframe[PandasEnum.ALLOCATION.value] = position return dataframe def change_regression( dataframe: pd.DataFrame, change_coefficient: float = 0.1, change_constant: float = 0.1 ) -> pd.DataFrame: """ This is a regression-type approach that directly calculates allocation from change in the research level. parameters: change_coefficient: The coefficient for allocation size versus the prior day fractional change in the research. change_constant: The coefficient for the constant contribution. """ research = dataframe["research"] position = (research / research.shift(1) - 1) * change_coefficient + change_constant dataframe[PandasEnum.ALLOCATION.value] = position return dataframe def difference_regression( dataframe: pd.DataFrame, difference_coefficient: float = 0.1, difference_constant: float = 0.1 ) -> pd.DataFrame: """ This trading rules regresses the 1-day price changes seen historical against the prior day's % change of the research series. parameters: difference_coefficient: The coefficient for dependence on the log gap between the signal series and the price series. difference_constant: The coefficient for the constant contribution. """ research = dataframe["research"] price = dataframe["price"] position = (research / price - 1) * difference_coefficient + difference_constant dataframe[PandasEnum.ALLOCATION.value] = position return dataframe def level_regression( dataframe: pd.DataFrame, level_coefficient: float = 0.1, level_constant: float = 0.1 ) -> pd.DataFrame: """ This is a regression-type approach that directly calculates allocation from research level. parameters: level_coefficient: The coefficient for allocation size versus the level of the signal. level_constant: The coefficient for the constant contribution. """ research = dataframe["research"] position = research * level_coefficient + level_constant dataframe[PandasEnum.ALLOCATION.value] = position return dataframe def level_and_change_regression( dataframe: pd.DataFrame, level_coefficient: float = 0.1, change_coefficient: float = 0.1, level_and_change_constant: float = 0.1, ) -> pd.DataFrame: """ This trading rules regresses the 1-day price changes seen historical against the prior day's % change of the research series and level of research series. parameters: level_coefficient: The coefficient for allocation size versus the level of the signal. change_coefficient: The coefficient for allocation size versus the prior day fractional change in the research. level_and_change_constant: The coefficient for the constant contribution. """ research = dataframe["research"] position = ( research * level_coefficient + (research / research.shift(1) - 1) * change_coefficient + level_and_change_constant ) dataframe[PandasEnum.ALLOCATION.value] = position return dataframe def buy_golden_cross_sell_death_cross( df: pd.DataFrame, allocation_size: float = 0.5, deallocation_size: float = 0.5, short_term_moving_avg_length: int = 50, long_term_moving_avg_length: int = 200, ) -> pd.DataFrame: """ This trading rule allocates specified percentage of strategy budget to asset when there is a golden cross and deallocates specified percentage of strategy budget from asset when there is a death cross. Allocation and deallocation percentages specified in the parameters. Moving average lengths also specified in the parameters. parameters: allocation_size: The percentage of strategy budget to be allocated to asset upon golden cross deallocation_size: The percentage of strategy budget to deallocate from asset upon death cross short_term_moving_avg_length: The number of days for the short-term moving average length (default: 50 days) long_term_moving_avg_length: The number of days for the long-term moving average length (default: 200 days) """ short_term_df = df["price"].rolling(short_term_moving_avg_length).mean() long_term_df = df["price"].rolling(long_term_moving_avg_length).mean() for i in range(long_term_moving_avg_length + 1, len(df["price"])): if short_term_df[i] >= long_term_df[i] and short_term_df[i - 1] < long_term_df[i - 1]: df.at[i, "allocation"] = allocation_size elif short_term_df[i] <= long_term_df[i] and short_term_df[i - 1] > long_term_df[i - 1]: df.at[i, "allocation"] = -deallocation_size return df def SMA_strategy(df: pd.DataFrame, window: int = 1, max_investment: float = 0.1) -> pd.DataFrame: """ Simple simple moving average strategy which buys when price is above signal and sells when price is below signal """ SMA = signals.simple_moving_average(df, window=window)["signal"] price_above_signal = df["close"] > SMA price_below_signal = df["close"] <= SMA df.loc[price_above_signal, PandasEnum.ALLOCATION.value] = max_investment df.loc[price_below_signal, PandasEnum.ALLOCATION.value] = -max_investment return df def WMA_strategy(df: pd.DataFrame, window: int = 1, max_investment: float = 0.1) -> pd.DataFrame: """ Weighted moving average strategy which buys when price is above signal and sells when price is below signal """ WMA = signals.weighted_moving_average(df, window=window)["signal"] price_above_signal = df["close"] > WMA price_below_signal = df["close"] <= WMA df.loc[price_above_signal, PandasEnum.ALLOCATION.value] = max_investment df.loc[price_below_signal, PandasEnum.ALLOCATION.value] = -max_investment return df def MACD_strategy( df: pd.DataFrame, short_period: int = 12, long_period: int = 26, window_signal: int = 9, max_investment: float = 0.1 ) -> pd.DataFrame: """ Moving average convergence divergence strategy which buys when MACD signal is above 0 and sells when MACD signal is below zero """ MACD_signal = signals.moving_average_convergence_divergence(df, short_period, long_period, window_signal)["signal"] signal_above_zero_line = MACD_signal > 0 signal_below_zero_line = MACD_signal <= 0 df.loc[signal_above_zero_line, PandasEnum.ALLOCATION.value] = max_investment df.loc[signal_below_zero_line, PandasEnum.ALLOCATION.value] = -max_investment return df def RSI_strategy(df: pd.DataFrame, window: int = 14, max_investment: float = 0.1) -> pd.DataFrame: """ Relative Strength Index """ # https://www.investopedia.com/terms/r/rsi.asp RSI = signals.relative_strength_index(df, window=window)["signal"] over_valued = RSI >= 70 under_valued = RSI <= 30 hold = RSI.between(30, 70) df.loc[over_valued, PandasEnum.ALLOCATION.value] = -max_investment df.loc[under_valued, PandasEnum.ALLOCATION.value] = max_investment df.loc[hold, PandasEnum.ALLOCATION.value] = 0.0 return df def stochastic_RSI_strategy(df: pd.DataFrame, window: int = 14, max_investment: float = 0.1) -> pd.DataFrame: """ Stochastic Relative Strength Index Strategy """ # https://www.investopedia.com/terms/s/stochrsi.asp stochRSI = signals.stochastic_relative_strength_index(df, window=window)["signal"] over_valued = stochRSI >= 0.8 under_valued = stochRSI <= 0.2 hold = stochRSI.between(0.2, 0.8) df.loc[over_valued, PandasEnum.ALLOCATION.value] = -max_investment df.loc[under_valued, PandasEnum.ALLOCATION.value] = max_investment df.loc[hold, PandasEnum.ALLOCATION.value] = 0.0 return df def EMA_strategy(df: pd.DataFrame, window: int = 1, max_investment: float = 0.1) -> pd.DataFrame: """ Exponential moving average strategy which buys when price is above signal and sells when price is below signal """ EMA = signals.exponentially_weighted_moving_average(df, window=window)["signal"] price_above_signal = df["close"] > EMA price_below_signal = df["close"] <= EMA df.loc[price_above_signal, PandasEnum.ALLOCATION.value] = max_investment df.loc[price_below_signal, PandasEnum.ALLOCATION.value] = -max_investment return df infertrade_export_allocations = { "fifty_fifty": { "function": fifty_fifty, "parameters": {}, "series": [], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "buy_and_hold": { "function": buy_and_hold, "parameters": {}, "series": [], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L37" }, }, "chande_kroll_crossover_strategy": { "function": chande_kroll_crossover_strategy, "parameters": {}, "series": [], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L43" }, }, "change_relationship": { "function": change_relationship, "parameters": {}, "series": [], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L59" }, }, "combination_relationship": { "function": combination_relationship, "parameters": {}, "series": [], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "difference_relationship": { "function": difference_relationship, "parameters": {}, "series": [], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "level_relationship": { "function": level_relationship, "parameters": {}, "series": [], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "constant_allocation_size": { "function": constant_allocation_size, "parameters": {"fixed_allocation_size": 1.0}, "series": [], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "high_low_difference": { "function": high_low_difference, "parameters": {"scale": 1.0, "constant": 0.0}, "series": ["high", "low"], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "sma_crossover_strategy": { "function": sma_crossover_strategy, "parameters": {"fast": 0, "slow": 0}, "series": ["price"], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "weighted_moving_averages": { "function": weighted_moving_averages, "parameters": { "avg_price_coeff": 1.0, "avg_research_coeff": 1.0, "avg_price_length": 2, "avg_research_length": 2, }, "series": ["research"], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "change_regression": { "function": change_regression, "parameters": {"change_coefficient": 0.1, "change_constant": 0.1}, "series": ["research"], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "difference_regression": { "function": difference_regression, "parameters": {"difference_coefficient": 0.1, "difference_constant": 0.1}, "series": ["price", "research"], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "level_regression": { "function": level_regression, "parameters": {"level_coefficient": 0.1, "level_constant": 0.1}, "series": ["research"], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "level_and_change_regression": { "function": level_and_change_regression, "parameters": {"level_coefficient": 0.1, "change_coefficient": 0.1, "level_and_change_constant": 0.1}, "series": ["research"], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "buy_golden_cross_sell_death_cross": { "function": buy_golden_cross_sell_death_cross, "parameters": { "allocation_size": 0.5, "deallocation_size": 0.5, "short_term_moving_avg_length": 50, "long_term_moving_avg_length": 200, }, "series": ["research"], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "SMA_strategy": { "function": SMA_strategy, "parameters": {"window": 1, "max_investment": 0.1}, "series": ["close"], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L31" }, }, "WMA_strategy": { "function": WMA_strategy, "parameters": {"window": 1, "max_investment": 0.1}, "series": ["close"], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L282" }, }, "MACD_strategy": { "function": MACD_strategy, "parameters": {"short_period": 12, "long_period": 26, "window_signal": 9, "max_investment": 0.1}, "series": ["close"], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L296" }, }, "RSI_strategy": { "function": RSI_strategy, "parameters": {"window": 14, "max_investment": 0.1}, "series": ["close"], "available_representation_types": { "github_permalink": "https://github.com/ta-oliver/infertrade/blob/f571d052d9261b7dedfcd23b72d925e75837ee9c/infertrade/algos/community/allocations.py#L309" },
from NER.utils import * from NER.embedding import embed import torch import matplotlib.pyplot as plt # single Task class rnn_single_crf(nn.Module): def __init__(self, cti_size, wti_size, num_tags , params): super().__init__() self.rnn = rnn(cti_size, wti_size, num_tags , params) self.crf = crf(num_tags , params) self = self.cuda(ACTIVE_DEVICE) if CUDA else self self.HRE = params['HRE'] self.BATCH_SIZE = params['BATCH_SIZE'] self.params = params def forward(self, xc, xw, y0): # for training self.zero_grad() self.rnn.batch_size = y0.size(0) self.crf.batch_size = y0.size(0) mask = y0[:, 1:].gt(PAD_IDX).float() #print("xw", xw.shape) #print('mask' , mask.shape) h = self.rnn(xc, xw, mask) #print("h :" , h.shape) Z = self.crf.forward(h, mask) #print("Y0 :" , y0 , Z) score = self.crf.score(h, y0, mask) #print("score :", score) return torch.mean(Z - score) # NLL loss def decode(self, xc, xw, doc_lens): # for inference self.rnn.batch_size = len(doc_lens) if self.HRE else xw.size(0) self.crf.batch_size = len(doc_lens) if self.HRE else xw.size(0) if self.HRE: mask = Tensor([[1] * x + [PAD_IDX] * (doc_lens[0] - x) for x in doc_lens]) else: mask = xw.gt(PAD_IDX).float() h = self.rnn(xc, xw, mask) return self.crf.decode(h, mask) def loaddata(self, sentences, cti, wti, itt , y0 = None): data = dataloader() block = [] for si, sent in enumerate(sentences): sent = normalize(sent) words = tokenize(sent) #sent.split(' ') x = [] for w in words: w = normalize(w) wxc = [cti[c] if c in cti else UNK_IDX for c in w] x.append((wxc , wti[w] if w in wti else UNK_IDX)) xc , xw = zip(*x) if y0: assert len(y0[si]) == len(xw) , "Tokens length is not the same as Target length (y0)!" block.append((sent, xc,xw , y0[si])) else: block.append((sent, xc,xw)) for s in block: if y0: data.append_item( x0 = [s[0]] , xc= [list(s[1])] , xw =[list(s[2])] , y0 = s[3]) data.append_row() else: data.append_item( x0 = [s[0]] , xc= [list(s[1])] , xw =[list(s[2])] , y0 = []) data.append_row() data.strip() data.sort() return data def predict(self , sentences , cti , wti , itt ): """ sentences : List of sentence space seperated (tokenization will be done simply by spliting the space between words) cti : Character to Index that model trained wti : Word to Index that model trained itt : Index To Tag (Inside Other Begin) """ data = self.loaddata(sentences,cti,wti,itt ) for batch in data.split(self.BATCH_SIZE, self.HRE): xc , xw = data.tensor(batch.xc , batch.xw , batch.lens) y1 = self.decode(xc, xw, batch.lens) data.y1.extend([[itt[i] for i in x] for x in y1]) data.unsort() return data def evaluate(self, sentences, cti , wti , itt , y0 , parameters = [] , model_name = None , save = False , filename = None ): """ sentences : List of sentence space seperated (tokenization will be done simply by spliting the space between words) cti : Character to Index that model trained wti : Word to Index that model trained itt : Index To Tag (Inside Other Begin) y0 : Target values to evaluate parameters : 'macro_precision','macro_recall','hmacro_f1', 'amacro_f1','micro_f1','auc' """ data = self.loaddata(sentences, cti, wti , itt , y0) for batch in data.split(self.BATCH_SIZE, self.HRE): xc , xw = data.tensor(batch.xc , batch.xw , batch.lens) y1 = self.decode(xc, xw, batch.lens) data.y1.extend([[itt[i] for i in x] for x in y1]) data.unsort() result = metrics(data.y0 , data.y1 , model_name=model_name,save=save,filename=filename) if parameters: print("============ evaluation results ============") for m in parameters: if m in result: print("\t" + m +" = %f"% result[m]) return data # Two Sequential # this is tested based on jupyter Run-rnn_two_crf_seq class rnn_two_crf_seq(nn.Module): def __init__(self, cti_size, wti_size , num_tags_iob , num_tag_ner , params): """ num_output_rnn : Maximum number of out put for the two iob and ner """ super().__init__() self.rnn_iob = rnn(cti_size, wti_size, num_tags_iob , params) self.crfiob = crf(num_tags_iob , params) self.HRE = params['HRE'] self.BATCH_SIZE = params['BATCH_SIZE'] self.NUM_DIRS = params['NUM_DIRS'] self.NUM_LAYERS = params['NUM_LAYERS'] self.DROPOUT = params['DROPOUT'] self.RNN_TYPE = params['RNN_TYPE'] self.HIDDEN_SIZE = params['HIDDEN_SIZE'] self.rnn_ner = getattr(nn, self.RNN_TYPE)( input_size = num_tags_iob, hidden_size = self.HIDDEN_SIZE // self.NUM_DIRS, num_layers = self.NUM_LAYERS, bias = True, batch_first = True, dropout = self.DROPOUT, bidirectional = (self.NUM_DIRS == 2) ) self.out = nn.Linear(self.HIDDEN_SIZE, num_tag_ner) # RNN output to tag self.crfner = crf(num_tag_ner , params) self.params = params self = self.cuda(ACTIVE_DEVICE) if CUDA else self def forward(self, xc, xw, yiob , yner): # for training self.zero_grad() self.rnn_iob.batch_size = xw.size(0) self.rnn_ner.batch_size = xw.size(0) self.crfiob.batch_size = xw.size(0) self.crfner.batch_size = xw.size(0) # Mask on sentence mask = xw[:,1:].gt(PAD_IDX).float() # Layer one get the embed and then go to crf for IOB h_iob = self.rnn_iob(xc, xw, mask) #mask_iob = yiob[:, 1:].gt(PAD_IDX).float() #print('MASK_IOB') #print(mask_iob) # this need to be backward when we train it () Ziob = self.crfiob.forward(h_iob, mask) # Result of IOB will go to the RNN and Predict the NER h_iob *= mask.unsqueeze(2) h_ner , _ = self.rnn_ner(h_iob) ner_out = self.out(h_ner) t = 2 # to see how CRF converge the model to the output #for _nerpred, _nery in zip(ner_out , yner): # plt.plot(_nerpred[_nery[t+1]].cpu().data.numpy()) # plt.vlines(x=_nery[t+1].cpu().data.numpy(),ymin= 0 , ymax=1) # plt.show() #print(_nerpred[_nery[t+1]].data , _nery[t+1].data) #ner_out *= mask.unsqueeze(2) #mask_ner = yner[:, 1:].gt(PAD_IDX).float() #print('MASK_NER') #print(mask_ner) Zner = self.crfner.forward(ner_out, mask) scoreiob = self.crfiob.score(h_iob, yiob, mask) scorener = self.crfner.score(ner_out, yner, mask) return torch.mean(Ziob - scoreiob) , torch.mean(Zner - scorener) # NLL loss def decode(self, xc, xw, doc_lens): # for inference self.rnn_iob.batch_size = len(doc_lens) if self.HRE else xw.size(0) self.rnn_ner.batch_size = len(doc_lens) if self.HRE else xw.size(0) self.crfiob.batch_size = len(doc_lens) if self.HRE else xw.size(0) self.crfner.batch_size = len(doc_lens) if self.HRE else xw.size(0) if self.HRE: mask = Tensor([[1] * x + [PAD_IDX] * (doc_lens[0] - x) for x in doc_lens]) else: mask = xw.gt(PAD_IDX).float() iob_pred = self.rnn_iob(xc, xw, mask) #iob_pred = self.iob(h_bio) h_ner , _ = self.rnn_ner(iob_pred) ner_pred = self.out(h_ner) return self.crfiob.decode(iob_pred, mask) , self.crfner.decode(ner_pred, mask) def loaddata(self, sentences , cti , wti , itt_iob , itt_ner , yiob=None , yner =None): data = dataloader() block = [] for si ,sent in enumerate(sentences) : sent = normalize(sent) words = tokenize(sent) #sent.split(' ') x = [] tokens = [] for w in words: w = normalize(w) wxc = [cti[c] if c in cti else UNK_IDX for c in w] x.append((wxc , wti[w] if w in wti else UNK_IDX)) tokens.append(w) xc , xw = zip(*x) if yiob and yner: assert len(yiob[si]) == len(xw) , "Tokens length is not the same as Target length (y0)!" assert len(yner[si]) == len(xw) , "Tokens length is not the same as Target length (y0)!" block.append((sent,tokens, xc,xw , yiob[si] , yner[si])) else: block.append((sent,tokens, xc,xw)) for s in block: if yiob and yner: data.append_item( x0 = [s[0]] , x1 = [s[1]] , xc= [list(s[2])] , xw =[list(s[3])] , yiob=s[4] , yner =s[5]) data.append_row() else: data.append_item( x0 = [s[0]] , x1 = [s[1]] , xc= [list(s[2])] , xw =[list(s[3])] , yiob=[] , yner =[] ) data.append_row() data.strip() data.sort() return data def predict(self , sentences , cti , wti , itt_iob , itt_ner): """ sentences : List of sentence space seperated (tokenization will be done simply by spliting the space between words) cti : Character to Index that model trained wti : Word to Index that model trained itt_iob : Index To Tag IOB (Inside Other Begin) itt_ner : Index To Tag Named Entity REcognition """ #itt_iob = {v:k for k,v in tti_iob.items()} #itt_ner = {v:k for k,v in tti_ner.items()} data = self.loaddata(sentences , cti , wti , itt_iob , itt_ner) for batch in data.split(self.BATCH_SIZE, self.HRE): xc , xw = data.tensor(batch.xc , batch.xw , batch.lens) yiob , yner = self.decode(xc, xw, batch.lens) #print(yiob , yner) #print([[itt_iob[i] if i in itt_iob else O for i in x] for x in yiob]) data.y1iob.extend([[itt_iob[i] for i in x] for x in yiob]) data.y1ner.extend([[itt_ner[i] for i in x] for x in yner]) data.unsort() #print(data.y1iob , data.x1) return data def evaluate(self, sentences , cti , wti , itt_iob , itt_ner , y0iob , y0ner , parameters = [] , model_name = None , save = False , filename = None ): """ sentences : List of sentence space seperated (tokenization will be done simply by spliting the space between words) cti : Character to
# 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. """ P1 tests for elastic load balancing and elastic IP """ # Import Local Modules from nose.plugins.attrib import attr from marvin.cloudstackTestCase import cloudstackTestCase import unittest from marvin.cloudstackAPI import (authorizeSecurityGroupIngress, disassociateIpAddress, deleteLoadBalancerRule) from marvin.lib.utils import cleanup_resources from marvin.lib.base import (Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange) from marvin.lib.common import (get_zone, get_domain, get_template) from marvin.sshClient import SshClient import time class Services: """Test elastic load balancing and elastic IP """ def __init__(self): self.services = { "account": { "email": "<EMAIL>", "firstname": "Test", "lastname": "User", "username": "test", # Random characters are appended for unique # username "password": "password", }, "service_offering": { "name": "Tiny Instance", "displaytext": "Tiny Instance", "cpunumber": 1, "cpuspeed": 100, # in MHz "memory": 128, # In MBs }, "lbrule": { "name": "SSH", "alg": "roundrobin", # Algorithm used for load balancing "privateport": 22, "publicport": 22, "openfirewall": False, }, "natrule": { "privateport": 22, "publicport": 22, "protocol": "TCP" }, "virtual_machine": { "displayname": "Test VM", "username": "root", "password": "password", "ssh_port": 22, "hypervisor": 'XenServer', # Hypervisor type should be same as # hypervisor type of cluster "privateport": 22, "publicport": 22, "protocol": 'TCP', }, "ostype": 'CentOS 5.3 (64-bit)', # Cent OS 5.3 (64 bit) "sleep": 60, "timeout": 10, } class TestEIP(cloudstackTestCase): @classmethod def setUpClass(cls): cls.testClient = super(TestEIP, cls).getClsTestClient() cls.api_client = cls.testClient.getApiClient() cls.services = Services().services try: cls.services["netscaler"] = cls.config.__dict__[ "netscalerDevice"].__dict__ except KeyError: raise unittest.SkipTest("Please make sure you have included netscalerDevice\ dict in your config file (keys - ipaddress, username,\ password") except Exception as e: raise unittest.SkipTest(e) # Get Zone, Domain and templates cls.domain = get_domain(cls.api_client) cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests()) cls.services['mode'] = cls.zone.networktype cls.template = get_template( cls.api_client, cls.zone.id, cls.services["ostype"] ) cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["virtual_machine"]["template"] = cls.template.id cls.service_offering = ServiceOffering.create( cls.api_client, cls.services["service_offering"] ) cls.account = Account.create( cls.api_client, cls.services["account"], admin=True, domainid=cls.domain.id ) # Spawn an instance cls.virtual_machine = VirtualMachine.create( cls.api_client, cls.services["virtual_machine"], accountid=cls.account.name, domainid=cls.account.domainid, serviceofferingid=cls.service_offering.id ) networks = Network.list( cls.api_client, zoneid=cls.zone.id, listall=True ) if isinstance(networks, list): # Basic zone has only one network i.e Basic network cls.guest_network = networks[0] else: raise Exception( "List networks returned empty response for zone: %s" % cls.zone.id) ip_addrs = PublicIPAddress.list( cls.api_client, associatednetworkid=cls.guest_network.id, isstaticnat=True, account=cls.account.name, domainid=cls.account.domainid, listall=True ) if isinstance(ip_addrs, list): cls.source_nat = ip_addrs[0] print("source_nat ipaddress : ", cls.source_nat.ipaddress) else: raise Exception( "No Source NAT IP found for guest network: %s" % cls.guest_network.id) cls._cleanup = [ cls.account, cls.service_offering, ] return @classmethod def tearDownClass(cls): try: # Cleanup resources used cleanup_resources(cls.api_client, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): self.apiclient = self.testClient.getApiClient() self.dbclient = self.testClient.getDbConnection() self.cleanup = [] return def tearDown(self): try: # Clean up, terminate the created network offerings cleanup_resources(self.apiclient, self.cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return @attr(tags=["eip"]) def test_01_eip_by_deploying_instance(self): """Test EIP by deploying an instance """ # Validate the following # 1. Instance gets an IP from GUEST IP range. # 2. One IP from EIP pool is taken and configured on NS # commands to verify on NS: # show ip, show inat- make sure that output says USIP : ON # 3. After allowing ingress rule based on source CIDR to the # respective port, verify that you are able to reach guest with EIP # 4. user_ip_address.is_system=1, user_ip_address.one_to_one_nat=1 self.debug("Fetching public network IP range for public network") ip_ranges = PublicIpRange.list( self.apiclient, zoneid=self.zone.id, forvirtualnetwork=True ) self.assertEqual( isinstance(ip_ranges, list), True, "Public IP range should return a valid range" ) # Guest network can have multiple IP ranges. In that case, split IP # address and then compare the values for ip_range in ip_ranges: self.debug("IP range: %s - %s" % ( ip_range.startip, ip_range.endip )) start_ip_list = ip_range.startip.split(".") end_ip_list = ip_range.endip.split(".") source_nat_list = self.source_nat.ipaddress.split(".") self.assertGreaterEqual( int(source_nat_list[3]), int(start_ip_list[3]), "The NAT should be greater/equal to start IP of guest network" ) self.assertLessEqual( int(source_nat_list[3]), int(end_ip_list[3]), "The NAT should be less/equal to start IP of guest network" ) # Verify listSecurity groups response security_groups = SecurityGroup.list( self.apiclient, account=self.account.name, domainid=self.account.domainid ) self.assertEqual( isinstance(security_groups, list), True, "Check for list security groups response" ) self.assertEqual( len(security_groups), 1, "Check List Security groups response" ) self.debug("List Security groups response: %s" % str(security_groups)) security_group = security_groups[0] self.debug( "Creating Ingress rule to allow SSH on default security group") cmd = authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd() cmd.domainid = self.account.domainid cmd.account = self.account.name cmd.securitygroupid = security_group.id cmd.protocol = 'TCP' cmd.startport = 22 cmd.endport = 22 cmd.cidrlist = '0.0.0.0/0' self.apiclient.authorizeSecurityGroupIngress(cmd) # COMMENTED: # try: # self.debug("SSH into VM: %s" % self.virtual_machine.ssh_ip) # ssh = self.virtual_machine.get_ssh_client( # ipaddress=self.source_nat.ipaddress) # except Exception as e: # self.fail("SSH Access failed for %s: %s" % \ # (self.virtual_machine.ipaddress, e) # ) # Fetch details from user_ip_address table in database self.debug( "select is_system, one_to_one_nat from user_ip_address\ where public_ip_address='%s';" % self.source_nat.ipaddress) qresultset = self.dbclient.execute( "select is_system, one_to_one_nat from user_ip_address\ where public_ip_address='%s';" % self.source_nat.ipaddress) self.assertEqual( isinstance(qresultset, list), True, "Check DB query result set for valid data" ) self.assertNotEqual( len(qresultset), 0, "Check DB Query result set" ) qresult = qresultset[0] self.assertEqual( qresult[0], 1, "user_ip_address.is_system value should be 1 for static NAT" ) self.assertEqual( qresult[1], 1, "user_ip_address.one_to_one_nat value should be 1 for static NAT" ) self.debug("SSH into netscaler: %s" % self.services["netscaler"]["ipaddress"]) ssh_client = SshClient( self.services["netscaler"]["ipaddress"], 22, self.services["netscaler"]["username"], self.services["netscaler"]["password"], ) self.debug("command: show ip") res = ssh_client.execute("show ip") result = str(res) self.debug("Output: %s" % result) self.assertEqual( result.count(self.source_nat.ipaddress), 1, "One IP from EIP pool should be taken and configured on NS" ) self.debug("Command:show inat") res = ssh_client.execute("show inat") result = str(res) self.debug("Output: %s" % result) self.assertEqual( result.count( "NAME: Cloud-Inat-%s" % self.source_nat.ipaddress), 1, "User source IP should be enabled for INAT service") return @attr(tags=["eip"]) def test_02_acquire_ip_enable_static_nat(self): """Test associate new IP and enable static NAT for new IP and the VM """ # Validate the following # 1. user_ip_address.is_system = 0 & user_ip_address.one_to_one_nat=1 # 2. releases default EIP whose user_ip_address.is_system=1 # 3. After allowing ingress rule based on source CIDR to the # respective port, verify that you are able to reach guest with EIP # 4. check configuration changes for EIP reflects on NS # commands to verify on NS : # * "show ip" # * "show inat" - make sure that output says USIP : ON self.debug("Acquiring new IP for network: %s" % self.guest_network.id) public_ip = PublicIPAddress.create( self.apiclient, accountid=self.account.name, zoneid=self.zone.id, domainid=self.account.domainid, services=self.services["virtual_machine"] ) self.debug("IP address: %s is acquired by network: %s" % ( public_ip.ipaddress.ipaddress, self.guest_network.id)) self.debug("Enabling static NAT for IP Address: %s" % public_ip.ipaddress.ipaddress) StaticNATRule.enable( self.apiclient, ipaddressid=public_ip.ipaddress.id, virtualmachineid=self.virtual_machine.id ) # Fetch details from user_ip_address table in database self.debug( "select is_system, one_to_one_nat from user_ip_address\ where public_ip_address='%s';" % public_ip.ipaddress.ipaddress) qresultset = self.dbclient.execute( "select is_system, one_to_one_nat from user_ip_address\ where public_ip_address='%s';" % public_ip.ipaddress.ipaddress) self.assertEqual( isinstance(qresultset, list), True, "Check DB query result set for valid data" ) self.assertNotEqual( len(qresultset), 0, "Check DB Query result set" ) qresult = qresultset[0] self.assertEqual( qresult[0], 0, "user_ip_address.is_system value should be 0 for new IP" ) self.assertEqual( qresult[1], 1, "user_ip_address.one_to_one_nat value should be 1 for static NAT" ) self.debug( "select is_system, one_to_one_nat from user_ip_address\ where public_ip_address='%s';" % self.source_nat.ipaddress) qresultset = self.dbclient.execute( "select is_system, one_to_one_nat from user_ip_address\ where public_ip_address='%s';" % self.source_nat.ipaddress) self.assertEqual( isinstance(qresultset, list), True, "Check DB query result set for valid data" ) self.assertNotEqual( len(qresultset), 0, "Check DB Query result set" ) qresult = qresultset[0] self.assertEqual( qresult[0], 0, "user_ip_address.is_system value should be 0 old source NAT" ) # try: # self.debug("SSH into VM: %s" % public_ip.ipaddress) # ssh = self.virtual_machine.get_ssh_client( # ipaddress=public_ip.ipaddress) # except Exception as e: # self.fail("SSH Access failed for %s: %s" % \ # (public_ip.ipaddress, e) # )
<filename>SeisSrcInv/plot.py #!python #----------------------------------------------------------------------------------------------------------------------------------------- # Script Description: # Script to take unconstrained moment tensor or DC or single force inversion result (from full waveform inversion) and plot results. # Input variables: # See run() function description. # Output variables: # See run() function description. # Created by <NAME>, 9th April 2018 #----------------------------------------------------------------------------------------------------------------------------------------- # Import neccessary modules: import numpy as np from numpy.linalg import eigh # For calculating eigenvalues and eigenvectors of symetric (Hermitian) matrices import matplotlib import matplotlib.pyplot as plt import obspy import scipy.io as sio # For importing .mat MT solution data import scipy.optimize as opt # For curve fitting import math # For plotting contours as line import os,sys import random from matplotlib import path # For getting circle bounding path for MT plotting from obspy.imaging.scripts.mopad import MomentTensor, BeachBall, NED2USE # For getting nodal planes for unconstrained moment tensors from obspy.core.event.source import farfield # For calculating MT radiation patterns from matplotlib.patches import Polygon, Circle # For plotting MT radiation patterns import matplotlib.patches as mpatches # For adding patches for creating legends etc from matplotlib.collections import PatchCollection # For plotting MT radiation patterns import glob import pickle import matplotlib.gridspec as gridspec # ------------------------------------------------ Specify module functions ------------------------------------------------ def load_MT_dict_from_file(matlab_data_filename): # If output from MTFIT: if matlab_data_filename[-3:] == "mat": data=sio.loadmat(matlab_data_filename) i=0 while True: try: # Load data UID from matlab file: if data['Events'][0].dtype.descr[i][0] == 'UID': uid=data['Events'][0][0][i][0] if data['Events'][0].dtype.descr[i][0] == 'Probability': MTp=data['Events'][0][0][i][0] # stored as a n length vector, the probability if data['Events'][0].dtype.descr[i][0] == 'MTSpace': MTs=data['Events'][0][0][i] # stored as a 6 by n array (6 as 6 moment tensor components) MTp_absolute = [] i+=1 except IndexError: break try: stations = data['Stations'] except KeyError: stations = [] # Else if output from full waveform inversion: elif matlab_data_filename[-3:] == "pkl": FW_dict = pickle.load(open(matlab_data_filename,"rb")) uid = FW_dict["uid"] MTp = FW_dict["MTp"] MTs = FW_dict["MTs"] stations = np.array(FW_dict["stations"], dtype=object) # And try to get absolute similarity/probability values: try: MTp_absolute = FW_dict["MTp_absolute"] except KeyError: MTp_absolute = [] else: print("Cannot recognise input filename.") return uid, MTp, MTp_absolute, MTs, stations def find_nearest(array,value): idx = (np.abs(array-value)).argmin() return array[idx], idx def load_MT_waveforms_dict_from_file(waveforms_data_filename): """Function to read waveforms dict output from full_waveform_inversion.""" wfs_dict = pickle.load(open(waveforms_data_filename, "rb")) return wfs_dict def get_full_MT_array(mt): full_MT = np.array( ([[mt[0],mt[3]/np.sqrt(2.),mt[4]/np.sqrt(2.)], [mt[3]/np.sqrt(2.),mt[1],mt[5]/np.sqrt(2.)], [mt[4]/np.sqrt(2.),mt[5]/np.sqrt(2.),mt[2]]]) ) return full_MT def TP_FP(T,P): """Converts T,P vectors to the fault normal and slip Converts the 3x3 Moment Tensor to the fault normal and slip vectors. Args T: numpy matrix of T vectors. P: numpy matrix of P vectors. Returns (numpy.matrix, numpy.matrix): tuple of Normal and slip vectors (Note: Function from MTFIT.MTconvert) """ if T.ndim==1: T=np.matrix(T) if P.ndim==1: P=np.matrix(P) if T.shape[0]!=3: T=T.T if P.shape[0]!=3: P=P.T N1=(T+P)/np.sqrt(np.diag(np.matrix(T+P).T*np.matrix(T+P))) N2=(T-P)/np.sqrt(np.diag(np.matrix(T-P).T*np.matrix(T-P))) return N1,N2 def MT33_TNPE(MT33): """Converts 3x3 matrix to T,N,P vectors and the eigenvalues Converts the 3x3 Moment Tensor to the T,N,P vectors and the eigenvalues. Args MT33: 3x3 numpy matrix Returns (numpy.matrix, numpy.matrix, numpy.matrix, numpy.array): tuple of T, N, P vectors and Eigenvalue array (Note: Function from MTFIT.MTconvert) """ E,L=np.linalg.eig(MT33) idx = E.argsort()[::-1] E=E[idx] L=L[:,idx] T=L[:,0] P=L[:,2] N=L[:,1] return T,N,P,E def FP_SDR(normal,slip): """Converts fault normal and slip to strike dip rake Coordinate system is North East Down. Args normal: numpy matrix - Normal vector slip: numpy matrix - Slip vector Returns (float, float, float): tuple of strike, dip and rake angles in radians (Note: Function from MTFIT.MTconvert) """ if type(slip)==np.ndarray: slip=slip/np.sqrt(np.sum(slip*slip)) else: slip=slip/np.sqrt(np.diag(slip.T*slip)) if type(normal)==np.ndarray: normal=normal/np.sqrt(np.sum(normal*normal)) else: normal=normal/np.sqrt(np.diag(normal.T*normal)) slip[:,np.array(normal[2,:]>0).flatten()]*=-1 normal[:,np.array(normal[2,:]>0).flatten()]*=-1 normal=np.array(normal) slip=np.array(slip) strike,dip=normal_SD(normal) rake=np.arctan2(-slip[2],slip[0]*normal[1]-slip[1]*normal[0]) strike[dip>np.pi/2]+=np.pi rake[dip>np.pi/2]=2*np.pi-rake[dip>np.pi/2] dip[dip>np.pi/2]=np.pi-dip[dip>np.pi/2] strike=np.mod(strike,2*np.pi) rake[rake>np.pi]-=2*np.pi rake[rake<-np.pi]+=2*np.pi return np.array(strike).flatten(),np.array(dip).flatten(),np.array(rake).flatten() def normal_SD(normal): """ Convert a plane normal to strike and dip Coordinate system is North East Down. Args normal: numpy matrix - Normal vector Returns (float, float): tuple of strike and dip angles in radians """ if not isinstance(normal, np.matrixlib.defmatrix.matrix): normal = np.array(normal)/np.sqrt(np.sum(normal*normal, axis=0)) else: normal = normal/np.sqrt(np.diag(normal.T*normal)) normal[:, np.array(normal[2, :] > 0).flatten()] *= -1 normal = np.array(normal) strike = np.arctan2(-normal[0], normal[1]) dip = np.arctan2((normal[1]**2+normal[0]**2), np.sqrt((normal[0]*normal[2])**2+(normal[1]*normal[2])**2)) strike = np.mod(strike, 2*np.pi) return strike, dip def MT33_SDR(MT33): """Converts 3x3 matrix to strike dip and rake values (in radians) Converts the 3x3 Moment Tensor to the strike, dip and rake. Args MT33: 3x3 numpy matrix Returns (float, float, float): tuple of strike, dip, rake angles in radians (Note: Function from MTFIT.MTconvert) """ T,N,P,E=MT33_TNPE(MT33) N1,N2=TP_FP(T,P) return FP_SDR(N1,N2) def rotation_matrix(axis, theta): """ Function to get rotation matrix given an axis of rotation and a rotation angle. Based on Euler-Rodrigues formula. Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. (From: https://stackoverflow.com/questions/6802577/rotation-of-3d-vector) """ axis = np.asarray(axis) axis = axis/math.sqrt(np.dot(axis, axis)) a = math.cos(theta/2.0) b, c, d = -axis*math.sin(theta/2.0) aa, bb, cc, dd = a*a, b*b, c*c, d*d bc, ad, ac, ab, bd, cd = b*c, a*d, a*c, a*b, b*d, c*d return np.array([[aa+bb-cc-dd, 2*(bc+ad), 2*(bd-ac)], [2*(bc-ad), aa+cc-bb-dd, 2*(cd+ab)], [2*(bd+ac), 2*(cd-ab), aa+dd-bb-cc]]) def get_slip_vector_from_full_MT(full_MT): """Function to get slip vector from full MT.""" # Get sorted eigenvectors: # Find the eigenvalues for the MT solution and sort into descending order: w,v = eigh(full_MT) # Find eigenvalues and associated eigenvectors for the symetric (Hermitian) MT matrix (for eigenvalue w[i], eigenvector is v[:,i]) full_MT_eigvals_sorted = np.sort(w)[::-1] # Sort eigenvalues into descending order # Get T-axis (eigenvector corresponding to highest eigenvalue): T_axis_eigen_value = full_MT_eigvals_sorted[0] # Highest eigenvalue value T_axis_eigenvector_idx = np.where(w==T_axis_eigen_value)[0][0] T_axis_vector = v[:,T_axis_eigenvector_idx] # Get null-axis (eigenvector corresponding to intermediate eigenvalue): null_axis_eigen_value = full_MT_eigvals_sorted[1] # Intermediate eigenvalue value null_axis_eigenvector_idx = np.where(w==null_axis_eigen_value)[0][0] null_axis_vector = v[:,null_axis_eigenvector_idx] # Get P-axis (eigenvector corresponding to lowest eigenvalue) (for completeness only): P_axis_eigen_value = full_MT_eigvals_sorted[2] # Lowest eigenvalue value P_axis_eigenvector_idx = np.where(w==P_axis_eigen_value)[0][0] P_axis_vector = v[:,P_axis_eigenvector_idx] # Get slip vector: # (For fault plane 1) slip_vector = (1./np.sqrt(2))*(T_axis_vector - P_axis_vector) normal_axis_vector = (1./np.sqrt(2))*(T_axis_vector + P_axis_vector) # s,d,r = MT33_SDR(full_MT) # sdr = [s[0], d[0], r[0]] # normal_axis_vector = np.array([- np.sin(sdr[1]) * np.sin(sdr[0]), # - np.sin(sdr[1]) * np.sin(sdr[0]), # np.cos(sdr[1])]) # slip_vector = [np.cos(sdr[2]) * np.cos(sdr[0]) + np.sin(sdr[2]) * np.cos(sdr[1]) * np.sin(sdr[0]), # - np.cos(sdr[2]) * np.sin(sdr[0]) + np.sin(sdr[2]) * np.cos(sdr[1]) * np.cos(sdr[0]), # np.sin(sdr[2]) * np.sin(sdr[1])] return slip_vector, normal_axis_vector, T_axis_vector, null_axis_vector, P_axis_vector def convert_spherical_coords_to_cartesian_coords(r,theta,phi): """Function to take spherical coords and convert to cartesian coords. (theta between 0 and pi, phi between 0 and 2pi)""" x = r*np.sin(theta)*np.cos(phi) y = r*np.sin(theta)*np.sin(phi) z = r*np.cos(theta) return x,y,z def Lambert_azimuthal_equal_area_projection_conv_XY_plane_for_MTs(x,y,z): """Function to take 3D grid coords for a cartesian coord system and convert to 2D equal area projection.""" # if z.all()>-1.0: # X = x * np.sqrt(1/(1+z)) # Y = y * np.sqrt(1/(1+z)) # else: X = x * np.sqrt(np.absolute(1/(1+z))) Y = y * np.sqrt(np.absolute(1/(1+z))) return X,Y def stereographic_equal_angle_projection_conv_XY_plane_for_MTs(x,y,z): """Function to take 3D grid coords for a cartesian coord system and convert to 2D stereographic equal angle projection.""" X = x / (1-z) Y = y / (1-z) return X,Y def rotate_threeD_coords_about_spec_axis(x, y, z, rot_angle, axis_for_rotation="x"): """Function to rotate about x-axis (right-hand rule). Rotation angle must be in radians.""" if axis_for_rotation == "x": x_rot = x y_rot = (y*np.cos(rot_angle)) - (z*np.sin(rot_angle)) z_rot = (y*np.sin(rot_angle)) + (z*np.cos(rot_angle)) elif axis_for_rotation == "y": x_rot = (x*np.cos(rot_angle)) + (z*np.sin(rot_angle)) y_rot = y z_rot = (z*np.cos(rot_angle)) - (x*np.sin(rot_angle)) elif axis_for_rotation == "z": x_rot = (x*np.cos(rot_angle)) - (y*np.sin(rot_angle)) y_rot = (x*np.sin(rot_angle)) + (y*np.cos(rot_angle)) z_rot = z return x_rot, y_rot, z_rot # def strike_dip_rake_to_slip_vector(strike, dip, rake): # """Function to convert strike, dip, rake to slip vector. # Returns normalised slip vector, in NED format. # Input angles must be in radians.""" # # Define initial vector to rotate: # vec = np.array([0.,1.,0.]) # In ENU format # # Rotate by strike about z-axis: # vec[0],vec[1],vec[2] = rotate_threeD_coords_about_spec_axis(vec[0],vec[1],vec[2], -strike, axis_for_rotation="z") # # Rotate by dip about x-axis: # vec[0],vec[1],vec[2] = rotate_threeD_coords_about_spec_axis(vec[0],vec[1],vec[2], dip, axis_for_rotation="x") # # Rotate by rake anticlockwise about z-axis: # vec[0],vec[1],vec[2] = rotate_threeD_coords_about_spec_axis(vec[0],vec[1],vec[2], rake, axis_for_rotation="y") # # Convert vec to NED foramt: # vec_NED = np.array([vec[1],vec[0],-1.*vec[2]]) # return vec_NED def create_and_plot_bounding_circle_and_path(ax): """Function to create and plot bounding circle for plotting MT solution. Inputs are ax to plot on. Outputs are ax and bounding_circle_path (defining area contained by bounding circle).""" # Setup bounding circle: theta = np.ones(200)*np.pi/2 phi = np.linspace(0.,2*np.pi,len(theta)) r = np.ones(len(theta)) x,y,z = convert_spherical_coords_to_cartesian_coords(r,theta,phi) X_bounding_circle,Y_bounding_circle = Lambert_azimuthal_equal_area_projection_conv_XY_plane_for_MTs(x,y,z) ax.plot(Y_bounding_circle,X_bounding_circle, c="k") # And create bounding path from circle: path_coords = [] # list to store path coords for
some well-defined way of referencing a part of an object.' aliases: - storageos_secret_ref_field_path spec_storageos_secret_ref_kind: description: - Kind of the referent. aliases: - storageos_secret_ref_kind spec_storageos_secret_ref_name: description: - Name of the referent. aliases: - storageos_secret_ref_name spec_storageos_secret_ref_namespace: description: - Namespace of the referent. aliases: - storageos_secret_ref_namespace spec_storageos_secret_ref_resource_version: description: - Specific resourceVersion to which this reference is made, if any. aliases: - storageos_secret_ref_resource_version spec_storageos_secret_ref_uid: description: - UID of the referent. aliases: - storageos_secret_ref_uid spec_storageos_volume_name: description: - VolumeName is the human-readable name of the StorageOS volume. Volume names are only unique within a namespace. aliases: - storageos_volume_name spec_storageos_volume_namespace: description: - VolumeNamespace specifies the scope of the volume within StorageOS. If no namespace is specified then the Pod's namespace will be used. This allows the Kubernetes name scoping to be mirrored within StorageOS for tighter integration. Set VolumeName to any name to override the default behaviour. Set to "default" if you are not using namespaces within StorageOS. Namespaces that do not pre-exist within StorageOS will be created. aliases: - storageos_volume_namespace spec_vsphere_volume_fs_type: description: - Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. aliases: - vsphere_volume_fs_type spec_vsphere_volume_storage_policy_id: description: - Storage Policy Based Management (SPBM) profile ID associated with the StoragePolicyName. aliases: - vsphere_volume_storage_policy_id spec_vsphere_volume_storage_policy_name: description: - Storage Policy Based Management (SPBM) profile name. aliases: - vsphere_volume_storage_policy_name spec_vsphere_volume_volume_path: description: - Path that identifies vSphere volume vmdk aliases: - vsphere_volume_volume_path src: description: - Provide a path to a file containing the YAML definition of the object. Mutually exclusive with I(resource_definition). type: path ssl_ca_cert: description: - Path to a CA certificate used to authenticate with the API. type: path state: description: - Determines if an object should be created, patched, or deleted. When set to C(present), the object will be created, if it does not exist, or patched, if parameter values differ from the existing object's attributes, and deleted, if set to C(absent). A patch operation results in merging lists and updating dictionaries, with lists being merged into a unique set of values. If a list contains a dictionary with a I(name) or I(type) attribute, a strategic merge is performed, where individual elements with a matching I(name_) or I(type) are merged. To force the replacement of lists, set the I(force) option to C(True). default: present choices: - present - absent username: description: - Provide a username for connecting to the API. verify_ssl: description: - Whether or not to verify the API server's SSL certificates. type: bool requirements: - kubernetes == 3.0.0 ''' EXAMPLES = ''' - name: Create persitent volume k8s_v1_persistent_volume.yml: name: mypv state: present capacity: storage: 1Gi access_modes: - ReadWriteOnce persistent_volume_reclaim_policy: Recycle host_path_path: /tmp/test_volume ''' RETURN = ''' api_version: type: string description: Requested API version persistent_volume: type: complex returned: when I(state) = C(present) contains: api_version: description: - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. type: str kind: description: - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. type: str metadata: description: - Standard object's metadata. type: complex contains: annotations: description: - Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. type: complex contains: str, str cluster_name: description: - The name of the cluster which the object belongs to. This is used to distinguish resources with same name and namespace in different clusters. This field is not set anywhere right now and apiserver is going to ignore it if set in create or update request. type: str creation_timestamp: description: - CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC. Populated by the system. Read-only. Null for lists. type: complex contains: {} deletion_grace_period_seconds: description: - Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only. type: int deletion_timestamp: description: - DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field. Once set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested. Populated by the system when a graceful deletion is requested. Read-only. type: complex contains: {} finalizers: description: - Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. type: list contains: str generate_name: description: - GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server. If this field is specified and the generated name exists, the server will NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header). Applied only if Name is not specified. type: str generation: description: - A sequence number representing a specific generation of the desired state. Populated by the system. Read-only. type: int initializers: description: - An initializer is a controller which enforces some system invariant at object creation time. This field is a list of initializers that have not yet acted on this object. If nil or empty, this object has been completely initialized. Otherwise, the object is considered uninitialized and is hidden (in list/watch and get calls) from clients that haven't explicitly asked to observe uninitialized objects. When an object is created, the system will populate this list with the current set of initializers. Only privileged users may set or modify this list. Once it is empty, it may not be modified further by any user. type: complex contains: pending: description: - Pending is a list of initializers that must execute in order before this object is visible. When the last pending initializer is removed, and no failing result is set, the
"""Collection of classes for display styling.""" # pylint: disable=C0302 # pylint: disable=too-many-instance-attributes import numpy as np from magpylib._src.defaults.defaults_utility import color_validator from magpylib._src.defaults.defaults_utility import get_defaults_dict from magpylib._src.defaults.defaults_utility import LINESTYLES_MATPLOTLIB_TO_PLOTLY from magpylib._src.defaults.defaults_utility import MagicProperties from magpylib._src.defaults.defaults_utility import MAGPYLIB_FAMILIES from magpylib._src.defaults.defaults_utility import SUPPORTED_PLOTTING_BACKENDS from magpylib._src.defaults.defaults_utility import SYMBOLS_MATPLOTLIB_TO_PLOTLY from magpylib._src.defaults.defaults_utility import validate_property_class from magpylib._src.defaults.defaults_utility import validate_style_keys def get_style_class(obj): """Returns style instance based on object type. If object has no attribute `_object_type` or is not found in `MAGPYLIB_FAMILIES` returns `BaseStyle` instance. """ obj_type = getattr(obj, "_object_type", None) style_fam = MAGPYLIB_FAMILIES.get(obj_type, None) if isinstance(style_fam, (list, tuple)): style_fam = style_fam[0] return STYLE_CLASSES.get(style_fam, BaseStyle) def get_style(obj, default_settings, **kwargs): """Returns default style based on increasing priority: - style from defaults - style from object - style from kwargs arguments """ # parse kwargs into style an non-style arguments style_kwargs = kwargs.get("style", {}) style_kwargs.update( {k[6:]: v for k, v in kwargs.items() if k.startswith("style") and k != "style"} ) # retrieve default style dictionary, local import to avoid circular import # pylint: disable=import-outside-toplevel styles_by_family = default_settings.display.style.as_dict() # construct object specific dictionary base on style family and default style obj_type = getattr(obj, "_object_type", None) obj_families = MAGPYLIB_FAMILIES.get(obj_type, []) obj_style_default_dict = { **styles_by_family["base"], **{ k: v for fam in obj_families for k, v in styles_by_family.get(fam, {}).items() }, } style_kwargs = validate_style_keys(style_kwargs) # create style class instance and update based on precedence obj_style = getattr(obj, "style", None) style = obj_style.copy() if obj_style is not None else BaseStyle() style_kwargs_specific = { k: v for k, v in style_kwargs.items() if k.split("_")[0] in style.as_dict() } style.update(**style_kwargs_specific, _match_properties=True) style.update( **obj_style_default_dict, _match_properties=False, _replace_None_only=True ) return style class BaseStyle(MagicProperties): """Base class for display styling options of `BaseGeo` objects. Parameters ---------- label: str, default=None Label of the class instance, e.g. to be displayed in the legend. description: dict or `Description` object, default=None Object description properties. color: str, default=None A valid css color. Can also be one of `['r', 'g', 'b', 'y', 'm', 'c', 'k', 'w']`. opacity: float, default=None object opacity between 0 and 1, where 1 is fully opaque and 0 is fully transparent. path: dict or `Path` object, default=None An instance of `Path` or dictionary of equivalent key/value pairs, defining the object path marker and path line properties. model3d: list of `Trace3d` objects, default=None A list of traces where each is an instance of `Trace3d` or dictionary of equivalent key/value pairs. Defines properties for an additional user-defined model3d object which is positioned relatively to the main object to be displayed and moved automatically with it. This feature also allows the user to replace the original 3d representation of the object. """ def __init__( self, label=None, description=None, color=None, opacity=None, path=None, model3d=None, **kwargs, ): super().__init__( label=label, description=description, color=color, opacity=opacity, path=path, model3d=model3d, **kwargs, ) @property def label(self): """Label of the class instance, e.g. to be displayed in the legend.""" return self._label @label.setter def label(self, val): self._label = val if val is None else str(val) @property def description(self): """Description with 'text' and 'show' properties.""" return self._description @description.setter def description(self, val): self._description = validate_property_class( val, "description", Description, self ) @property def color(self): """A valid css color. Can also be one of `['r', 'g', 'b', 'y', 'm', 'c', 'k', 'w']`.""" return self._color @color.setter def color(self, val): self._color = color_validator(val, parent_name=f"{type(self).__name__}") @property def opacity(self): """Object opacity between 0 and 1, where 1 is fully opaque and 0 is fully transparent.""" return self._opacity @opacity.setter def opacity(self, val): assert val is None or (isinstance(val, (float, int)) and 0 <= val <= 1), ( "The `opacity` property must be a value betwen 0 and 1,\n" f"but received {repr(val)} instead." ) self._opacity = val @property def path(self): """An instance of `Path` or dictionary of equivalent key/value pairs, defining the object path marker and path line properties.""" return self._path @path.setter def path(self, val): self._path = validate_property_class(val, "path", Path, self) @property def model3d(self): """3d object representation properties.""" return self._model3d @model3d.setter def model3d(self, val): self._model3d = validate_property_class(val, "model3d", Model3d, self) class Description(MagicProperties): """Defines properties for a description object. Parameters ---------- text: str, default=None Object description text. show: bool, default=None If True, adds legend entry suffix based on value. """ def __init__(self, text=None, show=None, **kwargs): super().__init__(text=text, show=show, **kwargs) @property def text(self): """Description text.""" return self._text @text.setter def text(self, val): assert val is None or isinstance(val, str), ( f"The `show` property of {type(self).__name__} must be a string,\n" f"but received {repr(val)} instead." ) self._text = val @property def show(self): """If True, adds legend entry suffix based on value.""" return self._show @show.setter def show(self, val): assert val is None or isinstance(val, bool), ( f"The `show` property of {type(self).__name__} must be either True or False,\n" f"but received {repr(val)} instead." ) self._show = val class Model3d(MagicProperties): """Defines properties for the 3d model representation of magpylib objects. Parameters ---------- showdefault: bool, default=True Shows/hides default 3d-model. data: dict or list of dicts, default=None A trace or list of traces where each is an instance of `Trace3d` or dictionary of equivalent key/value pairs. Defines properties for an additional user-defined model3d object which is positioned relatively to the main object to be displayed and moved automatically with it. This feature also allows the user to replace the original 3d representation of the object. """ def __init__(self, showdefault=True, data=None, **kwargs): super().__init__(showdefault=showdefault, data=data, **kwargs) @property def showdefault(self): """If True, show default model3d object representation, else hide it.""" return self._showdefault @showdefault.setter def showdefault(self, val): assert isinstance(val, bool), ( f"The `showdefault` property of {type(self).__name__} must be " f"one of `[True, False]`,\n" f"but received {repr(val)} instead." ) self._showdefault = val @property def data(self): """Data of 3d object representation (trace or list of traces).""" return self._data @data.setter def data(self, val): self._data = self._validate_data(val) def _validate_data(self, traces, **kwargs): if traces is None: traces = [] elif not isinstance(traces, (list, tuple)): traces = [traces] new_traces = [] for trace in traces: updatefunc = None if not isinstance(trace, Trace3d) and callable(trace): updatefunc = trace trace = Trace3d() if not isinstance(trace, Trace3d): trace = validate_property_class(trace, "data", Trace3d, self) if updatefunc is not None: trace.updatefunc = updatefunc trace = trace.update(kwargs) new_traces.append(trace) return new_traces def add_trace(self, trace=None, **kwargs): """Adds user-defined 3d model object which is positioned relatively to the main object to be displayed and moved automatically with it. This feature also allows the user to replace the original 3d representation of the object. trace: Trace3d instance, dict or callable Trace object. Can be a `Trace3d` instance or an dictionary with equivalent key/values pairs, or a callable returning the equivalent dictionary. backend: str Plotting backend corresponding to the trace. Can be one of `['matplotlib', 'plotly']`. constructor: str Model constructor function or method to be called to build a 3D-model object (e.g. 'plot_trisurf', 'Mesh3d). Must be in accordance with the given plotting backend. args: tuple, default=None Tuple or callable returning a tuple containing positional arguments for building a 3D-model object. kwargs: dict or callable, default=None Dictionary or callable returning a dictionary containing the keys/values pairs for building a 3D-model object. coordsargs: dict, default=None Tells magpylib the name of the coordinate arrays to be moved or rotated, by default: `{"x": "x", "y": "y", "z": "z"}`, if False, object is not rotated. show: bool, default=None Shows/hides model3d object based on provided trace. scale: float, default=1 Scaling factor by which the trace vertices coordinates are multiplied. updatefunc: callable, default=None Callable object with no arguments. Should return a dictionary with keys from the trace parameters. If provided, the function is called at `show` time and updates the trace parameters with the output dictionary. This allows to update a trace dynamically depending on class attributes, and postpone the trace construction to when the object is displayed. """ self._data += self._validate_data([trace], **kwargs) return self class Trace3d(MagicProperties): """Defines properties for an additional user-defined 3d model object which is positioned relatively to the main object to be displayed and moved automatically with it. This feature also allows the user to replace the original 3d representation of the object. Parameters ---------- backend: str Plotting backend corresponding to the trace. Can be one of `['matplotlib',
tpimport_lines += f'{line}\n' if part == 'sender': import_lines += ('from efro.message import MessageSender,' ' BoundMessageSender') tpimport_typing_extras = '' else: if single_message_type: import_lines += ('from efro.message import (MessageReceiver,' ' BoundMessageReceiver, Message, Response)') else: import_lines += ('from efro.message import MessageReceiver,' ' BoundMessageReceiver') tpimport_typing_extras = ', Awaitable' ovld = ', overload' if not single_message_type else '' tpimport_lines = textwrap.indent(tpimport_lines, ' ') out = ('# Released under the MIT License. See LICENSE for details.\n' f'#\n' f'"""Auto-generated {part} module. Do not edit by hand."""\n' f'\n' f'from __future__ import annotations\n' f'\n' f'from typing import TYPE_CHECKING{ovld}\n' f'\n' f'{import_lines}\n' f'\n' f'if TYPE_CHECKING:\n' f' from typing import Union, Any, Optional, Callable' f'{tpimport_typing_extras}\n' f'{tpimport_lines}' f'\n' f'\n') return out def do_create_sender_module(self, basename: str, protocol_create_code: str, enable_sync_sends: bool, enable_async_sends: bool, private: bool = False) -> str: """Used by create_sender_module(); do not call directly.""" # pylint: disable=too-many-locals import textwrap msgtypes = list(self.message_ids_by_type.keys()) ppre = '_' if private else '' out = self._get_module_header('sender') ccind = textwrap.indent(protocol_create_code, ' ') out += (f'class {ppre}{basename}(MessageSender):\n' f' """Protocol-specific sender."""\n' f'\n' f' def __init__(self) -> None:\n' f'{ccind}\n' f' super().__init__(protocol)\n' f'\n' f' def __get__(self,\n' f' obj: Any,\n' f' type_in: Any = None)' f' -> {ppre}Bound{basename}:\n' f' return {ppre}Bound{basename}' f'(obj, self)\n' f'\n' f'\n' f'class {ppre}Bound{basename}(BoundMessageSender):\n' f' """Protocol-specific bound sender."""\n') def _filt_tp_name(rtype: type[Response]) -> str: # We accept None to equal EmptyResponse so reflect that # in the type annotation. return 'None' if rtype is EmptyResponse else rtype.__name__ # Define handler() overloads for all registered message types. if msgtypes: for async_pass in False, True: if async_pass and not enable_async_sends: continue if not async_pass and not enable_sync_sends: continue pfx = 'async ' if async_pass else '' sfx = '_async' if async_pass else '' awt = 'await ' if async_pass else '' how = 'asynchronously' if async_pass else 'synchronously' if len(msgtypes) == 1: # Special case: with a single message types we don't # use overloads. msgtype = msgtypes[0] msgtypevar = msgtype.__name__ rtypes = msgtype.get_response_types() if len(rtypes) > 1: tps = ', '.join(_filt_tp_name(t) for t in rtypes) rtypevar = f'Union[{tps}]' else: rtypevar = _filt_tp_name(rtypes[0]) out += (f'\n' f' {pfx}def send{sfx}(self,' f' message: {msgtypevar})' f' -> {rtypevar}:\n' f' """Send a message {how}."""\n' f' out = {awt}self._sender.' f'send{sfx}(self._obj, message)\n' f' assert isinstance(out, {rtypevar})\n' f' return out\n') else: for msgtype in msgtypes: msgtypevar = msgtype.__name__ rtypes = msgtype.get_response_types() if len(rtypes) > 1: tps = ', '.join(_filt_tp_name(t) for t in rtypes) rtypevar = f'Union[{tps}]' else: rtypevar = _filt_tp_name(rtypes[0]) out += (f'\n' f' @overload\n' f' {pfx}def send{sfx}(self,' f' message: {msgtypevar})' f' -> {rtypevar}:\n' f' ...\n') out += (f'\n' f' {pfx}def send{sfx}(self, message: Message)' f' -> Optional[Response]:\n' f' """Send a message {how}."""\n' f' return {awt}self._sender.' f'send{sfx}(self._obj, message)\n') return out def do_create_receiver_module(self, basename: str, protocol_create_code: str, is_async: bool, private: bool = False) -> str: """Used by create_receiver_module(); do not call directly.""" # pylint: disable=too-many-locals import textwrap desc = 'asynchronous' if is_async else 'synchronous' ppre = '_' if private else '' msgtypes = list(self.message_ids_by_type.keys()) out = self._get_module_header('receiver') ccind = textwrap.indent(protocol_create_code, ' ') out += (f'class {ppre}{basename}(MessageReceiver):\n' f' """Protocol-specific {desc} receiver."""\n' f'\n' f' is_async = {is_async}\n' f'\n' f' def __init__(self) -> None:\n' f'{ccind}\n' f' super().__init__(protocol)\n' f'\n' f' def __get__(\n' f' self,\n' f' obj: Any,\n' f' type_in: Any = None,\n' f' ) -> {ppre}Bound{basename}:\n' f' return {ppre}Bound{basename}(' f'obj, self)\n') # Define handler() overloads for all registered message types. def _filt_tp_name(rtype: type[Response]) -> str: # We accept None to equal EmptyResponse so reflect that # in the type annotation. return 'None' if rtype is EmptyResponse else rtype.__name__ if msgtypes: cbgn = 'Awaitable[' if is_async else '' cend = ']' if is_async else '' if len(msgtypes) == 1: # Special case: when we have a single message type we don't # use overloads. msgtype = msgtypes[0] msgtypevar = msgtype.__name__ rtypes = msgtype.get_response_types() if len(rtypes) > 1: tps = ', '.join(_filt_tp_name(t) for t in rtypes) rtypevar = f'Union[{tps}]' else: rtypevar = _filt_tp_name(rtypes[0]) rtypevar = f'{cbgn}{rtypevar}{cend}' out += ( f'\n' f' def handler(\n' f' self,\n' f' call: Callable[[Any, {msgtypevar}], ' f'{rtypevar}],\n' f' )' f' -> Callable[[Any, {msgtypevar}], {rtypevar}]:\n' f' """Decorator to register message handlers."""\n' f' from typing import cast, Callable, Any\n' f' self.register_handler(cast(Callable' f'[[Any, Message], Response], call))\n' f' return call\n') else: for msgtype in msgtypes: msgtypevar = msgtype.__name__ rtypes = msgtype.get_response_types() if len(rtypes) > 1: tps = ', '.join(_filt_tp_name(t) for t in rtypes) rtypevar = f'Union[{tps}]' else: rtypevar = _filt_tp_name(rtypes[0]) rtypevar = f'{cbgn}{rtypevar}{cend}' out += (f'\n' f' @overload\n' f' def handler(\n' f' self,\n' f' call: Callable[[Any, {msgtypevar}], ' f'{rtypevar}],\n' f' )' f' -> Callable[[Any, {msgtypevar}], {rtypevar}]:\n' f' ...\n') out += ( '\n' ' def handler(self, call: Callable) -> Callable:\n' ' """Decorator to register message handlers."""\n' ' self.register_handler(call)\n' ' return call\n') out += (f'\n' f'\n' f'class {ppre}Bound{basename}(BoundMessageReceiver):\n' f' """Protocol-specific bound receiver."""\n') if is_async: out += ( '\n' ' async def handle_raw_message(self, message: str)' ' -> str:\n' ' """Asynchronously handle a raw incoming message."""\n' ' return await' ' self._receiver.handle_raw_message_async(\n' ' self._obj, message)\n') else: out += ( '\n' ' def handle_raw_message(self, message: str) -> str:\n' ' """Synchronously handle a raw incoming message."""\n' ' return self._receiver.handle_raw_message' '(self._obj, message)\n') return out class MessageSender: """Facilitates sending messages to a target and receiving responses. This is instantiated at the class level and used to register unbound class methods to handle raw message sending. Example: class MyClass: msg = MyMessageSender(some_protocol) @msg.send_method def send_raw_message(self, message: str) -> str: # Actually send the message here. # MyMessageSender class should provide overloads for send(), send_bg(), # etc. to ensure all sending happens with valid types. obj = MyClass() obj.msg.send(SomeMessageType()) """ def __init__(self, protocol: MessageProtocol) -> None: self.protocol = protocol self._send_raw_message_call: Optional[Callable[[Any, str], str]] = None self._send_async_raw_message_call: Optional[Callable[ [Any, str], Awaitable[str]]] = None def send_method( self, call: Callable[[Any, str], str]) -> Callable[[Any, str], str]: """Function decorator for setting raw send method.""" assert self._send_raw_message_call is None self._send_raw_message_call = call return call def send_async_method( self, call: Callable[[Any, str], Awaitable[str]] ) -> Callable[[Any, str], Awaitable[str]]: """Function decorator for setting raw send-async method.""" assert self._send_async_raw_message_call is None self._send_async_raw_message_call = call return call def send(self, bound_obj: Any, message: Message) -> Optional[Response]: """Send a message and receive a response. Will encode the message for transport and call dispatch_raw_message() """ if self._send_raw_message_call is None: raise RuntimeError('send() is unimplemented for this type.') msg_encoded = self.protocol.encode_message(message) response_encoded = self._send_raw_message_call(bound_obj, msg_encoded) response = self.protocol.decode_response(response_encoded) assert isinstance(response, (Response, type(None))) assert (response is None or type(response) in type(message).get_response_types()) return response async def send_async(self, bound_obj: Any, message: Message) -> Optional[Response]: """Send a message asynchronously using asyncio. The message will be encoded for transport and passed to dispatch_raw_message_async. """ if self._send_async_raw_message_call is None: raise RuntimeError('send_async() is unimplemented for this type.') msg_encoded = self.protocol.encode_message(message) response_encoded = await self._send_async_raw_message_call( bound_obj, msg_encoded) response = self.protocol.decode_response(response_encoded) assert isinstance(response, (Response, type(None))) assert (response is None or type(response) in type(message).get_response_types()) return response class BoundMessageSender: """Base class for bound senders.""" def __init__(self, obj: Any, sender: MessageSender) -> None: assert obj is not None self._obj = obj self._sender = sender @property def protocol(self) -> MessageProtocol: """Protocol associated with this sender.""" return self._sender.protocol def send_untyped(self, message: Message) -> Optional[Response]: """Send a message synchronously. Whenever possible, use the send() call provided by generated subclasses instead of this; it will provide better type safety. """ return self._sender.send(self._obj, message) async def send_async_untyped(self, message: Message) -> Optional[Response]: """Send a message asynchronously. Whenever possible, use the send_async() call provided by generated subclasses instead of this; it will provide better type safety. """ return await self._sender.send_async(self._obj, message) class MessageReceiver: """Facilitates receiving & responding to messages from a remote source. This is instantiated at the class level with unbound methods registered as handlers for different message types in the protocol. Example: class MyClass: receiver = MyMessageReceiver() # MyMessageReceiver fills out handler() overloads to ensure all # registered handlers have valid types/return-types. @receiver.handler def handle_some_message_type(self, message: SomeMsg) -> SomeResponse: # Deal with this message type here. # This will trigger the registered handler being called. obj = MyClass() obj.receiver.handle_raw_message(some_raw_data) Any unhandled Exception occurring during
* uk_33 + 25 * uk_34 + 2304 * uk_35 + 4368 * uk_36 + 10416 * uk_37 + 240 * uk_38 + 8281 * uk_39 + 5 * uk_4 + 19747 * uk_40 + 455 * uk_41 + 47089 * uk_42 + 1085 * uk_43 + 25 * uk_44 + 106179944855977 * uk_45 + 141265316367 * uk_46 + 73996118097 * uk_47 + 11211533045 * uk_48 + 107630717232 * uk_49 + 48 * uk_5 + 204049901419 * uk_50 + 486580534153 * uk_51 + 11211533045 * uk_52 + 187944057 * uk_53 + 98446887 * uk_54 + 14916195 * uk_55 + 143195472 * uk_56 + 271474749 * uk_57 + 647362863 * uk_58 + 14916195 * uk_59 + 91 * uk_6 + 51567417 * uk_60 + 7813245 * uk_61 + 75007152 * uk_62 + 142201059 * uk_63 + 339094833 * uk_64 + 7813245 * uk_65 + 1183825 * uk_66 + 11364720 * uk_67 + 21545615 * uk_68 + 51378005 * uk_69 + 217 * uk_7 + 1183825 * uk_70 + 109101312 * uk_71 + 206837904 * uk_72 + 493228848 * uk_73 + 11364720 * uk_74 + 392130193 * uk_75 + 935079691 * uk_76 + 21545615 * uk_77 + 2229805417 * uk_78 + 51378005 * uk_79 + 5 * uk_8 + 1183825 * uk_80 + 250047 * uk_81 + 130977 * uk_82 + 19845 * uk_83 + 190512 * uk_84 + 361179 * uk_85 + 861273 * uk_86 + 19845 * uk_87 + 68607 * uk_88 + 10395 * uk_89 + 2242306609 * uk_9 + 99792 * uk_90 + 189189 * uk_91 + 451143 * uk_92 + 10395 * uk_93 + 1575 * uk_94 + 15120 * uk_95 + 28665 * uk_96 + 68355 * uk_97 + 1575 * uk_98 + 145152 * uk_99, uk_0 + 47353 * uk_1 + 2983239 * uk_10 + 257796 * uk_100 + 601524 * uk_101 + 91476 * uk_102 + 544887 * uk_103 + 1271403 * uk_104 + 193347 * uk_105 + 2966607 * uk_106 + 451143 * uk_107 + 68607 * uk_108 + 4096 * uk_109 + 757648 * uk_11 + 8448 * uk_110 + 11264 * uk_111 + 23808 * uk_112 + 55552 * uk_113 + 8448 * uk_114 + 17424 * uk_115 + 23232 * uk_116 + 49104 * uk_117 + 114576 * uk_118 + 17424 * uk_119 + 1562649 * uk_12 + 30976 * uk_120 + 65472 * uk_121 + 152768 * uk_122 + 23232 * uk_123 + 138384 * uk_124 + 322896 * uk_125 + 49104 * uk_126 + 753424 * uk_127 + 114576 * uk_128 + 17424 * uk_129 + 2083532 * uk_13 + 35937 * uk_130 + 47916 * uk_131 + 101277 * uk_132 + 236313 * uk_133 + 35937 * uk_134 + 63888 * uk_135 + 135036 * uk_136 + 315084 * uk_137 + 47916 * uk_138 + 285417 * uk_139 + 4403829 * uk_14 + 665973 * uk_140 + 101277 * uk_141 + 1553937 * uk_142 + 236313 * uk_143 + 35937 * uk_144 + 85184 * uk_145 + 180048 * uk_146 + 420112 * uk_147 + 63888 * uk_148 + 380556 * uk_149 + 10275601 * uk_15 + 887964 * uk_150 + 135036 * uk_151 + 2071916 * uk_152 + 315084 * uk_153 + 47916 * uk_154 + 804357 * uk_155 + 1876833 * uk_156 + 285417 * uk_157 + 4379277 * uk_158 + 665973 * uk_159 + 1562649 * uk_16 + 101277 * uk_160 + 10218313 * uk_161 + 1553937 * uk_162 + 236313 * uk_163 + 35937 * uk_164 + 3969 * uk_17 + 1008 * uk_18 + 2079 * uk_19 + 63 * uk_2 + 2772 * uk_20 + 5859 * uk_21 + 13671 * uk_22 + 2079 * uk_23 + 256 * uk_24 + 528 * uk_25 + 704 * uk_26 + 1488 * uk_27 + 3472 * uk_28 + 528 * uk_29 + 16 * uk_3 + 1089 * uk_30 + 1452 * uk_31 + 3069 * uk_32 + 7161 * uk_33 + 1089 * uk_34 + 1936 * uk_35 + 4092 * uk_36 + 9548 * uk_37 + 1452 * uk_38 + 8649 * uk_39 + 33 * uk_4 + 20181 * uk_40 + 3069 * uk_41 + 47089 * uk_42 + 7161 * uk_43 + 1089 * uk_44 + 106179944855977 * uk_45 + 141265316367 * uk_46 + 35876905744 * uk_47 + 73996118097 * uk_48 + 98661490796 * uk_49 + 44 * uk_5 + 208534514637 * uk_50 + 486580534153 * uk_51 + 73996118097 * uk_52 + 187944057 * uk_53 + 47731824 * uk_54 + 98446887 * uk_55 + 131262516 * uk_56 + 277441227 * uk_57 + 647362863 * uk_58 + 98446887 * uk_59 + 93 * uk_6 + 12122368 * uk_60 + 25002384 * uk_61 + 33336512 * uk_62 + 70461264 * uk_63 + 164409616 * uk_64 + 25002384 * uk_65 + 51567417 * uk_66 + 68756556 * uk_67 + 145326357 * uk_68 + 339094833 * uk_69 + 217 * uk_7 + 51567417 * uk_70 + 91675408 * uk_71 + 193768476 * uk_72 + 452126444 * uk_73 + 68756556 * uk_74 + 409556097 * uk_75 + 955630893 * uk_76 + 145326357 * uk_77 + 2229805417 * uk_78 + 339094833 * uk_79 + 33 * uk_8 + 51567417 * uk_80 + 250047 * uk_81 + 63504 * uk_82 + 130977 * uk_83 + 174636 * uk_84 + 369117 * uk_85 + 861273 * uk_86 + 130977 * uk_87 + 16128 * uk_88 + 33264 * uk_89 + 2242306609 * uk_9 + 44352 * uk_90 + 93744 * uk_91 + 218736 * uk_92 + 33264 * uk_93 + 68607 * uk_94 + 91476 * uk_95 + 193347 * uk_96 + 451143 * uk_97 + 68607 * uk_98 + 121968 * uk_99, uk_0 + 47353 * uk_1 + 2983239 * uk_10 + 263340 * uk_100 + 601524 * uk_101 + 44352 * uk_102 + 568575 * uk_103 + 1298745 * uk_104 + 95760 * uk_105 + 2966607 * uk_106 + 218736 * uk_107 + 16128 * uk_108 + 79507 * uk_109 + 2036179 * uk_11 + 29584 * uk_110 + 81356 * uk_111 + 175655 * uk_112 + 401233 * uk_113 + 29584 * uk_114 + 11008 * uk_115 + 30272 * uk_116 + 65360 * uk_117 + 149296 * uk_118 + 11008 * uk_119 + 757648 * uk_12 + 83248 * uk_120 + 179740 * uk_121 + 410564 * uk_122 + 30272 * uk_123 + 388075 * uk_124 + 886445 * uk_125 + 65360 * uk_126 + 2024827 * uk_127 + 149296 * uk_128 + 11008 * uk_129 + 2083532 * uk_13 + 4096 * uk_130 + 11264 * uk_131 + 24320 * uk_132 + 55552 * uk_133 + 4096 * uk_134 + 30976 * uk_135 + 66880 * uk_136 + 152768 * uk_137 + 11264 * uk_138 + 144400 * uk_139 + 4498535 * uk_14 + 329840 * uk_140 + 24320 * uk_141 + 753424 * uk_142 + 55552 * uk_143 + 4096 * uk_144 + 85184 * uk_145 + 183920 * uk_146 + 420112 * uk_147 + 30976 * uk_148 + 397100 * uk_149 + 10275601 * uk_15 + 907060 * uk_150 + 66880 * uk_151 + 2071916 * uk_152 + 152768 * uk_153 + 11264 * uk_154 + 857375 * uk_155 + 1958425 * uk_156 + 144400 * uk_157 + 4473455 * uk_158 + 329840 * uk_159 + 757648 * uk_16 + 24320 * uk_160 + 10218313 * uk_161 + 753424 * uk_162 + 55552 * uk_163 + 4096 * uk_164 + 3969 * uk_17 + 2709 * uk_18 + 1008 * uk_19 + 63 * uk_2 + 2772 * uk_20 + 5985 * uk_21 + 13671 * uk_22 + 1008 * uk_23 + 1849 * uk_24 + 688 * uk_25
%(DFMapping__columns)s :param kwargs: passed to transform :param kwargs_fit: passed to fit :return: see transform """ if kwargs_fit is None: kwargs_fit = {} self.fit(df=df, col_names=col_names, values=values, columns=columns, **kwargs_fit) return self.transform(df=df, col_names=col_names, values=values, columns=columns, **kwargs) def to_excel(self, path: str, if_exists: str = 'error') -> None: """ Save the DFMapping object as an excel file. Useful if you want to edit the results of the automatically generated object to fit your specific needs. :param path: Path to save the excel file to :param if_exists: One of %(DFMapping__to_excel__if_exists)s, if 'error' raises exception, if 'replace' replaces existing files and if 'append' appends to file (while checking for duplicates) :return: None """ # -- functions def _write_excel_sheet(writer, mapping, sheet_name): # create DataFrame and transpose _df_mapping = pd.DataFrame(mapping, index=[0]).T # handle append if (if_exists == 'append') and (sheet_name in _sheet_names): # new mapping data comes below existing ones, duplicates are dropped (keep old) _df_mapping = pd.read_excel(path, sheet_name, index_col=0).append(_df_mapping)\ .pipe(drop_duplicate_indices) # write excel _df_mapping.to_excel(writer, sheet_name=sheet_name) # -- init # - assert if if_exists not in validations['DFMapping__to_excel__if_exists']: raise ValueError(f"if_exists must be one of {validations['DFMapping__to_excel__if_exists']}") # - handle if_exists _sheet_names = [] if os.path.exists(path): if if_exists == 'error': raise FileExistsError(f"file already exists, please specify if_exists as one of ") elif if_exists == 'append': _sheet_names = pd.ExcelFile(path).sheet_names # -- main # pandas ExcelWriter object (saves on close) with pd.ExcelWriter(path) as _writer: # col mapping _write_excel_sheet(writer=_writer, mapping=self.col_mapping, sheet_name='__columns__') # value mappings for _key, _mapping in self.value_mapping.items(): _write_excel_sheet(writer=_writer, mapping=_mapping, sheet_name=_key) def from_excel(self, path: str) -> None: """ Init the DFMapping object from an excel file. For example you could auto generate a DFMapping using googletrans and then adjust the translations you feel are inappropriate in the excel file. Then regenerate the object from the edited excel file. :param path: Path to the excel file :return: None """ def _read_excel(xls, sheet_name): return pd.read_excel(xls, sheet_name, index_col=0).T.to_dict(orient='records')[0] # open ExcelFile with pd.ExcelFile(path) as _xls: self.col_mapping = _read_excel(xls=_xls, sheet_name='__columns__') self.value_mapping = {} for _sheet_name in list_exclude(_xls.sheet_names, '__columns__'): self.value_mapping[_sheet_name] = _read_excel(xls=_xls, sheet_name=_sheet_name) # ---- functions # --- export @export def assert_df(df: Any, groupby: Union[SequenceOrScalar, bool] = False, name: str = 'df', ) -> Union[pd.DataFrame, Tuple[pd.DataFrame, List]]: """ assert that input is a pandas DataFrame, raise ValueError if it cannot be cast to DataFrame :param df: Object to be cast to DataFrame :param groupby: column to use as groupby :param name: name to use in the ValueError message, useful when calling from another function :return: pandas DataFrame """ try: df = pd.DataFrame(df).copy() except Exception as _e: print(f"{_e.__class__.__name__}: {_e}") raise ValueError(f"{name} must be a DataFrame or castable to DataFrame") if isinstance(groupby, bool) and not groupby: return df elif groupby is None or groupby in [[], GROUPBY_DUMMY, [GROUPBY_DUMMY]]: groupby = [GROUPBY_DUMMY] df[GROUPBY_DUMMY] = 1 else: groupby = assert_list(groupby) # drop duplicate columns df = drop_duplicate_cols(df) return df, groupby @export def optimize_pd(df: pd.DataFrame, c_int: bool = True, c_float: bool = True, c_cat: bool = True, cat_frac: float = .5, convert_dtypes: bool = True, drop_all_na_cols: bool = False) -> pd.DataFrame: """ optimize memory usage of a pandas df, automatically downcast all var types and converts objects to categories :param df: pandas DataFrame to be optimized. Other objects are implicitly cast to DataFrame :param c_int: Whether to downcast integers [optional] :param c_float: Whether to downcast floats [optional] :param c_cat: Whether to cast objects to categories. Uses cat_frac as condition [optional] :param cat_frac: If c_cat: If the column has less than cat_frac percent unique values it will be cast to category [optional] :param convert_dtypes: Whether to call convert dtypes (pandas 1.0.0+) [optional] :param drop_all_na_cols: Whether to drop columns that contain only missing values [optional] :return: the optimized pandas DataFrame """ # -- func # noinspection PyShadowingNames def _do_downcast(df, cols, downcast): if downcast is None: return df for _col in assert_list(cols): # downcast try: df[_col] = pd.to_numeric(df[_col], downcast=downcast) except Exception as _e: print(f"Downcast Error in {_col} - {_e.__class__}: {_e}") return df # -- init # avoid inplace operations df = assert_df(df) # pandas version flag _pandas_version_1_plus = int(pd.__version__.split('.')[0]) > 0 # not convert_dtypes not support before pandas 1.0.0 if not _pandas_version_1_plus: convert_dtypes = False # check for duplicate columns _duplicate_columns = get_duplicate_cols(df) if len(_duplicate_columns) > 0: warnings.warn('duplicate columns found: {}'.format(_duplicate_columns)) df = drop_duplicate_cols(df) # if applicable: drop columns containing only na if drop_all_na_cols: df = df.drop(df.columns[df.isnull().all()], axis=1) # -- main # if applicable: convert float columns containing integer values to dtype int if convert_dtypes: # scalar object to str (doesn't seem to work automatically as of 1.0.0) for _col in df.select_dtypes('object').columns: # noinspection PyTypeChecker df[_col] = df[_col].apply(lambda _: str(_) if is_scalar(_) else _) # df.convert_dtypes will be called after downcasting since it is not supported for some dtypes # casting if c_int: _include = dtypes['int'] # Int does not support downcasting as of pandas 1.0.0 -> check again later # if _pandas_version_1_plus: # _include += dtypes_Int _cols_int = df.select_dtypes(include=_include) # loop int columns for _col in _cols_int: # split integer columns in unsigned (all positive) and (unsigned) if df[_col].isna().sum() > 0: _downcast = None elif (df[_col] > 0).all(): _downcast = 'unsigned' else: _downcast = 'signed' df = _do_downcast(df=df, cols=_col, downcast=_downcast) if c_float: df = _do_downcast(df=df, cols=df.select_dtypes(include=['float']).columns, downcast='float') if c_cat: _include = ['object'] if _pandas_version_1_plus: _include += ['string'] for _col in df.select_dtypes(include=_include).columns: # if there are less than 1 - cat_frac unique elements: cast to category _count_unique = df[_col].dropna().drop_duplicates().shape[0] _count_no_na = df[_col].dropna().shape[0] if _count_no_na > 0 and (_count_unique / _count_no_na < (1 - cat_frac)): df[_col] = df[_col].astype('category') # call convert dtypes to handle downcasted dtypes if convert_dtypes: # try except is needed due to some compatibility issues try: df = df.convert_dtypes() except Exception as _e: print(f"skipped convert_dtypes due to: f{_e.__class__}: {_e}") return df @export def get_df_corr(df: pd.DataFrame, columns: List[str] = None, target: str = None, groupby: Union[str, list] = None) -> pd.DataFrame: """ Calculate Pearson Correlations for numeric columns, extends on pandas.DataFrame.corr but automatically melts the output. Used by :func:`~hhpy.plotting.corrplot_bar` :param df: input pandas DataFrame. Other objects are implicitly cast to DataFrame :param columns: Column to calculate the correlation for, defaults to all numeric columns [optional] :param target: Returns only correlations that involve the target column [optional] :param groupby: Returns correlations for each level of the group [optional] :return: pandas DataFrame containing all pearson correlations in a melted format """ # -- assert # df / groupby df, groupby = assert_df(df=df, groupby=groupby) # -- init # if there is a column called index it will create problems so rename it to '__index__' df = df.rename({'index': '__index__'}, axis=1) # columns defaults to numeric columns if columns is None: columns = df.select_dtypes(include=np.number).columns # -- main # init df as list of dfs _df_corr = [] # loop groups for _index, _df_i in df.groupby(groupby): # get corr _df_corr_i = _df_i.corr().reset_index().rename({'index': 'col_0'}, axis=1) # set upper right half to nan for _i, _col in enumerate(columns): _df_corr_i[_col] = np.where(_df_corr_i[_col].index <= _i, np.nan, _df_corr_i[_col]) # gather / melt _df_corr_i = pd.melt(_df_corr_i, id_vars=['col_0'], var_name='col_1', value_name='corr').dropna() # drop self correlation _df_corr_i = _df_corr_i[_df_corr_i['col_0'] != _df_corr_i['col_1']] # get identifier for _groupby in groupby: _df_corr_i[_groupby] = _df_i[_groupby].iloc[0] # append to list of dfs _df_corr.append(_df_corr_i) # merge _df_corr = concat(_df_corr) # clean dummy groupby if GROUPBY_DUMMY in _df_corr.columns: _df_corr.drop(GROUPBY_DUMMY, axis=1, inplace=True) else: # move groupby columns to front _df_corr = col_to_front(_df_corr, groupby) # reorder and keep only columns involving the target (if applicable) if target is not None: # if the target is col_1: switch it to col_0 _target_is_col_1 = (_df_corr['col_1'] == target) _df_corr['col_1'] = np.where(_target_is_col_1, _df_corr['col_0'], _df_corr['col_1']) _df_corr['col_0'] = np.where(_target_is_col_1, target, _df_corr['col_0']) # keep only target in col_0 _df_corr = _df_corr[_df_corr['col_0'] == target] # get absolute correlation _df_corr['corr_abs'] = np.abs(_df_corr['corr']) # sort descending _df_corr = _df_corr.sort_values(['corr_abs'], ascending=False).reset_index(drop=True) return _df_corr @export def drop_zero_cols(df: pd.DataFrame) -> pd.DataFrame: """ Drop columns with all 0 or None Values from DataFrame. Useful after applying one hot encoding. :param df: pandas DataFrame :return: pandas DataFrame without 0 columns. """ # noinspection PyUnresolvedReferences return
using :func:`torch.linalg.norm`. For example, `torch.linalg.norm(A, ord=1, dim=(0, 1))` always computes a matrix norm, but with `torch.linalg.vector_norm(A, ord=1, dim=(0, 1))` it is possible to compute a vector norm over the two dimensions. Args: A (Tensor): tensor of shape `(*, n)` or `(*, m, n)` where `*` is zero or more batch dimensions ord (int, float, inf, -inf, 'fro', 'nuc', optional): order of norm. Default: `None` dim (int, Tuple[int], optional): dimensions over which to compute the vector or matrix norm. See above for the behavior when :attr:`dim`\ `= None`. Default: `None` keepdim (bool, optional): If set to `True`, the reduced dimensions are retained in the result as dimensions with size one. Default: `False` Keyword args: out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. dtype (:class:`torch.dtype`, optional): If specified, the input tensor is cast to :attr:`dtype` before performing the operation, and the returned tensor's type will be :attr:`dtype`. Default: `None` Returns: A real-valued tensor, even when :attr:`A` is complex. Examples:: >>> from torch import linalg as LA >>> a = torch.arange(9, dtype=torch.float) - 4 >>> a tensor([-4., -3., -2., -1., 0., 1., 2., 3., 4.]) >>> b = a.reshape((3, 3)) >>> b tensor([[-4., -3., -2.], [-1., 0., 1.], [ 2., 3., 4.]]) >>> LA.norm(a) tensor(7.7460) >>> LA.norm(b) tensor(7.7460) >>> LA.norm(b, 'fro') tensor(7.7460) >>> LA.norm(a, float('inf')) tensor(4.) >>> LA.norm(b, float('inf')) tensor(9.) >>> LA.norm(a, -float('inf')) tensor(0.) >>> LA.norm(b, -float('inf')) tensor(2.) >>> LA.norm(a, 1) tensor(20.) >>> LA.norm(b, 1) tensor(7.) >>> LA.norm(a, -1) tensor(0.) >>> LA.norm(b, -1) tensor(6.) >>> LA.norm(a, 2) tensor(7.7460) >>> LA.norm(b, 2) tensor(7.3485) >>> LA.norm(a, -2) tensor(0.) >>> LA.norm(b.double(), -2) tensor(1.8570e-16, dtype=torch.float64) >>> LA.norm(a, 3) tensor(5.8480) >>> LA.norm(a, -3) tensor(0.) Using the :attr:`dim` argument to compute vector norms:: >>> c = torch.tensor([[1., 2., 3.], ... [-1, 1, 4]]) >>> LA.norm(c, dim=0) tensor([1.4142, 2.2361, 5.0000]) >>> LA.norm(c, dim=1) tensor([3.7417, 4.2426]) >>> LA.norm(c, ord=1, dim=1) tensor([6., 6.]) Using the :attr:`dim` argument to compute matrix norms:: >>> m = torch.arange(8, dtype=torch.float).reshape(2, 2, 2) >>> LA.norm(m, dim=(1,2)) tensor([ 3.7417, 11.2250]) >>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :]) (tensor(3.7417), tensor(11.2250)) """) vector_norm = _add_docstr(_linalg.linalg_vector_norm, r""" linalg.vector_norm(A, ord=2, dim=None, keepdim=False, *, dtype=None, out=None) -> Tensor Computes a vector norm. If :attr:`A` is complex valued, it computes the norm of :attr:`A`\ `.abs()` Supports input of float, double, cfloat and cdouble dtypes. This function does not necessarily treat multidimensonal attr:`A` as a batch of vectors, instead: - If :attr:`dim`\ `= None`, :attr:`A` will be flattened before the norm is computed. - If :attr:`dim` is an `int` or a `tuple`, the norm will be computed over these dimensions and the other dimensions will be treated as batch dimensions. This behavior is for consistency with :func:`torch.linalg.norm`. :attr:`ord` defines the vector norm that is computed. The following norms are supported: ====================== ======================================================== :attr:`ord` vector norm ====================== ======================================================== `2` (default) `2`-norm (see below) `inf` `max(abs(x))` `-inf` `min(abs(x))` `0` `sum(x != 0)` other `int` or `float` `sum(abs(x)^{ord})^{(1 / ord)}` ====================== ======================================================== where `inf` refers to `float('inf')`, NumPy's `inf` object, or any equivalent object. .. seealso:: :func:`torch.linalg.matrix_norm` computes a matrix norm. Args: A (Tensor): tensor, flattened by default, but this behavior can be controlled using :attr:`dim`. ord (int, float, inf, -inf, 'fro', 'nuc', optional): order of norm. Default: `2` dim (int, Tuple[int], optional): dimensions over which to compute the norm. See above for the behavior when :attr:`dim`\ `= None`. Default: `None` keepdim (bool, optional): If set to `True`, the reduced dimensions are retained in the result as dimensions with size one. Default: `False` Keyword args: out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. dtype (:class:`torch.dtype`, optional): If specified, the input tensor is cast to :attr:`dtype` before performing the operation, and the returned tensor's type will be :attr:`dtype`. Default: `None` Returns: A real-valued tensor, even when :attr:`A` is complex. Examples:: >>> from torch import linalg as LA >>> a = torch.arange(9, dtype=torch.float) - 4 >>> a tensor([-4., -3., -2., -1., 0., 1., 2., 3., 4.]) >>> b = a.reshape((3, 3)) >>> b tensor([[-4., -3., -2.], [-1., 0., 1.], [ 2., 3., 4.]]) >>> LA.vector_norm(a, ord=3.5) tensor(5.4345) >>> LA.vector_norm(b, ord=3.5) tensor(5.4345) """) matrix_norm = _add_docstr(_linalg.linalg_matrix_norm, r""" linalg.matrix_norm(A, ord='fro', dim=(-2, -1), keepdim=False, *, dtype=None, out=None) -> Tensor Computes a matrix norm. If :attr:`A` is complex valued, it computes the norm of :attr:`A`\ `.abs()` Support input of float, double, cfloat and cdouble dtypes. Also supports batches of matrices: the norm will be computed over the dimensions specified by the 2-tuple :attr:`dim` and the other dimensions will be treated as batch dimensions. The output will have the same batch dimensions. :attr:`ord` defines the matrix norm that is computed. The following norms are supported: ====================== ======================================================== :attr:`ord` matrix norm ====================== ======================================================== `'fro'` (default) Frobenius norm `'nuc'` nuclear norm `inf` `max(sum(abs(x), dim=1))` `-inf` `min(sum(abs(x), dim=1))` `1` `max(sum(abs(x), dim=0))` `-1` `min(sum(abs(x), dim=0))` `2` largest singular value `-2` smallest singular value ====================== ======================================================== where `inf` refers to `float('inf')`, NumPy's `inf` object, or any equivalent object. Args: A (Tensor): tensor with two or more dimensions. By default its shape is interpreted as `(*, m, n)` where `*` is zero or more batch dimensions, but this behavior can be controlled using :attr:`dim`. ord (int, inf, -inf, 'fro', 'nuc', optional): order of norm. Default: `'fro'` dim (Tuple[int, int], optional): dimensions over which to compute the norm. Default: `(-2, -1)` keepdim (bool, optional): If set to `True`, the reduced dimensions are retained in the result as dimensions with size one. Default: `False` Keyword args: out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. dtype (:class:`torch.dtype`, optional): If specified, the input tensor is cast to :attr:`dtype` before performing the operation, and the returned tensor's type will be :attr:`dtype`. Default: `None` Returns: A real-valued tensor, even when :attr:`A` is complex. Examples:: >>> from torch import linalg as LA >>> A = torch.arange(9, dtype=torch.float).reshape(3, 3) >>> A tensor([[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]) >>> LA.matrix_norm(A) tensor(14.2829) >>> LA.matrix_norm(A, ord=-1) tensor(9.) >>> B = A.expand(2, -1, -1) >>> B tensor([[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]], [[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]]) >>> LA.matrix_norm(B) tensor([14.2829, 14.2829]) >>> LA.matrix_norm(B, dim=(0, 2)) tensor([ 3.1623, 10.0000, 17.2627]) """) multi_dot = _add_docstr(_linalg.linalg_multi_dot, r""" linalg.multi_dot(tensors, *, out=None) Efficiently multiplies two or more matrices by reordering the multiplications so that the fewest arithmetic operations are performed. Supports inputs of float, double, cfloat and cdouble dtypes. This function does not support batched inputs. Every tensor in :attr:`tensors` must be 2D, except for the first and last which may be 1D. If the first tensor is a 1D vector of shape `(n,)` it is treated as a row vector of shape `(1, n)`, similarly if the last tensor is a 1D vector of shape `(n,)` it is treated as a column vector of shape `(n, 1)`. If the first and last tensors are matrices, the output will be a matrix. However, if either is a 1D vector, then the output will be a 1D vector. Differences with `numpy.linalg.multi_dot`: - Unlike `numpy.linalg.multi_dot`, the first and last tensors must either be 1D or 2D whereas NumPy allows them to be nD .. warning:: This function does not broadcast. .. note:: This function is implemented by chaining :func:`torch.mm` calls after computing the optimal matrix multiplication order. .. note:: The cost of multiplying two matrices with shapes `(a, b)` and `(b, c)` is `a * b * c`. Given matrices `A`, `B`, `C` with shapes `(10, 100)`, `(100, 5)`, `(5, 50)` respectively, we can calculate the cost of different multiplication orders as follows: .. math:: \begin{align*} \operatorname{cost}((AB)C) &= 10 \times 100 \times 5 + 10 \times 5 \times 50 = 7500 \\ \operatorname{cost}(A(BC)) &= 10 \times 100 \times 50 + 100 \times 5 \times 50 = 75000 \end{align*} In this case, multiplying `A` and `B` first followed by `C` is 10 times faster. Args: tensors (Sequence[Tensor]): two or more tensors to multiply. The first and last tensors may be 1D or 2D. Every other tensor must be 2D. Keyword args: out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. Examples:: >>> from torch.linalg import multi_dot >>> multi_dot([torch.tensor([1, 2]), torch.tensor([2, 3])]) tensor(8) >>> multi_dot([torch.tensor([[1, 2]]), torch.tensor([2, 3])]) tensor([8]) >>> multi_dot([torch.tensor([[1, 2]]), torch.tensor([[2], [3]])]) tensor([[8]]) >>> a = torch.arange(2 * 3).view(2, 3) >>> b = torch.arange(3 * 2).view(3, 2) >>> c = torch.arange(2 * 2).view(2, 2)
") return(4,None,False,None) rft.sessionLink=r.headers["Location"] rft.cleanupOnExit=cleanupOnExit rft.printStatus(3,r=r,addSessionLoginInfo=True) return(rc,r,j,d) def rfSessionDelete(self,rft,cmdTop=False,sessionLink=None): rft.printVerbose(4,"Transport: in Session Delete (Logout)") #if session link was passed-in (logout cmd) use that, otherwise, use the saved value in the transport if(sessionLink is None): # delete this session saved in rft.sessionId, rft.sessionLink # delete in rft self.printVerbose(5,"rfSessionDelete: deleting session:{}".format(rft.sessionId)) rft.printVerbose(4,"Transport: delete session: id:{}, link:{}".format(rft.sessionId, rft.sessionLink)) sessionLink=rft.sessionLink # now we have a login uri, login # POST the user credentials to the login URI, and read the SessionLink and SessionAuthToken from header rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'DELETE', rft.rootUri, relPath=sessionLink) if(rc!=0): rft.printErr("Error: Logout: Session Delete Failed: Delete to Sessions collection failed") rft.printErr(" sessionId:{}".format(sessionLink)) return(rc,None,False,None) # save the sessionId and SessionAuthToken to None self.sessionId=None self.sessionLink=None rc=0 return(rc,r,False,None) def rfCleanup(self,rft): #if we created a temp session in this cmd, logout self.printVerbose(5,"rfCleanup:Cleaningup session: {}".format(self.sessionId)) if((rft.cleanupOnExit is True ) and (rft.sessionId is not None) ): #delete the session rc,r,j,d=rft.rfSessionDelete(rft) #nothing else to do for now return(rc) else: return(0) def printVerbose(self,v,*argv, skip1=False, printV12=True,**kwargs): if(self.quiet): return(0) if( (v==1 or v==2) and (printV12 is True) and (self.verbose >= v )): if(skip1 is True): print("#") print("#",*argv, **kwargs) elif( (v==1 or v==2) and (self.verbose >4 )): if(skip1 is True): print("#") print("#",*argv, **kwargs) elif((v==3 ) and (printV12 is True) and (self.verbose >=v)): if(skip1 is True): print("#") print("#REQUEST:",*argv,file=sys.stdout,**kwargs) elif((v==4 or v==5) and (self.verbose >=v)): if(skip1 is True): print("#") print("#DB{}:".format(v),*argv,file=sys.stdout,**kwargs) elif( v==0): #print no mater value of verbose, but not if quiet=1 if(skip1 is True): print("") print(*argv, **kwargs) else: pass sys.stdout.flush() #if you set v= anything except 0,1,2,3,4,5 it is ignored def printStatus(self, s, r=None, hdrs=None, authMsg=None, addSessionLoginInfo=False): if(self.quiet): return(0) if( (s==1 ) and (self.status >= s ) and (r is not None) ): print("#STATUS: Last Response: r.status_code: {}".format(r.status_code)) elif( (s==2 ) and (self.status >= s ) and (r is not None) ): print("#STATUS: Last Response: r.url: {}".format(r.url)) print("#STATUS: Last Response: r.elapsed(responseTime): {0:.2f} sec".format(self.elapsed)) elif( (s==3 ) and (self.status >= s ) and (r is not None) ): if( addSessionLoginInfo is True): print("#____AUTH_TOKEN: {}".format(self.authToken)) print("#____SESSION_ID: {}".format(self.sessionId)) print("#____SESSION_URI: {}".format(self.sessionLink)) else: print("#REQUEST: {} {} ".format(r.request.method, r.request.url)) print("#__Request.Headers: {}".format(r.request.headers)) print("#__Request AuthType: {}".format(authMsg)) print("#__Request Data: {}".format(r.request.body)) print("#__Response.status_code: {}, r.url: {}".format(r.status_code,r.url)) print("#__Response.elapsed(responseTime): {0:.2f} sec".format(self.elapsed)) elif( (s==4 ) and (self.status >= s ) and (r is not None) ): print("#__Response.Headers: {}".format(r.headers)) elif( (s==5 ) and (self.status >= s ) ): print("#__Response. Data: {}".format(r.text)) else: pass #if you set v= anything except 1,2,3,4,5 it is ignored sys.stdout.flush() def printErr(self,*argv,noprog=False,prepend="",**kwargs): if( self.quiet == False): if(noprog is True): print(prepend,*argv, file=sys.stderr, **kwargs) else: print(prepend," {}:".format(self.program),*argv, file=sys.stderr, **kwargs) else: pass sys.stderr.flush() return(0) def printStatusErr4xx(self, status_code,*argv,noprog=False, prepend="",**kwargs): if(self.quiet): return(0) if( status_code < 400 ): self.printErr("status_code: {}".format(status_code)) else: if( status_code == 400 ): errMsg="Bad Request" elif( status_code == 401 ): errMsg="Unauthorized" elif( status_code == 402 ): errMsg="Payment Required ?" elif( status_code == 403 ): errMsg="Forbidden--user not authorized to perform action" elif( status_code == 404 ): errMsg="Not Found" elif( status_code == 405 ): errMsg="Method Not Allowed" elif( status_code == 406 ): errMsg="Not Acceptable" elif( status_code == 407 ): errMsg="Proxy Authentication Required" elif( status_code == 408 ): errMsg="Request Timeout" elif( status_code == 409 ): errMsg="Conflict" elif( status_code == 410 ): errMsg="Gone" elif( status_code == 411 ): errMsg="Length Required" elif( status_code == 412 ): errMsg="Precondition Failed" elif( status_code == 413 ): errMsg="Request Entity Too Large" elif( status_code == 414 ): errMsg="Request-URI Too Long" elif( status_code == 415 ): errMsg="Unsupported Media Type" elif( status_code == 416 ): errMsg="Requested Range Not Satisfiable" elif( status_code == 417 ): errMsg="Expectation Failed" elif( status_code < 500 ): errMsg="" elif( status_code >=500 ): errMsg="Internal Server Error" elif( status_code >=501 ): errMsg="Not Implemented" else: errMsg="" self.printErr("Transport: Response Error: status_code: {} -- {}".format(status_code, errMsg )) sys.stdout.flush() return(0) def getPathBy(self,rft, r, coll, prop=None): if('Members' not in coll): rft.printErr("Error: getPathBy: no members array in collection") return(None,1,None,False,None) else: numOfLinks=len(coll['Members']) if( numOfLinks == 0 ): rft.printErr("Error: getPathBy: empty members array") return(None,1,None,False,None) if(rft.Link is not None): for i in range (0,numOfLinks): if( '@odata.id' not in coll['Members'][i] ): rft.printErr("Error: getPathBy --Link option: improper formatted link-no @odata.id") return(None,1,None,False,None) else: path=coll['Members'][i]['@odata.id'] if( path == rft.Link ): return(path,0,None,False,None) #if we get here, there was no link in Members array that matched -L <link> rft.printErr("Error: getPathBy --Link option: none of the links in the collection matched -L<link>") return(None,1,None,False,None) elif(rft.oneOptn): if(numOfLinks > 1): rc, r, j, d = rft.listCollection(rft, r, coll, prop) id_list = [] if not rc and 'Members' in d: if prop is not None: if d['Members'] and '@odata.id' in d['Members'][0]: return(d['Members'][0]['@odata.id'],0,None,False,None) else: id_list = [m['Id'] for m in d['Members'] if 'Id' in m] rft.printErr("Error: No target specified, but multiple {} IDs found: {}" .format(rft.subcommand, repr(id_list))) rft.printErr("Re-issue command with '-I <Id>' to select target.") return(None,1,None,False,None) if('@odata.id' not in coll['Members'][0] ): rft.printErr("Error: getPathBy --One option: improper formatted link-no @odata.id") return(None,1,None,False,None) else: return(coll['Members'][0]['@odata.id'],0,None,False,None) elif( rft.firstOptn and not rft.gotMatchOptn): if( '@odata.id' not in coll['Members'][0] ): rft.printErr("Error: getPathBy --First option: improper formatted link-no @odata.id") return(None,1,None,False,None) else: return(coll['Members'][0]['@odata.id'],0,None,False,None) elif(rft.gotMatchOptn): baseUrl=r.url matchedPath=None matches=0 for i in range (0,numOfLinks): if( '@odata.id' not in coll['Members'][i] ): rft.printErr("Error: getPathBy --Id or --Match option: improper formatted link-no @odata.id") return(None,1,None,False,None) else: path=coll['Members'][i]['@odata.id'] rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', baseUrl, relPath=path) if(rc==0): # if matchProp found if( d[rft.matchProp] == rft.matchValue ): matchedPath=path matches +=1 if( matches > 1 ): rft.printErr("Error: getPathBy --Id or --Match option: failed: found multiple matches.") return(None,1,None,False,None) if(rft.firstOptn): return(matchedPath,rc,r,j,d) else: rft.printVerbose(4,"Transport:getPathBy:Match: failed match: matchProp={}, matchValue={}, readValue={}".format(rft.matchProp,rft.matchValue,d[rft.matchProp])) pass else: # the request to this member failed rft.printErr("Error: getPathBy --Id or --Match option: failed request to read collection member.") pass #after looping over all members in the array, #if here, if we got a match, return the path. If not, then no match was found. return none if( matches > 0 ): return(matchedPath,rc,r,j,d) else: rft.printErr("Error: getPathBy --Id or --Match option: no match found in collection") return(None,1,None,False,None) else: rft.printErr("Transport:getPathBy: Error: incorrect option specification") return(None,1,None,False,None) # returns <path> rc, r, j, d def getLevel2ResourceById(self,rft, r, coll): if('Members' not in coll): rft.printErr("Error: getPathBy2: no members array in collection") return(None,1,None,False,None) else: numOfLinks=len(coll['Members']) if( numOfLinks == 0 ): rft.printErr("Error: getPathBy2: empty members array") return(None,1,None,False,None) if(rft.linkLevel2 is not None): for i in range (0,numOfLinks): if( '@odata.id' not in coll['Members'][i] ): rft.printErr("Error: getPathBy --Link option: improper formatted link-no @odata.id") return(None,1,None,False,None) else: path=coll['Members'][i]['@odata.id'] if( path == rft.linkLevel2 ): return(path,0,None,False,None) #if we get here, there was no link in Members array that matched -L <link> rft.printErr("Error: getPathBy --Link option: none of the links in the collection matched -L<link>") return(None,1,None,False,None) elif(rft.gotMatchLevel2Optn is True): baseUrl=r.url for i in range (0,numOfLinks): if( '@odata.id' not in coll['Members'][i] ): rft.printErr("Error: getPathBy2 --Id or --Match option: improper formatted link-no @odata.id") return(None,1,None,False,None) else: path=coll['Members'][i]['@odata.id'] rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', baseUrl, relPath=path) if(rc==0): # if matchProp found if( d[rft.matchLevel2Prop] == rft.matchLevel2Value ): return(path,rc,r,j,d) else: rft.printVerbose(5,"Transport:getPathBy2:Match: failed match: matchProp={}, matchValue={}, readValue={}".format(rft.matchLevel2Prop,rft.matchLevel2Value,d[rft.matchLevel2Prop])) pass else: # the request to this member failed pass #after looping over all members in the array, #if here, if we got a match, return the path. If not, then no match was found. return none return(None,1,None,False,None) else: rft.printErr("Transport:getPathBy2: Error: incorrect option specification") return(None,1,None,False,None) # create a dict list of the collection containing: Id, <prop>, <rpath> # if prop=None, then the additional property is not included # return rc,r,j,d def listCollection(self, rft, r, coll, prop=None): if('Members' not in coll): rft.printErr("Error: listCollection: no members array in collection") return(4,None,False,None) else: numOfLinks=len(coll['Members']) if( numOfLinks == 0 ): rft.printVerbose(4,"listCollection: empty members array: {}") return(0,r,True,coll) # returns an empty collection baseUrl=r.url members=list() for i in range (0,numOfLinks): if( '@odata.id' not in coll['Members'][i] ): rft.printErr("Error: listCollection improper formatted link-no @odata.id") return(4,None,False,None) else: path=coll['Members'][i]['@odata.id'] rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=path) if(rc==0): # if remote host returned a response if( "Id" not in d ): rft.printErr("Error: listCollection: no \"Id\" property in Collection member") return(4,None,False,None) if( prop is not None): if( prop not in d): propVal=None; else: propVal=d[prop] # create a member dict. Always include Id and path listMember={"Id": d["Id"], "@odata.id": d["@odata.id"] } # if a property was specified