input
stringlengths
2.65k
237k
output
stringclasses
1 value
# Copyright (c) 2021 ING Wholesale Banking Advanced Analytics # # 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 histogrammar as hg import numpy as np from ..analysis.hist_numpy import assert_similar_hists from ..base import Module class HistStitcher(Module): """Module stitches histograms by date""" def __init__( self, mode="add", time_axis=None, time_bin_idx=None, read_key=None, delta_key=None, store_key=None, ): """Stitching histograms by first axis. :param str mode: options for histogram stitching: "add" or "replace". default is "add". :param str time_axis: name of the first axis, to stitch on. :param str time_bin_idx: value of delta dataset used for stitching, in case delta or first dataset is a batch without time_axis. Should be an ordered string or integer. :param str read_key: key of input histogram-dict to read from data store. (only required when calling transform(datastore) as module) :param str delta_key: key of delta histogram-dict to read from data store. (only required when calling transform(datastore) as module) :param str store_key: key of output data to store in data store (only required when calling transform(datastore) as module) """ super().__init__() self.mode = mode self.time_axis = time_axis self.time_bin_idx = time_bin_idx self.read_key = read_key self.delta_key = delta_key self.store_key = store_key self.allowed_modes = ["add", "replace"] assert self.mode in self.allowed_modes def transform(self, datastore): # --- get input dict lists self.logger.info( f'Stitching histograms "{self.read_key}" and "{self.delta_key}" as "{self.store_key}"' ) hists_basis = self.get_datastore_object(datastore, self.read_key, dtype=dict) hists_delta = self.get_datastore_object(datastore, self.delta_key, dtype=dict) stitched = self.stitch_histograms(self.mode, hists_basis, hists_delta) datastore[self.store_key] = stitched return datastore def stitch_histograms( self, mode=None, hists_basis=None, hists_delta=None, hists_list=None, time_axis="", time_bin_idx=None, ): """Stitching histograms by first axis. Histograms in hists_delta are added to those in hists_basis. Bins are summed or replaced, set this with 'mode'. 'time_axis' specifies the name of the first axis. If the time_axis is not found, it is created, and histograms get inserted the time_bin_idx values. :param str mode: options for histogram stitching: "add" or "replace" bins. default is "add". :param dict hists_basis: input dict of basis histograms. :param dict hists_delta: delta dict of histograms to add to hists_basis. :param list hists_list: alternative for [hists_basis, hists_delta, etc]. can have multiple deltas. first item in list is taken as hists_basis (optional) :param str time_axis: time-axis used for stitching (optional). :param time_bin_idx: (list of) time-value(s) at which to insert hist-deltas into hist-basis. :return: dict with stitched histograms. If stitching is not possible, returns hists_basis. """ # set stitching mode mode = ( mode if isinstance(mode, str) and mode in self.allowed_modes else self.mode ) time_axis = ( time_axis if isinstance(time_axis, str) and len(time_axis) > 0 else self.time_axis ) time_bin_idx = ( time_bin_idx if isinstance(time_bin_idx, (str, int, list, tuple)) else self.time_bin_idx ) hists_list = hists_list or [] if time_bin_idx is not None: if isinstance(time_bin_idx, (str, int)): time_bin_idx = [time_bin_idx] if not isinstance(time_bin_idx, (list, tuple)): raise TypeError( "time_bin_idx should be a (list of) ordered integer(s) or string(s)" ) dts = [type(tv) for tv in time_bin_idx] if not dts.count(dts[0]) == len(dts): raise TypeError(f"time_bin_idxs have inconsistent datatypes: {dts}") # basic checks and conversions if isinstance(hists_basis, dict) and len(hists_basis) > 0: hists_list.insert(0, hists_basis) if isinstance(hists_delta, dict) and len(hists_delta) > 0: hists_list.append(hists_delta) elif isinstance(hists_delta, list): for hd in hists_delta: if isinstance(hd, dict) and len(hd) > 0: hists_list.append(hd) if not isinstance(hists_list, list) or len(hists_list) == 0: raise TypeError( "hists_list should be a filled list of histogram dictionaries." ) for hd in hists_list: if not isinstance(hd, dict) or len(hd) == 0: raise TypeError( "hists_list should be a list of filled histogram dictionaries." ) hists_basis = hists_list[0] hists_delta = hists_list[1:] # determine possible features, used for comparisons below if isinstance(time_axis, str) and len(time_axis) > 0: self.feature_begins_with = f"{time_axis}:" # Three possibilities # 1. if there are no basis hists starting with "time_axis:", assume that this the very first batch. # 2. if delta(s) do not start with "time_axis:", assume that this is a set of batches without time_axis # 3. deltas already have a time-axis. start stitching of histograms by using bins.update() features_basis = self.get_features( list(hists_basis.keys()) ) # basis keys that start with time_axis if len(features_basis) > 0: # pruning of keys not starting with time_axis hists_list[0] = hists_basis = { k: h for k, h in hists_basis.items() if k in features_basis } # 1. if there are no basis hists starting with "time_axis:", assume that this the very first batch. if ( len(features_basis) == 0 and time_axis and len(hists_basis) > 0 and time_axis ): if time_bin_idx is None: self.logger.info( f'Inserting basis histograms in axis "{time_axis}" at bin index 0.' ) time_bin_idx = [0] hists_basis_new = {} for k, hist in hists_basis.items(): feature = f"{time_axis}:{k}" self.logger.debug(f'Now creating histogram "{feature}"') hists_basis_new[feature] = self._create_hist_with_time_axis( hist, time_bin_idx[0] ) # reset hists_basis features_basis = self.get_features(list(hists_basis_new.keys())) hists_list[0] = hists_basis = hists_basis_new time_bin_idx = time_bin_idx[1:] # -- is there a need to continue? There need to be overlapping hists. delta_keys = set() if len(hists_delta) > 0: delta_keys = set(hists_delta[0].keys()) for hd in hists_delta[1:]: delta_keys &= set(hd.keys()) if len(hists_delta) == 0 or len(delta_keys) == 0 or len(hists_basis) == 0: self.logger.debug( "No overlapping delta features. returning pruned hists_basis." ) return hists_basis stitched = {} # 2. if delta(s) do not start with "time_axis:", assume that this is a set of batches without time_axis features_delta = self.get_features( list(delta_keys) ) # delta keys that start with time_axis if ( len(features_basis) > 0 and len(features_delta) == 0 and len(delta_keys) > 0 and time_axis ): if time_bin_idx is None or len(time_bin_idx) == 0: time_bin_idx = self._generate_time_bin_idx( hists_basis, features_basis, time_axis, len(hists_delta) ) if time_bin_idx is None: raise ValueError( "Request to insert delta hists but time_bin_idx not set or deductable. Please set manually." ) self.logger.info( f'Inserting delta histograms in axis "{time_axis}" at bin indices {time_bin_idx}.' ) if len(hists_delta) != len(time_bin_idx): raise ValueError( "Not enough time_bin_idxs set to insert delta histograms." ) for key in list(delta_keys): feature = f"{time_axis}:{key}" if feature not in features_basis: continue self.logger.debug(f'Now inserting into histogram "{feature}"') hist_list = [hd[key] for hd in hists_delta] stitched[feature] = self._insert_hists( hists_basis[feature], hist_list, time_bin_idx, mode ) # add basis hists without any overlap for feature in features_basis: if feature not in stitched: stitched[feature] = hists_basis[feature] return stitched # 3. deltas already have a time-axis. start stitching of histograms by using bins.update() overlapping_keys = set(hists_list[0].keys()) for hd in hists_list[1:]: overlapping_keys &= set(hd.keys()) features_overlap = self.get_features( list(overlapping_keys) ) # all overlapping keys that start with time_axis if len(features_overlap) == 0: # no overlap, then return basis histograms self.logger.warning( "No overlapping basis-delta features. returning pruned hists_basis." ) return hists_basis for feature in features_overlap: self.logger.debug(f'Now stitching histograms "{feature}"') hist_list = [hd[feature] for hd in hists_list] stitched[feature] = self._stitch_by_update(mode, hist_list) # add basis hists without any overlap for feature in features_basis: if feature not in stitched: stitched[feature] = hists_basis[feature] return stitched def _find_max_time_bin_index(self, hists_basis, features_basis, time_axis): """Find the maximum time-bin index in dict of basis histograms :param hists_basis: dict of basis histograms :param features_basis: list of features to look at :param time_axis: name of time-axis :return: maximum time-bin index found or None """ # basic checks assert isinstance(time_axis, str) and len(time_axis) > 0
<filename>sdk/python/pulumi_mongodbatlas/network_peering.py # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import _utilities __all__ = ['NetworkPeeringArgs', 'NetworkPeering'] @pulumi.input_type class NetworkPeeringArgs: def __init__(__self__, *, container_id: pulumi.Input[str], project_id: pulumi.Input[str], provider_name: pulumi.Input[str], accepter_region_name: Optional[pulumi.Input[str]] = None, atlas_cidr_block: Optional[pulumi.Input[str]] = None, atlas_gcp_project_id: Optional[pulumi.Input[str]] = None, atlas_vpc_name: Optional[pulumi.Input[str]] = None, aws_account_id: Optional[pulumi.Input[str]] = None, azure_directory_id: Optional[pulumi.Input[str]] = None, azure_subscription_id: Optional[pulumi.Input[str]] = None, gcp_project_id: Optional[pulumi.Input[str]] = None, network_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, route_table_cidr_block: Optional[pulumi.Input[str]] = None, vnet_name: Optional[pulumi.Input[str]] = None, vpc_id: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a NetworkPeering resource. :param pulumi.Input[str] container_id: Unique identifier of the MongoDB Atlas container for the provider (GCP) or provider/region (AWS, AZURE). You can create an MongoDB Atlas container using the network_container resource or it can be obtained from the cluster returned values if a cluster has been created before the first container. :param pulumi.Input[str] project_id: The unique ID for the MongoDB Atlas project to create the database user. :param pulumi.Input[str] provider_name: Cloud provider to whom the peering connection is being made. (Possible Values `AWS`, `AZURE`, `GCP`). :param pulumi.Input[str] accepter_region_name: Specifies the AWS region where the peer VPC resides. For complete lists of supported regions, see [Amazon Web Services](https://docs.atlas.mongodb.com/reference/amazon-aws/). :param pulumi.Input[str] atlas_gcp_project_id: The Atlas GCP Project ID for the GCP VPC used by your atlas cluster that it is need to set up the reciprocal connection. :param pulumi.Input[str] aws_account_id: AWS Account ID of the owner of the peer VPC. :param pulumi.Input[str] azure_directory_id: Unique identifier for an Azure AD directory. :param pulumi.Input[str] azure_subscription_id: Unique identifier of the Azure subscription in which the VNet resides. :param pulumi.Input[str] gcp_project_id: GCP project ID of the owner of the network peer. :param pulumi.Input[str] network_name: Name of the network peer to which Atlas connects. :param pulumi.Input[str] resource_group_name: Name of your Azure resource group. :param pulumi.Input[str] route_table_cidr_block: AWS VPC CIDR block or subnet. :param pulumi.Input[str] vnet_name: Name of your Azure VNet. :param pulumi.Input[str] vpc_id: Unique identifier of the AWS peer VPC (Note: this is **not** the same as the Atlas AWS VPC that is returned by the network_container resource). """ pulumi.set(__self__, "container_id", container_id) pulumi.set(__self__, "project_id", project_id) pulumi.set(__self__, "provider_name", provider_name) if accepter_region_name is not None: pulumi.set(__self__, "accepter_region_name", accepter_region_name) if atlas_cidr_block is not None: pulumi.set(__self__, "atlas_cidr_block", atlas_cidr_block) if atlas_gcp_project_id is not None: pulumi.set(__self__, "atlas_gcp_project_id", atlas_gcp_project_id) if atlas_vpc_name is not None: pulumi.set(__self__, "atlas_vpc_name", atlas_vpc_name) if aws_account_id is not None: pulumi.set(__self__, "aws_account_id", aws_account_id) if azure_directory_id is not None: pulumi.set(__self__, "azure_directory_id", azure_directory_id) if azure_subscription_id is not None: pulumi.set(__self__, "azure_subscription_id", azure_subscription_id) if gcp_project_id is not None: pulumi.set(__self__, "gcp_project_id", gcp_project_id) if network_name is not None: pulumi.set(__self__, "network_name", network_name) if resource_group_name is not None: pulumi.set(__self__, "resource_group_name", resource_group_name) if route_table_cidr_block is not None: pulumi.set(__self__, "route_table_cidr_block", route_table_cidr_block) if vnet_name is not None: pulumi.set(__self__, "vnet_name", vnet_name) if vpc_id is not None: pulumi.set(__self__, "vpc_id", vpc_id) @property @pulumi.getter(name="containerId") def container_id(self) -> pulumi.Input[str]: """ Unique identifier of the MongoDB Atlas container for the provider (GCP) or provider/region (AWS, AZURE). You can create an MongoDB Atlas container using the network_container resource or it can be obtained from the cluster returned values if a cluster has been created before the first container. """ return pulumi.get(self, "container_id") @container_id.setter def container_id(self, value: pulumi.Input[str]): pulumi.set(self, "container_id", value) @property @pulumi.getter(name="projectId") def project_id(self) -> pulumi.Input[str]: """ The unique ID for the MongoDB Atlas project to create the database user. """ return pulumi.get(self, "project_id") @project_id.setter def project_id(self, value: pulumi.Input[str]): pulumi.set(self, "project_id", value) @property @pulumi.getter(name="providerName") def provider_name(self) -> pulumi.Input[str]: """ Cloud provider to whom the peering connection is being made. (Possible Values `AWS`, `AZURE`, `GCP`). """ return pulumi.get(self, "provider_name") @provider_name.setter def provider_name(self, value: pulumi.Input[str]): pulumi.set(self, "provider_name", value) @property @pulumi.getter(name="accepterRegionName") def accepter_region_name(self) -> Optional[pulumi.Input[str]]: """ Specifies the AWS region where the peer VPC resides. For complete lists of supported regions, see [Amazon Web Services](https://docs.atlas.mongodb.com/reference/amazon-aws/). """ return pulumi.get(self, "accepter_region_name") @accepter_region_name.setter def accepter_region_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "accepter_region_name", value) @property @pulumi.getter(name="atlasCidrBlock") def atlas_cidr_block(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "atlas_cidr_block") @atlas_cidr_block.setter def atlas_cidr_block(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "atlas_cidr_block", value) @property @pulumi.getter(name="atlasGcpProjectId") def atlas_gcp_project_id(self) -> Optional[pulumi.Input[str]]: """ The Atlas GCP Project ID for the GCP VPC used by your atlas cluster that it is need to set up the reciprocal connection. """ return pulumi.get(self, "atlas_gcp_project_id") @atlas_gcp_project_id.setter def atlas_gcp_project_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "atlas_gcp_project_id", value) @property @pulumi.getter(name="atlasVpcName") def atlas_vpc_name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "atlas_vpc_name") @atlas_vpc_name.setter def atlas_vpc_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "atlas_vpc_name", value) @property @pulumi.getter(name="awsAccountId") def aws_account_id(self) -> Optional[pulumi.Input[str]]: """ AWS Account ID of the owner of the peer VPC. """ return pulumi.get(self, "aws_account_id") @aws_account_id.setter def aws_account_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "aws_account_id", value) @property @pulumi.getter(name="azureDirectoryId") def azure_directory_id(self) -> Optional[pulumi.Input[str]]: """ Unique identifier for an Azure AD directory. """ return pulumi.get(self, "azure_directory_id") @azure_directory_id.setter def azure_directory_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "azure_directory_id", value) @property @pulumi.getter(name="azureSubscriptionId") def azure_subscription_id(self) -> Optional[pulumi.Input[str]]: """ Unique identifier of the Azure subscription in which the VNet resides. """ return pulumi.get(self, "azure_subscription_id") @azure_subscription_id.setter def azure_subscription_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "azure_subscription_id", value) @property @pulumi.getter(name="gcpProjectId") def gcp_project_id(self) -> Optional[pulumi.Input[str]]: """ GCP project ID of the owner of the network peer. """ return pulumi.get(self, "gcp_project_id") @gcp_project_id.setter def gcp_project_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "gcp_project_id", value) @property @pulumi.getter(name="networkName") def network_name(self) -> Optional[pulumi.Input[str]]: """ Name of the network peer to which Atlas connects. """ return pulumi.get(self, "network_name") @network_name.setter def network_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "network_name", value) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> Optional[pulumi.Input[str]]: """ Name of your Azure resource group. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="routeTableCidrBlock") def route_table_cidr_block(self) -> Optional[pulumi.Input[str]]: """ AWS VPC CIDR block or subnet. """ return pulumi.get(self, "route_table_cidr_block") @route_table_cidr_block.setter def route_table_cidr_block(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "route_table_cidr_block", value) @property @pulumi.getter(name="vnetName") def vnet_name(self) -> Optional[pulumi.Input[str]]: """ Name of your Azure VNet. """ return pulumi.get(self, "vnet_name") @vnet_name.setter def vnet_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "vnet_name", value) @property @pulumi.getter(name="vpcId") def vpc_id(self) -> Optional[pulumi.Input[str]]: """ Unique identifier of the AWS peer VPC (Note: this is **not** the same as the Atlas AWS VPC that is returned by the network_container resource). """ return pulumi.get(self, "vpc_id") @vpc_id.setter def vpc_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "vpc_id", value) @pulumi.input_type class _NetworkPeeringState: def __init__(__self__, *, accepter_region_name: Optional[pulumi.Input[str]] = None, atlas_cidr_block: Optional[pulumi.Input[str]] = None, atlas_gcp_project_id: Optional[pulumi.Input[str]] = None, atlas_id: Optional[pulumi.Input[str]] = None, atlas_vpc_name: Optional[pulumi.Input[str]] = None, aws_account_id: Optional[pulumi.Input[str]] = None, azure_directory_id: Optional[pulumi.Input[str]] = None, azure_subscription_id: Optional[pulumi.Input[str]] = None, connection_id: Optional[pulumi.Input[str]] = None, container_id: Optional[pulumi.Input[str]] = None, error_message: Optional[pulumi.Input[str]] = None, error_state: Optional[pulumi.Input[str]] = None, error_state_name: Optional[pulumi.Input[str]] = None, gcp_project_id: Optional[pulumi.Input[str]] = None, network_name: Optional[pulumi.Input[str]] = None, peer_id: Optional[pulumi.Input[str]] = None, project_id: Optional[pulumi.Input[str]] = None, provider_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, route_table_cidr_block: Optional[pulumi.Input[str]] = None, status: Optional[pulumi.Input[str]] = None, status_name: Optional[pulumi.Input[str]] = None, vnet_name: Optional[pulumi.Input[str]] = None, vpc_id: Optional[pulumi.Input[str]] = None): """ Input properties used for looking up and filtering NetworkPeering resources. :param pulumi.Input[str] accepter_region_name: Specifies the AWS region where the peer VPC resides. For complete lists of supported regions, see [Amazon Web Services](https://docs.atlas.mongodb.com/reference/amazon-aws/). :param pulumi.Input[str] atlas_gcp_project_id: The Atlas GCP Project ID for the GCP VPC used by your atlas cluster that it is need to set up the reciprocal connection. :param pulumi.Input[str] aws_account_id: AWS Account ID of the owner of the peer VPC. :param pulumi.Input[str] azure_directory_id: Unique identifier for an Azure AD directory. :param pulumi.Input[str] azure_subscription_id: Unique identifier of the Azure subscription in which the VNet resides. :param pulumi.Input[str] connection_id: Unique identifier of the Atlas network peering container. :param pulumi.Input[str] container_id: Unique identifier of the MongoDB Atlas container for the provider (GCP) or provider/region (AWS, AZURE). You can create an MongoDB Atlas container using the network_container resource or it can be obtained from the cluster returned values if a cluster has been created before the first container. :param pulumi.Input[str] error_message: When `"status" : "FAILED"`, Atlas provides a description of the error. :param pulumi.Input[str] error_state: Description of the Atlas error when `status` is `Failed`, Otherwise, Atlas returns `null`. :param pulumi.Input[str] error_state_name: Error
result_dict['utilization_memory'] = float(utilization_memory) or 0 utilization_tensor_slice_match = re.search(r'Block Utilization: (\d+\.\d+) Type: tensor_slice_top', line) if utilization_tensor_slice_match is not None: utilization_tensor_slice = utilization_tensor_slice_match.group(1) result_dict['utilization_tensor_slice'] = float(utilization_tensor_slice) or 0 utilization_device_match = re.search(r'Device Utilization: (\d+\.\d+)', line) if utilization_device_match is not None: utilization_device = utilization_device_match.group(1) result_dict['utilization_device'] = float(utilization_device) or 0 resource_usage_io_match = re.search(r'(\d+)\s+blocks of type: io', line) if resource_usage_io_match is not None and ("Netlist" in prev_line): resource_usage_io = resource_usage_io_match.group(1) result_dict['resource_usage_io'] = int(resource_usage_io) or 0 resource_usage_clb_match = re.search(r'(\d+)\s+blocks of type: clb', line) if resource_usage_clb_match is not None and ("Netlist" in prev_line): resource_usage_clb = resource_usage_clb_match.group(1) result_dict['resource_usage_clb'] = int(resource_usage_clb) or 0 #if result_dict['arch'] == "stratix": # resource_usage_dsp_match = re.search(r'(\d+)\s+blocks of type: mult_36', line) #elif result_dict['arch'] == "agilex": resource_usage_dsp_match = re.search(r'(\d+)\s+blocks of type: dsp_top', line) #else: # print("Unsupported architecture") # raise SystemExit(0) if resource_usage_dsp_match is not None and ("Netlist" in prev_line): resource_usage_dsp = resource_usage_dsp_match.group(1) result_dict['resource_usage_dsp'] = int(resource_usage_dsp) or 0 resource_usage_memory_match = re.search(r'(\d+)\s+blocks of type: memory', line) if resource_usage_memory_match is not None and ("Netlist" in prev_line): resource_usage_memory = resource_usage_memory_match.group(1) result_dict['resource_usage_memory'] = int(resource_usage_memory) or 0 resource_usage_tensor_slice_match = re.search(r'(\d+)\s+blocks of type: tensor_slice_top', line) if resource_usage_tensor_slice_match is not None and ("Netlist" in prev_line): resource_usage_tensor_slice = resource_usage_tensor_slice_match.group(1) result_dict['resource_usage_tensor_slice'] = int(resource_usage_tensor_slice) or 0 device_io_match = re.search(r'(\d+)\s+blocks of type: io', line) if device_io_match is not None and ("Architecture" in prev_line): device_io = device_io_match.group(1) result_dict['device_io'] = int(device_io) or 0 device_clb_match = re.search(r'(\d+)\s+blocks of type: clb', line) if device_clb_match is not None and ("Architecture" in prev_line): device_clb = device_clb_match.group(1) result_dict['device_clb'] = int(device_clb) or 0 device_dsp_match = re.search(r'(\d+)\s+blocks of type: dsp_top', line) if device_dsp_match is not None and ("Architecture" in prev_line): device_dsp = device_dsp_match.group(1) result_dict['device_dsp'] = int(device_dsp) or 0 device_memory_match = re.search(r'(\d+)\s+blocks of type: memory', line) if device_memory_match is not None and ("Architecture" in prev_line): device_memory = device_memory_match.group(1) result_dict['device_memory'] = int(device_memory) or 0 device_tensor_slice_match = re.search(r'(\d+)\s+blocks of type: tensor_slice_top', line) if device_tensor_slice_match is not None and ("Architecture" in prev_line): device_tensor_slice = device_tensor_slice_match.group(1) result_dict['device_tensor_slice'] = int(device_tensor_slice) or 0 resource_usage_adder_match = re.search(r'adder\s*:\s*(\d*)', line) if resource_usage_adder_match is not None and pb_types_usage is True: resource_usage_adder += int(resource_usage_adder_match.group(1)) result_dict['single_bit_adders'] = int(resource_usage_adder) or "Not found" resource_usage_lut_match = re.search(r'lut\s*:\s*(\d*)', line) if resource_usage_lut_match is not None and pb_types_usage is True: resource_usage_lut += int(resource_usage_lut_match.group(1)) result_dict['luts'] = int(resource_usage_lut) or 0 resource_usage_ff_match = re.search(r'ff\s*:\s*(\d*)', line) if resource_usage_ff_match is not None and pb_types_usage is True: resource_usage_ff += int(resource_usage_ff_match.group(1)) result_dict['ffs'] = resource_usage_ff or 0 max_fanout_match = re.search(r'Max Fanout\s*:\s*(.*)', line) if max_fanout_match is not None and ("Avg Fanout" in prev_line): max_fanout = max_fanout_match.group(1) result_dict['max_fanout'] = round(float(max_fanout)) or 0 max_non_global_fanout_match = re.search(r'Max Non Global Net Fanout\s*:\s*(.*)', line) if max_non_global_fanout_match is not None: max_non_global_fanout = max_non_global_fanout_match.group(1) result_dict['max_non_global_fanout'] = round(float(max_non_global_fanout)) or 0 near_crit_connections_match = re.search(r'\[ 0: 0.1\)\s*\d+\s*\(\s*([\d\.]*)%\)', line) if near_crit_connections_match is not None and ("Final Net Connection Criticality Histogram" in prev_line): near_crit_connections = near_crit_connections_match.group(1) result_dict['near_crit_connections'] = float(near_crit_connections) or 0 max_routing_channel_util_match = re.search(r'Maximum routing channel utilization:\s+(.*) at \(.*\)', line) if max_routing_channel_util_match is not None: result_dict['max_routing_channel_util'] = max_routing_channel_util_match.group(1) if routing_channel_util_section is True: routing_channel_hist_was_found = True routing_histogram_match = re.search(r'\[\s+(.*):\s+(.*)\)\s*.*\s*\(\s*(.*)%\)', line) if routing_histogram_match is not None: utilization_min = float(routing_histogram_match.group(1)) utilization_max = float(routing_histogram_match.group(2)) pct_of_total_channels = float(routing_histogram_match.group(3)) if pct_of_total_channels > largest_pct_of_total_channels: largest_pct_of_total_channels = pct_of_total_channels min_util_for_largest_pct_of_total_channels = utilization_min max_util_for_largest_pct_of_total_channels = utilization_max routing_histogram_1_inf_match = re.search(r'\[\s+1:\s+inf\)\s*(.*)\s*\(\s*(.*)%\)', line) if routing_histogram_1_inf_match is not None: result_dict["routing_histogram_1_inf_val"] = int(routing_histogram_1_inf_match.group(1)) result_dict["routing_histogram_1_inf_pct"] = float(routing_histogram_1_inf_match.group(2)) routing_histogram_09_1_match = re.search(r'\[\s+0.9:\s+1\)\s*(.*)\s*\(\s*(.*)%\)', line) if routing_histogram_09_1_match is not None: result_dict["routing_histogram_09_1_val"] = int(routing_histogram_09_1_match.group(1)) result_dict["routing_histogram_09_1_pct"] = float(routing_histogram_09_1_match.group(2)) routing_histogram_08_09_match = re.search(r'\[\s+0.8:\s+0.9\)\s*(.*)\s*\(\s*(.*)%\)', line) if routing_histogram_08_09_match is not None: result_dict["routing_histogram_08_09_val"] = int(routing_histogram_08_09_match.group(1)) result_dict["routing_histogram_08_09_pct"] = float(routing_histogram_08_09_match.group(2)) routing_histogram_07_08_match = re.search(r'\[\s+0.7:\s+0.8\)\s*(.*)\s*\(\s*(.*)%\)', line) if routing_histogram_07_08_match is not None: result_dict["routing_histogram_07_08_val"] = int(routing_histogram_07_08_match.group(1)) result_dict["routing_histogram_07_08_pct"] = float(routing_histogram_07_08_match.group(2)) routing_histogram_06_07_match = re.search(r'\[\s+0.6:\s+0.7\)\s*(.*)\s*\(\s*(.*)%\)', line) if routing_histogram_06_07_match is not None: result_dict["routing_histogram_06_07_val"] = int(routing_histogram_06_07_match.group(1)) result_dict["routing_histogram_06_07_pct"] = float(routing_histogram_06_07_match.group(2)) routing_histogram_05_06_match = re.search(r'\[\s+0.5:\s+0.6\)\s*(.*)\s*\(\s*(.*)%\)', line) if routing_histogram_05_06_match is not None: result_dict["routing_histogram_05_06_val"] = int(routing_histogram_05_06_match.group(1)) result_dict["routing_histogram_05_06_pct"] = float(routing_histogram_05_06_match.group(2)) routing_histogram_04_05_match = re.search(r'\[\s+0.4:\s+0.5\)\s*(.*)\s*\(\s*(.*)%\)', line) if routing_histogram_04_05_match is not None: result_dict["routing_histogram_04_05_val"] = int(routing_histogram_04_05_match.group(1)) result_dict["routing_histogram_04_05_pct"] = float(routing_histogram_04_05_match.group(2)) routing_histogram_03_04_match = re.search(r'\[\s+0.3:\s+0.4\)\s*(.*)\s*\(\s*(.*)%\)', line) if routing_histogram_03_04_match is not None: result_dict["routing_histogram_03_04_val"] = int(routing_histogram_03_04_match.group(1)) result_dict["routing_histogram_03_04_pct"] = float(routing_histogram_03_04_match.group(2)) routing_histogram_02_03_match = re.search(r'\[\s+0.2:\s+0.3\)\s*(.*)\s*\(\s*(.*)%\)', line) if routing_histogram_02_03_match is not None: result_dict["routing_histogram_02_03_val"] = int(routing_histogram_02_03_match.group(1)) result_dict["routing_histogram_02_03_pct"] = float(routing_histogram_02_03_match.group(2)) routing_histogram_01_02_match = re.search(r'\[\s+0.1:\s+0.2\)\s*(.*)\s*\(\s*(.*)%\)', line) if routing_histogram_01_02_match is not None: result_dict["routing_histogram_01_02_val"] = int(routing_histogram_01_02_match.group(1)) result_dict["routing_histogram_01_02_pct"] = float(routing_histogram_01_02_match.group(2)) routing_histogram_00_01_match = re.search(r'\[\s+0:\s+0.1\)\s*(.*)\s*\(\s*(.*)%\)', line) if routing_histogram_00_01_match is not None: result_dict["routing_histogram_00_01_val"] = int(routing_histogram_00_01_match.group(1)) result_dict["routing_histogram_00_01_pct"] = float(routing_histogram_00_01_match.group(2)) prev_line = line #calculated metrics if 'logic_area' in result_dict and 'resource_usage_clb' in result_dict \ and 'resource_usage_dsp' in result_dict and 'resource_usage_memory' in result_dict\ and 'resource_usage_tensor_slice' in result_dict: routing_area_clb = self.get_routing_area(result_dict["arch"], "clb") routing_area_dsp = self.get_routing_area(result_dict["arch"], "dsp") routing_area_memory = self.get_routing_area(result_dict["arch"], "memory") routing_area_tensor_slice = self.get_routing_area(result_dict["arch"], "tensor_slice") result_dict['routing_area'] = (routing_area_clb * result_dict['resource_usage_clb']) +\ (routing_area_dsp * result_dict['resource_usage_dsp']) +\ (routing_area_tensor_slice * result_dict['resource_usage_tensor_slice']) +\ (routing_area_memory * result_dict['resource_usage_memory']) result_dict['total_area'] = float(result_dict['logic_area']) + float(result_dict['routing_area']) if 'ffs' in result_dict and 'luts' in result_dict and 'resource_usage_clb' in result_dict \ and 'resource_usage_dsp' in result_dict and 'resource_usage_memory' in result_dict \ and 'single_bit_adders' in result_dict: result_dict['ff_to_lut_ratio'] = result_dict['ffs'] / result_dict['luts'] result_dict['dsp_to_clb_ratio'] = result_dict['resource_usage_dsp'] / result_dict['resource_usage_clb'] result_dict['memory_to_clb_ratio'] = result_dict['resource_usage_memory'] / result_dict['resource_usage_clb'] result_dict['adder_to_lut_ratio'] = result_dict['single_bit_adders'] / result_dict['luts'] result_dict['largest_pct_of_total_channels'] = largest_pct_of_total_channels result_dict['min_util_for_largest_pct_of_total_channels'] = min_util_for_largest_pct_of_total_channels result_dict['max_util_for_largest_pct_of_total_channels'] = max_util_for_largest_pct_of_total_channels ##-------------------------- ##extract information from odin.blif ##-------------------------- ##try to find <design>.odin.blif #odin_blif_filename = self.find_file(dirname, run_num, result_dict['design']+'.odin.blif') #if odin_blif_filename is None: # result_dict['odin_blif_found'] = "No" #else: # result_dict['odin_blif_found'] = "Yes" # netlist_primitives = 0 # odin_blif = open(odin_blif_filename, "r") # for line in odin_blif: # if ".latch" in line or ".subckt" in line or ".names" in line: # netlist_primitives = netlist_primitives + 1 # result_dict['netlist_primitives'] = netlist_primitives # result_dict['netlist_primitives>100k'] = (netlist_primitives > 100000) # odin_blif.close() #-------------------------- #identify whether this is ml or non-ml design #-------------------------- config_file = dirname + "/config/config.txt" config_fh = open(config_file, "r") result_dict["type"] = "non_ml" for line in config_fh: #if the name of the design file contains either .tensor_slice.v #or .dsp.v, that means it is an ml benchmarks. Non-ml benchmarks #don't have these two variations m = re.search("circuit_list_add=.*(tensor_slice|dsp).v", line) if m is not None: result_dict["type"] = "ml" break config_fh.close() #-------------------------- #extract information from pre-vpr.blif #-------------------------- #try to find <design>.pre-vpr.blif benchname = result_dict['design'] design_type = result_dict['type'] fpga_arch = result_dict['arch'] if design_type == "ml": if fpga_arch == "no_tensor_slice": design_file=benchname+".dsp" else: design_file=benchname+".tensor_slice" else: design_file = benchname result_dict['design_filename'] = design_file + ".v" if result_dict["exp"] == "exp5": if fpga_arch == "tensor_slice_5pct": design_file = re.sub(r'lstm', 'lstm_35_new', design_file) elif fpga_arch == "tensor_slice_10pct": design_file = re.sub(r'lstm', 'lstm_28_new', design_file) elif fpga_arch == "tensor_slice_15pct": design_file = re.sub(r'lstm', 'lstm_20_new', design_file) elif fpga_arch == "tensor_slice_20pct": design_file = re.sub(r'lstm', 'lstm_15_new', design_file) elif fpga_arch == "tensor_slice_25pct": design_file = re.sub(r'lstm', 'lstm_8_new', design_file) pre_vpr_blif_filename = self.find_file(dirname, run_num, design_file+'.pre-vpr.blif') if pre_vpr_blif_filename is None: result_dict['pre_vpr_blif_found'] = "No" else: result_dict['pre_vpr_blif_found'] = "Yes" netlist_primitives = 0 pre_vpr_blif = open(pre_vpr_blif_filename, "r") for line in pre_vpr_blif: if ".latch" in line or ".subckt" in line or ".names" in line: netlist_primitives = netlist_primitives + 1 result_dict['netlist_primitives'] = netlist_primitives result_dict['netlist_primitives>10k'] = (netlist_primitives > 10000) pre_vpr_blif.close() #-------------------------- #extract information from parse_results.txt #-------------------------- #try to find parse_results.txt parse_results_filename = self.find_file(dirname, run_num, 'parse_results.txt') if parse_results_filename is None: result_dict['parse_results_found'] = "No" else: result_dict['parse_results_found'] = "Yes" parse_results_filehandle = open(parse_results_filename, "r") parse_results_dict_reader = csv.DictReader(parse_results_filehandle, delimiter='\t') for row in parse_results_dict_reader: #print(row.keys()) #print(row.values()) result_dict['vtr_flow_elapsed_time'] = row['vtr_flow_elapsed_time'] result_dict['odin_time'] = row['odin_synth_time'] result_dict['abc_time'] = row['abc_synth_time'] result_dict['pack_time'] = row['pack_time'] result_dict['place_time'] = row['place_time'] result_dict['route_time'] = row['min_chan_width_route_time'] result_dict['vtr_flow_peak_memory_usage'] = max(float(row['max_odin_mem']), \ float(row['max_abc_mem']), \ float(row['max_vpr_mem'])) result_dict['logic_depth'] = row['abc_depth'] result_dict['device_height'] = row['device_height'] result_dict['device_width'] = row['device_width'] result_dict['device_grid_area'] = int(result_dict['device_width']) * int(result_dict['device_height']) result_dict['device_grid_side'] = math.sqrt(result_dict['device_grid_area']) result_dict['grid_size_limiter'] = row['device_limiting_resources'] #result_dict['min_channel_width'] = row['min_chan_width'] #result_dict['critical_path'] = row['critical_path_delay'] parse_results_filehandle.close() result_dict["tag"] = self.tag result_dict["date"] = date.today().strftime("%B %d, %Y") #-------------------------- # additional logic for 06-07 bucket in the routing util histogram # because VPR doesn't print this bucket for some reason #-------------------------- if result_dict['vpr_results_found'] == "Yes" and routing_channel_hist_was_found: total_channels = 2 * (int(result_dict["device_width"])-1) * (int(result_dict["device_height"])-1) result_dict["routing_histogram_06_07_val"] = \ total_channels - (\ result_dict["routing_histogram_1_inf_val"] + \ result_dict["routing_histogram_09_1_val"] + \ result_dict["routing_histogram_08_09_val"] + \ result_dict["routing_histogram_07_08_val"] + \ result_dict["routing_histogram_05_06_val"] + \ result_dict["routing_histogram_04_05_val"] + \ result_dict["routing_histogram_03_04_val"] + \ result_dict["routing_histogram_02_03_val"] + \ result_dict["routing_histogram_01_02_val"] + \ result_dict["routing_histogram_00_01_val"] ) result_dict["routing_histogram_06_07_pct"] = \ round(100 - (\ result_dict["routing_histogram_1_inf_pct"] + \ result_dict["routing_histogram_09_1_pct"] + \ result_dict["routing_histogram_08_09_pct"] + \ result_dict["routing_histogram_07_08_pct"] + \ result_dict["routing_histogram_05_06_pct"] + \ result_dict["routing_histogram_04_05_pct"] + \ result_dict["routing_histogram_03_04_pct"] + \ result_dict["routing_histogram_02_03_pct"] +
<reponame>songhaoyu/percvae import os import re import sys import time import numpy as np from tensorflow.contrib import layers from tensorflow.contrib.rnn import OutputProjectionWrapper from tensorflow.python.ops import array_ops from tensorflow.python.ops import embedding_ops from tensorflow.python.ops import variable_scope import rnn_cell_impl as rnn_cell from models.dynamic_rnn_decoder import dynamic_rnn_decoder from utils import gaussian_kld from utils import get_bi_rnn_encode from utils import get_rnn_encode from utils import get_bow from utils import norm_log_liklihood from utils import sample_gaussian from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.util import nest import tensorflow as tf class BaseTFModel(object): global_t = tf.placeholder(dtype=tf.int32, name="global_t") learning_rate = None scope = None @staticmethod def print_model_stats(tvars): total_parameters = 0 for variable in tvars: shape = variable.get_shape() variable_parametes = 1 for dim in shape: variable_parametes *= dim.value print("Trainable %s with %d parameters" % (variable.name, variable_parametes)) total_parameters += variable_parametes print("Total number of trainable parameters is %d" % total_parameters) @staticmethod def get_rnncell(cell_type, cell_size, keep_prob, num_layer): cells = [] for _ in range(num_layer): if cell_type == "gru": cell = rnn_cell.GRUCell(cell_size) else: cell = rnn_cell.LSTMCell(cell_size, use_peepholes=False, forget_bias=1.0) if keep_prob < 1.0: cell = rnn_cell.DropoutWrapper(cell, output_keep_prob=keep_prob) cells.append(cell) if num_layer > 1: cell = rnn_cell.MultiRNNCell(cells, state_is_tuple=True) else: cell = cells[0] return cell @staticmethod def print_loss(prefix, loss_names, losses, postfix): template = "%s " for name in loss_names: template += "%s " % name template += " %f " template += "%s" template = re.sub(' +', ' ', template) avg_losses = [] values = [prefix] for loss in losses: values.append(np.mean(loss)) avg_losses.append(np.mean(loss)) values.append(postfix) print(template % tuple(values)) return avg_losses def train(self, global_t, sess, train_feed): raise NotImplementedError("Train function needs to be implemented") def valid(self, *args, **kwargs): raise NotImplementedError("Valid function needs to be implemented") def batch_2_feed(self, *args, **kwargs): raise NotImplementedError("Implement how to unpack the back") def optimize(self, sess, config, loss, log_dir): if log_dir is None: return # optimization if self.scope is None: tvars = tf.trainable_variables() else: tvars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self.scope) grads = tf.gradients(loss, tvars) if config.grad_clip is not None: grads, _ = tf.clip_by_global_norm(grads, tf.constant(config.grad_clip)) # add gradient noise if config.grad_noise > 0: grad_std = tf.sqrt(config.grad_noise / tf.pow(1.0 + tf.to_float(self.global_t), 0.55)) grads = [g + tf.truncated_normal(tf.shape(g), mean=0.0, stddev=grad_std) for g in grads] if config.op == "adam": print("Use Adam") optimizer = tf.train.AdamOptimizer(config.init_lr) elif config.op == "rmsprop": print("Use RMSProp") optimizer = tf.train.RMSPropOptimizer(config.init_lr) else: print("Use SGD") optimizer = tf.train.GradientDescentOptimizer(self.learning_rate) self.train_ops = optimizer.apply_gradients(zip(grads, tvars)) self.print_model_stats(tvars) train_log_dir = os.path.join(log_dir, "checkpoints") print("Save summary to %s" % log_dir) self.train_summary_writer = tf.summary.FileWriter(train_log_dir, sess.graph) class perCVAE(BaseTFModel): def __init__(self, sess, config, api, log_dir, forward, scope=None, name=None): self.vocab = api.vocab self.rev_vocab = api.rev_vocab self.vocab_size = len(self.vocab) self.idf = api.index2idf self.gen_vocab_size = api.gen_vocab_size self.topic_vocab = api.topic_vocab self.topic_vocab_size = len(self.topic_vocab) self.da_vocab = api.dialog_act_vocab self.da_vocab_size = len(self.da_vocab) self.sess = sess self.scope = scope self.max_utt_len = config.max_utt_len self.max_per_len = config.max_per_len self.max_per_line = config.max_per_line self.max_per_words = config.max_per_words self.go_id = self.rev_vocab["<s>"] self.eos_id = self.rev_vocab["</s>"] self.context_cell_size = config.cxt_cell_size self.sent_cell_size = config.sent_cell_size self.memory_cell_size = config.memory_cell_size self.dec_cell_size = config.dec_cell_size self.hops = config.hops self.batch_size = config.batch_size self.test_samples = config.test_samples self.balance_factor = config.balance_factor with tf.name_scope("io"): self.first_dimension_size = self.batch_size self.input_contexts = tf.placeholder(dtype=tf.int32, shape=(self.first_dimension_size, None, self.max_utt_len), name="dialog_context") self.floors = tf.placeholder(dtype=tf.int32, shape=(self.first_dimension_size, None), name="floor") self.context_lens = tf.placeholder(dtype=tf.int32, shape=(self.first_dimension_size,), name="context_lens") self.topics = tf.placeholder(dtype=tf.int32, shape=(self.first_dimension_size,), name="topics") self.personas = tf.placeholder(dtype=tf.int32, shape=(self.first_dimension_size, self.max_per_line, self.max_per_len), name="personas") self.persona_words = tf.placeholder(dtype=tf.int32, shape=(self.first_dimension_size, self.max_per_line, self.max_per_len), name="persona_words") self.persona_position = tf.placeholder(dtype=tf.int32, shape=(self.first_dimension_size, None), name="persona_position") self.selected_persona = tf.placeholder(dtype=tf.int32, shape=(self.first_dimension_size, 1), name="selected_persona") self.query = tf.placeholder(dtype=tf.int32, shape=(self.first_dimension_size, self.max_utt_len), name="query") # target response given the dialog context self.output_tokens = tf.placeholder(dtype=tf.int32, shape=(self.first_dimension_size, None), name="output_token") self.output_lens = tf.placeholder(dtype=tf.int32, shape=(self.first_dimension_size,), name="output_lens") # optimization related variables self.learning_rate = tf.Variable(float(config.init_lr), trainable=False, name="learning_rate") self.learning_rate_decay_op = self.learning_rate.assign(tf.multiply(self.learning_rate, config.lr_decay)) self.global_t = tf.placeholder(dtype=tf.int32, name="global_t") self.use_prior = tf.placeholder(dtype=tf.bool, name="use_prior") max_context_lines = array_ops.shape(self.input_contexts)[1] max_out_len = array_ops.shape(self.output_tokens)[1] batch_size = array_ops.shape(self.input_contexts)[0] with variable_scope.variable_scope("wordEmbedding"): self.embedding = tf.get_variable("embedding", [self.vocab_size, config.embed_size], dtype=tf.float32) embedding_mask = tf.constant([0 if i == 0 else 1 for i in range(self.vocab_size)], dtype=tf.float32, shape=[self.vocab_size, 1]) embedding = self.embedding * embedding_mask input_embedding = embedding_ops.embedding_lookup(embedding, tf.reshape(self.input_contexts, [-1])) input_embedding = tf.reshape(input_embedding, [-1, self.max_utt_len, config.embed_size]) output_embedding = embedding_ops.embedding_lookup(embedding, self.output_tokens) persona_input_embedding = embedding_ops.embedding_lookup(embedding, tf.reshape(self.personas, [-1])) persona_input_embedding = tf.reshape(persona_input_embedding, [-1, self.max_per_len, config.embed_size]) if config.sent_type == "bow": input_embedding, sent_size = get_bow(input_embedding) output_embedding, _ = get_bow(output_embedding) persona_input_embedding, _ = get_bow(persona_input_embedding) elif config.sent_type == "rnn": sent_cell = self.get_rnncell("gru", self.sent_cell_size, config.keep_prob, 1) _, input_embedding, sent_size = get_rnn_encode(input_embedding, sent_cell, scope="sent_rnn") _, output_embedding, _ = get_rnn_encode(output_embedding, sent_cell, self.output_lens, scope="sent_rnn", reuse=True) _, persona_input_embedding, _ = get_rnn_encode(persona_input_embedding, sent_cell, scope="sent_rnn", reuse=True) elif config.sent_type == "bi_rnn": fwd_sent_cell = self.get_rnncell("gru", self.sent_cell_size, keep_prob=1.0, num_layer=1) bwd_sent_cell = self.get_rnncell("gru", self.sent_cell_size, keep_prob=1.0, num_layer=1) input_step_embedding, input_embedding, sent_size = get_bi_rnn_encode(input_embedding, fwd_sent_cell, bwd_sent_cell, scope="sent_bi_rnn") _, output_embedding, _ = get_bi_rnn_encode(output_embedding, fwd_sent_cell, bwd_sent_cell, self.output_lens, scope="sent_bi_rnn", reuse=True) _, persona_input_embedding, _ = get_bi_rnn_encode(persona_input_embedding, fwd_sent_cell, bwd_sent_cell, scope="sent_bi_rnn", reuse=True) else: raise ValueError("Unknown sent_type. Must be one of [bow, rnn, bi_rnn]") # reshape input into dialogs input_embedding = tf.reshape(input_embedding, [-1, max_context_lines, sent_size]) self.input_step_embedding = input_step_embedding self.encoder_state_size = sent_size if config.keep_prob < 1.0: input_embedding = tf.nn.dropout(input_embedding, config.keep_prob) with variable_scope.variable_scope("personaMemory"): embedding_mask = tf.constant([0 if i == 0 else 1 for i in range(self.vocab_size)], dtype=tf.float32, shape=[self.vocab_size, 1]) A = tf.get_variable("persona_embedding_A", [self.vocab_size, self.memory_cell_size], dtype=tf.float32) A = A * embedding_mask C = [] for hopn in range(self.hops): C.append( tf.get_variable("persona_embedding_C_hop_{}".format(hopn), [self.vocab_size, self.memory_cell_size], dtype=tf.float32) * embedding_mask) q_emb = tf.nn.embedding_lookup(A, self.query) u_0 = tf.reduce_sum(q_emb, 1) u = [u_0] for hopn in range(self.hops): if hopn == 0: m_emb_A = tf.nn.embedding_lookup(A, self.personas) m_A = tf.reshape(m_emb_A, [-1, self.max_per_len * self.max_per_line, self.memory_cell_size]) else: with tf.variable_scope('persona_hop_{}'.format(hopn)): m_emb_A = tf.nn.embedding_lookup(C[hopn - 1], self.personas) m_A = tf.reshape(m_emb_A, [-1, self.max_per_len * self.max_per_line, self.memory_cell_size]) u_temp = tf.transpose(tf.expand_dims(u[-1], -1), [0, 2, 1]) dotted = tf.reduce_sum(m_A * u_temp, 2) probs = tf.nn.softmax(dotted) probs_temp = tf.transpose(tf.expand_dims(probs, -1), [0, 2, 1]) with tf.variable_scope('persona_hop_{}'.format(hopn)): m_emb_C = tf.nn.embedding_lookup(C[hopn], tf.reshape(self.personas, [-1, self.max_per_len * self.max_per_line])) m_emb_C = tf.expand_dims(m_emb_C, -2) m_C = tf.reduce_sum(m_emb_C, axis=2) c_temp = tf.transpose(m_C, [0, 2, 1]) o_k = tf.reduce_sum(c_temp * probs_temp, axis=2) u_k = u[-1] + o_k u.append(u_k) persona_memory = u[-1] with variable_scope.variable_scope("contextEmbedding"): context_layers = 2 enc_cell = self.get_rnncell(config.cell_type, self.context_cell_size, keep_prob=1.0, num_layer=context_layers) _, enc_last_state = tf.nn.dynamic_rnn( enc_cell, input_embedding, dtype=tf.float32, sequence_length=self.context_lens) if context_layers > 1: if config.cell_type == 'lstm': enc_last_state = [temp.h for temp in enc_last_state] enc_last_state = tf.concat(enc_last_state, 1) else: if config.cell_type == 'lstm': enc_last_state = enc_last_state.h cond_embedding = tf.concat([persona_memory, enc_last_state], 1) with variable_scope.variable_scope("recognitionNetwork"): recog_input = tf.concat([cond_embedding, output_embedding, persona_memory], 1) self.recog_mulogvar = recog_mulogvar = layers.fully_connected(recog_input, config.latent_size * 2, activation_fn=None, scope="muvar") recog_mu, recog_logvar = tf.split(recog_mulogvar, 2, axis=1) with variable_scope.variable_scope("priorNetwork"): prior_fc1 = layers.fully_connected(cond_embedding, np.maximum(config.latent_size * 2, 100), activation_fn=tf.tanh, scope="fc1") prior_mulogvar = layers.fully_connected(prior_fc1, config.latent_size * 2, activation_fn=None, scope="muvar") prior_mu, prior_logvar = tf.split(prior_mulogvar, 2, axis=1) latent_sample = tf.cond(self.use_prior, lambda: sample_gaussian(prior_mu, prior_logvar), lambda: sample_gaussian(recog_mu, recog_logvar)) with variable_scope.variable_scope("personaSelecting"): condition = tf.concat([persona_memory, latent_sample], 1) self.persona_dist = tf.nn.log_softmax( layers.fully_connected(condition, self.max_per_line, activation_fn=tf.tanh, scope="persona_dist")) select_temp = tf.expand_dims(tf.argmax(self.persona_dist, 1, output_type=tf.int32), 1) index_temp = tf.expand_dims(tf.range(0, self.first_dimension_size, dtype=tf.int32), 1) persona_select = tf.concat([index_temp, select_temp], 1) selected_words_ordered = tf.reshape(tf.gather_nd(self.persona_words, persona_select), [self.max_per_len * self.first_dimension_size]) self.selected_words = tf.gather_nd(self.persona_words, persona_select) label = tf.reshape(selected_words_ordered, [self.max_per_len * self.first_dimension_size, 1]) index = tf.reshape(tf.range(self.first_dimension_size, dtype=tf.int32), [self.first_dimension_size, 1]) index = tf.reshape(tf.tile(index, [1, self.max_per_len]), [self.max_per_len * self.first_dimension_size, 1]) concated = tf.concat([index, label], 1) true_labels = tf.where(selected_words_ordered > 0) concated = tf.gather_nd(concated, true_labels) self.persona_word_mask = tf.sparse_to_dense(concated, [self.first_dimension_size, self.vocab_size], config.perw_weight, 0.0) self.other_word_mask = tf.sparse_to_dense(concated, [self.first_dimension_size, self.vocab_size], 0.0, config.othw_weight) self.persona_word_mask = self.persona_word_mask * self.idf with variable_scope.variable_scope("generationNetwork"): gen_inputs = tf.concat([cond_embedding, latent_sample], 1) # BOW loss bow_fc1 = layers.fully_connected(gen_inputs, 400, activation_fn=tf.tanh, scope="bow_fc1") if config.keep_prob < 1.0: bow_fc1 = tf.nn.dropout(bow_fc1, config.keep_prob) self.bow_logits = layers.fully_connected(bow_fc1, self.vocab_size, activation_fn=None, scope="bow_project") # Y loss dec_inputs = gen_inputs selected_attribute_embedding = None self.da_logits = tf.zeros((batch_size, self.da_vocab_size)) # Decoder if config.num_layer > 1: dec_init_state = [] for i in range(config.num_layer): temp_init = layers.fully_connected(dec_inputs, self.dec_cell_size, activation_fn=None, scope="init_state-%d" % i) if config.cell_type == 'lstm': temp_init = rnn_cell.LSTMStateTuple(temp_init, temp_init) dec_init_state.append(temp_init) dec_init_state = tuple(dec_init_state) else: dec_init_state = layers.fully_connected(dec_inputs, self.dec_cell_size, activation_fn=None, scope="init_state") if config.cell_type == 'lstm': dec_init_state = rnn_cell.LSTMStateTuple(dec_init_state, dec_init_state) with variable_scope.variable_scope("decoder"): dec_cell = self.get_rnncell(config.cell_type, self.dec_cell_size, config.keep_prob, config.num_layer) dec_cell = OutputProjectionWrapper(dec_cell, self.vocab_size) pos_cell = self.get_rnncell(config.cell_type, self.dec_cell_size, config.keep_prob, config.num_layer) pos_cell = OutputProjectionWrapper(pos_cell, self.vocab_size) with variable_scope.variable_scope("position"): self.pos_w_1 = tf.get_variable("pos_w_1", [self.dec_cell_size, 2], dtype=tf.float32) self.pos_b_1 = tf.get_variable("pos_b_1", [2], dtype=tf.float32) def position_function(states, logp=False): states = tf.reshape(states, [-1, self.dec_cell_size]) if logp: return tf.reshape( tf.nn.log_softmax(tf.matmul(states, self.pos_w_1) + self.pos_b_1), [self.first_dimension_size, -1, 2]) return tf.reshape( tf.nn.softmax(tf.matmul(states, self.pos_w_1) + self.pos_b_1), [self.first_dimension_size, -1, 2]) if forward: loop_func = self.context_decoder_fn_inference(position_function, self.persona_word_mask, self.other_word_mask, None, dec_init_state, embedding, start_of_sequence_id=self.go_id, end_of_sequence_id=self.eos_id, maximum_length=self.max_utt_len, num_decoder_symbols=self.vocab_size, context_vector=selected_attribute_embedding, ) dec_input_embedding = None dec_seq_lens = None else: loop_func = self.context_decoder_fn_train(dec_init_state,
<gh_stars>0 from matplotlib import pyplot as plt import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score, mean_squared_error from sklearn.preprocessing import StandardScaler def get_multiple_choice_value_count(df, field_name, do_norm=False, set_index=False, filter_condition=None, show_plot=True): ''' :param df: :param field_name, :param do_norm :param set_index, :param filter_condition: :param show_plot: :return: ''' choice_count, is_numerical_field = get_choice_count(df, field_name, filter_condition) choice_count = pd.DataFrame({'MultiLabels': list(choice_count.keys()), 'MultiValues': list(choice_count.values())}) if do_norm: choice_count.MultiValues = choice_count.MultiValues.apply(lambda x: np.around(x / choice_count.shape[0], 3)) if show_plot: choice_count.plot.bar(x='MultiLabels', y='MultiValues', title=''.join(['chosen values count for:', field_name]), figsize=(20, 10)) choice_count.rename(columns={'MultiLabels': field_name}, inplace=True) choice_count.sort_values(by=field_name, inplace=True) if set_index: choice_count.set_index(field_name, inplace=True) return choice_count def get_choice_count(df, field_name, filter_condition=None): ''' :param df: :param field_name: :param filter_condition: :return: ''' choice_count = {'nan': 0} is_numerical_field = False def map_str(sl): if isinstance(sl, str): for s in sl.split(';'): if choice_count.get(s, None): choice_count[s] += 1 else: choice_count[s] = 1 else: if np.isfinite(sl): if choice_count.get(sl, None): choice_count[sl] += 1 else: choice_count[sl] = 1 else: choice_count['nan'] += 1 if filter_condition: dff = df[df[list(filter_condition.keys())[0]] == list(filter_condition.values())[0]] else: dff = df.copy() dff[field_name].apply(lambda x: map_str(x)) if not choice_count['nan']: choice_count.pop('nan', None) for k in choice_count.keys(): try: if np.isfinite(float(k)): is_numerical_field = True except: continue return choice_count, is_numerical_field def compare_multiple_choice_with_filter(df, filed_name, filter_field, filter_values=[None, None]): ''' :param df: :param filed_name: :param filter_field: :param filter_values: :return: ''' fc_1 = get_multiple_choice_value_count(df, filed_name, do_norm=True, set_index=True, filter_condition={filter_field: filter_values[1]}, show_plot=False); fc_0 = get_multiple_choice_value_count(df, filed_name, do_norm=True, set_index=True, filter_condition={filter_field: filter_values[0]}, show_plot=False); comp_df = pd.merge(fc_1, fc_0, left_index=True, right_index=True) ff_n1 = ''.join([filter_field, '_', str(filter_values[1]), '_perc']) ff_n0 = ''.join([filter_field, '_', str(filter_values[0]), '_perc']) ff_n_diff = ''.join([filter_field, '_Diff_Vals']) comp_df.columns = [ff_n1, ff_n0] comp_df[ff_n_diff] = comp_df[ff_n1] - comp_df[ff_n0] return comp_df def compare_categorical_dataframes(fc_1, fc_0, fn_1, fn_0): ''' :param fc_1: :param fc_0: :param fn_1 :param fn_0 :return: ''' comp_df = pd.merge(fc_1, fc_0, left_index=True, right_index=True) ff_n1 = fn_1 ff_n0 = fn_0 ff_n_diff = 'Diff_Vals' comp_df.columns = [ff_n1, ff_n0] comp_df[ff_n_diff] = comp_df[ff_n1] - comp_df[ff_n0] return comp_df def job_satisfaction(job_sat_level): ''' :param job_sat_level: :return: ''' try: if job_sat_level == np.nan: return 0 if 'satisfied' == job_sat_level.split()[-1]: return 1 else: return 0 except: return 0 def higher_ed(formal_ed_str): ''' INPUT formal_ed_str - a string of one of the values from the Formal Education column OUTPUT return 1 if the string is in ("Master's degree", "Doctoral", "Professional degree") return 0 otherwise ''' try: if formal_ed_str == np.nan: return 0 for s in ("Master’s", "Doctoral", "Professional"): if s in formal_ed_str: return 1 else: return 0 except: return 0 def get_missing_row_percentage(df): """ # How much data is missing in each row of the dataset? :param df: :return: """ missing_rows = df.isna().mean(axis=1) df['MissingRows'] = missing_rows return df def get_outliers(df, missing_perc=0.15): ''' Perform an assessment of how much missing data there is in each column of the dataset. :param df: :params missing_perc: :return: dictionary of outliers columns and their percentage of missing value ''' outliers = df.isna().mean() outliers = outliers[outliers > missing_perc] return pd.DataFrame({'OutlierLabels': list(outliers.keys()), 'OutlierValues': list(outliers.values)}) def get_description(schema, column_name): ''' INPUT - schema - pandas dataframe with the schema of the developers survey column_name - string - the name of the column you would like to know about OUTPUT - desc - string - the description of the column ''' desc = list(schema[schema['Column'] == column_name]['Question'])[0] return desc def find_interval(data_inverval, val): ''' :param data_inverval: :param val: :return: ''' for c in data_inverval: if c.left <= val <= c.right: return np.round(c.mid) return np.round(val) def replace_nan_with_mean(x, mean_value): ''' :param x: :param mean_value: :param replace_nan: :return: ''' try: if np.isfinite(float(x)): return np.round(float(x)) else: return np.round(mean_value) except: return np.round(mean_value) def replace_special_str_with_number(df_field, special_strs={}): ''' :param df_field: :param special_strs: :return: ''' return df_field.apply(lambda x: special_strs.get(x, x)).astype(np.float) def categorize_values_in_range(df_field, cat_number, impute_withmean=True): ''' replace missing values with mean of all values :param df_field: :param cat_number: :param impute_withmean :return: ''' if impute_withmean: df_field = impute_with_mean(df_field) filed_name_clean = ''.join([df_field.name, 'Categorized']) cuts = pd.cut(df_field.array, cat_number) return df_field.apply(lambda x: find_interval(cuts.categories, x)), filed_name_clean def coef_weights(coefficients, X_train): ''' INPUT: coefficients - the coefficients of the linear model X_train - the training data, so the column names can be used OUTPUT: coefs_df - a dataframe holding the coefficient, estimate, and abs(estimate) Provides a dataframe that can be used to understand the most influential coefficients in a linear model by providing the coefficient estimates along with the name of the variable attached to the coefficient. ''' coefs_df = pd.DataFrame() coefs_df['est_int'] = X_train.columns coefs_df['coefs'] = lm_model.coef_ coefs_df['abs_coefs'] = np.abs(lm_model.coef_) coefs_df = coefs_df.sort_values('abs_coefs', ascending=False) return coefs_df def impute_with_mean(df_field): ''' :param df_field: :return: ''' mean_value = pd.to_numeric(df_field, errors='coerce').mean() return df_field.apply(lambda x: replace_nan_with_mean(x, mean_value)) def create_dummy_df(df, cutoff_rate=0.2): ''' INPUT: :param: df - pandas dataframe with categorical variables you want to dummy :param: cutoff_rate OUTPUT: df - a new dataframe that has the following characteristics: 1. contains all columns that were not specified as categorical 2. removes all the original columns in cat_cols 3. dummy columns for each of the categorical columns in cat_cols 4. if dummy_na is True - it also contains dummy columns for the NaN values 5. Use a prefix of the column name with an underscore (_) for separating ''' cat_cols = df.select_dtypes(include=['object']).columns for col in cat_cols: choice_count, is_numerical_field = get_choice_count(df, col) col_choices = [(col + '_' + k).replace(" ", "") for k in choice_count.keys()] df[col_choices] = pd.DataFrame([np.zeros(len(choice_count.keys()))], index=df.index) for i, j in df[col].items(): if isinstance(j, str): for s in j.split(";"): df[(col + '_' + s).replace(" ", "")][i] = 1 else: df[(col + '_' + str(j)).replace(" ", "")][i] = 1 for c in col_choices: if df[c].mean() < cutoff_rate: df.drop(columns=[c], inplace=True) df.drop(col, axis=1, inplace=True) return df def drop_categorical_columns(df): ''' :param df: :return: ''' return df.drop(df.select_dtypes(include=['object']).columns, axis=1) def clean_and_split_data(df, response_col, include_cat_field=False, desired_columns=[], cutoff_rate=0.2, test_size=0.30, rand_state=42): ''' INPUT: :param: df - a dataframe holding all the variables of interest :param: response_col - a string holding the name of the column :param: :param: cutoff_rate :param: include_cat_field :param: test_size :param: rand_state OUTPUT: X, y, X_train, X_test, y_train, y_test - output from sklearn train test split used for optimal model ''' # Dropping where the salary has missing values df = df.dropna(subset=[response_col], axis=0) # Drop columns with all NaN values df = df.dropna(how='all', axis=1) if desired_columns: df = df[desired_columns + [response_col]] if include_cat_field: df = create_dummy_df(df, cutoff_rate) else: df = drop_categorical_columns(df) # Mean function fill_mean = lambda col: col.fillna(col.mean()) # Fill the mean df = df.apply(fill_mean, axis=0) # Split into explanatory and response variables return split_data_to_train_test(df, response_col, test_size, rand_state) def split_data_to_train_test(df, response_col, test_size=0.30, rand_state=42): ''' :param df: :param rand_state: :param response_col: :param test_size: :return: ''' X = df.drop(response_col, axis=1) y = df[response_col] x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=rand_state) # Split into train and test return X, y, x_train, x_test, y_train, y_test def apply_standard_scaler(x_train, x_test): ''' :param x_train: :param x_test: :return: ''' scaler = StandardScaler() x_train = scaler.fit_transform(x_train) x_test = scaler.transform(x_test) return x_train, x_test def train_linear_model(x_train, y_train, x_test, y_test): ''' :param x_train: :param y_train: :param x_test: :param y_test: :return: ''' lm_model = LinearRegression(normalize=True) # Instantiate lm_model.fit(x_train, y_train) # Fit # Predict using your model y_test_preds = lm_model.predict(x_test) y_train_preds = lm_model.predict(x_train) # Score using your model test_score = r2_score(y_test, y_test_preds) train_score = r2_score(y_train, y_train_preds) return test_score, train_score, lm_model def find_optimal_lm_mod(X, y, cutoffs, test_size=.30, random_state=42, plot=True): ''' INPUT X - pandas dataframe, X matrix y - pandas dataframe, response variable cutoffs - list of ints, cutoff for number of non-zero values in dummy categorical vars test_size - float between 0 and 1, default 0.3, determines the proportion of data as test data random_state - int, default 42, controls random state for train_test_split plot - boolean, default 0.3, True to plot result OUTPUT r2_scores_test - list of floats of r2 scores on the test data r2_scores_train - list of floats of r2 scores on the train data lm_model - model object from sklearn X_train, X_test, y_train, y_test - output from sklearn train test split used for optimal model ''' r2_scores_test, r2_scores_train, num_feats, results = [], [], [], dict() for cutoff in cutoffs: # reduce X matrix reduce_X = X.iloc[:, np.where((X.sum() > cutoff) == True)[0]] num_feats.append(reduce_X.shape[1]) # split the data into train and test X_train, X_test, y_train, y_test = train_test_split(reduce_X, y, test_size=test_size, random_state=random_state) # fit the model and obtain pred response
feat is not None: gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) return 'fail' out_ds.ReleaseResultSet(sql_lyr) sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata_reference') feat = sql_lyr.GetNextFeature() if feat is not None: gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) return 'fail' out_ds.ReleaseResultSet(sql_lyr) out_ds.SetMetadataItem('IDENTIFIER', 'my_identifier') out_ds.SetMetadataItem('DESCRIPTION', 'my_description') out_ds = None # Still no metadata out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) if out_ds.GetMetadataItem('IDENTIFIER') != 'my_identifier': gdaltest.post_reason('fail') return 'fail' if out_ds.GetMetadataItem('DESCRIPTION') != 'my_description': gdaltest.post_reason('fail') return 'fail' sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata') feat = sql_lyr.GetNextFeature() if feat is not None: gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) return 'fail' out_ds.ReleaseResultSet(sql_lyr) sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata_reference') feat = sql_lyr.GetNextFeature() if feat is not None: gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) return 'fail' out_ds.ReleaseResultSet(sql_lyr) # Write metadata in global scope out_ds.SetMetadata({'bar':'foo'}, 'GEOPACKAGE') out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) if out_ds.GetMetadataItem('bar', 'GEOPACKAGE') != 'foo': gdaltest.post_reason('fail') return 'fail' sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata') feat = sql_lyr.GetNextFeature() if feat.GetField('id') != 1 or feat.GetField('md_scope') != 'dataset' or \ feat.GetField('md_standard_uri') != 'http://gdal.org' or \ feat.GetField('mime_type') != 'text/xml' or \ feat.GetField('metadata') != """<GDALMultiDomainMetadata> <Metadata> <MDI key="bar">foo</MDI> </Metadata> </GDALMultiDomainMetadata> """: gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) return 'fail' out_ds.ReleaseResultSet(sql_lyr) sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata_reference') feat = sql_lyr.GetNextFeature() if feat.GetField('reference_scope') != 'geopackage' or \ not feat.IsFieldNull('table_name') or \ not feat.IsFieldNull('column_name') or \ not feat.IsFieldNull('row_id_value') or \ not feat.IsFieldSet('timestamp') or \ feat.GetField('md_file_id') != 1 or \ not feat.IsFieldNull('md_parent_id'): gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) return 'fail' out_ds.ReleaseResultSet(sql_lyr) out_ds.SetMetadataItem('bar', 'baz', 'GEOPACKAGE') out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) if out_ds.GetMetadataItem('bar', 'GEOPACKAGE') != 'baz': gdaltest.post_reason('fail') return 'fail' out_ds.SetMetadata(None, 'GEOPACKAGE') out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) if len(out_ds.GetMetadata('GEOPACKAGE')) != 0: gdaltest.post_reason('fail') return 'fail' out_ds.SetMetadataItem('1','2') out_ds.SetMetadataItem('3','4','CUSTOM_DOMAIN') out_ds.SetMetadataItem('6','7', 'GEOPACKAGE') # Non GDAL metdata out_ds.ExecuteSQL("INSERT INTO gpkg_metadata VALUES (10, 'dataset', 'uri', 'text/plain', 'my_metadata')") out_ds.ExecuteSQL("INSERT INTO gpkg_metadata_reference VALUES ('geopackage',NULL,NULL,NULL,'2012-08-17T14:49:32.932Z',10,NULL)") out_ds.ExecuteSQL("INSERT INTO gpkg_metadata VALUES (11, 'dataset', 'uri', 'text/plain', 'other_metadata')") out_ds.ExecuteSQL("INSERT INTO gpkg_metadata_reference VALUES ('geopackage',NULL,NULL,NULL,'2012-08-17T14:49:32.932Z',11,NULL)") out_ds.ExecuteSQL("INSERT INTO gpkg_metadata VALUES (12, 'dataset', 'uri', 'text/plain', 'my_metadata_local')") out_ds.ExecuteSQL("INSERT INTO gpkg_metadata_reference VALUES ('table','tmp',NULL,NULL,'2012-08-17T14:49:32.932Z',12,NULL)") out_ds.ExecuteSQL("INSERT INTO gpkg_metadata VALUES (13, 'dataset', 'uri', 'text/plain', 'other_metadata_local')") out_ds.ExecuteSQL("INSERT INTO gpkg_metadata_reference VALUES ('table','tmp',NULL,NULL,'2012-08-17T14:49:32.932Z',13,NULL)") out_ds = None for i in range(2): out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) if out_ds.GetMetadataItem('1') != '2': gdaltest.post_reason('fail') return 'fail' if out_ds.GetMetadataItem('GPKG_METADATA_ITEM_1') != 'my_metadata_local': gdaltest.post_reason('fail') print(out_ds.GetMetadata()) return 'fail' if out_ds.GetMetadataItem('GPKG_METADATA_ITEM_2') != 'other_metadata_local': gdaltest.post_reason('fail') print(out_ds.GetMetadata()) return 'fail' if out_ds.GetMetadataItem('GPKG_METADATA_ITEM_1', 'GEOPACKAGE') != 'my_metadata': gdaltest.post_reason('fail') print(out_ds.GetMetadata('GEOPACKAGE')) return 'fail' if out_ds.GetMetadataItem('GPKG_METADATA_ITEM_2', 'GEOPACKAGE') != 'other_metadata': gdaltest.post_reason('fail') print(out_ds.GetMetadata('GEOPACKAGE')) return 'fail' if out_ds.GetMetadataItem('3', 'CUSTOM_DOMAIN') != '4': gdaltest.post_reason('fail') return 'fail' if out_ds.GetMetadataItem('6', 'GEOPACKAGE') != '7': gdaltest.post_reason('fail') return 'fail' out_ds.SetMetadata(out_ds.GetMetadata()) out_ds.SetMetadata(out_ds.GetMetadata('GEOPACKAGE'),'GEOPACKAGE') out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) out_ds.SetMetadata(None) out_ds.SetMetadata(None, 'CUSTOM_DOMAIN') out_ds.SetMetadata(None, 'GEOPACKAGE') out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) if out_ds.GetMetadataItem('GPKG_METADATA_ITEM_1', 'GEOPACKAGE') != 'my_metadata': gdaltest.post_reason('fail') print(out_ds.GetMetadata()) return 'fail' sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata WHERE id < 10') feat = sql_lyr.GetNextFeature() if feat is not None: gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) return 'fail' out_ds.ReleaseResultSet(sql_lyr) sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata_reference WHERE md_file_id < 10') feat = sql_lyr.GetNextFeature() if feat is not None: gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) return 'fail' out_ds.ReleaseResultSet(sql_lyr) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') return 'success' ############################################################################### # Two band, PNG def get_georeferenced_greyalpha_ds(): src_ds = gdal.Open('../gcore/data/stefan_full_greyalpha.tif') tmp_ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tmp.tif', src_ds.RasterXSize, src_ds.RasterYSize, 2) tmp_ds.SetGeoTransform([0,10,0,0,0,-10]) tmp_ds.WriteRaster(0, 0, src_ds.RasterXSize, src_ds.RasterYSize, src_ds.ReadRaster(0, 0, src_ds.RasterXSize, src_ds.RasterYSize)) return tmp_ds def gpkg_22(tile_drv_name = 'PNG'): if gdaltest.gpkg_dr is None: return 'skip' if tile_drv_name is None: tile_drv = gdaltest.png_dr if gdaltest.jpeg_dr is None: return 'skip' expected_cs = [ 2466, 10807 ] clamped_expected_cs = [ 1989, 1989, 1989, 11580 ] if tile_drv_name == 'PNG': tile_drv = gdaltest.png_dr expected_cs = [ 1970, 10807 ] clamped_expected_cs = [ 2100, 2100, 2100, 11580 ] elif tile_drv_name == 'JPEG': tile_drv = gdaltest.jpeg_dr expected_cs = [ 6782, 32706 ] clamped_expected_cs = [ 6538, 6538, 6538, 32744 ] elif tile_drv_name == 'WEBP': tile_drv = gdaltest.webp_dr if gdaltest.webp_supports_rgba: expected_cs = [ 13112, 10807 ] clamped_expected_cs = [ 13380, 13380, 13380, 11580 ] else: expected_cs = [ 13112, 32706 ] clamped_expected_cs = [ 13380, 13380, 13380, 32744 ] if tile_drv is None: return 'skip' gdal.Unlink('/vsimem/tmp.gpkg') tmp_ds = get_georeferenced_greyalpha_ds() if tile_drv_name: options = ['TILE_FORMAT=' + tile_drv_name, 'BLOCKSIZE=16'] else: options = ['BLOCKSIZE=16'] out_ds = gdaltest.gpkg_dr.CreateCopy('/vsimem/tmp.gpkg', tmp_ds, options = options) tmp_ds_filename = tmp_ds.GetDescription() ds = None gdal.Unlink(tmp_ds_filename) out_ds = None out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options = ['BAND_COUNT=2']) got_cs = [out_ds.GetRasterBand(i+1).Checksum() for i in range(2)] if got_cs != expected_cs: if tile_drv_name != 'WEBP' or got_cs not in ([4899, 10807], [6274, 10807]): gdaltest.post_reason('fail') print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) return 'fail' out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = [out_ds.GetRasterBand(i+1).Checksum() for i in range(4)] expected_cs = [ expected_cs[0], expected_cs[0], expected_cs[0], expected_cs[1] ] if got_cs != expected_cs: if tile_drv_name != 'WEBP' or got_cs not in ([4899, 4899, 4899, 10807], [4899, 4984, 4899, 10807], [6274, 6274, 6274, 10807]): gdaltest.post_reason('fail') print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) return 'fail' out_ds = None ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options = ['USE_TILE_EXTENT=YES']) got_cs = [ds.GetRasterBand(i+1).Checksum() for i in range(4)] if got_cs != clamped_expected_cs: if tile_drv_name != 'WEBP' or got_cs not in ([5266, 5266, 5266, 11580], [5266, 5310, 5266, 11580], [6436, 6436, 6436, 11580]): gdaltest.post_reason('fail') print('Got %s, expected %s' % (str(got_cs), str(clamped_expected_cs))) return 'fail' ds = None gdal.Unlink('/vsimem/tmp.gpkg') return 'success' ############################################################################### # Two band, JPEG def gpkg_23(): return gpkg_22(tile_drv_name = 'JPEG') ############################################################################### # Two band, WEBP def gpkg_24(): return gpkg_22(tile_drv_name = 'WEBP') ############################################################################### # Two band, mixed def gpkg_25(): return gpkg_22(tile_drv_name = None) ############################################################################### # Test TILING_SCHEME def gpkg_26(): if gdaltest.gpkg_dr is None: return 'skip' if gdaltest.png_dr is None: return 'skip' gdal.Unlink('/vsimem/tmp.gpkg') tests = [ ('CUSTOM', [4672, 4672, 4672, 4873], None), ('GoogleCRS84Quad', [3562, 3562, 3562, 3691], None), ('GoogleCRS84Quad', [3562, 3562, 3562, 3691], ['RESAMPLING=BILINEAR']), ('GoogleCRS84Quad', [3417, 3417, 3417, 3691], ['RESAMPLING=CUBIC']), ('GoogleCRS84Quad', [3562, 3562, 3562, 3691], ['ZOOM_LEVEL_STRATEGY=AUTO']), ('GoogleCRS84Quad', [14445, 14445, 14445, 14448], ['ZOOM_LEVEL_STRATEGY=UPPER']), ('GoogleCRS84Quad', [3562, 3562, 3562, 3691], ['ZOOM_LEVEL_STRATEGY=LOWER']), ('GoogleMapsCompatible', [4118, 4118, 4118, 4406], None), ('PseudoTMS_GlobalGeodetic', [3562, 3562, 3562, 3691], None), ('PseudoTMS_GlobalMercator', [4118, 4118, 4118, 4406], None) ] for (scheme, expected_cs, other_options) in tests: src_ds = gdal.Open('data/byte.tif') options = ['TILE_FORMAT=PNG', 'TILING_SCHEME='+scheme] if other_options: options = options + other_options ds = gdaltest.gpkg_dr.CreateCopy('/vsimem/tmp.gpkg', src_ds, options = options) ds = None ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = [ds.GetRasterBand(i+1).Checksum() for i in range(4)] # VC12 returns [3561, 3561, 3561, 3691] for GoogleCRS84Quad # and For GoogleCRS84Quad RESAMPLING=CUBIC, got [3415, 3415, 3415, 3691] if max([ abs(got_cs[i] - expected_cs[i]) for i in range(4)]) > 2: gdaltest.post_reason('fail') print('For %s, got %s, expected %s' % (scheme, str(got_cs), str(expected_cs))) if gdal.GetConfigOption('APPVEYOR') is None: return 'fail' ds = None gdal.Unlink('/vsimem/tmp.gpkg') tests = [ ('GoogleCRS84Quad', [[42255, 47336, 24963, 35707],[42253, 47333, 24961, 35707]], None), ('GoogleMapsCompatible', [[35429, 36787, 20035, 17849]], None) ] for (scheme, expected_cs, other_options) in tests: src_ds = gdal.Open('data/small_world.tif') options = ['TILE_FORMAT=PNG', 'TILING_SCHEME='+scheme] if other_options: options = options + other_options ds = gdaltest.gpkg_dr.CreateCopy('/vsimem/tmp.gpkg', src_ds, options = options) ds = None ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = [ds.GetRasterBand(i+1).Checksum() for i in range(4)] if got_cs not in expected_cs: gdaltest.post_reason('fail') print('For %s, got %s, expected %s' % (scheme, str(got_cs), str(expected_cs))) if gdal.GetConfigOption('APPVEYOR') is None: return 'fail' ds = None gdal.Unlink('/vsimem/tmp.gpkg') # Test a few error cases gdal.PushErrorHandler() ds = gdaltest.gpkg_dr.Create('/vsimem/tmp.gpkg', 1, 1, 1, options = ['TILING_SCHEME=GoogleCRS84Quad', 'BLOCKSIZE=128']) gdal.PopErrorHandler() if ds is not None: gdaltest.post_reason('fail') return 'fail' gdal.Unlink('/vsimem/tmp.gpkg') ds = gdaltest.gpkg_dr.Create('/vsimem/tmp.gpkg', 1, 1, 1, options = ['TILING_SCHEME=GoogleCRS84Quad']) # Test that implicit SRS registration works. if ds.GetProjectionRef().find('4326') < 0: gdaltest.post_reason('fail') return 'fail' gdal.PushErrorHandler() ret = ds.SetGeoTransform([0,10,0,0,0,-10]) gdal.PopErrorHandler() if ret == 0: gdaltest.post_reason('fail') return 'fail' srs = osr.SpatialReference() srs.ImportFromEPSG(32630) gdal.PushErrorHandler() ret = ds.SetProjection(srs.ExportToWkt()) gdal.PopErrorHandler() if ret == 0: gdaltest.post_reason('fail') return 'fail' gdal.PushErrorHandler() ds = None gdal.PopErrorHandler() gdal.Unlink('/vsimem/tmp.gpkg') # Invalid TILING_SCHEME src_ds = gdal.Open('data/byte.tif') gdal.PushErrorHandler() ds = gdaltest.gpkg_dr.CreateCopy('/foo/tmp.gpkg', src_ds, options = ['TILING_SCHEME=invalid']) gdal.PopErrorHandler() if ds is not None: gdaltest.post_reason('fail') return 'fail' # Invalid target filename src_ds = gdal.Open('data/byte.tif') gdal.PushErrorHandler() ds = gdaltest.gpkg_dr.CreateCopy('/foo/tmp.gpkg', src_ds, options = ['TILING_SCHEME=GoogleCRS84Quad']) gdal.PopErrorHandler() if ds is not None: gdaltest.post_reason('fail') return 'fail' # Source is not georeferenced src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') gdal.PushErrorHandler() ds = gdaltest.gpkg_dr.CreateCopy('/vsimem/tmp.gpkg', src_ds, options = ['TILING_SCHEME=GoogleCRS84Quad']) gdal.PopErrorHandler() if ds is not None: gdaltest.post_reason('fail') return 'fail' return 'success' ############################################################################### # Test behaviour with low block cache max def gpkg_27(): if gdaltest.gpkg_dr is None: return 'skip' if gdaltest.png_dr is None: return 'skip' gdal.Unlink('/vsimem/tmp.gpkg') oldSize = gdal.GetCacheMax() gdal.SetCacheMax(0) src_ds = gdal.Open('data/small_world.tif') out_ds = gdaltest.gpkg_dr.CreateCopy('/vsimem/tmp.gpkg', src_ds, options = ['TILE_FORMAT=PNG', 'BLOCKXSIZE=200', 'BLOCKYSIZE=200']) gdal.SetCacheMax(oldSize) expected_cs = [src_ds.GetRasterBand(i+1).Checksum() for i in range(3)] got_cs = [out_ds.GetRasterBand(i+1).Checksum() for i in range(3)] if got_cs !=
} for i in [xx, yy, xy, yx]: (pol1, pol2) = pol_dict[i][1] (sig1_pol, sig2_pol) = pol_dict[i][0] # broadcast in_inds broad_inds = np.logical_and( in_inds[sig1_inds, pol1, :], in_inds[sig2_inds, pol2, :], ) # broadcast indices and distances for bilinear interpolation sv_inds_right1 = sv_inds_right[sig1_inds, pol1, :][broad_inds] sv_inds_right2 = sv_inds_right[sig2_inds, pol2, :][broad_inds] ds1 = ds[sig1_inds, pol1, :][broad_inds] ds2 = ds[sig2_inds, pol2, :][broad_inds] self.data_array[crosses, :, i] = van_vleck_crosses_cheby( self.data_array[crosses, :, i], self.data_array.real[autos[sig1_inds], :, sig1_pol], self.data_array.real[autos[sig2_inds], :, sig2_pol], broad_inds, rho_coeff, sv_inds_right1, sv_inds_right2, ds1, ds2, cheby_approx, ) # correct yx autos sig_inds = ant_1_inds[good_autos] broad_inds = np.logical_and( in_inds[sig_inds, 0, :], in_inds[sig_inds, 1, :] ) sv_inds_right1 = sv_inds_right[sig_inds, 0, :][broad_inds] sv_inds_right2 = sv_inds_right[sig_inds, 1, :][broad_inds] ds1 = ds[sig_inds, 0, :][broad_inds] ds2 = ds[sig_inds, 1, :][broad_inds] self.data_array[good_autos, :, yx] = van_vleck_crosses_cheby( self.data_array[good_autos, :, yx], self.data_array.real[good_autos, :, yy], self.data_array.real[good_autos, :, xx], broad_inds, rho_coeff, sv_inds_right1, sv_inds_right2, ds1, ds2, cheby_approx, ) # add back in frequency axis self.data_array = self.data_array.reshape( (self.Nbls, self.Ntimes, self.Nfreqs, self.Npols) ) # solve integral directly else: # add back in frequency axis self.data_array = self.data_array.reshape( (self.Nbls, self.Ntimes, self.Nfreqs, self.Npols) ) for k in crosses: auto1 = autos[ant_1_inds[k]] auto2 = autos[ant_2_inds[k]] for j in range(self.Nfreqs): # get data sig1 = self.data_array.real[ auto1, :, j, np.array([yy, yy, xx, xx]) ].flatten() sig2 = self.data_array.real[ auto2, :, j, np.array([yy, xx, yy, xx]) ].flatten() khat = self.data_array[ k, :, j, np.array([yy, yx, xy, xx]) ].flatten() # correct real kap = van_vleck_crosses_int(khat.real, sig1, sig2, cheby_approx) self.data_array.real[ k, :, j, np.array([yy, yx, xy, xx]) ] = kap.reshape(self.Npols, self.Ntimes) # correct imaginary kap = van_vleck_crosses_int(khat.imag, sig1, sig2, cheby_approx) self.data_array.imag[ k, :, j, np.array([yy, yx, xy, xx]) ] = kap.reshape(self.Npols, self.Ntimes) # correct yx autos for k in good_autos: for j in range(self.Nfreqs): # get data sig1 = self.data_array.real[k, :, j, yy] sig2 = self.data_array.real[k, :, j, xx] khat = self.data_array[k, :, j, yx] # correct real kap = van_vleck_crosses_int(khat.real, sig1, sig2, cheby_approx) self.data_array.real[k, :, j, yx] = kap # correct imaginary kap = van_vleck_crosses_int(khat.imag, sig1, sig2, cheby_approx) self.data_array.imag[k, :, j, yx] = kap # correct xy autos self.data_array[good_autos, :, :, xy] = np.conj( self.data_array[good_autos, :, :, yx] ) # square autos self.data_array.real[auto_inds, :, :, pols] = ( self.data_array.real[auto_inds, :, :, pols] ** 2 ) # reshape to (nblts, nfreqs, npols) self.data_array = np.swapaxes(self.data_array, 0, 1) self.data_array = self.data_array.reshape(self.Nblts, self.Nfreqs, self.Npols) # rescale the data self.data_array *= nsamples # return data array to desired precision if self.data_array.dtype != data_array_dtype: self.data_array = self.data_array.astype(data_array_dtype) self.history += history_add_string def _flag_small_auto_ants( self, nsamples, flag_small_auto_ants, ant_1_inds, ant_2_inds, flagged_ant_inds ): """ Find and flag autocorrelations below a threshold. Specifically, look for autocorrelations < 0.5 * channel_width * int_time, as these have been found by the Van Vleck correction to indicate bad data. If flag_small_auto_ants is True, then antennas with autos below the threshold will be flagged completely. Otherwise, antennas will be flagged at only the times and frequencies at which their autos are below the threshold. Parameters ---------- nsamples : int Twice the numkber of electric field samples in an autocorrelation; equal to 2 * channel_width * int_time. The auto divided by nsamples is equal to the expectation value of the electric field samples squared. flag_small_auto_ants : bool Keyword option to flag antenna entirely or only at specific times and frequencies. ant_1_inds : numpy array of type int Indices of antenna 1 corresponding the the baseline-time axis. ant_2_inds : numpy array of type int Indices of antenna 2 corresponding the the baseline-time axis. flagged_ant_inds : numpy array of type int List of indices of flagged antennas. Returns ------- flagged_ant_inds : numpy array of type int Updated list of indices of flagged antennas. """ # calculate threshold so that average cross multiply = 0.25 threshold = 0.25 * nsamples # look for small autos and flag auto_inds = self.ant_1_array == self.ant_2_array autos = self.data_array.real[auto_inds, :, 0:2] # auto_flags = self.flag_array[auto_inds, :, 0:2] autos = autos.reshape(self.Ntimes, self.Nants_data, self.Nfreqs, 2) # find autos below threshold small_auto_flags = np.logical_and(autos != 0, autos <= threshold,) if flag_small_auto_ants: # find antenna indices for small sig ants and add to flagged_ant_inds ant_inds = np.unique(np.nonzero(small_auto_flags)[1]) ant_inds = ant_inds[~np.in1d(ant_inds, flagged_ant_inds)] if len(ant_inds) != 0: self.history += ( " The following antennas were flagged by the Van Vleck \ correction: " + str(ant_inds) + "." ) flagged_ant_inds = np.concatenate((flagged_ant_inds, ant_inds)) else: # get flags for small auto ants and add to flag array small_auto_flags = np.logical_or( small_auto_flags[:, :, :, 0], small_auto_flags[:, :, :, 1] ) # broadcast autos flags to corresponding crosses small_auto_flags = np.logical_or( small_auto_flags[:, ant_1_inds[: self.Nbls], :], small_auto_flags[:, ant_2_inds[: self.Nbls], :], ) small_auto_flags = small_auto_flags.reshape(self.Nblts, self.Nfreqs) self.flag_array = np.logical_or( self.flag_array, small_auto_flags[:, :, np.newaxis] ) return flagged_ant_inds def _get_pfb_shape(self, avg_factor): """ Get pfb shape from file and apply appropriate averaging. Parameters ---------- avg_factor : int Factor by which frequency channels have been averaged. Returns ------- cb_array : numpy array of type float Array corresponding to pfb shape for a coarse band. """ with h5py.File( DATA_PATH + "/mwa_config_data/MWA_rev_cb_10khz_doubles.h5", "r" ) as f: cb = f["coarse_band"][:] cb_array = cb.reshape(int(128 / avg_factor), int(avg_factor)) cb_array = np.average(cb_array, axis=1) return cb_array def _correct_coarse_band( self, cb_num, ant_1_inds, ant_2_inds, cb_array, dig_gains, nsamples, num_fine_chans, correct_van_vleck, remove_coarse_band, remove_dig_gains, ): """ Apply pfb, digital gain, and Van Vleck corrections to a coarse band. Parameters ---------- cb_num : int Index of coarse band. ant_1_inds : numpy array of type int Indices of antenna 1 corresponding the the baseline-time axis. ant_2_inds : numpy array of type int Indices of antenna 2 corresponding the the baseline-time axis. cb_array : numpy array of type float Array corresponding to pfb shape for a coarse band. dig_gains : numpy array of type float Array corresponding to digital gains for each antenna and coarse band. nsamples : int Twice the numkber of electric field samples in an autocorrelation; equal to 2 * channel_width * int_time. The auto divided by nsamples is equal to the expectation value of the electric field sample squared. num_fine_chans : int Number of fine channels in each data file. correct_van_vleck : bool Option to apply Van Vleck correction to data. remove_coarse_band : bool Option to remove pfb coarse band shape from data. remove_dig_gains : bool Option to remove digital gains from data. """ # get coarse band data as np.complex128 cb_data = self.data_array[ :, cb_num * num_fine_chans : (cb_num + 1) * num_fine_chans, : ].astype(np.complex128) # remove digital gains if remove_dig_gains: dig_gains1 = dig_gains[ant_1_inds, cb_num, np.newaxis, np.newaxis] dig_gains2 = dig_gains[ant_2_inds, cb_num, np.newaxis, np.newaxis] cb_data /= dig_gains1 cb_data /= dig_gains2 # remove coarse band if remove_coarse_band: cb_data /= cb_array[:num_fine_chans, np.newaxis] # put corrected data back into data array self.data_array[ :, cb_num * num_fine_chans : (cb_num + 1) * num_fine_chans, : ] = cb_data def _apply_corrections( self, ant_1_inds, ant_2_inds, avg_factor, dig_gains, spw_inds, num_fine_chans, flagged_ant_inds, cheby_approx, data_array_dtype, flag_small_auto_ants, correct_van_vleck, remove_coarse_band, remove_dig_gains, ): """ Prepare and apply pfb, digital gain, and Van Vleck corrections. Parameters ---------- ant_1_inds : numpy array of type int Indices of antenna 1 corresponding the the baseline-time axis. ant_2_inds : numpy array of type int Indices of antenna 2 corresponding the the baseline-time axis. avg_factor : int Factor by which frequency channels have been averaged. dig_gains : array Array of digital gains with shape (Nants, Ncoarse_chans). spw_inds : array of type int Array of coarse band numbers. num_fine_chans : int Number of fine channels in each data file. flagged_ant_inds : numpy array of type int List of indices of flagged antennas. cheby_approx : bool Option to use chebyshev approximation for Van Vleck correction. data_array_dtype : numpy dtype Datatype to store the output data_array as. flag_small_auto_ants : bool Option to completely flag antennas found by _flag_small_auto_ants. correct_van_vleck : bool Option to apply Van Vleck correction to data. remove_coarse_band : bool Option to remove pfb coarse band shape from data. remove_dig_gains : bool Option to remove digital gains from data. Returns ------- flagged_ant_inds : numpy array of type
\ heuristic_search.optimize(objective_function, self.iterations) self.selected_channels = \ [self.channel_names[index] for index in self.selected_indices] #==============================================================================# def evaluate_sensor_selection(cns, flow, metric, w, sensor_identifier, training_data, runs=1): """ Execute the evaluation flow """ # Getting together the two evaluation functions without self variables node_sequence = [ExternalGeneratorSourceNode(), BaseNode.node_from_yaml(cns)] # For all nodes of the flow for sub_node_spec in flow: # Use factory method to create node node_obj = BaseNode.node_from_yaml(sub_node_spec) # Append this node to the sequence of node node_sequence.append(node_obj) # Check if the nodes have to cache their outputs for index, node in enumerate(node_sequence): # If a node is trainable, it uses the outputs of its input node # at least twice, so we have to cache. if node.is_trainable(): node_sequence[index - 1].set_permanent_attributes(caching=True) # Split node might also request the data from their input nodes # (once for each split), depending on their implementation. We # assume the worst case and activate caching if node.is_split_node(): node_sequence[index - 1].set_permanent_attributes(caching=True) flow = NodeChain(node_sequence) for run in range(runs): flow[-1].set_run_number(run) # Set input data flow[0].set_generator(training_data) # For every split of the data while True: # As long as more splits are available # Compute the results of the flow for the current split # by calling the method on its last node flow[-1].process_current_split() # If no more splits are available if not flow[-1].use_next_split(): break # reset flow, collection is kept for the different runs for node in flow: node.reset() # Determine performance of the flow and store it in dict result_collection = flow[-1].get_result_dataset() performance = \ result_collection.get_average_performance(metric) \ - w * result_collection.get_performance_std(metric) return (sensor_identifier, performance) #==============================================================================# class PerformanceRanker(object): """ Rank sensors by performance after evaluating classification flows This class provides the functionality to evaluate different classification flows. Every flow has an sensor_identifier string associated. Afterwards, the classification performances (or a derived value - see std_weight parameter) are sorted and returned together with the associated identifier. .. note:: Classification performances are multiplied with (-1). In this way, high performances appear first in the sorted results. The flows differ in the sensors/channels that are used by using multiple Channel Name Selection (CNS) nodes. The way how these CNS nodes are generated, however, is specific for every particular selection procedure (such as "remove one backwards elimination" vs. "add one forward assembly"). The actual generation of the flows happens in generate_cns_nodes. This template class only has a dummy for that method - overwrite it in your ranker! See RemoveOnePerformanceRanker or AddOnePerformanceRanker for examples. **Parameters** :flow: The processing chain (YAML readable). Usually, the flow will at least consist of a CV-Splitter, a classifier, and a :class:`~pySPACE.missions.nodes.sink.classification_performance_sink.PerformanceSinkNode`. See the documentation of :class:`SensorSelectionBase` for an example. :metric: The :ref:`metric <metrics>` for the classification performance used for the calculation of the ranking, if a performance value is used. (*optional, default: Balanced_accuracy*) :std_weight: As a result of cross validation often more than one performance result (*p*) per sensor set is calculated. The score (*s*) of one particular constellation is thus computed by calculating .. math:: s = mean(p) - \\text{std\_weight} \\cdot \\text{std\_dev}(p) Hence, for std_weight = 0 the mean is used. With increasing std_weight large spreads get penalized more strongly. (*optional, default: 0*) :runs: May be specified to perform multiple runs (and thus different CV-Splits) (*optional, default: 1*) :pool_size: May be specified to achieve parallelization of the classification subflow as normally only the main flow is parallelled. .. note:: Currently a pool size larger than 1 will not work with the MulticoreBackend, because multiprocessing can't be nested. Use loadl backend instead or no pool size! .. todo:: Distribute subflows with the subflowhandler using backend specific parallelization. (*optional, default: 1*) :Author: <NAME> (<EMAIL>) & <NAME> :Created: 2011/09/23 """ def __init__(self,ranking_spec): self.flow = ranking_spec["flow"] self.metric = ranking_spec.get("metric","Balanced_accuracy") self.std_weight = ranking_spec.get("std_weight", 0) self.runs =ranking_spec.get("runs", 1) self.pool_size = ranking_spec.get("pool_size", 1) def get_ranking(self,selected_channels, training_data): """Compute the ranking of the selected channels.""" # to get the ranking, classification flows have to be evaluated on # different subsets of the channels. These subsets are generated by # different channel name selection nodes *cns_nodes* cns_nodes = self.generate_cns_nodes(selected_channels, training_data) ranking=[] # one core case if self.pool_size==1: for sensor_identifier,cns_node in cns_nodes: sensor,performance = \ evaluate_sensor_selection(cns=cns_node, flow=self.flow, metric=self.metric, w=self.std_weight, sensor_identifier=sensor_identifier, training_data=training_data, runs=self.runs) ranking.append((sensor,-performance)) # multiple cores: parallel case else: pool = processing.Pool(processes=self.pool_size) # This won't work with mcore results = [pool.apply_async(func=evaluate_sensor_selection, kwds={"cns":cns_node,"flow":self.flow, "metric":self.metric,"w":self.std_weight, "sensor_identifier":sensor_identifier, "training_data":training_data,"runs":self.runs}) for sensor_identifier,cns_node in cns_nodes] pool.close() # self._log("Waiting for parallel processes to finish") # this is not a node! there's no self._log here! pool.join(timeout=1e6) for result in results: sensor,performance =result.get() ranking.append((sensor,-performance)) del(pool) # sort by performance before return # NB: Performances have been multiplied by (-1), s.t. high performances # appear first in the sorted lists. return sorted(ranking,key=lambda t: t[1]) def generate_cns_nodes(self, selected_channels, training_data): """ This method has to be overwritten by the different sensor selection nodes """ raise NotImplementedError("Your method should overwrite the " "generate_cns_nodes method in your Ranker!") class RemoveOnePerformanceRanker(PerformanceRanker): """ Rank sensors by evaluating if classification performance drops without them Consider a set of n sensors. This ranker will always remove one sensor creating n-1 sized subsets. Every size n-1 subset is evaluated. NB: high performance == Unimportant sensor == good sensor to remove See the description of PerformanceRanker for the required parameters. :Author: <NAME> (<EMAIL>) & <NAME> :Created: 2011/09/23 """ def __init__(self,**kwargs): super(RemoveOnePerformanceRanker, self).__init__(**kwargs) def generate_cns_nodes(self, selected_channels, training_data): """ Generate Channel Name Selection Nodes that use the current channels minus 1 .. todo:: training_data parameter is not necessary! """ # generates the list with cns nodes, each of which has a different # sensor removed. This function is specifically what makes this the # "remove_one"-ranker cns_nodes=[] for element in selected_channels: # Remove element temporarily and create channel name selector node # that selects all the remaining channels=deepcopy(selected_channels) channels.remove(element) cns_nodes.append((element,{'node': 'Channel_Name_Selector', 'parameters': {'selected_channels': channels}})) return cns_nodes class AddOnePerformanceRanker(PerformanceRanker): """ Rank sensors by evaluating performance increase on usage Consider a set N of sensors and a fixed subset K of the sensors in N. This ranker will always add one sensor of N\K to K creating k+1 sized subsets. Every subset is than evaluated. The score of the added sensors is determined by the classification performance, s.t. high performance == good sensor to add See the description of PerformanceRanker for the required parameters. :Author: <NAME> (<EMAIL>) & <NAME> :Created: 2011/09/23 """ def __init__(self,**kwargs): super(AddOnePerformanceRanker, self).__init__(**kwargs) def generate_cns_nodes(self, selected_channels, training_data): """Generate Channel Name Selection Nodes that use the current channels plus 1""" # generates the list with cns nodes, each of which has a different # sensor added. This function is specifically what makes this the # "add_one"-ranker channels_to_pick_from = [x for x in training_data[0][0].channel_names if x not in selected_channels] cns_nodes=[] for element in channels_to_pick_from: # Remove element temporarily and create channel name selector node # that selects all the remaining channels=deepcopy(selected_channels) channels.append(element) cns_nodes.append((element,{'node': 'Channel_Name_Selector', 'parameters': {'selected_channels': channels}})) return cns_nodes class CoefficientRanker(object): """ Get a ranking from the second last processing node This ranking is given by this node, by adding up channel weights of linear classifiers or spatial filters. The details remain to the used node (last one in the node chain before sink node) and its method *get_sensor_ranking*. **Parameters** :flow: The classification flow (YAML readable). Usually, the flow will at least consist of a CV-Splitter, a classifier , and a Classification_Performance_Sink. See the documentation of SensorSelectionBase for an example. (*optional, default: 1*) """ def __init__(self,ranking_spec,run_number): self.flow = ranking_spec["flow"] self.run_number = run_number def get_ranking(self,selected_channels, training_data): cns_node = {'node': 'Channel_Name_Selector', 'parameters': {'selected_channels': selected_channels}} # code copy from evaluate_sensor_selection node_sequence = [ExternalGeneratorSourceNode(), BaseNode.node_from_yaml(cns_node)] # For all nodes of the flow for sub_node_spec in self.flow: # Use factory method to create node node_obj = BaseNode.node_from_yaml(sub_node_spec) # Append this node to the sequence of node
\ Field('fldOeePlantID', 'integer', label='Plant'), \ Field('fldOeeSubPlantID', 'integer', label='Sub-Plant'), \ Field('fldOeeDepartmentID', 'integer', label='Department'), \ Field('fldOeeModuleNr', 'integer', label='Module nr'), \ Field('fldOeeModuleTypeID', 'integer', label='Module-type'), \ Field('fldOeeModuleSensorStyleID', 'integer', label='Sensor-style'), \ Field('fldOeeModuleDescription', 'string', label='Module description'), \ Field('fldOeeModuleInformation', 'string', label='Module information'), \ Field('fldOeeModuleIpAddress', 'string', label='IP address'), \ Field('fldOeeModuleIpAddressPort', 'integer', label='IP Port'), \ Field('fldOeeModuleComPort', 'string', label='Com port'), \ Field('fldOeeModuleBitsPerSecond', 'integer', label='Bits per Second'), \ Field('fldOeeModuleDatabits', 'integer', label='Databits'), \ Field('fldOeeModuleStopBits', 'integer', label='StopBits'), \ Field('fldOeeModuleFlowControl', 'string', label='Flowcontrol'), \ Field('fldOeeModuleSensorAddress', 'integer', label='Sensor address'), \ Field('fldOeeModuleSensorResetAddress', 'integer', label='Sensor reset address'), \ Field('fldOeeModuleParity', 'string', label='Parity'), \ Field('fldOeeDateModified', 'datetime', label='Date modified', default = self.request.now), \ Field('fldOeeModuleHistory', 'boolean', label='History'), \ Field('fldOeeSync', 'boolean', label='Sync', default = True)) dboee77(dboee77.tblOee_Module.fldOeeModuleTableKeyID > 0).delete() dboee77.tblOee_Module.import_from_csv_file(open('oee' + strRandom + '.csv', 'r')) for row in rows: row.fldOeeSync = False row.update_record() rows = self.dboee((self.dboee.tblOee_MachineIOFailure.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_MachineIOFailure.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_MachineIOFailure.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_MachineIOFailure.fldOeeDepartmentID == intDepartmentNr)).select() rows.export_to_csv_file(open('oee' + strRandom + '.csv', 'wb')) dboee77.define_table('tblOee_MachineIOFailure', \ Field('fldOeeMachineIOFailureTableKeyID', 'id', readable=False), \ Field('fldOeeCountryID', 'integer', label='Country'), \ Field('fldOeePlantID', 'integer', label='Plant'), \ Field('fldOeeSubPlantID', 'integer', label='Sub-Plant'), \ Field('fldOeeDepartmentID', 'integer', label='Department'), \ Field('fldOeeMachineIOFailureNr', 'integer', label='I/O failure nr'), \ Field('fldOeeMachineIOFailureDescription', 'string', label='I/O failure'), \ Field('fldOeeMachineIOFailureInformation', 'string', label='I/O failure information'), \ Field('fldOeeMachineIOFailureHistory', 'boolean', label='History'), \ Field('fldOeeDateModified', 'datetime', label='Date modified', default = self.request.now), \ Field('fldOeeSync', 'boolean', label='Sync', default = True)) dboee77(dboee77.tblOee_MachineIOFailure.fldOeeMachineIOFailureTableKeyID > 0).delete() dboee77.tblOee_MachineIOFailure.import_from_csv_file(open('oee' + strRandom + '.csv', 'r')) for row in rows: row.fldOeeSync = False row.update_record() rows = self.dboee((self.dboee.tblOee_MachineShortbreak.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_MachineShortbreak.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_MachineShortbreak.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_MachineShortbreak.fldOeeDepartmentID == intDepartmentNr)).select() rows.export_to_csv_file(open('oee' + strRandom + '.csv', 'wb')) dboee77.define_table('tblOee_MachineShortbreak', \ Field('fldOeeMachineShortBreakTableKeyID', 'id', readable=False), \ Field('fldOeeCountryID', 'integer', label='Country'), \ Field('fldOeePlantID', 'integer', label='Plant'), \ Field('fldOeeSubPlantID', 'integer', label='Sub-Plant'), \ Field('fldOeeDepartmentID', 'integer', label='Department'), \ Field('fldOeeMachineShortBreakNr', 'integer', label='Shortbreak nr'), \ Field('fldOeeMachineShortBreakDescription', 'string', label='Shortbreak description'), \ Field('fldOeeMachineShortBreakInformation', 'string', label='Shortbreak information'), \ Field('fldOeeMachineShortBreakHistory', 'boolean', label='History'), \ Field('fldOeeDateModified', 'datetime', label='Date modified', default = self.request.now), \ Field('fldOeeSync', 'boolean', label='Sync', default = True)) dboee77(dboee77.tblOee_MachineShortbreak.fldOeeMachineShortBreakTableKeyID > 0).delete() dboee77.tblOee_MachineShortbreak.import_from_csv_file(open('oee' + strRandom + '.csv', 'r')) for row in rows: row.fldOeeSync = False row.update_record() rows = self.dboee((self.dboee.tblOee_MachineStatus.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_MachineStatus.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_MachineStatus.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_MachineStatus.fldOeeDepartmentID == intDepartmentNr)).select() rows.export_to_csv_file(open('oee' + strRandom + '.csv', 'wb')) dboee77.define_table('tblOee_MachineStatus', \ Field('fldOeeMachineStatusTableKeyID', 'id', readable=False), \ Field('fldOeeCountryID', 'integer', label='Country'), \ Field('fldOeePlantID', 'integer', label='Plant'), \ Field('fldOeeSubPlantID', 'integer', label='Sub-Plant'), \ Field('fldOeeDepartmentID', 'integer', label='Department'), \ Field('fldOeeMachineStatusNr', 'integer', label='Machine status nr'), \ Field('fldOeeMachineStatusDescription', 'string', label='Machine status description'), \ Field('fldOeeMachineStatusInformation', 'string', label='Machine status information'), \ Field('fldOeeMachineStatusHistory', 'boolean', label='History'), \ Field('fldOeeDateModified', 'datetime', label='Date modified', default = self.request.now), \ Field('fldOeeSync', 'boolean', label='Sync', default = True)) dboee77(dboee77.tblOee_MachineStatus.fldOeeMachineStatusTableKeyID > 0).delete() dboee77.tblOee_MachineStatus.import_from_csv_file(open('oee' + strRandom + '.csv', 'r')) for row in rows: row.fldOeeSync = False row.update_record() rows = self.dboee((self.dboee.tblOee_MachineUndefinedProduction.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_MachineUndefinedProduction.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_MachineUndefinedProduction.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_MachineUndefinedProduction.fldOeeDepartmentID == intDepartmentNr)).select() rows.export_to_csv_file(open('oee' + strRandom + '.csv', 'wb')) dboee77.define_table('tblOee_MachineUndefinedProduction', \ Field('fldOeeMachineUndefinedProductionTableKeyID', 'id', readable=False), \ Field('fldOeeCountryID', 'integer', label='Country'), \ Field('fldOeePlantID', 'integer', label='Plant'), \ Field('fldOeeSubPlantID', 'integer', label='Sub-Plant'), \ Field('fldOeeDepartmentID', 'integer', label='Department'), \ Field('fldOeeMachineUndefinedProductionNr', 'integer', label='Undefined Production nr'), \ Field('fldOeeMachineUndefinedProductionDescription', 'string', label='Undefined Production description'), \ Field('fldOeeMachineUndefinedProductionInformation', 'string', label='Undefined Production information'), \ Field('fldOeeMachineUndefinedProductionHistory', 'boolean', label='History'), \ Field('fldOeeDateModified', 'datetime', label='Date modified', default = self.request.now), \ Field('fldOeeSync', 'boolean', label='Sync', default = True)) dboee77(dboee77.tblOee_MachineUndefinedProduction.fldOeeMachineUndefinedProductionTableKeyID > 0).delete() dboee77.tblOee_MachineUndefinedProduction.import_from_csv_file(open('oee' + strRandom + '.csv', 'r')) for row in rows: row.fldOeeSync = False row.update_record() rows = self.dboee((self.dboee.tblOee_MachineUndefinedStandstill.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_MachineUndefinedStandstill.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_MachineUndefinedStandstill.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_MachineUndefinedStandstill.fldOeeDepartmentID == intDepartmentNr)).select() rows.export_to_csv_file(open('oee' + strRandom + '.csv', 'wb')) dboee77.define_table('tblOee_MachineUndefinedStandstill', \ Field('fldOeeMachineUndefinedStandstillTableKeyID', 'id', readable=False), \ Field('fldOeeCountryID', 'integer', label='Country'), \ Field('fldOeePlantID', 'integer', label='Plant'), \ Field('fldOeeSubPlantID', 'integer', label='Sub-Plant'), \ Field('fldOeeDepartmentID', 'integer', label='Department'), \ Field('fldOeeMachineUndefinedStandstillNr', 'integer', label='Undefined standstill nr'), \ Field('fldOeeMachineUndefinedStandstillDescription', 'string', label='Undefined standstill description'), \ Field('fldOeeMachineUndefinedStandstillInformation', 'string', label='Undefined standstill information'), \ Field('fldOeeMachineUndefinedStandstillHistory', 'boolean', label='History'), \ Field('fldOeeDateModified', 'datetime', label='Date modified', default = self.request.now), \ Field('fldOeeSync', 'boolean', label='Sync', default = True)) dboee77(dboee77.tblOee_MachineUndefinedStandstill.fldOeeMachineUndefinedStandstillTableKeyID > 0).delete() dboee77.tblOee_MachineUndefinedStandstill.import_from_csv_file(open('oee' + strRandom + '.csv', 'r')) for row in rows: row.fldOeeSync = False row.update_record() rows = self.dboee((self.dboee.tblOee_MachineUnscheduled.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_MachineUnscheduled.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_MachineUnscheduled.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_MachineUnscheduled.fldOeeDepartmentID == intDepartmentNr)).select() rows.export_to_csv_file(open('oee' + strRandom + '.csv', 'wb')) dboee77.define_table('tblOee_MachineUnscheduled', \ Field('fldOeeMachineUnscheduledTableKeyID', 'id', readable=False), \ Field('fldOeeCountryID', 'integer', label='Country'), \ Field('fldOeePlantID', 'integer', label='Plant'), \ Field('fldOeeSubPlantID', 'integer', label='Sub-Plant'), \ Field('fldOeeDepartmentID', 'integer', label='Department'), \ Field('fldOeeMachineUnscheduledNr', 'integer', label='Unscheduled nr'), \ Field('fldOeeMachineUnscheduledDescription', 'string', label='Unscheduled description'), \ Field('fldOeeMachineUnscheduledInformation', 'string', label='Unscheduled information'), \ Field('fldDateModified', 'datetime', label='Date modified', default = self.request.now), \ Field('fldOeeMachineUnscheduledHistory', 'boolean', label='History'), \ Field('fldOeeSync', 'boolean', label='Sync', default = True)) dboee77(dboee77.tblOee_MachineUnscheduled.fldOeeMachineUnscheduledTableKeyID > 0).delete() dboee77.tblOee_MachineUnscheduled.import_from_csv_file(open('oee' + strRandom + '.csv', 'r')) for row in rows: row.fldOeeSync = False row.update_record() rows = self.dboee((self.dboee.tblOee_MachineUnit.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_MachineUnit.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_MachineUnit.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_MachineUnit.fldOeeDepartmentID == intDepartmentNr)).select() rows.export_to_csv_file(open('oee' + strRandom + '.csv', 'wb')) dboee77.define_table('tblOee_MachineUnit', \ Field('fldOeeMachineUnitTableKeyID', 'id', readable=False), \ Field('fldOeeCountryID', 'integer', label='Country'), \ Field('fldOeePlantID', 'integer', label='Plant'), \ Field('fldOeeSubPlantID', 'integer', label='Sub-Plant'), \ Field('fldOeeDepartmentID', 'integer', label='Department'), \ Field('fldOeeMachineUnitNr', 'integer', label='Machine-unit nr'), \ Field('fldOeeMachineUnitDescription', 'string', label='Machine-unit description'), \ Field('fldOeeDateModified', 'datetime', label='Date modified', default = self.request.now), \ Field('fldOeeMachineUnitHistory', 'boolean', label='History'), \ Field('fldOeeSync', 'boolean', label='Sync', default = True)) dboee77(dboee77.tblOee_MachineUnit.fldOeeMachineUnitTableKeyID > 0).delete() dboee77.tblOee_MachineUnit.import_from_csv_file(open('oee' + strRandom + '.csv', 'r')) for row in rows: row.fldOeeSync = False row.update_record() rows = self.dboee((self.dboee.tblOee_Machine.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_Machine.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_Machine.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_Machine.fldOeeDepartmentID == intDepartmentNr)).select() rows.export_to_csv_file(open('oee' + strRandom + '.csv', 'wb')) dboee77.define_table('tblOee_Machine', \ Field('fldOeeMachineTableKeyID', 'id', readable=False), \ Field('fldOeeCountryID', 'integer', label='Country'), \ Field('fldOeePlantID', 'integer', label='Plant'), \ Field('fldOeeSubPlantID', 'integer', label='Sub-Plant'), \ Field('fldOeeDepartmentID', 'integer', label='Department'), \ Field('fldOeeMachineNr', 'integer', label='Machine nr'), \ Field('fldOeeMachineCode', 'integer', label='Machine code'), \ Field('fldOeeModuleID', 'integer', label='Module'), \ Field('fldOeeMachineShortBreakID', 'integer', label='Shortbreak'), \ Field('fldOeeMachineUndefinedProdID', 'integer', label='Undefined Production'), \ Field('fldOeeMachineUndefinedStandStillID', 'integer', label='Undefined Standstill'), \ Field('fldOeeMachineUnscheduledID', 'integer', label='Unscheduled'), \ Field('fldOeeMachineIOFailureID', 'integer', label='I/O failure'), \ Field('fldOeeMachineUnitID', 'integer', label='Machine-unit'), \ Field('fldOeeMachineDescription', 'string', label='Machine description'), \ Field('fldOeeMachineInformation', 'string', label='Machine information'), \ Field('fldOeeMachineSortOrder', 'integer', label='Machine sort order'), \ Field('fldOeeMachineProductionBoundaryTimer', 'integer', label='Production timer'), \ Field('fldOeeMachineProductionShortbreakTimer', 'integer', label='Shortbreak timer'), \ Field('fldOeeMachineStopCodeTimer', 'integer', label='Stopcode timer'), \ Field('fldOeeMachineSpeed', 'integer', label='Default speed'), \ Field('fldOeeMachineDevider', 'decimal(2,2)', label='Pulse factor'), \ Field('fldOeeMachineOperatorFactor', 'decimal(2,2)', label='Operator factor'), \ Field('fldOeeMachineTarget1OEE', 'integer', label='OEE target 1'), \ Field('fldOeeMachineTarget2OEE', 'integer', label='OEE target 2'), \ Field('fldOeeMachineWorkstationDescription', 'string', label='Workstation description'), \ Field('fldOeeMachineHistory', 'boolean', label='History'), \ Field('fldOeeDateModified', 'datetime', label='Date modified', default = self.request.now), \ Field('fldOeeSync', 'boolean', label='Sync', default = True)) dboee77(dboee77.tblOee_Machine.fldOeeMachineTableKeyID > 0).delete() dboee77.tblOee_Machine.import_from_csv_file(open('oee' + strRandom + '.csv', 'r')) for row in rows: row.fldOeeSync = False row.update_record() rows = self.dboee((self.dboee.tblOee_MachineActivity.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_MachineActivity.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_MachineActivity.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_MachineActivity.fldOeeDepartmentID == intDepartmentNr)).select() rows.export_to_csv_file(open('oee' + strRandom + '.csv', 'wb')) dboee77.define_table('tblOee_MachineActivity', \ Field('fldOeeMachineActivityTableKeyID', 'id', readable=False), \ Field('fldOeeCountryID', 'integer', label='Country'), \ Field('fldOeePlantID', 'integer', label='Plant'), \ Field('fldOeeSubPlantID', 'integer', label='Sub-Plant'), \ Field('fldOeeDepartmentID', 'integer', label='Department'), \ Field('fldOeeMachineActivityID', 'integer', label='Activity'), \ Field('fldOeeMachineID', 'integer', label='Machine'), \ Field('fldOeeMachineActivitySortOrder', 'integer', label='Sort order'), \ Field('fldOeeMachineActivityHistory', 'boolean', label='History'), \ Field('fldOeeDateModified', 'datetime', label='Date modified', default = self.request.now), \ Field('fldOeeSync', 'boolean', label='Sync', default = True)) dboee77(dboee77.tblOee_MachineActivity.fldOeeMachineActivityTableKeyID > 0).delete() dboee77.tblOee_MachineActivity.import_from_csv_file(open('oee' + strRandom + '.csv', 'r')) for row in rows: row.fldOeeSync = False row.update_record() rows = self.dboee((self.dboee.tblOee_DailySchedule.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_DailySchedule.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_DailySchedule.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_DailySchedule.fldOeeDepartmentID == intDepartmentNr)).select() rows.export_to_csv_file(open('oee' + strRandom + '.csv', 'wb')) dboee77.define_table('tblOee_DailySchedule', \ Field('fldOeeDailyScheduleTableKeyID', 'id', readable=False), \ Field('fldOeeDailyScheduleNr', 'integer'), \ Field('fldOeeCountryID', 'integer'), \ Field('fldOeePlantID', 'integer'), \ Field('fldOeeSubPlantID', 'integer'), \ Field('fldOeeDepartmentID', 'integer'), \ Field('fldOeeTeamID', 'integer'), \ Field('fldOeeShiftTimeID', 'integer'), \ Field('fldOeeDailyScheduleDescription', 'string'), \ Field('fldOeeDailyScheduleInformation', 'string'), \ Field('fldOeeDailyScheduleStartDate', 'datetime'), \ Field('fldOeeDailyScheduleEndDate', 'datetime'), \ Field('fldOeeDailyScheduleHistory', 'boolean'), \ Field('fldOeeDateModified', 'datetime'), \ Field('fldOeeSync', 'boolean', label='Sync', default = True)) dboee77(dboee77.tblOee_DailySchedule.fldOeeDailyScheduleTableKeyID > 0).delete() dboee77.tblOee_DailySchedule.import_from_csv_file(open('oee' + strRandom + '.csv', 'r')) for row in rows: row.fldOeeSync = False row.update_record() rows = self.dboee((self.dboee.tblOee_Article.fldOeeCountryID == intCountryNr) & \ (self.dboee.tblOee_Article.fldOeePlantID == intPlantNr) & \ (self.dboee.tblOee_Article.fldOeeSubPlantID == intSubPlantNr) & \ (self.dboee.tblOee_Article.fldOeeDepartmentID == intDepartmentNr)).select() rows.export_to_csv_file(open('oee' + strRandom + '.csv', 'wb')) dboee77.define_table('tblOee_Article', \ Field('fldOeeArticleTableKeyID', 'id', readable=False), \ Field('fldOeeCountryID', 'integer', label='Country'), \ Field('fldOeePlantID', 'integer', label='Plant'), \ Field('fldOeeSubPlantID', 'integer', label='Sub-Plant'), \ Field('fldOeeDepartmentID', 'integer', label='Department'), \ Field('fldOeeArticleNr', 'string', label='Article nr'), \ Field('fldOeeArticleDescription', 'string', label='Article description'), \ Field('fldOeeArticleInformation', 'string', label='Article information'), \ Field('fldOeeArticleNormSpeed', 'integer', label='Norm speed'), \ Field('fldOeeArticleHistory', 'boolean', label='History'), \ Field('fldOeeDateModified', 'datetime', label='Date modified', default = self.request.now), \ Field('fldOeeSync', 'boolean', label='Sync', default = True)) dboee77(dboee77.tblOee_Article.fldOeeArticleTableKeyID > 0).delete() dboee77.tblOee_Article.import_from_csv_file(open('oee' + strRandom
<reponame>jnietol/DVH-Analytics #!/usr/bin/env python # -*- coding: utf-8 -*- # tools.stats.py """ Take numerical data from main app and convert to a format suitable for statistical analysis in Regression and Control Chart tabs """ # Copyright (c) 2016-2019 <NAME> # This file is part of DVH Analytics, released under a BSD license. # See the file LICENSE included with this distribution, also # available at https://github.com/cutright/DVH-Analytics import numpy as np from scipy import stats as scipy_stats from sklearn import linear_model from sklearn.metrics import mean_squared_error, r2_score from regressors import stats as regressors_stats from dvha.db import sql_columns class StatsData: """Class used to to collect data for Regression and Control Chart This process is different than for Time Series since regressions require all variables to be the same length Parameters ---------- dvhs : DVH data from DVH query table_data : dict table data other than from DVHs. Has keys of 'Plans', 'Rxs', 'Beams' with values of QuerySQL objects """ def __init__(self, dvhs, table_data, group=1): self.dvhs = dvhs self.table_data = table_data self.group = group self.column_info = sql_columns.numerical self.correlation_variables = list(self.column_info) self.correlation_variables.sort() self.__map_data() def __map_data(self): self.data = {} stat_types = ["min", "mean", "median", "max"] for var in self.correlation_variables: if var in self.column_info.keys(): var_name = self.column_info[var]["var_name"] table = self.column_info[var]["table"] if table == "DVHs" and hasattr(self.dvhs, var_name): self.data[var] = { "units": self.column_info[var]["units"], "values": getattr(self.dvhs, var_name), } # single value variables elif table == "Plans" and hasattr( self.table_data[table], var_name ): src = self.table_data[table] self.data[var] = { "units": self.column_info[var]["units"], "values": [ getattr(src, var_name)[self.get_plan_index(uid)] for uid in self.uids ], } # multi value variables elif table == "Beams" and hasattr( self.table_data[table], var_name ): src = self.table_data[table] if str_starts_with_any_in_list( var, [ "Beam Complexity", "Beam Area", "Control Point MU", "Beam Perimeter", "Beam Energy", ], ): # stats of these four variable types have min, mean, median, and max types in DB # The following will take min, mean, median, or max of all values for a UID based on var type # Example, if var_name == Beam Complexity (Max), the following will return the Max of these temp = [] for uid in self.uids: indices = self.get_beam_indices(uid) beam_data = getattr( self.table_data["Beams"], var_name ) values = [ beam_data[i] for i in indices if beam_data[i] != "None" ] for stat in stat_types: if stat in var.lower(): if values: temp.append(getattr(np, stat)(values)) else: temp.append(None) self.data[var] = { "units": self.column_info[var]["units"], "values": temp, } else: temp = {s: [] for s in stat_types} for uid in self.uids: for stat in stat_types: values = self._get_src_values( src, var_name, uid ) values = [v for v in values if v != "None"] if values: temp[stat].append( getattr(np, stat)(values) ) else: temp[stat].append(None) for stat in stat_types: corr_key = "%s (%s)" % (var, stat.capitalize()) self.data[corr_key] = { "units": self.column_info[var]["units"], "values": temp[stat], } self._validate_data() def _validate_data(self): """Remove any variables that are constant to avoid crash on regression""" bad_vars = [] for var_name, var_obj in self.data.items(): if "Date" in var_name: if var_name != "Simulation Date": bad_vars.append(var_name) else: values = [ float(val) for val in var_obj["values"] if val != "None" and val is not None ] if not any(np.diff(values).tolist()): bad_vars.append(var_name) for var in bad_vars: self.data.pop(var) def update_endpoints_and_radbio(self): """Update endpoint and radbio data in self.data. This function is needed since all of these values are calculated after a query and user may change these values. """ if self.dvhs: if self.dvhs.endpoints["defs"]: for var in self.dvhs.endpoints["defs"]["label"]: if var not in self.variables: self.data[var] = { "units": "", "values": self.dvhs.endpoints["data"][var], } for var in self.variables: if var[0:2] in {"D_", "V_"}: if var not in self.dvhs.endpoints["defs"]["label"]: self.data.pop(var) if self.dvhs.eud: self.data["EUD"] = {"units": "Gy", "values": self.dvhs.eud} if self.dvhs.ntcp_or_tcp: self.data["NTCP or TCP"] = { "units": "", "values": self.dvhs.ntcp_or_tcp, } self._validate_data() @staticmethod def _get_src_values(src, var_name, uid): """ Parameters ---------- src : QuerySQL table data var_name : str attribute to be extracted from table data uid : str StudyInstanceUID stored in the SQL database Returns ------- list values of ``var_name`` from table data that match ``uid`` """ uid_indices = [ i for i, x in enumerate(src.study_instance_uid) if x == uid ] return [getattr(src, var_name)[i] for i in uid_indices] def get_plan_index(self, uid): """Get the index of ``uid`` from the Plans table Parameters ---------- uid : str StudyInstanceUID as stored in the SQL database Returns ------- int Plans table index for ``uid`` """ return self.table_data["Plans"].study_instance_uid.index(uid) def get_beam_indices(self, uid): """Get the indices of the Beams table with ``uid`` Parameters ---------- uid : str StudyInstanceUID as stored in the SQL database Returns ------- list Beams table indices that match ``uid`` """ return [ i for i, x in enumerate(self.table_data["Beams"].study_instance_uid) if x == uid ] def get_bokeh_data(self, x, y): """Get data in a format compatible with bokeh's ColumnDataSource.data Parameters ---------- x : str x-variable name y : str y-variable name Returns ------- dict x and y data """ if x in list(self.data) and y in list(self.data): # TODO: potential data length issue with study_instance_uid # Received the following error with 0.6.9, can't reproduce # BokehUserWarning: ColumnDataSource's columns must be of the # same length. Current lengths: # ('date', 69), ('mrn', 69), ('uid', 70), ('x', 69), ('y', 69) # Appears to point to this function's return? return { "uid": self.uids, "mrn": self.mrns, "date": self.sim_study_dates, "x": self.data[x]["values"], "y": self.data[y]["values"], } return {key: [] for key in ["uid", "mrn", "date", "x", "y"]} @property def uids(self): """StudyInstanceUIDs from DVH object Returns ------- list ``DVH.study_instance_uid`` """ return self.dvhs.study_instance_uid @property def mrns(self): """MRNs from DVH object Returns ------- list ``DVH.mrn`` """ return self.dvhs.mrn @property def sim_study_dates(self): """Simulation dates from Plans table Returns ------- list Simulation dates """ return self.data["Simulation Date"]["values"] @property def variables(self): """Get variable names for plotting Returns ------- list keys of ``StatsData.data`` sans 'Simulation Date' """ return [var for var in list(self.data) if var != "Simulation Date"] @property def vars_with_nan_values(self): """Find variable names that contain non-numerical values Returns ------- list Variable names that cannot be converted to ``float`` """ ans = [] for var in self.variables: for val in self.data[var]["values"]: try: float(val) except Exception: ans.append(var) break return ans def get_axis_title(self, variable): """Get the plot axis title for ``variable`` Parameters ---------- variable : str A key of ``StatsData.data`` Returns ------- str ``variable`` with units if stored """ if self.data[variable]["units"]: return "%s (%s)" % (variable, self.data[variable]["units"]) return variable def get_X_and_y(self, y_variable, x_variables, include_patient_info=False): """Collect data for input into multi-variable regression Parameters ---------- y_variable : str dependent variable x_variables : list independent variables include_patient_info : bool If True, return mrn, uid, dates with X and y Returns ------- type X, y or X, y, mrn, uid, dates """ data, mrn, uid, dates = [], [], [], [] y_var_data = [] for i, value in enumerate(self.data[y_variable]["values"]): y_var_data.append([value, np.nan][value == "None"]) mrn.append(self.mrns[i]) uid.append(self.uids[i]) dates.append(self.sim_study_dates[i]) data.append(y_var_data) for var in x_variables: x_var_data = [] for value in self.data[var]["values"]: x_var_data.append( [value, np.nan][str(value).lower() == "none"] ) data.append(x_var_data) data = np.array(data) bad_indices = get_index_of_nan(data) for bad_index in bad_indices[::-1]: data = np.delete(data, bad_index, 1) mrn.pop(bad_index) uid.pop(bad_index) dates.pop(bad_index) X = np.transpose(data[1:]) y = data[0] if not include_patient_info: return X, y return X, y, mrn, uid, dates def add_variable(self, variable, values, units=""): """Add a new variable to ``StatsData.data``, will not over-write Parameters ---------- variable : str variable name to be used as a key and plot title values : list values to be stored for ``variable`` units : str, optional Define units for display on plot """ if variable not in list(self.data): self.data[variable] = {"units": units, "values": values} if variable not in self.correlation_variables: self.correlation_variables.append(variable) self.correlation_variables.sort() def del_variable(self, variable): """Delete a variable from ``StatsData.data`` Parameters ---------- variable : str variable name """ if variable in list(self.data): self.data.pop(variable) if variable in self.correlation_variables: index = self.correlation_variables.index(variable) self.correlation_variables.pop(index) def set_variable_data(self, variable, data, units=None): """Replace the data for the given variable in ``StatsData.data`` Parameters ---------- variable : str variable name data : list new data units : str, optional Define units for display on plot """ self.data[variable]["values"] = data if units is not None: self.data[variable]["units"] = units def set_variable_units(self, variable, units): """Set the units for the given variable in ``StatsData.data`` Parameters ---------- variable
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import datetime from pathlib import Path from pbr import git from packaging import version as pkg_version from enum import Enum from . import settings from . import utils from . import exceptions from . import pygittools from . import wizard from . import prepare from . import logger _logger = logger.get_logger(__name__) _VERSION_REGEX = r"__version__ *= *['|\"]\S+" class ReleaseAction(Enum): MAKE_RELEASE = 'rel' REGENERATE = 'reg' def make_install(options=None, cwd='.'): _logger.info('Performing installation...') if not options or (options and options.force != 'force'): _check_repo_tree(cwd) _check_if_changes_to_commit(cwd) try: release_tag = pygittools.get_latest_tag(cwd) except pygittools.PygittoolsError as e: raise exceptions.ReleaseMetadataError(f"Retrieving release tag error: {e}", _logger) final_release_tag = _get_final_release_tag(release_tag, cwd) _run_setup_cmd(['install'], release_tag=final_release_tag, cwd=cwd) _logger.info('Installation completed.') def make_release(action=ReleaseAction.REGENERATE, prompt=True, push=True, release_data=None, options=None, cwd='.'): _logger.info('Preparing Source Distribution...') if not options or (options and options.force != 'force'): _check_repo_tree(cwd) _check_if_changes_to_commit(cwd) release_files_paths = [] config = utils.get_repo_config_from_setup_cfg(Path(cwd) / settings.FileName.SETUP_CFG) if prompt: action = _release_checkout(config) if action == ReleaseAction.MAKE_RELEASE: new_release_tag = _prompt_release_tag(cwd) new_release_msg = _prompt_release_msg(cwd) else: if action == ReleaseAction.MAKE_RELEASE: new_release_tag = release_data.tag new_release_msg = release_data.msg if action == ReleaseAction.MAKE_RELEASE: files_to_add = [] files_to_add.append(_update_project_version(config, new_release_tag, cwd)) files_to_add.append(_update_changelog(config, new_release_tag, new_release_msg, cwd)) files_to_add.append(_update_authors(config, cwd)) release_files_paths.extend(_commit_and_push_release_update(new_release_tag, new_release_msg, files_to_add=files_to_add, push=push, cwd=cwd)) release_tag = new_release_tag elif action == ReleaseAction.REGENERATE: try: release_tag = pygittools.get_latest_tag(cwd) except pygittools.PygittoolsError as e: raise exceptions.ReleaseMetadataError(f"Retrieving release tag error: {e}" f'Repository must be tagged before regenerate.', _logger) final_release_tag = _get_final_release_tag(release_tag, cwd, action) _run_setup_cmd(['sdist', 'bdist_wheel'], release_tag=final_release_tag, cwd=cwd) package_path = utils.get_latest_tarball(Path(cwd) / settings.DirName.DISTRIBUTION) if final_release_tag and final_release_tag not in package_path.name: raise exceptions.RuntimeError('Source Distribution preparing error! ' 'Sdidt package name not valid. Please try again.', _logger) _logger.info(f'Source Distribution {utils.get_rel_path(package_path, cwd)} prepared properly.') return package_path def _run_setup_cmd(cmd, release_tag=None, cwd='.'): setup_path = Path(cwd).resolve() / settings.FileName.SETUP_PY if not setup_path.exists(): raise exceptions.FileNotFoundError(f'{utils.get_rel_path(setup_path, cwd)} ' f'file not found that is necessary to the distribution process!', _logger) if release_tag: os.environ['PBR_VERSION'] = release_tag else: _logger.info('Release tag will be set by pbr automatically.') result = utils.execute_cmd([settings.Tools.PYTHON, setup_path.__str__()] + cmd, cwd) for line in result.splitlines(): _logger.info(line) def _get_final_release_tag(release_tag, cwd, action=None): if not action or (action == ReleaseAction.REGENERATE): try: tag_commit_hash = pygittools.get_tag_commit_hash(release_tag, cwd) except pygittools.PygittoolsError as e: raise exceptions.ReleaseMetadataError(f'Retrieving tag commit hash error: {e}', _logger) try: latest_commit_hash = pygittools.get_latest_commit_hash(cwd) except pygittools.PygittoolsError as e: raise exceptions.ReleaseMetadataError(f'Retrieving latest commit hash error: {e}', _logger) if tag_commit_hash == latest_commit_hash: return release_tag else: return None elif action == ReleaseAction.MAKE_RELEASE: return release_tag def _check_if_changes_to_commit(cwd): try: if pygittools.are_uncommited_changes(cwd): raise exceptions.UncommitedChangesError('There are changes to commit!', _logger) except pygittools.PygittoolsError: raise exceptions.UncommitedChangesError('Error checking if there are any changes to commit!', _logger) def _check_repo_tree(cwd): if not pygittools.is_work_tree(cwd): raise exceptions.WorkTreeNotFoundError('Git Work Tree not found! Please check ' 'if the git repository is initialized.', _logger) if not pygittools.is_any_commit(cwd): raise exceptions.NoCommitFoundError('There are no commits in repository. ' 'Please commit before release.', _logger) def _release_checkout(config): action = wizard.choose_one(__name__, 'Make Release or Regenerate a release package using the actual release metadata', choices=[ReleaseAction.MAKE_RELEASE.value, ReleaseAction.REGENERATE.value]) action = ReleaseAction.MAKE_RELEASE if action == ReleaseAction.MAKE_RELEASE.value else ReleaseAction.REGENERATE if action == ReleaseAction.MAKE_RELEASE: if not wizard.is_checkpoint_ok(__name__, 'Are you on the relevant branch?'): raise exceptions.ReleaseCheckoutError('Checkout to the proper branch!', _logger) if not wizard.is_checkpoint_ok(__name__, 'Are there any uncommited changes or files not ' 'added into the repo tree?', valid_value='n'): raise exceptions.ReleaseCheckoutError('Commit your changes!', _logger) if not wizard.is_checkpoint_ok(__name__, f'Is the {settings.FileName.README} file prepared correctly?'): raise exceptions.ReleaseCheckoutError(f'Complete {settings.FileName.README} file!', _logger) if not wizard.is_checkpoint_ok(__name__, f'Is there something that should be added to {settings.FileName.TODO} file?', valid_value='n'): raise exceptions.ReleaseCheckoutError(f'Complete {settings.FileName.TODO} file!', _logger) if config.changelog_type == settings.ChangelogType.PREPARED.value: if not wizard.is_checkpoint_ok(__name__, f'Is the {settings.FileName.CHANGELOG} file up to date?'): raise exceptions.ReleaseCheckoutError(f'Complete {settings.FileName.CHANGELOG} file!', _logger) return action def _update_project_version(config, release_tag, cwd='.'): if config.project_type == settings.ProjectType.MODULE.value: project_module_name = utils.get_module_name_with_suffix(config.project_name) file_version_path = Path(cwd).resolve() / project_module_name _update_version(file_version_path, release_tag, cwd) else: file_version_path = Path(cwd).resolve() / config.project_name / settings.FileName.PYINIT _update_version(file_version_path, release_tag, cwd) return file_version_path def _update_version(file_version_path, release_tag, cwd='.'): new_version_string = f"__version__ = '{release_tag}'" try: with open(file_version_path, 'r+t') as file: content = file.read() if not re.search(_VERSION_REGEX, content): raise exceptions.VersionNotFoundError(f'__version__ variable not found in the ' f'{utils.get_rel_path(file_version_path, cwd)} file. ' f'Please correct the file.', _logger) else: updated_content = re.sub(_VERSION_REGEX, new_version_string, content, 1) file.seek(0) file.truncate() file.write(updated_content) except FileNotFoundError: raise exceptions.FileNotFoundError(f'File {utils.get_rel_path(file_version_path, cwd)} with a __version__ ' f'variable not foud. File with the __version__ ' f'variable is searched using the project_name entry in ' f'{settings.FileName.SETUP_CFG}', _logger) def _update_changelog(config, new_release_tag, new_release_msg, cwd='.'): if config.changelog_type == settings.ChangelogType.GENERATED.value: changelog_filepath = _update_generated_changelog(config, new_release_tag, new_release_msg, cwd) else: changelog_filepath = _generate_prepared_file(config, settings.FileName.CHANGELOG, settings.FileName.CHANGELOG_PREPARED, cwd) return changelog_filepath def _update_generated_changelog(config, new_release_tag, new_release_msg, cwd='.'): _logger.info(f'Updating {settings.FileName.CHANGELOG} file...') changelog_path = Path(cwd).resolve() / settings.FileName.CHANGELOG try: changelog_content = pygittools.get_changelog( report_format='### Version: %(tag) | Released: %(taggerdate:short) \r\n%(contents)', cwd=cwd) except pygittools.PygittoolsError as e: raise exceptions.ChangelogGenerateError(f'Changelog generation error: {e}', _logger) if changelog_path.exists(): changelog_path.unlink() prepare.write_file_from_template(Path(settings.DirName.TEMPLATES) / settings.FileName.CHANGELOG_GENERATED, changelog_path, config.__dict__, cwd, verbose=False) with open(changelog_path, 'a') as file: file.write('\n') file.write(_get_changelog_entry(new_release_tag, new_release_msg)) file.write(changelog_content) _logger.info(f'{settings.FileName.CHANGELOG} file updated') return changelog_path def _get_changelog_entry(release_tag, release_msg): tagger_date = datetime.date.today().strftime('%Y-%m-%d') return f'### Version: {release_tag} | Released: {tagger_date} \n{release_msg}\n\n' def _commit_and_push_release_update(new_release_tag, new_release_msg, files_to_add=None, push=True, cwd='.', debug=None): if push: _logger.info('Commit updated release files, set tag and push...') else: _logger.info('Commit updated release files, set tag...') paths = [] for file_path in files_to_add: try: pygittools.add(file_path, cwd) except pygittools.PygittoolsError as e: raise exceptions.CommitAndPushReleaseUpdateError(f'{file_path.name} git add error: {e}', _logger) paths.append(file_path) try: pygittools.commit(settings.AUTOMATIC_RELEASE_COMMIT_MSG, cwd) except pygittools.PygittoolsError as e: raise exceptions.CommitAndPushReleaseUpdateError(f"git commit error: {e}", _logger) _logger.info('New commit with updated release files created.') try: pygittools.set_tag(new_release_tag, new_release_msg, cwd) if debug: raise pygittools.PygittoolsError('Error for debug', returncode=1) except pygittools.PygittoolsError as e: _clean_failed_release(new_release_tag, cwd) raise exceptions.ReleaseTagSetError(f"Error while setting release tag: {e}", _logger) try: new_latest_tag = pygittools.get_latest_tag(cwd) except pygittools.PygittoolsError as e: _clean_failed_release(new_release_tag, cwd) raise exceptions.ReleaseTagSetError(f"Error while check if the new release tag set properly: {e}", _logger) else: if new_latest_tag != new_release_tag: _clean_failed_release(new_release_tag, cwd) raise exceptions.ReleaseTagSetError('New release tag was set incorrectly.', _logger) _logger.info('New tag established.') if push and pygittools.is_origin_set(cwd): try: pygittools.push_with_tags(cwd) except pygittools.PygittoolsError as e: _logger.error(f"git push error: {e}") _logger.info('!!!IMPORTANT!!! Please check repository origin or credentials and push changes WITH TAGS manually! ' 'Releasing process is continued.') _logger.info('New release data commited with tag set properly.') else: _logger.info('New release data commited with tag set and pushed properly.') else: _logger.info('New release data commited with tag set properly.') return paths def _clean_failed_release(new_release_tag, cwd): _logger.warning('Revert release process.') try: pygittools.revert(1, cwd) except pygittools.PygittoolsError: raise exceptions.CriticalError('Critical Error occured when reverting an automatic last commit. ' 'Please check git log, repo tree and cleanup the mess.', _logger) latest_tag_remove_error = False try: tags = pygittools.list_tags(cwd) except pygittools.PygittoolsError: latest_tag_remove_error = True else: if new_release_tag in tags: try: pygittools.delete_tag(new_release_tag, cwd) except pygittools.PygittoolsError: latest_tag_remove_error = True if latest_tag_remove_error: raise exceptions.CriticalError('Critical Error occured when deleting an automatic latest tag. ' 'Please check git log, repo tree and cleanup the mess.', _logger) def _prompt_release_tag(cwd='.'): try: latest_release_tag = pygittools.get_latest_tag(cwd) except pygittools.PygittoolsError: _logger.tip(f'Repo has not been tagged yet. ' f'Proposed initial release tag: {settings.SUGGESTED_INITIAL_RELEASE_TAG}') is_tagged = False else: _logger.info(f'Last release tag: {latest_release_tag}') is_tagged = True is_release_tag_valid = False comparing_release_tags = True while not is_release_tag_valid: new_release_tag = input(f'Enter new release tag - <Major Version>.<Minor Version>.<Patch version> ' f'e.g. {settings.EXAMPLE_RELEASE_TAG}: ') if _is_release_tag_valid(new_release_tag): if is_tagged: if not _is_release_tag_valid(latest_release_tag): _logger.error('Latest release tag not valid!') if wizard.is_checkpoint_ok(__name__, 'Continue without comparing the ' 'new relese tag with the latest?'): comparing_release_tags = False else: raise exceptions.ReleaseTagError('Latest release tag not valid! ' 'Please remove it to continue.', _logger) if comparing_release_tags: if _is_higher_tag(latest_release_tag, new_release_tag): is_release_tag_valid = True else: _logger.error('Entered release tag less than the previous release tag! ' 'Correct and enter a new one.') else: return new_release_tag else: return new_release_tag else: _logger.error('Entered release tag not valid! Correct and enter new one.') return new_release_tag def _is_release_tag_valid(release_tag): try: normalized_version = pkg_version.Version(release_tag) except pkg_version.InvalidVersion: return False else: if str(normalized_version) == release_tag: return True else: _logger.error(f'Entered release tag not valid! Proposed release tag: {normalized_version}. ' f'Correct and enter new one.') return False def _is_higher_tag(latest_tag, new_tag): latest_tag_obj = pkg_version.Version(latest_tag) new_tag_obj = pkg_version.Version(new_tag) return new_tag_obj > latest_tag_obj def _prompt_release_msg(cwd='.'): tip_msg = f"""{settings.TIP_MSG_MARK}Below are commit messages generated from the last tag. {settings.TIP_MSG_MARK}If the last tag not exists, messages are from the first
<gh_stars>0 # flake8: noqa # type: ignore # Generated from IceSql.g4 by ANTLR 4.8 from omnibus._vendor.antlr4 import * if __name__ is not None and "." in __name__: from .IceSqlParser import IceSqlParser else: from IceSqlParser import IceSqlParser import dataclasses @dataclasses.dataclass(frozen=True) class IceSqlParserConfig: interval_units: bool = False DEFAULT_ICE_SQL_PARSER_CONFIG = IceSqlParserConfig() # This class defines a complete listener for a parse tree produced by IceSqlParser. class IceSqlListener(ParseTreeListener): # Enter a parse tree produced by IceSqlParser#singleStatement. def enterSingleStatement(self, ctx:IceSqlParser.SingleStatementContext): pass # Exit a parse tree produced by IceSqlParser#singleStatement. def exitSingleStatement(self, ctx:IceSqlParser.SingleStatementContext): pass # Enter a parse tree produced by IceSqlParser#statement. def enterStatement(self, ctx:IceSqlParser.StatementContext): pass # Exit a parse tree produced by IceSqlParser#statement. def exitStatement(self, ctx:IceSqlParser.StatementContext): pass # Enter a parse tree produced by IceSqlParser#createTable. def enterCreateTable(self, ctx:IceSqlParser.CreateTableContext): pass # Exit a parse tree produced by IceSqlParser#createTable. def exitCreateTable(self, ctx:IceSqlParser.CreateTableContext): pass # Enter a parse tree produced by IceSqlParser#colSpec. def enterColSpec(self, ctx:IceSqlParser.ColSpecContext): pass # Exit a parse tree produced by IceSqlParser#colSpec. def exitColSpec(self, ctx:IceSqlParser.ColSpecContext): pass # Enter a parse tree produced by IceSqlParser#insert. def enterInsert(self, ctx:IceSqlParser.InsertContext): pass # Exit a parse tree produced by IceSqlParser#insert. def exitInsert(self, ctx:IceSqlParser.InsertContext): pass # Enter a parse tree produced by IceSqlParser#delete. def enterDelete(self, ctx:IceSqlParser.DeleteContext): pass # Exit a parse tree produced by IceSqlParser#delete. def exitDelete(self, ctx:IceSqlParser.DeleteContext): pass # Enter a parse tree produced by IceSqlParser#select. def enterSelect(self, ctx:IceSqlParser.SelectContext): pass # Exit a parse tree produced by IceSqlParser#select. def exitSelect(self, ctx:IceSqlParser.SelectContext): pass # Enter a parse tree produced by IceSqlParser#cteSelect. def enterCteSelect(self, ctx:IceSqlParser.CteSelectContext): pass # Exit a parse tree produced by IceSqlParser#cteSelect. def exitCteSelect(self, ctx:IceSqlParser.CteSelectContext): pass # Enter a parse tree produced by IceSqlParser#cte. def enterCte(self, ctx:IceSqlParser.CteContext): pass # Exit a parse tree produced by IceSqlParser#cte. def exitCte(self, ctx:IceSqlParser.CteContext): pass # Enter a parse tree produced by IceSqlParser#setSelect. def enterSetSelect(self, ctx:IceSqlParser.SetSelectContext): pass # Exit a parse tree produced by IceSqlParser#setSelect. def exitSetSelect(self, ctx:IceSqlParser.SetSelectContext): pass # Enter a parse tree produced by IceSqlParser#setSelectItem. def enterSetSelectItem(self, ctx:IceSqlParser.SetSelectItemContext): pass # Exit a parse tree produced by IceSqlParser#setSelectItem. def exitSetSelectItem(self, ctx:IceSqlParser.SetSelectItemContext): pass # Enter a parse tree produced by IceSqlParser#setSelectKind. def enterSetSelectKind(self, ctx:IceSqlParser.SetSelectKindContext): pass # Exit a parse tree produced by IceSqlParser#setSelectKind. def exitSetSelectKind(self, ctx:IceSqlParser.SetSelectKindContext): pass # Enter a parse tree produced by IceSqlParser#parenSelect. def enterParenSelect(self, ctx:IceSqlParser.ParenSelectContext): pass # Exit a parse tree produced by IceSqlParser#parenSelect. def exitParenSelect(self, ctx:IceSqlParser.ParenSelectContext): pass # Enter a parse tree produced by IceSqlParser#primarySelect. def enterPrimarySelect(self, ctx:IceSqlParser.PrimarySelectContext): pass # Exit a parse tree produced by IceSqlParser#primarySelect. def exitPrimarySelect(self, ctx:IceSqlParser.PrimarySelectContext): pass # Enter a parse tree produced by IceSqlParser#topN. def enterTopN(self, ctx:IceSqlParser.TopNContext): pass # Exit a parse tree produced by IceSqlParser#topN. def exitTopN(self, ctx:IceSqlParser.TopNContext): pass # Enter a parse tree produced by IceSqlParser#allSelectItem. def enterAllSelectItem(self, ctx:IceSqlParser.AllSelectItemContext): pass # Exit a parse tree produced by IceSqlParser#allSelectItem. def exitAllSelectItem(self, ctx:IceSqlParser.AllSelectItemContext): pass # Enter a parse tree produced by IceSqlParser#identifierAllSelectItem. def enterIdentifierAllSelectItem(self, ctx:IceSqlParser.IdentifierAllSelectItemContext): pass # Exit a parse tree produced by IceSqlParser#identifierAllSelectItem. def exitIdentifierAllSelectItem(self, ctx:IceSqlParser.IdentifierAllSelectItemContext): pass # Enter a parse tree produced by IceSqlParser#expressionSelectItem. def enterExpressionSelectItem(self, ctx:IceSqlParser.ExpressionSelectItemContext): pass # Exit a parse tree produced by IceSqlParser#expressionSelectItem. def exitExpressionSelectItem(self, ctx:IceSqlParser.ExpressionSelectItemContext): pass # Enter a parse tree produced by IceSqlParser#expression. def enterExpression(self, ctx:IceSqlParser.ExpressionContext): pass # Exit a parse tree produced by IceSqlParser#expression. def exitExpression(self, ctx:IceSqlParser.ExpressionContext): pass # Enter a parse tree produced by IceSqlParser#binaryBooleanExpression. def enterBinaryBooleanExpression(self, ctx:IceSqlParser.BinaryBooleanExpressionContext): pass # Exit a parse tree produced by IceSqlParser#binaryBooleanExpression. def exitBinaryBooleanExpression(self, ctx:IceSqlParser.BinaryBooleanExpressionContext): pass # Enter a parse tree produced by IceSqlParser#predicatedBooleanExpression. def enterPredicatedBooleanExpression(self, ctx:IceSqlParser.PredicatedBooleanExpressionContext): pass # Exit a parse tree produced by IceSqlParser#predicatedBooleanExpression. def exitPredicatedBooleanExpression(self, ctx:IceSqlParser.PredicatedBooleanExpressionContext): pass # Enter a parse tree produced by IceSqlParser#unaryBooleanExpression. def enterUnaryBooleanExpression(self, ctx:IceSqlParser.UnaryBooleanExpressionContext): pass # Exit a parse tree produced by IceSqlParser#unaryBooleanExpression. def exitUnaryBooleanExpression(self, ctx:IceSqlParser.UnaryBooleanExpressionContext): pass # Enter a parse tree produced by IceSqlParser#cmpPredicate. def enterCmpPredicate(self, ctx:IceSqlParser.CmpPredicateContext): pass # Exit a parse tree produced by IceSqlParser#cmpPredicate. def exitCmpPredicate(self, ctx:IceSqlParser.CmpPredicateContext): pass # Enter a parse tree produced by IceSqlParser#isNullPredicate. def enterIsNullPredicate(self, ctx:IceSqlParser.IsNullPredicateContext): pass # Exit a parse tree produced by IceSqlParser#isNullPredicate. def exitIsNullPredicate(self, ctx:IceSqlParser.IsNullPredicateContext): pass # Enter a parse tree produced by IceSqlParser#betweenPredicate. def enterBetweenPredicate(self, ctx:IceSqlParser.BetweenPredicateContext): pass # Exit a parse tree produced by IceSqlParser#betweenPredicate. def exitBetweenPredicate(self, ctx:IceSqlParser.BetweenPredicateContext): pass # Enter a parse tree produced by IceSqlParser#inListPredicate. def enterInListPredicate(self, ctx:IceSqlParser.InListPredicateContext): pass # Exit a parse tree produced by IceSqlParser#inListPredicate. def exitInListPredicate(self, ctx:IceSqlParser.InListPredicateContext): pass # Enter a parse tree produced by IceSqlParser#inSelectPredicate. def enterInSelectPredicate(self, ctx:IceSqlParser.InSelectPredicateContext): pass # Exit a parse tree produced by IceSqlParser#inSelectPredicate. def exitInSelectPredicate(self, ctx:IceSqlParser.InSelectPredicateContext): pass # Enter a parse tree produced by IceSqlParser#inJinjaPredicate. def enterInJinjaPredicate(self, ctx:IceSqlParser.InJinjaPredicateContext): pass # Exit a parse tree produced by IceSqlParser#inJinjaPredicate. def exitInJinjaPredicate(self, ctx:IceSqlParser.InJinjaPredicateContext): pass # Enter a parse tree produced by IceSqlParser#likePredicate. def enterLikePredicate(self, ctx:IceSqlParser.LikePredicateContext): pass # Exit a parse tree produced by IceSqlParser#likePredicate. def exitLikePredicate(self, ctx:IceSqlParser.LikePredicateContext): pass # Enter a parse tree produced by IceSqlParser#primaryValueExpression. def enterPrimaryValueExpression(self, ctx:IceSqlParser.PrimaryValueExpressionContext): pass # Exit a parse tree produced by IceSqlParser#primaryValueExpression. def exitPrimaryValueExpression(self, ctx:IceSqlParser.PrimaryValueExpressionContext): pass # Enter a parse tree produced by IceSqlParser#unaryValueExpression. def enterUnaryValueExpression(self, ctx:IceSqlParser.UnaryValueExpressionContext): pass # Exit a parse tree produced by IceSqlParser#unaryValueExpression. def exitUnaryValueExpression(self, ctx:IceSqlParser.UnaryValueExpressionContext): pass # Enter a parse tree produced by IceSqlParser#traversalValueExpression. def enterTraversalValueExpression(self, ctx:IceSqlParser.TraversalValueExpressionContext): pass # Exit a parse tree produced by IceSqlParser#traversalValueExpression. def exitTraversalValueExpression(self, ctx:IceSqlParser.TraversalValueExpressionContext): pass # Enter a parse tree produced by IceSqlParser#castValueExpression. def enterCastValueExpression(self, ctx:IceSqlParser.CastValueExpressionContext): pass # Exit a parse tree produced by IceSqlParser#castValueExpression. def exitCastValueExpression(self, ctx:IceSqlParser.CastValueExpressionContext): pass # Enter a parse tree produced by IceSqlParser#arithValueExpression. def enterArithValueExpression(self, ctx:IceSqlParser.ArithValueExpressionContext): pass # Exit a parse tree produced by IceSqlParser#arithValueExpression. def exitArithValueExpression(self, ctx:IceSqlParser.ArithValueExpressionContext): pass # Enter a parse tree produced by IceSqlParser#traversalKey. def enterTraversalKey(self, ctx:IceSqlParser.TraversalKeyContext): pass # Exit a parse tree produced by IceSqlParser#traversalKey. def exitTraversalKey(self, ctx:IceSqlParser.TraversalKeyContext): pass # Enter a parse tree produced by IceSqlParser#functionCallExpression. def enterFunctionCallExpression(self, ctx:IceSqlParser.FunctionCallExpressionContext): pass # Exit a parse tree produced by IceSqlParser#functionCallExpression. def exitFunctionCallExpression(self, ctx:IceSqlParser.FunctionCallExpressionContext): pass # Enter a parse tree produced by IceSqlParser#caseExpression. def enterCaseExpression(self, ctx:IceSqlParser.CaseExpressionContext): pass # Exit a parse tree produced by IceSqlParser#caseExpression. def exitCaseExpression(self, ctx:IceSqlParser.CaseExpressionContext): pass # Enter a parse tree produced by IceSqlParser#intervalExpression. def enterIntervalExpression(self, ctx:IceSqlParser.IntervalExpressionContext): pass # Exit a parse tree produced by IceSqlParser#intervalExpression. def exitIntervalExpression(self, ctx:IceSqlParser.IntervalExpressionContext): pass # Enter a parse tree produced by IceSqlParser#selectExpression. def enterSelectExpression(self, ctx:IceSqlParser.SelectExpressionContext): pass # Exit a parse tree produced by IceSqlParser#selectExpression. def exitSelectExpression(self, ctx:IceSqlParser.SelectExpressionContext): pass # Enter a parse tree produced by IceSqlParser#parenExpression. def enterParenExpression(self, ctx:IceSqlParser.ParenExpressionContext): pass # Exit a parse tree produced by IceSqlParser#parenExpression. def exitParenExpression(self, ctx:IceSqlParser.ParenExpressionContext): pass # Enter a parse tree produced by IceSqlParser#castCallExpression. def enterCastCallExpression(self, ctx:IceSqlParser.CastCallExpressionContext): pass # Exit a parse tree produced by IceSqlParser#castCallExpression. def exitCastCallExpression(self, ctx:IceSqlParser.CastCallExpressionContext): pass # Enter a parse tree produced by IceSqlParser#dateExpression. def enterDateExpression(self, ctx:IceSqlParser.DateExpressionContext): pass # Exit a parse tree produced by IceSqlParser#dateExpression. def exitDateExpression(self, ctx:IceSqlParser.DateExpressionContext): pass # Enter a parse tree produced by IceSqlParser#extractExpression. def enterExtractExpression(self, ctx:IceSqlParser.ExtractExpressionContext): pass # Exit a parse tree produced by IceSqlParser#extractExpression. def exitExtractExpression(self, ctx:IceSqlParser.ExtractExpressionContext): pass # Enter a parse tree produced by IceSqlParser#jinjaExpression. def enterJinjaExpression(self, ctx:IceSqlParser.JinjaExpressionContext): pass # Exit a parse tree produced by IceSqlParser#jinjaExpression. def exitJinjaExpression(self, ctx:IceSqlParser.JinjaExpressionContext): pass # Enter a parse tree produced by IceSqlParser#simplePrimaryExpression. def enterSimplePrimaryExpression(self, ctx:IceSqlParser.SimplePrimaryExpressionContext): pass # Exit a parse tree produced by IceSqlParser#simplePrimaryExpression. def exitSimplePrimaryExpression(self, ctx:IceSqlParser.SimplePrimaryExpressionContext): pass # Enter a parse tree produced by IceSqlParser#simpleExpression. def enterSimpleExpression(self, ctx:IceSqlParser.SimpleExpressionContext): pass # Exit a parse tree produced by IceSqlParser#simpleExpression. def exitSimpleExpression(self, ctx:IceSqlParser.SimpleExpressionContext): pass # Enter a parse tree produced by IceSqlParser#typeSpec. def enterTypeSpec(self, ctx:IceSqlParser.TypeSpecContext): pass # Exit a parse tree produced by IceSqlParser#typeSpec. def exitTypeSpec(self, ctx:IceSqlParser.TypeSpecContext): pass # Enter a parse tree produced by IceSqlParser#expressionFunctionCall. def enterExpressionFunctionCall(self, ctx:IceSqlParser.ExpressionFunctionCallContext): pass # Exit a parse tree produced by IceSqlParser#expressionFunctionCall. def exitExpressionFunctionCall(self, ctx:IceSqlParser.ExpressionFunctionCallContext): pass # Enter a parse tree produced by IceSqlParser#kwargFunctionCall. def enterKwargFunctionCall(self, ctx:IceSqlParser.KwargFunctionCallContext): pass # Exit a parse tree produced by IceSqlParser#kwargFunctionCall. def exitKwargFunctionCall(self, ctx:IceSqlParser.KwargFunctionCallContext): pass # Enter a parse tree produced by IceSqlParser#nullsFunctionCall. def enterNullsFunctionCall(self, ctx:IceSqlParser.NullsFunctionCallContext): pass # Exit a parse tree produced by IceSqlParser#nullsFunctionCall. def exitNullsFunctionCall(self, ctx:IceSqlParser.NullsFunctionCallContext): pass # Enter a parse tree produced by IceSqlParser#starFunctionCall. def enterStarFunctionCall(self, ctx:IceSqlParser.StarFunctionCallContext): pass # Exit a parse tree produced by IceSqlParser#starFunctionCall. def exitStarFunctionCall(self, ctx:IceSqlParser.StarFunctionCallContext): pass # Enter a parse
# -*- coding: utf-8 -*- import pytz import re import time import openerp import openerp.service.report import uuid import collections import babel.dates from werkzeug.exceptions import BadRequest from datetime import datetime, timedelta from dateutil import parser from dateutil import rrule from dateutil.relativedelta import relativedelta from openerp import api from openerp import tools, SUPERUSER_ID from openerp.osv import fields, osv from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT from openerp.tools.translate import _ from openerp.http import request from operator import itemgetter import logging _logger = logging.getLogger(__name__) def calendar_id2real_id(calendar_id=None, with_date=False): """ Convert a "virtual/recurring event id" (type string) into a real event id (type int). E.g. virtual/recurring event id is 4-20091201100000, so it will return 4. @param calendar_id: id of calendar @param with_date: if a value is passed to this param it will return dates based on value of withdate + calendar_id @return: real event id """ if calendar_id and isinstance(calendar_id, (basestring)): res = calendar_id.split('-') if len(res) >= 2: real_id = res[0] if with_date: real_date = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT, time.strptime(res[1], "%Y%m%d%H%M%S")) start = datetime.strptime(real_date, DEFAULT_SERVER_DATETIME_FORMAT) end = start + timedelta(hours=with_date) return (int(real_id), real_date, end.strftime(DEFAULT_SERVER_DATETIME_FORMAT)) return int(real_id) return calendar_id and int(calendar_id) or calendar_id def get_real_ids(ids): if isinstance(ids, (basestring, int, long)): return calendar_id2real_id(ids) if isinstance(ids, (list, tuple)): return [calendar_id2real_id(id) for id in ids] class calendar_attendee(osv.Model): """ Calendar Attendee Information """ _name = 'calendar.attendee' _rec_name = 'cn' _description = 'Attendee information' def _compute_data(self, cr, uid, ids, name, arg, context=None): """ Compute data on function fields for attendee values. @param ids: list of calendar attendee's IDs @param name: name of field @return: dictionary of form {id: {'field Name': value'}} """ name = name[0] result = {} for attdata in self.browse(cr, uid, ids, context=context): id = attdata.id result[id] = {} if name == 'cn': if attdata.partner_id: result[id][name] = attdata.partner_id.name or False else: result[id][name] = attdata.email or '' return result STATE_SELECTION = [ ('needsAction', 'Needs Action'), ('tentative', 'Uncertain'), ('declined', 'Declined'), ('accepted', 'Accepted'), ] _columns = { 'state': fields.selection(STATE_SELECTION, 'Status', readonly=True, help="Status of the attendee's participation"), 'cn': fields.function(_compute_data, string='Common name', type="char", multi='cn', store=True), 'partner_id': fields.many2one('res.partner', 'Contact', readonly="True"), 'email': fields.char('Email', help="Email of Invited Person"), 'availability': fields.selection([('free', 'Free'), ('busy', 'Busy')], 'Free/Busy', readonly="True"), 'access_token': fields.char('Invitation Token'), 'event_id': fields.many2one('calendar.event', 'Meeting linked', ondelete='cascade'), } _defaults = { 'state': 'needsAction', } def copy(self, cr, uid, id, default=None, context=None): raise osv.except_osv(_('Warning!'), _('You cannot duplicate a calendar attendee.')) def onchange_partner_id(self, cr, uid, ids, partner_id, context=None): """ Make entry on email and availability on change of partner_id field. @param partner_id: changed value of partner id """ if not partner_id: return {'value': {'email': ''}} partner = self.pool['res.partner'].browse(cr, uid, partner_id, context=context) return {'value': {'email': partner.email}} def get_ics_file(self, cr, uid, event_obj, context=None): """ Returns iCalendar file for the event invitation. @param event_obj: event object (browse record) @return: .ics file content """ res = None def ics_datetime(idate, allday=False): if idate: if allday: return openerp.fields.Date.from_string(idate) else: return openerp.fields.Datetime.from_string(idate).replace(tzinfo=pytz.timezone('UTC')) return False try: # FIXME: why isn't this in CalDAV? import vobject except ImportError: return res cal = vobject.iCalendar() event = cal.add('vevent') if not event_obj.start or not event_obj.stop: raise osv.except_osv(_('Warning!'), _("First you have to specify the date of the invitation.")) event.add('created').value = ics_datetime(time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)) event.add('dtstart').value = ics_datetime(event_obj.start, event_obj.allday) event.add('dtend').value = ics_datetime(event_obj.stop, event_obj.allday) event.add('summary').value = event_obj.name if event_obj.description: event.add('description').value = event_obj.description if event_obj.location: event.add('location').value = event_obj.location if event_obj.rrule: event.add('rrule').value = event_obj.rrule if event_obj.alarm_ids: for alarm in event_obj.alarm_ids: valarm = event.add('valarm') interval = alarm.interval duration = alarm.duration trigger = valarm.add('TRIGGER') trigger.params['related'] = ["START"] if interval == 'days': delta = timedelta(days=duration) elif interval == 'hours': delta = timedelta(hours=duration) elif interval == 'minutes': delta = timedelta(minutes=duration) trigger.value = delta valarm.add('DESCRIPTION').value = alarm.name or 'Odoo' for attendee in event_obj.attendee_ids: attendee_add = event.add('attendee') attendee_add.value = 'MAILTO:' + (attendee.email or '') res = cal.serialize() return res def _send_mail_to_attendees(self, cr, uid, ids, email_from=tools.config.get('email_from', False), template_xmlid='calendar_template_meeting_invitation', force=False, context=None): """ Send mail for event invitation to event attendees. @param email_from: email address for user sending the mail @param force: If set to True, email will be sent to user himself. Usefull for example for alert, ... """ res = False if self.pool['ir.config_parameter'].get_param(cr, uid, 'calendar.block_mail', default=False) or context.get("no_mail_to_attendees"): return res mail_ids = [] data_pool = self.pool['ir.model.data'] mailmess_pool = self.pool['mail.message'] mail_pool = self.pool['mail.mail'] template_pool = self.pool['email.template'] local_context = context.copy() color = { 'needsAction': 'grey', 'accepted': 'green', 'tentative': '#FFFF00', 'declined': 'red' } if not isinstance(ids, (tuple, list)): ids = [ids] dummy, template_id = data_pool.get_object_reference(cr, uid, 'calendar', template_xmlid) dummy, act_id = data_pool.get_object_reference(cr, uid, 'calendar', "view_calendar_event_calendar") local_context.update({ 'color': color, 'action_id': self.pool['ir.actions.act_window'].search(cr, uid, [('view_id', '=', act_id)], context=context)[0], 'dbname': cr.dbname, 'base_url': self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url', default='http://localhost:8069', context=context) }) for attendee in self.browse(cr, uid, ids, context=context): if attendee.email and email_from and (attendee.email != email_from or force): ics_file = self.get_ics_file(cr, uid, attendee.event_id, context=context) mail_id = template_pool.send_mail(cr, uid, template_id, attendee.id, context=local_context) vals = {} if ics_file: vals['attachment_ids'] = [(0, 0, {'name': 'invitation.ics', 'datas_fname': 'invitation.ics', 'datas': str(ics_file).encode('base64')})] vals['model'] = None # We don't want to have the mail in the tchatter while in queue! the_mailmess = mail_pool.browse(cr, uid, mail_id, context=context).mail_message_id mailmess_pool.write(cr, uid, [the_mailmess.id], vals, context=context) mail_ids.append(mail_id) if mail_ids: res = mail_pool.send(cr, uid, mail_ids, context=context) return res def onchange_user_id(self, cr, uid, ids, user_id, *args, **argv): """ Make entry on email and availability on change of user_id field. @param ids: list of attendee's IDs @param user_id: changed value of User id @return: dictionary of values which put value in email and availability fields """ if not user_id: return {'value': {'email': ''}} user = self.pool['res.users'].browse(cr, uid, user_id, *args) return {'value': {'email': user.email, 'availability': user.availability}} def do_tentative(self, cr, uid, ids, context=None, *args): """ Makes event invitation as Tentative. @param ids: list of attendee's IDs """ return self.write(cr, uid, ids, {'state': 'tentative'}, context) def do_accept(self, cr, uid, ids, context=None, *args): """ Marks event invitation as Accepted. @param ids: list of attendee's IDs """ if context is None: context = {} meeting_obj = self.pool['calendar.event'] res = self.write(cr, uid, ids, {'state': 'accepted'}, context) for attendee in self.browse(cr, uid, ids, context=context): meeting_obj.message_post(cr, uid, attendee.event_id.id, body=_(("%s has accepted invitation") % (attendee.cn)), subtype="calendar.subtype_invitation", context=context) return res def do_decline(self, cr, uid, ids, context=None, *args): """ Marks event invitation as Declined. @param ids: list of calendar attendee's IDs """ if context is None: context = {} meeting_obj = self.pool['calendar.event'] res = self.write(cr, uid, ids, {'state': 'declined'}, context) for attendee in self.browse(cr, uid, ids, context=context): meeting_obj.message_post(cr, uid, attendee.event_id.id, body=_(("%s has declined invitation") % (attendee.cn)), subtype="calendar.subtype_invitation", context=context) return res def create(self, cr, uid, vals, context=None): if context is None: context = {} if not vals.get("email") and vals.get("cn"): cnval = vals.get("cn").split(':') email = filter(lambda x: x.__contains__('@'), cnval) vals['email'] = email and email[0] or '' vals['cn'] = vals.get("cn") res = super(calendar_attendee, self).create(cr, uid, vals, context=context) return res class res_partner(osv.Model): _inherit = 'res.partner' _columns = { 'calendar_last_notif_ack': fields.datetime('Last notification marked as read from base Calendar'), } def get_attendee_detail(self, cr, uid, ids, meeting_id, context=None): """ Return a list of tuple (id, name, status) Used by web_calendar.js : Many2ManyAttendee """ datas = [] meeting = None if meeting_id: meeting = self.pool['calendar.event'].browse(cr, uid, get_real_ids(meeting_id), context=context) for partner in self.browse(cr, uid, ids, context=context): data = self.name_get(cr, uid, [partner.id], context)[0] if meeting: for attendee in meeting.attendee_ids: if attendee.partner_id.id == partner.id: data = (data[0], data[1], attendee.state) datas.append(data) return datas def _set_calendar_last_notif_ack(self, cr, uid, context=None): partner = self.pool['res.users'].browse(cr, uid, uid, context=context).partner_id self.write(cr, uid, partner.id, {'calendar_last_notif_ack': datetime.now()}, context=context) return class calendar_alarm_manager(osv.AbstractModel): _name = 'calendar.alarm_manager' def get_next_potential_limit_alarm(self, cr, uid, seconds, notif=True, mail=True, partner_id=None, context=None): res = {} base_request = """ SELECT cal.id, cal.start - interval '1' minute * calcul_delta.max_delta AS first_alarm, CASE WHEN cal.recurrency THEN cal.final_date - interval '1' minute * calcul_delta.min_delta ELSE cal.stop - interval '1' minute * calcul_delta.min_delta END as last_alarm, cal.start as first_event_date, CASE WHEN cal.recurrency THEN cal.final_date ELSE cal.stop END as last_event_date, calcul_delta.min_delta, calcul_delta.max_delta, cal.rrule AS rule FROM calendar_event AS cal RIGHT JOIN ( SELECT rel.calendar_event_id, max(alarm.duration_minutes) AS max_delta,min(alarm.duration_minutes) AS min_delta FROM calendar_alarm_calendar_event_rel AS rel LEFT JOIN calendar_alarm AS alarm ON alarm.id = rel.calendar_alarm_id WHERE alarm.type in %s GROUP BY rel.calendar_event_id ) AS calcul_delta ON calcul_delta.calendar_event_id = cal.id """ filter_user = """ RIGHT JOIN calendar_event_res_partner_rel AS part_rel ON part_rel.calendar_event_id = cal.id AND part_rel.res_partner_id = %s """ #Add filter on type type_to_read = () if notif: type_to_read
from __future__ import annotations from collections import OrderedDict from datetime import datetime from decimal import Decimal from typing import TYPE_CHECKING, Final, Iterable, List, Tuple import colors from nation import ALL_NATIONS, Nation from starship import Starship if TYPE_CHECKING: from game_data import GameData def evaluate_ships(ships:Iterable[Starship]): """This is a pretyy complex function. It looks at the score values of the iterable of starships that was passed in and evaluate them. Idealy, it would check to see what the mission objective is to know how to score them. For example, for the mission objective was to find derlict ships and capture them befre the enemy could destroy them, then it would devide the iterable into three lists. The first list is for captured ship. These would be scored based on the condition they were in. The second list would be for ship that are still delrict. Pherhaps these would be treated as failures on the players fart for failing to capture them, and be scored at zero, or perhaps they woiuld be scored at half their condition. Finally the ships that were destroyed would be scored at zero. Args: ships (Iterable[Starship]): Ad itterable of Starship objects Returns: [tuple[float]]: total_ships, number_of_alive_ships, number_of_captured_ships, number_of_derlict_ships, number_of_destroyed_ships, highest_possible_score, total_alive_ships_scores, total_captured_ships_scores, total_derlict_ship_scores, total_destroyed_ship_scores """ total_ships = len(ships) _highest_possible_score = [ship.calculate_ship_stragic_value()[0] for ship in ships] highest_possible_score = sum(_highest_possible_score) _alive_ships = [ship for ship in ships if ship.ship_status.is_active] alive_ships = [ship for ship in _alive_ships if not ship.ship_is_captured] number_of_alive_ships = len(alive_ships) captured_ships = [ship for ship in _alive_ships if ship.ship_is_captured] number_of_captured_ships = len(captured_ships) destroyed_ships = [ship for ship in ships if ship.ship_status.is_destroyed] number_of_destroyed_ships = len(destroyed_ships) derlict_ships = [ship for ship in ships if ship.ship_status.is_recrewable] number_of_derlict_ships = len(derlict_ships) _alive_ships_scores = ( (ship.calculate_ship_stragic_value()) for ship in alive_ships ) alive_ships_scores = tuple( ship[1] for ship in _alive_ships_scores ) _captured_ships_scores = ( (ship.calculate_ship_stragic_value()) for ship in captured_ships ) captured_ships_scores = tuple( ship[1] for ship in _captured_ships_scores ) _derlict_ship_scores = ( (ship.calculate_ship_stragic_value(value_multiplier_for_derlict=1.0)) for ship in derlict_ships ) derlict_ship_scores = tuple( ship[1] for ship in _derlict_ship_scores ) destroyed_ship_scores = tuple( (ship.calculate_ship_stragic_value(value_multiplier_for_destroyed=0.0)[0]) for ship in destroyed_ships ) total_alive_ships_scores = sum(alive_ships_scores) total_captured_ships_scores = sum(captured_ships_scores) total_derlict_ship_scores = sum(derlict_ship_scores) total_destroyed_ship_scores = sum(destroyed_ship_scores) return ( total_ships, number_of_alive_ships, number_of_captured_ships, number_of_derlict_ships, number_of_destroyed_ships, highest_possible_score, total_alive_ships_scores, total_captured_ships_scores, total_derlict_ship_scores, total_destroyed_ship_scores ) def join_strings(strings:Iterable[str]): a = strings[-1] rest = strings[:-1] n = rest + ["and " + a] return ", ".join(n) class ScenerioEvaluation: @staticmethod def is_game_over(game_data:GameData): return not game_data.player.ship_status.is_active or game_data.is_time_up @staticmethod def generate_evaluation(game_data:GameData) -> Tuple[str, List[Tuple[str,str,Tuple[int,int,int]]]]: raise NotImplementedError @staticmethod def describe(amount:float, destroy_ship_classes:Iterable[str], protect_ship_classes:Iterable[str], capture_ship_classes:Iterable[str]): raise NotImplementedError @staticmethod def _the_player_did_bad_stuff( *, planets_depopulated:int, planets_angered:int, times_hit_prewarp_planet:int, prewarp_planets_depopulated:int, times_hit_poipulated_planet:int, player_nation:Nation ) -> List[str]: endingText = [] if planets_depopulated > 0: if planets_depopulated == 1: how_many_planets_killed = "a" elif planets_depopulated == 2: how_many_planets_killed = "two" elif planets_depopulated == 3: how_many_planets_killed = "three" else: how_many_planets_killed = "four" if planets_depopulated == 4 else "multiple" endingText.append( f"Your ship records indcated that torpedos fired from your ship were the cause of the destruction of \ {how_many_planets_killed} ," ) if planets_angered > 0: endingText.append("civilizations,") if planets_depopulated == planets_angered: how_many_planets_angered = "all" elif planets_angered == 1: how_many_planets_angered = "one" elif planets_angered == 2: how_many_planets_angered = "two" elif planets_angered == 3: how_many_planets_angered = "three" else: how_many_planets_angered = "four" if planets_angered == 4 else "many" endingText.append( f"{how_many_planets_angered} of which had good relations with the {player_nation.name_short} until you fired on them." ) else: endingText.append("civilizations.") if prewarp_planets_depopulated > 0: if prewarp_planets_depopulated == planets_depopulated: how_many_prewarp_planets_killed = "all" elif prewarp_planets_depopulated == 1: how_many_prewarp_planets_killed = "one" elif prewarp_planets_depopulated == 2: how_many_prewarp_planets_killed = "two" elif prewarp_planets_depopulated == 3: how_many_prewarp_planets_killed = "three" else: how_many_prewarp_planets_killed = "four" if planets_depopulated == 4 else "numerous" endingText.append( f"Horrifyingly, {how_many_prewarp_planets_killed} of those planets were prewarp civilizations." ) return endingText class DestroyEvaluation(ScenerioEvaluation): @staticmethod def is_game_over(game_data: GameData): return ScenerioEvaluation.is_game_over(game_data) or not [ ship for ship in game_data.target_enemy_ships if ship.ship_status.is_active or ship.ship_status.is_recrewable ] @staticmethod def describe(amount:float, destroy_ship_classes:Iterable[str], protect_ship_classes:Iterable[str], capture_ship_classes:Iterable[str]): return f"To win, the player must disable, capture, destroy or damage at least {amount:.%} of the following ship classes: {join_strings(destroy_ship_classes)}." @staticmethod def generate_evaluation(game_data: GameData): ending_text = [] #total_ships = len(gameDataGlobal.total_starships) - 1 all_enemy_ships = [ ship for ship in game_data.all_enemy_ships if not ship.is_mission_critical ] all_mission_critical_enemy_ships = game_data.target_enemy_ships total_ships, number_of_alive_ships, number_of_captured_ships, number_of_derlict_ships, number_of_destroyed_ships, highest_possible_score, total_alive_ships_scores, total_captured_ships_scores, total_derlict_ships_scores, total_destroyed_ships_scores = evaluate_ships(all_mission_critical_enemy_ships) alive_score_percentage = total_alive_ships_scores / highest_possible_score victory_percentage = 1 - alive_score_percentage destruction_score = total_destroyed_ships_scores + ( highest_possible_score - ( total_alive_ships_scores + total_captured_ships_scores + total_derlict_ships_scores ) ) minor_victory_percent = game_data.scenerio.victory_percent minor_defeat_percent = minor_victory_percent * 0.5 major_victory_percent = minor_victory_percent + (1 - minor_victory_percent) * 0.5 if destruction_score >= major_victory_percent: score_color =colors.green elif destruction_score >= minor_victory_percent: score_color = colors.lime else: score_color = colors.orange if destruction_score >= minor_defeat_percent else colors.red bonus_total_ships, bonus_number_of_alive_ships, bonus_number_of_captured_ships, bonus_number_of_derlict_ships, bonus_number_of_destroyed_ships, bonus_highest_possible_score, bonus_total_alive_ships_scores, bonus_total_captured_ships_scores, bonus_total_derlict_ships_scores, bonus_total_destroyed_ships_scores = evaluate_ships(all_enemy_ships) friendy_total_ships, number_of_alive_friendly_ships, number_of_captured_friendly_ships, number_of_derlict_friendy_ships, number_of_destroyed_friendy_ships, highest_possible_friendy_score, total_alive_friendy_ships_scores, total_captured_friendy_ships_scores, total_derlict_friendy_ships_scores, total_destroyed_friendy_ships_scores = evaluate_ships(game_data.all_allied_ships) evaluation_list:List[Tuple[str,str,Tuple[int,int,int]]] = [ ("Total Target Enemy Ships:", f"{total_ships:.2%}", colors.white), ("Percent of Target ships Survived:", f"{number_of_alive_ships / total_ships:.2%}", colors.red ), ("Percent of Target Ships Destroyed:", f"{number_of_destroyed_ships / total_ships:.2%}", score_color), ("Percent of Target Ships Captured:", f"{number_of_captured_ships / total_ships:.2%}", score_color), ("Percent of Target Ships Disabled:", f"{number_of_derlict_ships / total_ships:.2%}", score_color), ("Highest Possible Score:", f"{highest_possible_score:.2f}", colors.white), ("Total Victory Score:", f"{destruction_score:.2f}", score_color), ("Destruction Score:", f"{total_destroyed_ships_scores:.2f}", score_color), ("Captured Ship Score:", f"{total_captured_ships_scores:.2f}", score_color), ("Disabled Ship Score:", f"{total_derlict_ships_scores:.2f}", score_color), ("Points Remaining:", f"{total_alive_ships_scores:.2f}", colors.red) ] if bonus_total_ships > 0: evaluation_list.extend( [ ("Total Extra Enemy Ships:", f"{bonus_total_ships}", colors.white), ( "Percent of Bonus Ships Survived:", f"{bonus_number_of_alive_ships / bonus_total_ships:.2%}", colors.orange ), ( "Percent of Bonus Ships Destroyed:", f"{bonus_number_of_destroyed_ships / bonus_total_ships:.2%}", colors.lime ), ( "Percent of Bonus Ships Captured:", f"{bonus_number_of_captured_ships / bonus_total_ships:.2%}", colors.lime ), ( "Percent of Bonus Ships Captured:", f"{bonus_number_of_derlict_ships / bonus_total_ships:.2%}", colors.lime ), ("Highest Possible Bonus Score:", f"{bonus_highest_possible_score:.2f}", colors.white), ("Bonus Destruction Score:", f"{bonus_total_destroyed_ships_scores:.2f}", colors.lime), ("Bonus Captured Ship Score:", f"{bonus_total_captured_ships_scores:.2f}", colors.lime), ("Bonus Disabled Ship Score:", f"{bonus_total_derlict_ships_scores:.2f}", colors.lime), ("Bonus Points Remaining:", f"{bonus_total_alive_ships_scores:.2f}", colors.white) ] ) if friendy_total_ships > 0: evaluation_list.extend( [ ("Total Allied Ships:", f"{friendy_total_ships}", colors.white), ( "Percent of Allied Ships Survived:", f"{number_of_alive_friendly_ships / friendy_total_ships:.2%}", colors.green ), ( "Percent of Allied Ships Destroyed:", f"{1 - (number_of_alive_friendly_ships / friendy_total_ships):.2%}", colors.orange ), ( "Percent of Allied Ships Captured:", f"{number_of_captured_friendly_ships / friendy_total_ships:.2%}", colors.orange ), ( "Percent of Allied Ships Captured:" f"{number_of_derlict_friendy_ships / friendy_total_ships:.2%}", colors.orange ), ("Highest Possible Allied Loss Score:", f"{highest_possible_friendy_score:.2f}", colors.red), ("Allied Destruction Score:", f"{total_destroyed_friendy_ships_scores:.2f}", colors.lime), ("Allied Captured Ship Score:", f"{total_captured_friendy_ships_scores:.2f}", colors.lime), ("Allied Disabled Ship Score:", f"{total_derlict_friendy_ships_scores:.2f}", colors.lime), ("Loss Points Remaining:", f"{total_alive_friendy_ships_scores:.2f}", colors.green) ] ) planets_angered = game_data.player_record["planets_angered"] planets_depopulated = game_data.player_record["planets_depopulated"] prewarp_planets_depopulated = game_data.player_record["prewarp_planets_depopulated"] times_hit_planet = game_data.player_record["times_hit_planet"] times_hit_poipulated_planet = game_data.player_record["times_hit_poipulated_planet"] times_hit_prewarp_planet = game_data.player_record["times_hit_prewarp_planet"] did_the_player_do_bad_stuff = times_hit_poipulated_planet > 0 time_used = game_data.date_time - game_data.scenerio.startdate time_left = game_data.scenerio.enddate - game_data.date_time starting_stardate = game_data.starting_stardate ending_stardate = game_data.ending_stardate - starting_stardate current_stardate = game_data.stardate - starting_stardate used_time = current_stardate - starting_stardate max_time = ending_stardate - starting_stardate time_left_percent = used_time / max_time evaluation_list.extend( [ ( "Friendly Planets Angered:", f'{planets_angered}', colors.red if planets_angered else colors.green ), ( "Total Planets Depopulated:", f'{planets_depopulated}', colors.red if planets_depopulated else colors.green ), ( "Prewarp Planets Depopulated:", f'{prewarp_planets_depopulated}', colors.red if prewarp_planets_depopulated else colors.green ), ( "No. of Planetary Torpedo Hits:", f'{times_hit_planet}', colors.white ), ( "No. of Polulated Planetary Torpedo Hits:", f'{times_hit_poipulated_planet}', colors.red if times_hit_poipulated_planet else colors.green ), ( "No. of Wrewarp Planetary Torpedo Hits:", f'{times_hit_prewarp_planet}', colors.red if times_hit_prewarp_planet else colors.green ), ( "Time Used:", f"{time_used}", colors.white ), ( "Time Left:", f"{time_left}", colors.white ) ] ) player_nation = game_data.scenerio.your_nation player_nation_short = player_nation.name_short captain_rank_name = player_nation.captain_rank_name comander_rank_name = player_nation.comander_rank_name navy_name = player_nation.navy_name enemy_nation = game_data.scenerio.main_enemy_nation enemy_nation_name_short = enemy_nation.name_short enemy_nation_posessive = enemy_nation.name_possesive command = player_nation.command_name intel_name = player_nation.intelligence_agency congrats_text = player_nation.congrats_text all_enemy_ships_destroyed = number_of_alive_ships == 0 no_enemy_losses
distance (on the matrix-level).""" num = F @ F.T l2_norms = np.linalg.norm(F, axis=1) # compute vector l2-norm across rows denom = np.outer(l2_norms, l2_norms) cos_mat = (num / denom).clip(min=a_min, max=a_max) return cos_mat def compute_rdm(F: np.ndarray, method: str) -> np.ndarray: """Compute representational dissimilarity matrix based on some distance measure. Parameters ---------- F : ndarray Input array. Feature matrix of size n x m, where n corresponds to the number of observations and m is the number of latent dimensions. method : str Distance metric (e.g., correlation, cosine). Returns ------- output : ndarray Returns the representational dissimilarity matrix. """ methods = ['correlation', 'cosine', 'euclidean', 'gaussian'] assert method in methods, f'\nMethod to compute RDM must be one of {methods}.\n' if method == 'euclidean': rdm = squareform(pdist(F, method)) return rdm else: if method == 'correlation': rsm = correlation_matrix(F) elif method == 'cosine': rsm = cosine_matrix(F) elif method == 'gaussian': rsm = gaussian_kernel(F) return 1 - rsm def correlate_rdms( rdm_1: np.ndarray, rdm_2: np.ndarray, correlation: str='pearson', ) -> float: """Correlate the upper triangular parts of two distinct RDMs. Parameters ---------- rdm_1 : ndarray First RDM. rdm_2 : ndarray Second RDM. correlation : str Correlation coefficient (e.g., Spearman, Pearson). Returns ------- output : float Returns the correlation coefficient of the two RDMs. """ triu_inds = np.triu_indices(len(rdm_1), k=1) corr_func = getattr(scipy.stats, ''.join((correlation, 'r'))) rho = corr_func(rdm_1[triu_inds], rdm_2[triu_inds])[0] return rho def plot_rdm( out_path: str, F: np.ndarray, method: str='correlation', format: str='.png', colormap: str='cividis', show_plot: bool=False, ) -> None: """Compute and plot representational dissimilarity matrix based on some distance measure. Parameters ---------- out_path : str Output directory. Directory where to store plots. F : ndarray Input array. Feature matrix of size n x m, where n corresponds to the number of observations and m is the number of latent dimensions. method : str Distance metric (e.g., correlation, cosine). format : str Image format in which to store visualized RDM. colormap : str Colormap for visualization of RDM. show_plot : bool Whether to show visualization of RDM after storing it to disk. Returns ------- output : ndarray Returns the representational dissimilarity matrix. """ rdm = compute_rdm(F, method) plt.figure(figsize=(10, 4), dpi=200) plt.imshow(rankdata(rdm).reshape(rdm.shape), cmap=getattr(plt.cm, colormap)) plt.xticks([]) plt.yticks([]) plt.tight_layout() if not os.path.exists(out_path): print(f'\n...Output directory did not exists. Creating directories.\n') os.makedirs(out_path) plt.savefig(os.path.join(out_path, ''.join(('rdm', format)))) if show_plot: plt.show() plt.close() # ############################## # # BOOTSTRAPPING HELPER FUNCTIONS # # ############################## # def compute_pval_(human_correlations: dict, model_i: str, model_j: str) -> float: model_i_corrs = np.asarray(human_correlations[model_i]) model_j_corrs = np.asarray(human_correlations[model_j]) p_val = 1 - np.mean([model_i_corr > model_j_corr for model_i_corr, model_j_corr in zip(model_i_corrs, model_j_corrs)]) return p_val.round(3) def bootstrap_( features_i: np.ndarray, features_j: np.ndarray, model_i: str, model_j: str, human_rdm: np.ndarray, n_bootstraps: int=1000, dissimilarity: str='correlation', correlation: str='pearson', ) -> Tuple[Dict[str, list], float]: """Randomly sample with replacement (resampled dataset must be of equal size to the original, observed dataset)""" human_correlations = defaultdict(list) N = features_i.shape[0] for _ in range(n_bootstraps): resample_i = np.random.choice(np.arange(N), size=N, replace=True) resample_j = np.random.choice(np.arange(N), size=N, replace=True) rdm_i = compute_rdm(features_i[resample_i], dissimilarity) rdm_j = compute_rdm(features_j[resample_j], dissimilarity) human_rdm_resample_i = human_rdm[resample_i] human_rdm_resample_i = human_rdm_resample_i[:, resample_i] human_rdm_resample_j = human_rdm[resample_j] human_rdm_resample_j = human_rdm_resample_j[:, resample_j] human_corr_i = correlate_rdms(human_rdm_resample_i, rdm_i, correlation) human_corr_j = correlate_rdms(human_rdm_resample_j, rdm_j, correlation) human_correlations[model_i].append(human_corr_i) human_correlations[model_j].append(human_corr_j) return human_correlations def get_features( root: str, out_path: str, model_names: List[str], module_names: List[str], clip: List[bool], pretrained: bool, batch_size: int, flatten_acts: bool, ) -> Dict[str, Dict[str, np.ndarray]]: """Extract features for a list of neural network models and corresponding modules. Parameters ---------- root : str Root directory. Directory where images are stored. out_path : str PATH where order of images features should be stored. Files are alphabetically sorted and features are extracted accordingly. model_names : List[str] List of neural network models for which features should be extracted. module_names : List[str] List of neural network layers for which features should be extracted. Modules must correspond to models. This should be thought of as zipped lists. clip : List[bool] List of Booleans which indicates whether the corresponding model in the <model_names> list is a CLIP-based model or not (i.e., True if CLIP, else False) pretrained : bool Whether pretrained or randomly initialized models should be loaded into memory. batch_size : int Integer value that determines the number of images within a single mini-batch (i.e., subsample of the data). flatten_acts : bool Whether activation tensor (e.g., activations from an early layer of the neural network model) should be transformed into a feature vector. Returns ------- output : Dict[str, Dict[str, np.ndarray]] Returns a dictionary of feature matrices corresponding to the selected models and layers. """ device = 'cuda' if torch.cuda.is_available() else 'cpu' model_features = defaultdict(dict) for i, model_name in enumerate(model_names): model, transforms = load_model(model_name, pretrained=pretrained, model_path=None, device=device) dl = load_dl(root, out_path=out_path, batch_size=batch_size, transforms=transforms) features, _ = extract_features(model, dl, module_names[i], batch_size=batch_size, flatten_acts=flatten_acts, device=device, clip=clip[i]) model_features[model_name][module_names[i]] = features return model_features def compare_models_to_humans( root: str, out_path: str, model_names: List[str], module_names: List[str], clip: List[bool], pretrained: bool, batch_size: int, flatten_acts: bool, human_rdm: np.ndarray, save_features: bool=True, n_bootstraps: int=1000, dissimilarity: str='correlation', correlation: str='pearson', ) -> Dict[Tuple[str, str], Dict[Tuple[str, str], str]]: # extract features for each model and its corresponding module model_features = get_features( root, out_path, model_names, module_names, pretrained, batch_size, flatten_acts, clip, ) # save model features to disc if save_features: pickle_file_(model_features, out_path, 'features') # compare features of each model combination for N bootstraps scores = defaultdict(lambda: defaultdict(dict)) model_combs = list(itertools.combinations(model_names, 2)) for (model_i, model_j) in model_combs: module_i = module_names[model_names.index(model_i)] module_j = module_names[model_names.index(model_j)] features_i = model_features[model_i][module_i] features_j = model_features[model_j][module_j] human_correlations = bootstrap_( features_i=features_i, features_j=features_j, model_i=model_i, model_j=model_j, human_rdm=human_rdm, n_bootstraps=n_bootstraps, dissimilarity=dissimilarity, correlation=correlation, ) mean_human_corrs = (np.mean(human_correlations[model_i]), np.mean(human_correlations[model_j])) scores[(model_i, model_j)][(module_i, module_j)]['human_corrs'] = (human_correlations[model_i], human_correlations[model_j]) scores[(model_i, model_j)][(module_i, module_j)]['mean_human_corrs'] = mean_human_corrs return scores def compare_models( root: str, out_path: str, model_names: List[str], module_names: List[str], pretrained: bool, batch_size: int, flatten_acts: bool, clip: List[bool], save_features: bool=True, dissimilarity: str='correlation', correlation: str='pearson', ) -> pd.DataFrame: """Compare object representations of different models against each other. Parameters ---------- root : str Root directory. Directory from where to load images. out_path : str Output directory. Directory where to store features corresponding to each neural network model. model_names : List[str] List of neural network models whose object representations should be compared against. module_names : List[str] List of neural network layers for which features should be extracted. Modules must correspond to models. This should be thought of as zipped lists. pretrained : bool Whether pretrained or randomly initialized models should be loaded into memory. batch_size : int Integer value that determines the number of images within a single mini-batch (i.e., subsample of the data). flatten_acts : bool Whether activation tensor (e.g., activations from an early layer of the neural network model) should be transformed into a feature vector. clip : List[bool] List of Booleans which indicates whether the corresponding model in the <model_names> list is a CLIP-based model or not (i.e., True if CLIP, else False) save_features : bool Whether to save model features or solely compare their representations against each other without saving the features to disk. dissimilarity : str Distance metric to be used to compute RDMs corresponding to the model features. correlation : str Correlation coefficient (e.g., Spearman or Pearson) to be used when performing RSA. Returns ------- output : pd.DataFrame Returns a correlation matrix whose rows and columns correspond to the names of the models in <model_names>. The cell elements are the correlation coefficients for each model combination. The dataframe can subsequently be converted into a heatmap with matplotlib or seaborn. """ # extract features for each model and corresponding module model_features = get_features( root=root, out_path=out_path, model_names=model_names, module_names=module_names, clip=clip, pretrained=pretrained, batch_size=batch_size, flatten_acts=flatten_acts, ) # save model features to disc if save_features: pickle_file_(model_features, out_path, 'features') # compare features of each model combination for N bootstraps corrs = pd.DataFrame(np.eye(len(model_names)), index=np.arange(len(model_names)), columns=model_names, dtype=float) model_combs = list(itertools.combinations(model_names, 2)) for (model_i, model_j) in model_combs: module_i = module_names[model_names.index(model_i)] module_j = module_names[model_names.index(model_j)] features_i = model_features[model_i][module_i] features_j = model_features[model_j][module_j] rdm_i = compute_rdm(features_i, dissimilarity) rdm_j = compute_rdm(features_j, dissimilarity) corr = correlate_rdms(rdm_i, rdm_j, correlation) corrs.loc[model_names.index(model_i), model_j] = corr corrs.loc[model_names.index(model_j), model_i] = corr corrs['model_names'] = corrs.columns.to_list() corrs.set_index('model_names', inplace=True, drop=True) return corrs def pickle_file_(file: dict, out_path: str, f_name: str)
= ul[0]['_id'] if db_util.add_mongo_id(str(toid)) in user0['contacts']: ret.append(str(toid)) elif isinstance(_id, list): userlist = user_query(session, {'_id':from_id}) if len(userlist)==0: userlist = user_query(session, {'username':from_id}) if len(userlist)>0: user0 = userlist[0] if user0.has_key('contacts'): for id in _id: if db_util.add_mongo_id(id) in user0['contacts']: ret.append(id) return ret def get_destination_group(session, from_id, _id): ret = [] userset = set() grps = group_query(session, {'_id':_id}) for grp in grps: if grp.has_key('members') and len(grp['members'])>0: if db_util.add_mongo_id(from_id) in grp['members']: userset = userset.union(set(grp['members'])) userlist = list(userset) for id in userlist: ret.append(id) return ret def resend_offline_msg(session, to_id, limit=10): offlinecol = 'chat_log_offline' if gConfig['chat_platform']['mongodb'].has_key('collection_chat_log_offline'): offlinecol = gConfig['chat_platform']['mongodb']['collection_chat_log_offline'] collection = get_collection(offlinecol) arr = list(collection.find({'to':db_util.add_mongo_id(to_id)}).limit(limit).sort('timestamp', pymongo.DESCENDING)) ids = [i['_id'] for i in arr] collection.remove({'_id':{'$in': ids}}) for i in arr: gJoinableQueue.put(db_util.remove_mongo_id(i)) def chat(session, websocket, obj={}): tolist = [] if obj.has_key('from') and len(obj['from'])>0 and obj.has_key('msg') and len(obj['msg'])>0: if obj.has_key('to') and len(obj['to'])>0: tolist = get_destination(session, obj['from'], obj['to']) if obj.has_key('to_group') and len(obj['to_group']) > 0: tolist = get_destination_group(session, obj['from'], obj['to_group']) for k in tolist: try: d = {'op': 'chat/chat', 'from': obj['from'], 'to': k, 'timestamp': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 'msg': obj['msg']} gJoinableQueue.put(d) except gevent.queue.Full: print('chat queue is full') def request_response(session, websocket, obj={}): #'chat/request/contact/add', #'chat/request/contact/remove', #'chat/response/contact/add/accept', #'chat/response/contact/add/reject' #'chat/request/group/join' #'chat/request/group/quit' #'chat/response/group/join/accept', #'chat/response/group/join/reject', tolist = [] try: if obj['op'] == 'chat/response/contact/add/accept': if obj.has_key('from') and len(obj['from'])>0 and obj.has_key('to') and len(obj['to'])>0: collection = get_collection(gConfig['chat_platform']['mongodb']['collection_users']) userlist = user_query(session, {'_id':[obj['from'], obj['to']]}) for user in userlist: if str(user['_id']) == obj['from'] and not db_util.add_mongo_id(obj['to']) in user['contacts']: user['contacts'].append(db_util.add_mongo_id(obj['to'])) if str(user['_id']) == obj['to'] and not db_util.add_mongo_id(obj['from']) in user['contacts']: user['contacts'].append(db_util.add_mongo_id(obj['from'])) user['update_date'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) collection.save(user) fromuser = {} fromuser['op'] = obj['op'] fromuser['_id'] = obj['from'] fromuser['from'] = obj['to'] fromuser['to'] = obj['from'] fromuser['contacts'] = json.loads(user_contact_get(session, {'_id':obj['from'],'user_detail':True})) gJoinableQueue.put(db_util.remove_mongo_id(fromuser)) touser = {} touser['op'] = obj['op'] touser['_id'] = obj['to'] touser['from'] = obj['from'] touser['to'] = obj['to'] touser['contacts'] = json.loads(user_contact_get(session, {'_id':obj['to'],'user_detail':True})) gJoinableQueue.put(db_util.remove_mongo_id(touser)) elif obj['op'] == 'chat/response/contact/add/reject': if obj.has_key('from') and len(obj['from'])>0 and obj.has_key('to') and len(obj['to'])>0: userlist = user_query(session, {'_id':obj['from']}) if len(userlist)>0: user0 = userlist[0] user0['op'] = obj['op'] user0['from'] = obj['from'] user0['to'] = obj['to'] if user0.has_key('password'): del user0['password'] if user0.has_key('contacts'): del user0['contacts'] if obj.has_key('reject_reason') and len(obj['reject_reason'])>0: user0['reject_reason'] = obj['reject_reason'] gJoinableQueue.put(db_util.remove_mongo_id(user0)) elif obj['op'] == 'chat/request/contact/add': if obj.has_key('from') and len(obj['from'])>0 and obj.has_key('to') and len(obj['to'])>0: userlist = user_query(session, {'_id':obj['from']}) if len(userlist)>0: user0 = userlist[0] user0['op'] = obj['op'] user0['from'] = obj['from'] user0['to'] = obj['to'] if user0.has_key('password'): del user0['password'] if user0.has_key('contacts'): del user0['contacts'] gJoinableQueue.put(db_util.remove_mongo_id(user0)) elif obj['op'] == 'chat/request/contact/remove': if obj.has_key('from') and len(obj['from'])>0 and obj.has_key('to') and len(obj['to'])>0: collection = get_collection(gConfig['chat_platform']['mongodb']['collection_users']) userlist = user_query(session, {'_id':[obj['from'], obj['to']]}) remover, removee = None, None for user in userlist: if str(user['_id']) == obj['from'] and db_util.add_mongo_id(obj['to']) in user['contacts']: user['contacts'].remove(db_util.add_mongo_id(obj['to'])) remover = user['display_name'] if str(user['_id']) == obj['to'] and db_util.add_mongo_id(obj['from']) in user['contacts']: user['contacts'].remove(db_util.add_mongo_id(obj['from'])) removee = user['display_name'] user['update_date'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) collection.save(user) fromuser = {} fromuser['op'] = obj['op'] fromuser['_id'] = obj['from'] fromuser['from'] = obj['to'] fromuser['to'] = obj['from'] fromuser['remover'] = remover fromuser['removee'] = removee fromuser['remove_type'] = 'remover' fromuser['contacts'] = json.loads(user_contact_get(session, {'_id':obj['from'], 'user_detail':True})) gJoinableQueue.put(db_util.remove_mongo_id(fromuser)) touser = {} touser['op'] = obj['op'] touser['_id'] = obj['to'] touser['from'] = obj['from'] touser['to'] = obj['to'] touser['remover'] = remover touser['removee'] = removee touser['remove_type'] = 'removee' touser['contacts'] = json.loads(user_contact_get(session, {'_id':obj['to'], 'user_detail':True})) gJoinableQueue.put(db_util.remove_mongo_id(touser)) elif obj['op'] == 'chat/request/group/join': if obj.has_key('from') and len(obj['from'])>0 and obj.has_key('to_group') and len(obj['to_group'])>0: grps = group_query(session, {'_id':obj['to_group']}) if len(grps)>0: grp0 = grps[0] userlist = user_query(session, {'_id':obj['from']}) if len(userlist)>0: user0 = userlist[0] user0['op'] = obj['op'] user0['from'] = obj['from'] user0['request_src'] = obj['from'] user0['to_group'] = obj['to_group'] user0['to'] = grp0['owner_id'] if user0.has_key('password'): del user0['password'] if user0.has_key('contacts'): del user0['contacts'] gJoinableQueue.put(db_util.remove_mongo_id(user0)) elif obj['op'] == 'chat/request/group/quit': if obj.has_key('from') and len(obj['from'])>0 and obj.has_key('to_group') and len(obj['to_group'])>0: grps = group_query(session, {'_id':obj['to_group']}) if len(grps)>0: grp0 = grps[0] members = [] if db_util.add_mongo_id(obj['from']) in grp0['members']: grp0['members'].remove(db_util.add_mongo_id(obj['from'])) members = [str(i) for i in grp0['members']] collection = get_collection(gConfig['chat_platform']['mongodb']['collection_groups']) collection.save(grp0) broadcast(session, websocket, members, {'op':obj['op'], 'from':obj['from'], 'to_group':obj['to_group']} ) elif obj['op'] == 'chat/response/group/join/accept': if obj.has_key('to_group') and len(obj['to_group'])>0 and obj.has_key('request_src') and len(obj['request_src'])>0: grps = group_query(session, {'_id': obj['to_group']}) if len(grps)>0: grp0 = grps[0] if not db_util.add_mongo_id(obj['request_src']) in grp0['members']: grp0['members'].append(db_util.add_mongo_id(obj['request_src'])) collection = get_collection(gConfig['chat_platform']['mongodb']['collection_groups']) collection.save(grp0) members = [str(i) for i in grp0['members']] broadcast(session, websocket, members, obj) elif obj['op'] == 'chat/response/group/join/reject': if obj.has_key('from') and len(obj['from'])>0 and obj.has_key('to') and len(obj['to'])>0 and obj.has_key('to_group') and len(obj['to_group'])>0: userlist = user_query(session, {'_id':obj['from']}) if len(userlist)>0: user0 = userlist[0] user0['op'] = obj['op'] user0['from'] = obj['from'] user0['to'] = obj['to'] user0['to_group'] = obj['to_group'] if user0.has_key('password'): del user0['password'] if user0.has_key('contacts'): del user0['contacts'] if obj.has_key('reject_reason') and len(obj['reject_reason'])>0: user0['reject_reason'] = obj['reject_reason'] gJoinableQueue.put(db_util.remove_mongo_id(user0)) #else: #d = {'op': obj['op'], 'from':obj['from'], 'to':k, 'timestamp':time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),} #gJoinableQueue.put(d) except gevent.queue.Full: print('chat queue is full') def broadcast(session, websocket, alist, obj={}): for i in alist: d = {} #d['timestamp'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) for k in obj.keys(): d[k] = obj[k] if isinstance(i, str) or isinstance(i, unicode): d['to'] = i elif isinstance(i, dict): if i.has_key('_id'): d['to'] = i['_id'] try: gJoinableQueue.put(d) except: pass def handle_websocket(environ): ws = get_websocket(environ) app = gConfig['wsgi']['application'] #session_id = None #channel = '' #if environ.has_key('HTTP_COOKIE'): #arr = environ['HTTP_COOKIE'].split('=') #if len(arr)>1: #session_id = arr[1] interval = 1.0 try: interval = float(gConfig[app]['websocket']['interval_poll']) except: interval = 1.0 while ws and not ws.closed: obj = ws_recv(environ) if obj and isinstance(obj, dict) and obj.has_key('op'): if obj['op'] == 'queue_size': qsize = 0 if gJoinableQueue: qsize = gJoinableQueue.qsize() ws.send(json.dumps({'queue_size':qsize}, ensure_ascii=True, indent=4)) elif obj['op'] == 'chat/online': rec = [] if obj.has_key('_id') and len(obj['_id'])>0: rec = user_query(session, {'_id':obj['_id']}) elif obj.has_key('username') and len(obj['username'])>0: rec = user_query(session, {'username':obj['username']}) if len(rec)>0: r0 = rec[0] _id = str(r0['_id']) online(_id, ws) r0['contacts'] = json.loads(user_contact_get(session, {'_id':_id,'user_detail':True})) r0['groups'] = json.loads(user_group_get(session, {'_id':_id,'user_detail':True})) d = db_util.remove_mongo_id(r0) d['op'] = obj['op'] d['from'] = _id d['to'] = _id d['timestamp'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) gJoinableQueue.put(d) #ws.send(json.dumps(d, ensure_ascii=True, indent=4)) if obj.has_key('inform_contact') and obj['inform_contact'] is True: other_contacts = gWebSocketsMap.keys()[:] if _id in other_contacts: other_contacts.remove(_id) broadcast(session, ws, other_contacts, {'op':'chat/info/online','from':_id}) limit = 10 if gConfig['chat_platform'].has_key('resend') and gConfig['chat_platform']['resend'].has_key('max_resend_record_num'): try: limit = int(gConfig['chat_platform']['resend']['max_resend_record_num']) except: pass resend_offline_msg(session, _id, limit) else: ws.send(json.dumps({'result':'chat_online_user_not_exist'}, ensure_ascii=True, indent=4)) elif obj['op'] == 'chat/offline': if obj.has_key('_id'): _id = obj['_id'] if obj.has_key('inform_contact') and obj['inform_contact'] is True: other_contacts = gWebSocketsMap.keys()[:] if _id in other_contacts: other_contacts.remove(_id) broadcast(session, ws, other_contacts, {'op':'chat/info/offline','from':_id, 'timestamp': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}) offline(_id) elif obj.has_key('username'): rec = user_query(session, {'username':obj['username']}) if len(rec)>0: _id = str(rec[0]['_id']) if obj.has_key('inform_contact') and obj['inform_contact'] is True: other_contacts = gWebSocketsMap.keys()[:] if _id in other_contacts: other_contacts.remove(_id) broadcast(session, ws, other_contacts, {'op':'chat/info/offline','from':_id}) offline(_id) else: ws.send(json.dumps({'result':'chat_offline_user_not_exist'}, ensure_ascii=True, indent=4)) else: ws.send(json.dumps({'result':'chat_offline_username_or_id_required'}, ensure_ascii=True, indent=4)) elif obj['op'] == 'chat/chat': chat(session, ws, obj) elif 'chat/request' in obj['op'] or 'chat/response' in obj['op']: request_response(session, ws, obj) else: try: ws.send('') except: _id = None for k in gWebSocketsMap.keys(): if ws in gWebSocketsMap[k] : _id = k break if _id: print('websocket[%s] is closed2' % _id) offline(_id) broadcast(session, None, gWebSocketsMap.keys(), {'op':'chat/info/offline', 'from':_id}) gevent.sleep(interval) if ws and ws.closed: del ws def check_url_token(querydict): is_token_pass = False enable_url_md5_check = False md5prefix = '' if gConfig['chat_platform'].has_key('security') \ and gConfig['chat_platform']['security'].has_key('md5prefix'): md5prefix = str(gConfig['chat_platform']['security']['md5prefix']) if gConfig['chat_platform'].has_key('security') \ and gConfig['chat_platform']['security'].has_key('enable_url_md5_check') \ and gConfig['chat_platform']['security']['enable_url_md5_check'].lower() == 'true': enable_url_md5_check = True else: is_token_pass = True if enable_url_md5_check: print('checking token...') if querydict.has_key('_token'): plain = '%s_|_%s' % (md5prefix, time.strftime('%Y%m%d%H')) token = md5.new(plain).hexdigest() if token == str(querydict['_token']): is_token_pass = True return is_token_pass def chat_broadcast(session, querydict): ret = '{}' tolist = [] if querydict.has_key('from') and len(querydict['from'])>0: if querydict.has_key('to'): if isinstance(querydict['to'], str) or isinstance(querydict['to'], unicode): tolist.append(querydict['to']) if isinstance(querydict['to'], list): tolist.extend(querydict['to']) else: ret = json.dumps({'result':u'chat_broadcast_to_required'}, ensure_ascii=True, indent=4) else: ret = json.dumps({'result':u'chat_broadcast_from_required'}, ensure_ascii=True, indent=4) if querydict.has_key('msg') and len(querydict['msg'])>0: for k in tolist: try: d = {'op': 'chat/chat', 'from': querydict['from'], 'to': k, 'timestamp': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 'msg': querydict['msg']} gJoinableQueue.put(d) except gevent.queue.Full: print('chat queue is full') ret = json.dumps({'result':u'chat queue is full'}, ensure_ascii=True, indent=4) else: ret = json.dumps({'result':u'chat_broadcast_msg_required'}, ensure_ascii=True, indent=4) return ret def chat_log_query(session, querydict): limit = 0 skip = 0 filter_str = '' from_id, to_id = None, None if querydict.has_key('from') and (isinstance(querydict['from'], str) or isinstance(querydict['from'], unicode)) and len(querydict['from'])>0: from_id = querydict['from'] if querydict.has_key('to') and (isinstance(querydict['to'], str) or isinstance(querydict['to'], unicode)) and len(querydict['to'])>0: to_id = querydict['to'] if from_id is None or to_id is None: return json.dumps({'result':u'chat_log_query_from_and_to_required'}, ensure_ascii=True, indent=4) if querydict.has_key('limit'): try: limit = int(querydict['limit']) except: pass del querydict['limit'] if querydict.has_key('skip'): try: skip = int(querydict['skip']) except: pass del querydict['skip'] if querydict.has_key('filter'): filter_str = querydict['filter'] del querydict['filter'] #
self._py_history.clear() for i in range(1, readline.get_current_history_length() + 1): # noinspection PyArgumentList self._py_history.append(readline.get_history_item(i)) readline.clear_history() # Restore cmd2's history for item in cmd2_env.history: readline.add_history(item) if self._completion_supported(): # Restore cmd2's tab completion settings readline.set_completer(cmd2_env.readline_settings.completer) readline.set_completer_delims(cmd2_env.readline_settings.delims) if rl_type == RlType.GNU: rl_basic_quote_characters.value = cmd2_env.readline_settings.basic_quotes if 'gnureadline' in sys.modules: # Restore what the readline module pointed to if cmd2_env.readline_module is None: del sys.modules['readline'] else: sys.modules['readline'] = cmd2_env.readline_module py_description = ("Invoke Python command or shell\n" "\n" "Note that, when invoking a command directly from the command line, this shell\n" "has limited ability to parse Python statements into tokens. In particular,\n" "there may be problems with whitespace and quotes depending on their placement.\n" "\n" "If you see strange parsing behavior, it's best to just open the Python shell\n" "by providing no arguments to py and run more complex statements there.") py_parser = DEFAULT_ARGUMENT_PARSER(description=py_description) py_parser.add_argument('command', nargs=argparse.OPTIONAL, help="command to run") py_parser.add_argument('remainder', nargs=argparse.REMAINDER, help="remainder of command") # Preserve quotes since we are passing these strings to Python @with_argparser(py_parser, preserve_quotes=True) def do_py(self, args: argparse.Namespace, *, pyscript: Optional[str] = None) -> Optional[bool]: """ Enter an interactive Python shell :param args: Namespace of args on the command line :param pyscript: optional path to a pyscript file to run. This is intended only to be used by run_pyscript after it sets up sys.argv for the script. If populated, this takes precedence over all other arguments. (Defaults to None) :return: True if running of commands should stop """ def py_quit(): """Function callable from the interactive Python console to exit that environment""" raise EmbeddedConsoleExit from .py_bridge import PyBridge py_bridge = PyBridge(self) saved_sys_path = None if self.in_pyscript(): self.perror("Recursively entering interactive Python shells is not allowed") return try: self._in_py = True py_code_to_run = '' # Make a copy of self.py_locals for the locals dictionary in the Python environment we are creating. # This is to prevent pyscripts from editing it. (e.g. locals().clear()). It also ensures a pyscript's # environment won't be filled with data from a previously run pyscript. Only make a shallow copy since # it's OK for py_locals to contain objects which are editable in a pyscript. localvars = dict(self.py_locals) localvars[self.py_bridge_name] = py_bridge localvars['quit'] = py_quit localvars['exit'] = py_quit if self.self_in_py: localvars['self'] = self # Handle case where we were called by run_pyscript if pyscript is not None: # Read the script file expanded_filename = os.path.expanduser(pyscript) try: with open(expanded_filename) as f: py_code_to_run = f.read() except OSError as ex: self.pexcept("Error reading script file '{}': {}".format(expanded_filename, ex)) return localvars['__name__'] = '__main__' localvars['__file__'] = expanded_filename # Place the script's directory at sys.path[0] just as Python does when executing a script saved_sys_path = list(sys.path) sys.path.insert(0, os.path.dirname(os.path.abspath(expanded_filename))) else: # This is the default name chosen by InteractiveConsole when no locals are passed in localvars['__name__'] = '__console__' if args.command: py_code_to_run = args.command if args.remainder: py_code_to_run += ' ' + ' '.join(args.remainder) # Set cmd_echo to True so PyBridge statements like: py app('help') # run at the command line will print their output. py_bridge.cmd_echo = True # Create the Python interpreter interp = InteractiveConsole(locals=localvars) # Check if we are running Python code if py_code_to_run: # noinspection PyBroadException try: interp.runcode(py_code_to_run) except BaseException: # We don't care about any exception that happened in the Python code pass # Otherwise we will open an interactive Python shell else: cprt = 'Type "help", "copyright", "credits" or "license" for more information.' instructions = ('End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, `exit()`.\n' 'Non-Python commands can be issued with: {}("your command")' .format(self.py_bridge_name)) saved_cmd2_env = None # noinspection PyBroadException try: # Get sigint protection while we set up the Python shell environment with self.sigint_protection: saved_cmd2_env = self._set_up_py_shell_env(interp) interp.interact(banner="Python {} on {}\n{}\n\n{}\n". format(sys.version, sys.platform, cprt, instructions)) except BaseException: # We don't care about any exception that happened in the interactive console pass finally: # Get sigint protection while we restore cmd2 environment settings with self.sigint_protection: if saved_cmd2_env is not None: self._restore_cmd2_env(saved_cmd2_env) finally: with self.sigint_protection: if saved_sys_path is not None: sys.path = saved_sys_path self._in_py = False return py_bridge.stop run_pyscript_parser = DEFAULT_ARGUMENT_PARSER(description="Run a Python script file inside the console") run_pyscript_parser.add_argument('script_path', help='path to the script file', completer_method=path_complete) run_pyscript_parser.add_argument('script_arguments', nargs=argparse.REMAINDER, help='arguments to pass to script', completer_method=path_complete) @with_argparser(run_pyscript_parser) def do_run_pyscript(self, args: argparse.Namespace) -> Optional[bool]: """ Run a Python script file inside the console :return: True if running of commands should stop """ # Expand ~ before placing this path in sys.argv just as a shell would args.script_path = os.path.expanduser(args.script_path) # Add some protection against accidentally running a non-Python file. The happens when users # mix up run_script and run_pyscript. if not args.script_path.endswith('.py'): self.pwarning("'{}' does not have a .py extension".format(args.script_path)) selection = self.select('Yes No', 'Continue to try to run it as a Python script? ') if selection != 'Yes': return # Save current command line arguments orig_args = sys.argv try: # Overwrite sys.argv to allow the script to take command line arguments sys.argv = [args.script_path] + args.script_arguments # noinspection PyTypeChecker py_return = self.do_py('', pyscript=args.script_path) finally: # Restore command line arguments to original state sys.argv = orig_args return py_return # Only include the do_ipy() method if IPython is available on the system if ipython_available: # pragma: no cover ipython_parser = DEFAULT_ARGUMENT_PARSER(description="Enter an interactive IPython shell") @with_argparser(ipython_parser) def do_ipy(self, _: argparse.Namespace) -> Optional[bool]: """ Enter an interactive IPython shell :return: True if running of commands should stop """ from .py_bridge import PyBridge # noinspection PyUnusedLocal def load_ipy(cmd2_app: Cmd, py_bridge: PyBridge): """ Embed an IPython shell in an environment that is restricted to only the variables in this function :param cmd2_app: instance of the cmd2 app :param py_bridge: a PyBridge """ # Create a variable pointing to py_bridge and name it using the value of py_bridge_name exec("{} = py_bridge".format(cmd2_app.py_bridge_name)) # Add self variable pointing to cmd2_app, if allowed if cmd2_app.self_in_py: exec("self = cmd2_app") # Delete these names from the environment so IPython can't use them del cmd2_app del py_bridge # Start ipy shell embed(banner1=('Entering an embedded IPython shell. Type quit or <Ctrl>-d to exit.\n' 'Run Python code from external files with: run filename.py\n'), exit_msg='Leaving IPython, back to {}'.format(sys.argv[0])) if self.in_pyscript(): self.perror("Recursively entering interactive Python shells is not allowed") return try: self._in_py = True new_py_bridge = PyBridge(self) load_ipy(self, new_py_bridge) return new_py_bridge.stop finally: self._in_py = False history_description = "View, run, edit, save, or clear previously entered commands" history_parser = DEFAULT_ARGUMENT_PARSER(description=history_description) history_action_group = history_parser.add_mutually_exclusive_group() history_action_group.add_argument('-r', '--run', action='store_true', help='run selected history items') history_action_group.add_argument('-e', '--edit', action='store_true', help='edit and then run selected history items') history_action_group.add_argument('-o', '--output_file', metavar='FILE', help='output commands to a script file, implies -s', completer_method=path_complete) history_action_group.add_argument('-t', '--transcript', metavar='TRANSCRIPT_FILE', help='output commands and results to a transcript file,\nimplies -s', completer_method=path_complete) history_action_group.add_argument('-c', '--clear', action='store_true', help='clear all history') history_format_group = history_parser.add_argument_group(title='formatting') history_format_group.add_argument('-s', '--script', action='store_true', help='output commands in script format, i.e. without command\n' 'numbers') history_format_group.add_argument('-x', '--expanded', action='store_true', help='output fully parsed commands with any aliases and\n' 'macros expanded, instead of typed commands') history_format_group.add_argument('-v', '--verbose', action='store_true', help='display history and include expanded commands if they\n' 'differ from the typed command') history_format_group.add_argument('-a', '--all', action='store_true', help='display all commands, including ones persisted from\n' 'previous sessions') history_arg_help = ("empty all history items\n" "a one history item by number\n" "a..b, a:b, a:, ..b items by indices (inclusive)\n" "string items containing string\n" "/regex/ items matching regular expression") history_parser.add_argument('arg', nargs=argparse.OPTIONAL, help=history_arg_help) @with_argparser(history_parser) def do_history(self, args: argparse.Namespace) -> Optional[bool]: """ View, run, edit, save, or clear previously entered commands :return: True if running of commands should stop """ # -v must be used alone with no other options if args.verbose: if args.clear or args.edit or args.output_file or args.run or args.transcript \ or args.expanded or args.script: self.poutput("-v can not be used with any other options") self.poutput(self.history_parser.format_usage()) return # -s and -x can only be used if none of these options are present: [-c -r -e -o -t] if (args.script or args.expanded) \ and (args.clear or args.edit or args.output_file or args.run or args.transcript): self.poutput("-s and -x can not be used with -c, -r, -e, -o, or -t") self.poutput(self.history_parser.format_usage()) return if args.clear: # Clear command
1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0], [1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1], [0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1], [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0], [0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0], [1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1], [1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0], [1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0], [0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0], [1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1], [0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1], [0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0], [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1,
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # # Copyright © 2018 Dell Inc. or its subsidiaries. All rights reserved. # Dell, EMC, and other trademarks are trademarks of Dell Inc. or its subsidiaries. # Other trademarks may be trademarks of their respective owners. # # 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> # import sys import os import re import json import time import glob import xml.etree.ElementTree as ET from enum import Enum from datetime import datetime from omsdk.sdkprint import PrettyPrint from omsdk.sdkcenum import EnumWrapper, TypeHelper from omsdk.lifecycle.sdkupdate import Update from omsdk.catalog.sdkupdatemgr import UpdateManager from omsdk.catalog.updaterepo import RepoComparator, UpdateFilterCriteria from omsdk.catalog.updaterepo import UpdatePresenceEnum, UpdateNeededEnum, UpdateTypeEnum from omdrivers.enums.iDRAC.iDRACEnums import * from omsdk.sdkcunicode import UnicodeWriter from omsdk.sdkfile import FileOnShare PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 try: from pysnmp.hlapi import * from pysnmp.smi import * PySnmpPresent = True except ImportError: PySnmpPresent = False class iDRACUpdate(Update): def __init__(self, entity): if PY2: super(iDRACUpdate, self).__init__(entity, iDRACFirmEnum) else: super().__init__(entity, iDRACFirmEnum) self.reset() self._job_mgr = entity.job_mgr def _sw_instance(self, comp): ilist = [] clist = self._comp_to_fqdd(comp) for firmware in self.firmware_json["Firmware"]: if firmware['FQDD'] in clist and firmware['Status'] == "Installed": ilist.append(firmware['InstanceID']) return ilist def _update_from_uri(self, firm_image_path, componentFQDD, job_wait=True): rjson = self.entity._install_from_uri(uri=firm_image_path, target=componentFQDD) rjson['file'] = str(share) if job_wait: rjson = self._job_mgr._job_wait(rjson['file'], rjson) return rjson def reset(self): self.sw_inited = False self._swidentity = {} self.firmware_json = {} self.installed_firmware = {} def get_swidentity(self): if self.sw_inited: logger.debug("Already present") return self.firmware_json self.entity._get_entries(self.firmware_json, self.firmware_enum) logger.debug(self.firmware_json) for obj in self.firmware_json: self.installed_firmware[obj] = [] for entry in self.firmware_json[obj]: if 'Status' in entry and entry['Status'] == 'Installed': self.installed_firmware[obj].append(entry) return self.firmware_json def _get_swidentity_hash(self): self.get_swidentity() for comp in self.firmware_json: for swentry in self.firmware_json[comp]: if not "FQDD" in swentry: continue if swentry["FQDD"] in self._swidentity: if not isinstance(self._swidentity[swentry["FQDD"]], list): self._swidentity[swentry["FQDD"]] = [self._swidentity[swentry["FQDD"]]] else: self._swidentity[swentry["FQDD"]] = {} self._swidentity[swentry["FQDD"]] = {} if "ComponentID" in swentry and swentry["ComponentID"]: for val in ["ComponentID"]: self._swidentity[swentry["FQDD"]][val] = swentry[val] else: for val in ["VendorID", "SubVendorID", "DeviceID", "SubDeviceID"]: self._swidentity[swentry["FQDD"]][val] = swentry[val] for val in ["ComponentType", "InstanceID", "VersionString", "Status"]: self._swidentity[swentry["FQDD"]][val] = swentry[val] self._swidentity[swentry["FQDD"]]["ComponentClass"] = "unknown" # TODO RESTORE # for mycomp in self.protocolspec.compmap: # if re.match(self.protocolspec.compmap[mycomp],swentry["FQDD"]): # self.swidentity[swentry["FQDD"]]["ComponentClass"] = mycomp self.sw_inited = True return self._swidentity def get_installed_fw_redfish(self): try: rjson = self.entity._list_fw_inventory_redfish() if rjson['Status'] != 'Success': return rjson members_uris = self.get_redfishjson_using_responsecode(rjson) if not members_uris: logger.debug("Failed to get installed firmware") return {"Status": "Failed", "Message": "Unable to get Installed Firmware"} fwlist = [] for member in members_uris: member_uri = member['@odata.id'] if "Previous" not in member_uri: rjson = self.get_fwdetail_using_uri(str(member_uri)) if rjson: fwlist.append(rjson) return {"Firmware": fwlist} except: logger.debug("Failed to get installed firmware") return {"Status": "Failed", "Message": "Unable to get Installed Firmware"} def get_fwdetail_using_uri(self, r_uri): try: rjson = self.entity._get_resource_redfish(resource_uri=r_uri) if 'Data' not in rjson or rjson['Status'] != 'Success' or 'body' not in rjson['Data']: return None fw_json = {} fw_json['Name'] = rjson['Data']['body']['Name'] fw_json['Id'] = rjson['Data']['body']['Id'] fw_json['Status'] = rjson['Data']['body']['Status'] fw_json['Updateable'] = rjson['Data']['body']['Updateable'] fw_json['Version'] = rjson['Data']['body']['Version'] return fw_json except: logger.debug("Error in getting fw deatil from uri:" + r_uri) return None def get_redfishjson_using_responsecode(self, r_json): try: if 'Data' not in r_json: logger.debug("Failed to get json from response") return None if 'body' not in r_json['Data']: logger.debug("reponse body is not present") return None if 'Members' not in r_json['Data']['body']: logger.debug("No installed firmware found") return None return r_json['Data']['body']['Members'] except Exception: logger.debug("Failed to get installed firmware, exception:") return None @property def InstalledFirmware(self): if self.entity.use_redfish: return self.get_installed_fw_redfish() self.get_swidentity() return self.installed_firmware @property def AllUpdates(self): return self.get_updates_matching(catalog='Catalog') @property def AvailableUpdates(self): criteria = UpdateFilterCriteria() criteria.include_packages(UpdatePresenceEnum.Present) return self.get_updates_matching(catalog='Catalog', criteria=criteria) @property def NeededUpdates(self): criteria = UpdateFilterCriteria() criteria.include_update_needed(UpdateNeededEnum.Needed) return self.get_updates_matching(catalog='Catalog', criteria=criteria) def get_updates_matching(self, catalog='Catalog', criteria=None): updmgr = UpdateManager.get_instance() if not updmgr: updates = RepoComparator(self.InstalledFirmware).final() else: (ignore, cache_cat) = updmgr.getCatalogScoper(catalog) updates = cache_cat.compare(self.entity.SystemIDInHex, self.InstalledFirmware) if not criteria: return updates retval = {} for comp in updates: for update in updates[comp]: if not criteria.meets(update): continue if comp not in retval: retval[comp] = [] retval[comp].append(update) return retval def save_invcollector_file(self, invcol_output_file): with UnicodeWriter(invcol_output_file) as output: self._save_invcollector(output) def serialize_inventory(self, myshare): share = myshare.format(ip=self.entity.ipaddr) swfqdd_list = [firmware['FQDD'] for firmware in \ self.InstalledFirmware["Firmware"]] with UnicodeWriter(share.local_full_path) as f: f._write_output(json.dumps({ 'Model_Hex': self.entity.SystemIDInHex, 'Model': self.entity.Model, 'IPAddress': self.entity.ipaddr, 'ServiceTag': self.entity.ServiceTag, 'Firmware': self.InstalledFirmware['Firmware'], 'ComponentMap': self.entity.config_mgr._fqdd_to_comp_map(swfqdd_list)}, sort_keys=True, indent=4, separators=(',', ': '))) def update_from_repo(self, catalog_path, apply_update=True, reboot_needed=False, job_wait=True): if isinstance(catalog_path, str): # Catalog name updmgr = UpdateManager.get_instance() if not updmgr: return {} (cache_share, ignore) = updmgr.getCatalogScoper(catalog_path) else: # DRM Repo cache_share = catalog_path catalog_dir = FileOnShare(remote=cache_share.remote_folder_path, isFolder=True, creds=cache_share.creds) catalog_file = cache_share.remote_file_name if self.entity.use_redfish: if isinstance(catalog_path, FileOnShare) and catalog_path.mount_point is None: raise ValueError("Share path or mount point does not exist") rjson = self.entity._update_from_repo_using_redfish(ipaddress=catalog_dir.remote_ipaddr, share_name=catalog_dir.remote.share_name, share_type=IFRShareTypeEnum[catalog_dir.remote_share_type.name.lower()], username=catalog_dir.creds.username, password=<PASSWORD>, reboot_needed=reboot_needed, catalog_file=catalog_file, apply_update=ApplyUpdateEnum[str(apply_update)], ignore_cert_warning=IgnoreCertWarnEnum['On']) if TypeHelper.resolve(catalog_dir.remote_share_type) == TypeHelper.resolve(ShareTypeEnum.NFS): rjson = self.entity._update_repo_nfs(share=catalog_dir, creds=catalog_dir.creds, catalog=catalog_file, apply=URLApplyUpdateEnum[str(apply_update)].value, reboot=RebootEnum[str(reboot_needed)].value) else: rjson = self.entity._update_repo(share=catalog_dir, creds=catalog_dir.creds, catalog=catalog_file, apply=URLApplyUpdateEnum[str(apply_update)].value, reboot=RebootEnum[str(reboot_needed)].value) rjson['file'] = str(cache_share) if job_wait: rjson = self._job_mgr._job_wait(rjson['file'], rjson) if not self.entity.use_redfish: rjson['job_details'] = self.entity._update_get_repolist() return rjson def update_from_dell_repo_url(self, ipaddress=None, share_name=None, share_type=None, catalog_file="Catalog.xml", apply_update=True, reboot_needed=False, ignore_cert_warning=True, job_wait=True): rjson = self.entity._update_dell_repo_url(ipaddress=ipaddress, share_type=URLShareTypeEnum[share_type].value, catalog_file=catalog_file, apply_update=URLApplyUpdateEnum[str(apply_update)].value, reboot_needed=RebootEnum[str(reboot_needed)].value, ignore_cert_warning=URLCertWarningEnum[str(ignore_cert_warning)].value) file_format = "{0}://{1}/{2}/{3}" if share_name else "{0}://{1}{2}/{3}" rjson['file'] = file_format.format(share_type, ipaddress, share_name, catalog_file) if job_wait: rjson = self._job_mgr._job_wait(rjson['file'], rjson) if not self.entity.use_redfish: rjson['job_details'] = self.entity._update_get_repolist() return rjson def update_from_repo_url(self, ipaddress=None, share_type=None, share_name=None, share_user=None, share_pwd=<PASSWORD>, catalog_file="Catalog.xml", apply_update=True, reboot_needed=False, ignore_cert_warning=True, job_wait=True): if self.entity.use_redfish: warning = IgnoreCertWarnEnum["On"] if ignore_cert_warning else IgnoreCertWarnEnum["Off"] rjson = self.entity._update_from_repo_using_redfish(ipaddress=ipaddress, share_name=share_name, share_type=IFRShareTypeEnum[share_type], username=share_user, password=<PASSWORD>, reboot_needed=reboot_needed, catalog_file=catalog_file, apply_update=ApplyUpdateEnum[str(apply_update)], ignore_cert_warning=warning.value) else: rjson = self.entity._update_repo_url(ipaddress=ipaddress, share_type=URLShareTypeEnum[share_type].value, share_name=share_name, catalog_file=catalog_file, apply_update=URLApplyUpdateEnum[str(apply_update)].value, reboot_needed=RebootEnum[str(reboot_needed)].value, ignore_cert_warning=URLCertWarningEnum[str(ignore_cert_warning)].value) file_format = "{0}://{1}/{2}/{3}" if share_name else "{0}://{1}{2}/{3}" rjson['file'] = file_format.format(share_type, ipaddress, share_name, catalog_file) if job_wait: rjson = self._job_mgr._job_wait(rjson['file'], rjson) if not self.entity.use_redfish: rjson['job_details'] = self.entity._update_get_repolist() return rjson ##below methods to update firmware using redfish will be reimplemented using Type Manager system def _get_scp_path(self, catalog_dir): """ :param catalog_dir: object for Folder containing Catalog on share. :param catalog_dir: FileOnShare. :returns: returns a tuple containing remote scp path(full) and the scp file name """ catalog_path_str = catalog_dir.remote_full_path scp_file = 'scp_' + self.entity.ServiceTag + '_' + datetime.now().strftime('%Y%m%d_%H%M%S') + ".xml" scp_path = catalog_path_str + os.path.sep + scp_file return (scp_path, scp_file) def update_from_repo_usingscp_redfish(self, catalog_dir, catalog_file, mount_point, apply_update=True, reboot_needed=False, job_wait=True): """Performs firmware update on target server using scp RepositoyUpdate attribute :param catalog_dir: object for Folder containing Catalog on share. :param catalog_dir: FileOnShare. :param catalog_file: Catalog file name :param catalog_file: str. :param mount_point: local share on which remote(catalog_dir) folder has been mounted :param mount_point: str. :returns: returns status of firmware update through scp """ (scp_path, scp_file) = self._get_scp_path(catalog_dir) myshare = FileOnShare(scp_path).addcreds(catalog_dir.creds) # exports only that component which contains RepositoryUpdate attribute rjson = self.entity.config_mgr.scp_export(share_path=myshare, target='System.Embedded.1') if 'Status' not in rjson or rjson['Status'] != 'Success': return {'Status': 'Failed', 'Message': 'Export of scp failed for firmware update'} scpattrval = {'RepositoryUpdate': catalog_file} localfile = mount_point.share_path + os.path.sep + scp_file self.edit_xml_file(localfile, scpattrval) if reboot_needed: shutdown = ShutdownTypeEnum.Graceful else: shutdown = ShutdownTypeEnum.NoReboot rjson = self.entity.config_mgr.scp_import(share_path=myshare, shutdown_type=shutdown, job_wait=job_wait) if job_wait: rjson['file'] = localfile rjson = self._job_mgr._job_wait(rjson['file'], rjson) rjson['job_details'] = self.entity._update_get_repolist() return rjson def edit_xml_file(self, file_location, attr_val_dict): """Edit and save exported scp's attributes which are passed in attr_val_dict :param file_location: locally mounted location(full path) of the exported scp . :param file_location: str. :param attr_val_dict: attribute and value pairs as dict :param attr_val_dict: dict. :returns: returns None """ tree = ET.parse(file_location) root = tree.getroot() for attr in attr_val_dict: xpath = ".//*[@Name='" + str(attr) + "']" attribute_element = root.find(xpath) attribute_element.text = str(attr_val_dict.get(attr)) tree.write(file_location) return def update_get_repolist(self): return self.entity._update_get_repolist() def _save_invcollector(self, output): # self.entity.get_entityjson() # if not "System" in self.entity.entityjson: # logger.debug("ERROR: Entityjson is empty") # return self._get_swidentity_hash() output._write_output('<SVMInventory>\n') output._write_output(' <System') if "System" in self.entity.entityjson: for (invstr, field) in [("Model", "Model"), ("systemID", "SystemID"), ("Name", "HostName")]: if field in self.entity.entityjson["System"]: output._write_output(" " + invstr + "=\"" + self.entity.entityjson["System"][field] + "\"") output._write_output( ' InventoryTime="{0}">\n'.format(str(datetime.strftime(datetime.now(), "%Y-%m-%dT%H:%M:%S")))) for ent in self._swidentity: output._write_output(' <Device') for (invstr, field) in [("componentID", "ComponentID"), ("vendorID", "VendorID"), ("deviceID", "DeviceID"), ("subVendorID", "SubVendorID"), ("subDeviceID", "SubDeviceID")]: if field in self._swidentity[ent]: output._write_output(" " + invstr
import math import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions.multinomial import Multinomial import numpy as np from encoders import * # code based on: https://github.com/zalandoresearch/pytorch-vq-vae/blob/master/vq-vae.ipynb class SequenceQuantizer(nn.Module): def __init__(self, codebook_size, d_model, commitment_cost, padding_idx=None): super(SequenceQuantizer, self).__init__() self.d_model = d_model self.codebook_size = codebook_size self.padding_idx = padding_idx self.codebook = nn.Embedding(self.codebook_size, self.d_model, padding_idx=padding_idx) if padding_idx is not None: self.codebook.weight.data[padding_idx] = 0 self.commitment_cost = commitment_cost def forward(self, inputs, padding_mask=None, commitment_cost=None): device = inputs.device if commitment_cost is None: commitment_cost = self.commitment_cost # inputs can be: # 2-dimensional [B x E] (already flattened) # 3-dimensional [B x T x E] (e.g., batch of sentences) # 4-dimensional [B x S x T x E] (e.g., batch of documents) input_shape = inputs.size() input_dims = inputs.dim() # Flatten input flat_input = inputs.reshape(-1, self.d_model) # Calculate distances distances = (torch.sum(flat_input**2, dim=1, keepdim=True) + torch.sum(self.codebook.weight**2, dim=1) - 2 * torch.matmul(flat_input, self.codebook.weight.t())) # TODO: generalize this to any padding_idx if padding_mask is not None: # no normal token gets mapped to discrete value 0 distances[:, 0][~padding_mask.reshape(-1)] = np.inf # all pad tokens get mapped to discrete value 0 distances[:, 1:][padding_mask.reshape(-1, 1).expand(-1, self.codebook_size - 1)] = np.inf # Encoding encoding_indices = torch.argmin(distances, dim=1).unsqueeze(1) encodings = torch.zeros(encoding_indices.shape[0], self.codebook_size).to(device) encodings.scatter_(1, encoding_indices, 1) # Quantize and unflatten quantized = torch.matmul(encodings, self.codebook.weight).view(input_shape) # Loss if padding_mask is not None: num_nonpad_elements = torch.sum(~padding_mask) * self.d_model e_latent_loss = torch.sum((quantized.detach() - inputs)**2) / num_nonpad_elements q_latent_loss = torch.sum((quantized - inputs.detach())**2) / num_nonpad_elements else: e_latent_loss = torch.mean((quantized.detach() - inputs)**2) q_latent_loss = torch.mean((quantized - inputs.detach())**2) loss = q_latent_loss + commitment_cost * e_latent_loss quantized = inputs + (quantized - inputs).detach() avg_probs = torch.mean(encodings, dim=0) perplexity = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + 1e-10))) return quantized, encoding_indices.reshape(input_shape[:input_dims - 1]), loss, perplexity def set_codebook(self, new_codebook): self.codebook.weight.copy_(new_codebook) class SequenceQuantizerEMA(nn.Module): def __init__(self, codebook_size, d_model, commitment_cost, decay=0.99, epsilon=1e-5, padding_idx=None): super(SequenceQuantizerEMA, self).__init__() self.d_model = d_model self.codebook_size = codebook_size self.padding_idx = padding_idx self.codebook = nn.Embedding(self.codebook_size, self.d_model, padding_idx=padding_idx) if padding_idx is not None: self.codebook.weight.data[padding_idx] = 0 self.commitment_cost = commitment_cost self.register_buffer('_ema_cluster_size', torch.zeros(codebook_size)) self._ema_w = nn.Parameter(torch.Tensor(codebook_size, self.d_model)) self._ema_w.data.copy_(self.codebook.weight.data) self._decay = decay self._epsilon = epsilon self.discard_ema_cluster_sizes = False def forward(self, inputs, padding_mask=None, commitment_cost=None, temp=None): device = inputs.device if commitment_cost is None: commitment_cost = self.commitment_cost if temp is None: temp = self.temp # inputs can be: # 2-dimensional [B x E] (already flattened) # 3-dimensional [B x T x E] (e.g., batch of sentences) # 4-dimensional [B x S x T x E] (e.g., batch of documents) input_shape = inputs.size() input_dims = inputs.dim() # Flatten input flat_input = inputs.reshape(-1, self.d_model) # Calculate distances distances = (torch.sum(flat_input**2, dim=1, keepdim=True) + torch.sum(self.codebook.weight**2, dim=1) - 2 * torch.matmul(flat_input, self.codebook.weight.t())) # TODO: generalize this to any padding_idx if padding_mask is not None: # no normal token gets mapped to discrete value 0 distances[:, 0][~padding_mask.reshape(-1)] = np.inf # all pad tokens get mapped to discrete value 0 distances[:, 1:][padding_mask.reshape(-1, 1).expand(-1, self.codebook_size - 1)] = np.inf # Encoding encoding_indices = torch.argmin(distances, dim=1).unsqueeze(1) encodings = torch.zeros(encoding_indices.shape[0], self.codebook_size).to(device) encodings.scatter_(1, encoding_indices, 1) # Quantize and unflatten quantized = torch.matmul(encodings, self.codebook.weight).view(input_shape) # Loss if padding_mask is not None: num_nonpad_elements = torch.sum(~padding_mask) * self.d_model e_latent_loss = torch.sum((quantized.detach() - inputs)**2) / num_nonpad_elements else: e_latent_loss = torch.mean((quantized.detach() - inputs)**2) loss = commitment_cost * e_latent_loss # Use EMA to update the embedding vectors if self.training: if self.discard_ema_cluster_sizes: self._ema_cluster_size = torch.sum(encodings, 0) self.discard_ema_cluster_sizes = False else: self._ema_cluster_size = self._ema_cluster_size * self._decay + \ (1 - self._decay) * torch.sum(encodings, 0) # Laplace smoothing of the cluster size n = torch.sum(self._ema_cluster_size.data) self._ema_cluster_size = ( (self._ema_cluster_size + self._epsilon) / (n + self.codebook_size * self._epsilon) * n) dw = torch.matmul(encodings.t(), flat_input) self._ema_w = nn.Parameter(self._ema_w * self._decay + (1 - self._decay) * dw) normalized_ema_w = self._ema_w / self._ema_cluster_size.unsqueeze(1) if self.padding_idx is not None: normalized_ema_w[self.padding_idx] = 0 self.codebook.weight = nn.Parameter(normalized_ema_w) quantized = inputs + (quantized - inputs).detach() avg_probs = torch.mean(encodings, dim=0) perplexity = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + 1e-10))) return quantized, encoding_indices.reshape(input_shape[:input_dims - 1]), loss, perplexity def set_codebook(self, new_codebook, discard_ema_cluster_sizes=False): self.codebook.weight.copy_(new_codebook) self._ema_w.copy_(new_codebook) self.discard_ema_cluster_sizes = discard_ema_cluster_sizes class SequenceQuantizerSoftEMA(nn.Module): def __init__(self, codebook_size, d_model, commitment_cost, num_samples=10, temp=1.0, ema_decay=0.99, epsilon=1e-5, padding_idx=None): super(SequenceQuantizerSoftEMA, self).__init__() self.d_model = d_model self.codebook_size = codebook_size self.padding_idx = padding_idx self.codebook = nn.Embedding(self.codebook_size, self.d_model, padding_idx=padding_idx) if padding_idx is not None: self.codebook.weight.data[padding_idx] = 0 self.commitment_cost = commitment_cost self.num_samples = num_samples self.temp = temp self.register_buffer('_ema_cluster_size', torch.zeros(codebook_size)) self._ema_w = nn.Parameter(torch.Tensor(codebook_size, self.d_model)) self._ema_w.data.copy_(self.codebook.weight.data) self._decay = ema_decay self._epsilon = epsilon self.discard_ema_cluster_sizes = False def forward(self, inputs, padding_mask=None, commitment_cost=None, temp=None): device = inputs.device if commitment_cost is None: commitment_cost = self.commitment_cost if temp is None: temp = self.temp # inputs can be: # 2-dimensional [B x E] (already flattened) # 3-dimensional [B x T x E] (e.g., batch of sentences) # 4-dimensional [B x S x T x E] (e.g., batch of documents) input_shape = inputs.size() input_dims = inputs.dim() # Flatten input flat_input = inputs.reshape(-1, self.d_model) # Calculate distances distances = (torch.sum(flat_input**2, dim=1, keepdim=True) + torch.sum(self.codebook.weight**2, dim=1) - 2 * torch.matmul(flat_input, self.codebook.weight.t())) # TODO: generalize this to any padding_idx if padding_mask is not None: # no normal token gets mapped to discrete value 0 distances[:, 0][~padding_mask.reshape(-1)] = np.inf # all pad tokens get mapped to discrete value 0 distances[:, 1:][padding_mask.reshape(-1, 1).expand(-1, self.codebook_size - 1)] = np.inf # Define multinomial distribution and sample from it multi = Multinomial(total_count=self.num_samples, logits=-distances / temp) samples = multi.sample().to(device) # Soft-quantize and unflatten quantized = torch.matmul(samples, self.codebook.weight).view(input_shape) / self.num_samples # Loss if padding_mask is not None: num_nonpad_elements = torch.sum(~padding_mask) * self.d_model e_latent_loss = torch.sum((quantized.detach() - inputs)**2) / num_nonpad_elements else: e_latent_loss = torch.mean((quantized.detach() - inputs)**2) loss = commitment_cost * e_latent_loss # Use EMA to update the embedding vectors if self.training: if self.discard_ema_cluster_sizes: self._ema_cluster_size = torch.sum(samples, 0) / self.num_samples self.discard_ema_cluster_sizes = False else: self._ema_cluster_size = self._ema_cluster_size * self._decay + \ (1 - self._decay) * \ (torch.sum(samples, 0) / self.num_samples) # Laplace smoothing of the cluster size n = torch.sum(self._ema_cluster_size.data) self._ema_cluster_size = ( (self._ema_cluster_size + self._epsilon) / (n + self.codebook_size * self._epsilon) * n) dw = torch.matmul(samples.t(), flat_input) / self.num_samples self._ema_w = nn.Parameter(self._ema_w * self._decay + (1 - self._decay) * dw) normalized_ema_w = self._ema_w / self._ema_cluster_size.unsqueeze(1) if self.padding_idx is not None: normalized_ema_w[self.padding_idx] = 0 self.codebook.weight = nn.Parameter(normalized_ema_w) quantized = inputs + (quantized - inputs).detach() avg_probs = torch.mean(samples, dim=0) / self.num_samples perplexity = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + 1e-10))) samples = samples.reshape(list(input_shape[:input_dims - 1]) + [self.codebook_size]) return quantized, samples, loss, perplexity def cluster(self, inputs, padding_mask=None): device = inputs.device # inputs can be: # 2-dimensional [B x E] (already flattened) # 3-dimensional [B x T x E] (e.g., batch of sentences) # 4-dimensional [B x S x T x E] (e.g., batch of documents) input_shape = inputs.size() input_dims = inputs.dim() # Flatten input flat_input = inputs.reshape(-1, self.d_model) # Calculate distances distances = (torch.sum(flat_input**2, dim=1, keepdim=True) + torch.sum(self.codebook.weight**2, dim=1) - 2 * torch.matmul(flat_input, self.codebook.weight.t())) # TODO: generalize this to any padding_idx if padding_mask is not None: # no normal token gets mapped to discrete value 0 distances[:, 0][~padding_mask.reshape(-1)] = np.inf # all pad tokens get mapped to discrete value 0 distances[:, 1:][padding_mask.reshape(-1, 1).expand(-1, self.codebook_size - 1)] = np.inf # Encoding encoding_indices = torch.argmin(distances, dim=1).unsqueeze(1) encodings = torch.zeros(encoding_indices.shape[0], self.codebook_size).to(device) encodings.scatter_(1, encoding_indices, 1) # Quantize and unflatten quantized = torch.matmul(encodings, self.codebook.weight).view(input_shape) encoding_indices = encoding_indices.reshape(input_shape[:input_dims - 1]) distances = distances.reshape(list(input_shape[:-1]) + [self.codebook_size]).detach() return quantized, encoding_indices, distances def set_codebook(self, new_codebook, discard_ema_cluster_sizes=False): self.codebook.weight.copy_(new_codebook) self._ema_w.copy_(new_codebook) self.discard_ema_cluster_sizes = discard_ema_cluster_sizes class TransformerDocumentQuantizer(SequenceQuantizer): def __init__(self, codebook_size=64, d_model=200, commitment_cost=0.25, nlayers=3, internal_nheads=4, output_nheads=4, d_ff=512, pooling_final_linear=True, output_resize=True, dropout=0.1): if output_resize: self.d_output = d_model self.pooling_final_linear = True super(TransformerDocumentQuantizer, self).__init__( codebook_size, d_model, commitment_cost) else: assert d_model % output_nheads == 0, 'Number of output heads must divide d_model' self.d_output = d_model // output_nheads self.pooling_final_linear = pooling_final_linear super(TransformerDocumentQuantizer, self).__init__( codebook_size, self.d_output, commitment_cost) self.nlayers = nlayers self.internal_nheads = internal_nheads self.output_nheads = output_nheads self.d_ff = d_ff self.dropout = dropout self.encoder = TransformerDocumentEncoder( d_model=d_model, sentence_nlayers=nlayers, sentence_internal_nheads=internal_nheads, sentence_output_nheads=output_nheads, sentence_d_ff=d_ff, use_single_pooling_norm=True, pooling_final_linear=self.pooling_final_linear, pooling_final_linear_size=self.d_output, pooling_same_linear=True, dropout=dropout) def forward(self, inputs, padding_mask=None, quantize=True, residual_coeff=0.0, commitment_cost=None): assert
from JumpScale import j from JumpScale.baselib.atyourservice81.Actor import Actor from JumpScale.baselib.atyourservice81.Blueprint import Blueprint from JumpScale.baselib.atyourservice81.models.ActorsCollection import ActorsCollection from JumpScale.baselib.atyourservice81.models.ServicesCollection import ServicesCollection from JumpScale.baselib.jobcontroller.models.JobsCollections import JobsCollection from JumpScale.baselib.atyourservice81.AtYourServiceDependencies import build_nodes, create_graphs, get_task_batches, create_job import colored_traceback colored_traceback.add_hook(always=True) import yaml import os from collections import namedtuple VALID_ACTION_STATE = ['new', 'installing', 'ok', 'error', 'disabled', 'changed'] DBTuple = namedtuple("DB", ['actors', 'services']) class AtYourServiceRepo(): def __init__(self, name, gitrepo, path, model=None): self._init = False self.indocker = j.atyourservice.indocker self.debug = j.atyourservice.debug self.logger = j.atyourservice.logger self._todo = [] self.path = path self.git = gitrepo self.name = name self._db = None if model is None: self.model = j.atyourservice._repos.find(path=path)[0] else: self.model = model j.atyourservice._loadActionBase() @property def db(self): if self._db is None: self._db = DBTuple( ActorsCollection(self), ServicesCollection(self) ) return self._db def _getsshconnections(self, service_path): # get ssh connections from ays services path c = j.tools.cuisine.local if not j.sal.fs.exists(service_path): return if not j.sal.fs.exists("%s/.ssh/known_hosts" % j.dirs.homeDir): return _, out, _ = c.core.run("find %s -name 'data.json' -exec egrep -iH 'ippublic|sshPort' {} \;" % service_path, showout=False) connections = dict() if out: for item in out.splitlines(): # example line # "'./services/node!tweakernode/os!tweakernode/data.json: "sshPort":2203,'" results = item.replace('"', '').replace(',', '').split(':') if results[0] not in connections: connections[results[0]] = dict() if results[1].strip() == 'sshPort' and 'port' not in connections[results[0]]: connections[results[0]]['port'] = results[2] elif results[1].strip() == 'ipPublic'and 'ip' not in connections[results[0]]: connections[results[0]]['ip'] = results[2] return connections def destroy(self): # remove ips from known hosts c = j.tools.cuisine.local service_path = j.sal.fs.joinPaths(self.path, "services") connections = self._getsshconnections(service_path) if connections: for key, val in connections.items(): if 'ip' in val and val['ip'].strip(): if 'port' not in val: c.core.run('ssh-keygen -f "%s/.ssh/known_hosts" -R %s' % (j.dirs.homeDir, val['ip'])) else: c.core.run('ssh-keygen -f "%s/.ssh/known_hosts" -R \'[%s]:%s\'' % (j.dirs.homeDir, val['ip'], val['port'])) j.sal.fs.removeDirTree(service_path) j.sal.fs.removeDirTree(j.sal.fs.joinPaths(self.path, "actors")) j.sal.fs.removeDirTree(j.sal.fs.joinPaths(self.path, "recipes")) # for old time sake # removing the related jobs jobs = set() services = self.db.services.list() jc = JobsCollection() for service in services: job_keys = jc._list_keys(serviceKey=service) for job_key in job_keys: index = jc.getIndexFromKey(job_key) if index: jobs.add(index) else: self.logger.warn('No index found job with key [%s]' % job_key) jc._db.index_remove(list(jobs)) # removing related actors, services , and the repo model itslef. self.db.actors.destroy() self.db.services.destroy() self.model.delete() def enable_noexec(self): """ Enable the no_exec mode. Once this mode is enabled, no action will ever be execute. But the state of the action will be updated as if everything went fine (state ok) This mode can be used for demo or testing """ self.model.enable_no_exec() def disable_noexec(self): """ Enable the no_exec mode. see enable_no_exec for further info """ self.model.disable_no_exec() # ACTORS def actorCreate(self, name): """ will look for name inside & create actor from it """ actorTemplate = self.templateGet(name) actor = Actor(aysrepo=self, template=actorTemplate) return actor def actorGet(self, name, reload=False, die=False): actor_models = self.db.actors.find(name=name) if len(actor_models) == 1: obj = actor_models[0].objectGet(self) elif len(actor_models) > 1: raise j.exceptions.Input(message="More than one actor found with name:%s" % name, level=1, source="", tags="", msgpub="") elif len(actor_models) < 1: # checking if we have the actor on the file system actors_dir = j.sal.fs.joinPaths(self.path, 'actors') results = j.sal.fs.walkExtended(actors_dir, files=False, dirPattern=name) if len(results) == 1: return Actor(aysrepo=self, name=name) elif die: raise j.exceptions.Input(message="Could not find actor with name:%s" % name, level=1, source="", tags="", msgpub="") obj = self.actorCreate(name) if reload: obj.loadFromFS() return obj def actorGetByKey(self, key): return self.db.actors.get(key).objectGet(self) def actorExists(self, name): len(self.db.actors.find(name=name)) > 0 @property def actors(self): actors = {} for model in self.db.actors.find(): if model.dbobj.state != "disabled": actors[model.dbobj.name] = model.objectGet(aysrepo=self) return actors # TEMPLATES @property def templates(self): """ """ templates = {} # need to link to templates of factory and then overrule with the local ones for key, template in j.atyourservice.actorTemplates.items(): templates[key] = template # load local templates path = j.sal.fs.joinPaths(self.path, "actorTemplates") if j.sal.fs.exists(path): for template in j.atyourservice._actorTemplatesGet(self.git, path=path, aysrepo=self, result=[]): # here we want to overrides the global templates with local one. so having duplicate name is normal templates[template.name] = template return templates def templateGet(self, name, die=True): """ @param first means, will only return first found template instance """ if name in self.templates: return self.templates[name] if die: raise j.exceptions.Input( "Cannot find template with name:%s" % name) def templateExists(self, name): if self.templateGet(name, die=False) is None: return False return True def actorTemplatesFind(self, name="", domain="", role=''): res = [] for template in self.templates: if not(name == "" or template.name == name): # no match continue continue if not(domain == "" or template.domain == domain): # no match continue continue if not (role == '' or template.role == role): # no match continue continue res.append(template) return res # SERVICES @property def services(self): services = [] for service_model in self.db.services.find(): if service_model.dbobj.state != "disabled": services.append(service_model.objectGet(aysrepo=self)) return services def serviceGet(self, role, instance, key=None, die=True): """ Return service indentifier by role and instance or key throw error if service is not found or if more than one service is found """ if role.strip() == "" or instance.strip() == "": raise j.exceptions.Input("role and instance cannot be empty.") objs = self.db.services.find(actor="%s.*" % role, name=instance) if len(objs) == 0: if die: raise j.exceptions.Input(message="Cannot find service %s:%s" % (role, instance), level=1, source="", tags="", msgpub="") return None return objs[0].objectGet(self) def serviceGetByKey(self, key): return self.db.services.get(key=key).objectGet(self) @property def serviceKeys(self): return [model.key for model in self.db.services.find()] # @property # def servicesTree(self): # # TODO: implement, needs to come from db now # raise RuntimeError() # if self._servicesTree: # return self._servicesTree # producers = [] # parents = {"name": "sudoroot", "children": []} # for root in j.sal.fs.walk(j.dirs.ays, recurse=1, pattern='*state.yaml', return_files=1, depth=2): # servicekey = j.sal.fs.getBaseName(j.sal.fs.getDirName(root)) # service = self.services.get(servicekey) # for _, producerinstances in service.producers.items(): # for producer in producerinstances: # producers.append([child.key, producer.key]) # parents["children"].append(self._nodechildren( # service, {"children": [], "name": servicekey}, producers)) # self._servicesTree['parentchild'] = parents # self._servicesTree['producerconsumer'] = producers # return self._servicesTree def serviceSetState(self, actions=[], role="", instance="", state="new"): """ get run with self.runGet... will not mark if state in skipIfIn """ if state not in VALID_ACTION_STATE: raise j.exceptions.Input(message='%s is not a valid state. Should one of %s' % (state, ', '.join(VALID_ACTION_STATE))) if "install" in actions: if "init" not in actions: actions.insert(0, "init") for action in actions: for service in self.services: if role != "" and service.model.role != role: continue if instance != "" and service.name != instance: continue try: action_obj = service.model.actions[action] action_obj.state = state service.save() except KeyError: # mean action with this name doesn't exist continue def servicesFind(self, name="", actor="", state="", parent="", producer="", hasAction="", includeDisabled=False, first=False): """ @param name can be the full name e.g. myappserver or a prefix but then use e.g. myapp.* @param actor can be the full name e.g. node.ssh or role e.g. node.* (but then need to use the .* extension, which will match roles) @param parent is in form $actorName!$instance @param producer is in form $actorName!$instance @param state: new installing ok error disabled changed """ res = [] for service_model in self.db.services.find(name=name, actor=actor, state=state, parent=parent, producer=producer): if hasAction != "" and hasAction not in service_model.actionsState.keys(): continue if includeDisabled is False and service_model.dbobj.state == "disabled": continue res.append(service_model.objectGet(self)) if first: if len(res) == 0: raise j.exceptions.Input("cannot find service %s|%s:%s" % (self.name, actor, name), "ays.servicesFind") return res[0] return res # BLUEPRINTS def get_blueprints_paths(self): bpdir = j.sal.fs.joinPaths(self.path, "blueprints") items = [] if j.sal.fs.exists(path=bpdir): items = j.sal.fs.listFilesInDir(bpdir) return items def _load_blueprints(self): bps = {} items = self.get_blueprints_paths() for path in items: if path not in bps: bps[path] = Blueprint(self, path=path) return bps @property def blueprints(self): """ only shows the ones which are on predefined location """ bps = [] for path, bp in self._load_blueprints().items(): if bp.active: bps.append(bp) bps = sorted(bps, key=lambda bp: bp.name) return bps @property def blueprintsDisabled(self): """ Show the disabled blueprints """ bps = [] for path, bp in self._load_blueprints().items(): if bp.active is False: bps.append(bp) bps = sorted(bps, key=lambda bp: bp.name) return bps def blueprintExecute(self, path="", content="", role="", instance=""): bp = None if path == "" and content == "": for bp in self.blueprints: if not bp.is_valid: self.logger.warning("blueprint %s not executed because it doesn't have a valid format" % bp.path) return bp.load(role=role, instance=instance) else: bp = Blueprint(self, path=path, content=content) # self._blueprints[bp.path] = bp if not bp.is_valid: return bp.load(role=role, instance=instance) self.init(role=role, instance=instance) def to_camel_case(snake_str): components = snake_str.split('_') return components[0] + "".join(x.title() for x in components[1:]) templates = []
from pprint import pprint import pokebase as pb pkmnData = [ { "name": 'Bulbasaur', "value": "bulbasaur", "image": "img/bulbasaur.png" }, { "name": 'Ivysaur', "value": "ivysaur", "image": "img/ivysaur.png" }, { "name": 'Venusaur', "value": "venusaur", "image": "img/venusaur.png" }, { "name": 'Charmander', "value": "charmander", "image": "img/charmander.png" }, { "name": 'Charmeleon', "value": "charmeleon", "image": "img/charmeleon.png" }, { "name": 'Charizard', "value": "charizard", "image": "img/charizard.png" }, { "name": 'Squirtle', "value": "squirtle", "image": "img/squirtle.png" }, { "name": 'Wartortle', "value": "wartortle", "image": "img/wartortle.png" }, { "name": 'Blastoise', "value": "blastoise", "image": "img/blastoise.png" }, { "name": 'Caterpie', "value": "caterpie", "image": "img/caterpie.png" }, { "name": 'Metapod', "value": "metapod", "image": "img/metapod.png" }, { "name": 'Butterfree', "value": "butterfree", "image": "img/butterfree.png" }, { "name": 'Weedle', "value": "weedle", "image": "img/weedle.png", "exclude": ['swsh'] }, { "name": 'Kakuna', "value": "kakuna", "image": "img/kakuna.png", "exclude": ['swsh'] }, { "name": 'Beedrill', "value": "beedrill", "image": "img/beedrill.png", "exclude": ['swsh'] }, { "name": 'Pidgey', "value": "pidgey", "image": "img/pidgey.png", "exclude": ['swsh'] }, { "name": 'Pidgeotto', "value": "pidgeotto", "image": "img/pidgeotto.png", "exclude": ['swsh'] }, { "name": 'Pidgeot', "value": "pidgeot", "image": "img/pidgeot.png", "exclude": ['swsh'] }, { "name": 'Rattata', "value": "rattata", "image": "img/rattata.png", "exclude": ['swsh'] }, { "name": 'Raticate', "value": "raticate", "image": "img/raticate.png", "exclude": ['swsh'] }, { "name": 'Spearow', "value": "spearow", "image": "img/spearow.png", "exclude": ['swsh'] }, { "name": 'Fearow', "value": "fearow", "image": "img/fearow.png", "exclude": ['swsh'] }, { "name": 'Ekans', "value": "ekans", "image": "img/ekans.png", "exclude": ['swsh'] }, { "name": 'Arbok', "value": "arbok", "image": "img/arbok.png", "exclude": ['swsh'] }, { "name": 'Pikachu', "value": "pikachu", "image": "img/pikachu.png" }, { "name": 'Raichu', "value": "raichu", "image": "img/raichu.png" }, { "name": 'Sandshrew', "value": "sandshrew", "image": "img/sandshrew.png" }, { "name": 'Sandslash', "value": "sandslash", "image": "img/sandslash.png" }, { "name": 'Nidoran♀', "value": "nidoran-female", "image": "img/nidoran-female.png" }, { "name": 'Nidorina', "value": "nidorina", "image": "img/nidorina.png" }, { "name": 'Nidoqueen', "value": "nidoqueen", "image": "img/nidoqueen.png" }, { "name": 'Nidoran♂', "value": "nidoran-male", "image": "img/nidoran-male.png" }, { "name": 'Nidorino', "value": "nidorino", "image": "img/nidorino.png" }, { "name": 'Nidoking', "value": "nidoking", "image": "img/nidoking.png" }, { "name": 'Clefairy', "value": "clefairy", "image": "img/clefairy.png" }, { "name": 'Clefable', "value": "clefable", "image": "img/clefable.png" }, { "name": 'Vulpix', "value": "vulpix", "image": "img/vulpix.png" }, { "name": 'Ninetales', "value": "ninetales", "image": "img/ninetales.png" }, { "name": 'Jigglypuff', "value": "jigglypuff", "image": "img/jigglypuff.png" }, { "name": 'Wigglytuff', "value": "wigglytuff", "image": "img/wigglytuff.png" }, { "name": 'Zubat', "value": "zubat", "image": "img/zubat.png" }, { "name": 'Golbat', "value": "golbat", "image": "img/golbat.png" }, { "name": 'Oddish', "value": "oddish", "image": "img/oddish.png" }, { "name": 'Gloom', "value": "gloom", "image": "img/gloom.png" }, { "name": 'Vileplume', "value": "vileplume", "image": "img/vileplume.png" }, { "name": 'Paras', "value": "paras", "image": "img/paras.png", "exclude": ['swsh'] }, { "name": 'Parasect', "value": "parasect", "image": "img/parasect.png", "exclude": ['swsh'] }, { "name": 'Venonat', "value": "venonat", "image": "img/venonat.png", "exclude": ['swsh'] }, { "name": 'Venomoth', "value": "venomoth", "image": "img/venomoth.png", "exclude": ['swsh'] }, { "name": 'Diglett', "value": "diglett", "image": "img/diglett.png" }, { "name": 'Dugtrio', "value": "dugtrio", "image": "img/dugtrio.png" }, { "name": 'Meowth', "value": "meowth", "image": "img/meowth.png" }, { "name": 'Persian', "value": "persian", "image": "img/persian.png" }, { "name": 'Psyduck', "value": "psyduck", "image": "img/psyduck.png" }, { "name": 'Golduck', "value": "golduck", "image": "img/golduck.png" }, { "name": 'Mankey', "value": "mankey", "image": "img/mankey.png", "exclude": ['swsh'] }, { "name": 'Primeape', "value": "primeape", "image": "img/primeape.png", "exclude": ['swsh'] }, { "name": 'Growlithe', "value": "growlithe", "image": "img/growlithe.png" }, { "name": 'Arcanine', "value": "arcanine", "image": "img/arcanine.png" }, { "name": 'Poliwag', "value": "poliwag", "image": "img/poliwag.png" }, { "name": 'Poliwhirl', "value": "poliwhirl", "image": "img/poliwhirl.png" }, { "name": 'Poliwrath', "value": "poliwrath", "image": "img/poliwrath.png" }, { "name": 'Abra', "value": "abra", "image": "img/abra.png" }, { "name": 'Kadabra', "value": "kadabra", "image": "img/kadabra.png" }, { "name": 'Alakazam', "value": "alakazam", "image": "img/alakazam.png" }, { "name": 'Machop', "value": "machop", "image": "img/machop.png" }, { "name": 'Machoke', "value": "machoke", "image": "img/machoke.png" }, { "name": 'Machamp', "value": "machamp", "image": "img/machamp.png" }, { "name": 'Bellsprout', "value": "bellsprout", "image": "img/bellsprout.png", "exclude": ['swsh'] }, { "name": 'Weepinbell', "value": "weepinbell", "image": "img/weepinbell.png", "exclude": ['swsh'] }, { "name": 'Victreebel', "value": "victreebel", "image": "img/victreebel.png", "exclude": ['swsh'] }, { "name": 'Tentacool', "value": "tentacool", "image": "img/tentacool.png" }, { "name": 'Tentacruel', "value": "tentacruel", "image": "img/tentacruel.png" }, { "name": 'Geodude', "value": "geodude", "image": "img/geodude.png", "exclude": ['swsh'] }, { "name": 'Graveler', "value": "graveler", "image": "img/graveler.png", "exclude": ['swsh'] }, { "name": 'Golem', "value": "golem", "image": "img/golem.png", "exclude": ['swsh'] }, { "name": 'Ponyta', "value": "ponyta", "image": "img/ponyta.png" }, { "name": 'Rapidash', "value": "rapidash", "image": "img/rapidash.png" }, { "name": 'Slowpoke', "value": "slowpoke", "image": "img/slowpoke.png" }, { "name": 'Slowbro', "value": "slowbro", "image": "img/slowbro.png" }, { "name": 'Magnemite', "value": "magnemite", "image": "img/magnemite.png" }, { "name": 'Magneton', "value": "magneton", "image": "img/magneton.png" }, { "name": 'Farfetch\'d', "value": "farfetchd", "image": "img/farfetchd.png" }, { "name": 'Doduo', "value": "doduo", "image": "img/doduo.png", "exclude": ['swsh'] }, { "name": 'Dodrio', "value": "dodrio", "image": "img/dodrio.png", "exclude": ['swsh'] }, { "name": 'Seel', "value": "seel", "image": "img/seel.png", "exclude": ['swsh'] }, { "name": 'Dewgong', "value": "dewgong", "image": "img/dewgong.png", "exclude": ['swsh'] }, { "name": 'Grimer', "value": "grimer", "image": "img/grimer.png", "exclude": ['swsh'] }, { "name": 'Muk', "value": "muk", "image": "img/muk.png", "exclude": ['swsh'] }, { "name": 'Shellder', "value": "shellder", "image": "img/shellder.png" }, { "name": 'Cloyster', "value": "cloyster", "image": "img/cloyster.png" }, { "name": 'Gastly', "value": "gastly", "image": "img/gastly.png" }, { "name": 'Haunter', "value": "haunter", "image": "img/haunter.png" }, { "name": 'Gengar', "value": "gengar", "image": "img/gengar.png" }, { "name": 'Onix', "value": "onix", "image": "img/onix.png" }, { "name": 'Drowzee', "value": "drowzee", "image": "img/drowzee.png", "exclude": ['swsh'] }, { "name": 'Hypno', "value": "hypno", "image": "img/hypno.png", "exclude": ['swsh'] }, { "name": 'Krabby', "value": "krabby", "image": "img/krabby.png" }, { "name": 'Kingler', "value": "kingler", "image": "img/kingler.png" }, { "name": 'Voltorb', "value": "voltorb", "image": "img/voltorb.png", "exclude": ['swsh'] }, { "name": 'Electrode', "value": "electrode", "image": "img/electrode.png", "exclude": ['swsh'] }, { "name": 'Exeggcute', "value": "exeggcute", "image": "img/exeggcute.png" }, { "name": 'Exeggutor', "value": "exeggutor", "image": "img/exeggutor.png" }, { "name": 'Cubone', "value": "cubone", "image": "img/cubone.png" }, { "name": 'Marowak', "value": "marowak", "image": "img/marowak.png" }, { "name": 'Hitmonlee', "value": "hitmonlee", "image": "img/hitmonlee.png" }, { "name": 'Hitmonchan', "value": "hitmonchan", "image": "img/hitmonchan.png" }, { "name": 'Lickitung', "value": "lickitung", "image": "img/lickitung.png" }, { "name": 'Koffing', "value": "koffing", "image": "img/koffing.png" }, { "name": 'Weezing', "value": "weezing", "image": "img/weezing.png" }, { "name": 'Rhyhorn', "value": "rhyhorn", "image": "img/rhyhorn.png" }, { "name": 'Rhydon', "value": "rhydon", "image": "img/rhydon.png" }, { "name": 'Chansey', "value": "chansey", "image": "img/chansey.png" }, { "name": 'Tangela', "value": "tangela", "image": "img/tangela.png" }, { "name": 'Kangaskhan', "value": "kangaskhan", "image": "img/kangaskhan.png" }, { "name": 'Horsea', "value": "horsea", "image": "img/horsea.png" }, { "name": 'Seadra', "value": "seadra", "image": "img/seadra.png" }, { "name": 'Goldeen', "value": "goldeen", "image": "img/goldeen.png" }, { "name": 'Seaking', "value": "seaking", "image": "img/seaking.png" }, { "name": 'Staryu', "value": "staryu", "image": "img/staryu.png" }, { "name": 'Starmie', "value": "starmie", "image": "img/starmie.png" }, { "name": '<NAME>', "value": "mr-mime", "image": "img/mr-mime.png" }, { "name": 'Scyther', "value": "scyther", "image": "img/scyther.png" }, { "name": 'Jynx', "value": "jynx", "image": "img/jynx.png" }, { "name": 'Electabuzz', "value": "electabuzz", "image": "img/electabuzz.png" }, { "name": 'Magmar', "value": "magmar", "image": "img/magmar.png" }, { "name": 'Pinsir', "value": "pinsir", "image": "img/pinsir.png" }, { "name": 'Tauros', "value": "tauros", "image": "img/tauros.png" }, { "name": 'Magikarp', "value": "magikarp", "image": "img/magikarp.png" }, { "name": 'Gyarados', "value": "gyarados", "image": "img/gyarados.png" }, { "name": 'Lapras', "value": "lapras", "image": "img/lapras.png" }, { "name": 'Ditto', "value": "ditto", "image": "img/ditto.png" }, { "name": 'Eevee', "value": "eevee", "image": "img/eevee.png" }, { "name": 'Vaporeon', "value": "vaporeon", "image": "img/vaporeon.png" }, { "name": 'Jolteon', "value": "jolteon", "image": "img/jolteon.png" }, { "name": 'Flareon', "value": "flareon", "image": "img/flareon.png" }, { "name": 'Porygon', "value": "porygon", "image": "img/porygon.png" }, { "name": 'Omanyte', "value": "omanyte", "image": "img/omanyte.png" }, { "name": 'Omastar', "value": "omastar", "image": "img/omastar.png" }, { "name": 'Kabuto', "value": "kabuto", "image": "img/kabuto.png" }, { "name": 'Kabutops', "value": "kabutops", "image": "img/kabutops.png" }, { "name": 'Aerodactyl', "value": "aerodactyl", "image": "img/aerodactyl.png" }, { "name": 'Snorlax', "value": "snorlax", "image": "img/snorlax.png" }, { "name": 'Articuno', "value": "articuno", "image": "img/articuno.png" }, { "name": 'Zapdos', "value": "zapdos", "image": "img/zapdos.png" }, { "name": 'Moltres', "value": "moltres", "image": "img/moltres.png" }, { "name": 'Dratini', "value": "dratini", "image": "img/dratini.png" }, { "name": 'Dragonair', "value": "dragonair", "image": "img/dragonair.png" }, { "name": 'Dragonite', "value": "dragonite", "image": "img/dragonite.png" }, { "name": 'Mewtwo', "value": "mewtwo", "image": "img/mewtwo.png" }, { "name": 'Mew',
<gh_stars>1-10 """ Adapted from https://github.com/YujiaBao/Distributional-Signatures """ import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import \ pack_padded_sequence, pad_packed_sequence class BASE(nn.Module): ''' BASE model ''' def __init__(self, args): super(BASE, self).__init__() self.args = args # cached tensor for speed self.I_way = nn.Parameter(torch.eye(self.args.way, dtype=torch.float), requires_grad=False) def _compute_l2(self, XS, XQ): ''' Compute the pairwise l2 distance @param XS (support x): support_size x ebd_dim @param XQ (support x): query_size x ebd_dim @return dist: query_size x support_size ''' diff = XS.unsqueeze(0) - XQ.unsqueeze(1) dist = torch.norm(diff, dim=2) return dist def _compute_cos(self, XS, XQ): ''' Compute the pairwise cos distance @param XS (support x): support_size x ebd_dim @param XQ (support x): query_size x ebd_dim @return dist: query_size support_size ''' dot = torch.matmul( XS.unsqueeze(0).unsqueeze(-2), XQ.unsqueeze(1).unsqueeze(-1) ) dot = dot.squeeze(-1).squeeze(-1) scale = (torch.norm(XS, dim=1).unsqueeze(0) * torch.norm(XQ, dim=1).unsqueeze(1)) scale = torch.max(scale, torch.ones_like(scale) * 1e-8) dist = 1 - dot/scale return dist def reidx_y(self, YS, YQ): ''' Map the labels into 0,..., way @param YS: batch_size @param YQ: batch_size @return YS_new: batch_size @return YQ_new: batch_size ''' unique1, inv_S = torch.unique(YS, sorted=True, return_inverse=True) unique2, inv_Q = torch.unique(YQ, sorted=True, return_inverse=True) if len(unique1) != len(unique2): raise ValueError( 'Support set classes are different from the query set') if len(unique1) != self.args.way: raise ValueError( 'Support set classes are different from the number of ways') if int(torch.sum(unique1 - unique2).item()) != 0: raise ValueError( 'Support set classes are different from the query set classes') Y_new = torch.arange(start=0, end=self.args.way, dtype=unique1.dtype, device=unique1.device) return Y_new[inv_S], Y_new[inv_Q] def _init_mlp(self, in_d, hidden_ds, drop_rate): modules = [] for d in hidden_ds[:-1]: modules.extend([ nn.Dropout(drop_rate), nn.Linear(in_d, d), nn.ReLU()]) in_d = d modules.extend([ nn.Dropout(drop_rate), nn.Linear(in_d, hidden_ds[-1])]) return nn.Sequential(*modules) def _label2onehot(self, Y): ''' Map the labels into 0,..., way @param Y: batch_size @return Y_onehot: batch_size * ways ''' Y_onehot = F.embedding(Y, self.I_way) return Y_onehot @staticmethod def compute_acc(pred, true): ''' Compute the accuracy. @param pred: batch_size * num_classes @param true: batch_size ''' return torch.mean((torch.argmax(pred, dim=1) == true).float()).item() class R2D2(BASE): ''' META-LEARNING WITH DIFFERENTIABLE CLOSED-FORM SOLVERS ''' def __init__(self, ebd_dim, args): super(R2D2, self).__init__(args) self.ebd_dim = ebd_dim # meta parameters to learn self.lam = nn.Parameter(torch.tensor(-1, dtype=torch.float)) self.alpha = nn.Parameter(torch.tensor(0, dtype=torch.float)) self.beta = nn.Parameter(torch.tensor(1, dtype=torch.float)) # lambda and alpha is learned in the log space # cached tensor for speed self.I_support = nn.Parameter( torch.eye(self.args.shot * self.args.way, dtype=torch.float), requires_grad=False) self.I_way = nn.Parameter(torch.eye(self.args.way, dtype=torch.float), requires_grad=False) def _compute_w(self, XS, YS_onehot): ''' Compute the W matrix of ridge regression @param XS: support_size x ebd_dim @param YS_onehot: support_size x way @return W: ebd_dim * way ''' W = XS.t() @ torch.inverse( XS @ XS.t() + (10. ** self.lam) * self.I_support) @ YS_onehot return W def _label2onehot(self, Y): ''' Map the labels into 0,..., way @param Y: batch_size @return Y_onehot: batch_size * ways ''' Y_onehot = F.embedding(Y, self.I_way) return Y_onehot def forward(self, XS, YS, XQ, YQ): ''' @param XS (support x): support_size x ebd_dim @param YS (support y): support_size @param XQ (support x): query_size x ebd_dim @param YQ (support y): query_size @return acc @return loss ''' YS, YQ = self.reidx_y(YS, YQ) YS_onehot = self._label2onehot(YS) W = self._compute_w(XS, YS_onehot) pred = (10.0 ** self.alpha) * XQ @ W + self.beta loss = F.cross_entropy(pred, YQ) acc = BASE.compute_acc(pred, YQ) logprobas = F.log_softmax(pred, dim=-1) return acc, loss, logprobas class RNN(nn.Module): def __init__(self, input_dim, hidden_dim, num_layers, bidirectional, dropout): super(RNN, self).__init__() self.rnn = nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True, bidirectional=bidirectional, dropout=dropout) def _sort_tensor(self, input, lengths): ''' pack_padded_sequence requires the length of seq be in descending order to work. Returns the sorted tensor, the sorted seq length, and the indices for inverting the order. Input: input: batch_size, seq_len, * lengths: batch_size Output: sorted_tensor: batch_size-num_zero, seq_len, * sorted_len: batch_size-num_zero sorted_order: batch_size num_zero ''' sorted_lengths, sorted_order = lengths.sort(0, descending=True) sorted_input = input[sorted_order] _, invert_order = sorted_order.sort(0, descending=False) # Calculate the num. of sequences that have len 0 nonzero_idx = sorted_lengths.nonzero() num_nonzero = nonzero_idx.size()[0] num_zero = sorted_lengths.size()[0] - num_nonzero # temporarily remove seq with len zero sorted_input = sorted_input[:num_nonzero] sorted_lengths = sorted_lengths[:num_nonzero] return sorted_input, sorted_lengths, invert_order, num_zero def _unsort_tensor(self, input, invert_order, num_zero): ''' Recover the origin order Input: input: batch_size-num_zero, seq_len, hidden_dim invert_order: batch_size num_zero Output: out: batch_size, seq_len, * ''' if num_zero == 0: input = input[invert_order] else: dim0, dim1, dim2 = input.size() zero = torch.zeros((num_zero, dim1, dim2), device=input.device, dtype=input.dtype) input = torch.cat((input, zero), dim=0) input = input[invert_order] return input def forward(self, text, text_len): ''' Input: text, text_len text Variable batch_size * max_text_len * input_dim text_len Tensor batch_size Output: text text Variable batch_size * max_text_len * output_dim ''' # Go through the rnn # Sort the word tensor according to the sentence length, and pack them together sort_text, sort_len, invert_order, num_zero = self._sort_tensor(input=text, lengths=text_len) text = pack_padded_sequence(sort_text, lengths=sort_len.cpu().numpy(), batch_first=True) # Run through the word level RNN text, _ = self.rnn(text) # batch_size, max_doc_len, args.word_hidden_size # Unpack the output, and invert the sorting text = pad_packed_sequence(text, batch_first=True)[0] # batch_size, max_doc_len, rnn_size text = self._unsort_tensor(text, invert_order, num_zero) # batch_size, max_doc_len, rnn_size return text class META(nn.Module): def __init__(self, ebd, args): super(META, self).__init__() self.args = args self.ebd = ebd self.aux = get_embedding(args) self.ebd_dim = 768 input_dim = int(args.meta_idf) + self.aux.embedding_dim + \ int(args.meta_w_target) + int(args.meta_iwf) if args.meta_ebd: # abalation use distributional signatures with word ebd may fail input_dim += self.ebd_dim if args.embedding == 'meta': self.rnn = RNN(input_dim, 25, 1, True, 0) self.seq = nn.Sequential( nn.Dropout(self.args.dropout), nn.Linear(50, 1), ) else: # use a mlp to predict the weight individually self.seq = nn.Sequential( nn.Linear(input_dim, 50), nn.ReLU(), nn.Dropout(self.args.dropout), nn.Linear(50, 1)) def forward(self, data, return_score=False): ''' @param data dictionary @key text: batch_size * max_text_len @key text_len: batch_size @param return_score bool set to true for visualization purpose @return output: batch_size * embedding_dim ''' ebd = self.ebd(data) scale = self.compute_score(data, ebd) ebd = torch.sum(ebd * scale, dim=1) if return_score: return ebd, scale return ebd def _varlen_softmax(self, logit, text_len): ''' Compute softmax for sentences with variable length @param: logit: batch_size * max_text_len @param: text_len: batch_size @return: score: batch_size * max_text_len ''' logit = torch.exp(logit) mask = torch.arange( logit.size()[-1], device=logit.device, dtype=text_len.dtype).expand(*logit.size() ) < text_len.unsqueeze(-1) logit = mask.float() * logit score = logit / torch.sum(logit, dim=1, keepdim=True) return score def compute_score(self, data, ebd, return_stats=False): ''' Compute the weight for each word @param data dictionary @param return_stats bool return statistics (input and output) for visualization purpose @return scale: batch_size * max_text_len * 1 ''' # preparing the input for the meta model x = self.aux(data) if self.args.meta_idf: idf = F.embedding(data['text'], data['idf']).detach() x = torch.cat([x, idf], dim=-1) if self.args.meta_iwf: iwf = F.embedding(data['text'], data['iwf']).detach() x = torch.cat([x, iwf], dim=-1) if self.args.meta_ebd: x = torch.cat([x, ebd], dim=-1) if self.args.meta_w_target: if self.args.meta_target_entropy: w_target = ebd @ data['w_target'] w_target = F.softmax(w_target, dim=2) * F.log_softmax(w_target, dim=2) w_target = -torch.sum(w_target, dim=2, keepdim=True) w_target = 1.0 / w_target x = torch.cat([x, w_target.detach()], dim=-1) else: # for rr approxmiation, use the max weight to approximate # task-specific importance w_target = torch.abs(ebd @ data['w_target']) w_target = w_target.max(dim=2, keepdim=True)[0] x = torch.cat([x, w_target.detach()], dim=-1) if self.args.embedding == 'meta': # run the LSTM hidden = self.rnn(x, data['text_len']) else: hidden = x # predict the logit logit = self.seq(hidden).squeeze(-1) # batch_size * max_text_len score = self._varlen_softmax(logit, data['text_len']).unsqueeze(-1) if return_stats: return score.squeeze(), idf.squeeze(), w_target.squeeze() else: return score def get_embedding(args): ''' @return AUX module with aggregated embeddings or None if args.aux did not provide additional embeddings ''' aux = [] for ebd in args.auxiliary: if ebd == 'pos': aux.append(POS(args)) else: raise ValueError('Invalid argument for auxiliary ebd') if args.cuda != -1: aux = [a.cuda(args.cuda) for a in aux] model = AUX(aux, args) if args.cuda != -1: return model.cuda(args.cuda) else: return model class AVG(nn.Module): ''' An aggregation method that encodes every document by its average word embeddings. ''' def __init__(self, ebd, args): super(AVG, self).__init__() self.ebd = ebd self.ebd_dim = 768 def forward(self, ebd): ''' @param data dictionary @param weights placeholder used for maml @return output: batch_size * embedding_dim ''' ebd = self.ebd(data) # count length excluding <pad> and <unk>. is_zero = (torch.sum(torch.abs(ebd), dim=2) > 1e-8).float() soft_len = torch.sum(is_zero, dim=1, keepdim=True) soft_len[soft_len < 1] = 1 # # don't
missing_keys = [] unexpected_keys = [] error_msgs = [] # copy state_dict so _load_from_state_dict can modify it metadata = getattr(state_dict, "_metadata", None) state_dict = state_dict.copy() if metadata is not None: state_dict._metadata = metadata def load(module, prefix=""): local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {}) module._load_from_state_dict( state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs, ) for name, child in module._modules.items(): if child is not None: load(child, prefix + name + ".") start_prefix = "" if not hasattr(model, "bert") and any( s.startswith("bert.") for s in state_dict.keys() ): start_prefix = "bert." load(model, prefix=start_prefix) if len(missing_keys) > 0: logger.info( "Weights of {} not initialized from pretrained model: {}".format( model.__class__.__name__, missing_keys ) ) if len(unexpected_keys) > 0: logger.info( "Weights from pretrained model not used in {}: {}".format( model.__class__.__name__, unexpected_keys ) ) if len(error_msgs) > 0: raise RuntimeError( "Error(s) in loading state_dict for {}:\n\t{}".format( model.__class__.__name__, "\n\t".join(error_msgs) ) ) return model class BertModel(BertPreTrainedModel): def __init__(self, config): super(BertModel, self).__init__(config) self.embeddings = BertEmbeddings(config) self.encoder = BertEncoder(config) self.pooler = BertPooler(config) self.apply(self.init_bert_weights) def forward( self, input_ids, token_type_ids=None, attention_mask=None, output_attention_mask=False, model_distillation=False, output_all_encoded_layers=False, ): if attention_mask is None: attention_mask = torch.ones_like(input_ids) if token_type_ids is None: token_type_ids = torch.zeros_like(input_ids) extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) extended_attention_mask = extended_attention_mask.to( dtype=next(self.parameters()).dtype ) # fp16 compatibility extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 embedding_output = self.embeddings(input_ids, token_type_ids) encoded_layers = self.encoder(embedding_output, extended_attention_mask) encoded_layers, attention_layers = encoded_layers sequence_output = encoded_layers[-1] pooled_output = self.pooler(sequence_output) if output_attention_mask: return ( encoded_layers, attention_layers, pooled_output, extended_attention_mask, ) if model_distillation: return encoded_layers, attention_layers if not output_all_encoded_layers: encoded_layers = encoded_layers[-1] return encoded_layers, pooled_output class BertPredictionHeadTransform(nn.Module): def __init__(self, config): super(BertPredictionHeadTransform, self).__init__() # Need to unty it when we separate the dimensions of hidden and emb self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str) or ( sys.version_info[0] == 2 and isinstance(config.hidden_act, unicode) # noqa: F821 ): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states class BertLMPredictionHead(nn.Module): def __init__(self, config, bert_model_embedding_weights): super(BertLMPredictionHead, self).__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear( bert_model_embedding_weights.size(1), bert_model_embedding_weights.size(0), bias=False, ) self.decoder.weight = bert_model_embedding_weights self.bias = nn.Parameter(torch.zeros(bert_model_embedding_weights.size(0))) def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) + self.bias return hidden_states class BertOnlyMLMHead(nn.Module): def __init__(self, config, bert_model_embedding_weights): super(BertOnlyMLMHead, self).__init__() self.predictions = BertLMPredictionHead(config, bert_model_embedding_weights) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores class BertOnlyNSPHead(nn.Module): def __init__(self, config): super(BertOnlyNSPHead, self).__init__() self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, pooled_output): seq_relationship_score = self.seq_relationship(pooled_output) return seq_relationship_score class BertPreTrainingHeads(nn.Module): def __init__(self, config, bert_model_embedding_weights): super(BertPreTrainingHeads, self).__init__() self.predictions = BertLMPredictionHead(config, bert_model_embedding_weights) self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, sequence_output, pooled_output): prediction_scores = self.predictions(sequence_output) seq_relationship_score = self.seq_relationship(pooled_output) return prediction_scores, seq_relationship_score class BertForPreTraining(BertPreTrainedModel): """BERT model with pre-training heads. This module comprises the BERT model followed by the two pre-training heads: - the masked language modeling head, and - the next sentence classification head. Params: config: a BertConfig class instance with the configuration to build a new model. Inputs: `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length] with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts `extract_features.py`, `run_classifier.py` and `run_squad.py`) `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to a `sentence B` token (see BERT paper for more details). `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max input sequence length in the current batch. It's the mask that we typically use for attention when a batch has varying length sentences. `masked_lm_labels`: optional masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length] with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss is only computed for the labels set in [0, ..., vocab_size] `next_sentence_label`: optional next sentence classification loss: torch.LongTensor of shape [batch_size] with indices selected in [0, 1]. 0 => next sentence is the continuation, 1 => next sentence is a random sentence. Outputs: if `masked_lm_labels` and `next_sentence_label` are not `None`: Outputs the total_loss which is the sum of the masked language modeling loss and the next sentence classification loss. if `masked_lm_labels` or `next_sentence_label` is `None`: Outputs a tuple comprising - the masked language modeling logits of shape [batch_size, sequence_length, vocab_size], and - the next sentence classification logits of shape [batch_size, 2]. Example usage: ```python # Already been converted into WordPiece token ids input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]]) input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]]) token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]]) config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072) model = BertForPreTraining(config) masked_lm_logits_scores, seq_relationship_logits = model(input_ids, token_type_ids, input_mask) ``` """ def __init__(self, config): super(BertForPreTraining, self).__init__(config) self.bert = BertModel(config) self.cls = BertPreTrainingHeads( config, self.bert.embeddings.word_embeddings.weight ) self.apply(self.init_bert_weights) def forward( self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None, next_sentence_label=None, ): sequence_output, pooled_output = self.bert( input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False ) prediction_scores, seq_relationship_score = self.cls( sequence_output, pooled_output ) if masked_lm_labels is not None and next_sentence_label is not None: loss_fct = CrossEntropyLoss(ignore_index=-1) masked_lm_loss = loss_fct( prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1), ) next_sentence_loss = loss_fct( seq_relationship_score.view(-1, 2), next_sentence_label.view(-1) ) total_loss = masked_lm_loss + next_sentence_loss return total_loss elif masked_lm_labels is not None: loss_fct = CrossEntropyLoss(ignore_index=-1) masked_lm_loss = loss_fct( prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1), ) total_loss = masked_lm_loss return total_loss else: return prediction_scores, seq_relationship_score class BertForMaskedLM(BertPreTrainedModel): """BERT model with the masked language modeling head. This module comprises the BERT model followed by the masked language modeling head. Params: config: a BertConfig class instance with the configuration to build a new model. Inputs: `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length] with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts `extract_features.py`, `run_classifier.py` and `run_squad.py`) `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to a `sentence B` token (see BERT paper for more details). `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max input sequence length in the current batch. It's the mask that we typically use for attention when a batch has varying length sentences. `masked_lm_labels`: masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length] with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss is only computed for the labels set in [0, ..., vocab_size] Outputs: if `masked_lm_labels` is not `None`: Outputs the masked language modeling loss. if `masked_lm_labels` is `None`: Outputs the masked language modeling logits of shape [batch_size, sequence_length, vocab_size]. Example usage: ```python # Already been converted into WordPiece token ids input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]]) input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]]) token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]]) config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072) model = BertForMaskedLM(config) masked_lm_logits_scores = model(input_ids, token_type_ids, input_mask) ``` """ def __init__(self, config): super(BertForMaskedLM, self).__init__(config) self.bert = BertModel(config) self.cls = BertOnlyMLMHead(config, self.bert.embeddings.word_embeddings.weight) self.apply(self.init_bert_weights) def forward( self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None, output_att=False, infer=False, ): sequence_output, _ = self.bert( input_ids, token_type_ids, attention_mask, output_all_encoded_layers=True, output_att=output_att, ) if output_att: sequence_output, att_output = sequence_output prediction_scores = self.cls(sequence_output[-1]) if masked_lm_labels is not None: loss_fct = CrossEntropyLoss(ignore_index=-1) masked_lm_loss = loss_fct( prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1), ) if not output_att: return masked_lm_loss else: return masked_lm_loss, att_output else: if not output_att: return prediction_scores else: return prediction_scores, att_output class BertForSequenceClassification(BertPreTrainedModel): """BERT model for classification. This module is composed of the BERT model with a linear layer on top of the pooled output. Params: `config`: a BertConfig class instance with the configuration to build a new model. `num_labels`: the number of classes for the classifier. Default = 2. Inputs: `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
%s" % str(delta_p)); common.DebugPrint("update_step(): t = %s" % str(t)); assert delta_p.ndim < 3; #% Compute and apply the update if time_flag == 1: #t=t+delta_p[end]; t += delta_p[-1]; # t is scalar #delta_p = [delta_p(1:end-1); 0]; delta_p = np.r_[np.ravel(delta_p, order="F")[: -1], 0]; else: #delta_p = [delta_p(1:end); 0]; delta_p = np.r_[np.ravel(delta_p, order="F"), 0]; # np.zeros()... Try also np.r_[np.ravel(delta_p)] if common.MY_DEBUG_STDOUT: common.DebugPrint("update_step(): delta_p.shape = %s" % \ str(delta_p.shape)); #delta_p=reshape(delta_p,3,3); delta_p = delta_p.reshape( (3, 3), order="F" ); #warp_p = warp_p + delta_p; warp_p = warp_p + delta_p; #warp_p(3,3) = 1; warp_p[2, 2] = 1.0; if common.MY_DEBUG_STDOUT: common.DebugPrint("update_step(): warp_p.shape = %s" % \ str(warp_p.shape)); common.DebugPrint("update_step(): warp_p = %s" % str(warp_p)); common.DebugPrint("update_step(): delta_p.shape = %s" % \ str(delta_p.shape)); common.DebugPrint("update_step(): delta_p = %s" % str(delta_p)); return warp_p, t; # Note: r_capture is actually the cv2.VideoCapture object. #function [out]=short_time_seq(r_path, index, nof, imres, imformat) def short_time_seq(r_capture, index, nof, imres, imformat): if common.MY_DEBUG_STDOUT: common.DebugPrint("short_time_seq(): imres = %s" % str(imres)); common.DebugPrint("short_time_seq(): index = %s" % str(index)); common.DebugPrint("short_time_seq(): nof = %s" % str(nof)); """ # We don't need to do resizing here because imres is already "resized" if # it's the case if config.VIDEO_FRAME_RESIZE_SCALING_FACTOR != 1: out = np.empty( (imres[0] * config.VIDEO_FRAME_RESIZE_SCALING_FACTOR, \ imres[1] * config.VIDEO_FRAME_RESIZE_SCALING_FACTOR, \ nof), \ dtype=MATRIX_FLOAT_TYPE); else: #out = np.zeros( (imres[0], imres[1], nof), dtype=MATRIX_FLOAT_TYPE); out = np.empty( (imres[0], imres[1], nof), dtype=MATRIX_FLOAT_TYPE); """ #% nof: number of frames #out=zeros([imres nof]); #out = np.zeros( (imres[0], imres[1], nof) ); # This gives rather big differences in warp: out = np.zeros( (imres[0], imres[1], nof), dtype=np.uint8); out = np.empty( (imres[0], imres[1], nof), dtype=MATRIX_FLOAT_TYPE); #for i=-(nof-1)/2:(nof-1)/2 for i in range(-(nof-1) / 2, (nof-1) / 2 + 1): if common.MY_DEBUG_STDOUT: common.DebugPrint("short_time_seq(): i = %d" % i); common.DebugPrint("short_time_seq(): i + (nof + 1) / 2 = %d" % \ (i + (nof + 1) / 2)); #%Alex: sometimes it crashes here saying it doesn't find an image like 1999.jpeg, when the first frame is 2000.jpeg #fileName = [r_path num2str(index+i,'%.6d') imformat]; #% Alex #%index #%i #%fileName #out(:,:,i+(nof+1)/2)=imread(fileName); """ This error we get if we read an RGB frame, instead of gray (8bpp). ValueError: operands could not be broadcast together with shapes (240,320) (240,320,3). """ out[:, :, i + (nof + 1) / 2 - 1] = MyImageRead(r_capture, index + i); if common.MY_DEBUG_STDOUT: common.DebugPrint( \ "short_time_seq(): " \ "out[:, :, i + (nof + 1) / 2 - 1].shape = %s" % \ str(out[:, :, i + (nof + 1) / 2 - 1].shape)); common.DebugPrint( \ "short_time_seq(): " \ "out[:, :, i + (nof + 1) / 2 - 1].dtype = %s" % \ str(out[:, :, i + (nof + 1) / 2 - 1].dtype)); return out; # This function is available at http://www.mathworks.com/matlabcentral/fileexchange/25397-imgaussian """ function I=imgaussian(I,sigma,siz) % IMGAUSSIAN filters an 1D, 2D color/greyscale or 3D image with an % Gaussian filter. This function uses for filtering IMFILTER or if % compiled the fast mex code imgaussian.c . Instead of using a % multidimensional gaussian kernel, it uses the fact that a Gaussian % filter can be separated in 1D gaussian kernels. % % J=IMGAUSSIAN(I,SIGMA,SIZE) % % inputs, % I: The 1D, 2D greyscale/color, or 3D input image with % data type Single or Double % SIGMA: The sigma used for the Gaussian kernel % SIZE: Kernel size (single value) (default: sigma*6) % % outputs, % J: The gaussian filtered image % % note, compile the code with: mex imgaussian.c -v % % example, % I = im2double(imread('peppers.png')); % figure, imshow(imgaussian(I,10)); % % Function is written by D.Kroon University of Twente (September 2009) """ #function I=imgaussian(I,sigma,siz) def imgaussian(I, sigma, siz=-1): if common.MY_DEBUG_STDOUT: common.DebugPrint( \ "Entered imgaussian(I.shape=%s, sigma=%s, siz=%s)" % \ (str(I.shape), str(sigma), str(siz))); # Used only when doing multi-level ECC # TODO: Not tested WELL #if(~exist('siz','var')), siz=sigma*6; end if siz == -1: siz=sigma*6; """ From opencv2refman.pdf (also http://docs.opencv.org/doc/tutorials/imgproc/gausian_median_blur_bilateral_filter/gausian_median_blur_bilateral_filter.html#gaussian-filter): cv2.GaussianBlur(src, ksize, sigmaX[, dst[, sigmaY[, borderType ]]]) -> dst src - input image; the image can have any number of channels, which are processed inde-pendently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. dst - output image of the same size and type as src. ksize - Gaussian kernel size. ksize.width and ksize.height can differ but they both must be positive and odd. Or, they can be zero's and then they are computed from sigma* . sigmaX - Gaussian kernel standard deviation in X direction. sigmaY - Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, respectively (see getGaussianKernel() for details); to fully control the result regardless of possible future modifications of all this semantics, it is recommended to specify all of ksize, sigmaX, and sigmaY. borderType - pixel extrapolation method (see borderInterpolate() for details). The function convolves the source image with the specified Gaussian kernel. In-place filtering is supported. """ """ From http://docs.opencv.org/modules/imgproc/doc/filtering.html#void%20GaussianBlur%28InputArray%20src,%20OutputArray%20dst,%20Size%20ksize,%20double%20sigmaX,%20double%20sigmaY,%20int%20borderType%29 cv2.GaussianBlur(src, ksize, sigmaX[, dst[, sigmaY[, borderType]]]) -> dst Note: was getting an exception: "SystemError: new style getargs format but argument is not a tuple" when giving: res = cv2.GaussianBlur(src=I, ksize=(siz, siz), sigmaX=sigma); (see solution below and at http://stackoverflow.com/questions/13225525/system-error-new-style-getargs-format-but-argument-is-not-a-tuple-when-using) """ #TODO: test if GaussianBlur is equivalent #I = I.T; siz = int(siz); res = cv2.GaussianBlur(src=I, ksize=(siz, siz), sigmaX=sigma); #res = res.T; return res; #function I=imgaussian(I,sigma,siz) #% IMGAUSSIAN filters an 1D, 2D color/greyscale or 3D image with an #% Gaussian filter. This function uses for filtering IMFILTER or if #% compiled the fast mex code imgaussian.c . Instead of using a #% multidimensional gaussian kernel, it uses the fact that a Gaussian #% filter can be separated in 1D gaussian kernels. #% #% J=IMGAUSSIAN(I,SIGMA,SIZE) #% #% inputs, #% I: The 1D, 2D greyscale/color, or 3D input image with #% data type Single or Double #% SIGMA: The sigma used for the Gaussian kernel #% SIZE: Kernel size (single value) (default: sigma*6) #% #% outputs, #% J: The gaussian filtered image #% #% note, compile the code with: mex imgaussian.c -v #% #% example, #% I = im2double(imread('peppers.png')); #% figure, imshow(imgaussian(I,10)); #% #% Function is written by D.Kroon University of Twente (September 2009) #if(~exist('siz','var')), siz=sigma*6; end if sigma > 0: #% Make 1D Gaussian kernel #x=-ceil(siz/2):ceil(siz/2); x = range(-math.ceil(siz / 2.0), math.ceil(siz / 2.0) + 1); #H = exp(-(x.^2/(2*sigma^2))); H = np.exp(-(x ** 2 / (2.0 * pow(sigma, 2)))); #H = H/sum(H(:)); H = H / H[:].sum(); #% Filter each dimension with the 1D Gaussian kernels\ #if(ndims(I)==1) #if len(I.shape) == 1: if I.ndim == 1: assert False; #I=imfilter(I,H, 'same' ,'replicate'); I = imfilter(I, H, "same", "replicate"); #elseif(ndims(I)==2) elif I.ndim == 2: #Hx=reshape(H,[length(H) 1]); Hx = H.reshape((H.size, 1), order="F"); #Hy=reshape(H,[1 length(H)]); Hy = H.reshape((1, H.size), order="F"); #I=imfilter(imfilter(I,Hx, 'same' ,'replicate'),Hy, 'same' ,'replicate'); I = imfilter( \ imfilter(I, Hx, "same", "replicate"), \ Hy, "same", "replicate"); #elseif(ndims(I)==3) elif I.ndim == 3: assert False; """ if(size(I,3)<4) % Detect if 3D or color image Hx=reshape(H,[length(H) 1]); Hy=reshape(H,[1 length(H)]); for k=1:size(I,3) I(:,:,k)=imfilter(imfilter(I(:,:,k),Hx, 'same' ,'replicate'),Hy, 'same' ,'replicate'); end else Hx=reshape(H,[length(H) 1 1]); Hy=reshape(H,[1 length(H) 1]); Hz=reshape(H,[1 1 length(H)]); I=imfilter(imfilter(imfilter(I,Hx, 'same' ,'replicate'),Hy, 'same' ,'replicate'),Hz, 'same' ,'replicate'); """ else: if common.MY_DEBUG_STDOUT: common.DebugPrint( \ "imgaussian:input: unsupported input dimension"); assert False; return I; """ TODO: See Paper TPAMI2013, Appendix II for details on computation J_{\Phi}. jacobian_h is already implemented in the C++ OpenCV of ECC image (not video) registration implementation as calculate_jacobian_homography(src1, src2, jacobian, map_matrix)?? """ #function dW_dp = jacobian_h(nx, ny, warp_p,time_extention_flag,pixel_select) def jacobian_h(nx, ny, warp_p, time_extension_flag, pixel_select): if common.MY_DEBUG_STDOUT: #common.DebugPrint( \ print( \ "Entered jacobian_h(nx.shape=%s, ny.shape=%s, warp_p.shape=%s, " \ "time_extension_flag=%d, pixel_select=%d)" % \ (str(nx.shape), str(ny.shape), str(warp_p.shape), \ time_extension_flag, pixel_select)); if pixel_select == 0: #snx=numel(nx); snx = nx.size; #sny=numel(ny); sny = ny.size; #jacob_x = kron(nx,ones(sny, 1)); jacob_x = Matlab.kron(nx, np.ones( (sny, 1) ) ); if common.MY_DEBUG_STDOUT: common.DebugPrint("jacobian_h(): jacob_x.shape = %s" % \ str(jacob_x.shape)); #jacob_y = kron([ny]',ones(1,snx)); jacob_y = Matlab.kron(np.array([ny]).T, np.ones( (1, snx) ) ); if common.MY_DEBUG_STDOUT: common.DebugPrint("jacobian_h(): jacob_y.shape = %s" % \ str(jacob_y.shape)); #% jacob_x=nx(:,ones(1,sny))'; #% jacob_y=ny(:,ones(1,snx)); #jacob_zero = zeros(sny, snx); jacob_zero = np.zeros( (sny, snx) ); #jacob_one = ones(sny, snx); jacob_one = np.ones( (sny, snx) ); #% % Easy bits #% jac_x = kron([0:nx - 1],ones(ny,
= {curve.oid: curve for curve in supportedCurves} hexAt = "\x00" class PrivateKey: def __init__(self, curve=secp256k1, secret=None): self.curve = curve self.secret = secret or RandomInteger.between(1, curve.N - 1) def publicKey(self): curve = self.curve publicPoint = Math.multiply( p=curve.G, n=self.secret, N=curve.N, A=curve.A, P=curve.P, ) return PublicKey(point=publicPoint, curve=curve) def toString(self): return BinaryAscii.stringFromNumber(number=self.secret, length=self.curve.length()) def toDer(self): encodedPublicKey = self.publicKey().toString(encoded=True) return encodeSequence( encodeInteger(1), encodeOctetString(self.toString()), encodeConstructed(0, encodeOid(*self.curve.oid)), encodeConstructed(1, encodeBitString(encodedPublicKey)), ) def toPem(self): return toPem(der=toBytes(self.toDer()), name="EC PRIVATE KEY") @classmethod def fromPem(cls, string): privateKeyPem = string[string.index("-----BEGIN EC PRIVATE KEY-----"):] return cls.fromDer(fromPem(privateKeyPem)) @classmethod def fromDer(cls, string): t, empty = removeSequence(string) if len(empty) != 0: raise Exception( "trailing junk after DER private key: " + BinaryAscii.hexFromBinary(empty) ) one, t = removeInteger(t) if one != 1: raise Exception( "expected '1' at start of DER private key, got %d" % one ) privateKeyStr, t = removeOctetString(t) tag, curveOidStr, t = removeConstructed(t) if tag != 0: raise Exception("expected tag 0 in DER private key, got %d" % tag) oidCurve, empty = removeObject(curveOidStr) if len(empty) != 0: raise Exception( "trailing junk after DER private key curve_oid: %s" % BinaryAscii.hexFromBinary(empty) ) if oidCurve not in curvesByOid: raise Exception( "unknown curve with oid %s; The following are registered: %s" % ( oidCurve, ", ".join([curve.name for curve in supportedCurves]) ) ) curve = curvesByOid[oidCurve] if len(privateKeyStr) < curve.length(): privateKeyStr = hexAt * (curve.lenght() - len(privateKeyStr)) + privateKeyStr return cls.fromString(privateKeyStr, curve) @classmethod def fromString(cls, string, curve=secp256k1): return PrivateKey(secret=BinaryAscii.numberFromString(string), curve=curve) class Signature: def __init__(self, r, s, recoveryId=None): self.r = r self.s = s self.recoveryId = recoveryId def toDer(self, withRecoveryId=False): encodedSequence = encodeSequence(encodeInteger(self.r), encodeInteger(self.s)) if not withRecoveryId: return encodedSequence return chr(27 + self.recoveryId) + encodedSequence def toBase64(self, withRecoveryId=False): return toString(Base64.encode(toBytes(self.toDer(withRecoveryId=withRecoveryId)))) @classmethod def fromDer(cls, string, recoveryByte=False): recoveryId = None if recoveryByte: recoveryId = string[0] if isinstance(string[0], intTypes) else ord(string[0]) recoveryId -= 27 string = string[1:] rs, empty = removeSequence(string) if len(empty) != 0: raise Exception("trailing junk after DER signature: %s" % BinaryAscii.hexFromBinary(empty)) r, rest = removeInteger(rs) s, empty = removeInteger(rest) if len(empty) != 0: raise Exception("trailing junk after DER numbers: %s" % BinaryAscii.hexFromBinary(empty)) return Signature(r=r, s=s, recoveryId=recoveryId) @classmethod def fromBase64(cls, string, recoveryByte=False): der = Base64.decode(string) return cls.fromDer(der, recoveryByte) class Math: @classmethod def multiply(cls, p, n, N, A, P): """ Fast way to multily point and scalar in elliptic curves :param p: First Point to mutiply :param n: Scalar to mutiply :param N: Order of the elliptic curve :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :param A: Coefficient of the first-order term of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point that represents the sum of First and Second Point """ return cls._fromJacobian( cls._jacobianMultiply( cls._toJacobian(p), n, N, A, P, ), P, ) @classmethod def add(cls, p, q, A, P): """ Fast way to add two points in elliptic curves :param p: First Point you want to add :param q: Second Point you want to add :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :param A: Coefficient of the first-order term of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point that represents the sum of First and Second Point """ return cls._fromJacobian( cls._jacobianAdd( cls._toJacobian(p), cls._toJacobian(q), A, P, ), P, ) @classmethod def inv(cls, x, n): """ Extended Euclidean Algorithm. It's the 'division' in elliptic curves :param x: Divisor :param n: Mod for division :return: Value representing the division """ if x == 0: return 0 lm, hm = 1, 0 low, high = x % n, n while low > 1: r = high // low nm, new = hm - lm * r, high - low * r lm, low, hm, high = nm, new, lm, low return lm % n @classmethod def _toJacobian(cls, p): """ Convert point to Jacobian coordinates :param p: First Point you want to add :return: Point in Jacobian coordinates """ return Point(p.x, p.y, 1) @classmethod def _fromJacobian(cls, p, P): """ Convert point back from Jacobian coordinates :param p: First Point you want to add :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point in default coordinates """ z = cls.inv(p.z, P) return Point( (p.x * z ** 2) % P, (p.y * z ** 3) % P, ) @classmethod def _jacobianDouble(cls, p, A, P): """ Double a point in elliptic curves :param p: Point you want to double :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :param A: Coefficient of the first-order term of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point that represents the sum of First and Second Point """ if not p.y: return Point(0, 0, 0) ysq = (p.y ** 2) % P S = (4 * p.x * ysq) % P M = (3 * p.x ** 2 + A * p.z ** 4) % P nx = (M**2 - 2 * S) % P ny = (M * (S - nx) - 8 * ysq ** 2) % P nz = (2 * p.y * p.z) % P return Point(nx, ny, nz) @classmethod def _jacobianAdd(cls, p, q, A, P): """ Add two points in elliptic curves :param p: First Point you want to add :param q: Second Point you want to add :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :param A: Coefficient of the first-order term of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point that represents the sum of First and Second Point """ if not p.y: return q if not q.y: return p U1 = (p.x * q.z ** 2) % P U2 = (q.x * p.z ** 2) % P S1 = (p.y * q.z ** 3) % P S2 = (q.y * p.z ** 3) % P if U1 == U2: if S1 != S2: return Point(0, 0, 1) return cls._jacobianDouble(p, A, P) H = U2 - U1 R = S2 - S1 H2 = (H * H) % P H3 = (H * H2) % P U1H2 = (U1 * H2) % P nx = (R ** 2 - H3 - 2 * U1H2) % P ny = (R * (U1H2 - nx) - S1 * H3) % P nz = (H * p.z * q.z) % P return Point(nx, ny, nz) @classmethod def _jacobianMultiply(cls, p, n, N, A, P): """ Multily point and scalar in elliptic curves :param p: First Point to mutiply :param n: Scalar to mutiply :param N: Order of the elliptic curve :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :param A: Coefficient of the first-order term of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point that represents the sum of First and Second Point """ if p.y == 0 or n == 0: return Point(0, 0, 1) if n == 1: return p if n < 0 or n >= N: return cls._jacobianMultiply(p, n % N, N, A, P) if (n % 2) == 0: return cls._jacobianDouble( cls._jacobianMultiply( p, n // 2, N, A, P ), A, P, ) # (n % 2) == 1: return cls._jacobianAdd( cls._jacobianDouble( cls._jacobianMultiply( p, n // 2, N, A, P, ), A, P, ), p, A, P, ) class PublicKey: def __init__(self, point, curve): self.point = point self.curve = curve def toString(self, encoded=False): xString = BinaryAscii.stringFromNumber( number=self.point.x, length=self.curve.length(), ) yString = BinaryAscii.stringFromNumber( number=self.point.y, length=self.curve.length(), ) return "\x00\x04" + xString + yString if encoded else xString + yString def toDer(self): oidEcPublicKey = (1, 2, 840, 10045, 2, 1) encodeEcAndOid
further than max radius are stopped. Between the two, the velocity decreases linearly""" self._base_min_radius = (self._road_front_vehicles + self._road_extra_front_actors) * self._road_spawn_dist self._base_max_radius = (self._road_front_vehicles + self._road_extra_front_actors + 1) * self._road_spawn_dist self._min_radius = self._base_min_radius self._max_radius = self._base_max_radius def initialise(self): """Creates the background activity actors. Pressuposes that the ego is at a road""" self._create_junction_dict() ego_wp = self._route[0] self._road_ego_key = get_lane_key(ego_wp) same_dir_wps = get_same_dir_lanes(ego_wp) self._initialise_road_behavior(same_dir_wps, ego_wp) self._initialise_opposite_sources() self._initialise_road_checker() def update(self): new_status = py_trees.common.Status.RUNNING prev_ego_index = self._route_index # Check if the TM destroyed an actor if self._route_index > 0: self._check_background_actors() # Get ego's odometry. For robustness, the closest route point will be used location = CarlaDataProvider.get_location(self._ego_actor) ego_wp = self._update_ego_route_location(location) ego_transform = ego_wp.transform if self.debug: string = 'EGO_' + self._ego_state[0].upper() draw_string(self._world, location, string, self._ego_state, False) # Parameters and scenarios self._update_parameters() self._manage_break_scenario() # Update ego state if self._ego_state == 'junction': self._monitor_ego_junction_exit(ego_wp) self._monitor_nearby_junctions() # Update_actors if self._ego_state == 'junction': self._monitor_ego_junction_exit(ego_wp) self._update_junction_actors() self._update_junction_sources() else: self._update_road_actors(prev_ego_index, self._route_index) self._move_road_checker(prev_ego_index, self._route_index) self._move_opposite_sources(prev_ego_index, self._route_index) self._update_opposite_sources() # Update non junction sources self._update_opposite_actors(ego_transform) self._update_road_sources(ego_transform.location) self._monitor_scenario_4_end(ego_transform.location) return new_status def terminate(self, new_status): """Destroy all actors""" all_actors = self._get_actors() for actor in list(all_actors): self._destroy_actor(actor) super(BackgroundBehavior, self).terminate(new_status) def _get_actors(self): """Returns a list of all actors part of the background activity""" actors = self._road_actors + self._opposite_actors for junction in self._active_junctions: actors.extend(list(junction.actor_dict)) return actors def _check_background_actors(self): """Checks if the Traffic Manager has removed a backgroudn actor""" background_actors = self._get_actors() alive_ids = [actor.id for actor in self._world.get_actors().filter('vehicle*')] for actor in background_actors: if actor.id not in alive_ids: self._remove_actor_info(actor) ################################ ## Junction cache ## ################################ def _create_junction_dict(self): """Extracts the junctions the ego vehicle will pass through.""" data = self._get_junctions_data() fake_data, filtered_data = self._filter_fake_junctions(data) self._get_fake_lane_pairs(fake_data) route_data = self._join_complex_junctions(filtered_data) self._add_junctions_topology(route_data) self._junctions = route_data def _get_junctions_data(self): """Gets all the junctions the ego passes through""" junction_data = [] junction_num = 0 start_index = 0 # Ignore the junction the ego spawns at for i in range(0, self._route_length - 1): if not self._is_junction(self._route[i]): start_index = i break for i in range(start_index, self._route_length - 1): next_wp = self._route[i+1] prev_junction = junction_data[-1] if len(junction_data) > 0 else None # Searching for the junction exit if prev_junction and prev_junction.route_exit_index is None: if not self._is_junction(next_wp) or next_wp.get_junction().id != junction_id: prev_junction.route_exit_index = i+1 # Searching for a junction elif self._is_junction(next_wp): junction_id = next_wp.get_junction().id if prev_junction: start_dist = self._accum_dist[i] prev_end_dist = self._accum_dist[prev_junction.route_exit_index] prev_junction.exit_road_length = start_dist - prev_end_dist # Same junction as the prev one and closer than 2 meters if prev_junction and prev_junction.junctions[-1].id == junction_id: start_dist = self._accum_dist[i] prev_end_dist = self._accum_dist[prev_junction.route_exit_index] distance = start_dist - prev_end_dist if distance < 2: prev_junction.junctions.append(next_wp.get_junction()) prev_junction.route_exit_index = None continue junction_data.append(Junction(next_wp.get_junction(), junction_num, i)) junction_num += 1 if len(junction_data) > 0: road_end_dist = self._accum_dist[self._route_length - 1] if junction_data[-1].route_exit_index: route_start_dist = self._accum_dist[junction_data[-1].route_exit_index] else: route_start_dist = self._accum_dist[self._route_length - 1] junction_data[-1].exit_road_length = road_end_dist - route_start_dist return junction_data def _filter_fake_junctions(self, data): """ Filters fake junctions. As a general note, a fake junction is that where no road lane divide in two. However, this might fail for some CARLA maps, so check junctions which have all lanes straight too """ fake_data = [] filtered_data = [] threshold = math.radians(15) for junction_data in data: used_entry_lanes = [] used_exit_lanes = [] for junction in junction_data.junctions: for entry_wp, exit_wp in junction.get_waypoints(carla.LaneType.Driving): entry_wp = self._get_junction_entry_wp(entry_wp) if not entry_wp: continue if get_lane_key(entry_wp) not in used_entry_lanes: used_entry_lanes.append(get_lane_key(entry_wp)) exit_wp = self._get_junction_exit_wp(exit_wp) if not exit_wp: continue if get_lane_key(exit_wp) not in used_exit_lanes: used_exit_lanes.append(get_lane_key(exit_wp)) if not used_entry_lanes and not used_exit_lanes: fake_data.append(junction_data) continue found_turn = False for entry_wp, exit_wp in junction_data.junctions[0].get_waypoints(carla.LaneType.Driving): entry_heading = entry_wp.transform.get_forward_vector() exit_heading = exit_wp.transform.get_forward_vector() dot = entry_heading.x * exit_heading.x + entry_heading.y * exit_heading.y if dot < math.cos(threshold): found_turn = True break if not found_turn: fake_data.append(junction_data) else: filtered_data.append(junction_data) return fake_data, filtered_data def _get_complex_junctions(self): """ Function to hardcode the topology of some complex junctions. This is done for the roundabouts, as the current API doesn't offer that info as well as others such as the gas station at Town04. If there are micro lanes between connected junctions, add them to the fake_lane_keys, connecting them when their topology is calculated """ complex_junctions = [] fake_lane_keys = [] if 'Town03' in self._map.name: # Roundabout, take it all as one complex_junctions.append([ self._map.get_waypoint_xodr(1100, -5, 16.6).get_junction(), self._map.get_waypoint_xodr(1624, -5, 25.3).get_junction(), self._map.get_waypoint_xodr(1655, -5, 8.3).get_junction(), self._map.get_waypoint_xodr(1772, 3, 16.2).get_junction(), self._map.get_waypoint_xodr(1206, -5, 5.9).get_junction()]) fake_lane_keys.extend([ ['37*-4', '36*-4'], ['36*-4', '37*-4'], ['37*-5', '36*-5'], ['36*-5', '37*-5'], ['38*-4', '12*-4'], ['12*-4', '38*-4'], ['38*-5', '12*-5'], ['12*-5', '38*-5']]) # Gas station complex_junctions.append([ self._map.get_waypoint_xodr(1031, -1, 11.3).get_junction(), self._map.get_waypoint_xodr(100, -1, 18.8).get_junction(), self._map.get_waypoint_xodr(1959, -1, 22.7).get_junction()]) fake_lane_keys.extend([ ['32*-2', '33*-2'], ['33*-2', '32*-2'], ['32*-1', '33*-1'], ['33*-1', '32*-1'], ['32*4', '33*4'], ['33*4', '32*4'], ['32*5', '33*5'], ['33*5', '32*5']]) elif 'Town04' in self._map.name: # Gas station complex_junctions.append([ self._map.get_waypoint_xodr(518, -1, 8.1).get_junction(), self._map.get_waypoint_xodr(886, 1, 10.11).get_junction(), self._map.get_waypoint_xodr(467, 1, 25.8).get_junction()]) self._fake_lane_pair_keys.extend(fake_lane_keys) return complex_junctions def _join_complex_junctions(self, filtered_data): """ Joins complex junctions into one. This makes it such that all the junctions, as well as their connecting lanes, are treated as the same junction """ route_data = [] prev_index = -1 # If entering a complex, add all its junctions to the list for junction_data in filtered_data: junction = junction_data.junctions[0] prev_junction = route_data[-1] if len(route_data) > 0 else None complex_junctions = self._get_complex_junctions() # Get the complex index current_index = -1 for i, complex_junctions in enumerate(complex_junctions): complex_ids = [j.id for j in complex_junctions] if junction.id in complex_ids: current_index = i break if current_index == -1: # Outside a complex, add it route_data.append(junction_data) elif current_index == prev_index: # Same complex as the previous junction prev_junction.route_exit_index = junction_data.route_exit_index else: # New complex, add it junction_ids = [j.id for j in junction_data.junctions] for complex_junction in complex_junctions: if complex_junction.id not in junction_ids: junction_data.junctions.append(complex_junction) route_data.append(junction_data) prev_index = current_index return route_data def _get_fake_lane_pairs(self, fake_data): """Gets a list of entry-exit lanes of the fake junctions""" for fake_junctions_data in fake_data: for junction in fake_junctions_data.junctions: for entry_wp, exit_wp in junction.get_waypoints(carla.LaneType.Driving): while self._is_junction(entry_wp): entry_wps = entry_wp.previous(0.5) if len(entry_wps) == 0: break # Stop when there's no prev entry_wp = entry_wps[0] if self._is_junction(entry_wp): continue # Triggered by the loops break while self._is_junction(exit_wp): exit_wps = exit_wp.next(0.5) if len(exit_wps) == 0: break # Stop when there's no prev exit_wp = exit_wps[0] if self._is_junction(exit_wp): continue # Triggered by the loops break self._fake_junction_ids.append(junction.id) self._fake_lane_pair_keys.append([get_lane_key(entry_wp), get_lane_key(exit_wp)]) def _get_junction_entry_wp(self, entry_wp): """For a junction waypoint, returns a waypoint outside of it that entrys into its lane""" # Exit the junction while self._is_junction(entry_wp): entry_wps = entry_wp.previous(0.2) if len(entry_wps) == 0: return None # Stop when there's no prev entry_wp = entry_wps[0] return entry_wp def _get_junction_exit_wp(self, exit_wp): """For a junction waypoint, returns a waypoint outside of it from which the lane exits the junction""" while self._is_junction(exit_wp): exit_wps = exit_wp.next(0.2) if len(exit_wps) == 0: return None # Stop when there's no prev exit_wp = exit_wps[0] return exit_wp def _get_closest_junction_waypoint(self, waypoint, junction_wps): """ Matches a given wp to another one inside the list. This is first done by checking its key, and if this fails, the closest wp is chosen """ # Check the lane keys junction_keys = [get_lane_key(waypoint_) for waypoint_ in junction_wps] if get_lane_key(waypoint) in junction_keys: return waypoint # Get the closest one closest_dist = float('inf') closest_junction_wp = None route_location = waypoint.transform.location for junction_wp in junction_wps: distance = junction_wp.transform.location.distance(route_location) if distance < closest_dist: closest_dist = distance closest_junction_wp = junction_wp return closest_junction_wp def _is_route_wp_behind_junction_wp(self, route_wp, junction_wp): """Checks if an actor is behind the ego. Uses the route transform""" route_location = route_wp.transform.location junction_transform = junction_wp.transform junction_heading = junction_transform.get_forward_vector() wps_vec = route_location - junction_transform.location if junction_heading.x * wps_vec.x + junction_heading.y * wps_vec.y < - 0.09: # 85º return True return False def _add_junctions_topology(self, route_data): """Gets the entering and exiting lanes of a multijunction""" for junction_data in route_data: used_entry_lanes = [] used_exit_lanes = [] entry_lane_wps = [] exit_lane_wps = [] if self.debug: print(' --------------------- ') for junction in junction_data.junctions: for entry_wp, exit_wp in junction.get_waypoints(carla.LaneType.Driving): entry_wp = self._get_junction_entry_wp(entry_wp) if not entry_wp: continue if get_lane_key(entry_wp) not in used_entry_lanes: used_entry_lanes.append(get_lane_key(entry_wp)) entry_lane_wps.append(entry_wp) if self.debug: draw_point(self._world, entry_wp.transform.location, 'small', 'entry', True) exit_wp = self._get_junction_exit_wp(exit_wp) if not exit_wp: continue if get_lane_key(exit_wp) not in used_exit_lanes: used_exit_lanes.append(get_lane_key(exit_wp)) exit_lane_wps.append(exit_wp) if self.debug: draw_point(self._world, exit_wp.transform.location, 'small', 'exit', True) #
<reponame>jzcmyz/OpenManage-Enterprise # # _author_ = <NAME> <<EMAIL>> # # Copyright (c) 2021 Dell EMC Corporation # # 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. # """ #### Synopsis Retrieves the warranty information for all devices on an OME instance. #### Description You can provide a keyword argument to filter devices by the service description. For example you can specify 'pro' and that would match a Service Level Description of 'Silver Support or ProSupport' For authentication X-Auth is used over Basic Authentication Note that the credentials entered are not stored to disk. #### Example python get_warranty_information.py --ip 192.168.1.93 --user admin --password password --warranty-keyword prosupport --out-file <csv_file> """ import argparse import csv import json import sys from argparse import RawTextHelpFormatter from getpass import getpass from os.path import isfile from pprint import pprint from urllib.parse import urlparse try: import urllib3 import requests except ModuleNotFoundError: print("This program requires urllib3 and requests. To install them on most systems run `pip install requests" "urllib3`") sys.exit(0) def authenticate(ome_ip_address: str, ome_username: str, ome_password: str) -> dict: """ Authenticates with OME and creates a session Args: ome_ip_address: IP address of the OME server ome_username: Username for OME ome_password: OME password Returns: A dictionary of HTTP headers Raises: Exception: A generic exception in the event of a failure to connect """ authenticated_headers = {'content-type': 'application/json'} session_url = 'https://%s/api/SessionService/Sessions' % ome_ip_address user_details = {'UserName': ome_username, 'Password': <PASSWORD>, 'SessionType': 'API'} try: session_info = requests.post(session_url, verify=False, data=json.dumps(user_details), headers=authenticated_headers) except requests.exceptions.ConnectionError: print("Failed to connect to OME. This typically indicates a network connectivity problem. Can you ping OME?") sys.exit(0) if session_info.status_code == 201: authenticated_headers['X-Auth-Token'] = session_info.headers['X-Auth-Token'] return authenticated_headers print("There was a problem authenticating with OME. Are you sure you have the right username, password, " "and IP?") raise Exception("There was a problem authenticating with OME. Are you sure you have the right username, " "password, and IP?") def get_data(authenticated_headers: dict, url: str, odata_filter: str = None, max_pages: int = None) -> dict: """ This function retrieves data from a specified URL. Get requests from OME return paginated data. The code below handles pagination. This is the equivalent in the UI of a list of results that require you to go to different pages to get a complete listing. Args: authenticated_headers: A dictionary of HTTP headers generated from an authenticated session with OME url: The API url against which you would like to make a request odata_filter: An optional parameter for providing an odata filter to run against the API endpoint. max_pages: The maximum number of pages you would like to return Returns: Returns a dictionary of data received from OME """ next_link_url = None if odata_filter: count_data = requests.get(url + '?$filter=' + odata_filter, headers=authenticated_headers, verify=False) if count_data.status_code == 400: print("Received an error while retrieving data from %s:" % url + '?$filter=' + odata_filter) pprint(count_data.json()['error']) return {} count_data = count_data.json() if count_data['@odata.count'] <= 0: print("No results found!") return {} else: count_data = requests.get(url, headers=authenticated_headers, verify=False).json() if 'value' in count_data: data = count_data['value'] else: data = count_data if '@odata.nextLink' in count_data: # Grab the base URI next_link_url = '{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url)) + count_data['@odata.nextLink'] i = 1 while next_link_url is not None: # Break if we have reached the maximum number of pages to be returned if max_pages: if i >= max_pages: break else: i = i + 1 response = requests.get(next_link_url, headers=authenticated_headers, verify=False) next_link_url = None if response.status_code == 200: requested_data = response.json() if requested_data['@odata.count'] <= 0: print("No results found!") return {} # The @odata.nextLink key is only present in data if there are additional pages. We check for it and if it # is present we get a link to the page with the next set of results. if '@odata.nextLink' in requested_data: next_link_url = '{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url)) + \ requested_data['@odata.nextLink'] if 'value' in requested_data: data += requested_data['value'] else: data += requested_data else: print("Unknown error occurred. Received HTTP response code: " + str(response.status_code) + " with error: " + response.text) raise Exception("Unknown error occurred. Received HTTP response code: " + str(response.status_code) + " with error: " + response.text) return data def query_yes_no(question: str, default: str = "yes") -> bool: """ Prompts the user with a yes/no question Args: question: The question to ask the user default: Whether the default answer is no or yes. Defaults to yes Returns: A boolean - true if yes and false if no """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n") def confirm_isvalid(output_filepath: str = "", input_filepath: str = "") -> bool: """ Tests whether a filepath is valid or not. You can only provide either input_filepath or output_filepath. Not both. Args: output_filepath: The path to an output file you want to test input_filepath:The path to an input file you want to test Returns: Returns true if the path is valid and false if it is not """ if input_filepath != "" and output_filepath != "": print("You can only provide either an InputFilePath or an OutputFilePath.") sys.exit(0) if isfile(output_filepath): if not query_yes_no(output_filepath + " already exists? Do you want to continue? (y/n): ", "no"): return False if output_filepath: try: open(output_filepath, 'w') except OSError: print("The filepath %s does not appear to be valid. This could be due to an incorrect path or a permissions" " issue." % output_filepath) return False if input_filepath: try: open(input_filepath, 'r') return True except OSError: print("The filepath %s does not appear to be valid. This could be due to an incorrect path or a permissions" " issue." % input_filepath) return False if __name__ == '__main__': urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) parser = argparse.ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter) parser.add_argument("--ip", "-i", required=True, help="OME Appliance IP") parser.add_argument("--user", "-u", required=False, help="Username for OME Appliance", default="admin") parser.add_argument("--password", "-p", required=False, help="Password for OME Appliance") parser.add_argument("--out-file", "-f", required=False, help="The name of a file to which you want to write your VLANs") parser.add_argument("--warranty-keyword", "-k", required=False, type=str, help="Performs a case insensitive search against the field 'Service Level Description' in the " "OME UI. This allows you to search for a specific type of warranty. For example, searching" " prosupport would return all warranties with the word prosupport in their description.") args = parser.parse_args() base_uri = 'https://%s/api/WarrantyService/Warranties' % args.ip if not args.password: if not sys.stdin.isatty(): # notify user that they have a bad terminal # perhaps if os.name == 'nt': , prompt them to use winpty? print("Your terminal is not compatible with Python's getpass module. You will need to provide the" " --password argument instead. See https://stackoverflow.com/a/58277159/4427375") sys.exit(0) else: password = getpass() else: password = args.password try: headers = authenticate(args.ip, args.user, password) if not headers: sys.exit(0) print("Sending the request to OME...") warranty_info = get_data(headers, base_uri) if warranty_info: if args.warranty_keyword: # Use a list comprehension to filter the dictionaries warranty_info = [warranty for warranty in warranty_info if args.warranty_keyword.lower() in warranty['ServiceLevelDescription'].lower()] if args.out_file: if not confirm_isvalid(output_filepath=args.out_file): sys.exit(0) # Use UTF 8 in case there are non-ASCII characters like 格蘭特 print("Writing CSV to file...") with open(args.out_file, 'w', encoding='utf-8', newline='') as csv_file: # This code takes the list of dictionaries called warranty info, extracts the first dictionary in # the list, which we assume will have keys identical to the other dictionaries in the list, # creates an iterable from its keys, and then runs it through a
RiskMeasureUnit) else get_enum_value(RiskMeasureUnit, value) self._property_changed('unit') class CSLCurrencyArray(Base): """An array of currencies""" def __init__(self, currencyValues: Tuple[CSLCurrency, ...] = None): super().__init__() self.__currencyValues = currencyValues @property def currencyValues(self) -> Tuple[CSLCurrency, ...]: """A currency""" return self.__currencyValues @currencyValues.setter def currencyValues(self, value: Tuple[CSLCurrency, ...]): self.__currencyValues = value self._property_changed('currencyValues') class CSLSchedule(Base): """A schedule""" def __init__(self, firstDate: datetime.date = None, lastDate: datetime.date = None, calendarName: str = None, period: str = None, delay: str = None, businessDayConvention: str = None, dayCountConvention: str = None, daysPerTerm: str = None, delayBusinessDayConvention: str = None, delayCalendarName: str = None, hasResetDate: bool = None, termFormula: str = None, extraDates: Tuple[CSLDateArrayNamedParam, ...] = None, extraDatesByOffset: Tuple[CSLSymCaseNamedParam, ...] = None): super().__init__() self.__firstDate = firstDate self.__lastDate = lastDate self.__calendarName = calendarName self.__period = period self.__delay = delay self.__businessDayConvention = businessDayConvention self.__dayCountConvention = dayCountConvention self.__daysPerTerm = daysPerTerm self.__delayBusinessDayConvention = delayBusinessDayConvention self.__delayCalendarName = delayCalendarName self.__hasResetDate = hasResetDate self.__termFormula = termFormula self.__extraDates = extraDates self.__extraDatesByOffset = extraDatesByOffset @property def firstDate(self) -> datetime.date: """ISO 8601-formatted date""" return self.__firstDate @firstDate.setter def firstDate(self, value: datetime.date): self.__firstDate = value self._property_changed('firstDate') @property def lastDate(self) -> datetime.date: """ISO 8601-formatted date""" return self.__lastDate @lastDate.setter def lastDate(self, value: datetime.date): self.__lastDate = value self._property_changed('lastDate') @property def calendarName(self) -> str: """The name of the holiday calendar""" return self.__calendarName @calendarName.setter def calendarName(self, value: str): self.__calendarName = value self._property_changed('calendarName') @property def period(self) -> str: """Tenor""" return self.__period @period.setter def period(self, value: str): self.__period = value self._property_changed('period') @property def delay(self) -> str: """Tenor""" return self.__delay @delay.setter def delay(self, value: str): self.__delay = value self._property_changed('delay') @property def businessDayConvention(self) -> str: return self.__businessDayConvention @businessDayConvention.setter def businessDayConvention(self, value: str): self.__businessDayConvention = value self._property_changed('businessDayConvention') @property def dayCountConvention(self) -> str: return self.__dayCountConvention @dayCountConvention.setter def dayCountConvention(self, value: str): self.__dayCountConvention = value self._property_changed('dayCountConvention') @property def daysPerTerm(self) -> str: return self.__daysPerTerm @daysPerTerm.setter def daysPerTerm(self, value: str): self.__daysPerTerm = value self._property_changed('daysPerTerm') @property def delayBusinessDayConvention(self) -> str: return self.__delayBusinessDayConvention @delayBusinessDayConvention.setter def delayBusinessDayConvention(self, value: str): self.__delayBusinessDayConvention = value self._property_changed('delayBusinessDayConvention') @property def delayCalendarName(self) -> str: """The name of the holiday calendar""" return self.__delayCalendarName @delayCalendarName.setter def delayCalendarName(self, value: str): self.__delayCalendarName = value self._property_changed('delayCalendarName') @property def hasResetDate(self) -> bool: return self.__hasResetDate @hasResetDate.setter def hasResetDate(self, value: bool): self.__hasResetDate = value self._property_changed('hasResetDate') @property def termFormula(self) -> str: return self.__termFormula @termFormula.setter def termFormula(self, value: str): self.__termFormula = value self._property_changed('termFormula') @property def extraDates(self) -> Tuple[CSLDateArrayNamedParam, ...]: """A named array of dates""" return self.__extraDates @extraDates.setter def extraDates(self, value: Tuple[CSLDateArrayNamedParam, ...]): self.__extraDates = value self._property_changed('extraDates') @property def extraDatesByOffset(self) -> Tuple[CSLSymCaseNamedParam, ...]: """A named tenor.""" return self.__extraDatesByOffset @extraDatesByOffset.setter def extraDatesByOffset(self, value: Tuple[CSLSymCaseNamedParam, ...]): self.__extraDatesByOffset = value self._property_changed('extraDatesByOffset') class DataSetFieldMap(Base): """The mapping between data set field and risk measure type""" def __init__(self, dataSetId: str, field: str, resultsField: str, riskMeasure: RiskMeasure): super().__init__() self.__dataSetId = dataSetId self.__field = field self.__resultsField = resultsField self.__riskMeasure = riskMeasure @property def dataSetId(self) -> str: """Unique id of dataset.""" return self.__dataSetId @dataSetId.setter def dataSetId(self, value: str): self.__dataSetId = value self._property_changed('dataSetId') @property def field(self) -> str: """The field for data set, e.g. rate""" return self.__field @field.setter def field(self, value: str): self.__field = value self._property_changed('field') @property def resultsField(self) -> str: """The source field in the results, e.g. value or fixedRate""" return self.__resultsField @resultsField.setter def resultsField(self, value: str): self.__resultsField = value self._property_changed('resultsField') @property def riskMeasure(self) -> RiskMeasure: """The measure to perform risk on. Each risk measure consists of an asset class, a measure type, and a unit.""" return self.__riskMeasure @riskMeasure.setter def riskMeasure(self, value: RiskMeasure): self.__riskMeasure = value self._property_changed('riskMeasure') class FieldFilterMap(Base): def __init__(self, **kwargs): super().__init__() self.__queueClockTimeLabel = kwargs.get('queueClockTimeLabel') self.__marketPnl = kwargs.get('marketPnl') self.__year = kwargs.get('year') self.__sustainAsiaExJapan = kwargs.get('sustainAsiaExJapan') self.__investmentRate = kwargs.get('investmentRate') self.__assetClassificationsGicsSubIndustry = kwargs.get('assetClassificationsGicsSubIndustry') self.__mdapiClass = kwargs.get('mdapiClass') self.__bidUnadjusted = kwargs.get('bidUnadjusted') self.__economicTermsHash = kwargs.get('economicTermsHash') self.__neighbourAssetId = kwargs.get('neighbourAssetId') self.__simonIntlAssetTags = kwargs.get('simonIntlAssetTags') self.__path = kwargs.get('path') self.__availableInventory = kwargs.get('availableInventory') self.__clientContact = kwargs.get('clientContact') self.__est1DayCompletePct = kwargs.get('est1DayCompletePct') self.__rank = kwargs.get('rank') self.__mixedSwapOtherReportedSDR = kwargs.get('mixedSwapOtherReportedSDR') self.__dataSetCategory = kwargs.get('dataSetCategory') self.__createdById = kwargs.get('createdById') self.__vehicleType = kwargs.get('vehicleType') self.__dailyRisk = kwargs.get('dailyRisk') self.__bosInBpsLabel = kwargs.get('bosInBpsLabel') self.__energy = kwargs.get('energy') self.__marketDataType = kwargs.get('marketDataType') self.__sentimentScore = kwargs.get('sentimentScore') self.__bosInBps = kwargs.get('bosInBps') self.__pointClass = kwargs.get('pointClass') self.__fxSpot = kwargs.get('fxSpot') self.__bidLow = kwargs.get('bidLow') self.__valuePrevious = kwargs.get('valuePrevious') self.__fairVarianceVolatility = kwargs.get('fairVarianceVolatility') self.__avgTradeRate = kwargs.get('avgTradeRate') self.__shortLevel = kwargs.get('shortLevel') self.__hedgeVolatility = kwargs.get('hedgeVolatility') self.__version = kwargs.get('version') self.__tags = kwargs.get('tags') self.__underlyingAssetId = kwargs.get('underlyingAssetId') self.__clientExposure = kwargs.get('clientExposure') self.__correlation = kwargs.get('correlation') self.__exposure = kwargs.get('exposure') self.__gsSustainSubSector = kwargs.get('gsSustainSubSector') self.__domain = kwargs.get('domain') self.__marketDataAsset = kwargs.get('marketDataAsset') self.__forwardTenor = kwargs.get('forwardTenor') self.__unadjustedHigh = kwargs.get('unadjustedHigh') self.__sourceImportance = kwargs.get('sourceImportance') self.__eid = kwargs.get('eid') self.__jsn = kwargs.get('jsn') self.__relativeReturnQtd = kwargs.get('relativeReturnQtd') self.__displayName = kwargs.get('displayName') self.__minutesToTrade100Pct = kwargs.get('minutesToTrade100Pct') self.__marketModelId = kwargs.get('marketModelId') self.__quoteType = kwargs.get('quoteType') self.__realizedCorrelation = kwargs.get('realizedCorrelation') self.__tenor = kwargs.get('tenor') self.__esPolicyPercentile = kwargs.get('esPolicyPercentile') self.__atmFwdRate = kwargs.get('atmFwdRate') self.__tcmCostParticipationRate75Pct = kwargs.get('tcmCostParticipationRate75Pct') self.__close = kwargs.get('close') self.__tcmCostParticipationRate100Pct = kwargs.get('tcmCostParticipationRate100Pct') self.__disclaimer = kwargs.get('disclaimer') self.__measureIdx = kwargs.get('measureIdx') self.__a = kwargs.get('a') self.__b = kwargs.get('b') self.__loanFee = kwargs.get('loanFee') self.__c = kwargs.get('c') self.__equityVega = kwargs.get('equityVega') self.__lenderPayment = kwargs.get('lenderPayment') self.__deploymentVersion = kwargs.get('deploymentVersion') self.__fiveDayMove = kwargs.get('fiveDayMove') self.__borrower = kwargs.get('borrower') self.__valueFormat = kwargs.get('valueFormat') self.__performanceContribution = kwargs.get('performanceContribution') self.__targetNotional = kwargs.get('targetNotional') self.__fillLegId = kwargs.get('fillLegId') self.__delisted = kwargs.get('delisted') self.__rationale = kwargs.get('rationale') self.__regionalFocus = kwargs.get('regionalFocus') self.__volumePrimary = kwargs.get('volumePrimary') self.__series = kwargs.get('series') self.__simonId = kwargs.get('simonId') self.__newIdeasQtd = kwargs.get('newIdeasQtd') self.__congestion = kwargs.get('congestion') self.__adjustedAskPrice = kwargs.get('adjustedAskPrice') self.__quarter = kwargs.get('quarter') self.__factorUniverse = kwargs.get('factorUniverse') self.__eventCategory = kwargs.get('eventCategory') self.__impliedNormalVolatility = kwargs.get('impliedNormalVolatility') self.__unadjustedOpen = kwargs.get('unadjustedOpen') self.__arrivalRt = kwargs.get('arrivalRt') self.__criticality = kwargs.get('criticality') self.__transactionCost = kwargs.get('transactionCost') self.__servicingCostShortPnl = kwargs.get('servicingCostShortPnl') self.__bidAskSpread = kwargs.get('bidAskSpread') self.__optionType = kwargs.get('optionType') self.__tcmCostHorizon3Hour = kwargs.get('tcmCostHorizon3Hour') self.__clusterDescription = kwargs.get('clusterDescription') self.__creditLimit = kwargs.get('creditLimit') self.__positionAmount = kwargs.get('positionAmount') self.__numberOfPositions = kwargs.get('numberOfPositions') self.__windSpeed = kwargs.get('windSpeed') self.__openUnadjusted = kwargs.get('openUnadjusted') self.__maRank = kwargs.get('maRank') self.__askPrice = kwargs.get('askPrice') self.__eventId = kwargs.get('eventId') self.__borrowerId = kwargs.get('borrowerId') self.__dataProduct = kwargs.get('dataProduct') self.__sectors = kwargs.get('sectors') self.__mqSymbol = kwargs.get('mqSymbol') self.__annualizedTrackingError = kwargs.get('annualizedTrackingError') self.__additionalPriceNotationType = kwargs.get('additionalPriceNotationType') self.__volSwap = kwargs.get('volSwap') self.__annualizedRisk = kwargs.get('annualizedRisk') self.__blockTradesAndLargeNotionalOffFacilitySwaps = kwargs.get('blockTradesAndLargeNotionalOffFacilitySwaps') self.__bmPrimeId = kwargs.get('bmPrimeId') self.__corporateAction = kwargs.get('corporateAction') self.__conviction = kwargs.get('conviction') self.__grossExposure = kwargs.get('grossExposure') self.__benchmarkMaturity = kwargs.get('benchmarkMaturity') self.__gRegionalScore = kwargs.get('gRegionalScore') self.__volumeComposite = kwargs.get('volumeComposite') self.__volume = kwargs.get('volume') self.__factorId = kwargs.get('factorId') self.__hardToBorrow = kwargs.get('hardToBorrow') self.__adv = kwargs.get('adv') self.__stsFxCurrency = kwargs.get('stsFxCurrency') self.__wpk = kwargs.get('wpk') self.__shortConvictionMedium = kwargs.get('shortConvictionMedium') self.__bidChange = kwargs.get('bidChange') self.__exchange = kwargs.get('exchange') self.__expiration = kwargs.get('expiration') self.__tradePrice = kwargs.get('tradePrice') self.__cleared = kwargs.get('cleared') self.__esPolicyScore = kwargs.get('esPolicyScore') self.__loanId = kwargs.get('loanId') self.__primeIdNumeric = kwargs.get('primeIdNumeric') self.__cid = kwargs.get('cid') self.__onboarded = kwargs.get('onboarded') self.__liquidityScore = kwargs.get('liquidityScore') self.__importance = kwargs.get('importance') self.__sourceDateSpan = kwargs.get('sourceDateSpan') self.__assetClassificationsGicsSector = kwargs.get('assetClassificationsGicsSector') self.__underlyingDataSetId = kwargs.get('underlyingDataSetId') self.__stsAssetName = kwargs.get('stsAssetName') self.__closeUnadjusted = kwargs.get('closeUnadjusted') self.__valueUnit = kwargs.get('valueUnit') self.__bidHigh = kwargs.get('bidHigh') self.__adjustedLowPrice = kwargs.get('adjustedLowPrice') self.__netExposureClassification = kwargs.get('netExposureClassification') self.__longConvictionLarge = kwargs.get('longConvictionLarge') self.__fairVariance = kwargs.get('fairVariance') self.__hitRateWtd = kwargs.get('hitRateWtd') self.__oad = kwargs.get('oad') self.__bosInBpsDescription = kwargs.get('bosInBpsDescription') self.__lowPrice = kwargs.get('lowPrice') self.__realizedVolatility = kwargs.get('realizedVolatility') self.__rate = kwargs.get('rate') self.__adv22DayPct = kwargs.get('adv22DayPct') self.__alpha = kwargs.get('alpha') self.__client = kwargs.get('client') self.__cloneParentId = kwargs.get('cloneParentId') self.__company = kwargs.get('company') self.__convictionList = kwargs.get('convictionList') self.__settlementFrequency = kwargs.get('settlementFrequency') self.__priceRangeInTicksLabel = kwargs.get('priceRangeInTicksLabel') self.__ticker = kwargs.get('ticker') self.__inRiskModel = kwargs.get('inRiskModel') self.__tcmCostHorizon1Day = kwargs.get('tcmCostHorizon1Day') self.__servicingCostLongPnl = kwargs.get('servicingCostLongPnl') self.__stsRatesCountry = kwargs.get('stsRatesCountry') self.__meetingNumber = kwargs.get('meetingNumber') self.__exchangeId = kwargs.get('exchangeId') self.__horizon = kwargs.get('horizon') self.__midGspread = kwargs.get('midGspread') self.__tcmCostHorizon20Day = kwargs.get('tcmCostHorizon20Day') self.__longLevel = kwargs.get('longLevel') self.__sourceValueForecast = kwargs.get('sourceValueForecast') self.__shortConvictionLarge = kwargs.get('shortConvictionLarge') self.__realm = kwargs.get('realm') self.__bid = kwargs.get('bid') self.__dataDescription = kwargs.get('dataDescription') self.__counterPartyStatus = kwargs.get('counterPartyStatus') self.__composite22DayAdv = kwargs.get('composite22DayAdv') self.__dollarExcessReturn = kwargs.get('dollarExcessReturn') self.__gsn = kwargs.get('gsn') self.__isAggressive = kwargs.get('isAggressive') self.__orderId = kwargs.get('orderId') self.__gss = kwargs.get('gss') self.__percentOfMediandv1m = kwargs.get('percentOfMediandv1m') self.__lendables = kwargs.get('lendables') self.__assetClass = kwargs.get('assetClass') self.__gsideid = kwargs.get('gsideid') self.__bosInTicksLabel = kwargs.get('bosInTicksLabel') self.__ric = kwargs.get('ric') self.__positionSourceId = kwargs.get('positionSourceId') self.__division = kwargs.get('division') self.__marketCapUSD = kwargs.get('marketCapUSD') self.__gsSustainRegion = kwargs.get('gsSustainRegion') self.__deploymentId = kwargs.get('deploymentId') self.__highPrice = kwargs.get('highPrice') self.__loanStatus = kwargs.get('loanStatus') self.__shortWeight = kwargs.get('shortWeight') self.__absoluteShares = kwargs.get('absoluteShares') self.__action = kwargs.get('action') self.__model = kwargs.get('model') self.__id = kwargs.get('id') self.__arrivalHaircutVwapNormalized = kwargs.get('arrivalHaircutVwapNormalized') self.__priceComponent = kwargs.get('priceComponent') self.__queueClockTimeDescription = kwargs.get('queueClockTimeDescription') self.__loanRebate = kwargs.get('loanRebate') self.__period = kwargs.get('period') self.__indexCreateSource = kwargs.get('indexCreateSource') self.__fiscalQuarter = kwargs.get('fiscalQuarter') self.__deltaStrike = kwargs.get('deltaStrike') self.__marketImpact = kwargs.get('marketImpact') self.__eventType = kwargs.get('eventType') self.__assetCountLong = kwargs.get('assetCountLong') self.__valueActual = kwargs.get('valueActual') self.__bcid = kwargs.get('bcid') self.__collateralCurrency = kwargs.get('collateralCurrency') self.__originalCountry = kwargs.get('originalCountry') self.__touchLiquidityScore = kwargs.get('touchLiquidityScore') self.__field = kwargs.get('field') self.__factorCategoryId = kwargs.get('factorCategoryId') self.__spot = kwargs.get('spot') self.__expectedCompletionDate = kwargs.get('expectedCompletionDate') self.__loanValue = kwargs.get('loanValue') self.__tradingRestriction = kwargs.get('tradingRestriction') self.__skew = kwargs.get('skew') self.__status = kwargs.get('status') self.__sustainEmergingMarkets = kwargs.get('sustainEmergingMarkets') self.__totalReturnPrice = kwargs.get('totalReturnPrice') self.__city = kwargs.get('city') self.__totalPrice = kwargs.get('totalPrice') self.__embededOption = kwargs.get('embededOption') self.__eventSource
<filename>src/main_nosim.py import random import numpy as np import torch from torch import nn, optim import torchvision.transforms as transforms from data import NADataset, TorchDataset import argparse from tqdm import tqdm from decoders_nosim import ActionDecoder from metric_dtw import DTW from sim_mul import simulator import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt parser = argparse.ArgumentParser(description='NA Task') parser.add_argument('--workers', default=4, type=int, help='num of workers') parser.add_argument('--batch_size', default=8, type=int, help='batch size') parser.add_argument('--batch_size_val', default=8, type=int, help='batch size') parser.add_argument('--num_epochs', default=300, type=int, help='num of epochs') parser.add_argument('--max_input', default=150, type=int, help='max input size') parser.add_argument('--seed', default=1234, type=int, help='seeds') parser.add_argument('--hsz', default=128, type=int, help='hidden size') parser.add_argument('--lr', default=0.001, type=float, help='hidden size') parser.add_argument('--port', default=1111, type=int, help='port number') parser.add_argument('--sim_num', default=4, type=int, help='the num of sims') s_turn = 0 e_turn = 2 def get_tuple(args, split, batch_size, shuffle=True, drop_last=True, max_length=100): dataset = NADataset(split) torch_ds = TorchDataset(dataset, max_length=max_length) print("The size of data split %s is %d" % (split, len(torch_ds))) loader = torch.utils.data.DataLoader(torch_ds, batch_size=batch_size, shuffle=shuffle, num_workers=args.workers, pin_memory=True, drop_last=drop_last) return dataset, torch_ds, loader def calLossAvg(loss): seq_len = (loss != 0.0).float().sum(-1) loss_avg = loss.sum(-1) / (seq_len + 0.000001) loss_avg = loss_avg.mean() return loss_avg def train(args, sim, model_navi, model_assem, optimizer, train_tuple, valid_seen_tuple): sim.resnet_extractor.eval() train_ds, train_tds, train_loader = train_tuple loss_func = torch.nn.CrossEntropyLoss(ignore_index=0, reduction='none') best_dtw_score = 0.0 for epoch in range(args.num_epochs): iterator = tqdm(enumerate(train_loader), total=len(train_tds)//args.batch_size, unit="batch") pos_error = 0.0 total_cnt = 0.0 tot_init_dist = 0.0 for k, (mapids, insts, actions, paths, rots, objPos) in iterator: res = sim.mapIDset(mapids, train=True, epoch=epoch) inst_navi, inst_assem, leng_navi, leng_assem = insts inst_navi, inst_assem, leng_navi, leng_assem = \ inst_navi.cuda(), inst_assem.cuda(), leng_navi.cuda(), leng_assem.cuda() acts_navi, acts_assem, leng_acts_navi, leng_acts_assem = actions acts_navi, acts_assem, leng_acts_navi, leng_acts_assem = \ acts_navi.cuda(), acts_assem.cuda(), leng_acts_navi.cuda(), leng_acts_assem.cuda() path_navi, path_assem, path_leng_navi, path_leng_assem = paths rot_navi, rot_assem, rot_leng_navi, rot_leng_assem = rots pos_navi, pos_assem = objPos pos_navi, pos_assem = pos_navi.cuda(), pos_assem.cuda() bsz = pos_navi.size(0) losses_navi = [] losses_assem = [] object_pos = torch.zeros(bsz).cuda() init_dist = torch.zeros(bsz).cuda() global s_turn, e_turn for i in range(s_turn, e_turn): optimizer.zero_grad() A, logit_navi, B, C, D, pos_seq_gt, obj_ids, E, agent_pos = model_navi(epoch, mapids, i, inst_navi[:,i,:], leng_navi[:,i], acts_navi[:,i,:], path_navi[:,i,:], rot_navi[:,i,:], phase='navi') res = sim.shift(train=True, epoch=epoch) diff_pow = (pos_navi[:,i,:] - agent_pos.cuda())**2 innersum = torch.sum(diff_pow, dim=-1) object_pos += torch.sqrt(innersum) diff_pow = (pos_navi[:,i,:] - path_navi[:,i,0,:].cuda())**2 innersum = torch.sum(diff_pow, dim=-1) init_dist += torch.sqrt(innersum) loss_navi = loss_func(logit_navi.contiguous().view(-1, 5), acts_navi[:,i,1:].contiguous().view(-1)) if True: bsz = logit_navi.size(0) loss_navi = loss_navi.view(bsz, -1) loss_navi = calLossAvg(loss_navi) loss_navi.backward() nn.utils.clip_grad_norm_(model_navi.parameters(), 5.) optimizer.step() optimizer.zero_grad() _, logit_assem, _, _, _, pos_seq_gt, _, obj_place, agent_pos = model_assem(epoch, mapids, i, inst_assem[:,i,:], leng_assem[:,i], acts_assem[:,i,:], path_assem[:,i,:], rot_assem[:,i,:], phase='assembly') res = sim.shift(train=True, epoch=epoch) loss_assem = loss_func(logit_assem.contiguous().view(-1, 5), acts_assem[:,i,1:].contiguous().view(-1)) if True: loss_assem = loss_assem.view(bsz, -1) loss_assem = calLossAvg(loss_assem) loss_assem.backward() nn.utils.clip_grad_norm_(model_assem.parameters(), 5.) optimizer.step() losses_navi.append(loss_navi) losses_assem.append(loss_assem) total_cnt += bsz pos_error += object_pos / 3 loss_total = sum(losses_navi) + sum(losses_assem) iterator.set_postfix(loss=sum(losses_navi).item()) dtw_score = evaluation(args, epoch, sim, model_navi, model_assem, valid_seen_tuple) if dtw_score > best_dtw_score: dtw_score = best_dtw_score save(model_navi, model_assem, "best_model", epoch) def save(model_navi, model_assem, name, epoch): model_navi_path = os.path.join("best_models", '%s_model_navi_%s.pth' % (name, str(epoch))) model_assem_path = os.path.join("best_models", '%s_model_assem_%s.pth' % (name, str(epoch))) torch.save(model_navi.state_dict(), model_navi_path) torch.save(model_assem.state_dict(), model_assem_path) def load(model_navi, model_assem, name, epoch): model_navi_path = os.path.join("best_models", '%s_model_navi_%s.pth' % (name, str(epoch))) model_assem_path = os.path.join("best_models", '%s_model_assem_%s.pth' % (name, str(epoch))) model_navi_state_dict = torch.load(model_navi_path) model_assem_state_dict = torch.load(model_assem_path) model_navi.load_state_dict(model_navi_state_dict) model_assem.load_state_dict(model_assem_state_dict) def evaluation(args, epoch, sim, model_navi, model_assem, valid_tuple, log_name="scores.txt"): with torch.no_grad(): valid_ds, valid_tds, valid_loader = valid_tuple model_navi.eval() model_assem.eval() sim.resnet_extractor.eval() dtw = DTW() total_outter_score = 0.0 total_cnt = 0.0 pos_error = 0.0 pos_error_each = 0.0 coc_3_total = 0.0 coc_5_total = 0.0 coc_7_total = 0.0 tot_init_dist = 0.0 placement_dist = 0.0 placement_error = 0.0 placement_error_0 = 0.0 placement_error_3 = 0.0 placement_error_5 = 0.0 placement_error_7 = 0.0 placement_success = 0.0 placement_success_0 = 0.0 placement_success_3 = 0.0 placement_success_5 = 0.0 placement_success_7 = 0.0 pick_score_turn1 = 0.0 pick_score_turn2 = 0.0 dtw_score_each = torch.zeros(3) dtw_score_each_tot = 0.0 map_path = {} iterator = tqdm(enumerate(valid_loader), total=len(valid_tds)//args.batch_size, unit="batch") for k, (mapids, insts, actions, paths, rots, objPos) in iterator: res = sim.mapIDset(mapids, epoch=epoch) inst_navi, inst_assem, leng_navi, leng_assem = insts inst_navi, inst_assem, leng_navi, leng_assem = \ inst_navi.cuda(), inst_assem.cuda(), leng_navi.cuda(), leng_assem.cuda() acts_navi, acts_assem, leng_acts_navi, leng_acts_assem = actions acts_navi, acts_assem, leng_acts_navi, leng_acts_assem = \ acts_navi.cuda(), acts_assem.cuda(), leng_acts_navi, leng_acts_assem path_navi, path_assem, path_leng_navi, path_leng_assem = paths rot_navi, rot_assem, rot_leng_navi, rot_leng_assem = rots pos_navi, pos_assem = objPos pos_navi, pos_assem = pos_navi.cuda(), pos_assem.cuda() pos_seq_navi_list = [] pos_len_navi_list = [] pos_seq_navi_list_gt = [] pos_len_navi_list_gt = [] pos_seq_assem_list = [] pos_len_assem_list = [] pos_seq_assem_list_gt = [] pos_len_assem_list_gt = [] collected_object = [[], []] bsz = pos_navi.size(0) init_dist = torch.zeros(bsz).cuda() object_pos = torch.zeros(bsz).cuda() object_pos_each = torch.zeros(bsz, 3).cuda() coc_0 = torch.zeros(bsz, 2).cuda() coc_3 = torch.zeros(bsz, 2).cuda() coc_5 = torch.zeros(bsz, 2).cuda() coc_7 = torch.zeros(bsz, 2).cuda() placement = torch.zeros(bsz, 2, 3).cuda() object_dist = torch.zeros(bsz, 2).cuda() object_place = torch.zeros(bsz, 2).cuda() object_place_0 = torch.zeros(bsz, 2).cuda() object_place_3 = torch.zeros(bsz, 2).cuda() object_place_5 = torch.zeros(bsz, 2).cuda() object_place_7 = torch.zeros(bsz, 2).cuda() object_success = torch.zeros(bsz, 2).cuda() object_success_0 = torch.zeros(bsz, 2).cuda() object_success_3 = torch.zeros(bsz, 2).cuda() object_success_5 = torch.zeros(bsz, 2).cuda() object_success_7 = torch.zeros(bsz, 2).cuda() global s_turn, e_turn for i in range(s_turn, e_turn): _, logit_navi, _, pos_seq_navi, pos_len_navi, pos_seq_gt, obj_ids, obj_place, agent_pos = model_navi(-1, mapids, i, inst_navi[:,i,:], leng_navi[:,i], acts_navi[:,i,:], path_navi[:,i,:], rot_navi[:,i,:], phase='navi') pos_seq_navi_list.append(pos_seq_navi.cpu()) pos_len_navi_list.append(pos_len_navi.cpu()) pos_seq_navi_list_gt.append(pos_seq_gt.cpu()) collected_object[i].append(sum((obj_ids==i).float())) diff_pow = (pos_navi[:,i,:] - agent_pos.cuda())**2 innersum = torch.sum(diff_pow, dim=-1) object_pos += torch.sqrt(innersum) object_pos_each[:, i] = torch.sqrt(innersum) coc_0[:,i] = (obj_ids==i).float() coc_3[:,i] = (torch.sqrt(innersum) < 3.0).float() coc_5[:,i] = (torch.sqrt(innersum) < 5.0).float() coc_7[:,i] = (torch.sqrt(innersum) < 7.0).float() diff_pow = (pos_navi[:,i,:] - path_navi[:,i,0,:].cuda())**2 innersum = torch.sum(diff_pow, dim=-1) init_dist += torch.sqrt(innersum) res = sim.shift(epoch=epoch) _, logit_assem, _, pos_seq_assem, pos_len_assem, pos_seq_gt, _, obj_place, agent_pos = model_assem(-1, mapids, i, inst_assem[:,i,:], leng_assem[:,i], acts_assem[:,i,:], path_assem[:,i,:], rot_assem[:,i,:], phase='assembly') pos_seq_assem_list.append(pos_seq_assem.cpu()) pos_len_assem_list.append(pos_len_assem.cpu()) pos_seq_assem_list_gt.append(pos_seq_gt.cpu()) obj_place[obj_place==-1] = 100 placement[:,i,:] = obj_place.cuda() manhattanD = torch.abs(pos_assem[:,i,:] - obj_place.cuda()) innersum = torch.sum(manhattanD, dim=-1) object_dist[:,i] += innersum object_place[:,i] += 1/(1 + innersum ** 2) object_place_0[:,i] += 1/(1 + innersum ** 2) object_place_3[:,i] += 1/(1 + innersum ** 2) object_place_5[:,i] += 1/(1 + innersum ** 2) object_place_7[:,i] += 1/(1 + innersum ** 2) object_success[:,i] += (innersum == 0).float() object_success_0[:,i] += (innersum == 0).float() object_success_3[:,i] += (innersum == 0).float() object_success_5[:,i] += (innersum == 0).float() object_success_7[:,i] += (innersum == 0).float() if True: object_place_0[:,i][coc_0[:,i]!=1] = 0 object_success_0[:,i] *= coc_0[:,i] object_place_3[:,i][coc_3[:,i]!=1] = 0 object_success_3[:,i] *= coc_3[:,i] object_place_5[:,i][coc_5[:,i]!=1] = 0 object_success_5[:,i] *= coc_5[:,i] object_place_7[:,i][coc_7[:,i]!=1] = 0 object_success_7[:,i] *= coc_7[:,i] res = sim.shift(epoch=epoch) tot_init_dist += init_dist / 2 pos_error += object_pos / 2 pos_error_each += object_pos_each coc_3_total += coc_3 coc_5_total += coc_5 coc_7_total += coc_7 placement_dist += object_dist placement_error += object_place placement_error_0 += object_place_0 placement_error_3 += object_place_3 placement_error_5 += object_place_5 placement_error_7 += object_place_7 placement_success += object_success placement_success_0 += object_success_0 placement_success_3 += object_success_3 placement_success_5 += object_success_5 placement_success_7 += object_success_7 pick_score_turn1 += sum(collected_object[0]) pick_score_turn2 += sum(collected_object[1]) bsz = path_navi.size(0) total_cnt += bsz for idx in range(bsz): total_inner_score = 0.0 mapid = mapids[idx].item() map_path[mapid] = {"path_gen":[], "path_gt":[], "dtw":[], "path_assem_gen":[], "path_assem_gt":[], "ptc":[], "ctc0":[], "ctc3":[], "ctc5":[], "ctc7":[], "placement":[]} for j in range(s_turn, e_turn): dtw_score = dtw(pos_seq_navi_list[j][idx], pos_seq_navi_list_gt[j][idx], pos_len_navi_list[j][idx], path_leng_navi[idx][j], metric='ndtw') path_gen = pos_seq_navi_list[j][idx][:pos_len_navi_list[j][idx]].tolist() path_gt = pos_seq_navi_list_gt[j][idx][:path_leng_navi[idx][j]].tolist() path_assem_gen = pos_seq_assem_list[j][idx][:pos_len_assem_list[j][idx]].tolist() path_assem_gt = pos_seq_assem_list_gt[j][idx][:path_leng_assem[idx][j]].tolist() map_path[mapid]["path_gen"].append(path_gen) map_path[mapid]["path_gt"].append(path_gt) map_path[mapid]["path_assem_gen"].append(path_assem_gen) map_path[mapid]["path_assem_gt"].append(path_assem_gt) map_path[mapid]["dtw"].append(dtw_score.item()) map_path[mapid]["ptc"].append(object_success[idx,j].item()) map_path[mapid]["ctc0"].append(coc_0[idx,j].item()) map_path[mapid]["ctc3"].append(coc_3[idx,j].item()) map_path[mapid]["ctc5"].append(coc_5[idx,j].item()) map_path[mapid]["ctc7"].append(coc_7[idx,j].item()) map_path[mapid]["placement"].append(placement[idx,j].tolist()) total_inner_score += dtw_score dtw_score_each[j] += dtw_score total_inner_score /= 2 total_outter_score += total_inner_score dtw_avg = total_outter_score / total_cnt pick_score_avg = (pick_score_turn1 + pick_score_turn2)/2/ total_cnt with open("evalScores/" + log_name, 'a') as f: print("epoch", epoch, file=f) print("eval target-agent init dist", torch.sum(tot_init_dist)/total_cnt, file=f) print("eval target-agent dist", torch.sum(pos_error)/total_cnt, file=f) print(file=f) print("eval CTC-3 1 turn", torch.sum(coc_3_total[:,0])/total_cnt, file=f) print("eval CTC-3 2 turn", torch.sum(coc_3_total[:,1])/total_cnt, file=f) print("eval CTC-3 total", torch.sum(coc_3_total)/2/total_cnt, file=f) print(file=f) print("eval CTC-5 1 turn", torch.sum(coc_5_total[:,0])/total_cnt, file=f) print("eval CTC-5 2 turn", torch.sum(coc_5_total[:,1])/total_cnt, file=f) print("eval CTC-5 total", torch.sum(coc_5_total)/2/total_cnt, file=f) print(file=f) print("eval CTC-7 1 turn", torch.sum(coc_7_total[:,0])/total_cnt, file=f) print("eval CTC-7 2 turn", torch.sum(coc_7_total[:,1])/total_cnt, file=f) print("eval CTC-7 total", torch.sum(coc_7_total)/2/total_cnt, file=f) print(file=f) print("eval target-agent dist 1 turn", torch.sum(pos_error_each[:,0])/total_cnt, file=f) print("eval target-agent dist 2 turn", torch.sum(pos_error_each[:,1])/total_cnt, file=f) print(file=f) print("eval placement dist 1 turn", torch.sum(placement_dist[:,0])/total_cnt, file=f) print("eval placement dist 2 turn", torch.sum(placement_dist[:,1])/total_cnt, file=f) print("eval placement dist total", torch.sum(placement_dist)/2/total_cnt, file=f) print(file=f) print("eval rPOD 1 turn", torch.sum(placement_error[:,0])/total_cnt, file=f) print("eval rPOD 2 turn", torch.sum(placement_error[:,1])/total_cnt, file=f) print("eval rPOD total", torch.sum(placement_error)/2/total_cnt, file=f) print(file=f) print("eval rPOD_0 1 turn", torch.sum(placement_error_0[:,0])/total_cnt, file=f) print("eval rPOD_0 2 turn", torch.sum(placement_error_0[:,1])/total_cnt, file=f) print("eval rPOD_0 total", torch.sum(placement_error_0)/2/total_cnt, file=f) print(file=f) print("eval rPOD_3 1 turn", torch.sum(placement_error_3[:,0])/total_cnt, file=f) print("eval rPOD_3 2 turn", torch.sum(placement_error_3[:,1])/total_cnt, file=f) print("eval rPOD_3 total", torch.sum(placement_error_3)/2/total_cnt, file=f) print(file=f) print("eval rPOD_5 1
always fit first item skips = np.empty((num_x, 2), dtype=np.intp) else: # TODO maybe use another function when fitting all points in order # to skip the if check_fits check for every x-value; does it affect # calculation time that much? check_fits = False # TODO once numba minimum version is >= 0.47, can use dtype kwarg in np.arange fits = np.arange(num_x).astype(np.intp) # numba cannot compile in nopython mode when directly creating # np.array([], dtype=np.intp), so work-around by creating np.array([[0, 0]]) # and then index with [:total_skips], which becomes np.array([]) # since total_skips is 0 when delta is <= 0. skips = np.array([[0, 0]], dtype=np.intp) windows = np.empty((num_x, 2), dtype=np.intp) windows[0] = (0, total_points) total_fits = 1 total_skips = 0 skip_start = 0 skip_range = x[0] + delta left = 0 right = total_points for i in range(1, num_x - 1): x_val = x[i] if check_fits: # use x[i+1] rather than x[i] since it ensures that the last value within # the range x_last_fit + delta is used; x[i+1] is also guranteed to be >= x[i] if x[i + 1] < skip_range: if not skip_start: skip_start = i continue else: skip_range = x_val + delta fits[total_fits] = i if skip_start: skips[total_skips] = (skip_start - 1, i + 1) total_skips += 1 skip_start = 0 while right < num_x and x_val - x[left] > x[right] - x_val: left += 1 right += 1 window = windows[total_fits] window[0] = left window[1] = right total_fits += 1 if skip_start: # fit second to last x-value fits[total_fits] = num_x - 2 if x[-1] - x[-2] < x[-2] - x[num_x - total_points]: windows[total_fits] = (num_x - total_points, num_x) else: windows[total_fits] = (num_x - total_points - 1, num_x - 1) total_fits += 1 skips[total_skips] = (skip_start - 1, num_x - 1) total_skips += 1 # always fit last item fits[total_fits] = num_x - 1 windows[total_fits] = (num_x - total_points, num_x) total_fits += 1 return windows[:total_fits], fits[:total_fits], skips[:total_skips] def loess(data, x_data=None, fraction=0.2, total_points=None, poly_order=1, scale=3.0, tol=1e-3, max_iter=10, symmetric_weights=False, use_threshold=False, num_std=1, use_original=False, weights=None, return_coef=False, conserve_memory=True, delta=0.0): """ Locally estimated scatterplot smoothing (LOESS). Performs polynomial regression at each data point using the nearest points. Parameters ---------- data : array-like, shape (N,) The y-values of the measured data, with N data points. x_data : array-like, shape (N,), optional The x-values of the measured data. Default is None, which will create an array from -1 to 1 with N points. fraction : float, optional The fraction of N data points to include for the fitting on each point. Default is 0.2. Not used if `total_points` is not None. total_points : int, optional The total number of points to include for the fitting on each point. Default is None, which will use `fraction` * N to determine the number of points. scale : float, optional A scale factor applied to the weighted residuals to control the robustness of the fit. Default is 3.0, as used in [9]_. Note that the original loess procedure in [10]_ used a `scale` of ~4.05. poly_order : int, optional The polynomial order for fitting the baseline. Default is 1. tol : float, optional The exit criteria. Default is 1e-3. max_iter : int, optional The maximum number of iterations. Default is 10. symmetric_weights : bool, optional If False (default), will apply weighting asymmetrically, with residuals < 0 having a weight of 1, according to [9]_. If True, will apply weighting the same for both positive and negative residuals, which is regular LOESS. If `use_threshold` is True, this parameter is ignored. use_threshold : bool, optional If False (default), will compute weights each iteration to perform the robust fitting, which is regular LOESS. If True, will apply a threshold on the data being fit each iteration, based on the maximum values of the data and the fit baseline, as proposed by [11]_, similar to the modpoly and imodpoly techniques. num_std : float, optional The number of standard deviations to include when thresholding. Default is 1, which is the value used for the imodpoly technique. Only used if `use_threshold` is True. use_original : bool, optional If False (default), will compare the baseline of each iteration with the y-values of that iteration [12]_ when choosing minimum values for thresholding. If True, will compare the baseline with the original y-values given by `data` [13]_. Only used if `use_threshold` is True. weights : array-like, shape (N,), optional The weighting array. If None (default), then will be an array with size equal to N and all values set to 1. return_coef : bool, optional If True, will convert the polynomial coefficients for the fit baseline to a form that fits the input x_data and return them in the params dictionary. Default is False, since the conversion takes time. conserve_memory : bool, optional If False, will cache the distance-weighted kernels for each value in `x_data` on the first iteration and reuse them on subsequent iterations to save time. The shape of the array of kernels is (len(`x_data`), `total_points`). If True (default), will recalculate the kernels each iteration, which uses very little memory, but is slower. Can usually set to False unless `x_data` and`total_points` are quite large and the function causes memory issues when cacheing the kernels. If numba is installed, there is no significant time difference since the calculations are sped up. delta : float, optional If `delta` is > 0, will skip all but the last x-value in the range x_last + `delta`, where x_last is the last x-value to be fit using weighted least squares, and instead use linear interpolation to calculate the fit for those x-values (same behavior as in statsmodels [14]_ and Cleveland's original Fortran lowess implementation [15]_). Fits all x-values if `delta` is <= 0. Default is 0.0. Note that `x_data` is scaled to fit in the range [-1, 1], so `delta` should likewise be scaled. For example, if the desired `delta` value was ``0.01 * (max(x_data) - min(x_data))``, then the correctly scaled `delta` would be 0.02 (ie. ``0.01 * (1 - (-1))``). Returns ------- baseline : numpy.ndarray, shape (N,) The calculated baseline. params : dict A dictionary with the following items: * 'weights': numpy.ndarray, shape (N,) The weight array used for fitting the data. Does NOT contain the individual distance-weighted kernels for each x-value. * 'tol_history': numpy.ndarray An array containing the calculated tolerance values for each iteration. The length of the array is the number of iterations completed. If the last value in the array is greater than the input `tol` value, then the function did not converge. * 'coef': numpy.ndarray, shape (N, poly_order + 1) Only if `return_coef` is True. The array of polynomial parameters for the baseline, in increasing order. Can be used to create a polynomial using numpy.polynomial.polynomial.Polynomial(). If `delta` is > 0, the coefficients for any skipped x-value will all be 0. Raises ------ ValueError Raised if the number of points per window for the fitting is less than `poly_order` + 1 or greater than the total number of points. Notes ----- The iterative, robust, aspect of the fitting can be achieved either through reweighting based on the residuals (the typical usage), or thresholding the fit data based on the residuals, as proposed by [11]_, similar to the modpoly and imodpoly techniques. In baseline literature, this procedure is sometimes called "rbe", meaning "robust baseline estimate". References ---------- .. [9] <NAME>., et al. Baseline subtraction using robust local regression estimation. J. Quantitative Spectroscopy and Radiative Transfer, 2001, 68, 179-193. .. [10] <NAME>. Robust locally weighted regression and smoothing scatterplots. Journal of the American Statistical Association, 1979, 74(368), 829-836. .. [11] <NAME>. Comparison of Several Methods of Chromatographic Baseline Removal with a New Approach Based on Quantile Regression. Chromatographia, 2011, 73, 721-731. .. [12] <NAME>., et al. Baseline correction by
from __future__ import annotations import sys from PyQt5.uic import loadUi from PyQt5 import QtWidgets from PyQt5.QtCore import QSize, Qt, QRect, QObject, QCoreApplication, QMetaObject, QPropertyAnimation from PyQt5.QtWidgets import QApplication, QWidget, QProgressBar, QLabel, QTabWidget, QGridLayout, QVBoxLayout, \ QHBoxLayout, QSizePolicy, QSpacerItem, QStyle, QStyleFactory, QPushButton, QFrame, QFontDialog, QStackedWidget,\ QLineEdit, QTextBrowser, QTextEdit, QPlainTextEdit, QTableWidget, QTableWidgetItem, QToolBox, QComboBox, QAbstractItemView from PyQt5.QtGui import QImage, QIcon, QPixmap, QPalette, QBrush, QColor, QFontDatabase, QFont, QCursor class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u"Cowin Notifier") MainWindow.resize(1000, 600) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u"centralwidget") self.horizontalLayout = QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName(u"horizontalLayout") self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.frame = QFrame(self.centralwidget) self.frame.setObjectName(u"frame") self.frame.setStyleSheet(u"background-color: rgb(15, 21, 25);") self.frame.setFrameShape(QFrame.StyledPanel) self.frame.setFrameShadow(QFrame.Raised) self.horizontalLayout_2 = QHBoxLayout(self.frame) self.horizontalLayout_2.setObjectName(u"horizontalLayout_2") self.frame_2 = QFrame(self.frame) self.frame_2.setObjectName(u"frame_2") self.frame_2.setMaximumSize(QSize(180, 16777215)) self.frame_2.setFrameShape(QFrame.StyledPanel) self.frame_2.setFrameShadow(QFrame.Raised) self.verticalLayout_2 = QVBoxLayout(self.frame_2) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setObjectName(u"verticalLayout_2") self.verticalLayout_2.setContentsMargins(0, -1, 0, 0) self.frame_4 = QFrame(self.frame_2) self.frame_4.setObjectName(u"frame_4") self.frame_4.setStyleSheet(u"background-color: rgb(56, 75, 89);") self.frame_4.setFrameShape(QFrame.StyledPanel) self.frame_4.setFrameShadow(QFrame.Raised) self.horizontalLayout_4 = QHBoxLayout(self.frame_4) self.horizontalLayout_4.setSpacing(0) self.horizontalLayout_4.setObjectName(u"horizontalLayout_4") self.horizontalLayout_4.setContentsMargins(15, 0, 0, 0) self.label = QLabel(self.frame_4) self.label.setObjectName(u"label") font = QFont() font.setPointSize(12) self.label.setFont(font) self.label.setStyleSheet(u"color: rgb(255, 255, 255);") self.horizontalLayout_4.addWidget(self.label) self.verticalLayout_2.addWidget(self.frame_4, 0, Qt.AlignTop) self.frame_6 = QFrame(self.frame_2) self.frame_6.setObjectName(u"frame_6") sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_6.sizePolicy().hasHeightForWidth()) self.frame_6.setSizePolicy(sizePolicy) self.frame_6.setStyleSheet(u"background-color: rgb(24, 34, 43);") self.frame_6.setFrameShape(QFrame.StyledPanel) self.frame_6.setFrameShadow(QFrame.Raised) self.verticalLayout_3 = QVBoxLayout(self.frame_6) self.verticalLayout_3.setSpacing(0) self.verticalLayout_3.setObjectName(u"verticalLayout_3") self.verticalLayout_3.setContentsMargins(0, -1, 0, -1) self.frame_5 = QFrame(self.frame_6) self.frame_5.setObjectName(u"frame_5") self.frame_5.setFrameShape(QFrame.StyledPanel) self.frame_5.setFrameShadow(QFrame.Raised) self.verticalLayout_4 = QVBoxLayout(self.frame_5) self.verticalLayout_4.setObjectName(u"verticalLayout_4") self.slot_checker = QPushButton(self.frame_5) self.slot_checker.setObjectName(u"slot_checker") sizePolicy1 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.slot_checker.sizePolicy().hasHeightForWidth()) self.slot_checker.setSizePolicy(sizePolicy1) self.slot_checker.setStyleSheet(u"color: rgb(255, 255, 255);\n" "background-color: rgb(15, 24, 31);") self.verticalLayout_4.addWidget(self.slot_checker) self.verticalLayout_3.addWidget(self.frame_5, 0, Qt.AlignTop) self.frame_8 = QFrame(self.frame_6) self.frame_8.setObjectName(u"frame_8") sizePolicy2 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.frame_8.sizePolicy().hasHeightForWidth()) self.frame_8.setSizePolicy(sizePolicy2) self.frame_8.setStyleSheet(u"") self.frame_8.setFrameShape(QFrame.StyledPanel) self.frame_8.setFrameShadow(QFrame.Raised) self.verticalLayout = QVBoxLayout(self.frame_8) self.verticalLayout.setSpacing(6) self.verticalLayout.setObjectName(u"verticalLayout") self.verticalLayout.setContentsMargins(9, 9, 9, 9) self.frame_7 = QFrame(self.frame_8) self.frame_7.setObjectName(u"frame_7") self.frame_7.setStyleSheet(u"background-color: rgb(56, 75, 89);") self.frame_7.setFrameShape(QFrame.StyledPanel) self.frame_7.setFrameShadow(QFrame.Raised) self.horizontalLayout_6 = QHBoxLayout(self.frame_7) self.horizontalLayout_6.setObjectName(u"horizontalLayout_6") self.horizontalLayout_6.setContentsMargins(10, 0, 0, 3) self.label_4 = QLabel(self.frame_7) self.label_4.setObjectName(u"label_4") self.label_4.setFont(font) self.label_4.setStyleSheet(u"color: rgb(255, 255, 255);") self.horizontalLayout_6.addWidget(self.label_4) self.verticalLayout.addWidget(self.frame_7) self.linkdin_link = QPushButton(self.frame_8) self.linkdin_link.setObjectName(u"linkdin_link") self.linkdin_link.setStyleSheet(u"color: rgb(255, 255, 255);\n" "background-color: rgb(15, 24, 31);") icon = QIcon() icon.addFile(u"image/linkedin.png", QSize(), QIcon.Normal, QIcon.Off) self.linkdin_link.setIcon(icon) self.verticalLayout.addWidget(self.linkdin_link) self.git_link = QPushButton(self.frame_8) self.git_link.setObjectName(u"git_link") self.git_link.setStyleSheet(u"color: rgb(255, 255, 255);\n" "background-color: rgb(15, 24, 31);") icon1 = QIcon() icon1.addFile(u"image/github.png", QSize(), QIcon.Normal, QIcon.Off) self.git_link.setIcon(icon1) self.verticalLayout.addWidget(self.git_link) self.verticalLayout_3.addWidget(self.frame_8, 0, Qt.AlignBottom) self.verticalLayout_2.addWidget(self.frame_6) self.horizontalLayout_2.addWidget(self.frame_2) self.stackedWidget = QStackedWidget(self.frame) self.stackedWidget.setObjectName(u"stackedWidget") self.page = QWidget() self.page.setObjectName(u"page") sizePolicy1.setHeightForWidth(self.page.sizePolicy().hasHeightForWidth()) self.page.setSizePolicy(sizePolicy1) self.horizontalLayout_8 = QHBoxLayout(self.page) self.horizontalLayout_8.setObjectName(u"horizontalLayout_8") self.horizontalLayout_8.setContentsMargins(0, -1, -1, -1) self.frame_21 = QFrame(self.page) self.frame_21.setObjectName(u"frame_21") self.frame_21.setStyleSheet(u"background-color: rgb(15, 24, 31);") self.frame_21.setFrameShape(QFrame.StyledPanel) self.frame_21.setFrameShadow(QFrame.Raised) self.verticalLayout_19 = QVBoxLayout(self.frame_21) self.verticalLayout_19.setSpacing(4) self.verticalLayout_19.setObjectName(u"verticalLayout_19") self.verticalLayout_19.setContentsMargins(-1, 0, -1, -1) self.label_2 = QLabel(self.frame_21) self.label_2.setObjectName(u"label_2") self.label_2.setFont(font) self.label_2.setStyleSheet(u"color: rgb(255,255,255);\n" "background-color: rgb(56, 75, 89);") self.verticalLayout_19.addWidget(self.label_2) self.frame_25 = QFrame(self.frame_21) self.frame_25.setObjectName(u"frame_25") sizePolicy1.setHeightForWidth(self.frame_25.sizePolicy().hasHeightForWidth()) self.frame_25.setSizePolicy(sizePolicy1) self.frame_25.setFrameShape(QFrame.StyledPanel) self.frame_25.setFrameShadow(QFrame.Raised) self.horizontalLayout_13 = QHBoxLayout(self.frame_25) self.horizontalLayout_13.setSpacing(0) self.horizontalLayout_13.setObjectName(u"horizontalLayout_13") self.horizontalLayout_13.setContentsMargins(0, 0, 0, 0) self.frame_26 = QFrame(self.frame_25) self.frame_26.setObjectName(u"frame_26") self.frame_26.setFrameShape(QFrame.StyledPanel) self.frame_26.setFrameShadow(QFrame.Raised) self.verticalLayout_12 = QVBoxLayout(self.frame_26) self.verticalLayout_12.setSpacing(0) self.verticalLayout_12.setObjectName(u"verticalLayout_12") self.verticalLayout_12.setContentsMargins(0, 0, 0, 0) self.frame_27 = QFrame(self.frame_26) self.frame_27.setObjectName(u"frame_27") sizePolicy1.setHeightForWidth(self.frame_27.sizePolicy().hasHeightForWidth()) self.frame_27.setSizePolicy(sizePolicy1) self.frame_27.setFrameShape(QFrame.StyledPanel) self.frame_27.setFrameShadow(QFrame.Raised) self.horizontalLayout_16 = QHBoxLayout(self.frame_27) self.horizontalLayout_16.setSpacing(0) self.horizontalLayout_16.setObjectName(u"horizontalLayout_16") self.horizontalLayout_16.setContentsMargins(0, 0, 0, 0) self.frame_28 = QFrame(self.frame_27) self.frame_28.setObjectName(u"frame_28") sizePolicy.setHeightForWidth(self.frame_28.sizePolicy().hasHeightForWidth()) self.frame_28.setSizePolicy(sizePolicy) self.frame_28.setFrameShape(QFrame.StyledPanel) self.frame_28.setFrameShadow(QFrame.Raised) self.verticalLayout_13 = QVBoxLayout(self.frame_28) self.verticalLayout_13.setObjectName(u"verticalLayout_13") self.frame_29 = QFrame(self.frame_28) self.frame_29.setObjectName(u"frame_29") sizePolicy1.setHeightForWidth(self.frame_29.sizePolicy().hasHeightForWidth()) self.frame_29.setSizePolicy(sizePolicy1) self.frame_29.setFrameShape(QFrame.StyledPanel) self.frame_29.setFrameShadow(QFrame.Raised) self.horizontalLayout_17 = QHBoxLayout(self.frame_29) self.horizontalLayout_17.setSpacing(0) self.horizontalLayout_17.setObjectName(u"horizontalLayout_17") self.horizontalLayout_17.setContentsMargins(0, 0, 0, -1) self.frame_30 = QFrame(self.frame_29) self.frame_30.setObjectName(u"frame_30") self.frame_30.setFrameShape(QFrame.StyledPanel) self.frame_30.setFrameShadow(QFrame.Raised) self.horizontalLayout_18 = QHBoxLayout(self.frame_30) self.horizontalLayout_18.setSpacing(0) self.horizontalLayout_18.setObjectName(u"horizontalLayout_18") self.horizontalLayout_18.setContentsMargins(0, 0, 0, -1) self.tableWidget = QTableWidget(self.frame_30) if (self.tableWidget.columnCount() < 3): self.tableWidget.setColumnCount(3) brush = QBrush(QColor(0, 0, 0, 255)) brush.setStyle(Qt.SolidPattern) __qtablewidgetitem = QTableWidgetItem() __qtablewidgetitem.setBackground(QColor(255, 255, 255)); __qtablewidgetitem.setForeground(brush); self.tableWidget.setHorizontalHeaderItem(0, __qtablewidgetitem) __qtablewidgetitem1 = QTableWidgetItem() __qtablewidgetitem1.setForeground(brush); self.tableWidget.setHorizontalHeaderItem(1, __qtablewidgetitem1) __qtablewidgetitem2 = QTableWidgetItem() __qtablewidgetitem2.setForeground(brush); self.tableWidget.setHorizontalHeaderItem(2, __qtablewidgetitem2) if (self.tableWidget.rowCount() < 25): self.tableWidget.setRowCount(25) __qtablewidgetitem3 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(0, __qtablewidgetitem3) __qtablewidgetitem4 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(1, __qtablewidgetitem4) __qtablewidgetitem5 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(2, __qtablewidgetitem5) __qtablewidgetitem6 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(3, __qtablewidgetitem6) __qtablewidgetitem7 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(4, __qtablewidgetitem7) __qtablewidgetitem8 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(5, __qtablewidgetitem8) __qtablewidgetitem9 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(6, __qtablewidgetitem9) __qtablewidgetitem10 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(7, __qtablewidgetitem10) __qtablewidgetitem11 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(8, __qtablewidgetitem11) __qtablewidgetitem12 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(9, __qtablewidgetitem12) __qtablewidgetitem13 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(10, __qtablewidgetitem13) __qtablewidgetitem14 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(11, __qtablewidgetitem14) __qtablewidgetitem15 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(12, __qtablewidgetitem15) __qtablewidgetitem16 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(13, __qtablewidgetitem16) __qtablewidgetitem17 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(14, __qtablewidgetitem17) __qtablewidgetitem18 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(15, __qtablewidgetitem18) __qtablewidgetitem19 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(16, __qtablewidgetitem19) __qtablewidgetitem20 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(17, __qtablewidgetitem20) __qtablewidgetitem21 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(18, __qtablewidgetitem21) __qtablewidgetitem22 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(19, __qtablewidgetitem22) __qtablewidgetitem23 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(20, __qtablewidgetitem23) __qtablewidgetitem24 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(21, __qtablewidgetitem24) __qtablewidgetitem25 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(22, __qtablewidgetitem25) __qtablewidgetitem26 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(23, __qtablewidgetitem26) __qtablewidgetitem27 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(24, __qtablewidgetitem27) self.tableWidget.setObjectName(u"tableWidget") sizePolicy2.setHeightForWidth(self.tableWidget.sizePolicy().hasHeightForWidth()) self.tableWidget.setSizePolicy(sizePolicy2) self.tableWidget.setStyleSheet(u"color:rgb(255,255,255);") self.tableWidget.setFrameShape(QFrame.WinPanel) self.tableWidget.setFrameShadow(QFrame.Raised) self.tableWidget.setDragEnabled(True) self.tableWidget.setAlternatingRowColors(False) self.tableWidget.setSelectionMode(QAbstractItemView.MultiSelection) self.tableWidget.horizontalHeader().setMinimumSectionSize(32) self.horizontalLayout_18.addWidget(self.tableWidget) self.horizontalLayout_17.addWidget(self.frame_30) self.verticalLayout_13.addWidget(self.frame_29) self.frame_31 = QFrame(self.frame_28) self.frame_31.setObjectName(u"frame_31") sizePolicy1.setHeightForWidth(self.frame_31.sizePolicy().hasHeightForWidth()) self.frame_31.setSizePolicy(sizePolicy1) self.frame_31.setFrameShape(QFrame.StyledPanel) self.frame_31.setFrameShadow(QFrame.Raised) self.verticalLayout_14 = QVBoxLayout(self.frame_31) self.verticalLayout_14.setSpacing(0) self.verticalLayout_14.setObjectName(u"verticalLayout_14") self.verticalLayout_14.setContentsMargins(0, 0, 0, 0) self.frame_32 = QFrame(self.frame_31) self.frame_32.setObjectName(u"frame_32") self.frame_32.setFrameShape(QFrame.StyledPanel) self.frame_32.setFrameShadow(QFrame.Raised) self.horizontalLayout_19 = QHBoxLayout(self.frame_32) self.horizontalLayout_19.setSpacing(0) self.horizontalLayout_19.setObjectName(u"horizontalLayout_19") self.horizontalLayout_19.setContentsMargins(0, 0, 0, 10) self.frame_33 = QFrame(self.frame_32) self.frame_33.setObjectName(u"frame_33") self.frame_33.setFrameShape(QFrame.StyledPanel) self.frame_33.setFrameShadow(QFrame.Raised) self.verticalLayout_15 = QVBoxLayout(self.frame_33) self.verticalLayout_15.setSpacing(0) self.verticalLayout_15.setObjectName(u"verticalLayout_15") self.verticalLayout_15.setContentsMargins(0, 0, 0, 0) self.frame_34 = QFrame(self.frame_33) self.frame_34.setObjectName(u"frame_34") self.frame_34.setFrameShape(QFrame.StyledPanel) self.frame_34.setFrameShadow(QFrame.Raised) self.horizontalLayout_20 = QHBoxLayout(self.frame_34) self.horizontalLayout_20.setSpacing(30) self.horizontalLayout_20.setObjectName(u"horizontalLayout_20") self.horizontalLayout_20.setContentsMargins(0, 0, 0, 0) self.label_9 = QLabel(self.frame_34) self.label_9.setObjectName(u"label_9") self.label_9.setStyleSheet(u"color: rgb(255, 255, 255);\n" "background-color: rgb(56, 75, 89);\n" "border: 3px solid rgb(56, 75, 89);") self.horizontalLayout_20.addWidget(self.label_9) self.pincode_no = QLineEdit(self.frame_34) self.pincode_no.setObjectName(u"pincode_no") sizePolicy3 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.pincode_no.sizePolicy().hasHeightForWidth()) self.pincode_no.setSizePolicy(sizePolicy3) self.pincode_no.setStyleSheet(u"color: rgb(255, 255, 255);\n" "") self.horizontalLayout_20.addWidget(self.pincode_no) self.label_10 = QLabel(self.frame_34) self.label_10.setObjectName(u"label_10") self.label_10.setStyleSheet(u"color: rgb(255, 255, 255);\n" "background-color: rgb(56, 75, 89);\n" "border: 3px solid rgb(56, 75, 89);") self.horizontalLayout_20.addWidget(self.label_10) self.deos_no = QLineEdit(self.frame_34) self.deos_no.setObjectName(u"deos_no") self.deos_no.setStyleSheet(u"color: rgb(255, 255, 255);") self.deos_no.setInputMethodHints(Qt.ImhDigitsOnly|Qt.ImhPreferNumbers) self.horizontalLayout_20.addWidget(self.deos_no) self.verticalLayout_15.addWidget(self.frame_34) self.horizontalLayout_19.addWidget(self.frame_33) self.verticalLayout_14.addWidget(self.frame_32) self.frame_35 = QFrame(self.frame_31) self.frame_35.setObjectName(u"frame_35") self.frame_35.setFrameShape(QFrame.StyledPanel) self.frame_35.setFrameShadow(QFrame.Raised) self.verticalLayout_16 = QVBoxLayout(self.frame_35) self.verticalLayout_16.setSpacing(10) self.verticalLayout_16.setObjectName(u"verticalLayout_16") self.verticalLayout_16.setContentsMargins(0, 0, 0, 0) self.frame_36 = QFrame(self.frame_35) self.frame_36.setObjectName(u"frame_36") self.frame_36.setFrameShape(QFrame.StyledPanel) self.frame_36.setFrameShadow(QFrame.Raised) self.verticalLayout_17 = QVBoxLayout(self.frame_36) self.verticalLayout_17.setSpacing(0) self.verticalLayout_17.setObjectName(u"verticalLayout_17") self.verticalLayout_17.setContentsMargins(0, 0, 0, 0) self.frame_37 = QFrame(self.frame_36) self.frame_37.setObjectName(u"frame_37") self.frame_37.setFrameShape(QFrame.StyledPanel) self.frame_37.setFrameShadow(QFrame.Raised) self.verticalLayout_18 = QVBoxLayout(self.frame_37) self.verticalLayout_18.setSpacing(0) self.verticalLayout_18.setObjectName(u"verticalLayout_18") self.verticalLayout_18.setContentsMargins(0, 0, 0, 10) self.frame_38 = QFrame(self.frame_37) self.frame_38.setObjectName(u"frame_38") self.frame_38.setFrameShape(QFrame.StyledPanel) self.frame_38.setFrameShadow(QFrame.Raised) self.horizontalLayout_21 = QHBoxLayout(self.frame_38) self.horizontalLayout_21.setSpacing(20) self.horizontalLayout_21.setObjectName(u"horizontalLayout_21") self.horizontalLayout_21.setContentsMargins(0, 0, 0, 10) self.label_11 = QLabel(self.frame_38) self.label_11.setObjectName(u"label_11") self.label_11.setStyleSheet(u"color: rgb(255, 255, 255);\n" "background-color: rgb(56, 75, 89);\n" "border: 3px solid rgb(56, 75, 89);") self.horizontalLayout_21.addWidget(self.label_11) self.statename_line = QLineEdit(self.frame_38) self.statename_line.setObjectName(u"statename_line") sizePolicy3.setHeightForWidth(self.statename_line.sizePolicy().hasHeightForWidth()) self.statename_line.setSizePolicy(sizePolicy3) self.statename_line.setStyleSheet(u"color: rgb(255, 255, 255);") self.statename_line.setInputMethodHints(Qt.ImhNone) self.horizontalLayout_21.addWidget(self.statename_line) self.label_12 = QLabel(self.frame_38) self.label_12.setObjectName(u"label_12") self.label_12.setStyleSheet(u"color: rgb(255, 255, 255);\n" "background-color: rgb(56, 75, 89);\n" "border: 3px solid rgb(56, 75, 89);\n" "") self.horizontalLayout_21.addWidget(self.label_12) self.cityname_line = QLineEdit(self.frame_38) self.cityname_line.setObjectName(u"cityname_line") self.cityname_line.setStyleSheet(u"color: rgb(255, 255, 255);\n" "") self.horizontalLayout_21.addWidget(self.cityname_line) self.verticalLayout_18.addWidget(self.frame_38) self.frame_39 = QFrame(self.frame_37) self.frame_39.setObjectName(u"frame_39") self.frame_39.setFrameShape(QFrame.StyledPanel) self.frame_39.setFrameShadow(QFrame.Raised) self.horizontalLayout_22 = QHBoxLayout(self.frame_39) self.horizontalLayout_22.setSpacing(10) self.horizontalLayout_22.setObjectName(u"horizontalLayout_22") self.horizontalLayout_22.setContentsMargins(0, 0, 0, 0) self.agetype_box = QComboBox(self.frame_39) self.agetype_box.addItem("") self.agetype_box.addItem("") self.agetype_box.addItem("") self.agetype_box.setObjectName(u"agetype_box") sizePolicy1.setHeightForWidth(self.agetype_box.sizePolicy().hasHeightForWidth()) self.agetype_box.setSizePolicy(sizePolicy1) self.agetype_box.setStyleSheet(u"color: rgb(255, 255, 255);\n" "background-color: rgb(56, 75, 89);\n" "border: 3px solid rgb(56, 75, 89);") self.horizontalLayout_22.addWidget(self.agetype_box) self.vaccinetype_box = QComboBox(self.frame_39) self.vaccinetype_box.addItem("") self.vaccinetype_box.addItem("") self.vaccinetype_box.setObjectName(u"vaccinetype_box") sizePolicy1.setHeightForWidth(self.vaccinetype_box.sizePolicy().hasHeightForWidth()) self.vaccinetype_box.setSizePolicy(sizePolicy1) self.vaccinetype_box.setStyleSheet(u"color: rgb(255, 255, 255);\n" "background-color: rgb(56, 75, 89);\n" "border: 3px solid rgb(56, 75, 89);") self.horizontalLayout_22.addWidget(self.vaccinetype_box) self.paidtype_box = QComboBox(self.frame_39) self.paidtype_box.addItem("") self.paidtype_box.addItem("") self.paidtype_box.setObjectName(u"paidtype_box") sizePolicy1.setHeightForWidth(self.paidtype_box.sizePolicy().hasHeightForWidth()) self.paidtype_box.setSizePolicy(sizePolicy1) self.paidtype_box.setStyleSheet(u"color: rgb(255, 255, 255);\n" "background-color: rgb(56, 75, 89);\n" "border: 3px solid rgb(56, 75, 89);") self.horizontalLayout_22.addWidget(self.paidtype_box) self.pinsub_btn = QPushButton(self.frame_39) self.pinsub_btn.setObjectName(u"pinsub_btn") sizePolicy4 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.pinsub_btn.sizePolicy().hasHeightForWidth()) self.pinsub_btn.setSizePolicy(sizePolicy4) self.pinsub_btn.setStyleSheet(u"color: rgb(255, 255, 255);;\n" "border: 3px solid rgb(56, 75, 89);") self.horizontalLayout_22.addWidget(self.pinsub_btn) self.verticalLayout_18.addWidget(self.frame_39) self.verticalLayout_17.addWidget(self.frame_37) self.verticalLayout_16.addWidget(self.frame_36) self.verticalLayout_14.addWidget(self.frame_35) self.verticalLayout_13.addWidget(self.frame_31, 0, Qt.AlignBottom) self.horizontalLayout_16.addWidget(self.frame_28) self.verticalLayout_12.addWidget(self.frame_27) self.frame_40 = QFrame(self.frame_26) self.frame_40.setObjectName(u"frame_40") self.frame_40.setFrameShape(QFrame.StyledPanel) self.frame_40.setFrameShadow(QFrame.Raised) self.horizontalLayout_23 = QHBoxLayout(self.frame_40) self.horizontalLayout_23.setSpacing(0) self.horizontalLayout_23.setObjectName(u"horizontalLayout_23") self.horizontalLayout_23.setContentsMargins(0, 0, 0, 0) self.pin_error = QLineEdit(self.frame_40) self.pin_error.setObjectName(u"pin_error") sizePolicy3.setHeightForWidth(self.pin_error.sizePolicy().hasHeightForWidth()) self.pin_error.setSizePolicy(sizePolicy3) self.pin_error.setStyleSheet(u"color: rgb(255, 255, 255);") self.pin_error.setReadOnly(True) self.horizontalLayout_23.addWidget(self.pin_error) self.verticalLayout_12.addWidget(self.frame_40, 0, Qt.AlignBottom) self.horizontalLayout_13.addWidget(self.frame_26) self.verticalLayout_19.addWidget(self.frame_25) self.horizontalLayout_8.addWidget(self.frame_21) self.stackedWidget.addWidget(self.page) self.page_2 = QWidget() self.page_2.setObjectName(u"page_2") self.horizontalLayout_3 = QHBoxLayout(self.page_2) self.horizontalLayout_3.setObjectName(u"horizontalLayout_3") self.gitview = QFrame(self.page_2) self.gitview.setObjectName(u"gitview") self.gitview.setFrameShape(QFrame.StyledPanel) self.gitview.setFrameShadow(QFrame.Raised) self.horizontalLayout_5 = QHBoxLayout(self.gitview) self.horizontalLayout_5.setObjectName(u"horizontalLayout_5") self.horizontalLayout_3.addWidget(self.gitview) self.stackedWidget.addWidget(self.page_2) self.page_3 = QWidget() self.page_3.setObjectName(u"page_3") self.horizontalLayout_7 = QHBoxLayout(self.page_3) self.horizontalLayout_7.setObjectName(u"horizontalLayout_7") self.frame_9 = QFrame(self.page_3) self.frame_9.setObjectName(u"frame_9") self.frame_9.setFrameShape(QFrame.StyledPanel) self.frame_9.setFrameShadow(QFrame.Raised) self.horizontalLayout_9 = QHBoxLayout(self.frame_9) self.horizontalLayout_9.setObjectName(u"horizontalLayout_9") self.horizontalLayout_9.setContentsMargins(50, -1, 50, -1) self.frame_10 = QFrame(self.frame_9) self.frame_10.setObjectName(u"frame_10") self.frame_10.setStyleSheet(u"") self.frame_10.setFrameShape(QFrame.StyledPanel) self.frame_10.setFrameShadow(QFrame.Raised) self.verticalLayout_5 = QVBoxLayout(self.frame_10) self.verticalLayout_5.setObjectName(u"verticalLayout_5") self.dj_pic = QLabel(self.frame_10) self.dj_pic.setObjectName(u"dj_pic") self.dj_pic.setStyleSheet(u"border: 5px inset rgb(56, 75, 89);\n" "") self.dj_pic.setScaledContents(False) self.verticalLayout_5.addWidget(self.dj_pic) self.dj = QPushButton(self.frame_10) self.dj.setObjectName(u"dj") self.dj.setStyleSheet(u"color: rgb(255,255,255);") self.verticalLayout_5.addWidget(self.dj) self.horizontalLayout_9.addWidget(self.frame_10, 0, Qt.AlignHCenter|Qt.AlignVCenter) self.frame_11 = QFrame(self.frame_9) self.frame_11.setObjectName(u"frame_11") self.frame_11.setFrameShape(QFrame.StyledPanel) self.frame_11.setFrameShadow(QFrame.Raised) self.horizontalLayout_10 = QHBoxLayout(self.frame_11) self.horizontalLayout_10.setObjectName(u"horizontalLayout_10") self.label_6 = QLabel(self.frame_11) self.label_6.setObjectName(u"label_6") self.label_6.setMaximumSize(QSize(16777215, 378)) self.label_6.setPixmap(QPixmap(u"image/support (5).png")) self.label_6.setScaledContents(False) self.label_6.setWordWrap(True) self.horizontalLayout_10.addWidget(self.label_6) self.horizontalLayout_9.addWidget(self.frame_11, 0, Qt.AlignHCenter|Qt.AlignVCenter) self.frame_3 = QFrame(self.frame_9) self.frame_3.setObjectName(u"frame_3") self.frame_3.setStyleSheet(u"") self.frame_3.setFrameShape(QFrame.StyledPanel) self.frame_3.setFrameShadow(QFrame.Raised) self.verticalLayout_6 = QVBoxLayout(self.frame_3) self.verticalLayout_6.setObjectName(u"verticalLayout_6") self.rohit_pic = QLabel(self.frame_3) self.rohit_pic.setObjectName(u"rohit_pic") self.rohit_pic.setStyleSheet(u"border: 5px inset rgb(56, 75, 89);\n" "") self.verticalLayout_6.addWidget(self.rohit_pic) self.rohit = QPushButton(self.frame_3) self.rohit.setObjectName(u"rohit") self.rohit.setStyleSheet(u"color: rgb(255,255,255);") self.verticalLayout_6.addWidget(self.rohit) self.horizontalLayout_9.addWidget(self.frame_3, 0, Qt.AlignHCenter|Qt.AlignVCenter) self.horizontalLayout_7.addWidget(self.frame_9) self.stackedWidget.addWidget(self.page_3) self.horizontalLayout_2.addWidget(self.stackedWidget) self.horizontalLayout.addWidget(self.frame) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.stackedWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"Cowin Notifier", None)) self.label.setText(QCoreApplication.translate("MainWindow", u"Menu", None)) self.slot_checker.setText(QCoreApplication.translate("MainWindow", u" Slots Checker ", None)) self.label_4.setText(QCoreApplication.translate("MainWindow", u"Support Me", None)) self.linkdin_link.setText(QCoreApplication.translate("MainWindow", u" Linkdin", None)) self.git_link.setText(QCoreApplication.translate("MainWindow", u" Github", None)) self.label_2.setText(QCoreApplication.translate("MainWindow", u"Cowin Notifier", None)) ___qtablewidgetitem = self.tableWidget.horizontalHeaderItem(0) ___qtablewidgetitem.setText(QCoreApplication.translate("MainWindow", u"NAME", None)); ___qtablewidgetitem1 = self.tableWidget.horizontalHeaderItem(1) ___qtablewidgetitem1.setText(QCoreApplication.translate("MainWindow", u"ADDRESS", None)); ___qtablewidgetitem2 = self.tableWidget.horizontalHeaderItem(2) ___qtablewidgetitem2.setText(QCoreApplication.translate("MainWindow", u"TOTAL_DOES", None)); ___qtablewidgetitem3 = self.tableWidget.verticalHeaderItem(0) ___qtablewidgetitem3.setText(QCoreApplication.translate("MainWindow", u"1", None)); ___qtablewidgetitem4 = self.tableWidget.verticalHeaderItem(1) ___qtablewidgetitem4.setText(QCoreApplication.translate("MainWindow", u"2", None)); ___qtablewidgetitem5 = self.tableWidget.verticalHeaderItem(2) ___qtablewidgetitem5.setText(QCoreApplication.translate("MainWindow", u"3", None)); ___qtablewidgetitem6 = self.tableWidget.verticalHeaderItem(3) ___qtablewidgetitem6.setText(QCoreApplication.translate("MainWindow", u"4", None)); ___qtablewidgetitem7 = self.tableWidget.verticalHeaderItem(4) ___qtablewidgetitem7.setText(QCoreApplication.translate("MainWindow", u"5", None)); ___qtablewidgetitem8 = self.tableWidget.verticalHeaderItem(5) ___qtablewidgetitem8.setText(QCoreApplication.translate("MainWindow", u"6", None)); ___qtablewidgetitem9 = self.tableWidget.verticalHeaderItem(6) ___qtablewidgetitem9.setText(QCoreApplication.translate("MainWindow", u"7", None)); ___qtablewidgetitem10 = self.tableWidget.verticalHeaderItem(7) ___qtablewidgetitem10.setText(QCoreApplication.translate("MainWindow", u"8", None)); ___qtablewidgetitem11 = self.tableWidget.verticalHeaderItem(8) ___qtablewidgetitem11.setText(QCoreApplication.translate("MainWindow", u"9", None)); ___qtablewidgetitem12 = self.tableWidget.verticalHeaderItem(9) ___qtablewidgetitem12.setText(QCoreApplication.translate("MainWindow", u"10", None)); ___qtablewidgetitem13 = self.tableWidget.verticalHeaderItem(10) ___qtablewidgetitem13.setText(QCoreApplication.translate("MainWindow", u"11", None)); ___qtablewidgetitem14 = self.tableWidget.verticalHeaderItem(11) ___qtablewidgetitem14.setText(QCoreApplication.translate("MainWindow", u"12", None)); ___qtablewidgetitem15 = self.tableWidget.verticalHeaderItem(12) ___qtablewidgetitem15.setText(QCoreApplication.translate("MainWindow", u"13", None));
filter_entity, 'is_warning_list': is_warning_list, 'entity': entity } @view_config( route_name='check_login_availability', renderer='json' ) def check_login_availability(request): """checks it the given login is available """ login_name = request.matchdict['login'] logger.debug('checking availability for: %s' % login_name) available = 1 if login_name: user = User.query.filter(User.login == login_name).first() if user: available = 0 return { 'available': available } @view_config( route_name='check_email_availability', renderer='json' ) def check_email_availability(request): """checks it the given email is available """ email = request.matchdict['email'] logger.debug('checking availability for: %s' % email) available = 1 if email: user = User.query.filter(User.email == email).first() if user: available = 0 return { 'available': available } @view_config( route_name='get_entity_resources', permission='Read_User', renderer='json' ) @view_config( route_name='get_resources', permission='Read_User', renderer='json' ) @view_config( route_name='get_resource', permission='Read_User', renderer='json' ) def get_resources(request): """returns Users for Resource View """ # TODO: This is a very ugly function, please define the borders and use cases correctly and then clean it from stalker_pyramid.views.task import generate_recursive_task_query start = time.time() # return users for now # /resources/ # /resources/26/ resource_id = request.matchdict.get('id') logger.debug('resource_id: %s' % resource_id) parent_id = request.params.get('parent_id') logger.debug('parent_id: %s' % parent_id) execute = DBSession.connection().execute entity_type = None if resource_id: # get the entity type of that resource data = execute('select entity_type from "SimpleEntities" where id=%s' % resource_id).fetchone() if data: entity_type = data[0] else: return [] else: # default to User entity_type = "User" logger.debug('entity_type : %s' % entity_type) # get resource details plus time logs if not parent_id: if entity_type == 'Department': resource_sql_query = """select "SimpleEntities".id, "SimpleEntities".name, "SimpleEntities".entity_type, count(*) as resource_count from "SimpleEntities" join "Department_Users" on "Department_Users".did = "SimpleEntities".id where "SimpleEntities".entity_type = '%s' """ % entity_type elif entity_type == 'User': resource_sql_query = """select "SimpleEntities".id, "SimpleEntities".name, "SimpleEntities".entity_type, 1 as resource_count from "SimpleEntities" where "SimpleEntities".entity_type = '%s' """ % entity_type elif entity_type in ['Studio', 'Project']: resource_sql_query = """select "SimpleEntities".id, "SimpleEntities".name, "SimpleEntities".entity_type, count(*) as resource_count from "SimpleEntities" join "Department_Users" on "Department_Users".did = "SimpleEntities".id """ if resource_id and entity_type not in ["Studio", "Project"]: resource_sql_query += "and id=%s group by id, name, entity_type order by name" % resource_id else: resource_sql_query += "group by id, name, entity_type order by name" # if the given entity is a Department return all the time logs of the # users of that department time_log_query = """select "TimeLogs".id, "TimeLogs".task_id, extract(epoch from "TimeLogs".start) * 1000 as start, extract(epoch from "TimeLogs".end) * 1000 as end from "TimeLogs" """ tasks_query = """select tasks.id, tasks.full_path, extract(epoch from "Tasks".computed_start) * 1000 as start, extract(epoch from "Tasks".computed_end) * 1000 as end -- start with tasks (with full names) from ( %(recursive_task_query)s ) as tasks join "Tasks" on tasks.id = "Tasks".id """ % { 'recursive_task_query': generate_recursive_task_query(ordered=False) } has_children = False if entity_type == "User": time_log_query += "where resource_id = %(id)s" tasks_query += """join "Task_Resources" on "Tasks".id = "Task_Resources".task_id where not ( exists ( select 1 from "Tasks" where "Tasks".parent_id = tasks.id ) ) and resource_id = %(id)s """ has_children = False elif entity_type in ["Department", "Studio"]: time_log_query += """ join "Department_Users" on "Department_Users".uid = "TimeLogs".resource_id where did = %(id)s""" tasks_query += """join "Task_Resources" on "Tasks".id = "Task_Resources".task_id join "Department_Users" on "Task_Resources".resource_id = "Department_Users".uid join "SimpleEntities" as "Task_SimpleEntities" on "Tasks".id = "Task_SimpleEntities".id where not ( exists ( select 1 from "Tasks" where "Tasks".parent_id = tasks.id ) ) and did = %(id)s group by tasks.id, tasks.full_path, "Tasks".start, "Tasks".end, "Tasks".computed_start, "Tasks".computed_end order by start """ has_children = True elif entity_type == "Project": # the resource is a Project return all the project tasks and # return all the time logs of the users in that project time_log_query += """ join "Project_Users" on "Project_Users".user_id = "TimeLogs".resource_id -- where did = %(id)s """ # tasks_query += """ # -- select all the leaf tasks of the users of a specific Project # select # "Tasks".id, # "Task_SimpleEntities".name, # extract(epoch from "Tasks".computed_start) * 1000 as start, # extract(epoch from "Tasks".computed_end) * 1000 as end # from "Tasks" # join "SimpleEntities" as "Task_SimpleEntities" on "Tasks".id = "Task_SimpleEntities".id # where not ( # exists ( # select 1 # from "Tasks" # where "Tasks".parent_id = tasks.id # ) # ) and project_id = %(id)s # group by id, "Task_SimpleEntities".name, start, "end", "Tasks".computed_start, "Tasks".computed_end # order by start # """ tasks_query += """join "Task_Resources" on "Tasks".id = "Task_Resources".task_id join "Project_Users" on "Project_Users".user_id = "Task_Resources".resource_id join "SimpleEntities" as "Task_SimpleEntities" on "Tasks".id = "Task_SimpleEntities".id where not ( exists ( select 1 from "Tasks" where "Tasks".parent_id = tasks.id ) ) and "Project_Users".project_id = %(id)s group by tasks.id, tasks.full_path, "Tasks".start, "Tasks".end, "Tasks".computed_start, "Tasks".computed_end order by start """ has_children = True else: # return departments ??? should also return Groups, Project etc. # that contains users resource_sql_query = """select "Users".id, "SimpleEntities".name, "SimpleEntities".entity_type, 1 as resource_count from "Users" join "SimpleEntities" on "SimpleEntities".id = "Users".id join "Department_Users" on "Department_Users".uid = "Users".id join "Departments" on "Department_Users".did = "Departments".id where "Departments".id = %(id)s order by name """ % {'id': parent_id} time_log_query = """select "TimeLogs".id, "TimeLogs".task_id, extract(epoch from "TimeLogs".start) * 1000 as start, extract(epoch from "TimeLogs".end) * 1000 as end from "TimeLogs" where resource_id = %(id)s """ tasks_query = """select tasks.id, tasks.full_path, extract(epoch from "Tasks".computed_start) * 1000 as start, extract(epoch from "Tasks".computed_end) * 1000 as end from ( %(recursive_task_query)s ) as tasks join "Tasks" on tasks.id = "Tasks".id join "Task_Resources" on tasks.id = "Task_Resources".task_id where not ( exists ( select 1 from "Tasks" where "Tasks".parent_id = tasks.id ) ) and resource_id = %(id)s """ has_children = False # logger.debug('resource_sql_query : %s' % resource_sql_query) # logger.debug('time_log_query : %s' % time_log_query) # logger.debug('tasks_sql_query : %s' % tasks_query) resources_result = execute(resource_sql_query).fetchall() # logger.debug('resources_result : %s' % resources_result) link = '/%s/%s/view' % (entity_type.lower(), '%s') data = [ { 'id': rr[0], 'name': rr[1], 'type': rr[2], 'resource_count': rr[3], 'hasChildren': has_children, 'link': link % rr[0], 'time_logs': [ { 'id': tr[0], 'task_id': tr[1], 'start': tr[2], 'end': tr[3] } for tr in execute( time_log_query % { 'id': rr[0] }).fetchall() ], 'tasks': [ { 'id': tr[0], 'name': tr[1], 'start': tr[2], 'end': tr[3] } for tr in execute( tasks_query % { 'recursive_task_query': generate_recursive_task_query(False), 'id': rr[0] } ).fetchall() ] } for rr in resources_result ] end = time.time() logger.debug('get_resources took : %s seconds' % (end - start)) data_count = len(data) content_range = '%s-%s/%s' % (0, data_count - 1, data_count) resp = Response( json_body=data ) resp.content_range = content_range return resp @view_config( route_name='delete_user_dialog', renderer='templates/modals/confirm_dialog.jinja2' ) def delete_user_dialog(request): """deletes the user with the given id """ logger.debug('delete_user_dialog is starts') user_id = request.matchdict.get('id') user = User.query.get(user_id) came_from = request.params.get('came_from', request.current_route_path()) action = '/users/%s/delete?came_from=%s' % (user_id, came_from) message = \ 'Are you sure you want to ' \ '<strong>delete User %s </strong>?' % user.name logger.debug('action: %s' % action) return { 'came_from': came_from, 'message': message, 'action': action } @view_config( route_name='delete_user', permission='Delete_User' ) def delete_user(request): """deletes the user with the given id """ user_id = request.matchdict.get('id') user = User.query.get(user_id) if not user: transaction.abort() return Response('Can not find a User with id: %s' % user_id, 500) try: DBSession.delete(user) transaction.commit() request.session.flash( 'success: %s is deleted' % user.name ) except Exception as e: transaction.abort() c = StdErrToHTMLConverter(e) transaction.abort() request.session.flash( c.html() ) return Response(c.html(), 500) return Response('Successfully deleted user: %s' % user_id) @view_config( route_name='update_entity_user' ) def update_entity_user(request): """updates user for given entity """ logger.debug('update_entity_user_role is starts') logged_in_user = get_logged_in_user(request) utc_now = datetime.datetime.now(pytz.utc) entity_id = request.matchdict.get('id') entity = Entity.query.get(entity_id) if not entity: transaction.abort() return Response('Can not find a entity with id: %s' % entity_id, 500) user_id = request.params.get('id', -1) user = User.query.filter(User.id == user_id).first() rate = request.params.get('rate', None) role_name = request.params.get('role', None) role = query_role(role_name) type_name = request.params.get('type_name', None) type = query_type("User", type_name) logger.debug('user_id: %s' % user_id) logger.debug('role_name: %s' % role_name) logger.debug('rate: %s' % rate) logger.debug('entity.entity_type: %s' % entity.entity_type) if not user: transaction.abort() return Response('Can not find a User with id: %s' % user_id, 500) if type: user.type = type user.date_updated = utc_now user.updated_by = logged_in_user if user not in entity.users: entity.users.append(user) if entity.entity_type in ["Project", "Client", "Department"]: query_string = '%(class_name)sUser.query.filter(%(class_name)sUser.user_id == user_id).filter(%(class_name)sUser.%(attr_name)s == entity_id)' q = eval(query_string % {'class_name': entity.entity_type, 'attr_name': '%s_id' % entity.entity_type.lower() }) entity_user = q.first() entity_user.role = role if rate: entity_user.rate = int(rate) logger.debug('entity_user: %s' % entity_user) logger.debug('entity_user.rate: %s' % entity_user.rate) entity_user.date_updated = utc_now
<filename>line_breaker.py # encoding: utf-8 '''Line breaking''' from numpy import array, float64, argmax, argmin, uint8, ones, floor, mean, std, where, argsort import cv2 as cv from utils import check_for_overlap from fast_utils import ftrim, fadd_padding import sys from bisect import bisect, bisect_right from feature_extraction import normalize_and_extract_features from classify import load_cls, label_chars cls = load_cls('logistic-cls') class LineCut(object): '''Line Cutting object - breaks lines in a page where lines are separated by empty whitespace Parameters: -------------------- shapes: page_element object, (see page_elements.py) thresh_scale: float, default=.9995 A threshold value for determining the breakline in the event that there is black pixel noise between lines. Should be set high to avoid setting line breaks through characters themselves. Attributes: ----------- lines_chars: list of lists, length=number of lines on page. Each sub-list contains the indices for the bounding boxes/contours assigned to its corresponding line. line_indices: list of int, indices of breaklines with respect to page_array baselines: list of int, the index of the baseline for each line where baseline here is usually a line that goes through all the thick "head" (Tibetan: mgo) parts found on most Tibetan letters Methods: -------- get_box: return the bounding box for a given index get_contour: return the contour for a given index The get_box, get_contour methods are mostly here for API compatibility with LineCluster. ''' def __init__(self, shapes, thresh_scale=.9995): self.shapes = shapes self.baselines = [] ### Inflate chars to avoid vowels breaking off their lines inflated = shapes.img_arr.copy() INFL_ITER = shapes.conf['line_cut_inflation'] inflated = cv.erode(inflated, None, iterations=INFL_ITER) self.vsum = inflated.sum(axis=1) ### Determine line indices vsum_max = self.vsum.max() threshold = vsum_max * thresh_scale self.line_indices = [] for i, s in enumerate(self.vsum): if s < threshold and self.vsum[i - 1] >= threshold: self.line_indices.append(i - 1) li = self.line_indices self.k = len(self.line_indices) ### Calculate heights of lines. Split out lines that are too tall diffs = [li[i+1] - li[i] - len(where(self.vsum[li[i]:li[i+1]] == vsum_max)[0]) for i in range(len(li[:-2]))] too_tall = [] for i in range(len(diffs)): otherdiffs = diffs[:i] + diffs[i+1:] odmean = mean(otherdiffs) odstd = std(otherdiffs) if diffs[i] > 2*odstd + odmean: #TODO: use better criteria for above condition too_tall.append(i) if shapes.conf['stop_line_cut']: if len(too_tall) > 0: return # ### Separate lines deemed too tall # added_lines = 0 # for i in too_tall: # i += added_lines # padding = floor(diffs[i]*.25) # top_bound = self.line_indices[i] + padding # bottom_bound = self.line_indices[i+1] - padding # # print top_bound, bottom_bound # extra_line = top_bound + self.shapes.img_arr[top_bound:bottom_bound].sum(axis=1).argmax() # insert_point = bisect(self.line_indices, extra_line) # self.line_indices.insert(insert_point, extra_line) # added_lines += 1 # li = self.line_indices # diffs = [li[i+1] - li[i] for i in range(len(li[:-2]))] ############## Draw line breaks on original page # for l in self.line_indices: # self.shapes.img_arr[l] = 0 # import Image # Image.fromarray(self.shapes.img_arr*255).show() ############## self.assign_char_indices() # self._remove_small_noise() def get_baselines(self): if not self.baselines: for i, k in enumerate(self.line_indices[:-1]): vsum_vals = self.vsum[k:self.line_indices[i+1]] if vsum_vals.any(): self.baselines.append(k +\ argmin(vsum_vals)) self.baselines.append(self.line_indices[-1]+\ argmin(self.vsum[self.line_indices[-1]:])) return self.baselines def assign_char_indices(self): ''' Notes: ------ Complexity: nlogn for sorting linear for zip and index extraction bisect is log n ''' char_tops = zip(self.shapes.get_tops(), self.shapes.get_indices()) char_tops.sort(key=lambda x: x[0]) sorted_indices = [i[1] for i in char_tops] _line_insert_indxs = [] _line_insert_indxs.extend([bisect(char_tops, (i - 1,)) for i in self.line_indices]) self.lines_chars = [] if not _line_insert_indxs: raise for i, l in enumerate(_line_insert_indxs[:-1]): self.lines_chars.append(sorted_indices[l:_line_insert_indxs[i+1]]) self.lines_chars.append(sorted_indices[_line_insert_indxs[-1]:]) self.k = len(self.line_indices) ## Small contour insertion cctops = [self.shapes.get_boxes()[i][1] for i in self.shapes.small_contour_indices] char_tops = zip(cctops, self.shapes.small_contour_indices) char_tops.sort(key=lambda x: x[0]) sorted_indices = [i[1] for i in char_tops] _line_insert_indxs = [] _line_insert_indxs.extend([bisect_right(char_tops, (i - 1,)) for i in self.line_indices]) self.small_cc_lines_chars = [] if not _line_insert_indxs: sys.exit() for i, l in enumerate(_line_insert_indxs[:-1]): self.small_cc_lines_chars.append(sorted_indices[l:_line_insert_indxs[i+1]]) self.small_cc_lines_chars.append(sorted_indices[_line_insert_indxs[-1]:]) self.small_cc_lines_chars = [self.small_cc_lines_chars[i] for i in range(len(self.lines_chars)) if self.lines_chars[i]] if self.shapes.detect_o: cctops = [self.shapes.get_boxes()[i][1] for i in self.shapes.naros] char_tops = zip(cctops, self.shapes.naros) char_tops.sort(key=lambda x: x[0]) sorted_indices = [i[1] for i in char_tops] _line_insert_indxs = [] _line_insert_indxs.extend([bisect_right(char_tops, (i - 1,)) for i in self.line_indices]) if not _line_insert_indxs: sys.exit() self.line_naros = [] for i, l in enumerate(_line_insert_indxs[:-1]): self.line_naros.append(sorted_indices[l:_line_insert_indxs[i+1]]) self.line_naros.append(sorted_indices[_line_insert_indxs[-1]:]) self.line_naros = [self.line_naros[i] for i in range(len(self.lines_chars)) if self.lines_chars[i]] if self.shapes.low_ink: cctops = [lib[1] for lib in self.shapes.low_ink_boxes] char_tops = zip(cctops, self.shapes.low_ink_boxes) char_tops.sort(key=lambda x: x[0]) sorted_indices = [i[1] for i in char_tops] _line_insert_indxs = [] _line_insert_indxs.extend([bisect_right(char_tops, (i - 1,)) for i in self.line_indices]) self.low_ink_boxes = [] if not _line_insert_indxs: sys.exit() for i, l in enumerate(_line_insert_indxs[:-1]): self.low_ink_boxes.append(sorted_indices[l:_line_insert_indxs[i+1]]) self.low_ink_boxes.append(sorted_indices[_line_insert_indxs[-1]:]) self.low_ink_boxes= [self.low_ink_boxes[i] for i in range(len(self.lines_chars)) if self.lines_chars[i]] # # for c in small_cc: # t = self.shapes.get_boxes()[c][1] # for i, line in enumerate(self.lines_chars): # if i+1 < len(self.lines_chars): # if self.lines_chars[i+1]: # next_topmost = self.shapes.get_boxes()[self.lines_chars[i+1][0]][1] # if topmost < t and t < next_topmost: # self.small_cc_lines_chars[i].append(c) # break # topmost = next_topmost # def _remove_small_noise(self): global_tsek_mean = self.shapes.tsek_mean global_tsek_std = self.shapes.tsek_std global_char_mean = self.shapes.char_mean global_char_std = self.shapes.char_std for l in self.lines_chars: widths = [self.shapes.get_boxes()[i][2] for i in l] char_mean, char_std, tsek_mean, tsek_std = self.shapes.char_gaussians(widths) for i in l: if self.shapes.get_boxes()[i][2] < (global_tsek_mean - 1 * global_tsek_std) and not char_mean < global_char_mean -.5* global_char_std: l.remove(i) # elif len(l) < 4 and global_tsek_mean - global_tsek_std <= self.shapes.get_boxes()[i][2] <= global_tsek_mean + global_tsek_std: # l.remove(i) # These two functions are for API compatability with LineCluster def get_box(self, ind): return self.shapes.get_boxes()[ind] def get_contour(self, ind): return self.shapes.contours[ind] class LineCluster(object): '''Line Cluster object - breaks lines by clustering according to tops of bounding boxes. Useful in cases where it drawing a straight line between page lines is difficult. Requires you know how many lines are on the page beforehand. Parameters: -------------------- shapes: page_element object, (see page_elements.py) k: int, required number of lines on the page Attributes: ----------- lines_chars: list of lists, length=number of lines on page. Each sub-list contains the indices for the bounding boxes/contours assigned to its corresponding line. line_indices: list of int, indices of breaklines with respect to page_array baselines: list of int, the index of the baseline for each line where baseline here is usually a line that goes through all the thick "head" (Tibetan: mgo) parts found on most Tibetan letters Methods: -------- get_box: return the bounding box for a given index get_contour: return the contour for a given index The get_box, get_contour methods are mostly here for API compatibility with LineCluster. Notes: ------ This code is messy and in progress. Some of the logic in the end contains hardcoded values particular to the Nyingma Gyudbum which is obviously useless for general cases. ''' def __init__(self, shapes, k): from sklearn.cluster import KMeans self.shapes = shapes self.k = k self.page_array = shapes.img_arr if shapes.conf['line_cluster_pos'] == 'top': tops = array(shapes.get_tops(), dtype=float64) elif shapes.conf['line_cluster_pos'] == 'center': tops = array( [t[1] + .5*shapes.char_mean for t in shapes.get_boxes() if t[3] > 2* shapes.tsek_mean], dtype=float64 ) else: raise ValueError, "The line_cluster_pos argument must be either 'top' or 'center'" tops.shape = (len(tops), 1) kmeans = KMeans(n_clusters=k) # print tops kmeans.fit(tops) ################## ######## mark cluster centroids on original image and show them # img_arr = shapes.img_arr.copy() # for centroid in kmeans.cluster_centers_: ## print centroid[0] # img_arr[centroid[0],:] = 0 # # import Image # Image.fromarray(img_arr*255).show() #######################3 lines = [[] for i in range(k)] ind = shapes.get_indices() ### Assign char pointers (ind) to the appropriate line ### # [lines[kmeans.labels_[i]].append(ind[i]) for i in range(len(ind))] [lines[kmeans.predict(shapes.get_boxes()[ind[i]][1])[0]].append(ind[i]) for i in range(len(ind))] lines = [l for l in lines if l] self.k = len(lines) boxes = shapes.get_boxes() ### Sort indices so they are in order from top to bottom using y from the first box in each line sort_inx = list(argsort([boxes[line[0]][1] for line in lines])) lines.sort(key=lambda line: boxes[line[0]][1]) ### Get breaklines for splitting up lines ### Uses the topmost box in each line cluster to determine breakline try: topmosts = [min([boxes[i][1] for i in line]) for line in lines] except ValueError: print 'failed to get topmosts...' raise vsums = self.page_array.sum(axis=1) breaklines = [] delta = 25 for c in topmosts: if c - delta < 0: lower = 0 else: lower =
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import argparse import os import sys py3 = sys.version_info.major == 3 def warn(msg): print('[powerline-bash] ', msg) if py3: def unicode(x): return x class Powerline: symbols = { 'compatible': { 'lock': 'RO', 'network': 'SSH', 'separator': u'\u25B6', 'separator_thin': u'\u276F' }, 'patched': { 'lock': u'\uE0A2', 'network': u'\uE0A2', 'separator': u'\uE0B0', 'separator_thin': u'\uE0B1' }, 'flat': { 'lock': '', 'network': '', 'separator': '', 'separator_thin': '' }, } color_templates = { 'bash': '\\[\\e%s\\]', 'zsh': '%%{%s%%}', 'bare': '%s', } def __init__(self, args, cwd): self.args = args self.cwd = cwd mode, shell = args.mode, args.shell self.color_template = self.color_templates[shell] self.reset = self.color_template % '[0m' self.lock = Powerline.symbols[mode]['lock'] self.network = Powerline.symbols[mode]['network'] self.separator = Powerline.symbols[mode]['separator'] self.separator_thin = Powerline.symbols[mode]['separator_thin'] self.segments = [] def color(self, prefix, code): if code is None: return '' else: return self.color_template % ('[%s;5;%sm' % (prefix, code)) def fgcolor(self, code): return self.color('38', code) def bgcolor(self, code): return self.color('48', code) def append(self, content, fg, bg, separator=None, separator_fg=None): self.segments.append((content, fg, bg, separator if separator is not None else self.separator, separator_fg if separator_fg is not None else bg)) def draw(self): text = (''.join(self.draw_segment(i) for i in range(len(self.segments))) + self.reset) + ' ' if py3: return text else: return text.encode('utf-8') def draw_segment(self, idx): segment = self.segments[idx] next_segment = self.segments[idx + 1] if idx < len(self.segments)-1 else None return ''.join(( self.fgcolor(segment[1]), self.bgcolor(segment[2]), segment[0], self.bgcolor(next_segment[2]) if next_segment else self.reset, self.fgcolor(segment[4]), segment[3])) class RepoStats: symbols = { 'detached': u'\u2693', 'ahead': u'\u2B06', 'behind': u'\u2B07', 'staged': u'\u2714', 'not_staged': u'\u270E', 'untracked': u'\u2753', 'conflicted': u'\u273C' } def __init__(self): self.ahead = 0 self.behind = 0 self.untracked = 0 self.not_staged = 0 self.staged = 0 self.conflicted = 0 @property def dirty(self): qualifiers = [ self.untracked, self.not_staged, self.staged, self.conflicted, ] return sum(qualifiers) > 0 def __getitem__(self, _key): return getattr(self, _key) def n_or_empty(self, _key): """Given a string name of one of the properties of this class, returns the value of the property as a string when the value is greater than 1. When it is not greater than one, returns an empty string. As an example, if you want to show an icon for untracked files, but you only want a number to appear next to the icon when there are more than one untracked files, you can do: segment = repo_stats.n_or_empty("untracked") + icon_string """ return unicode(self[_key]) if int(self[_key]) > 1 else u'' def add_to_powerline(self, powerline, color): def add(_key, fg, bg): if self[_key]: s = u" {}{} ".format(self.n_or_empty(_key), self.symbols[_key]) powerline.append(s, fg, bg) add('ahead', color.GIT_AHEAD_FG, color.GIT_AHEAD_BG) add('behind', color.GIT_BEHIND_FG, color.GIT_BEHIND_BG) add('staged', color.GIT_STAGED_FG, color.GIT_STAGED_BG) add('not_staged', color.GIT_NOTSTAGED_FG, color.GIT_NOTSTAGED_BG) add('untracked', color.GIT_UNTRACKED_FG, color.GIT_UNTRACKED_BG) add('conflicted', color.GIT_CONFLICTED_FG, color.GIT_CONFLICTED_BG) def get_valid_cwd(): """ We check if the current working directory is valid or not. Typically happens when you checkout a different branch on git that doesn't have this directory. We return the original cwd because the shell still considers that to be the working directory, so returning our guess will confuse people """ # Prefer the PWD environment variable. Python's os.getcwd function follows # symbolic links, which is undesirable. But if PWD is not set then fall # back to this func try: cwd = os.getenv('PWD') or os.getcwd() except: warn("Your current directory is invalid. If you open a ticket at " + "https://github.com/milkbikis/powerline-shell/issues/new " + "we would love to help fix the issue.") sys.stdout.write("> ") sys.exit(1) parts = cwd.split(os.sep) up = cwd while parts and not os.path.exists(up): parts.pop() up = os.sep.join(parts) if cwd != up: warn("Your current directory is invalid. Lowest valid directory: " + up) return cwd if __name__ == "__main__": arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--cwd-mode', action='store', help='How to display the current directory', default='fancy', choices=['fancy', 'plain', 'dironly']) arg_parser.add_argument('--cwd-only', action='store_true', help='Deprecated. Use --cwd-mode=dironly') arg_parser.add_argument('--cwd-max-depth', action='store', type=int, default=5, help='Maximum number of directories to show in path') arg_parser.add_argument('--cwd-max-dir-size', action='store', type=int, help='Maximum number of letters displayed for each directory in the path') arg_parser.add_argument('--colorize-hostname', action='store_true', help='Colorize the hostname based on a hash of itself.') arg_parser.add_argument('--mode', action='store', default='patched', help='The characters used to make separators between segments', choices=['patched', 'compatible', 'flat']) arg_parser.add_argument('--shell', action='store', default='bash', help='Set this to your shell type', choices=['bash', 'zsh', 'bare']) arg_parser.add_argument('prev_error', nargs='?', type=int, default=0, help='Error code returned by the last command') args = arg_parser.parse_args() powerline = Powerline(args, get_valid_cwd()) class DefaultColor: """ This class should have the default colors for every segment. Please test every new segment with this theme first. """ USERNAME_FG = 250 USERNAME_BG = 240 USERNAME_ROOT_BG = 124 HOSTNAME_FG = 250 HOSTNAME_BG = 238 HOME_SPECIAL_DISPLAY = True HOME_BG = 31 # blueish HOME_FG = 15 # white PATH_BG = 237 # dark grey PATH_FG = 250 # light grey CWD_FG = 254 # nearly-white grey SEPARATOR_FG = 244 READONLY_BG = 124 READONLY_FG = 254 SSH_BG = 166 # medium orange SSH_FG = 254 REPO_CLEAN_BG = 148 # a light green color REPO_CLEAN_FG = 0 # black REPO_DIRTY_BG = 161 # pink/red REPO_DIRTY_FG = 15 # white JOBS_FG = 39 JOBS_BG = 238 CMD_PASSED_BG = 236 CMD_PASSED_FG = 15 CMD_FAILED_BG = 161 CMD_FAILED_FG = 15 SVN_CHANGES_BG = 148 SVN_CHANGES_FG = 22 # dark green GIT_AHEAD_BG = 240 GIT_AHEAD_FG = 250 GIT_BEHIND_BG = 240 GIT_BEHIND_FG = 250 GIT_STAGED_BG = 22 GIT_STAGED_FG = 15 GIT_NOTSTAGED_BG = 130 GIT_NOTSTAGED_FG = 15 GIT_UNTRACKED_BG = 52 GIT_UNTRACKED_FG = 15 GIT_CONFLICTED_BG = 9 GIT_CONFLICTED_FG = 15 VIRTUAL_ENV_BG = 35 # a mid-tone green VIRTUAL_ENV_FG = 00 class Color(DefaultColor): """ This subclass is required when the user chooses to use 'default' theme. Because the segments require a 'Color' class for every theme. """ pass import os def add_virtual_env_segment(powerline): env = os.getenv('VIRTUAL_ENV') or os.getenv('CONDA_ENV_PATH') if env is None: return env_name = os.path.basename(env) bg = Color.VIRTUAL_ENV_BG fg = Color.VIRTUAL_ENV_FG powerline.append(' %s ' % env_name, fg, bg) add_virtual_env_segment(powerline) def add_username_segment(powerline): import os if powerline.args.shell == 'bash': user_prompt = ' \\u ' elif powerline.args.shell == 'zsh': user_prompt = ' %n ' else: user_prompt = ' %s ' % os.getenv('USER') if os.getenv('USER') == 'root': bgcolor = Color.USERNAME_ROOT_BG else: bgcolor = Color.USERNAME_BG powerline.append(user_prompt, Color.USERNAME_FG, bgcolor) add_username_segment(powerline) def add_hostname_segment(powerline): if powerline.args.colorize_hostname: from lib.color_compliment import stringToHashToColorAndOpposite from lib.colortrans import rgb2short from socket import gethostname hostname = gethostname() FG, BG = stringToHashToColorAndOpposite(hostname) FG, BG = (rgb2short(*color) for color in [FG, BG]) host_prompt = ' %s ' % hostname.split('.')[0] powerline.append(host_prompt, FG, BG) else: if powerline.args.shell == 'bash': host_prompt = ' \\h ' elif powerline.args.shell == 'zsh': host_prompt = ' %m ' else: import socket host_prompt = ' %s ' % socket.gethostname().split('.')[0] powerline.append(host_prompt, Color.HOSTNAME_FG, Color.HOSTNAME_BG) add_hostname_segment(powerline) import os def add_ssh_segment(powerline): if os.getenv('SSH_CLIENT'): powerline.append(' %s ' % powerline.network, Color.SSH_FG, Color.SSH_BG) add_ssh_segment(powerline) import os ELLIPSIS = u'\u2026' def replace_home_dir(cwd): home = os.getenv('HOME') if cwd.startswith(home): return '~' + cwd[len(home):] return cwd def split_path_into_names(cwd): names = cwd.split(os.sep) if names[0] == '': names = names[1:] if not names[0]: return ['/'] return names def requires_special_home_display(name): """Returns true if the given directory name matches the home indicator and the chosen theme should use a special home indicator display.""" return (name == '~' and Color.HOME_SPECIAL_DISPLAY) def maybe_shorten_name(powerline, name): """If the user has asked for each directory name to be shortened, will return the name up to their specified length. Otherwise returns the full name.""" if powerline.args.cwd_max_dir_size: return name[:powerline.args.cwd_max_dir_size] return name def get_fg_bg(name): """Returns the foreground and background color to use for the given name. """ if requires_special_home_display(name): return (Color.HOME_FG, Color.HOME_BG,) return (Color.PATH_FG, Color.PATH_BG,) def add_cwd_segment(powerline): cwd = powerline.cwd or os.getenv('PWD') if not py3: cwd = cwd.decode("utf-8") cwd = replace_home_dir(cwd) if powerline.args.cwd_mode == 'plain': powerline.append(' %s ' % (cwd,), Color.CWD_FG, Color.PATH_BG) return names = split_path_into_names(cwd) max_depth = powerline.args.cwd_max_depth if max_depth <= 0: warn("Ignoring --cwd-max-depth argument since it's not greater than 0") elif len(names) > max_depth: # https://github.com/milkbikis/powerline-shell/issues/148 # n_before is the number is the number of directories to put before the # ellipsis. So if you are at ~/a/b/c/d/e and max depth is 4, it will # show `~ a ... d e`. # # max_depth must be greater than n_before or else you end up repeating # parts of the path with the way the splicing is written below. n_before = 2 if max_depth > 2 else max_depth - 1 names = names[:n_before] + [ELLIPSIS] + names[n_before - max_depth:] if (powerline.args.cwd_mode == 'dironly' or powerline.args.cwd_only): #
<reponame>etherlabsio/ai-engine<filename>services/keyphrase/extract_keyphrases.py import networkx as nx import logging from timeit import default_timer as timer import traceback from typing import List, Dict, Tuple, Text import numpy as np from fuzzywuzzy import fuzz, process from graphrank.core import GraphRank from graphrank.utils import TextPreprocess, GraphUtils from .utils import KeyphraseUtils from .ranker import KeyphraseRanker from .s3io import S3IO from .word_graph import WordGraphBuilder from .queries import Queries from .graph_filtration import GraphFilter from .redis_store import RedisStore from .objects import ( Phrase, PhraseType, SegmentType, Segment, KeyphraseType, Keyphrase, EntityType, Entity, SummaryRequest, ContextRequest, Request, Score, ) MIND_STORE = "keyphrase/minds" CONTEXT_STORE = "keyphrase/contexts" logger = logging.getLogger(__name__) class KeyphraseExtractor(object): def __init__( self, s3_client=None, s3_mind_client=None, encoder_lambda_client=None, lambda_function=None, ner_lambda_function=None, nats_manager=None, redis_host: str = "localhost", active_env: str = "staging2", ): self.context_dir = "/context-instance-graphs/" self.feature_dir = "/sessions/" self.mind_dir = active_env + "/minds/" self.s3_client = s3_client self.s3_mind_client = s3_mind_client self.mind_store = RedisStore(id=MIND_STORE, host=redis_host) self.context_store = RedisStore(id=CONTEXT_STORE, host=redis_host) self.graph_filter_object = GraphFilter(s3_client=self.s3_mind_client) self.utils = KeyphraseUtils( graph_filter_object=self.graph_filter_object, mind_store=self.mind_store, mind_dir=self.mind_dir, ) self.io_util = S3IO( s3_client=s3_client, graph_utils_obj=GraphUtils(), utils=self.utils, ) self.query_client = Queries(nats_manager=nats_manager) self.ranker = KeyphraseRanker( encoder_lambda_client=encoder_lambda_client, lambda_function=lambda_function, s3_io_util=self.io_util, context_dir=self.context_dir, utils=self.utils, query_client=self.query_client, ) self.wg = WordGraphBuilder( graphrank_obj=GraphRank(), textpreprocess_obj=TextPreprocess(), graphutils_obj=GraphUtils(), keyphrase_utils_obj=self.utils, lambda_client=encoder_lambda_client, ner_lambda_function=ner_lambda_function, ) self.syntactic_filter = [ "JJ", "JJR", "JJS", "NN", "NNP", "NNS", "VB", "VBP", "NNPS", "FW", ] def get_graph_id(self, req_data: ContextRequest) -> Text: context_id = req_data.contextId instance_id = req_data.instanceId graph_id = context_id + ":" + instance_id return graph_id def wake_up_lambda(self, req_data: ContextRequest): # Start the encoder lambda to avoid cold start problem logger.info("Invoking lambda to reduce cold-start ...") test_segment = ["Wake up Sesame!"] self.ranker.get_embeddings(input_list=test_segment, req_data=req_data) self.wg.call_custom_ner(input_segment="<IGN>") def initialize_meeting_graph( self, req_data: ContextRequest, store_redis: bool = True ): graph_id = self.get_graph_id(req_data=req_data) context_id = req_data.contextId instance_id = req_data.instanceId mind_id = req_data.mindId mind_id = mind_id.lower() session_id = instance_id + ":" + mind_id meeting_word_graph = nx.Graph(graphId=graph_id) logger.info( "Meeting word graph intialized", extra={"currentGraphId": meeting_word_graph.graph.get("graphId")}, ) logger.info("Uploading serialized graph object") self.io_util.upload_s3( graph_obj=meeting_word_graph, context_id=context_id, instance_id=instance_id, s3_dir=self.context_dir, ) if store_redis: mind_filter_graph = nx.Graph() try: mind_graph_path = self.mind_dir + mind_id + "/kp_entity_graph.pkl" mind_filter_graph = self.graph_filter_object.download_mind( graph_file_path=mind_graph_path ) self.mind_store.set_object(key=session_id, object=mind_filter_graph) logger.info( "Loaded Entity-KP Filter graph", extra={ "contextId": context_id, "instanceId": instance_id, "mindId": mind_id, "sessionId": session_id, }, ) except Exception as e: logger.error(e) finally: mind_filter_graph.clear() # Start the encoder lambda to avoid cold start problem self.wake_up_lambda(req_data=req_data) def _retrieve_word_graph(self, req_data: Request) -> nx.Graph: """ Download meeting word graph from s3 Args: req_data: Returns: """ context_id = req_data.contextId instance_id = req_data.instanceId # Get graph object from S3 meeting_word_graph = self.io_util.download_s3( context_id=context_id, instance_id=instance_id, s3_dir=self.context_dir ) return meeting_word_graph def _update_word_graph( self, req_data: Request, meeting_word_graph: nx.Graph ) -> nx.Graph: """ Populate instance information, add meeting word graph to context graph and upload the context graph Args: req_data: meeting_word_graph: Returns: """ context_id = req_data.contextId instance_id = req_data.instanceId # Write back the graph object to S3 self.io_util.upload_s3( graph_obj=meeting_word_graph, context_id=context_id, instance_id=instance_id, s3_dir=self.context_dir, ) return meeting_word_graph def populate_and_embed_graph( self, req_data: Request, segment_object: SegmentType, session_id: str, highlight: bool = False, group_id: str = None, filter_by_graph: bool = False, ) -> Tuple[Request, nx.Graph]: meeting_word_graph = self.populate_word_graph( req_data=req_data, segment_object=segment_object ) # Compute embeddings for segments and keyphrases modified_request_obj = self.compute_embeddings( req_data=req_data, segment_object=segment_object, meeting_word_graph=meeting_word_graph, highlight=highlight, group_id=group_id, filter_by_graph=filter_by_graph, session_id=session_id, ) return modified_request_obj, meeting_word_graph def populate_word_graph( self, req_data: Request, segment_object: SegmentType ) -> nx.Graph: start = timer() # Get graph objects meeting_word_graph = self._retrieve_word_graph(req_data=req_data) # Populate word graph for the current instance try: text_list = self.utils.read_segments(segment_object=segment_object) meeting_word_graph = self.wg.build_custom_graph( text_list=text_list, graph=meeting_word_graph ) end = timer() logger.info( "Populated graph and written to s3", extra={ "graphId": meeting_word_graph.graph.get("graphId"), "nodes": meeting_word_graph.number_of_nodes(), "edges": meeting_word_graph.number_of_edges(), "instanceId": req_data.instanceId, "responseTime": end - start, }, ) except Exception as e: end = timer() logger.error( "Error populating graph", extra={ "err": e, "responseTime": end - start, "instanceId": req_data.instanceId, }, ) # Push updated meeting graph meeting_word_graph = self._update_word_graph( req_data=req_data, meeting_word_graph=meeting_word_graph ) return meeting_word_graph def compute_embeddings( self, req_data: Request, segment_object: SegmentType, session_id: str, meeting_word_graph: nx.Graph = None, default_form: Text = "descriptive", highlight: bool = False, group_id: str = None, filter_by_graph: bool = False, ) -> Request: """ Compute embedding vectors for segments and segment-keyphrases and store them as node attributes in the knowledge graph. Args: default_form: segment_object: meeting_word_graph: req_data: Returns: """ context_id = req_data.contextId instance_id = req_data.instanceId if meeting_word_graph is None: # Get graph objects meeting_word_graph = self._retrieve_word_graph(req_data=req_data) phrase_object_list = self.extract_keywords( segment_object=segment_object, meeting_word_graph=meeting_word_graph, filter_by_graph=filter_by_graph, session_id=session_id, ) # Get segment text for i, phrase_object in enumerate(phrase_object_list): seg_text = segment_object[i].originalText segment_id = phrase_object.segmentId segment_keyphrase_obj = [ kp_obj for kp_obj in phrase_object.keyphrases if kp_obj.type == default_form ] segment_entity_obj = phrase_object.entities keyphrase_list = [kp_obj.originalForm for kp_obj in segment_keyphrase_obj] entities_list = [ent_obj.originalForm for ent_obj in segment_entity_obj] input_phrases_list = entities_list input_phrases_list.extend(keyphrase_list) # Compute segment embedding vector segment_embedding = self.ranker.get_embeddings( input_list=[seg_text], req_data=req_data ) # Compute keyphrase embedding vectors keyphrase_embeddings = self.ranker.get_embeddings( input_list=input_phrases_list, req_data=req_data ) # Combine segment and keyphrase embeddings and serialize them f_name = segment_id if highlight is True: f_name = segment_id + "_" + group_id npz_s3_path = self._form_update_embeddings( context_id=context_id, instance_id=instance_id, f_name=f_name, segment_embedding=segment_embedding, keyphrase_embeddings=keyphrase_embeddings, input_phrases_list=input_phrases_list, ) # # Update context graph with embedding vectors attributed_segment_obj = self._form_segment_attr_object( segment=segment_object[i], highlight=highlight, npz_file_path=npz_s3_path, group_id=group_id, ) attributed_segment_obj = self._form_keyphrase_attr_object( segment=attributed_segment_obj, keyphrase_object=segment_keyphrase_obj, entity_object=segment_entity_obj, ) req_data.segments[i] = attributed_segment_obj logger.info( "features embeddings computed and stored", extra={"embeddingUri": npz_s3_path}, ) modified_request_object = req_data return modified_request_object def _form_update_embeddings( self, context_id: Text, instance_id: Text, f_name: Text, segment_embedding: np.ndarray, keyphrase_embeddings: List[np.ndarray], input_phrases_list: List[Text], ) -> Text: # Combine segment and keyphrase embeddings and serialize them segment_embedding_dict = {f_name: np.array(segment_embedding)} ( phrase_hash_dict, phrase_embedding_dict, ) = self.utils.map_embeddings_to_phrase( phrase_list=input_phrases_list, embedding_list=keyphrase_embeddings, ) segment_keyphrase_embeddings = { **segment_embedding_dict, **phrase_embedding_dict, } # Serialize the entire segment-keyphrase embedding dictionary to NPZ npz_file_name = self.utils.serialize_to_npz( embedding_dict=segment_keyphrase_embeddings, file_name=f_name ) npz_s3_path = self.io_util.upload_npz( context_id=context_id, instance_id=instance_id, feature_dir=self.feature_dir, npz_file_name=npz_file_name, ) return npz_s3_path def _form_segment_attr_object( self, segment: Segment, highlight: bool, npz_file_path: Text, group_id: Text, ) -> Segment: # Update context graph with embedding vectors segment.text = segment.originalText segment.embedding_vector_uri = npz_file_path segment.highlight = False segment.embedding_model = "USE_v1" if highlight: segment.embedding_vector_group_uri = npz_file_path segment.groupId = group_id segment.embedding_model = "USE_v1" segment.highlight = True return segment def _form_keyphrase_attr_object( self, segment: Segment, keyphrase_object: List[Keyphrase], entity_object: List[Entity], ) -> Segment: segment.keyphrases = keyphrase_object segment.entities = entity_object return segment def encode_word_graph(self, word_graph: nx.Graph) -> nx.Graph: word_graph = self.ranker.compute_edge_weights(word_graph) return word_graph async def get_keyphrases( self, req_data: Request, segment_object: SegmentType, session_id: str, summary_object: SummaryRequest = None, meeting_word_graph: nx.Graph = None, n_kw: int = 10, default_form: Text = "descriptive", rank_by: Text = "norm_boosted_sim", sort_by: Text = "loc", validate: bool = False, highlight: bool = False, group_id: str = None, filter_by_graph: bool = False, ) -> Tuple[Dict, SummaryRequest]: start = timer() context_id = req_data.contextId instance_id = req_data.instanceId # Use startTime of the first segment as relative starting point relative_time = self.utils.format_time( segment_object[0].startTime, datetime_object=True ) try: if meeting_word_graph is None: # Get graph objects meeting_word_graph = self._retrieve_word_graph(req_data=req_data) logger.info("Computing features before extracting keyphrases") # Repopulate the graphs modified_request_obj, meeting_word_graph = self.populate_and_embed_graph( req_data=req_data, segment_object=segment_object, highlight=highlight, group_id=group_id, session_id=session_id, filter_by_graph=filter_by_graph, ) phrase_object_list = self.extract_keywords( segment_object=segment_object, meeting_word_graph=meeting_word_graph, relative_time=relative_time, filter_by_graph=filter_by_graph, session_id=session_id, highlight=highlight, ) try: ranked_phrase_object_list = await self.ranker.compute_relevance( phrase_object_list=phrase_object_list, highlight=highlight, group_id=group_id, ) ( keyphrases, phrase_object, entity_obj, keyphrase_obj, ) = self.prepare_keyphrase_output( phrase_object=ranked_phrase_object_list, top_n=n_kw, default_form=default_form, rank_by=rank_by, sort_by=sort_by, remove_phrases=True, ) except Exception as e: logger.warning( "Error computing keyphrase relevance", extra={"warnMsg": e, "trace": traceback.print_exc()}, ) ( keyphrases, phrase_object, entity_obj, keyphrase_obj, ) = self.prepare_keyphrase_output( phrase_object=phrase_object_list, top_n=n_kw, default_form=default_form, rank_by="pagerank", sort_by=sort_by, remove_phrases=False, ) if highlight: summary_object.segments = modified_request_obj.segments summary_object.keyphrases = keyphrase_obj summary_object.entities = entity_obj if validate: self._make_validation( phrase_object=phrase_object, context_id=context_id, instance_id=instance_id, ) logger.debug( "keyphrases extracted successfully", extra={"result": keyphrases, "summaryObject": summary_object}, ) result = {"keyphrases": keyphrases} return result, summary_object except Exception as e: end = timer() logger.error( "Error extracting keyphrases from segment", extra={ "responseTime": end - start, "instanceId": instance_id, "segmentsReceived": [seg_id.id for seg_id in segment_object], "err": e, "errMsg": traceback.print_exc(), }, ) print(traceback.print_exc()) raise def _make_validation(self, phrase_object: PhraseType, context_id, instance_id): validation_id = self.utils.hash_sha_object() # Convert Class object to python List[Dict] validation_data = Phrase.get_dict(phrase_object) validation_file_name = self.utils.write_to_json( validation_data, file_name="keyphrase_validation_" + validation_id ) self.io_util.upload_validation( context_id=context_id, feature_dir=self.feature_dir, instance_id=instance_id, validation_file_name=validation_file_name, ) async def get_keyphrases_with_offset( self, req_data: Request, segment_object: SegmentType, session_id: str, meeting_word_graph: nx.Graph = None, n_kw: int = 10, default_form: Text = "descriptive", rank_by: Text = "segment_relevance", sort_by: Text = "loc", validate: bool = False, highlight: bool = False, filter_by_graph: bool = False, **kwargs, ): start = timer() keyphrase_offsets = [] context_id = req_data.contextId instance_id = req_data.instanceId group_id = kwargs.get("group_id")
self.buffer if self.compressed else self.file # move the buffer to the starting position buffer.seek(0 if self.compressed else self.offset + 1) return buffer def _read_offsets(self): # get the buffer for this cluster buffer = self._source_buffer() # read the offset for the first blob offset0 = unpack("<I", buffer.read(4))[0] # store this one in the list of offsets self._offsets.append(offset0) # calculate the number of blobs by dividing the first blob by 4 number_of_blobs = int(offset0 / 4) for idx in range(number_of_blobs - 1): # store the offsets to all other blobs self._offsets.append(unpack("<I", buffer.read(4))[0]) def read_blob(self, blob_index): # check if the blob falls within the range if blob_index >= len(self._offsets) - 1: raise IOError("Blob index exceeds number of blobs available: %s" % blob_index) buffer = self._source_buffer() # get the buffer for this cluster # calculate the size of the blob blob_size = self._offsets[blob_index+1] - self._offsets[blob_index] # move to the position of the blob relative to current position buffer.seek(self._offsets[blob_index], 1) return buffer.read(blob_size) class DirectoryBlock(Block): def __init__(self, structure, encoding): super().__init__(structure, encoding) def unpack_from_file(self, file, seek=None): # read the first fields as defined in the ARTICLE_ENTRY structure field_values = super()._unpack_from_file(file, seek) # then read in the url, which is a zero terminated field field_values["url"] = read_zero_terminated(file, self._encoding) # followed by the title, which is again a zero terminated field field_values["title"] = read_zero_terminated(file, self._encoding) field_values["namespace"] = field_values["namespace"].decode( encoding=self._encoding, errors="ignore") return field_values class ArticleEntryBlock(DirectoryBlock): def __init__(self, encoding): super().__init__(ARTICLE_ENTRY, encoding) class RedirectEntryBlock(DirectoryBlock): def __init__(self, encoding): super().__init__(REDIRECT_ENTRY, encoding) ##### # Support functions to simplify (1) the uniform creation of a URL # given a namespace, and (2) searching in the index. ##### def full_url(namespace, url): return str(namespace) + '/' + str(url) def binary_search(func, item, front, end): found = False middle = 0 # continue as long as the boundaries don't cross and we haven't found it while front < end and not found: middle = floor((front + end) / 2) # determine the middle index # use the provided function to find the item at the middle index found_item = func(middle) if found_item == item: found = True # flag it if the item is found else: if found_item < item: # if the middle is too early ... # move the front index to the middle # (+ 1 to make sure boundaries can be crossed) front = middle + 1 else: # if the middle falls too late ... # move the end index to the middle # (- 1 to make sure boundaries can be crossed) end = middle - 1 return middle if found else None class ZIMFile: """ The main class to access a ZIM file. Two important public methods are: get_article_by_url(...) is used to retrieve an article given its namespace and url. get_main_page() is used to retrieve the main page article for the given ZIM file. """ def __init__(self, filename, encoding): self._enc = encoding # open the file as a binary file self.file = open(filename, "rb") # retrieve the header fields self.header_fields = HeaderBlock(self._enc).unpack_from_file(self.file) self.mimetype_list = MimeTypeListBlock(self._enc).unpack_from_file( self.file, self.header_fields["mimeListPos"]) # create the object once for easy access self.redirectEntryBlock = RedirectEntryBlock(self._enc) self.articleEntryBlock = ArticleEntryBlock(self._enc) self.clusterFormat = ClusterBlock(self._enc) def _read_offset(self, index, field_name, field_format, length): # move to the desired position in the file if index != 0xffffffff: self.file.seek(self.header_fields[field_name] + int(length*index)) # and read and return the particular format read = self.file.read(length) # return unpack("<" + field_format, self.file.read(length))[0] return unpack("<" + field_format, read)[0] return None def _read_url_offset(self, index): return self._read_offset(index, "urlPtrPos", "Q", 8) def _read_title_offset(self, index): return self._read_offset(index, "titlePtrPos", "L", 4) def _read_cluster_offset(self, index): return self._read_offset(index, "clusterPtrPos", "Q", 8) def _read_directory_entry(self, offset): """ Read a directory entry using an offset. :return: a DirectoryBlock - either as Article Entry or Redirect Entry """ self.file.seek(offset) # move to the desired offset # retrieve the mimetype to determine the type of block fields = unpack("<H", self.file.read(2)) # get block class if fields[0] == 0xffff: directory_block = self.redirectEntryBlock else: directory_block = self.articleEntryBlock # unpack and return the desired Directory Block return directory_block.unpack_from_file(self.file, offset) def read_directory_entry_by_index(self, index): """ Read a directory entry using an index. :return: a DirectoryBlock - either as Article Entry or Redirect Entry """ # find the offset for the given index offset = self._read_url_offset(index) if offset is not None: # read the entry at that offset directory_values = self._read_directory_entry(offset) # set the index in the list of values directory_values["index"] = index return directory_values # and return all these directory values def _read_blob(self, cluster_index, blob_index): # get the cluster offset offset = self._read_cluster_offset(cluster_index) # get the actual cluster data cluster_data = ClusterData(self.file, offset, self._enc) # return the data read from the cluster at the given blob index return cluster_data.read_blob(blob_index) def _get_article_by_index(self, index, follow_redirect=True): # get the info from the DirectoryBlock at the given index entry = self.read_directory_entry_by_index(index) if entry is not None: # check if we have a Redirect Entry if 'redirectIndex' in entry.keys(): # if we follow up on redirects, return the article it is # pointing to if follow_redirect: redirected_article = self._get_article_by_index(entry['redirectIndex'], follow_redirect) redirected_article.is_redirect = True return redirected_article # otherwise, simply return no data # and provide the redirect index as the metadata. else: return Article(None, entry['namespace'], entry['redirectIndex'], entry['title'], entry['url'], True) else: # otherwise, we have an Article Entry # get the data and return the Article data = self._read_blob(entry['clusterNumber'], entry['blobNumber']) return Article(data, entry['namespace'], self.mimetype_list[entry['mimetype']], entry['title'], entry['url'], False) else: return None def _get_entry_by_url(self, namespace, url, linear=False): if linear: # if we are performing a linear search ... # ... simply iterate over all articles for idx in range(self.header_fields['articleCount']): # get the info from the DirectoryBlock at that index entry = self.read_directory_entry_by_index(idx) # if we found the article ... if entry['url'] == url and entry['namespace'] == namespace: # return the DirectoryBlock entry and index of the entry return entry, idx # return None, None if we could not find the entry return None, None else: front = middle = 0 end = len(self) title = full_url(namespace, url) found = False # continue as long as the boundaries don't cross and # we haven't found it while front <= end and not found: middle = floor((front + end) / 2) # determine the middle index entry = self.read_directory_entry_by_index(middle) found_title = full_url(entry['namespace'], entry['url']) if found_title == title: found = True # flag it if the item is found else: if found_title < title: # if the middle is too early ... # move the front index to middle # (+ 1 to ensure boundaries can be crossed) front = middle + 1 else: # if the middle falls too late ... # move the end index to middle # (- 1 to ensure boundaries can be crossed) end = middle - 1 if found: # return the tuple with directory entry and index # (note the comma before the second argument) return self.read_directory_entry_by_index(middle), middle return None, None def get_article_by_url(self, namespace, url, follow_redirect=True): entry, idx = self._get_entry_by_url(namespace, url) # get the entry if idx: # we found an index and return the article at that index return self._get_article_by_index( idx, follow_redirect=follow_redirect) def get_main_page(self): """ Get the main page of the ZIM file. """ main_page = self._get_article_by_index(self.header_fields['mainPage']) if main_page is not None: return main_page def metadata(self): """ Retrieve the metadata attached to the ZIM file. :return: a dict with the entry url as key and the metadata as value """ metadata = {} # iterate backwards over the entries for i in range(self.header_fields['articleCount'] - 1, -1, -1): entry = self.read_directory_entry_by_index(i) # get the entry if entry['namespace'] == 'M': # check that it is still metadata # turn the key to lowercase as per Kiwix standards m_name = entry['url'].lower() # get the data, which is encoded as an article metadata[m_name] = self._get_article_by_index(i)[0] else: # stop as soon as we are no longer looking at metadata break return metadata def __len__(self): # retrieve the number of articles in the ZIM file return self.header_fields['articleCount'] def __iter__(self): """
<gh_stars>1-10 #!/usr/bin/python2 import certifi import ipwhois import itertools import json import logging import netaddr import os import pymysql import re import requests import socket import subprocess import sys import threading import time import urllib2 import urllib3 import uuid import Queue from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool logging.basicConfig(format='rtb_latency %(funcName)s %(levelname)s %(message)s') logger = logging.getLogger('rtb_latency') urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def dj(_dict): """Converts dicts to JSON and safely handles non-serializable items""" return json.dumps( _dict, default=lambda o: 'ERROR: Item not JSON serializable', sort_keys=True, indent=3) def genconfig(): """ Reads config from file and further populates config with dynamic data. :return: config as dict """ # Open config file logger.debug('Loading config file...') try: with open('config.json', 'r') as config_file: config = json.loads(config_file.read()) except Exception as e: logger.error('Unable to read config file:\n%s', e) sys.exit(1) logger.debug('Requesting GeoIP from geoiplookup.io...') try: request = requests.get('https://json.geoiplookup.io/') config['geoip'] = request.json() config['public_ip'] = config['geoip']['ip'] except Exception as e: logger.error('Error obtaining GeoIP from geoiplookup.io:\n%s', e) return config config = genconfig() logger.setLevel(logging.getLevelName(config['log_level'])) def extract_hostname(string): """ Extract FQDN or IP from a full URL :param string: A URL as a string :return: FQDN or IP as a string """ if '//' in string: return re.findall(r'(?<=//)[\w.\-]+', string)[0] else: return string def extract_path(string): """ Extract FQDN or IP from a full URL :param string: A URL as a string :return: FQDN or IP as a string """ return re.sub(r'[^/]*//[^:/]*', '', string) def graphite_safe(string): """ Sanitizes a string so that it can be used as part of a Graphite line. It does this by replacing non-alphanumeric characters with underscores. :param string: Your string to sanitize :return: Your sanitized string """ # Convert whitespaces to underscores string = re.sub(r'\s', '_', string) # Convert non-alphanumeric characters to underscores string = re.sub(r'[^\w]', '_', string) # Collapse repeating underscores into one while '__' in string: string = string.replace('__', '_') return string def build_host_dict(): """ Generates host list from sources defined in config file. Example output: { "provider_name": { "path": "URI suffix", "region_major": { "region_minor": ["IP_address", ...], "star": ["IP_address", ...] }, }, } :return: Providers as dict """ checks = {} for id, source in enumerate(config['load_hosts']): if config['load_hosts'][id]['method'] == 'file': try: filepath = config['load_hosts'][id]['path'] logger.debug('Loading hosts from JSON file: ' + filepath) checks.update(json.loads(open(filepath, 'r').read())) except Exception: logger.exception('Could not open JSON host file: ' + filepath) elif config['load_hosts'][id]['method'] == 'mysql': try: logger.debug('Loading hosts from MySQL DB...') mysql_conn = pymysql.cursors.DictCursor(pymysql.connect( host=config['load_hosts'][id]['mysql_host'], user=config['load_hosts'][id]['mysql_user'], passwd=config['load_hosts'][id]['mysql_pass'], database=config['load_hosts'][id]['mysql_db'] )) result_count = mysql_conn.execute( config['load_hosts'][id]['mysql_query'] ) result_count result_dict = mysql_conn.fetchall() for id, row in enumerate(result_dict): row provider = result_dict[id]['provider'] if provider not in checks: checks[provider] = {} for region_major in config['regions']['major']: checks[provider][region_major] = {'star': []} for region_minor in config['regions']['minor']: checks[provider][region_major][region_minor] = [] for region in result_dict[id]: if 'http' in result_dict[id][region]: try: region_major, region_minor = region.split('_') provider_host = extract_hostname(result_dict[id][region]) checks[provider]['path'] = extract_path(result_dict[id][region]) _, _, provider_endpoints = socket.gethostbyname_ex(provider_host) provider_endpoints.append(provider_host) for endpoint in provider_endpoints: if endpoint not in checks[provider][region_major][region_minor]: checks[provider][region_major][region_minor].append(endpoint) if endpoint not in checks[provider][region_major]['star']: checks[provider][region_major]['star'].append(endpoint) except Exception: logger.exception('Trouble processing provider ' + provider + ' URL: ' + result_dict[id][region]) except Exception: logger.exception('Could not load hosts from MySQL.') else: logger.error('Unknown source type for hosts: ' + source) logger.debug('Checks dict:\n%s', dj(checks)) return checks def genbid(): """ Generates a unique test bid compliant with OpenRTB 2.3 :return: JSON body as string """ return json.dumps({ "ext": { "pchain": config['rtb']['bid_ext_pchain'] }, "id": str(uuid.uuid4()), "test": 1, "imp": [{ "id": "1", "banner": { "w": 160, "h": 600, "pos": 3 }, "secure": 0 }], "site": { "id": "1", "domain": config['rtb']['bid_site_domain'], "page": config['rtb']['bid_site_page'], "publisher": { "id": config['rtb']['bid_site_publisher_id'] } }, "device": { "dnt": 0, "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36", "ip": config['public_ip'], "geo": { "lat": config['geoip']['latitude'], "lon": config['geoip']['longitude'], "country": config['geoip']['country_code'], "region": config['geoip']['region'], "city": config['geoip']['city'], "zip": str(config['geoip']['postal_code']), "type": 2 }, "language": "en", "os": "OS X", "devicetype": 2, "osv": "10.12.6" }, "user": { "id": config['rtb']['bid_user_id'] }, "at": 2 }) def net_debug(host): """ Gather path information about a remote IP for debugging :param ip: IP address to check path to. :return: JSON dictionary """ if netaddr.valid_ipv4(host): ip = host try: hostname = socket.gethostbyaddr(host)[0] except: hostname = host else: ip = socket.gethostbyname(host) hostname = host try: as_remote = ipwhois.asn.IPASN(ipwhois.net.Net(ip)).lookup() as_local = ipwhois.asn.IPASN(ipwhois.net.Net(config['public_ip'])).lookup() except Exception as e: as_local = { 'asn': None, 'asn_cidr': None, } as_remote = { 'asn': None, 'asn_cidr': None, 'asn_description': None, } logger.error('Unable to determine ASN for IP: %s\n%s', ip, e) try: command = ['traceroute', '-A', '-I', '-e', '-N 1', '-q 1', str(ip)] cmd = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output = cmd.communicate() retcode = cmd.poll() if retcode == 0: traceroute = output[0].split('\n') del traceroute[0] del traceroute[-1] else: raise subprocess.CalledProcessError(retcode, command, output=output) except Exception as e: logger.error('Traceroute failed for %s:\n%s', ip, e) logger.debug('command: %s\nstdout:\n%s\nstderr:\n%s', command, output[0], output[1]) traceroute = [] logger.warn('for host: %s\n%s', host, dj({ 'local_asn': as_local['asn'], 'local_asn_cidr': as_local['asn_cidr'], 'local_ip': config['public_ip'], 'remote_asn': as_remote['asn'], 'remote_asn_cidr': as_remote['asn_cidr'], 'remote_asn_descr': as_remote['asn_description'], 'remote_hostname': hostname, 'remote_ip': ip, 'traceroute': traceroute })) def http_get_latency(host): """ Performs an HTTP GET request and returns latency. :param host: Hostname as string. :return: Timestamp as float of seconds or nothing """ logger.debug('Sending HTTP GET to: ' + extract_hostname(host)) for proto in ['https://', 'http://']: try: s = requests.Session() s.mount(proto, requests.adapters.HTTPAdapter(max_retries=1)) start = time.time() req = s.get( proto + host, timeout=config['timeout']) end = time.time() if req.status_code < 400: return end - start else: logger.error('Request failed to: %s code=%s text=%s', host, req.status_code, req.text) except Exception as e: logger.error('Request failed to: %s\n%s', host, e) def rtb_latency(host, path): """ Sends a test RTB bid to host and returns latency. :param host: Hostname as string :return: Timestamp as float of seconds or nothing """ logger.debug('Sending test bid to: %s', host) for proto in ['https://', 'http://']: try: s = requests.Session() s.mount(proto, requests.adapters.HTTPAdapter(max_retries=1)) start = time.time() req = s.post( proto + host + path, data=genbid(), timeout=config['timeout'], headers=config['rtb']['headers'], verify=False) end = time.time() logger.debug('Request time for host %s: %s', host, end - start) if req.status_code <= 204 and req.status_code >= 200: return end - start else: logger.error('Request failed to: %s code=%s text=%s', host, req.status_code, req.text) except Exception as e: logger.error('Request failed to: %s\n%s', host, e) def ping(host='google.com', number=1, wait_sec=1): """ Ping host and format output :param host: hostname or IP as string :param number: ping count :param wait_sec: ping timeout :return: dict """ logger.debug('Pinging host: %s', host) result = { 'host': host, 'count': number } try: command = ['ping', '-c', str(number), '-W', str(wait_sec), str(host)] cmd = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output = cmd.communicate() except Exception as e: logger.warn('Error calling ping:\n%s', e) logger.debug('command: %s\nstdout:\n%s\nstderr:\n%s', command, output[0], output[1]) try: for line in output[0].split('\n'): if 'round-trip' in line: timing = line.split()[3].split('/') result['avg'] = float(timing[1]) / 1000 result['dev'] = float(timing[3]) / 1000 result['max'] = float(timing[2]) / 1000 result['min'] = float(timing[0]) / 1000 if 'packets' in line: result['loss'] = line.split()[5] logger.debug('Ping result for host %s:\n%s', host, dj(result)) except Exception as e: logger.error('Unable to parse output of ping: %s', e) return result def icmp_latency(host): """ Pings a host. Requires script to be run as root in order to function. :param host: Hostname as string :return: Timestamp as float of seconds or nothing """ try: result = ping(host=host, number=1, wait_sec=1) return result['avg'] except: pass def average_latency(host, protocol, path): """ Return average latency of checks to host for given protocol. Errors will break the loop and an average will be calculated of whatever data we have. If that doesn't work, it will return '-1'. :param host: hostname string :param protocol: protocol string :return: average latency in seconds as float """ latencies = [] for count in range(0, config['check_count']): if protocol == "icmp": result = icmp_latency(host) if result: latencies.append(result) else: break elif protocol == "rtb": result = rtb_latency(host, path) if result: latencies.append(result) else: break elif protocol == "get": result = http_get_latency(host) if result: latencies.append(result) else: break else: logger.error('Unknown protocol: %s (count=%s)', protocol, count) return try: avg_latency = sum(latencies) / float(len(latencies)) except Exception as e: logger.debug(e) avg_latency = -1 if avg_latency > config['latency_warn'] or avg_latency == -1: logger.warn('Latency to %s is %ss.', host, str(avg_latency)) net_debug(host) return avg_latency def send_graphite( provider, protocol, latency, endpoint, remote_region, graphite_host=config["graphite_host"], graphite_port=config["graphite_port"], graphite_prefix=config["graphite_prefix"] ): """ Send a latency metric to Graphite. Line format: prefix.provider.remote_region.local_host.protocol latency_in_milliseconds timestamp :param provider: provider name as string :param protocol: protocol as
self.wavepattern == 'SWS': res_df.loc[i, :] = self.norm_sws(param_c, channel) elif self.wavepattern == 'SPN': res_df.loc[i, :] = self.norm_spn(param_c, channel) else: raise NameError(f'Wavepattern {self.wavepattern} is unvalid.') if i%10 == 0: with open(res_p/resname, 'wb') as f: pickle.dump(res_df, f) print(f'Now i={i}, and pickled') with open(res_p/resname, 'wb') as f: pickle.dump(res_df, f) def two_bifur_singleprocess(self, args) -> None: core, param_lst, r_df, channel1, channel2, res_p, resname = args for p_lst in param_lst: m, param_c = p_lst r_name = f'{resname}_{m}.pickle' for i in tqdm(r_df.columns): param_cc = copy(param_c) # param_cc[f'g_{channel2}'] = param_cc[f'g_{channel2}'] * i/1000 param_cc[channel2] = param_cc[channel2] * i/1000 if self.wavepattern == 'SWS': # try: # r_df.loc[m, i] = 1000 / np.diff(self.norm_sws(param_cc, channel2, channel1)).mean() # except: # r_df.loc[m, i] = None pass elif self.wavepattern == 'SPN': try: r_df.loc[m, i] = 1000 / np.diff(self.norm_spn(param=param_cc, channel=channel1, channel2=channel2)).mean() except: r_df.loc[m, i] = None else: raise NameError(f'Wavepattern {self.wavepattern} is unvalid.') with open(res_p/r_name, 'wb') as f: pickle.dump(r_df, f) def two_bifur_multi_singleprocess(self, ncore, filename, channel1, channel2, diff, interval): p: Path = Path.cwd().parents[0] data_p: Path = p / 'results' / f'{self.wavepattern}_params' / self.model_name res_p: Path = p / 'results' / 'normalization_mp_ca' / 'two_bifurcation' / f'{self.model_name}' / f'{channel1}_{channel2}' channel1 = 'g_' + channel1 channel2 = 'g_' + channel2 res_p.mkdir(parents=True, exist_ok=True) with open(data_p/filename, 'rb') as f: param = pickle.load(f) self.model.set_params(param) self.model.leak.set_div() param.loc['g_nal'] = self.model.leak.gnal param.loc['g_kl'] = self.model.leak.gkl start = 1000 - diff end = 1000 + diff + 1 # index: channel_1, columns: channel_2 magnif_lst = np.arange(start, end, interval) res_df = pd.DataFrame(index=magnif_lst, columns=magnif_lst) resname = f'{filename}_{diff}' args: List = [] for core, m_lst in enumerate(np.array_split(magnif_lst, ncore)): param_lst = [] for m in m_lst: param_c = copy(param) # param_c[f'g_{channel1}'] = param_c[f'g_{channel1}'] * m/1000 param_c[channel1] = param_c[channel1] * m/1000 param_lst.append([m, param_c]) r_df = res_df.loc[m_lst, :] args.append((core, param_lst, r_df, channel1, channel2, res_p, resname)) with Pool(processes=ncore) as pool: pool.map(self.two_bifur_singleprocess, args) def load_two_bifur(self, filename, ch1, ch2, diff, interval): p: Path = Path.cwd().parents[0] res_p: Path = p / 'results' / 'normalization_mp_ca' / 'two_bifurcation' / f'{self.model_name}' / f'{ch1}_{ch2}' start = 1000 - diff end = 1000 + diff + 1 magnif_lst = np.arange(start, end, interval) self.res_df = pd.DataFrame(index=magnif_lst, columns=magnif_lst) for m in magnif_lst: resname = f'{filename}_{diff}_{m}.pickle' with open(res_p/resname, 'rb') as f: self.res_df.loc[m, :] = pickle.load(f).iloc[0, :] def time_bifurcation_all(self, filename: str, channel: str, magnif: float) -> None: """ Calculate time points for 1st~6th burst firing for the representative parameter set through bifurcation. Parameters ---------- filename : str the name of file in which parameter sets are contained """ p: Path = Path.cwd().parents[0] data_p: Path = p / 'results' / f'{self.wavepattern}_params' / self.model_name resname: str = f'{filename}_{channel}_{magnif}_time.pickle' res_p: Path = p / 'results' / 'normalization_mp_ca' / 'bifurcation_all' / f'{self.model_name}' res_p.mkdir(parents=True, exist_ok=True) with open(data_p/filename, 'rb') as f: df = pickle.load(f) res_df = pd.DataFrame([], columns=range(7), index=range(len(df))) for i in tqdm(range(len(df))): param = df.iloc[i, :] self.model.set_params(param) self.model.leak.set_div() param.loc['g_nal'] = self.model.leak.gnal param.loc['g_kl'] = self.model.leak.gkl param_c = copy(param) param_c[channel] = param_c[channel] * magnif if self.wavepattern == 'SWS': res_df.loc[i, :] = self.norm_sws(param_c, channel) elif self.wavepattern == 'SPN': res_df.loc[i, :] = self.norm_spn(param_c, channel) else: raise NameError(f'Wavepattern {self.wavepattern} is unvalid.') if i%10 == 0: with open(res_p/resname, 'wb') as f: pickle.dump(res_df, f) print(f'Now i={i}, and pickled') with open(res_p/resname, 'wb') as f: pickle.dump(res_df, f) def load_time_bifurcation_all(self, dataname: str, diff: float=0.025): p: Path = Path.cwd().parents[0] res_p = p / 'results' / 'normalization_mp_ca' / 'bifurcation_all' / f'{self.model_name}' magnif_u = 1 + diff magnif_d = 1 - diff if self.wavepattern == 'SWS': with open(res_p/f'{dataname}_g_kvhh_1.0_time.pickle', 'rb') as f: self.norm_t = pickle.load(f) self.norm_fr = 1000 / self.norm_t.dropna().diff(axis=1).mean(axis=1) elif self.wavepattern == 'SPN': with open(res_p/f'{dataname}_g_kvsi_1.0_time.pickle', 'rb') as f: self.norm_t = pickle.load(f) self.norm_fr = 1000 / self.norm_t.dropna().diff(axis=1).mean(axis=1) with open(res_p/f'{dataname}_g_kleak_{magnif_u}_time.pickle', 'rb') as f: self.kl_t_u = pickle.load(f) self.kl_fr_u = 1000 / self.kl_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kleak_{magnif_d}_time.pickle', 'rb') as f: self.kl_t_d = pickle.load(f) self.kl_fr_d = 1000 / self.kl_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kvsi_{magnif_u}_time.pickle', 'rb') as f: self.kvsi_t_u = pickle.load(f) self.kvsi_fr_u = 1000 / self.kvsi_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kvsi_{magnif_d}_time.pickle', 'rb') as f: self.kvsi_t_d = pickle.load(f) self.kvsi_fr_d = 1000 / self.kvsi_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kca_{magnif_u}_time.pickle', 'rb') as f: self.kca_t_u = pickle.load(f) self.kca_fr_u = 1000 / self.kca_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kca_{magnif_d}_time.pickle', 'rb') as f: self.kca_t_d = pickle.load(f) self.kca_fr_d = 1000 / self.kca_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_naleak_{magnif_u}_time.pickle', 'rb') as f: self.nal_t_u = pickle.load(f) self.nal_fr_u = 1000 / self.nal_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_naleak_{magnif_d}_time.pickle', 'rb') as f: self.nal_t_d = pickle.load(f) self.nal_fr_d = 1000 / self.nal_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_nap_{magnif_u}_time.pickle', 'rb') as f: self.nap_t_u = pickle.load(f) self.nap_fr_u = 1000 / self.nap_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_nap_{magnif_d}_time.pickle', 'rb') as f: self.nap_t_d = pickle.load(f) self.nap_fr_d = 1000 / self.nap_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_cav_{magnif_u}_time.pickle', 'rb') as f: self.cav_t_u = pickle.load(f) self.cav_fr_u = 1000 / self.cav_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_cav_{magnif_d}_time.pickle', 'rb') as f: self.cav_t_d = pickle.load(f) self.cav_fr_d = 1000 / self.cav_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_t_ca_{magnif_u}_time.pickle', 'rb') as f: self.tca_t_u = pickle.load(f) self.tca_fr_u = 1000 / self.tca_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_t_ca_{magnif_d}_time.pickle', 'rb') as f: self.tca_t_d = pickle.load(f) self.tca_fr_d = 1000 / self.tca_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr data_dic = { 'kleak': [self.kl_fr_u, self.kl_fr_d], 'kca': [self.kca_fr_u, self.kca_fr_d], 'naleak': [self.nal_fr_u, self.nal_fr_d], 'cav': [self.cav_fr_u, self.cav_fr_d], 'nap': [self.nap_fr_u, self.nap_fr_d], 'tca': [self.tca_fr_u, self.tca_fr_d], } if self.model_name == 'AN': with open(res_p/f'{dataname}_g_nav_{magnif_u}_time.pickle', 'rb') as f: self.nav_t_u = pickle.load(f) self.nav_fr_u = 1000 / self.nav_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_nav_{magnif_d}_time.pickle', 'rb') as f: self.nav_t_d = pickle.load(f) self.nav_fr_d = 1000 / self.nav_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kvhh_{magnif_u}_time.pickle', 'rb') as f: self.kvhh_t_u = pickle.load(f) self.kvhh_fr_u = 1000 / self.kvhh_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kvhh_{magnif_d}_time.pickle', 'rb') as f: self.kvhh_t_d = pickle.load(f) self.kvhh_fr_d = 1000 / self.kvhh_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kvsi_{magnif_u}_time.pickle', 'rb') as f: self.kvsi_t_u = pickle.load(f) self.kvsi_fr_u = 1000 / self.kvsi_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kvsi_{magnif_d}_time.pickle', 'rb') as f: self.kvsi_t_d = pickle.load(f) self.kvsi_fr_d = 1000 / self.kvsi_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kva_{magnif_u}_time.pickle', 'rb') as f: self.kva_t_u = pickle.load(f) self.kva_fr_u = 1000 / self.kva_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kva_{magnif_d}_time.pickle', 'rb') as f: self.kva_t_d = pickle.load(f) self.kva_fr_d = 1000 / self.kva_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kir_{magnif_u}_time.pickle', 'rb') as f: self.kir_t_u = pickle.load(f) self.kir_fr_u = 1000 / self.kir_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kir_{magnif_d}_time.pickle', 'rb') as f: self.kir_t_d = pickle.load(f) self.kir_fr_d = 1000 / self.kir_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_ampar_{magnif_u}_time.pickle', 'rb') as f: self.ampar_t_u = pickle.load(f) self.ampar_fr_u = 1000 / self.ampar_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_ampar_{magnif_d}_time.pickle', 'rb') as f: self.ampar_t_d = pickle.load(f) self.ampar_fr_d = 1000 / self.ampar_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_nmdar_{magnif_u}_time.pickle', 'rb') as f: self.nmdar_t_u = pickle.load(f) self.nmdar_fr_u = 1000 / self.nmdar_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_nmdar_{magnif_d}_time.pickle', 'rb') as f: self.nmdar_t_d = pickle.load(f) self.nmdar_fr_d = 1000 / self.nmdar_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_gabar_{magnif_u}_time.pickle', 'rb') as f: self.gabar_t_u = pickle.load(f) self.gabar_fr_u = 1000 / self.gabar_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_gabar_{magnif_d}_time.pickle', 'rb') as f: self.gabar_t_d = pickle.load(f) self.gabar_fr_d = 1000 / self.gabar_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr data_dic['nav'] = [self.nav_fr_u, self.nav_fr_d] data_dic['kvhh'] = [self.kvhh_fr_u, self.kvhh_fr_d] data_dic['kvsi'] = [self.kvsi_fr_u, self.kvsi_fr_d] data_dic['kva'] = [self.kva_fr_u, self.kva_fr_d] data_dic['kir'] = [self.kir_fr_u, self.kir_fr_d] data_dic['ampar'] = [self.ampar_fr_u, self.ampar_fr_d] data_dic['nmdar'] = [self.nmdar_fr_u, self.nmdar_fr_d] data_dic['gabar'] = [self.gabar_fr_u, self.gabar_fr_d] elif self.model_name == 'SAN': with open(res_p/f'{dataname}_g_kvhh_{magnif_u}_time.pickle', 'rb') as f: self.kvhh_t_u = pickle.load(f) self.kvhh_fr_u = 1000 / self.kvhh_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kvhh_{magnif_d}_time.pickle', 'rb') as f: self.kvhh_t_d = pickle.load(f) self.kvhh_fr_d = 1000 / self.kvhh_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr data_dic['kvhh'] = [self.kvhh_fr_u, self.kvhh_fr_d] elif self.model_name == 'RAN': with open(res_p/f'{dataname}_g_kvsi_{magnif_u}_time.pickle', 'rb') as f: self.kvsi_t_u = pickle.load(f) self.kvsi_fr_u = 1000 / self.kvsi_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr with open(res_p/f'{dataname}_g_kvsi_{magnif_d}_time.pickle', 'rb') as f: self.kvsi_t_d = pickle.load(f) self.kvsi_fr_d = 1000 / self.kvsi_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr data_dic['kvsi'] = [self.kvsi_fr_u, self.kvsi_fr_d] len_data = len(self.norm_fr) self.n_df = pd.DataFrame(index=data_dic.keys(), columns=['inc', 'dec']) self.diff_df = pd.DataFrame(index=data_dic.keys(), columns=['inc', 'dec']) self.diff_sig = pd.DataFrame(index=data_dic.keys(), columns=['inc', 'dec']) for ch in data_dic.keys(): n_inc = 0 n_dec = 0 avg_inc = 0 avg_dec = 0 var_inc = 0 var_dec = 0 fr_u, fr_d = data_dic[ch] fr_u.index = range(len(fr_u)) fr_d.index = range(len(fr_d)) sh_idx = np.intersect1d(fr_u.dropna().index, fr_d.dropna().index) sh_idx = sh_idx.astype(int) for idx in sh_idx: if fr_d[idx] < 0.1 or fr_u[idx] > 2.0: pass elif fr_d[idx] > 2.0 or fr_u[idx] < 0.1: pass elif fr_d[idx] < 0.975 and fr_u[idx] > 1.025: n_inc += 1 diff = fr_u[idx] - fr_d[idx] avg_inc_min1 = copy(avg_inc) avg_inc += (diff - avg_inc) / n_inc var_inc += (diff - avg_inc_min1) * (diff - avg_inc) elif fr_d[idx] > 1.025
<reponame>hyperion-ml/hyperion<filename>hyperion/io/audio_reader.py """ Copyright 2018 Johns Hopkins University (Author: <NAME>) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ import os import logging import io import math import subprocess import soundfile as sf import numpy as np from ..hyp_defs import float_cpu from ..utils import SCPList, SegmentList valid_ext = [ ".wav", ".flac", ".ogg", ".au", ".avr", ".caf", ".htk", ".iff", ".mat", ".mpc", ".oga", ".pvf", ".rf64", ".sd2", ".sds", ".sf", ".voc", "w64", ".wve", ".xi", ] class AudioReader(object): """Class to read audio files from wav, flac or pipe Attributes: file_path: scp file with formant file_key wavspecifier (audio_file/pipe) or SCPList object. segments_path: segments file with format: segment_id file_id tbeg tend wav_scale: multiplies signal by scale factor """ def __init__(self, file_path, segments_path=None, wav_scale=2 ** 15 - 1): self.file_path = file_path if isinstance(file_path, SCPList): self.scp = file_path else: self.scp = SCPList.load(file_path, sep=" ", is_wav=True) self.segments_path = segments_path if segments_path is None: self.segments = None self.with_segments = False else: self.with_segments = True if isinstance(file_path, SegmentList): self.segments = segments_path else: self.segments = SegmentList.load( segments_path, sep=" ", index_by_file=False ) self.wav_scale = wav_scale @property def keys(self): if self.with_segments: return np.asarray(self.segments["segment_id"]) return self.scp.key def __enter__(self): """Function required when entering contructions of type with AudioReader('file.h5') as f: keys, data = f.read() """ return self def __exit__(self, exc_type, exc_value, traceback): """Function required when exiting from contructions of type with AudioReader('file.h5') as f: keys, data = f.read() """ pass @staticmethod def read_wavspecifier(wavspecifier, scale=2 ** 15, time_offset=0, time_dur=0): """Reads an audiospecifier (audio_file/pipe) It reads from pipe or from all the files that can be read by `libsndfile <http://www.mega-nerd.com/libsndfile/#Features>` Args: wavspecifier: A pipe, wav, flac, ogg file etc. scale: Multiplies signal by scale factor time_offset: float indicating the start time to read in the utterance. time_durs: floats indicating the number of seconds to read from the utterance, if 0 it reads untils the end """ wavspecifier = wavspecifier.strip() if wavspecifier[-1] == "|": wavspecifier = wavspecifier[:-1] x, fs = AudioReader.read_pipe(wavspecifier, scale) if time_offset == 0 and time_dur == 0: return x, fs start_sample = int(math.floor(time_offset * fs)) num_samples = int(math.floor(time_dur * fs)) if num_samples == 0: return x[start_sample:], fs end_sample = start_sample + num_samples assert end_sample <= len(x) return x[start_sample:end_sample], fs ext = os.path.splitext(wavspecifier)[1] if ext in valid_ext: if time_offset == 0 and time_dur == 0: x, fs = sf.read(wavspecifier, dtype=float_cpu()) x *= scale return x, fs with sf.SoundFile(wavspecifier, "r") as f: fs = f.samplerate start_sample = int(math.floor(time_offset * fs)) num_samples = int(math.floor(time_dur * fs)) f.seek(start_sample) if num_samples > 0: x = scale * f.read(num_samples, dtype=float_cpu()) else: x = scale * f.read(dtype=float_cpu()) return x, fs raise Exception("Unknown format for %s" % (wavspecifier)) @staticmethod def read_pipe(wavspecifier, scale=2 ** 15): """Reads wave file from a pipe Args: wavspecifier: Shell command with pipe output scale: Multiplies signal by scale factor """ # proc = subprocess.Popen(wavspecifier, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) proc = subprocess.Popen(wavspecifier, shell=True, stdout=subprocess.PIPE) pipe = proc.communicate()[0] if proc.returncode != 0: raise Exception( "Wave read pipe command %s returned code %d" % (wavspecifier, proc.returncode) ) x, fs = sf.read(io.BytesIO(pipe), dtype=float_cpu()) x *= scale return x, fs def _read_segment(self, segment, time_offset=0, time_dur=0): """Reads a wave segment Args: segment: pandas DataFrame (segment_id , file_id, tbeg, tend) Returns: Wave, sampling frequency """ file_id = segment["file_id"] t_beg = segment["tbeg"] + time_offset t_end = segment["tend"] if time_dur > 0: t_end_new = t_beg + time_dur assert t_end_new <= t_end t_end = t_end_new file_path, _, _ = self.scp[file_id] x_i, fs_i = self.read_wavspecifier(file_path, self.wav_scale) num_samples_i = len(x_i) s_beg = int(t_beg * fs_i) if s_beg >= num_samples_i: raise Exception( "segment %s tbeg=%.2f (num_sample=%d) longer that wav file %s (num_samples=%d)" % (key, tbeg, sbeg, file_id, num_samples_i) ) s_end = int(t_end * fs_i) if s_end > num_samples_i or t_end < 0: s_end = num_samples_i x_i = x_i[s_beg:s_end] return x_i, fs_i def read(self): pass class SequentialAudioReader(AudioReader): def __init__( self, file_path, segments_path=None, wav_scale=2 ** 15 - 1, part_idx=1, num_parts=1, ): super().__init__(file_path, segments_path, wav_scale=wav_scale) self.cur_item = 0 self.part_idx = part_idx self.num_parts = num_parts if self.num_parts > 1: if self.with_segments: self.segments = self.segments.split(self.part_idx, self.num_parts) else: self.scp = self.scp.split( self.part_idx, self.num_parts, group_by_key=False ) def __iter__(self): """Needed to build an iterator, e.g.: r = SequentialAudioReader(...) for key, s, fs in r: print(key) process(s) """ return self def __next__(self): """Needed to build an iterator, e.g.: r = SequentialAudioReader(...) for key , s, fs in r: process(s) """ key, x, fs = self.read(1) if len(key) == 0: raise StopIteration return key[0], x[0], fs[0] def next(self): """__next__ for Python 2""" return self.__next__() def reset(self): """Returns the file pointer to the begining of the dataset, then we can start reading the features again. """ self.cur_item = 0 def eof(self): """End of file. Returns: True, when we have read all the recordings in the dataset. """ if self.with_segments: return self.cur_item == len(self.segments) return self.cur_item == len(self.scp) def read(self, num_records=0, time_offset=0, time_durs=0): """Reads next num_records audio files Args: num_records: Number of audio files to read. time_offset: List of floats indicating the start time to read in the utterance. time_durs: List of floats indicating the number of seconds to read from each utterance Returns: key: List of recording names. data: List of waveforms fs: list of sample freqs """ if num_records == 0: if self.with_segments: num_records = len(self.segments) - self.cur_item else: num_records = len(self.scp) - self.cur_item offset_is_list = isinstance(time_offset, (list, np.ndarray)) dur_is_list = isinstance(time_durs, (list, np.ndarray)) keys = [] data = [] fs = [] for i in range(num_records): if self.eof(): break offset_i = time_offset[i] if offset_is_list else time_offset dur_i = time_durs[i] if dur_is_list else time_durs if self.with_segments: segment = self.segments[self.cur_item] key = segment["segment_id"] x_i, fs_i = self._read_segment(segment, offset_i, dur_i) else: key, file_path, _, _ = self.scp[self.cur_item] x_i, fs_i = self.read_wavspecifier( file_path, self.wav_scale, offset_i, dur_i ) keys.append(key) data.append(x_i) fs.append(fs_i) self.cur_item += 1 return keys, data, fs @staticmethod def filter_args(**kwargs): valid_args = ("part_idx", "num_parts", "wav_scale") return dict((k, kwargs[k]) for k in valid_args if k in kwargs) @staticmethod def add_class_args(parser, prefix=None): if prefix is None: p1 = "--" else: p1 = "--" + prefix + "." parser.add_argument( p1 + "wav-scale", default=2 ** 15 - 1, type=float, help=("multiplicative factor for waveform"), ) try: parser.add_argument( p1 + "part-idx", type=int, default=1, help=( "splits the list of files into num-parts and " "processes part-idx" ), ) parser.add_argument( p1 + "num-parts", type=int, default=1, help=( "splits the list of files into num-parts and " "processes part-idx" ), ) except: pass add_argparse_args = add_class_args class RandomAccessAudioReader(AudioReader): def __init__(self, file_path, segments_path=None, wav_scale=2 ** 15 - 1): super().__init__(file_path, segments_path, wav_scale) def _read(self, keys, time_offset=0, time_durs=0): """Reads the waveforms for the recordings in keys. Args: keys: List of recording/segment_ids names. Returns: data: List of waveforms """ if isinstance(keys, str): keys = [keys] offset_is_list = isinstance(time_offset, (list, np.ndarray)) dur_is_list = isinstance(time_durs, (list, np.ndarray)) data = [] fs = [] for i, key in enumerate(keys): offset_i = time_offset[i] if offset_is_list else time_offset dur_i = time_durs[i] if dur_is_list else time_durs if self.with_segments: if not (key in self.segments): raise Exception("Key %s not found" % key) segment = self.segments[key] x_i, fs_i = self._read_segment(segment, offset_i, dur_i) else: if not (key in self.scp): raise Exception("Key %s not found" % key) file_path, _, _ = self.scp[key] x_i, fs_i = self.read_wavspecifier( file_path, self.wav_scale, offset_i, dur_i ) data.append(x_i) fs.append(fs_i) return data, fs def read(self, keys, time_offset=0, time_durs=0): """Reads the waveforms for the recordings in keys. Args: keys: List of recording/segment_ids names. Returns: data: List of waveforms fs: List of sampling freq. """ try: x, fs = self._read(keys, time_offset=time_offset, time_durs=time_durs) except: if isinstance(keys, str): keys = [keys] if not isinstance(time_offset, (list, np.ndarray)): time_offset = [time_offset] * len(keys) if not isinstance(time_durs, (list, np.ndarray)): time_durs = [time_durs] * len(keys) try: # some files produce error in the fseek after reading the data, # this seems an issue from pysoundfile or soundfile lib itself # we try to read from # time-offset to the end of the file, and remove the extra frames later, # this solves the problem in most cases logging.info( ( "error-1 reading at keys={} offset={} " "retrying reading until end-of-file ..." ).format(keys, time_offset) ) x, fs = self._read(keys, time_offset=time_offset) for i in
* (c[13] + c[17] * p_r + c[19] * SA_r) # + x * (c[11] + p_r * (c[14] + c[18] * p_r) + SA_r * (c[16] + # c[20] * p_r + c[22] * SA_r))) - saturation_fraction * 1e-3 * # (2.4 - a * SA) * (1 + b * (1 - SA / SSO)) # # CT_error = np.abs(CT_freeze - CT) # # tmp = np.logical_or(p > 10000, SA > 120 # out = np.logical_and(tmp, p + SA * 71.428571428571402 > 13571.42857142857) # CT_error[out] = np.ma.masked brine_SA_CT = SA tmp = np.logical_or(p > 10000, SA > 120) out = np.logical_and(tmp, p + SA * 71.428571428571402 > 13571.42857142857) brine_SA_CT[out] = np.ma.masked # If the CT input is too warm, then there is no (positive) value of SA # that represents frozen seawater. brine_SA_CT[Itw] = -99 # NOTE: Mask these? return brine_SA_CT @match_args_return def brineSA_t(t, p, saturation_fraction=1): """ Calculates the Absolute Salinity of seawater at the freezing temperature. That is, the output is the Absolute Salinity of seawater, with the fraction saturation_fraction of dissolved air, that is in equilibrium with ice at in-situ temperature t and pressure p. If the input values are such that there is no positive value of Absolute Salinity for which seawater is frozen, the output, brineSA_t, is put equal to -99. Parameters ---------- t : array_like in situ temperature [:math:`^\circ` C (ITS-90)] p : array_like sea pressure [dbar] saturation_fraction : fraction between 0, 1. The saturation fraction of dissolved air in seawater. Default is 0 or completely saturated. Returns ------- brine_SA_t : array_like Absolute Salinity of seawater when it freezes [ g/kg ] Examples -------- TODO References ---------- .. [1] IOC, SCOR and IAPSO, 2010: The international thermodynamic equation of seawater - 2010: Calculation and use of thermodynamic properties. Intergovernmental Oceanographic Commission, Manuals and Guides No. 56, UNESCO (English), 196 pp. See sections 3.33. """ t, p, saturation_fraction = np.broadcast_arrays(t, p, saturation_fraction, subok=True) if np.logical_or(saturation_fraction < 0, saturation_fraction > 1).any(): raise ValueError('Saturation_fraction MUST be between zero and one.') p_r = p * 1e-4 # Form the first estimate of brine_SA_t, called SA here, from a polynomial # in CT and p_r. SA = -(t + 9 * p_r) / 0.06 # A rough estimate to get the saturated CT. SA = np.maximum(SA, 0) CT = CT_from_t(SA, t, p) CTsat = CT - (1 - saturation_fraction) * 1e-3 * (2.4 - a * SA) * (1 + b * (1 - SA / SSO)) SA = P[0] + p * (P[2] + P[4] * CTsat + p * (P[5] + CTsat * (P[7] + P[9] * CTsat) + p * (P[8] + CTsat * (P[10] + P[12] * CTsat) + p * (P[11] + P[13] * CTsat + P[14] * p)))) + CTsat * (P[1] + CTsat * (P[3] + P[6] * p)) t_freezing_zero_SA = t_freezing(np.zeros_like(t), p, saturation_fraction) # Find t > t_freezing_zero_SA. If this is the case, the input values # represent seawater that is not frozen (at any positive SA). Itw = (t > t_freezing_zero_SA) # Itw stands for "I_too_warm" SA[Itw] = np.ma.masked # Find -SA_cut_off < SA < SA_cut_off, replace the above estimate of SA # with one based on (t_freezing_zero_SA - t). SA_cut_off = 2.5 # This is the band of SA within +- 2.5 g/kg of SA = 0, # which we treat differently in calculating the initial # values of both SA and dCT_dSA. Ico = (np.abs(SA) < SA_cut_off) Icoa = np.logical_and(SA < 0, SA >= -SA_cut_off) SA[Icoa] = 0 # Find SA < -SA_cut_off, set them to masked. SA[SA < -SA_cut_off] = np.ma.masked # Form the first estimate of dt_dSA, the derivative of t with respect # to SA at fixed p, using the coefficients, t0 ... t22 from t_freezing. SA_r = 0.01 * SA x = np.sqrt(SA_r) dt_dSA_part = 2 * T[1] + x * (3 * T[2] + x * (4 * T[3] + x * (5 * T[4] + x * (6 * T[5] + 7 * T[6] * x)))) + p_r * (2 * T[10] + p_r * (2 * T[12] + p_r * (2 * T[15] + 4 * T[21] * x * x)) + x * x * (4 * T[13] + 4 * T[17] * p_r + 6 * T[19] * x * x) + x * (3 * T[11] + 3 * p_r * (T[14] + T[18] * p_r) + x * x * (5 * T[16] + 5 * T[20] * p_r + 7 * T[22] * x * x))) dt_dSA = 0.5 * 0.01 * dt_dSA_part + saturation_fraction * 1e-3 / 70.33008 # Now replace the estimate of SA with the one based on # (t_freezing_zero_SA - t) when (abs(SA) < SA_cut_off). SA[Ico] = (t[Ico] - t_freezing_zero_SA[Ico]) / dt_dSA[Ico] # Begin the modified Newton-Raphson method to find the root of # t_freeze = t for SA. Number_of_Iterations = 5 for I_iter in range(0, Number_of_Iterations): SA_old = SA t_freeze = t_freezing(SA_old, p, saturation_fraction) SA = SA_old - (t_freeze - t) / dt_dSA # Half-way point of the modified Newton-Raphson solution method. SA_r = 0.5 * 0.01 * (SA + SA_old) # Mean value of SA and SA_old. x = np.sqrt(SA_r) dt_dSA_part = (2 * T[1] + x * (3 * T[2] + x * (4 * T[3] + x * (5 * T[4] + x * (6 * T[5] + 7 * T[6] * x)))) + p_r * (2 * T[10] + p_r * (2 * T[12] + p_r * (2 * T[15] + 4 * T[21] * x * x)) + x * x * (4 * T[13] + 4 * T[17] * p_r + 6 * T[19] * x * x) + x * (3 * T[11] + 3 * p_r * (T[14] + T[18] * p_r) + x * x * (5 * T[16] + 5 * T[20] * p_r + 7 * T[22] * x * x)))) dt_dSA = (0.5 * 0.01 * dt_dSA_part + saturation_fraction * 1e-3 / 70.33008) SA = SA_old - (t_freeze - t) / dt_dSA # The following lines of code, if implemented, calculate the error of this # function in terms of in-situ temperature. With Number_of_Iterations = 4, # the max error in t is 3x10^-13 C. With Number_of_Iterations = 5, the max # error in t is 2x10^-14 C, which is the machine precision of the computer. # Number_of_Iterations = 5 is what we recommend. # # SA[SA < 0] = np.ma.masked # # t_freeze = t_freezing(SA, p, saturation_fraction) # t_error = np.abs(t_freeze - t) # tmp = np.logical_or(p > 10000, SA > 120) # out = np.logical_and(tmp, p + SA * 71.428571428571402 > 13571.42857142857) # t_error[out] = np.ma.masked brine_SA_t = SA tmp = np.logical_or(p > 10000, SA > 120) out = np.logical_and(tmp, p + SA * 71.428571428571402 > 13571.42857142857) brine_SA_t[out] = np.ma.masked brine_SA_t[Itw] = -99 # If the t input is too warm, then there is no # (positive) value of SA that represents frozen # seawater. return brine_SA_t @match_args_return def CT_freezing(SA, p, saturation_fraction=1): """ Calculates the Conservative Temperature at which seawater freezes. Parameters ---------- SA : array_like Absolute Salinity [g/kg] p : array_like sea pressure [dbar] saturation_fraction : fraction between 0, 1. The saturation fraction of dissolved air in seawater. Default is 0 or completely saturated. Returns ------- CT_freezing : array_like Conservative Temperature at freezing of seawater [:math:`^\circ` C (ITS-90)] Examples -------- TODO References ---------- .. [1] IOC, SCOR and IAPSO, 2010: The international thermodynamic equation of seawater - 2010: Calculation and use of thermodynamic properties. Intergovernmental Oceanographic Commission, Manuals and Guides No. 56, UNESCO (English), 196 pp. See sections 3.33 and 3.34. """ SA, p, saturation_fraction = np.broadcast_arrays(SA, p, saturation_fraction, subok=True) if (SA < 0).any(): raise ValueError('SA must be non-negative!')
bal['asset'].lower() == asset.lower(): return bal return None async def get_my_trades(self, **params): return await self._get('myTrades', True, data=params) async def get_system_status(self): return await self._request_margin_api('get', 'system/status') async def get_account_status(self, **params): return await self._request_margin_api('get', 'account/status', True, data=params) async def get_account_api_trading_status(self, **params): return await self._request_margin_api('get', 'account/apiTradingStatus', True, data=params) async def get_account_api_permissions(self, **params): return await self._request_margin_api('get', 'account/apiRestrictions', True, data=params) async def get_dust_log(self, **params): return await self._request_margin_api('get', 'asset/dribblet', True, data=params) async def transfer_dust(self, **params): return await self._request_margin_api('post', 'asset/dust', True, data=params) async def get_asset_dividend_history(self, **params): return await self._request_margin_api('get', 'asset/assetDividend', True, data=params) async def make_universal_transfer(self, **params): return await self._request_margin_api('post', 'asset/transfer', signed=True, data=params) async def query_universal_transfer_history(self, **params): return await self._request_margin_api('get', 'asset/transfer', signed=True, data=params) async def get_trade_fee(self, **params): return await self._request_margin_api('get', 'asset/tradeFee', True, data=params) async def get_asset_details(self, **params): return await self._request_margin_api('get', 'asset/assetDetail', True, data=params) # Withdraw Endpoints async def withdraw(self, **params): # force a name for the withdrawal if one not set if 'coin' in params and 'name' not in params: params['name'] = params['coin'] return await self._request_margin_api('post', 'capital/withdraw/apply', True, data=params) async def get_deposit_history(self, **params): return await self._request_margin_api('get', 'capital/deposit/hisrec', True, data=params) async def get_withdraw_history(self, **params): return await self._request_margin_api('get', 'capital/withdraw/history', True, data=params) async def get_withdraw_history_id(self, withdraw_id, **params): result = await self.get_withdraw_history(**params) for entry in result: if 'id' in entry and entry['id'] == withdraw_id: return entry raise Exception("There is no entry with withdraw id", result) async def get_deposit_address(self, coin: str, network: Optional[str] = None, **params): params['coin'] = coin if network: params['network'] = network return await self._request_margin_api('get', 'capital/deposit/address', True, data=params) # User Stream Endpoints async def stream_get_listen_key(self): res = await self._post('userDataStream', False, data={}) return res['listenKey'] async def stream_keepalive(self, listenKey): params = { 'listenKey': listenKey } return await self._put('userDataStream', False, data=params) async def stream_close(self, listenKey): params = { 'listenKey': listenKey } return await self._delete('userDataStream', False, data=params) # Margin Trading Endpoints async def get_margin_account(self, **params): return await self._request_margin_api('get', 'margin/account', True, data=params) async def get_isolated_margin_account(self, **params): return await self._request_margin_api('get', 'margin/isolated/account', True, data=params) async def get_margin_asset(self, **params): return await self._request_margin_api('get', 'margin/asset', data=params) async def get_margin_symbol(self, **params): return await self._request_margin_api('get', 'margin/pair', data=params) async def get_margin_all_assets(self, **params): return await self._request_margin_api('get', 'margin/allAssets', data=params) async def get_margin_all_pairs(self, **params): return await self._request_margin_api('get', 'margin/allPairs', data=params) async def create_isolated_margin_account(self, **params): return await self._request_margin_api('post', 'margin/isolated/create', signed=True, data=params) async def get_isolated_margin_symbol(self, **params): return await self._request_margin_api('get', 'margin/isolated/pair', signed=True, data=params) async def get_all_isolated_margin_symbols(self, **params): return await self._request_margin_api('get', 'margin/isolated/allPairs', signed=True, data=params) async def toggle_bnb_burn_spot_margin(self, **params): return await self._request_margin_api('post', 'bnbBurn', signed=True, data=params) async def get_bnb_burn_spot_margin(self, **params): return await self._request_margin_api('get', 'bnbBurn', signed=True, data=params) async def get_margin_price_index(self, **params): return await self._request_margin_api('get', 'margin/priceIndex', data=params) async def transfer_margin_to_spot(self, **params): params['type'] = 2 return await self._request_margin_api('post', 'margin/transfer', signed=True, data=params) async def transfer_spot_to_margin(self, **params): params['type'] = 1 return await self._request_margin_api('post', 'margin/transfer', signed=True, data=params) async def transfer_isolated_margin_to_spot(self, **params): params['transFrom'] = "ISOLATED_MARGIN" params['transTo'] = "SPOT" return await self._request_margin_api('post', 'margin/isolated/transfer', signed=True, data=params) async def transfer_spot_to_isolated_margin(self, **params): params['transFrom'] = "SPOT" params['transTo'] = "ISOLATED_MARGIN" return await self._request_margin_api('post', 'margin/isolated/transfer', signed=True, data=params) async def create_margin_loan(self, **params): return await self._request_margin_api('post', 'margin/loan', signed=True, data=params) async def repay_margin_loan(self, **params): return await self._request_margin_api('post', 'margin/repay', signed=True, data=params) async def create_margin_order(self, **params): return await self._request_margin_api('post', 'margin/order', signed=True, data=params) async def cancel_margin_order(self, **params): return await self._request_margin_api('delete', 'margin/order', signed=True, data=params) async def get_margin_loan_details(self, **params): return await self._request_margin_api('get', 'margin/loan', signed=True, data=params) async def get_margin_repay_details(self, **params): return await self._request_margin_api('get', 'margin/repay', signed=True, data=params) async def get_margin_interest_history(self, **params): return await self._request_margin_api('get', 'margin/interestHistory', signed=True, data=params) async def get_margin_force_liquidation_rec(self, **params): return await self._request_margin_api('get', 'margin/forceLiquidationRec', signed=True, data=params) async def get_margin_order(self, **params): return await self._request_margin_api('get', 'margin/order', signed=True, data=params) async def get_open_margin_orders(self, **params): return await self._request_margin_api('get', 'margin/openOrders', signed=True, data=params) async def get_all_margin_orders(self, **params): return await self._request_margin_api('get', 'margin/allOrders', signed=True, data=params) async def get_margin_trades(self, **params): return await self._request_margin_api('get', 'margin/myTrades', signed=True, data=params) async def get_max_margin_loan(self, **params): return await self._request_margin_api('get', 'margin/maxBorrowable', signed=True, data=params) async def get_max_margin_transfer(self, **params): return await self._request_margin_api('get', 'margin/maxTransferable', signed=True, data=params) # Margin OCO async def create_margin_oco_order(self, **params): return await self._request_margin_api('post', 'margin/order/oco', signed=True, data=params) async def cancel_margin_oco_order(self, **params): return await self._request_margin_api('delete', 'margin/orderList', signed=True, data=params) async def get_margin_oco_order(self, **params): return await self._request_margin_api('get', 'margin/orderList', signed=True, data=params) async def get_open_margin_oco_orders(self, **params): return await self._request_margin_api('get', 'margin/allOrderList', signed=True, data=params) # Cross-margin async def margin_stream_get_listen_key(self): res = await self._request_margin_api('post', 'userDataStream', signed=False, data={}) return res['listenKey'] async def margin_stream_keepalive(self, listenKey): params = { 'listenKey': listenKey } return await self._request_margin_api('put', 'userDataStream', signed=False, data=params) async def margin_stream_close(self, listenKey): params = { 'listenKey': listenKey } return await self._request_margin_api('delete', 'userDataStream', signed=False, data=params) # Isolated margin async def isolated_margin_stream_get_listen_key(self, symbol): params = { 'symbol': symbol } res = await self._request_margin_api('post', 'userDataStream/isolated', signed=False, data=params) return res['listenKey'] async def isolated_margin_stream_keepalive(self, symbol, listenKey): params = { 'symbol': symbol, 'listenKey': listenKey } return await self._request_margin_api('put', 'userDataStream/isolated', signed=False, data=params) async def isolated_margin_stream_close(self, symbol, listenKey): params = { 'symbol': symbol, 'listenKey': listenKey } return await self._request_margin_api('delete', 'userDataStream/isolated', signed=False, data=params) # Lending Endpoints async def get_lending_product_list(self, **params): return await self._request_margin_api('get', 'lending/daily/product/list', signed=True, data=params) async def get_lending_daily_quota_left(self, **params): return await self._request_margin_api('get', 'lending/daily/userLeftQuota', signed=True, data=params) async def purchase_lending_product(self, **params): return await self._request_margin_api('post', 'lending/daily/purchase', signed=True, data=params) async def get_lending_daily_redemption_quota(self, **params): return await self._request_margin_api('get', 'lending/daily/userRedemptionQuota', signed=True, data=params) async def redeem_lending_product(self, **params): return await self._request_margin_api('post', 'lending/daily/redeem', signed=True, data=params) async def get_lending_position(self, **params): return await self._request_margin_api('get', 'lending/daily/token/position', signed=True, data=params) async def get_fixed_activity_project_list(self, **params): return await self._request_margin_api('get', 'lending/project/list', signed=True, data=params) async def get_lending_account(self, **params): return await self._request_margin_api('get', 'lending/union/account', signed=True, data=params) async def get_lending_purchase_history(self, **params): return await self._request_margin_api('get', 'lending/union/purchaseRecord', signed=True, data=params) async def get_lending_redemption_history(self, **params): return await self._request_margin_api('get', 'lending/union/redemptionRecord', signed=True, data=params) async def get_lending_interest_history(self, **params): return await self._request_margin_api('get', 'lending/union/interestHistory', signed=True, data=params) async def change_fixed_activity_to_daily_position(self, **params): return await self._request_margin_api('post', 'lending/positionChanged', signed=True, data=params) # Sub Accounts async def get_sub_account_list(self, **params): return await self._request_margin_api('get', 'sub-account/list', True, data=params) async def get_sub_account_transfer_history(self, **params): return await self._request_margin_api('get', 'sub-account/sub/transfer/history', True, data=params) async def get_sub_account_futures_transfer_history(self, **params): return await self._request_margin_api('get', 'sub-account/futures/internalTransfer', True, data=params) async def create_sub_account_futures_transfer(self, **params): return await self._request_margin_api('post', 'sub-account/futures/internalTransfer', True, data=params) async def get_sub_account_assets(self, **params): return await self._request_margin_api('get', 'sub-account/assets', True, data=params) async def query_subaccount_spot_summary(self, **params): return await self._request_margin_api('get', 'sub-account/spotSummary', True, data=params) async def get_subaccount_deposit_address(self, **params): return await self._request_margin_api('get', 'capital/deposit/subAddress', True, data=params) async def get_subaccount_deposit_history(self, **params): return await self._request_margin_api('get', 'capital/deposit/subHisrec', True, data=params) async def get_subaccount_futures_margin_status(self, **params): return await self._request_margin_api('get', 'sub-account/status', True, data=params) async def enable_subaccount_margin(self, **params): return await self._request_margin_api('post', 'sub-account/margin/enable', True, data=params) async def get_subaccount_margin_details(self, **params): return await self._request_margin_api('get', 'sub-account/margin/account', True, data=params) async def get_subaccount_margin_summary(self, **params): return await self._request_margin_api('get', 'sub-account/margin/accountSummary', True, data=params) async def enable_subaccount_futures(self, **params): return await self._request_margin_api('post', 'sub-account/futures/enable', True, data=params) async def get_subaccount_futures_details(self, **params): return await self._request_margin_api('get', 'sub-account/futures/account', True, data=params) async def get_subaccount_futures_summary(self, **params): return await self._request_margin_api('get', 'sub-account/futures/accountSummary', True, data=params) async def get_subaccount_futures_positionrisk(self, **params): return await self._request_margin_api('get', 'sub-account/futures/positionRisk', True, data=params) async def make_subaccount_futures_transfer(self, **params): return await self._request_margin_api('post', 'sub-account/futures/transfer', True, data=params) async def make_subaccount_margin_transfer(self, **params): return await self._request_margin_api('post', 'sub-account/margin/transfer', True, data=params) async def make_subaccount_to_subaccount_transfer(self, **params): return await self._request_margin_api('post', 'sub-account/transfer/subToSub', True, data=params) async def make_subaccount_to_master_transfer(self, **params): return await self._request_margin_api('post', 'sub-account/transfer/subToMaster', True, data=params) async def get_subaccount_transfer_history(self, **params): return await self._request_margin_api('get', 'sub-account/transfer/subUserHistory', True, data=params) async def make_subaccount_universal_transfer(self, **params): return await self._request_margin_api('post', 'sub-account/universalTransfer', True, data=params) async def get_universal_transfer_history(self, **params): return await self._request_margin_api('get', 'sub-account/universalTransfer', True, data=params) # Futures API async def futures_ping(self): return await self._request_futures_api('get', 'ping') async def futures_time(self): return await self._request_futures_api('get', 'time') async def futures_exchange_info(self): return await self._request_futures_api('get', 'exchangeInfo') async def futures_order_book(self, **params): return await self._request_futures_api('get', 'depth', data=params) async def futures_recent_trades(self, **params): return await self._request_futures_api('get', 'trades', data=params) async def futures_historical_trades(self, **params): return await self._request_futures_api('get', 'historicalTrades', data=params) async def futures_aggregate_trades(self, **params): return await self._request_futures_api('get', 'aggTrades', data=params) async def futures_klines(self, **params): return await self._request_futures_api('get', 'klines', data=params) async def futures_continous_klines(self, **params): return await self._request_futures_api('get', 'continuousKlines', data=params) async def futures_historical_klines(self, symbol, interval, start_str, end_str=None, limit=500): return self._historical_klines(symbol, interval, start_str, end_str=end_str, limit=limit, klines_type=HistoricalKlinesType.FUTURES) async def futures_historical_klines_generator(self, symbol, interval, start_str, end_str=None): return self._historical_klines_generator(symbol, interval, start_str, end_str=end_str, klines_type=HistoricalKlinesType.FUTURES) async def futures_mark_price(self, **params): return await self._request_futures_api('get', 'premiumIndex', data=params) async def futures_funding_rate(self, **params): return await self._request_futures_api('get', 'fundingRate', data=params) async def futures_ticker(self, **params): return await self._request_futures_api('get', 'ticker/24hr', data=params) async def futures_symbol_ticker(self, **params): return await self._request_futures_api('get', 'ticker/price', data=params) async def futures_orderbook_ticker(self, **params): return await self._request_futures_api('get', 'ticker/bookTicker', data=params) async def futures_liquidation_orders(self, **params): return await self._request_futures_api('get', 'forceOrders', signed=True, data=params) async def futures_adl_quantile_estimate(self, **params): return await self._request_futures_api('get', 'adlQuantile', signed=True, data=params) async def futures_open_interest(self, **params): return await self._request_futures_api('get',
<reponame>QBioLab/Nymphscopy import ctypes def PIGCS(dll): # DLL initialization and comm functions # int PI_FUNC_DECL PI_InterfaceSetupDlg(const char* szRegKeyName); dll.PI_InterfaceSetupDlg.argtypes = [ctypes.c_char_p] dll.PI_InterfaceSetupDlg.restype = ctypes.c_int # int PI_FUNC_DECL PI_ConnectRS232(int nPortNr, int iBaudRate); dll.PI_ConnectRS232.argtypes = [ctypes.c_int, ctypes.c_int] dll.PI_ConnectRS232.restype = ctypes.c_int # int PI_FUNC_DECL PI_TryConnectRS232(int port, int baudrate); dll.PI_TryConnectRS232.argtypes = [ctypes.c_int, ctypes.c_int] dll.PI_TryConnectRS232.restype = ctypes.c_int # int PI_FUNC_DECL PI_TryConnectUSB(const char* szDescription); dll.PI_TryConnectUSB.argtypes = [ctypes.c_char_p] dll.PI_TryConnectUSB.restype = ctypes.c_int # BOOL PI_FUNC_DECL PI_IsConnecting(int threadID, BOOL* bCOnnecting); dll.PI_IsConnecting.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_bool)] dll.PI_IsConnecting.restype = ctypes.c_bool # int PI_FUNC_DECL PI_GetControllerID(int threadID); dll.PI_GetControllerID.argtypes = [ctypes.c_int] dll.PI_GetControllerID.restype = ctypes.c_int # BOOL PI_FUNC_DECL PI_CancelConnect(int threadI); dll.PI_CancelConnect.argtypes = [ctypes.c_int] dll.PI_CancelConnect.restype = ctypes.c_bool # int PI_FUNC_DECL PI_ConnectRS232ByDevName(const char* szDevName, int BaudRate); This syntax does not exist, while PI_ConnectRS232details could be found # dll.PI_ConnectRS232ByDevName.argtypes = [ctypes.c_char_p, ctypes.c_int] # dll.PI_ConnectRS232ByDevName.restype = ctypes.c_int # int PI_FUNC_DECL PI_OpenRS232DaisyChain(int iPortNumber, int iBaudRate, int* pNumberOfConnectedDaisyChainDevices, char* szDeviceIDNs, int iBufferSize); dll.PI_OpenRS232DaisyChain.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int), ctypes.c_char_p, ctypes.c_int] dll.PI_OpenRS232DaisyChain.restype = ctypes.c_int # int PI_FUNC_DECL PI_ConnectDaisyChainDevice(int iPortId, int iDeviceNumber); dll.PI_ConnectDaisyChainDevice.argtypes = [ctypes.c_int, ctypes.c_int] dll.PI_ConnectDaisyChainDevice.restype = ctypes.c_int # void PI_FUNC_DECL PI_CloseDaisyChain(int iPortId); dll.PI_CloseDaisyChain.argtypes = [ctypes.c_int] dll.PI_CloseDaisyChain.restype = None # int PI_FUNC_DECL PI_ConnectNIgpib(int nBoard, int nDevAddr); dll.PI_ConnectNIgpib.argtypes = [ctypes.c_int, ctypes.c_int] dll.PI_ConnectNIgpib.restype = ctypes.c_int # int PI_FUNC_DECL PI_ConnectTCPIP(const char* szHostname, int port); dll.PI_ConnectTCPIP.argtypes = [ctypes.c_char_p, ctypes.c_int] dll.PI_ConnectTCPIP.restype = ctypes.c_int # int PI_FUNC_DECL PI_EnableTCPIPScan(int iMask); dll.PI_EnableTCPIPScan.argtypes = [ctypes.c_int] dll.PI_EnableTCPIPScan.restype = ctypes.c_int # int PI_FUNC_DECL PI_EnumerateTCPIPDevices(char* szBuffer, int iBufferSize, const char* szFilter); dll.PI_EnumerateTCPIPDevices.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p] dll.PI_EnumerateTCPIPDevices.restype = ctypes.c_int # int PI_FUNC_DECL PI_ConnectTCPIPByDescription(const char* szDescription); dll.PI_ConnectTCPIPByDescription.argtypes = [ctypes.c_char_p] dll.PI_ConnectTCPIPByDescription.restype = ctypes.c_int # int PI_FUNC_DECL PI_OpenTCPIPDaisyChain(const char* szHostname, int port, int* pNumberOfConnectedDaisyChainDevices, char* szDeviceIDNs, int iBufferSize); dll.PI_OpenTCPIPDaisyChain.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.POINTER(ctypes.c_int), ctypes.c_char_p, ctypes.c_int] dll.PI_OpenTCPIPDaisyChain.restype = ctypes.c_int # int PI_FUNC_DECL PI_EnumerateUSB(char* szBuffer, int iBufferSize, const char* szFilter); dll.PI_EnumerateUSB.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p] dll.PI_EnumerateUSB.restype = ctypes.c_int # int PI_FUNC_DECL PI_ConnectUSB(const char* szDescription); dll.PI_ConnectUSB.argtypes = [ctypes.c_char_p] dll.PI_ConnectUSB.restype = ctypes.c_int # int PI_FUNC_DECL PI_ConnectUSBWithBaudRate(const char* szDescription,int iBaudRate); dll.PI_ConnectUSBWithBaudRate.argtypes = [ctypes.c_char_p, ctypes.c_int] dll.PI_ConnectUSBWithBaudRate.restype = ctypes.c_int # int PI_FUNC_DECL PI_OpenUSBDaisyChain(const char* szDescription, int* pNumberOfConnectedDaisyChainDevices, char* szDeviceIDNs, int iBufferSize); dll.PI_OpenUSBDaisyChain.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_int), ctypes.c_char_p, ctypes.c_int] dll.PI_OpenUSBDaisyChain.restype = ctypes.c_int # BOOL PI_FUNC_DECL PI_IsConnected(int ID); dll.PI_IsConnected.argtypes = [ctypes.c_int] dll.PI_IsConnected.restype = ctypes.c_bool # void PI_FUNC_DECL PI_CloseConnection(int ID); dll.PI_CloseConnection.argtypes = [ctypes.c_int] dll.PI_CloseConnection.restype = None # int PI_FUNC_DECL PI_GetError(int ID); dll.PI_GetError.argtypes = [ctypes.c_int] dll.PI_GetError.restype = ctypes.c_int # BOOL PI_FUNC_DECL PI_SetErrorCheck(int ID, BOOL bErrorCheck); dll.PI_SetErrorCheck.argtypes = [ctypes.c_int, ctypes.c_bool] dll.PI_SetErrorCheck.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_TranslateError(int errNr, char* szBuffer, int iBufferSize); dll.PI_TranslateError.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int] dll.PI_TranslateError.restype = ctypes.c_bool # int PI_FUNC_DECL PI_SetTimeout(int ID, int timeoutInMS); dll.PI_SetTimeout.argtypes = [ctypes.c_int, ctypes.c_int] dll.PI_SetTimeout.restype = ctypes.c_int # int PI_FUNC_DECL PI_SetDaisyChainScanMaxDeviceID(int maxID); dll.PI_SetDaisyChainScanMaxDeviceID.argtypes = [ctypes.c_int] dll.PI_SetDaisyChainScanMaxDeviceID.restype = ctypes.c_int # BOOL PI_FUNC_DECL PI_EnableReconnect(int ID, BOOL bEnable); dll.PI_EnableReconnect.argtypes = [ctypes.c_int, ctypes.c_bool] dll.PI_EnableReconnect.restype = ctypes.c_bool # int PI_FUNC_DECL PI_SetNrTimeoutsBeforeClose(int ID, int nrTimeoutsBeforeClose); dll.PI_SetNrTimeoutsBeforeClose.argtypes = [ctypes.c_int, ctypes.c_int] dll.PI_SetNrTimeoutsBeforeClose.restype = ctypes.c_int # BOOL PI_FUNC_DECL PI_GetInterfaceDescription(int ID, char* szBuffer, int iBufferSize); dll.PI_GetInterfaceDescription.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int] dll.PI_GetInterfaceDescription.restype = ctypes.c_bool # general # BOOL PI_FUNC_DECL PI_qERR(int ID, int* pnError); dll.PI_qERR.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_int)] dll.PI_qERR.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qIDN(int ID, char* szBuffer, int iBufferSize); dll.PI_qIDN.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int] dll.PI_qIDN.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_INI(int ID, const char* szAxes); dll.PI_INI.argtypes = [ctypes.c_int, ctypes.c_char_p] dll.PI_INI.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qHLP(int ID, char* szBuffer, int iBufferSize); dll.PI_qHLP.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int] dll.PI_qHLP.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qHPA(int ID, char* szBuffer, int iBufferSize); dll.PI_qHPA.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int] dll.PI_qHPA.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qHPV(int ID, char* szBuffer, int iBufferSize); dll.PI_qHPV.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int] dll.PI_qHPV.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qCSV(int ID, double* pdCommandSyntaxVersion); dll.PI_qCSV.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_double)] dll.PI_qCSV.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qOVF(int ID, const char* szAxes, BOOL* piValueArray); dll.PI_qOVF.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_bool)] dll.PI_qOVF.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_RBT(int ID); dll.PI_RBT.argtypes = [ctypes.c_int] dll.PI_RBT.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_REP(int ID); dll.PI_REP.argtypes = [ctypes.c_int] dll.PI_REP.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_BDR(int ID, int iBaudRate); dll.PI_BDR.argtypes = [ctypes.c_int, ctypes.c_int] dll.PI_BDR.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qBDR(int ID, int* iBaudRate); dll.PI_qBDR.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_int)] dll.PI_qBDR.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_DBR(int ID, int iBaudRate); dll.PI_DBR.argtypes = [ctypes.c_int, ctypes.c_int] dll.PI_DBR.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qDBR(int ID, int* iBaudRate); dll.PI_qDBR.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_int)] dll.PI_qDBR.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qVER(int ID, char* szBuffer, int iBufferSize); dll.PI_qVER.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int] dll.PI_qVER.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qSSN(int ID, char* szSerialNumber, int iBufferSize); dll.PI_qSSN.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int] dll.PI_qSSN.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_CCT(int ID, int iCommandType); dll.PI_CCT.argtypes = [ctypes.c_int, ctypes.c_int] dll.PI_CCT.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qCCT(int ID, int *iCommandType); dll.PI_qCCT.argtypes = [ctypes.c_int, ctypes.c_int] dll.PI_qCCT.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qTVI(int ID, char* szBuffer, int iBufferSize); dll.PI_qTVI.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int] dll.PI_qTVI.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_IFC(int ID, const char* szParameters, const char* szValues); dll.PI_IFC.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p] dll.PI_IFC.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qIFC(int ID, const char* szParameters, char* szBuffer, int iBufferSize); dll.PI_qIFC.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int] dll.PI_qIFC.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_IFS(int ID, const char* szPassword, const char* szParameters, const char* szValues); dll.PI_IFS.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p] dll.PI_IFS.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qIFS(int ID, const char* szParameters, char* szBuffer, int iBufferSize); dll.PI_qIFS.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int] dll.PI_qIFS.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qECO(int ID, const char* szSendString, char* szValues, int iBufferSize); dll.PI_qECO.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int] dll.PI_qECO.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_MOV(int ID, const char* szAxes, const double* pdValueArray); dll.PI_MOV.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_MOV.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qMOV(int ID, const char* szAxes, double* pdValueArray); dll.PI_qMOV.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_qMOV.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_MVR(int ID, const char* szAxes, const double* pdValueArray); dll.PI_MVR.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_MVR.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_MVE(int ID, const char* szAxes, const double* pdValueArray); dll.PI_MVE.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_MVE.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_POS(int ID, const char* szAxes, const double* pdValueArray); dll.PI_POS.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_POS.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qPOS(int ID, const char* szAxes, double* pdValueArray); dll.PI_qPOS.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_qPOS.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_IsMoving(int ID, const char* szAxes, BOOL* pbValueArray); dll.PI_IsMoving.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_bool)] dll.PI_IsMoving.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_HLT(int ID, const char* szAxes); dll.PI_HLT.argtypes = [ctypes.c_int, ctypes.c_char_p] dll.PI_HLT.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_STP(int ID); dll.PI_STP.argtypes = [ctypes.c_int] dll.PI_STP.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_StopAll(int ID); dll.PI_StopAll.argtypes = [ctypes.c_int] dll.PI_StopAll.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qONT(int ID, const char* szAxes, BOOL* pbValueArray); dll.PI_qONT.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_bool)] dll.PI_qONT.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_RTO(int ID, const char* szAxes); dll.PI_RTO.argtypes = [ctypes.c_int, ctypes.c_char_p] dll.PI_RTO.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qRTO(int ID, const char* szAxes, int* piValueArray); dll.PI_qRTO.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_int)] dll.PI_qRTO.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_ATZ(int ID, const char* szAxes, const double* pdLowvoltageArray, const BOOL* pfUseDefaultArray); dll.PI_ATZ.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_bool)] dll.PI_ATZ.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qATZ(int ID, const char* szAxes, int* piAtzResultArray); dll.PI_qATZ.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_int)] dll.PI_qATZ.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_AOS(int ID, const char* szAxes, const double* pdValueArray); dll.PI_AOS.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_AOS.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qAOS(int ID, const char* szAxes, double* pdValueArray); dll.PI_qAOS.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_qAOS.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_HasPosChanged(int ID, const char* szAxes, BOOL* pbValueArray); dll.PI_HasPosChanged.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_bool)] dll.PI_HasPosChanged.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_GetErrorStatus(int ID, BOOL* pbIsReferencedArray, BOOL* pbIsReferencing, BOOL* pbIsMovingArray, BOOL* pbIsMotionErrorArray); dll.PI_GetErrorStatus.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_bool), ctypes.POINTER(ctypes.c_bool), ctypes.POINTER(ctypes.c_bool), ctypes.POINTER(ctypes.c_bool)] dll.PI_GetErrorStatus.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_SVA(int ID, const char* szAxes, const double* pdValueArray); dll.PI_SVA.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_SVA.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qSVA(int ID, const char* szAxes, double* pdValueArray); dll.PI_qSVA.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_qSVA.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_SVR(int ID, const char* szAxes, const double* pdValueArray); dll.PI_SVR.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_SVR.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_DFH(int ID, const char* szAxes); dll.PI_DFH.argtypes = [ctypes.c_int, ctypes.c_char_p] dll.PI_DFH.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qDFH(int ID, const char* szAxes, double* pdValueArray); dll.PI_qDFH.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_qDFH.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_GOH(int ID, const char* szAxes); dll.PI_GOH.argtypes = [ctypes.c_int, ctypes.c_char_p] dll.PI_GOH.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qCST(int ID, const char* szAxes, char* szNames, int iBufferSize); dll.PI_qCST.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int] dll.PI_qCST.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_CST(int ID, const char* szAxes, const char* szNames); dll.PI_CST.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p] dll.PI_CST.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qVST(int ID, char* szBuffer, int iBufferSize); dll.PI_qVST.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int] dll.PI_qVST.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qPUN(int ID, const char* szAxes, char* szUnit, int iBufferSize); dll.PI_qPUN.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int] dll.PI_qPUN.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_SVO(int ID, const char* szAxes, const BOOL* pbValueArray); dll.PI_SVO.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_bool)] dll.PI_SVO.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qSVO(int ID, const char* szAxes, BOOL* pbValueArray); dll.PI_qSVO.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_bool)] dll.PI_qSVO.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_SMO( int ID, const char* szAxes, const int* piValueArray); dll.PI_SMO.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_int)] dll.PI_SMO.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qSMO(int ID, const char* szAxes, int* piValueArray); dll.PI_qSMO.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_int)] dll.PI_qSMO.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_DCO(int ID, const char* szAxes, const BOOL* pbValueArray); dll.PI_DCO.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_bool)] dll.PI_DCO.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qDCO(int ID, const char* szAxes, BOOL* pbValueArray); dll.PI_qDCO.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_bool)] dll.PI_qDCO.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_BRA(int ID, const char* szAxes, const BOOL* pbValueArray); dll.PI_BRA.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_bool)] dll.PI_BRA.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qBRA(int ID, const char* szAxes, BOOL* pbValueArray); dll.PI_qBRA.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_bool)] dll.PI_qBRA.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_RON(int ID, const char* szAxes, const BOOL* pbValueArray); dll.PI_RON.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_bool)] dll.PI_RON.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qRON(int ID, const char* szAxes, BOOL* pbValueArray); dll.PI_qRON.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_bool)] dll.PI_qRON.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_VEL(int ID, const char* szAxes, const double* pdValueArray); dll.PI_VEL.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_VEL.restype = ctypes.c_bool # BOOL PI_FUNC_DECL PI_qVEL(int ID, const char* szAxes, double* pdValueArray); dll.PI_qVEL.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)] dll.PI_qVEL.restype = ctypes.c_bool # BOOL
# Opencart countries # {"name": "Aaland Islands", "iso_code_2": "AX", "iso_code_3": "ALA"}, # {"name": "Afghanistan", "iso_code_2": "AF", "iso_code_3": "AFG"}, # {"name": "Albania", "iso_code_2": "AL", "iso_code_3": "ALB"}, # {"name": "Algeria", "iso_code_2": "DZ", "iso_code_3": "DZA"}, # {"name": "American Samoa", "iso_code_2": "AS", "iso_code_3": "ASM"}, # {"name": "Andorra", "iso_code_2": "AD", "iso_code_3": "AND"}, # {"name": "Angola", "iso_code_2": "AO", "iso_code_3": "AGO"}, # {"name": "Anguilla", "iso_code_2": "AI", "iso_code_3": "AIA"}, # {"name": "Antarctica", "iso_code_2": "AQ", "iso_code_3": "ATA"}, # {"name": "Antigua and Barbuda", "iso_code_2": "AG", "iso_code_3": "ATG"}, # {"name": "Argentina", "iso_code_2": "AR", "iso_code_3": "ARG"}, # {"name": "Armenia", "iso_code_2": "AM", "iso_code_3": "ARM"}, # {"name": "Aruba", "iso_code_2": "AW", "iso_code_3": "ABW"}, # {"name": "Ascension Island (British)", "iso_code_2": "AC", "iso_code_3": "ASC"}, # {"name": "Australia", "iso_code_2": "AU", "iso_code_3": "AUS"}, # {"name": "Austria", "iso_code_2": "AT", "iso_code_3": "AUT"}, # {"name": "Azerbaijan", "iso_code_2": "AZ", "iso_code_3": "AZE"}, # {"name": "Bahamas", "iso_code_2": "BS", "iso_code_3": "BHS"}, # {"name": "Bahrain", "iso_code_2": "BH", "iso_code_3": "BHR"}, # {"name": "Bangladesh", "iso_code_2": "BD", "iso_code_3": "BGD"}, # {"name": "Barbados", "iso_code_2": "BB", "iso_code_3": "BRB"}, # {"name": "Belarus", "iso_code_2": "BY", "iso_code_3": "BLR"}, # {"name": "Belgium", "iso_code_2": "BE", "iso_code_3": "BEL"}, # {"name": "Belize", "iso_code_2": "BZ", "iso_code_3": "BLZ"}, # {"name": "Benin", "iso_code_2": "BJ", "iso_code_3": "BEN"}, # {"name": "Bermuda", "iso_code_2": "BM", "iso_code_3": "BMU"}, # {"name": "Bhutan", "iso_code_2": "BT", "iso_code_3": "BTN"}, # {"name": "Bolivia", "iso_code_2": "BO", "iso_code_3": "BOL"}, # {"name": "Bonaire, Sint Eustatius and Saba", "iso_code_2": "BQ", "iso_code_3": "BES"}, # {"name": "Bosnia and Herzegovina", "iso_code_2": "BA", "iso_code_3": "BIH"}, # {"name": "Botswana", "iso_code_2": "BW", "iso_code_3": "BWA"}, # {"name": "Bouvet Island", "iso_code_2": "BV", "iso_code_3": "BVT"}, # {"name": "Brazil", "iso_code_2": "BR", "iso_code_3": "BRA"}, # {"name": "British Indian Ocean Territory", "iso_code_2": "IO", "iso_code_3": "IOT"}, # {"name": "<NAME>alam", "iso_code_2": "BN", "iso_code_3": "BRN"}, # {"name": "Bulgaria", "iso_code_2": "BG", "iso_code_3": "BGR"}, # {"name": "Burkina Faso", "iso_code_2": "BF", "iso_code_3": "BFA"}, # {"name": "Burundi", "iso_code_2": "BI", "iso_code_3": "BDI"}, # {"name": "Cambodia", "iso_code_2": "KH", "iso_code_3": "KHM"}, # {"name": "Cameroon", "iso_code_2": "CM", "iso_code_3": "CMR"}, # {"name": "Canada", "iso_code_2": "CA", "iso_code_3": "CAN"}, # {"name": "Canary Islands", "iso_code_2": "IC", "iso_code_3": "ICA"}, # {"name": "Cape Verde", "iso_code_2": "CV", "iso_code_3": "CPV"}, # {"name": "Cayman Islands", "iso_code_2": "KY", "iso_code_3": "CYM"}, # {"name": "Central African Republic", "iso_code_2": "CF", "iso_code_3": "CAF"}, # {"name": "Chad", "iso_code_2": "TD", "iso_code_3": "TCD"}, # {"name": "Chile", "iso_code_2": "CL", "iso_code_3": "CHL"}, # {"name": "China", "iso_code_2": "CN", "iso_code_3": "CHN"}, # {"name": "Christmas Island", "iso_code_2": "CX", "iso_code_3": "CXR"}, # {"name": "Cocos (Keeling) Islands", "iso_code_2": "CC", "iso_code_3": "CCK"}, # {"name": "Colombia", "iso_code_2": "CO", "iso_code_3": "COL"}, # {"name": "Comoros", "iso_code_2": "KM", "iso_code_3": "COM"}, # {"name": "Congo", "iso_code_2": "CG", "iso_code_3": "COG"}, # {"name": "Cook Islands", "iso_code_2": "CK", "iso_code_3": "COK"}, # {"name": "Costa Rica", "iso_code_2": "CR", "iso_code_3": "CRI"}, # {"name": "<NAME>'Ivoire", "iso_code_2": "CI", "iso_code_3": "CIV"}, # {"name": "Croatia", "iso_code_2": "HR", "iso_code_3": "HRV"}, # {"name": "Cuba", "iso_code_2": "CU", "iso_code_3": "CUB"}, # {"name": "Curacao", "iso_code_2": "CW", "iso_code_3": "CUW"}, # {"name": "Cyprus", "iso_code_2": "CY", "iso_code_3": "CYP"}, # {"name": "Czech Republic", "iso_code_2": "CZ", "iso_code_3": "CZE"}, # {"name": "Democratic Republic of Congo", "iso_code_2": "CD", "iso_code_3": "COD"}, # {"name": "Denmark", "iso_code_2": "DK", "iso_code_3": "DNK"}, # {"name": "Djibouti", "iso_code_2": "DJ", "iso_code_3": "DJI"}, # {"name": "Dominica", "iso_code_2": "DM", "iso_code_3": "DMA"}, # {"name": "Dominican Republic", "iso_code_2": "DO", "iso_code_3": "DOM"}, # {"name": "East Timor", "iso_code_2": "TL", "iso_code_3": "TLS"}, # {"name": "Ecuador", "iso_code_2": "EC", "iso_code_3": "ECU"}, # {"name": "Egypt", "iso_code_2": "EG", "iso_code_3": "EGY"}, # {"name": "El Salvador", "iso_code_2": "SV", "iso_code_3": "SLV"}, # {"name": "Equatorial Guinea", "iso_code_2": "GQ", "iso_code_3": "GNQ"}, # {"name": "Eritrea", "iso_code_2": "ER", "iso_code_3": "ERI"}, # {"name": "Estonia", "iso_code_2": "EE", "iso_code_3": "EST"}, # {"name": "Ethiopia", "iso_code_2": "ET", "iso_code_3": "ETH"}, # {"name": "Falkland Islands (Malvinas)", "iso_code_2": "FK", "iso_code_3": "FLK"}, # {"name": "Faroe Islands", "iso_code_2": "FO", "iso_code_3": "FRO"}, # {"name": "Fiji", "iso_code_2": "FJ", "iso_code_3": "FJI"}, # {"name": "Finland", "iso_code_2": "FI", "iso_code_3": "FIN"}, # {"name": "France, Metropolitan", "iso_code_2": "FR", "iso_code_3": "FRA"}, # {"name": "French Guiana", "iso_code_2": "GF", "iso_code_3": "GUF"}, # {"name": "French Polynesia", "iso_code_2": "PF", "iso_code_3": "PYF"}, # {"name": "French Southern Territories", "iso_code_2": "TF", "iso_code_3": "ATF"}, # {"name": "FYROM", "iso_code_2": "MK", "iso_code_3": "MKD"}, # {"name": "Gabon", "iso_code_2": "GA", "iso_code_3": "GAB"}, # {"name": "Gambia", "iso_code_2": "GM", "iso_code_3": "GMB"}, # {"name": "Georgia", "iso_code_2": "GE", "iso_code_3": "GEO"}, # {"name": "Germany", "iso_code_2": "DE", "iso_code_3": "DEU"}, # {"name": "Ghana", "iso_code_2": "GH", "iso_code_3": "GHA"}, # {"name": "Gibraltar", "iso_code_2": "GI", "iso_code_3": "GIB"}, # {"name": "Greece", "iso_code_2": "GR", "iso_code_3": "GRC"}, # {"name": "Greenland", "iso_code_2": "GL", "iso_code_3": "GRL"}, # {"name": "Grenada", "iso_code_2": "GD", "iso_code_3": "GRD"}, # {"name": "Guadeloupe", "iso_code_2": "GP", "iso_code_3": "GLP"}, # {"name": "Guam", "iso_code_2": "GU", "iso_code_3": "GUM"}, # {"name": "Guatemala", "iso_code_2": "GT", "iso_code_3": "GTM"}, # {"name": "Guernsey", "iso_code_2": "GG", "iso_code_3": "GGY"}, # {"name": "Guinea", "iso_code_2": "GN", "iso_code_3": "GIN"}, # {"name": "Guinea-Bissau", "iso_code_2": "GW", "iso_code_3": "GNB"}, # {"name": "Guyana", "iso_code_2": "GY", "iso_code_3": "GUY"}, # {"name": "Haiti", "iso_code_2": "HT", "iso_code_3": "HTI"}, # {"name": "Heard and <NAME> Islands", "iso_code_2": "HM", "iso_code_3": "HMD"}, # {"name": "Honduras", "iso_code_2": "HN", "iso_code_3": "HND"}, # {"name": "Hong Kong", "iso_code_2": "HK", "iso_code_3": "HKG"}, # {"name": "Hungary", "iso_code_2": "HU", "iso_code_3": "HUN"}, # {"name": "Iceland", "iso_code_2": "IS", "iso_code_3": "ISL"}, # {"name": "India", "iso_code_2": "IN", "iso_code_3": "IND"}, # {"name": "Indonesia", "iso_code_2": "ID", "iso_code_3": "IDN"}, # {"name": "Iran (Islamic Republic of)", "iso_code_2": "IR", "iso_code_3": "IRN"}, # {"name": "Iraq", "iso_code_2": "IQ", "iso_code_3": "IRQ"}, # {"name": "Ireland", "iso_code_2": "IE", "iso_code_3": "IRL"}, # {"name": "Isle of Man", "iso_code_2": "IM", "iso_code_3": "IMN"}, # {"name": "Israel", "iso_code_2": "IL", "iso_code_3": "ISR"}, # {"name": "Italy", "iso_code_2": "IT", "iso_code_3": "ITA"}, # {"name": "Jamaica", "iso_code_2": "JM", "iso_code_3": "JAM"}, # {"name": "Japan", "iso_code_2": "JP", "iso_code_3": "JPN"}, # {"name": "Jersey", "iso_code_2": "JE", "iso_code_3": "JEY"}, # {"name": "Jordan", "iso_code_2": "JO", "iso_code_3": "JOR"}, # {"name": "Kazakhstan", "iso_code_2": "KZ", "iso_code_3": "KAZ"}, # {"name": "Kenya", "iso_code_2": "KE", "iso_code_3": "KEN"}, # {"name": "Kiribati", "iso_code_2": "KI", "iso_code_3": "KIR"}, # {"name": "Korea, Republic of", "iso_code_2": "KR", "iso_code_3": "KOR"}, # {"name": "Kosovo, Republic of", "iso_code_2": "XK", "iso_code_3": "UNK"}, # {"name": "Kuwait", "iso_code_2": "KW", "iso_code_3": "KWT"}, # {"name": "Kyrgyzstan", "iso_code_2": "KG", "iso_code_3": "KGZ"}, # {"name": "Lao People's Democratic Republic", "iso_code_2": "LA", "iso_code_3": "LAO"}, # {"name": "Latvia", "iso_code_2": "LV", "iso_code_3": "LVA"}, # {"name": "Lebanon", "iso_code_2": "LB", "iso_code_3": "LBN"}, # {"name": "Lesotho", "iso_code_2": "LS", "iso_code_3": "LSO"}, # {"name": "Liberia", "iso_code_2": "LR", "iso_code_3": "LBR"}, # {"name": "Libyan Arab Jamahiriya", "iso_code_2": "LY", "iso_code_3": "LBY"}, # {"name": "Liechtenstein", "iso_code_2": "LI", "iso_code_3": "LIE"}, # {"name": "Lithuania", "iso_code_2": "LT", "iso_code_3": "LTU"}, # {"name": "Luxembourg", "iso_code_2": "LU", "iso_code_3": "LUX"}, # {"name": "Macau", "iso_code_2": "MO", "iso_code_3": "MAC"}, # {"name": "Madagascar", "iso_code_2": "MG", "iso_code_3": "MDG"}, # {"name": "Malawi", "iso_code_2": "MW", "iso_code_3": "MWI"}, # {"name": "Malaysia", "iso_code_2": "MY", "iso_code_3": "MYS"}, # {"name": "Maldives", "iso_code_2": "MV", "iso_code_3": "MDV"}, # {"name": "Mali", "iso_code_2": "ML", "iso_code_3": "MLI"}, # {"name": "Malta", "iso_code_2": "MT", "iso_code_3": "MLT"}, # {"name": "<NAME>", "iso_code_2": "MH", "iso_code_3": "MHL"}, # {"name": "Martinique", "iso_code_2": "MQ", "iso_code_3": "MTQ"}, # {"name": "Mauritania", "iso_code_2": "MR", "iso_code_3": "MRT"}, # {"name": "Mauritius", "iso_code_2": "MU", "iso_code_3": "MUS"}, # {"name": "Mayotte", "iso_code_2": "YT", "iso_code_3": "MYT"}, # {"name": "Mexico", "iso_code_2": "MX", "iso_code_3": "MEX"}, # {"name": "Micronesia, Federated States of", "iso_code_2": "FM", "iso_code_3": "FSM"}, # {"name": "Moldova, Republic of", "iso_code_2": "MD", "iso_code_3": "MDA"}, # {"name": "Monaco", "iso_code_2": "MC", "iso_code_3": "MCO"}, # {"name": "Mongolia", "iso_code_2": "MN", "iso_code_3": "MNG"}, # {"name": "Montenegro", "iso_code_2": "ME", "iso_code_3": "MNE"}, # {"name": "Montserrat", "iso_code_2": "MS", "iso_code_3": "MSR"}, # {"name": "Morocco", "iso_code_2": "MA", "iso_code_3": "MAR"}, # {"name": "Mozambique", "iso_code_2": "MZ", "iso_code_3": "MOZ"}, # {"name": "Myanmar", "iso_code_2": "MM", "iso_code_3": "MMR"}, # {"name": "Namibia", "iso_code_2": "NA", "iso_code_3": "NAM"}, # {"name": "Nauru", "iso_code_2": "NR", "iso_code_3": "NRU"}, # {"name": "Nepal", "iso_code_2": "NP", "iso_code_3": "NPL"}, # {"name": "Netherlands", "iso_code_2": "NL", "iso_code_3": "NLD"}, # {"name": "Netherlands Antilles", "iso_code_2": "AN", "iso_code_3": "ANT"}, # {"name": "New Caledonia", "iso_code_2": "NC", "iso_code_3": "NCL"}, # {"name": "New Zealand", "iso_code_2": "NZ", "iso_code_3": "NZL"}, # {"name": "Nicaragua", "iso_code_2": "NI", "iso_code_3": "NIC"}, # {"name": "Niger", "iso_code_2": "NE", "iso_code_3": "NER"}, # {"name": "Nigeria", "iso_code_2": "NG", "iso_code_3": "NGA"}, # {"name": "Niue", "iso_code_2": "NU", "iso_code_3": "NIU"}, # {"name": "Norfolk Island", "iso_code_2": "NF", "iso_code_3": "NFK"}, # {"name": "North Korea", "iso_code_2": "KP", "iso_code_3": "PRK"}, # {"name": "Northern Mariana Islands", "iso_code_2": "MP", "iso_code_3": "MNP"}, # {"name": "Norway", "iso_code_2": "NO", "iso_code_3": "NOR"}, # {"name": "Oman", "iso_code_2": "OM", "iso_code_3": "OMN"}, # {"name": "Pakistan", "iso_code_2": "PK", "iso_code_3": "PAK"}, # {"name": "Palau", "iso_code_2": "PW", "iso_code_3": "PLW"}, # {"name": "Palestinian Territory, Occupied", "iso_code_2": "PS", "iso_code_3": "PSE"}, # {"name": "Panama", "iso_code_2": "PA", "iso_code_3": "PAN"}, # {"name": "Papua New Guinea", "iso_code_2": "PG", "iso_code_3": "PNG"}, # {"name": "Paraguay", "iso_code_2": "PY", "iso_code_3": "PRY"}, # {"name": "Peru", "iso_code_2": "PE", "iso_code_3": "PER"}, # {"name": "Philippines", "iso_code_2": "PH", "iso_code_3": "PHL"}, # {"name": "Pitcairn", "iso_code_2": "PN", "iso_code_3": "PCN"}, # {"name": "Poland", "iso_code_2": "PL", "iso_code_3": "POL"}, # {"name": "Portugal", "iso_code_2": "PT", "iso_code_3": "PRT"}, # {"name": "<NAME>", "iso_code_2": "PR", "iso_code_3": "PRI"}, # {"name": "Qatar", "iso_code_2": "QA", "iso_code_3": "QAT"}, # {"name": "Reunion", "iso_code_2": "RE", "iso_code_3": "REU"}, # {"name": "Romania", "iso_code_2": "RO", "iso_code_3": "ROM"}, # {"name": "Russian Federation", "iso_code_2": "RU", "iso_code_3": "RUS"}, # {"name": "Rwanda", "iso_code_2": "RW", "iso_code_3": "RWA"}, # {"name": "Saint Kitts and Nevis", "iso_code_2": "KN", "iso_code_3": "KNA"}, # {"name": "<NAME>", "iso_code_2": "LC", "iso_code_3": "LCA"}, # {"name": "Saint Vincent and the Grenadines", "iso_code_2": "VC", "iso_code_3": "VCT"}, # {"name": "Samoa", "iso_code_2": "WS", "iso_code_3": "WSM"}, # {"name": "San Marino", "iso_code_2": "SM", "iso_code_3": "SMR"}, # {"name": "<NAME>", "iso_code_2": "ST", "iso_code_3": "STP"}, # {"name": "<NAME>", "iso_code_2": "SA", "iso_code_3": "SAU"}, # {"name": "Senegal", "iso_code_2": "SN", "iso_code_3": "SEN"}, # {"name": "Serbia", "iso_code_2": "RS", "iso_code_3": "SRB"}, # {"name": "Seychelles", "iso_code_2": "SC", "iso_code_3": "SYC"}, # {"name": "Sierra Leone",
<filename>biasMetrics/metrics.py class NuancedROC: """Method for calculating nuanced AUR ROC scores to assess model bias. Nuanced AUC ROC scores allow for a closer look into how a classification model performs across any specifed sub-population in the trainging set. There are three different types of nuanced roc metrics included in this class. Subgroup (SG) ROC: This calculates the AUC ROC score for only a specific subgroup of the population. This value can be compared against the overall AUC ROC score for the entire population to see if the model underperforms or overperforms in classifying the subgroup in question. Background Positive Subgroup Negative (BPSN) ROC: This calculates the AUC ROC score for positive (relative to the target) members of the background (non-subgroup) population and negative members of the subgroup population. This value can be compared to see how the model performs at differentiating between positive members on the background population and negative members of the subgroup population. Background Negative Subgroup Positive (BNSP) ROC: This calculates the AUC ROC score for negative (relative to the target) members of the background (non-subgroup) population and positive members of the subgroup population. This value can be compared to see how the model performs at differentiating between negative members on the background population and positive members of the subgroup population. Read more about how to compare scores in "Nuanced Metrics for Measuring Unintended Bias with Real Data for Text Classification" by <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. https://arxiv.org/abs/1903.04561 Methods ---------- score : Calculates nuanced roc scores for all given parameters and and returns a heat map with the scores for each subpopulation. Attributes ---------- mean_SG_roc : Returns the mean of the SG ROCs for all subgroups. mean_BPSN_roc : Returns the mean of the BPSN ROCs for all subgroups. mean_BNSP_roc : Returns the mean of the BNSP ROCs for all subgroups. mean_roc : Returns the weighted mean of the SG, BPSN, and BNSP scores for all specified subgroups. summary : Prints out all the scores for each subgroup. """ def __init__(self): import pandas as pd self.output_df = pd.DataFrame() def score(self, y_true, y_probs, subgroup_df, output=True): """Parameters ---------- y_true : pandas Series, pandas DataFrame The true values for all observations. y_pred : pandas Series, pandas DataFrame The model's predicted values for all observations. subgroup_df : pandas DataFrame Dataframe of all subgroups to be compared. Each column should be a specific subgroup with 1 to indicating the observation is a part of the subgroup and 0 indicating it is not. There should be no other values besides 1 or 0 in the dataframe.""" import numpy as np import pandas as pd from sklearn.metrics import roc_auc_score def calc_SG_roc(parameter, df): SG = df.loc[df[parameter] == 1] SG_roc = roc_auc_score(y_true=SG.target, y_score=SG['probs']) return SG_roc # define functions to calculate specific ROC AUC for subpopulations within the data def calc_BPSN_roc(parameter, df): BPSN = df[((df.target == 1) & (df[parameter] == 0)) | ((df.target == 0) & (df[parameter] == 1))] BPSN_roc = roc_auc_score(y_true=BPSN.target, y_score=BPSN['probs']) return BPSN_roc def calc_BNSP_roc(parameter, df): BNSP = df[((df.target == 0) & (df[parameter] == 0)) | ((df.target == 1) & (df[parameter] == 1))] BNSP_roc = roc_auc_score(y_true=BNSP.target, y_score=BNSP['probs']) return BNSP_roc # ensure that the passed dataframe has an appropriate axis subgroup_df.reset_index(drop=True, inplace=True) # ensure input true and prob values are formatted correctly if type(y_true) == pd.core.frame.DataFrame: y_true.columns = ['target'] y_true.reset_index(drop=True, inplace=True) else: y_true = pd.DataFrame(y_true, columns=['target']).reset_index(drop=True) if type(y_probs) == pd.core.frame.DataFrame: y_probs.columns = ['probs'] y_probs.reset_index(drop=True, inplace=True) else: y_probs = pd.DataFrame(y_probs, columns=['probs']).reset_index(drop=True) # combine all inputs into a DataFrame input_df = pd.concat([y_true, y_probs, subgroup_df], axis=1) # build dataframe and fill with ROC AUC metrics self.output_df = pd.DataFrame(index=subgroup_df.columns, columns=['SG-ROC', 'BPSN-ROC', 'BNSP-ROC']) for col in subgroup_df.columns: self.output_df.loc[col] = [calc_SG_roc(col, input_df), calc_BPSN_roc(col, input_df), calc_BNSP_roc(col, input_df)] self.model_roc = roc_auc_score(y_true=y_true, y_score=y_probs) self.mean_SG_roc = self.output_df['SG-ROC'].mean() self.mean_BPSN_roc = self.output_df['BPSN-ROC'].mean() self.mean_BNSP_roc = self.output_df['BNSP-ROC'].mean() self.mean_bias_roc = np.mean([self.output_df['SG-ROC'].mean(), self.output_df['BPSN-ROC'].mean(), self.output_df['BNSP-ROC'].mean()]) if output: import seaborn as sns print(f'Model ROC: {round(self.model_roc, 3)}') sns.heatmap(self.output_df.astype('float32'), center = self.model_roc, cmap='RdYlGn', annot = True, linewidths=2 ); def summary(self): print(f'Model ROC: {self.model_roc}') print() print(f'Mean Bias ROC: {self.mean_bias_roc}') print() print(f'Mean SG ROC: {self.mean_SG_roc}') print() print(f'Mean BPSN ROC: {self.mean_BPSN_roc}') print() print(f'Mean BNSP ROC: {self.mean_BNSP_roc}') print() print(self.output_df) class AEG: """Method for calculating the Average Equality Gap (AEG) for true positive rates (TPR) from a subpopulation and the background population to assess model bias. AEG scores allow a closer look into how a binary classification model performs across any specified subpopulation in the dataset. It compares how the difference between TPR for a subpopulation the background population across all probability thresholds. A perfectly balanced model will have a score of 0, indicating there is no difference in the TPR between the two populations. A total imbalance in the model will result in a score of 0.5 or -0.5, depending on the direction of the skew. In this case all scores are interpreted relative to the subpopulation. Positive scores indicate the model skews towards the subpopulation and negative scores indicate the model skews away from the subpopulation. Conceptually this is difference between the curve of the rates (x(t)) and the line y = x (y(t)) calculated as the integral (0, 1) of x(t) - y(t). This class makes use of a simplified closed-form solution using the Mann Whitney U test. There are two different AEG metrics included in this class. Positive AEG: Calculates the average distance between the TPRs for all members of the subpopulation and background population in the target class (1). Positive scores indicate a rightward shift in the subpopulation and a tendency for the model to produce false positives. Negative scores indicate a leftward shift in the subpopulation and a tendency for the model to produce false negatives. Negative AEG: Calculates the average distance between the TPRs for all members of the subpopulation and background population in the non-target class (0). Positive scores indicate a rightward shift in the subpopulation and a tendency for the model to produce false positives. Negative scores indicate a leftward shift in the subpopulation and a tendency for the model to produce false negatives. Read more about how to compare scores in "Nuanced Metrics for Measuring Unintended Bias with Real Data for Text Classification" by <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. https://arxiv.org/abs/1903.04561 Methods ---------- score : Calculates positive and negative AEG scores for all given parameters and returns a heat map with the scores for each subpopulation. """ def __init__(self): import pandas as pd self.output_df = pd.DataFrame() def score(self, y_true, y_probs, subgroup_df, output=True): """Parameters ---------- y_true : pandas Series, pandas DataFrame The true values for all observations. y_pred : pandas Series, pandas DataFrame The model's predicted values for all observations. subgroup_df : pandas DataFrame Dataframe of all subgroups to be compared. Each column should be a specific subgroup with 1 to indicating the observation is a part of the subgroup and 0 indicating it is not. There should be no other values besides 1 or 0 in the dataframe. output : boolean (default = True) If true returns a heatmap of the AEG scores. """ import numpy as np import pandas as pd from scipy.stats import mannwhitneyu def calc_pos_aeg(parameter, df): sub_probs = df[((df.target == 1) & (df[parameter] == 1))]['probs'] back_probs = df[((df.target == 1) & (df[parameter] == 0))]['probs'] pos_aeg = (.5 - (mannwhitneyu(sub_probs, back_probs)[0] / (len(sub_probs)*len(back_probs)))) return round(pos_aeg, 2) def calc_neg_aeg(parameter, df): sub_probs = df[((df.target == 0) & (df[parameter] == 1))]['probs'] back_probs = df[((df.target == 0) & (df[parameter] == 0))]['probs'] neg_aeg = (.5 - (mannwhitneyu(sub_probs, back_probs)[0] / (len(sub_probs)*len(back_probs)))) return round(neg_aeg, 2) # ensure that the passed dataframe
<reponame>inesmersak/minesweeper<filename>minolovec.py from tkinter import * from tkinter import messagebox from PIL import Image, ImageTk from polje import * import racunalnik import random import threading # array barv za stevilke na polju BARVE = {1: '#8B00FF', 2: '#4B0082', 3: '#0000FF', 4: '#20A106', 5: '#F2CB1D', 6: '#FF7F00', 7: '#FF0000', 8: '#000000', 9: '#000000'} class Minesweeper(): def __init__(self, master, velikost, mine): self.velikost = velikost # velikost kvadratnega igralnega polja self.kvadratek = 30 # velikost enega kvadratka na igralnem polju self.mine = mine # stevilo min self.polje = [[Polje(j, i) for i in range(self.velikost)] for j in range(self.velikost)] self.preostale_mine = IntVar(value=self.mine) self.zmage = IntVar(0) self.porazi = IntVar(0) self.gameactive = True # ali igra poteka self.odprta_polja = [] # vsa trenutno odprta polja self.zaprta_polja = [(i, j) for i in range(self.velikost) for j in range(self.velikost)] # vsa trenutno zaprta # polja self.zastave = [] # vsa polja, ki so trenutno oznacena z zastavico # --- INTELIGENCA --- self.vlakno = None self.inteligenca = None self.p = None # poteza self.pomoc = True # ali igralec zeli pomoc racunalnika ali ne self.zakasnitev = 30 # zakasnitev risanja potez racunalnika # --- GUI --- self.master = master # da ga lahko kasneje unicimo self.ozadje = '#BABABA' # barva ozadja polj zastava = Image.open('flag_small.png') self.zastava = ImageTk.PhotoImage(zastava) # nalozimo sliko zastave bomba = Image.open('bomb_small.png') self.bomba = ImageTk.PhotoImage(bomba) # nalozimo sliko mine self.nastavitve = None # okno z nastavitvami self.maxvelikost = 30 # maksimalna velikost, ki jo bo uporabnik lahko izbral pri nastavitvah self.izbrana_velikost = None # velikost, ki jo je uporabnik izbral self.izbrane_mine = None # stevilo min, ki jih bo uporabnik izbral self.izbran_igralec = None # ali bo uporabnik izbral resevanje s pomocjo racunalnika master.title('Minolovec') okvir = Frame(master) okvir.grid() menu = Menu(master) master.config(menu=menu) podmenu = Menu(menu) podmenu.add_command(label='Nova igra [F1]', command=self.nova_igra) podmenu.add_command(label='Nastavitve [F2]', command=self.okno_z_nastavitvami) podmenu.add_separator() podmenu.add_command(label='Izhod [Esc]', command=self.izhod) menu.add_cascade(label='File', menu=podmenu) Label(okvir, text='Zmage: ').grid(row=0, column=0) Label(okvir, textvariable=self.zmage).grid(row=0, column=1, sticky='W') Label(okvir, text='Porazi: ').grid(row=1, column=0) Label(okvir, textvariable=self.porazi).grid(row=1, column=1, sticky='W') Label(okvir, text='Preostale mine: ').grid(row=2, column=0, sticky='S') Label(okvir, textvariable=self.preostale_mine).grid(row=2, column=1, sticky='WS') self.poteza_racunalnika = Button(okvir, text='Namig', command=self.prepusti_racunalniku) self.poteza_racunalnika.grid(row=0, column=2, rowspan=3) self.platno = Canvas(okvir, width=self.velikost*self.kvadratek, height=self.velikost*self.kvadratek, background='#FFFFFF', bd=1, highlightthickness=1, highlightbackground='#000000') self.platno.grid(row=3, column=0, columnspan=3) self.narisi_mrezo() self.platno.bind("<Button-1>", self.klik) self.platno.bind("<Button-3>", self.klik) master.bind("<F1>", self.nova_igra) master.bind("<F2>", self.okno_z_nastavitvami) master.bind("<Escape>", self.izhod) self.okno_z_nastavitvami() # *********************** # PRIPRAVA IGRE # *********************** def spremeni_stevilko_polj(self, x, y): """ Spremeni stevilko polj okoli mine, ta je podana s koordinatami x in y. """ for z in range(max(0, x-1), min(x+2, self.velikost)): for w in range(max(0, y-1), min(y+2, self.velikost)): if self.polje[z][w].vrednost != 'x': self.polje[z][w].vrednost += 1 def napolni(self): """ Nakljucno napolni igralno polje s 'self.mine' stevilom min. Mine so oznacene z x, prazni kvadratki z 0. """ i = self.mine prazno = [(x, y) for x in range(self.velikost) for y in range(self.velikost)] while i > 0: (x, y) = random.choice(prazno) prazno.remove((x, y)) self.polje[x][y].vrednost = 'x' self.spremeni_stevilko_polj(x, y) i -= 1 def nova_igra(self, *args): """ Resetira vse spremenljivke in pripravi novo igro. """ if self.vlakno is not None: self.vlakno.join() self.polje = [[Polje(j, i) for i in range(self.velikost)] for j in range(self.velikost)] self.napolni() self.preostale_mine.set(self.mine) self.platno.delete(ALL) self.platno.config(width=self.velikost*self.kvadratek, height=self.velikost*self.kvadratek) self.narisi_mrezo() self.gameactive = True self.zaprta_polja = [(i, j) for i in range(self.velikost) for j in range(self.velikost)] self.odprta_polja = [] self.zastave = [] # self.prikazi_celotno_polje(True) # prikazovanje celotnega polja za debugiranje if self.pomoc: self.platno.after(self.zakasnitev, self.prepusti_racunalniku) # *********************** # NASTAVITEV IGRE # *********************** def ponastavi(self, *args): """ Ponastavi parametre igre glede na podatke, vnešene v okno z nastavitvami. Klice se ob kliku na gumb 'V redu' ali ob pritisku na <Enter> znotraj okna z nastavitvami. """ try: m = int(self.izbrane_mine.get()) v = int(self.izbrana_velikost.get()) if m > v ** 2: messagebox.showerror('Nepravilno število min', 'Vnešeno število min je večje od površine polja!') self.nastavitve.focus() self.izbrana_velikost.focus() elif v > self.maxvelikost: messagebox.showerror('Prevelika velikost polja', 'Prosim, vnesite velikost med 1 in {0}!'.format( self.maxvelikost)) self.nastavitve.focus() self.izbrana_velikost.focus() else: self.velikost = v self.mine = m self.pomoc = True if self.izbran_igralec.get() else False if self.pomoc: self.poteza_racunalnika.grid_remove() else: self.poteza_racunalnika.grid() self.nastavitve.destroy() self.gameactive = True self.nova_igra() except ValueError: messagebox.showerror('Nepravilna vrednost', 'Vnesli ste nepravilno vrednost!') self.nastavitve.focus() self.izbrana_velikost.focus() def posodobi_max_stevilo_min(self): """ Glede na vneseno velikost polja posodobi zgornjo mejo za stevilo min v oknu za nastavitve. """ velikost = int(self.izbrana_velikost.get()) self.izbrane_mine.config(to=velikost**2) def okno_z_nastavitvami(self, *args): """ Odpre okno z nastavitvami. """ self.nastavitve = Toplevel() self.nastavitve.title('Nastavitve') self.nastavitve.transient(self.master) # poskrbi, da je okno z nastavitvami vedno nad glavnim oknom self.nastavitve.focus() self.gameactive = False trenutna_velikost = StringVar() trenutna_velikost.set(self.velikost) Label(self.nastavitve, text='Velikost polja: ').grid(row=0, column=0, sticky='W') self.izbrana_velikost = Spinbox(self.nastavitve, from_=2, to=self.maxvelikost, textvariable=trenutna_velikost, command=self.posodobi_max_stevilo_min) self.izbrana_velikost.grid(row=0, column=1) self.izbrana_velikost.focus() trenutne_mine = StringVar() trenutne_mine.set(self.mine) Label(self.nastavitve, text='Število min: ').grid(row=1, column=0, sticky='W') self.izbrane_mine = Spinbox(self.nastavitve, from_=1, to=int(self.izbrana_velikost.get())**2, textvariable=trenutne_mine) self.izbrane_mine.grid(row=1, column=1) self.izbran_igralec = IntVar() self.izbran_igralec.set(1 if self.pomoc else 0) Checkbutton(self.nastavitve, text='Igro naj rešuje računalnik', var=self.izbran_igralec).grid(row=2, column=0, columnspan=2) Button(self.nastavitve, text='V redu', command=self.ponastavi).grid(row=3, column=1) self.nastavitve.bind("<Return>", self.ponastavi) def izhod(self, *args): """ Poskrbi za unicenje threada in glavnega okna ob izhodu iz igre. """ if self.vlakno is not None: self.vlakno.join() self.master.destroy() # *********************** # <NAME> # *********************** def poteza(self, p): """ Sprejme potezo p in jo izvede. """ (x, y, m) = p if self.gameactive: if m: # če je m True, je uporabnik kliknil z desno tipko, torej oznacimo polje z zastavo ozn = self.polje[x][y].oznaci() if ozn: # polje smo uspesno oznacili self.narisi_mino(x, y) mine = self.preostale_mine.get() if (x, y) in self.zastave: self.zastave.remove((x, y)) self.zaprta_polja.append((x, y)) self.preostale_mine.set(mine + 1) else: self.zaprta_polja.remove((x, y)) self.zastave.append((x, y)) self.preostale_mine.set(mine - 1) self.preveri() else: # sicer polje odpremo if not self.polje[x][y].flagged: self.odpri_blok((x, y)) self.preveri() if self.gameactive and self.pomoc: self.platno.after(self.zakasnitev, self.prepusti_racunalniku) # ce igro resuje racunalnik, # potem ponovno poklicemo metodo, ki od racunalnika pridobi novo potezo def odpri_blok(self, koord): """ Sprejme tuple koord s koordinatami, kamor je uporabnik levo-kliknil (kjer je prazno polje), in odpre vsa sosednja polja, ce je stevilo min v okolici polja 0. Postopek ponavlja za vsako polje, ki se odpre, dokler ne naleti na polje, ki ima v okolici kaksno mino. """ checked = [koord] odpri = [koord] while odpri: x, y = odpri.pop() odpr = self.polje[x][y].odpri() if odpr: self.narisi_polje(x, y) if self.polje[x][y].prikaz == 'x': self.preveri(mina=True) break self.zaprta_polja.remove((x, y)) self.odprta_polja.append((x, y)) checked.append((x, y)) if self.polje[x][y].vrednost == 0: for i in range(max(0, x - 1), min(x + 2, self.velikost)): for j in range(max(0, y - 1), min(y + 2, self.velikost)): if not self.polje[i][j].odprto and not (i, j) in checked: odpri.append((i, j)) def polno(self): """ Preveri, ali je igralno polje zapolnjeno. """ if self.zaprta_polja: return False return True def preveri(self, mina=False): """ Preveri, ali je igre konec. Neobvezen parameter mina pove, ali je bila metoda poklicana, ker je igralec stopil na mino. """ polno = self.polno() if mina: self.gameactive = False self.porazi.set(self.porazi.get() + 1) elif polno and self.preostale_mine.get() == 0: # polje je pravilno izpolnjeno self.gameactive = False self.zmage.set(self.zmage.get() + 1) # *********************** # INPUT # *********************** def klik(self, klik): """ Metoda, ki je bindana na levi in desni klik miske. Ce igra poteka, naredi potezo glede na to, ali je uporabnik kliknil levo ali desno tipko. """ if self.gameactive and not self.pomoc: # uporabnik lahko klikne, ce igra poteka in ce je ne resuje racunalnik y = klik.x // self.kvadratek x = klik.y // self.kvadratek if x < self.velikost and y < self.velikost: # uporabnik je kliknil znotraj polja flag = True if klik.num == 3 else False # ali je uporabnik kliknil z desno ali levo tipko miske self.poteza((x, y, flag)) # *********************** # RISANJE # *********************** def narisi_mrezo(self): """ Narise mrezo na Canvasu. """ for i in range(1, self.velikost): self.platno.create_line(i * self.kvadratek, 0, i * self.kvadratek, self.velikost * self.kvadratek) self.platno.create_line(0, i * self.kvadratek, self.velikost * self.kvadratek, i * self.kvadratek) def narisi_polje(self, x, y): """ Narise kvadratek s stevilko. """ kvad = self.izracunaj_kvadratek(x, y) self.platno.create_rectangle(*kvad, fill=self.ozadje) stevilka = self.polje[x][y].vrednost sredina = self.izracunaj_sredino_kvadratka(x, y) if stevilka == 'x': self.platno.create_rectangle(*kvad, fill='#FF0000') self.platno.create_image(sredina, image=self.bomba) elif stevilka != 0: barva = BARVE[stevilka] self.platno.create_text(sredina, text=stevilka, font=('Arial', 14, 'bold'), fill=barva) def narisi_mino(self, x, y): """ Ali narise ali zbrise zastavico na polje. """ flag = self.polje[x][y].flagged # polje smo ze oznacili/odznacili, treba ga je samo
# /*********************************************************************** # # This file is part of KEEL-software, the Data Mining tool for regression, # classification, clustering, pattern mining and so on. # # Copyright (C) 2004-2010 # # <NAME> (<EMAIL>) # <NAME> (<EMAIL>) # <NAME> (<EMAIL>) # <NAME> (<EMAIL>) # <NAME> (<EMAIL>) # <NAME> (<EMAIL>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/ # # **********************************************************************/ # /* # * Attributes.java # * # * Created on 20 de junio de 2004, 10:06 # */ from skltemplate.help_classes.Attribute import Attribute # /** # * <p> # * <b> Attributes </b> # * </p> # * # * This class is a static class that, basically, contains a Vector of defined # * attributes in the train file. Although it keeps all the attributes, it divides # * them in two groups, the input attributes and the output attributes. It could # * be that, depending on the @inputs and @outputs defined in the train file, some # * of the attributes are not valid, so, their values are not loaded to the API # * dataset. Even in this case, the non-careful attributes information is mantained # * in this static class. # * # * @author <NAME> # * @see Attribute # * @version keel0.1 # */ class Attributes: # # ///////////////////////////////////////////////////////////////////////////// # /////////////// ATTRIBUTES OF THE ATTRIBUTES CLASS ////////////////////////// # ///////////////////////////////////////////////////////////////////////////// # # /** # * It contains all the attributes definitions. # */ attributes = [] # /** # * It contains a reference to all input attributes. # */ inputAttr = [] # /** # * It contains a reference to all output attributes. # */ outputAttr = [] # /** # * It contains a reference to all undefined attributes. # */ undefinedAttr = [] # /** # * A flag indicating if the vector contains any nominal attribute. # */ hasNominal = False # # /** # * A flag indicating if the vector contains any integer attribute. # */ hasInteger = False # /** # * A flag indicating if the vector contains any real attribute. # */ hasReal = False # /** # * It indicates if there are missing values # */ hasMissing = False # /** # * A vector containing the types of each attribute. # */ #private static int []type; # /** # * String that keeps the relation name # */ relationName = "" # ///////////////////////////////////////////////////////////////////////////// # ///////////////// METHODS OF THE ATTRIBUTES CLASS /////////////////////////// # ///////////////////////////////////////////////////////////////////////////// # /** # * clearAll # * This method clears all the static members of the class. # * It is used when another data set is wanted to be loaded # */ def clearAll(self): self.attributes = [] self.inputAttr = [] self.outputAttr = [] self.undefinedAttr = [] self.hasNominal = False self.hasInteger = False self.hasReal = False self.hasMissing = False self.relationName = None #end clearAll # /** # * This method adds an attribute definition. # * @param attr is the new attribute to be added. # */ def addAttribute(self, attr): print("In addAttribute,addAttribute begin......") print(attr) if(not self.isExistent(self,attr)): self.attributes.append(attr) attType = attr.getType() print("Attribute type is :" + str(attType)) if(attType==Attribute.NOMINAL): self.hasNominal= True print("hasNominal is true") elif(attType==Attribute.INTEGER) : self.hasInteger= True print("hasInteger is true") elif(attType==Attribute.REAL): self.hasReal = True print("hasReal is true") numberAttribute=len(self.attributes) print("There are " + str(numberAttribute) + "attribute in Attribute class") for attr in self.attributes: attr_name = attr.getName() print("attr name is :"+ str(attr_name)) #end addAttribute # * The function returns true if the attribute is existent, # will return True else return False otherwise. # */ def isExistent(self,attr): result = False for attrExistent in self.attributes: if attr.getName()==attrExistent.getName(): result = True break return result #end isExistent # /** # * The function returns if there is any nominal attribute # * @return True if there is any nominal attribute, False otherwise. # */ def hasNominalAttributes(self): return self.hasNominal #end hasNominalAttributes # /** # * The function returns if there is any integer attribute. # * @return True if there is any integer attribute, False otherwise. # */ def hasIntegerAttributes(self): return self.hasInteger #end hasIntegerAttributes # /** # * The function returns if there is any real attribute. # * @returnTrue if there is any real attribute, False otherwise. # */ def hasRealAttributes(self): return self.hasReal #end hasRealAttributes # /** # * The function returns if there is any missing value # * @return if there is any missing value, False otherwise. # */ def hasMissingValues(self): return self.hasMissing #end hasMissingValues # /** # * It returns the attribute requested. # * @param _name is the name of the attribute. # * @return the attribute requested. # */ def getAttributeByName(self,_name): print("Begin getAttribute ......") size=len(self.attributes) stopPos=0 for i in range (0,size): print("size of attributes = "+ str(size)) attribute = self.attributes[i] if attribute.getName()==_name: stopPos = i break if (stopPos == size) : return None return attribute #end getAttribute # /** # * It does return an array with all attributes # * @return an array with all attributes # */ def getAttributes(self): if (len(self.attributes) == 0): return None attr = [Attribute() for x in range (0, len(self.attributes))] for i in range(0, len(attr)): attr[i] = self.attributes[i] return attr #end getAttribute # /** # * It returns the input attribute being int the position passed as an argument. # * @param pos is the position of the attribute wanted. # * @return the input attribute being int the position passed as an argument. # */ def getInputAttribute(self, pos): print("pos is :" + str(pos)+ ",self.inputAttr"+ str(self.inputAttr)) if pos<0 or pos >= len(self.inputAttr): print("Return None for getInputAttribute !!!") return None return self.inputAttr[pos] #end getInputAttribute # /** # * It does return all the input attributes # * @return all the input attributesgetOutputHeader # */ def getInputAttributes(self): if (len(self.inputAttr) == 0) : return None attr = [Attribute() for x in range (0, len(self.inputAttr))] for i in range (0, len(attr)): attr[i] = self.inputAttr[i] return attr #end getInputAttribute # /** # * It does return an String with the @inputs in keel format. # * @return an string with the @inputs definition . # */ def getInputHeader(self): aux = "@inputs " ending = "," for i in range(0, len(self.inputAttr)): if (i == len(self.inputAttr) - 1): ending = "" attribute=self.inputAttr[i] aux += (attribute).getName() + ending return aux #end getInputHeader # /** # * It does return a String with all the input attributes definition in keel # * format. The order of the attributes is the order of lecture. # * @return a String with the input attributes definition. # */ def getInputAttributesHeader(self): aux = "" for i in range (0, len(self.inputAttr)): #Writting the name and type of the attribute aux += self.inputAttr[i].toString()+"\n" return aux #end getInputAttributesHeader # # /** # * It does return all the output attributes. # * @return all the output attributes. # */ def getOutputAttributes(self): print("get Output Attributes in Attributes begin.......") if len(self.outputAttr) == 0: print("The output attributes are 0:") return None else: attr= [Attribute() for x in range(0,len(self.outputAttr))] for i in range(0,len(self.outputAttr)): attr[i]=self.outputAttr[i] return self.outputAttr #end outputAttributes # /* # * It returns the output attribute being int the position passed as an argument. # * @param pos is the position of the attribute wanted. # * @return the output attribute being int the position passed as an argument. # */ def getOutputAttribute(self,pos): if pos<0 or pos >= len(self.outputAttr): return None return self.outputAttr[pos] #end getOutputAttribute # /** # * It does return an String with the @outputs in keel format. # * @return an string with the @outputs definition . # */ def getOutputHeader(self): aux = "@outputs " ending = "," for i in range (0, len(self.outputAttr)): if (i == len(self.outputAttr) - 1): ending=" " aux = aux+ self.outputAttr[i].getName() + ending return aux #end getOutputHeader # /** # * It does return a String with all the output attributes definition in keel # * format. The order of the attributes is the order of lecture. # * @return a String with the output attributes definition. # */ def getOutputAttributesHeader(self): aux = "" for i in range
<gh_stars>10-100 import abc import enum import functools import itertools import json import pathlib import shutil import subprocess from collections import defaultdict from enum import Enum from logging import getLogger from subprocess import PIPE from typing import * from onlinejudge_verify.config import get_config from onlinejudge_verify.languages import special_comments from onlinejudge_verify.languages.models import Language, LanguageEnvironment logger = getLogger(__name__) _metadata_by_manifest_path: Dict[pathlib.Path, Dict[str, Any]] = {} _cargo_checked_workspaces: Set[pathlib.Path] = set() _related_source_files_by_workspace: Dict[pathlib.Path, Dict[pathlib.Path, FrozenSet[pathlib.Path]]] = {} class _ListDependenciesBackend: @abc.abstractmethod def list_dependencies(self, path: pathlib.Path, *, basedir: pathlib.Path) -> List[pathlib.Path]: raise NotImplementedError class _NoBackend(_ListDependenciesBackend): def list_dependencies(self, path: pathlib.Path, *, basedir: pathlib.Path) -> List[pathlib.Path]: return _list_dependencies_by_crate(path, basedir=basedir, cargo_udeps_toolchain=None) class _CargoUdeps(_ListDependenciesBackend): toolchain: str = 'nightly' def __init__(self, *, toolchain: Optional[str]): if toolchain is not None: self.toolchain = toolchain def list_dependencies(self, path: pathlib.Path, *, basedir: pathlib.Path) -> List[pathlib.Path]: return _list_dependencies_by_crate(path, basedir=basedir, cargo_udeps_toolchain=self.toolchain) @functools.lru_cache(maxsize=None) def _list_dependencies_by_crate(path: pathlib.Path, *, basedir: pathlib.Path, cargo_udeps_toolchain: Optional[str]) -> List[pathlib.Path]: """The `list_dependencies` implementation for `_NoBackend` and `CargoUdeps`. :param path: A parameter in `Language.list_dependencies`. :param basedir: A parameter in `Language.list_dependencies`. :param cargo_udeps_toolchain: A Rust toolchain name for cargo-udeps. If it is `None`, we don't run cargo-udeps. :returns: Paths to the `.rs` files for `Language.list_dependencies`. """ path = basedir / path # We regard that a generated file does not depend on any files. for parent in path.parents: if (parent.parent / 'Cargo.toml').exists() and parent.parts[-1] == 'target': logger.warning('This is a generated file!: %s', path) return [path] metadata = _cargo_metadata(cwd=path.parent) # First, collects source files in the same crate. common_result = set(_source_files_in_same_targets(path, _related_source_files(basedir, metadata))) main_package_and_target = _find_target(metadata, path) if not main_package_and_target: return sorted(common_result) main_package, main_target = main_package_and_target packages_by_id = {p['id']: p for p in metadata['packages']} class DependencyNamespace(Enum): NORMAL_DEVELOPMENT = enum.auto() BUILD = enum.auto() @classmethod def from_dep_kind(cls, kind: str): if kind == 'build': return cls.BUILD return cls.NORMAL_DEVELOPMENT # Collect the `(|dev-|build-)dependencies` into a <is a `build-dependency`> → (<"extern crate name"> → <package>) dictionary. dependencies: DefaultDict[DependencyNamespace, Dict[str, Dict[str, Any]]] = defaultdict(dict) for dep in next(n['deps'] for n in metadata['resolve']['nodes'] if n['id'] == main_package['id']): if _need_dev_deps(main_target) or any(k['kind'] is None for k in dep['dep_kinds']): dependencies[DependencyNamespace.NORMAL_DEVELOPMENT][dep['name']] = packages_by_id[dep['pkg']] if any(k['kind'] == 'build' for k in dep['dep_kinds']): dependencies[DependencyNamespace.BUILD][dep['name']] = packages_by_id[dep['pkg']] # If `cargo_udeps_toolchain` is present, collects packages that are "unused" by `target`. unused_packages = defaultdict(set) if cargo_udeps_toolchain is not None: explicit_names_in_toml = {(DependencyNamespace.from_dep_kind(d['kind']), d['rename']) for d in main_package['dependencies'] if d['rename']} if not shutil.which('cargo-udeps'): raise RuntimeError('`cargo-udeps` not in $PATH') unused_deps = json.loads(subprocess.run( ['rustup', 'run', cargo_udeps_toolchain, 'cargo', 'udeps', '--output', 'json', '--manifest-path', main_package['manifest_path'], *_target_option(main_target)], cwd=metadata['workspace_root'], check=False, stdout=PIPE, ).stdout.decode())['unused_deps'].values() unused_dep = next((u for u in unused_deps if u['manifest_path'] == main_package['manifest_path']), None) if unused_dep: names_in_toml = [(DependencyNamespace.NORMAL_DEVELOPMENT, name_in_toml) for name_in_toml in [*unused_dep['normal'], *unused_dep['development']]] names_in_toml.extend((DependencyNamespace.BUILD, name_in_toml) for name_in_toml in unused_dep['build']) for dependency_namespace, name_in_toml in names_in_toml: if (dependency_namespace, name_in_toml) in explicit_names_in_toml: # If the `name_in_toml` is explicitly renamed one, it equals to the `extern_crate_name`. unused_package = dependencies[dependency_namespace][name_in_toml]['id'] else: # Otherwise, it equals to the `package.name`. unused_package = next(p['id'] for p in dependencies[dependency_namespace].values() if p['name'] == name_in_toml) unused_packages[dependency_namespace].add(unused_package) # Finally, adds source files related to the depended crates except: # # - those detected by cargo-udeps # - those come from Crates.io or Git repositories (e.g. `proconio`, other people's libraries including `ac-library-rs`) # `main_package` should always be included. # Note that cargo-udeps does not detect it if it is unused. # https://github.com/est31/cargo-udeps/pull/35 depended_packages = [main_package] for dependency_namespace, values in dependencies.items(): for depended_package in values.values(): if depended_package['id'] not in unused_packages[dependency_namespace] and not depended_package['source']: depended_packages.append(depended_package) ret = common_result for depended_package in depended_packages: depended_targets = [t for t in depended_package['targets'] if t != main_target and (_is_build(t) or _is_lib_or_proc_macro(t))] assert len(depended_targets) <= 2 for depended_target in depended_targets: related_source_files = _related_source_files(basedir, _cargo_metadata_by_manifest_path(pathlib.Path(depended_package["manifest_path"]))) ret |= _source_files_in_same_targets(pathlib.Path(depended_target['src_path']).resolve(strict=True), related_source_files) return sorted(ret) def _related_source_files(basedir: pathlib.Path, metadata: Dict[str, Any]) -> Dict[pathlib.Path, FrozenSet[pathlib.Path]]: """Collects all of the `.rs` files recognized by a workspace. :param basedir: A parameter from `Language.list_dependencies`. :param metadata: Output of `cargo metadata` :returns: A (main source file) → (other related files) map """ if pathlib.Path(metadata['workspace_root']) in _related_source_files_by_workspace: return _related_source_files_by_workspace[pathlib.Path(metadata['workspace_root'])] # Runs `cargo check` to generate `$target_directory/debug/deps/*.d`. if pathlib.Path(metadata['workspace_root']) not in _cargo_checked_workspaces: subprocess.run( ['cargo', 'check', '--manifest-path', str(pathlib.Path(metadata['workspace_root'], 'Cargo.toml')), '--workspace', '--all-targets'], cwd=metadata['workspace_root'], check=True, ) _cargo_checked_workspaces.add(pathlib.Path(metadata['workspace_root'])) ret: Dict[pathlib.Path, FrozenSet[pathlib.Path]] = dict() targets_in_workspace = itertools.chain.from_iterable(p['targets'] for p in metadata['packages'] if p['id'] in metadata['workspace_members']) for target in targets_in_workspace: # Finds the **latest** "dep-info" file that contains a line in the following format, and parses the line. # # ``` # <relative/absolute path to the `.d` file itself>: <relative/absolute path to the root source file> <relative/aboslute paths to the other related files>... # ``` # # - https://github.com/rust-lang/cargo/blob/rust-1.49.0/src/cargo/core/compiler/fingerprint.rs#L1979-L1997 # - https://github.com/rust-lang/cargo/blob/rust-1.49.0/src/cargo/core/compiler/fingerprint.rs#L1824-L1830 if _is_build(target): dep_info_paths = pathlib.Path(metadata['target_directory'], 'debug', 'build').rglob(f'{_crate_name(target)}-*.d') elif _is_example(target): dep_info_paths = pathlib.Path(metadata['target_directory'], 'debug', 'examples').glob(f'{_crate_name(target)}-*.d') else: dep_info_paths = pathlib.Path(metadata['target_directory'], 'debug', 'deps').glob(f'{_crate_name(target)}-*.d') for dep_info_path in sorted(dep_info_paths, key=lambda p: p.stat().st_mtime_ns, reverse=True): with open(dep_info_path) as file: dep_info = file.read() for line in dep_info.splitlines(): ss = line.split(': ') if len(ss) == 2 and pathlib.Path(metadata['workspace_root'], ss[0]) == dep_info_path: paths = [] it = iter(ss[1].split()) for s in it: while s.endswith('\\'): s = s.rstrip('\\') s += ' ' s += next(it) path = pathlib.Path(metadata['workspace_root'], s).resolve(strict=True) # Ignores paths that don't start with the `basedir`. (e.g. `/dev/null`, `/usr/local/share/foo/bar`) try: # `PurePath.is_relative_to` is since Python 3.9. _ = path.relative_to(basedir) paths.append(path) except ValueError: pass if paths[:1] == [pathlib.Path(target['src_path']).resolve(strict=True)]: ret[paths[0]] = frozenset(paths[1:]) break else: continue break else: logger.error('no `.d` file for `%s`', target["name"]) _related_source_files_by_workspace[pathlib.Path(metadata['workspace_root'])] = ret return ret def _source_files_in_same_targets(path: pathlib.Path, related_source_files: Dict[pathlib.Path, FrozenSet[pathlib.Path]]) -> FrozenSet[pathlib.Path]: """Returns `.rs` file paths relating to `path`. :param path: Path to a `.rs` file :param related_source_files: Output of `_related_source_files` :returns: Relating `.rs` file paths """ # If `p` is `src_path` of a target, it does not belong to any other target unless it's weirdly symlinked, if path in related_source_files: return frozenset({path, *related_source_files[path]}) # Otherwise, it may be used by multiple targets with `#[path = ".."] mod foo;` or something. return frozenset(itertools.chain.from_iterable({k, *v} for (k, v) in related_source_files.items() if path in v)) or frozenset({path}) class RustLanguageEnvironment(LanguageEnvironment): def compile(self, path: pathlib.Path, *, basedir: pathlib.Path, tempdir: pathlib.Path) -> None: path = basedir / path metadata = _cargo_metadata(cwd=path.parent) target = _ensure_target(metadata, path) subprocess.run( ['cargo', 'build', '--release', *_target_option(target)], cwd=path.parent, check=True, ) def get_execute_command(self, path: pathlib.Path, *, basedir: pathlib.Path, tempdir: pathlib.Path) -> List[str]: path = basedir / path metadata = _cargo_metadata(cwd=path.parent) target = _ensure_target(metadata, path) return [str(pathlib.Path(metadata['target_directory'], 'release', *([] if _is_bin(target) else ['examples']), target['name']))] class RustLanguage(Language): _list_dependencies_backend: _ListDependenciesBackend def __init__(self, *, config: Optional[Dict[str, Any]] = None): if config is None: config = get_config().get('languages', {}).get('rust', {}) # Parses `languages.rust.list_dependencies_backend`. if 'list_dependencies_backend' in config: list_dependencies_backend = config['list_dependencies_backend'] if not isinstance(list_dependencies_backend, dict): raise RuntimeError('`languages.rust.list_dependencies_backend` must be `dict`') if 'kind' not in list_dependencies_backend: raise RuntimeError('missing `languages.rust.list_dependencies_backend.kind`') list_dependencies_backend_kind = list_dependencies_backend['kind'] if not isinstance(list_dependencies_backend_kind, str): raise RuntimeError('`languages.rust.list_dependencies_backend.kind` must be `str`') if list_dependencies_backend_kind == 'none': self._list_dependencies_backend = _NoBackend() elif list_dependencies_backend_kind == 'cargo-udeps': if 'toolchain' not in list_dependencies_backend: toolchain = None elif isinstance(list_dependencies_backend['toolchain'], str): toolchain = list_dependencies_backend['toolchain'] else: raise RuntimeError('`languages.rust.list_dependencies_backend.toolchain` must be `str`') self._list_dependencies_backend = _CargoUdeps(toolchain=toolchain) else: raise RuntimeError("expected 'none' or 'cargo-udeps' for `languages.rust.list_dependencies_backend.kind`") else: self._list_dependencies_backend = _NoBackend() def list_dependencies(self, path: pathlib.Path, *, basedir: pathlib.Path) -> List[pathlib.Path]: return self._list_dependencies_backend.list_dependencies(path, basedir=basedir) def bundle(self, path: pathlib.Path, *, basedir: pathlib.Path, options: Dict[str, Any]) -> bytes: raise NotImplementedError def is_verification_file(self, path: pathlib.Path, *, basedir: pathlib.Path) -> bool: path = basedir / path metadata = _cargo_metadata(cwd=path.parent) package_and_target = _find_target(metadata, path) if not package_and_target: return False _, target = package_and_target return _is_bin_or_example_bin(target) and 'PROBLEM' in special_comments.list_special_comments(path) def list_environments(self, path: pathlib.Path, *, basedir: pathlib.Path) -> Sequence[RustLanguageEnvironment]: return [RustLanguageEnvironment()] def _cargo_metadata(cwd: pathlib.Path) -> Dict[str, Any]: """Returns "metadata" for a Cargo.toml file in `cwd` or its parent directories. :raises ValueError: if `cwd` is not absolute or contains `..` :returns: Output of `cargo metadata` command """ if not cwd.is_absolute() or '..' in cwd.parts: raise ValueError(f'the `cwd` parameter must be absolute and must not contain `..`: {cwd}') # https://docs.rs/cargo/0.49.0/src/cargo/util/important_paths.rs.html#6-20 for directory in [cwd, *cwd.parents]: manifest_path = directory / 'Cargo.toml' if manifest_path.exists(): return _cargo_metadata_by_manifest_path(manifest_path) raise RuntimeError(f'could not find `Cargo.toml` in `{cwd}` or any parent directory') def _cargo_metadata_by_manifest_path(manifest_path: pathlib.Path) -> Dict[str, Any]: """Returns "metadata" for a certain `Cargo.toml`. :returns: Output of `cargo metadata` command """ if manifest_path in _metadata_by_manifest_path: return _metadata_by_manifest_path[manifest_path] metadata = _run_cargo_metadata(manifest_path) root_manifest_path = pathlib.Path(metadata['workspace_root'], 'Cargo.toml') if root_manifest_path != manifest_path:
<filename>sal/plugin.py<gh_stars>0 """Plugin classes and helpers This module contains the base plugin class (`BasePlugin`), from which the three actual-plugin classes are derived: `Widget`, `DetailPlugin`, and `ReportPlugin`. It also provides a manager for locating plugin modules that have been properly deployed into the Sal plugin directories, with .yapsy info files. The `OldPluginAdapter` class allows the `PluginManager` and all client code to adapt old-style plugins to the newer API and subsequently only use the new API. Finally, an `OSFamilies` class exists simply as a way to protect against typos in plugin code when specifying OS family names. Public Classes: OSFamilies Widget DetailPlugin ReportPlugin PluginManager OldPluginWrapper """ import logging import os from yapsy.IPlugin import IPlugin import yapsy.PluginManager from django.conf import settings from django.http import Http404 from django.shortcuts import get_object_or_404 from django.template import loader from sal.decorators import handle_access, is_global_admin from server.models import Machine, Plugin, MachineDetailPlugin, Report from server.text_utils import class_to_title # TODO: This can be removed along with the legacy plugin support code DEPRECATED_PAGES = { 'all': 'front', 'business_unit': 'bu_dashboard', 'machine_group': 'group_dashboard', 'machine': 'machine_detail'} class OSFamilies(object): chromeos = "ChromeOS" darwin = "Darwin" linux = "Linux" windows = "Windows" class BasePlugin(IPlugin): """Base class for Sal plugin types to inherit from. Public Attributes: name (str): Name of the class and .yapsy config file `name`. title (str): Plugin `name` that is de-camelcased into a display name. order (int or None): Plugin's display order value (retrieved from database), or None if it's not enabled. enabled (bool): Whether plugin is enabled for display (retrieved from database). description (str): Plugin description. Defaults to '' only_use_deployed_machines (bool): Plugins normally only show deployed machines (the default is True). Set to False to tell the plugin to use all machines when calling `get_queryset`. model (django.db.model): Model plugin should use in its `get_queryset` calls. supported_os_families (list of str): OS families for which this plugin should filter machines by. Defaults to `[OSFamilies.darwin, OSFamilies.windows, OSFamilies.linux, OSFamilies.chromeos]`. template (str): Relative path to plugin's template file. Defaults to '' and plugin will construct a path to a default template; see the `get_template` method for more information. widget_width (int): Plugin's width. Defaults to 4 Copied from Yapsy config: path (str): Path to plugin module on the system. copyright (str): Copyright information. Defaults to ''. author (str): Name of the author. Defaults to ''. website (str): URL to a website. Defaults to ''. version (str): Plugin version number. Defaults to '0.1'. Public Methods: get_widget_width get_description get_template get_queryset widget_content: Returns rendered content of the plugin. get_context: All subclasses need to reimplement this. super_get_context: Call this base classes' get_context. """ _db_model = Plugin description = '' only_use_deployed_machines = True model = Machine supported_os_families = [ OSFamilies.darwin, OSFamilies.windows, OSFamilies.linux, OSFamilies.chromeos ] template = '' widget_width = 4 def __repr__(self): return self.__class__.__name__ @property def name(self): return repr(self) @property def title(self): """Return the title of the plugin. This uses the class name, broken along capital letters (and handling multiple capitals in a row). Subclasses can simply declare a `title` str if they just want to set something other than the class name. """ return class_to_title(self.__class__.__name__) @property def enabled(self): try: self._db_model.objects.get(name=self.name) return True except self._db_model.DoesNotExist: return False @property def order(self): try: db_plugin = self._db_model.objects.get(name=self.name) return db_plugin.order except self._db_model.DoesNotExist: return None def get_template(self, *args, **kwargs): """Get the plugin's django template. This method by default looks up the template attribute. If that's not available, it tries to construct a template path from the name of the plugin's class, lowercased. (i.e. BasePlugin would have a computed template path of 'baseplugin/templates/baseplugin.html'). To allow this method to be overridden by clients, it accepts **kwargs. See the `widget_content` method to see the primary use of this method; it's called with the machines queryset, the `group_type`, and `group_id`, so an overriden `get_template` could select from different templates based on the contextual data. Args: kwargs: Unused in this implementation. Returns: Django template for this plugin. """ if self.template: template = self.template else: # Construct path to templates from plugin's full path. template = "{0}/templates/{1}.html".format( self.path[:self.path.rfind('/')], self.__class__.__name__.lower()) return loader.get_template(template) def get_supported_os_families(self, **kwargs): return self.supported_os_families def get_widget_width(self, *args, **kwargs): return self.widget_width def get_description(self, *args, **kwargs): return self.description def get_queryset(self, request, **kwargs): """Get a filtered queryset for this plugin's Machine model. Filters machines to only members of the passed group. Filters undeployed machines if deployed is True. Filters out machines that don't match this plugin's supported_os_families. Args: request (Request): The request passed from the View. **kwargs: Expected kwargs follow group_type (str): One of 'all' (the default), 'business_unit', or 'machine_group'. group_id (int, str): ID of the group_type's object to filter by. Default to 0. deployed (bool): Filter by Machine.deployed. Defaults to True. Returns: Filtered queryset. """ group_type = kwargs.get('group_type', 'all') group_id = kwargs.get('group_id', 0) # Check access before doing anything else. handle_access(request, group_type, group_id) queryset = self.model.objects.filter(os_family__in=self.get_supported_os_families()) # By default, plugins filter out undeployed machines. if self.only_use_deployed_machines: queryset = self.model.objects.filter(deployed=True) if group_type == "business_unit": queryset = queryset.filter(machine_group__business_unit__pk=group_id) elif group_type == "machine_group": queryset = queryset.filter(machine_group__pk=group_id) elif is_global_admin(request.user): # GA users won't have business units, so just do nothing. pass else: # The 'all' / 'front' type is being requested. queryset = queryset.filter( machine_group__business_unit__in=request.user.businessunit_set.all()) return queryset def widget_content(self, request, **kwargs): queryset = self.get_queryset(request, **kwargs) context = self.get_context(queryset, **kwargs) template = self.get_template(request, **kwargs) return template.render(context) def get_context(self, queryset, **kwargs): """Process input into a context suitable for rendering. This method must be overridden by subclasses; You can't call super on this because of the way yapsy constructs the instance. Args: queryset (QuerySet of Machines or Machine): Machine(s) to consider while generating plugin's output. **kwargs: (Expected keys below) group_type (str): One of 'all', 'business_unit', 'machine_group', or 'machine', determining the limits of the machines query. group_id (int): Primary key value of the associated group. Returns: Dict suitable for plugin's template to render. Default implementation returns the method's **kwargs, and adds in the plugin itself with key 'plugin'. """ kwargs['plugin'] = self return kwargs def super_get_context(self, queryset, **kwargs): """Helper method to call the base Plugin classes' get_context. Yapsy munges the class of instantiated plugins, so you can't simply call `super(ClassName, self)...`. This method will dig the correct `get_context` out and call it. """ method = eval('super(self.__class__.__bases__[0], self).get_context') return method(queryset, **kwargs) def checkin_processor(self, machine, report_data): """Process checkin data prior to recording in DB. The default implementation does nothing. Plugins can define a checkin processor method by overriding this. This processor is run at the conclusion of the client checkin, and includes the report data processed during that run. Args: machine (server.models.Machine): The machine checking in. report_data (dict): All of the report data. """ pass def profiles_processor(self, machine, profiles_list): """Process profiles prior to recording in DB. The default implementation does nothing. Plugins can define a profiles processor method by overriding this. This processor is run at the conclusion of the client checkin within the profiles route, and includes the complete profile list processed during that run. Args: machine (server.models.Machine): The machine checking in. profiles_list (dict): All of the profiles data. """ pass class FilterMixin(object): """Adds filter_machines method to Plugins Public_Methods filter_machines: Filter passed machines using filter method. filter: All subclasses must reimplement this method. """ def filter_machines(self, machines, data): """Filter machines using plugin's `filter` method. Args: machines (Queryset of machines): Machines to filter. data (str): Some value that `filter` will use to restrict queryset by. Returns: Tuple of filtered machines, data Raises: Http404 if plugin's `filter` method responds with None, None """ machines, data = self.filter(machines, data) if not machines.exists() and not data: raise Http404 return machines, data def filter(self, machines, data): """Filter machines further for redirect to a machine list view This method is used when a link originating from the output of the plugin needs to redirect to a machine list view. This method is then used by the machine list view to filter the machines prior to list display. All subclasses should reimplement this, as the default implementation does nothing. Args: machines (queryset of Machines): Machines to be filtered. data (str): Some value used in the body of this method for filtering. Used in the
return example class SpeakerActivityMapper: def __init__(self, options, context=0, json_path=database_jsons): """ Add speaker activity per STFT frame to each example. :param options: nt.Options object containing arguments for STFT length and shift. :param context: Speaker activity added before and after actual utterance. Context is given in seconds. :param json_path: Path to database json files. """ assert 'frame_length' in options.keys() and \ 'frame_step' in options.keys(), \ 'Options object must specify STFT parameters "frame_length" and ' \ '"frame_step"' self.frame_length = options['frame_length'] self.frame_step = options['frame_step'] self.context = context self.speaker_activity = dict() if isinstance(json_path, str): json_path = Path(json_path) db = Chime5() sessions = [sess for sess_list in db.map_dataset_to_sessions.values() for sess in sess_list] for session_id in sessions: try: json_sess = load_json(json_path / 'chime5_speech_activity' / f'{session_id}.json' ) except FileNotFoundError: continue target_speakers = sorted([key for key in json_sess.keys() if key.startswith('P')] ) speaker_activity = { target: to_numpy(json_sess[target][target], 0, 10800*16000, sample_step=1, dtype=np.int16) for target in target_speakers } self.speaker_activity[session_id] = speaker_activity def __call__(self, example): """ :param example: example_dict :return: example_dict with add. key "speaker_activity_per_frame" """ _, session_id, kaldi_start, kaldi_end = re.split('[_-]', example[K.EXAMPLE_ID]) start = (int(kaldi_start) - self.context * 100) * 160 end = (int(kaldi_end) + self.context * 100) * 160 speaker_activity = self.speaker_activity[session_id] pad_width = self.frame_length - self.frame_step # Consider fading speaker_activity_per_frame = { target: segment_axis_v2(np.pad(activity[start:end], pad_width, mode='constant'), length=self.frame_length, shift=self.frame_step, end='pad' # Consider padding ).any(1) for target, activity in speaker_activity.items() } example['speaker_activity_per_frame'] = speaker_activity_per_frame return example def activity_frequency_to_time( frequency_activity, stft_window_length, stft_shift, stft_fading, time_length=None, ): """ >>> from nt.transform import istft >>> vad = np.array( [0, 1, 0, 1, 0, 0, 1, 0, 0]) >>> np.set_printoptions(suppress=True) >>> activity_frequency_to_time(vad, stft_window_length=4, stft_shift=2, stft_fading=False) array([False, False, True, True, True, True, True, True, True, True, False, False, True, True, True, True, False, False, False, False]) >>> activity_frequency_to_time([vad, vad], stft_window_length=4, stft_shift=2, stft_fading=False) array([[False, False, True, True, True, True, True, True, True, True, False, False, True, True, True, True, False, False, False, False], [False, False, True, True, True, True, True, True, True, True, False, False, True, True, True, True, False, False, False, False]]) """ if stft_fading: raise NotImplementedError(stft_fading) frequency_activity = np.asarray(frequency_activity) # import from nt.transform import istft # cbj.istft # frequency_activity = frequency_activity frequency_activity = np.broadcast_to( frequency_activity[..., None], (*frequency_activity.shape, stft_window_length) ) time_activity = np.zeros( (*frequency_activity.shape[:-2], frequency_activity.shape[-2] * stft_shift + stft_window_length - stft_shift) ) # Get the correct view to time_signal time_signal_seg = segment_axis_v2( time_activity, stft_window_length, stft_shift, end=None ) # Unbuffered inplace add # np.add.at( # time_signal_seg, # ..., # frequency_activity # ) # It is not nessesary to do a unbuffered assignment, because it is alwais # the same value that gets assigned. time_signal_seg[frequency_activity > 0] = 1 time_activity = time_activity != 0 if time_length is not None: if time_length == time_activity.shape[-1]: pass elif time_length < time_activity.shape[-1]: delta = time_activity.shape[-1] - time_length assert delta < stft_window_length - stft_shift, (delta, stft_window_length, stft_shift) time_activity = time_activity[..., :time_length] elif time_length > time_activity.shape[-1]: delta = time_length - time_activity.shape[-1] assert delta < stft_window_length - stft_shift, (delta, stft_window_length, stft_shift) time_activity = pad_axis( time_activity[..., :time_length], pad_width=(0, delta), axis=-1, ) else: raise Exception('Can not happen') assert time_length == time_activity.shape[-1], (time_length, time_activity.shape) return time_activity != 0 def activity_time_to_frequency( time_activity, stft_window_length, stft_shift, stft_fading, stft_pad=True, ): """ >>> from nt.transform import stft >>> signal = np.array([0, 0, 0, 0, 0, 1, -3, 0, 5, 0, 0, 0, 0, 0]) >>> vad = np.array( [0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0]) >>> np.set_printoptions(suppress=True) >>> print(stft(signal, size=4, shift=2, fading=True, window=np.ones)) [[ 0.+0.j 0.+0.j 0.+0.j] [ 0.+0.j 0.+0.j 0.+0.j] [ 1.+0.j 0.+1.j -1.+0.j] [-2.+0.j 3.-1.j -4.+0.j] [ 2.+0.j -8.+0.j 2.+0.j] [ 5.+0.j 5.+0.j 5.+0.j] [ 0.+0.j 0.+0.j 0.+0.j] [ 0.+0.j 0.+0.j 0.+0.j]] >>> activity_time_to_frequency(vad, stft_window_length=4, stft_shift=2, stft_fading=True) array([False, False, True, True, True, True, False, False]) >>> activity_time_to_frequency([vad, vad], stft_window_length=4, stft_shift=2, stft_fading=True) array([[False, False, True, True, True, True, False, False], [False, False, True, True, True, True, False, False]]) >>> print(stft(signal, size=4, shift=2, fading=False, window=np.ones)) [[ 0.+0.j 0.+0.j 0.+0.j] [ 1.+0.j 0.+1.j -1.+0.j] [-2.+0.j 3.-1.j -4.+0.j] [ 2.+0.j -8.+0.j 2.+0.j] [ 5.+0.j 5.+0.j 5.+0.j] [ 0.+0.j 0.+0.j 0.+0.j]] >>> activity_time_to_frequency(vad, stft_window_length=4, stft_shift=2, stft_fading=False) array([False, True, True, True, True, False]) >>> activity_time_to_frequency([vad, vad], stft_window_length=4, stft_shift=2, stft_fading=False) array([[False, True, True, True, True, False], [False, True, True, True, True, False]]) >>> activity_time_to_frequency(np.zeros(200000), stft_window_length=1024, stft_shift=256, stft_fading=False, stft_pad=False).shape (778,) >>> from nt.transform import stft >>> stft(np.zeros(200000), size=1024, shift=256, fading=False, pad=False).shape (778, 513) """ assert np.asarray(time_activity).dtype != np.object, (type(time_activity), np.asarray(time_activity).dtype) time_activity = np.asarray(time_activity) if stft_fading: pad_width = np.array([(0, 0)] * time_activity.ndim) pad_width[-1, :] = stft_window_length - stft_shift # Consider fading time_activity = np.pad( time_activity, pad_width, mode='constant' ) return segment_axis_v2( time_activity, length=stft_window_length, shift=stft_shift, end='pad' if stft_pad else 'cut' ).any(axis=-1) class CrossTalkFilter: def __init__(self, dataset: str, json_path=database_jsons, with_crosstalk='no', min_overlap=0.0, max_overlap=0.0): """ Filter examples according to with_crosstalk and min_overlap and max_overlap :param dataset: Chime5 dataset ('train', 'dev' or 'test') :param json_path: Path to json database. May be a string or Path object :param with_crosstalk: A string from ['yes', 'no', 'all']. If 'yes', return all utterances which have at least one sample overlap. If 'no', return all samples which are overlap-free. If 'all', return all samples whose overlap is between `min_overlap` and `max_overlap`. By default, 'all' will return only the utterances with no overlap. Defaults to 'no'. :param min_overlap: If with_crosstalk is 'yes' or 'all', defines the lower bound the overlap on the utterance needs to have to return True. Ratio given in overlapping samples over total utterance samples :param max_overlap: If with_crosstalk is 'no' or 'all', defines the upper bound the overlap on the utterance is allowed to have to return True. Ratio given in overlapping samples over total utterance samples """ assert with_crosstalk in ['yes', 'no', 'all'], \ f'with_crosstalk must be a value from ["yes", "no", "all"], ' \ 'not {with_crosstalk}' self.mapper = OverlapMapper(dataset, json_path) self.with_crosstalk = with_crosstalk self.min_overlap = min_overlap self.max_overlap = max_overlap def __call__(self, example): """ :param example: example_dict with example_id in it :return: True if either 1. self.with_crosstalk='no' and overlap_ratio in [0, self.max_overlap] or 2. self.with_crosstalk='yes' and overlap_ratio in (self.min_overlap, 1] or 3. self.with_crosstalk='all' and overlap_ratio in [self.min_overlap, self.max_overlap] """ if 'overlap' not in example.keys(): example = self.mapper(example) overlap_ratio = example['overlap'] if self.with_crosstalk == 'no' and overlap_ratio <= self.max_overlap: return True elif self.with_crosstalk == 'yes' and overlap_ratio > self.min_overlap: return True elif self.with_crosstalk == 'all' and \ (self.min_overlap <= overlap_ratio <= self.max_overlap): return True else: return False def _adjust_start_end( worn_start, worn_end, array_start, array_end, ): """ >>> w_s = np.random.randint(0, 100) >>> w_e = w_s + np.random.randint(1, 100) >>> a_s = np.random.randint(0, 100) >>> a_e = a_s + w_e - w_s >>> def test(a_s, a_e, delta_s, delta_e): ... res = _adjust_start_end(w_s, w_e, a_s, a_e) ... if (a_s + delta_s, a_e + delta_e) != res: ... raise AssertionError(f'Expected changes {delta_s} {delta_e}, got {res[0] - a_s} {res[1] - a_e}. {(w_s, w_e, a_s, a_e)}') >>> test(a_s, a_e, 0, 0) >>> test(a_s, a_e+1, 0, -1) >>> test(a_s, a_e-1, 0, +1) >>> test(a_s+1, a_e, 0, +1) >>> test(a_s-1, a_e, 0, -1) >>> test(a_s, a_e+2, 1, -1) >>> test(a_s, a_e-2, -1, 1) >>> test(a_s, a_e+3, 1, -2) >>> test(a_s, a_e-3, -1, +2) >>> test(a_s, a_e+4, 2, -2) >>> test(a_s, a_e-4, -2, +2) >>> test(a_s, a_e+5, 2, -3) >>> test(a_s, a_e-5, -2, +3) >>> _adjust_start_end(10, 20, 10, 19) (10, 20) >>> _adjust_start_end(10, 20, 10, 21) (10, 20) """ worn_duration = worn_end - worn_start array_duration = array_end - array_start if worn_duration == array_duration: new_start, new_end = array_start, array_end elif worn_duration > array_duration: delta = worn_duration - array_duration delta_start = delta // 2 delta_end = (delta + 1) // 2 new_start, new_end = array_start - delta_start, array_end + delta_end elif worn_duration < array_duration: delta = array_duration - worn_duration delta_start = delta // 2 delta_end = (delta + 1) // 2 new_start, new_end = array_start + delta_start, array_end - delta_end else: raise Exception('Can not happen.') assert new_end - new_start == worn_duration, ( f'worn: {worn_end} - {worn_start} = {worn_duration}, ' f'array: {array_end} - {array_start} = {array_duration}, ' f'new: {new_end} - {new_start} = {new_end
to input list with identifier '{matcher}'. Please use unique identifier") new_list.append(ff) return new_list def get_file_from_substring(filt, path, return_msg='error', exclude=None): """get_file_from_substring This function returns the file given a path and a substring. Avoids annoying stuff with glob. Now also allows multiple filters to be applied to the list of files in the directory. The idea here is to construct a binary matrix of shape (files_in_directory, nr_of_filters), and test for each filter if it exists in the filename. If all filters are present in a file, then the entire row should be 1. This is what we'll be looking for. If multiple files are found in this manner, a list of paths is returned. If only 1 file was found, the string representing the filepath will be returned. Parameters ---------- filt: str, list tag for files we need to select. Now also support a list of multiple filters. path: str path to the directory from which we need to remove files return_msg: str, optional whether to raise an error (*return_msg='error') or return None (*return_msg=None*). Default = 'error'. exclude: str, optional: Specify string to exclude from options. This criteria will be ensued after finding files that conform to `filt` as final filter. Returns ---------- str path to the files containing `string`. If no files could be found, `None` is returned list list of paths if multiple files were found Raises ---------- FileNotFoundError If no files usingn the specified filters could be found Example ---------- >>> get_file_from_substring("R2", "/path/to/prf") '/path/to/prf/r2.npy' >>> get_file_from_substring(['gauss', 'best_vertices'], "path/to/pycortex/sub-xxx") '/path/to/pycortex/sub-xxx/sub-xxx_model-gauss_desc-best_vertices.csv' >>> get_file_from_substring(['best_vertices'], "path/to/pycortex/sub-xxx") ['/path/to/pycortex/sub-xxx/sub-xxx_model-gauss_desc-best_vertices.csv', '/path/to/pycortex/sub-xxx/sub-xxx_model-norm_desc-best_vertices.csv'] """ input_is_list = False if isinstance(filt, str): filt = [filt] if isinstance(filt, list): # list and sort all files in the directory if isinstance(path, str): files_in_directory = sorted(os.listdir(path)) elif isinstance(path, list): input_is_list = True files_in_directory = path.copy() else: raise ValueError("Unknown input type; should be string to path or list of files") # the idea is to create a binary matrix for the files in 'path', loop through the filters, and find the row where all values are 1 filt_array = np.zeros((len(files_in_directory), len(filt))) for ix,f in enumerate(files_in_directory): for filt_ix,filt_opt in enumerate(filt): filt_array[ix,filt_ix] = filt_opt in f # now we have a binary <number of files x number of filters> array. If all filters were available in a file, the entire row should be 1, # so we're going to look for those rows full_match = np.ones(len(filt)) full_match_idc = np.where(np.all(filt_array==full_match,axis=1))[0] if len(full_match_idc) == 1: fname = files_in_directory[full_match_idc[0]] if input_is_list: return fname else: f = opj(path, fname) if exclude != None: if exclude not in f: return opj(path, fname) else: if return_msg == "error": raise FileNotFoundError(f"Could not find file with filters: {filt} and exclusion of [{exclude}] in '{path}'") else: return None else: return opj(path, fname) elif len(full_match_idc) > 1: match_list = [] for match in full_match_idc: fname = files_in_directory[match] if input_is_list: match_list.append(fname) else: match_list.append(opj(path, fname)) if exclude != None: return [f for f in match_list if exclude not in f] else: return match_list # return match_list else: if return_msg == "error": raise FileNotFoundError(f"Could not find file with filters: {filt} in {path}") else: return None def get_bids_file(layout, filter=None): """get_bids_file This search function is more tailored for BIDSified data, and requires a list of BIDS-filenames as per output for `l = BIDSLayout(dir, validate=False)` & `fn = l.get(session='1', datatype='anat')` for instance. From this list the script will look the list of given filters. Parameters ---------- layout: :abbr:`BIDS (Brain Imaging Data Structure)` layout object BIDS-layout object obtained with `BIDSLayout` filter: str, optional filter for particular strings Returns ---------- str filenames meeting the specifications (i.e., existing in `layout` and containing strings specified in `filters`) Example ---------- >>> layout = BIDSLayout(somedir).get(session='1', datatype='anat') >>> fn = get_bids_file(layout, filter=['str1', 'str2', 'str3']) """ import warnings warnings.filterwarnings("ignore") l = [] for i in layout: if all(f in i for f in filter) == True: l.append(i) if len(l) == 1: return l[0] else: return l def get_matrixfromants(mat, invert=False): """get_matrixfromants This function greps the rotation and translation matrices from the matrix-file create by `antsRegistration`. It basically does the same as on of the ANTs functions, but still.. Parameters ---------- mat: str string pointing to a *.mat*-file containing the transformation. invert: bool Boolean for inverting the matrix (`invert=False`) or not (`invert=True`) Return ---------- numpy.ndarray (4,4) array representing the transformation matrix """ try: genaff = io.loadmat(mat) key = list(genaff.keys())[0] matrix = np.hstack((genaff[key][0:9].reshape( 3, 3), genaff[key][9:].reshape(3, 1))) matrix = np.vstack([matrix, [0, 0, 0, 1]]) except: # assuming I just got a matrix matrix = np.loadtxt(mat) if invert == True: matrix = np.linalg.inv(matrix) return matrix def make_chicken_csv(coord, input="ras", output_file=None, vol=0.343): """make_chicken_csv This function creates a .csv-file like the chicken.csv example from ANTs to warp a coordinate using a transformation file. ANTs assumes the input coordinate to be LPS, but this function can deal with RAS-coordinates too. (see https://github.com/stnava/chicken for the reason of this function's name) Parameters ---------- coord: np.ndarray numpy array containing the three coordinates in x,y,z direction input: str specify whether your coordinates uses RAS or LPS convention (default is RAS, and will be converted to LPS to create the file) output_file: str path-like string pointing to an output file (.csv!) vol: float volume of voxels (pixdim_x*pixdim_y*pixdim_z). If you're using the standard 0.7 MP2RAGE, the default vol will be ok Returns ---------- str path pointing to the `csv`-file containing the coordinate Example ---------- >>> make_chicken_csv(np.array([-16.239,-67.23,-2.81]), output_file="sub-001_space-fs_desc-lpi.csv") "sub-001_space-fs_desc-lpi.csv" """ if len(coord) > 3: coord = coord[:3] if input.lower() == "ras": # ras2lps LPS = np.array([[-1,0,0], [0,-1,0], [0,0,1]]) coord = LPS @ coord # rows = ["x,y,z,t,label,mass,volume,count", f"{coord[0]},{coord[1]},{coord[2]},0,1,1,{vol},1"] with open(output_file, "w") as target: writer = csv.writer(target, delimiter=",") writer.writerow(["x","y","z","t","label","mass","volume","count"]) writer.writerow([coord[0],coord[1],coord[2],0,1,1,vol,1]) return output_file def read_chicken_csv(chicken_file, return_type="lps"): """read_chicken_csv Function to get at least the coordinates from a csv file used with antsApplyTransformsToPoints. (see https://github.com/stnava/chicken for the reason of this function's name) Parameters ---------- chicken_file: str path-like string pointing to an input file (.csv!) return_type: str specify the coordinate system that the output should be in Returns ---------- numpy.ndarray (3,) array containing the coordinate in `chicken_file` Example ---------- >>> read_chicken_csv("sub-001_space-fs_desc-lpi.csv") array([-16.239,-67.23,-2.81]) """ contents = pd.read_csv(chicken_file) coord = np.squeeze(contents.iloc[:,0:3].values) if return_type.lower() == "lps": return coord elif return_type.lower() == "ras": # ras2lps LPS = np.array([[-1,0,0], [0,-1,0], [0,0,1]]) return LPS@coord def fix_slicetiming(json_dir, TR=1.5, slc=60): """fix_slicetiming Function to fix the slicetiming in json file. Assumes there already is a key called SliceTiming in the json files. You'll only need to specify the directory the json-files are in, the TR, (default = 1.5), and the number of slices (default = 60) Parameters ---------- json_dir: str path to folder containing json files TR: float repetition time slc: int number of slices Returns ---------- str updated json-file Example ---------- >>> fix_slicetiming('path/to/folder/with/json', TR=1.5, slc=60) """ op = os.listdir(json_dir) for ii in op: if ii.endswith('.json'): with open(opj(json_dir,ii)) as in_file: data = json.load(in_file) data['SliceTiming'] = list(np.tile(np.linspace(0, TR, int(slc/3), endpoint=False), 3)) with open(opj(json_dir,ii), 'w') as out_file: json.dump(data, out_file, indent=4) class VertexInfo: """ VertexInfo This object reads a .csv file containing relevant information about the angles, vertex position, and normal vector. Parameters ---------- infofile: str path to the information file containing `best_vertices` in the filename subject: str subject ID as used in `SUBJECTS_DIR` Returns ---------- attr sets attributes in the class """ def __init__(self, infofile=None, subject=None, hemi="lh"): self.infofile = infofile self.data = pd.read_csv(self.infofile, index_col=0) # try to set the index to hemi. It will throw an error if you want to set the index while there already is an index. # E.g., initially we will set the index to 'hemi'. If we then later on read in that file again, the index is already # set try: self.data = self.data.set_index('hemi') except: pass if hemi == "lh" or hemi.lower() == "l" or hemi.lower() == "left": self.hemi = "L" elif hemi == "rh" or hemi.lower() == "r" or hemi.lower() == "right": self.hemi = "R" else:
<gh_stars>0 import csv import codecs import logging from django import forms from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as _ from django.db import IntegrityError from django.core.exceptions import ValidationError from .constants import VALUE_UNITS, PACKAGE_TYPES, POWER_UNITS, INTERFACE_TYPES, TEMPERATURE_UNITS, DISTANCE_UNITS, WAVELENGTH_UNITS, \ WEIGHT_UNITS, FREQUENCY_UNITS, VOLTAGE_UNITS, CURRENT_UNITS, MEMORY_UNITS, SUBSCRIPTION_TYPES, ROLE_TYPES, CONFIGURATION_TYPES from .models import Part, PartClass, Manufacturer, ManufacturerPart, Subpart, Seller, SellerPart, UserMeta, \ Organization, PartRevision, AssemblySubparts, Assembly from .validators import decimal, numeric from .utils import listify_string, stringify_list, check_references_for_duplicates, prep_for_sorting_nicely, get_from_dict logger = logging.getLogger(__name__) class UserModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, user): l = "[" + user.email + "]" if user.first_name: l += " " + user.first_name if user.last_name: l += " " + user.last_name return l class UserForm(forms.ModelForm): class Meta: model = get_user_model() # User fields = ['first_name', 'last_name', 'email'] class UserAddForm(forms.ModelForm): class Meta: model = UserMeta fields = ['role'] email = forms.EmailField(initial=None, required=True) def __init__(self, *args, **kwargs): self.organization = kwargs.pop('organization', None) super(UserAddForm, self).__init__(*args, **kwargs) def clean_username(self): cleaned_data = super(UserAddForm, self).clean() email = cleaned_data.get('email') try: UM = get_user_model() user = UM.objects.get(email=email) user_meta = UserMeta.objects.get(user=user) if user_meta.organization == self.organization: validation_error = forms.ValidationError( "User '{0}' already belongs to {1}.".format(email, self.organization), code='invalid') self.add_error('email', validation_error) elif user_meta.organization: validation_error = forms.ValidationError( "User '{}' belongs to another organization.".format(email), code='invalid') self.add_error('email', validation_error) except UM.DoesNotExist: validation_error = forms.ValidationError( "User '{}' does not exist.".format(email), code='invalid') self.add_error('email', validation_error) return email def save(self): username = self.cleaned_data.get('username') role = self.cleaned_data.get('role') user = User.objects.get(username=username) user_meta = UserMeta.objects.get(user=user) user_meta.organization = self.organization user_meta.role = role user_meta.save() return user_meta class UserMetaForm(forms.ModelForm): class Meta: model = UserMeta exclude = ['user', ] def __init__(self, *args, **kwargs): self.organization = kwargs.pop('organization', None) super(UserMetaForm, self).__init__(*args, **kwargs) def save(self): self.instance.organization = self.organization self.instance.save() return self.instance class OrganizationForm(forms.Form): def __init__(self, *args, **kwargs): self.organization = kwargs.pop('organization', None) super(OrganizationForm, self).__init__(*args, **kwargs) user_queryset = get_user_model().objects.filter( id__in=UserMeta.objects.filter(organization=self.organization, role='A').values_list('user', flat=True)).order_by( 'first_name', 'last_name', 'email') self.fields['owner'] = UserModelChoiceField(queryset=user_queryset, label='Owner', initial=self.organization.owner, required=True) self.fields['name'] = forms.CharField(label="Name", initial=self.organization.name, required=True) def save(self): self.organization.owner = self.cleaned_data.get('owner') self.organization.name = self.cleaned_data.get('name') self.organization.save() return self.organization class NumberItemLenForm(forms.Form): def __init__(self, *args, **kwargs): self.organization = kwargs.pop('organization', None) super(NumberItemLenForm, self).__init__(*args, **kwargs) self.fields['number_item_len'] = forms.IntegerField(max_value=Part.NUMBER_ITEM_MAX_LEN, min_value=self.organization.number_item_len, initial=self.organization.number_item_len) def save(self): self.organization.number_item_len = self.cleaned_data.get('number_item_len') self.organization.save() return self.organization.number_item_len class PartInfoForm(forms.Form): quantity = forms.IntegerField(label='Quantity for Cost Estimate', min_value=1) class ManufacturerForm(forms.ModelForm): class Meta: model = Manufacturer exclude = ['organization', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].required = False class ManufacturerPartForm(forms.ModelForm): class Meta: model = ManufacturerPart exclude = ['part', ] def __init__(self, *args, **kwargs): self.organization = kwargs.pop('organization', None) super(ManufacturerPartForm, self).__init__(*args, **kwargs) self.fields['manufacturer'].required = False self.fields['manufacturer_part_number'].required = False self.fields['manufacturer'].queryset = Manufacturer.objects.filter(organization=self.organization).order_by('name') class SellerPartForm(forms.ModelForm): class Meta: model = SellerPart exclude = ['manufacturer_part', 'data_source', ] new_seller = forms.CharField(max_length=128, label='-or- Create new seller (leave blank if selecting)', required=False) field_order = ['seller', 'new_seller', 'unit_cost', 'nre_cost', 'lead_time_days', 'minimum_order_quantity', 'minimum_pack_quantity', ] def __init__(self, *args, **kwargs): self.organization = kwargs.pop('organization', None) self.manufacturer_part = kwargs.pop('manufacturer_part', None) super(SellerPartForm, self).__init__(*args, **kwargs) if self.manufacturer_part is not None: self.instance.manufacturer_part = self.manufacturer_part self.fields['seller'].queryset = Seller.objects.filter( organization=self.organization).order_by('name') self.fields['seller'].required = False def clean(self): cleaned_data = super(SellerPartForm, self).clean() seller = cleaned_data.get('seller') new_seller = cleaned_data.get('new_seller') if seller and new_seller: raise forms.ValidationError("Cannot have a seller and a new seller.", code='invalid') elif new_seller: obj, created = Seller.objects.get_or_create(name__iexact=new_seller, organization=self.organization, defaults={'name': new_seller}) cleaned_data['seller'] = obj elif not seller: raise forms.ValidationError("Must specify a seller.", code='invalid') class PartClassForm(forms.ModelForm): class Meta: model = PartClass fields = ['code', 'name', 'comment'] def __init__(self, *args, **kwargs): self.organization = kwargs.pop('organization', None) super(PartClassForm, self).__init__(*args, **kwargs) self.fields['code'].required = False self.fields['name'].required = False def clean_code(self): cleaned_data = super(PartClassForm, self).clean() code = cleaned_data.get('code') if not code.isdigit() or int(code) < 0: validation_error = forms.ValidationError( "Part class code must be a positive number.", code='invalid') self.add_error('code', validation_error) part_class_with_code = None try: part_class_with_code = PartClass.objects.get(code=code, organization=self.organization) if part_class_with_code and self.instance and self.instance.id != part_class_with_code.id: validation_error = forms.ValidationError( "Part class with code {} is already defined.".format(code), code='invalid') self.add_error('code', validation_error) except PartClass.DoesNotExist: pass return code def clean_name(self): cleaned_data = super(PartClassForm, self).clean() name = cleaned_data.get('name') part_class_with_name = None try: part_class_with_name = PartClass.objects.get(name__iexact=name, organization=self.organization) if part_class_with_name and self.instance and self.instance.id != part_class_with_name.id: validation_error = forms.ValidationError( "Part class with name {} is already defined.".format(name), code='invalid') self.add_error('name', validation_error) except PartClass.DoesNotExist: pass return name def save(self): cleaned_data = super(PartClassForm, self).clean() code = cleaned_data.get('code') name = cleaned_data.get('name') comment = cleaned_data.get('comment') if (self.instance): self.instance.code = code self.instance.name = name self.instance.comment = comment self.instance.organization = self.organization self.instance.save() else: try: PartClass.objects.create(code=code, name__iexact=name, comment=comment, organization=self.organization) except IntegrityError: validation_error = forms.ValidationError( "Part class {0} {1} is already defined.".format(code, name), code='invalid') self.add_error(None, validation_error) return self.instance class PartClassSelectionForm(forms.Form): def __init__(self, *args, **kwargs): self.organization = kwargs.pop('organization', None) super(PartClassSelectionForm, self).__init__(*args, **kwargs) self.fields['part_class'] = forms.ModelChoiceField(queryset=PartClass.objects.filter(organization=self.organization).order_by('code'), empty_label="- Select Part Class -", label='List parts by class', required=False) class PartClassCSVForm(forms.Form): file = forms.FileField(required=False) def __init__(self, *args, **kwargs): self.organization = kwargs.pop('organization', None) super(PartClassCSVForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(PartClassCSVForm, self).clean() file = self.cleaned_data.get('file') self.successes = list() self.warnings = list() try: csvline_decoded = file.readline().decode('utf-8') dialect = csv.Sniffer().sniff(csvline_decoded) file.open() reader = csv.reader(codecs.iterdecode(file, 'utf-8'), dialect) headers = [h.lower() for h in next(reader)] must_headers = ('code', 'name') for hdr in must_headers: if hdr not in headers: validation_error = forms.ValidationError("Missing required column named '{}'.".format(hdr), code='invalid') self.add_error(None, validation_error) if 'comment' in hdr and 'description' in hdr: validation_error = forms.ValidationError("Can only have a column named 'comment' or a column named 'description'.".format(hdr), code='invalid') self.add_error(None, validation_error) row_count = 1 # Skip over header row for row in reader: row_count += 1 part_class_data = {} for idx, item in enumerate(row): part_class_data[headers[idx]] = item if 'name' in part_class_data and 'code' in part_class_data: try: name = part_class_data['name'] code = part_class_data['code'] if not code.isdigit() or int(code) < 0: validation_error = forms.ValidationError( "Part class 'code' in row {} must be a positive number. Uploading of this part class skipped.".format(row_count), code='invalid') self.add_error(None, validation_error) continue if 'description' in part_class_data: description_or_comment = part_class_data['description'] if 'description' in part_class_data else '' elif 'comment' in part_class_data: description_or_comment = part_class_data['comment'] if 'comment' in part_class_data else '' PartClass.objects.create(code=code, name=name, comment=description_or_comment, organization=self.organization) self.successes.append("Part class {0} {1} on row {2} created.".format(code, name, row_count)) except IntegrityError: validation_error = forms.ValidationError( "Part class {0} {1} on row {2} is already defined. Uploading of this part class skipped.".format(code, name, row_count), code='invalid') self.add_error(None, validation_error) else: validation_error = forms.ValidationError( "In row {} must specify both 'code' and 'name'. Uploading of this part class skipped.".format(row_count), code='invalid') self.add_error(None, validation_error) except UnicodeDecodeError as e: self.add_error(None, forms.ValidationError("CSV File Encoding error, try encoding your file as utf-8, and upload again. \ If this keeps happening, reach out to <EMAIL> with your csv file and we'll do our best to \ fix your issue!", code='invalid')) logger.warning("UnicodeDecodeError: {}".format(e)) raise ValidationError("Specific Error: {}".format(e), code='invalid') return cleaned_data class PartCSVForm(forms.Form): file = forms.FileField(required=False) def __init__(self, *args, **kwargs): self.organization = kwargs.pop('organization', None) super(PartCSVForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(PartCSVForm, self).clean() file = self.cleaned_data.get('file') self.successes = list() self.warnings = list() try: csvline_decoded = file.readline().decode('utf-8') dialect = csv.Sniffer().sniff(csvline_decoded) file.open() reader = csv.reader(codecs.iterdecode(file, 'utf-8'), dialect) headers = [h.lower() for h in next(reader)] if 'part_class' not in headers and 'part_number' not in headers: raise ValidationError("Missing required column named 'part_class' or column named 'part_number'", code='invalid') if 'revision' not in headers: raise ValidationError("Missing required column named 'revision'", code='invalid') if 'description' not in headers: if 'value' not in headers or 'value_units' not in headers: raise ValidationError("Missing required column named 'description' or columns named 'value' and 'value_units'", code='invalid') row_count = 1 # Skip over header row for row in reader: row_count += 1 part_data = {} for idx, item in enumerate(row): part_data[headers[idx]] = item part_number = get_from_dict(part_data, ['part_number', 'pn', 'part no', 'part number', 'part_no', ]) part_class = get_from_dict(part_data, ['part_class', 'part class', 'class', ]) number_item = None number_variation = None revision = get_from_dict(part_data, ['revision', 'rev', 'part_rev', 'part rev', 'part_revision', 'part revision']) mpn = get_from_dict(part_data, ['manufacturer_part_number', 'mpn', ]) mfg_name = get_from_dict(part_data, ['mfg', 'manufacturer', 'mfg name', 'manufacturer name', ]) description = get_from_dict(part_data, ['description', 'desc', 'desc.', ]) value = get_from_dict(part_data, ['value', 'val', 'val.', ]) value_units = get_from_dict(part_data, ['value_units', 'value units', 'val. units', 'val units', ]) # Check part number for uniqueness. If part number not specified # then Part.save() will create one. if part_number: try: (number_class, number_item, number_variation) = Part.parse_part_number(part_number, self.organization.number_item_len) part_class = PartClass.objects.get(code=number_class, organization=self.organization) Part.objects.get( number_class=part_class, number_item=number_item, number_variation=number_variation, organization=self.organization ) self.add_error(None, "Part number {0} in row {1} already exists. Uploading of this part skipped.".format(part_number, row_count)) continue except AttributeError as e:
list(self.coordList[0][subDictName].keys()) labels = sorted(list(set(labels))) return labels def WriteCoordsToTable(self, mode=['ALL']): ''' This function gathers all the Pix info from the master dictionary, and parses it down into data suitable for several dat tables. You can provide an alternate mode(s) if you're trying to do more efficient operations like update x/y/z coordinates only. mode='ALL' (updates everything, this is the default) mode='XYZ' (updates coordinates only) mode='RANGES' (updates ranges only) mode='MASKS' (updates masks only) mode='CHANS' (updates chans only) mode='SEL' (updates selection only) ''' # debug('Has not had coordinate sets properly implemented...') # NOTE: this MAY not need the coordinateSetIndex argument since we likely want to write out whatever we have all the time, # when the mode is set to something that includes coordinates..... # debug('Writing Coords to Table') if len( self.coordList.items() ) > 0: if len({ 'ALL', 'XYZ' }.intersection( set(mode) )) > 0: # gather, build, then write the coords table. namesList = self.generateHeader('coords') # optional sort SORT_ORDER = {"x": 0, "y": 1, "z": 2, "w": 3} namesList.sort( key=lambda val: SORT_ORDER[val] ) # build up 2d list we will write to table DAT. coordList0 = [ [ self.CoordSetFetch(k,name,0) for name in namesList ] for k,v in self.coordList.items() ] coordList1 = [ [ self.CoordSetFetch(k,name,1) for name in namesList ] for k,v in self.coordList.items() ] coordList2 = [ [ self.CoordSetFetch(k,name,2) for name in namesList ] for k,v in self.coordList.items() ] coordList3 = [ [ self.CoordSetFetch(k,name,3) for name in namesList ] for k,v in self.coordList.items() ] maskList0 = [ self.CoordSetMaskFetch(k,'x',0) for k,v in self.coordList.items() ] maskList1 = [ self.CoordSetMaskFetch(k,'x',1) for k,v in self.coordList.items() ] maskList2 = [ self.CoordSetMaskFetch(k,'x',2) for k,v in self.coordList.items() ] maskList3 = [ self.CoordSetMaskFetch(k,'x',3) for k,v in self.coordList.items() ] coordListT = [ list(map(list, zip(*coordList0))), list(map(list, zip(*coordList1))), list(map(list, zip(*coordList2))), list(map(list, zip(*coordList3))), ] # send data to script CHOP. pixCoordsChop.clear() pixCoordsChop.numSamples = len(coordList0) for j in range(4): # 4 max coord sets for now. suffix = str(j) for i,each in enumerate(namesList): c = pixCoordsChop.appendChan(each+suffix) c.vals = coordListT[j][i] # write out the utilization masks to W. we'll use these throughout where we need to know if a coord is intentionally 0,0,0 or if it's a null coord. c = pixCoordsChop.appendChan('w0') c.vals = maskList0 c = pixCoordsChop.appendChan('w1') c.vals = maskList1 c = pixCoordsChop.appendChan('w2') c.vals = maskList2 c = pixCoordsChop.appendChan('w3') c.vals = maskList3 if len({ 'ALL', 'CHANS' }.intersection( set(mode) )) > 0: #### leaving this as table dat, since the data requirements are slightly dif. # gather, build, then write the chans table. chansList = self.generateHeader('chans') pixChansTable.text = '\t'.join(chansList) if len({ 'ALL', 'RANGES' }.intersection( set(mode) )) > 0: chansList = self.generateHeader('chans') rangesNameList = [ [name+'_min',name+'_max'] for name in chansList ] rangesNameList = [ y for x in rangesNameList for y in x ] # build up 2d list we will write to table DAT. fullList = [ # [ v['chans'][name]['min'] for name in chansList ] + # [ v['chans'][name]['max'] for name in chansList ] [ v['chans'].get( name , {"max": 255,"min": 0} )['min'] for name in chansList ] + [ v['chans'].get( name , {"max": 255,"min": 0} )['max'] for name in chansList ] for k,v in self.coordList.items() ] # transpose list. fullListT = list(map(list, zip(*fullList))) # send data to script CHOP. pixRangesChop.clear() pixRangesChop.numSamples = len(fullList) for i,each in enumerate(rangesNameList): c = pixRangesChop.appendChan(each) c.vals = fullListT[i] if len({ 'ALL', 'MASKS' }.intersection( set(mode) )) > 0: namesList = self.generateHeader('masks') # build up 2d list we will write to table DAT. # this is wrong, didn't acomodate situations where the mask was not there. # fullList = [ [ v['masks'][name]['val'] for name in namesList ] for k,v in self.coordList.items() ] fullList = [ [ v['masks'].get(name,{'val':0})['val'] for name in namesList ] for k,v in self.coordList.items() ] # transpose list. fullListT = list(map(list, zip(*fullList))) # send data to script CHOP. pixMasksChop.clear() pixMasksChop.numSamples = len(fullList) for i,each in enumerate(namesList): c = pixMasksChop.appendChan(each) c.vals = fullListT[i] if len({ 'ALL', 'SEL' }.intersection( set(mode) )) > 0: namesList = ['selected'] # build up 2d list we will write to table DAT. fullList = [ [ v[name] for name in namesList ] for k,v in self.coordList.items() ] # transpose list. fullListT = list(map(list, zip(*fullList))) # send data to script CHOP. pixSelectionChop.clear() pixSelectionChop.numSamples = len(fullList) for i,each in enumerate(namesList): c = pixSelectionChop.appendChan(each) c.vals = fullListT[i] # write some data to the datablock obj about our Pix. DATABLOCK.par.Lenpix = self.ArcLen()# assume default coordinate set. else: recurseScriptDat = op('recurseForceCookScriptChops') pixCoordsChop.clear() pixRangesChop.clear() pixMasksChop.clear() pixSelectionChop.clear() recurseScriptDat.run( [pixCoordsChop,pixRangesChop,pixMasksChop,pixSelectionChop,pixChansTable] ) DATABLOCK.par.Clippedgenerators = '' op.Viewport.par.Fixturesaredirty = 1 return def ShiftSelection(self, shiftAmt = -1): ''' shift selection forwards or backwards by provided amount. ''' # get length of coords list, for modulo. totalLen = len(self.coordList.items()) # dicts are mutable, so we need a copy that won't change that we can reference. originalCopy = copy.deepcopy(self.coordList) # loop through our "live" coordList and re assign values from copy using modulo and # our shift offset amount. for key, value in self.coordList.items(): self.coordList[(key+shiftAmt)%totalLen]["selected"] = originalCopy[key]["selected"] return def GrowShrinkSelection(self, GrowAmt = 1, direction = 1): ''' Grows or shrinks the selection by x amount. ''' for x in range(GrowAmt): # get length of coords list, for modulo. maxIndex = len(self.coordList.items()) - 1 # if we are growing selection if direction == 1: # loop through our "live" coordList and grow RISING edge for key, value in self.coordList.items(): backOne = tdu.clamp(key - direction,0,maxIndex) if value["selected"] == 1: self.coordList[backOne]["selected"] = 1 # loop through our "live" coordList and grow FALLING edge for x in range(len(self.coordList.items()))[::-1]: forwardOne = tdu.clamp(x + direction,0,maxIndex) if self.coordList[x]["selected"] == 1: self.coordList[forwardOne]["selected"] = 1 # if we are shrinking selection elif direction == -1: # loop through our "live" coordList and shrink RISING edge for x in range(len(self.coordList.items()))[::-1]: backOne = tdu.clamp(x - direction,0,maxIndex) if self.coordList[x]["selected"] == 0: self.coordList[backOne]["selected"] = 0 # loop through our "live" coordList and grow RISING edge for key, value in self.coordList.items(): forwardOne = tdu.clamp(key + direction,0,maxIndex) if value["selected"] == 0: self.coordList[forwardOne]["selected"] = 0 return def PixToWorldSpace(self, sourceDat, destDat): parentMat = parent.obj.worldTransform offsetPos = tdu.Position(0,0,0) resultList = [] for row in sourceDat.rows()[1::]: x = float(row[0].val) y = float(row[1].val) z = float(row[2].val) offsetPos[0] = x offsetPos[1] = y offsetPos[2] = z newPos = parentMat * offsetPos lineString = "%f\t%f\t%f"%(newPos[0],newPos[1],newPos[2]) resultList += [ lineString ] finalStr = "\r\n".join(resultList) destDat.text = finalStr return def GetPixDictAsWorldSpace(self , optionalWorldSpaceMatrix = None, coordSetIndex=-1): ''' This function returns the entire Pix sub structure as it is, but with the coordinates of each pix in world space. ''' # debug('Has not had coordinate sets properly implemented...') # if -1, means we fetch this dynamically. if coordSetIndex == -1: coordSetIndex = self.ActiveCoordsetIndex() # NOTE - this should probably be implemented for all coordinate sets all the time. if optionalWorldSpaceMatrix == None: parentMat = parent.obj.worldTransform else: parentMat = optionalWorldSpaceMatrix offsetPos = tdu.Position(0,0,0) newDict = {} for k, v in self.coordList.items(): offsetPos[0] = self.CoordSetFetch(k,'x',coordSetIndex) offsetPos[1] = self.CoordSetFetch(k,'y',coordSetIndex) offsetPos[2] = self.CoordSetFetch(k,'z',coordSetIndex) newPos = parentMat * offsetPos newDict[k] = copy.deepcopy(v) try: newDict[k]['coords']['x']['val'] = newPos.x newDict[k]['coords']['y']['val'] = newPos.y newDict[k]['coords']['z']['val'] = newPos.z except: newDict[k][coordSetIndex] = {'x':{'val':0}, 'y':{'val':0}, 'z':{'val':0}} newDict[k]['coords']['x']['val'] = newPos.x newDict[k]['coords']['y']['val'] = newPos.y newDict[k]['coords']['z']['val'] = newPos.z return newDict def WorldSpacePixData(self , coordSetIndex=-1): ''' this function returns some useful info about the Pix in this fixture. namely, the min and max bounds of the x/y/z dims for use elsewhere. NOTE: this returns the world space position. ''' # debug('Has not had coordinate sets properly implemented...') # if -1, means we fetch this dynamically. if coordSetIndex == -1: coordSetIndex = self.ActiveCoordsetIndex() parentMat = parent.obj.worldTransform offsetPos = tdu.Position(0,0,0) resultList = [] for k, v in self.coordList.items(): x = self.CoordSetFetch(k,'x',coordSetIndex) y = self.CoordSetFetch(k,'y',coordSetIndex) z = self.CoordSetFetch(k,'z',coordSetIndex) offsetPos[0] = x offsetPos[1] = y offsetPos[2] = z newPos = parentMat * offsetPos resultList += [ list(newPos) ] return resultList def DeviceID____________________________(self): val = -1 try: val = parent.obj.par.Deviceid.eval() except: try: val = parent.obj.inputCOMPs[0].par.Deviceid.eval() except: try: val = parent.obj.inputCOMPs[0].inputCOMPs[0].par.Deviceid.eval() except: val = 0 return val ####################### START MASK FUNCTIONS HERE ########################## # reset the masks dict inside each Pix to an empty dict. # this erases all masks. def ResetMasks(self): # iterate through all items in coordsList. for key, value in self.coordList.items(): self.coordList[key]['masks'] = {} return def DeleteMask(self, maskName = None): # if chan name is provided as anything other than None. if maskName != None: # iterate through all items in coordsList. for key, value in self.coordList.items(): # try and retrieve the masks dict. if it's not there, we get None. MaskDict = value.get('masks', None) # if there was a mask dict. if MaskDict != None: # print(MaskDict) # try and retrieve a chan by the provided name. # will not fail but return None if none exists by that name. foundMask = MaskDict.get(maskName, None) # if we found a chan, delete it. if foundMask != None: del self.coordList[key]['masks'][maskName] # pass return def AddMask(self, maskName = None, maskValue = None): # if chan name is provided as anything other than None. if maskName != None: maskName2 = tdu.legalName( maskName ) if maskName2 != maskName: op.NOTIFV2.Notify('The name entered was not valid, it was converted to: %s'%(maskName2)) # iterate through all items in coordsList. for key, value in self.coordList.items(): selected = int(self.coordList[key]['selected']) if maskValue == None: finalValue = selected else: finalValue = maskValue # try and retrieve the masks dict. if it's not there, we get None. MaskDict = value.get('masks', None) # if there was a mask dict. if MaskDict != None: # add the new mask item to the masks dict if it existed already, set mask value to 1. self.coordList[key]['masks'][maskName2] = {'val':finalValue} # if mask dict did not exist, we probably still want to add the mask, we just have
start sweeping: stat = ENA.sweep(bench) #getting the estimated sweeping time print("Time-taken for this loop would be: %s (%spts)" %(stat[1]['TIME'], stat[1]['POINTS'])) print("Operation Complete: %s" %bool(ENA.measure(bench))) # adjusting display on ENA: ENA.autoscal(bench) ENA.selectrace(bench, action=['Set', 'para 1 calc 1']) data = ENA.sdata(bench) print(Fore.YELLOW + "\rProgress: %.3f%%" %((i+1)/datasize*buffersize_1*100), end='\r', flush=True) # test for the last loop if there is if testeach: # test each measure-loop: loopcount += [len(measure_loop_1)] loop_dur += [time() - prev] stage, prev = clocker(stage, prev) # Marking time ENA.close(bench) if "opt" not in xyfreq.data: # check if it is in optional-state PSG0.close(sogo, False) if "opt" not in fluxbias.data: # check if it is in optional-state YOKO.close(yokog, False) yield loopcount, loop_dur else: if get_status("CW_Sweep")['pause']: break else: yield data if not get_status("CW_Sweep")['repeat']: set_status("CW_Sweep", dict(pause=True)) ENA.close(bench) if "opt" not in xyfreq.data: # check if it is in optional-state PSG0.rfoutput(sogo, action=['Set', 0]) PSG0.close(sogo, False) if "opt" not in fluxbias.data: # check if it is in optional-state YOKO.output(yokog, 0) YOKO.close(yokog, False) return # ********************************************************************************************************************************************************** # 3. Square-wave Pulse measurement @settings(2) # data-density def SQE_Pulse(user, tag="", corder={}, comment='', dayindex='', taskentry=0, resumepoint=0, instr=['YOKO', 'PSGV', 'PSGA', 'AWG', 'VSA'], testeach=False): '''Time-domain Square-wave measurement: C-Structure: ['Flux-Bias', 'Average', 'Pulse-Period', 'ADC-delay', 'LO-Frequency', 'LO-Power', 'RO-Frequency', 'RO-Power', 'RO-ifLevel', 'RO-Pulse-Delay', 'RO-Pulse-Width', 'XY-Frequency', 'XY-Power', 'XY-ifLevel', 'XY-Pulse-Delay', 'XY-Pulse-Width', 'Sampling-Time'] (IQ-Bandwidth (250MHz or its HALFlings) + Acquisition-Time (dt must be multiples of 2ns)) ''' # Loading sample: sample = get_status("MSSN")[session['user_name']]['sample'] # sample = get_status("MSSN")['abc']['sample'] # by-pass HTTP-request before interface is ready # pushing pre-measurement parameters to settings: yield user, sample, tag, instr, corder, comment, dayindex, taskentry, testeach set_status("SQE_Pulse", dict(msg='measurement started', active=instr)) # ***USER_DEFINED*** Controlling-PARAMETER(s) ====================================================================================== config = corder['C-Config'] structure = corder['C-Structure'] fluxbias = waveform(corder['Flux-Bias']) averaging = waveform(corder['Average']) pperiod = waveform(corder['Pulse-Period']) adcdelay = waveform(corder['ADC-delay']) lofreq = waveform(corder['LO-Frequency']) lopowa = waveform(corder['LO-Power']) rofreq = waveform(corder['RO-Frequency']) ropowa = waveform(corder['RO-Power']) roiflevel = waveform(corder['RO-ifLevel']) ropdelay = waveform(corder['RO-Pulse-Delay']) ropwidth = waveform(corder['RO-Pulse-Width']) xyfreq = waveform(corder['XY-Frequency']) xypowa = waveform(corder['XY-Power']) xyiflevel = waveform(corder['XY-ifLevel']) xypdelay = waveform(corder['XY-Pulse-Delay']) xypwidth = waveform(corder['XY-Pulse-Width']) samptime = waveform(corder['Sampling-Time']) # Total data points: datasize = int(prod([waveform(corder[param]).count for param in structure], dtype='uint64')) * 2 #data density of 2 due to IQ print("data size: %s" %datasize) # Pre-loop settings: # Optionals: # YOKO: if "opt" not in fluxbias.data: # check if it is in optional-state / serious-state yokog = YOKO.Initiate(current=True, which=yoko_choice) # pending option YOKO.output(yokog, 1) # PSGV: if "opt" not in xyfreq.data: # check if it is in optional-state / serious-state sogo = PSG0.Initiate() # pending option PSG0.rfoutput(sogo, action=['Set', 1]) # Basics: # PSGA for LO: saga = PSG1.Initiate() # pending option PSG1.rfoutput(saga, action=['Set', 1]) # AWG for Control: ifperiod = pperiod.data[0] # PENDING: make pulse-period a peripheral (a constant config every scheduled run) awgsess = AWG.Initiate() AWG.clock(awgsess, action=['Set', 'EFIXed',2.5e9]) AWG.clear_waveform(awgsess,'all') AWG.alloff(awgsess, action=['Set',1]) # PRESET Output: '''Prepare DAC:''' for ch in range(4): channel = str(ch + 1) AWG.prepare_DAC(awgsess, channel, int(ifperiod*2.5)) # Turn on all 4 channels: AWG.compose_DAC(awgsess, 1, array(squarewave(ifperiod, 0, 0, 1, dt=0.4, clock_multiples=1))) AWG.compose_DAC(awgsess, 2, array(squarewave(ifperiod, 0, 0, 1, dt=0.4, clock_multiples=1))) AWG.compose_DAC(awgsess, 3, array(squarewave(ifperiod, 0, 0, 1, dt=0.4, clock_multiples=1))) AWG.compose_DAC(awgsess, 4, array(squarewave(ifperiod, 0, 0, 1, dt=0.4, clock_multiples=1))) AWG.alloff(awgsess, action=['Set',0]) AWG.ready(awgsess) AWG.play(awgsess) # VSA for Readout vsasess = VSA.InitWithOptions() # Buffer-size for lowest-bound data-collecting instrument: buffersize_1 = samptime.count * 2 #data density of 2 due to IQ print("Buffer-size: %s" %buffersize_1) # User-defined Measurement-FLOW ============================================================================================== if testeach: # measure-time contribution from each measure-loop loopcount, loop_dur = [], [] stage, prev = clocker(0) # Marking starting point of time # Registerring parameter(s)-structure cstructure = [waveform(corder[param]).count for param in structure][:-1] # The last one will become a buffer print('cstructure: %s' %cstructure) measure_loop_1 = range(resumepoint//buffersize_1,datasize//buffersize_1) # saving chunck by chunck improves speed a lot! while True: for i in measure_loop_1: print(Back.BLUE + Fore.WHITE + 'measure %s/%s' %(i,datasize//buffersize_1)) # determining the index-locations for each parameters, i.e. the address at any instance caddress = cdatasearch(i, cstructure) # setting each c-order (From High to Low level of execution): # *************************************************************** for j in range(len(cstructure)-1): # the last one will be run for every i (common sense!) if (not i%prod(cstructure[j+1::])) or i==resumepoint//buffersize_1: # virtual for-loop using exact-multiples condition # print("entering %s-stage" %j) # Optionals: # YOKO if structure[j] == 'Flux-Bias': if "opt" not in fluxbias.data: # check if it is in optional-state if testeach: # adding instrument transition-time between set-values: loopcount += [fluxbias.count] if fluxbias.count > 1: loop_dur += [abs(fluxbias.data[0]-fluxbias.data[1])/0.2 + 35*1e-3] # manually calculating time without really setting parameter on the instrument else: loop_dur += [0] stage, prev = clocker(stage, prev) # Marking time else: YOKO.sweep(yokog, str(fluxbias.data[caddress[structure.index('Flux-Bias')]]), pulsewidth=77*1e-3, sweeprate=0.0007) # A-mode: sweeprate=0.0007 A/s ; V-mode: sweeprate=0.07 V/s # PSG if structure[j] == 'XY-Frequency': if "opt" not in xyfreq.data: # check if it is in optional-state PSG0.frequency(sogo, action=['Set', str(xyfreq.data[caddress[structure.index('XY-Frequency')]]) + "GHz"]) if structure[j] == 'XY-Power': if "opt" not in xypowa.data: # check if it is in optional-state PSG0.power(sogo, action=['Set', str(xypowa.data[caddress[structure.index('XY-Power')]]) + "dBm"]) if structure[j] == 'RO-Frequency': if "opt" not in rofreq.data: # check if it is in optional-state PSG1.frequency(saga, action=['Set', str(rofreq.data[caddress[structure.index('RO-Frequency')]]) + "GHz"]) if structure[j] == 'RO-Power': if "opt" not in ropowa.data: # check if it is in optional-state PSG1.power(saga, action=['Set', str(ropowa.data[caddress[structure.index('RO-Power')]]) + "dBm"]) # Basic # AWG (Every-loop) # define waveforms' elements: ifontime = float(xypwidth.data[caddress[structure.index('XY-Pulse-Width')]]), float(ropwidth.data[caddress[structure.index('RO-Pulse-Width')]]) if "lockxypwd" in str(ropdelay.data[0]): if '+' in str(ropdelay.data[0]): rooffset = float(ropdelay.data[0].split('+')[1]) else: rooffset = 0 # default value ifdelay = float(xypdelay.data[caddress[structure.index('XY-Pulse-Delay')]]), float(xypwidth.data[caddress[structure.index('XY-Pulse-Width')]]) + rooffset print("RO-Pulse Delays behind XY-Pulse for %sns" %(ifdelay[1]-ifdelay[0])) else: ifdelay = float(xypdelay.data[caddress[structure.index('XY-Pulse-Delay')]]), float(ropdelay.data[caddress[structure.index('RO-Pulse-Delay')]]) ifscale = float(xyiflevel.data[caddress[structure.index('XY-ifLevel')]]), float(roiflevel.data[caddress[structure.index('RO-ifLevel')]]) # assigning I-channels for XY and RO: AWG.compose_DAC(awgsess, 1, array(squarewave(ifperiod, ifontime[0], ifdelay[0], ifscale[0], dt=0.4, clock_multiples=1))) AWG.compose_DAC(awgsess, 3, array(squarewave(ifperiod, ifontime[1], ifdelay[1], ifscale[1], dt=0.4, clock_multiples=1)), 1, 200) # put marker on RO channel-I print('Waveform is Ready: %s' %str(AWG.ready(awgsess))) # Basic / Buffer: # VSA (Every-loop) avenum = int(averaging.data[caddress[structure.index('Average')]]) if config['lock-period'] == 'yes': recurrence = int(min([floor(256e6/ifperiod), avenum])) avenum = int(ceil(avenum / recurrence)) else: #default recurrence = 1 VSA.acquisition_time(vsasess, action=['Set',float(recurrence*samptime.count*2e-9)]) # minimum time resolution VSA.preselector_enabled(vsasess, action=['Set',False]) # disable preselector to allow the highest bandwidth of 250MHz print(Fore.YELLOW + "Recurrence: %s" %recurrence) if "lockro" in str(lofreq.data[0]): if '+' in str(lofreq.data[0]): lof_offset = float(lofreq.data[0].split('+')[1]) elif '-' in str(lofreq.data[0]): lof_offset = -float(lofreq.data[0].split('-')[1]) else: lof_offset = 0 # default value VSA.frequency(vsasess, action=['Set',float(rofreq.data[caddress[structure.index('RO-Frequency')]])*1e9+lof_offset]) # freq offset / correction in Hz print("Locking on RO at %sGHz" %(VSA.frequency(vsasess)[1]/1e9)) else: VSA.frequency(vsasess, action=['Set',float(lofreq.data[caddress[structure.index('LO-Frequency')]])*1e9]) VSA.power(vsasess, action=['Set',float(lopowa.data[caddress[structure.index('LO-Power')]])]) VSA.bandwidth(vsasess, action=['Set',250e6]) # maximum LO bandwidth of 250MHz (500MHz Sampling-rate gives 2ns of time resolution) VSA.trigger_source(vsasess, action=['Set',int(1)]) # External Trigger (slave) # Delay for Readout if "lockxypwd" in str(ropdelay.data[0]): # trigger-delay sync with xy-pulse-width for Rabi measurement: VSA.trigger_delay(vsasess, action=['Set', float(adcdelay.data[caddress[structure.index('ADC-delay')]]) + \ float(xypwidth.data[caddress[structure.index('XY-Pulse-Width')]])*1e-9 + rooffset*1e-9]) print("ACQ delays with XY-Pulse for %sns" %int(VSA.trigger_delay(vsasess)[1]/1e-9)) elif "lockropdelay" in str(adcdelay.data[0]): # trigger-delay sync with ro-pulse-delay for T1 measurement: VSA.trigger_delay(vsasess, action=['Set', float(ropdelay.data[caddress[structure.index('RO-Pulse-Delay')]])*1e-9]) print("ACQ delays with RO-Pulse for %sns" %int(VSA.trigger_delay(vsasess)[1]/1e-9)) else: VSA.trigger_delay(vsasess, action=['Set', float(adcdelay.data[caddress[structure.index('ADC-delay')]])]) VSA.external_trigger_level(vsasess, action=['Set',float(0.3)]) VSA.external_trigger_slope(vsasess, action=['Set',int(1)]) # Positive slope VSA.trigger_timeout(vsasess, action=['Set',int(1000)]) # 1s of timeout stat = VSA.Init_Measure(vsasess) # Initiate Measurement # Start Quantum machine: # Start Averaging Loop: vsasn = VSA.samples_number(vsasess)[1] if (vsasn%recurrence) and (recurrence>1): errormsg = "Period must be multiples of 2ns" set_status("SQE_Pulse", dict(msg=errormsg, pause=True)) print(Fore.RED + errormsg) break iqdata = zeros((avenum*recurrence,int(2*vsasn/recurrence))) # Max number of points for VSA in the buffer = 128MS # BUT: M9202A doesn't support Segment Acquisition, which I'm trying to do as follows: for c in range(avenum): VSA.Arm_Measure(vsasess) gd = VSA.Get_Data(vsasess, 2*vsasn) # iqdata[c*recurrence:(c+1)*recurrence,:] = array(gd[1]['ComplexData']).reshape(recurrence,int(2*vsasn/recurrence)) iqdata[c,:] = mean(array(gd[1]['ComplexData']).reshape(recurrence,int(2*vsasn/recurrence)), axis=0) # exporting data for saving endata = zeros(int(2*vsasn/recurrence)) if config['data-option'] == 'AP': print(Fore.BLUE + "%s mode:" %config) idata, qdata = iqdata[:,0::2], iqdata[:,1::2] Adata = mean(sqrt(power(idata,2) + power(qdata,2)), axis=0) Pdata = mean(arctan2(qdata, idata), axis=0) endata[0::2], endata[1::2] = Adata, Pdata else: #default print(Fore.BLUE + "%s mode:" %config) iqdata = mean(iqdata, axis=0) endata = iqdata print("Operation Complete") print(Fore.YELLOW + "\rProgress: %.3f%%" %((i+1)/datasize*buffersize_1*100), end='\r', flush=True) # test for the last loop if there is if testeach: # test each measure-loop: loopcount += [len(measure_loop_1)] loop_dur += [time() - prev] stage, prev =
for explanation. """ if platform.system() == 'Windows': return os.path.getctime(path_to_file) else: stat = os.stat(path_to_file) try: return stat.st_birthtime except AttributeError: # We're probably on Linux. No easy way to get creation dates here, # so we'll settle for when its content was last modified. return stat.st_mtime def get_temp(): """ returns system temp """ logger.info("Reading CORE TEMP...") with open("/sys/class/thermal/thermal_zone0/temp") as f: CPUTemp = f.read() F = str(int(CPUTemp)/1000.0 * 1.8 + 32) C = (float(F) - 32) * 5.0/9.0 return F, C def get_hostname(): """ return system hostname """ return socket.gethostname() def uptime1(): ''' Return uptimes based on seconds since last boot ''' with open('/proc/uptime', 'r') as f: uptime_seconds = float(f.readline().split()[0]) seconds = str(int(uptime_seconds % 60)) minutes = str(int(uptime_seconds /60 % 60)) hours = str(int(uptime_seconds / 60 / 60 % 24)) days = str(int(uptime_seconds / 60 /60 / 24)) # Time unit strings time_d = ' days, ' time_h = ' hours, ' time_m = ' minutes' time_s = ' seconds.' # Change time strings for lower units, prepend zeros if int(days) == 1: time_d = ' day, ' if int(hours) <= 9: hours = '0' + hours if int(hours) == 1: time_h = 'hour ' if int(minutes) <= 9: minutes = '0' + minutes if int(minutes) == 1: time_m = ' minute ' if int(seconds) <= 9: seconds = '0' + seconds if int(seconds) == 1: time_s = ' second.' #print("") #print(days + time_d + hours + ':' + minutes + ':' + seconds) #print('Uptime is ' +days + time_d + hours + time_h + minutes + time_m +' and ' + seconds + time_s) return days, hours, minutes, seconds def get_gateway_ping(): """ pings the gateway to get an idea of lan quality """ logger.info("Reading GW LATENCY...") cmd = """gw=$(route -n | grep UG | awk '{ print $2 }'); ping -c1 $gw | grep '64 bytes'| cut -d'=' -f4""" return subprocess.check_output(cmd, shell=True).decode('utf-8').strip() def get_internet_ping(): """ pings the internet to get an idea of wan quality """ logger.info("Reading LATENCY...") cmd = """ping -c1 dxmini.com| grep '64 bytes'| cut -d'=' -f4""" return subprocess.check_output(cmd, shell=True).decode('utf-8').strip() def uptime(): """ return raspi uptime """ logger.info("Reading UPTIME") return float(subprocess.check_output(['cat', '/proc/uptime']).decode('utf-8').split()[0]) def get_service_tag(): """ returns service tag from flash memory generates one if it's not found """ serialfile = '/etc/dxmini_serial' if os.path.isfile(serialfile): logger.info("Reading SERVICE_TAG...") with open(serialfile,"r") as fi: serial = fi.read() return int(serial) else: serial = "".join(str(uuid.uuid4()).split('-')[3:]).upper() logger.warn("Generating new DXMNI service_tag {}".format(serial)) serial = str(int(serial, 16)) with open(serialfile,"w") as fi: fi.write(serial) fi.close() return int(serial) def get_shadow_tag(): """ returns shadow tag from flash memory generates one if it's not found """ serialfile = '/etc/dxmini_shadow' if os.path.isfile(serialfile): logger.info("Reading SHADOW_TAG...") with open(serialfile,"r") as fi: serial = fi.read() return serial else: serial = "".join(str(uuid.uuid4()).split('-')).upper() logger.warn("Generating new DXMNI shadow_tag {}".format(serial)) with open(serialfile,"w") as fi: fi.write(serial) fi.close() return serial def get_upnp_settings(): """ retrieves current upnp configurations """ upnp_enabled_cmd = """/bin/grep '$DAEMON -a' /usr/local/sbin/pistar-upnp.service | /bin/grep -v -e '^#' | /usr/bin/awk '{ print $4 " " $5 " " $6}'""" upnp_disabled_cmd = """/bin/grep '$DAEMON -a' /usr/local/sbin/pistar-upnp.service | /bin/grep -e '^#' | /usr/bin/awk '{ print $5 " " $6 " " $7}'""" if os.path.isfile('/usr/local/sbin/pistar-upnp.service'): enabled_upnp = subprocess.check_output(upnp_enabled_cmd, shell=True).decode('utf-8') disabled_upnp = subprocess.check_output(upnp_disabled_cmd, shell=True).decode('utf-8') enabled_ports = {'UDP': [], 'TCP': []} disabled_ports = {'UDP': [], 'TCP': []} for line in enabled_upnp.rstrip().split('\n'): fields = line.split() inside = int(fields[0]) outside = int(fields[1]) proto = fields[2] enabled_ports[proto].append({"in": inside, "out": outside}) for line in disabled_upnp.rstrip().split('\n'): fields = line.split() inside = int(fields[0]) outside = int(fields[1]) proto = fields[2] disabled_ports[proto].append({"in": inside, "out": outside}) return {"enabled": enabled_ports, "disabled": disabled_ports} else: return dict() def get_dxmini_panel_version(): """ ew this is hacky """ logger.info("Reading PHP_APPLICATION_VERSION_DATA...") r = requests.get('http://localhost/config/version.php') resp = r.json() return (resp['VENDOR_PANEL_VERSION'], resp['VENDOR_PANEL_REVISION'], resp['PISTAR_VERSION']) def get_model(): """ returns model from flash """ logger.info("Reading DEVICE_MODEL...") serialfile = '/etc/dxmini_model' if os.path.isfile(serialfile): with open(serialfile,"r") as fi: serial = fi.read() return serial.strip() else: return None def get_timezone(): """return tzinfo""" logger.info("Reading TIMEZONE...") myfile = '/etc/timezone' if os.path.isfile(myfile): with open(myfile,"r") as fi: tz = fi.read() return str(tz).strip() else: return None def get_revision(): """ returns revision from flash """ logger.info("Reading DEVICE_REVISION...") serialfile = '/etc/dxmini_revision' if os.path.isfile(serialfile): with open(serialfile,"r") as fi: serial = fi.read() return serial.strip() else: return None def get_issue(): """ returns distro from /etc/issue """ logger.info("Reading DEVICE_ISSUE...") serialfile = '/etc/issue.net' if os.path.isfile(serialfile): with open(serialfile,"r") as fi: serial = fi.read() return serial.strip() else: return None def get_historical_calls(mmdvm_config): """ get current call """ histuser_file = '/etc/.callsign_history' if not os.path.isfile(histuser_file): logger.info("Scheduling rebuild of callsign index") history = {"first_call": get_current_call(mmdvm_config), "callsign_history": [get_current_call(mmdvm_config)]} with open(histuser_file,"w") as fi: logger.info("Build new callsign index") fi.write(json.dumps(history, indent=3)) return history else: with open(histuser_file,"r") as fi: history = json.loads(fi.read()) if get_current_call(mmdvm_config) not in history['callsign_history']: logger.info("Adding new CALL") history['callsign_history'].append(get_current_call(mmdvm_config)) with open(histuser_file,"w") as fi: logger.info("Write new callsign index") fi.write(json.dumps(history, indent=3)) return history else: logger.info("Reading CALLSIGN...") return history def get_historical_rids(mmdvm_config): """ get historical radio ids """ histuser_file = '/etc/.rid_history' if not os.path.isfile(histuser_file): logger.info("Need to build DMR_ID index") history = {"first_rid": get_current_rid(mmdvm_config), "rid_history": [get_current_rid(mmdvm_config)]} with open(histuser_file,"w") as fi: logger.info("Build new DMR_ID index") fi.write(json.dumps(history, indent=3)) return history else: with open(histuser_file,"r") as fi: history = json.loads(fi.read()) if get_current_rid(mmdvm_config) not in history['rid_history']: logger.info("Adding new DMR_ID") history['rid_history'].append(get_current_rid(mmdvm_config)) with open(histuser_file,"w") as fi: logger.info("Write new DMR_ID index") fi.write(json.dumps(history, indent=3)) return history else: logger.info("Reading DMR_ID...") return history def get_current_call(config): """ returns first call used in flash """ firstuser_file = '/etc/first_user' first_user = config['general'].get('callsign', None) if first_user: with open(firstuser_file,"w") as fi: fi.write(first_user) else: return "N0CALL" return first_user def get_current_rid(config): """ returns current radio id """ firstuser_file = '/etc/first_rid' first_user = config['general'].get('id', None) if first_user: with open(firstuser_file,"w") as fi: fi.write(first_user) else: return "0000000" return first_user def get_customer_production_date(): """ returns when the DXMINI goes into production """ serialfile = '/.in_production' if os.path.isfile(serialfile): return int(creation_date('/.in_production')) else: return None def file_age_in_seconds(pathname): """ return a files exact age in seconds """ if not os.path.isfile(pathname): touch(pathname) return time.time() - os.stat(pathname)[stat.ST_MTIME] def get_interface(): """ get interface stats """ logger.info("Reading INTERFACE COUNTERS...") hwaddr = subprocess.check_output("ifconfig wlan0| head -1 | awk '{ print $5 }'", shell=True).decode('utf-8').strip() meta_1 = [{ x.strip().split('=')[0].lower().replace(' ', '_') : x.strip().split('=')[1] } for x in subprocess.check_output("iwconfig wlan0 | grep Tx-Power", shell=True).decode('utf-8').strip().split(' ')] meta_2 = [{ x.strip().split('=')[0].lower().replace(' ', '_') : x.strip().split('=')[1] } for x in subprocess.check_output("iwconfig wlan0 | grep 'Signal level'", shell=True).decode('utf-8').strip().split(' ')] meta_3 = [{ x.strip().split(':')[0].lower().replace(' ', '_') : x.strip().split(':')[1] } for x in subprocess.check_output("iwconfig wlan0 | grep 'Access Point'", shell=True).decode('utf-8').strip().split(' ')] meta_4 = [{ x.strip().split(':')[0].lower().replace(' ', '_') : x.strip().split(':')[1] } for x in subprocess.check_output("iwconfig wlan0 | grep 'Missed beacon'", shell=True).decode('utf-8').strip().split(' ')] meta_5 = [{ x.strip().split(':')[0].lower().replace(' ', '_') : x.strip().split(':')[1] } for x in subprocess.check_output("iwconfig wlan0 | grep 'nvalid crypt'", shell=True).decode('utf-8').strip().split(' ')] rx_packets = [{ x.split(':')[0].lower().replace(' ', '_') : x.split(':')[1]} for x in subprocess.check_output("ifconfig wlan0 | grep 'RX packets'", shell=True).decode('utf-8').strip().split(' ')[1:]] tx_packets = [{ x.split(':')[0].lower().replace(' ', '_') : x.split(':')[1]} for x in subprocess.check_output("ifconfig wlan0 | grep 'TX packets'", shell=True).decode('utf-8').strip().split(' ')[1:]] new_dict = {} for item in meta_1: for k, v in item.items(): new_dict[k] = v for item in meta_2: for k, v in item.items(): new_dict[k] = v for item in meta_3: for k, v in item.items(): new_dict[k] = v for item in meta_4: for k, v in item.items(): new_dict[k] = v for item in meta_5: for k, v in item.items(): new_dict[k] = v new_dict['rx_counts'] = dict() for item in rx_packets: for k, v in item.items(): new_dict['rx_counts'][k] = v new_dict['tx_counts'] = dict() for item in tx_packets: for k, v in item.items(): new_dict['tx_counts'][k] = v del new_dict['access_point'] new_dict['hwaddr_ap'] = ":".join(subprocess.check_output("iwconfig wlan0 | grep 'Access Point'", shell=True).decode('utf-8').strip().split(' ')[2].split(':')[1:]).strip().lower() new_dict['hwaddr'] = hwaddr.lower() new_dict['ipaddr'] = get_nat_ip() return new_dict def get_nat_ip(): """ get the local address """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable, neat trick eh? s.connect(('10.255.255.255', 1)) a = s.getsockname()[0] except: a = '127.0.0.1' finally: s.close() return a def register_client(): mmdvm_config = get_mmdvm_config() historical_calls = get_historical_calls(mmdvm_config) historical_rids = get_historical_rids(mmdvm_config) gw_ping = get_gateway_ping() net_ping = get_internet_ping() temp = get_temp() web_panel_version, web_panel_rev, web_panel_upstream_version = get_dxmini_panel_version() hello = { "entry": { "user": { "api_token": get_shadow_tag(), "tz": get_timezone(), "activation_dt": { 'dt': get_customer_production_date(), 'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(get_customer_production_date()))}, "identities": { "ham": { "initial": historical_calls['first_call'], "history": historical_calls['callsign_history'], "current": get_current_call(mmdvm_config), }, "dmr": { "initial":
<reponame>BenjaminLiuPenrose/Berkeley-CS-100 # Databricks notebook source exported at Fri, 24 Jun 2016 23:04:35 UTC # MAGIC %md # MAGIC <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/"> <img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-nd/4.0/88x31.png"/> </a> <br/> This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/"> Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. </a> # COMMAND ---------- # MAGIC %md # MAGIC #![Spark Logo](http://spark-mooc.github.io/web-assets/images/ta_Spark-logo-small.png) + ![Python Logo](http://spark-mooc.github.io/web-assets/images/python-logo-master-v3-TM-flattened_small.png) # MAGIC # **Spark Tutorial: Learning Apache Spark** # MAGIC # MAGIC This tutorial will teach you how to use [Apache Spark](http://spark.apache.org/), a framework for large-scale data processing, within a notebook. Many traditional frameworks were designed to be run on a single computer. However, many datasets today are too large to be stored on a single computer, and even when a dataset can be stored on one computer (such as the datasets in this tutorial), the dataset can often be processed much more quickly using multiple computers. # MAGIC # MAGIC Spark has efficient implementations of a number of transformations and actions that can be composed together to perform data processing and analysis. Spark excels at distributing these operations across a cluster while abstracting away many of the underlying implementation details. Spark has been designed with a focus on scalability and efficiency. With Spark you can begin developing your solution on your laptop, using a small dataset, and then use that same code to process terabytes or even petabytes across a distributed cluster. # MAGIC # MAGIC **During this tutorial we will cover:** # MAGIC # MAGIC * *Part 1:* Basic notebook usage and [Python](https://docs.python.org/2/) integration # MAGIC * *Part 2:* An introduction to using [Apache Spark](https://spark.apache.org/) with the [PySpark SQL API](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark-sql-module) running in a notebook # MAGIC * *Part 3:* Using DataFrames and chaining together transformations and actions # MAGIC * *Part 4*: Python Lambda functions and User Defined Functions # MAGIC * *Part 5:* Additional DataFrame actions # MAGIC * *Part 6:* Additional DataFrame transformations # MAGIC * *Part 7:* Caching DataFrames and storage options # MAGIC * *Part 8:* Debugging Spark applications and lazy evaluation # MAGIC # MAGIC The following transformations will be covered: # MAGIC * `select()`, `filter()`, `distinct()`, `dropDuplicates()`, `orderBy()`, `groupBy()` # MAGIC # MAGIC The following actions will be covered: # MAGIC * `first()`, `take()`, `count()`, `collect()`, `show()` # MAGIC # MAGIC Also covered: # MAGIC * `cache()`, `unpersist()` # MAGIC # MAGIC Note that, for reference, you can look up the details of these methods in the [Spark's PySpark SQL API](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark-sql-module) # COMMAND ---------- # MAGIC %md # MAGIC ## **Part 1: Basic notebook usage and [Python](https://docs.python.org/2/) integration ** # COMMAND ---------- # MAGIC %md # MAGIC ### (1a) Notebook usage # MAGIC # MAGIC A notebook is comprised of a linear sequence of cells. These cells can contain either markdown or code, but we won't mix both in one cell. When a markdown cell is executed it renders formatted text, images, and links just like HTML in a normal webpage. The text you are reading right now is part of a markdown cell. Python code cells allow you to execute arbitrary Python commands just like in any Python shell. Place your cursor inside the cell below, and press "Shift" + "Enter" to execute the code and advance to the next cell. You can also press "Ctrl" + "Enter" to execute the code and remain in the cell. These commands work the same in both markdown and code cells. # COMMAND ---------- # This is a Python cell. You can run normal Python code here... print 'The sum of 1 and 1 is {0}'.format(1+1) # COMMAND ---------- # Here is another Python cell, this time with a variable (x) declaration and an if statement: x = 42 if x > 40: print 'The sum of 1 and 2 is {0}'.format(1+2) # COMMAND ---------- # MAGIC %md # MAGIC ### (1b) Notebook state # MAGIC # MAGIC As you work through a notebook it is important that you run all of the code cells. The notebook is stateful, which means that variables and their values are retained until the notebook is detached (in Databricks) or the kernel is restarted (in Jupyter notebooks). If you do not run all of the code cells as you proceed through the notebook, your variables will not be properly initialized and later code might fail. You will also need to rerun any cells that you have modified in order for the changes to be available to other cells. # COMMAND ---------- # This cell relies on x being defined already. # If we didn't run the cells from part (1a) this code would fail. print x * 2 # COMMAND ---------- # MAGIC %md # MAGIC ### (1c) Library imports # MAGIC # MAGIC We can import standard Python libraries ([modules](https://docs.python.org/2/tutorial/modules.html)) the usual way. An `import` statement will import the specified module. In this tutorial and future labs, we will provide any imports that are necessary. # COMMAND ---------- # Import the regular expression library import re m = re.search('(?<=abc)def', 'abcdef') m.group(0) # COMMAND ---------- # Import the datetime library import datetime print 'This was last run on: {0}'.format(datetime.datetime.now()) # COMMAND ---------- # MAGIC %md # MAGIC ## **Part 2: An introduction to using [Apache Spark](https://spark.apache.org/) with the [PySpark SQL API](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark-sql-module) running in a notebook** # COMMAND ---------- # MAGIC %md # MAGIC ### Spark Context # MAGIC # MAGIC In Spark, communication occurs between a driver and executors. The driver has Spark jobs that it needs to run and these jobs are split into tasks that are submitted to the executors for completion. The results from these tasks are delivered back to the driver. # MAGIC # MAGIC In part 1, we saw that normal Python code can be executed via cells. When using Databricks this code gets executed in the Spark driver's Java Virtual Machine (JVM) and not in an executor's JVM, and when using an Jupyter notebook it is executed within the kernel associated with the notebook. Since no Spark functionality is actually being used, no tasks are launched on the executors. # MAGIC # MAGIC In order to use Spark and its DataFrame API we will need to use a `SQLContext`. When running Spark, you start a new Spark application by creating a [SparkContext](http://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.SparkContext). You can then create a [SQLContext](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.SQLContext) from the `SparkContext`. When the `SparkContext` is created, it asks the master for some cores to use to do work. The master sets these cores aside just for you; they won't be used for other applications. When using Databricks, both a `SparkContext` and a `SQLContext` are created for you automatically. `sc` is your `SparkContext`, and `sqlContext` is your `SQLContext`. # COMMAND ---------- # MAGIC %md # MAGIC ### (2a) Example Cluster # MAGIC The diagram shows an example cluster, where the slots allocated for an application are outlined in purple. (Note: We're using the term _slots_ here to indicate threads available to perform parallel work for Spark. # MAGIC Spark documentation often refers to these threads as _cores_, which is a confusing term, as the number of slots available on a particular machine does not necessarily have any relationship to the number of physical CPU # MAGIC cores on that machine.) # MAGIC # MAGIC <img src="http://spark-mooc.github.io/web-assets/images/cs105x/diagram-2a.png" style="height: 800px;float: right"/> # MAGIC # MAGIC You can view the details of your Spark application in the Spark web UI. The web UI is accessible in Databricks by going to "Clusters" and then clicking on the "Spark UI" link for your cluster. In the web UI, under the "Jobs" tab, you can see a list of jobs that have been scheduled or run. It's likely there isn't any thing interesting here yet because we haven't run any jobs, but we'll return to this page later. # MAGIC # MAGIC At a high level, every Spark application consists of a driver program that launches various parallel operations on executor Java Virtual Machines (JVMs) running either in a cluster or locally on the same machine. In Databricks, "Databricks Shell" is the driver program. When running locally, `pyspark` is the driver program. In all cases, this driver program contains the main loop for the program and creates distributed datasets
<reponame>Abhi58/sympy from sympy import (Symbol, Matrix, MatrixSymbol, S, Indexed, Basic, Set, And, Tuple, Eq, FiniteSet, ImmutableMatrix, nsimplify, Lambda, Mul, Sum, Dummy, Lt, IndexedBase, linsolve, Piecewise, eye) from sympy.stats.rv import (RandomIndexedSymbol, random_symbols, RandomSymbol, _symbol_converter) from sympy.stats.joint_rv import JointDistributionHandmade, JointDistribution from sympy.core.compatibility import string_types from sympy.core.relational import Relational from sympy.stats.symbolic_probability import Probability, Expectation from sympy.stats.stochastic_process import StochasticPSpace from sympy.logic.boolalg import Boolean __all__ = [ 'StochasticProcess', 'DiscreteTimeStochasticProcess', 'DiscreteMarkovChain', 'TransitionMatrixOf', 'StochasticStateSpaceOf' ] def _set_converter(itr): """ Helper function for converting list/tuple/set to Set. If parameter is not an instance of list/tuple/set then no operation is performed. Returns ======= Set The argument converted to Set. Raises ====== TypeError If the argument is not an instance of list/tuple/set. """ if isinstance(itr, (list, tuple, set)): itr = FiniteSet(*itr) if not isinstance(itr, Set): raise TypeError("%s is not an instance of list/tuple/set."%(itr)) return itr def _matrix_checks(matrix): if not isinstance(matrix, (Matrix, MatrixSymbol, ImmutableMatrix)): raise TypeError("Transition probabilities etiher should " "be a Matrix or a MatrixSymbol.") if matrix.shape[0] != matrix.shape[1]: raise ValueError("%s is not a square matrix"%(matrix)) if isinstance(matrix, Matrix): matrix = ImmutableMatrix(matrix.tolist()) return matrix class StochasticProcess(Basic): """ Base class for all the stochastic processes whether discrete or continuous. Parameters ========== sym: Symbol or string_types state_space: Set The state space of the stochastic process, by default S.Reals. For discrete sets it is zero indexed. See Also ======== DiscreteTimeStochasticProcess """ index_set = S.Reals def __new__(cls, sym, state_space=S.Reals, **kwargs): sym = _symbol_converter(sym) state_space = _set_converter(state_space) return Basic.__new__(cls, sym, state_space) @property def symbol(self): return self.args[0] @property def state_space(self): return self.args[1] def __call__(self, time): """ Overrided in ContinuousTimeStochasticProcess. """ raise NotImplementedError("Use [] for indexing discrete time stochastic process.") def __getitem__(self, time): """ Overrided in DiscreteTimeStochasticProcess. """ raise NotImplementedError("Use () for indexing continuous time stochastic process.") def probability(self, condition): raise NotImplementedError() def joint_distribution(self, *args): """ Computes the joint distribution of the random indexed variables. Parameters ========== args: iterable The finite list of random indexed variables/the key of a stochastic process whose joint distribution has to be computed. Returns ======= JointDistribution The joint distribution of the list of random indexed variables. An unevaluated object is returned if it is not possible to compute the joint distribution. Raises ====== ValueError: When the arguments passed are not of type RandomIndexSymbol or Number. """ args = list(args) for i, arg in enumerate(args): if S(arg).is_Number: if self.index_set.is_subset(S.Integers): args[i] = self.__getitem__(arg) else: args[i] = self.__call__(arg) elif not isinstance(arg, RandomIndexedSymbol): raise ValueError("Expected a RandomIndexedSymbol or " "key not %s"%(type(arg))) if args[0].pspace.distribution == None: # checks if there is any distribution available return JointDistribution(*args) # TODO: Add tests for the below part of the method, when implementation of Bernoulli Process # is completed pdf = Lambda(*[arg.name for arg in args], expr=Mul.fromiter(arg.pspace.distribution.pdf(arg) for arg in args)) return JointDistributionHandmade(pdf) def expectation(self, condition, given_condition): raise NotImplementedError("Abstract method for expectation queries.") class DiscreteTimeStochasticProcess(StochasticProcess): """ Base class for all discrete stochastic processes. """ def __getitem__(self, time): """ For indexing discrete time stochastic processes. Returns ======= RandomIndexedSymbol """ if time not in self.index_set: raise IndexError("%s is not in the index set of %s"%(time, self.symbol)) idx_obj = Indexed(self.symbol, time) pspace_obj = StochasticPSpace(self.symbol, self) return RandomIndexedSymbol(idx_obj, pspace_obj) class TransitionMatrixOf(Boolean): """ Assumes that the matrix is the transition matrix of the process. """ def __new__(cls, process, matrix): if not isinstance(process, DiscreteMarkovChain): raise ValueError("Currently only DiscreteMarkovChain " "support TransitionMatrixOf.") matrix = _matrix_checks(matrix) return Basic.__new__(cls, process, matrix) process = property(lambda self: self.args[0]) matrix = property(lambda self: self.args[1]) class StochasticStateSpaceOf(Boolean): def __new__(cls, process, state_space): if not isinstance(process, DiscreteMarkovChain): raise ValueError("Currently only DiscreteMarkovChain " "support StochasticStateSpaceOf.") state_space = _set_converter(state_space) return Basic.__new__(cls, process, state_space) process = property(lambda self: self.args[0]) state_space = property(lambda self: self.args[1]) class DiscreteMarkovChain(DiscreteTimeStochasticProcess): """ Represents discrete Markov chain. Parameters ========== sym: Symbol state_space: Set Optional, by default, S.Reals trans_probs: Matrix/ImmutableMatrix/MatrixSymbol Optional, by default, None Examples ======== >>> from sympy.stats import DiscreteMarkovChain, TransitionMatrixOf >>> from sympy import Matrix, MatrixSymbol, Eq >>> from sympy.stats import P >>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T) >>> YS = DiscreteMarkovChain("Y") >>> Y.state_space {0, 1, 2} >>> Y.transition_probabilities Matrix([ [0.5, 0.2, 0.3], [0.2, 0.5, 0.3], [0.2, 0.3, 0.5]]) >>> TS = MatrixSymbol('T', 3, 3) >>> P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TS)) T[0, 2]*T[1, 0] + T[1, 1]*T[1, 2] + T[1, 2]*T[2, 2] >>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) 0.36 """ index_set = S.Naturals0 def __new__(cls, sym, state_space=S.Reals, trans_probs=None): sym = _symbol_converter(sym) state_space = _set_converter(state_space) if trans_probs != None: trans_probs = _matrix_checks(trans_probs) return Basic.__new__(cls, sym, state_space, trans_probs) @property def transition_probabilities(self): """ Transition probabilities of discrete Markov chain, either an instance of Matrix or MatrixSymbol. """ return self.args[2] def _extract_information(self, given_condition): """ Helper function to extract information, like, transition probabilities, state space, etc. """ trans_probs, state_space = self.transition_probabilities, self.state_space if isinstance(given_condition, And): gcs = given_condition.args for gc in gcs: if isinstance(gc, TransitionMatrixOf): trans_probs = gc.matrix if isinstance(gc, StochasticStateSpaceOf): state_space = gc.state_space if isinstance(gc, Eq): given_condition = gc if isinstance(given_condition, TransitionMatrixOf): trans_probs = given_condition.matrix if isinstance(given_condition, StochasticStateSpaceOf): state_space = given_condition.state_space return trans_probs, state_space, given_condition def _check_trans_probs(self, trans_probs): """ Helper function for checking the validity of transition probabilities. """ if not isinstance(trans_probs, MatrixSymbol): rows = trans_probs.tolist() for row in rows: if (sum(row) - 1) != 0: raise ValueError("Probabilities in a row must sum to 1. " "If you are using Float or floats then please use Rational.") def _work_out_state_space(self, state_space, given_condition, trans_probs): """ Helper function to extract state space if there is a random symbol in the given condition. """ # if given condition is None, then there is no need to work out # state_space from random variables if given_condition != None: rand_var = list(given_condition.atoms(RandomSymbol) - given_condition.atoms(RandomIndexedSymbol)) if len(rand_var) == 1: state_space = rand_var[0].pspace.set if not FiniteSet(*[i for i in range(trans_probs.shape[0])]).is_subset(state_space): raise ValueError("state space is not compatible with the transition probabilites.") return state_space def _preprocess(self, given_condition, evaluate): """ Helper function for pre-processing the information. """ is_insufficient = False if not evaluate: # avoid pre-processing if the result is not to be evaluated return (True, None, None, None) # extracting transition matrix and state space trans_probs, state_space, given_condition = self._extract_information(given_condition) # given_condition does not have sufficient information # for computations if trans_probs == None or \ given_condition == None: is_insufficient = True else: # checking transition probabilities self._check_trans_probs(trans_probs) # working out state space state_space = self._work_out_state_space(state_space, given_condition, trans_probs) return is_insufficient, trans_probs, state_space, given_condition def _transient2transient(self): """ Computes the one step probabilities of transient states to transient states. Used in finding fundamental matrix, absorbing probabilties. """ trans_probs = self.transition_probabilities if not isinstance(trans_probs, ImmutableMatrix): return None m = trans_probs.shape[0] trans_states = [i for i in range(m) if trans_probs[i, i] != 1] t2t = [[trans_probs[si, sj] for sj in trans_states] for si in trans_states] return ImmutableMatrix(t2t) def _transient2absorbing(self): """ Computes the one step probabilities of transient states to absorbing states. Used in finding fundamental matrix, absorbing probabilties. """ trans_probs = self.transition_probabilities if not isinstance(trans_probs, ImmutableMatrix): return None m, trans_states, absorb_states = \ trans_probs.shape[0], [], [] for i in range(m): if trans_probs[i, i] == 1: absorb_states.append(i) else: trans_states.append(i) if not absorb_states or not trans_states: return None t2a = [[trans_probs[si, sj] for sj in absorb_states] for si in trans_states] return ImmutableMatrix(t2a) def fundamental_matrix(self): Q = self._transient2transient() if Q == None: return None I = eye(Q.shape[0]) if (I - Q).det() == 0: raise ValueError("Fundamental matrix doesn't exists.") return ImmutableMatrix((I - Q).inv().tolist()) def absorbing_probabilites(self): """ Computes the absorbing probabilities, i.e., the ij-th entry of the matrix denotes the probability of Markov chain being absorbed in state j starting from state i. """ R = self._transient2absorbing() N = self.fundamental_matrix() if R == None or N == None: return None return N*R def is_regular(self): w = self.fixed_row_vector() if w is None or isinstance(w, (Lambda)): return None return all((wi > 0) == True for wi in w.row(0)) def is_absorbing_state(self, state): trans_probs = self.transition_probabilities if isinstance(trans_probs, ImmutableMatrix) and \ state < trans_probs.shape[0]: return S(trans_probs[state, state]) == S.One def is_absorbing_chain(self): trans_probs = self.transition_probabilities return any(self.is_absorbing_state(state) == True for state in range(trans_probs.shape[0])) def fixed_row_vector(self): trans_probs
<reponame>hulecom/read-GRACE-harmonics #!/usr/bin/env python u""" calc_sensitivity_kernel.py Written by <NAME> (06/2021) Calculates spatial sensitivity kernels through a least-squares mascon procedure COMMAND LINE OPTIONS: --help: list the command line options -O X, --output-directory X: output directory for mascon files --lmin X: minimum spherical harmonic degree -l X, --lmax X: maximum spherical harmonic degree -m X, --mmax X: maximum spherical harmonic order -R X, --radius X: Gaussian smoothing radius (km) -n X, --love X: Load Love numbers dataset 0: Han and Wahr (1995) values from PREM 1: Gegout (2005) values from PREM 2: Wang et al. (2012) values from PREM --reference X: Reference frame for load love numbers CF: Center of Surface Figure (default) CM: Center of Mass of Earth System CE: Center of Mass of Solid Earth -F X, --format X: input and output data format ascii netCDF4 HDF5 --mask X: Land-sea mask for redistributing mascon mass and land water flux --mascon-file X: index file of mascons spherical harmonics --redistribute-mascons: redistribute mascon mass over the ocean --fit-method X: method for fitting sensitivity kernel to harmonics 1: mass coefficients 2: geoid coefficients --log: Output log of files created for each job -V, --verbose: Verbose output of processing run -M X, --mode X: Permissions mode of the files created PYTHON DEPENDENCIES: numpy: Scientific Computing Tools For Python https://numpy.org https://numpy.org/doc/stable/user/numpy-for-matlab-users.html netCDF4: Python interface to the netCDF C library https://unidata.github.io/netcdf4-python/netCDF4/index.html h5py: Pythonic interface to the HDF5 binary data format. https://www.h5py.org/ future: Compatibility layer between Python 2 and Python 3 https://python-future.org/ PROGRAM DEPENDENCIES: read_love_numbers.py: reads Load Love Numbers from Han and Wahr (1995) plm_holmes.py: Computes fully normalized associated Legendre polynomials gauss_weights.py: Computes the Gaussian weights as a function of degree ocean_stokes.py: reads a land-sea mask and converts to spherical harmonics gen_stokes.py: converts a spatial field into spherical harmonic coefficients harmonic_summation.py: calculates a spatial field from spherical harmonics harmonics.py: spherical harmonic data class for processing GRACE/GRACE-FO destripe_harmonics.py: calculates the decorrelation (destriping) filter and filters the GRACE/GRACE-FO coefficients for striping errors ncdf_read_stokes.py: reads spherical harmonic netcdf files ncdf_stokes.py: writes output spherical harmonic data to netcdf hdf5_read_stokes.py: reads spherical harmonic HDF5 files hdf5_stokes.py: writes output spherical harmonic data to HDF5 spatial.py: spatial data class for reading, writing and processing data ncdf_read.py: reads input spatial data from netCDF4 files hdf5_read.py: reads input spatial data from HDF5 files ncdf_write.py: writes output spatial data to netCDF4 hdf5_write.py: writes output spatial data to HDF5 units.py: class for converting GRACE/GRACE-FO Level-2 data to specific units utilities.py: download and management utilities for files REFERENCES: <NAME>, <NAME> and <NAME>. "Regional acceleration in ice mass loss from Greenland and Antarctica using GRACE time-variable gravity data". Geophysical Research Letters, 41(22):8130-8137, 2014. https://doi.org/10.1002/2014GL061052 <NAME>, <NAME>, <NAME>, and <NAME> Swenson "Recent contributions of glaciers and ice caps to sea level rise". Nature, 482, 514-518 (2012). https://doi.org/10.1038/nature10847 <NAME>, <NAME>, <NAME> Swenson, "Dwindling groundwater resources in northern India, from satellite gravity observations", Geophysical Research Letters, 36(18), L18401, (2009). https://doi.org/10.1029/2009GL039401 UPDATE HISTORY: Updated 06/2021: switch from parameter files to argparse arguments Updated 05/2021: define int/float precision to prevent deprecation warning Updated 04/2021: add parser object for removing commented or empty lines Updated 01/2021: harmonics object output from gen_stokes.py/ocean_stokes.py Updated 12/2020: added more love number options Updated 10/2020: use argparse to set command line parameters Updated 08/2020: use utilities to define path to load love numbers file Updated 04/2020: using the harmonics class for spherical harmonic operations updated load love numbers read function Updated 10/2019: changing Y/N flags to True/False Updated 10/2018: verify integers for python3 compatibility Updated 06/2018: using python3 compatible octal and input Updated 03/2018: added extrapolation of load love numbers if LMAX > 696 Updated 09/2017: use a different land-sea mask for calculating ocean_Ylms use rcond=-1 in numpy least-squares algorithm Updated 05/2016: using __future__ print function Updated 02/2016: direct calculation of number of harmonics n_harm use getopt parameters to set number of PROCESSES to run in parallel, whether or not to output a log file, added new help module Updated 11/2015: create unique log filenames Updated 07/2015: added output of the sensitivity kernel Ylms in addition to the spatial fields (rather than just the spatial fields) will output logs with parameters and output_files added multiprocessing error handling with traceback Updated 05/2015: added parameter MMAX for LMAX != MMAX added portion to redistribute mascon mass uniformly over the ocean Updated 10/2014: distributed computing with the multiprocessing module added INTERVAL parameter for (degree spacing)/2 input/output file type (ascii, netCDF4, HDF5) Updated 05/2014: added import functions Updated 02/2014: updated comments and added os.path.joins for connecting directories and files (generalizing code) some general updates to the program code Updated 08/2013: general updates to inputting data Updated 03/2012: edited to use new gen_stokes time-series option Written 02/2012 """ from __future__ import print_function, division import sys import os import re import time import argparse import numpy as np import traceback import gravity_toolkit.utilities as utilities from gravity_toolkit.harmonics import harmonics from gravity_toolkit.spatial import spatial from gravity_toolkit.units import units from gravity_toolkit.read_love_numbers import read_love_numbers from gravity_toolkit.plm_holmes import plm_holmes from gravity_toolkit.gauss_weights import gauss_weights from gravity_toolkit.ocean_stokes import ocean_stokes from gravity_toolkit.harmonic_summation import harmonic_summation #-- PURPOSE: keep track of threads def info(args): print(os.path.basename(sys.argv[0])) print(args) print('module name: {0}'.format(__name__)) if hasattr(os, 'getppid'): print('parent process: {0:d}'.format(os.getppid())) print('process id: {0:d}'.format(os.getpid())) #-- PURPOSE: read load love numbers for the range of spherical harmonic degrees def load_love_numbers(LMAX, LOVE_NUMBERS=0, REFERENCE='CF'): """ Reads PREM load Love numbers for the range of spherical harmonic degrees and applies isomorphic parameters Arguments --------- LMAX: maximum spherical harmonic degree Keyword arguments ----------------- LOVE_NUMBERS: Load Love numbers dataset 0: Han and Wahr (1995) values from PREM 1: Gegout (2005) values from PREM 2: Wang et al. (2012) values from PREM REFERENCE: Reference frame for calculating degree 1 love numbers CF: Center of Surface Figure (default) CM: Center of Mass of Earth System CE: Center of Mass of Solid Earth Returns ------- kl: Love number of Gravitational Potential hl: Love number of Vertical Displacement ll: Love number of Horizontal Displacement """ #-- load love numbers file if (LOVE_NUMBERS == 0): #-- PREM outputs from Han and Wahr (1995) #-- https://doi.org/10.1111/j.1365-246X.1995.tb01819.x love_numbers_file = utilities.get_data_path( ['data','love_numbers']) header = 2 columns = ['l','hl','kl','ll'] elif (LOVE_NUMBERS == 1): #-- PREM outputs from Gegout (2005) #-- http://gemini.gsfc.nasa.gov/aplo/ love_numbers_file = utilities.get_data_path( ['data','Load_Love2_CE.dat']) header = 3 columns = ['l','hl','ll','kl'] elif (LOVE_NUMBERS == 2): #-- PREM outputs from Wang et al. (2012) #-- https://doi.org/10.1016/j.cageo.2012.06.022 love_numbers_file = utilities.get_data_path( ['data','PREM-LLNs-truncated.dat']) header = 1 columns = ['l','hl','ll','kl','nl','nk'] #-- LMAX of load love numbers from Han and Wahr (1995) is 696. #-- from Wahr (2007) linearly interpolating kl works #-- however, as we are linearly extrapolating out, do not make #-- LMAX too much larger than 696 #-- read arrays of kl, hl, and ll Love Numbers hl,kl,ll = read_love_numbers(love_numbers_file, LMAX=LMAX, HEADER=header, COLUMNS=columns, REFERENCE=REFERENCE, FORMAT='tuple') #-- return a tuple of load love numbers return (hl,kl,ll) #-- PURPOSE: calculate a regional time-series through a least #-- squares mascon process def calc_sensitivity_kernel(LMAX, RAD, LMIN=None, MMAX=None, LOVE_NUMBERS=0, REFERENCE=None, DATAFORM=None, MASCON_FILE=None, REDISTRIBUTE_MASCONS=False, FIT_METHOD=0, LANDMASK=None, DDEG=None, INTERVAL=None, OUTPUT_DIRECTORY=None, MODE=0o775): #-- file information suffix = dict(ascii='txt', netCDF4='nc', HDF5='H5') #-- file parser for reading index files #-- removes commented lines (can comment out files in the index) #-- removes empty lines (if there are extra empty lines) parser = re.compile(r'^(?!\#|\%|$)', re.VERBOSE) #-- Create output Directory if not currently existing if (not os.access(OUTPUT_DIRECTORY,os.F_OK)): os.mkdir(OUTPUT_DIRECTORY) #-- list object of output files for file logs (full path) output_files = [] #-- read arrays of kl, hl, and ll Love Numbers hl,kl,ll = load_love_numbers(LMAX, LOVE_NUMBERS=LOVE_NUMBERS, REFERENCE=REFERENCE) #-- Earth Parameters factors = units(lmax=LMAX).harmonic(hl,kl,ll) #-- Average Density of the Earth [g/cm^3] rho_e = factors.rho_e #-- Average Radius of the Earth [cm] rad_e = factors.rad_e #-- input/output string for both LMAX==MMAX and LMAX != MMAX cases MMAX = np.copy(LMAX) if not MMAX else MMAX order_str = 'M{0:d}'.format(MMAX) if (MMAX != LMAX) else '' #-- Calculating the Gaussian smoothing for radius RAD if (RAD != 0): wt = 2.0*np.pi*gauss_weights(RAD,LMAX) gw_str = '_r{0:0.0f}km'.format(RAD) else: #-- else = 1 wt = np.ones((LMAX+1)) gw_str = '' #-- Read Ocean function and convert to Ylms for redistribution
FITS filename Seq = Sequence number Disk = Disk number for underlying files FOV = Field of view (deg) for Mosaic doFull = If True, create full field (FOV) image NField = Number of fields defined in input, if unspecified derive from data and FOV xCells = Cell spacing in X (asec) for all images, if unspecified derive from data yCells = Cell spacing in Y (asec) for all images, if unspecified derive from data nx = Minimum number of cells in X for NField images if unspecified derive from data ny = Minimum number of cells in Y for NField images if unspecified derive from data RAShift = Right ascension shift (AIPS convention) for each field if unspecified derive from FOV and data DecShift = Declination for each field if unspecified derive from FOV and data Catalog = AIPSVZ format catalog for defining outliers, None=do not use OutlierFlux = Minimum estimated outlyer flux density (Jy) OutlierDist = Maximum distance to add outlyers (deg) OutlierSI = Spectral index to estimate flux density OutlierSize = Size of outlyer field (pixels) returns = Output UVImager with defined ImageMosaic """ ################################################################ # Get input parameters InData = input["InData"] # # Checks if not UV.PIsA(InData): raise TypeError('UVCreateImage: Bad input UV data') # Set control values on UV dim[0] = 1; dim[1] = 1; dim[2] = 1; dim[3] = 1; dim[4] = 1 inInfo = UV.PGetList(InData) # Add control to UV data # Calibration/editing/selection InfoList.PAlwaysPutBoolean (inInfo, "doCalSelect", dim, [input["doCalSelect"]]) dim[0] = 4; InfoList.PAlwaysPutString (inInfo, "Stokes", dim, [input["Stokes"]]) dim[0] = 1; InfoList.PAlwaysPutInt (inInfo, "BChan", dim, [input["BChan"]]) InfoList.PAlwaysPutInt (inInfo, "EChan", dim, [input["EChan"]]) InfoList.PAlwaysPutInt (inInfo, "BIF", dim, [input["BIF"]]) InfoList.PAlwaysPutInt (inInfo, "EIF", dim, [input["EIF"]]) itemp = int(input["doPol"]) InfoList.PAlwaysPutInt (inInfo, "doPol", dim, [itemp]) InfoList.PAlwaysPutInt (inInfo, "doCalib", dim, [input["doCalib"]]) InfoList.PAlwaysPutInt (inInfo, "doBand", dim, [input["doBand"]]) InfoList.PAlwaysPutInt (inInfo, "gainUse", dim, [input["gainUse"]]) InfoList.PAlwaysPutInt (inInfo, "flagVer", dim, [input["flagVer"]]) InfoList.PAlwaysPutInt (inInfo, "BLVer", dim, [input["BLVer"]]) InfoList.PAlwaysPutInt (inInfo, "BPVer", dim, [input["BPVer"]]) InfoList.PAlwaysPutInt (inInfo, "Subarray", dim, [input["Subarray"]]) InfoList.PAlwaysPutInt (inInfo, "freqID", dim, [input["freqID"]]) InfoList.PAlwaysPutInt (inInfo, "corrType", dim, [input["corrType"]]) dim[0] = 2 InfoList.PAlwaysPutFloat (inInfo, "UVRange", dim, input["UVRange"]) dim[0] = 3 InfoList.PAlwaysPutFloat (inInfo, "Smooth", dim, input["Smooth"]) dim[0] = 2 InfoList.PAlwaysPutFloat (inInfo, "timeRange", dim, input["timeRange"]) dim[0] = len(input["Antennas"]) InfoList.PAlwaysPutInt (inInfo, "Antennas", dim, input["Antennas"]) dim[0] = 16; dim[1] = len(input["Sources"]) InfoList.PAlwaysPutString (inInfo, "Sources", dim, input["Sources"]) # Weighting parameters dim[0] = 1; dim[1] = 1; InfoList.PAlwaysPutFloat (inInfo, "Robust", dim, [input["Robust"]]) InfoList.PAlwaysPutInt (inInfo, "WtBox", dim, [input["WtBox"]]) InfoList.PAlwaysPutInt (inInfo, "WtFunc", dim, [input["WtFunc"]]) InfoList.PAlwaysPutFloat (inInfo, "WtPower",dim, [input["WtPower"]]) dim[0] = len(input["UVTaper"]) InfoList.PAlwaysPutFloat (inInfo, "UVTaper", dim, input["UVTaper"]) WtSize = input["WtSize"] if (WtSize>0): print("WtSize", WtSize) # Change name for C routine. dim[0] = 1; InfoList.PAlwaysPutInt (inInfo, "nuGrid", dim, [WtSize]) InfoList.PAlwaysPutInt (inInfo, "nvGrid", dim, [WtSize]) # Define image dim[0] = 1; dim[1] = 1; InfoList.PAlwaysPutInt (inInfo, "imFileType",dim, [input["Type"]]) InfoList.PAlwaysPutInt (inInfo, "imSeq", dim, [input["Seq"]]) InfoList.PAlwaysPutInt (inInfo, "imDisk", dim, [input["Disk"]]) InfoList.PAlwaysPutFloat (inInfo, "FOV", dim, [input["FOV"]]) InfoList.PAlwaysPutBoolean (inInfo, "doFull", dim, [input["doFull"]]) InfoList.PAlwaysPutInt (inInfo, "NField", dim, [input["NField"]]) InfoList.PAlwaysPutFloat (inInfo, "xCells", dim, [input["xCells"]]) InfoList.PAlwaysPutFloat (inInfo, "yCells", dim, [input["yCells"]]) InfoList.PAlwaysPutFloat (inInfo, "OutlierFlux", dim, [input["OutlierFlux"]]) InfoList.PAlwaysPutFloat (inInfo, "OutlierDist", dim, [input["OutlierDist"]]) InfoList.PAlwaysPutFloat (inInfo, "OutlierSI", dim, [input["OutlierSI"]]) InfoList.PAlwaysPutInt (inInfo, "OutlierSize", dim, [input["OutlierSize"]]) dim[0] = len(input["Name"]) InfoList.PAlwaysPutString (inInfo, "imName", dim, [input["Name"]]) dim[0] = len(input["Class"]) InfoList.PAlwaysPutString (inInfo, "imClass", dim, [input["Class"]]) dim[0] = len(input["Catalog"]) InfoList.PAlwaysPutString (inInfo, "Catalog", dim, [input["Catalog"]]) dim[0] = len(input["nx"]) InfoList.PAlwaysPutInt (inInfo, "nx", dim, input["nx"]) dim[0] = len(input["ny"]) InfoList.PAlwaysPutInt (inInfo, "ny", dim, input["ny"]) dim[0] = len(input["RAShift"]) InfoList.PAlwaysPutFloat (inInfo, "RAShift", dim, input["RAShift"]) dim[0] = len(input["DecShift"]) InfoList.PAlwaysPutFloat (inInfo, "DecShift", dim, input["DecShift"]) # # Create out = UVImager(name, InData.me, err.me) # show any errors #OErr.printErrMsg(err, "UVImage: Error creating UVImager object") # return out # end UVCreateImage def PCopy (inImager, outImager, err): """ Make a shallow copy of input object. Makes structure the same as inImager, copies pointers (probably not very useful) inImager = Python UVImager object to copy outImager = Output Python UVImager object, must be defined err = Python Obit Error/message stack """ ################################################################ # Checks if not PIsA(inImager): raise TypeError("inImager MUST be a Python Obit UVImager") if not PIsA(outImager): raise TypeError("outImager MUST be a Python Obit UVImager") if not OErr.OErrIsA(err): raise TypeError("err MUST be an OErr") # Obit.UVImageCopy (inImager.me, outImager.me, err.me) if err.isErr: OErr.printErrMsg(err, "Error copying UVImage") # end PCopy def PGetMosaic (InImager, err): """ Return the member ImageMosaic returns ImageMosaic InImager = Python ImageMosaic object err = Python Obit Error/message stack """ ################################################################ # Checks if not PIsA(InImager): raise TypeError("InImager MUST be a Python Obit UVImager") # out = ImageMosaic.ImageMosaic("None", 1) out.me = Obit.UVImagerGetMosaic(InImager.me, err.me) if err.isErr: OErr.printErrMsg(err, "Error obtaining Mosaic member") return out # end PGetMosaic def PGetUV (InImager): """ Return the member uvdata returns uv data (as UV) InImager = Python ImageMosaic object """ ################################################################ # Checks if not PIsA(InImager): raise TypeError("InImager MUST be a Python Obit UVImager") # out = UV.UV("None") out.me = Obit.UVImagerGetUV(InImager.me) return out # end PGetMosaic # Define UVWeight input dictionary UVWeightInput={'structure':['UVWeight',[('InImager','Input UVImager'), ('Robust', 'Briggs robust parameter. (AIPS definition)'), ('UVTaper', 'UV plane taper, sigma in klambda,deg as [maj, min, pa]'), ('WtSize', 'Size of weighting grid in cells [image]'), ('WtBox', 'Size of weighting box in cells [def 0]'), ('WtFunc', 'Weighting convolution function [def. 1]'), ('WtPower', 'Power to raise weights to. [def = 1.0]'), ('Channel', 'Channel (1-rel) number to image, 0-> all.')]], # defaults 'InImager':None, 'DoWeight': True, 'Robust': 0.0, 'UVTaper': [0.0,0.0,0.0], 'WtSize':-1, 'WtBox':0, 'WtFunc':1, 'WtPower':1.0, 'Channel': 0 } def PUVWeight (InImager, err, input=UVWeightInput): """ Apply any calibration/editing/selection and do UV weighting UV Data is calibrated and weighted, values in input override those given when the UVImage was created. This operation is optionally done in PUVImage. err = Python Obit Error/message stack input = input parameter dictionary Input dictionary entries: InImager = Input Python UVImager to image Robust = Briggs robust parameter. (AIPS definition) UVTaper = UV plane taper, sigma in klambda,deg as [maj, min, pa] WtSize = Size of weighting grid in cells [same as image nx] WtBox = Size of weighting box in cells [def 1] WtFunc = Weighting convolution function [def. 1] 1=Pill box, 2=linear, 3=exponential, 4=Gaussian if positive, function is of radius, negative in u and v. WtPower = Power to raise weights to. [def = 1.0] Note: a power of 0.0 sets all the output weights to 1 as modified by uniform/Tapering weighting. Applied in determinng weights as well as after. Channel = Channel (1-rel) number to image, 0-> all. """ ################################################################ # Get input parameters Channel = input["Channel"] WtSize = input["WtSize"] # # Checks if not PIsA(InImager): raise TypeError('PUVWeight: Bad input UVImager') # Set control values on UV dim[0] = 1; dim[1] = 1; dim[2] = 1; dim[3] = 1; dim[4] = 1 inInfo = UV.PGetList(PGetUV(InImager)) InfoList.PAlwaysPutFloat (inInfo, "Robust", dim, [input["Robust"]]) InfoList.PAlwaysPutInt (inInfo, "WtBox", dim, [input["WtBox"]]) InfoList.PAlwaysPutInt (inInfo, "WtFunc", dim, [input["WtFunc"]]) InfoList.PAlwaysPutFloat (inInfo, "WtPower",dim, [input["WtPower"]]) dim[1] = len(input["UVTaper"]) InfoList.PAlwaysPutFloat (inInfo, "Taper", dim, input["UVTaper"]) if (WtSize>0): print("WtSize", WtSize) # Change name for C routine. dim[0] = 1; InfoList.PAlwaysPutInt (inInfo, "nuGrid", dim, [WtSize]) InfoList.PAlwaysPutInt (inInfo, "nvGrid", dim, [WtSize]) # Obit.UVImagerWeight (InImager.me, err.me) if err.isErr: OErr.printErrMsg(err, "Error weighting UV data") # show any messages, bail if errors #OErr.printErrMsg(err, "PUVWeight: Error weighting UV data") # # end PUVWeight def PUVImage (InImager, err, field=0, doWeight=False, doBeam=True, doFlatten=False): """ Form image optionally doing the calibration/weighting and flatten stages UV Data is imaged to form dirty beam. Control parameters are those on UV data passed at UVImager creation. InImager = UVImager object field = field number (1-rel) to image, 0=> all err = Python Obit Error/message stack doWeight = Do weighting (Uniform, tapering,...) before imaging If True then input data is modified. doBeam = Make Beam before image, must be done once. doFlatten = Flatten image mosaic onto single image """ ################################################################ # # Checks if not PIsA(InImager): print("input class actually ",InImager.__class__) raise TypeError('PUVImage: Bad input UVImager') # Obit.UVImagerImage (InImager.me, field, doWeight, doBeam, doFlatten, err.me) if err.isErr: OErr.printErrMsg(err, "Error Imaging data") # show any messages, bail if errors
'frame': 377, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.958358564980967, 'attempts': 2, 'timeIncrement': 0.000258234416308831, 'increment': 377, 'stepTime': 0.958358564980967, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 378, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.958745916605431, 'attempts': 1, 'timeIncrement': 0.000387351624463246, 'increment': 378, 'stepTime': 0.958745916605431, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 379, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.959326944042125, 'attempts': 1, 'timeIncrement': 0.000581027436694869, 'increment': 379, 'stepTime': 0.959326944042125, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 380, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.960198485197168, 'attempts': 1, 'timeIncrement': 0.000871541155042304, 'increment': 380, 'stepTime': 0.960198485197168, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.960198485197168, 'attempts': ' 1U', 'timeIncrement': 0.00130731173256346, 'increment': 381, 'stepTime': 0.960198485197168, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 9, 'phase': STANDARD_PHASE, 'equilibrium': 9}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 381, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.960852141063449, 'attempts': 2, 'timeIncrement': 0.000653655866281728, 'increment': 381, 'stepTime': 0.960852141063449, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.960852141063449, 'attempts': ' 1U', 'timeIncrement': 0.000980483799422592, 'increment': 382, 'stepTime': 0.960852141063449, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 4, 'phase': STANDARD_PHASE, 'equilibrium': 4}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 382, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.961097262013305, 'attempts': 2, 'timeIncrement': 0.000245120949855648, 'increment': 382, 'stepTime': 0.961097262013305, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 383, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.961464943438089, 'attempts': 1, 'timeIncrement': 0.000367681424783472, 'increment': 383, 'stepTime': 0.961464943438089, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 384, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.962016465575264, 'attempts': 1, 'timeIncrement': 0.000551522137175208, 'increment': 384, 'stepTime': 0.962016465575264, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 385, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.962843748781027, 'attempts': 1, 'timeIncrement': 0.000827283205762812, 'increment': 385, 'stepTime': 0.962843748781027, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.962843748781027, 'attempts': ' 1U', 'timeIncrement': 0.00124092480864422, 'increment': 386, 'stepTime': 0.962843748781027, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 5, 'phase': STANDARD_PHASE, 'equilibrium': 5}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 386, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.963153979983188, 'attempts': 2, 'timeIncrement': 0.000310231202161054, 'increment': 386, 'stepTime': 0.963153979983188, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 387, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.963619326786429, 'attempts': 1, 'timeIncrement': 0.000465346803241582, 'increment': 387, 'stepTime': 0.963619326786429, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 388, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.964317346991292, 'attempts': 1, 'timeIncrement': 0.000698020204862372, 'increment': 388, 'stepTime': 0.964317346991292, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(WARNING, {'phase': STANDARD_PHASE, 'message': 'EXCESSIVE DISTORTION AT A TOTAL OF 89 INTEGRATION POINTS IN SOLID (CONTINUUM) ELEMENTS', 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.964317346991292, 'attempts': ' 1U', 'timeIncrement': 0.00104703030729356, 'increment': 389, 'stepTime': 0.964317346991292, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 4, 'phase': STANDARD_PHASE, 'equilibrium': 4}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 389, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.964579104568115, 'attempts': 2, 'timeIncrement': 0.00026175757682339, 'increment': 389, 'stepTime': 0.964579104568115, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 390, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.96497174093335, 'attempts': 1, 'timeIncrement': 0.000392636365235084, 'increment': 390, 'stepTime': 0.96497174093335, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 391, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.965560695481203, 'attempts': 1, 'timeIncrement': 0.000588954547852627, 'increment': 391, 'stepTime': 0.965560695481203, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 392, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.966444127302982, 'attempts': 1, 'timeIncrement': 0.00088343182177894, 'increment': 392, 'stepTime': 0.966444127302982, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.966444127302982, 'attempts': ' 1U', 'timeIncrement': 0.00132514773266841, 'increment': 393, 'stepTime': 0.966444127302982, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 5, 'phase': STANDARD_PHASE, 'equilibrium': 5}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 393, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.966775414236149, 'attempts': 2, 'timeIncrement': 0.000331286933167103, 'increment': 393, 'stepTime': 0.966775414236149, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 394, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.967272344635899, 'attempts': 1, 'timeIncrement': 0.000496930399750654, 'increment': 394, 'stepTime': 0.967272344635899, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 395, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.968017740235525, 'attempts': 1, 'timeIncrement': 0.000745395599625981, 'increment': 395, 'stepTime': 0.968017740235525, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(WARNING, {'phase': STANDARD_PHASE, 'message': 'FORCE equilibrium accepted using the alternate tolerance.', 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 396, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.969135833634964, 'attempts': 1, 'timeIncrement': 0.00111809339943897, 'increment': 396, 'stepTime': 0.969135833634964, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 11, 'phase': STANDARD_PHASE, 'equilibrium': 11}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 397, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.969974403684544, 'attempts': 1, 'timeIncrement': 0.000838570049579228, 'increment': 397, 'stepTime': 0.969974403684544, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 10, 'phase': STANDARD_PHASE, 'equilibrium': 10}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 398, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.970812973734123, 'attempts': 1, 'timeIncrement': 0.000838570049579228, 'increment': 398, 'stepTime': 0.970812973734123, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 4, 'phase': STANDARD_PHASE, 'equilibrium': 4}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 399, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.971651543783702, 'attempts': 1, 'timeIncrement': 0.000838570049579228, 'increment': 399, 'stepTime': 0.971651543783702, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 6, 'phase': STANDARD_PHASE, 'equilibrium': 6}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 400, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.972490113833281, 'attempts': 1, 'timeIncrement': 0.000838570049579228, 'increment': 400, 'stepTime': 0.972490113833281, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 401, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.97332868388286, 'attempts': 1, 'timeIncrement': 0.000838570049579228, 'increment': 401, 'stepTime': 0.97332868388286, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 4, 'phase': STANDARD_PHASE, 'equilibrium': 4}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 402, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.974586538957229, 'attempts': 1, 'timeIncrement': 0.00125785507436884, 'increment': 402, 'stepTime': 0.974586538957229, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 8, 'phase': STANDARD_PHASE, 'equilibrium': 8}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 403, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.975844394031598, 'attempts': 1, 'timeIncrement': 0.00125785507436884, 'increment': 403, 'stepTime': 0.975844394031598, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 8, 'phase': STANDARD_PHASE, 'equilibrium': 8}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 404, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.977102249105967, 'attempts': 1, 'timeIncrement': 0.00125785507436884, 'increment': 404, 'stepTime': 0.977102249105967, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 8, 'phase': STANDARD_PHASE, 'equilibrium': 8}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 405, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.978360104180336, 'attempts': 1, 'timeIncrement': 0.00125785507436884, 'increment': 405, 'stepTime': 0.978360104180336, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 8, 'phase': STANDARD_PHASE, 'equilibrium': 8}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 406, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.979617959254705, 'attempts': 1, 'timeIncrement': 0.00125785507436884, 'increment': 406, 'stepTime': 0.979617959254705, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 8, 'phase': STANDARD_PHASE, 'equilibrium': 8}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 407, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.980875814329073, 'attempts': 1, 'timeIncrement': 0.00125785507436884, 'increment': 407, 'stepTime': 0.980875814329073, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 8, 'phase': STANDARD_PHASE, 'equilibrium': 8}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 408, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.982133669403442, 'attempts': 1, 'timeIncrement': 0.00125785507436884, 'increment': 408, 'stepTime': 0.982133669403442, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 8, 'phase': STANDARD_PHASE, 'equilibrium': 8}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.982133669403442, 'attempts': ' 1U', 'timeIncrement': 0.00125785507436884, 'increment': 409, 'stepTime': 0.982133669403442, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 6, 'phase': STANDARD_PHASE, 'equilibrium': 6}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame':
import re from urllib import urlencode from django.http import Http404 from django.shortcuts import render, redirect from django.core.urlresolvers import reverse from django.core.files.storage import default_storage from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.files.uploadhandler import TemporaryFileUploadHandler from django.views.decorators.csrf import csrf_exempt, csrf_protect from go.contacts.forms import ( ContactForm, ContactGroupForm, UploadContactsForm, SmartGroupForm, SelectContactGroupForm) from go.contacts import tasks, utils from go.contacts.import_handlers import ( handle_import_new_contacts, handle_import_existing_is_truth, handle_import_upload_is_truth, ContactImportException) from go.contacts.parsers import ContactFileParser, ContactParserException from go.contacts.parsers.base import FieldNormalizer from go.vumitools.contact import ContactError def _query_to_kwargs(query): pattern = r'(?P<key>[^ :]+):[ ]*(?P<value>[^:]*[^ :])(?:(?=( [^:]+:)|$))' tuples = re.findall(pattern, query) return dict([(t[0], t[1]) for t in tuples]) def _group_url(group_key): return reverse('contacts:group', kwargs={'group_key': group_key}) @login_required def index(request): return redirect(reverse('contacts:groups')) @login_required def groups(request, type=None): contact_store = request.user_api.contact_store if request.POST: contact_group_form = ContactGroupForm(request.POST) smart_group_form = SmartGroupForm(request.POST) if '_new_group' in request.POST: if contact_group_form.is_valid(): group = contact_store.new_group( contact_group_form.cleaned_data['name']) messages.add_message( request, messages.INFO, 'New group created') return redirect(_group_url(group.key)) elif '_new_smart_group' in request.POST: if smart_group_form.is_valid(): name = smart_group_form.cleaned_data['name'] query = smart_group_form.cleaned_data['query'] smart_group = contact_store.new_smart_group( name, query) return redirect(_group_url(smart_group.key)) elif '_delete' in request.POST: groups = request.POST.getlist('group') for group_key in groups: group = contact_store.get_group(group_key) tasks.delete_group.delay(request.user_api.user_account_key, group.key) messages.info(request, '%d groups will be deleted ' 'shortly.' % len(groups)) return redirect(reverse('contacts:groups')) elif '_export' in request.POST: tasks.export_many_group_contacts.delay( request.user_api.user_account_key, request.POST.getlist('group')) messages.info(request, 'The export is scheduled and should ' 'complete within a few minutes.') return redirect(reverse('contacts:groups')) else: contact_group_form = ContactGroupForm() smart_group_form = SmartGroupForm() user_query = request.GET.get('q', '') query = user_query if query: if ':' not in query: query = 'name:%s' % (query,) keys = contact_store.groups.raw_search(query).get_keys() groups = utils.groups_by_key(contact_store, *keys) else: if type == 'static': groups = contact_store.list_static_groups() elif type == 'smart': groups = contact_store.list_smart_groups() else: groups = contact_store.list_groups() groups = sorted(groups, key=lambda group: group.created_at, reverse=True) paginator = Paginator(groups, 15) try: page = paginator.page(request.GET.get('p', 1)) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) pagination_params = urlencode({ 'query': query, }) return render(request, 'contacts/group_list.html', { 'paginator': paginator, 'pagination_params': pagination_params, 'page': page, 'query': user_query, 'contact_group_form': contact_group_form, }) @csrf_exempt def group(request, group_key): # the upload handlers can only be set before touching request.POST or # request.FILES. The CsrfViewMiddleware touches request.POST, avoid # this by doing the CSRF manually with a separate view request.upload_handlers = [TemporaryFileUploadHandler()] return _group(request, group_key) @login_required @csrf_protect def _group(request, group_key): contact_store = request.user_api.contact_store group = contact_store.get_group(group_key) if group.is_smart_group(): return _smart_group(request, contact_store, group) else: return _static_group(request, contact_store, group) @login_required @csrf_protect def _static_group(request, contact_store, group): if group is None: raise Http404 if request.method == 'POST': group_form = ContactGroupForm(request.POST) if '_save_group' in request.POST: if group_form.is_valid(): group.name = group_form.cleaned_data['name'] group.save() messages.info(request, 'The group name has been updated') return redirect(_group_url(group.key)) elif '_export' in request.POST: tasks.export_group_contacts.delay( request.user_api.user_account_key, group.key) messages.info(request, 'The export is scheduled and should ' 'complete within a few minutes.') return redirect(_group_url(group.key)) elif '_remove' in request.POST: contacts = request.POST.getlist('contact') for person_key in contacts: contact = contact_store.get_contact_by_key(person_key) contact.groups.remove(group) contact.save() messages.info( request, '%d Contacts removed from group' % len(contacts)) return redirect(_group_url(group.key)) elif '_delete_group_contacts' in request.POST: tasks.delete_group_contacts.delay( request.user_api.user_account_key, group.key) messages.info(request, "The group's contacts will be deleted shortly.") return redirect(_group_url(group.key)) elif '_delete_group' in request.POST: tasks.delete_group.delay(request.user_api.user_account_key, group.key) messages.info(request, 'The group will be deleted shortly.') return redirect(reverse('contacts:index')) elif '_complete_contact_upload' in request.POST: try: import_rule = request.POST.get('import_rule') import_handler = { 'existing_is_truth': handle_import_existing_is_truth, 'upload_is_truth': handle_import_upload_is_truth, }.get(import_rule, handle_import_new_contacts) import_handler(request, group) messages.info( request, 'The contacts are being imported. ' 'We will notify you via email when the import ' 'has been completed') except (ContactParserException, ContactImportException), e: if isinstance(e, ContactImportException): error_msg = str(e) else: error_msg = 'Something is wrong with the file' messages.error(request, error_msg) _, file_path = utils.get_file_hints_from_session(request) default_storage.delete(file_path) utils.clear_file_hints_from_session(request) return redirect(_group_url(group.key)) else: upload_contacts_form = UploadContactsForm(request.POST, request.FILES) if upload_contacts_form.is_valid(): file_object = upload_contacts_form.cleaned_data['file'] file_name, file_path = utils.store_temporarily(file_object) utils.store_file_hints_in_session( request, file_name, file_path) return redirect(_group_url(group.key)) else: # We didn't get any useful POST variables, so just redirect # back to the group page without doing anything. return redirect(_group_url(group.key)) else: group_form = ContactGroupForm({ 'name': group.name, }) context = { 'group': group, 'group_form': group_form, } if 'clear-upload' in request.GET: # FIXME this is a debug statement utils.clear_file_hints_from_session(request) if utils.has_uncompleted_contact_import(request): try: file_name, file_path = utils.get_file_hints_from_session(request) file_type, parser = ContactFileParser.get_parser(file_name) has_header, headers, row = parser.guess_headers_and_row(file_path) context.update({ 'contact_data_headers': headers, 'field_normalizer': FieldNormalizer(), 'contact_data_row': row, # NOTE: Only if we have a key (contact UUID) value in the # row we can look at updating contacts instead of # only writing new ones. 'can_update_contacts': 'key' in row, }) except (ValueError, ContactParserException): messages.error(request, 'Something is wrong with the file') utils.clear_file_hints_from_session(request) default_storage.delete(file_path) query = request.GET.get('q', '') if query: if not ':' in query: query = 'name:%s' % (query,) keys = contact_store.contacts.raw_search(query).get_keys() else: keys = contact_store.get_contacts_for_group(group) limit = min(int(request.GET.get('limit', 100)), len(keys)) if keys: messages.info( request, "Showing %s of the group's %s contact(s)" % (limit, len(keys))) contacts = utils.contacts_by_key(contact_store, *keys[:limit]) context.update({ 'query': request.GET.get('q'), 'selected_contacts': contacts, 'member_count': contact_store.count_contacts_for_group(group), }) return render(request, 'contacts/static_group_detail.html', context) @csrf_protect @login_required def _smart_group(request, contact_store, group): if request.method == 'POST': if '_save_group' in request.POST: smart_group_form = SmartGroupForm(request.POST) if smart_group_form.is_valid(): group.name = smart_group_form.cleaned_data['name'] group.query = smart_group_form.cleaned_data['query'] group.save() return redirect(_group_url(group.key)) elif '_export' in request.POST: tasks.export_group_contacts.delay( request.user_api.user_account_key, group.key, True) messages.info(request, 'The export is scheduled and should ' 'complete within a few minutes.') return redirect(_group_url(group.key)) elif '_delete_group_contacts' in request.POST: tasks.delete_group_contacts.delay( request.user_api.user_account_key, group.key) messages.info( request, "The group's contacts will be deleted shortly.") return redirect(_group_url(group.key)) elif '_delete_group' in request.POST: tasks.delete_group.delay(request.user_api.user_account_key, group.key) messages.info(request, 'The group will be deleted shortly.') return redirect(reverse('contacts:index')) else: # We didn't get any useful POST variables, so just redirect back to # the group page without doing anything. return redirect(_group_url(group.key)) else: smart_group_form = SmartGroupForm({ 'name': group.name, 'query': group.query, }) keys = contact_store.get_contacts_for_group(group) limit = min(int(request.GET.get('limit', 100)), len(keys)) if keys: messages.info( request, "Showing %s of the group's %s contact(s)" % (limit, len(keys))) contacts = utils.contacts_by_key(contact_store, *keys[:limit]) return render(request, 'contacts/smart_group_detail.html', { 'group': group, 'selected_contacts': contacts, 'group_form': smart_group_form, }) @csrf_exempt def people(request): # the upload handlers can only be set before touching request.POST or # request.FILES. The CsrfViewMiddleware touches request.POST, avoid # this by doing the CSRF manually with a separate view request.upload_handlers = [TemporaryFileUploadHandler()] return _people(request) @login_required @csrf_protect def _people(request): contact_store = request.user_api.contact_store upload_contacts_form = None group = None if request.method == 'POST': if '_delete' in request.POST: contacts = request.POST.getlist('contact') for person_key in contacts: contact = contact_store.get_contact_by_key(person_key) contact.delete() messages.info(request, '%d Contacts deleted' % len(contacts)) elif '_export' in request.POST: tasks.export_contacts.delay( request.user_api.user_account_key, request.POST.getlist('contact')) messages.info(request, 'The export is scheduled and should ' 'complete within a few minutes.') elif '_export_all' in request.POST: tasks.export_all_contacts.delay( request.user_api.user_account_key) messages.info(request, 'The export is scheduled and should ' 'complete within a few minutes.') else: # first parse the CSV file and create Contact instances # from them for attaching to a group later upload_contacts_form = UploadContactsForm( request.POST, request.FILES) if upload_contacts_form.is_valid(): # We could be creating a new contact group. if request.POST.get('name'): new_group_form = ContactGroupForm(request.POST) if new_group_form.is_valid(): group = contact_store.new_group( new_group_form.cleaned_data['name']) # We could be using an existing contact group. elif request.POST.get('contact_group'): select_group_form = SelectContactGroupForm( request.POST, groups=contact_store.list_groups()) if select_group_form.is_valid(): group = contact_store.get_group( select_group_form.cleaned_data['contact_group']) if group is None: messages.error(request, 'Please select a group or provide ' 'a new group name.') else: file_object = upload_contacts_form.cleaned_data['file'] file_name, file_path = utils.store_temporarily(file_object) utils.store_file_hints_in_session( request, file_name, file_path) return redirect(_group_url(group.key)) else: messages.error( request, 'Something went wrong with the upload.') select_contact_group_form = SelectContactGroupForm( groups=contact_store.list_groups()) # TODO: A lot of this stuff is duplicated from the similar group search # in the groups() view. We need a function that does that to avoid # the duplication. user_query = request.GET.get('q', '') query = user_query if query: if not ':' in query: query = 'name:%s' % (query,) keys = contact_store.contacts.raw_search(query).get_keys() else: keys = contact_store.list_contacts() limit = min(int(request.GET.get('limit', 100)), len(keys)) messages.info(request, "Showing %s of %s contact(s)" % (limit, len(keys))) smart_group_form = SmartGroupForm(initial={'query': query}) contacts = utils.contacts_by_key(contact_store, *keys[:limit]) return render(request, 'contacts/contact_list.html', { 'query': user_query, 'selected_contacts': contacts, 'smart_group_form': smart_group_form, 'upload_contacts_form': upload_contacts_form or UploadContactsForm(), 'select_contact_group_form': select_contact_group_form, }) @login_required def person(request, person_key): contact_store = request.user_api.contact_store try: contact = contact_store.get_contact_by_key(person_key) except ContactError: raise Http404 groups = contact_store.list_groups() if request.method == 'POST': if '_delete' in request.POST: contact.delete() messages.info(request, 'Contact deleted') return redirect(reverse('contacts:people')) else: form = ContactForm(request.POST, groups=groups) if form.is_valid(): for k, v in form.cleaned_data.items(): if k == 'groups': contact.groups.clear() for group in v: contact.add_to_group(group) continue setattr(contact, k, v) contact.save() messages.add_message(request, messages.INFO, 'Profile Updated') return redirect(reverse('contacts:person', kwargs={ 'person_key': contact.key})) else: messages.error(request, 'Please correct the problem below.') else: form = ContactForm(groups=groups, initial={ 'name': contact.name, 'surname': contact.surname, 'email_address':
u'4', u'5', u'6', u'7', u'8', u'9', u'A', u'B', u'C', u'D', u'E', u'F', u'G', u'H', u'J', u'K', u'L', u'M', u'N', u'O', u'P', u'Q', u'R', u'S', u'SA', u'SB', u'SC', u'SD', u'SG', u'SL', u'SP', u'SX', u'SY', u'SZ', u'T', u'U', u'V', u'W', u'X', u'Y'] ) ), Element( u'HSD08', Properties(desc=u'Ship/Delivery Pattern Time Code', req_sit=u'S', data_type=(u'ID',u'1',u'1'), position=8, codes=[u'A', u'B', u'C', u'D', u'E', u'F', u'G', u'Y'] ) ), ), Segment( u'CL1', Properties(syntax='',req_sit=u'S',repeat=u'1',pos=u'110',desc=u'Institutional Claim Code'), Element( u'CL101', Properties(desc=u'Admission Type Code', req_sit=u'S', data_type=(u'ID',u'1',u'1'), position=1, codes=[] ) ), Element( u'CL102', Properties(desc=u'Admission Source Code', req_sit=u'S', data_type=(u'ID',u'1',u'1'), position=2, codes=[] ) ), Element( u'CL103', Properties(desc=u'Patient Status Code', req_sit=u'S', data_type=(u'ID',u'1',u'2'), position=3, codes=[] ) ), Element( u'CL104', Properties(desc=u'Nursing Home Residential Status Code', req_sit=u'S', data_type=(u'ID',u'1',u'1'), position=4, codes=[u'1', u'2', u'3', u'4', u'5', u'6', u'7', u'8', u'9'] ) ), ), Segment( u'CR1', Properties(syntax='',req_sit=u'S',repeat=u'1',pos=u'120',desc=u'Ambulance Transport Information'), Element( u'CR101', Properties(desc=u'Unit or Basis for Measurement Code', req_sit=u'N', data_type=(u'ID',u'2',u'2'), position=1, codes=[] ) ), Element( u'CR102', Properties(desc=u'Weight', req_sit=u'N', data_type=(u'R',u'1',u'10'), position=2, codes=[] ) ), Element( u'CR103', Properties(desc=u'Ambulance Transport Code', req_sit=u'R', data_type=(u'ID',u'1',u'1'), position=3, codes=[u'I', u'R', u'T', u'X'] ) ), Element( u'CR104', Properties(desc=u'Ambulance Transport Reason Code', req_sit=u'N', data_type=(u'ID',u'1',u'1'), position=4, codes=[] ) ), Element( u'CR105', Properties(desc=u'Unit or Basis for Measurement Code', req_sit=u'S', data_type=(u'ID',u'2',u'2'), position=5, codes=[u'DH', u'DK'] ) ), Element( u'CR106', Properties(desc=u'Quantity', req_sit=u'S', data_type=(u'R',u'1',u'15'), position=6, codes=[] ) ), Element( u'CR107', Properties(desc=u'Address Information', req_sit=u'S', data_type=(u'AN',u'1',u'55'), position=7, codes=[] ) ), Element( u'CR108', Properties(desc=u'Address Information', req_sit=u'S', data_type=(u'AN',u'1',u'55'), position=8, codes=[] ) ), Element( u'CR109', Properties(desc=u'Description', req_sit=u'N', data_type=(u'AN',u'1',u'80'), position=9, codes=[] ) ), Element( u'CR110', Properties(desc=u'Description', req_sit=u'N', data_type=(u'AN',u'1',u'80'), position=10, codes=[] ) ), ), Segment( u'CR2', Properties(syntax='',req_sit=u'S',repeat=u'1',pos=u'130',desc=u'Spinal Manipulation Service Information'), Element( u'CR201', Properties(desc=u'Count', req_sit=u'S', data_type=(u'N0',u'1',u'9'), position=1, codes=[] ) ), Element( u'CR202', Properties(desc=u'Quantity', req_sit=u'S', data_type=(u'R',u'1',u'15'), position=2, codes=[] ) ), Element( u'CR203', Properties(desc=u'Subluxation Level Code', req_sit=u'S', data_type=(u'ID',u'2',u'3'), position=3, codes=[u'C1', u'C2', u'C3', u'C4', u'C5', u'C6', u'C7', u'CO', u'IL', u'L1', u'L2', u'L3', u'L4', u'L5', u'OC', u'SA', u'T1', u'T10', u'T11', u'T12', u'T2', u'T3', u'T4', u'T5', u'T6', u'T7', u'T8', u'T9'] ) ), Element( u'CR204', Properties(desc=u'Subluxation Level Code', req_sit=u'S', data_type=(u'ID',u'2',u'3'), position=4, codes=[u'C1', u'C2', u'C3', u'C4', u'C5', u'C6', u'C7', u'CO', u'IL', u'L1', u'L2', u'L3', u'L4', u'L5', u'OC', u'SA', u'T1', u'T10', u'T11', u'T12', u'T2', u'T3', u'T4', u'T5', u'T6', u'T7', u'T8', u'T9'] ) ), Element( u'CR205', Properties(desc=u'Unit or Basis for Measurement Code', req_sit=u'S', data_type=(u'ID',u'2',u'2'), position=5, codes=[u'DA', u'MO', u'WK', u'YR'] ) ), Element( u'CR206', Properties(desc=u'Quantity', req_sit=u'S', data_type=(u'R',u'1',u'15'), position=6, codes=[] ) ), Element( u'CR207', Properties(desc=u'Quantity', req_sit=u'S', data_type=(u'R',u'1',u'15'), position=7, codes=[] ) ), Element( u'CR208', Properties(desc=u'Nature of Condition Code', req_sit=u'N', data_type=(u'ID',u'1',u'1'), position=8, codes=[] ) ), Element( u'CR209', Properties(desc=u'Yes/No Condition or Response Code', req_sit=u'N', data_type=(u'ID',u'1',u'1'), position=9, codes=[] ) ), Element( u'CR210', Properties(desc=u'Description', req_sit=u'N', data_type=(u'AN',u'1',u'80'), position=10, codes=[] ) ), Element( u'CR211', Properties(desc=u'Description', req_sit=u'N', data_type=(u'AN',u'1',u'80'), position=11, codes=[] ) ), Element( u'CR212', Properties(desc=u'Yes/No Condition or Response Code', req_sit=u'N', data_type=(u'ID',u'1',u'1'), position=12, codes=[] ) ), ), Segment( u'CR5', Properties(syntax='',req_sit=u'S',repeat=u'1',pos=u'140',desc=u'Home Oxygen Therapy Information'), Element( u'CR501', Properties(desc=u'Certification Type Code', req_sit=u'N', data_type=(u'ID',u'1',u'1'), position=1, codes=[] ) ), Element( u'CR502', Properties(desc=u'Quantity', req_sit=u'N', data_type=(u'R',u'1',u'15'), position=2, codes=[] ) ), Element( u'CR503', Properties(desc=u'Oxygen Equipment Type Code', req_sit=u'S', data_type=(u'ID',u'1',u'1'), position=3, codes=[u'A', u'B', u'C', u'D', u'E', u'O'] ) ), Element( u'CR504', Properties(desc=u'Oxygen Equipment Type Code', req_sit=u'S', data_type=(u'ID',u'1',u'1'), position=4, codes=[u'A', u'B', u'C', u'D', u'E', u'O'] ) ), Element( u'CR505', Properties(desc=u'Description', req_sit=u'S', data_type=(u'AN',u'1',u'80'), position=5, codes=[] ) ), Element( u'CR506', Properties(desc=u'Quantity', req_sit=u'R', data_type=(u'R',u'1',u'15'), position=6, codes=[] ) ), Element( u'CR507', Properties(desc=u'Quantity', req_sit=u'S', data_type=(u'R',u'1',u'15'), position=7, codes=[] ) ), Element( u'CR508', Properties(desc=u'Quantity', req_sit=u'S', data_type=(u'R',u'1',u'15'), position=8, codes=[] ) ), Element( u'CR509', Properties(desc=u'Description', req_sit=u'S', data_type=(u'AN',u'1',u'80'), position=9, codes=[] ) ), Element( u'CR510', Properties(desc=u'Quantity', req_sit=u'N', data_type=(u'R',u'1',u'15'), position=10, codes=[] ) ), Element( u'CR511', Properties(desc=u'Quantity', req_sit=u'N', data_type=(u'R',u'1',u'15'), position=11, codes=[] ) ), Element( u'CR512', Properties(desc=u'Oxygen Test Condition Code', req_sit=u'N', data_type=(u'ID',u'1',u'1'), position=12, codes=[] ) ), Element( u'CR513', Properties(desc=u'Oxygen Test Findings Code', req_sit=u'N', data_type=(u'ID',u'1',u'1'), position=13, codes=[] ) ), Element( u'CR514', Properties(desc=u'Oxygen Test Findings Code', req_sit=u'N', data_type=(u'ID',u'1',u'1'), position=14, codes=[] ) ), Element( u'CR515', Properties(desc=u'Oxygen Test Findings Code', req_sit=u'N', data_type=(u'ID',u'1',u'1'), position=15, codes=[] ) ), Element( u'CR516', Properties(desc=u'Quantity', req_sit=u'S', data_type=(u'R',u'1',u'15'), position=16, codes=[] ) ), Element( u'CR517', Properties(desc=u'Oxygen Delivery System Code', req_sit=u'R', data_type=(u'ID',u'1',u'1'), position=17, codes=[u'A', u'B', u'C', u'D', u'E'] ) ), Element( u'CR518', Properties(desc=u'Oxygen Equipment Type Code', req_sit=u'S', data_type=(u'ID',u'1',u'1'), position=18, codes=[u'A', u'B', u'C', u'D', u'E', u'O'] ) ), ), Segment( u'CR6', Properties(syntax='',req_sit=u'S',repeat=u'1',pos=u'150',desc=u'Home Health Care Information'), Element( u'CR601', Properties(desc=u'Prognosis Code', req_sit=u'R', data_type=(u'ID',u'1',u'1'), position=1, codes=[u'1', u'2', u'3', u'4', u'5', u'6', u'7', u'8'] ) ), Element( u'CR602', Properties(desc=u'Date', req_sit=u'R', data_type=(u'DT',u'8',u'8'), position=2, codes=[] ) ), Element( u'CR603', Properties(desc=u'Date Time Period Format Qualifier', req_sit=u'S', data_type=(u'ID',u'2',u'3'), position=3, codes=[u'RD8'] ) ), Element( u'CR604', Properties(desc=u'Date Time Period', req_sit=u'S', data_type=(u'AN',u'1',u'35'), position=4, codes=[] ) ), Element( u'CR605', Properties(desc=u'Date', req_sit=u'N', data_type=(u'DT',u'8',u'8'), position=5, codes=[] ) ), Element( u'CR606', Properties(desc=u'Yes/No Condition or Response Code', req_sit=u'N', data_type=(u'ID',u'1',u'1'), position=6, codes=[] ) ), Element( u'CR607', Properties(desc=u'Yes/No Condition or Response Code', req_sit=u'R', data_type=(u'ID',u'1',u'1'), position=7, codes=[u'N', u'U', u'Y'] ) ), Element( u'CR608', Properties(desc=u'Certification Type Code', req_sit=u'R', data_type=(u'ID',u'1',u'1'), position=8, codes=[u'1', u'2', u'3', u'4', u'I', u'R', u'S'] ) ), Element( u'CR609', Properties(desc=u'Date', req_sit=u'N', data_type=(u'DT',u'8',u'8'), position=9, codes=[] ) ), Element( u'CR610', Properties(desc=u'Product/Service ID Qualifier', req_sit=u'N', data_type=(u'ID',u'2',u'2'), position=10, codes=[] ) ), Element( u'CR611', Properties(desc=u'Medical Code Value', req_sit=u'N', data_type=(u'AN',u'1',u'15'), position=11, codes=[] ) ), Element( u'CR612', Properties(desc=u'Date', req_sit=u'N', data_type=(u'DT',u'8',u'8'), position=12, codes=[] ) ), Element( u'CR613', Properties(desc=u'Date', req_sit=u'N', data_type=(u'DT',u'8',u'8'), position=13, codes=[] ) ), Element( u'CR614', Properties(desc=u'Date', req_sit=u'N', data_type=(u'DT',u'8',u'8'), position=14, codes=[] ) ), Element( u'CR615', Properties(desc=u'Date Time Period Format Qualifier', req_sit=u'N', data_type=(u'ID',u'2',u'3'), position=15, codes=[] ) ), Element( u'CR616', Properties(desc=u'Date Time Period', req_sit=u'N', data_type=(u'AN',u'1',u'35'), position=16, codes=[] ) ), Element( u'CR617', Properties(desc=u'Patient Location Code', req_sit=u'N', data_type=(u'ID',u'1',u'1'), position=17, codes=[] ) ), Element( u'CR618', Properties(desc=u'Date', req_sit=u'N', data_type=(u'DT',u'8',u'8'), position=18, codes=[] ) ), Element( u'CR619', Properties(desc=u'Date', req_sit=u'N', data_type=(u'DT',u'8',u'8'), position=19, codes=[] ) ), Element( u'CR620', Properties(desc=u'Date', req_sit=u'N', data_type=(u'DT',u'8',u'8'), position=20, codes=[] ) ), Element( u'CR621', Properties(desc=u'Date', req_sit=u'N', data_type=(u'DT',u'8',u'8'), position=21, codes=[] ) ), ), Segment( u'PWK', Properties(syntax='',req_sit=u'S',repeat=u'10',pos=u'155',desc=u'Additional Service Information'), Element( u'PWK01', Properties(desc=u'Report Type Code', req_sit=u'R', data_type=(u'ID',u'2',u'2'), position=1, codes=[u'03', u'04', u'05', u'06', u'07', u'08', u'09', u'10', u'11', u'13', u'15', u'21', u'48', u'55', u'59', u'77', u'A3', u'A4', u'AM', u'AS', u'AT', u'B2', u'B3', u'BR', u'BS', u'BT', u'CB', u'CK', u'D2', u'DA', u'DB', u'DG', u'DJ', u'DS', u'FM', u'HC', u'HR', u'I5', u'IR', u'LA', u'M1', u'NN', u'OB', u'OC', u'OD', u'OE', u'OX', u'P4', u'P5', u'P6', u'P7', u'PE', u'PN', u'PO', u'PQ', u'PY', u'PZ', u'QC', u'QR', u'RB', u'RR', u'RT', u'RX', u'SG', u'V5', u'XP'] ) ), Element( u'PWK02', Properties(desc=u'Report Transmission Code', req_sit=u'R', data_type=(u'ID',u'1',u'2'), position=2, codes=[u'BM', u'EL', u'EM', u'FX', u'VO'] ) ), Element( u'PWK03', Properties(desc=u'Report Copies Needed', req_sit=u'N', data_type=(u'N0',u'1',u'2'), position=3, codes=[] ) ), Element( u'PWK04', Properties(desc=u'Entity Identifier Code', req_sit=u'N', data_type=(u'ID',u'2',u'3'), position=4, codes=[] ) ), Element( u'PWK05', Properties(desc=u'Identification Code Qualifier', req_sit=u'S', data_type=(u'ID',u'1',u'2'), position=5, codes=[u'AC'] ) ), Element( u'PWK06', Properties(desc=u'Identification Code', req_sit=u'S', data_type=(u'AN',u'2',u'80'), position=6, codes=[] ) ), Element( u'PWK07', Properties(desc=u'Description', req_sit=u'S', data_type=(u'AN',u'1',u'80'), position=7, codes=[] ) ), Composite( u'C002', Properties(req_sit=u'N',refdes='',seq=u'08',desc=u'Actions Indicated'), ), Element( u'PWK09', Properties(desc=u'Request Category Code', req_sit=u'N', data_type=(u'ID',u'1',u'2'), position=9, codes=[] ) ), ), Segment( u'MSG', Properties(syntax='',req_sit=u'S',repeat=u'1',pos=u'160',desc=u'Message Text'), Element( u'MSG01', Properties(desc=u'Free-form Message Text', req_sit=u'R', data_type=(u'AN',u'1',u'264'), position=1, codes=[] ) ), Element( u'MSG02', Properties(desc=u'Printer Carriage Control Code', req_sit=u'N', data_type=(u'ID',u'2',u'2'), position=2, codes=[] ) ), Element( u'MSG03', Properties(desc=u'Number', req_sit=u'N', data_type=(u'N0',u'1',u'9'), position=3, codes=[] ) ), ), parsed_278_2010F, ) parsed_278_2000E = Loop( u'2000E', Properties(looptype='',repeat=u'>1',pos=u'180',req_sit=u'R',desc=u'Service Provider Level'), Segment( u'HL', Properties(syntax='',req_sit=u'R',repeat=u'1',pos=u'010',desc=u'Service Provider Level'), Element( u'HL01', Properties(desc=u'Hierarchical ID Number', req_sit=u'R', data_type=(u'AN',u'1',u'12'), position=1, codes=[] ) ), Element( u'HL02', Properties(desc=u'Hierarchical Parent ID Number', req_sit=u'R', data_type=(u'AN',u'1',u'12'), position=2, codes=[] ) ), Element( u'HL03', Properties(desc=u'Hierarchical Level Code', req_sit=u'R', data_type=(u'ID',u'1',u'2'), position=3, codes=[u'19'] ) ), Element( u'HL04', Properties(desc=u'Hierarchical Child Code', req_sit=u'R', data_type=(u'ID',u'1',u'1'), position=4, codes=[u'1'] ) ), ), Segment( u'MSG', Properties(syntax='',req_sit=u'S',repeat=u'1',pos=u'160',desc=u'Message Text'), Element( u'MSG01', Properties(desc=u'Free-form Message Text', req_sit=u'R', data_type=(u'AN',u'1',u'264'), position=1, codes=[] ) ), Element( u'MSG02', Properties(desc=u'Printer Carriage Control Code', req_sit=u'N', data_type=(u'ID',u'2',u'2'), position=2, codes=[] ) ), Element( u'MSG03', Properties(desc=u'Number', req_sit=u'N', data_type=(u'N0',u'1',u'9'), position=3, codes=[] ) ), ), parsed_278_2010E, parsed_278_2000F, ) parsed_278_2000D = Loop( u'2000D', Properties(looptype='',repeat=u'1',pos=u'180',req_sit=u'S',desc=u'Dependent Level'), Segment( u'HL', Properties(syntax='',req_sit=u'R',repeat=u'1',pos=u'010',desc=u'Dependent Level'), Element( u'HL01', Properties(desc=u'Hierarchical ID Number', req_sit=u'R', data_type=(u'AN',u'1',u'12'), position=1, codes=[] ) ), Element( u'HL02', Properties(desc=u'Hierarchical Parent ID Number', req_sit=u'R', data_type=(u'AN',u'1',u'12'), position=2, codes=[] ) ), Element( u'HL03', Properties(desc=u'Hierarchical Level Code', req_sit=u'R', data_type=(u'ID',u'1',u'2'), position=3, codes=[u'23'] ) ), Element( u'HL04', Properties(desc=u'Hierarchical Child Code', req_sit=u'R', data_type=(u'ID',u'1',u'1'), position=4, codes=[u'1'] ) ), ), Segment( u'TRN', Properties(syntax='',req_sit=u'S',repeat=u'3',pos=u'020',desc=u'Patient Event Tracking Number'), Element( u'TRN01', Properties(desc=u'Trace Type Code', req_sit=u'R', data_type=(u'ID',u'1',u'2'), position=1, codes=[u'1', u'2'] ) ), Element( u'TRN02', Properties(desc=u'Reference Identification', req_sit=u'R', data_type=(u'AN',u'1',u'50'), position=2, codes=[] ) ), Element( u'TRN03', Properties(desc=u'Originating Company Identifier', req_sit=u'R', data_type=(u'AN',u'10',u'10'), position=3, codes=[] ) ), Element( u'TRN04', Properties(desc=u'Reference Identification', req_sit=u'S', data_type=(u'AN',u'1',u'50'), position=4, codes=[] ) ), ), Segment( u'AAA', Properties(syntax='',req_sit=u'S',repeat=u'9',pos=u'030',desc=u'Dependent Request Validation'), Element( u'AAA01', Properties(desc=u'Yes/No Condition or Response Code', req_sit=u'R', data_type=(u'ID',u'1',u'1'), position=1, codes=[u'N', u'Y'] )
<reponame>rsdoherty/azure-sdk-for-python # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrest.polling import LROPoller, NoPolling from msrestazure.polling.arm_polling import ARMPolling from .. import models class AccountsOperations(object): """AccountsOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. :ivar api_version: Client Api Version. Constant value: "2016-11-01". """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2016-11-01" self.config = config def list( self, filter=None, top=None, skip=None, select=None, orderby=None, count=None, custom_headers=None, raw=False, **operation_config): """Gets the first page of Data Lake Analytics accounts, if any, within the current subscription. This includes a link to the next page, if any. :param filter: OData filter. Optional. :type filter: str :param top: The number of items to return. Optional. :type top: int :param skip: The number of items to skip over before returning elements. Optional. :type skip: int :param select: OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. :type select: str :param orderby: OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional. :type orderby: str :param count: The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional. :type count: bool :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of DataLakeAnalyticsAccountBasic :rtype: ~azure.mgmt.datalake.analytics.account.models.DataLakeAnalyticsAccountBasicPaged[~azure.mgmt.datalake.analytics.account.models.DataLakeAnalyticsAccountBasic] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = self.list.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} if filter is not None: query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') if top is not None: query_parameters['$top'] = self._serialize.query("top", top, 'int', minimum=1) if skip is not None: query_parameters['$skip'] = self._serialize.query("skip", skip, 'int', minimum=1) if select is not None: query_parameters['$select'] = self._serialize.query("select", select, 'str') if orderby is not None: query_parameters['$orderby'] = self._serialize.query("orderby", orderby, 'str') if count is not None: query_parameters['$count'] = self._serialize.query("count", count, 'bool') query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.DataLakeAnalyticsAccountBasicPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.DataLakeAnalyticsAccountBasicPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DataLakeAnalytics/accounts'} def list_by_resource_group( self, resource_group_name, filter=None, top=None, skip=None, select=None, orderby=None, count=None, custom_headers=None, raw=False, **operation_config): """Gets the first page of Data Lake Analytics accounts, if any, within a specific resource group. This includes a link to the next page, if any. :param resource_group_name: The name of the Azure resource group. :type resource_group_name: str :param filter: OData filter. Optional. :type filter: str :param top: The number of items to return. Optional. :type top: int :param skip: The number of items to skip over before returning elements. Optional. :type skip: int :param select: OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. :type select: str :param orderby: OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional. :type orderby: str :param count: The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional. :type count: bool :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of DataLakeAnalyticsAccountBasic :rtype: ~azure.mgmt.datalake.analytics.account.models.DataLakeAnalyticsAccountBasicPaged[~azure.mgmt.datalake.analytics.account.models.DataLakeAnalyticsAccountBasic] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = self.list_by_resource_group.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} if filter is not None: query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') if top is not None: query_parameters['$top'] = self._serialize.query("top", top, 'int', minimum=1) if skip is not None: query_parameters['$skip'] = self._serialize.query("skip", skip, 'int', minimum=1) if select is not None: query_parameters['$select'] = self._serialize.query("select", select, 'str') if orderby is not None: query_parameters['$orderby'] = self._serialize.query("orderby", orderby, 'str') if count is not None: query_parameters['$count'] = self._serialize.query("count", count, 'bool') query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.DataLakeAnalyticsAccountBasicPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.DataLakeAnalyticsAccountBasicPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts'} def _create_initial( self, resource_group_name, account_name, parameters, custom_headers=None, raw=False, **operation_config): # Construct URL url = self.create.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'accountName': self._serialize.url("account_name", account_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'CreateDataLakeAnalyticsAccountParameters') # Construct and send request request = self._client.put(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('DataLakeAnalyticsAccount', response) if response.status_code == 201: deserialized = self._deserialize('DataLakeAnalyticsAccount', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create( self, resource_group_name, account_name, parameters, custom_headers=None, raw=False, polling=True, **operation_config): """Creates the specified Data Lake Analytics account. This supplies the user with computation services for Data Lake Analytics workloads. :param resource_group_name: The name of the Azure resource group. :type resource_group_name: str :param account_name: The name of the Data Lake Analytics account. :type account_name: str :param parameters: Parameters supplied to create a new Data Lake Analytics account. :type parameters: ~azure.mgmt.datalake.analytics.account.models.CreateDataLakeAnalyticsAccountParameters :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns DataLakeAnalyticsAccount or ClientRawResponse<DataLakeAnalyticsAccount> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.datalake.analytics.account.models.DataLakeAnalyticsAccount] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.datalake.analytics.account.models.DataLakeAnalyticsAccount]] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._create_initial( resource_group_name=resource_group_name, account_name=account_name, parameters=parameters, custom_headers=custom_headers, raw=True, **operation_config ) def get_long_running_output(response): deserialized = self._deserialize('DataLakeAnalyticsAccount', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized lro_delay = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) elif polling is False: polling_method = NoPolling() else: polling_method = polling return LROPoller(self._client, raw_result, get_long_running_output, polling_method) create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}'} def get( self, resource_group_name, account_name, custom_headers=None, raw=False, **operation_config): """Gets details of the specified Data Lake Analytics account. :param resource_group_name: The name of the Azure resource group. :type resource_group_name: str :param account_name: The name of the Data Lake Analytics
<reponame>mitdo/o2ac-ur<gh_stars>10-100 #!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2020, OMRON SINIC X # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of OMRON SINIC X nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Author: <NAME>, <NAME> import o2ac_routines.helpers as helpers from o2ac_routines.common import O2ACCommon import copy import numpy as np import rospy import geometry_msgs.msg import tf_conversions from math import pi, radians from ur_control import conversions tau = 2.0*pi # Part of math from Python 3.6 class CalibrationClass(O2ACCommon): """ These routines check the robots' calibration by moving them to objects defined in the scene. """ def __init__(self): super(CalibrationClass, self).__init__() self.a_bot_downward_orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, tau/4, tau/2)) self.bin_names = ["bin3_1", "bin2_4", "bin2_3", "bin2_2", "bin2_1", "bin1_2", "bin1_1", "bin1_4", "bin1_5", "bin1_3"] # Neutral downward in the taskboard frames rospy.sleep(.5) # Use this instead of waiting, so that simulation can be used def offset_pose_in_own_coordinate_system(self, ps, offset): """ ps is the PoseStamped to offset. offset is a Point. """ rospy.loginfo("Received pose to offset to TCP link:") rospy.loginfo(str(ps.pose.position.x) + ", " + str(ps.pose.position.y) + ", " + str(ps.pose.position.z)) rospy.loginfo(str(ps.pose.orientation.x) + ", " + str(ps.pose.orientation.y) + ", " + str(ps.pose.orientation.z) + ", " + str(ps.pose.orientation.w)) m = geometry_msgs.msg.TransformStamped() m.header.frame_id = ps.header.frame_id m.child_frame_id = "temp_pose__" m.transform.translation.x = ps.pose.position.x m.transform.translation.y = ps.pose.position.y m.transform.translation.z = ps.pose.position.z m.transform.rotation.x = ps.pose.orientation.x m.transform.rotation.y = ps.pose.orientation.y m.transform.rotation.z = ps.pose.orientation.z m.transform.rotation.w = ps.pose.orientation.w self.listener.setTransform(m) ps_with_offset = geometry_msgs.msg.PoseStamped() ps_with_offset.header.frame_id = "temp_pose__" ps_with_offset.pose.position.x = offset.x ps_with_offset.pose.position.y = offset.y ps_with_offset.pose.position.z = offset.z ps_with_offset.pose.orientation.w = 1.0 ps_new = self.listener.transformPose(ps.header.frame_id, ps_with_offset) rospy.loginfo("New pose:") rospy.loginfo(str(ps_new.pose.position.x) + ", " + str(ps_new.pose.position.y) + ", " + str(ps_new.pose.position.z)) rospy.loginfo(str(ps_new.pose.orientation.x) + ", " + str(ps_new.pose.orientation.y) + ", " + str(ps_new.pose.orientation.z) + ", " + str(ps_new.pose.orientation.w)) return ps_new # TODO: Implement the above in the function below def cycle_through_calibration_poses(self, poses, robot_name, speed=0.1, with_approach=False, use_z_for_approach=False, move_lin=False, go_home=True, end_effector_link=""): home_pose = "home" if "screw" in end_effector_link: home_pose = "screw_ready" if with_approach and not use_z_for_approach: rospy.logwarn("with_approach only moves in the X direction of the header frame. Be careful.") for pose in poses: ps_approach = copy.deepcopy(pose) if not use_z_for_approach: ps_approach.pose.position.x -= .05 else: ps_approach.pose.position.z += .05 rospy.loginfo("============ Press `Enter` to move " + robot_name + " to " + pose.header.frame_id) helpers.publish_marker(pose, namespace="place_pose") raw_input() robot = self.active_robots[robot_name] if go_home: robot.go_to_named_pose(home_pose) if with_approach: robot.go_to_pose_goal(ps_approach, speed=speed, end_effector_link=end_effector_link, move_lin=move_lin) if rospy.is_shutdown(): break if with_approach: robot.go_to_pose_goal(ps_approach, speed=speed, end_effector_link=end_effector_link, move_lin=move_lin) robot.go_to_pose_goal(pose, speed=speed, end_effector_link=end_effector_link, move_lin=move_lin) else: robot.go_to_pose_goal(pose, speed=speed, end_effector_link=end_effector_link, move_lin=move_lin) rospy.loginfo("============ Press `Enter` to proceed ") raw_input() if with_approach: robot.go_to_pose_goal(ps_approach, speed=speed, end_effector_link=end_effector_link, move_lin=move_lin) if go_home: robot.go_to_named_pose(home_pose, force_ur_script=move_lin) if go_home: rospy.loginfo("Moving all robots home again.") self.a_bot.go_to_named_pose("home") self.b_bot.go_to_named_pose("home") self.c_bot.go_to_named_pose("home") return def assembly_calibration_base_plate(self, robot_name="b_bot", end_effector_link="", panel_name="", rotation=0): # if not self.set_assembly("wrs_assembly_2020"): rospy.loginfo("============ Calibrating base plate for the assembly task. ============") rospy.loginfo("eef link " + end_effector_link + " should be 5 mm above each corner of the plate.") self.publish_part_in_assembled_position("base", marker_only=True) robot = self.active_robots[robot_name] self.make_space_for_robot(robot_name) if end_effector_link == "": robot.go_to_named_pose("home") elif "screw" in end_effector_link or "suction" in end_effector_link: robot.go_to_named_pose("screw_ready") poses = [] pose0 = geometry_msgs.msg.PoseStamped() pose0.pose.orientation.w = 1.0 pose0.pose.position.x = -.014 zero_rot = -tau/2 if robot_name == "a_bot" else 0 pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(zero_rot + rotation, 0, 0)) self.allow_collisions_with_robot_hand("base_fixture_top", robot_name) if panel_name == "motor_panel": for i in range(2): poses.append(copy.deepcopy(pose0)) poses[0].header.frame_id = "assembled_part_01_screw_hole_panel2_1" poses[1].header.frame_id = "assembled_part_01_screw_hole_panel2_2" elif panel_name == "bearing_panel": for i in range(2): poses.append(copy.deepcopy(pose0)) poses[0].header.frame_id = "assembled_part_01_screw_hole_panel1_1" poses[1].header.frame_id = "assembled_part_01_screw_hole_panel1_2" else: for i in range(4): poses.append(copy.deepcopy(pose0)) poses[0].header.frame_id = "assembled_part_01_screw_hole_panel2_2" poses[1].header.frame_id = "assembled_part_01_screw_hole_panel2_1" poses[2].header.frame_id = "assembled_part_01_screw_hole_panel1_2" poses[3].header.frame_id = "assembled_part_01_screw_hole_panel1_1" print("moving to #", len(poses), "poses") self.cycle_through_calibration_poses(poses, robot_name, go_home=False, end_effector_link=end_effector_link, move_lin=True, with_approach=True) return def assembly_calibration_assembled_parts(self): rospy.loginfo("============ Calibrating full assembled parts for the assembly task. ============") rospy.loginfo("b_bot gripper tip should go close to some important spots.") poses = [] pose0 = geometry_msgs.msg.PoseStamped() pose0.pose.orientation.w = 1.0 pose0.pose.position.x = -.02 for i in range(5): poses.append(copy.deepcopy(pose0)) poses[1].header.frame_id = "assembled_part_03" # Top of plate 2 poses[1].pose.position.x = .058 poses[1].pose.position.y = -.0025 poses[1].pose.position.z = .095 + .01 poses[1].pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, tau/4, 0)) poses[2].header.frame_id = "assembled_part_08_front_tip" # Front of rotary shaft poses[2].pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, 0, -tau/2)) poses[2].pose.position.x = .03 poses[3].header.frame_id = "assembled_part_14_screw_head" poses[3].pose.position.x = -.03 poses[4].header.frame_id = "assembled_part_04_tip" poses[4].pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(-tau/2, 0, -tau/2)) poses[4].pose.position.x = .03 self.cycle_through_calibration_poses(poses, "b_bot", go_home=True) return def taskboard_calibration_with_tools(self, robot_name="b_bot", end_effector_link="", hole=""): rospy.loginfo("============ Calibrating taskboard screw holes. ============") rospy.loginfo("eef link " + end_effector_link + " should be 5 mm above each corner of the plate.") self.make_space_for_robot(robot_name) self.active_robots[robot_name].go_to_named_pose("horizontal_screw_ready") # self.go_to_named_pose("home", robot_name) poses = [] pose0 = geometry_msgs.msg.PoseStamped() pose0.pose.orientation.w = 1.0 pose0.pose.position.x = -.002 if robot_name == "a_bot": pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(-tau/12, 0, 0)) if end_effector_link == "a_bot_gripper_tip_link": pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(-tau/4, 0, 0)) elif robot_name == "b_bot": pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(tau/12, 0, 0)) if end_effector_link == "b_bot_gripper_tip_link": pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(tau/6, 0, 0)) if not hole: for i in range(3): poses.append(copy.deepcopy(pose0)) poses[0].header.frame_id = "taskboard_set_screw_link" poses[1].header.frame_id = "taskboard_m3_screw_link" poses[2].header.frame_id = "taskboard_m4_screw_link" elif hole == "m4": poses.append(copy.deepcopy(pose0)) poses[0].header.frame_id = "taskboard_m4_screw_link" poses[0].pose.position.y += -0.001 # MAGIC NUMBER (points right) poses[0].pose.position.z += 0.002 # MAGIC NUMBER (points down) elif hole == "m3": poses.append(copy.deepcopy(pose0)) poses[0].header.frame_id = "taskboard_m3_screw_link" poses[0].pose.position.y += 0.001 # MAGIC NUMBER (points right) poses[0].pose.position.z += -0.001 # MAGIC NUMBER (points down) elif hole == "setscrew": poses.append(copy.deepcopy(pose0)) poses[0].header.frame_id = "taskboard_set_screw_link" poses[0].pose.position.y += -0.002 # MAGIC NUMBER (points right) poses[0].pose.position.z += 0.003 # MAGIC NUMBER (points down) self.cycle_through_calibration_poses(poses, robot_name, go_home=False, with_approach=True, end_effector_link=end_effector_link, move_lin=True) self.active_robots[robot_name].go_to_named_pose("horizontal_screw_ready") return def tray_sponge_calibration(self, robot_name="a_bot", end_effector_link="a_bot_gripper_tip_link"): rospy.loginfo("============ Touching tray sponge. ============") rospy.loginfo("eef link " + end_effector_link + " should be touching the tray sponge in middle, then left, then right.") if robot_name == "a_bot": self.b_bot.go_to_named_pose("home") elif robot_name == "b_bot": self.a_bot.go_to_named_pose("home") poses = [] pose0 = geometry_msgs.msg.PoseStamped() pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, tau/4, 0)) pose0.header.frame_id = "tray_center" pose0.pose.position.z = 0.003 for i in range(3): poses.append(copy.deepcopy(pose0)) poses[0].pose.position.y = 0.0 poses[1].pose.position.y = -0.1 poses[2].pose.position.y = 0.1 self.cycle_through_calibration_poses(poses, robot_name, go_home=False, with_approach=True, end_effector_link=end_effector_link, move_lin=True) return def tray_corners_calibration(self, robot_name="a_bot", end_effector_link="a_bot_gripper_tip_link"): rospy.loginfo("============ Touching tray corners. ============") rospy.loginfo("eef link " + end_effector_link + " should go to the tray corners.") if robot_name == "a_bot": self.b_bot.go_to_named_pose("home") elif robot_name == "b_bot": self.a_bot.go_to_named_pose("home") poses = [] pose0 = geometry_msgs.msg.PoseStamped() pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, tau/4, 0)) pose0.pose.position.z = 0.01 for i in range(4): poses.append(copy.deepcopy(pose0)) poses[0].header.frame_id = "traycorner_1_link" poses[1].header.frame_id = "traycorner_2_link" poses[2].header.frame_id = "traycorner_3_link" poses[3].header.frame_id = "traycorner_4_link" self.cycle_through_calibration_poses(poses, robot_name, go_home=False, with_approach=False, end_effector_link=end_effector_link, move_lin=True) return def touch_workspace_center(self): rospy.loginfo("============ Touching workspace center. ============") self.a_bot.go_to_named_pose("home") self.b_bot.go_to_named_pose("home") poses = [] pose_a = geometry_msgs.msg.PoseStamped() pose_a.header.frame_id = "workspace_center" pose_a.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, tau/4, 0)) pose_a.pose.position.x = .0 pose_a.pose.position.y = -.2 pose_a.pose.position.z = .03 pose_b = copy.deepcopy(pose_a) pose_b.pose.position.x = .0 pose_b.pose.position.y = .3 pose_b.pose.position.z = .03 pose_c = copy.deepcopy(pose_a) pose_c.pose.position.x = -.3 pose_c.pose.position.y = .2 pose_c.pose.position.z = .03 rospy.loginfo("============ Going to 2 cm above the table. ============") self.b_bot.go_to_pose_goal(pose_b, speed=1.0) self.a_bot.go_to_pose_goal(pose_a, speed=1.0) rospy.loginfo("============ Press enter to go to .1 cm above the table. ============") i = raw_input() if not rospy.is_shutdown(): pose_a.pose.position.z = .001 pose_b.pose.position.z = .001 pose_c.pose.position.z = .001 self.b_bot.go_to_pose_goal(pose_b, speed=0.01) self.a_bot.go_to_pose_goal(pose_a, speed=0.01) rospy.loginfo("============ Press enter to go home. ============") raw_input() self.a_bot.go_to_named_pose("home") self.b_bot.go_to_named_pose("home") return def workspace_level_calibration(self,
specifies the index of the server that we want to use. Default is 0. async_req (bool): execute request asynchronously Returns: bt_app_element_modify_info.BTAppElementModifyInfo If the method is called asynchronously, returns the request thread. """ kwargs["async_req"] = kwargs.get("async_req", False) kwargs["_return_http_data_only"] = kwargs.get( "_return_http_data_only", True ) kwargs["_preload_content"] = kwargs.get("_preload_content", True) kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) kwargs["_host_index"] = kwargs.get("_host_index", 0) kwargs["did"] = did kwargs["eid"] = eid kwargs["wvm"] = wvm kwargs["wvmid"] = wvmid kwargs["sid"] = sid return self.call_with_http_info(**kwargs) self.delete_app_element_content = Endpoint( settings={ "response_type": (bt_app_element_modify_info.BTAppElementModifyInfo,), "auth": ["OAuth2"], "endpoint_path": "/api/appelements/d/{did}/{wvm}/{wvmid}/e/{eid}/content/subelements/{sid}", "operation_id": "delete_app_element_content", "http_method": "DELETE", "servers": [], }, params_map={ "all": [ "did", "eid", "wvm", "wvmid", "sid", "transaction_id", "parent_change_id", "description", ], "required": ["did", "eid", "wvm", "wvmid", "sid",], "nullable": [], "enum": [], "validation": [], }, root_map={ "validations": {}, "allowed_values": {}, "openapi_types": { "did": (str,), "eid": (str,), "wvm": (str,), "wvmid": (str,), "sid": (str,), "transaction_id": (str,), "parent_change_id": (str,), "description": (str,), }, "attribute_map": { "did": "did", "eid": "eid", "wvm": "wvm", "wvmid": "wvmid", "sid": "sid", "transaction_id": "transactionId", "parent_change_id": "parentChangeId", "description": "description", }, "location_map": { "did": "path", "eid": "path", "wvm": "path", "wvmid": "path", "sid": "path", "transaction_id": "query", "parent_change_id": "query", "description": "query", }, "collection_format_map": {}, }, headers_map={ "accept": ["application/vnd.onshape.v1+json;charset=UTF-8;qs=0.1"], "content_type": [], }, api_client=api_client, callable=__delete_app_element_content, ) def __delete_reference(self, did, eid, wvm, wvmid, rid, **kwargs): """Delete Reference # 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_reference(did, eid, wvm, wvmid, rid, async_req=True) >>> result = thread.get() Args: did (str): eid (str): wvm (str): wvmid (str): rid (str): Keyword Args: transaction_id (str): [optional] parent_change_id (str): [optional] description (str): [optional] _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int): specifies the index of the server that we want to use. Default is 0. async_req (bool): execute request asynchronously Returns: bt_app_element_reference_info.BTAppElementReferenceInfo If the method is called asynchronously, returns the request thread. """ kwargs["async_req"] = kwargs.get("async_req", False) kwargs["_return_http_data_only"] = kwargs.get( "_return_http_data_only", True ) kwargs["_preload_content"] = kwargs.get("_preload_content", True) kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) kwargs["_host_index"] = kwargs.get("_host_index", 0) kwargs["did"] = did kwargs["eid"] = eid kwargs["wvm"] = wvm kwargs["wvmid"] = wvmid kwargs["rid"] = rid return self.call_with_http_info(**kwargs) self.delete_reference = Endpoint( settings={ "response_type": ( bt_app_element_reference_info.BTAppElementReferenceInfo, ), "auth": ["OAuth2"], "endpoint_path": "/api/appelements/d/{did}/{wvm}/{wvmid}/e/{eid}/references/{rid}", "operation_id": "delete_reference", "http_method": "DELETE", "servers": [], }, params_map={ "all": [ "did", "eid", "wvm", "wvmid", "rid", "transaction_id", "parent_change_id", "description", ], "required": ["did", "eid", "wvm", "wvmid", "rid",], "nullable": [], "enum": [], "validation": [], }, root_map={ "validations": {}, "allowed_values": {}, "openapi_types": { "did": (str,), "eid": (str,), "wvm": (str,), "wvmid": (str,), "rid": (str,), "transaction_id": (str,), "parent_change_id": (str,), "description": (str,), }, "attribute_map": { "did": "did", "eid": "eid", "wvm": "wvm", "wvmid": "wvmid", "rid": "rid", "transaction_id": "transactionId", "parent_change_id": "parentChangeId", "description": "description", }, "location_map": { "did": "path", "eid": "path", "wvm": "path", "wvmid": "path", "rid": "path", "transaction_id": "query", "parent_change_id": "query", "description": "query", }, "collection_format_map": {}, }, headers_map={ "accept": ["application/vnd.onshape.v1+json;charset=UTF-8;qs=0.1"], "content_type": [], }, api_client=api_client, callable=__delete_reference, ) def __get_app_element_history(self, did, eid, wvm, wvmid, **kwargs): """Get History # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_app_element_history(did, eid, wvm, wvmid, async_req=True) >>> result = thread.get() Args: did (str): eid (str): wvm (str): wvmid (str): Keyword Args: _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int): specifies the index of the server that we want to use. Default is 0. async_req (bool): execute request asynchronously Returns: bt_app_element_history_info.BTAppElementHistoryInfo If the method is called asynchronously, returns the request thread. """ kwargs["async_req"] = kwargs.get("async_req", False) kwargs["_return_http_data_only"] = kwargs.get( "_return_http_data_only", True ) kwargs["_preload_content"] = kwargs.get("_preload_content", True) kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) kwargs["_host_index"] = kwargs.get("_host_index", 0) kwargs["did"] = did kwargs["eid"] = eid kwargs["wvm"] = wvm kwargs["wvmid"] = wvmid return self.call_with_http_info(**kwargs) self.get_app_element_history = Endpoint( settings={ "response_type": (bt_app_element_history_info.BTAppElementHistoryInfo,), "auth": ["OAuth2"], "endpoint_path": "/api/appelements/d/{did}/{wvm}/{wvmid}/e/{eid}/content/history", "operation_id": "get_app_element_history", "http_method": "GET", "servers": [], }, params_map={ "all": ["did", "eid", "wvm", "wvmid",], "required": ["did", "eid", "wvm", "wvmid",], "nullable": [], "enum": [], "validation": [], }, root_map={ "validations": {}, "allowed_values": {}, "openapi_types": { "did": (str,), "eid": (str,), "wvm": (str,), "wvmid": (str,), }, "attribute_map": { "did": "did", "eid": "eid", "wvm": "wvm", "wvmid": "wvmid", }, "location_map": { "did": "path", "eid": "path", "wvm": "path", "wvmid": "path", }, "collection_format_map": {}, }, headers_map={ "accept": ["application/vnd.onshape.v1+json;charset=UTF-8;qs=0.1"], "content_type": [], }, api_client=api_client, callable=__get_app_element_history, ) def __get_sub_element_content(self, did, eid, wvm, wvmid, **kwargs): """Get Content # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_sub_element_content(did, eid, wvm, wvmid, async_req=True) >>> result = thread.get() Args: did (str): eid (str): wvm (str): wvmid (str): Keyword Args: transaction_id (str): [optional] change_id (str): [optional] base_change_id (str): [optional] subelement_id (str): [optional] link_document_id (str): [optional] _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int): specifies the index of the server that we want to use. Default is 0. async_req (bool): execute request asynchronously Returns: bt_app_element_content_info.BTAppElementContentInfo If the method is called asynchronously, returns the request thread. """ kwargs["async_req"] = kwargs.get("async_req", False) kwargs["_return_http_data_only"] = kwargs.get( "_return_http_data_only", True ) kwargs["_preload_content"] = kwargs.get("_preload_content", True) kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) kwargs["_host_index"] = kwargs.get("_host_index", 0) kwargs["did"] = did kwargs["eid"] = eid kwargs["wvm"] = wvm kwargs["wvmid"] = wvmid return self.call_with_http_info(**kwargs) self.get_sub_element_content = Endpoint( settings={ "response_type": (bt_app_element_content_info.BTAppElementContentInfo,), "auth": ["OAuth2"], "endpoint_path": "/api/appelements/d/{did}/{wvm}/{wvmid}/e/{eid}/content", "operation_id": "get_sub_element_content", "http_method": "GET", "servers": [], }, params_map={ "all": [ "did", "eid", "wvm", "wvmid", "transaction_id", "change_id", "base_change_id", "subelement_id", "link_document_id", ], "required": ["did", "eid", "wvm", "wvmid",], "nullable": [], "enum": [], "validation": [], }, root_map={ "validations": {}, "allowed_values": {}, "openapi_types": { "did": (str,), "eid": (str,), "wvm": (str,), "wvmid": (str,), "transaction_id": (str,), "change_id": (str,), "base_change_id": (str,), "subelement_id": (str,), "link_document_id": (str,), }, "attribute_map": { "did": "did", "eid": "eid", "wvm": "wvm", "wvmid": "wvmid", "transaction_id": "transactionId", "change_id": "changeId", "base_change_id": "baseChangeId", "subelement_id": "subelementId", "link_document_id": "linkDocumentId", }, "location_map": { "did": "path", "eid": "path", "wvm": "path", "wvmid": "path", "transaction_id": "query", "change_id": "query", "base_change_id": "query", "subelement_id": "query", "link_document_id": "query", }, "collection_format_map": {}, }, headers_map={ "accept": ["application/vnd.onshape.v1+json;charset=UTF-8;qs=0.1"], "content_type": [], }, api_client=api_client, callable=__get_sub_element_content, ) def __get_subelement_ids(self, did, eid, wvm, wvmid, **kwargs): """Get Sub-element IDs # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_subelement_ids(did, eid, wvm, wvmid, async_req=True)
# Copyright 2020 Petuum, Inc. All Rights Reserved. # # It includes the derived work based on: # # Copyright 2018 The TensorFlow 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. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import yaml import os import sys import tensorflow as tf # pylint: disable=g-bad-import-order from absl import app from absl import flags from absl import logging from os.path import expanduser from tensorflow_addons.optimizers import LazyAdam # pylint: enable=g-bad-import-order from utils.recommendation import constants as rconst from utils.recommendation import movielens from utils.recommendation import ncf_common from utils.recommendation import ncf_input_pipeline from utils.recommendation import neumf_model from utils.flags import core as flags_core from utils.logs import logger from utils.logs import mlperf_helper from utils.misc import keras_utils from utils.misc import model_helpers ######################################################################### # Import AutoDist and Strategy from autodist import AutoDist from autodist.strategy.ps_strategy import PS from autodist.strategy.ps_lb_strategy import PSLoadBalancing from autodist.strategy.partitioned_ps_strategy import PartitionedPS from autodist.strategy.all_reduce_strategy import AllReduce from autodist.strategy.parallax_strategy import Parallax ######################################################################### FLAGS = flags.FLAGS class IncrementEpochCallback(tf.keras.callbacks.Callback): """A callback to increase the requested epoch for the data producer. The reason why we need this is because we can only buffer a limited amount of data. So we keep a moving window to represent the buffer. This is to move the one of the window's boundaries for each epoch. """ def __init__(self, producer): self._producer = producer def on_epoch_begin(self, epoch, logs=None): self._producer.increment_request_epoch() class CustomEarlyStopping(tf.keras.callbacks.Callback): """Stop training has reached a desired hit rate.""" def __init__(self, monitor, desired_value): super(CustomEarlyStopping, self).__init__() self.monitor = monitor self.desired = desired_value self.stopped_epoch = 0 def on_epoch_end(self, epoch, logs=None): current = self.get_monitor_value(logs) if current and current >= self.desired: self.stopped_epoch = epoch self.model.stop_training = True def on_train_end(self, logs=None): if self.stopped_epoch > 0: print("Epoch %05d: early stopping" % (self.stopped_epoch + 1)) def get_monitor_value(self, logs): logs = logs or {} monitor_value = logs.get(self.monitor) if monitor_value is None: logging.warning( "Early stopping conditioned on metric `%s` " "which is not available. Available metrics are: %s", self.monitor, ",".join( list( logs.keys()))) return monitor_value def _get_keras_model(params): """Constructs and returns the model.""" batch_size = params["batch_size"] user_input = tf.keras.layers.Input( shape=(1,), name=movielens.USER_COLUMN, dtype=tf.int32) item_input = tf.keras.layers.Input( shape=(1,), name=movielens.ITEM_COLUMN, dtype=tf.int32) valid_pt_mask_input = tf.keras.layers.Input( shape=(1,), name=rconst.VALID_POINT_MASK, dtype=tf.bool) dup_mask_input = tf.keras.layers.Input( shape=(1,), name=rconst.DUPLICATE_MASK, dtype=tf.int32) label_input = tf.keras.layers.Input( shape=(1,), name=rconst.TRAIN_LABEL_KEY, dtype=tf.bool) base_model = neumf_model.construct_model(user_input, item_input, params) logits = base_model.output zeros = tf.keras.layers.Lambda(lambda x: x * 0)(logits) softmax_logits = tf.keras.layers.concatenate([zeros, logits], axis=-1) keras_model = tf.keras.Model( inputs={ movielens.USER_COLUMN: user_input, movielens.ITEM_COLUMN: item_input, rconst.VALID_POINT_MASK: valid_pt_mask_input, rconst.DUPLICATE_MASK: dup_mask_input, rconst.TRAIN_LABEL_KEY: label_input}, outputs=softmax_logits) keras_model.summary() return keras_model def run_ncf(FLAGS): """Run NCF training and eval with Keras.""" ######################################################################### # Construct AutoDist with ResourceSpec for Different Strategies resource_spec_file = os.path.join( os.path.dirname(__file__), '../resource_spec.yml') resource_info = yaml.safe_load(open(resource_spec_file, 'r')) try: node_num = len(resource_info['nodes']) except ValueError: print("nodes need to be set in specficiation file") try: gpu_num = len(resource_info['nodes'][0]['gpus']) except ValueError: print("gpus need to be set in specficiation file") if FLAGS.autodist_patch_tf: os.environ['AUTODIST_PATCH_TF'] = '1' else: os.environ['AUTODIST_PATCH_TF'] = '0' if FLAGS.proxy: local_proxy_variable = True else: local_proxy_variable = False if FLAGS.autodist_strategy == 'PS': autodist = AutoDist( resource_spec_file, PS( local_proxy_variable=local_proxy_variable)) elif FLAGS.autodist_strategy == 'PSLoadBalancing': autodist = AutoDist(resource_spec_file, PSLoadBalancing( local_proxy_variable=local_proxy_variable)) elif FLAGS.autodist_strategy == 'PartitionedPS': autodist = AutoDist(resource_spec_file, PartitionedPS( local_proxy_variable=local_proxy_variable)) elif FLAGS.autodist_strategy == 'AllReduce': autodist = AutoDist(resource_spec_file, AllReduce(chunk_size=256)) elif FLAGS.autodist_strategy == 'Parallax': autodist = AutoDist( resource_spec_file, Parallax( chunk_size=256, local_proxy_variable=local_proxy_variable)) else: raise ValueError( 'the strategy can be only from PS, PSLoadBalancing, PartitionedPS, AllReduce, Parallax') ######################################################################### if FLAGS.seed is not None: print("Setting tf seed") tf.random.set_seed(FLAGS.seed) model_helpers.apply_clean(FLAGS) if FLAGS.dtype == "fp16" and FLAGS.fp16_implementation == "keras": policy = tf.keras.mixed_precision.experimental.Policy( "mixed_float16", loss_scale=flags_core.get_loss_scale( FLAGS, default_for_fp16="dynamic")) tf.keras.mixed_precision.experimental.set_policy(policy) params = ncf_common.parse_flags(FLAGS) params["distribute_strategy"] = None batch_size = params["batch_size"] time_callback = keras_utils.TimeHistory(batch_size, FLAGS.log_steps) callbacks = [time_callback] producer, input_meta_data = None, None generate_input_online = params["train_dataset_path"] is None if generate_input_online: num_users, num_items, _, _, producer = ncf_common.get_inputs(params) producer.start() per_epoch_callback = IncrementEpochCallback(producer) callbacks.append(per_epoch_callback) else: assert params["eval_dataset_path"] and params["input_meta_data_path"] with tf.io.gfile.GFile(params["input_meta_data_path"], "rb") as reader: input_meta_data = json.loads(reader.read().decode("utf-8")) num_users = input_meta_data["num_users"] num_items = input_meta_data["num_items"] params["num_users"], params["num_items"] = num_users, num_items if FLAGS.early_stopping: early_stopping_callback = CustomEarlyStopping( "val_HR_METRIC", desired_value=FLAGS.hr_threshold) callbacks.append(early_stopping_callback) with tf.Graph().as_default(), autodist.scope(): (train_input_dataset, eval_input_dataset, num_train_steps, num_eval_steps) = ( ncf_input_pipeline.create_ncf_input_data(params, producer, input_meta_data, None)) steps_per_epoch = None if generate_input_online else num_train_steps keras_model = _get_keras_model(params) if FLAGS.optimizer == 'adam': optimizer = tf.keras.optimizers.Adam( learning_rate=params["learning_rate"], beta_1=params["beta1"], beta_2=params["beta2"], epsilon=params["epsilon"]) elif FLAGS.optimizer == 'sgd': optimizer = tf.keras.optimizers.SGD( learning_rate=params["learning_rate"]) elif FLAGS.optimizer == 'lazyadam': optimizer = LazyAdam( learning_rate=params["learning_rate"], beta_1=params["beta1"], beta_2=params["beta2"], epsilon=params["epsilon"]) else: raise ValueError('Do not support other optimizers...') if FLAGS.fp16_implementation == "graph_rewrite": optimizer = tf.compat.v1.train.experimental.enable_mixed_precision_graph_rewrite( optimizer, loss_scale=flags_core.get_loss_scale(FLAGS, default_for_fp16="dynamic")) elif FLAGS.dtype == "fp16" and params["keras_use_ctl"]: optimizer = tf.keras.mixed_precision.experimental.LossScaleOptimizer( optimizer, tf.keras.mixed_precision.experimental.global_policy().loss_scale) return run_ncf_custom_training( params, autodist, keras_model, optimizer, callbacks, train_input_dataset, eval_input_dataset, num_train_steps, num_eval_steps, generate_input_online=generate_input_online, return_simulation=FLAGS.simulation_strategy_id is not None) def run_ncf_custom_training(params, autodist, keras_model, optimizer, callbacks, train_input_dataset, eval_input_dataset, num_train_steps, num_eval_steps, generate_input_online=True, return_simulation=False): """Runs custom training loop. Args: params: Dictionary containing training parameters. strategy: Distribution strategy to be used for distributed training. keras_model: Model used for training. optimizer: Optimizer used for training. callbacks: Callbacks to be invoked between batches/epochs. train_input_dataset: tf.data.Dataset used for training. eval_input_dataset: tf.data.Dataset used for evaluation. num_train_steps: Total number of steps to run for training. num_eval_steps: Total number of steps to run for evaluation. generate_input_online: Whether input data was generated by data producer. When data is generated by data producer, then train dataset must be re-initialized after every epoch. Returns: A tuple of train loss and a list of training and evaluation results. """ loss_object = tf.keras.losses.SparseCategoricalCrossentropy( reduction="sum", from_logits=True) train_input_iterator = tf.compat.v1.data.make_one_shot_iterator( train_input_dataset).get_next() def step_fn(features): softmax_logits = keras_model(features) softmax_logits = tf.cast(softmax_logits, "float32") labels = features[rconst.TRAIN_LABEL_KEY] loss = loss_object( labels, softmax_logits, sample_weight=features[rconst.VALID_POINT_MASK]) loss *= (1.0 / params["batch_size"]) if FLAGS.dtype == "fp16": loss = optimizer.get_scaled_loss(loss) grads = tf.gradients(loss, keras_model.trainable_variables) if FLAGS.dtype == "fp16": grads = optimizer.get_unscaled_gradients(grads) grads_and_vars = list(zip(grads, keras_model.trainable_variables)) if FLAGS.dense_gradient: grads_and_vars = neumf_model.sparse_to_dense_grads(grads_and_vars) train_op = optimizer.apply_gradients(grads_and_vars) return loss, train_op, keras_model.trainable_variables, grads, optimizer for callback in callbacks: callback.on_train_begin() if FLAGS.ml_perf: eval_summary_writer, train_summary_writer = None, None else: summary_dir = os.path.join(FLAGS.model_dir, "summaries") eval_summary_writer = tf.summary.create_file_writer( os.path.join(summary_dir, "eval")) train_summary_writer = tf.summary.create_file_writer( os.path.join(summary_dir, "train")) loss_op, train_op, vars, grads, optimizer = step_fn(train_input_iterator) ##################################################################### # Create distributed session. # Instead of using the original TensorFlow session for graph execution, # let's use AutoDist's distributed session, in which a computational # graph for distributed training is constructed. # # [original line] # >>> sess = tf.compat.v1.Session() sess = autodist.create_distributed_session() ##################################################################### for epoch in range(FLAGS.num_epochs): for cb in callbacks: cb.on_epoch_begin(epoch) train_loss = 0 for step in range(FLAGS.trial_steps): current_step = step + epoch * num_train_steps for c in callbacks: c.on_batch_begin(current_step) loss_val, _ = sess.run([loss_op, train_op]) train_loss += loss_val if train_summary_writer and step % 1000 == 0: with train_summary_writer.as_default(): tf.summary.scalar( "training_loss", train_loss / (step + 1), step=current_step) for c in callbacks: c.on_batch_end(current_step) train_loss /= num_train_steps logging.info( "Done training epoch %s, epoch loss=%s.", epoch + 1, train_loss) for c in callbacks: c.on_train_end() return train_loss def build_stats(loss, eval_result, time_callback): """Normalizes and returns dictionary of stats. Args: loss: The final loss at training time. eval_result: Output of the eval step. Assumes first value is eval_loss and second value is accuracy_top_1. time_callback: Time tracking callback likely used during keras.fit. Returns: Dictionary of normalized results. """ stats = {} if loss: stats["loss"] = loss if eval_result: stats["eval_loss"] = eval_result[0] stats["eval_hit_rate"] = eval_result[1] if time_callback: timestamp_log = time_callback.timestamp_log stats["step_timestamp_log"] = timestamp_log stats["train_finish_time"] = time_callback.train_finish_time if len(timestamp_log) > 1: stats["avg_exp_per_second"] = ( time_callback.batch_size * time_callback.log_steps * (len(time_callback.timestamp_log) - 1) / (timestamp_log[-1].timestamp - timestamp_log[0].timestamp)) return stats def define_trial_run_flags(): flags.DEFINE_string( name='resource', default='', help='resource specification') flags.DEFINE_integer( name='trial_steps', default=100, help='number of steps for trial') flags.DEFINE_enum( name="optimizer", default="adam", enum_values=[ "adam", "lazyadam", "sgd"], case_sensitive=False, help=flags_core.help_wrap("optimizer to use.")) flags.DEFINE_bool( name='dense_gradient', default='True', help='whether to use dense gradient') flags.DEFINE_string( name='simulation_strategy_id', default=None, help='strategy id to simulate') flags.DEFINE_string( name='simulation_folder', default=None, help='folder to store simulation result') flags.DEFINE_string( name='autodist_strategy', default='PS', help='the autodist strategy') flags.DEFINE_boolean( name='autodist_patch_tf', default=True, help='AUTODIST_PATCH_TF') flags.DEFINE_boolean(name='proxy', default=True, help='proxy') flags.DEFINE_string( name='default_data_dir', default='~/movielens', help='the default data directory') flags.DEFINE_integer( name='num_epochs', default=3, help='number of training epochs') def main(_): logdir = '/tmp/logs' if not os.path.exists(logdir): os.makedirs(logdir)
#!/usr/bin/env python3 """Game Engine Provides the logic for a simplified connect the dots game. The code in this module determines and enforces the rules of the game. Callers are responsible for the game's presentation component, or user experience (UX) The playing surface consits of 3x3 grid of dots: @ @ @ @ @ @ @ @ @ The game allows two players, X and Y, to alternately add horizontal and vertical lines to connect the dots. The following shows a game in progress: @---@ @ | | @ @ @ | @ @---@ When a player completes a square, that player wins the square and retains control of the next turn. The following shows a game in which player Y has completed a square: @---@ @ | | @ @---@ | Y | @ @---@ If a player connects two dots and does not complete a square, control passes to the other player. A player must add a line during his/her turn. The game ends when all dots ahve been connected. The player with more squares wins the game, and the game is a draw if both players have two squares each. This game engine manages 12 lines. Each line distinguished by its name (a string) as shown here: @---'North_Northwest'---@---'North_Northeast'---@ | | | | | | | | | 'West_Northwest' 'North_Center' 'East_Northeast' | | | | | | | | | @---'West_Center'-------@-----'East_Center'-----@ | | | | | | | | | 'West_Southwest' 'South_Center' 'East_Southeast' | | | | | | | | | @---'South_Southwest'---@---'South_Southeast'---@ The game engine manages four squares. Each square is distinguished by it's name (a string) as shown here: @---------------@---------------@ | | | | | | | 'top_left' | 'top_right' | | | | @---------------@---------------@ | | | | | | | 'bottom_left' |'bottom_right' | | | | | | | @---------------@---------------@ The string 'X' represents player X, and the string 'Y' represents playey Y. """ # NOTE: # ---------------------------------------------------------------------------- # Global vars (private) - maintain the state of the game. prefix vars with # underscores to dicourage access outside this module. # ---------------------------------------------------------------------------- # Boolean vars that keep track of whether or not a line exists between two # dots. E.g. If _n_nw is True, the line identifeid as 'North_Northwest' # exists. # ---------------------------------------------------------------------------- # @----_n_nw---@---_n_ne---@ # | | | # _w_nw _n_c _e_ne # | | | # @----_w_c----@----_e_c---@ # | | | # _w_sw _s_c _e_se # | | | # @---_s_sw----@---_s_se___@ # Init Line status (exists) - Initally, no lines exist anywhere (False) _n_nw, _n_ne, _n_c = False, False, False _w_nw, _w_sw, _w_c = False, False, False _e_ne, _e_se, _e_c = False, False, False _s_sw, _s_se, _s_c = False, False, False # Init Current player - A string, 'X' for player X or 'Y' for player Y _current_player = 'X' # Init square ownership as None # A string reps ownership, 'X' for player X or 'Y' for player Y _top_left_owner, _top_right_owner = None, None _bottom_left_owner, _bottom_right_owner = None, None ############################################################################## # Note: Private Functions (prefixed with underscore) # Functions accessed only within this module #----------------------------------------------------------------------------- def _update_square(sq): """(str) -> bool Updates the owner of square <sq>, if possible. <sq> must one of the strings; 'top_left', 'top_right', 'bottom_left', or 'bottom_right'. Function Checks to see: 1. If the square currently is not owned by a player and 2. if all the lines are in place to complete the sqaure. If both conditions are met, it marks the square with the current player and returns True. If one of the players already owns the square, or if not all lines exist to complete the square, returns False. """ # Declare global vars affected by function global _top_left_owner, _top_right_owner, _bottom_left_owner, \ _bottom_right_owner if sq == 'top_left' and _top_left_owner == None and _n_nw and _n_c and \ _w_c and _w_nw: _top_left_owner = _current_player return True elif sq == 'top_right' and _top_right_owner == None and _n_ne and _e_ne \ and _e_c and _n_c: _top_right_owner = _current_player return True elif sq == 'bottom_left' and _bottom_left_owner == None and _w_c and _s_c \ and _s_sw and _w_sw: _bottom_left_owner = _current_player return True elif sq == 'bottom_right' and _bottom_right_owner == None and _e_c and \ _e_se and _s_se and _s_c: _bottom_right_owner = _current_player return True else: return False # Ownership unchanged def _update_squares(): """() -> bool Attepts to update the owners of all the squares that a new line might affect. Returns True if one or more squares receives a new owner, otherwise False """ top_left = _update_square('top_left') top_right = _update_square('top_right') bottom_left = _update_square('bottom_left') bottom_right = _update_square('bottom_right') return top_left or top_right or bottom_left or bottom_right ############################################################################## ############################################################################## # NOTE: Functions that reveal or control the state of the current game. # These functions are meant to be accessed outside of this module #----------------------------------------------------------------------------- def add_line(line): """(str) -> bool Attempts to add a line between two dots. The parameter <line> must be one of 'North_Northeast', 'North_Northwest', 'East_Center', etc, (A string represnting a line on the game board) If the line is not present, adds the line and returns True. If the line is already present, no change to state of game board and returns False """ # Declare global vars the func may affect maintaining the game-state global _n_nw, _n_c, _n_ne, _s_c, _s_se, _s_sw, _e_c, _e_se, _e_ne, \ _w_c, _w_sw, _w_nw, _current_player line_added = False # Init unsuccessful by defaulr if line == 'North_Northwest' and not _n_nw: _n_nw = True line_added = True elif line == 'North_Center' and not _n_c: _n_c = True line_added = True elif line == 'North_Northeast' and not _n_ne: _n_ne = True line_added = True elif line == 'South_Center' and not _s_c: _s_c = True line_added = True elif line == 'South_Southeast' and not _s_se: _s_se = True line_added = True elif line == 'South_Southwest' and not _s_sw: _s_sw = True line_added = True elif line == 'East_Center' and not _e_c: _e_c = True line_added = True elif line == 'East_Southeast' and not _e_se: _e_se = True line_added = True elif line == 'East_Northeast' and not _e_ne: _e_ne = True line_added = True elif line == 'West_Northwest' and not _w_nw: _w_nw = True line_added = True elif line == 'West_Southwest' and not _w_sw: _w_sw = True line_added = True elif line == 'West_Center' and not _w_c: _w_c = True line_added = True # If line added succesfully, check whether it completes square if line_added and not _update_squares(): # Turn move to next player upoun a successful move if _current_player == 'X': _current_player = 'Y' else: _current_player = 'X' return line_added def square_owner(sq): """ (str) -> str or NoneType Checks who owns the given square <sq> <sq> must be one of the strings, 'top_left', 'top_right', 'bottom_right' or 'bottom_left' Returns the player who owns the given square, and None if no-one owns it """ if sq == 'top_left': return _top_left_owner elif sq == 'top_right': return _top_right_owner elif sq == 'bottom_left': return _bottom_left_owner elif sq == 'bottom_right': return _bottom_right_owner else: return None def check_line(line): """(str) -> bool Checks whether the line <line> exists. The parameter <line> must be one of 'North_Northeast', 'North_Northwest', 'East_Center', etc, (A string represnting a line on the game board) Returns True if the line exists on the game board, otherwise False if it doesn't exist yet """ if line == 'North_Northwest': return _n_nw elif line == 'North_Center': return _n_c elif line == 'North_Northeast': return _n_ne elif line == 'South_Center': return _s_c elif line == 'South_Southeast': return _s_se elif line == 'South_Southwest': return _s_sw elif line == 'East_Center': return _e_c elif line == 'East_Southeast': return _e_se elif line == 'East_Northeast': return _e_ne elif line == 'West_Northwest': return _w_nw elif line == 'West_Southwest': return _w_sw elif line == 'West_Center': return _w_c else: return False def winner(): # TODO: Fix Display """() -> str or NoneType Declares the game's winner, player X, player Y or a draw Returns 'X' or 'Y', or 'Draw' if the game board is full and
#!bin/env python import os from functools import partial import copy import numpy as np from numpy import sqrt, tanh from scipy import optimize import matplotlib.pyplot as plt __author__ = '<NAME>' __copyright__ = 'Copyright 2015' __license__ = 'MIT' __version__ = '0.95' __email__ = '<EMAIL>' __status__ = 'Development' DEBUG = False class Jet(): """Numerical analysis of a 2D, heated, turbulent free jet Literature: T. CEBECI, P. BRADSHAW "Physical and computational aspects of convective heat transfer" Springer 198 """ def __init__(self): """Summary""" self.Reynolds = 10000.0 self.Prandtl = 0.72 self.Prandtl_turb = 0.9 self.turbulent = False self.results = [] self.solver_message = None self.nx = 0 # centerline boundary condition for the energy equation (dp0=0) # switch between temperature or heat flux boundary type self.alfa0 = 0.0 self.alfa1 = 1.0 # plot scaling limits self.scale_min = 1.e10 self.scale_max = -1.e10 print('') print('**************************************************') print('**************************************************') print('********** 2D TURBULENT HEATED FREE JET **********') print('**************************************************') print('**************************************************') def set_Reynolds(self, Reynolds): self.Reynolds = Reynolds def set_Prandtl(self, Prandtl): self.Prandtl = Prandtl def set_Prandtl_turb(self, Prandtl_turb): self.Prandtl_turb = Prandtl_turb def set_FluidProperties(self, Reynolds, Prandtl, Prandtl_turb): self.set_Reynolds(Reynolds) self.set_Prandtl(Prandtl) self.set_Prandtl_turb(Prandtl_turb) def print_FluidAndFlowInformation(self): print(' ') print('***************************') print('***** FLOW PROPERTIES *****') print('***************************') print(' REYNOLDS = %s' % (self.Reynolds)) print(' PRANDTL = %s' % (self.Prandtl)) print(' PRANDTL turbulent = %s' % (self.Prandtl_turb)) if self.turbulent: print(' TURBULENCE = ON') else: print(' TURBULENCE = OFF') def mesh(self, gsimax=10, dgsi=0.01, etae=8, deta1=0.01, stretch=1.12): """Mesh generation for 2D rectangular transformed grid Args: gsimax (int, optional): Description dgsi (float, optional): Description etae (int, optional): Description deta1 (float, optional): Description stretch (float, optional): Description """ self.dgsi = dgsi self.etae = etae self.stretch = stretch # calculation of grid points from spacing parameters if stretch < 1.0001: etamax = etae / deta1 else: # equation (13.49, page 400) etamax = np.log(1.0 + (stretch - 1.0) * etae / deta1) / \ np.log(stretch) self.etamax = int(etamax) self.gsimax = gsimax + 1 # initialize arrays # done here, as etamax first time available here self.f = np.zeros([self.etamax, 2]) self.u = np.zeros([self.etamax, 2]) self.v = np.zeros([self.etamax, 2]) self.g = np.zeros([self.etamax, 2]) self.p = np.zeros([self.etamax, 2]) self.b = np.zeros([self.etamax, 2]) self.e = np.zeros([self.etamax, 2]) # initialize grid arrays self.gsi = np.zeros([self.gsimax + 1]) self.eta = np.zeros([self.etamax]) self.deta = np.zeros([self.etamax - 1]) self.a = np.zeros([self.etamax]) self.gsi[0] = 1.0 self.deta[0] = deta1 for i in range(1, self.gsimax + 1): self.gsi[i] = self.gsi[i - 1] + dgsi for j in range(1, self.etamax - 1): self.deta[j] = stretch * self.deta[j - 1] for j in range(1, self.etamax): self.a[j] = 0.5 * self.deta[j - 1] self.eta[j] = self.eta[j - 1] + self.deta[j - 1] print(' ') print('***************************') print('***** MESH PROPERTIES *****') print('***************************') print(' GSI sstart: ', self.gsi[0]) print(' GSI spacing: ', dgsi) print(' ETA spacing (initial): ', deta1) print(' ETA growth rate: ', stretch) print(' ETA boundary (ETAE given): ', etae) print(' ETA boundary (ETAE calculated): ', self.eta[-1]) print(' Number of grid points in GSI direction: ', self.gsimax) print(' Number of grid points in ETA direction: ', self.etamax) def boundary_conditions(self): """Initial velocity and temperature profiles. Equation (14.31), page 445 """ gsi0 = self.gsi[self.nx] beta = 27.855 etac = 1.0 term = beta * 3.0 * gsi0**(2. / 3.) / sqrt(self.Reynolds) for j in range(self.etamax): tanf = tanh(term * (self.eta[j] - etac)) self.u[j, 0] = 3.0 / 2.0 * gsi0**(1. / 3.) * (1.0 - tanf) self.v[j, 0] = - term * 3.0 / 2.0 * gsi0**(1. / 3.) * \ (1.0 - tanf**2) self.g[j, 0] = self.u[j, 0] / 3.0 * gsi0**(1. / 3.) self.p[j, 0] = self.v[j, 0] / 3.0 * gsi0**(1. / 3.) self.b[j, 0] = 1.0 self.e[j, 0] = 1.0 / self.Prandtl self.f[j, 0] = self.f[j - 1, 0] + self.a[j] * \ (self.u[j, 0] + self.u[j - 1, 0]) # boundary conditions at jet center (symmetry) self.f[0, 0] = 0.0 self.v[0, 0] = 0.0 self.p[0, 0] = 0.0 # boundary conditions at jet boundary (ambient) self.u[-1, 0] = 0.0 self.g[-1, 0] = 0.0 self.turbulence() # at first gsi stage make turbulence equal to second step self.b[:, 0] = copy.copy(self.b[:, 1]) self.e[:, 0] = copy.copy(self.e[:, 1]) # smooth initial profiles in order to avoid non-smooth # places, e.g. at jet center for derivatives iter = 5 for k in range(iter): # self.f[1:-1] = 0.5 * (self.f[2:] + self.f[0:-2]) # self.u[1:-1] = 0.5 * (self.u[2:] + self.u[0:-2]) self.v[1:-1] = 0.5 * (self.v[2:] + self.v[0:-2]) # self.g[1:-1] = 0.5 * (self.g[2:] + self.g[0:-2]) self.p[1:-1] = 0.5 * (self.p[2:] + self.p[0:-2]) def turbulence(self): umaxh = 0.5 * self.u[0, 0] # Find slice (i.e. index range) where u less than umaxh index = np.where(self.u[:, 0] <= umaxh) if index: # index of u where u first time is less than umaxh j = index[0][0] # etab = self.eta[j - 1] + (self.eta[j] - self.eta[j - 1]) / \ (self.u[j, 0] - self.u[j - 1, 0]) * (umaxh - self.u[j - 1, 0]) else: etab = self.eta[self.etamax] if self.turbulent: # compute turbulence viscosity eddy_viscosity = 0.037 * etab * self.u[0, 0] * \ np.sqrt(self.Reynolds) * self.gsi[self.nx]**(1. / 3.) else: # zero eddy viscosity for laminar flow eddy_viscosity = 0.0 # under-relaxation of eddy_viscosity self.urel_visc = np.tanh(self.gsi[self.nx] - 0.4) eddy_viscosity = eddy_viscosity * self.urel_visc print(' Eddy viscosity under-relaxation = {:5.3f}'. format(self.urel_visc)) for j in range(self.etamax): self.b[j, 1] = 1.0 + eddy_viscosity self.e[j, 1] = 1.0 / self.Prandtl + \ eddy_viscosity / self.Prandtl_turb def solver(self, solver_type, iterations): # knowns f_o = copy.copy(self.f[:, 0]) u_o = copy.copy(self.u[:, 0]) v_o = copy.copy(self.v[:, 0]) g_o = copy.copy(self.g[:, 0]) p_o = copy.copy(self.p[:, 0]) self.turbulence() # extra parameters for 'function' # are later wrapped with partial b = copy.copy(self.b[:, 1]) e = copy.copy(self.e[:, 1]) b_o = copy.copy(self.b[:, 0]) e_o = copy.copy(self.e[:, 0]) nx = copy.copy(self.nx) gsi = copy.copy(self.gsi) deta = copy.copy(self.deta) etamax = copy.copy(self.etamax) # def F(unknowns, F_args=[nx, gsi, deta, etamax, b, e, b_o, e_o]): """Summary Args: unknowns (np.array): f, u, v, g, p Returns: TYPE: Description """ # unknowns if DEBUG: print('unknowns', unknowns) print('nx', nx) print('gsi', gsi) # (f, u, v, g, p) = unknowns f = unknowns[0: etamax] u = unknowns[etamax:2 * etamax] v = unknowns[2 * etamax:3 * etamax] g = unknowns[3 * etamax:4 * etamax] p = unknowns[4 * etamax:5 * etamax] alpha = 3.0 / 2.0 * (gsi[nx] + gsi[nx - 1]) / \ (gsi[nx] - gsi[nx - 1]) eq1 = np.zeros_like(f) eq2 = np.zeros_like(f) eq3 = np.zeros_like(f) eq4 = np.zeros_like(f) eq5 = np.zeros_like(f) # boundary conditions at jet center (symmetry) f[0] = 0.0 v[0] = 0.0 p[0] = 0.0 f_o[0] = 0.0 v_o[0] = 0.0 p_o[0] = 0.0 # boundary conditions at jet outer boundary (ambient) u[-1] = 0.0 g[-1] = 0.0 u_o[-1] = 0.0 g_o[-1] = 0.0 # array slicing for index j # [1:] means index j # [:-1] means index j-1 # ODE: f' = u eq1[1:] = 1.0 / deta * (f[1:] - f[:-1]) - 0.5 * (u[1:] + u[:-1]) # ODE: u' = v eq2[1:] = 1.0 / deta * (u[1:] - u[:-1]) - 0.5 * (v[1:] + v[:-1]) # ODE: g' = p eq3[1:] = 1.0 / deta * (g[1:] - g[:-1]) - 0.5 * (p[1:] + p[:-1]) # PDE: Momentum mom1 = 1.0 / deta * (b[1:] * v[1:] - b[:-1] * v[:-1]) mom2 = (1.0 - alpha) * 0.5 * (u[1:]**2 + u[:-1]**2) mom3 = (1.0 + alpha) * 0.5 * (f[1:] * v[1:] + f[:-1] * v[:-1]) mom4 = alpha * 0.25 * ((v_o[1:] + v_o[:-1]) * (f[1:] + f[:-1]) - (v[1:] + v[:-1]) * (f_o[1:] + f_o[:-1])) mom5 = 1.0 / deta * (b_o[1:] * v_o[1:] - b_o[:-1] * v_o[:-1]) mom6 = (1.0 + alpha) * 0.5 * (u_o[1:]**2 + u_o[:-1]**2) mom7 = (1.0 - alpha) * 0.5 * (f_o[1:] * v_o[1:] + f_o[:-1] * v_o[:-1]) eq4[1:] = mom1 + mom2 + mom3 + mom4 + mom5 + mom6 + mom7 # PDE: Energy ene1 = 1.0 / deta * (e[1:] * p[1:] - e[:-1]
# -*- coding: utf-8 -*- """ Created on 29/03/2020 @author: Mahdad THIS IS THE CLASS FOR "MACHINE LEARNING & DEPRESSION PROJECT." The class is capable of extracting relevant features, applying various machine- learning algorithms and finally applying Randomized grid search to tune hyper- parameters of different classifiers. After each method of the class, there is a short description, introducing the relevant input/outputs. """ #%% Importing libs import numpy as np import pandas as pd import pywt from scipy.signal import butter, lfilter, periodogram, spectrogram, welch from sklearn.ensemble import RandomForestClassifier import heapq from scipy.signal import argrelextrema from sklearn.model_selection import cross_val_score from sklearn.metrics import confusion_matrix import seaborn as sb import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from scipy.stats import kurtosis, skew from entropy.entropy import spectral_entropy from scipy.fftpack import fft import h5py import time class ML_Depression(): def __init__(self, filename, channel, fs, T): self.filename = filename self.channel = channel self.fs = fs self.T = T def FeatureExtraction(self): ''' ~~~~~~################## INSTRUCTION #################~~~~~~~~ ---- THIS IS A FUNCTION TO EXTRACT FEATURES AND THEN USE THEM FOR ANY KIND OF SUPERVISED MACHINE LEARNING ALGORITHM. INPUTS: 1) filename : full directory of train-test split (e.g. .h5 file saved via Prepare_for_CNN.py) 2) channel : channel of interest, e.g. 'fp2-M1' OUTPUTS: 1) X : Concatenation of all featureset after random permutation. 2) y : Relevant labels of "X". ''' # Loading data section # Load data tic = time.time() fname = self.filename # choose channel to extract features from ch = self.channel fs = self.fs #Hz T = self.T #sec # Split train and test with h5py.File(fname, 'r') as rf: xtest = rf['.']['x_test_' + ch].value xtrain = rf['.']['x_train_' + ch].value ytest = rf['.']['y_test_' + ch].value ytrain = rf['.']['y_train_' + ch].value print('train and test data loaded in : {} secs'.format(time.time()-tic)) # Flatten data for filter and normalization X_train = np.reshape(xtrain, (np.shape(xtrain)[0] * np.shape(xtrain)[1] ,1)) X_test = np.reshape(xtest, (np.shape(xtest)[0] * np.shape(xtest)[1] ,1)) #%% Filtering section ## Defining preprocessing function ## def butter_bandpass_filter(data, lowcut, highcut, fs, order = 2): nyq = 0.5 * fs low = lowcut /nyq high = highcut/nyq b, a = butter(order, [low, high], btype='band') #print(b,a) y = lfilter(b, a, data) return y # Apply filter X_train = butter_bandpass_filter(data=X_train, lowcut=.3, highcut=20, fs=fs, order=2) X_test = butter_bandpass_filter(data=X_test , lowcut=.3, highcut=20, fs=fs, order=2) #%% Normalization section - DEACTIVATED #sc = StandardScaler() #X_train = sc.fit_transform(X_train) #X_test = sc.transform(X_test) #%% Reshaping data per epoch X_train = np.reshape(X_train, (int(len(X_train) / (fs*T)), fs*T)) X_test = np.reshape(X_test, (int(len(X_test) / (fs*T)), fs*T)) X = np.concatenate((X_train, X_test)) Y = np.concatenate((ytrain, ytest)) #%% Feature Extraction section # Defining EEG bands: eeg_bands = {'Delta' : (0.5, 4), 'Theta' : (4 , 8), 'Alpha' : (8 , 12), 'Beta' : (12 , 20), 'Sigma' : (12 , 16), 'Sigma_slow': (12 , 14), 'Sigma_fast': (14 , 16)} # Initializing variables of interest eeg_band_fft = dict() freq_ix = dict() Features = np.empty((0, 42)) # Settings of peridogram Window = 'hann' # zero-padding added with respect to (Nfft=2^(nextpow2(len(window)))) Nfft = 2 ** 15 # Defining freq. resoultion fm, _ = periodogram(x = X[0,:], fs = fs, nfft = Nfft , window = Window) tic = time.time() # Finding the index of different freq bands with respect to "fm" # for band in eeg_bands: freq_ix[band] = np.where((fm >= eeg_bands[band][0]) & (fm <= eeg_bands[band][1]))[0] print('Feature extraction started ... Please wait ...') # Defining for loop to extract features per epoch for i in np.arange(len(X)): data = X[i,:] # Compute the "total" power inside the investigational window _ , pxx = periodogram(x = data, fs = fs, nfft = Nfft , window = Window) # Initialization for wavelet cA_values = [] cD_values = [] cA_mean = [] cA_std = [] cA_Energy = [] cD_mean = [] cD_std = [] cD_Energy = [] Entropy_D = [] Entropy_A = [] first_diff = np.zeros(len(data)-1) '''Power in differnt freq ranges ''' # Total pow is defined form 0.5 - 20 Hz pow_total = np.sum(pxx[np.arange(freq_ix['Delta'][0], freq_ix['Beta'][-1]+1)]) Pow_Delta = np.sum(pxx[freq_ix['Delta']]) / pow_total Pow_Theta = np.sum(pxx[freq_ix['Theta']]) / pow_total Pow_Alpha = np.sum(pxx[freq_ix['Alpha']]) / pow_total Pow_Beta = np.sum(pxx[freq_ix['Beta']]) / pow_total Pow_Sigma = np.sum(pxx[freq_ix['Sigma']]) / pow_total Pow_Sigma_slow = np.sum(pxx[freq_ix['Sigma_slow']]) / pow_total Pow_Sigma_fast = np.sum(pxx[freq_ix['Sigma_fast']]) / pow_total '''Apply Welch to see the dominant Max power in each freq band''' ff, Psd = welch(x = data, fs = fs, window = 'hann', nperseg= 512, nfft = Nfft) Pow_max_Total = np.max(Psd[np.arange(freq_ix['Delta'][0], freq_ix['Beta'][-1]+1)]) Pow_max_Delta = np.max(Psd[freq_ix['Delta']]) Pow_max_Theta = np.max(Psd[freq_ix['Theta']]) Pow_max_Alpha = np.max(Psd[freq_ix['Alpha']]) Pow_max_Beta = np.max(Psd[freq_ix['Beta']]) Pow_max_Sigma = np.max(Psd[freq_ix['Sigma']]) Pow_max_Sigma_slow = np.max(Psd[freq_ix['Sigma_slow']]) Pow_max_Sigma_fast = np.max(Psd[freq_ix['Sigma_fast']]) ''' Spectral Entropy ''' Entropy_Welch = spectral_entropy(x = data, sf=fs, method='welch', nperseg = 512) Entropy_fft = spectral_entropy(x = data, sf=fs, method='fft') ''' Wavelet Decomposition ''' cA,cD=pywt.dwt(data,'coif1') cA_values.append(cA) cD_values.append(cD) cA_mean.append(np.mean(cA_values)) cA_std.append(np.std(cA_values)) cA_Energy.append(np.sum(np.square(cA_values))) cD_mean.append(np.mean(cD_values)) cD_std.append(np.std(cD_values)) cD_Energy.append(np.sum(np.square(cD_values))) Entropy_D.append(np.sum(np.square(cD_values) * np.log(np.square(cD_values)))) Entropy_A.append(np.sum(np.square(cA_values) * np.log(np.square(cA_values)))) ''' Hjorth Parameters ''' hjorth_activity = np.var(data) diff_input = np.diff(data) diff_diffinput = np.diff(diff_input) hjorth_mobility = np.sqrt(np.var(diff_input)/hjorth_activity) hjorth_diffmobility = np.sqrt(np.var(diff_diffinput)/np.var(diff_input)) hjorth_complexity = hjorth_diffmobility / hjorth_mobility ''' Statisctical features''' Kurt = kurtosis(data, fisher = False) Skewness = skew(data) Mean = np.mean(data) Median = np.median(data) Std = np.std(data) ''' Coefficient of variation ''' coeff_var = Std / Mean ''' First and second difference mean and max ''' sum1 = 0.0 sum2 = 0.0 Max1 = 0.0 Max2 = 0.0 for j in range(len(data)-1): sum1 += abs(data[j+1]-data[j]) first_diff[j] = abs(data[j+1]-data[j]) if first_diff[j] > Max1: Max1 = first_diff[j] # fi for j in range(len(data)-2): sum2 += abs(first_diff[j+1]-first_diff[j]) if abs(first_diff[j+1]-first_diff[j]) > Max2 : Max2 = first_diff[j+1]-first_diff[j] diff_mean1 = sum1 / (len(data)-1) diff_mean2 = sum2 / (len(data)-2) diff_max1 = Max1 diff_max2 = Max2 ''' Variance and Mean of Vertex to Vertex Slope ''' t_max = argrelextrema(data, np.greater)[0] amp_max = data[t_max] t_min = argrelextrema(data, np.less)[0] amp_min = data[t_min] tt = np.concatenate((t_max,t_min),axis=0) if len(tt)>0: tt.sort() #sort on the basis of time h=0 amp = np.zeros(len(tt)) res = np.zeros(len(tt)-1) for l in range(len(tt)): amp[l] = data[tt[l]] out = np.zeros(len(amp)-1) for j in range(len(amp)-1): out[j] = amp[j+1]-amp[j] amp_diff = out out = np.zeros(len(tt)-1) for j in range(len(tt)-1): out[j] = tt[j+1]-tt[j] tt_diff = out for q in range(len(amp_diff)): res[q] = amp_diff[q]/tt_diff[q] #calculating slope slope_mean = np.mean(res) slope_var = np.var(res) else: slope_var, slope_mean = 0, 0 ''' Spectral mean ''' Spectral_mean = 1 / (freq_ix['Beta'][-1] - freq_ix['Delta'][0]) * (Pow_Delta + Pow_Theta + Pow_Alpha + Pow_Beta + Pow_Sigma + Pow_Sigma_slow + Pow_Sigma_fast) ''' Wrapping up featureset ''' feat = [pow_total, Pow_Delta, Pow_Theta, Pow_Alpha, Pow_Beta, Pow_Sigma, cA_mean[0], cA_std[0], cA_Energy[0], cD_Energy[0], cD_mean[0], cD_std[0], Entropy_D[0], Entropy_A[0], Entropy_Welch, Entropy_fft, Pow_Sigma_slow, Pow_Sigma_fast, Kurt, Skewness, Mean, Median, Spectral_mean, hjorth_activity, hjorth_mobility, hjorth_complexity, Std, coeff_var, diff_mean1, diff_mean2, diff_max1, diff_max2, slope_mean, slope_var, Pow_max_Total, Pow_max_Delta, Pow_max_Theta, Pow_max_Alpha, Pow_max_Beta, Pow_max_Sigma, Pow_max_Sigma_slow, Pow_max_Sigma_fast] Features = np.row_stack((Features,feat)) #%% Replace the NaN values of features with the mean of each feature column print('Features were successfully extracted in: {} secs'.format(time.time()-tic)) aa, bb = np.where(np.isnan(Features)) for j in np.arange(int(len(aa))): Features[aa[j],bb[j]] = np.nanmean(Features[:,bb[j]]) print('the NaN values were successfully replaced with the mean of related feature.') #%% Normalizing features Feat_train = Features[:int(len(X_train)),:] Feat_test = Features[int(len(X_train)):,:] sc = StandardScaler() Feat_train = sc.fit_transform(Feat_train) Feat_test = sc.transform(Feat_test) #%% Shuffle train and test data with rand perumtation rp_train = np.random.permutation(len(Feat_train)) rp_test = np.random.permutation(len(Feat_test)) Feat_train_rp = Feat_train[rp_train,:] Feat_test_rp = Feat_test[rp_test,:] y_train_rp = ytrain[rp_train,1] y_test_rp = ytest[rp_test,1] # Concatenation for k-fold cross validation X = np.row_stack((Feat_train_rp, Feat_test_rp)) y = np.concatenate((y_train_rp, y_test_rp)) return X, y, Feat_train_rp, Feat_test_rp, y_train_rp, y_test_rp ######################## DEFINING SUPERVISED CLASSIFIERs ###################### #%% Random Forest def RandomForest_Modelling(self, X, y, n_estimators = 500, cv = 10): tic = time.time() classifier_RF = RandomForestClassifier(n_estimators = n_estimators) accuracies_RF = cross_val_score(estimator = classifier_RF, X = X, y = y, cv = cv) Acc_cv10_RF = accuracies_RF.mean() std_cv10_RF = accuracies_RF.std() print(f'Cross validation finished: Mean Accuracy
<reponame>heavyairship/LambdaCalc<gh_stars>1-10 ########################################################################## # Parsing/reduction for the Lambda Calculus # # # Syntax for valid Lambda terms: # # x Variable: A character or string that represents an atomic value. # # (Lx.M) Abstraction: A function definition that binds the parameter # variable x in the body M, which is a Lambda term. # # (M N) Application: Application of a function M to an argument N, both # of which are lambda terms. # # Parentheses may be omitted, in which case the following rules apply: # the body of an Abstraction extends as far right as possible; and # Applications are left-associative. ########################################################################## # Abstract base class for a Lambda Calculus Expression class LambdaExpr(object): def red_bn(self, memoize): # Reduction by name # See: https://www.itu.dk/~sestoft/papers/sestoft-lamreduce.pdf pass def red_no(self, memoize): # Reduction by normal order # See: https://www.itu.dk/~sestoft/papers/sestoft-lamreduce.pdf pass def red(self, memoize): # Default reduction pass def app(self, argument): pass def sub(self, var, expr): pass def free(self): pass def canon(self): pass def __str__(self): pass ########################################################################## # Lambda Calculus Variable class Var(LambdaExpr): def __init__(self, var): self.var = var def red_bn(self, memoize): return self def red_no(self, memoize): return self def red(self, memoize): return self.red_no(memoize) def app(self, argument): if not isinstance(argument, LambdaExpr): raise TypeError return App(self, argument) def sub(self, var, expr): if not isinstance(var, str) or not isinstance(expr, LambdaExpr): raise TypeError return self if self.var != var else expr def free(self): return set([self.var]) def canon(self): return self if self.var[0] == canonPre else Var(fresh(canonPre)) def __str__(self): return self.var ########################################################################## # Lambda Calculus Abstraction class Abs(LambdaExpr): def __init__(self, param, body): self.param = param self.body = body def red_bn(self, memoize): return self def red_no(self, memoize): if memoize: can = str(canon(self)) if can in redMap: return can[redMap] out = Abs(self.param, self.body.red_no(memoize)) if memoize: redMap[can] = out return out def red(self, memoize): return self.red_no(memoize) def app(self, argument): if not isinstance(argument, LambdaExpr): raise TypeError return self.body.sub(self.param, argument) def sub(self, var, expr): if not isinstance(var, str) or not isinstance(expr, LambdaExpr): raise TypeError if self.param == var: return self if self.param in expr.free(): f = fresh() selfFree = self.free() while (f in selfFree) or (f == self.param): f = fresh() return Abs(f, self.body.sub(self.param, Var(f))).sub(var, expr) return Abs(self.param, self.body.sub(var, expr)) def free(self): return self.body.free() - set([self.param]) def canon(self): f = fresh(canonPre) return Abs(f, self.body.sub(self.param, Var(f)).canon()) def __str__(self): return "(L%s.%s)" % (self.param, str(self.body)) ########################################################################## # Lambda Calculus Application class App(LambdaExpr): def __init__(self, first, second): self.first = first self.second = second def red_bn(self, memoize): if memoize: can = str(canon(self)) if can in redMap: return redMap[can] first = self.first.red_bn(memoize) if isinstance(first, Abs): out = first.app(self.second).red_bn(memoize) else: out = App(first, self.second) if memoize: redMap[can] = out return out def red_no(self, memoize): if memoize: can = str(canon(self)) if can in redMap: return redMap[can] first = self.first.red_bn(memoize) if isinstance(first, Abs): out = first.app(self.second).red_no(memoize) else: out = App(first.red_no(memoize), self.second.red_no(memoize)) if memoize: redMap[can] = out return out def red(self, memoize): return self.red_no(memoize) def app(self, argument): if not isinstance(argument, LambdaExpr): raise TypeError return App(self, argument) def sub(self, var, expr): if not isinstance(var, str) or not isinstance(expr, LambdaExpr): raise TypeError return App(self.first.sub(var, expr), self.second.sub(var, expr)) def free(self): return self.first.free().union(self.second.free()) def canon(self): return App(self.first.canon(), self.second.canon()) def __str__(self): return "(%s %s)" % (str(self.first), str(self.second)) # Used to memoize reductions for better time efficiency redMap = {} counter = -1 canonPre = "#" def fresh(pre="@"): global counter counter += 1 return "%s%d" % (pre, counter) def resetFresh(): global counter counter = -1 def canon(expr): if not isinstance(expr, LambdaExpr): raise TypeError resetFresh() can = expr.canon() resetFresh() return can def reduce(expr, memoize=False): global redMap if not isinstance(expr, LambdaExpr): raise TypeError resetFresh() redMap = {} out = expr.red(memoize) resetFresh() redMap = {} return out ########################################################################## # Parsing def whitespace(c): return c in ['\t', '\r', '\n', ' '] def separator(c): return c in ['=', ';', '(', ')', '.', 'L'] def tokenize(data): tokens = [] var = '' for idx, c in enumerate(data): if whitespace(c): if var != '': tokens.append(var) var = '' elif separator(c): if var != '': tokens.append(var) var = '' tokens.append(c) else: var += c if var != '': tokens.append(var) var = '' return tokens def parseTerm(t, bindings): # Terms are integers, bound identifiers, and variables if not isinstance(t, str): raise TypeError("expected to parse term from string") if numeric(t): return encodeI(int(t)) elif t in bindings: return bindings[t] elif validIden(t): return Var(t) else: raise ValueError("invalid identifier `%s`" % t) def alphabetic(c): return ('a' <= c and c <= 'z') or ('A' <= c and c <= 'Z') def symbolic(c): return c in ["'", '|', '&', '^', '!', '~', '*', '+', '/', '-', '%', '$', '@', '<', '>'] def numeric(iden): for c in iden: if c < '0' or c > '9': return False return True def validIden(iden): if numeric(iden): return False if iden == 'let': return False for c in iden: if c == 'L': return False if not symbolic(c) and not alphabetic(c) and not numeric(c): return False return True def parseBindings(tokens, bindings): idx = 0 while idx < len(tokens): t = tokens[idx] if t == "let": # Parse `let` keyword idx += 1 # Parse identifier iden = tokens[idx] if not validIden(iden): raise ValueError("identifier `%s` is not valid" % iden) idx += 1 # Parse `=` assignment operator assn = tokens[idx] if not assn == "=": raise ValueError("expected assignment operator `=` not `%s`" % assn) idx += 1 # Find beginning/end for expression begin = idx while idx < len(tokens) and tokens[idx] != ';': idx += 1 if idx >= len(tokens): raise ValueError("expected token `;`") end = idx # Parse expression and add to bindings expr = parseTokens(tokens[begin:end], bindings) if expr is None: raise ValueError("empty expressions not allowed"); bindings[iden] = expr # Parse `;` terminator idx += 1 else: idx += 1 return bindings def removeLetBindings(tokens): out = [] idx = 0 while idx < len(tokens): t = tokens[idx] if t == 'let': while idx < len(tokens) and tokens[idx] != ';': idx += 1 if idx >= len(tokens): raise ValueError("expected token `;`") else: out.append(t) idx += 1 return out def parseTokens(tokens, bindings): # Holds parsed expressions stack = [] while len(tokens) != 0: if tokens[0] == '(': # Parse expression in `( )` # Parse opening `(` temp = [] temp.append(tokens.pop(0)) # Parse until matching `)` left = 1 right = 0 while left != right and len(tokens) > 0: if tokens[0] == '(': left += 1 if tokens[0] == ')': right += 1 temp.append(tokens.pop(0)) if left != right: raise ValueError("could not match parentheses") # Recurse on contents between `( )`, leaving off the parentheses stack.append(parseTokens(temp[1:-1], bindings)) elif tokens[0] == 'L': # Parse abstraction expression, e.g. Lx.M # Parse `L` tokens.pop(0) # Parse param if len(tokens) == 0: raise ValueError("missing param after `L`") param = tokens.pop(0) if not validIden(param): raise ValueError("`%s` is an invalid abstraction param" % param) # Parse `.` if len(tokens) == 0 or tokens.pop(0) != '.': raise ValueError("expected `.` after param") # Parse body temp = [] while len(tokens) != 0: temp.append(tokens.pop(0)) # Recurse on body stack.append(Abs(param, parseTokens(temp, bindings))) else: # Parse a term expression (base case) stack.append(parseTerm(tokens.pop(0), bindings)) while len(stack) > 1: # Parse applications in a left-associative manner first = stack.pop(0) second = stack.pop(0) stack.insert(0, App(first, second)) # Return the parsed expression if it exsits. If there is no expression, # that means the input was empty or entirely let-bindings. return stack[0] if len(stack) > 0 else None def parse(data): global bindings loadstdlib() tokens = tokenize(data) bindings.update(parseBindings(tokens, bindings)) return parseTokens(removeLetBindings(tokens), bindings) ########################################################################## # Load the standard library import os stdlibLoaded = False bindings = {} def loadstdlib(): global bindings global stdlibLoaded if stdlibLoaded: return stdlibLoaded = True prefix = os.path.join(os.path.dirname(os.path.realpath(__file__)), "stdlib") # This ordering is important, e.g. since pair.l depends on logic.l # FixMe: implement some kind of dependency system. filenames = ['fix.l', 'logic.l', 'pair.l', 'control.l', 'list.l', 'arithmetic.l'] for fname in filenames: with open(os.path.join(prefix, fname)) as f: bindings.update(parseBindings(tokenize(f.read()), bindings)) ########################################################################## # Church Encoding def decode(l): # The Church encodings for 0 and False are alpha-equivalent, # so we need to use the hack below to force decoding Lf.Lx.x # as 0 rather than False. if str(l) == "(Lf.(Lx.x))": return 0
import threading from numpy.core.fromnumeric import std import py_trees from py_trees.common import Status import py_trees_ros import rospy import numpy as np import subprocess import os import signal from threading import Thread import sys import time try: from queue import Queue,LifoQueue, Empty except ImportError: from Queue import Queue,LifoQueue, Empty # python 2.x log_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),"..","..","logs") class RunRos(py_trees.behaviour.Behaviour): """ Runs and returns RUNNING status for as long as given process is running, will return FAILURE whenever it halts, and if killed via blackboard kill key will return SUCCESS and won't reset untill this key is cleared (i.e. will keep returning SUCCESS ). Optionally can serve as short process launcher """ def __init__(self,name,blackboard_alive_key,blackboard_kill_trigger_key,launch_file=None,node_file=None,package="dr_phil",args=[],success_on_non_error_exit=False): """ Args: name: name of the behaviour blackboard_alive_key: the key which will be set as long as the process is running blackboard_kill_trigger_key: the key which if set will cause the node to kill the process and keep returning SUCCESS as long as it's set (on the next tick of this node) launch_file: the full filename of the launchfile package: the package containing the launch file (DEFAULT: "dr_phil") success_on_non_error_exit: will not return FAILURE if process exits with successfull return code (i.e. completes), use for running single-use launchfiles/nodes """ super().__init__(name=name) self.package = package self.launch_file = launch_file self.node_file = node_file self.blackboard = py_trees.Blackboard() self.alive_key = blackboard_alive_key self.kill_key = blackboard_kill_trigger_key self.success_on_non_error_exit = success_on_non_error_exit self.args = args self.process = None self.last_success = False self.stdout_queue = None self.stderr_queue = None def initialise(self): # if we previously succeeded, i.e. either: # 1) another node killed us on purpose # 2) we run a single-use node/launchfile to completion if self.last_success: self.feedback_message = "completed" if self.blackboard.get(self.kill_key) is None: self.last_success = False self.feedback_message = "re-starting process" else: self.feedback_message += " , kill key set, not-starting new processes" else: # if we were just started, or previously failed self.feedback_message = "starting process" # TODO: check this is not redundant cosnidering terminate() calls it too # AFAIK terminate will trigger a kill before each initialization anyway self.kill_subprocess() def update(self): # if we were killed successfully last time # keep returning SUCCESS if self.last_success: return py_trees.Status.SUCCESS # check if there is already a subprocess running, i.e. if we started it # if already running, check on it untill watch time is over if self.process is not None: self.feedback_message= "running process" # check on the process ok = self.is_subprocess_ok() # if process is still running successfully if ok == 0: # check kill trigger if self.blackboard.get(self.kill_key) is not None: # kill self.logger.debug("process ended stdout dump: "+self.get_last_n_lines(self.stdout_queue,50)) self.kill_subprocess() self.last_success = True return py_trees.Status.SUCCESS return py_trees.Status.RUNNING # if process died when not expected elif ok == 2 or (ok == 1 and not self.success_on_non_error_exit): self.logger.error("stderr dump: "+self.get_last_n_lines(self.stderr_queue,50)) self.logger.error("stdout dump: "+self.get_last_n_lines(self.stdout_queue,50)) return py_trees.Status.FAILURE # if process died but we expected it else: self.logger.debug("process ended stdout dump: "+self.get_last_n_lines(self.stdout_queue,50)) self.last_success = True return py_trees.Status.SUCCESS else: # start a subprocess self.start_subprocess() return py_trees.Status.RUNNING def terminate(self,newState): # before we enter each initialize or after we are pre-empted # we make sure to not leave hanging processes self.kill_subprocess() def get_last_n_lines(self,queue,n): if queue is None: return l = "" for i in range(n): try: line = self.stdout_queue.get_nowait() # or q.get(timeout=.1) except Empty: pass # do nothing else: # got line l += "\n" + str(line) return l def kill_subprocess(self): """ kills subprocess started if it was started, otherwise does nothing """ # if it exists kill it and clear the blackboard if self.process is not None: try: os.killpg(os.getpgid(self.process.pid), signal.SIGTERM) except Exception as e: print("COULD NOT KILL, {0}".format(self.process)) raise e self.blackboard.set(self.alive_key,None) def start_subprocess(self): file = self.launch_file if self.node_file is None else self.node_file main_cmd = "roslaunch" if self.node_file is None else "rosrun" arg = " " for k in self.args: arg += "{0} ".format(k) command = "{0} {1} {2} {3}".format( main_cmd, self.package, file, arg) self.feedback_message = command ON_POSIX = 'posix' in sys.builtin_module_names # log = open(os.path.join(log_dir,"{0}.log".format(self.name)),"w") # log.truncate(0) launch_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, preexec_fn=os.setsid, close_fds=ON_POSIX, # bufsize=1, # universal_newlines=True ) # make sure not to overflow the output, i learned this the hard way # subprocess will freeze if you do # want to have a nonblocking way of reading output, start a separate thread for each output channel # read continously and store in non blocking to read structure shared with main program self.stdout_queue = LifoQueue() self.stderr_queue = LifoQueue() self.launch_log_thread(launch_process.stdout,self.stdout_queue) self.launch_log_thread(launch_process.stderr,self.stderr_queue) self.process = launch_process self.blackboard.set(self.alive_key,True) def subprocess_store_output(self,out,queue): """ will read the data from the out - io source and put it on the queue, WILL BLOCK the thread """ while True: try: for line in out: queue.put(line) except: # locked, just wait print("out is locked") time.sleep(5) pass def launch_log_thread(self,out,queue): """ launches a new thread for storing output for the given io source into the given queue """ thread = Thread(target=self.subprocess_store_output, args=(out,queue)) thread.daemon = True thread.start() return thread def is_subprocess_ok(self): """ returns 0 if subprocess alive, 1 if terminated without error and 2 if terminated with error. Updates state accordingly """ state = self.process.poll() if state is None: # ok return 0 elif state == 0: # terminated without error self.feedback_message = "process exit with return code 0" self.process = None self.blackboard.set(self.alive_key,None) return 1 else: # terminated with error (out,err) = self.process.communicate() self.feedback_message = "process terminated" self.logger.warning("process terminated with sig: {0}".format(-state)) self.logger.warning("stderr: {0}".format(err)) self.logger.warning("stdout: {0}".format(out)) self.process = None self.blackboard.set(self.alive_key,None) return 2 class PublishTopic(py_trees.behaviour.Behaviour): """ a behaviour which publishes a certain message and returning RUNNING on success. Can be set to return success on publish""" def __init__(self,name,msg,msg_type,topic,queue_size=1,success_on_publish=False,success_after_n_publishes=None): """ Args: name: the name of the behaviour msg_type: the type of message to be published topic: the topic on which to publish the message queue_size: the publisher queue size success_on_publish: when true, will return SUCCESS after publishing each time success_after_n_publishes: when set to any integer, will return success after publishing n times without failure """ super().__init__(name=name) self.msg = msg self.publisher = rospy.Publisher(topic,msg_type,queue_size=queue_size) self.success_on_publish = success_on_publish self.n_target = -1 if success_after_n_publishes is None else success_after_n_publishes def initialise(self): pass def update(self): self.feedback_message = "Waiting for data" try: self.feedback_message = "Published" self.publisher.publish(self.msg) except: self.feedback_message = "Publisher failure" return py_trees.common.Status.FAILURE if self.success_on_publish or self.n_target >= 0: self.n_target -= 1 if self.n_target > 0: return py_trees.common.Status.RUNNING else: return py_trees.common.Status.SUCCESS else: return py_trees.common.Status.RUNNING class MessageChanged(py_trees_ros.subscribers.Handler): """ Listens to topic and returns running before receiving 2 messages, which are then compared for changes If they have changed SUCCESS is returned, and otherwise FAILURE """ def __init__(self, name, topic_name, topic_type,compare_method=None,waiting_timeout=None,timeout_status : py_trees.Status = py_trees.Status.FAILURE): """ Args: name: the name of the behaviour topic_name: the topic to listen to for changes topic_type: the type of message to expect, compare_method: a function which takes in (msg1,msg2) of topic_type and returns bool (true => changed) waiting_timeout: the time after which if no second message is received, timeout is triggered timeout_status: the status to return on timeout """ super().__init__(name=name, topic_name=topic_name, topic_type=topic_type) self.second_msg = None self.first_msg = None self.waiting_timeout = waiting_timeout self.timeout_status = timeout_status self.compare_method = compare_method def initialise(self): self.start_time = time.time() self.first_msg = None self.second_msg = None return super().initialise() def message_changed(self,msg1,msg2): if self.compare_method is not None: return self.compare_method(msg1,msg2) else: return not msg1 == msg2 def update(self): # we always wait for first message with RUNNING with self.data_guard: if self.first_msg == None: self.feedback_message = "waiting for first message" if self.msg != None: self.first_msg = self.msg self.msg = None self.feedback_message = "waiting for second message" return py_trees.Status.RUNNING else: return py_trees.Status.RUNNING # then we possibly timeout on waiting for second timeout = self.waiting_timeout is not None if timeout: time_left = (time.time() - self.start_time) - self.waiting_timeout if time_left <= 0: self.feedback_message = "timed out" return self.timeout_status # await second if self.second_msg == None: if self.msg != None: self.second_msg = self.msg self.msg = None else: return py_trees.Status.RUNNING # do comparison, only reached with first and second message present # and if
<reponame>vandenberghinc/dev0s<filename>dev0s/classes/encryption/aes.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # imports. from dev0s.classes.defaults.files import * from dev0s.classes.defaults.defaults import defaults from dev0s.classes.response import response as _response_ from dev0s.classes.defaults.objects import * from dev0s.classes import utils from dev0s.classes.encryption import rsa # imports. import base64, string, random from Crypto.Cipher import AES as _AES_ from Crypto import Random from Crypto.Protocol.KDF import PBKDF2 # unpack format & encrypted. def unpack(content): if " " not in content: raise ValueError("Encrypted format is incorrectly packed.") format = "" for i in content: if i not in [" "]: format += i else: break if format == "": raise ValueError("Encrypted format is incorrectly packed.") return format, content[len(format)+1:] # the symetric aes 254 object class. class AES(object): def __init__(self, passphrase=None): # docs. DOCS = { "module":"dev0s.encryption.AES", "initialized":False, "description":[], "chapter": "Encryption", } # check params. response = _response_.parameters.check({ "passphrase:str":passphrase,}) if not response.success: raise ValueError(response.error) # arguments. self.passphrase = passphrase # variables. self.block_size = 16 self.pad = lambda s: s + (self.block_size - len(s) % self.block_size) * chr(self.block_size - len(s) % self.block_size) self.unpad = lambda s: s[:-ord(s[len(s) - 1:])] # def encrypt(self, raw): if raw in ["", b"", None, False]: return _response_.error("Can not encrypt null data.") raw = Formats.denitialize(raw) response = self.get_key() if not response.success: return response key = response["key"] salt = response["salt"] if isinstance(raw, bytes): raw = raw.decode() raw = self.pad(raw) iv = Random.new().read(_AES_.block_size) cipher = _AES_.new(key, _AES_.MODE_CBC, iv) encrypted = base64.b64encode(iv + salt + cipher.encrypt(raw.encode())) if raw != b"" and encrypted == b"": return _response_.error("Failed to encrypt the specified data with the current passphrase / salt.") return _response_.success("Successfully encrypted the specified data.", { "encrypted":encrypted, }) def decrypt(self, enc): if enc in ["", b"", None, False]: return _response_.error("Can not decrypt null data.") enc = Formats.denitialize(enc) if isinstance(enc, str): enc = enc.encode() enc = base64.b64decode(enc) iv_salt = enc[:32] iv = iv_salt[:16] salt = iv_salt[16:] response = self.get_key(salt=salt) if not response.success: return response key = response["key"] cipher = _AES_.new(key, _AES_.MODE_CBC, iv) decrypted = self.unpad(cipher.decrypt(enc[32:])) if enc != b"" and decrypted == b"": return _response_.error("Failed to decrypt the specified data with the current passphrase / salt.") return _response_.success("Successfully decrypted the specified data.", { "decrypted":decrypted, }) def get_key(self, salt=None): if salt == None: salt = self.generate_salt()["salt"] if isinstance(salt, str): salt = salt.encode() kdf = PBKDF2(self.passphrase, salt, 64, 1000) key = kdf[:32] return _response_.success("Successfully loaded the aes key.", { "key":key, "salt":salt, }) def generate_salt(self): length=16 chars = ''.join([string.ascii_uppercase, string.ascii_lowercase, string.digits]) salt = ''.join(random.choice(chars) for x in range(length)) return _response_.success("Successfully generated a salt.", { "salt":salt, }) # the asymmetric aes 254 object class. class AsymmetricAES(object): def __init__(self, # the public key (str). public_key=None, # the private key (str). private_key=None, # the key passphrase (str, null). passphrase=None, # enable memory when the keys are not saved. memory=False, ): # docs. DOCS = { "module":"dev0s.encryption.AsymmetricAES", "initialized":False, "description":[], "chapter": "Encryption", } # attributes. self.rsa = rsa.RSA(public_key=public_key, private_key=private_key, passphrase=passphrase, memory=memory) # functions. def generate_keys(self): return self.rsa.generate_keys() def load_keys(self): return self.rsa.load_keys() def load_private_key(self): return self.rsa.load_private_key() # def load_public_key(self): return self.rsa.load_public_key() # def edit_passphrase(self, passphrase=None): return self.rsa.edit_passphrase(passphrase=passphrase) # def encrypt(self, string, decode=False): string = Formats.denitialize(string) if isinstance(string, bytes): string = string.decode() # encrypt data with aes. passphrase = String().generate(length=64, digits=True, capitalize=True) aes = AES(passphrase=passphrase) response = aes.encrypt(string) if not response.success: return response aes_encrypted = response["encrypted"] if b" " in aes_encrypted: return _response_.error("AES encrypt data contains invalid ' ' character(s).") # encrypt aes key with rsa. response = self.rsa.encrypt_string(passphrase, decode=False) if not response.success: return response rsa_encrypted = response["encrypted"] # pack encrypted. encrypted = rsa_encrypted+b" "+aes_encrypted # success. if decode: encrypted = encrypted.decode() return _response_.success("Successfully encrypted the specified data.", { "encrypted":encrypted }) # def decrypt(self, string, decode=False): # split encrypted aes key. string = Formats.denitialize(string) if isinstance(string, bytes): string = string.decode() try: key,encrypted = unpack(string) #except: except KeyboardInterrupt: return _response_.error("Unable to unpack the encrypted data.") # decypt key with rsa. response = self.rsa.decrypt_string(key, decode=False) if not response.success: return response passphrase = response["decrypted"].decode() # decrypt with aes. aes = AES(passphrase=passphrase) response = aes.decrypt(encrypted) if not response.success: return response decrypted = response["decrypted"] # success. if decode: decrypted = decrypted.decode() return _response_.success("Successfully decrypted the specified data.", { "decrypted":decrypted }) # def encrypt_file(self, input=None, output=None, remove=False, base64_encoding=False): input = Formats.denitialize(input) output = Formats.denitialize(output) # check params. response = _response_.parameters.check({ "input":input, "output":output,}) if not response.success: return response # encrypt. data = Files.load(input, format="bytes") if base64_encoding: data = base64.b64encode(data) response = self.encrypt(data, decode=False) if not response.success: return response # write out. try: Files.save(output, response["encrypted"], format="bytes") except: return _response_.error(f"Failed to write out encrypted file {output}.") # remove. if remove and input != output: try: os.remove(input) except PermissionError: os.system(f"sudo rm -fr {input}") # handler. return _response_.success(f"Successfully encrypted file {input} to {output}.") # def decrypt_file(self, input=None, output=None, remove=False, base64_encoding=False): input = Formats.denitialize(input) output = Formats.denitialize(output) # check params. response = _response_.parameters.check({ "input":input, "output":output,}) if not response.success: return response # encrypt. response = self.decrypt(Files.load(input, format="bytes"), decode=False) if not response.success: return response # write out. decrypted = response.decrypted if base64_encoding: decrypted = base64.b64decode(decrypted) try: Files.save(output, decrypted, format="bytes") except: return _response_.error(f"Failed to write out decrypted file {output}.") # remove. if remove and input != output: try: os.remove(input) except PermissionError: os.system(f"sudo rm -fr {input}") # handler. return _response_.success(f"Successfully decrypted file {input} to {output}.") # def encrypt_directory(self, input=None, output=None, remove=False): input = Formats.denitialize(input) output = Formats.denitialize(output) # checks. file_path = FilePath(input) if not file_path.exists(): return _response_.error(f"Directory [{input}] does not exist.") if not file_path.directory(): return _response_.error(f"Directory path [{input}] is not a directory.") # zip path. if output == None: if input[len(input)-1] == "/": zip_path = input[:-1] else: zip_path = str(input) zip_path = f'{zip_path}.enc.zip' elif ".enc.zip" not in output: return _response_.error(f"Invalid output format [{output}], the format must end with [***.enc.zip]") else: zip_path = output # check output. if Files.exists(zip_path): return _response_.error(f"output path [{zip_path}] already exists.") # create zip. zip = Zip(path=zip_path) zip.create(source=input) # encrypt zip. response = self.encrypt_file(input=zip.file_path.path, output=zip.file_path.path, remove=False, base64_encoding=True) if response.success and Files.exists(zip.file_path.path) : if remove and input != output: try: os.system(f"rm -fr {input}") if Files.exists(input): raise PermissionError("") except PermissionError: os.system(f"sudo rm -fr {input}") return _response_.success(f"Successfully encrypted directory [{input}].") else: zip.file_path.delete(forced=True) return _response_.error(f"Failed to encrypt directory [{input}].") # def decrypt_directory(self, input=None, output=None, remove=False): input = Formats.denitialize(input) output = Formats.denitialize(output) # checks. file_path = FilePath(input) if not file_path.exists(): return _response_.error(f"Input [{input}] does not exist.") if file_path.directory(): return _response_.error(f"Input path [{input}] is a directory.") # dir path. if output == None: if ".enc.zip" not in input: return _response_.error(f"Invalid input format [{input}], the format must end with [***.enc.zip]") dir_path = output.replace(".enc.zip", "/").replace("//","/").replace("//","/").replace("//","/") else: if ".enc.zip" in output: return _response_.error(f"Invalid output format [{output}], the format can not end with [***.enc.zip]") dir_path = output.replace(".enc.zip", "/") # check output. l_dir_path = dir_path if l_dir_path[len(l_dir_path)-1] == "/": l_dir_path = l_dir_path[:-1] if Files.exists(l_dir_path): return _response_.error(f"Output path [{l_dir_path}] already exists.") # decrypt zip. tmp_zip = f"/tmp/{FilePath(input).name()}" if Files.exists(tmp_zip): os.system(f"rm -fr {tmp_zip}") response = self.decrypt_file(input=input, output=tmp_zip, remove=False, base64_encoding=True) if not response.success: return _response_.error(f"Failed to decrypted directory [{input}], error: {response.error}") # extract zip. tmp_extract = f"/tmp/{String('').generate(length=32,capitalize=True,digits=True)}/" if Files.exists(tmp_extract): os.system(f"rm -fr {tmp_extract}") os.mkdir(tmp_extract) zip = Zip(path=tmp_zip) zip.extract(base=tmp_extract) paths = Files.Directory(path=tmp_extract).paths() if len(paths) == 1: os.system(f"mv {paths[0]} {output}") if Files.exists(output): os.system(f"rm -fr {tmp_extract}") os.system(f"rm -fr {tmp_zip}") if remove and input != output: try: os.remove(input) except PermissionError: os.system(f"sudo rm -fr {input}") return _response_.success(f"Successfully decrypted directory [{input}].") else: os.system(f"rm -fr {tmp_extract}") os.system(f"rm -fr {tmp_zip}") return _response_.error(f"Failed to decrypt directory [{input}].") else: os.system(f"rm -fr {tmp_extract}") os.system(f"rm -fr {tmp_zip}") return _response_.error(f"Failed to decrypt directory [{input}].") # # properties. @property def generated(self): return self.rsa.generated @property def activated(self): return self.rsa.activated @property def public_key_activated(self): return self.rsa.public_key_activated @property def private_key_activated(self): return self.rsa.private_key_activated # the aes database object class. class Database(object): def __init__(self, # the aes object class. aes=None, # the root path of the database. path=None, ): # docs. DOCS = { "module":"dev0s.encryption.Database", "initialized":False, "description":[], "chapter": "Encryption", } # defaults. #self.__class__.__name__ = "Database" # check params. response = _response_.parameters.check({ "aes:object":aes, "path:str":path,}) if not response.success: raise ValueError(response.error) # arguments. self.aes = aes self.path = f"{gfp.clean(path, remove_first_slash=False, remove_last_slash=True, remove_double_slash=True)}/" self.file_path = self.fp = FilePath(self.path) if not self.fp.exists(): os.system(f"mkdir {self.fp.path}") self.fp.ownership.set(owner=defaults.vars.owner) self.fp.permission.set(permission=770) # # functions. def activate(self, # the key;s passphrase (optional). passphrase=None, ): # passphrase. if passphrase != None: self.aes.rsa.passphrase = passphrase # check root. if not Files.exists(f"{self.path}"): return _response_.error(f"Encrypted database root [{self.path}] does not exist.") # activate keys. response = self.aes.load_keys() if not response.success: return response # success. return _response_.success(f"Successfully activated encrypted database [{self.path}].") # def check(self, # the subpath of the content (! param number 1). path=None, # the default content data (! param number 2). default=None, # save the changes. save=True, ): if not self.activated: return _response_.error(f"Encrypted database {self.path} is not activated yet, call database.activate() first.") response = _response_.parameters.check({ "path:str":path, "default:str,dict,list,int,float":default, "save:bool":save,}) if not response.success: return response response = self.load(path=path, default=default) if not response.success: return response format, content = response.unpack(["format", "content"]) response = content.check(default=default, save=save) if not response.success: return response return _response_.success(f"Successfully checked content {path}.", { "content":content, "format":format, }) def load(self, # the subpath of the content (! param number 1). path=None, # the default data, specify to call self.check() automatically on the data object. default=None, ): if not self.activated: return _response_.error(f"Encrypted database [{self.path}] is not activated yet, call database.activate() first.") response = _response_.parameters.check({ "path:str":path,}) if not response.success: return response path = gfp.clean(f"{self.path}/{path}", remove_last_slash=True, remove_double_slash=True) if not os.path.exists(str(path)): if default == None: return _response_.error(f"Specified path [{path}] does not exist.") elif isinstance(default, (str, String, File)): if isinstance(default, File): default = default.data return _response_.success(f"Successfully parsed {path}.", { "format":"File", "content":self.File(path=path, default=str(default), aes=self.aes), }) elif isinstance(default, (list, Array)): return _response_.success(f"Successfully parsed {path}.", { "format":"Array", "content":self.Array(path=path, default=default, aes=self.aes), }) elif isinstance(default, (dict, Dictionary)): return _response_.success(f"Successfully parsed {path}.", { "format":"Dictionary", "content":self.Dictionary(path=path, default=default, aes=self.aes), }) else: try: format, _ = unpack(Files.load(path)) except Exception as e: return _response_.error(f"Failed to load content {path}, {e}.") if format in ["list", "Array"]: return _response_.success(f"Successfully parsed {path}.", { "format":"Array", "content":self.Array(path=path, default=default, aes=self.aes), }) elif format in ["dict", "Dictionary"]: return _response_.success(f"Successfully parsed {path}.", { "format":"Dictionary", "content":self.Dictionary(path=path, default=default, aes=self.aes), }) elif format in ["file", "File"]: return _response_.success(f"Successfully parsed {path}.", { "format":"File", "content":self.File(path=path, default=default, aes=self.aes), }) else: return _response_.error(f"Unknown format [{format}] for path [{path}].") def save(self, # the content object (! param number 1). content=None, ): if not self.activated: return _response_.error(f"Encrypted database {self.path} is not activated yet, call database.activate() first.") response = _response_.parameters.check({ "content:object":content,}) if not response.success: return response response = content.save() if not response.success: return response return _response_.success(f"Successfully saved content {path}.") # properties. @property def activated(self): return self.aes.activated @property def public_key_activated(self): return self.aes.public_key_activated @property def private_key_activated(self): return self.aes.private_key_activated # a file data object class File(File): def __init__(self, # the path. path=None, # the default data, specify to call self.check() automatically. default=None, # the aes object. aes=None, ): # docs. DOCS = { "module":"dev0s.encryption.Database.File", "initialized":False, "description":[], "chapter": "Encryption", } # attributes self.path = f"{gfp.clean(path, remove_first_slash=False, remove_last_slash=True, remove_double_slash=True)}" self.base = FilePath(self.path).base() self.aes = aes self.loaded = False File.__init__(self, path=self.path) if default != None: self.check(default=default, save=True) def load(self): try: format, content = unpack(Files.load(self.path)) except Exception as e: return
# # Tests CellML 1.0 schema validation # from __future__ import absolute_import, division from __future__ import print_function, unicode_literals import logging import os import pytest from lxml import etree import check from . import shared from .report import Report_1_0 as Report # Expected instances where the schema says a valid file is invalid false_negatives = {} # Expected error messages expected_messages = { # Not in spec: Root node '0.0.root_node_not_model': "No matching global declaration available for the validation root", '0.0.root_node_two_elements': "Extra content at the end of the document", '0.0.root_node_two_models': "Extra content at the end of the document", '0.0.root_node_namespace_wrong': "No matching global declaration available for the validation root", # Not in spec: Real number format '0.1.real_number_invalid_1': 'not accepted by the pattern', '0.1.real_number_invalid_2': 'not accepted by the pattern', '0.1.real_number_invalid_3': 'not accepted by the pattern', '0.1.real_number_invalid_4': 'not accepted by the pattern', '0.1.real_number_invalid_5': 'not accepted by the pattern', '0.1.real_number_invalid_6': 'not accepted by the pattern', # 2.4.1 CellML Identifiers '2.4.1.identifier_empty': #"'name': '' is not a valid value", 'not accepted by the pattern', '2.4.1.identifier_only_underscore': 'not accepted by the pattern', '2.4.1.identifier_unexpected_character_1': 'not accepted by the pattern', '2.4.1.identifier_unexpected_character_2': 'not accepted by the pattern', '2.4.1.identifier_unexpected_character_unicode': 'not accepted by the pattern', # 2.4.2. Allowable CellML elements and attributes '2.4.2.imaginary_attributes_1': "The attribute 'fruit' is not allowed", '2.4.2.imaginary_attributes_2': "The attribute 'cellml:fruit' is not allowed", '2.4.2.imaginary_elements_1': "Element 'cellml:fruit': This element is not expected", '2.4.2.imaginary_elements_2': "Element 'cellml:import': This element is not expected", # 2.4.4 Text in CellML elements '2.4.4.text_in_component': "Element 'cellml:component': Character content other than white", '2.4.4.text_in_component_ref': "Element 'cellml:component_ref': Character content other than white", '2.4.4.text_in_connection': "Element 'cellml:connection': Character content other than white", '2.4.4.text_in_group': "Element 'cellml:group': Character content other than white", '2.4.4.text_in_map_components': "Element 'cellml:map_components': Character content other than white", '2.4.4.text_in_map_variables': "Element 'cellml:map_variables': Character content other than white", '2.4.4.text_in_model': "Element 'cellml:model': Character content other than white", '2.4.4.text_in_reaction': "Element 'cellml:reaction': Character content other than white", '2.4.4.text_in_relationship_ref': "Element 'cellml:relationship_ref': Character content other than", '2.4.4.text_in_role': "Element 'cellml:role': Character content other than white", '2.4.4.text_in_unit': "Element 'cellml:unit': Character content other than white", '2.4.4.text_in_units_1': "Element 'cellml:units': Character content other than white", '2.4.4.text_in_units_2': "Element 'cellml:units': Character content other than white", '2.4.4.text_in_variable': "Element 'cellml:variable': Character content other than white", '2.4.4.text_in_variable_ref': "Element 'cellml:variable_ref': Character content other than white", # 2.5.1 Identifiers are case sensitive '2.5.1.identifiers_are_case_sensitive': "No match found for key-sequence", # 2.5.2 There are no attributes in the CellML namespace '2.5.2.attribute_in_cellml_namespace': "The attribute 'cellml:private_interface' is not allowed", # 2.5.3 Extension namespaces again # 3.4.1.1 Models contain only units, component, group, connection '3.4.1.1.model_with_component_ref': "Element 'cellml:component_ref': This element is not expected", '3.4.1.1.model_with_map_components': "Element 'cellml:map_components': This element is not expected", '3.4.1.1.model_with_map_variables': "Element 'cellml:map_variables': This element is not expected", '3.4.1.1.model_with_model': "Element 'cellml:model': This element is not expected", '3.4.1.1.model_with_reaction': "Element 'cellml:reaction': This element is not expected", '3.4.1.1.model_with_relationship_ref': "Element 'cellml:relationship_ref': This element is not expected", '3.4.1.1.model_with_role': "Element 'cellml:role': This element is not expected", '3.4.1.1.model_with_unit': "Element 'cellml:unit': This element is not expected", '3.4.1.1.model_with_variable_ref': "Element 'cellml:variable_ref': This element is not expected", '3.4.1.1.model_with_variable': "Element 'cellml:variable': This element is not expected", # 3.4.1.1 Models must have a name '3.4.1.1.model_name_missing': "Element 'cellml:model': The attribute 'name' is required", # 3.4.1.2 A model name must be a valid identifier '3.4.1.2.model_name_invalid': 'not accepted by the pattern', # 3.4.2.1 Components contain only units, variable, reaction, math '3.4.2.1.component_with_component': "Element 'cellml:component': This element is not expected", '3.4.2.1.component_with_component_ref': "Element 'cellml:component_ref': This element is not expected", '3.4.2.1.component_with_connection': "Element 'cellml:connection': This element is not expected", '3.4.2.1.component_with_group': "Element 'cellml:group': This element is not expected", '3.4.2.1.component_with_map_components': "Element 'cellml:map_components': This element is not expected", '3.4.2.1.component_with_map_variables': "Element 'cellml:map_variables': This element is not expected", '3.4.2.1.component_with_model': "Element 'cellml:model': This element is not expected", '3.4.2.1.component_with_relationship_ref': "Element 'cellml:relationship_ref': This element is not expected", '3.4.2.1.component_with_role': "Element 'cellml:role': This element is not expected", '3.4.2.1.component_with_unit': "Element 'cellml:unit': This element is not expected", '3.4.2.1.component_with_variable_ref': "Element 'cellml:variable_ref': This element is not expected", # 3.4.2.1 Components must have a name '3.4.2.1.component_name_missing': "Element 'cellml:component': The attribute 'name' is required", # 3.4.2.2 A component name must be a valid identifier '3.4.2.2.component_name_invalid': 'not accepted by the pattern', # 3.4.2.2 Component names must be unique '3.4.2.2.component_name_duplicate': "Duplicate key-sequence ['c1']", # 3.4.3.1 Variables can't contain any elements '3.4.3.1.variable_with_component': "Element 'cellml:component': This element is not expected", '3.4.3.1.variable_with_component_ref': "Element 'cellml:component_ref': This element is not expected", '3.4.3.1.variable_with_connection': "Element 'cellml:connection': This element is not expected", '3.4.3.1.variable_with_group': "Element 'cellml:group': This element is not expected", '3.4.3.1.variable_with_map_components': "Element 'cellml:map_components': This element is not expected", '3.4.3.1.variable_with_map_variables': "Element 'cellml:map_variables': This element is not expected", '3.4.3.1.variable_with_model': "Element 'cellml:model': This element is not expected", '3.4.3.1.variable_with_reaction': "Element 'cellml:reaction': This element is not expected", '3.4.3.1.variable_with_relationship_ref': "Element 'cellml:relationship_ref': This element is not expected", '3.4.3.1.variable_with_role': "Element 'cellml:role': This element is not expected", '3.4.3.1.variable_with_unit': "Element 'cellml:unit': This element is not expected", '3.4.3.1.variable_with_units': "Element 'cellml:units': This element is not expected", '3.4.3.1.variable_with_variable_ref': "Element 'cellml:variable_ref': This element is not expected", '3.4.3.1.variable_with_variable': "Element 'cellml:variable': This element is not expected", # 3.4.3.1 Variables must have a name attribute '3.4.3.1.variable_name_missing': "The attribute 'name' is required but missing", # 3.4.3.1 Variables must have a units attribute '3.4.3.1.variable_units_missing': "Element 'cellml:variable': The attribute 'units' is required", # 3.4.3.2 A variable name must be an identifier '3.4.3.2.variable_name_invalid': 'not accepted by the pattern', # 3.4.3.2 A variable name must be unique with the component '3.4.3.2.variable_name_duplicate': "Element 'cellml:variable': Duplicate key-sequence", # 3.4.3.4 A public interface must be one of in/out/none '3.4.3.4.variable_interface_public_invalid': "not an element of the set", # 3.4.3.5 A private interface must be one of in/out/none '3.4.3.5.variable_interface_private_invalid': "not an element of the set", # 3.4.3.7 The initial value (if present) must be a real number '3.4.3.7.variable_initial_value_empty': 'not accepted by the pattern', '3.4.3.7.variable_initial_value_invalid': 'not accepted by the pattern', # 3.4.4.1 A connection must have map_components and map_variables '3.4.4.1.connection_empty': "Element 'cellml:connection': Missing child element(s).", # 3.4.4.1 A connection can only contain map_components and map_variables '3.4.4.1.connection_with_component': "Element 'cellml:component': This element is not expected", '3.4.4.1.connection_with_component_ref': "Element 'cellml:component_ref': This element is not expected", '3.4.4.1.connection_with_connection': "Element 'cellml:connection': This element is not expected", '3.4.4.1.connection_with_group': "Element 'cellml:group': This element is not expected", '3.4.4.1.connection_with_map_components': "Element 'cellml:map_components': This element is not expected", '3.4.4.1.connection_with_map_variables': "Element 'cellml:map_variables': This element is not expected", '3.4.4.1.connection_with_model': "Element 'cellml:model': This element is not expected", '3.4.4.1.connection_with_name_attribute': "Element 'cellml:connection', attribute 'name'", '3.4.4.1.connection_with_reaction': "Element 'cellml:reaction': This element is not expected", '3.4.4.1.connection_with_relationship_ref': "Element 'cellml:relationship_ref': This element is not expected", '3.4.4.1.connection_with_role': "Element 'cellml:role': This element is not expected", '3.4.4.1.connection_with_unit': "Element 'cellml:unit': This element is not expected", '3.4.4.1.connection_with_units': "Element 'cellml:units': This element is not expected", '3.4.4.1.connection_with_variable_ref': "Element 'cellml:variable_ref': This element is not expected", '3.4.4.1.connection_with_variable': "Element 'cellml:variable': This element is not expected", # 3.4.5.1 A map_components must declare component_1 and component_2 '3.4.5.1.map_components_component_1_missing': "Element 'cellml:map_components': The attribute 'component_1' is req", '3.4.5.1.map_components_component_2_missing': "Element 'cellml:map_components': The attribute 'component_2' is req", # 3.4.5.1 A map_components cannot have cellml children or math '3.4.5.1.map_components_with_component': "Element 'cellml:component': This element is not expected", '3.4.5.1.map_components_with_component_ref': "Element 'cellml:component_ref': This element is not expected", '3.4.5.1.map_components_with_connection': "Element 'cellml:connection': This element is not expected", '3.4.5.1.map_components_with_group': "Element 'cellml:group': This element is not expected", '3.4.5.1.map_components_with_map_components': "Element 'cellml:map_components': This element is not expected", '3.4.5.1.map_components_with_map_variables': "Element 'cellml:map_variables': This element is not expected", '3.4.5.1.map_components_with_model': "Element 'cellml:model': This element is not expected", '3.4.5.1.map_components_with_reaction': "Element 'cellml:reaction': This element is not expected", '3.4.5.1.map_components_with_relationship_ref': "Element 'cellml:relationship_ref': This element is not expected", '3.4.5.1.map_components_with_role': "Element 'cellml:role': This element is not expected", '3.4.5.1.map_components_with_unit': "Element 'cellml:unit': This element is not expected", '3.4.5.1.map_components_with_units': "Element 'cellml:units': This element is not expected", '3.4.5.1.map_components_with_variable_ref': "Element 'cellml:variable_ref': This element is not expected", '3.4.5.1.map_components_with_variable': "Element 'cellml:variable': This element is not expected", # 3.4.5.2 component_1 must refer to an existing component '3.4.5.2.map_components_component_1_nonexistent': "Element 'cellml:map_components': No match found for key-sequence", # 3.4.5.3 component_2 must refer to an existing component '3.4.5.3.map_components_component_2_nonexistent': "Element 'cellml:map_components': No match found for key-sequence", # 3.4.5.4 Each map_components in a model must be unique '3.4.5.4.map_components_duplicate': "Element 'cellml:map_components': Duplicate key-sequence", # 3.4.6.1 A map_variables must declare variable_1 and variable_2 '3.4.6.1.map_variables_variable_1_missing': "Element 'cellml:map_variables': The attribute 'variable_1' is req", '3.4.6.1.map_variables_variable_2_missing': "Element 'cellml:map_variables': The attribute 'variable_2' is req", # 3.4.6.1 A map_variables cannot have cellml children or math '3.4.6.1.map_variables_with_component': "Element 'cellml:component': This element is not expected", '3.4.6.1.map_variables_with_component_ref': "Element 'cellml:component_ref': This element is not expected", '3.4.6.1.map_variables_with_connection': "Element 'cellml:connection': This element is not expected", '3.4.6.1.map_variables_with_group': "Element 'cellml:group': This element is not expected", '3.4.6.1.map_variables_with_map_components': "Element 'cellml:map_components': This element
#!/usr/bin/env python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import glob import logging import os import shutil import tempfile import pyauto_functional # Must be imported before pyauto import pyauto class TranslateTest(pyauto.PyUITest): """Tests that translate works correctly""" spanish = 'es' after_translate = 'AFTER_TRANSLATE' before_translate = 'BEFORE_TRANSLATE' translating = 'TRANSLATING' translation_error = 'TRANSLATION_ERROR' def Debug(self): """ Test method for experimentation. """ while True: raw_input('Hit <enter> to dump translate info.. ') self.pprint(self.GetTranslateInfo()) def _GetDefaultSpanishURL(self): return self.GetHttpURLForDataPath('translate', self.spanish, 'google.html') def _GetDefaultEnglishURL(self): return self.GetHttpURLForDataPath('title1.html') def _NavigateAndWaitForBar(self, url, window_index=0, tab_index=0): self.NavigateToURL(url, window_index, tab_index) self.assertTrue(self.WaitForInfobarCount( 1, windex=window_index, tab_index=tab_index)) def _ClickTranslateUntilSuccess(self, window_index=0, tab_index=0): """Since the translate can fail due to server error, continue trying until it is successful or until it has tried too many times.""" max_tries = 10 curr_try = 0 while (curr_try < max_tries and not self.ClickTranslateBarTranslate(window_index=window_index, tab_index=tab_index)): curr_try = curr_try + 1 if curr_try == max_tries: self.fail('Translation failed more than %d times.' % max_tries) def _AssertTranslateWorks(self, url, original_language): """Translate the page at the given URL and assert that the page has been translated. """ self._NavigateAndWaitForBar(url) translate_info = self.GetTranslateInfo() self.assertEqual(original_language, translate_info['original_language']) self.assertFalse(translate_info['page_translated']) self.assertTrue(translate_info['can_translate_page']) self.assertTrue('translate_bar' in translate_info) self._ClickTranslateUntilSuccess() translate_info = self.GetTranslateInfo() self.assertTrue(translate_info['can_translate_page']) self.assertTrue('translate_bar' in translate_info) translate_bar = translate_info['translate_bar'] self.assertEquals(self.after_translate, translate_info['translate_bar']['bar_state']) self.assertEquals(original_language, translate_bar['original_lang_code']) def testTranslate(self): """Tests that a page was translated if the user chooses to translate.""" self._AssertTranslateWorks(self._GetDefaultSpanishURL(), self.spanish) def testNoTranslate(self): """Tests that a page isn't translated if the user declines translate.""" self._NavigateAndWaitForBar(self._GetDefaultSpanishURL()) self.SelectTranslateOption('decline_translation') translate_info = self.GetTranslateInfo() self.assertEqual(self.spanish, translate_info['original_language']) self.assertFalse(translate_info['page_translated']) self.assertTrue(translate_info['can_translate_page']) # If the user goes to the site again, the infobar should drop down but # the page should not be automatically translated. self._NavigateAndWaitForBar(self._GetDefaultSpanishURL()) translate_info = self.GetTranslateInfo() self.assertFalse(translate_info['page_translated']) self.assertTrue(translate_info['can_translate_page']) self.assertTrue('translate_bar' in translate_info) self.assertEquals(self.before_translate, translate_info['translate_bar']['bar_state']) def testNeverTranslateLanguage(self): """Tests that blacklisting a language for translate works.""" self._NavigateAndWaitForBar(self._GetDefaultSpanishURL()) self.SelectTranslateOption('never_translate_language') translate_info = self.GetTranslateInfo() self.assertEqual(self.spanish, translate_info['original_language']) self.assertFalse(translate_info['page_translated']) self.assertFalse(translate_info['can_translate_page']) spanish_wikipedia = 'http://es.wikipedia.org/wiki/Wikipedia:Portada' self.NavigateToURL(spanish_wikipedia) translate_info = self.GetTranslateInfo() self.assertEqual(self.spanish, translate_info['original_language']) self.assertFalse(translate_info['page_translated']) self.assertFalse(translate_info['can_translate_page']) def testAlwaysTranslateLanguage(self): """Tests that the always translate a language option works.""" self._NavigateAndWaitForBar(self._GetDefaultSpanishURL()) self.SelectTranslateOption('toggle_always_translate') self._ClickTranslateUntilSuccess() translate_info = self.GetTranslateInfo() self.assertEquals(self.spanish, translate_info['original_language']) self.assertTrue(translate_info['page_translated']) self.assertTrue(translate_info['can_translate_page']) self.assertTrue('translate_bar' in translate_info) self.assertEquals(self.after_translate, translate_info['translate_bar']['bar_state']) # Go to another spanish site and verify that it is translated. # Note that the 'This page has been translated..." bar will show up. self._NavigateAndWaitForBar( 'http://es.wikipedia.org/wiki/Wikipedia:Portada') translate_info = self.GetTranslateInfo() self.assertTrue('translate_bar' in translate_info) curr_bar_state = translate_info['translate_bar']['bar_state'] # We don't care whether the translation has finished, just that it is # trying to translate. self.assertTrue(curr_bar_state is self.after_translate or self.translating or self.translation_error, 'Bar state was %s.' % curr_bar_state) def testNeverTranslateSite(self): """Tests that blacklisting a site for translate works.""" spanish_google = 'http://www.google.com/webhp?hl=es' self._NavigateAndWaitForBar(spanish_google) self.SelectTranslateOption('never_translate_site') translate_info = self.GetTranslateInfo() self.assertFalse(translate_info['page_translated']) self.assertFalse(translate_info['can_translate_page']) french_google = 'http://www.google.com/webhp?hl=fr' # Go to another page in the same site and verify that the page can't be # translated even though it's in a different language. self.NavigateToURL(french_google) translate_info = self.GetTranslateInfo() self.assertFalse(translate_info['page_translated']) self.assertFalse(translate_info['can_translate_page']) def testRevert(self): """Tests that reverting a site to its original language works.""" self._NavigateAndWaitForBar(self._GetDefaultSpanishURL()) self._ClickTranslateUntilSuccess() self.RevertPageTranslation() translate_info = self.GetTranslateInfo() self.assertFalse(translate_info['page_translated']) self.assertTrue(translate_info['can_translate_page']) def testBarNotVisibleOnSSLErrorPage(self): """Test Translate bar is not visible on SSL error pages.""" self._NavigateAndWaitForBar(self._GetDefaultSpanishURL()) translate_info = self.GetTranslateInfo() self.assertTrue('translate_bar' in translate_info) self.assertTrue(translate_info['can_translate_page']) # This page is an ssl error page. self.NavigateToURL('https://www.sourceforge.net') self.assertTrue(self.WaitForInfobarCount(0)) translate_info = self.GetTranslateInfo() self.assertFalse('translate_bar' in translate_info) def testBarNotVisibleOnEnglishPage(self): """Test Translate bar is not visible on English pages.""" self._NavigateAndWaitForBar(self._GetDefaultSpanishURL()) translate_info = self.GetTranslateInfo() self.assertTrue('translate_bar' in translate_info) self.assertTrue(translate_info['can_translate_page']) # With the translate bar visible in same tab open an English page. self.NavigateToURL(self._GetDefaultEnglishURL()) self.assertTrue(self.WaitForInfobarCount(0)) translate_info = self.GetTranslateInfo() self.assertFalse('translate_bar' in translate_info) def testTranslateDiffURLs(self): """Test that HTTP, HTTPS, and file urls all get translated.""" http_url = 'http://www.google.com/webhp?hl=es' https_url = 'https://www.google.com/webhp?hl=es' file_url = self._GetDefaultSpanishURL() for url in (http_url, https_url, file_url): self._AssertTranslateWorks(url, self.spanish) def testNotranslateMetaTag(self): """Test "notranslate" meta tag.""" self._NavigateAndWaitForBar(self._GetDefaultSpanishURL()) self.NavigateToURL(self.GetFileURLForDataPath( 'translate', 'notranslate_meta_tag.html')) self.assertTrue(self.WaitForInfobarCount(0)) translate_info = self.GetTranslateInfo() self.assertFalse('translate_bar' in translate_info) def testToggleTranslateOption(self): """Test to toggle the 'Always Translate' option.""" self._NavigateAndWaitForBar(self._GetDefaultSpanishURL()) # Assert the default. translate_info = self.GetTranslateInfo() self.assertFalse(translate_info['page_translated']) self.assertTrue('translate_bar' in translate_info) # Select 'Always Translate'. self.SelectTranslateOption('toggle_always_translate') self._ClickTranslateUntilSuccess() translate_info = self.GetTranslateInfo() self.assertTrue(translate_info['page_translated']) # Reload the tab and confirm the page was translated. self.GetBrowserWindow(0).GetTab(0).Reload() self.assertTrue(self.WaitForInfobarCount(1)) success = self.WaitUntilTranslateComplete() # Sometimes the translation fails. Continue clicking until it succeeds. if not success: self._ClickTranslateUntilSuccess() # Uncheck 'Always Translate' self.SelectTranslateOption('toggle_always_translate') self.PerformActionOnInfobar('dismiss', 0) translate_info = self.GetTranslateInfo() self.assertTrue(translate_info['page_translated']) self.assertFalse('translate_bar' in translate_info) # Reload the tab and confirm that the page has not been translated. self.GetBrowserWindow(0).GetTab(0).Reload() translate_info = self.GetTranslateInfo() self.assertFalse(translate_info['page_translated']) self.assertTrue('translate_bar' in translate_info) def testSessionRestore(self): """Test that session restore restores the translate infobar and other translate settings. """ # Due to crbug.com/51439, we must open two tabs here. self.NavigateToURL("http://www.news.google.com") self.AppendTab(pyauto.GURL("http://www.google.com/webhp?hl=es")) self.assertTrue(self.WaitForInfobarCount(1, tab_index=1)) translate_info = self.GetTranslateInfo(tab_index=1) self.assertTrue('translate_bar' in translate_info) self.SelectTranslateOption('toggle_always_translate', tab_index=1) self._ClickTranslateUntilSuccess(tab_index=1) self.SetPrefs(pyauto.kRestoreOnStartup, 1) self.RestartBrowser(clear_profile=False) self.assertTrue(self.WaitForInfobarCount(1, tab_index=1)) self.WaitUntilTranslateComplete(tab_index=1) translate_info = self.GetTranslateInfo(tab_index=1) self.assertTrue('translate_bar' in translate_info) # Sometimes translation fails. We don't really care whether it succeededs, # just that a translation was attempted. self.assertNotEqual(self.before_translate, translate_info['translate_bar']['bar_state']) def testGoBackAndForwardToTranslatePage(self): """Tests that translate bar re-appears after backward and forward navigation to a page that can be translated. """ no_trans_url = self._GetDefaultEnglishURL() trans_url = self._GetDefaultSpanishURL() self._NavigateAndWaitForBar(trans_url) translate_info = self.GetTranslateInfo() self.assertTrue('translate_bar' in translate_info) self.NavigateToURL(no_trans_url) self.assertTrue(self.WaitForInfobarCount(0)) self.assertFalse('translate_bar' in self.GetTranslateInfo()) # Go back to the page that should be translated and assert that the # translate bar re-appears. self.GetBrowserWindow(0).GetTab(0).GoBack() self.assertTrue(self.WaitForInfobarCount(1)) self.assertTrue('translate_bar' in self.GetTranslateInfo()) # Now test going forward. self.NavigateToURL(no_trans_url) translate_info = self.GetTranslateInfo() self.assertFalse('translate_bar' in translate_info) self._AssertTranslateWorks(trans_url, self.spanish) self.GetBrowserWindow(0).GetTab(0).GoBack() self.assertTrue(self.WaitForInfobarCount(0)) translate_info = self.GetTranslateInfo() self.assertFalse('translate_bar' in translate_info) self.GetBrowserWindow(0).GetTab(0).GoForward() self.assertTrue(self.WaitForInfobarCount(1)) translate_info = self.GetTranslateInfo() self.assertTrue(translate_info['can_translate_page']) self.assertTrue('translate_bar' in translate_info) def testForCrashedTab(self): """Tests that translate bar is dimissed if the renderer crashes.""" crash_url = 'about:crash' self._NavigateAndWaitForBar(self._GetDefaultSpanishURL()) translate_info = self.GetTranslateInfo() self.assertTrue('translate_bar' in translate_info) self.NavigateToURL(crash_url) self.assertTrue(self.WaitForInfobarCount(0)) self.assertFalse('translate_bar' in self.GetTranslateInfo()) def testTranslatePrefs(self): """Test the Prefs:Translate option.""" # Assert defaults first. self.assertTrue(self.GetPrefsInfo().Prefs(pyauto.kEnableTranslate)) # Uncheck. self.SetPrefs(pyauto.kEnableTranslate, False) self.NavigateToURL(self._GetDefaultSpanishURL()) self.assertFalse('translate_bar' in self.GetTranslateInfo()) # Restart the browser and assert the translate preference stays. self.RestartBrowser(clear_profile=False) self.assertFalse(self.GetPrefsInfo().Prefs(pyauto.kEnableTranslate)) self.NavigateToURL(self._GetDefaultSpanishURL()) self.assertFalse('translate_bar' in self.GetTranslateInfo()) def testAlwaysTranslateLanguageButton(self): """Test the always translate language button.""" spanish_url = self._GetDefaultSpanishURL() self._NavigateAndWaitForBar(spanish_url) # The 'Always Translate' button doesn't show up until the user has clicked # 'Translate' for a language 3 times. for unused in range(3): self._ClickTranslateUntilSuccess() self.GetBrowserWindow(0).GetTab(0).Reload() # Click the 'Always Translate' button. self.assertTrue(self.GetTranslateInfo()\ ['translate_bar']['always_translate_lang_button_showing']) self.SelectTranslateOption('click_always_translate_lang_button') # Navigate to another Spanish page and verify it was translated. self._NavigateAndWaitForBar('http://www.google.com/webhp?hl=es') self.WaitUntilTranslateComplete() # Assert that a translation was attempted. We don't care if it was error # or success. self.assertNotEqual(self.before_translate, self.GetTranslateInfo()['translate_bar']['bar_state']) def testNeverTranslateLanguageButton(self): """Test the never translate language button.""" spanish_url = self._GetDefaultSpanishURL() self._NavigateAndWaitForBar(spanish_url) # The 'Never Translate' button doesn't show up until the user has clicked # 'Nope' for a language 3 times. for unused in range(3): self.SelectTranslateOption('decline_translation') self.GetBrowserWindow(0).GetTab(0).Reload() # Click the 'Never Translate' button. self.assertTrue(self.GetTranslateInfo()\ ['translate_bar']['never_translate_lang_button_showing']) self.SelectTranslateOption('click_never_translate_lang_button') # Navigate to another Spanish page and verify the page can't be translated. # First navigate to a French page, wait for bar, navigate to Spanish page # and wait for bar to go away. self._NavigateAndWaitForBar('http://www.google.com/webhp?hl=fr') self.NavigateToURL('http://www.google.com/webhp?hl=es') self.assertTrue(self.WaitForInfobarCount(0)) self.assertFalse(self.GetTranslateInfo()['can_translate_page']) def testChangeTargetLanguageAlwaysTranslate(self): """Tests that the change target language option works with always translate on reload. This test is motivated by crbug.com/37313. """ self._NavigateAndWaitForBar(self._GetDefaultSpanishURL()) self._ClickTranslateUntilSuccess() # Select a different target language on translate info bar (French). self.ChangeTranslateToLanguage('French') translate_info = self.GetTranslateInfo() self.assertTrue('translate_bar' in translate_info) self.assertEqual('fr', translate_info['translate_bar']['target_lang_code']) # Select always translate Spanish to French. self.SelectTranslateOption('toggle_always_translate') # Reload the page and assert that the page has been translated to French. self.GetBrowserWindow(0).GetTab(0).Reload() self.WaitUntilTranslateComplete() translate_info = self.GetTranslateInfo() self.assertTrue(translate_info['page_translated']) self.assertTrue(translate_info['can_translate_page']) self.assertTrue('translate_bar' in translate_info) self.assertEqual('fr', translate_info['translate_bar']['target_lang_code']) def testSeveralLanguages(self): """Verify translation for several languages. This assumes that there is a directory of directories in the data dir. The directory is called 'translate', and within that directory there are subdirectories for each language code. Ex. a subdirectory 'es' with Spanish html files. """ corpora_path = os.path.join(self.DataDir(), 'translate') corp_dir = glob.glob(os.path.join(corpora_path, '??')) + \ glob.glob(os.path.join(corpora_path, '??-??')) for language in corp_dir: files = glob.glob(os.path.join(language, '*.html*')) lang_code = os.path.basename(language) logging.debug('Starting language %s' % lang_code) # Translate each html file in the language directory. for lang_file in files: logging.debug('Starting file %s' % lang_file) lang_file = self.GetFileURLForPath(lang_file) self._AssertTranslateWorks(lang_file, lang_code) def _CreateCrazyDownloads(self): """Doownload files with filenames containing special chars. The files are created on the fly and cleaned after use. """ download_dir = self.GetDownloadDirectory().value()
except Exception: return "Could not retrieve object: %s" % box_name if box is None: self.app.inform.emit('[WARNING_NOTCL] %s: %s' % (_("No object Box. Using instead"), obj)) box = obj scale_factor_x = scale_factor_x scale_factor_y = scale_factor_y def make_negative_film(scale_factor_x, scale_factor_y): log.debug("FilmTool.export_negative().make_negative_film()") scale_reference = 'center' self.screen_dpi = self.app.qapp.screens()[0].logicalDotsPerInch() new_png_dpi = self.ui.png_dpi_spinner.get_value() dpi_rate = new_png_dpi / self.screen_dpi # Determine bounding area for svg export bounds = box.bounds() tr_scale_reference = (bounds[0], bounds[1]) if dpi_rate != 1 and ftype == 'png': scale_factor_x += dpi_rate scale_factor_y += dpi_rate scale_reference = (bounds[0], bounds[1]) if box.kind.lower() == 'geometry': flat_geo = [] if box.multigeo: for tool in box.tools: flat_geo += box.flatten(box.tools[tool]['solid_geometry']) box_geo = unary_union(flat_geo) else: box_geo = unary_union(box.flatten()) else: box_geo = unary_union(box.flatten()) skew_ref = 'center' if skew_reference != 'center': xmin, ymin, xmax, ymax = box_geo.bounds if skew_reference == 'topleft': skew_ref = (xmin, ymax) elif skew_reference == 'bottomleft': skew_ref = (xmin, ymin) elif skew_reference == 'topright': skew_ref = (xmax, ymax) elif skew_reference == 'bottomright': skew_ref = (xmax, ymin) transformed_box_geo = box_geo if scale_factor_x and not scale_factor_y: transformed_box_geo = affinity.scale(transformed_box_geo, scale_factor_x, 1.0, origin=tr_scale_reference) elif not scale_factor_x and scale_factor_y: transformed_box_geo = affinity.scale(transformed_box_geo, 1.0, scale_factor_y, origin=tr_scale_reference) elif scale_factor_x and scale_factor_y: transformed_box_geo = affinity.scale(transformed_box_geo, scale_factor_x, scale_factor_y, origin=tr_scale_reference) if skew_factor_x and not skew_factor_y: transformed_box_geo = affinity.skew(transformed_box_geo, skew_factor_x, 0.0, origin=skew_ref) elif not skew_factor_x and skew_factor_y: transformed_box_geo = affinity.skew(transformed_box_geo, 0.0, skew_factor_y, origin=skew_ref) elif skew_factor_x and skew_factor_y: transformed_box_geo = affinity.skew(transformed_box_geo, skew_factor_x, skew_factor_y, origin=skew_ref) if mirror: if mirror == 'x': transformed_box_geo = affinity.scale(transformed_box_geo, 1.0, -1.0) if mirror == 'y': transformed_box_geo = affinity.scale(transformed_box_geo, -1.0, 1.0) if mirror == 'both': transformed_box_geo = affinity.scale(transformed_box_geo, -1.0, -1.0) bounds = transformed_box_geo.bounds size = bounds[2] - bounds[0], bounds[3] - bounds[1] exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor, scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y, skew_factor_x=skew_factor_x, skew_factor_y=skew_factor_y, mirror=mirror, scale_reference=scale_reference, skew_reference=skew_reference ) uom = obj.units.lower() # Convert everything to strings for use in the xml doc svgwidth = str(size[0] + (2 * boundary)) svgheight = str(size[1] + (2 * boundary)) minx = str(bounds[0] - boundary) miny = str(bounds[1] + boundary + size[1]) miny_rect = str(bounds[1] - boundary) # Add a SVG Header and footer to the svg output from shapely # The transform flips the Y Axis so that everything renders # properly within svg apps such as inkscape svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \ 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" ' svg_header += 'width="' + svgwidth + uom + '" ' svg_header += 'height="' + svgheight + uom + '" ' svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" ' svg_header += '>' svg_header += '<g transform="scale(1,-1)">' svg_footer = '</g> </svg>' # Change the attributes of the exported SVG # We don't need stroke-width - wrong, we do when we have lines with certain width # We set opacity to maximum # We set the color to WHITE root = ET.fromstring(exported_svg) for child in root: child.set('fill', '#FFFFFF') child.set('opacity', '1.0') child.set('stroke', '#FFFFFF') # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" ' # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" ' # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"' first_svg_elem_tag = 'rect' first_svg_elem_attribs = { 'x': minx, 'y': miny_rect, 'width': svgwidth, 'height': svgheight, 'id': 'neg_rect', 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0' } root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs)) exported_svg = ET.tostring(root) svg_elem = svg_header + str(exported_svg) + svg_footer # Parse the xml through a xml parser just to add line feeds # and to make it look more pretty for the output doc = parse_xml_string(svg_elem) doc_final = doc.toprettyxml() if ftype == 'svg': try: with open(filename, 'w') as fp: fp.write(doc_final) except PermissionError: self.app.inform.emit('[WARNING] %s' % _("Permission denied, saving not possible.\n" "Most likely another app is holding the file open and not accessible.")) return 'fail' elif ftype == 'png': try: doc_final = StringIO(doc_final) drawing = svg2rlg(doc_final) renderPM.drawToFile(drawing, filename, 'PNG') # if new_png_dpi == default_dpi: # renderPM.drawToFile(drawing, filename, 'PNG') # else: # renderPM.drawToFile(drawing, filename, 'PNG', dpi=new_png_dpi) except Exception as e: log.debug("FilmTool.export_negative() --> PNG output --> %s" % str(e)) return 'fail' else: try: if self.units == 'INCH': unit = inch else: unit = mm doc_final = StringIO(doc_final) drawing = svg2rlg(doc_final) p_size = self.ui.pagesize_combo.get_value() if p_size == 'Bounds': renderPDF.drawToFile(drawing, filename) else: if self.ui.orientation_radio.get_value() == 'p': page_size = portrait(self.ui.pagesize[p_size]) else: page_size = landscape(self.ui.pagesize[p_size]) my_canvas = canvas.Canvas(filename, pagesize=page_size) my_canvas.translate(bounds[0] * unit, bounds[1] * unit) renderPDF.draw(drawing, my_canvas, 0, 0) my_canvas.save() except Exception as e: log.debug("FilmTool.export_negative() --> PDF output --> %s" % str(e)) return 'fail' if self.app.defaults["global_open_style"] is False: self.app.file_opened.emit("SVG", filename) self.app.file_saved.emit("SVG", filename) self.app.inform.emit('[success] %s: %s' % (_("Film file exported to"), filename)) if use_thread is True: def job_thread_film(): with self.app.proc_container.new(_("Working...")): try: make_negative_film(scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y) except Exception as e: log.debug("export_negative() process -> %s" % str(e)) return self.app.worker_task.emit({'fcn': job_thread_film, 'params': []}) else: make_negative_film(scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y) def export_positive(self, obj_name, box_name, filename, scale_stroke_factor=0.00, scale_factor_x=1, scale_factor_y=1, skew_factor_x=None, skew_factor_y=None, skew_reference='center', mirror=None, orientation_val='p', pagesize_val='A4', color_val='black', opacity_val=1.0, use_thread=True, ftype='svg'): """ Exports a Geometry Object to an SVG file in positive black. :param obj_name: the name of the FlatCAM object to be saved :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved :param filename: Path to the file to save to. :param scale_stroke_factor: factor by which to change/scale the thickness of the features :param scale_factor_x: factor to scale the geometry on the X axis :param scale_factor_y: factor to scale the geometry on the Y axis :param skew_factor_x: factor to skew the geometry on the X axis :param skew_factor_y: factor to skew the geometry on the Y axis :param skew_reference: reference to use for skew. Can be 'bottomleft', 'bottomright', 'topleft', 'topright' and those are the 4 points of the bounding box of the geometry to be skewed. :param mirror: can be 'x' or 'y' or 'both'. Axis on which to mirror the svg geometry :param orientation_val: :param pagesize_val: :param color_val: :param opacity_val: :param use_thread: if to be run in a separate thread; boolean :param ftype: the type of file for saving the film: 'svg', 'png' or 'pdf' :return: """ self.app.defaults.report_usage("export_positive()") if filename is None: filename = self.app.defaults["global_last_save_folder"] self.app.log.debug("export_svg() black") try: obj = self.app.collection.get_by_name(str(obj_name)) except Exception: return "Could not retrieve object: %s" % obj_name try: box = self.app.collection.get_by_name(str(box_name)) except Exception: return "Could not retrieve object: %s" % box_name if box is None: self.inform.emit('[WARNING_NOTCL] %s: %s' % (_("No object Box. Using instead"), obj)) box = obj scale_factor_x = scale_factor_x scale_factor_y = scale_factor_y p_size = pagesize_val orientation = orientation_val color = color_val transparency_level = opacity_val def make_positive_film(p_size, orientation, color, transparency_level, scale_factor_x, scale_factor_y): log.debug("FilmTool.export_positive().make_positive_film()") scale_reference = 'center' self.screen_dpi = self.app.qapp.screens()[0].logicalDotsPerInch() new_png_dpi = self.ui.png_dpi_spinner.get_value() dpi_rate = new_png_dpi / self.screen_dpi # Determine bounding area for svg export bounds = box.bounds() tr_scale_reference = (bounds[0], bounds[1]) if dpi_rate != 1 and ftype == 'png': scale_factor_x += dpi_rate scale_factor_y += dpi_rate scale_reference = (bounds[0], bounds[1]) if box.kind.lower() == 'geometry': flat_geo = [] if box.multigeo: for tool in box.tools: flat_geo += box.flatten(box.tools[tool]['solid_geometry']) box_geo = unary_union(flat_geo) else: box_geo = unary_union(box.flatten()) else: box_geo = unary_union(box.flatten()) skew_ref = 'center' if skew_reference != 'center': xmin, ymin, xmax, ymax = box_geo.bounds if skew_reference == 'topleft': skew_ref = (xmin, ymax) elif skew_reference == 'bottomleft': skew_ref = (xmin, ymin) elif skew_reference == 'topright': skew_ref = (xmax, ymax) elif skew_reference == 'bottomright': skew_ref = (xmax, ymin) transformed_box_geo = box_geo if scale_factor_x and not scale_factor_y: transformed_box_geo = affinity.scale(transformed_box_geo, scale_factor_x, 1.0, origin=tr_scale_reference) elif not scale_factor_x and scale_factor_y: transformed_box_geo = affinity.scale(transformed_box_geo, 1.0, scale_factor_y, origin=tr_scale_reference) elif scale_factor_x and scale_factor_y: transformed_box_geo = affinity.scale(transformed_box_geo, scale_factor_x, scale_factor_y, origin=tr_scale_reference) if skew_factor_x and not skew_factor_y: transformed_box_geo = affinity.skew(transformed_box_geo, skew_factor_x, 0.0, origin=skew_ref) elif not skew_factor_x and skew_factor_y: transformed_box_geo = affinity.skew(transformed_box_geo, 0.0, skew_factor_y, origin=skew_ref) elif skew_factor_x and skew_factor_y: transformed_box_geo = affinity.skew(transformed_box_geo, skew_factor_x, skew_factor_y, origin=skew_ref) if mirror: if mirror == 'x': transformed_box_geo = affinity.scale(transformed_box_geo, 1.0, -1.0) if mirror == 'y': transformed_box_geo = affinity.scale(transformed_box_geo, -1.0, 1.0) if mirror == 'both': transformed_box_geo = affinity.scale(transformed_box_geo, -1.0, -1.0) bounds = transformed_box_geo.bounds size = bounds[2] - bounds[0], bounds[3] - bounds[1] exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor, scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y, skew_factor_x=skew_factor_x, skew_factor_y=skew_factor_y, mirror=mirror, scale_reference=scale_reference, skew_reference=skew_reference
todays_charge = Decimal(0) else: tier_type = 'downgrade' todays_charge = Decimal(0) else: if tier_limit <= current_limit: # This means the customer is underpaying, by today's standards. # We should not let them upgrade in the normal way. # If we don't want this to happen, we should work it out via # the Perma admin, the Perma Payments admin, and/or CyberSource Business Center tier_type = 'unavailable' todays_charge = Decimal(0) else: tier_type = 'upgrade' todays_charge = prorated_ratio * (tier_rate - current_rate) tier.update({ 'type': tier_type, 'link_limit': str(tier['link_limit']), 'link_limit_effective_timestamp': now.timestamp() if tier_type == 'upgrade' else next_payment.timestamp(), 'todays_charge': "{0:.2f}".format(todays_charge.quantize(Decimal('.01'))), 'recurring_amount': "{0:.2f}".format(tier_rate), 'recurring_start_date': next_payment.strftime("%Y-%m-%d"), 'next_payment': next_payment }) def get_subscription_info(self, now): timestamp = now.timestamp() next_month = first_day_of_next_month(now) next_year = today_next_year(now) subscription = self.get_subscription() tiers = [] if subscription and subscription.get('pending_change'): # allow the user to effective cancel the pending change, # reverting to / rescheduling whatever is on record as # their "current" subscription, in Perma required_fields = { 'customer_pk': self.pk, 'customer_type': self.customer_type, 'timestamp': timestamp, 'amount': '0.00', 'recurring_amount': subscription['rate'], 'recurring_frequency': subscription['frequency'], 'recurring_start_date': subscription['paid_through'].strftime("%Y-%m-%d"), 'link_limit': subscription['link_limit'], 'link_limit_effective_timestamp': now.timestamp() } tiers.append({ 'type': 'cancel_downgrade', 'period': subscription['frequency'], 'limit': subscription['link_limit'], 'rate': subscription['rate'], 'next_payment': subscription['paid_through'].strftime("%Y-%m-%d"), 'required_fields': required_fields, 'encrypted_data': prep_for_perma_payments(required_fields).decode('utf-8') }) else: for tier in settings.TIERS[self.customer_type]: self.annotate_tier(tier, subscription, now, next_month, next_year) required_fields = { 'customer_pk': self.pk, 'customer_type': self.customer_type, 'timestamp': timestamp, 'amount': tier['todays_charge'], 'recurring_amount': tier['recurring_amount'], 'recurring_frequency': tier['period'], 'recurring_start_date': tier['recurring_start_date'], 'link_limit': tier['link_limit'], 'link_limit_effective_timestamp': tier['link_limit_effective_timestamp'] } tiers.append({ 'type': tier['type'], 'period': tier['period'], 'limit': tier['link_limit'], 'rate': tier['recurring_amount'], 'next_payment': tier['next_payment'], 'required_fields': required_fields, 'encrypted_data': prep_for_perma_payments(required_fields).decode('utf-8') }) return { 'customer': self, 'subscription': subscription, 'tiers': tiers, 'can_change_tiers': any(tier['type'] in ['upgrade', 'downgrade', 'cancel_downgrade'] for tier in tiers) } def credit_for_purchased_links(self, purchases): credited_link_count = 0 for purchase in purchases: try: with transaction.atomic(): link_quantity = int(purchase["link_quantity"]) self.bonus_links = (self.bonus_links or 0) + link_quantity self.save(update_fields=['bonus_links']) try: r = requests.post( settings.ACKNOWLEDGE_PURCHASE_URL, data={ 'encrypted_data': prep_for_perma_payments({ 'timestamp': datetime.utcnow().timestamp(), 'purchase_pk': purchase['id'] }) } ) assert r.ok, r.status_code except (requests.RequestException, AssertionError) as e: msg = "Communication with Perma-Payments failed: {}".format(str(e)) logger.error(msg) raise PermaPaymentsCommunicationException(msg) credited_link_count += link_quantity except PermaPaymentsCommunicationException: # I think we want the function to return even if it fails... # We'll be notified via the error message, and the calling # can do its best to proceed... having failed to credit the user # for their links. (Presumably, the customer will also complain if failure persists.) pass return credited_link_count def get_bonus_packages(self): bonus_packages = [] for package in settings.BONUS_PACKAGES: required_fields = { 'timestamp': datetime.utcnow().timestamp(), 'customer_pk': self.pk, 'customer_type': self.customer_type, 'amount': package['price'], 'link_quantity': package['link_quantity'] } bonus_packages.append({ 'amount': required_fields['amount'], 'link_quantity': required_fields['link_quantity'], 'unit_cost': float(required_fields['amount']) / int(required_fields['link_quantity']), 'encrypted_data': prep_for_perma_payments(required_fields).decode('utf-8') }) return bonus_packages @cached_property def subscription_status(self): try: subscription = self.get_subscription() except PermaPaymentsCommunicationException: subscription = { 'status': self.cached_subscription_status, 'paid_through': self.cached_paid_through } if subscription_is_active(subscription): return 'active' if subscription_has_problem(subscription): return 'problem' return None def link_creation_allowed(self): """ Must be implemented by children """ raise NotImplementedError ### MODELS ### class RegistrarQuerySet(QuerySet): def approved(self): return self.filter(status="approved") class Registrar(CustomerModel): """ This is a library, a court, a firm, or similar. """ name = models.CharField(max_length=400) email = models.EmailField(max_length=254) website = models.URLField(max_length=500) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=20, default='pending', choices=(('pending','pending'),('approved','approved'),('denied','denied'))) orgs_private_by_default = models.BooleanField(default=False, help_text="Whether new orgs created for this registrar default to private links.") show_partner_status = models.BooleanField(default=False, help_text="Whether to show this registrar in our list of partners.") partner_display_name = models.CharField(max_length=400, blank=True, null=True, help_text="Optional. Use this to override 'name' for the partner list.") logo = models.ImageField(upload_to='registrar_logos', blank=True, null=True) address = models.CharField(max_length=500, blank=True, null=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) link_count = models.IntegerField(default=0) # A cache of the number of links under this registrars's purview (sum of all associated org links) objects = RegistrarQuerySet.as_manager() tracker = FieldTracker() history = HistoricalRecords() tags = TaggableManager(blank=True) class Meta: ordering = ['name'] def __str__(self): return self.name def save(self, *args, **kwargs): name_has_changed = self.tracker.has_changed('name') super(Registrar, self).save(*args, **kwargs) if name_has_changed: # Rename top-level sponsored folders if registrar name changes. folders = Folder.objects.filter(sponsored_by=self, parent__is_sponsored_root_folder=True) folders.update(name=self.name) def link_count_in_time_period(self, start_time=None, end_time=None): links = Link.objects.filter(organization__registrar=self) return link_count_in_time_period(links, start_time, end_time) def link_count_this_year(self): return self.link_count_in_time_period(tz_datetime(timezone.now().year, 1, 1)) def most_active_org_in_time_period(self, start_time=None, end_time=None): return most_active_org_in_time_period(self.organizations, start_time, end_time) def most_active_org_this_year(self): return most_active_org_in_time_period(self.organizations, tz_datetime(timezone.now().year, 1, 1)) def active_registrar_users(self): return self.users.filter(is_active=True) def link_creation_allowed(self): # No logic yet for handling paid Registrar customers with limits: # all paid-up Registrar customers get unlimited links. assert self.unlimited if self.nonpaying: return True if self.id in settings.SPECIAL_UNLIMITED_LINKS_FOR_REGISTRAR: return True return self.subscription_status == 'active' Registrar._meta.get_field('nonpaying').default = True Registrar._meta.get_field('unlimited').default = True Registrar._meta.get_field('base_rate').default = Decimal(settings.DEFAULT_BASE_RATE_REGISTRAR) class OrganizationQuerySet(QuerySet): def accessible_to(self, user): qset = self.user_access_filter(user) if qset is None: return self.none() else: return self.filter(qset) def user_access_filter(self, user): if user.is_organization_user: return Q(id__in=user.organizations.all()) elif user.is_registrar_user(): return Q(registrar_id=user.registrar_id) elif user.is_staff: return Q() # all else: return None OrganizationManager = DeletableManager.from_queryset(OrganizationQuerySet) class Organization(DeletableModel): """ This is generally a journal. """ name = models.CharField(max_length=400) registrar = models.ForeignKey(Registrar, null=True, related_name="organizations", on_delete=models.CASCADE) shared_folder = models.OneToOneField('Folder', blank=True, null=True, related_name="top_level_for_org", on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) default_to_private = models.BooleanField(default=False) link_count = models.IntegerField(default=0) # A cache of the number of links under this org's purview objects = OrganizationManager() tracker = FieldTracker() history = HistoricalRecords() class Meta: indexes = [ models.Index(fields=['user_deleted']), ] def save(self, *args, **kwargs): if not self.pk: self.default_to_private = self.registrar.orgs_private_by_default name_has_changed = self.tracker.has_changed('name') super(Organization, self).save(*args, **kwargs) if not self.shared_folder: # Make sure shared folder is created for each org. self.create_shared_folder() elif name_has_changed: # Rename shared folder if org name changes. self.shared_folder.name = self.name self.shared_folder.save() def __str__(self): return self.name def create_shared_folder(self): if self.shared_folder: return shared_folder = Folder(name=self.name, organization=self, is_shared_folder=True) shared_folder.save() self.shared_folder = shared_folder self.save() def link_count_in_time_period(self, start_time=None, end_time=None): links = Link.objects.filter(organization=self) return link_count_in_time_period(links, start_time, end_time) def link_count_this_year(self): return self.link_count_in_time_period(tz_datetime(timezone.now().year, 1, 1)) def accessible_to(self, user): if user.is_staff: return True if user.is_registrar_user(): return self.registrar_id == user.registrar_id return self.users.filter(pk=user.pk).exists() class Sponsorship(models.Model): registrar = models.ForeignKey(Registrar, on_delete=models.PROTECT, related_name='sponsorships') user = models.ForeignKey('LinkUser', on_delete=models.CASCADE, related_name='sponsorships') status = models.CharField(max_length=10, blank=True, null=True, choices=(('active','Active: user may create links.'), ('inactive', 'Inactive: user may view, but not create, links.')), default='active') status_changed = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey('LinkUser', related_name='created_sponsorships', on_delete=models.PROTECT) class Meta: constraints = [ models.UniqueConstraint(fields=['registrar', 'user'], name='unique_sponsorship'), ] tracker = FieldTracker() def save(self, *args, **kwargs): status_changed = self.tracker.has_changed('status') super().save(*args, **kwargs) if not self.folders: self.user.create_sponsored_folder(self.registrar) if status_changed: self.folders.update(read_only=self.status == 'inactive') @property def folders(self): return Folder.objects.filter(owned_by=self.user, sponsored_by=self.registrar) class LinkUserManager(BaseUserManager): def create_user(self, email, registrar, organization, date_joined, first_name, last_name, authorized_by, password=None): """ Creates and saves a User with the given email, registrar and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), registrar=registrar, date_joined = date_joined, first_name = first_name, last_name = last_name, authorized_by = authorized_by, ) user.set_password(password) user.save() user.organizations.add(organization) user.save() user.create_root_folder() return user # This is a temporary workaround for the problem described in # https://github.com/jazzband/django-model-utils/issues/331#issuecomment-478994563 # where django-model-utils FieldTracker breaks the setter for overridden attributes on abstract base classes del AbstractBaseUser.is_active class LinkUser(CustomerModel, AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, db_index=True, error_messages={'unique': u"A user with that email address already exists.",} ) registrar = models.ForeignKey(Registrar, blank=True, null=True, related_name='users', help_text="If set, this user is a registrar user. This should not be set if org is set!", on_delete=models.CASCADE) pending_registrar = models.ForeignKey(Registrar, blank=True, null=True, related_name='pending_users', on_delete=models.CASCADE) organizations = models.ManyToManyField(Organization, blank=True, related_name='users', help_text="If set, this user is an org user. This should not be set if registrar is set!<br><br>" "Note: <b>This list will include deleted orgs of which this user is a member.</b> This is a historical" " record and deleted org memberships cannot be removed.<br><br>" ) sponsoring_registrars = models.ManyToManyField( Registrar, blank=True, related_name='sponsored_users', through=Sponsorship, through_fields=('user', 'registrar'), help_text="If set, this user is sponsored by a registrar. Any user can be sponsored by any registrar." ) is_active = models.BooleanField(default=False) is_confirmed = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=45, blank=True) last_name = models.CharField(max_length=45, blank=True) root_folder = models.OneToOneField('Folder', blank=True, null=True, on_delete=models.CASCADE) sponsored_root_folder = models.OneToOneField('Folder', blank=True, null=True, on_delete=models.CASCADE, related_name='sponsored_user') requested_account_type = models.CharField(max_length=45, blank=True, null=True) requested_account_note = models.CharField(max_length=45, blank=True, null=True) link_count = models.IntegerField(default=0) # A cache of the number of links created by this user notes = models.TextField(blank=True) objects = LinkUserManager() tracker = FieldTracker() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = 'User' def save(self, *args, **kwargs): super(LinkUser, self).save(*args, **kwargs) # make sure root folder is created for each user. if not self.root_folder: self.create_root_folder() def get_full_name(self): """ Use either First
c.PDFExporter.latex_count = 3 # # c.PDFExporter.jinja_logic_block_end = '*))' # Shell command used to compile latex. # c.PDFExporter.latex_command = [u'pdflatex', u'{filename}'] # ------------------------------------------------------------------------------ # PythonExporter configuration # ------------------------------------------------------------------------------ # Exports a Python code file. # PythonExporter will inherit config from: TemplateExporter, Exporter # # c.PythonExporter.jinja_variable_block_start = '' # # c.PythonExporter.jinja_variable_block_end = '' # formats of raw cells to be included in this Exporter's output. # c.PythonExporter.raw_mimetypes = [] # Name of the template file to use # c.PythonExporter.template_file = u'default' # List of preprocessors available by default, by name, namespace, instance, or # type. # c.PythonExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] # # c.PythonExporter.template_path = ['.'] # Extension of the file that should be written to disk # c.PythonExporter.file_extension = '.txt' # # c.PythonExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.PythonExporter.filters = {} # # c.PythonExporter.jinja_comment_block_start = '' # # c.PythonExporter.jinja_logic_block_end = '' # # c.PythonExporter.jinja_logic_block_start = '' # # c.PythonExporter.template_extension = '.tpl' # List of preprocessors, by name or namespace, to enable. # c.PythonExporter.preprocessors = [] # ------------------------------------------------------------------------------ # RSTExporter configuration # ------------------------------------------------------------------------------ # Exports restructured text documents. # RSTExporter will inherit config from: TemplateExporter, Exporter # # c.RSTExporter.jinja_variable_block_start = '' # # c.RSTExporter.jinja_variable_block_end = '' # formats of raw cells to be included in this Exporter's output. # c.RSTExporter.raw_mimetypes = [] # Name of the template file to use # c.RSTExporter.template_file = u'default' # List of preprocessors available by default, by name, namespace, instance, or # type. # c.RSTExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] # # c.RSTExporter.template_path = ['.'] # Extension of the file that should be written to disk # c.RSTExporter.file_extension = '.txt' # # c.RSTExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.RSTExporter.filters = {} # # c.RSTExporter.jinja_comment_block_start = '' # # c.RSTExporter.jinja_logic_block_end = '' # # c.RSTExporter.jinja_logic_block_start = '' # # c.RSTExporter.template_extension = '.tpl' # List of preprocessors, by name or namespace, to enable. # c.RSTExporter.preprocessors = [] # ------------------------------------------------------------------------------ # SlidesExporter configuration # ------------------------------------------------------------------------------ # Exports HTML slides with reveal.js # SlidesExporter will inherit config from: HTMLExporter, TemplateExporter, # Exporter # # c.SlidesExporter.jinja_variable_block_start = '' # # c.SlidesExporter.jinja_variable_block_end = '' # formats of raw cells to be included in this Exporter's output. # c.SlidesExporter.raw_mimetypes = [] # Name of the template file to use # c.SlidesExporter.template_file = u'default' # List of preprocessors available by default, by name, namespace, instance, or # type. # c.SlidesExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] # # c.SlidesExporter.template_path = ['.'] # Extension of the file that should be written to disk # c.SlidesExporter.file_extension = '.txt' # # c.SlidesExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.SlidesExporter.filters = {} # # c.SlidesExporter.jinja_comment_block_start = '' # # c.SlidesExporter.jinja_logic_block_end = '' # # c.SlidesExporter.jinja_logic_block_start = '' # # c.SlidesExporter.template_extension = '.tpl' # List of preprocessors, by name or namespace, to enable. # c.SlidesExporter.preprocessors = [] # ------------------------------------------------------------------------------ # TemplateExporter configuration # ------------------------------------------------------------------------------ # Exports notebooks into other file formats. Uses Jinja 2 templating engine to # output new formats. Inherit from this class if you are creating a new # template type along with new filters/preprocessors. If the filters/ # preprocessors provided by default suffice, there is no need to inherit from # this class. Instead, override the template_file and file_extension traits via # a config file. # # - citation2latex - highlight2html - filter_data_type - markdown2html - # markdown2rst - get_lines - ansi2latex - strip_ansi - add_prompts - # comment_lines - ascii_only - markdown2latex - escape_latex - add_anchor - # ipython2python - posix_path - highlight2latex - path2url - prevent_list_blocks # - ansi2html - wrap_text - indent - strip_dollars - html2text - # strip_files_prefix # TemplateExporter will inherit config from: Exporter # # c.TemplateExporter.jinja_variable_block_start = '' # # c.TemplateExporter.jinja_variable_block_end = '' # formats of raw cells to be included in this Exporter's output. # c.TemplateExporter.raw_mimetypes = [] # Name of the template file to use # c.TemplateExporter.template_file = u'default' # List of preprocessors available by default, by name, namespace, instance, or # type. # c.TemplateExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] # # c.TemplateExporter.template_path = ['.'] # Extension of the file that should be written to disk # c.TemplateExporter.file_extension = '.txt' # # c.TemplateExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.TemplateExporter.filters = {} # # c.TemplateExporter.jinja_comment_block_start = '' # # c.TemplateExporter.jinja_logic_block_end = '' # # c.TemplateExporter.jinja_logic_block_start = '' # # c.TemplateExporter.template_extension = '.tpl' # List of preprocessors, by name or namespace, to enable. # c.TemplateExporter.preprocessors = [] # ------------------------------------------------------------------------------ # CSSHTMLHeaderPreprocessor configuration # ------------------------------------------------------------------------------ # Preprocessor used to pre-process notebook for HTML output. Adds IPython # notebook front-end CSS and Pygments CSS to HTML output. # CSSHTMLHeaderPreprocessor will inherit config from: Preprocessor, # NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.CSSHTMLHeaderPreprocessor.default_language = 'ipython' # CSS highlight class identifier # c.CSSHTMLHeaderPreprocessor.highlight_class = '.highlight' # # c.CSSHTMLHeaderPreprocessor.enabled = False # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.CSSHTMLHeaderPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # ------------------------------------------------------------------------------ # ClearOutputPreprocessor configuration # ------------------------------------------------------------------------------ # Removes the output from all code cells in a notebook. # ClearOutputPreprocessor will inherit config from: Preprocessor, NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.ClearOutputPreprocessor.default_language = 'ipython' # # c.ClearOutputPreprocessor.enabled = False # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.ClearOutputPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # ------------------------------------------------------------------------------ # ConvertFiguresPreprocessor configuration # ------------------------------------------------------------------------------ # Converts all of the outputs in a notebook from one format to another. # ConvertFiguresPreprocessor will inherit config from: Preprocessor, # NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.ConvertFiguresPreprocessor.default_language = 'ipython' # Format the converter writes # c.ConvertFiguresPreprocessor.to_format = u'' # # c.ConvertFiguresPreprocessor.enabled = False # Format the converter accepts # c.ConvertFiguresPreprocessor.from_format = u'' # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.ConvertFiguresPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # ------------------------------------------------------------------------------ # ExecutePreprocessor configuration # ------------------------------------------------------------------------------ # Executes all the cells in a notebook # ExecutePreprocessor will inherit config from: Preprocessor, NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.ExecutePreprocessor.default_language = 'ipython' # If execution of a cell times out, interrupt the kernel and continue executing # other cells rather than throwing an error and stopping. # c.ExecutePreprocessor.interrupt_on_timeout = False # # c.ExecutePreprocessor.enabled = False # The time to wait (in seconds) for output from executions. # c.ExecutePreprocessor.timeout = 30 # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.ExecutePreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # ------------------------------------------------------------------------------ # ExtractOutputPreprocessor configuration # ------------------------------------------------------------------------------ # Extracts all of the outputs from the notebook file. The extracted outputs # are returned in the 'resources' dictionary. # ExtractOutputPreprocessor will inherit config from: Preprocessor, # NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.ExtractOutputPreprocessor.default_language = 'ipython' # # c.ExtractOutputPreprocessor.output_filename_template = '{unique_key}_{cell_index}_{index}{extension}' # # c.ExtractOutputPreprocessor.extract_output_types = set(['image/png', 'application/pdf', 'image/jpeg', 'image/svg+xml']) # # c.ExtractOutputPreprocessor.enabled = False # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.ExtractOutputPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # ------------------------------------------------------------------------------ # HighlightMagicsPreprocessor configuration # ------------------------------------------------------------------------------ # Detects and tags code cells that use a different languages than Python. # HighlightMagicsPreprocessor will inherit config from: Preprocessor, # NbConvertBase # Syntax highlighting for magic's extension languages. Each item associates a # language magic extension such as %%R, with a pygments lexer such as r. # c.HighlightMagicsPreprocessor.languages = {} # # c.HighlightMagicsPreprocessor.enabled = False # DEPRECATED default highlight language, please use language_info metadata # instead # c.HighlightMagicsPreprocessor.default_language = 'ipython' # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.HighlightMagicsPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # ------------------------------------------------------------------------------ # LatexPreprocessor configuration # ------------------------------------------------------------------------------ # Preprocessor for latex destined documents. # # Mainly populates the `latex` key in the resources dict, adding definitions for # pygments highlight styles. # LatexPreprocessor will inherit config from: Preprocessor, NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.LatexPreprocessor.default_language = 'ipython' # # c.LatexPreprocessor.enabled = False # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.LatexPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # ------------------------------------------------------------------------------ # Preprocessor configuration # ------------------------------------------------------------------------------ # A configurable preprocessor # # Inherit from this class if you wish to have configurability for your # preprocessor. # # Any configurable traitlets this class exposed will be configurable in profiles # using c.SubClassName.attribute = value # # you can overwrite :meth:`preprocess_cell` to apply a transformation # independently on each cell or :meth:`preprocess` if you prefer your own logic. # See corresponding docstring for informations. # # Disabled by default and can be enabled via the config by # 'c.YourPreprocessorName.enabled = True' # Preprocessor will inherit config
# coding: utf-8 """ Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST API documentation you must add the header \"Authorization: Bearer &lt;&lt;API-TOKEN&gt;&gt;\" to your HTTP requests.</p> # noqa: E501 OpenAPI spec version: v2 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from wavefront_api_client.models.user_group import UserGroup # noqa: F401,E501 class CustomerPreferences(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'blacklisted_emails': 'dict(str, int)', 'created_epoch_millis': 'int', 'creator_id': 'str', 'customer_id': 'str', 'default_user_groups': 'list[UserGroup]', 'deleted': 'bool', 'grant_modify_access_to_everyone': 'bool', 'hidden_metric_prefixes': 'dict(str, int)', 'hide_ts_when_querybuilder_shown': 'bool', 'id': 'str', 'invite_permissions': 'list[str]', 'landing_dashboard_slug': 'str', 'show_onboarding': 'bool', 'show_querybuilder_by_default': 'bool', 'updated_epoch_millis': 'int', 'updater_id': 'str' } attribute_map = { 'blacklisted_emails': 'blacklistedEmails', 'created_epoch_millis': 'createdEpochMillis', 'creator_id': 'creatorId', 'customer_id': 'customerId', 'default_user_groups': 'defaultUserGroups', 'deleted': 'deleted', 'grant_modify_access_to_everyone': 'grantModifyAccessToEveryone', 'hidden_metric_prefixes': 'hiddenMetricPrefixes', 'hide_ts_when_querybuilder_shown': 'hideTSWhenQuerybuilderShown', 'id': 'id', 'invite_permissions': 'invitePermissions', 'landing_dashboard_slug': 'landingDashboardSlug', 'show_onboarding': 'showOnboarding', 'show_querybuilder_by_default': 'showQuerybuilderByDefault', 'updated_epoch_millis': 'updatedEpochMillis', 'updater_id': 'updaterId' } def __init__(self, blacklisted_emails=None, created_epoch_millis=None, creator_id=None, customer_id=None, default_user_groups=None, deleted=None, grant_modify_access_to_everyone=None, hidden_metric_prefixes=None, hide_ts_when_querybuilder_shown=None, id=None, invite_permissions=None, landing_dashboard_slug=None, show_onboarding=None, show_querybuilder_by_default=None, updated_epoch_millis=None, updater_id=None): # noqa: E501 """CustomerPreferences - a model defined in Swagger""" # noqa: E501 self._blacklisted_emails = None self._created_epoch_millis = None self._creator_id = None self._customer_id = None self._default_user_groups = None self._deleted = None self._grant_modify_access_to_everyone = None self._hidden_metric_prefixes = None self._hide_ts_when_querybuilder_shown = None self._id = None self._invite_permissions = None self._landing_dashboard_slug = None self._show_onboarding = None self._show_querybuilder_by_default = None self._updated_epoch_millis = None self._updater_id = None self.discriminator = None if blacklisted_emails is not None: self.blacklisted_emails = blacklisted_emails if created_epoch_millis is not None: self.created_epoch_millis = created_epoch_millis if creator_id is not None: self.creator_id = creator_id self.customer_id = customer_id if default_user_groups is not None: self.default_user_groups = default_user_groups if deleted is not None: self.deleted = deleted self.grant_modify_access_to_everyone = grant_modify_access_to_everyone if hidden_metric_prefixes is not None: self.hidden_metric_prefixes = hidden_metric_prefixes self.hide_ts_when_querybuilder_shown = hide_ts_when_querybuilder_shown if id is not None: self.id = id if invite_permissions is not None: self.invite_permissions = invite_permissions if landing_dashboard_slug is not None: self.landing_dashboard_slug = landing_dashboard_slug self.show_onboarding = show_onboarding self.show_querybuilder_by_default = show_querybuilder_by_default if updated_epoch_millis is not None: self.updated_epoch_millis = updated_epoch_millis if updater_id is not None: self.updater_id = updater_id @property def blacklisted_emails(self): """Gets the blacklisted_emails of this CustomerPreferences. # noqa: E501 List of blacklisted emails of the customer # noqa: E501 :return: The blacklisted_emails of this CustomerPreferences. # noqa: E501 :rtype: dict(str, int) """ return self._blacklisted_emails @blacklisted_emails.setter def blacklisted_emails(self, blacklisted_emails): """Sets the blacklisted_emails of this CustomerPreferences. List of blacklisted emails of the customer # noqa: E501 :param blacklisted_emails: The blacklisted_emails of this CustomerPreferences. # noqa: E501 :type: dict(str, int) """ self._blacklisted_emails = blacklisted_emails @property def created_epoch_millis(self): """Gets the created_epoch_millis of this CustomerPreferences. # noqa: E501 :return: The created_epoch_millis of this CustomerPreferences. # noqa: E501 :rtype: int """ return self._created_epoch_millis @created_epoch_millis.setter def created_epoch_millis(self, created_epoch_millis): """Sets the created_epoch_millis of this CustomerPreferences. :param created_epoch_millis: The created_epoch_millis of this CustomerPreferences. # noqa: E501 :type: int """ self._created_epoch_millis = created_epoch_millis @property def creator_id(self): """Gets the creator_id of this CustomerPreferences. # noqa: E501 :return: The creator_id of this CustomerPreferences. # noqa: E501 :rtype: str """ return self._creator_id @creator_id.setter def creator_id(self, creator_id): """Sets the creator_id of this CustomerPreferences. :param creator_id: The creator_id of this CustomerPreferences. # noqa: E501 :type: str """ self._creator_id = creator_id @property def customer_id(self): """Gets the customer_id of this CustomerPreferences. # noqa: E501 The id of the customer preferences are attached to # noqa: E501 :return: The customer_id of this CustomerPreferences. # noqa: E501 :rtype: str """ return self._customer_id @customer_id.setter def customer_id(self, customer_id): """Sets the customer_id of this CustomerPreferences. The id of the customer preferences are attached to # noqa: E501 :param customer_id: The customer_id of this CustomerPreferences. # noqa: E501 :type: str """ if customer_id is None: raise ValueError("Invalid value for `customer_id`, must not be `None`") # noqa: E501 self._customer_id = customer_id @property def default_user_groups(self): """Gets the default_user_groups of this CustomerPreferences. # noqa: E501 List of default user groups of the customer # noqa: E501 :return: The default_user_groups of this CustomerPreferences. # noqa: E501 :rtype: list[UserGroup] """ return self._default_user_groups @default_user_groups.setter def default_user_groups(self, default_user_groups): """Sets the default_user_groups of this CustomerPreferences. List of default user groups of the customer # noqa: E501 :param default_user_groups: The default_user_groups of this CustomerPreferences. # noqa: E501 :type: list[UserGroup] """ self._default_user_groups = default_user_groups @property def deleted(self): """Gets the deleted of this CustomerPreferences. # noqa: E501 :return: The deleted of this CustomerPreferences. # noqa: E501 :rtype: bool """ return self._deleted @deleted.setter def deleted(self, deleted): """Sets the deleted of this CustomerPreferences. :param deleted: The deleted of this CustomerPreferences. # noqa: E501 :type: bool """ self._deleted = deleted @property def grant_modify_access_to_everyone(self): """Gets the grant_modify_access_to_everyone of this CustomerPreferences. # noqa: E501 Whether modify access of new entites is granted to Everyone or to the Creator # noqa: E501 :return: The grant_modify_access_to_everyone of this CustomerPreferences. # noqa: E501 :rtype: bool """ return self._grant_modify_access_to_everyone @grant_modify_access_to_everyone.setter def grant_modify_access_to_everyone(self, grant_modify_access_to_everyone): """Sets the grant_modify_access_to_everyone of this CustomerPreferences. Whether modify access of new entites is granted to Everyone or to the Creator # noqa: E501 :param grant_modify_access_to_everyone: The grant_modify_access_to_everyone of this CustomerPreferences. # noqa: E501 :type: bool """ if grant_modify_access_to_everyone is None: raise ValueError("Invalid value for `grant_modify_access_to_everyone`, must not be `None`") # noqa: E501 self._grant_modify_access_to_everyone = grant_modify_access_to_everyone @property def hidden_metric_prefixes(self): """Gets the hidden_metric_prefixes of this CustomerPreferences. # noqa: E501 Metric prefixes which should be hidden from user # noqa: E501 :return: The hidden_metric_prefixes of this CustomerPreferences. # noqa: E501 :rtype: dict(str, int) """ return self._hidden_metric_prefixes @hidden_metric_prefixes.setter def hidden_metric_prefixes(self, hidden_metric_prefixes): """Sets the hidden_metric_prefixes of this CustomerPreferences. Metric prefixes which should be hidden from user # noqa: E501 :param hidden_metric_prefixes: The hidden_metric_prefixes of this CustomerPreferences. # noqa: E501 :type: dict(str, int) """ self._hidden_metric_prefixes = hidden_metric_prefixes @property def hide_ts_when_querybuilder_shown(self): """Gets the hide_ts_when_querybuilder_shown of this CustomerPreferences. # noqa: E501 Whether to hide TS source input when Querybuilder is shown # noqa: E501 :return: The hide_ts_when_querybuilder_shown of this CustomerPreferences. # noqa: E501 :rtype: bool """ return self._hide_ts_when_querybuilder_shown @hide_ts_when_querybuilder_shown.setter def hide_ts_when_querybuilder_shown(self, hide_ts_when_querybuilder_shown): """Sets the hide_ts_when_querybuilder_shown of this CustomerPreferences. Whether to hide TS source input when Querybuilder is shown # noqa: E501 :param hide_ts_when_querybuilder_shown: The hide_ts_when_querybuilder_shown of this CustomerPreferences. # noqa: E501 :type: bool """ if hide_ts_when_querybuilder_shown is None: raise ValueError("Invalid value for `hide_ts_when_querybuilder_shown`, must not be `None`") # noqa: E501 self._hide_ts_when_querybuilder_shown = hide_ts_when_querybuilder_shown @property def id(self): """Gets the id of this CustomerPreferences. # noqa: E501 :return: The id of this CustomerPreferences. # noqa: E501 :rtype: str """ return self._id @id.setter def id(self, id): """Sets the id of this CustomerPreferences. :param id: The id of this CustomerPreferences. # noqa: E501 :type: str """ self._id = id @property def invite_permissions(self): """Gets the invite_permissions of this CustomerPreferences. # noqa: E501 List of permissions that are assigned to newly invited users # noqa: E501 :return: The invite_permissions of this CustomerPreferences. # noqa: E501 :rtype: list[str] """ return self._invite_permissions @invite_permissions.setter def invite_permissions(self, invite_permissions): """Sets the invite_permissions of this CustomerPreferences. List of permissions that are assigned to newly invited users # noqa: E501 :param invite_permissions: The invite_permissions of this CustomerPreferences. # noqa: E501 :type: list[str] """ self._invite_permissions = invite_permissions @property def landing_dashboard_slug(self): """Gets the landing_dashboard_slug of this CustomerPreferences. # noqa: E501 Dashboard where user will be redirected from landing page # noqa: E501 :return: The landing_dashboard_slug of this CustomerPreferences. # noqa: E501 :rtype: str """ return self._landing_dashboard_slug @landing_dashboard_slug.setter def landing_dashboard_slug(self, landing_dashboard_slug): """Sets the landing_dashboard_slug of this CustomerPreferences. Dashboard where user will be redirected from landing page # noqa: E501 :param landing_dashboard_slug: The landing_dashboard_slug of this CustomerPreferences. # noqa: E501 :type: str """ self._landing_dashboard_slug = landing_dashboard_slug @property def show_onboarding(self): """Gets the show_onboarding of this CustomerPreferences. # noqa:
"LSZR" : "ACH", "LSZT" : "", "KUOS" : "", "LSZH" : "ZRH", "LSZK" : "", "LSZJ" : "", "KLUF" : "LUF", "LSZL" : "ZJI", "LSZA" : "LUG", "KLUK" : "LUK", "LSZC" : "BXO", "LSZB" : "BRN", "LSZG" : "", "LSZF" : "", "UMOO" : "MVQ", "KBMI" : "BMI", "SNOX" : "ORX", "YMNE" : "WME", "RJKI" : "KKX", "RJKN" : "TKN", "RJKA" : "ASJ", "RJKB" : "", "PHDH" : "HDH", "NZWF" : "WKA", "DTKA" : "TBJ", "CZWL" : "ZWL", "VNSB" : "SYH", "CZWH" : "XLB", "VNSI" : "SIF", "MRGP" : "", "VNSK" : "SKH", "MYER" : "RSD", "MYEH" : "ELH", "MYEM" : "GHB", "VNST" : "IMK", "MYEN" : "", "MYEG" : "", "MYEF" : "GGT", "UHHK" : "", "UATG" : "GUW", "UHHH" : "KHV", "SWLB" : "LBR", "SWLC" : "RVD", "KFYV" : "FYV", "KAKR" : "AKC", "UATT" : "AKX", "FALI" : "", "OPJA" : "", "EFSO" : "SOT", "SYLT" : "LTM", "OPJI" : "JIW", "SBAA" : "CDJ", "GECT" : "JCU", "OIAA" : "ABD", "FZBI" : "NIO", "ULDD" : "AMV", "SBAN" : "", "KBOI" : "BOI", "YBNS" : "BSJ", "OIAD" : "", "ZBYC" : "YCU", "YBNA" : "BNK", "ZBYN" : "TYN", "FZBA" : "INO", "MHLC" : "LCE", "NFO" : "Tonga", "WA19" : "", "BLF" : "BLF", "YOLD" : "OLP", "SVGU" : "GUQ", "EVLA" : "LPX", "SVGI" : "GUI", "SVGD" : "", "BGNN" : "JNN", "ZGOW" : "SWA", "BGNS" : "JNS", "YPAG" : "PUG", "SWOB" : "FBA", "YPAM" : "PMK", "GMMI" : "ESU", "GMMH" : "VIL", "GMMN" : "CMN", "GMML" : "EUN", "GMMB" : "", "GMMA" : "SMW", "LEPP" : "PNA", "GMME" : "RBA", "LJPZ" : "POW", "GMMZ" : "OZZ", "GMMY" : "NNA", "GMMX" : "RAK", "SMCO" : "TOT", "GMMW" : "NDR", "ZUAL" : "NGQ", "VDSR" : "REP", "KCRP" : "CRP", "KCRQ" : "CLD", "KCRW" : "CRW", "KHND" : "HSH", "OENG" : "EAM", "TQPF" : "AXA", "FSPP" : "PRI", "EDWG" : "AGE", "MREC" : "", "LKRO" : "", "OG39" : "", "EDWL" : "LGO", "VTPP" : "PHS", "PABT" : "BTT", "PABR" : "BRW", "VTPT" : "TKT", "VTPY" : "", "VTPB" : "PHY", "PABE" : "BET", "PABA" : "BTI", "LOLW" : "", "PABM" : "BMX", "KBPT" : "BPT", "VTPN" : "", "VTPO" : "THS", "VTPL" : "", "VTPM" : "MAQ", "AYKK" : "KRI", "AYKI" : "UNG", "AYKM" : "KMA", "EDWQ" : "", "KPTB" : "PTB", "KPTK" : "PTK", "AYKV" : "KVG", "ENLI" : "FAN", "SCVM" : "", "ENLK" : "LKN", "HTBU" : "BKZ", "UDSG" : "LWN", "SCVD" : "ZAL", "KELM" : "ELM", "KELO" : "LYU", "MNCI" : "RNI", "EGHD" : "PLH", "KELP" : "ELP", "EGHA" : "", "EGHC" : "LEQ", "DABS" : "TEE", "EGHN" : "", "EGHH" : "BOH", "KELY" : "ELY", "EGHJ" : "BBP", "DABT" : "BLJ", "ZPZT" : "ZAT", "AYMN" : "MDU", "DENX" : "", "MBGT" : "GDT", "GATS" : "", "GATB" : "TOM", "BPAP" : "", "EBCI" : "CRL", "KSZL" : "SZL", "LGNX" : "JNX", "FZKA" : "BUX", "UWGG" : "GOJ", "UIIB" : "", "UIII" : "IKT", "UIIR" : "", "VGTJ" : "", "SBMQ" : "MCP", "SBMS" : "", "SBMT" : "", "SBMW" : "MVF", "SBMY" : "MNX", "EFOU" : "OUL", "SBMA" : "MAB", "SBMC" : "MQH", "SBMD" : "", "SBME" : "MEA", "SBMG" : "MGF", "SBMK" : "MOC", "SBML" : "MII", "SBMN" : "", "SBMO" : "MCZ", "ZSNJ" : "NKG", "MNMG" : "MGA", "ZSNB" : "NGB", "EKLS" : "", "KUNV" : "SCE", "ETAR" : "RMS", "KVEL" : "VEL", "ETAD" : "SPM", "KMTC" : "MTC", "KMTN" : "MTN", "KMTH" : "MTH", "KMTJ" : "MTJ", "SEAM" : "ATF", "FGRS" : "", "FQUG" : "", "SKNV" : "NVA", "EGVA" : "FFD", "SKNQ" : "NQU", "KRIU" : "RIU", "KRIV" : "RIV", "KRIW" : "RIW", "KRIR" : "RIR", "KRID" : "RID", "KRIF" : "RIF", "KRIC" : "RIC", "KRIL" : "RIL", "TJIG" : "SIG", "UNEE" : "KEJ", "VERC" : "IXR", "VERK" : "RRK", "YKMB" : "KRB", "IRUF" : "IRU", "UTOD" : "", "SNIG" : "", "FNLB" : "", "FNLU" : "LAD", "KHQU" : "HQU", "KLSV" : "LSV", "KUIN" : "UIN", "KLSE" : "LSE", "KLSF" : "LSF", "UMMS" : "MSQ", "UMMG" : "GNA", "UMMB" : "", "UMMM" : "MHP", "KCOE" : "COE", "VRMO" : "GKK", "YGFN" : "GFN", "K4A7" : "4A7", "MTJE" : "JEE", "MTJA" : "", "DTMB" : "MIR", "MGPB" : "PBR", "LGLE" : "LRS", "KAMA" : "AMA", "PFAL" : "AET", "FEFF" : "BGF", "SWBR" : "RBB", "HDOB" : "OBC", "FEFT" : "BBT", "LGSO" : "JSY", "MPOA" : "PUE", "LSGE" : "", "UKKV" : "ZTR", "DAFI" : "QDJ", "KOSH" : "OSH", "OJAQ" : "AQJ", "KOSC" : "OSC", "OJAI" : "AMM", "OJAM" : "ADJ", "OMSJ" : "SHJ", "KOSU" : "OSU", "TIST" : "STT", "TISX" : "STX", "YYMI" : "XMY", "KIJD" : "IJD", "SVAC" : "AGV", "NTTR" : "RFP", "LGHL" : "PKH", "SVAN" : "AAO", "YPCC" : "CCK", "SVAT" : "", "YPCE" : "", "LEVX" : "VGO", "LEVS" : "", "LEVT" : "VIT", "YBLT" : "", "LQBK" : "BNX", "LEVD" : "VLL", "MDHE" : "HEX", "WKBR" : "", "LLNV" : "", "ZUCK" : "CKG", "SBFT" : "", "KNPA" : "NPA", "ENGM" : "OSL", "SBPF" : "PFB", "SBPC" : "POO", "SBPB" : "", "SBPA" : "POA", "SBPN" : "PNB", "SBPL" : "PNZ", "SBPK" : "PET", "SBPJ" : "PMW", "KHLN" : "HLN", "SBPV" : "PVH", "KHLR" : "HLR", "SBPS" : "BPS", "SBPP" : "PMG", "SIAM" : "MSI", "MRCR" : "RIK", "MRCV" : "TNO", "KCZG" : "CZG", "MRCA" : "CSC", "MRCC" : "OTR", "MRCH" : "", "ZGMX" : "MXZ", "VVBM" : "BMV", "VNRK" : "RUK", "UESS" : "CYX", "UESU" : "ZKP", "UEST" : "IKS", "LRCL" : "CLJ", "LRCK" : "CND", "KBRD" : "BRD", "SERB" : "", "TLDO" : "", "UESK" : "", "KBRL" : "BRL", "KBRO" : "BRO", "UESO" : "CKH", "YWCA" : "WIO", "UUBS" : "KLF", "ENRS" : "RET", "KEND" : "END", "SCTB" : "", "SCTC" : "ZCO", "HADC" : "DSE", "KY72" : "", "HADD" : "DEM", "ENRY" : "RYG", "SCTE" : "PMC", "EGJB" : "GCI", "HTLM" : "LKY", "EGJA" : "ACI", "KENV" : "ENV", "HTLI" : "LDI", "ENRA" : "MQN", "ENRO" : "RRS", "ENRM" : "RVK", "HADR" : "DIR", "UODD" : "DKS", "HADT" : "DBT", "ENRI" : "", "YSOL" : "SLJ", "MUGT" : "GAO", "ZHYC" : "YIH", "MUGM" : "", "PFEL" : "ELI", "WAPP" : "AMQ", "ZABR" : "", "WAPL" : "LUV", "EBAW" : "ANR", "KDHT" : "DHT", "KJLN" : "JLN", "PKMA" : "ENT", "PKMJ" : "MAJ", "KDHN" : "DHN", "EIKN" : "NOC", "HRZA" : "KME", "VGRJ" : "RJH", "KWYS" : "WYS", "SBOI" : "", "CZEM" : "ZEM", "ZSLQ" : "HYN", "DNPO" : "PHC", "ZSLY" : "LYI", "HDTJ" : "TDJ", "ZSLG" : "LYG", "OPSK" : "SKZ", "MPDA" : "DAV", "OPSN" : "SYW", "YMYB" : "MBH", "KMVY" : "MVY", "OPSD" : "KDU", "LVGZ" : "GZA", "OPSS" : "SDT", "OPST" : "SKT", "OPSU" : "SUL", "KMVL" : "MVL", "RJAN" : "", "SKUL" : "ULQ", "SKLC" : "", "SKLG" : "LQM", "LWOH" : "OHD", "SKLP" : "LPD", "SKLT" : "LET", "Q51" : "KIO", "KRKS" : "RKS", "KRKP" : "RKP", "KRKD" : "RKD", "UNKL" : "KJA", "UNKM" : "", "EFME" : "", "UNKI" : "", "EFMA" : "MHQ", "EFMI" : "MIK", "SKUC" : "AUC", "YLEV" : "LEL", "KESN" : "ESN", "KESC" : "ESC", "YLEO" : "LNO", "FB57" : "", "YKOW" : "KWM", "KESF" : "ESF", "HESH" : "SSH", "HESN" : "ASW", "HESC" : "SKV", "FNNG" : "GXG", "SNKV" : "", "LDSB" : "BWK", "SWEI" : "ERN", "KGYR" : "", "UMKK" : "KGD", "SMZO" : "ORG", "KGYY" : "GYY", "CYAW" : "YAW", "CYAV" : "YAV", "CYAT" : "YAT", "CYAS" : "YKG", "MGRT" : "", "CYAZ" : "YAZ", "CYAY" : "YAY", "CYAX" : "", "CYAG" : "YAG", "KNOP" : "ONP", "CYAC" : "YAC", "KNOW" : "NOW", "CYAM" : "YAM", "VVTS" : "SGN", "DGAA" : "ACC", "RCTP" : "TPE", "YHID" : "HID", "KAOH" : "AOH", "LKKT" : "", "LKKU" : "", "KAOO" : "AOO", "EKSP" :
<reponame>artberryx/LSD import copy import pathlib import time import dowel_wrapper import akro import numpy as np import torch from PIL import Image from moviepy import editor as mpy from garage.envs import EnvSpec from garage.misc.tensor_utils import discount_cumsum from matplotlib import figure from matplotlib.patches import Ellipse from sklearn import decomposition class EnvSpecEx(EnvSpec): def __init__(self, observation_space, action_space, pure_observation_space, option_space, ): super().__init__(observation_space, action_space) self.pure_observation_space = pure_observation_space self.option_space = option_space def make_env_spec_for_option_policy(env_spec, num_option_params, use_option=True): option_space = None if use_option: option_space = akro.Box(low=-np.inf, high=np.inf, shape=(num_option_params,)) space = akro.concat(env_spec.observation_space, option_space) else: space = env_spec.observation_space new_spec = EnvSpecEx( action_space=env_spec.action_space, observation_space=space, pure_observation_space=env_spec.observation_space, option_space=option_space, ) return new_spec def get_torch_concat_obs(obs, option, dim=1): concat_obs = torch.cat([obs] + [option], dim=dim) return concat_obs def get_np_concat_obs(obs, option): concat_obs = np.concatenate([obs] + [option]) return concat_obs def get_normalizer_preset(normalizer_type): if normalizer_type == 'off': normalizer_mean = np.array([0.]) normalizer_std = np.array([1.]) elif normalizer_type == 'half_cheetah_preset': normalizer_mean = np.array( [-0.07861924, -0.08627162, 0.08968642, 0.00960849, 0.02950368, -0.00948337, 0.01661406, -0.05476654, -0.04932635, -0.08061652, -0.05205841, 0.04500197, 0.02638421, -0.04570961, 0.03183838, 0.01736591, 0.0091929, -0.0115027]) normalizer_std = np.array( [0.4039283, 0.07610687, 0.23817, 0.2515473, 0.2698137, 0.26374814, 0.32229397, 0.2896734, 0.2774097, 0.73060024, 0.77360505, 1.5871304, 5.5405455, 6.7097645, 6.8253727, 6.3142195, 6.417641, 5.9759197]) elif normalizer_type == 'ant_preset': normalizer_mean = np.array( [0.00486117, 0.011312, 0.7022248, 0.8454677, -0.00102548, -0.00300276, 0.00311523, -0.00139029, 0.8607109, -0.00185301, -0.8556998, 0.00343217, -0.8585605, -0.00109082, 0.8558013, 0.00278213, 0.00618173, -0.02584622, -0.00599026, -0.00379596, 0.00526138, -0.0059213, 0.27686235, 0.00512205, -0.27617684, -0.0033233, -0.2766923, 0.00268359, 0.27756855]) normalizer_std = np.array( [0.62473416, 0.61958003, 0.1717569, 0.28629342, 0.20020866, 0.20572574, 0.34922406, 0.40098143, 0.3114514, 0.4024826, 0.31057045, 0.40343934, 0.3110796, 0.40245822, 0.31100526, 0.81786263, 0.8166509, 0.9870919, 1.7525449, 1.7468817, 1.8596431, 4.502961, 4.4070187, 4.522444, 4.3518476, 4.5105968, 4.3704205, 4.5175962, 4.3704395]) elif normalizer_type == 'humanoid_preset': normalizer_mean = np.array( [-8.1131503e-02, -7.3915249e-04, 9.5715916e-01, 9.5207644e-01, 2.0175683e-03, -6.3051097e-02, -1.2828799e-02, -5.4687279e-04, -2.4450898e-01, 7.7590477e-03, -3.2982033e-02, -1.7136147e-02, -1.7263800e-01, -1.6152242e+00, -3.4986842e-02, -3.4458160e-02, -1.6019167e-01, -1.5958424e+00, 3.0278003e-01, -2.7908441e-01, -3.4809363e-01, -2.9139769e-01, 2.8643531e-01, -3.4040874e-01, -3.8491020e-01, 2.6394178e-05, -1.2304888e+00, 3.6492027e-02, -6.8305099e-01, -8.6309865e-02, 9.3602976e-03, -5.4201365e-01, 1.1908096e-02, -9.6945368e-02, -4.0906958e-02, -3.0476081e-01, -3.3397417e+00, -8.6432390e-02, -6.1523411e-02, -2.6818362e-01, -3.3175933e+00, 7.4578458e-01, -9.6735454e-01, -1.1773691e+00, -7.7269357e-01, 9.5517111e-01, -1.1721193e+00]) normalizer_std = np.array( [0.12630117, 0.09309318, 0.31789413, 0.07312579, 0.12920779, 0.21994449, 0.1426761, 0.18718153, 0.43414274, 0.32560128, 0.1282181, 0.23556797, 0.4009979, 0.97610635, 0.12872458, 0.23611404, 0.4062315, 0.9686742, 0.3580939, 0.42217487, 0.49625927, 0.3586807, 0.4218451, 0.50105387, 0.5517619, 0.43790612, 0.8357725, 1.3804333, 2.4758842, 2.2540345, 3.15485, 4.4246655, 2.8681147, 2.6601605, 3.5328803, 5.8904147, 6.434801, 2.6590736, 3.5234997, 5.899381, 6.412176, 2.5906591, 3.0781884, 3.3108664, 2.5866294, 3.0885093, 3.2871766]) return normalizer_mean, normalizer_std def get_2d_colors(points, min_point, max_point): points = np.array(points) min_point = np.array(min_point) max_point = np.array(max_point) colors = (points - min_point) / (max_point - min_point) colors = np.hstack(( colors, (2 - np.sum(colors, axis=1, keepdims=True)) / 2, )) colors = np.clip(colors, 0, 1) colors = np.c_[colors, np.full(len(colors), 0.8)] return colors def get_option_colors(options, color_range=4): num_options = options.shape[0] dim_option = options.shape[1] if dim_option <= 2: # Use a predefined option color scheme if dim_option == 1: options_2d = [] d = 2. for i in range(len(options)): option = options[i][0] if option < 0: abs_value = -option options_2d.append((d - abs_value * d, d)) else: abs_value = option options_2d.append((d, d - abs_value * d)) options = np.array(options_2d) # options = np.c_[options, options] option_colors = get_2d_colors(options, (-color_range, -color_range), (color_range, color_range)) else: if dim_option > 3 and num_options >= 3: pca = decomposition.PCA(n_components=3) # Add random noises to break symmetry. pca_options = np.vstack((options, np.random.randn(dim_option, dim_option))) pca.fit(pca_options) option_colors = np.array(pca.transform(options)) elif dim_option > 3 and num_options < 3: option_colors = options[:, :3] elif dim_option == 3: option_colors = options # max_colors = np.max(option_colors, axis=0) # min_colors = np.min(option_colors, axis=0) max_colors = np.array([color_range] * 3) min_colors = np.array([-color_range] * 3) if all((max_colors - min_colors) > 0): option_colors = (option_colors - min_colors) / (max_colors - min_colors) option_colors = np.clip(option_colors, 0, 1) option_colors = np.c_[option_colors, np.full(len(option_colors), 0.8)] return option_colors def draw_2d_gaussians(means, stddevs, colors, ax, fill=False, alpha=0.8, use_adaptive_axis=False, draw_unit_gaussian=True, plot_axis=None): means = np.clip(means, -1000, 1000) stddevs = np.clip(stddevs, -1000, 1000) square_axis_limit = 2.0 if draw_unit_gaussian: ellipse = Ellipse(xy=(0, 0), width=2, height=2, edgecolor='r', lw=1, facecolor='none', alpha=0.5) ax.add_patch(ellipse) for mean, stddev, color in zip(means, stddevs, colors): if len(mean) == 1: mean = np.concatenate([mean, [0.]]) stddev = np.concatenate([stddev, [0.1]]) ellipse = Ellipse(xy=mean, width=stddev[0] * 2, height=stddev[1] * 2, edgecolor=color, lw=1, facecolor='none' if not fill else color, alpha=alpha) ax.add_patch(ellipse) square_axis_limit = max( square_axis_limit, np.abs(mean[0] + stddev[0]), np.abs(mean[0] - stddev[0]), np.abs(mean[1] + stddev[1]), np.abs(mean[1] - stddev[1]), ) square_axis_limit = square_axis_limit * 1.2 ax.axis('scaled') if plot_axis is None: if use_adaptive_axis: ax.set_xlim(-square_axis_limit, square_axis_limit) ax.set_ylim(-square_axis_limit, square_axis_limit) else: ax.set_xlim(-5, 5) ax.set_ylim(-5, 5) else: ax.axis(plot_axis) def prepare_video(v, n_cols=None): orig_ndim = v.ndim if orig_ndim == 4: v = v[None, ] #b, t, c, h, w = v.shape _, t, c, h, w = v.shape if v.dtype == np.uint8: v = np.float32(v) / 255. def is_power2(num): return num != 0 and ((num & (num - 1)) == 0) # pad to nearest power of 2, all at once # if not is_power2(v.shape[0]): # len_addition = int(2**v.shape[0].bit_length() - v.shape[0]) # v = np.concatenate( # (v, np.zeros(shape=(len_addition, t, c, h, w))), axis=0) # n_rows = 2**((b.bit_length() - 1) // 2) if n_cols is None: if v.shape[0] <= 3: n_cols = v.shape[0] elif v.shape[0] <= 9: n_cols = 3 else: n_cols = 6 if v.shape[0] % n_cols != 0: len_addition = n_cols - v.shape[0] % n_cols v = np.concatenate( (v, np.zeros(shape=(len_addition, t, c, h, w))), axis=0) n_rows = v.shape[0] // n_cols v = np.reshape(v, newshape=(n_rows, n_cols, t, c, h, w)) v = np.transpose(v, axes=(2, 0, 4, 1, 5, 3)) v = np.reshape(v, newshape=(t, n_rows * h, n_cols * w, c)) return v def save_video(runner, label, tensor, fps=15, n_cols=None): def _to_uint8(t): # If user passes in uint8, then we don't need to rescale by 255 if t.dtype != np.uint8: t = (t * 255.0).astype(np.uint8) return t if tensor.dtype in [np.object]: tensor = [_to_uint8(prepare_video(t, n_cols)) for t in tensor] else: tensor = prepare_video(tensor, n_cols) tensor = _to_uint8(tensor) # Encode sequence of images into gif string clip = mpy.ImageSequenceClip(list(tensor), fps=fps) plot_path = (pathlib.Path(runner._snapshotter.snapshot_dir) / 'plots' # / f'{label}_{runner.step_itr}.gif') / f'{label}_{runner.step_itr}.mp4') plot_path.parent.mkdir(parents=True, exist_ok=True) # clip.write_gif(plot_path, verbose=False, logger=None) clip.write_videofile(str(plot_path), audio=False, verbose=False, logger=None) def save_trajectories(runner, label, tensor, skip_frame=3, n_cols=None): epsilon = 1e-6 tensor = prepare_video(tensor, n_cols) image = np.ones(tensor.shape[1:]) for i, frame in enumerate(tensor): image_mask = (image.mean(axis=2) < 1. - epsilon).astype(int)[..., np.newaxis] frame_mask = (frame.mean(axis=2) < 1. - epsilon).astype(int)[..., np.newaxis] if i % skip_frame == 0: image = frame_mask * frame + (1 - frame_mask) * image image = image * 255. image = image.astype(np.uint8) image = np.clip(image, 0, 255) im = Image.fromarray(image, 'RGB') im.save("mujoco.png") def record_video(runner, label, trajectories, n_cols=None, skip_frames=1): renders = [] for trajectory in trajectories: render = trajectory['env_infos']['render'] if render.ndim >= 5: render = render.reshape(-1, *render.shape[-3:]) elif render.ndim == 1: render = np.concatenate(render, axis=0) renders.append(render) max_length = max([len(render) for render in renders]) for i, render in enumerate(renders): renders[i] = np.concatenate([render, np.zeros((max_length - render.shape[0], *render.shape[1:]), dtype=render.dtype)], axis=0) renders[i] = renders[i][::skip_frames] renders = np.array(renders) save_video(runner, label, renders, n_cols=n_cols) def get_ori_coords(ori, offset=0): if ori.ndim == 3: ori = np.concatenate(ori, axis=0) t = np.arange(0, len(ori)) + offset theta = np.arctan2(ori[:, 1], ori[:, 0]) for i in range(1, len(ori)): if theta[i] - theta[i - 1] > 5: theta[i:] -= 2 * np.pi elif theta[i] - theta[i - 1] < -5: theta[i:] += 2 * np.pi return np.c_[t, theta] class FigManager: def __init__(self, runner, label, extensions=None, subplot_spec=None): self.runner = runner self.label = label self.fig = figure.Figure() if subplot_spec is not None: self.ax = self.fig.subplots(*subplot_spec).flatten() else: self.ax = self.fig.add_subplot() if extensions is None: self.extensions = ['png'] else: self.extensions = extensions def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): plot_paths = [(pathlib.Path(self.runner._snapshotter.snapshot_dir) / 'plots' / f'{self.label}_{self.runner.step_itr}.{extension}') for extension in self.extensions] plot_paths[0].parent.mkdir(parents=True, exist_ok=True) for plot_path in plot_paths: self.fig.savefig(plot_path, dpi=300) dowel_wrapper.get_tabular('plot').record(self.label, self.fig) class MeasureAndAccTime: def __init__(self, target): assert isinstance(target, list) assert len(target) == 1 self._target = target def __enter__(self): self._time_enter = time.time() return self def __exit__(self, exc_type, exc_val, exc_tb): self._target[0] += (time.time() - self._time_enter) class Timer: def __init__(self): self.t = time.time() def __call__(self, msg='', *args, **kwargs): print(f'{msg}: {time.time() - self.t:.20f}') self.t = time.time() def valuewise_sequencify_dicts(dicts): result = dict((k, []) for k in dicts[0].keys()) for d in dicts: for k, v in d.items(): result[k].append(v) return result def zip_dict(d): keys = list(d.keys()) values = [d[k] for k in keys] for z in zip(*values): yield dict((k, v) for k, v in zip(keys, z)) def split_paths(paths, chunking_points): assert 0 in chunking_points assert len(chunking_points) >= 2 if len(chunking_points) ==
from datetime import date, datetime, timedelta from flask import current_app from notifications_utils.timezones import convert_utc_to_bst from sqlalchemy import Date, Integer, and_, desc, func, union from sqlalchemy.dialects.postgresql import insert from sqlalchemy.sql.expression import case, literal from app import db from app.dao.date_util import ( get_financial_year_dates, get_financial_year_for_datetime, ) from app.dao.organisation_dao import dao_get_organisation_live_services from app.models import ( EMAIL_TYPE, INTERNATIONAL_POSTAGE_TYPES, KEY_TYPE_NORMAL, KEY_TYPE_TEAM, LETTER_TYPE, NOTIFICATION_STATUS_TYPES_BILLABLE_FOR_LETTERS, NOTIFICATION_STATUS_TYPES_BILLABLE_SMS, NOTIFICATION_STATUS_TYPES_SENT_EMAILS, SMS_TYPE, AnnualBilling, FactBilling, LetterRate, NotificationAllTimeView, NotificationHistory, Organisation, Rate, Service, ) from app.utils import get_london_midnight_in_utc def fetch_sms_free_allowance_remainder_until_date(end_date): # ASSUMPTION: AnnualBilling has been populated for year. billing_year = get_financial_year_for_datetime(end_date) start_of_year = date(billing_year, 4, 1) billable_units = func.coalesce(func.sum(FactBilling.billable_units * FactBilling.rate_multiplier), 0) query = db.session.query( AnnualBilling.service_id.label("service_id"), AnnualBilling.free_sms_fragment_limit, billable_units.label('billable_units'), func.greatest((AnnualBilling.free_sms_fragment_limit - billable_units).cast(Integer), 0).label('sms_remainder') ).outerjoin( # if there are no ft_billing rows for a service we still want to return the annual billing so we can use the # free_sms_fragment_limit) FactBilling, and_( AnnualBilling.service_id == FactBilling.service_id, FactBilling.bst_date >= start_of_year, FactBilling.bst_date < end_date, FactBilling.notification_type == SMS_TYPE, ) ).filter( AnnualBilling.financial_year_start == billing_year, ).group_by( AnnualBilling.service_id, AnnualBilling.free_sms_fragment_limit, ) return query def fetch_sms_billing_for_all_services(start_date, end_date): # ASSUMPTION: AnnualBilling has been populated for year. allowance_left_at_start_date_query = fetch_sms_free_allowance_remainder_until_date(start_date).subquery() sms_billable_units = func.sum(FactBilling.billable_units * FactBilling.rate_multiplier) # subtract sms_billable_units units accrued since report's start date to get up-to-date # allowance remainder sms_allowance_left = func.greatest(allowance_left_at_start_date_query.c.sms_remainder - sms_billable_units, 0) # billable units here are for period between start date and end date only, so to see # how many are chargeable, we need to see how much free allowance was used up in the # period up until report's start date and then do a subtraction chargeable_sms = func.greatest(sms_billable_units - allowance_left_at_start_date_query.c.sms_remainder, 0) sms_cost = chargeable_sms * FactBilling.rate query = db.session.query( Organisation.name.label('organisation_name'), Organisation.id.label('organisation_id'), Service.name.label("service_name"), Service.id.label("service_id"), allowance_left_at_start_date_query.c.free_sms_fragment_limit, FactBilling.rate.label('sms_rate'), sms_allowance_left.label("sms_remainder"), sms_billable_units.label('sms_billable_units'), chargeable_sms.label("chargeable_billable_sms"), sms_cost.label('sms_cost'), ).select_from( Service ).outerjoin( allowance_left_at_start_date_query, Service.id == allowance_left_at_start_date_query.c.service_id ).outerjoin( Service.organisation ).join( FactBilling, FactBilling.service_id == Service.id, ).filter( FactBilling.bst_date >= start_date, FactBilling.bst_date <= end_date, FactBilling.notification_type == SMS_TYPE, ).group_by( Organisation.name, Organisation.id, Service.id, Service.name, allowance_left_at_start_date_query.c.free_sms_fragment_limit, allowance_left_at_start_date_query.c.sms_remainder, FactBilling.rate, ).order_by( Organisation.name, Service.name ) return query.all() def fetch_letter_costs_and_totals_for_all_services(start_date, end_date): query = db.session.query( Organisation.name.label("organisation_name"), Organisation.id.label("organisation_id"), Service.name.label("service_name"), Service.id.label("service_id"), func.sum(FactBilling.notifications_sent).label("total_letters"), func.sum(FactBilling.notifications_sent * FactBilling.rate).label("letter_cost") ).select_from( Service ).outerjoin( Service.organisation ).join( FactBilling, FactBilling.service_id == Service.id, ).filter( FactBilling.service_id == Service.id, FactBilling.bst_date >= start_date, FactBilling.bst_date <= end_date, FactBilling.notification_type == LETTER_TYPE, ).group_by( Organisation.name, Organisation.id, Service.id, Service.name, ).order_by( Organisation.name, Service.name ) return query.all() def fetch_letter_line_items_for_all_services(start_date, end_date): formatted_postage = case( [(FactBilling.postage.in_(INTERNATIONAL_POSTAGE_TYPES), "international")], else_=FactBilling.postage ).label("postage") postage_order = case( (formatted_postage == "second", 1), (formatted_postage == "first", 2), (formatted_postage == "international", 3), else_=0 # assumes never get 0 as a result ) query = db.session.query( Organisation.name.label("organisation_name"), Organisation.id.label("organisation_id"), Service.name.label("service_name"), Service.id.label("service_id"), FactBilling.rate.label("letter_rate"), formatted_postage, func.sum(FactBilling.notifications_sent).label("letters_sent"), ).select_from( Service ).outerjoin( Service.organisation ).join( FactBilling, FactBilling.service_id == Service.id, ).filter( FactBilling.bst_date >= start_date, FactBilling.bst_date <= end_date, FactBilling.notification_type == LETTER_TYPE, ).group_by( Organisation.name, Organisation.id, Service.id, Service.name, FactBilling.rate, formatted_postage ).order_by( Organisation.name, Service.name, postage_order, FactBilling.rate, ) return query.all() def fetch_billing_totals_for_year(service_id, year): """ Returns a row for each distinct rate and notification_type from ft_billing over the specified financial year e.g. ( rate=0.0165, notification_type=sms, notifications_sent=123, ... ) The "query_service_<type>..." subqueries for each notification_type all return the same columns but differ internally e.g. SMS has to incorporate a rate multiplier. Each subquery returns the same set of columns, which we pick from here before the big union. """ return db.session.query( union(*[ db.session.query( query.c.notification_type.label("notification_type"), query.c.rate.label("rate"), func.sum(query.c.notifications_sent).label("notifications_sent"), func.sum(query.c.chargeable_units).label("chargeable_units"), func.sum(query.c.cost).label("cost"), func.sum(query.c.free_allowance_used).label("free_allowance_used"), func.sum(query.c.charged_units).label("charged_units"), ).group_by( query.c.rate, query.c.notification_type ) for query in [ query_service_sms_usage_for_year(service_id, year).subquery(), query_service_email_usage_for_year(service_id, year).subquery(), query_service_letter_usage_for_year(service_id, year).subquery(), ] ]).subquery() ).order_by( "notification_type", "rate", ).all() def fetch_monthly_billing_for_year(service_id, year): """ Returns a row for each distinct rate, notification_type, postage and month from ft_billing over the specified financial year e.g. ( rate=0.0165, notification_type=sms, postage=none, month=2022-04-01 00:00:00, notifications_sent=123, ... ) The "postage" field is "none" except for letters. Each subquery takes care of anything specific to the notification type e.g. rate multipliers for SMS. Since the data in ft_billing is only refreshed once a day for all services, we also update the table on-the-fly if we need accurate data for this year. """ _, year_end = get_financial_year_dates(year) today = convert_utc_to_bst(datetime.utcnow()).date() # if year end date is less than today, we are calculating for data in the past and have no need for deltas. if year_end >= today: data = fetch_billing_data_for_day(process_day=today, service_id=service_id, check_permissions=True) for d in data: update_fact_billing(data=d, process_day=today) return db.session.query( union(*[ db.session.query( query.c.rate.label("rate"), query.c.notification_type.label("notification_type"), query.c.postage.label("postage"), func.date_trunc('month', query.c.bst_date).cast(Date).label("month"), func.sum(query.c.notifications_sent).label("notifications_sent"), func.sum(query.c.chargeable_units).label("chargeable_units"), func.sum(query.c.cost).label("cost"), func.sum(query.c.free_allowance_used).label("free_allowance_used"), func.sum(query.c.charged_units).label("charged_units"), ).group_by( query.c.rate, query.c.notification_type, query.c.postage, 'month', ) for query in [ query_service_sms_usage_for_year(service_id, year).subquery(), query_service_email_usage_for_year(service_id, year).subquery(), query_service_letter_usage_for_year(service_id, year).subquery(), ] ]).subquery() ).order_by( "month", "notification_type", "rate", ).all() def query_service_email_usage_for_year(service_id, year): year_start, year_end = get_financial_year_dates(year) return db.session.query( FactBilling.bst_date, FactBilling.postage, # should always be "none" FactBilling.notifications_sent, FactBilling.billable_units.label("chargeable_units"), FactBilling.rate, FactBilling.notification_type, literal(0).label("cost"), literal(0).label("free_allowance_used"), FactBilling.billable_units.label("charged_units"), ).filter( FactBilling.service_id == service_id, FactBilling.bst_date >= year_start, FactBilling.bst_date <= year_end, FactBilling.notification_type == EMAIL_TYPE ) def query_service_letter_usage_for_year(service_id, year): year_start, year_end = get_financial_year_dates(year) return db.session.query( FactBilling.bst_date, FactBilling.postage, FactBilling.notifications_sent, # We can't use billable_units here as it represents the # sheet count for letters, which is already accounted for # in the rate. We actually charge per letter, not sheet. FactBilling.notifications_sent.label("chargeable_units"), FactBilling.rate, FactBilling.notification_type, (FactBilling.notifications_sent * FactBilling.rate).label("cost"), literal(0).label("free_allowance_used"), FactBilling.notifications_sent.label("charged_units"), ).filter( FactBilling.service_id == service_id, FactBilling.bst_date >= year_start, FactBilling.bst_date <= year_end, FactBilling.notification_type == LETTER_TYPE ) def query_service_sms_usage_for_year(service_id, year): """ Returns rows from the ft_billing table with some calculated values like cost, incorporating the SMS free allowance e.g. ( bst_date=2022-04-27, notifications_sent=12, chargeable_units=12, rate=0.0165, [cost=0 <== covered by the free allowance], [cost=0.198 <== if free allowance exhausted], [cost=0.099 <== only some free allowance left], ... ) In order to calculate how much free allowance is left, we need to work out how much was used for previous bst_dates - cumulative_chargeable_units - which we then subtract from the free allowance for the year. cumulative_chargeable_units is calculated using a "window" clause, which has access to all the rows identified by the query filter. Note that it's not affected by any GROUP BY clauses that happen in outer queries. https://www.postgresql.org/docs/current/tutorial-window.html ASSUMPTION: rates always change at midnight i.e. there can only be one rate on a given bst_date. This means we don't need to worry about how to assign free allowance if it happens to run out when a rate changes. """ year_start, year_end = get_financial_year_dates(year) this_rows_chargeable_units = FactBilling.billable_units * FactBilling.rate_multiplier # Subquery for the number of chargeable units in all rows preceding this one, # which might be none if this is the first row (hence the "coalesce"). For # some reason the end result is a decimal despite all the input columns being # integer - this seems to be a Sqlalchemy quirk (works in raw SQL). chargeable_units_used_before_this_row = func.coalesce( func.sum(this_rows_chargeable_units).over( # order is "ASC" by default order_by=[FactBilling.bst_date], # first row to previous row rows=(None, -1) ).cast(Integer), 0 ) # Subquery for how much free allowance we have left before the current row, # so we can work out the cost for this row after taking it into account. remaining_free_allowance_before_this_row = func.greatest( AnnualBilling.free_sms_fragment_limit - chargeable_units_used_before_this_row, 0 ) # Subquery for the number of chargeable_units that we will actually charge # for, after taking any remaining free allowance into account. charged_units = func.greatest(this_rows_chargeable_units - remaining_free_allowance_before_this_row, 0) free_allowance_used = func.least(remaining_free_allowance_before_this_row, this_rows_chargeable_units) return db.session.query( FactBilling.bst_date, FactBilling.postage, # should always be "none" FactBilling.notifications_sent, this_rows_chargeable_units.label("chargeable_units"), FactBilling.rate, FactBilling.notification_type, (charged_units * FactBilling.rate).label("cost"), free_allowance_used.label("free_allowance_used"), charged_units.label("charged_units"), ).join( AnnualBilling, AnnualBilling.service_id == service_id ).filter( FactBilling.service_id == service_id, FactBilling.bst_date >= year_start, FactBilling.bst_date <= year_end, FactBilling.notification_type == SMS_TYPE, AnnualBilling.financial_year_start == year, ) def delete_billing_data_for_service_for_day(process_day, service_id): """ Delete all ft_billing data for a given service on a given bst_date Returns how many rows were deleted """ return FactBilling.query.filter( FactBilling.bst_date == process_day, FactBilling.service_id == service_id ).delete() def fetch_billing_data_for_day(process_day, service_id=None, check_permissions=False): start_date = get_london_midnight_in_utc(process_day) end_date = get_london_midnight_in_utc(process_day + timedelta(days=1)) current_app.logger.info("Populate ft_billing for {} to {}".format(start_date, end_date)) transit_data = [] if not service_id: services = Service.query.all() else: services = [Service.query.get(service_id)] for service in services: for notification_type in (SMS_TYPE, EMAIL_TYPE, LETTER_TYPE): if (not check_permissions) or service.has_permission(notification_type): results = _query_for_billing_data( notification_type=notification_type, start_date=start_date, end_date=end_date, service=service ) transit_data += results return transit_data def _query_for_billing_data(notification_type, start_date, end_date, service): def _email_query(): return db.session.query( NotificationAllTimeView.template_id, literal(service.crown).label('crown'), literal(service.id).label('service_id'), literal(notification_type).label('notification_type'), literal('ses').label('sent_by'), literal(0).label('rate_multiplier'), literal(False).label('international'), literal(None).label('letter_page_count'), literal('none').label('postage'), literal(0).label('billable_units'), func.count().label('notifications_sent'), ).filter( NotificationAllTimeView.status.in_(NOTIFICATION_STATUS_TYPES_SENT_EMAILS), NotificationAllTimeView.key_type.in_((KEY_TYPE_NORMAL, KEY_TYPE_TEAM)), NotificationAllTimeView.created_at >= start_date, NotificationAllTimeView.created_at < end_date, NotificationAllTimeView.notification_type == notification_type, NotificationAllTimeView.service_id == service.id ).group_by( NotificationAllTimeView.template_id, ) def _sms_query(): sent_by = func.coalesce(NotificationAllTimeView.sent_by, 'unknown') rate_multiplier = func.coalesce(NotificationAllTimeView.rate_multiplier, 1).cast(Integer) international = func.coalesce(NotificationAllTimeView.international,
696611, 696617, 696623, 696629, 696653, 696659, 696679, 696691, 696719, 696721, 696737, 696743, 696757, 696763, 696793, 696809, 696811, 696823, 696827, 696833, 696851, 696853, 696887, 696889, 696893, 696907, 696929, 696937, 696961, 696989, 696991, 697009, 697013, 697019, 697033, 697049, 697063, 697069, 697079, 697087, 697093, 697111, 697121, 697127, 697133, 697141, 697157, 697181, 697201, 697211, 697217, 697259, 697261, 697267, 697271, 697303, 697327, 697351, 697373, 697379, 697381, 697387, 697397, 697399, 697409, 697423, 697441, 697447, 697453, 697457, 697481, 697507, 697511, 697513, 697519, 697523, 697553, 697579, 697583, 697591, 697601, 697603, 697637, 697643, 697673, 697681, 697687, 697691, 697693, 697703, 697727, 697729, 697733, 697757, 697759, 697787, 697819, 697831, 697877, 697891, 697897, 697909, 697913, 697937, 697951, 697967, 697973, 697979, 697993, 697999, 698017, 698021, 698039, 698051, 698053, 698077, 698083, 698111, 698171, 698183, 698239, 698249, 698251, 698261, 698263, 698273, 698287, 698293, 698297, 698311, 698329, 698339, 698359, 698371, 698387, 698393, 698413, 698417, 698419, 698437, 698447, 698471, 698483, 698491, 698507, 698521, 698527, 698531, 698539, 698543, 698557, 698567, 698591, 698641, 698653, 698669, 698701, 698713, 698723, 698729, 698773, 698779, 698821, 698827, 698849, 698891, 698899, 698903, 698923, 698939, 698977, 698983, 699001, 699007, 699037, 699053, 699059, 699073, 699077, 699089, 699113, 699119, 699133, 699151, 699157, 699169, 699187, 699191, 699197, 699211, 699217, 699221, 699241, 699253, 699271, 699287, 699289, 699299, 699319, 699323, 699343, 699367, 699373, 699379, 699383, 699401, 699427, 699437, 699443, 699449, 699463, 699469, 699493, 699511, 699521, 699527, 699529, 699539, 699541, 699557, 699571, 699581, 699617, 699631, 699641, 699649, 699697, 699709, 699719, 699733, 699757, 699761, 699767, 699791, 699793, 699817, 699823, 699863, 699931, 699943, 699947, 699953, 699961, 699967, 700001, 700027, 700057, 700067, 700079, 700081, 700087, 700099, 700103, 700109, 700127, 700129, 700171, 700199, 700201, 700211, 700223, 700229, 700237, 700241, 700277, 700279, 700303, 700307, 700319, 700331, 700339, 700361, 700363, 700367, 700387, 700391, 700393, 700423, 700429, 700433, 700459, 700471, 700499, 700523, 700537, 700561, 700571, 700573, 700577, 700591, 700597, 700627, 700633, 700639, 700643, 700673, 700681, 700703, 700717, 700751, 700759, 700781, 700789, 700801, 700811, 700831, 700837, 700849, 700871, 700877, 700883, 700897, 700907, 700919, 700933, 700937, 700949, 700963, 700993, 701009, 701011, 701023, 701033, 701047, 701089, 701117, 701147, 701159, 701177, 701179, 701209, 701219, 701221, 701227, 701257, 701279, 701291, 701299, 701329, 701341, 701357, 701359, 701377, 701383, 701399, 701401, 701413, 701417, 701419, 701443, 701447, 701453, 701473, 701479, 701489, 701497, 701507, 701509, 701527, 701531, 701549, 701579, 701581, 701593, 701609, 701611, 701621, 701627, 701629, 701653, 701669, 701671, 701681, 701699, 701711, 701719, 701731, 701741, 701761, 701783, 701791, 701819, 701837, 701863, 701881, 701903, 701951, 701957, 701963, 701969, 702007, 702011, 702017, 702067, 702077, 702101, 702113, 702127, 702131, 702137, 702139, 702173, 702179, 702193, 702199, 702203, 702211, 702239, 702257, 702269, 702281, 702283, 702311, 702313, 702323, 702329, 702337, 702341, 702347, 702349, 702353, 702379, 702391, 702407, 702413, 702431, 702433, 702439, 702451, 702469, 702497, 702503, 702511, 702517, 702523, 702529, 702539, 702551, 702557, 702587, 702589, 702599, 702607, 702613, 702623, 702671, 702679, 702683, 702701, 702707, 702721, 702731, 702733, 702743, 702773, 702787, 702803, 702809, 702817, 702827, 702847, 702851, 702853, 702869, 702881, 702887, 702893, 702913, 702937, 702983, 702991, 703013, 703033, 703039, 703081, 703117, 703121, 703123, 703127, 703139, 703141, 703169, 703193, 703211, 703217, 703223, 703229, 703231, 703243, 703249, 703267, 703277, 703301, 703309, 703321, 703327, 703331, 703349, 703357, 703379, 703393, 703411, 703441, 703447, 703459, 703463, 703471, 703489, 703499, 703531, 703537, 703559, 703561, 703631, 703643, 703657, 703663, 703673, 703679, 703691, 703699, 703709, 703711, 703721, 703733, 703753, 703763, 703789, 703819, 703837, 703849, 703861, 703873, 703883, 703897, 703903, 703907, 703943, 703949, 703957, 703981, 703991, 704003, 704009, 704017, 704023, 704027, 704029, 704059, 704069, 704087, 704101, 704111, 704117, 704131, 704141, 704153, 704161, 704177, 704183, 704189, 704213, 704219, 704233, 704243, 704251, 704269, 704279, 704281, 704287, 704299, 704303, 704309, 704321, 704357, 704393, 704399, 704419, 704441, 704447, 704449, 704453, 704461, 704477, 704507, 704521, 704527, 704549, 704551, 704567, 704569, 704579, 704581, 704593, 704603, 704617, 704647, 704657, 704663, 704681, 704687, 704713, 704719, 704731, 704747, 704761, 704771, 704777, 704779, 704783, 704797, 704801, 704807, 704819, 704833, 704839, 704849, 704857, 704861, 704863, 704867, 704897, 704929, 704933, 704947, 704983, 704989, 704993, 704999, 705011, 705013, 705017, 705031, 705043, 705053, 705073, 705079, 705097, 705113, 705119, 705127, 705137, 705161, 705163, 705167, 705169, 705181, 705191, 705197, 705209, 705247, 705259, 705269, 705277, 705293, 705307, 705317, 705389, 705403, 705409, 705421, 705427, 705437, 705461, 705491, 705493, 705499, 705521, 705533, 705559, 705613, 705631, 705643, 705689, 705713, 705737, 705751, 705763, 705769, 705779, 705781, 705787, 705821, 705827, 705829, 705833, 705841, 705863, 705871, 705883, 705899, 705919, 705937, 705949, 705967, 705973, 705989, 706001, 706003, 706009, 706019, 706033, 706039, 706049, 706051, 706067, 706099, 706109, 706117, 706133, 706141, 706151, 706157, 706159, 706183, 706193, 706201, 706207, 706213, 706229, 706253, 706267, 706283, 706291, 706297, 706301, 706309, 706313, 706337, 706357, 706369, 706373, 706403, 706417, 706427, 706463, 706481, 706487, 706499, 706507, 706523, 706547, 706561, 706597, 706603, 706613, 706621, 706631, 706633, 706661, 706669, 706679, 706703, 706709, 706729, 706733, 706747, 706751, 706753, 706757, 706763, 706787, 706793, 706801, 706829, 706837, 706841, 706847, 706883, 706897, 706907, 706913, 706919, 706921, 706943, 706961, 706973, 706987, 706999, 707011, 707027, 707029, 707053, 707071, 707099, 707111, 707117, 707131, 707143, 707153, 707159, 707177, 707191, 707197, 707219, 707249, 707261, 707279, 707293, 707299, 707321, 707341, 707359, 707383, 707407, 707429, 707431, 707437, 707459, 707467, 707501, 707527, 707543, 707561, 707563, 707573, 707627, 707633, 707647, 707653, 707669, 707671, 707677, 707683, 707689, 707711, 707717, 707723, 707747, 707753, 707767, 707789, 707797, 707801, 707813, 707827, 707831, 707849, 707857, 707869, 707873, 707887, 707911, 707923, 707929, 707933, 707939, 707951, 707953, 707957, 707969, 707981, 707983, 708007, 708011, 708017, 708023, 708031, 708041, 708047, 708049, 708053, 708061, 708091, 708109, 708119, 708131, 708137, 708139, 708161, 708163, 708179, 708199, 708221, 708223, 708229, 708251, 708269, 708283, 708287, 708293, 708311, 708329, 708343, 708347, 708353, 708359, 708361, 708371, 708403, 708437, 708457, 708473, 708479, 708481, 708493, 708497, 708517, 708527, 708559, 708563, 708569, 708583, 708593, 708599, 708601, 708641, 708647, 708667, 708689, 708703, 708733, 708751, 708803, 708823, 708839, 708857, 708859, 708893, 708899, 708907, 708913, 708923, 708937, 708943, 708959, 708979, 708989, 708991, 708997, 709043, 709057, 709097, 709117, 709123, 709139, 709141, 709151, 709153, 709157, 709201, 709211, 709217, 709231, 709237, 709271, 709273, 709279, 709283, 709307, 709321, 709337, 709349, 709351, 709381, 709409, 709417, 709421, 709433, 709447, 709451, 709453, 709469, 709507, 709519, 709531, 709537, 709547, 709561, 709589, 709603, 709607, 709609, 709649, 709651, 709663, 709673, 709679, 709691, 709693, 709703, 709729, 709739, 709741, 709769, 709777, 709789, 709799, 709817, 709823, 709831, 709843, 709847, 709853, 709861, 709871, 709879, 709901, 709909, 709913, 709921, 709927, 709957, 709963, 709967, 709981, 709991, 710009, 710023, 710027, 710051, 710053, 710081, 710089, 710119, 710189, 710207, 710219, 710221, 710257, 710261, 710273, 710293, 710299, 710321, 710323, 710327, 710341, 710351, 710371, 710377, 710383, 710389, 710399, 710441, 710443, 710449, 710459, 710473, 710483, 710491, 710503, 710513, 710519, 710527, 710531, 710557, 710561, 710569, 710573, 710599, 710603, 710609, 710621, 710623, 710627, 710641, 710663, 710683, 710693, 710713, 710777, 710779, 710791, 710813, 710837, 710839, 710849, 710851, 710863, 710867, 710873, 710887, 710903, 710909, 710911, 710917, 710929, 710933, 710951, 710959, 710971, 710977, 710987, 710989, 711001, 711017, 711019, 711023, 711041, 711049, 711089, 711097, 711121, 711131, 711133, 711143, 711163, 711173, 711181, 711187, 711209, 711223, 711259, 711287, 711299, 711307, 711317, 711329, 711353, 711371, 711397, 711409, 711427, 711437, 711463, 711479, 711497, 711499, 711509, 711517, 711523, 711539, 711563, 711577, 711583, 711589, 711617, 711629, 711649, 711653, 711679, 711691, 711701, 711707, 711709, 711713, 711727, 711731, 711749, 711751, 711757, 711793, 711811, 711817, 711829, 711839, 711847, 711859, 711877, 711889, 711899, 711913, 711923, 711929, 711937, 711947, 711959, 711967, 711973, 711983, 712007, 712021, 712051, 712067, 712093, 712109, 712121, 712133, 712157, 712169, 712171, 712183, 712199, 712219, 712237, 712279, 712289, 712301, 712303, 712319, 712321, 712331, 712339, 712357, 712409, 712417, 712427, 712429, 712433, 712447, 712477, 712483, 712489, 712493, 712499, 712507, 712511, 712531, 712561, 712571, 712573, 712601, 712603, 712631, 712651, 712669, 712681, 712687, 712693, 712697, 712711, 712717, 712739, 712781, 712807, 712819, 712837, 712841, 712843, 712847, 712883, 712889, 712891, 712909, 712913, 712927, 712939, 712951, 712961, 712967, 712973, 712981, 713021, 713039, 713059, 713077, 713107, 713117, 713129, 713147, 713149, 713159, 713171, 713177, 713183, 713189, 713191, 713227, 713233, 713239, 713243, 713261, 713267, 713281, 713287, 713309, 713311, 713329, 713347, 713351, 713353, 713357, 713381, 713389, 713399, 713407, 713411, 713417, 713467, 713477, 713491, 713497, 713501, 713509, 713533, 713563, 713569, 713597, 713599,
Leakage': 0.00611897, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00348781, 'Renaming Unit/Peak Dynamic': 4.56169, 'Renaming Unit/Runtime Dynamic': 0.97034, 'Renaming Unit/Subthreshold Leakage': 0.070483, 'Renaming Unit/Subthreshold Leakage with power gating': 0.0362779, 'Runtime Dynamic': 11.5616, 'Subthreshold Leakage': 6.21877, 'Subthreshold Leakage with power gating': 2.58311}, {'Area': 32.0201, 'Execution Unit/Area': 7.68434, 'Execution Unit/Complex ALUs/Area': 0.235435, 'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646, 'Execution Unit/Complex ALUs/Peak Dynamic': 0.0306731, 'Execution Unit/Complex ALUs/Runtime Dynamic': 0.226781, 'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111, 'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163, 'Execution Unit/Floating Point Units/Area': 4.6585, 'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156, 'Execution Unit/Floating Point Units/Peak Dynamic': 0.283316, 'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033, 'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829, 'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061, 'Execution Unit/Gate Leakage': 0.120359, 'Execution Unit/Instruction Scheduler/Area': 1.66526, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.212041, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519, 'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913, 'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223, 'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562, 'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763, 'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.342014, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964, 'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262, 'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388, 'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608, 'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451, 'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.172637, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446, 'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.726693, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346, 'Execution Unit/Integer ALUs/Area': 0.47087, 'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291, 'Execution Unit/Integer ALUs/Peak Dynamic': 0.199077, 'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344, 'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222, 'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833, 'Execution Unit/Peak Dynamic': 4.64421, 'Execution Unit/Register Files/Area': 0.570804, 'Execution Unit/Register Files/Floating Point RF/Area': 0.208131, 'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788, 'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0535245, 'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00889395, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968, 'Execution Unit/Register Files/Gate Leakage': 0.000622708, 'Execution Unit/Register Files/Integer RF/Area': 0.362673, 'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992, 'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0710135, 'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0657762, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675, 'Execution Unit/Register Files/Peak Dynamic': 0.124538, 'Execution Unit/Register Files/Runtime Dynamic': 0.0746702, 'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387, 'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643, 'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912, 'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402, 'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.157276, 'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.433896, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543, 'Execution Unit/Runtime Dynamic': 1.86742, 'Execution Unit/Subthreshold Leakage': 1.79543, 'Execution Unit/Subthreshold Leakage with power gating': 0.688821, 'Gate Leakage': 0.368936, 'Instruction Fetch Unit/Area': 5.85939, 'Instruction Fetch Unit/Branch Predictor/Area': 0.138516, 'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.00156056, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.00156056, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.00141628, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 0.000579461, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045, 'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838, 'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732, 'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05, 'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602, 'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000944881, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733, 'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00548227, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282, 'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954, 'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758, 'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867, 'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.0129246, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357, 'Instruction Fetch Unit/Gate Leakage': 0.0589979, 'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323, 'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05, 'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827, 'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0632324, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682, 'Instruction Fetch Unit/Instruction Cache/Area': 3.14635, 'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931, 'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 4.02212, 'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.171937, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386, 'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799, 'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493, 'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404, 'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.214766, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104, 'Instruction Fetch Unit/Peak Dynamic': 6.43584, 'Instruction Fetch Unit/Runtime Dynamic': 0.468342, 'Instruction Fetch Unit/Subthreshold Leakage': 0.932286, 'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843, 'L2/Area': 4.53318, 'L2/Gate Leakage': 0.015464, 'L2/Peak Dynamic': 0.0125604, 'L2/Runtime Dynamic': 0.00259161, 'L2/Subthreshold Leakage': 0.834142, 'L2/Subthreshold Leakage with power gating': 0.401066, 'Load Store Unit/Area': 8.80901, 'Load Store Unit/Data Cache/Area': 6.84535, 'Load Store Unit/Data Cache/Gate Leakage': 0.0279261, 'Load Store Unit/Data Cache/Peak Dynamic': 3.16157, 'Load Store Unit/Data Cache/Runtime Dynamic': 0.92438, 'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675, 'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085, 'Load Store Unit/Gate Leakage': 0.0350888, 'Load Store Unit/LoadQ/Area': 0.0836782, 'Load Store Unit/LoadQ/Gate Leakage': 0.00059896, 'Load Store Unit/LoadQ/Peak Dynamic': 0.0622605, 'Load Store Unit/LoadQ/Runtime Dynamic': 0.0622606, 'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961, 'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918, 'Load Store Unit/Peak Dynamic': 3.45558, 'Load Store Unit/Runtime Dynamic': 1.29369, 'Load Store Unit/StoreQ/Area': 0.322079, 'Load Store Unit/StoreQ/Gate Leakage': 0.00329971, 'Load Store Unit/StoreQ/Peak Dynamic': 0.153524, 'Load Store Unit/StoreQ/Runtime Dynamic': 0.307048, 'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621, 'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004, 'Load Store Unit/Subthreshold Leakage': 0.591321, 'Load Store Unit/Subthreshold Leakage with power gating': 0.283293, 'Memory Management Unit/Area': 0.4339, 'Memory Management Unit/Dtlb/Area': 0.0879726, 'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729, 'Memory Management Unit/Dtlb/Peak Dynamic': 0.0544861, 'Memory Management Unit/Dtlb/Runtime Dynamic': 0.0546744, 'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699, 'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485, 'Memory Management Unit/Gate Leakage': 0.00808595, 'Memory Management Unit/Itlb/Area': 0.301552, 'Memory Management Unit/Itlb/Gate Leakage': 0.00393464, 'Memory Management Unit/Itlb/Peak Dynamic': 0.250081, 'Memory Management Unit/Itlb/Runtime Dynamic': 0.0281875, 'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758, 'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842, 'Memory Management Unit/Peak Dynamic': 0.499787, 'Memory Management Unit/Runtime Dynamic': 0.0828619, 'Memory Management Unit/Subthreshold Leakage': 0.0766103, 'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333, 'Peak Dynamic': 18.6374, 'Renaming Unit/Area': 0.303608, 'Renaming Unit/FP Front End RAT/Area': 0.131045, 'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123, 'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468, 'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.140798, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885, 'Renaming Unit/Free List/Area': 0.0340654, 'Renaming Unit/Free List/Gate Leakage': 2.5481e-05, 'Renaming Unit/Free List/Peak Dynamic': 0.0306032, 'Renaming Unit/Free List/Runtime Dynamic': 0.0112802, 'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144, 'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064, 'Renaming Unit/Gate Leakage': 0.00708398, 'Renaming Unit/Int Front End RAT/Area': 0.0941223, 'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242, 'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965, 'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.10582, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage':
# -*- coding: utf-8 -*- #!/usr/bin/env python # # Copyright 2014-2020 BigML # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Base class for sources' REST calls https://bigml.com/api/sources """ import sys import os import urllib2 import numbers try: #added to allow GAE to work from google.appengine.api import urlfetch GAE_ENABLED = True except ImportError: GAE_ENABLED = False import ssl try: import simplejson as json except ImportError: import json from threading import Thread PYTHON_2_7_9 = len(urllib2.urlopen.__defaults__) > 2 PYTHON_2 = sys.version_info < (3, 0) if PYTHON_2: from poster.encode import multipart_encode, MultipartParam if PYTHON_2_7_9: from bigml.sslposter import StreamingHTTPSHandler, register_openers elif PYTHON_2: from poster.streaminghttp import StreamingHTTPSHandler, register_openers else: from requests_toolbelt import MultipartEncoder import mimetypes from bigml.util import (localize, clear_console_line, reset_console_line, console_log, is_url) from bigml.bigmlconnection import ( HTTP_CREATED, HTTP_ACCEPTED, HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_PAYMENT_REQUIRED, HTTP_NOT_FOUND, HTTP_TOO_MANY_REQUESTS, HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR, GAE_ENABLED, SEND_JSON) from bigml.bigmlconnection import json_load from bigml.resourcehandler import (check_resource_type, resource_is_ready, get_source_id) from bigml.constants import SOURCE_PATH, UPLOADING from bigml.resourcehandler import ResourceHandler, LOGGER if PYTHON_2: register_openers() else: import requests from bigml.util import maybe_save class SourceHandler(ResourceHandler): """This class is used by the BigML class as a mixin that provides the REST calls to sources. It should not be instantiated independently. """ def __init__(self): """Initializes the SourceHandler. This class is intended to be used as a mixin on ResourceHandler, that inherits its attributes and basic method from BigMLConnection, and must not be instantiated independently. """ self.source_url = self.url + SOURCE_PATH def _create_remote_source(self, url, args=None): """Creates a new source using a URL """ create_args = {} if args is not None: create_args.update(args) create_args.update({"remote": url}) create_args = self._add_project(create_args) body = json.dumps(create_args) return self._create(self.source_url, body) def _create_inline_source(self, src_obj, args=None): """Create source from inline data The src_obj data should be a list of rows stored as dict or list objects. """ create_args = {} if args is not None: create_args.update(args) create_args = self._add_project(create_args) # some basic validation if (not isinstance(src_obj, list) or ( not all([isinstance(row, dict) for row in src_obj]) and not all([isinstance(row, list) for row in src_obj]))): raise TypeError( 'ERROR: inline source must be a list of dicts or a ' 'list of lists') create_args.update({"data": json.dumps(src_obj)}) body = json.dumps(create_args) return self._create(self.source_url, body) def _upload_source(self, args, source, out=sys.stdout): """Uploads a source asynchronously. """ def update_progress(param, current, total): """Updates source's progress. """ progress = round(current * 1.0 / total, 2) if progress < 1.0: source['object']['status']['progress'] = progress resource = self._process_source(source['resource'], source['location'], source['object'], args=args, progress_bar=True, callback=update_progress, out=out) source['code'] = resource['code'] source['resource'] = resource['resource'] source['location'] = resource['location'] source['object'] = resource['object'] source['error'] = resource['error'] def _stream_source(self, file_name, args=None, async_load=False, progress_bar=False, out=sys.stdout): """Creates a new source. """ def draw_progress_bar(param, current, total): """Draws a text based progress report. """ pct = 100 - ((total - current) * 100) / (total) console_log("Uploaded %s out of %s bytes [%s%%]" % ( localize(current), localize(total), pct), reset=True) create_args = {} if args is not None: create_args.update(args) if 'source_parser' in create_args: create_args['source_parser'] = json.dumps( create_args['source_parser']) resource_id = None location = None resource = None error = None try: if isinstance(file_name, basestring): create_args.update({os.path.basename(file_name): open(file_name, "rb")}) else: create_args = create_args.items() name = 'Stdin input' create_args.append(MultipartParam(name, filename=name, fileobj=file_name)) except IOError, exception: raise IOError("Error: cannot read training set. %s" % str(exception)) if async_load: source = { 'code': HTTP_ACCEPTED, 'resource': resource_id, 'location': location, 'object': {'status': {'message': 'The upload is in progress', 'code': UPLOADING, 'progress': 0.0}}, 'error': error} upload_args = (create_args, source) thread = Thread(target=self._upload_source, args=upload_args, kwargs={'out': out}) thread.start() return source return self._process_source(resource_id, location, resource, args=create_args, progress_bar=progress_bar, callback=draw_progress_bar, out=out) def _process_source(self, resource_id, location, resource, args=None, progress_bar=False, callback=None, out=sys.stdout): """Creates a new source. """ code = HTTP_INTERNAL_SERVER_ERROR error = { "status": { "code": code, "message": "The resource couldn't be created"}} if args is None: args = {} args = self._add_project(args, True) if progress_bar and callback is not None: body, headers = multipart_encode(args, cb=callback) else: body, headers = multipart_encode(args) url = self._add_credentials(self.source_url) if GAE_ENABLED: try: response = urlfetch.fetch(url=url, payload="".join(body), method=urlfetch.POST, headers=headers) code = response.status_code content = response.content if code in [HTTP_CREATED]: if 'location' in response.headers: location = response.headers['location'] resource = json_load(response.content) resource_id = resource['resource'] error = {} elif code in [HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_PAYMENT_REQUIRED, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_TOO_MANY_REQUESTS]: error = json_load(response.content) LOGGER.error(self.error_message(error, method='create')) elif code != HTTP_ACCEPTED: LOGGER.error("Unexpected error (%s)", code) code = HTTP_INTERNAL_SERVER_ERROR except urlfetch.Error, exception: LOGGER.error("Error establishing connection: %s", str(exception)) else: try: request = urllib2.Request(url, body, headers) # try using the new SSL checking in python 2.7.9 try: if not self.verify and PYTHON_2_7_9: context = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH) context.verify_mode = ssl.CERT_NONE https_handler = StreamingHTTPSHandler(context=context) opener = urllib2.build_opener(https_handler) urllib2.install_opener(opener) response = urllib2.urlopen(request) else: response = urllib2.urlopen(request) except AttributeError: response = urllib2.urlopen(request) clear_console_line(out=out) reset_console_line(out=out) code = response.getcode() if code == HTTP_CREATED: location = response.headers['location'] content = response.read() resource = json_load(content) resource_id = resource['resource'] error = {} except ValueError: LOGGER.error("Malformed response.") except urllib2.HTTPError, exception: code = exception.code if code in [HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_PAYMENT_REQUIRED, HTTP_NOT_FOUND, HTTP_TOO_MANY_REQUESTS]: content = exception.read() error = json_load(content) LOGGER.error(self.error_message(error, method='create')) else: LOGGER.error("Unexpected error (%s)", code) code = HTTP_INTERNAL_SERVER_ERROR except urllib2.URLError, exception: LOGGER.error("Error establishing connection: %s", str(exception)) error = exception.args return { 'code': code, 'resource': resource_id, 'location': location, 'object': resource, 'error': error} def _create_local_source(self, file_name, args=None): """Creates a new source using a local file. This function is only used from Python 3. No async-prepared. """ create_args = {} if args is not None: create_args.update(args) for key, value in create_args.items(): if value is not None and (isinstance(value, list) or isinstance(value, dict)): create_args[key] = json.dumps(value) elif value is not None and isinstance(value, numbers.Number): # the multipart encoder only accepts strings and files create_args[key] = str(value) code = HTTP_INTERNAL_SERVER_ERROR resource_id = None location = None resource = None error = { "status": { "code": code, "message": "The resource couldn't be created"}} try: if isinstance(file_name, basestring): name = os.path.basename(file_name) file_handler = open(file_name, "rb") else: name = 'Stdin input' file_handler = file_name except IOError: sys.exit("ERROR: cannot read training set") url = self._add_credentials(self.source_url) create_args = self._add_project(create_args, True) if GAE_ENABLED: try: req_options = { 'url': url, 'method': urlfetch.POST, 'headers': SEND_JSON, 'data': create_args, 'files': {name: file_handler}, 'validate_certificate': self.verify } response = urlfetch.fetch(**req_options) except urlfetch.Error, exception: LOGGER.error("HTTP request error: %s", str(exception)) return maybe_save(resource_id, self.storage, code, location, resource, error) else: try: files = {"file": (name, file_handler, mimetypes.guess_type(name)[0])} files.update(create_args) multipart = MultipartEncoder(fields=files) response = requests.post( \ url, headers={'Content-Type': multipart.content_type}, data=multipart, verify=self.verify) except (requests.ConnectionError, requests.Timeout, requests.RequestException), exc: LOGGER.error("HTTP request error: %s", str(exc)) code = HTTP_INTERNAL_SERVER_ERROR return maybe_save(resource_id, self.storage, code, location, resource, error) try: code = response.status_code if code == HTTP_CREATED: location = response.headers['location'] resource = json_load(response.content) resource_id = resource['resource'] error = None elif code in [HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_PAYMENT_REQUIRED, HTTP_NOT_FOUND, HTTP_TOO_MANY_REQUESTS]: error = json_load(response.content) else: LOGGER.error("Unexpected error (%s)" % code) code = HTTP_INTERNAL_SERVER_ERROR except ValueError: LOGGER.error("Malformed response") return maybe_save(resource_id, self.storage, code, location, resource, error) def create_source(self, path=None, args=None, async_load=False, progress_bar=False, out=sys.stdout): """Creates a new source. The source can be a local file path or a URL. """ if path is None: raise Exception('A local path or a valid URL must be provided.') if is_url(path): return self._create_remote_source(path, args=args) elif isinstance(path, list): return self._create_inline_source(path, args=args) elif PYTHON_2: return self._stream_source(file_name=path, args=args, async_load=async_load, progress_bar=progress_bar, out=out) else: return self._create_local_source(file_name=path, args=args) def get_source(self, source, query_string=''): """Retrieves a remote source. The source parameter should be a string containing the source id or the dict returned by create_source. As source is an evolving object that is processed until it reaches the FINISHED or FAULTY state, thet function will return a dict that encloses the source values and state info available at the time it is called. """ check_resource_type(source, SOURCE_PATH, message="A source id is needed.") source_id = get_source_id(source) if source_id: return self._get("%s%s" % (self.url, source_id), query_string=query_string) def source_is_ready(self, source): """Checks whether a source' status is FINISHED. """ check_resource_type(source, SOURCE_PATH, message="A source id is needed.") source = self.get_source(source) return resource_is_ready(source)
b9f==''\ and board.s6f+board.s7f+board.s8f=='': moves = '5f9f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b5f)and b2i==''\ and board.s3h+board.s4g=='': moves ='5f2i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B',Bboard.b5f)and b3h==''\ and board.s4g=='': moves ='5f3h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b5f)and b7d==''\ and board.s6e=='': moves ='5f7d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b5f)and b8c==''\ and board.s6e+board.s7d=='': moves ='5f8c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b5f)and b9b==''\ and board.s6e+board.s7d+board.s8c=='': moves ='5f9b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b5f)and b8i==''\ and board.s7h+board.s6g=='': moves ='5f8i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B',Bboard.b5f)and b7h==''\ and board.s6g=='': moves ='5f7h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b5f)and b3d==''\ and board.s4e=='': moves ='5f3d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b5f)and b2c==''\ and board.s4e+board.s3d=='': moves ='5f2c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B', Bboard.b5f)and b8c==''\ and board.s6e+board.s7d=='': moves ='5f8c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B', Bboard.b5f)and b2c==''\ and board.s4e+board.s3d=='': moves ='5f2c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if Bboard.b6f !='': if re.match(r'[PLSGRK+]', Bboard.b6f)and b6e=='': moves = '6f6e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[SGBK+]', Bboard.b6f)and b5e=='': moves = '6f5e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[SGBK+]', Bboard.b6f)and b7e=='': moves = '6f7e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GRK+]', Bboard.b6f)and b5f=='': moves = '6f5f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GRK+]', Bboard.b6f)and b7f=='': moves = '6f7f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GRK+]', Bboard.b6f)and b6g=='': moves = '6f6g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|\+B|B|S|K',Bboard.b6f)and b5g=='': moves = '6f5g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|\+B|B|S|K',Bboard.b6f)and b7g=='': moves = '6f7g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('N', Bboard.b6f)and b5d=='': moves = '6f5d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('N', Bboard.b6f)and b7d=='': moves = '6f7d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b6f)and b6a==''\ and board.s6b+board.s6c+board.s6d+board.s6e=='': moves = '6f6a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'R|L', Bboard.b6f)and b6a==''\ and board.s6b+board.s6c+board.s6d+board.s6e=='': moves = '6f6a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b6f)and b6b==''\ and board.s6c+board.s6d+board.s6e=='': moves = '6f6b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'R|L', Bboard.b6f)and b6b==''\ and board.s6c+board.s6d+board.s6e=='': moves = '6f6b+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|L', Bboard.b6f)and b6c==''\ and board.s6d+board.s6e=='': moves = '6f6c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'R|L', Bboard.b6f)and b6c==''\ and board.s6d+board.s6e=='': moves = '6f6c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R|L', Bboard.b6f)and b6d==''\ and board.s6e=='': moves = '6f6d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b6f)and b6h==''\ and board.s6g=='': moves = '6f6h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b6f)and b6i==''\ and board.s6g+board.s6h=='': moves = '6f6i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b6f)and b9f==''\ and board.s8f+board.s7f=='': moves = '6f9f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b6f)and b8f==''\ and board.s7f=='': moves = '6f8f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b6f)and b4f==''\ and board.s5f=='': moves = '6f4f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b6f)and b3f==''\ and board.s5f+board.s4f=='': moves = '6f3f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b6f)and b2f==''\ and board.s5f+board.s4f+board.s3f=='': moves = '6f2f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b6f)and b1f==''\ and board.s5f+board.s4f+board.s3f+board.s2f=='': moves = '6f1f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b6f)and b9i==''\ and board.s8h+board.s7g=='': moves = '6f9i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b6f)and b8h==''\ and board.s7g=='': moves = '6f8h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b6f)and b4d==''\ and board.s5e=='': moves = '6f4d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b6f)and b3c==''\ and board.s5e+board.s4d=='': moves = '6f3c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b6f)and b2b==''\ and board.s5e+board.s4d+board.s3c=='': moves = '6f2b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b6f)and b1a==''\ and board.s5e+board.s4d+board.s3c+board.s2b=='': moves = '6f1a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b6f)and b3i==''\ and board.s4h+board.s5g=='': moves = '6f3i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b6f)and b4h==''\ and board.s5g=='': moves = '6f4h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b6f)and b8d==''\ and board.s7e=='': moves = '6f8d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b6f)and b9c==''\ and board.s7e+board.s8d=='': moves = '6f9c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B', Bboard.b6f)and b3c==''\ and board.s5e+board.s4d=='': moves = '6f3c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B', Bboard.b6f)and b2b==''\ and board.s5e+board.s4d+board.s3c=='': moves = '6f2b+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B', Bboard.b6f)and b9c==''\ and board.s7e+board.s8d=='': moves = '6f9c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B', Bboard.b6f)and b1a==''\ and board.s5e+board.s4d+board.s3c+board.s2b=='': moves = '6f1a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if Bboard.b7f !='': if re.match(r'[PLSGRK+]', Bboard.b7f)and b7e=='': moves = '7f7e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[SGBK+]', Bboard.b7f)and b6e=='': moves = '7f6e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[SGBK+]', Bboard.b7f)and b8e=='': moves = '7f8e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GRK+]', Bboard.b7f)and b6f=='': moves = '7f6f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GRK+]', Bboard.b7f)and b8f=='': moves = '7f8f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GRK+]', Bboard.b7f)and b7g=='': moves = '7f7g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|\+B|B|S|K',Bboard.b7f)and b6g=='': moves = '7f6g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|\+B|B|S|K',Bboard.b7f)and b8g=='': moves = '7f8g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('N', Bboard.b7f)and b6d=='': moves = '7f6d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('N', Bboard.b7f)and b8d=='': moves = '7f8d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b7f)and b7a==''\ and board.s7b+board.s7c+board.s7d+board.s7e=='': moves = '7f7a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'R|L', Bboard.b7f)and b7a==''\ and board.s7b+board.s7c+board.s7d+board.s7e=='': moves = '7f7a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b7f)and b7b==''\ and board.s7c+board.s7d+board.s7e=='': moves = '7f7b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'R|L', Bboard.b7f)and b7b==''\ and board.s7c+board.s7d+board.s7e=='': moves = '7f7b+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|L', Bboard.b7f)and b7c==''\ and board.s7d+board.s7e=='': moves = '7f7c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'R|L', Bboard.b7f)and b7c==''\ and board.s7d+board.s7e=='': moves = '7f7c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R|L', Bboard.b7f)and b7d==''\ and board.s7e=='': moves = '7f7d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b7f)and b7h==''\ and board.s7g=='': moves = '7f7h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b7f)and b7i==''\ and board.s7g+board.s7h=='': moves = '7f7i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b7f)and b9f==''\ and board.s8f=='': moves = '7f9f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b7f)and b5f==''\ and board.s6f=='': moves = '7f5f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b7f)and b4f==''\ and board.s6f+board.s5f=='': moves = '7f4f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b7f)and b3f==''\ and board.s6f+board.s5f+board.s4f=='': moves = '7f3f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b7f)and b2f==''\ and board.s6f+board.s5f+board.s4f+board.s3f=='': moves = '7f2f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|R', Bboard.b7f)and b1f==''\ and board.s6f+board.s5f+board.s4f+board.s3f+board.s2f=='': moves = '7f1f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b7f)and b9h==''\ and board.s8g=='': moves = '7f9h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b7f)and b5d==''\ and board.s6e=='': moves = '7f5d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b7f)and b4c==''\ and board.s6e+board.s5d=='': moves = '7f4c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b7f)and b3b==''\ and board.s6e+board.s5d+board.s4c=='': moves = '7f3b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b7f)and b2a==''\ and board.s6e+board.s5d+board.s4c+board.s3b=='': moves = '7f2a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b7f)and b4i==''\ and board.s5h+board.s6g=='': moves = '7f4i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b7f)and b5h==''\ and board.s6g=='': moves = '7f5h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+B|B', Bboard.b7f)and b9d==''\ and board.s8e=='': moves = '7f9d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B', Bboard.b7f)and b4c==''\ and board.s6e+board.s5d=='': moves = '7f4c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B', Bboard.b7f)and b3b==''\ and board.s6e+board.s5d+board.s4c=='': moves = '7f3b+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B', Bboard.b7f)and b2a==''\ and board.s6e+board.s5d+board.s4c+board.s3b=='': moves = '7f2a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if Bboard.b8f !='': if re.match(r'[PLSGRK+]', Bboard.b8f)and b8e=='': moves = '8f8e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[SGBK+]', Bboard.b8f)and b7e=='': moves = '8f7e' kaihimore(moves) if oute.oute == 0: depth1.append(moves)
sort alphabetically self.all_shapes = sorted(self.all_shapes, key=lambda x: x.qname) # compute top layer exit = [] for c in self.all_shapes: if not c.parents(): exit += [c] self.toplayer_shapes = exit # sorted(exit, key=lambda x: x.id) # doesnt work def build_entity_from_uri(self, uri, ontospyClass=None): """ Extract RDF statements having a URI as subject, then instantiate the RdfEntity Python object so that it can be queried further. Passing <ontospyClass> allows to instantiate a user-defined RdfEntity subclass. NOTE: the entity is not attached to any index. In future version we may create an index for these (individuals?) keeping into account that any existing model entity could be (re)created this way. """ if not ontospyClass: ontospyClass = RdfEntity elif not issubclass(ontospyClass, RdfEntity): printDebug("Error: <%s> is not a subclass of ontospy.RdfEntity" % str(ontospyClass)) return None else: pass qres = self.sparqlHelper.entityTriples(uri) if qres: entity = ontospyClass(rdflib.URIRef(uri), None, self.namespaces, None, self.pref_title, self.pref_lang,) entity.triples = qres entity._buildGraph() # force construction of mini graph # try to add class info test = entity.getValuesForProperty(rdflib.RDF.type) if test: entity.rdftype = test entity.rdftype_qname = [entity._build_qname(x) for x in test] return entity else: return None # ------------ # === methods to refine the ontology structure === # # ------------ def __buildDomainRanges(self, aProp): """ extract domain/range details and add to Python objects """ domains = chain(aProp.rdflib_graph.objects( None, rdflib.term.URIRef(u'http://schema.org/domainIncludes')), aProp.rdflib_graph.objects( None, rdflib.RDFS.domain)) ranges = chain(aProp.rdflib_graph.objects( None, rdflib.term.URIRef(u'http://schema.org/rangeIncludes')), aProp.rdflib_graph.objects( None, rdflib.RDFS.range)) for x in domains: if isBlankNode(x): aProp.domains += [RdfEntity(x, None, self.namespaces, is_Bnode=True)] else: aClass = self.get_class(uri=str(x)) if aClass: aProp.domains += [aClass] aClass.domain_of += [aProp] else: # edge case: it's not an OntoClass instance aProp.domains += [OntoClass(x, None, self.namespaces, True, # ext_model arg self.pref_title, self.pref_lang,)] for x in ranges: if isBlankNode(x): aProp.domains += [RdfEntity(x, None, self.namespaces, is_Bnode=True)] else: aClass = self.get_class(uri=str(x)) if aClass: aProp.ranges += [aClass] aClass.range_of += [aProp] else: # eg a DataType property has xsd:STRING # here we're storing an ontospy entities but not adding it to # the main index aProp.ranges += [OntoClass(x, None, self.namespaces, True, self.pref_title, self.pref_lang,)] def __computeTopLayer(self): """ deprecated: now this is calculated when entities get extracted """ exit = [] for c in self.all_classes: if not c.parents(): exit += [c] self.toplayer_classes = exit # sorted(exit, key=lambda x: x.id) # doesnt work # properties exit = [] for c in self.all_properties: if not c.parents(): exit += [c] self.toplayer_properties = exit # sorted(exit, key=lambda x: x.id) # doesnt work # skos exit = [] for c in self.all_skos_concepts: if not c.parents(): exit += [c] self.toplayer_skos = exit # sorted(exit, key=lambda x: x.id) # doesnt work def __computeInferredProperties(self): """ :return: attach a list of dicts to each class, detailing valid props up the subsumption tree """ exit = [] for c in self.all_classes: c.domain_of_inferred = self.getInferredPropertiesForClass(c, "domain_of") c.range_of_inferred = self.getInferredPropertiesForClass(c, "range_of") def getInferredPropertiesForClass(self, aClass, rel="domain_of"): """ returns all properties valid for a class (as they have it in their domain) recursively ie traveling up the descendants tree Note: results in a list of dicts including itself Note [2]: all properties with no domain info are added at the top as [None, props] :return: [{<Class *http://xmlns.com/foaf/0.1/Person*>: [<Property *http://xmlns.com/foaf/0.1/currentProject*>,<Property *http://xmlns.com/foaf/0.1/familyName*>, etc....]}, {<Class *http://www.w3.org/2003/01/geo/wgs84_pos#SpatialThing*>: [<Property *http://xmlns.com/foaf/0.1/based_near*>, etc...]}, ] """ _list = [] if rel == "domain_of": _list.append({aClass: aClass.domain_of}) for x in aClass.ancestors(): if x.domain_of: _list.append({x: x.domain_of}) # add properties from Owl:Thing ie the inference layer topLevelProps = [p for p in self.all_properties if p.domains == []] if topLevelProps: _list.append({self.OWLTHING: topLevelProps}) elif rel == "range_of": _list.append({aClass: aClass.range_of}) for x in aClass.ancestors(): if x.domain_of: _list.append({x: x.range_of}) # add properties from Owl:Thing ie the inference layer topLevelProps = [p for p in self.all_properties if p.ranges == []] if topLevelProps: _list.append({self.OWLTHING: topLevelProps}) return _list # =============== # methods for retrieving objects # ================ def get_class(self, id=None, uri=None, match=None): """ get the saved-class with given ID or via other methods... Note: it tries to guess what is being passed.. In [1]: g.get_class(uri='http://www.w3.org/2000/01/rdf-schema#Resource') Out[1]: <Class *http://www.w3.org/2000/01/rdf-schema#Resource*> In [2]: g.get_class(10) Out[2]: <Class *http://purl.org/ontology/bibo/AcademicArticle*> In [3]: g.get_class(match="person") Out[3]: [<Class *http://purl.org/ontology/bibo/PersonalCommunicationDocument*>, <Class *http://purl.org/ontology/bibo/PersonalCommunication*>, <Class *http://xmlns.com/foaf/0.1/Person*>] """ if not id and not uri and not match: return None if type(id) == type("string"): uri = id id = None if not is_http(uri): match = uri uri = None if match: if type(match) != type("string"): return [] res = [] if ":" in match: # qname for x in self.all_classes: if match.lower() in x.qname.lower(): res += [x] else: for x in self.all_classes: if match.lower() in x.uri.lower(): res += [x] return res else: for x in self.all_classes: if id and x.id == id: return x if uri and x.uri.lower() == uri.lower(): return x return None def get_property(self, id=None, uri=None, match=None): """ get the saved-class with given ID or via other methods... Note: analogous to getClass method """ if not id and not uri and not match: return None if type(id) == type("string"): uri = id id = None if not is_http(uri): match = uri uri = None if match: if type(match) != type("string"): return [] res = [] if ":" in match: # qname for x in self.all_properties: if match.lower() in x.qname.lower(): res += [x] else: for x in self.all_properties: if match.lower() in x.uri.lower(): res += [x] return res else: for x in self.all_properties: if id and x.id == id: return x if uri and x.uri.lower() == uri.lower(): return x return None def get_skos(self, id=None, uri=None, match=None): """ get the saved skos concept with given ID or via other methods... Note: it tries to guess what is being passed as above """ if not id and not uri and not match: return None if type(id) == type("string"): uri = id id = None if not is_http(uri): match = uri uri = None if match: if type(match) != type("string"): return [] res = [] if ":" in match: # qname for x in self.all_skos_concepts: if match.lower() in x.qname.lower(): res += [x] else: for x in self.all_skos_concepts: if match.lower() in x.uri.lower(): res += [x] return res else: for x in self.all_skos_concepts: if id and x.id == id: return x if uri and x.uri.lower() == uri.lower(): return x return None def get_any_entity(self, id=None, uri=None, match=None): """ get a generic entity with given ID or via other methods... """ if not id and not uri and not match: return None if type(id) == type("string"): uri = id id = None if not is_http(uri): match = uri uri = None if match: if type(match) != type("string"): return [] res = [] if ":" in match: # qname for x in self.all_classes: if match.lower() in x.qname.lower(): res += [x] for x in self.all_properties: if match.lower() in x.qname.lower(): res += [x] else: for x in self.all_classes: if match.lower() in x.uri.lower(): res += [x] for x in self.all_properties: if match.lower() in x.uri.lower(): res += [x] return res else: for x in self.all_classes: if id and x.id == id: return x if uri and x.uri.lower() == uri.lower(): return x for x in self.all_properties: if id and x.id == id: return x if uri and x.uri.lower() == uri.lower(): return x return None def get_ontology(self, id=None, uri=None, match=None): """ get the saved-ontology with given ID or via other methods... """ if not id and not uri and not match: return None if type(id) == type("string"): uri = id id = None if not is_http(uri): match = uri uri = None if match: if type(match) != type("string"): return [] res = [] for x in self.all_ontologies: if match.lower() in x.uri.lower(): res += [x] return res else: for x in self.all_ontologies: if id and x.id == id: return x if uri and x.uri.lower() == uri.lower(): return x return None def nextClass(self, classuri): """Returns the next class in the list of classes. If it's the last one, returns the first one.""" if classuri == self.all_classes[-1].uri: return self.all_classes[0] flag = False for x in self.all_classes: if flag == True: return x if x.uri == classuri: flag = True return None def nextProperty(self, propuri): """Returns the next property in the list of properties. If it's the last one, returns the first one.""" if propuri == self.all_properties[-1].uri: return self.all_properties[0] flag = False for x in self.all_properties: if flag == True: return x if x.uri == propuri: flag = True return None def nextConcept(self, concepturi): """Returns the next skos concept in the list of concepts. If it's the last one, returns the first one.""" if concepturi == self.all_skos_concepts[-1].uri: return self.all_skos_concepts[0] flag = False for x in self.all_skos_concepts: if flag == True: return x if x.uri == concepturi: flag = True return None def ontologyClassTree(self): """ Returns a dict representing the ontology tree Top level = {0:[top classes]} Multi inheritance is represented explicitly """ treedict = {} if self.all_classes: treedict[0] = self.toplayer_classes for element in self.all_classes: if element.children(): treedict[element] = element.children() return treedict return treedict def ontologyPropTree(self): """ Returns a dict representing the ontology tree Top level = {0:[top properties]} Multi inheritance is represented explicitly """ treedict = {} if self.all_properties: treedict[0] = self.toplayer_properties for element in self.all_properties: if element.children(): treedict[element] = element.children() return treedict return treedict def ontologyConceptTree(self): """ Returns a dict representing the skos tree Top level = {0:[top concepts]} Multi inheritance is represented explicitly """ treedict = {} if self.all_skos_concepts: treedict[0] = self.toplayer_skos for element in self.all_skos_concepts: if element.children(): treedict[element] = element.children() return treedict return treedict def ontologyShapeTree(self): """ Returns a dict representing the ontology tree Top level = {0:[top properties]} Multi inheritance is represented explicitly """ treedict = {} if self.all_shapes: treedict[0] = self.toplayer_shapes for element in self.all_shapes: if element.children(): treedict[element] = element.children() return treedict return treedict # ------------ # === utils === # # ------------ def rdf_source(self, format="turtle"): """ Wrapper for rdflib serializer method. Valid options are: xml, n3, turtle, nt, pretty-xml, json-ld [trix not working out of the box] """ s = self.rdflib_graph.serialize(format=format) if isinstance(s, bytes): s = s.decode('utf-8') return s def serialize(self, format="turtle"): "for backward compatibility" return self.rdf_source(format) def query(self, stringa): """SPARQL query / wrapper for rdflib sparql query method """ qres = self.rdflib_graph.query(stringa) return list(qres) def sparql(self, stringa): "SPARQL query / replacement for query" return self.query(stringa) def stats(self): """ shotcut to pull out useful info for a graph""" out = [] out += [("Ontologies", len(self.all_ontologies))] out += [("Triples", self.triplesCount())] out += [("Classes", len(self.all_classes))] out += [("Properties", len(self.all_properties))] out += [("Annotation Properties", len(self.all_properties_annotation))] out += [("Object Properties", len(self.all_properties_object))] out += [("Datatype Properties", len(self.all_properties_datatype))] out += [("Skos Concepts", len(self.all_skos_concepts))] out += [("Data Shapes", len(self.all_shapes))] # out += [("Individuals", len(self.individuals))] @TODO out += [("Data Sources", len(self.sources))] return out def triplesCount(self): """ 2016-08-18 the try/except is a dirty solution to a problem emerging with counting graph length on cached Graph objects.. """ #
value is selected self.click_edit_section('cat_1') self.findBy('xpath', '//span[@class="meter" and @style="width:0%"]') self.findBy('xpath', '//select[@name="qg_3-0-key_4"]') chosen_field = self.findBy('xpath', '//a[@class="chosen-single"]') self.assertEqual(chosen_field.text, '-') # She sees that she can select a Value by mouse click self.select_chosen_element('id_qg_3_0_key_4_chosen', 'Afghanistan') self.assertEqual(chosen_field.text, 'Afghanistan') # She sees that the form progress was updated self.findBy( 'xpath', '//span[@class="meter" and @style="width: 50%;"]') # She submits the form and sees that the value was submitted, # progress of Category 1 is now updated self.submit_form_step() self.findBy('xpath', '//*[text()[contains(.,"Key 4")]]') self.findBy('xpath', '//*[text()[contains(.,"Afghanistan")]]') progress_indicator = self.findBy( 'xpath', '(//div[@class="tech-section-progress"])[2]/span[@class="steps"]') self.assertIn('1/', progress_indicator.text) # She goes back to the form and sees that the value is still selected # and the progress is updated self.click_edit_section('cat_1') self.findBy('xpath', '//select[@name="qg_3-0-key_4"]') chosen_field = self.findBy('xpath', '//a[@class="chosen-single"]') self.assertEqual(chosen_field.text, 'Afghanistan') self.findBy( 'xpath', '//span[@class="meter" and @style="width: 50%;"]') # She selects another value, sees that the form progress is still at # the same value self.select_chosen_element('id_qg_3_0_key_4_chosen', 'Germany') self.assertEqual(chosen_field.text, 'Germany') self.findBy( 'xpath', '//span[@class="meter" and @style="width: 50%;"]') # She submits the form and sees the value was updated self.submit_form_step() self.findBy('xpath', '//*[text()[contains(.,"Key 4")]]') self.findBy('xpath', '//*[text()[contains(.,"Germany")]]') # She submits the entire form and sees the value is on the details page self.review_action('submit') self.findBy('xpath', '//*[text()[contains(.,"Key 4")]]') self.findBy('xpath', '//*[text()[contains(.,"Germany")]]') def test_selects_with_chosen_repeating(self): # Alice logs in self.doLogin() # She goes to a step of the questionnaire self.browser.get(self.live_server_url + reverse( route_questionnaire_new_step, kwargs={'identifier': 'new', 'step': 'cat_0'})) self.rearrangeFormHeader() # She clicks the button to add a non-registered person create_radio = self.findBy( 'xpath', '//input[@name="form-user-radio" and @value="create"]') create_radio.click() # She sees Key 4, which is a select, rendered with Chosen. # Initially, no value is selected. self.findBy('xpath', '//select[@name="qg_31-0-key_4"]') chosen_fields = self.findManyBy('xpath', '//div[contains(@class, "form-user-tab-create")]//a[@class="chosen-single"]') self.assertEqual(len(chosen_fields), 1) self.assertEqual(chosen_fields[0].text, '-') # She sees that she can select a Value by mouse click self.select_chosen_element('id_qg_31_0_key_4_chosen', 'Afghanistan') self.assertEqual(chosen_fields[0].text, 'Afghanistan') # She adds another questiongroup self.findBy('xpath', '//a[@data-questiongroup-keyword="qg_31"]').click() # She clicks the tab to add a non-registered person create_radios = self.findManyBy( 'xpath', '//input[@name="form-user-radio" and @value="create"]') create_radios[1].click() # No idea why 2 clicks are necessary create_radios[1].click() # She sees another chosen field which is empty self.findBy('xpath', '//select[@name="qg_31-1-key_4"]') chosen_fields = self.findManyBy('xpath', '//div[contains(@class, "form-user-tab-create")]//a[@class="chosen-single"]') self.assertEqual(len(chosen_fields), 2) self.assertEqual(chosen_fields[0].text, 'Afghanistan') self.assertEqual(chosen_fields[1].text, '-') self.select_chosen_element('id_qg_31_1_key_4_chosen', 'Germany') chosen_fields = self.findManyBy('xpath', '//div[contains(@class, "form-user-tab-create")]//a[@class="chosen-single"]') self.assertEqual(len(chosen_fields), 2) self.assertEqual(chosen_fields[0].text, 'Afghanistan') self.assertEqual(chosen_fields[1].text, 'Germany') # She submits the form and sees the value was updated self.submit_form_step() self.findBy('xpath', '//*[text()[contains(.,"Key 4")]]') self.findBy('xpath', '//*[text()[contains(.,"Germany")]]') self.findBy('xpath', '//*[text()[contains(.,"Afghanistan")]]') # She submits the entire form and sees the value is on the details page self.review_action('submit') self.findBy('xpath', '//*[text()[contains(.,"Key 4")]]') self.findBy('xpath', '//*[text()[contains(.,"Germany")]]') self.findBy('xpath', '//*[text()[contains(.,"Afghanistan")]]') def test_checkbox(self): # Alice logs in self.doLogin() # She goes to a step of the questionnaire self.browser.get(self.live_server_url + reverse( route_questionnaire_new_step, kwargs={'identifier': 'new', 'step': 'cat_2'})) # She sees that no Checkbox of Key 13 is selected by default self.findByNot( 'xpath', '//input[@name="qg_10-0-key_13" and @checked="checked"]') # She sees that the form progress is at 0 self.findBy('xpath', '//span[@class="meter" and @style="width:0%"]') # She submits the form empty and sees that no value was submitted, # progress of Category 2 is still 0 self.submit_form_step() self.findByNot('xpath', '//*[text()[contains(.,"Key 13")]]') progress_indicator = self.findBy( 'xpath', '(//div[@class="tech-section-progress"])[3]/span[@class="steps"]') self.assertIn('0/', progress_indicator.text) # She goes back to the questionnaire step and sees that form # progress is still at 0 and no checkbox is selected self.click_edit_section('cat_2') self.findBy('xpath', '//span[@class="meter" and @style="width:0%"]') self.findByNot( 'xpath', '//input[@name="qg_10-0-key_13" and @checked="checked"]') # She selects a first checkbox and sees that the form progress # was updated self.findBy( 'xpath', '(//input[@name="qg_10-0-key_13"])[1]').click() self.findBy( 'xpath', '//span[@class="meter" and @style="width: 25%;"]') # She submits the step and sees that the value was submitted and # the form progress on the overview page is updated self.submit_form_step() self.findBy('xpath', '//*[text()[contains(.,"Key 13")]]') self.findBy('xpath', '//*[text()[contains(.,"Value 13_1")]]') progress_indicator = self.findBy( 'xpath', '(//div[@class="tech-section-progress"])[3]/span[@class="steps"]') self.assertIn('1/', progress_indicator.text) # She goes back to the step and sees that the first checkbox is # selected, form progress is at 1 self.click_edit_section('cat_2') self.findBy( 'xpath', '//span[@class="meter" and @style="width: 25%;"]') # She deselects the first value and sees that the progress was # updated self.findBy( 'xpath', '(//input[@name="qg_10-0-key_13"])[1]').click() self.findBy( 'xpath', '//span[@class="meter" and @style="width: 0%;"]') # She then selects the second and third values and submits the # form self.findBy( 'xpath', '(//input[@name="qg_10-0-key_13"])[2]').click() self.findBy( 'xpath', '(//input[@name="qg_10-0-key_13"])[3]').click() self.submit_form_step() # The overview now shows both values self.findBy('xpath', '//*[text()[contains(.,"Key 13")]]') self.findByNot('xpath', '//*[text()[contains(.,"Value 13_1")]]') self.findBy('xpath', '//*[text()[contains(.,"Value 13_2")]]') self.findBy('xpath', '//*[text()[contains(.,"Value 13_3")]]') # She submits the form and sees that the radio value is stored # correctly self.review_action('submit') self.findBy('xpath', '//*[text()[contains(.,"Key 13")]]') self.findByNot('xpath', '//*[text()[contains(.,"Value 13_1")]]') self.findBy('xpath', '//*[text()[contains(.,"Value 13_2")]]') self.findBy('xpath', '//*[text()[contains(.,"Value 13_3")]]') def test_checkbox_other(self): # Alice logs in self.doLogin() # She goes to a step of the questionnaire self.browser.get(self.live_server_url + reverse( route_questionnaire_new_step, kwargs={'identifier': 'new', 'step': 'cat_1'})) self.rearrangeFormHeader() # She sees there are checkboxes and one "other" checkbox with a # textfield cb_1 = self.findBy('id', 'id_qg_36-0-key_50_1_1') cb_2 = self.findBy('id', 'id_qg_36-0-key_50_1_2') other_cb = self.findBy( 'xpath', '//label[@for="id_qg_36-0-original_key_51"]/input[' 'contains(@class, "checkbox-other")]') other_textfield = self.findBy('id', 'id_qg_36-0-original_key_51') # She sees the textfield is readonly self.assertEqual(other_textfield.get_attribute('readonly'), 'true') # She selects the first checkbox, the other checkbox is still not # selected, the textfield readonly cb_1.click() self.assertEqual(other_textfield.get_attribute('readonly'), 'true') self.assertIsNone(other_cb.get_attribute('checked')) # She selects the other checkbox and sees she can now enter some text other_cb.click() self.assertEqual(other_cb.get_attribute('checked'), 'true') self.assertIsNone(other_textfield.get_attribute('readonly')) # She selects another checkbox cb_2.click() self.assertEqual(other_cb.get_attribute('checked'), 'true') self.assertIsNone(other_textfield.get_attribute('readonly')) # She enters some text other_textfield.send_keys('foo content') # She deselects the first checkbox cb_1.click() self.assertEqual(other_cb.get_attribute('checked'), 'true') self.assertIsNone(other_textfield.get_attribute('readonly')) self.assertEqual(other_textfield.get_attribute('value'), 'foo content') # She submits the step and sees the values are both submitted self.submit_form_step() self.findBy('xpath', '//*[text()[contains(.,"medium")]]') self.findBy('xpath', '//*[text()[contains(.,"foo content")]]') # She goes back to the form self.click_edit_section('cat_1') cb_1 = self.findBy('id', 'id_qg_36-0-key_50_1_1') cb_2 = self.findBy('id', 'id_qg_36-0-key_50_1_2') other_cb = self.findBy( 'xpath', '//label[@for="id_qg_36-0-original_key_51"]/input[' 'contains(@class, "checkbox-other")]') other_textfield = self.findBy('id', 'id_qg_36-0-original_key_51') # She sees the correct checkboxes are selected self.assertEqual(cb_2.get_attribute('checked'), 'true') self.assertEqual(other_cb.get_attribute('checked'), 'true') self.assertIsNone(other_textfield.get_attribute('readonly')) self.assertEqual(other_textfield.get_attribute('value'), 'foo content') # She deselects the other checkbox and sees the textfield is emptied other_cb.click() self.assertIsNone(other_cb.get_attribute('checked')) self.assertEqual(other_textfield.get_attribute('readonly'), 'true') self.assertEqual(other_textfield.get_attribute('value'), '') # She selects it again and enters some text other_cb.click() other_textfield.send_keys('foo bar') # She submits the step self.submit_form_step() self.findBy('xpath', '//*[text()[contains(.,"medium")]]') self.findBy('xpath', '//*[text()[contains(.,"foo bar")]]') # She submits the entire questionnaire self.review_action('submit') self.findBy('xpath', '//*[text()[contains(.,"medium")]]') self.findBy('xpath', '//*[text()[contains(.,"foo bar")]]') def test_image_checkbox(self): # Alice logs in self.doLogin() # She goes to a step of the questionnaire self.browser.get(self.live_server_url + reverse( route_questionnaire_new_step, kwargs={'identifier': 'new', 'step': 'cat_4'})) self.rearrangeFormHeader() # She sees that no Checkbox of Key 14 is selected by default self.findByNot( 'xpath', '//input[@name="qg_11-0-key_14" and @checked="checked"]') # She sees that the form progress is at 0 self.findBy('xpath', '//span[@class="meter" and @style="width:0%"]') # She submits the form empty and sees that no value was submitted, # progress of Category 4 is still 0 self.submit_form_step() self.findByNot('xpath', '//article//*[text()[contains(.,"Key 14")]]') progress_indicator = self.findBy( 'xpath', '(//div[@class="tech-section-progress"])[5]/span[@class="steps"]') self.assertIn('0/', progress_indicator.text) WebDriverWait(self.browser, 10).until( EC.visibility_of_element_located((By.ID, "cat_4")) ) # She goes back to the questionnaire step and sees that form # progress is still at 0 and no checkbox is selected self.click_edit_section('cat_4') self.findBy('xpath', '//span[@class="meter" and @style="width:0%"]') self.findByNot( 'xpath', '//input[@name="qg_11-0-key_14" and @checked="checked"]') # She selects a first checkbox and sees that the form progress # was updated self.findBy( 'xpath', '//label[@for="id_qg_11-0-key_14_1"]').click() self.findBy( 'xpath', '//span[@class="meter" and @style="width: 16.6667%;"]') # She submits the step and sees that the value was submitted and # the form progress on the overview page is updated self.submit_form_step() self.findBy('xpath', '//img[@alt="Value 14_1"]') progress_indicator = self.findBy( 'xpath', '(//div[@class="tech-section-progress"])[5]/span[@class="steps"]') self.assertIn('1/', progress_indicator.text) # She goes back to the step and sees that the first checkbox is # selected, form progress is at 1 self.click_edit_section('cat_4') self.findBy( 'xpath', '//span[@class="meter" and @style="width: 16.6667%;"]') # She deselects the first value and sees that the progress was # updated self.findBy( 'xpath', '//label[@for="id_qg_11-0-key_14_1"]').click() self.findBy( 'xpath', '//span[@class="meter" and @style="width: 0%;"]') # She then selects the second and third values and submits the # form self.findBy( 'xpath', '//label[@for="id_qg_11-0-key_14_2"]').click() self.findBy( 'xpath', '//label[@for="id_qg_11-0-key_14_3"]').click() self.submit_form_step() # The overview now shows both values self.findByNot( 'xpath', '//div[contains(@class, "output")]/img[@alt="Value 14_1"]') self.findBy( 'xpath', '//div[contains(@class, "output")]/img[@alt="Value 14_2"]') self.findBy( 'xpath', '//div[contains(@class, "output")]/img[@alt="Value 14_3"]') # She submits the form and sees that the radio value is stored # correctly self.review_action('submit') self.findByNot( 'xpath', '//div[contains(@class, "output")]/img[@alt="Value 14_1"]') self.findBy( 'xpath', '//div[contains(@class, "output")]/img[@alt="Value 14_2"]') self.findBy( 'xpath', '//div[contains(@class, "output")]/img[@alt="Value 14_3"]') def test_measure_conditional(self): # Alice logs in self.doLogin() # She goes to a step of the questionnaire self.browser.get(self.live_server_url + reverse( route_questionnaire_new_step, kwargs={'identifier': 'new', 'step': 'cat_4'})) self.rearrangeFormHeader() # She sees the measure box for Key 21 self.findBy( 'xpath', '//div[@class="button-bar"]/ul/li/input[@name="qg_16-0-key_21"]') # She sees
<gh_stars>1-10 import torch.nn as nn import torch class ConvBnRelu(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, strides=1, padding=0, dilation=1, groups=1, is_bn_relu=False, use_bias=False, name=" "): super(ConvBnRelu, self).__init__() self.block_name = name self.in_channels = in_channels self.out_channels = out_channels self.kernel = kernel_size self.strides = strides self.padding = padding self.groups = groups self.is_bn_relu = is_bn_relu self.relu = nn.ReLU(inplace=True) self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=strides, dilation=dilation, padding=padding, groups=groups, use_bias=use_bias) self.bn = nn.BatchNorm2d(out_channels) def hybrid_forward(self, x): print("********************************") print("this is for checking ConvBnRelu Block Parameters") print("%s --- in_channels: %d, out_channels: %d, kernel_size: %d, strides: %d, padding: %d, groups: %d, is_bn_relu: %s" % (self.block_name, self.in_channels, self.out_channels, self.kernel, self.strides, self.padding, self.groups, self.is_bn_relu)) x = self.conv(x) if self.is_bn_relu: x = self.relu(self.bn(x)) print("Conv BN ReLU") else: x = self.bn(nn.relu(x)) print("Conv ReLU BN") return x class Stem_Block(nn.Module): ''' Stem Block is placed before stage and after input image ''' def __init__(self, in_channels, out_channels, image_size, use_se=False, **kwargs): super(Stem_Block, self).__init__(**kwargs) self.image_size = image_size self.in_channels = in_channels self.out_channels = out_channels self.conv1 = ConvBnRelu(in_channels=in_channels, out_channel=out_channels, kernel_size=3, stride=2, padding=1, is_bn_relu=True) self.branch_maxpool = nn.MaxPool2d((2, 2), (2, 2)) self.branch_conv2 = ConvBnRelu(in_channels=out_channels, out_channel=out_channels//2, kernel_size=1, stride=1, padding=0, is_bn_relu=True) self.branch_conv3 = ConvBnRelu(in_channels=out_channels//2, out_channel=out_channels, kernel_size=3, stride=2, padding=1, is_bn_relu=True) self.concat_conv4 = ConvBnRelu(in_channels=out_channels*2, out_channel=out_channels, kernel_size=1, stride=1, padding=0, is_bn_relu=True) def hybrid_forward(self, x): x = self.conv1(x) # branch 1 x_branch1 = self.branch_conv2(x) x_branch1 = self.branch_conv3(x_branch1) # branch 2 x_branch2 = self.branch_maxpool(x) # concat & conv x_concat = torch.cat(x_branch1, x_branch2, dim = 1) x_out = self.concat_conv4(x_concat) print("#------------------------#") print("this is for VarGNet explore stem block") print("feature maps: %d, in_channels: %d, out_channels: %d" % (self.image_size, self.in_channels, self.out_channels)) return x_out class VarGNet_explore_v2_UnitB(nn.Module): # """VarGNet v1 unit for stride=2""" # Variable Group Network, Transition Block, Highlight: # 1: Inverted Residual Structure Inspired by MobileNet-V2 # 2: Merge two Depthwise Seperable Conv together # 3: Cardinality Introduced By ResNeXt def __init__(self, in_channels, out_channels, image_size, strides=2, group_base=8, factor=2, use_se=False, name=" ", **kwargs): super(VarGNet_explore_v2_UnitB, self).__init__(**kwargs) if strides==2: assert out_channels // in_channels == 2 assert in_channels % 8 == 0 self.in_channels = in_channels self.out_channels = out_channels self.first_increased_channels = in_channels * factor self.second_increased_channels = self.out_channels * factor self.group_base = group_base self.feature_map = image_size self.relu = nn.ReLU(inplace=True) self.se = None ## First cardinality Inverted Residual Structure ## First group conv takes place of depthwise conv self.group_conv1 = ConvBnRelu(in_channels=self.in_channels, out_channels=self.first_increased_channels, kernel_size=3, strides=strides, padding=1, groups=self.in_channels // self.group_base, is_bn_relu=True, name=name+"group_conv1") ## First pointwise conv self.pointwise_conv2 = ConvBnRelu(in_channels=self.first_increased_channels, out_channels=self.out_channels, kernel_size=1, strides=1, padding=0, is_bn_relu=True, name=name+"pointwise_conv2") ## Second cardinality Inverted Residual Structure ## Second group conv takes place of depthwise conv self.group_conv3 = ConvBnRelu(in_channels=self.in_channels , out_channels=self.first_increased_channels, kernel_size=3, strides=strides, padding=1, groups=self.in_channels // self.group_base, is_bn_relu=True, name=name+"group_conv3") ## Second pointwise conv self.pointwise_conv4 = ConvBnRelu(in_channels=self.first_increased_channels, out_channels=self.out_channels, kernel_size=1, strides=1, padding=0, is_bn_relu=True, name=name+"pointwise_conv4") ## group conv takes place of depthwise conv after merging two cardinality together self.group_conv5 = ConvBnRelu(in_channels=self.out_channels, out_channels=self.second_increased_channels, kernel_size=3, strides=1, padding=1, groups=self.first_increased_channels // self.group_base, is_bn_relu=True, name=name+"group_conv5") ## pointwise conv after merging two cardinality together self.pointwise_conv6 = ConvBnRelu(in_channels=self.second_increased_channels, out_channels=out_channels, kernel_size=1, strides=1, padding=0, is_bn_relu=True, name=name+"pointwise_conv6") ## Short Cut Conv ## group conv takes place of depthwise conv self.group_conv7 = ConvBnRelu(in_channels=self.in_channels, out_channels=self.first_increased_channels, kernel_size=3, strides=strides, padding=1, groups=self.in_channels // self.group_base, is_bn_relu=True, name=name+"group_conv7") ## pointwise conv self.pointwise_conv8 = ConvBnRelu(in_channels=self.first_increased_channels, out_channels=out_channels, kernel_size=1, strides=1, padding=0, is_bn_relu=True, name=name+"pointwise_conv8") def hybrid_forward(self, x): # Cardinality Inverted Residual Structure print("###########################################################################################") print("VarGNet Transition Block, Input Feature Size: %d x %d" % (self.feature_map, self.feature_map)) print("VarGNet Transition Block, Input Channels: %d" % (self.in_channels)) print("VarGNet Transition Block, Group Base Channels: %d, Group Numbers: %d" % (self.group_base, self.in_channels // self.group_base)) print("#------------------------------------------------------------") x_cardi1 = self.group_conv1(x) x_cardi1 = self.pointwise_conv2(x_cardi1) x_cardi2 = self.group_conv3(x) x_cardi2 = self.pointwise_conv4(x_cardi2) x_cardi = self.relu(x_cardi1 + x_cardi2) x_cardi = self.group_conv5(x_cardi) x_cardi = self.pointwise_conv6(x_cardi) # Short Cut Branch x_out = self.group_conv7(x) x_out = self.pointwise_conv8(x_out) print("#------------------------------------------------------------") print("VarGNet Transition Block, Cardinality Channels: %d" % (self.first_increased_channels)) print("VarGNet Transition Block, Increased_channels: %d" % (self.second_increased_channels)) x_out = self.relu(x_cardi + x_out) return x_out class VarGNet_explore_v2_UnitA(nn.Module): # """VarGNet v1 unit for stride=1""" # Variable Group Network, Stage Block, Highlight: # 1: Devire from mobilenet MobileNet # 2: Merge two depthwise seperable conv together # 3: Introduce classical residual block def __init__(self, in_channels, out_channels, image_size, strides=1, group_base=8, factor=2, is_shortcut=False, use_se=False, use_sk=False, use_se_global_conv=False, name=" ", **kwargs): super(VarGNet_explore_v2_UnitA, self).__init__() assert in_channels == out_channels assert in_channels % 8 == 0 self.in_channels = in_channels self.out_channels = out_channels self.bottleneck_channels = in_channels * factor self.group_base = group_base self.feature_map = image_size self.is_shortcut = is_shortcut self.relu = nn.ReLU(inplace=True) # First group conv takes place of depthwise conv self.group_conv1 = ConvBnRelu(in_channels=self.in_channels, out_channels=self.bottleneck_channels, kernel_size=3, strides=strides, padding=1, groups=self.in_channels // self.group_base, is_bn_relu=True, name=name+"group_conv1") # First pointwise conv self.pointwise_conv2 = ConvBnRelu(in_channels=self.bottleneck_channels, out_channels=in_channels, kernel_size=1, strides=1, padding=0, is_bn_relu=True, name=name+"pointwise_conv2") # Second group conv takes place of depthwise conv self.group_conv3 = ConvBnRelu(in_channels=in_channels, out_channels=self.bottleneck_channels, kernel_size=3, strides=1, padding=1, groups=self.in_channels // self.group_base, is_bn_relu=True, name=name+"group_conv3") # Second pointwise conv self.pointwise_conv4 = ConvBnRelu(in_channels=self.bottleneck_channels, out_channels=out_channels, kernel_size=1, strides=1, padding=0, is_bn_relu=True, name=name+"pointwise_conv4") if is_shortcut: self.group_conv5 = ConvBnRelu(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=3, strides=strides, padding=1, groups=self.in_channels // self.group_base, is_bn_relu=True, name=name+"group_conv5") # First pointwise conv self.pointwise_conv6 = ConvBnRelu(in_channels=self.out_channels, out_channels=self.out_channels, kernel_size=1, strides=1, padding=0, is_bn_relu=True, name=name+"pointwise_conv6") def hybrid_forward(self, x): print("###########################################################################################") print("VarGNet Stage Block, Input Feature Size: %d x %d" % (self.feature_map, self.feature_map)) print("VarGNet Stage Block, Input Channels: %d" % (self.in_channels)) print("VarGNet Stage Block, Group Base Channels: %d, Group Numbers: %d" % (self.group_base, self.in_channels // self.group_base)) print("VarGNet Stage Block, Bottleneck Channels: %d" % (self.bottleneck_channels)) print("#------------------------------------------------------------") out = self.group_conv1(x) out = self.pointwise_conv2(out) # ---------------------------------------------------------------------------------------------- # script for train_imagenet_vargnet_explore_v2_1x_double_se_ratio2_cosine_batch128_epoch240_submit.sh # script for train_imagenet_vargnet_explore_v2_1x_double_se_ratio4_cosine_batch128_epoch240_submit.sh # if self.se: # print("VarGNet Stage Block, This is for checking first SE_Block") # out = self.se(out) # ---------------------------------------------------------------------------------------------- out = self.group_conv3(out) out = self.pointwise_conv4(out) if self.is_shortcut: print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") print("VarGNet ShortCut: takes place of input data with Conv(3x3) and Conv(1x1)") x = self.group_conv5(x) x = self.pointwise_conv6(x) out = self.relu(x + out) print("#------------------------------------------------------------") return out class VarGNet_explore_V2(nn.Module): """ VarGNet V2 model ---------- block : HybridBlock Class for the VarGNet block. Options are VarGNet V1, VarGNet V2. layers : list of int Numbers of layers in each block channels : list of int Numbers of channels in each block. Length should be one larger than layers list. classes : int, default 1000 Number of classification classes. use_se : bool, default False Whether to use Squeeze-and-Excitation module """ def __init__(self, channels, factor=2, group_base_channels=8, unitB_repeat_list=[1,1,1], unitA_repeat_list=[2,6,3], classes=2, use_se=False, use_se_global_conv=False, **kwargs): super(VarGNet_explore_V2, self).__init__(**kwargs) assert len(unitB_repeat_list) == len(unitA_repeat_list) image_size = 256 last_channels = int(max(channels/32, 1.0)*1024) self.features = nn.Sequential() self.features.add_module('convo', nn.Conv2D(in_channels=3, out_channels=channels, kernel_size=3, strides=2, padding=1, use_bias=False)) self.features.add_module('bn0', nn.BatchNorm(channels)) # self.features.add(nn.MaxPool2D(pool_size=(3, 3), strides=(2, 2), padding=1)) # ---------------------------------------------------------------------------------------------- # script for train_imagenet_vargnet_explore_v2_1x_headstage_se_cosine_batch128_epoch240_submit.sh self.features.add_module('UnitA_0', VarGNet_explore_v2_UnitA(in_channels=channels, out_channels=channels, image_size=image_size//2, strides=2, is_shortcut=True, group_base=group_base_channels, factor=1, use_se_global_conv=False, use_se=use_se, name="VarGNet_explore_v2_head_block")) # script for train_imagenet_vargnet_explore_v2_1x_se_headstage_se_cosine_batch128_epoch240_submit.sh # self.features.add(VarGNet_explore_v2_UnitA(in_channels=channels, out_channels=channels, image_size=image_size//2, strides=2, is_shortcut=True, # group_base=group_base_channels, factor=1, use_se_global_conv=use_se_global_conv, use_se=True, name="VarGNet_explore_v2_head_block")) # ---------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------- # script for train_imagenet_vargnet_explore_v2_1x_stem_cosine_batch128_epoch240_submit.sh # self.features.add(Stem_Block(3, channels, image_size)) # ---------------------------------------------------------------------------------------------- image_size = image_size//4 for i in range(len(unitB_repeat_list)): unitB_repeats, unitA_repeats = unitB_repeat_list[i], unitA_repeat_list[i] for j in range(unitB_repeats): # self.features.add(VarGNet_explore_v2_UnitB(in_channels=channels, out_channels=channels*2, image_size=image_size, # group_base=group_base_channels, factor=factor, use_se=False, name="VarGNet_explore_v2_Downsample_%d_%d_" %(i+1, j+1))) # ---------------------------------------------------------------------------------------------- # script for train_imagenet_vargnet_explore_v2_1x_se_all_ratio2_cosine_batch128_epoch240_submit.sh self.features.add_module('stage%d_UnitB_%d'%(i+1, j+1), VarGNet_explore_v2_UnitB(in_channels=channels, out_channels=channels*2, image_size=image_size, strides=2, group_base=group_base_channels, factor=factor, use_se=False, name="VarGNet_explore_v2_Downsample_%d_%d_" %(i+1, j+1))) # ---------------------------------------------------------------------------------------------- channels = channels*2 image_size = image_size//2 for k in range(unitA_repeats): self.features.add_module('stage%d_UnitA_%d'%(i+1, k+1), VarGNet_explore_v2_UnitA(in_channels=channels, out_channels=channels, image_size=image_size, strides=1, group_base=group_base_channels, factor=factor, use_se_global_conv=use_se_global_conv, use_se=use_se, use_sk=False, name="VarGNet_explore_v2_Stage_%d_%d_"%(i+1, k+1))) self.features.add_module('head_conv0', nn.Conv2d(in_channels = channels, out_channels = last_channels, kernel_size=1, stride=1, padding=0)) self.features.add('head_bn0', nn.BatchNorm2d(last_channels)) self.features.add('head_relu0', nn.ReLU(inplace=True) # replace GlobalAvgPool2D with Global Depthwise Conv # self.features.add(nn.GlobalAvgPool2D()) self.features.add('global_avg_pool', nn.Conv2d(in_channels = last_channels, out_channels = last_channels, kernel_size=image_size, stride=1, padding=0, groups=last_channels, use_bias=False)) self.features.add('head_bn1', nn.BatchNorm(last_channels)) self.features.add_module('head_relu1', nn.ReLU(inplace=True)) self.output = nn.Linear(last_channels, classes) def hybrid_forward(self, x): x = self.features(x) x = x.view(x.size(0), -1) x = self.output(x) return x vargnet_v1_specification ={ 0.25: (8, 2, [3,1], [2,1], int(32*0.25)), 0.5: (8, 2, [3,1], [2,1], int(32*0.5)), 0.75: (8, 2, [3,1], [2,1], int(32*0.75)), 1 : (8, 2, [3,1], [2,1], int(32*1.0)), 1.25: (8, 2, [3,1], [2,1], int(32*1.25)), 1.5 : (8, 2, [3,1], [2,1], int(32*1.5)), 1.75: (8, 2, [3,1], [2,1], int(32*1.75)), 2 : (8, 2, [3,1], [2,1], int(32*2.0)),} vargnet_v2_specification ={ 0.25: (8, 2, [1,1,1], [2,6,3], int(32*0.25)), 0.5: (8, 2, [1,1,1], [2,6,3], int(32*0.5)), 0.75: (8, 2, [1,1,1], [2,6,3], int(32*0.75)), 1 : (8, 2, [1,1,1], [2,6,3], int(32*1.0)), 1.25: (8, 2, [1,1,1], [2,6,3], int(32*1.25)), 1.5 : (8, 2, [1,1,1], [2,6,3], int(32*1.5)), 1.75: (8,
def ws_27(self, ws): """ Cols: Subject Sex Rows: Photographed """ counts = Counter() for media_type, model in tm_person_models.items(): if 'is_photograph' in [field_name.name for field_name in model._meta.get_fields()]: rows = model.objects\ .values('sex', 'is_photograph')\ .filter(**{model.sheet_name() + '__country__in':self.country_list})\ .filter(sex__in=self.male_female_ids)\ .annotate(n=Count('id')) rows = self.apply_weights(rows, model.sheet_db_table(), media_type) counts.update({(r['sex'], r['is_photograph']): r['n'] for r in rows}) self.tabulate(ws, counts, self.male_female, IS_PHOTOGRAPH, row_perc=False) self.tabulate_historical(ws, '27', self.male_female, IS_PHOTOGRAPH, write_row_headings=False) def ws_28(self, ws): """ Cols: Medium, Journalist Sex Rows: Region :: Reporters + Presenters """ overall_column = ws.dim_colmax if self.report_type == 'country': secondary_counts = OrderedDict() for media_type, model in tm_journalist_models.items(): counts = Counter() country = model.sheet_name() + '__country' rows = model.objects\ .values('sex', country)\ .filter(**{country + '__in': self.country_list})\ .filter(sex__in=self.male_female_ids)\ .annotate(n=Count('id')) rows = self.apply_weights(rows, model.sheet_db_table(), media_type) for row in rows: counts.update({(row['sex'], row['country']): row['n']}) secondary_counts[media_type] = counts self.tabulate_secondary_cols(ws, secondary_counts, self.male_female, self.countries, row_perc=True, show_N=True) else: secondary_counts = OrderedDict() for media_type, model in tm_journalist_models.items(): counts = Counter() region = model.sheet_name() + '__country_region__region' rows = model.objects\ .values('sex', region)\ .filter(**{region + '__in': self.all_region_list})\ .filter(sex__in=self.male_female_ids)\ .annotate(n=Count('id')) rows = self.apply_weights(rows, model.sheet_db_table(), media_type) for row in rows: region_id = [r[0] for r in self.all_regions if r[1] == row['region']][0] counts.update({(row['sex'], region_id): row['n']}) secondary_counts[media_type] = counts self.tabulate_secondary_cols(ws, secondary_counts, self.male_female, self.all_regions, row_perc=True, show_N=True) self.tabulate_historical(ws, '28', self.male_female, self.regions, r=7) overall_row = ws.dim_rowmax + 2 ws.write(overall_row, overall_column-1, "Overall", self.label) overall_column +=1 for media_type in secondary_counts: counts = secondary_counts[media_type] value = sum([counts[x] for x in counts if x[0] in self.female_ids]) total = sum(counts.values()) self.write_overall_value(ws, value, total, overall_column, overall_row, write_overall=False) overall_column +=4 def ws_28b(self, ws, gen_dataset=False): """ Cols: Media; Journo Type; Sex Rows: Country :: Newspaper, Television, Radio, Twitter, Internet by region and country """ c = 1 r = 8 write_row_headings = True for media_type, model in journalist_models.items(): if media_type in broadcast_journalist_models: reporter = [('Reporter', [2])] else: # Newspaper journos don't have roles reporter = [('Reporter', [])] col = c + (1 if write_row_headings else 0) merge_range = (len(reporter) * len(self.male_female) * 2) - 1 ws.merge_range(r-4, col, r-4, col + merge_range, clean_title(media_type), self.col_heading) secondary_counts = OrderedDict() if self.report_type == 'country': for journo_type, role_ids in reporter: counts = Counter() country = model.sheet_name() + '__country' rows = model.objects\ .values('sex', country)\ .filter(**{country + '__in': self.country_list})\ .filter(sex__in=self.male_female_ids)\ .annotate(n=Count('id')) if media_type in REPORTER_MEDIA: # Newspaper journos don't have roles rows = rows.filter(role__in=role_ids) rows = self.apply_weights(rows, model.sheet_db_table(), media_type) for row in rows: counts.update({(row['sex'], row['country']): row['n']}) secondary_counts[journo_type] = counts self.tabulate_secondary_cols(ws, secondary_counts, self.male_female, self.countries, row_perc=True, show_N=True, c=c, r=r, write_row_headings=write_row_headings) c += (len(reporter) * len(self.male_female) * 2) + (1 if write_row_headings else 0) write_row_headings = False if gen_dataset: tabulate_dataset("ws_28b", ["Medium", "Gender", "Year", "Geography", "Count"], secondary_counts, ws_28b_dataset, medium=media_type, regions=dict(self.countries)) else: for journo_type, role_ids in reporter: counts = Counter() region = model.sheet_name() + '__country_region__region' rows = model.objects\ .values('sex', region)\ .filter(**{region + '__in': self.all_region_list})\ .filter(sex__in=self.male_female_ids)\ .annotate(n=Count('id')) if media_type in REPORTER_MEDIA: # Newspaper journos don't have roles rows = rows.filter(role__in=role_ids) rows = self.apply_weights(rows, model.sheet_db_table(), media_type) for row in rows: region_id = [reg[0] for reg in self.all_regions if reg[1] == row["region"]][0] counts.update({(row['sex'], region_id): row['n']}) secondary_counts[journo_type] = counts self.tabulate_secondary_cols(ws, secondary_counts, self.male_female, self.all_regions, row_perc=True, show_N=True, c=c, r=r, write_row_headings=write_row_headings) c += (len(reporter) * len(self.male_female) * 2) + (1 if write_row_headings else 0) write_row_headings = False if gen_dataset: tabulate_dataset("ws_28b", ["Medium", "Gender", "Year", "Geography", "Count"], secondary_counts, ws_28b_dataset, medium=media_type, regions=self.all_regions) def ws_28c(self, ws, gen_dataset=False): """ Cols: Media; Journo Type; Sex Rows: Country :: Radio, Television by region and country """ c = 1 r = 8 write_row_headings = True for media_type, model in broadcast_journalist_models.items(): presenter = [('Presenter',[1, 3])] col = c + (1 if write_row_headings else 0) merge_range = (len(presenter) * len(self.male_female) * 2) - 1 ws.merge_range(r-4, col, r-4, col + merge_range, clean_title(media_type), self.col_heading) secondary_counts = OrderedDict() if self.report_type == 'country': for journo_type, role_ids in presenter: counts = Counter() country = model.sheet_name() + '__country' rows = model.objects\ .values('sex', country)\ .filter(**{country + '__in': self.country_list})\ .filter(sex__in=self.male_female_ids)\ .annotate(n=Count('id')) if media_type in REPORTER_MEDIA: # Newspaper journos don't have roles rows = rows.filter(role__in=role_ids) rows = self.apply_weights(rows, model.sheet_db_table(), media_type) for row in rows: counts.update({(row['sex'], row['country']): row['n']}) secondary_counts[journo_type] = counts self.tabulate_secondary_cols(ws, secondary_counts, self.male_female, self.countries, row_perc=True, show_N=True, c=c, r=r, write_row_headings=write_row_headings) c += (len(presenter) * len(self.male_female) * 2) + (1 if write_row_headings else 0) write_row_headings = False if gen_dataset: tabulate_dataset("ws_28c", ["Medium", "Gender", "Year", "Geography", "Count"], secondary_counts, ws_28c_dataset, medium=media_type, regions=dict(self.countries)) else: for journo_type, role_ids in presenter: counts = Counter() region = model.sheet_name() + '__country_region__region' rows = model.objects\ .values('sex', region)\ .filter(**{region + '__in': self.all_region_list})\ .filter(sex__in=self.male_female_ids)\ .annotate(n=Count('id')) if media_type in REPORTER_MEDIA: # Newspaper journos don't have roles rows = rows.filter(role__in=role_ids) rows = self.apply_weights(rows, model.sheet_db_table(), media_type) for row in rows: region_id = [reg[0] for reg in self.all_regions if reg[1] == row["region"]][0] counts.update({(row['sex'], region_id): row['n']}) secondary_counts[journo_type] = counts self.tabulate_secondary_cols(ws, secondary_counts, self.male_female, self.all_regions, row_perc=True, show_N=True, c=c, r=r, write_row_headings=write_row_headings) c += (len(presenter) * len(self.male_female) * 2) + (1 if write_row_headings else 0) write_row_headings = False if gen_dataset: tabulate_dataset("ws_28c", ["Medium", "Gender", "Year", "Geography", "Count"], secondary_counts, ws_28c_dataset, medium=media_type, regions=self.all_regions) def ws_29(self, ws): """ Cols: Regions, Journalist Sex Rows: Scope :: Reporters only """ if self.report_type == 'country': secondary_counts = OrderedDict() for country_code, country_name in self.countries: counts = Counter() for media_type, model in tm_journalist_models.items(): sheet_name = model.sheet_name() country = sheet_name + '__country' scope = sheet_name + '__scope' if 'scope' in [field_name.name for field_name in model._meta.get_field(sheet_name).remote_field.model._meta.get_fields()]: rows = model.objects\ .values('sex', scope)\ .filter(**{country + '__in': self.country_list})\ .filter(sex__in=self.male_female_ids)\ .annotate(n=Count('id')) if media_type in REPORTER_MEDIA: rows = rows.filter(role=REPORTERS) rows = self.apply_weights(rows, model.sheet_db_table(), media_type) for row in rows: counts.update({(row['sex'], row['scope']): row['n']}) secondary_counts[country_name] = counts self.tabulate_secondary_cols(ws, secondary_counts, self.male_female, SCOPE, row_perc=False, show_N=True) else: secondary_counts = OrderedDict() for region_id, region_name in self.regions: counts = Counter() for media_type, model in tm_journalist_models.items(): sheet_name = model.sheet_name() region = sheet_name + '__country_region__region' scope = sheet_name + '__scope' if 'scope' in [field_name.name for field_name in model._meta.get_field(sheet_name).remote_field.model._meta.get_fields()]: rows = model.objects\ .values('sex', scope)\ .filter(**{region: region_name})\ .filter(sex__in=self.male_female_ids)\ .annotate(n=Count('id')) if media_type in REPORTER_MEDIA: rows = rows.filter(role=REPORTERS) rows = self.apply_weights(rows, model.sheet_db_table(), media_type) for row in rows: counts.update({(row['sex'], row['scope']): row['n']}) secondary_counts[region_name] = counts self.tabulate_secondary_cols(ws, secondary_counts, self.male_female, SCOPE, row_perc=False, show_N=True) c = ws.dim_colmax + 2 self.tabulate_historical(ws, '29', self.male_female, SCOPE, write_row_headings=True, c=c, major_cols=self.regions, show_N_and_P=True) def ws_30(self, ws, gen_dataset=False): """ Cols: Region, Sex of reporter Rows: Major Topics :: Reporters only """ overall_column = ws.dim_colmax if self.report_type == 'country': secondary_counts = OrderedDict() for country_code, country_name in self.countries: counts = Counter() for media_type, model in tm_journalist_models.items(): sheet_name = model.sheet_name() country = sheet_name + '__country' topic = sheet_name + '__topic' if 'topic' in [field_name.name for field_name in model._meta.get_field(sheet_name).remote_field.model._meta.get_fields()]: rows = model.objects\ .values('sex', topic)\ .filter(**{country + '__in': self.country_list})\ .filter(sex__in=self.male_female_ids)\ .annotate(n=Count('id')) if media_type in REPORTER_MEDIA: rows = rows.filter(role=REPORTERS) rows = self.apply_weights(rows, model.sheet_db_table(), media_type) for row in rows: major_topic = TOPIC_GROUPS[row['topic']] counts.update({(row['sex'], major_topic): row['n']}) secondary_counts[country_name] = counts self.tabulate_secondary_cols(ws, secondary_counts, self.male_female, MAJOR_TOPICS, row_perc=False, show_N=True) else: secondary_counts = OrderedDict() for region_id, region_name in self.regions: counts = Counter() for media_type, model in tm_journalist_models.items(): sheet_name = model.sheet_name() region = sheet_name + '__country_region__region' topic = sheet_name + '__topic' if 'topic' in [field_name.name for field_name in model._meta.get_field(sheet_name).remote_field.model._meta.get_fields()]: rows = model.objects\ .values('sex', topic)\ .filter(**{region: region_name})\ .filter(sex__in=self.male_female_ids)\ .annotate(n=Count('id')) if media_type in REPORTER_MEDIA: rows = rows.filter(role=REPORTERS) rows = self.apply_weights(rows, model.sheet_db_table(), media_type) for row in rows: major_topic = TOPIC_GROUPS[row['topic']] counts.update({(row['sex'], major_topic): row['n']}) secondary_counts[region_name] = counts self.tabulate_secondary_cols(ws, secondary_counts, self.male_female, MAJOR_TOPICS, row_perc=False, show_N=True) c = ws.dim_colmax + 2 overall_row = ws.dim_rowmax + 2 ws.write(overall_row, overall_column-1, "Overall", self.label) overall_column +=1 for region in secondary_counts: counts = secondary_counts[region] value = sum([counts[x] for x in counts if x[0] in self.female_ids]) total = sum(counts.values()) self.write_overall_value(ws, value, total, overall_column, overall_row, write_overall=False) overall_column +=4 self.tabulate_historical(ws, '30', self.male_female, MAJOR_TOPICS, write_row_headings=True, major_cols=self.regions, c=c, show_N_and_P=True) if gen_dataset: tabulate_dataset("ws_30", ["Topic", "Gender", "Year", "Geography", "Count"], secondary_counts, ws_30_dataset) def ws_31(self, ws): """ Cols: Sex of Reporter Rows: Minor Topics """ counts = Counter() for media_type, model in tm_journalist_models.items(): sheet_name = model.sheet_name() topic = sheet_name + '__topic' if 'topic' in [field_name.name for field_name in model._meta.get_field(sheet_name).remote_field.model._meta.get_fields()]: rows = model.objects\ .values('sex', topic)\ .filter(**{model.sheet_name() + '__country__in':self.country_list})\ .filter(sex__in=self.male_female_ids)\ .annotate(n=Count('id')) if media_type in REPORTER_MEDIA: rows = rows.filter(role=REPORTERS) rows = self.apply_weights(rows, model.sheet_db_table(), media_type) counts.update({(r['sex'], r['topic']): r['n'] for r in rows}) self.tabulate(ws, counts, self.male_female, [y for x in TOPICS for y in x[1]], row_perc=True, filter_cols=self.female)
#!/usr/bin/python # Wrap everything in a single function to avoid polluting the global namespace # more than necessary. def main(): # noqa import ctypes import os import six import sys import warnings AllModules = False if len(sys.argv) == 1 and not hasattr(sys, 'frozen'): AllModules = True if not AllModules and sys.argv[:2][-1] != '--all': pass else: # IMPORT ALL MODULES import modules_pyexe_list # noqa, this is the output of modules_pyexe print(dir(modules_pyexe_list)) # for installers to include submodules # END IMPORT ALL MODULES # Import modules which failed to be included in the auto-generated list. import setuptools._vendor.pyparsing # noqa def alternate_raw_input(prompt=None): """ Write the prompt to stderr, then call raw_input without a prompt. This is to try to mimic better what the python executable does. Enter: prompt: prompt to print to stderr. """ if prompt and len(prompt): sys.stderr.write(prompt) sys.stderr.flush() return six.moves.input('') def get_env_flag(currentValue, key): """ Check if the environment has a key. Parse this as a positive integer, if possible, otherwise treat it like 1. Return the greater of the current value and the parsed value. """ if not os.environ.get(key): return currentValue try: value = int(os.environ.get(key)) if value < 0: value = 1 except ValueError: value = 1 return max(currentValue, value) def print_version(details=1): """ Print the current version. Enter: details: 0 if part of help, 1 for basic verison, 2 for more details. """ from py_version import Version, Description print('%s, Version %s' % (Description, Version)) if details > 1: print('Python %s' % (sys.version)) # pywin32 import win32api fileinfo = win32api.GetFileVersionInfo(win32api.__file__, '\\') print('pywin32: %s' % str(fileinfo['FileVersionLS'] >> 16)) # Others import importlib for module_name in ('pip', 'psutil', 'setuptools', 'six'): module = importlib.import_module(module_name) print('%s: %s' % (module_name, module.__version__)) def run_file(runFile, runFileArgv, skipFirstLine, globenv): """ Exec a file with a limited set of globals. We can't use runpy.run_path for (a) skipped first line, (b) Python 2.7 and zipapps (pyz files). Rather than use run_path in the limited cases where it can be used, we use one code path for executing files in general. Enter: runFile: path of the file to exec. runFileArgv: arguments to set sys.argv to. SkipFileLine: True to skip the first line of the file. globenv: global environment to use. """ import codecs import re import zipfile sys.argv[:] = runFileArgv if zipfile.is_zipfile(os.path.abspath(runFile)): sys.path[0:0] = [runFile] with zipfile.ZipFile(runFile) as zptr: src = zptr.open('__main__.py').read() else: if not Isolated: sys.path[0:0] = [os.path.split(os.path.abspath(runFile))[0]] with open(runFile, 'rb') as fptr: src = fptr.read() # This is similar to what universal newline support does useenc = 'utf-8' if sys.version_info >= (3, ) else 'latin-1' if src.startswith(codecs.BOM_UTF8): useenc = 'utf-8' src = src[len(codecs.BOM_UTF8):] src = src.replace(b'\r\n', b'\n').replace(b'\r', b'\n') if skipFirstLine: src = src.split(b'\n', 1)[1] if b'\n' in src else b'' # first two lines may contain encoding: firsttwo = src.split(b'\n', 2) coding_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)') try: match = coding_re.match(firsttwo[0].decode('utf8')) except Exception: match = None if match: useenc = match.group(1) src = b'\n'.join(firsttwo[1:]) else: try: match = coding_re.match(firsttwo[1].decode('utf8')) except Exception: match = None if match: useenc = match.group(1) src = b'\n'.join(firsttwo[:1] + firsttwo[2:]) src = src.decode(useenc) # If we use anything other than the actual globals() dictionary, # multiprocessing doesn't work. Therefore, mutate globals() and # merge back in when done. globs = globals() originalGlobals = globs.copy() globs.clear() globs.update(globenv) globs['__name__'] = '__main__' globs['__file__'] = runFile six.exec_(src, globs) # globs.clear() globs.update(originalGlobals) def skip_once(cls, method): """ The first time a mthod of a class is called, skip doing the action. Enter: cls: the class instance with the method. method: the name of the method (a string). """ orig = getattr(cls, method, None) def skip(*args, **kwargs): setattr(cls, method, orig) setattr(cls, method, skip) if hasattr(sys, 'frozen'): delattr(sys, 'frozen') Help = False Interactive = None InteractiveArgv = None Isolated = False NoSiteFlag = False Optimize = 0 PrintVersion = 0 QuietFlag = False RunCommand = None RunFile = None RunModule = None SkipFirstLine = False StartupFile = None TabcheckFlag = 0 Unbuffered = False UseEnvironment = True VerboseFlag = 0 Warning3k = 0 WarningBytes = 0 WarningDivision = None WarningOptions = [] skip = 0 sys.dont_write_bytecode = False for i in six.moves.range(1, len(sys.argv)): # noqa if skip: skip -= 1 continue arg = sys.argv[i] if arg.startswith('-') and len(arg) > 1 and arg[1:2] != '-': for let in arg[1:]: if let == 'b': WarningBytes += 1 elif let == 'B': sys.dont_write_bytecode = True elif let == 'c': RunCommand = sys.argv[i+1+skip] RunCommandArgv = ['-c'] + sys.argv[i+2+skip:] skip = len(sys.argv) elif let == 'd': # We don't have to do anything for this flag, since we # never bundle with a debug build of Python pass elif let == 'E': UseEnvironment = False elif let == 'h': Help = True elif let == 'i': Interactive = True elif let == 'I' and sys.version_info >= (3, ): UseEnvironment = False Isolated = True elif let == 'm' and i+1 < len(sys.argv): RunModule = sys.argv[i+1+skip] RunModuleArgv = sys.argv[i+1+skip:] skip = len(sys.argv) elif let == 'O': Optimize += 1 elif let == 'q' and sys.version_info >= (3, ): QuietFlag = True elif let == 'Q' and sys.version_info < (3, ): if arg.startswith('-' + let) and len(arg) > 2: WarningDivision = arg[2:] else: WarningDivision = sys.argv[i+1+skip] skip += 1 if WarningDivision not in ('old', 'warn', 'warnall', 'new'): sys.stderr.write("""-Q option should be `-Qold', `-Qwarn', `-Qwarnall', or `-Qnew' only usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ... Try `%s -h' for more information. """ % (sys.argv[0], sys.argv[0])) sys.exit(2) if arg.startswith('-' + let) and len(arg) > 2: break elif let == 'R': # We can't change the hash seed after start, so ignore it. pass elif let == 's': # We don't have to do anything for this flag, since we # never have a local user site-packages directory in # stand-alone mode pass elif let == 'S': NoSiteFlag = True elif let == 't' and sys.version_info < (3, ): TabcheckFlag += 1 elif let == 'u': Unbuffered = True elif let == 'v': VerboseFlag += 1 elif let == 'V': PrintVersion += 1 elif let == 'W': if arg.startswith('-' + let) and len(arg) > 2: WarningOptions.append(arg[2:]) break else: WarningOptions.append(sys.argv[i+1+skip]) skip += 1 elif let == 'x': SkipFirstLine = True elif let == 'X': # We don't have do anything for this flag, as the basic # implementation doesn't have such options. if arg.startswith('-' + let) and len(arg) > 2: break else: skip += 1 elif let == '3' and sys.version_info < (3, ): Warning3k += 1 TabcheckFlag = max(TabcheckFlag, 1) else: Help = True elif ((arg == '--check-hash-based-pycs' or arg.startswith('--check-hash-based-pycs=')) and sys.version_info >= (3, 6)): # There is no exposure to this option in Python's DLL, so can't do # it if '=' not in arg: skip += 1 elif arg == '--all': pass elif arg == '--help' or arg == '/?': Help = True elif arg == '--version': PrintVersion += 1 elif arg == '-': Interactive = 'check' InteractiveArgv = ['-'] + sys.argv[i+1+skip:] skip = len(sys.argv) elif arg.startswith('-'): Help = True elif not RunFile: RunFile = sys.argv[i+skip] RunFileArgv = sys.argv[i+skip:] skip = len(sys.argv) if Help: print_version(0) print('usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...' % sys.argv[0]) print("""Options and arguments (and corresponding environment variables):""") if sys.version_info >= (3, ): print("""-b : issue warnings about str(bytes_instance), str(bytearray_instance) and comparing bytes/bytearray with str. (-bb: issue errors)""") print("""-B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x -c cmd : program passed in as string (terminates option list) -E : ignore PYTHON* environment variables (such as PYTHONPATH) -h : print this help message and exit (also --help, /?) -i : inspect interactively after running script; forces a prompt even if stdin does not appear to be a terminal; also PYTHONINSPECT=x""") if sys.version_info >= (3, ): print("""-I : isolate Python from the user's environment (implies -E and -s)""") print("""-m mod : run library module
return '%s' % (self.__major) else: return 'any version' def __repr__(self): if self.__major is not None: if self.__minor is not None: if self.__subminor is not None: return 'Version(%s, %s, %s)' % (self.__major, self.__minor, self.__subminor) else: return 'Version(%s, %s)' % (self.__major, self.__minor) else: return 'Version(%s)' % (self.__major) else: return 'Version()' def __contains__(self, other): """Whether a version includes another. >>> Version(1, 2, 3) in Version(1, 2, 3) True >>> Version(1, 2, 2) in Version(1, 2, 3) False >>> Version(1, 2, 4) in Version(1, 2, 3) False >>> Version(1, 2) in Version(1, 2, 3) False >>> Version(1, 2, 3) in Version(1, 2) True >>> Version(1, 3) in Version(1, Range(2, 4)) True >>> Version(1, 2, 3) in Version() True """ if self.__major is not None: if other.__major is None or \ not other.__major in self.__major: return False if self.__minor is not None: if other.__minor is None or \ not other.__minor in self.__minor: return False if self.__subminor is not None: if other.__subminor is None or \ not other.__subminor in self.__subminor: return False return True def __ge__(self, rhs): """Whether a version is greater than another. >>> Version(1, 2, 3) >= Version(1, 2, 3) True >>> Version(1, 2, 4) >= Version(1, 2, 3) True >>> Version(1, 3, 2) >= Version(1, 2, 3) True >>> Version(2, 0, 0) >= Version(1, 10, 23) True >>> Version(1, 2, 3) >= Version(1, 2, 4) False >>> Version(1, 2, 3) >= Version(1, 3, 2) False """ assert self.__major is not None and rhs.__major is not None if self.__major == rhs.__major: minor = self.__minor or 0 rhs_minor = rhs.__minor or 0 if minor == rhs_minor: subminor = self.__subminor or 0 rhs_subminor = rhs.__subminor or 0 return subminor >= rhs_subminor else: return minor > rhs_minor else: return self.__major > rhs.__major def __eq__(self, rhs): return all(getattr(self, a) == getattr(rhs, a) for a in ('major', 'minor', 'subminor')) def __hash__(self): return hash(str(self)) class Runner(Builder): class Reporting(Enumerated, values=['always', 'never', 'on_failure']): pass def __init__(self, exe, args=None, env=None, stdin=None, prefix=None, targets=None, sources=[], runs=1, name=None, timeout=TIMEOUT, out=None, err=None, status=None, bench=None ): ''' name -- the basename for the output files, defaults to exe exe -- the executable to run args -- the arguments env -- environment variables to pass ''' self.__args = args or [] self.__exe = exe self.__name = name or self.__exe # The basename for the output files, e.g. `tests/overlay-kelips`. # Used by `_node` to forge output Nodes such as # `tests/overlay-kelips.out`. self.__basename = Runner.basename(exe, name) self.__out = out or self._node('out') self.__err = err or self._node('err') self.__status = status or self._node('status') self.__bench = bench or self._node('bench') self.__sources = [exe] + sources self.__env = env self.__timeout = timeout self.__runs = runs if stdin is None: self.__input = None elif isinstance(stdin, bytes): self.__input = stdin elif isinstance(stdin, str): self.__input = stdin.encode('utf-8') else: raise Exception( 'stdin must be \"str\" or \"bytes\", got \"%s\"' % type(stdin).__name__) self.__prefix = prefix or [] self.stdout_reporting = Runner.Reporting.never self.stderr_reporting = Runner.Reporting.always import drake.cxx if isinstance(exe, drake.cxx.Executable): self.__sources += exe.dynamic_libraries super().__init__( self.__sources, [self.__out, self.__err, self.__status, self.__bench] + (targets or [])) @staticmethod def basename(exe, name=None): return exe.name_relative.dirname() / (name or exe.path().basename()) @property def status(self): return self.__status def _node(self, ext): '''The Node of an output file. E.g., `self.output('valgrind')` to generate the Valgrind output for this runner.''' return node('{}.{}'.format(self.__basename, ext)) def __reporting_set(self, val): self.stdout_reporting = val self.stderr_reporting = val reporting = property(fget=None, fset=__reporting_set) def _must_report(self, reporting, status): if reporting is Runner.Reporting.always: return True elif reporting is Runner.Reporting.on_failure: return status != 0 else: return False def _report_node(self, node): with open(str(node.path()), 'rb') as f: eol = True while True: b = f.read(4096) if not b: break if eol: eol = False sys.stdout.write(' ') for c in b: if c == '\n': eol = True if c > 127: sys.stdout.write('\\x%x' % c) elif c == '\\': sys.stdout.write('\\\\') else: sys.stdout.write(chr(c)) def _report_node_binary(self, node): with open(str(node.path()), 'rb') as f: while True: b = f.read(4096) if not b: break sys.stdout.buffer.write(b) def execute(self): import subprocess import time def run(): count = 0 with open(str(self.__out.path()), 'w') as out, \ open(str(self.__err.path()), 'w') as err, \ open(str(self.__bench.path()), 'w') as bench, \ open(str(self.__status.path()), 'w') as rv: while count < self.__runs: count += 1 if self.__runs > 1: run_name = 'Run %s/%s' % (count, self.__runs) line = str('-' * len(run_name)) header = '%s%s\n%s\n%s\n' % ( '' if count == 1 else '\n', line, run_name, line) print(header, file=out, flush=True) print(header, file=err, flush=True) if self.__env is not None: output_env = ('%s=%s ' % (var, pipes.quote(str(value))) for var, value in sorted(self.__env.items())) else: output_env = () output_cmd = (pipes.quote(str(a)) for a in self.command) self.output(' '.join(chain(output_env, output_cmd)), 'Run %s%s' % ( self.__name, ' (%s/%s)' % (count, self.__runs) if self.__runs > 1 else '')) env = dict(_OS.environ) if self.__env is not None: env.update(self.__env) env = { k: str(v) for k, v in env.items() } try: start_time = time.time() p = subprocess.Popen([str(c) for c in self.command], stdout=out, stderr=err, stdin=subprocess.PIPE, env=env) if self.__input: p.communicate(self.__input, timeout=self.__timeout) p.wait(timeout=self.__timeout) end_time = time.time() print('%s' % (end_time - start_time), file=bench) status = p.returncode if status != 0: break except Exception: import traceback traceback.print_exc() return False print(status, file=rv) return status status = self._run_job(run) if status is False: return False self._report(status) assert status is not None return status == 0 def _report(self, status): if status: print('{}: exit status: {}'.format(self, status)) if self._must_report(self.stdout_reporting, status): self._report_node(self.__out) if self._must_report(self.stderr_reporting, status): self._report_node(self.__err) @property def command(self): path = str(self.__exe.path()) if not self.__exe.path().absolute(): path = './%s' % path return self.__prefix + [path] + list(map(str, self.__args)) @property def executable(self): return self.__exe def __str__(self): return str(self.__name) def hash(self): return { 'command': self.command, 'env': self.__env, } class TestSuite(Rule): def __init__(self, *args, **kwargs): Rule.__init__(self, *args, **kwargs) self.__success = 0 self.__failures = 0 @property def success(self): return self.__success @property def failures(self): return self.__failures @property def total(self): return self.success + self.failures def report_dependencies(self, deps): failures = [] for dep in deps: if dep.build_status: self.__success += 1 else: failures.append(dep) self.__failures += 1 self.builder.output('%s: %s / %s tests passed.' % (self, self.success, self.total)) def __str__(self): return 'Test suite %s' % self.name() class HTTPDownload(Builder): def __init__(self, url, dest, fingerprint=None, disable_ssl_certificate_validation=False, **kwargs): self.__urls = [url] if isinstance(url, str) else url self.__dest = dest self.__fingerprint = fingerprint Builder.__init__(self, [], [self.__dest]) def execute(self): def job(): self.output('Download {} to {}'.format( pretty_listing(self.__urls, any=True), self.__dest), 'Download {}'.format(self.__dest)) response = None for url in self.__urls: try: response = requests.get(url) except: continue else: if response.status_code == 200: break if response is None: raise Exception( 'unable to download {}'.format( pretty_listing( self.__urls, any=True, quantifier=True))) return response.status_code, response.content status, content = self._run_job(job) if status != 200: print('download failed with status %s' % status, file=sys.stderr) return False if self.__fingerprint is not None: import hashlib d = hashlib.md5() d.update(content) h = d.hexdigest() if h != self.__fingerprint: raise Exception( 'wrong checksum for %s: %s' % (self.__dest, h)) with open(str(self.__dest.path()), 'wb') as f: f.write(content) return True def __str__(self): return 'Download of %s' % self.__dest def __repr__(self): return 'HTTPDownload(%s, %s)' % (self.__urls, self.__dest) def download(url, fingerprint=None, where=drake.Path('.'), name=None, disable_ssl_certificate_validation=False, ): where = drake.Path(where) if name is None: from urllib.parse import urlparse name = drake.Path(urlparse(url).path).basename() target = drake.node(where / name) downloader = drake.HTTPDownload( url, target, fingerprint=fingerprint, disable_ssl_certificate_validation=disable_ssl_certificate_validation, ) return target class ArchiveExtractor(Builder): def __init__(self, tarball, targets=[], patches=None, patch_dir=drake.Path('.')): """ Constructor @param targets: list of paths (not nodes) @param patches: list of (patch_node, strip_level) """ self.__tarball = tarball self.__patches = patches if patches is not None else () self.__patch_dir = drake.Path(patch_dir) directory = self.__tarball.name_relative.dirname() self.__targets = [node(directory / target) for target in targets] self.__destination = self.__tarball.path().dirname() # targets = [] # with tarfile.open(str(self.__tarball.path()), 'r') as f: # for name in f.getnames(): # targets.append(directory / name) # for target in targets: # print(target) # self.__targets = nodes(*targets) patch_nodes = map(lambda x: x[0], self.__patches) Builder.__init__(self, list(chain((tarball,), patch_nodes)), self.__targets, create_directories=False) @property def tarball(self): return self.__tarball @property def destination(self): return self.__destination def execute(self): self.output( 'Extract %s to %s' % (self.__tarball, self.destination), 'Extract %s' % self.__tarball) self._run_job(self.extract) for patch in self.__patches: if not self.cmd( 'Apply %s' % patch[0], [ 'patch', '-N', '-p',
params={ "access_token": "Zenodo access token required with every request.", "bucket_url": "bucket url is found in zenodo.links.bucket", "file_path": "file path of file to upload", }, ) def post(self): """Upload a file into a zenodo deposition""" parser = reqparse.RequestParser() parser.add_argument( "access_token", type=str, required=True, help="access_token is required. accessToken needs to be of type str", ) parser.add_argument( "bucket_url", type=str, required=True, help="bucket_url is required. bucket_url needs to be of type str", ) parser.add_argument( "file_path", type=str, required=True, help="file_path is required. accessToken needs to be of type str", ) args = parser.parse_args() access_token = args["access_token"] bucket_url = args["bucket_url"] file_path = args["file_path"] return uploadFileToZenodoDeposition(access_token, bucket_url, file_path) @zenodo.route("/deposition/metadata", endpoint="zenodoAddMetadata") class zenodoAddMetadata(Resource): @zenodo.doc( responses={200: "Success", 401: "Authentication error"}, params={ "access_token": "Zenodo access token required with every request.", "deposition_id": "deposition id is found in zenodo.id", "metadata": "json string with metadata to add to the deposition", }, ) def post(self): """Add metadata to a zenodo deposition""" parser = reqparse.RequestParser() parser.add_argument( "access_token", type=str, required=True, help="access_token is required. accessToken needs to be of type str", ) parser.add_argument( "deposition_id", type=str, required=True, help="deposition_id is required. deposition_id needs to be of type str", ) parser.add_argument( "metadata", type=str, required=True, help="metadata is required. metadata needs to be a json string", ) args = parser.parse_args() access_token = args["access_token"] deposition_id = args["deposition_id"] metadata = json.loads(args["metadata"]) return addMetadataToZenodoDeposition(access_token, deposition_id, metadata) @zenodo.route("/deposition/publish", endpoint="zenodoPublish") class zenodoPublish(Resource): @zenodo.doc( responses={200: "Success", 401: "Authentication error"}, params={ "access_token": "Zenodo access token required with every request.", "deposition_id": "deposition id of the zenodo object", }, ) def post(self): """Publish a zenodo deposition""" parser = reqparse.RequestParser() parser.add_argument( "access_token", type=str, required=True, help="access_token is required. accessToken needs to be of type str", ) parser.add_argument( "deposition_id", type=str, required=True, help="deposition_id is required. deposition_id needs to be of type str", ) args = parser.parse_args() access_token = args["access_token"] deposition_id = args["deposition_id"] return publishZenodoDeposition(access_token, deposition_id) @zenodo.route("/deposition/files", endpoint="zenodoDeleteFile") class zenodoDeleteFile(Resource): @zenodo.doc( responses={200: "Success", 401: "Authentication error"}, params={ "access_token": "Zenodo access token required with every request.", "deposition_id": "deposition id of the zenodo object", "file_id": "file id of the file to delete", }, ) def delete(self): """Delete a zenodo deposition file""" parser = reqparse.RequestParser() parser.add_argument( "access_token", type=str, required=True, help="access_token is required. accessToken needs to be of type str", ) parser.add_argument( "deposition_id", type=str, required=True, help="deposition_id is required. deposition_id needs to be of type str", ) parser.add_argument( "file_id", type=str, required=True, help="file_id is required. file_id needs to be of type str", ) args = parser.parse_args() access_token = args["access_token"] deposition_id = args["deposition_id"] file_id = args["file_id"] return removeFileFromZenodoDeposition(access_token, deposition_id, file_id) @zenodo.route("/deposition/newversion", endpoint="zenodoNewVersion") class zenodoNewVersion(Resource): @zenodo.doc( responses={200: "Success", 401: "Authentication error"}, params={ "access_token": "Zenodo access token required with every request.", "deposition_id": "deposition id of the zenodo object", }, ) def post(self): """Delete a zenodo deposition""" parser = reqparse.RequestParser() parser.add_argument( "access_token", type=str, required=True, help="access_token is required. accessToken needs to be of type str", ) parser.add_argument( "deposition_id", type=str, required=True, help="deposition_id is required. deposition_id needs to be of type str", ) args = parser.parse_args() access_token = args["access_token"] deposition_id = args["deposition_id"] return createNewZenodoDepositionVersion(access_token, deposition_id) ############################################################################### # GitHub API endpoints ############################################################################### github = api.namespace("github", description="GitHub operations") @github.route("/upload", endpoint="uploadToGithub") class uploadToGithub(Resource): @github.doc( responses={200: "Success", 401: "Validation error"}, params={ "access_token": "GitHub authorization token to upload files", "repo_name": "name of the repository to upload to", "file_name": "file name of file to upload", "file_path": "file path of file to upload", }, ) def post(self): """Upload a file into a GitHub repository""" parser = reqparse.RequestParser() parser.add_argument( "file_path", type=str, required=True, help="file path of file to upload. file_path needs to be of type str", ) parser.add_argument( "file_name", type=str, required=True, help="file_name is required. file_name needs to be of type str", ) parser.add_argument( "access_token", type=str, required=True, help="access_token is required. accessToken needs to be of type str", ) parser.add_argument( "repo_name", type=str, required=True, help="repo_name is required. repo_name needs to be of type str", ) args = parser.parse_args() access_token = args["access_token"] file_name = args["file_name"] file_path = args["file_path"] repo_name = args["repo_name"] return uploadFileToGithub(access_token, file_name, file_path, repo_name) @github.route("/user/repos", endpoint="GetAllRepos") class GetAllRepos(Resource): @github.doc( responses={200: "Success", 401: "Validation error"}, params={ "access_token": "GitHub authorization token for the user", }, ) def get(self): """Get all repositories for a user""" parser = reqparse.RequestParser() parser.add_argument( "access_token", type=str, required=True, help="access_token is required. accessToken needs to be of type str", ) args = parser.parse_args() access_token = args["access_token"] return getUserRepositories(access_token) @github.route("/repo/contributors", endpoint="GetAllContributorsForRepo") class GetAllContributorsForRepo(Resource): @github.doc( responses={200: "Success", 401: "Validation error"}, params={ "access_token": "GitHub authorization token for the user", "owner": "owner of the repository", "repo": "repository name", }, ) def get(self): """Get all contributors for a repository""" parser = reqparse.RequestParser() parser.add_argument( "access_token", type=str, required=True, help="access_token is required. accessToken needs to be of type str", ) parser.add_argument( "owner", type=str, required=True, help="owner is required. owner needs to be of type str", ) parser.add_argument( "repo", type=str, required=True, help="repo is required. repo needs to be of type str", ) args = parser.parse_args() access_token = args["access_token"] owner = args["owner"] repo = args["repo"] return getRepoContributors(access_token, owner, repo) @github.route("/repo/releases", endpoint="GetAllReleasesForRepo") class GetAllReleasesForRepo(Resource): @github.doc( responses={200: "Success", 401: "Validation error"}, params={ "access_token": "GitHub authorization token for the user", "owner": "owner of the repository", "repo": "repository name", }, ) def get(self): """Get all releases for a repository""" parser = reqparse.RequestParser() parser.add_argument( "access_token", type=str, required=True, help="access_token is required. accessToken needs to be of type str", ) parser.add_argument( "owner", type=str, required=True, help="owner is required. owner needs to be of type str", ) parser.add_argument( "repo", type=str, required=True, help="repo is required. repo needs to be of type str", ) args = parser.parse_args() access_token = args["access_token"] owner = args["owner"] repo = args["repo"] return getRepoReleases(access_token, owner, repo) @github.route("/repo/tree", endpoint="getRepoContentsTree") class getRepoContentsTree(Resource): @github.doc( responses={200: "Success", 401: "Validation error"}, params={ "access_token": "GitHub authorization token for the user", "owner": "owner of the repository", "repo": "repository name", }, ) def get(self): """Get repository contents as a tree""" parser = reqparse.RequestParser() parser.add_argument( "access_token", type=str, required=True, help="access_token is required. accessToken needs to be of type str", ) parser.add_argument( "owner", type=str, required=True, help="owner is required. owner needs to be of type str", ) parser.add_argument( "repo", type=str, required=True, help="repo is required. repo needs to be of type str", ) args = parser.parse_args() access_token = args["access_token"] owner = args["owner"] repo = args["repo"] return getRepoContentTree(access_token, owner, repo) @github.route("/repo/file/contents", endpoint="getRepoFileContents") class getRepoFileContents(Resource): @github.doc( responses={200: "Success", 401: "Validation error"}, params={ "access_token": "GitHub authorization token for the user", "owner": "owner of the repository", "repo": "repository name", "file_name": "name of file to be read", }, ) def get(self): """Get the contents of a file in a repository""" parser = reqparse.RequestParser() parser.add_argument( "access_token", type=str, required=True, help="access_token is required. accessToken needs to be of type str", ) parser.add_argument( "owner", type=str, required=True, help="owner is required. owner needs to be of type str", ) parser.add_argument( "repo", type=str, required=True, help="repo is required. repo needs to be of type str", ) parser.add_argument( "file_name", type=str, required=True, help="file_name is required. fileName needs to be of type str", ) args = parser.parse_args() access_token = args["access_token"] owner = args["owner"] repo = args["repo"] file_name = args["file_name"] return getFileFromRepo(access_token, owner, repo, file_name) ############################################################################### # Utilities ############################################################################### utilities = api.namespace("utilities", description="utilities for random tasks") @utilities.route("/checkforfolders", endpoint="checkForFolders") class checkForFolders(Resource): @utilities.doc( responses={200: "Success", 400: "Validation error"}, params={ "folder_path": "folder path to check if sub folders are present.", }, ) def post(self): """Checks if folders are present in the currently provided path""" parser = reqparse.RequestParser() parser.add_argument( "folder_path", type=str, required=True, help="folder path to check if sub folders are present.", ) args = parser.parse_args() folder_path = args["folder_path"] return foldersPresent(folder_path) @utilities.route("/zipfolder", endpoint="ZipFolder") class ZipFolder(Resource): @utilities.doc( responses={200: "Success", 400: "Validation error"}, params={ "folder_path": "folder path to zip.", }, ) def post(self): """Zips a folder""" parser = reqparse.RequestParser() parser.add_argument( "folder_path", type=str, required=True, help="folder path to zip.", ) args = parser.parse_args() folder_path = args["folder_path"] return zipFolder(folder_path) @utilities.route("/deletefile", endpoint="deleteFile") class DeleteFile(Resource): @utilities.doc( responses={200: "Success", 400: "Validation error"}, params={ "file_path": "file path to delete.", }, ) def delete(self): """Deletes a file""" parser = reqparse.RequestParser() parser.add_argument( "file_path", type=str, required=True, help="file path to delete.", ) args = parser.parse_args() file_path = args["file_path"] return deleteFile(file_path) @utilities.route("/requestjson", endpoint="RequestJSON") class RequestJSON(Resource): @utilities.doc( responses={200: "Success", 400: "Validation error"}, params={ "url": "url to request from the web.", }, ) def get(self): """request a json file from the web""" parser = reqparse.RequestParser() parser.add_argument( "url", type=str, required=True, help="url that needs a CORS proxy", ) args = parser.parse_args() url = args["url"] return requestJSON(url) @utilities.route("/createfile", endpoint="CreateFile") class CreateFile(Resource): @utilities.doc( responses={200:
import logging import re import datetime from django import forms from django.conf import settings from django.core.cache import cache from django.db.models.signals import pre_save, pre_delete from django.http import HttpResponseRedirect, HttpResponse, JsonResponse, Http404 # Create your views here. from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.text import Truncator from django.views.decorators.cache import never_cache from django.views.generic import ListView, DetailView, CreateView, UpdateView, FormView, RedirectView from haystack.generic_views import SearchView from notifications.signals import notify from Blog.signals import refresh_cache_signals_save_articles, refresh_cache_signals_delete_articles from account.models import BlogUser, Attention from blogs.form import ArticleEditForm, MySearchForm from collection.models import Collection from comment.form import CommentForm from blogs.models import Artical from appeal.forms import AppealForm import math logger = logging.getLogger("django") class BaseArticleView(ListView): paginate_by = 5 key_prefix = "" def get_cache_data(self,key): key = self.key_prefix.format(key[0],key[1]) if cache.get(key): res = cache.get(key) return res else: return None def set_cache_data(self,key,value): key = self.key_prefix.format(key[0],key[1]) cache.set(key,value) class IndexView(BaseArticleView): template_name = "blogs/article_index.html" cur_page = 1 key_prefix = "article-index-{}-{}" def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() allow_empty = self.get_allow_empty() if not allow_empty: # When pagination is enabled and object_list is a queryset, # it's better to do a cheap query than to load the unpaginated # queryset in memory. if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'): is_empty = not self.object_list.exists() else: is_empty = not self.object_list if is_empty: raise Http404(_('Empty list and “%(class_name)s.allow_empty” is False.') % { 'class_name': self.__class__.__name__, }) context = self.get_context_data() if request.is_ajax(): try: object_list = [] for o in list(context["object_list"]): temp = {} temp["title"] = o.title img = re.findall(r'img src="(.*?)"', o.body, re.S) if len(img) > 0: img = img[0] else: img = "" temp["img_url"] = img body = re.sub(u"\<.*?\>", "", o.body) body = Truncator(body).chars(70) img_static = settings.DOMAIN+"static/image/design/" thumb_up_img = img_static + "点赞 (5).png" collections_img = img_static + "article_collectio.png" comment_img = img_static + "评论 (3).png" temp["thumb_up_img"] = thumb_up_img temp["collections_img"] = collections_img temp["comment_img"] = comment_img temp["body"] = body temp["comment_counts"] = o.comment_set.count() temp["thump_up_counts"] = o.thumb_up temp["collection_count"] = o.article.count() temp["article_url"] = o.get_absolute_url() object_list.append(temp) page_has_next = context["page_obj"].has_next() loc = self.request.GET.get("loc") return JsonResponse( { "object_list":object_list, "page_has_next":page_has_next, "loc":loc } ) except Exception as e: print(e) else: headers = self.get_queryset().order_by("-views")[:5] context["headers"] =headers return self.render_to_response(context) def get_queryset(self): articles = self.get_cache_data(("article","")) if not articles: articles = Artical.objects.filter(status="e") self.set_cache_data(("articles",""),articles) return articles def get_context_data(self, *, object_list=None, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) img_path = settings.MEDIA_URL + "/" + str(self.request.user.head_path) context["img_path"] = img_path context["user"] = self.request.user return context class Article_Detail(DetailView): template_name = "blogs/article_detail.html" model = Artical context_object_name = "article" pk_url_kwarg = "article_id" def dispatch(self, request, *args, **kwargs): return super(Article_Detail,self).dispatch(request,*args,**kwargs) def get_object(self, queryset=None): obj = super(Article_Detail, self).get_object(queryset=queryset) self.obj = obj self.obj.viewed() return obj def get_context_data(self, **kwargs): context = super(Article_Detail, self).get_context_data(**kwargs) comment_form = CommentForm() comment_form.fields.update({ "name": forms.CharField(widget=forms.HiddenInput), "article_id": forms.IntegerField(widget=forms.HiddenInput), "email": forms.EmailField(widget=forms.HiddenInput) }) follower_list = [] user = BlogUser.objects.get(username=self.request.user.username) followers = user.user.all() for f in followers: follower_list.append(BlogUser.objects.get(username=f.B_follower)) user = self.request.user username = user.username comment_form.fields["name"].initial = username comment_form.fields["article_id"].initial = self.obj.id appeal_form = AppealForm() appeal_form.fields["appealed_article"].initial = self.obj context["appeal_form"] = appeal_form result = Collection.objects.filter(blog_user__username=username,collected_article=self.obj) is_collected = False if result: is_collected = True else: is_collected = False context["follower_list"] = follower_list context["is_collected"] = is_collected collected_count = Collection.objects.filter(collected_article=self.obj).count() context["collected_count"] = collected_count comment_form.fields["email"].initial = user.email img_path = cache.get("img_path", None) if not img_path: img_path = settings.MEDIA_URL+"/"+str(user.head_path) context["img_path"] = img_path context["comment_dict"], context["header"] = self.obj.get_comment_list() context["form"] = comment_form follower = context["object"].author if follower.username != self.request.user.username: context["is_show"] = True if follower in follower_list: context["is_follower"] = True else: context["is_follower"] = False else: context["is_show"] = False return context class ArticleDealView(RedirectView): @method_decorator(never_cache) def post(self, request, *args, **kwargs): if request.is_ajax(): try: get_type = request.POST.get("type") title = request.POST.get("title") username = request.POST.get("author") author = BlogUser.objects.get(username=username) article = Artical.objects.get(title=title,author=author) result = 0 recipient = author verb = "" target = article action_object = None description = "" if get_type == "thumb_up":#点赞 article.thumb_up+=1 article.save() result = 1 verb = "点赞" description = "thump" action_object = "thump" if get_type == "collection": # 收藏 collection = Collection(blog_user=self.request.user, collected_article=article) collection.save() result = 3 verb = "收藏" description = "collection" action_object = collection elif get_type == "cancleCollection":#取消收藏 collection = Collection.objects.get(collected_article=article,blog_user=self.request.user) collection.delete() result = 4 verb = "取消收藏" action_object = collection description = "collection" notify.send( self.request.user, recipient=recipient, verb=verb, target=article, action_object=action_object, description=description ) except Exception as e: print(e) return JsonResponse( {"result":result} ) class ArticleEditView(CreateView): form_class = ArticleEditForm template_name = "blogs/editarticle/editArticle.html" def form_valid(self, form): article_form = form.save(False) article_form.author = self.request.user pre_save.connect(refresh_cache_signals_save_articles,sender=Artical) article_form.save(True) url = reverse("blog:index") return HttpResponseRedirect(url) def form_invalid(self, form): form.fields["title"].initial = form.cleaned_data["title"] form.fields["status"].initial = form.cleaned_data["status"] error_message="" try: form.fields["body"].initial = form.cleaned_data["body"] except KeyError as e: error_message = "文章内容不能为空" return self.render_to_response( { "form": form, "error_message":error_message } ) class ArticleUpdateVuew(UpdateView): form_class = ArticleEditForm template_name = "blogs/updateArticle.html" model = Artical def get(self, request, *args, **kwargs): get_type = request.GET.get("type") pk = kwargs["pk"] if get_type == "remove": pre_delete.connect(refresh_cache_signals_delete_articles,sender=Artical) Artical.objects.get(pk=pk).delete() return HttpResponseRedirect(reverse( "blog:manageArticle" )) elif get_type=="draw": article = Artical.objects.get(pk=pk) article.status = "d" article.save() return HttpResponseRedirect(reverse( "blog:manageArticle" )) elif get_type == "express": article = Artical.objects.get(pk=pk) article.status = "e" article.save() return HttpResponseRedirect(reverse( "blog:manageArticle" )) else: return super(ArticleUpdateVuew,self).get(request,*args,**kwargs) def get_context_data(self, **kwargs): context = super(ArticleUpdateVuew,self).get_context_data(**kwargs) pk = self.request.GET.get("pk") context["pk"] = pk return context # @method_decorator(cache_page(60*60*24),name="dispatch") class PersonaBlogView(BaseArticleView): template_name = 'blogs/person.html' key_prefix = "blog/person/personalArticle-{}-{}" model = Artical paginate_by = 8 def get_cache_key(self,username): return self.key_prefix.format(username) def get_follower_list(self,username): follower_list = [] user = BlogUser.objects.get(username=username) follower = Attention.objects.filter(user_id=user) self.set_cache_data(("follower-users", username), follower) for f in follower: users = BlogUser.objects.filter(username=f.B_follower) for u in users: follower_list.append(u) return follower_list def get_queryset(self): get_type = self.request.GET.get("type") username = self.request.GET.get("username") follower_list = [] if not username: user = self.request.user username = user.username else: user = BlogUser.objects.get(username=username) if not get_type: articles = self.get_cache_data(("articles",username)) if not articles: articles = Artical.objects.filter(author=user) time = datetime.datetime.now() - datetime.timedelta(days=2) articles = articles.filter(pub_time__gte=time) self.set_cache_data(("articles",username),articles) return articles else: get_type = int(get_type) if get_type == 1: follower_list = self.get_cache_data(("attention-follower-user",username)) follower_list = follower_list if follower_list else [] if not follower_list: follower_list = self.get_follower_list(username) return follower_list elif get_type == 2: follower_list = self.get_cache_data(("attention-fans-user",username)) follower_list = follower_list if follower_list else [] if not follower_list: fans = Attention.objects.filter(B_follower=user) for f in fans: users = BlogUser.objects.filter(username=f.user) for u in users: follower_list.append(u) return follower_list elif get_type == 3: pass elif get_type == 4: collection_list = self.get_cache_data(("collections-article",username)) collection_list = collection_list if collection_list else [] if not collection_list: collection = Collection.objects.filter(blog_user=user) collection_list = [] for col in collection: collection_list.append(Artical.objects.get(pk=col.collected_article_id)) return collection_list def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() allow_empty = self.get_allow_empty() if not allow_empty: # When pagination is enabled and object_list is a queryset, # it's better to do a cheap query than to load the unpaginated # queryset in memory. if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'): is_empty = not self.object_list.exists() else: is_empty = not self.object_list if is_empty: raise Http404(_('Empty list and “%(class_name)s.allow_empty” is False.') % { 'class_name': self.__class__.__name__, }) get_type = self.request.GET.get("type") username = self.request.GET.get("username") if not username: user = self.request.user else: user = BlogUser.objects.get(username=username) follower_list = self.get_cache_data(("main-attention-follower_list",self.request.user.username)) follower_list = follower_list if follower_list else [] if not follower_list: follower_list = self.get_follower_list(self.request.user.username) self.set_cache_data(("main-attention-follower_list",self.request.user.username),follower_list) if get_type: get_type = int(get_type) info = {} """ get_type 为空,显示最新动态 get_type 为1,显示关注用户列表 get_type 为2,显示f粉丝用户列表 get_type 为3,显示随笔列表 get_type 为4,显示收藏列表 """ articles = self.get_cache_data(("all_articles",username)) if not articles: articles = Artical.objects.filter(author=user) self.set_cache_data(("all_articles",username),articles) if get_type == 3: self.object_list = articles context = self.get_context_data() person_character_count = 0 person_article_count = len(articles) if get_type==1: for u in context["object_list"]: follower_count = Attention.objects.filter(user=u).count() collection_count = Collection.objects.filter(blog_user=u).count() article = Artical.objects.filter(author=u) character_count = 0 for a in article: character_count += len(a.body) article_count = len(article) info[u.username] = {"follower_count": follower_count, "collection_count": collection_count, "character_count": character_count, "article_count": article_count} context["info"] = info elif get_type == 2: for u in context["object_list"]: follower_count = Attention.objects.filter(user=u).count() collection_count = Collection.objects.filter(blog_user=u).count() article = Artical.objects.filter(author=u) character_count = 0 for a in article: character_count += len(a.body) article_count = len(article) info[u.username] = {"follower_count": follower_count, "collection_count": collection_count, "character_count": character_count, "article_count": article_count} context["info"] = info for a in articles: person_character_count+=len(a.body) context["person_character_count"] = person_character_count context["person_article_count"] = person_article_count context["user"] = user context["type"] = get_type context["follower_list"] = follower_list return self.render_to_response(context) class ArticleManagerView(BaseArticleView): template_name = "blogs/editarticle/article_manager.html" model = Artical key_prefix = "article-manager-{}-{}" def get_queryset(self): author = self.request.user articles = self.get_cache_data(("articles",author.username)) if not articles: articles = Artical.objects.filter(author=author) self.set_cache_data(("articles",author.username),articles) get_type = self.request.GET.get("type") if not get_type: return articles else: get_type = int(get_type) if get_type == 1: articles=articles.order_by("-pub_time")#时间降序 elif get_type == 2: articles=articles.order_by("pub_time")#时间升序 elif get_type == 3: articles=articles.order_by("-thumb_up")#点赞数降序 elif get_type == 4: articles=articles.order_by("thumb_up")#点赞数升序 elif get_type == 5: articles=articles.order_by("-views")#阅读量降序 elif get_type == 6: articles=articles.order_by("views")#阅读量升序 return articles class MySearchView(SearchView): """My custom search view.""" template_name =
"ctype" : self._ctype, "refname" : self._refname, "optpointer" : self._optpointer and "*" or "", "optreference" : self._optpointer and "&" or "", "optaddarg" : self._optaddarg and ", const %s value" % self._ctype or "" } for (k, v) in extradict.items(): mapping[k] = v return mapping def GetVarName(self, var): return '%(var)s->%(name)s_data' % self.GetTranslation({ 'var' : var }) def GetVarLen(self, var): return 'sizeof(%s)' % self._ctype def GetFuncName(self): return '%s_%s_get' % (self._struct.Name(), self._name) def GetDeclaration(self, funcname): code = [ 'int %s(struct %s *, %s *);' % ( funcname, self._struct.Name(), self._ctype ) ] return code def CodeGet(self): code = ( 'int', '%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, ' '%(ctype)s *value)', '{', ' if (msg->%(name)s_set != 1)', ' return (-1);', ' *value = msg->%(name)s_data;', ' return (0);', '}' ) code = '\n'.join(code) code = code % self.GetTranslation() return code.split('\n') def AssignFuncName(self): return '%s_%s_assign' % (self._struct.Name(), self._name) def AddFuncName(self): return '%s_%s_add' % (self._struct.Name(), self._name) def AssignDeclaration(self, funcname): code = [ 'int %s(struct %s *, const %s);' % ( funcname, self._struct.Name(), self._ctype ) ] return code def CodeAssign(self): code = [ 'int', '%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,' ' const %(ctype)s value)', '{', ' msg->%(name)s_set = 1;', ' msg->%(name)s_data = value;', ' return (0);', '}' ] code = '\n'.join(code) code = code % self.GetTranslation() return code.split('\n') def CodeClear(self, structname): code = [ '%s->%s_set = 0;' % (structname, self.Name()) ] return code def CodeComplete(self, structname, var_name): return [] def CodeFree(self, name): return [] def CodeBase(self): code = [ '%(parent_name)s_%(name)s_assign,', '%(parent_name)s_%(name)s_get,' ] if self.Array(): code.append('%(parent_name)s_%(name)s_add,') code = '\n'.join(code) code = code % self.GetTranslation() return code.split('\n') class EntryBytes(Entry): def __init__(self, type, name, tag, length): # Init base class Entry.__init__(self, type, name, tag) self._length = length self._ctype = 'ev_uint8_t' def GetInitializer(self): return "NULL" def GetVarLen(self, var): return '(%s)' % self._length def CodeArrayAdd(self, varname, value): # XXX: copy here return [ '%(varname)s = NULL;' % { 'varname' : varname } ] def GetDeclaration(self, funcname): code = [ 'int %s(struct %s *, %s **);' % ( funcname, self._struct.Name(), self._ctype ) ] return code def AssignDeclaration(self, funcname): code = [ 'int %s(struct %s *, const %s *);' % ( funcname, self._struct.Name(), self._ctype ) ] return code def Declaration(self): dcl = ['ev_uint8_t %s_data[%s];' % (self._name, self._length)] return dcl def CodeGet(self): name = self._name code = [ 'int', '%s_%s_get(struct %s *msg, %s **value)' % ( self._struct.Name(), name, self._struct.Name(), self._ctype), '{', ' if (msg->%s_set != 1)' % name, ' return (-1);', ' *value = msg->%s_data;' % name, ' return (0);', '}' ] return code def CodeAssign(self): name = self._name code = [ 'int', '%s_%s_assign(struct %s *msg, const %s *value)' % ( self._struct.Name(), name, self._struct.Name(), self._ctype), '{', ' msg->%s_set = 1;' % name, ' memcpy(msg->%s_data, value, %s);' % ( name, self._length), ' return (0);', '}' ] return code def CodeUnmarshal(self, buf, tag_name, var_name, var_len): code = [ 'if (evtag_unmarshal_fixed(%(buf)s, %(tag)s, ' '%(var)s, %(varlen)s) == -1) {', ' event_warnx("%%s: failed to unmarshal %(name)s", __func__);', ' return (-1);', '}' ] return TranslateList(code, self.GetTranslation({ 'var' : var_name, 'varlen' : var_len, 'buf' : buf, 'tag' : tag_name })) def CodeMarshal(self, buf, tag_name, var_name, var_len): code = ['evtag_marshal(%s, %s, %s, %s);' % ( buf, tag_name, var_name, var_len)] return code def CodeClear(self, structname): code = [ '%s->%s_set = 0;' % (structname, self.Name()), 'memset(%s->%s_data, 0, sizeof(%s->%s_data));' % ( structname, self._name, structname, self._name)] return code def CodeInitialize(self, name): code = ['memset(%s->%s_data, 0, sizeof(%s->%s_data));' % ( name, self._name, name, self._name)] return code def Verify(self): if not self._length: raise RpcGenError( 'Entry "%s" needs a length ' 'around line %d' % (self._name, self.LineCount())) Entry.Verify(self) class EntryInt(Entry): def __init__(self, type, name, tag, bits=32): # Init base class Entry.__init__(self, type, name, tag) self._can_be_array = 1 if bits == 32: self._ctype = 'ev_uint32_t' self._marshal_type = 'int' if bits == 64: self._ctype = 'ev_uint64_t' self._marshal_type = 'int64' def GetInitializer(self): return "0" def CodeArrayFree(self, var): return [] def CodeArrayAssign(self, varname, srcvar): return [ '%(varname)s = %(srcvar)s;' % { 'varname' : varname, 'srcvar' : srcvar } ] def CodeArrayAdd(self, varname, value): """Returns a new entry of this type.""" return [ '%(varname)s = %(value)s;' % { 'varname' : varname, 'value' : value } ] def CodeUnmarshal(self, buf, tag_name, var_name, var_len): code = [ 'if (evtag_unmarshal_%(ma)s(%(buf)s, %(tag)s, &%(var)s) == -1) {', ' event_warnx("%%s: failed to unmarshal %(name)s", __func__);', ' return (-1);', '}' ] code = '\n'.join(code) % self.GetTranslation({ 'ma' : self._marshal_type, 'buf' : buf, 'tag' : tag_name, 'var' : var_name }) return code.split('\n') def CodeMarshal(self, buf, tag_name, var_name, var_len): code = [ 'evtag_marshal_%s(%s, %s, %s);' % ( self._marshal_type, buf, tag_name, var_name)] return code def Declaration(self): dcl = ['%s %s_data;' % (self._ctype, self._name)] return dcl def CodeInitialize(self, name): code = ['%s->%s_data = 0;' % (name, self._name)] return code class EntryString(Entry): def __init__(self, type, name, tag): # Init base class Entry.__init__(self, type, name, tag) self._can_be_array = 1 self._ctype = 'char *' def GetInitializer(self): return "NULL" def CodeArrayFree(self, varname): code = [ 'if (%(var)s != NULL) free(%(var)s);' ] return TranslateList(code, { 'var' : varname }) def CodeArrayAssign(self, varname, srcvar): code = [ 'if (%(var)s != NULL)', ' free(%(var)s);', '%(var)s = strdup(%(srcvar)s);', 'if (%(var)s == NULL) {', ' event_warnx("%%s: strdup", __func__);', ' return (-1);', '}' ] return TranslateList(code, { 'var' : varname, 'srcvar' : srcvar }) def CodeArrayAdd(self, varname, value): code = [ 'if (%(value)s != NULL) {', ' %(var)s = strdup(%(value)s);', ' if (%(var)s == NULL) {', ' goto error;', ' }', '} else {', ' %(var)s = NULL;', '}' ] return TranslateList(code, { 'var' : varname, 'value' : value }) def GetVarLen(self, var): return 'strlen(%s)' % self.GetVarName(var) def CodeMakeInitalize(self, varname): return '%(varname)s = NULL;' % { 'varname' : varname } def CodeAssign(self): name = self._name code = """int %(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg, const %(ctype)s value) { if (msg->%(name)s_data != NULL) free(msg->%(name)s_data); if ((msg->%(name)s_data = strdup(value)) == NULL) return (-1); msg->%(name)s_set = 1; return (0); }""" % self.GetTranslation() return code.split('\n') def CodeUnmarshal(self, buf, tag_name, var_name, var_len): code = ['if (evtag_unmarshal_string(%(buf)s, %(tag)s, &%(var)s) == -1) {', ' event_warnx("%%s: failed to unmarshal %(name)s", __func__);', ' return (-1);', '}' ] code = '\n'.join(code) % self.GetTranslation({ 'buf' : buf, 'tag' : tag_name, 'var' : var_name }) return code.split('\n') def CodeMarshal(self, buf, tag_name, var_name, var_len): code = ['evtag_marshal_string(%s, %s, %s);' % ( buf, tag_name, var_name)] return code def CodeClear(self, structname): code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()), ' free(%s->%s_data);' % (structname, self.Name()), ' %s->%s_data = NULL;' % (structname, self.Name()), ' %s->%s_set = 0;' % (structname, self.Name()), '}' ] return code def CodeInitialize(self, name): code = ['%s->%s_data = NULL;' % (name, self._name)] return code def CodeFree(self, name): code = ['if (%s->%s_data != NULL)' % (name, self._name), ' free (%s->%s_data);' % (name, self._name)] return code def Declaration(self): dcl = ['char *%s_data;' % self._name] return dcl class EntryStruct(Entry): def __init__(self, type, name, tag, refname): # Init base class Entry.__init__(self, type, name, tag) self._optpointer = False self._can_be_array = 1 self._refname = refname self._ctype = 'struct %s*' % refname self._optaddarg = False def GetInitializer(self): return "NULL" def GetVarLen(self, var): return '-1' def CodeArrayAdd(self, varname, value): code = [ '%(varname)s = %(refname)s_new();', 'if (%(varname)s == NULL)', ' goto error;' ] return TranslateList(code, self.GetTranslation({ 'varname' : varname })) def CodeArrayFree(self, var): code = [ '%(refname)s_free(%(var)s);' % self.GetTranslation( { 'var' : var }) ] return code def CodeArrayAssign(self, var, srcvar): code = [ 'int had_error = 0;', 'struct evbuffer *tmp = NULL;', '%(refname)s_clear(%(var)s);', 'if ((tmp = evbuffer_new()) == NULL) {', ' event_warn("%%s: evbuffer_new()", __func__);', ' had_error = 1;', ' goto done;', '}', '%(refname)s_marshal(tmp, %(srcvar)s);', 'if (%(refname)s_unmarshal(%(var)s, tmp) == -1) {', ' event_warnx("%%s: %(refname)s_unmarshal", __func__);', ' had_error = 1;', ' goto done;', '}', 'done:' 'if (tmp != NULL)', ' evbuffer_free(tmp);', 'if (had_error) {', ' %(refname)s_clear(%(var)s);', ' return (-1);', '}' ] return TranslateList(code, self.GetTranslation({ 'var' : var, 'srcvar' : srcvar})) def CodeGet(self): name = self._name code = [ 'int', '%s_%s_get(struct %s *msg, %s *value)' % ( self._struct.Name(), name, self._struct.Name(), self._ctype), '{', ' if (msg->%s_set != 1) {' % name, ' msg->%s_data = %s_new();' % (name, self._refname), '
############################################################################ # # Copyright (c) 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################ """Adapter-style interface registry This implementation is based on a notion of "surrogate" interfaces. $Id: adapter.py 38178 2005-08-30 21:50:19Z mj $ """ # Implementation notes # We keep a collection of surrogates. # A surrogate is a surrogate for a specification (interface or # declaration). We use weak references in order to remove surrogates # if the corresponding specification goes away. # Each surrogate keeps track of: # - The adapters registered directly for that surrogate, and # - The "implied" adapters, which is the adapters that can be computed # from instances of that surrogate. # The later data structure takes into account adapters registered for # specifications that the registered surrogate extends. # The registrations are of the form: # {(subscription, with, name, specification) -> factories} # where: # 'subscription' is a flag indicating if this registration is for # subscription adapters. # 'with' is a tuple of specs that is non-empty only in the case # of multi-adapters. # 'name' is a unicode adapter name. Unnamed adapters have an empty # name. # 'specification' is the interface being adapted to. # 'factories' is normally a tuple of factories, but can be anything. # (See the "raw" option to the query-adapter calls.) For subscription # adapters, it is a tuple of tuples of factories. # The implied adapters are held in a single dictionary. The items in the # dictionary are of several forms: # For single adapters: # # {specification -> {name -> object} # # where object is usually a sequence of factories # For multiple adapters: # # {(specification, order) -> {name -> {with -> object}}} # For single subscription adapters: # # {('s', specification) -> tuple([object])} # For multiple-subscription adapters: # # {('s', specification, order) -> {with -> tuple([object])}} from __future__ import generators import weakref from zope.interface.ro import ro from zope.interface.declarations import providedBy from zope.interface.interface import InterfaceClass, Interface Default = InterfaceClass("Default", (), {}) Null = InterfaceClass("Null", (), {}) # 2.2 backwards compatability try: enumerate except NameError: def enumerate(l): i = 0 for o in l: yield i, o i += 1 try: basestring except NameError: basestring = (str, unicode) class ReadProperty(object): def __init__(self, func): self.func = func def __get__(self, inst, class_): if inst is None: return self return self.func(inst) class Surrogate(object): """Specification surrogate A specification surrogate is used to hold adapter registrations on behalf of a specification. """ def __init__(self, spec, registry): self.spec = spec.weakref() self.registry = registry spec.subscribe(self) self.adapters = {} self.dependents = weakref.WeakKeyDictionary() self.registry = registry self.__bases__ = [registry.get(base) for base in spec.__bases__] for base in self.__bases__: base.subscribe(self) def dirty(self): if 'get' in self.__dict__: # Not already dirty del self.selfImplied del self.multImplied del self.get bases = [self.registry.get(base) for base in self.spec().__bases__] if bases != self.__bases__: # Our bases changed. unsubscribe from the old ones # and subscribe to the new ones for base in self.__bases__: base.unsubscribe(self) self.__bases__ = bases for base in bases: base.subscribe(self) for dependent in self.dependents.keys(): dependent.dirty() def clean(self): for base in self.__bases__: base.unsubscribe(self) self.__bases__ = [self.registry.get(base) for base in self.spec().__bases__] for base in self.__bases__: base.subscribe(self) self.selfImplied, self.multImplied = adapterImplied(self.adapters) implied = {} ancestors = ro(self) # Collect implied data in reverse order to have more specific data # override less-specific data. ancestors.reverse() for ancestor in ancestors: for key, v in ancestor.selfImplied.iteritems(): # key is specification or ('s', specification) subscription = isinstance(key, tuple) and key[0] == 's' if subscription: # v is tuple of subs implied[key] = implied.get(key, ()) + v else: oldbyname = implied.get(key) if not oldbyname: implied[key] = oldbyname = {} # v is name -> object oldbyname.update(v) for key, v in ancestor.multImplied.iteritems(): # key is (specification, order) # or ('s', specification, order) subscription = key[0] == 's' if subscription: oldwithobs = implied.get(key) if not oldwithobs: oldwithobs = implied[key] = {} # v is {with -> tuple([object])} for with, objects in v.iteritems(): oldwithobs[with] = oldwithobs.get(with, ()) + objects else: oldbyname = implied.get(key) if not oldbyname: implied[key] = oldbyname = {} # v is {name -> {with -> ?}} for name, withobs in v.iteritems(): oldwithobs = oldbyname.get(name) if not oldwithobs: oldwithobs = oldbyname[name] = {} # withobs is {with -> object} oldwithobs.update(withobs) # Now flatten with mappings to tuples for key, v in implied.iteritems(): if isinstance(key, tuple): if key[0] == 's': # subscriptions if isinstance(v, dict): implied[key] = v.items() else: byname = v for name, value in byname.iteritems(): if isinstance(value, dict): # We have {with -> value} # convert it to sorted [(with, value] byname[name] = orderwith(value) self.get = implied.get def get(self, key): """Get an implied value This is only called when the surrogate is dirty """ self.clean() return self.__dict__['get'](key) def selfImplied(self): """Return selfImplied when dirty """ self.clean() return self.__dict__['selfImplied'] selfImplied = ReadProperty(selfImplied) def multiImplied(self): """Return _multiImplied when dirty """ self.clean() return self.__dict__['multiImplied'] multiImplied = ReadProperty(multiImplied) def subscribe(self, dependent): self.dependents[dependent] = 1 def unsubscribe(self, dependent): del self.dependents[dependent] def _adaptTo(self, specification, object, name='', with=()): if object is None: try: del self.adapters[False, tuple(with), name, specification] except KeyError: pass else: self.adapters[False, tuple(with), name, specification ] = object self.dirty() def _subscriptionAdaptTo(self, specification, object, with=()): if object is None: raise TypeError("Unregistering subscription adapters isn't " "implemented") key = (True, tuple(with), '', specification) self.adapters[key] = self.adapters.get(key, ()) + (object, ) self.dirty() def changed(self, which=None): self.dirty() def __repr__(self): return '<%s(%s)>' % (self.__class__.__name__, self.spec()) def orderwith(bywith): # Convert {with -> adapter} to withs, [(with, value)] # such that there are no i, j, i < j, such that # withs[j][0] extends withs[i][0]. withs = [] for with, value in bywith.iteritems(): for i, (w, v) in enumerate(withs): if withextends(with, w): withs.insert(i, (with, value)) break else: withs.append((with, value)) return withs def withextends(with1, with2): for spec1, spec2 in zip(with1, with2): if spec1.extends(spec2): return True if spec1 != spec2: break return False class AdapterLookup(object): # Adapter lookup support # We have a class here because we want to provide very # fast lookup support in C and making this part of the adapter # registry itself would provide problems if someone wanted # persistent adapter registries, because we want C slots for fast # lookup that would clash with persistence-supplied slots. # so this class acts a little bit like a lookup adapter for the adapter # registry. def __init__(self, registry, surrogates, _remove): self._registry = registry self._surrogateClass = registry._surrogateClass self._default = registry._default self._null = registry._null self._surrogates = surrogates self._remove = _remove def lookup(self, required, provided, name='', default=None): order = len(required) if order == 1: # Simple adapter: s = self.get(required[0]) byname = s.get(provided) if byname: value = byname.get(name) else: value = None if value is None: byname = self._default.get(provided) if byname: value = byname.get(name, default) else: return default return value elif order == 0: # null adapter byname = self._null.get(provided) if byname: return byname.get(name, default) else: return default # Multi adapter with = required[1:] key = provided, order for surrogate in self.get(required[0]), self._default: byname = surrogate.get(key) if not byname: continue bywith = byname.get(name) if not bywith: continue # Selecting multi-adapters is not just a matter of matching the # required interfaces of the adapter to the ones passed. Several # adapters might match, but we only want the best one. We use a # ranking algorithm to determine the best match. # `best` carries the rank and value of the best found adapter. best = None for rwith, value in bywith: # the `rank` describes how well the found adapter matches. rank = [] for rspec, spec in zip(rwith, with): if not spec.isOrExtends(rspec): break # This one is no good # Determine the rank of this particular specification. rank.append(list(spec.__sro__).index(rspec)) else: # If the new rank is better than the best previously # recorded one, make the new adapter the best one found. rank =
<filename>PerformanceGraphs.py #! /usr/bin/env nix-shell #! nix-shell -i python3 -p python3 python36Packages.matplotlib # (C) Copyright 2018-2019 Hewlett Packard Enterprise Development LP # 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 random import math import sys import matplotlib.pyplot as plt import matplotlib.cbook as cbook import numpy as np import statistics as st import os import argparse # TODO utilize import logging #lambdas lambdaPerformanceTime = lambda x: x[1].mean lambdaSpeedup = lambda x: x[1].speedup lambdaPerformanceTimeError = lambda x: x[1].stdev lambdaSpeedupError = lambda x: x[1].speedupError lambdaParallelEfficiency = lambda x: x[1].parallelEfficiency * 100 lambdaData = lambda x: np.array(x[1].data) #plotnames plotNameExecutionTime = "executionTime" plotNameExecutionTimeViolin = "executionTimeViolin" plotNameSpeedup = "speedup" plotNameParallelEfficiency = "parallelEfficiency" plotNameSpeedupParallelEfficiency = "speedupAndParallelEfficiency" cli = argparse.ArgumentParser() cli.add_argument('--delim', '-d', nargs='?', default=';', dest='delim', help='Specifies the delimiter used between single time measurements. Default: ;') cli.add_argument('--outdir', '-o', nargs='?', default='out', dest='outdir', help='The directory to output the data. The directory is created when not existing. If files are already in there they are overwritten. Default: out') cli.add_argument('--time-unit', nargs='?', default='ms', dest='time_unit', help='The time unit to print as a label to the diagrams. Default: ms') cli.add_argument('--hide-x-label', action='store_true', dest='hide_x_label', help='Hides the x label from every Graph. Use this if the label does not fit your use case.') cli.add_argument('--no-error', action='store_true', dest='no_error_bars', help='Hide error bars') cli.add_argument('--defaultName', nargs='?', default='default', dest='defaultTestCaseName', help='Defines the default name of a test without a name in the identifier. Default: default') cli.add_argument('--baselineIndex', '-b', nargs='?', default=0, type=int, dest='baselineIndex', help='Define which index to assume for a baseline to calculate speedup and scalability Default: 0') cli.add_argument('--yscale', nargs='?', default=None, type=str, dest='yscale', help='Define yscale used for matplotlib plots e.g. log (for logarithmic scale) Defaults to matplotlib default') cli.add_argument('--xscale', nargs='?', default=None, type=str, dest='xscale', help='Define xscale used for matplotlib plots e.g. log (for logarithmic scale) Defaults to matplotlib default') cli.add_argument('input', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help='File to read for input data. Defaults to reading stdin') args = cli.parse_args() # quick and easy way to remove array bars. Just make every error 0 if args.no_error_bars: lambdaPerformanceTimeError = lambda x: 0 lambdaSpeedupError = lambda x: 0 # global variables and read parameters #y_labels y_label_Time = f"time in {args.time_unit}" y_label_Speedup = "speedup" y_label_ScaleEff= "parallel efficiency in %" x_label_numberThreads = "Number of threads used" if args.hide_x_label: x_label_numberThreads = "" #delim = ";" if args.delim == None and not type(args.delim) == str: raise BaseException("No delimeter specified") #defaultTestCaseName = "default" #outdir = "out" #if outdir == None: # outdir = "out" if args.outdir.endswith('/'): args.outdir = args.outdir[:-1] def createFolder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print ('Could not create directory: ' + directory) raise createFolder(args.outdir) #def testCaseFolder(testCase): #if testCase == None or testCase == "": #raise "no Test case specified" #if outdir != None and outdir != "": #return outdir + "/" + testCase + "/" #else: #return testCase + "/" print("Using the following values") print("\toutdir= " + args.outdir) print("\tdeliminator= " + args.delim) print("\tdefault test name= " + args.defaultTestCaseName) print("\ttime unit= " + args.time_unit) if args.input is sys.stdin: print("\tReading from stdin") else: print("\tReading from file") if args.hide_x_label: print("\tHiding x-labels") #-------------class Definitions class SingleTestRun: def __init__(self, caseName="", machine="", numThreads="a", data=None): self.caseName = caseName if self.caseName == None or self.caseName == "": self.caseName = args.defaultTestCaseName self.machine = machine if self.machine == None or self.machine == "": raise BaseException("machine can't be empty string") self.numThreads = int(numThreads) self.minimum=min(data) self.maximum=max(data) self.mean=st.mean(data) self.stdev=st.stdev(data) self.data=data self.relativeError=self.stdev / self.mean self.baselineReceived=False def calculateValuesFromBaseline(self, baseline): if not type(baseline) is SingleTestRun: raise BaseException("Expected Single test run as baseline") self.baselineReceived = True if self==baseline: self.speedup = 1.0 self.parallelEfficiency = 1.0 self.speedupError = self.relativeError # * 1.0 else: self.speedup = baseline.mean / self.mean self.parallelEfficiency = self.speedup / self.numThreads self.speedupError = (self.relativeError + baseline.relativeError) * self.speedup def draw(self): folder = self.__createTestCaseFolder() self.__zero_basedScatter(folder) self.__simpleScatter(folder) def report(self): folder = self.__createTestCaseFolder() with open(folder + "/" + "report.txt", 'w') as f: f.write(self.toString(separator='\n')) f.write('\n') # Line break at end of line for easier reading def getCaseIdentifier(self): return self.caseName + "$" + self.machine + "$" + str(self.numThreads) def toString(self, separator=" "): stringData = self.getCaseIdentifier() + ":" stringData += separator + "min: " + str(self.minimum) stringData += separator + "max: " + str(self.maximum) stringData += separator + "mean: " + str(self.mean) stringData += separator + "stdev: " + str(self.stdev) stringData += separator + "relativeError: " + str(self.relativeError) if self.baselineReceived: stringData += separator + "speedup: " + str(self.speedup) stringData += separator + "speedupError: " + str(self.speedupError) stringData += separator + "parallelEfficiency: " + str(self.parallelEfficiency) else: stringData += separator + "No baseline received yet" return stringData def __repr__(self): return self.toString() def __str__(self): return self.toString() def __createTestCaseFolder(self): folder = args.outdir + "/" + self.caseName createFolder(folder) folder += "/" + self.machine createFolder(folder) folder += "/" + str(self.numThreads) createFolder(folder) return folder def __zero_basedScatter(self, folder): x_axis = list(range(len(self.data))) plt.clf() plt.scatter(x=x_axis, y=self.data, marker=".") plt.xlabel("n th run") plt.ylabel(y_label_Time) plt.ylim(bottom=0) createFolder(folder) plt.savefig(folder + "/zeroBasedScatter.pdf") def __simpleScatter(self, folder=""): x_axis = list(range(len(self.data))) plt.clf() plt.scatter(x=x_axis, y=self.data, marker=".") plt.axis('tight') plt.xlabel("n th run") plt.ylabel(y_label_Time) createFolder(folder) plt.savefig(folder + "/simpleScatter.pdf") class MachineTestCase: def __init__(self, machine="", caseName=""): self.caseName = caseName if self.caseName == None or self.caseName == "": self.caseName = args.defaultTestCaseName self.machine = machine if self.machine == None or self.machine == "": raise BaseException("machine can't be empty string") self.testRuns = {} def addTestRun(self, testRun): if not type(testRun) is SingleTestRun: raise TypeError("Expected object of type SingleTestRun") if testRun.numThreads in self.testRuns: print(self) print(testRun) raise RuntimeError("Test run already exists: " + testRun.getCaseIdentifier()) self.testRuns[testRun.numThreads] = testRun def __repr__(self): return str(self.runsPerMachine) def __createTestCaseFolder(self): folder = args.outdir + "/" + self.caseName createFolder(folder) folder += "/" + self.machine createFolder(folder) return folder def generateBaseLine(self, index=0): baseline = self.testRuns.get(index, None) if not baseline: return False for run in self.testRuns.values(): run.calculateValuesFromBaseline(baseline) return True def __drawGraph(self, mappingData=None, mappingError=None, plotName="", folder="", y_label="", drawViolin=False, yscale=None, xscale=None): if not type(plotName) is str or plotName=="": raise BaseException("Expected plotName that is non empty string") if not type(folder) is str or folder=="": raise BaseException("Expected folder that is non empty string") plt.clf() if drawViolin: self.drawViolinPartFromLampda(mappingData) else: self.drawPartFromLampda(mappingData, mappingError) plt.xlabel(x_label_numberThreads) plt.ylabel(y_label) if xscale: plt.xscale(xscale) if yscale: plt.yscale(yscale) else: plt.ylim(bottom=0) createFolder(folder) plt.savefig(folder + "/" + plotName + ".pdf", bbox_inches='tight') def __drawGraphTwins(self, mappingData1=None, mappingData2=None, mappingError1=None, mappingError2=None, plotName="", folder="", y_label1="", y_label2=""): if not type(plotName) is str or plotName=="": raise BaseException("Expected plotName that is non empty string") if not type(folder) is str or folder=="": raise BaseException("Expected folder that is non empty string") plt.clf() fig, ax1 = plt.subplots() self.drawPartFromLampda(mappingData1, mappingError1, plt=ax1, fmt='b-') ax1.set_xlabel(x_label_numberThreads) ax1.set_ylabel(y_label1, color='b') ax1.set_ylim(bottom=0) ax1.tick_params('y', colors='b') ax2 = ax1.twinx() self.drawPartFromLampda(mappingData2, mappingError2, plt=ax2, fmt='r-') ax2.set_ylabel(y_label2, color='r') ax2.set_ylim(bottom=0) ax2.tick_params('y', colors='r') createFolder(folder) plt.savefig(folder + "/" + plotName + ".pdf", bbox_inches='tight') def drawPartFromLampda(self, mappingData=None, mappingError=None, plt=plt, **kwargs): if mappingData == None or mappingError == None: raise BaseException("Expected mapping functions do determine what to draw") dictionarySortedByK = sorted(self.testRuns.items()) x_data = list(map(lambda x: x[0], dictionarySortedByK)) y_data = list(map(mappingData, dictionarySortedByK)) y_err = list(map(mappingError, dictionarySortedByK)) plt.errorbar(x_data, y_data, y_err, label=self.machine, **kwargs) def drawPartFromLampdaBar(self, mappingData=None, mappingError=None, plt=plt, width=0.9, offset=-0.45, **kwargs): if mappingData == None or mappingError == None: raise BaseException("Expected mapping functions do determine what to draw") dictionarySortedByK = sorted(self.testRuns.items()) x_data = np.array(list(map(lambda x: x[0], dictionarySortedByK))) + offset y_data = list(map(mappingData, dictionarySortedByK)) y_err = list(map(mappingError, dictionarySortedByK)) plt.bar(x_data, y_data, label=self.machine, yerr=y_err, width=width, **kwargs) def drawViolinPartFromLampda(self, mappingData=None): if mappingData == None: raise BaseException("Expected mapping functions do determine what to draw") dictionarySortedByK = sorted(self.testRuns.items()) x_data = list(map(lambda x: x[0], dictionarySortedByK)) y_data = list(map(mappingData, dictionarySortedByK)) # can't add label for violin plot therefor not adding it plt.violinplot(y_data, x_data, showmeans=True) def drawAll(self, baselineIndex=0, yscale=None, xscale=None): self.draw(baselineIndex=baselineIndex, yscale=yscale, xscale=xscale) for testRun in self.testRuns.values(): testRun.draw() def reportAll(self): for testRun
<gh_stars>1-10 # ===================================================================================================================== # # Tensor Abstraction Layer Objects 0.0.8-ALPHA # EVALUATION METRICS # # Framework design by <NAME> # Licensed under the MIT License # # ===================================================================================================================== import json import numpy as np #TODO: Remove dependency of sklearn, scipy from sklearn import metrics from TALOS.FileSystem import Storage #--------------------------------------------------------------------------------------------------- def SimpleEncode(ndarray): return json.dumps(ndarray.tolist()) #--------------------------------------------------------------------------------------------------- def SimpleDecode(jsonDump): return np.array(json.loads(jsonDump)) #--------------------------------------------------------------------------------------------------- #================================================================================================== class MetricsKind: SUPERVISED_CLASSIFICATION = 0 UNSUPERVISED_CLASSIFICATION = 1 SUPERVISED_CLASSIFICATION_EXTRA = 2 UNSUPERVISED_CLASSIFICATION_EXTRA = 3 UNSUPERVISED_CLUSTERING = 4 SUPERVISED_CLUSTERING = 5 REGRESSION = 6 FUNCTION_APPROXIMATION = 8 RETRIEVAL = 10 DETECTION = 12 TRACKING = 14 #================================================================================================== #================================================================================================== class ClassificationMetricsCalculator(object): __verboseLevel = 1 #------------------------------------------------------------------------------------ def __init__(self): #........ | Instance Attributes | .............................................. # // Basic \\ self.ClassTrue = None self.ClassFalse = None self.ClassActual = None self.ClassRecall = None self.ClassPrecision = None self.ClassF1Score = None self.Recall = None self.Precision = None self.F1Score = None # // Extended Stats \\ self.RecallMean = None self.PrecisionMean = None self.F1ScoreMean = None self.RecallMedian = None self.PrecisionMedian = None self.F1ScoreMedian = None self.RecallStd = None self.PrecisionStd = None self.F1ScoreStd = None self.RecallMin = None self.PrecisionMin = None self.F1ScoreMin = None self.RecallMax = None self.PrecisionMax = None self.F1ScoreMax = None #................................................................................ #------------------------------------------------------------------------------------ def __calculateClassStats(self): self.RecallMean = np.mean(self.ClassRecall) self.PrecisionMean = np.mean(self.ClassPrecision) self.F1ScoreMean = np.mean(self.ClassF1Score) self.RecallMedian = np.median(self.ClassRecall) self.PrecisionMedian = np.median(self.ClassPrecision) self.F1ScoreMedian = np.median(self.ClassF1Score) self.RecallStd = np.std(self.ClassRecall) self.PrecisionStd = np.std(self.ClassPrecision) self.F1ScoreStd = np.std(self.ClassF1Score) self.RecallMin = np.min(self.ClassRecall) self.PrecisionMin = np.min(self.ClassPrecision) self.F1ScoreMin = np.min(self.ClassF1Score) self.RecallMax = np.max(self.ClassRecall) self.PrecisionMax = np.max(self.ClassPrecision) self.F1ScoreMax = np.max(self.ClassF1Score) if type(self).__verboseLevel >= 2: print("Recall Stats: Min:%.4f Max:%4.f Med:%.4f Mean:%.4f Std:%.4f" % (self.RecallMin, self.RecallMax, self.RecallMedian, self.RecallMean, self.RecallStd)) print("Precision Stats: Min:%.4f Max:%4.f Med:%.4f Mean:%.4f Std:%.4f" % (self.PrecisionMin, self.PrecisionMax, self.PrecisionMedian, self.PrecisionMean, self.PrecisionStd)) print("F1Score Stats: Min:%.4f Max:%4.f Med:%.4f Mean:%.4f Std:%.4f" % (self.F1ScoreMin, self.F1ScoreMax, self.F1ScoreMedian, self.F1ScoreMean, self.F1ScoreStd)) #------------------------------------------------------------------------------------ def Calculate(self, p_nTrue, p_nFalse, p_nActual): nTrue = np.sum(np.asarray(p_nTrue), axis=0) nFalse = np.sum(np.asarray(p_nFalse), axis=0) nActual = np.sum(np.asarray(p_nActual), axis=0) self.ClassTrue = nTrue self.ClassFalse = nFalse self.ClassActual = nActual #TODO: Confusion Matrix #print(nTrue) #print(nFalse) #print(nActual) #print(np.sum(nActual)) self.ClassRecall = nTrue / (nActual + 1e-7) self.ClassPrecision = nTrue / (nTrue + nFalse + 1e-7) self.ClassF1Score = (2.0 * ( self.ClassRecall * self.ClassPrecision) ) / ( self.ClassRecall + self.ClassPrecision + + 1e-7) if type(self).__verboseLevel >= 3: print("ClassRecall", self.ClassRecall) print("ClassPrecision", self.ClassPrecision) print("ClassF1Score", self.ClassF1Score) self.__calculateClassStats() #TODO: Weight by Support self.Recall = np.average(self.ClassRecall) self.Precision = np.average(self.ClassPrecision) self.F1Score = np.average(self.ClassF1Score) if type(self).__verboseLevel >= 2: print("Avg Class Recall", self.Recall) print("Avg Class Precision", self.Precision) print("Avg Class F1Score", self.F1Score) #print("Recall:%f Precision:%f F1Score:%f" % (self.Recall, self.Precision, self.F1Score)) #------------------------------------------------------------------------------------ #================================================================================================== #================================================================================================== class ClassificationMetrics(object): #------------------------------------------------------------------------------------ def __init__(self): #........ | Instance Attributes | .............................................. self.Kind = MetricsKind.SUPERVISED_CLASSIFICATION self.ActualClasses = None self.PredictedClasses = None self.PredictedProbsTop = None self.IDs = None self.TopCount = None self.Accuracy = None self.TopKAccuracy = None self.AveragePrecision = None self.AverageRecall = None self.AverageF1Score = None self.AverageSupport = None self.Precision = None self.Recall = None self.F1Score = None self.Support = None self.ConfusionMatrix = None self.ClassCount = 0 #................................................................................ #------------------------------------------------------------------------------------ def CalculateTopK(self, p_nTopKappa, p_nTopKCorrect): self.TopKappa = p_nTopKappa self.TopKAccuracy = np.mean(p_nTopKCorrect) print("TopKAccuracy", self.TopKAccuracy) #self.TopKAccuracy #------------------------------------------------------------------------------------ def Calculate(self, p_nActual, p_nPredicted, p_nPredictedProbsTop=None): self.ActualClasses = p_nActual self.PredictedClasses = p_nPredicted self.PredictedProbsTop = p_nPredictedProbsTop if self.PredictedProbsTop is not None: self.TopCount = p_nPredictedProbsTop.shape[1] # Confusion matrix layout is # predicted # - - - - - - - - # actual | # | self.ConfusionMatrix = metrics.confusion_matrix(self.ActualClasses, self.PredictedClasses) self.Accuracy = metrics.accuracy_score(self.ActualClasses, self.PredictedClasses) self.Precision, self.Recall, self.F1Score, self.Support = metrics.precision_recall_fscore_support(self.ActualClasses, self.PredictedClasses, average=None) self.AveragePrecision, self.AverageRecall, self.AverageF1Score, self.AverageSupport = metrics.precision_recall_fscore_support(self.ActualClasses, self.PredictedClasses, average='weighted') self.ClassCount = self.Recall.shape[0] #------------------------------------------------------------------------------------ def Save(self, p_sFileName): oData = { "FileFormat" : "TALOS008" ,"Kind" : self.Kind ,"IDs" : self.IDs ,"Actual" : self.ActualClasses ,"Predicted" : self.PredictedClasses ,"PredictedProbsTop" : self.PredictedProbsTop ,"TopKappa" : self.TopKappa ,"Accuracy" : self.Accuracy ,"TopKAccuracy" : self.TopKAccuracy ,"AveragePrecision" : self.AveragePrecision ,"AverageRecall" : self.AverageRecall ,"AverageF1Score" : self.AverageF1Score ,"AverageSupport" : self.AverageSupport #,"Top1Error" : None #,"Top5Error" : None ,"ClassPrecision" : self.Precision ,"ClassRecall" : self.Recall ,"ClassF1Score" : self.F1Score ,"ClassSupport" : self.Support ,"ConfusionMatrix" : self.ConfusionMatrix } Storage.SerializeObjectToFile(p_sFileName, oData) #------------------------------------------------------------------------------------ def Load(self, p_sFileName): oData = Storage.DeserializeObjectFromFile(p_sFileName) assert oData is not None, "Evaluation results file not found %s" % p_sFileName self.IDs = oData["IDs"] self.Kind = oData["Kind"] self.ActualClasses = oData["Actual"] self.PredictedClasses = oData["Predicted"] self.PredictedProbsTop = oData["PredictedProbsTop"] if self.PredictedProbsTop is not None: self.TopCount = self.PredictedProbsTop.shape[1] if "TopKappa" in oData: self.TopKappa = oData["TopKappa"] if "Accuracy" in oData: self.Accuracy = oData["Accuracy"] if "TopKAccuracy" in oData: self.TopKAccuracy = oData["TopKAccuracy"] self.AveragePrecision = oData["AveragePrecision"] self.AverageRecall = oData["AverageRecall"] self.AverageF1Score = oData["AverageF1Score"] self.AverageSupport = oData["AverageSupport"] #self.Top1Error = oData["Top1Error"] #self.Top5Error = oData["Top5Error"] self.Precision = oData["ClassPrecision"] self.Recall = oData["ClassRecall"] self.F1Score = oData["ClassF1Score"] self.Support = oData["ClassSupport"] self.ConfusionMatrix = oData["ConfusionMatrix"] self.ClassCount = self.Recall.shape[0] #------------------------------------------------------------------------------------ def MissClassified(self, p_nClassIndex): oIDs = [] for nIndex, nActual in enumerate(self.ActualClasses): if (nActual == p_nClassIndex) and (nActual != self.PredictedClasses[nIndex]): oIDs.append(self.IDs[nIndex]) return oIDs #------------------------------------------------------------------------------------ #================================================================================================== #================================================================================================== class ClassificationBest(object): #------------------------------------------------------------------------------------ def __init__(self, p_sEvaluationResultsFolder=None): #........ | Instance Attributes | .............................................. self.Folder = p_sEvaluationResultsFolder self.ResultFiles = None self.KeepEpochs = 3 self.TopCount = 5 self.EpochNumber=None self.FileNames=None self.Accuracy=None self.Recall=None self.Precision=None self.F1Score=None self.Points=None self.ClassCount=None self.IsBinary=False self.BestIndexes = None # // Persistent Data \\ self.BestEpochs = None self.Points = None self.Recall = None self.Precision = None self.F1Score = None self.CrossF1Score = None self.ObjectiveF1Score = None self.PositiveF1Score = None self.BestPoints = None self.BestRecall = None self.BestPrecision = None self.BestF1Score = None self.BestCrossF1Score = None self.BestObjectiveF1Score = None self.BestPositiveF1Score = None self.DiscardedEpochs = None self.BestRecallEpochs = None self.BestPrecisionEpochs = None self.BestF1ScoreEpochs = None self.BestCrossF1ScoreEpochs = None self.BestObjectiveF1ScoreEpochs = None self.BestPositiveScoreEpochs = None #................................................................................ if self.Folder is not None: self.__listFiles() #------------------------------------------------------------------------------------ def Save(self, p_sFileName): oData = { "FileFormat" : "TALOS008" ,"IsBinary" : self.IsBinary ,"EpochNumber" : self.EpochNumber ,"FileNames" : self.FileNames ,"Accuracy" : self.Accuracy ,"Recall" : self.Recall ,"Precision" : self.Precision ,"F1Score" : self.F1Score ,"CrossF1Score" : self.CrossF1Score ,"ObjectiveF1Score" : self.ObjectiveF1Score ,"PositiveF1Score" : self.PositiveF1Score ,"BestEpochs" : self.BestEpochs ,"BestPoints" : self.BestPoints ,"BestRecall" : self.BestRecall ,"BestPrecision" : self.BestPrecision ,"BestF1Score" : self.BestF1Score ,"BestCrossF1Score" : self.BestCrossF1Score ,"BestObjectiveF1Score" : self.BestObjectiveF1Score ,"BestPositiveF1Score" : self.BestPositiveF1Score ,"DiscardedEpochs" : self.DiscardedEpochs ,"BestRecallEpochs" : self.BestRecallEpochs ,"BestPrecisionEpochs" : self.BestPrecisionEpochs ,"BestF1ScoreEpochs" : self.BestF1ScoreEpochs ,"BestCrossF1ScoreEpochs" : self.BestCrossF1ScoreEpochs ,"BestObjectiveF1ScoreEpochs": self.BestObjectiveF1ScoreEpochs ,"BestPositiveScoreEpochs" : self.BestPositiveScoreEpochs } Storage.SerializeObjectToFile(p_sFileName, oData, p_bIsOverwritting=True) #------------------------------------------------------------------------------------ def IndexOfEpoch(self, p_nEpochNumber): nFoundPos = None for nIndex, nEpochNumber in enumerate(self.EpochNumber): if nEpochNumber == p_nEpochNumber: nFoundPos = nIndex break return nFoundPos #------------------------------------------------------------------------------------ def GetBestIndex(self): return self.IndexOfEpoch( self.BestEpochs[0] ) #------------------------------------------------------------------------------------ def Load(self, p_sFileName): oData = Storage.DeserializeObjectFromFile(p_sFileName, p_bIsVerbose=False) assert oData is not None, "File %s not found" % p_sFileName self.BestEpochs = oData["BestEpochs"] self.IsBinary = oData["IsBinary"] self.EpochNumber = oData["EpochNumber"] self.FileNames = oData["FileNames"] self.Accuracy = oData["Accuracy"] self.Recall = oData["Recall"] self.Precision = oData["Precision"] self.F1Score = oData["F1Score"] self.CrossF1Score = oData["CrossF1Score"] if "ObjectiveF1Score" in oData: self.ObjectiveF1Score = oData["ObjectiveF1Score"] self.PositiveF1Score = oData["PositiveF1Score"] self.BestPoints = oData["BestPoints"] self.BestRecall = oData["BestRecall"] self.BestPrecision = oData["BestPrecision"] self.BestF1Score = oData["BestF1Score"] self.BestCrossF1Score = oData["BestCrossF1Score"] if "BestObjectiveF1Score" in oData: self.BestObjectiveF1Score = oData["BestObjectiveF1Score"] self.BestPositiveF1Score = oData["BestPositiveF1Score"] self.DiscardedEpochs = oData["DiscardedEpochs"] self.BestRecallEpochs = oData["BestRecallEpochs"] self.BestPrecisionEpochs = oData["BestPrecisionEpochs"] self.BestF1ScoreEpochs = oData["BestF1ScoreEpochs"] self.BestCrossF1ScoreEpochs = oData["BestCrossF1ScoreEpochs"] if "BestObjectiveF1ScoreEpochs" in oData: self.BestObjectiveF1ScoreEpochs = oData["BestObjectiveF1ScoreEpochs"] self.BestPositiveScoreEpochs = oData["BestPositiveScoreEpochs"] #------------------------------------------------------------------------------------ def __listFiles(self): sEvaluationResultFiles = Storage.GetFilesSorted(self.Folder) self.FileNames = [] self.ResultFiles = [] for sFile in sEvaluationResultFiles: sFileNameFull = Storage.JoinPath(self.Folder, sFile) self.FileNames.append(sFileNameFull) self.ResultFiles.append( [sFile, sFileNameFull]) nFileCount = len(self.ResultFiles) self.EpochNumber=np.zeros((nFileCount), np.float32 ) self.Accuracy=np.zeros((nFileCount), np.float32 ) self.Recall=np.zeros((nFileCount), np.float32 ) self.Precision=np.zeros((nFileCount), np.float32 ) self.F1Score=np.zeros((nFileCount), np.float32 ) self.Points=np.zeros((nFileCount), np.float32 ) self.CrossF1Score=np.zeros((nFileCount), np.float32 ) self.ObjectiveF1Score=np.zeros((nFileCount), np.float32 ) self.PositiveF1Score=np.zeros((nFileCount), np.float32 ) #------------------------------------------------------------------------------------ def __loadAll(self): for nIndex, sFileRec in enumerate(self.ResultFiles): _, sEpochNumber, _ = Storage.SplitFileName(sFileRec[0]) sFileNameFull = sFileRec[1] oMetrics = ClassificationMetrics() oMetrics.Load(sFileNameFull) print("Accuracy:%f Top%dAccuracy%s" % (oMetrics.Accuracy, oMetrics.TopKappa, oMetrics.TopKAccuracy)) self.EpochNumber[nIndex] = int(sEpochNumber) self.Accuracy[nIndex] = oMetrics.Accuracy self.Recall[nIndex] = oMetrics.AverageRecall self.Precision[nIndex] = oMetrics.AveragePrecision self.F1Score[nIndex] = oMetrics.AverageF1Score if oMetrics.ClassCount == 2: self.IsBinary=True # Cross entropy of the F1 scores for binary classification. self.CrossF1Score[nIndex] = -(oMetrics.F1Score[0]*np.log10(oMetrics.F1Score[1])+ oMetrics.F1Score[1]*np.log10(oMetrics.F1Score[0])) self.ObjectiveF1Score[nIndex] = self.F1Score[nIndex] / self.CrossF1Score[nIndex] # Special binary classification, with the class 0 the class positives self.PositiveF1Score[nIndex] = oMetrics.F1Score[0] print(sEpochNumber, oMetrics.F1Score[0], oMetrics.F1Score[1], self.CrossF1Score[nIndex], self.ObjectiveF1Score[nIndex]) #------------------------------------------------------------------------------------ def
# sapid lisp # python implementation # <EMAIL>, https://github.com/GillesArcas/sapid-lisp # MIT license from __future__ import print_function import sys import os import time # Configuration TailRecursionOptimization = 'MutualRecursion' # None | 'TailRecursion' | 'MutualRecursion' # 2/3 compatibility if sys.version_info < (3,): integer_types = (int, long,) else: integer_types = (int,) if sys.version_info < (3,): func_name_attribute = 'func_name' else: func_name_attribute = '__name__' if sys.version_info < (3,): input_func = raw_input else: input_func = input # Items # sapid provides 4 types of items: symbol, cons, int and str. # int (including long) and str are native. class symbol: def __init__(self, pname, ftype=None, fval=None): self.pname = pname self.cval = None self.ftype = ftype self.fval = fval self.plist = Nil self.isvar = True def __lt__(self, x): return self.pname < x.pname def __gt__(self, x): return self.pname > x.pname def __str__(self): return self.pname class cons: def __init__(self, car, cdr): self.car = car self.cdr = cdr def __str__(self): return '(' + str(self.car) + ' . ' + str(self.cdr) + ')' # Symbols Oblist = {} def intern(x, ftype=None, fval=None): # case sensitive if x in Oblist: y = Oblist[x] if ftype != None: y.ftype = ftype if fval != None: y.fval = fval return y else: Oblist[x] = symbol(x, ftype, fval) return Oblist[x] # Builtin symbols def InitSymbols(): global Nil, T, FSubr, SSubr, Subr0, Sub1, Subr2, Subr12, Lambda, Macro, DMacro FunctionTypeSymbols = [ 'Subr0', 'Subr1', 'Subr2', 'Subr01', 'Subr12', 'NSubr', 'SSubr', 'FSubr', 'Lambda', 'Macro', 'DMacro'] ErrorSymbols = [ 'UndefSymError', 'UndefFuncError', 'UndefTagError', 'NotSymbolArgError', 'NotNumberArgError', 'NotStringArgError', 'NotConsArgError', 'NotListArgError', 'NotCharArgError', 'NotVarError', 'ArgNumberError', 'ArgError', 'BindingError', 'SyntaxError', 'IoError', 'IndexError'] # Dummy definition for Nil required to intern Nil and give value to its plist. # Nil plist is updated latter. Other symbols get the correct plist value. Nil = None # Intern standard symbols in lower case for sym in ['Nil', 'T', 'TopError', 'Eof']: globals()[sym] = intern(sym.lower()) # Intern error symbols in camel case for sym in ErrorSymbols: globals()[sym] = intern(sym) # Make Nil and T constant, complete Nil plist, and make Nil a list. Nil.cval = Nil Nil.isvar = False T.cval = T T.isvar = False Nil.plist = Nil Nil.car = Nil Nil.cdr = Nil # Make function definition form return their own value SSubr = intern('ssubr') for sym in FunctionTypeSymbols: globals()[sym] = intern(sym.lower(), SSubr, subr_selfvalue) # Add eval function to each ftype symbol FSubr.evalfunc = evalfsubr SSubr.evalfunc = evalssubr Subr0.evalfunc = evalsubr0 Subr1.evalfunc = evalsubr1 Subr2.evalfunc = evalsubr2 Subr01.evalfunc = evalsubr01 Subr12.evalfunc = evalsubr12 NSubr.evalfunc = evalnsubr Lambda.evalfunc = evalexpr Macro.evalfunc = evalmacro DMacro.evalfunc = evaldmacro # Add apply function to each ftype symbol FSubr.applyfunc = evalfsubr SSubr.applyfunc = evalssubr Subr0.applyfunc = evalsubr0 Subr1.applyfunc = applysubr1 Subr2.applyfunc = applysubr2 Subr01.applyfunc = applysubr01 Subr12.applyfunc = applysubr12 NSubr.applyfunc = applynsubr Lambda.applyfunc = applyexpr Macro.applyfunc = evalmacro DMacro.applyfunc = evalmacro # same as macro, no form to rplac # Predicates def symbolp(x): return isinstance(x, symbol) def numberp(x): return isinstance(x, integer_types) def stringp(x): return isinstance(x, str) def consp(x): return isinstance(x, cons) def atom(x): return not consp(x) def listp(x): return x == Nil or consp(x) def null(x): return x == Nil def variablep(x): return symbolp(x) and x.isvar def unboundp(x): return x.cval == None def charp(x): return stringp(x) and len(x) == 1 # Evaluation stack Stack = [] # Evaluation def eval(x): if symbolp(x): if unboundp(x): error(UndefSymError, 'eval', x) else: return x.cval if numberp(x) or stringp(x): return x if consp(x): return evalform(x, x.car, x.cdr) # Form evaluation def evalform(form, func, larg): if symbolp(func): return evalfn(form, func, func.ftype, func.fval, larg) elif consp(func): if stringp(func.cdr): return evalfn(form, func, func.car, globals()[func.cdr], larg) else: return evalfn(form, func, func.car, func.cdr, larg) else: error(UndefFuncError, 'eval', func) # Function evaluation def evalfn(form, func, ftype, fval, larg): if hasattr(ftype, 'evalfunc'): return ftype.evalfunc(func, fval, larg, form) else: error(UndefFuncError, 'eval', func) # Evaluation of builtin functions # The minimum number of arguments is tested, extra arguments are ignored. def evalssubr(func, fval, larg, form): return form def evalfsubr(func, fval, larg, form): return fval(larg) def evalsubr0(func, fval, larg, form): return fval() def evalsubr1(func, fval, larg, form): assert_condition(consp(larg), ArgNumberError, func, 0) x = evalprotect(larg.car) return fval(x) def evalsubr2(func, fval, larg, form): assert_condition(consp(larg), ArgNumberError, func, 0) assert_condition(consp(larg.cdr), ArgNumberError, func, 1) x = evalprotect(larg.car) y = evalprotect(larg.cdr.car) return fval(x, y) def evalnsubr(func, fval, larg, form): evargs = [] while consp(larg): evargs.append(evalprotect(larg.car)) larg = larg.cdr return fval(evargs) def evalsubr01(func, fval, larg, form): x = evalprotect(larg.car) if consp(larg) else None return fval(x) def evalsubr12(func, fval, larg, form): assert_condition(consp(larg), ArgNumberError, func, 0) x = evalprotect(larg.car) y = evalprotect(larg.cdr.car) if consp(larg.cdr) else None return fval(x, y) # Evaluation of expr function calls without recursion optimization if TailRecursionOptimization == None: def evalexpr(func, fval, larg, form, evalargs=True): bind(func, fval, fval.car, larg, evalargs) try: x = eprogn(fval.cdr) finally: unbind() return x if TailRecursionOptimization == None: def evalprotect(expr): return eval(expr) # Evaluation of expr function calls with tail recursion optimization class TailRecException(Exception): def __init__(self, fval): self.fval = fval if TailRecursionOptimization == 'TailRecursion': def evalexpr(func, fval, larg, form, evalargs=True): bind(func, fval, fval.car, larg, evalargs) if istailrec(fval): Stack.pop() raise TailRecException(fval) try: while True: try: x = eprogn(fval.cdr) break except TailRecException: pass finally: unbind() return x if TailRecursionOptimization == 'TailRecursion': def istailrec(fv): # the binding record of the call to test is already pushed # tests previous one i = len(Stack) - 2 stackrec = Stack[i] if 'lambda' not in stackrec: return False if stackrec['lambda'] == fv: return True else: return False if TailRecursionOptimization != None: def evalprotect(expr): # adds something in the stack to avoid tail recursion detection try: Stack.append({'eval': expr}) return eval(expr) finally: Stack.pop() # Evaluation of expr function calls with tail and mutual recursion optimization if TailRecursionOptimization == 'MutualRecursion': def evalexpr(func, fval, larg, form, evalargs=True): bind(func, fval, fval.car, larg, evalargs) if istailrec(fval): Stack.pop() raise TailRecException(fval) try: while True: try: x = eprogn(fval.cdr) break except TailRecException as e: if e.fval == fval: pass # tail recursion else: bindmerge() # mutual recursion Stack.pop() raise except TailRecException: raise except: unbind() raise else: unbind() return x if TailRecursionOptimization == 'MutualRecursion': def istailrec(fv): # the binding record of the call to test is already pushed # compares with previous ones i = len(Stack) - 2 while i >= 0: stackrec = Stack[i] if 'lambda' not in stackrec: return False if stackrec['lambda'] == fv: return True i -= 1 else: return False # Binding def bind(func, fval, lpar, larg, evalargs=True): # evaluates and saves arguments in stack record stackrec = {} stackrec['lambda'] = fval # store argument values in stack record while consp(lpar): if atom(larg): error(BindingError, func, larg) elif not variablep(lpar.car): error(NotVarError, func, lpar.car) elif evalargs: stackrec[lpar.car] = evalprotect(larg.car) else: stackrec[lpar.car] = larg.car lpar = lpar.cdr larg = larg.cdr # store values of possible binding between symbol and list of values if variablep(lpar) and listp(larg): if evalargs: stackrec[lpar] = evlis(larg) else: stackrec[lpar] = larg # swap cell values and values in stack record for key in stackrec.keys(): if symbolp(key): key.cval, stackrec[key] = stackrec[key], key.cval # push stack record Stack.append(stackrec) def unbind(): # pop record stackrec = Stack.pop() # restore environment for key in stackrec.keys(): if symbolp(key): key.cval = stackrec[key] def bindmerge(): # merge bindings from top record with previous one stackrec1 = Stack[len(Stack) - 1] stackrec2 = Stack[len(Stack) - 2] for x in stackrec1: if x != 'lambda' and x not in stackrec2: stackrec2[x] = stackrec1[x] # Evaluation of macros def evalmacro(func, fval, larg, form): x = applyexpr(func, fval, larg, form) return eval(x) def evaldmacro(func, fval, larg, form): x = applyexpr(func, fval, larg, form) if atom(x): return eval(x) else: # displaces calling form with expansion form.car = x.car form.cdr = x.cdr return eval(form) # Apply def applyform(func, larg): if symbolp(func): return applyfn(func, func.ftype, func.fval, larg) elif consp(func): if stringp(func.cdr): return applyfn(func, func.car, globals()[func.cdr], larg) else: return applyfn(func, func.car, func.cdr, larg) else: error(UndefFuncError, 'apply', func) def applyfn(func, ftype, fval, larg): if hasattr(ftype, 'applyfunc'): return ftype.applyfunc(func, fval, larg, None) else: error(UndefFuncError, 'apply', func) def applysubr1(func, fval, larg, form): assert_condition(consp(larg), ArgNumberError, func, 0) return fval(larg.car) def applysubr2(func, fval, larg, form): assert_condition(consp(larg), ArgNumberError, func, 0) assert_condition(consp(larg.cdr), ArgNumberError, func, 1) return fval(larg.car, larg.cdr.car) def applynsubr(func, fval, larg, form): return fval(hostlist(larg)) def applysubr01(func, fval, larg, form): return fval(larg.car if consp(larg) else None) def applysubr12(func, fval, larg, form): assert_condition(consp(larg), ArgNumberError, func, 0) return fval(larg.car, larg.cdr.car if consp(larg.cdr) else None) def applyexpr(func, fval, larg, form): return evalexpr(func, fval, larg, form, evalargs=False) # Evaluation of lists def eprogn(x): if atom(x): if
this properly, so it is returned as-is. # Hm, should we call __ctypes_from_outparam__ on the # result? return result @patcher.no_replace def __setitem__(self, index, value): "Attempt 'self.Item[index] = value'" try: self.Item[index] = value except ArgumentError as err: (hresult, text, details) = err.args if hresult == -2147352565: # DISP_E_BADINDEX raise IndexError("invalid index") else: raise except TypeError: msg = "%r object does not support item assignment" raise TypeError(msg % type(self)) if has_name("_NewEnum"): @patcher.Patch(self) class _(object): def __iter__(self): "Return an iterator over the _NewEnum collection." # This method returns a pointer to _some_ _NewEnum interface. # It relies on the fact that the code generator creates next() # methods for them automatically. # # Better would maybe to return an object that # implements the Python iterator protocol, and # forwards the calls to the COM interface. enum = self._NewEnum if isinstance(enum, types.MethodType): # _NewEnum should be a propget property, with dispid -4. # # Sometimes, however, it is a method. enum = enum() if hasattr(enum, "Next"): return enum # _NewEnum returns an IUnknown pointer, QueryInterface() it to # IEnumVARIANT from comtypes.automation import IEnumVARIANT return enum.QueryInterface(IEnumVARIANT) def _make_case_insensitive(self): # The __map_case__ dictionary maps lower case names to the # names in the original spelling to enable case insensitive # method and attribute access. try: self.__dict__["__map_case__"] except KeyError: d = {} d.update(getattr(self, "__map_case__", {})) self.__map_case__ = d def _make_dispmethods(self, methods): if self._case_insensitive_: self._make_case_insensitive() # create dispinterface methods and properties on the interface 'self' properties = {} for m in methods: what, name, idlflags, restype, argspec = m # is it a property set or property get? is_prop = False # argspec is a sequence of tuples, each tuple is: # ([paramflags], type, name) try: memid = [x for x in idlflags if isinstance(x, int)][0] except IndexError: raise TypeError("no dispid found in idlflags") if what == "DISPPROPERTY": # DISPPROPERTY assert not argspec # XXX does not yet work for properties with parameters accessor = self._disp_property(memid, idlflags) is_prop = True setattr(self, name, accessor) elif what == "DISPMETHOD": # DISPMETHOD # argspec is a tuple of (idlflags, type, name[, # defval]) items. method = self._disp_method(memid, name, idlflags, restype, argspec) ## not in 2.3 method.__name__ = name if 'propget' in idlflags: nargs = len(argspec) properties.setdefault((name, nargs), [None, None, None])[0] = method is_prop = True elif 'propput' in idlflags: nargs = len(argspec)-1 properties.setdefault((name, nargs), [None, None, None])[1] = method is_prop = True elif 'propputref' in idlflags: nargs = len(argspec)-1 properties.setdefault((name, nargs), [None, None, None])[2] = method is_prop = True else: setattr(self, name, method) # COM is case insensitive. # # For a method, this is the real name. For a property, # this is the name WITHOUT the _set_ or _get_ prefix. if self._case_insensitive_: self.__map_case__[name.lower()] = name if is_prop: self.__map_case__[name[5:].lower()] = name[5:] for (name, nargs), methods in properties.items(): # methods contains [propget or None, propput or None, propputref or None] if methods[1] is not None and methods[2] is not None: # both propput and propputref. # # Create a setter method that examines the argument type # and calls 'propputref' if it is an Object (in the VB # sense), or call 'propput' otherwise. propput = methods[1] propputref = methods[2] def put_or_putref(self, *args): if _is_object(args[-1]): return propputref(self, *args) else: return propput(self, *args) methods[1] = put_or_putref del methods[2] elif methods[2] is not None: # use propputref del methods[1] else: # use propput (if any) del methods[2] if nargs: setattr(self, name, named_property("%s.%s" % (self.__name__, name), *methods)) else: assert len(methods) <= 2 setattr(self, name, property(*methods)) # COM is case insensitive if self._case_insensitive_: self.__map_case__[name.lower()] = name # Some ideas, (not only) related to disp_methods: # # Should the functions/methods we create have restype and/or # argtypes attributes? def _disp_method(self, memid, name, idlflags, restype, argspec): if 'propget' in idlflags: def getfunc(obj, *args, **kw): return self.Invoke(obj, memid, _invkind=2, *args, **kw) # DISPATCH_PROPERTYGET return getfunc elif 'propput' in idlflags: def putfunc(obj, *args, **kw): return self.Invoke(obj, memid, _invkind=4, *args, **kw) # DISPATCH_PROPERTYPUT return putfunc elif 'propputref' in idlflags: def putfunc(obj, *args, **kw): return self.Invoke(obj, memid, _invkind=8, *args, **kw) # DISPATCH_PROPERTYPUTREF return putfunc # a first attempt to make use of the restype. Still, support # for named arguments and default argument values should be # added. if hasattr(restype, "__com_interface__"): interface = restype.__com_interface__ def func(s, *args, **kw): result = self.Invoke(s, memid, _invkind=1, *args, **kw) if result is None: return return result.QueryInterface(interface) else: def func(obj, *args, **kw): return self.Invoke(obj, memid, _invkind=1, *args, **kw) # DISPATCH_METHOD return func def _disp_property(self, memid, idlflags): # XXX doc string missing in property def _get(obj): return obj.Invoke(memid, _invkind=2) # DISPATCH_PROPERTYGET if "readonly" in idlflags: return property(_get) def _set(obj, value): # Detect whether to use DISPATCH_PROPERTYPUT or # DISPATCH_PROPERTYPUTREF invkind = 8 if _is_object(value) else 4 return obj.Invoke(memid, value, _invkind=invkind) return property(_get, _set) def __get_baseinterface_methodcount(self): "Return the number of com methods in the base interfaces" try: result = 0 for itf in self.mro()[1:-1]: result += len(itf.__dict__["_methods_"]) return result except KeyError as err: (name,) = err.args if name == "_methods_": raise TypeError("baseinterface '%s' has no _methods_" % itf.__name__) raise def _fix_inout_args(self, func, argtypes, paramflags): # This function provides a workaround for a bug in ctypes. # [in, out] parameters must be converted with the argtype's # .from_param() method BEFORE they are passed to the _ctypes # build_callargs() function in Modules/_ctypes/_ctypes.c. # # For details see below. # # TODO: The workaround should be disabled when a ctypes # version is used where the bug is fixed. SIMPLETYPE = type(c_int) BYREFTYPE = type(byref(c_int())) def call_with_inout(self_, *args, **kw): args = list(args) # Indexed by order in the output outargs = {} outnum = 0 for i, info in enumerate(paramflags): direction = info[0] if direction & 3 == 3: # This is an [in, out] parameter. # # Determine name and required type of the parameter. name = info[1] # [in, out] parameters are passed as pointers, # this is the pointed-to type: atyp = argtypes[i]._type_ # Get the actual parameter, either as positional or # keyword arg. try: try: v = args[i] except IndexError: v = kw[name] except KeyError: # no parameter was passed, make an empty one # of the required type v = atyp() else: # parameter was passed, call .from_param() to # convert it to a ctypes type. if getattr(v, "_type_", None) is atyp: # Array of or pointer to type 'atyp' was # passed, pointer to 'atyp' expected. pass elif type(atyp) is SIMPLETYPE: # The from_param method of simple types # (c_int, c_double, ...) returns a byref() # object which we cannot use since later # it will be wrapped in a pointer. Simply # call the constructor with the argument # in that case. v = atyp(v) else: v = atyp.from_param(v) assert not isinstance(v, BYREFTYPE) outargs[outnum] = v outnum += 1 if len(args) > i: args[i] = v else: kw[name] = v elif direction & 2 == 2: outnum += 1 rescode = func(self_, *args, **kw) # If there is only a single output value, then do not expect it to # be iterable. if outnum == 1: # rescode is not iterable if len(outargs) == 1: rescode = rescode.__ctypes_from_outparam__() return rescode rescode = list(rescode) for outnum, o in outargs.items(): rescode[outnum] = o.__ctypes_from_outparam__() return rescode return call_with_inout def _make_methods(self, methods): if self._case_insensitive_: self._make_case_insensitive() # we insist on an _iid_ in THIS class! try: iid = self.__dict__["_iid_"] except KeyError: raise AttributeError("this class must define an _iid_") else: iid = text_type(iid) ## if iid in com_interface_registry: ## # Warn when multiple interfaces are defined with identical iids. ## # This would also trigger if we reload() a module that contains ## # interface types, so suppress the warning in this case. ## other = com_interface_registry[iid] ## if self.__name__ != other.__name__ or self.__module__ != other.__module__: ## text = "Multiple interface defn: %s, %s" % (self, other) ## warnings.warn(text, UserWarning) com_interface_registry[iid] = self del iid vtbl_offset =
<filename>hyperion/instrument/polarization/variable_waveplate.py """ ====================== LCC25 (thorlabs) model ====================== This class (variable_waveplate_gui.py) is the model to drive the LCC25 variable waveplate controller. It ads the use of units with pint and the wavelength calibration to obtain make the variable waveplate a quarter waveplate for a given wavelength. :copyright: by Hyperion Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from time import sleep import os import numpy as np from hyperion import logging from hyperion.instrument.base_instrument import BaseInstrument from hyperion import ur, package_path class VariableWaveplate(BaseInstrument): """ This class is the model for the LCC25 analog voltage generator for the variable waveplate from thorlabs. """ def __init__(self, settings): """ Init of the class. It needs a settings dictionary that contains the following fields (mandatory) * port: COM port name where the LCC25 is connected * enable: logical to say if the initialize enables the output * dummy: logical to say if the connection is real or dummy (True means dummy) * controller: this should point to the controller to use and with / add the name of the class to use Note: When you set the setting 'dummy' = True, the controller to be loaded is the dummy one by default, i.e. the class will automatically overwrite the 'controller' with 'hyperion.controller.thorlabs.lcc25/LccDummy' Example: settings = {'port':'COM8', 'enable': None, 'dummy' : True, 'controller': 'hyperion.controller.thorlabs.lcc25/Lcc'} """ super().__init__(settings) self.logger = logging.getLogger(__name__) self._port = settings['port'] # property self._output = settings['enable'] self._mode = None self._freq = None self._wavelength = 532*ur('nm') # default wavelength self.MODES = ['Modulation', 'Voltage1', 'Voltage2', 'QWP'] self.logger.info('Initializing Variable Waveplate with settings: {}'.format(settings)) # this is to load the calibration file self.calibration = {} self.logger.debug('Get the source path') cal_file = os.path.join(package_path, 'instrument', 'polarization', 'lookup_table_qwp_voltage_calibration_2019-03-15.txt') self.logger.info('Using Variable Waveplate QWP calibration file: {}'.format(cal_file)) self.load_calibration(cal_file) # initialize self.initialize() # mandatory! if self._output is None: self._output = self.output else: self.output = self._output # mode self._mode = self.mode def initialize(self): """ initializes the connection with the controller """ if not self.controller._is_initialized: self.logger.info('Initializing') self.controller.initialize() else: self.logger.info('Already initialized') def load_calibration(self, cal_file): """ This method loads the calibration file cal_file :param cal_file: calibration file complete path, including extension (txt expected) :type cal_file: string """ self.logger.debug('Trying to load the calibration file: {}'.format(cal_file)) cal = np.loadtxt(cal_file) self.logger.info('Loaded the calibration file: {}'.format(cal_file)) self.calibration['file'] = cal_file self.calibration['original_data'] = cal aux = cal[:, 0] self.calibration['wavelength'] = cal[aux.argsort(), 0] * ur('nm') self.calibration['wavelength_limits'] = (np.min(self.calibration['wavelength']), np.max(self.calibration['wavelength'])) self.calibration['qwp'] = cal[aux.argsort(), 1] * ur('volt') self.calibration['qwp error'] = cal[aux.argsort(), 2] * ur('volt') #self.logger.debug('Calibration dictionary: {}'.format(self.calibration)) self.logger.info('Done loading calibration.') def idn(self): """ Ask for the identification """ self.logger.info('Asking for identification.') return self.controller.idn() def get_analog_value(self, channel): """ Gets the analog voltage of the channel. :param channel: Port number. Range depends on device :type channel: int :return: voltage: voltage in use for the channel :rtype: pint quantity """ self.logger.debug('Asking for analog value at channel {}.'.format(channel)) value = self.controller.get_voltage(channel) # bits has no units return value def set_analog_value(self, channel, value): """ Sets the analog voltage of the channel. :param channel: Port number. Range depends on device :type channel: int :param value: The input value in Volts between 0 and 25 (Pint type) :type value: pint quantity """ self.logger.debug('Setting analog value {} for channel {}.'.format(value, channel)) self.controller.set_voltage(channel, value) return value def quarter_waveplate_voltage(self, wavelength, method = 'lookup'): """ This method gives the voltage needed to set on the LCC25 to get a quarter waveplate (QWP) behaviour for a given wavelength. It is based on a calibration file that relates the QWP voltage to a wavelength and (so far) uses a linear fit to those data points. :param wavelength: The input wavelength :type wavelength: pint Quantity :param method: method to extrapolate between measured data points :type method: string :return: the QWP voltage :rtype: pint quantity """ self.logger.debug('Getting the quarter waveplate voltage from calibration with method: {}'.format(method)) if wavelength.m_as('nm') < self.calibration['wavelength_limits'][0].m_as('nm') or \ wavelength.m_as('nm') > self.calibration['wavelength_limits'][1].m_as('nm'): self.logger.warning('The required wavelength is outside the calibration range for bias voltage') if wavelength.m_as('nm') < self.calibration['wavelength_limits'][0].m_as('nm'): wavelength = self.calibration['wavelength_limits'][0] if wavelength.m_as('nm') > self.calibration['wavelength_limits'][1].m_as('nm'): wavelength = self.calibration['wavelength_limits'][1] self.logger.warning('Getting the voltage for {} instead.'.format(wavelength)) methods = ['lookup'] if method not in methods: self.logger.warning('The required method to use for the calibration is not implemented. \n' 'Using lookup method.') if method == 'lookup': x = self.calibration['wavelength'] y = self.calibration['qwp'] v = self.do_interp(wavelength, x, y) self.logger.debug('The QWP voltage for {} is {}'.format(wavelength, v)) self._wavelength = wavelength return v def do_interp(self, w, x, y): """ This function interpolates the voltage value for the wavelength value w, using the calibration data (x,y) where x is wavelength and y is voltage :param w: desired wavelength :type w: pint quantity :param x: wavelength vector from calibration :type x: pint quantity :param y: calibrated voltage values :type y: pint quantity :return: the voltage for the desired wavelength :rtype: pint quantity """ self.logger.debug('Wavelength to interpolate: {}'.format(w)) #self.logger.debug('x: {} \n y: {}'.format(x, y)) value = np.interp(w.m_as('nm'), x.m_as('nm'), y.m_as('volt') ) self.logger.debug('interpolated value: {}'.format(value)) value = round(value, 3) return value * ur('volt') def set_quarter_waveplate_voltage(self, wavelength): """ This method sets the quarter-wave plate (QWP) voltage to the variable-wave plate for a given wavelength. It uses Voltage 1 for output. :param wavelength: The input wavelength :type wavelength: pint Quantity :return: the voltage set to the controller :rtype: pint quantity """ if self.mode != 'QWP': self.mode = 'QWP' self.logger.debug('Getting the quarter-wave plate voltage') v = self.quarter_waveplate_voltage(wavelength) self.logger.debug('Setting the QWP voltage for {} in channel 1.'.format(wavelength)) self.set_analog_value(1, v) return v def finalize(self, state=False): """ Closes the connection to the device """ self.logger.info('Finalizing connection with Variable Waveplate. Setting output to: {}'.format(state)) self.controller.output = state sleep(0.1) self.controller.finalize() @property def freq(self): """ Modulation frequency when the operation mode is 'modulation' (mode = 0) : getter : Asks for the current frequency :return: The frequency value :rtype: pint quantity : setter : :param F: frequency in Hz. It can be any value between 0.5 and 150Hz. :type F: pint Quantity """ self.logger.debug('Ask for the current frequency.') ans = self.controller.freq self._freq = ans return self._freq @freq.setter def freq(self, F): self._freq = F self.controller.freq = F self.logger.info('Changed frequency to {} '.format(F)) @property def output(self): """ Tells if the output is enabled or not. :getter: :return: output state :rtype: logical :setter: :param state: value for the amplitude to set in Volts :type state: logical """ self.logger.debug('Asking for the output state') self._output = self.controller.output return self._output @output.setter def output(self, state): self.logger.debug('Setting the output state to {}'.format(state)) self._output = state self.controller.output = state #return self._output @property def mode(self): """ Operation mode The possible modes are: 'Modulation': sends a 2kHz sin wave modulated with a square wave where voltage 1 is one limit and voltage 2 is the second. the modulation frequency can be changed with the command 'freq' in the 0.5-150 Hz range. 'Voltage1' : sends a 2kHz sin wave with RMS value set by voltage 1 'Voltage2' : sends a 2kHz sin wave with RMS value set by voltage 2 'QWP' : uses the calibration file to set the voltage that acts as a quarter-wave plate for the specified wavelength. : getter : Gets the current mode :return: current mode :rtype: string : setter : Sets the mode :param mode: type of operation. :type mode: string """ self.logger.debug('Getting the mode of operation') if self._mode != 'QWP': mode = self.controller.mode self.logger.debug('The mode from controller is: {}'.format(mode)) self._mode = self.MODES[mode] return self._mode @mode.setter def mode(self, mode): ind = self.MODES.index(mode) if ind == 3: ind = 1 self.controller.mode = ind self.logger.debug('Changed to mode "{}" '.format(mode)) self._mode = mode if __name__ == '__main__': logging.stream_level = "INFO" log = logging.getLogger(__name__) dummy_mode = [False] # add here false to unit_test the code with the real device for dummy in dummy_mode: print('Running in dummy = {}'.format(dummy)) with VariableWaveplate(settings = {'port':'COM8', 'enable': False, 'dummy' : dummy, 'controller': 'hyperion.controller.thorlabs.lcc25/Lcc'}) as dev: # output status and set log.info('The output is: {}'.format(dev.output)) dev.output = True log.info('The output is: {}'.format(dev.output)) # mode log.info('The mode is: {}'.format(dev.mode)) for m in range(4): dev.mode = dev.MODES[m] log.info('The mode is: {}'.format(dev.mode)) # set voltage