repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list | possible_versions
list |
---|---|---|---|---|---|
tensorflow/gnn | [
"c529f2a83230c028186f6c6754e17587e4ec90d1"
] | [
"tensorflow_gnn/graph/adjacency.py"
] | [
"\"\"\"GraphTensor adjacency types.\"\"\"\n\nfrom typing import Dict, Mapping, Optional, Tuple, Union\n\nimport tensorflow as tf\nfrom tensorflow_gnn.graph import graph_constants as const\nfrom tensorflow_gnn.graph import graph_piece as gp\nfrom tensorflow_gnn.graph import tensor_utils as utils\n\n# pylint: disable=g-direct-tensorflow-import\nfrom tensorflow.python.framework import type_spec\n# pylint: enable=g-direct-tensorflow-import\n\nField = const.Field\nFieldSpec = const.FieldSpec\nIncidentNodeTag = const.IncidentNodeTag\nNodeSetName = const.NodeSetName\n\nIndex = Tuple[NodeSetName, Field]\nIndices = Mapping[IncidentNodeTag, Index]\n\n\nclass HyperAdjacency(gp.GraphPieceBase):\n \"\"\"Stores how (hyper-)edges connect tuples of nodes from incident node sets.\n\n The incident node sets in the hyper-adjacency are referenced by a unique\n integer identifier called the node set tag. (For a non-hyper graph, it is\n conventional to use the integers `tfgnn.SOURCE` and `tfgnn.TARGET`.) This\n allows the hyper-adjacency to connect nodes from the same or different node\n sets. Each hyper-edge connects a fixed number of nodes, one node from each\n incident node set. The adjacency information is stored as a mapping from the\n node set tags to integer tensors containing indices of nodes in corresponding\n node sets. Those tensors are indexed by edges. All index tensors have the same\n type spec and shape of `[*graph_shape, num_edges]`, where num_edges is the\n number of edges in the edge set (could be potentially ragged). The index\n tensors are of `tf.Tensor` type if num_edges is not None or\n `graph_shape.rank = 0` and of `tf.RaggedTensor` type otherwise.\n\n The HyperAdjacency is a composite tensor.\n \"\"\"\n\n # TODO(b/210004712): Replace `*_` by more Pythonic `*`.\n @classmethod\n @tf.__internal__.dispatch.add_dispatch_support\n def from_indices(cls,\n indices: Indices,\n *_,\n validate: bool = True) -> 'HyperAdjacency':\n \"\"\"Constructs a new instance from the `indices` tensors.\n\n Example 1. Single graph (rank is 0). Connects pairs of nodes (a[0], b[2]),\n (a[1], b[1]), (a[2], b[0]) from node sets a and b:\n\n tfgnn.HyperAdjacency.from_indices({\n tfgnn.SOURCE: ('a', [0, 1, 2]),\n tfgnn.TARGET: ('b', [2, 1, 0])\n })\n\n Example 2. Single hypergraph (rank is 0). Connects triplets of nodes\n (a[0], b[2], c[1]), (a[1], b[1], c[0]) from the node sets a, b and c:\n\n tfgnn.HyperAdjacency.from_indices({\n 0: ('a', [0, 1]),\n 1: ('b', [2, 1]),\n 2: ('c', [1, 0]),\n })\n\n Example 3. Batch of two graphs (rank is 1). Connects pairs of nodes in\n graph 0: (a[0], b[2]), (a[1], b[1]); graph 1: (a[2], b[0]):\n\n tfgnn.HyperAdjacency.from_indices({\n tfgnn.SOURCE: ('a', tf.ragged.constant([[0, 1], [2]])),\n tfgnn.TARGET: ('b', tf.ragged.constant([[2, 1], [0]])),\n })\n\n Args:\n indices: A mapping from node tags to 2-tuples of node set name and node\n index tensor. The index tensors must have the same type spec and shape\n of `[*graph_shape, num_edges]`, where num_edges is the number of edges\n in each graph (could be ragged). The index tensors are of `tf.Tensor`\n type if num_edges is not None or `graph_shape.rank = 0` and of\n `tf.RaggedTensor` type otherwise.\n validate: If True, checks that node indices have the same type spec.\n\n Returns:\n A `HyperAdjacency` tensor with its `shape` and `indices_dtype` being\n inferred from the passed `indices` values.\n \"\"\"\n if _:\n raise TypeError('Positional arguments are not supported:', _)\n\n indices = {\n key: (name, gp.convert_to_tensor_or_ragged(index))\n for key, (name, index) in indices.items()\n }\n\n if validate or const.validate_internal_results:\n indices = _validate_indices(indices)\n\n data = {\n _node_tag_to_index_key(tag): index\n for tag, (_, index) in indices.items()\n }\n # This graph piece uses metadata fields as a mapping from an indcident node\n # tag as f'{const.INDEX_KEY_PREFIX}{node_tag}' (see b/187015015) to the\n # node set name.\n metadata = {\n _node_tag_to_index_key(tag): name for tag, (name, _) in indices.items()\n }\n indicative_index_tensor = _get_indicative_index(data)\n return cls._from_data(\n data,\n shape=indicative_index_tensor.shape[:-1],\n indices_dtype=indicative_index_tensor.dtype,\n metadata=metadata)\n\n def __getitem__(self, node_set_tag: IncidentNodeTag) -> Field:\n \"\"\"Returns an index tensor for the given node set tag.\"\"\"\n return self._data[_node_tag_to_index_key(node_set_tag)]\n\n def node_set_name(self, node_set_tag: IncidentNodeTag) -> NodeSetName:\n \"\"\"Returns a node set name for the given node set tag.\"\"\"\n return self.spec.node_set_name(node_set_tag)\n\n def get_indices_dict(\n self) -> Dict[IncidentNodeTag, Tuple[NodeSetName, Field]]:\n \"\"\"Returns copy of indices as a dictionary.\"\"\"\n return {\n _index_key_to_node_tag(key):\n (self.node_set_name(_index_key_to_node_tag(key)), index)\n for key, index in self._data.items()\n }\n\n def _merge_batch_to_components(\n self, num_edges_per_example: Field,\n num_nodes_per_example: Mapping[NodeSetName, Field]) -> 'HyperAdjacency':\n if self.rank == 0:\n return self\n\n flat_adj = super()._merge_batch_to_components(\n num_edges_per_example=num_edges_per_example,\n num_nodes_per_example=num_nodes_per_example)\n assert isinstance(flat_adj, HyperAdjacency)\n\n def flatten_indices(node_tag_key, index: Field) -> Field:\n node_set_name = self.spec._metadata[node_tag_key] # pylint: disable=protected-access\n return utils.flatten_indices(index, num_edges_per_example,\n num_nodes_per_example[node_set_name])\n\n new_data = {\n node_tag_key: flatten_indices(node_tag_key, index)\n for node_tag_key, index in flat_adj._data.items() # pylint: disable=protected-access\n }\n return self.__class__(new_data, flat_adj.spec)\n\n @staticmethod\n def _type_spec_cls():\n return HyperAdjacencySpec\n\n\n@type_spec.register('tensorflow_gnn.HyperAdjacencySpec')\nclass HyperAdjacencySpec(gp.GraphPieceSpecBase):\n \"\"\"A type spec for `tfgnn.HyperAdjacency`.\"\"\"\n\n @classmethod\n def from_incident_node_sets(\n cls,\n incident_node_sets: Mapping[IncidentNodeTag, NodeSetName],\n index_spec: FieldSpec = tf.TensorSpec((None,),\n const.default_indices_dtype)\n ) -> 'HyperAdjacencySpec':\n \"\"\"Constructs a new instance from the `incident_node_sets`.\n\n Args:\n incident_node_sets: A mapping from incident node tags to node set names.\n index_spec: type spec for all index tensors of shape\n `[*graph_shape, num_edges]`, where num_edges is the number of edges in\n each graph. If num_edges is not None or `graph_shape.rank = 0` the spec\n must be of `tf.TensorSpec` type and of `tf.RaggedTensorSpec` type\n otherwise.\n\n Returns:\n A `HyperAdjacencySpec` TypeSpec.\n \"\"\"\n if not (index_spec.shape.rank > 0 and\n index_spec.dtype in (tf.int32, tf.int64)):\n raise ValueError(\n 'Index spec must have rank > 0 and dtype in (tf.int32, tf.int64),'\n f' got {index_spec}')\n\n data_spec = {\n _node_tag_to_index_key(tag): index_spec for tag in incident_node_sets\n }\n # This graph piece uses metadata fields as a mapping from an indcident node\n # tag as f'{const.INDEX_KEY_PREFIX}{node_tag}' (see b/187015015) to the\n # node set name.\n metadata = {\n _node_tag_to_index_key(tag): name\n for tag, name in incident_node_sets.items()\n }\n return cls._from_data_spec(\n data_spec,\n shape=index_spec.shape[:-1],\n indices_dtype=index_spec.dtype,\n metadata=metadata)\n\n @property\n def value_type(self):\n return HyperAdjacency\n\n def __getitem__(self, node_set_tag: IncidentNodeTag) -> FieldSpec:\n \"\"\"Returns an index tensor type spec for the given node set tag.\"\"\"\n return self._data_spec[_node_tag_to_index_key(node_set_tag)]\n\n def get_index_specs_dict(\n self) -> Dict[IncidentNodeTag, Tuple[NodeSetName, FieldSpec]]:\n \"\"\"Returns copy of indices type specs as a dictionary.\"\"\"\n return {\n _index_key_to_node_tag(key):\n (self.node_set_name(_index_key_to_node_tag(key)), index)\n for key, index in self._data_spec.items()\n }\n\n def node_set_name(self, node_set_tag: IncidentNodeTag) -> NodeSetName:\n \"\"\"Returns a node set name for the given node set tag.\"\"\"\n return self._metadata[_node_tag_to_index_key(node_set_tag)]\n\n @property\n def total_size(self) -> Optional[int]:\n \"\"\"The total number of edges if known.\"\"\"\n ind_spec = _get_indicative_index(self._data_spec)\n assert ind_spec is not None\n return ind_spec.shape[:(self.rank + 1)].num_elements()\n\n\nclass Adjacency(HyperAdjacency):\n \"\"\"Stores how edges connect pairs of nodes from source and target node sets.\n\n Each hyper-edge connect one node from the source node set with one node from\n the target node sets. The source and target node sets could be the same.\n The adjacency information is a pair of integer tensors containing indices of\n nodes in source and target node sets. Those tensors are indexed by\n edges, have the same type spec and shape of `[*graph_shape, num_edges]`,\n where num_edges is the number of edges in the edge set (could be potentially\n ragged). The index tensors are of `tf.Tensor` type if num_edges is not None\n or `graph_shape.rank = 0` and of`tf.RaggedTensor` type otherwise.\n\n The Adjacency is a composite tensor and a special case of tfgnn.HyperAdjacency\n class with `tfgnn.SOURCE` and `tfgnn.TARGET` node tags used for the source and\n target nodes correspondingly.\n \"\"\"\n\n # TODO(b/210004712): Replace `*_` by more Pythonic `*`.\n @classmethod\n @tf.__internal__.dispatch.add_dispatch_support\n def from_indices(cls,\n source: Index,\n target: Index,\n *_,\n validate: bool = True) -> 'Adjacency':\n \"\"\"Constructs a new instance from the `source` and `target` node indices.\n\n Example 1. Single graph (rank is 0). Connects pairs of nodes (a[0], b[2]),\n (a[1], b[1]), (a[2], b[0]) from node sets a and b:\n\n tfgnn.Adjacency.from_indices(('a', [0, 1, 2]),\n ('b', [2, 1, 0]))\n\n Example 2. Batch of two graphs (rank is 1). Connects pairs of nodes in\n graph 0: (a[0], b[2]), (a[1], b[1]); graph 1: (a[2], b[0]):\n\n tfgnn.Adjacency.from_indices(('a', tf.ragged.constant([[0, 1], [2]])),\n ('b', tf.ragged.constant([[2, 1], [0]])))\n\n Args:\n source: The tuple of node set name and nodes index integer tensor. The\n index must have shape of `[*graph_shape, num_edges]`, where num_edges\n is the number of edges in each graph (could be ragged). It has\n `tf.Tensor` type if num_edges is not None or `graph_shape.rank = 0` and\n `tf.RaggedTensor` type otherwise.\n target: Like `source` field, but for target edge endpoint. Index tensor\n must have the same type spec as for the `source`.\n validate: If True, checks that source and target indices have the same\n type spec.\n\n Returns:\n An `Adjacency` tensor with a shape and an indices_dtype being inferred\n from the `indices` values.\n \"\"\"\n if _:\n raise TypeError('Positional arguments are not supported:', _)\n return super().from_indices({const.SOURCE: source, const.TARGET: target})\n\n @property\n def source(self) -> Field:\n \"\"\"The indices of source nodes.\"\"\"\n return self[const.SOURCE]\n\n @property\n def target(self) -> Field:\n \"\"\"The indices of target nodes.\"\"\"\n return self[const.TARGET]\n\n @property\n def source_name(self) -> NodeSetName:\n \"\"\"The node set name of source nodes.\"\"\"\n return self.node_set_name(const.SOURCE)\n\n @property\n def target_name(self) -> NodeSetName:\n \"\"\"The node set name of target nodes.\"\"\"\n return self.node_set_name(const.TARGET)\n\n @staticmethod\n def _type_spec_cls():\n return AdjacencySpec\n\n def __repr__(self):\n return (f'Adjacency(source=(\\'{self.source_name}\\', '\n f'{utils.short_repr(self.source)}), '\n f'target=(\\'{self.target_name}\\', '\n f'{utils.short_repr(self.target)}))')\n\n\n@type_spec.register('tensorflow_gnn.AdjacencySpec')\nclass AdjacencySpec(HyperAdjacencySpec):\n \"\"\"A type spec for `tfgnn.Adjacency`.\"\"\"\n\n @classmethod\n def from_incident_node_sets(\n cls,\n source_node_set: NodeSetName,\n target_node_set: NodeSetName,\n index_spec: FieldSpec = tf.TensorSpec((None,),\n const.default_indices_dtype)\n ) -> 'AdjacencySpec':\n \"\"\"Constructs a new instance from the `incident_node_sets`.\n\n Args:\n source_node_set: The name of the source node set.\n target_node_set: The name of the target node set.\n index_spec: type spec for source and target index tensors of shape\n `[*graph_shape, num_edges]`, where num_edges is the number of edges in\n each graph. If num_edges is not None or `graph_shape.rank = 0` the spec\n must be of `tf.TensorSpec` type and of `tf.RaggedTensorSpec` type\n otherwise.\n\n Returns:\n A `AdjacencySpec` TypeSpec.\n \"\"\"\n return super().from_incident_node_sets(\n {const.SOURCE: source_node_set,\n const.TARGET: target_node_set}, index_spec)\n\n @property\n def value_type(self):\n return Adjacency\n\n @property\n def source(self) -> FieldSpec:\n return self[const.SOURCE]\n\n @property\n def target(self) -> FieldSpec:\n return self[const.TARGET]\n\n @property\n def source_name(self) -> NodeSetName:\n \"\"\"Returns the node set name for source nodes.\"\"\"\n return self.node_set_name(const.SOURCE)\n\n @property\n def target_name(self) -> NodeSetName:\n \"\"\"Returns the node set name for target nodes.\"\"\"\n return self.node_set_name(const.TARGET)\n\n\ndef _validate_indices(indices: Indices) -> Indices:\n \"\"\"Checks that indices have compatible shapes.\"\"\"\n if not indices:\n raise ValueError('`indices` must contain at least one entry.')\n\n assert_ops = []\n\n def check_index(tag, name, index):\n if index.dtype not in (tf.int32, tf.int64):\n raise ValueError((f'Adjacency indices ({tag}, {name}) must have '\n f'tf.int32 or tf.int64 dtype, got {index.dtype}'))\n if isinstance(index, tf.RaggedTensor):\n if index.flat_values.shape.rank != 1:\n raise ValueError(\n (f'Adjacency indices ({tag_0}, {name_0}) as ragged tensor must'\n f' have flat values rank 1, got {index.flat_values.shape.rank}'))\n\n def check_compatibility(tag_0, name_0, index_0, tag_i, name_i, index_i):\n err_message = ('Adjacency indices are not compatible:'\n f' ({tag_0}, {name_0}) and ({tag_i}, {name_i})')\n try:\n if index_0.dtype != index_i.dtype:\n raise ValueError(err_message)\n\n if isinstance(index_0, tf.Tensor) and isinstance(index_i, tf.Tensor):\n assert_ops.append(\n tf.assert_equal(\n tf.shape(index_0), tf.shape(index_i), message=err_message))\n return\n\n if isinstance(index_0, tf.RaggedTensor) and isinstance(\n index_i, tf.RaggedTensor):\n if index_0.ragged_rank != index_i.ragged_rank:\n raise ValueError(err_message)\n for partition_0, partition_i in zip(index_0.nested_row_splits,\n index_i.nested_row_splits):\n assert_ops.append(\n tf.assert_equal(partition_0, partition_i, message=err_message))\n\n assert_ops.append(\n tf.assert_equal(\n tf.shape(index_0.flat_values),\n tf.shape(index_i.flat_values),\n message=err_message))\n return\n except:\n raise ValueError(err_message) from None\n\n raise ValueError(err_message)\n\n indices = sorted(list(indices.items()), key=lambda i: i[0])\n tag_0, (name_0, index_0) = indices[0]\n check_index(tag_0, name_0, index_0)\n for tag_i, (name_i, index_i) in indices[1:]:\n check_index(tag_i, name_i, index_i)\n check_compatibility(tag_0, name_0, index_0, tag_i, name_i, index_i)\n\n # Apply identity operations to all index tensors to ensure that assertions are\n # executed in the graph mode.\n with tf.control_dependencies(assert_ops):\n result = {}\n for node_tag, (node_set, index) in indices:\n result[node_tag] = (node_set, tf.identity(index))\n\n return result\n\n\ndef _node_tag_to_index_key(node_tag: IncidentNodeTag) -> str:\n \"\"\"Converts node incident tag to internal string representation.\n\n GraphPiece requires that all its metadata entries are keyed by string keys.\n This function converts node incident tags to their string representations\n which are used to store incident node set names in metadata and indices\n tensors in the GraphPiece data.\n\n See `GraphPiece` class for more information.\n\n Args:\n node_tag: node incident tag.\n\n Returns:\n Internal string key representation.\n \"\"\"\n if not isinstance(node_tag, IncidentNodeTag):\n raise ValueError(\n f'Node set tag must be integer, got {type(node_tag).__name__}')\n return f'{const.INDEX_KEY_PREFIX}{node_tag}'\n\n\ndef _index_key_to_node_tag(index_key: str) -> IncidentNodeTag:\n \"\"\"Recovers node incident tag from internal string representation.\n\n See `_node_tag_to_index_key`.\n\n Args:\n index_key: internal node incident tag string representation.\n\n Returns:\n Node incident tag.\n \"\"\"\n assert index_key.startswith(const.INDEX_KEY_PREFIX)\n return int(index_key[len(const.INDEX_KEY_PREFIX):])\n\n\ndef _get_indicative_index(\n indices: Mapping[str, Union[Field, FieldSpec]]) -> Union[Field, FieldSpec]:\n \"\"\"Deterministically selects one of the index tensors from the `indices`.\"\"\"\n assert indices\n _, result = min(indices.items(), key=lambda item: item[0])\n\n assert isinstance(\n result, (tf.Tensor, tf.RaggedTensor, tf.TensorSpec, tf.RaggedTensorSpec))\n assert result.shape.rank >= 1\n return result\n"
] | [
[
"tensorflow.control_dependencies",
"tensorflow.shape",
"tensorflow.identity",
"tensorflow.python.framework.type_spec.register",
"tensorflow.assert_equal",
"tensorflow.TensorSpec"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.13"
]
}
] |
jimfhahn/Annif | [
"1a35a273bbdda1f98ac98099fec1bc38e984f327",
"1a35a273bbdda1f98ac98099fec1bc38e984f327"
] | [
"annif/util.py",
"annif/suggestion.py"
] | [
"\"\"\"Utility functions for Annif\"\"\"\n\nimport glob\nimport os\nimport os.path\nimport tempfile\nimport numpy as np\nfrom annif import logger\nfrom annif.suggestion import VectorSuggestionResult\n\n\ndef atomic_save(obj, dirname, filename, method=None):\n \"\"\"Save the given object (which must have a .save() method, unless the\n method parameter is given) into the given directory with the given\n filename, using a temporary file and renaming the temporary file to the\n final name.\"\"\"\n\n prefix, suffix = os.path.splitext(filename)\n tempfd, tempfilename = tempfile.mkstemp(\n prefix=prefix, suffix=suffix, dir=dirname)\n os.close(tempfd)\n logger.debug('saving %s to temporary file %s', str(obj)[:90], tempfilename)\n if method is not None:\n method(obj, tempfilename)\n else:\n obj.save(tempfilename)\n for fn in glob.glob(tempfilename + '*'):\n newname = fn.replace(tempfilename, os.path.join(dirname, filename))\n logger.debug('renaming temporary file %s to %s', fn, newname)\n os.rename(fn, newname)\n\n\ndef cleanup_uri(uri):\n \"\"\"remove angle brackets from a URI, if any\"\"\"\n if uri.startswith('<') and uri.endswith('>'):\n return uri[1:-1]\n return uri\n\n\ndef merge_hits(weighted_hits, subject_index):\n \"\"\"Merge hits from multiple sources. Input is a sequence of WeightedSuggestion\n objects. A SubjectIndex is needed to convert between subject IDs and URIs.\n Returns an SuggestionResult object.\"\"\"\n\n weights = [whit.weight for whit in weighted_hits]\n scores = [whit.hits.as_vector(subject_index) for whit in weighted_hits]\n result = np.average(scores, axis=0, weights=weights)\n return VectorSuggestionResult(result)\n\n\ndef parse_sources(sourcedef):\n \"\"\"parse a source definition such as 'src1:1.0,src2' into a sequence of\n tuples (src_id, weight)\"\"\"\n\n sources = []\n totalweight = 0.0\n for srcdef in sourcedef.strip().split(','):\n srcval = srcdef.strip().split(':')\n src_id = srcval[0]\n if len(srcval) > 1:\n weight = float(srcval[1])\n else:\n weight = 1.0\n sources.append((src_id, weight))\n totalweight += weight\n return [(srcid, weight / totalweight) for srcid, weight in sources]\n\n\ndef parse_args(param_string):\n \"\"\"Parse a string of comma separated arguments such as '42,43,key=abc' into\n a list of positional args [42, 43] and a dict of keyword args {key: abc}\"\"\"\n\n if not param_string:\n return [], {}\n posargs = []\n kwargs = {}\n param_strings = param_string.split(',')\n for p_string in param_strings:\n parts = p_string.split('=')\n if len(parts) == 1:\n posargs.append(p_string)\n elif len(parts) == 2:\n kwargs[parts[0]] = parts[1]\n return posargs, kwargs\n\n\ndef boolean(val):\n \"\"\"Convert the given value to a boolean True/False value, if it isn't already.\n True values are '1', 'yes', 'true', and 'on' (case insensitive), everything\n else is False.\"\"\"\n\n return str(val).lower() in ('1', 'yes', 'true', 'on')\n\n\ndef identity(x):\n \"\"\"Identity function: return the given argument unchanged\"\"\"\n return x\n\n\ndef metric_code(metric):\n \"\"\"Convert a human-readable metric name into an alphanumeric string\"\"\"\n return metric.translate(metric.maketrans(' ', '_', '()'))\n",
"\"\"\"Representing suggested subjects.\"\"\"\n\nimport abc\nimport collections\nimport itertools\nimport numpy as np\n\n\nSubjectSuggestion = collections.namedtuple(\n 'SubjectSuggestion', 'uri label notation score')\nWeightedSuggestion = collections.namedtuple(\n 'WeightedSuggestion', 'hits weight subjects')\n\n\nclass SuggestionFilter:\n \"\"\"A reusable filter for filtering SubjectSuggestion objects.\"\"\"\n\n def __init__(self, subject_index, limit=None, threshold=0.0):\n self._subject_index = subject_index\n self._limit = limit\n self._threshold = threshold\n\n def __call__(self, orighits):\n return LazySuggestionResult(\n lambda: orighits.filter(self._subject_index,\n self._limit,\n self._threshold))\n\n\nclass SuggestionResult(metaclass=abc.ABCMeta):\n \"\"\"Abstract base class for a set of hits returned by an analysis\n operation.\"\"\"\n\n @abc.abstractmethod\n def as_list(self, subject_index):\n \"\"\"Return the hits as an ordered sequence of SubjectSuggestion objects,\n highest scores first.\"\"\"\n pass # pragma: no cover\n\n @abc.abstractmethod\n def as_vector(self, subject_index, destination=None):\n \"\"\"Return the hits as a one-dimensional score vector\n where the indexes match the given subject index. If destination array\n is given (not None) it will be used, otherwise a new array will\n be created.\"\"\"\n pass # pragma: no cover\n\n @abc.abstractmethod\n def filter(self, subject_index, limit=None, threshold=0.0):\n \"\"\"Return a subset of the hits, filtered by the given limit and\n score threshold, as another SuggestionResult object.\"\"\"\n pass # pragma: no cover\n\n @abc.abstractmethod\n def __len__(self):\n \"\"\"Return the number of hits with non-zero scores.\"\"\"\n pass # pragma: no cover\n\n\nclass LazySuggestionResult(SuggestionResult):\n \"\"\"SuggestionResult implementation that wraps another SuggestionResult which\n is initialized lazily only when it is actually accessed. Method calls\n will be proxied to the wrapped SuggestionResult.\"\"\"\n\n def __init__(self, construct):\n \"\"\"Create the proxy object. The given construct function will be\n called to create the actual SuggestionResult when it is needed.\"\"\"\n self._construct = construct\n self._object = None\n\n def _initialize(self):\n if self._object is None:\n self._object = self._construct()\n\n def as_list(self, subject_index):\n self._initialize()\n return self._object.as_list(subject_index)\n\n def as_vector(self, subject_index, destination=None):\n self._initialize()\n return self._object.as_vector(subject_index, destination)\n\n def filter(self, subject_index, limit=None, threshold=0.0):\n self._initialize()\n return self._object.filter(subject_index, limit, threshold)\n\n def __len__(self):\n self._initialize()\n return len(self._object)\n\n\nclass VectorSuggestionResult(SuggestionResult):\n \"\"\"SuggestionResult implementation based primarily on NumPy vectors.\"\"\"\n\n def __init__(self, vector):\n vector_f32 = vector.astype(np.float32)\n # limit scores to the range 0.0 .. 1.0\n self._vector = np.minimum(np.maximum(vector_f32, 0.0), 1.0)\n self._subject_order = None\n self._lsr = None\n\n def _vector_to_list_suggestion(self, subject_index):\n hits = []\n for subject_id in self.subject_order:\n score = self._vector[subject_id]\n if score <= 0.0:\n break # we can skip the remaining ones\n subject = subject_index[subject_id]\n hits.append(\n SubjectSuggestion(\n uri=subject[0],\n label=subject[1],\n notation=subject[2],\n score=float(score)))\n return ListSuggestionResult(hits)\n\n @property\n def subject_order(self):\n if self._subject_order is None:\n self._subject_order = np.argsort(self._vector)[::-1]\n return self._subject_order\n\n def as_list(self, subject_index):\n if self._lsr is None:\n self._lsr = self._vector_to_list_suggestion(subject_index)\n return self._lsr.as_list(subject_index)\n\n def as_vector(self, subject_index, destination=None):\n if destination is not None:\n np.copyto(destination, self._vector)\n return destination\n return self._vector\n\n def filter(self, subject_index, limit=None, threshold=0.0):\n mask = (self._vector > threshold)\n deprecated_ids = subject_index.deprecated_ids()\n if limit is not None:\n limit_mask = np.zeros_like(self._vector, dtype=bool)\n deprecated_set = set(deprecated_ids)\n top_k_subjects = itertools.islice(\n (subj for subj in self.subject_order\n if subj not in deprecated_set), limit)\n limit_mask[list(top_k_subjects)] = True\n mask = mask & limit_mask\n else:\n deprecated_mask = np.ones_like(self._vector, dtype=bool)\n deprecated_mask[deprecated_ids] = False\n mask = mask & deprecated_mask\n vsr = VectorSuggestionResult(self._vector * mask)\n return ListSuggestionResult(vsr.as_list(subject_index))\n\n def __len__(self):\n return (self._vector > 0.0).sum()\n\n\nclass ListSuggestionResult(SuggestionResult):\n \"\"\"SuggestionResult implementation based primarily on lists of hits.\"\"\"\n\n def __init__(self, hits):\n self._list = [self._enforce_score_range(hit)\n for hit in hits\n if hit.score > 0.0]\n self._vector = None\n\n @staticmethod\n def _enforce_score_range(hit):\n if hit.score > 1.0:\n return hit._replace(score=1.0)\n return hit\n\n @classmethod\n def create_from_index(cls, hits, subject_index):\n subject_suggestions = []\n for hit in hits:\n subject_id = subject_index.by_uri(hit.uri)\n if subject_id is None:\n continue\n subject = subject_index[subject_id]\n subject_suggestions.append(\n SubjectSuggestion(uri=hit.uri,\n label=subject[1],\n notation=subject[2],\n score=hit.score))\n return ListSuggestionResult(subject_suggestions)\n\n def _list_to_vector(self, subject_index, destination):\n if destination is None:\n destination = np.zeros(len(subject_index), dtype=np.float32)\n\n for hit in self._list:\n subject_id = subject_index.by_uri(hit.uri)\n if subject_id is not None:\n destination[subject_id] = hit.score\n return destination\n\n def as_list(self, subject_index):\n return self._list\n\n def as_vector(self, subject_index, destination=None):\n if self._vector is None:\n self._vector = self._list_to_vector(subject_index, destination)\n return self._vector\n\n def filter(self, subject_index, limit=None, threshold=0.0):\n hits = sorted(self._list, key=lambda hit: hit.score, reverse=True)\n filtered_hits = [hit for hit in hits\n if hit.score >= threshold and hit.score > 0.0 and\n hit.label is not None]\n if limit is not None:\n filtered_hits = filtered_hits[:limit]\n return ListSuggestionResult(filtered_hits)\n\n def __len__(self):\n return len(self._list)\n"
] | [
[
"numpy.average"
],
[
"numpy.ones_like",
"numpy.maximum",
"numpy.zeros_like",
"numpy.copyto",
"numpy.argsort"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
turoger/dgl | [
"4c7781f5c2a80f3b72c8888af10b6dbfbab3c31e",
"4c7781f5c2a80f3b72c8888af10b6dbfbab3c31e"
] | [
"examples/pytorch/rgcn/experimental/write_mag.py",
"python/dgl/dataloading/dataloader.py"
] | [
"import dgl\nimport json\nimport torch as th\nimport numpy as np\nfrom ogb.nodeproppred import DglNodePropPredDataset\nfrom pyinstrument import Profiler\n\n# Load OGB-MAG.\ndataset = DglNodePropPredDataset(name='ogbn-mag')\nhg_orig, labels = dataset[0]\nsubgs = {}\nfor etype in hg_orig.canonical_etypes:\n u, v = hg_orig.all_edges(etype=etype)\n subgs[etype] = (u, v)\n subgs[(etype[2], 'rev-'+etype[1], etype[0])] = (v, u)\nhg = dgl.heterograph(subgs)\nhg.nodes['paper'].data['feat'] = hg_orig.nodes['paper'].data['feat']\nprint(hg)\n#subg_nodes = {}\n#for ntype in hg.ntypes:\n# subg_nodes[ntype] = np.random.choice(hg.number_of_nodes(ntype), int(hg.number_of_nodes(ntype) / 5), replace=False)\n#hg = dgl.compact_graphs(dgl.node_subgraph(hg, subg_nodes))\n\nprofiler = Profiler()\nprofiler.start()\n\n# OGB-MAG is stored in heterogeneous format. We need to convert it into homogeneous format.\ng = dgl.to_homogeneous(hg)\ng.ndata['orig_id'] = g.ndata[dgl.NID]\ng.edata['orig_id'] = g.edata[dgl.EID]\nprint('|V|=' + str(g.number_of_nodes()))\nprint('|E|=' + str(g.number_of_edges()))\nprint('|NTYPE|=' + str(len(th.unique(g.ndata[dgl.NTYPE]))))\n\n# Store the metadata of nodes.\nnum_node_weights = 0\nnode_data = [g.ndata[dgl.NTYPE].numpy()]\nfor ntype_id in th.unique(g.ndata[dgl.NTYPE]):\n node_data.append((g.ndata[dgl.NTYPE] == ntype_id).numpy())\n num_node_weights += 1\nnode_data.append(g.ndata['orig_id'].numpy())\nnode_data = np.stack(node_data, 1)\nnp.savetxt('mag_nodes.txt', node_data, fmt='%d', delimiter=' ')\n\n# Store the node features\nnode_feats = {}\nfor ntype in hg.ntypes:\n for name in hg.nodes[ntype].data:\n node_feats[ntype + '/' + name] = hg.nodes[ntype].data[name]\ndgl.data.utils.save_tensors(\"node_feat.dgl\", node_feats)\n\n# Store the metadata of edges.\nsrc_id, dst_id = g.edges()\nedge_data = th.stack([src_id, dst_id,\n g.edata['orig_id'],\n g.edata[dgl.ETYPE]], 1)\nnp.savetxt('mag_edges.txt', edge_data.numpy(), fmt='%d', delimiter=' ')\n\n# Store the edge features\nedge_feats = {}\nfor etype in hg.etypes:\n for name in hg.edges[etype].data:\n edge_feats[etype + '/' + name] = hg.edges[etype].data[name]\ndgl.data.utils.save_tensors(\"edge_feat.dgl\", edge_feats)\n\n# Store the basic metadata of the graph.\ngraph_stats = [g.number_of_nodes(), g.number_of_edges(), num_node_weights]\nwith open('mag_stats.txt', 'w') as filehandle:\n filehandle.writelines(\"{} {} {}\".format(graph_stats[0], graph_stats[1], graph_stats[2]))\n\n# Store the ID ranges of nodes and edges of the entire graph.\nnid_ranges = {}\neid_ranges = {}\nfor ntype in hg.ntypes:\n ntype_id = hg.get_ntype_id(ntype)\n nid = th.nonzero(g.ndata[dgl.NTYPE] == ntype_id, as_tuple=True)[0]\n per_type_nid = g.ndata['orig_id'][nid]\n assert np.all((per_type_nid == th.arange(len(per_type_nid))).numpy())\n assert np.all((nid == th.arange(nid[0], nid[-1] + 1)).numpy())\n nid_ranges[ntype] = [int(nid[0]), int(nid[-1] + 1)]\nfor etype in hg.etypes:\n etype_id = hg.get_etype_id(etype)\n eid = th.nonzero(g.edata[dgl.ETYPE] == etype_id, as_tuple=True)[0]\n assert np.all((eid == th.arange(eid[0], eid[-1] + 1)).numpy())\n eid_ranges[etype] = [int(eid[0]), int(eid[-1] + 1)]\nwith open('mag.json', 'w') as outfile:\n json.dump({'nid': nid_ranges, 'eid': eid_ranges}, outfile, indent=4)\n\nprofiler.stop()\nprint(profiler.output_text(unicode=True, color=True))\n",
"\"\"\"Data loaders\"\"\"\n\nfrom collections.abc import Mapping, Sequence\nfrom abc import ABC, abstractproperty, abstractmethod\nimport re\nimport numpy as np\nfrom .. import transform\nfrom ..base import NID, EID\nfrom .. import backend as F\nfrom .. import utils\nfrom ..batch import batch\nfrom ..convert import heterograph\nfrom ..heterograph import DGLHeteroGraph as DGLGraph\nfrom ..distributed.dist_graph import DistGraph\n\n# pylint: disable=unused-argument\ndef assign_block_eids(block, frontier):\n \"\"\"Assigns edge IDs from the original graph to the message flow graph (MFG).\n\n See also\n --------\n BlockSampler\n \"\"\"\n for etype in block.canonical_etypes:\n block.edges[etype].data[EID] = frontier.edges[etype].data[EID][\n block.edges[etype].data[EID]]\n return block\n\ndef _tensor_or_dict_to_numpy(ids):\n if isinstance(ids, Mapping):\n return {k: F.zerocopy_to_numpy(v) for k, v in ids.items()}\n else:\n return F.zerocopy_to_numpy(ids)\n\ndef _locate_eids_to_exclude(frontier_parent_eids, exclude_eids):\n \"\"\"Find the edges whose IDs in parent graph appeared in exclude_eids.\n\n Note that both arguments are numpy arrays or numpy dicts.\n \"\"\"\n if isinstance(frontier_parent_eids, Mapping):\n result = {\n k: np.isin(frontier_parent_eids[k], exclude_eids[k]).nonzero()[0]\n for k in frontier_parent_eids.keys() if k in exclude_eids.keys()}\n return {k: F.zerocopy_from_numpy(v) for k, v in result.items()}\n else:\n result = np.isin(frontier_parent_eids, exclude_eids).nonzero()[0]\n return F.zerocopy_from_numpy(result)\n\ndef _find_exclude_eids_with_reverse_id(g, eids, reverse_eid_map):\n if isinstance(eids, Mapping):\n eids = {g.to_canonical_etype(k): v for k, v in eids.items()}\n exclude_eids = {\n k: F.cat([v, F.gather_row(reverse_eid_map[k], v)], 0)\n for k, v in eids.items()}\n else:\n exclude_eids = F.cat([eids, F.gather_row(reverse_eid_map, eids)], 0)\n return exclude_eids\n\ndef _find_exclude_eids_with_reverse_types(g, eids, reverse_etype_map):\n exclude_eids = {g.to_canonical_etype(k): v for k, v in eids.items()}\n reverse_etype_map = {\n g.to_canonical_etype(k): g.to_canonical_etype(v)\n for k, v in reverse_etype_map.items()}\n exclude_eids.update({reverse_etype_map[k]: v for k, v in exclude_eids.items()})\n return exclude_eids\n\ndef _find_exclude_eids(g, exclude_mode, eids, **kwargs):\n \"\"\"Find all edge IDs to exclude according to :attr:`exclude_mode`.\n\n Parameters\n ----------\n g : DGLGraph\n The graph.\n exclude_mode : str, optional\n Can be either of the following,\n\n None (default)\n Does not exclude any edge.\n\n 'reverse_id'\n Exclude all edges specified in ``eids``, as well as their reverse edges\n of the same edge type.\n\n The mapping from each edge ID to its reverse edge ID is specified in\n the keyword argument ``reverse_eid_map``.\n\n This mode assumes that the reverse of an edge with ID ``e`` and type\n ``etype`` will have ID ``reverse_eid_map[e]`` and type ``etype``.\n\n 'reverse_types'\n Exclude all edges specified in ``eids``, as well as their reverse\n edges of the corresponding edge types.\n\n The mapping from each edge type to its reverse edge type is specified\n in the keyword argument ``reverse_etype_map``.\n\n This mode assumes that the reverse of an edge with ID ``e`` and type ``etype``\n will have ID ``e`` and type ``reverse_etype_map[etype]``.\n eids : Tensor or dict[etype, Tensor]\n The edge IDs.\n reverse_eid_map : Tensor or dict[etype, Tensor]\n The mapping from edge ID to its reverse edge ID.\n reverse_etype_map : dict[etype, etype]\n The mapping from edge etype to its reverse edge type.\n \"\"\"\n if exclude_mode is None:\n return None\n elif exclude_mode == 'reverse_id':\n return _find_exclude_eids_with_reverse_id(g, eids, kwargs['reverse_eid_map'])\n elif exclude_mode == 'reverse_types':\n return _find_exclude_eids_with_reverse_types(g, eids, kwargs['reverse_etype_map'])\n else:\n raise ValueError('unsupported mode {}'.format(exclude_mode))\n\n\nclass BlockSampler(object):\n \"\"\"Abstract class specifying the neighborhood sampling strategy for DGL data loaders.\n\n The main method for BlockSampler is :meth:`sample_blocks`,\n which generates a list of message flow graphs (MFGs) for a multi-layer GNN given a set of\n seed nodes to have their outputs computed.\n\n The default implementation of :meth:`sample_blocks` is\n to repeat :attr:`num_layers` times the following procedure from the last layer to the first\n layer:\n\n * Obtain a frontier. The frontier is defined as a graph with the same nodes as the\n original graph but only the edges involved in message passing on the current layer.\n Customizable via :meth:`sample_frontier`.\n\n * Optionally, if the task is link prediction or edge classfication, remove edges\n connecting training node pairs. If the graph is undirected, also remove the\n reverse edges. This is controlled by the argument :attr:`exclude_eids` in\n :meth:`sample_blocks` method.\n\n * Convert the frontier into a MFG.\n\n * Optionally assign the IDs of the edges in the original graph selected in the first step\n to the MFG, controlled by the argument ``return_eids`` in\n :meth:`sample_blocks` method.\n\n * Prepend the MFG to the MFG list to be returned.\n\n All subclasses should override :meth:`sample_frontier`\n method while specifying the number of layers to sample in :attr:`num_layers` argument.\n\n Parameters\n ----------\n num_layers : int\n The number of layers to sample.\n return_eids : bool, default False\n Whether to return the edge IDs involved in message passing in the MFG.\n If True, the edge IDs will be stored as an edge feature named ``dgl.EID``.\n\n Notes\n -----\n For the concept of frontiers and MFGs, please refer to\n :ref:`User Guide Section 6 <guide-minibatch>` and\n :doc:`Minibatch Training Tutorials <tutorials/large/L0_neighbor_sampling_overview>`.\n \"\"\"\n def __init__(self, num_layers, return_eids):\n self.num_layers = num_layers\n self.return_eids = return_eids\n\n def sample_frontier(self, block_id, g, seed_nodes):\n \"\"\"Generate the frontier given the destination nodes.\n\n The subclasses should override this function.\n\n Parameters\n ----------\n block_id : int\n Represents which GNN layer the frontier is generated for.\n g : DGLGraph\n The original graph.\n seed_nodes : Tensor or dict[ntype, Tensor]\n The destination nodes by node type.\n\n If the graph only has one node type, one can just specify a single tensor\n of node IDs.\n\n Returns\n -------\n DGLGraph\n The frontier generated for the current layer.\n\n Notes\n -----\n For the concept of frontiers and MFGs, please refer to\n :ref:`User Guide Section 6 <guide-minibatch>` and\n :doc:`Minibatch Training Tutorials <tutorials/large/L0_neighbor_sampling_overview>`.\n \"\"\"\n raise NotImplementedError\n\n def sample_blocks(self, g, seed_nodes, exclude_eids=None):\n \"\"\"Generate the a list of MFGs given the destination nodes.\n\n Parameters\n ----------\n g : DGLGraph\n The original graph.\n seed_nodes : Tensor or dict[ntype, Tensor]\n The destination nodes by node type.\n\n If the graph only has one node type, one can just specify a single tensor\n of node IDs.\n exclude_eids : Tensor or dict[etype, Tensor]\n The edges to exclude from computation dependency.\n\n Returns\n -------\n list[DGLGraph]\n The MFGs generated for computing the multi-layer GNN output.\n\n Notes\n -----\n For the concept of frontiers and MFGs, please refer to\n :ref:`User Guide Section 6 <guide-minibatch>` and\n :doc:`Minibatch Training Tutorials <tutorials/large/L0_neighbor_sampling_overview>`.\n \"\"\"\n blocks = []\n exclude_eids = (\n _tensor_or_dict_to_numpy(exclude_eids) if exclude_eids is not None else None)\n for block_id in reversed(range(self.num_layers)):\n frontier = self.sample_frontier(block_id, g, seed_nodes)\n\n # Removing edges from the frontier for link prediction training falls\n # into the category of frontier postprocessing\n if exclude_eids is not None:\n parent_eids = frontier.edata[EID]\n parent_eids_np = _tensor_or_dict_to_numpy(parent_eids)\n located_eids = _locate_eids_to_exclude(parent_eids_np, exclude_eids)\n if not isinstance(located_eids, Mapping):\n # (BarclayII) If frontier already has a EID field and located_eids is empty,\n # the returned graph will keep EID intact. Otherwise, EID will change\n # to the mapping from the new graph to the old frontier.\n # So we need to test if located_eids is empty, and do the remapping ourselves.\n if len(located_eids) > 0:\n frontier = transform.remove_edges(\n frontier, located_eids, store_ids=True)\n frontier.edata[EID] = F.gather_row(parent_eids, frontier.edata[EID])\n else:\n # (BarclayII) remove_edges only accepts removing one type of edges,\n # so I need to keep track of the edge IDs left one by one.\n new_eids = parent_eids.copy()\n for k, v in located_eids.items():\n if len(v) > 0:\n frontier = transform.remove_edges(\n frontier, v, etype=k, store_ids=True)\n new_eids[k] = F.gather_row(parent_eids[k], frontier.edges[k].data[EID])\n frontier.edata[EID] = new_eids\n\n block = transform.to_block(frontier, seed_nodes)\n\n if self.return_eids:\n assign_block_eids(block, frontier)\n\n seed_nodes = {ntype: block.srcnodes[ntype].data[NID] for ntype in block.srctypes}\n\n blocks.insert(0, block)\n return blocks\n\nclass Collator(ABC):\n \"\"\"Abstract DGL collator for training GNNs on downstream tasks stochastically.\n\n Provides a :attr:`dataset` object containing the collection of all nodes or edges,\n as well as a :attr:`collate` method that combines a set of items from\n :attr:`dataset` and obtains the message flow graphs (MFGs).\n\n Notes\n -----\n For the concept of MFGs, please refer to\n :ref:`User Guide Section 6 <guide-minibatch>` and\n :doc:`Minibatch Training Tutorials <tutorials/large/L0_neighbor_sampling_overview>`.\n \"\"\"\n @abstractproperty\n def dataset(self):\n \"\"\"Returns the dataset object of the collator.\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def collate(self, items):\n \"\"\"Combines the items from the dataset object and obtains the list of MFGs.\n\n Parameters\n ----------\n items : list[str, int]\n The list of node or edge IDs or type-ID pairs.\n\n Notes\n -----\n For the concept of MFGs, please refer to\n :ref:`User Guide Section 6 <guide-minibatch>` and\n :doc:`Minibatch Training Tutorials <tutorials/large/L0_neighbor_sampling_overview>`.\n \"\"\"\n raise NotImplementedError\n\n# TODO(BarclayII): DistGraph.idtype and DistGraph.device are in the code, however\n# the underlying DGLGraph object could be None. I was unable to figure out how\n# to properly implement those two properties so I'm working around that. If the\n# graph is a DistGraph, I assume that the dtype and device of the data should\n# be the same as the graph already.\n#\n# After idtype and device get properly implemented, we should remove these two\n# _prepare_* functions.\n\ndef _prepare_tensor_dict(g, data, name, is_distributed):\n if is_distributed:\n x = F.tensor(next(iter(data.values())))\n return {k: F.copy_to(F.astype(v, F.dtype(x)), F.context(x)) for k, v in data.items()}\n else:\n return utils.prepare_tensor_dict(g, data, name)\n\ndef _prepare_tensor(g, data, name, is_distributed):\n return F.tensor(data) if is_distributed else utils.prepare_tensor(g, data, name)\n\nclass NodeCollator(Collator):\n \"\"\"DGL collator to combine nodes and their computation dependencies within a minibatch for\n training node classification or regression on a single graph with neighborhood sampling.\n\n Parameters\n ----------\n g : DGLGraph\n The graph.\n nids : Tensor or dict[ntype, Tensor]\n The node set to compute outputs.\n block_sampler : dgl.dataloading.BlockSampler\n The neighborhood sampler.\n\n Examples\n --------\n To train a 3-layer GNN for node classification on a set of nodes ``train_nid`` on\n a homogeneous graph where each node takes messages from all neighbors (assume\n the backend is PyTorch):\n\n >>> sampler = dgl.dataloading.MultiLayerNeighborSampler([15, 10, 5])\n >>> collator = dgl.dataloading.NodeCollator(g, train_nid, sampler)\n >>> dataloader = torch.utils.data.DataLoader(\n ... collator.dataset, collate_fn=collator.collate,\n ... batch_size=1024, shuffle=True, drop_last=False, num_workers=4)\n >>> for input_nodes, output_nodes, blocks in dataloader:\n ... train_on(input_nodes, output_nodes, blocks)\n\n Notes\n -----\n For the concept of MFGs, please refer to\n :ref:`User Guide Section 6 <guide-minibatch>` and\n :doc:`Minibatch Training Tutorials <tutorials/large/L0_neighbor_sampling_overview>`.\n \"\"\"\n def __init__(self, g, nids, block_sampler):\n self.g = g\n self._is_distributed = isinstance(g, DistGraph)\n if not isinstance(nids, Mapping):\n assert len(g.ntypes) == 1, \\\n \"nids should be a dict of node type and ids for graph with multiple node types\"\n self.block_sampler = block_sampler\n\n if isinstance(nids, Mapping):\n self.nids = _prepare_tensor_dict(g, nids, 'nids', self._is_distributed)\n self._dataset = utils.FlattenedDict(self.nids)\n else:\n self.nids = _prepare_tensor(g, nids, 'nids', self._is_distributed)\n self._dataset = self.nids\n\n @property\n def dataset(self):\n return self._dataset\n\n def collate(self, items):\n \"\"\"Find the list of MFGs necessary for computing the representation of given\n nodes for a node classification/regression task.\n\n Parameters\n ----------\n items : list[int] or list[tuple[str, int]]\n Either a list of node IDs (for homogeneous graphs), or a list of node type-ID\n pairs (for heterogeneous graphs).\n\n Returns\n -------\n input_nodes : Tensor or dict[ntype, Tensor]\n The input nodes necessary for computation in this minibatch.\n\n If the original graph has multiple node types, return a dictionary of\n node type names and node ID tensors. Otherwise, return a single tensor.\n output_nodes : Tensor or dict[ntype, Tensor]\n The nodes whose representations are to be computed in this minibatch.\n\n If the original graph has multiple node types, return a dictionary of\n node type names and node ID tensors. Otherwise, return a single tensor.\n MFGs : list[DGLGraph]\n The list of MFGs necessary for computing the representation.\n \"\"\"\n if isinstance(items[0], tuple):\n # returns a list of pairs: group them by node types into a dict\n items = utils.group_as_dict(items)\n items = _prepare_tensor_dict(self.g, items, 'items', self._is_distributed)\n else:\n items = _prepare_tensor(self.g, items, 'items', self._is_distributed)\n\n blocks = self.block_sampler.sample_blocks(self.g, items)\n output_nodes = blocks[-1].dstdata[NID]\n input_nodes = blocks[0].srcdata[NID]\n\n return input_nodes, output_nodes, blocks\n\nclass EdgeCollator(Collator):\n \"\"\"DGL collator to combine edges and their computation dependencies within a minibatch for\n training edge classification, edge regression, or link prediction on a single graph\n with neighborhood sampling.\n\n Given a set of edges, the collate function will yield\n\n * A tensor of input nodes necessary for computing the representation on edges, or\n a dictionary of node type names and such tensors.\n\n * A subgraph that contains only the edges in the minibatch and their incident nodes.\n Note that the graph has an identical metagraph with the original graph.\n\n * If a negative sampler is given, another graph that contains the \"negative edges\",\n connecting the source and destination nodes yielded from the given negative sampler.\n\n * A list of MFGs necessary for computing the representation of the incident nodes\n of the edges in the minibatch.\n\n Parameters\n ----------\n g : DGLGraph\n The graph from which the edges are iterated in minibatches and the subgraphs\n are generated.\n eids : Tensor or dict[etype, Tensor]\n The edge set in graph :attr:`g` to compute outputs.\n block_sampler : dgl.dataloading.BlockSampler\n The neighborhood sampler.\n g_sampling : DGLGraph, optional\n The graph where neighborhood sampling and message passing is performed.\n\n Note that this is not necessarily the same as :attr:`g`.\n\n If None, assume to be the same as :attr:`g`.\n exclude : str, optional\n Whether and how to exclude dependencies related to the sampled edges in the\n minibatch. Possible values are\n\n * None, which excludes nothing.\n\n * ``'reverse_id'``, which excludes the reverse edges of the sampled edges. The said\n reverse edges have the same edge type as the sampled edges. Only works\n on edge types whose source node type is the same as its destination node type.\n\n * ``'reverse_types'``, which excludes the reverse edges of the sampled edges. The\n said reverse edges have different edge types from the sampled edges.\n\n If ``g_sampling`` is given, ``exclude`` is ignored and will be always ``None``.\n reverse_eids : Tensor or dict[etype, Tensor], optional\n The mapping from original edge ID to its reverse edge ID.\n\n Required and only used when ``exclude`` is set to ``reverse_id``.\n\n For heterogeneous graph this will be a dict of edge type and edge IDs. Note that\n only the edge types whose source node type is the same as destination node type\n are needed.\n reverse_etypes : dict[etype, etype], optional\n The mapping from the edge type to its reverse edge type.\n\n Required and only used when ``exclude`` is set to ``reverse_types``.\n negative_sampler : callable, optional\n The negative sampler. Can be omitted if no negative sampling is needed.\n\n The negative sampler must be a callable that takes in the following arguments:\n\n * The original (heterogeneous) graph.\n\n * The ID array of sampled edges in the minibatch, or the dictionary of edge\n types and ID array of sampled edges in the minibatch if the graph is\n heterogeneous.\n\n It should return\n\n * A pair of source and destination node ID arrays as negative samples,\n or a dictionary of edge types and such pairs if the graph is heterogenenous.\n\n A set of builtin negative samplers are provided in\n :ref:`the negative sampling module <api-dataloading-negative-sampling>`.\n\n Examples\n --------\n The following example shows how to train a 3-layer GNN for edge classification on a\n set of edges ``train_eid`` on a homogeneous undirected graph. Each node takes\n messages from all neighbors.\n\n Say that you have an array of source node IDs ``src`` and another array of destination\n node IDs ``dst``. One can make it bidirectional by adding another set of edges\n that connects from ``dst`` to ``src``:\n\n >>> g = dgl.graph((torch.cat([src, dst]), torch.cat([dst, src])))\n\n One can then know that the ID difference of an edge and its reverse edge is ``|E|``,\n where ``|E|`` is the length of your source/destination array. The reverse edge\n mapping can be obtained by\n\n >>> E = len(src)\n >>> reverse_eids = torch.cat([torch.arange(E, 2 * E), torch.arange(0, E)])\n\n Note that the sampled edges as well as their reverse edges are removed from\n computation dependencies of the incident nodes. This is a common trick to avoid\n information leakage.\n\n >>> sampler = dgl.dataloading.MultiLayerNeighborSampler([15, 10, 5])\n >>> collator = dgl.dataloading.EdgeCollator(\n ... g, train_eid, sampler, exclude='reverse_id',\n ... reverse_eids=reverse_eids)\n >>> dataloader = torch.utils.data.DataLoader(\n ... collator.dataset, collate_fn=collator.collate,\n ... batch_size=1024, shuffle=True, drop_last=False, num_workers=4)\n >>> for input_nodes, pair_graph, blocks in dataloader:\n ... train_on(input_nodes, pair_graph, blocks)\n\n To train a 3-layer GNN for link prediction on a set of edges ``train_eid`` on a\n homogeneous graph where each node takes messages from all neighbors (assume the\n backend is PyTorch), with 5 uniformly chosen negative samples per edge:\n\n >>> sampler = dgl.dataloading.MultiLayerNeighborSampler([15, 10, 5])\n >>> neg_sampler = dgl.dataloading.negative_sampler.Uniform(5)\n >>> collator = dgl.dataloading.EdgeCollator(\n ... g, train_eid, sampler, exclude='reverse_id',\n ... reverse_eids=reverse_eids, negative_sampler=neg_sampler,\n >>> dataloader = torch.utils.data.DataLoader(\n ... collator.dataset, collate_fn=collator.collate,\n ... batch_size=1024, shuffle=True, drop_last=False, num_workers=4)\n >>> for input_nodes, pos_pair_graph, neg_pair_graph, blocks in dataloader:\n ... train_on(input_nodse, pair_graph, neg_pair_graph, blocks)\n\n For heterogeneous graphs, the reverse of an edge may have a different edge type\n from the original edge. For instance, consider that you have an array of\n user-item clicks, representated by a user array ``user`` and an item array ``item``.\n You may want to build a heterogeneous graph with a user-click-item relation and an\n item-clicked-by-user relation.\n\n >>> g = dgl.heterograph({\n ... ('user', 'click', 'item'): (user, item),\n ... ('item', 'clicked-by', 'user'): (item, user)})\n\n To train a 3-layer GNN for edge classification on a set of edges ``train_eid`` with\n type ``click``, you can write\n\n >>> sampler = dgl.dataloading.MultiLayerNeighborSampler([15, 10, 5])\n >>> collator = dgl.dataloading.EdgeCollator(\n ... g, {'click': train_eid}, sampler, exclude='reverse_types',\n ... reverse_etypes={'click': 'clicked-by', 'clicked-by': 'click'})\n >>> dataloader = torch.utils.data.DataLoader(\n ... collator.dataset, collate_fn=collator.collate,\n ... batch_size=1024, shuffle=True, drop_last=False, num_workers=4)\n >>> for input_nodes, pair_graph, blocks in dataloader:\n ... train_on(input_nodes, pair_graph, blocks)\n\n To train a 3-layer GNN for link prediction on a set of edges ``train_eid`` with type\n ``click``, you can write\n\n >>> sampler = dgl.dataloading.MultiLayerNeighborSampler([15, 10, 5])\n >>> neg_sampler = dgl.dataloading.negative_sampler.Uniform(5)\n >>> collator = dgl.dataloading.EdgeCollator(\n ... g, train_eid, sampler, exclude='reverse_types',\n ... reverse_etypes={'click': 'clicked-by', 'clicked-by': 'click'},\n ... negative_sampler=neg_sampler)\n >>> dataloader = torch.utils.data.DataLoader(\n ... collator.dataset, collate_fn=collator.collate,\n ... batch_size=1024, shuffle=True, drop_last=False, num_workers=4)\n >>> for input_nodes, pos_pair_graph, neg_pair_graph, blocks in dataloader:\n ... train_on(input_nodes, pair_graph, neg_pair_graph, blocks)\n\n Notes\n -----\n For the concept of MFGs, please refer to\n :ref:`User Guide Section 6 <guide-minibatch>` and\n :doc:`Minibatch Training Tutorials <tutorials/large/L0_neighbor_sampling_overview>`.\n \"\"\"\n def __init__(self, g, eids, block_sampler, g_sampling=None, exclude=None,\n reverse_eids=None, reverse_etypes=None, negative_sampler=None):\n self.g = g\n self._is_distributed = isinstance(g, DistGraph)\n if not isinstance(eids, Mapping):\n assert len(g.etypes) == 1, \\\n \"eids should be a dict of etype and ids for graph with multiple etypes\"\n self.block_sampler = block_sampler\n\n # One may wish to iterate over the edges in one graph while perform sampling in\n # another graph. This may be the case for iterating over validation and test\n # edge set while perform neighborhood sampling on the graph formed by only\n # the training edge set.\n # See GCMC for an example usage.\n if g_sampling is not None:\n self.g_sampling = g_sampling\n self.exclude = None\n else:\n self.g_sampling = self.g\n self.exclude = exclude\n\n self.reverse_eids = reverse_eids\n self.reverse_etypes = reverse_etypes\n self.negative_sampler = negative_sampler\n\n if isinstance(eids, Mapping):\n self.eids = _prepare_tensor_dict(g, eids, 'eids', self._is_distributed)\n self._dataset = utils.FlattenedDict(self.eids)\n else:\n self.eids = _prepare_tensor(g, eids, 'eids', self._is_distributed)\n self._dataset = self.eids\n\n @property\n def dataset(self):\n return self._dataset\n\n def _collate(self, items):\n if isinstance(items[0], tuple):\n # returns a list of pairs: group them by node types into a dict\n items = utils.group_as_dict(items)\n items = _prepare_tensor_dict(self.g_sampling, items, 'items', self._is_distributed)\n else:\n items = _prepare_tensor(self.g_sampling, items, 'items', self._is_distributed)\n\n pair_graph = self.g.edge_subgraph(items)\n seed_nodes = pair_graph.ndata[NID]\n\n exclude_eids = _find_exclude_eids(\n self.g,\n self.exclude,\n items,\n reverse_eid_map=self.reverse_eids,\n reverse_etype_map=self.reverse_etypes)\n\n blocks = self.block_sampler.sample_blocks(\n self.g_sampling, seed_nodes, exclude_eids=exclude_eids)\n input_nodes = blocks[0].srcdata[NID]\n\n return input_nodes, pair_graph, blocks\n\n def _collate_with_negative_sampling(self, items):\n if isinstance(items[0], tuple):\n # returns a list of pairs: group them by node types into a dict\n items = utils.group_as_dict(items)\n items = _prepare_tensor_dict(self.g_sampling, items, 'items', self._is_distributed)\n else:\n items = _prepare_tensor(self.g_sampling, items, 'items', self._is_distributed)\n\n pair_graph = self.g.edge_subgraph(items, preserve_nodes=True)\n induced_edges = pair_graph.edata[EID]\n\n neg_srcdst = self.negative_sampler(self.g, items)\n if not isinstance(neg_srcdst, Mapping):\n assert len(self.g.etypes) == 1, \\\n 'graph has multiple or no edge types; '\\\n 'please return a dict in negative sampler.'\n neg_srcdst = {self.g.canonical_etypes[0]: neg_srcdst}\n # Get dtype from a tuple of tensors\n dtype = F.dtype(list(neg_srcdst.values())[0][0])\n neg_edges = {\n etype: neg_srcdst.get(etype, (F.tensor([], dtype), F.tensor([], dtype)))\n for etype in self.g.canonical_etypes}\n neg_pair_graph = heterograph(\n neg_edges, {ntype: self.g.number_of_nodes(ntype) for ntype in self.g.ntypes})\n\n pair_graph, neg_pair_graph = transform.compact_graphs([pair_graph, neg_pair_graph])\n pair_graph.edata[EID] = induced_edges\n\n seed_nodes = pair_graph.ndata[NID]\n\n exclude_eids = _find_exclude_eids(\n self.g,\n self.exclude,\n items,\n reverse_eid_map=self.reverse_eids,\n reverse_etype_map=self.reverse_etypes)\n\n blocks = self.block_sampler.sample_blocks(\n self.g_sampling, seed_nodes, exclude_eids=exclude_eids)\n input_nodes = blocks[0].srcdata[NID]\n\n return input_nodes, pair_graph, neg_pair_graph, blocks\n\n def collate(self, items):\n \"\"\"Combines the sampled edges into a minibatch for edge classification, edge\n regression, and link prediction tasks.\n\n Parameters\n ----------\n items : list[int] or list[tuple[str, int]]\n Either a list of edge IDs (for homogeneous graphs), or a list of edge type-ID\n pairs (for heterogeneous graphs).\n\n Returns\n -------\n Either ``(input_nodes, pair_graph, blocks)``, or\n ``(input_nodes, pair_graph, negative_pair_graph, blocks)`` if negative sampling is\n enabled.\n\n input_nodes : Tensor or dict[ntype, Tensor]\n The input nodes necessary for computation in this minibatch.\n\n If the original graph has multiple node types, return a dictionary of\n node type names and node ID tensors. Otherwise, return a single tensor.\n pair_graph : DGLGraph\n The graph that contains only the edges in the minibatch as well as their incident\n nodes.\n\n Note that the metagraph of this graph will be identical to that of the original\n graph.\n negative_pair_graph : DGLGraph\n The graph that contains only the edges connecting the source and destination nodes\n yielded from the given negative sampler, if negative sampling is enabled.\n\n Note that the metagraph of this graph will be identical to that of the original\n graph.\n blocks : list[DGLGraph]\n The list of MFGs necessary for computing the representation of the edges.\n \"\"\"\n if self.negative_sampler is None:\n return self._collate(items)\n else:\n return self._collate_with_negative_sampling(items)\n\nclass GraphCollator(object):\n \"\"\"Given a set of graphs as well as their graph-level data, the collate function will batch the\n graphs into a batched graph, and stack the tensors into a single bigger tensor. If the\n example is a container (such as sequences or mapping), the collate function preserves\n the structure and collates each of the elements recursively.\n\n If the set of graphs has no graph-level data, the collate function will yield a batched graph.\n\n Examples\n --------\n To train a GNN for graph classification on a set of graphs in ``dataset`` (assume\n the backend is PyTorch):\n\n >>> dataloader = dgl.dataloading.GraphDataLoader(\n ... dataset, batch_size=1024, shuffle=True, drop_last=False, num_workers=4)\n >>> for batched_graph, labels in dataloader:\n ... train_on(batched_graph, labels)\n \"\"\"\n def __init__(self):\n self.graph_collate_err_msg_format = (\n \"graph_collate: batch must contain DGLGraph, tensors, numpy arrays, \"\n \"numbers, dicts or lists; found {}\")\n self.np_str_obj_array_pattern = re.compile(r'[SaUO]')\n\n #This implementation is based on torch.utils.data._utils.collate.default_collate\n def collate(self, items):\n \"\"\"This function is similar to ``torch.utils.data._utils.collate.default_collate``.\n It combines the sampled graphs and corresponding graph-level data\n into a batched graph and tensors.\n\n Parameters\n ----------\n items : list of data points or tuples\n Elements in the list are expected to have the same length.\n Each sub-element will be batched as a batched graph, or a\n batched tensor correspondingly.\n\n Returns\n -------\n A tuple of the batching results.\n \"\"\"\n elem = items[0]\n elem_type = type(elem)\n if isinstance(elem, DGLGraph):\n batched_graphs = batch(items)\n return batched_graphs\n elif F.is_tensor(elem):\n return F.stack(items, 0)\n elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \\\n and elem_type.__name__ != 'string_':\n if elem_type.__name__ == 'ndarray' or elem_type.__name__ == 'memmap':\n # array of string classes and object\n if self.np_str_obj_array_pattern.search(elem.dtype.str) is not None:\n raise TypeError(self.graph_collate_err_msg_format.format(elem.dtype))\n\n return self.collate([F.tensor(b) for b in items])\n elif elem.shape == (): # scalars\n return F.tensor(items)\n elif isinstance(elem, float):\n return F.tensor(items, dtype=F.float64)\n elif isinstance(elem, int):\n return F.tensor(items)\n elif isinstance(elem, (str, bytes)):\n return items\n elif isinstance(elem, Mapping):\n return {key: self.collate([d[key] for d in items]) for key in elem}\n elif isinstance(elem, tuple) and hasattr(elem, '_fields'): # namedtuple\n return elem_type(*(self.collate(samples) for samples in zip(*items)))\n elif isinstance(elem, Sequence):\n # check to make sure that the elements in batch have consistent size\n item_iter = iter(items)\n elem_size = len(next(item_iter))\n if not all(len(elem) == elem_size for elem in item_iter):\n raise RuntimeError('each element in list of batch should be of equal size')\n transposed = zip(*items)\n return [self.collate(samples) for samples in transposed]\n\n raise TypeError(self.graph_collate_err_msg_format.format(elem_type))\n"
] | [
[
"numpy.stack",
"torch.unique",
"torch.nonzero",
"torch.arange",
"numpy.savetxt",
"torch.stack"
],
[
"numpy.isin"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Moonquakes/Tensorflow-lite-Demo | [
"20f00de6797c89bc1077ac165b11a3cc026d63cb",
"20f00de6797c89bc1077ac165b11a3cc026d63cb"
] | [
"tensorflow/python/data/experimental/kernel_tests/serialization/cache_dataset_serialization_test.py",
"tensorflow/python/data/experimental/ops/distribute_options.py"
] | [
"# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for checkpointing the CacheDataset.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nfrom absl.testing import parameterized\n\nfrom tensorflow.python.data.kernel_tests import checkpoint_test_base\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import combinations\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.platform import test\n\n\nclass CacheDatasetCheckpointTest(checkpoint_test_base.CheckpointTestBase,\n parameterized.TestCase):\n\n def setUp(self):\n self.range_size = 10\n self.num_repeats = 3\n self.num_outputs = self.range_size * self.num_repeats\n self.cache_file_prefix = 'test'\n\n def make_dataset_fn(self, is_memory):\n if is_memory:\n filename = ''\n else:\n filename = os.path.join(self.get_temp_dir(), self.cache_file_prefix)\n\n def ds_fn():\n return dataset_ops.Dataset.range(self.range_size).cache(filename).repeat(\n self.num_repeats)\n\n return ds_fn\n\n def expected_outputs(self):\n return list(range(self.range_size)) * self.num_repeats\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(is_memory=[True, False])))\n def testCheckpointBeforeOneEpoch(self, is_memory):\n ds_fn = self.make_dataset_fn(is_memory)\n\n # Generate 5 entries from iterator and save checkpoint.\n outputs = self.gen_outputs(ds_fn, [], 5, verify_exhausted=False)\n self.assertSequenceEqual(outputs, range(5))\n\n # Restore from checkpoint and produce the rest of the elements from the\n # iterator.\n outputs.extend(\n self.gen_outputs(\n ds_fn, [],\n self.num_outputs - 5,\n ckpt_saved=True,\n verify_exhausted=False))\n self.assertSequenceEqual(outputs, self.expected_outputs())\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(is_memory=[True, False])))\n def testCheckpointBeforeOneEpochThenRunFewSteps(self, is_memory):\n ds_fn = self.make_dataset_fn(is_memory)\n\n # Generate 8 entries from iterator but save checkpoint after producing 5.\n outputs = self.gen_outputs(\n ds_fn, [5], 8, verify_exhausted=False, save_checkpoint_at_end=False)\n self.assertSequenceEqual(outputs, range(8))\n\n outputs = outputs[:5]\n outputs.extend(\n self.gen_outputs(\n ds_fn, [],\n self.num_outputs - 5,\n ckpt_saved=True,\n verify_exhausted=False))\n self.assertSequenceEqual(outputs, self.expected_outputs())\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(is_memory=[True, False])))\n def testCheckpointAfterOneEpoch(self, is_memory):\n ds_fn = self.make_dataset_fn(is_memory)\n\n # Generate 15 entries from iterator and save checkpoint.\n outputs = self.gen_outputs(ds_fn, [], 15, verify_exhausted=False)\n self.assertSequenceEqual(outputs, list(range(10)) + list(range(5)))\n\n # Restore from checkpoint and produce the rest of the elements from the\n # iterator.\n outputs.extend(\n self.gen_outputs(\n ds_fn, [],\n self.num_outputs - 15,\n ckpt_saved=True,\n verify_exhausted=False))\n self.assertSequenceEqual(outputs, self.expected_outputs())\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(is_memory=[True, False])))\n def testCheckpointAfterOneEpochThenRunFewSteps(self, is_memory):\n ds_fn = self.make_dataset_fn(is_memory)\n\n # Generate 18 entries from iterator but save checkpoint after producing 15.\n outputs = self.gen_outputs(\n ds_fn, [15], 18, verify_exhausted=False, save_checkpoint_at_end=False)\n self.assertSequenceEqual(outputs, list(range(10)) + list(range(8)))\n\n outputs = list(range(10)) + list(range(5)) + self.gen_outputs(\n ds_fn, [],\n self.num_outputs - 15,\n ckpt_saved=True,\n verify_exhausted=False)\n self.assertSequenceEqual(outputs, list(range(10)) * 3)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(is_memory=[True, False])))\n def testCheckpointBeforeOneEpochButRunCompleteEpoch(self, is_memory):\n ds_fn = self.make_dataset_fn(is_memory)\n\n # Generate 13 entries from iterator but save checkpoint after producing 5.\n outputs = self.gen_outputs(\n ds_fn, [5], 13, verify_exhausted=False, save_checkpoint_at_end=False)\n self.assertSequenceEqual(outputs, list(range(10)) + list(range(3)))\n\n # Since we ran for more than one epoch, the cache was completely written.\n # The ckpt was saved when the iterator was in cache-write mode. Test that\n # the iterator falls back to read mode after restoring if the cache has\n # been completely written.\n\n outputs = list(range(5)) + self.gen_outputs(\n ds_fn, [],\n self.num_outputs - 5,\n ckpt_saved=True,\n verify_exhausted=False)\n self.assertSequenceEqual(outputs, list(range(10)) * 3)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(is_memory=[True, False])))\n def testCheckpointUnusedWriterIterator(self, is_memory):\n ds_fn = self.make_dataset_fn(is_memory)\n\n # Checkpoint before get_next is called even once.\n outputs = self.gen_outputs(ds_fn, [], 0, verify_exhausted=False)\n self.assertSequenceEqual(outputs, [])\n\n outputs = self.gen_outputs(\n ds_fn, [], self.num_outputs, ckpt_saved=True, verify_exhausted=False)\n self.assertSequenceEqual(outputs, list(range(10)) * 3)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(is_memory=[True, False])))\n def testCheckpointUnusedMidwayWriterIterator(self, is_memory):\n ds_fn = self.make_dataset_fn(is_memory)\n\n # Produce 5 elements and checkpoint.\n outputs = self.gen_outputs(ds_fn, [], 5, verify_exhausted=False)\n self.assertSequenceEqual(outputs, range(5))\n\n # Restore from checkpoint, then produce no elements and checkpoint.\n outputs.extend(\n self.gen_outputs(ds_fn, [], 0, ckpt_saved=True, verify_exhausted=False))\n self.assertSequenceEqual(outputs, range(5))\n\n # Restore from checkpoint and produce rest of the elements.\n outputs.extend(\n self.gen_outputs(\n ds_fn, [],\n self.num_outputs - 5,\n ckpt_saved=True,\n verify_exhausted=False))\n self.assertSequenceEqual(outputs, list(range(10)) * 3)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(is_memory=[True, False])))\n def testUnusedCheckpointError(self, is_memory):\n ds_fn = self.make_dataset_fn(is_memory)\n\n # Produce 5 elements and save ckpt.\n outputs = self.gen_outputs(ds_fn, [], 5, verify_exhausted=False)\n self.assertSequenceEqual(outputs, range(5))\n\n if is_memory:\n outputs = self.gen_outputs(\n ds_fn, [], self.num_outputs, verify_exhausted=False)\n self.assertSequenceEqual(outputs, self.expected_outputs())\n else:\n # Since the complete cache has not been written, a new iterator which does\n # not restore the checkpoint will throw an error since there is a partial\n # cache shard.\n with self.assertRaises(errors.AlreadyExistsError):\n outputs = self.gen_outputs(\n ds_fn, [], self.num_outputs, verify_exhausted=False)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(is_memory=[True, False])))\n def testIgnoreCheckpointIfCacheWritten(self, is_memory):\n ds_fn = self.make_dataset_fn(is_memory)\n\n # Produce 15 elements and save ckpt. This will write the complete cache.\n outputs = self.gen_outputs(ds_fn, [], 15, verify_exhausted=False)\n self.assertSequenceEqual(outputs, list(range(10)) + list(range(5)))\n\n # Build the iterator again but do not restore from ckpt. Since the cache\n # has already been written we should be able to use it.\n outputs = self.gen_outputs(\n ds_fn, [], self.num_outputs, verify_exhausted=False)\n self.assertSequenceEqual(outputs, list(range(10)) * 3)\n\n\nif __name__ == '__main__':\n test.main()\n",
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Experimental API for controlling distribution in `tf.data` pipelines.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport enum\n\nfrom tensorflow.core.framework import dataset_options_pb2\nfrom tensorflow.python.data.util import options\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n@tf_export(\"data.experimental.AutoShardPolicy\")\nclass AutoShardPolicy(enum.IntEnum):\n \"\"\"Represents the type of auto-sharding to use.\n\n OFF: No sharding will be performed.\n\n AUTO: Attempts FILE-based sharding, falling back to DATA-based sharding.\n\n FILE: Shards by input files (i.e. each worker will get a set of files to\n process). When this option is selected, make sure that there is at least as\n many files as workers. If there are fewer input files than workers, a runtime\n error will be raised.\n\n DATA: Shards by elements produced by the dataset. Each worker will process the\n whole dataset and discard the portion that is not for itself. Note that for\n this mode to correctly partitions the dataset elements, the dataset needs to\n produce elements in a deterministic order.\n\n HINT: Looks for the presence of `shard(SHARD_HINT, ...)` which is treated as a\n placeholder to replace with `shard(num_workers, worker_index)`.\n \"\"\"\n OFF = -1\n AUTO = 0\n FILE = 1\n DATA = 2\n HINT = 3\n\n @classmethod\n def _to_proto(cls, obj):\n \"\"\"Convert enum to proto.\"\"\"\n if obj == cls.OFF:\n return dataset_options_pb2.AutoShardPolicy.OFF\n if obj == cls.FILE:\n return dataset_options_pb2.AutoShardPolicy.FILE\n if obj == cls.DATA:\n return dataset_options_pb2.AutoShardPolicy.DATA\n if obj == cls.AUTO:\n return dataset_options_pb2.AutoShardPolicy.AUTO\n if obj == cls.HINT:\n return dataset_options_pb2.AutoShardPolicy.HINT\n raise ValueError(\"%s._to_proto() is called with undefined enum %s.\" %\n (cls.__name__, obj.name))\n\n @classmethod\n def _from_proto(cls, pb):\n \"\"\"Convert proto to enum.\"\"\"\n if pb == dataset_options_pb2.AutoShardPolicy.OFF:\n return cls.OFF\n if pb == dataset_options_pb2.AutoShardPolicy.FILE:\n return cls.FILE\n if pb == dataset_options_pb2.AutoShardPolicy.DATA:\n return cls.DATA\n if pb == dataset_options_pb2.AutoShardPolicy.AUTO:\n return cls.AUTO\n if pb == dataset_options_pb2.AutoShardPolicy.HINT:\n return cls.HINT\n raise ValueError(\"%s._from_proto() is called with undefined enum %s.\" %\n (cls.__name__, pb))\n\n\n@tf_export(\"data.experimental.ExternalStatePolicy\")\nclass ExternalStatePolicy(enum.Enum):\n \"\"\"Represents how to handle external state during serialization.\n\n See the `tf.data.Options.experimental_external_state_policy` documentation\n for more information.\n \"\"\"\n WARN = 0\n IGNORE = 1\n FAIL = 2\n\n @classmethod\n def _to_proto(cls, obj):\n \"\"\"Convert enum to proto.\"\"\"\n if obj == cls.IGNORE:\n return dataset_options_pb2.ExternalStatePolicy.IGNORE\n if obj == cls.FAIL:\n return dataset_options_pb2.ExternalStatePolicy.FAIL\n if obj == cls.WARN:\n return dataset_options_pb2.ExternalStatePolicy.WARN\n raise ValueError(\"%s._to_proto() is called with undefined enum %s.\" %\n (cls.__name__, obj.name))\n\n @classmethod\n def _from_proto(cls, pb):\n \"\"\"Convert proto to enum.\"\"\"\n if pb == dataset_options_pb2.ExternalStatePolicy.IGNORE:\n return cls.IGNORE\n if pb == dataset_options_pb2.ExternalStatePolicy.FAIL:\n return cls.FAIL\n if pb == dataset_options_pb2.ExternalStatePolicy.WARN:\n return cls.WARN\n raise ValueError(\"%s._from_proto() is called with undefined enum %s.\" %\n (cls.__name__, pb))\n\n\n@tf_export(\"data.experimental.DistributeOptions\")\nclass DistributeOptions(options.OptionsBase):\n \"\"\"Represents options for distributed data processing.\n\n You can set the distribution options of a dataset through the\n `experimental_distribute` property of `tf.data.Options`; the property is\n an instance of `tf.data.experimental.DistributeOptions`.\n\n ```python\n options = tf.data.Options()\n options.experimental_distribute.auto_shard_policy = AutoShardPolicy.OFF\n dataset = dataset.with_options(options)\n ```\n \"\"\"\n\n auto_shard_policy = options.create_option(\n name=\"auto_shard_policy\",\n ty=AutoShardPolicy,\n docstring=\"The type of sharding to use. See \"\n \"`tf.data.experimental.AutoShardPolicy` for additional information.\",\n default_factory=lambda: AutoShardPolicy.AUTO)\n\n num_devices = options.create_option(\n name=\"num_devices\",\n ty=int,\n docstring=\n \"The number of devices attached to this input pipeline. This will be \"\n \"automatically set by `MultiDeviceIterator`.\")\n\n def _to_proto(self):\n pb = dataset_options_pb2.DistributeOptions()\n pb.auto_shard_policy = AutoShardPolicy._to_proto(self.auto_shard_policy) # pylint: disable=protected-access\n if self.num_devices is not None:\n pb.num_devices = self.num_devices\n return pb\n\n def _from_proto(self, pb):\n self.auto_shard_policy = AutoShardPolicy._from_proto(pb.auto_shard_policy) # pylint: disable=protected-access\n if pb.WhichOneof(\"optional_num_devices\") is not None:\n self.num_devices = pb.num_devices\n"
] | [
[
"tensorflow.python.data.kernel_tests.test_base.default_test_combinations",
"tensorflow.python.platform.test.main",
"tensorflow.python.framework.combinations.combine",
"tensorflow.python.data.ops.dataset_ops.Dataset.range"
],
[
"tensorflow.python.data.util.options.create_option",
"tensorflow.core.framework.dataset_options_pb2.DistributeOptions",
"tensorflow.python.util.tf_export.tf_export"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"2.8",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.5",
"1.7",
"1.4"
]
}
] |
MD-Studio/MDStudio_SMARTCyp | [
"92ebd48af891188d509c23e297437218c00ec136"
] | [
"examples/example_helpers.py"
] | [
"# -*- coding: utf-8 -*-\n\nimport pandas\nimport glob\n\nfrom rdkit import Chem\nfrom rdkit.Chem.Draw import rdMolDraw2D\n\nno_wrap_div = \"\"\"\n <div style=\"display: flex; flex-wrap: wrap; justify-content: space-around\">\n <div>{0}<div style=\"text-align:center\">Docking</div></div>\n <div>{1}<div style=\"text-align:center\">SMARTCyp</div></div>\n <div>{2}<div style=\"text-align:center\">FAME 3</div></div>\n <div>{3}<div style=\"text-align:center\">MetPred</div></div>\n </div>\"\"\"\n\n\ndef show_predictions(mol, prob, cutoff=0.75, show_prob_label=False):\n \"\"\"\n Build 2D depiction of rdkit molecule\n Label atoms with index number and SOM prediction probabilities if\n above cutoff.\n \"\"\"\n\n prob_dict = dict([(int(a.split('.')[1]), b) for a, b in prob.items()])\n\n Chem.rdDepictor.Compute2DCoords(mol)\n for atom in mol.GetAtoms():\n idx = atom.GetIdx() + 1\n if show_prob_label:\n atom.SetProp('molAtomMapNumber', '{0}-{1:.2f}'.format(idx, prob_dict.get(idx, 0.0)))\n else:\n atom.SetProp('molAtomMapNumber', '{0}'.format(idx))\n\n drawer = rdMolDraw2D.MolDraw2DSVG(350, 225)\n drawer.DrawMolecule(mol, highlightAtoms=[i - 1 for i in prob_dict if prob_dict[i] >= cutoff])\n drawer.FinishDrawing()\n\n return drawer.GetDrawingText().replace('svg:', '')\n\n\ndef get_dataset():\n\n data = {}\n for case in glob.glob('*.mol2'):\n name = case.split('.')[0]\n mol = '{0}.mol'.format(name)\n data[name] = {'mol2': open(case, 'rb').read(), 'mol': open(mol, 'rb').read()}\n\n return data\n\n\ndef process_fame_results(fame_out, df):\n \"\"\"\n Add Fame results to pandas DataFrame and determine cutoff propensity\n \"\"\"\n atom_labels = dict([(int(a.split('.')[1]), a) for a in df.index])\n\n fame_pred = {}\n cutoff = 1.0\n for pred in fame_out.get('predictions', []):\n fame_pred = dict([(atom_labels[a['atomID']], a['probability']) for a in pred['atomPredictions']])\n\n fame_positives = [a['probability'] for a in pred['atomPredictions'] if a['decision']]\n if (fame_positives):\n cutoff = min(fame_positives)\n\n break\n\n df['FAME'] = pandas.Series(fame_pred)\n\n return df, cutoff\n\n\ndef process_metpred_results(metpred_out, df):\n \"\"\"\n Add MetPred results to pandas DataFrame and determine cutoff propensity\n \"\"\"\n atom_labels = dict([(int(a.split('.')[1]), a) for a in df.index])\n\n metpred_pred = {}\n metpred_type = {}\n for pred in metpred_out.get('predictions', []):\n metpred_pred[atom_labels[pred['atom']]] = pred['normalizedOccurrenceRatio']\n metpred_type[atom_labels[pred['atom']]] = '; '.join([reaction['type'] for reaction in pred['reactionTypes']])\n\n df['MetPred'] = pandas.Series(metpred_pred)\n df['MetPred reaction'] = pandas.Series(metpred_type)\n\n return df, df['MetPred'].min()\n\n\ndef style_dataframe(df, smartcyp_cutoff=0.75, docking_cutoff=0.75, fame_cutoff=1.0):\n\n def highlight_som(df, color='#f08783'):\n df1 = pandas.DataFrame('', index=df.index, columns=df.columns)\n df1.loc[(df['SMARTCyp'] >= smartcyp_cutoff), 'SMARTCyp'] = 'background-color: {}'.format(color)\n df1.loc[(df['Docking'] >= docking_cutoff), 'Docking'] = 'background-color: {}'.format(color)\n df1.loc[(df['FAME'] >= fame_cutoff), 'FAME'] = 'background-color: {}'.format(color)\n df1.loc[(df['MetPred'] > 0), 'MetPred'] = 'background-color: {}'.format(color)\n return df1\n\n return df.style.apply(highlight_som, axis=None).set_precision(3)\n"
] | [
[
"pandas.Series",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
indudhiman/bragg-edge | [
"56af0a448534ef9cb5428879ba900e194dc05db2"
] | [
"ibeatles/step2/roi_handler.py"
] | [
"try:\n from PyQt4 import QtGui, QtCore\nexcept:\n from PyQt5 import QtGui, QtCore\nimport pyqtgraph as pg\nimport numpy as np\n\nimport ibeatles.step2.gui_handler\n\n\nclass Step2RoiHandler(object):\n \n def __init__(self, parent=None):\n self.parent = parent\n \n def save_table(self):\n list_roi = self.parent.list_roi['normalization']\n\n for _row, roi in enumerate(list_roi):\n try:\n _row_infos = self.get_row(_row)\n except ValueError:\n return\n \n list_roi[_row] = _row_infos\n \n self.parent.list_roi['normalization'] = list_roi\n\n def enable_selected_roi(self):\n list_roi = self.parent.list_roi['normalization']\n list_roi_id = self.parent.list_roi_id['normalization']\n \n for index, roi in enumerate(list_roi):\n \n _roi_id = list_roi_id[index]\n is_roi_visible = roi[0]\n if is_roi_visible:\n _roi_id.setVisible(True)\n else:\n _roi_id.setVisible(False)\n \n def get_row(self, row=-1):\n if row == -1:\n return []\n \n # use flag\n _flag_widget = self.parent.ui.normalization_tableWidget.cellWidget(row, 0)\n if _flag_widget is None:\n raise ValueError\n flag = _flag_widget.isChecked()\n \n # x0\n _item = self.parent.ui.normalization_tableWidget.item(row, 1)\n if _item is None:\n raise ValueError\n x0 = str(_item.text())\n \n # y0\n _item = self.parent.ui.normalization_tableWidget.item(row, 2)\n if _item is None:\n raise ValueError\n y0 = str(_item.text())\n \n # width\n _item = self.parent.ui.normalization_tableWidget.item(row, 3)\n if _item is None:\n raise ValueError\n width = str(_item.text())\n \n # height\n _item = self.parent.ui.normalization_tableWidget.item(row, 4)\n if _item is None:\n raise ValueError\n height = str(_item.text())\n \n return [flag, x0, y0, width, height, -1]\n\n def save_roi(self):\n list_roi_id = self.parent.list_roi_id['normalization']\n list_roi = self.parent.list_roi['normalization']\n\n sample = self.parent.data_metadata['normalization']['data']\n image_item = self.parent.step2_ui['image_view'].imageItem\n\n for _index, _roi_id in enumerate(list_roi_id):\n region = _roi_id.getArraySlice(sample, image_item)\n x0 = region[0][0].start\n x1 = region[0][0].stop-1\n y0 = region[0][1].start\n y1 = region[0][1].stop-1\n\n width = x1-x0\n height = y1-y0\n \n _roi = list_roi[_index]\n _roi[1] = x0\n _roi[2] = y0\n _roi[3] = width\n _roi[4] = height\n \n list_roi[_index] = _roi\n \n self.parent.list_roi['normalization'] = list_roi\n \n def remove_roi(self):\n selection = self.parent.ui.normalization_tableWidget.selectedRanges()\n if selection == []:\n return\n \n selection = selection[0]\n _row_selected = selection.bottomRow()\n \n self.parent.ui.normalization_tableWidget.removeRow(_row_selected)\n \n list_roi = self.parent.list_roi['normalization']\n list_roi_id = self.parent.list_roi_id['normalization']\n new_list_roi = []\n new_list_roi_id = []\n for _index, _roi in enumerate(list_roi):\n if _index == _row_selected:\n self.parent.step2_ui['image_view'].removeItem(list_roi_id[_index])\n continue\n new_list_roi.append(_roi)\n new_list_roi_id.append(list_roi_id[_index])\n \n self.parent.list_roi['normalization'] = new_list_roi\n self.parent.list_roi_id['normalization'] = new_list_roi_id\n\n o_gui = ibeatles.step2.gui_handler.Step2GuiHandler(parent = self.parent)\n o_gui.check_add_remove_roi_buttons()\n\n def add_roi_in_image(self):\n roi = pg.ROI([0,0],[20,20])\n roi.addScaleHandle([1,1],[0,0])\n roi.sigRegionChangeFinished.connect(self.parent.normalization_manual_roi_changed)\n self.parent.step2_ui['image_view'].addItem(roi)\n return roi\n\n def add_roi(self):\n nbr_row_table = self.parent.ui.normalization_tableWidget.rowCount()\n new_roi_id = self.add_roi_in_image()\n\n self.parent.list_roi['normalization'].append(self.parent.init_array_normalization)\n self.parent.list_roi_id['normalization'].append(new_roi_id)\n\n self.insert_row(row=nbr_row_table)\n \n o_gui = ibeatles.step2.gui_handler.Step2GuiHandler(parent = self.parent)\n o_gui.check_add_remove_roi_buttons() \n \n def get_item(self, text):\n _item = QtGui.QTableWidgetItem(text)\n #_item.setBackground(color)\n return _item\n\n def insert_row(self, row=-1):\n self.parent.ui.normalization_tableWidget.insertRow(row)\n \n init_array = self.parent.list_roi['normalization'][-1]\n [flag, x0, y0, width, height, not_used] = init_array\n \n # button\n _widget = QtGui.QCheckBox()\n _widget.setChecked(flag)\n QtCore.QObject.connect(_widget, QtCore.SIGNAL(\"stateChanged(int)\"), self.parent.normalization_row_status_changed)\n self.parent.ui.normalization_tableWidget.setCellWidget(row, 0, _widget)\n \n # x0\n _item = self.get_item(str(x0))\n self.parent.ui.normalization_tableWidget.setItem(row, 1, _item)\n \n # y0\n _item = self.get_item(str(y0))\n self.parent.ui.normalization_tableWidget.setItem(row, 2, _item)\n \n # width\n _item = self.get_item(str(width))\n self.parent.ui.normalization_tableWidget.setItem(row, 3, _item)\n \n # height\n _item = self.get_item(str(height))\n self.parent.ui.normalization_tableWidget.setItem(row, 4, _item)\n \n def get_list_of_roi_to_use(self):\n list_roi = []\n\n nbr_row = self.parent.ui.normalization_tableWidget.rowCount()\n for _row in np.arange(nbr_row):\n _row_value = self.get_row(row=_row)\n if _row_value[0]:\n _roi = _row_value[1:5]\n list_roi.append(_roi) \n\n return list_roi"
] | [
[
"numpy.arange"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
aw02m/Spiking_neural_networks | [
"4c23c50b52b15a9e5709cb672fd18cd22218b9f2",
"4c23c50b52b15a9e5709cb672fd18cd22218b9f2"
] | [
"notebooks/bif-betaeps_third.py",
"discrete_network/tests/test_cubic_calculation.py"
] | [
"import numpy as np\nimport torch\nfrom discrete_network.network import KNNet, KNNetParameters, KNNetState\nfrom discrete_network.method.force_method import ForceParameters, ForceLearn\nfrom discrete_network.device import device\nimport matplotlib.pyplot as plt\n\nprint(f\"Device = {device.type}\")\n\n# params_spiking = KNNetParameters(eps = 0.015, beta = 0.0, d = 0.26, a = 0.25, J = 0.1081 + 0.1)\n# params_spiking = KNNetParameters(eps = 0.015, beta = 0.03, d = 0.26, a = 0.25, J = 0.1081 + 0.1)\n# params_spiking = KNNetParameters(eps = 0.015, beta = 0.05, d = 0.26, a = 0.25, J = 0.15)\n\n# normal spike\n# params_spiking = KNNetParameters(eps = 0.02, beta = 0.0, d = 0.26, a = 0.25, J = 0.1081 + 0.1)\n# params_spiking = KNNetParameters(eps = 0.03, beta = 0.035, d = 0.26, a = 0.25, J = 0.1081 + 0.1)\n\ndef one_neuron(x0, y0, iteration, p: KNNetParameters):\n \"\"\"The dynamics of one neuron. Return x, y.\"\"\"\n x, y = np.zeros(iteration), np.zeros(iteration)\n x[0], y[0] = x0, y0\n for i in range(iteration - 1):\n x[i + 1] = (\n x[i]\n + x[i] * (x[i] - p.a) * (1 - x[i])\n - p.beta * (x[i] > p.d)\n - y[i]\n )\n y[i + 1] = y[i] + p.eps * (x[i] - p.J)\n return x, y\n\nimin = 0; icrit = 20000; nt = 21000\n\ninput_size = 0\nhidden_size = 2000\noutput_size = 2\n\neps_start = 0.01\neps_stop = 0.1\neps = eps_start + (eps_stop - eps_start) * torch.rand(hidden_size, 1).to(device)\n\na = 0.25\n\nJ = (1 + a - torch.sqrt(1 + a * a - a + 3 * eps)) / 3\nJ = J.to(device)\n\np = KNNetParameters(\n eps=eps, a=torch.as_tensor(a), J=J, q=1.1, g=0.1, x_th=torch.as_tensor(0.65),\n beta=torch.as_tensor(0.0)\n)\n\nbifparams = []\nbifparams_second = []\n\nfor i in np.arange(0.03, 0.04, 0.001):\n for j in np.arange(0.025, 0.1, 0.002):\n params_spiking = KNNetParameters(eps = j, beta = i, d = 0.26, a = 0.25, J = 0.1081 + 0.1)\n f_out_x, f_out_y = one_neuron(0.3, 0, nt, params_spiking)\n f_out = np.concatenate([[f_out_x], [f_out_y]], 0).T\n\n x_initial = 0.9 * torch.rand(hidden_size, 1).to(device)\n y_initial = torch.zeros(hidden_size, 1).to(device)\n z_initial = torch.zeros(hidden_size, 1).to(device)\n ISPC_initial = torch.zeros(hidden_size, 1).to(device)\n initial_state = KNNetState(x=x_initial, y=y_initial, z=z_initial, ISPC=ISPC_initial)\n net = KNNet(input_size, hidden_size, output_size, p=p)\n net.to_device(device)\n lp = ForceParameters(stop_learning=icrit, start_learning=imin)\n fl = ForceLearn(net=net, lp=lp, save_states=True)\n\n train_logs, states = fl.train(target_outputs=f_out, state=initial_state)\n\n L2 = torch.linalg.norm(train_logs[-1000:, 0, 0] - f_out[-1000:, 0])\n L2_second = torch.linalg.norm(train_logs[-1000:, 1, 0] - f_out[-1000:, 1])\n\n print(torch.log(L2))\n bifparams.append([i, j, torch.log(L2).item()])\n bifparams_second.append([i, j, torch.log(L2_second).item()])\n print(f'1dim: {bifparams[-1]}, 2dim: {bifparams_second[-1]}')\n\n\nbifparams = np.array(bifparams)\nbifparams_second = np.array(bifparams_second)\nnp.save('./betaeps_3', bifparams)\nnp.save('./betaeps_second_3', bifparams_second)",
"import torch\nfrom ..network import cubicFunction\n\ndef test_cubic_function_zero_input_zero_parameters():\n data = torch.zeros(1).type(torch.float)\n parameter = torch.as_tensor(0.).type(torch.float)\n output = cubicFunction(data, parameter)\n assert torch.allclose(output, torch.tensor([0]).type(torch.float))\n\ndef test_cubic_function_zero_input():\n data = torch.tensor([1, 2, 3]).type(torch.float)\n parameter = torch.as_tensor(0.).type(torch.float)\n output = cubicFunction(data, parameter)\n target_output = data * (data - parameter) * (1.0 - data)\n\n assert torch.allclose(output,target_output)\n\ndef test_cubic_function():\n data = torch.tensor([1, 2, 3]).type(torch.float)\n parameter = torch.as_tensor(0.).type(torch.float)\n output = cubicFunction(data, parameter)\n target_output = data * (data - parameter) * (1.0 - data)\n assert torch.allclose(output, target_output)\n\n"
] | [
[
"torch.zeros",
"torch.sqrt",
"numpy.arange",
"numpy.save",
"torch.linalg.norm",
"numpy.concatenate",
"torch.log",
"torch.rand",
"numpy.array",
"numpy.zeros",
"torch.as_tensor"
],
[
"torch.tensor",
"torch.allclose",
"torch.as_tensor",
"torch.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
arharvey918/python-dlpy | [
"423985ebe65acbcbe9a7996bb26aee5e66eddc49",
"423985ebe65acbcbe9a7996bb26aee5e66eddc49"
] | [
"dlpy/model_conversion/sas_onnx_parse.py",
"dlpy/tests/test_model.py"
] | [
"#!/usr/bin/env python\n# encoding: utf-8\n#\n# Copyright SAS Institute\n#\n# Licensed under the Apache License, Version 2.0 (the License);\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n''' Convert ONNX models to SAS models '''\n\nimport sys\nimport warnings\n\nimport h5py\nimport numpy as np\nfrom onnx import numpy_helper\nfrom onnx.shape_inference import infer_shapes\n\nfrom dlpy.layers import (InputLayer, Conv2d, Pooling, Dense, OutputLayer,\n BN, Concat, Res, GroupConv2d, GlobalAveragePooling2D)\nfrom dlpy.model_conversion.onnx_graph import OnnxGraph, OnnxNode\nfrom dlpy.model_conversion.onnx_transforms import (ConstToInitializer,\n InitReshape, InitUnsqueeze,\n FuseMulAddBN)\n\n# The supported ONNX ops that can be parsed by this module\n_onnx_ops = ['Conv', 'MaxPool', 'AveragePool', 'GlobalAveragePool',\n 'BatchNormalization', 'Concat', 'Gemm', 'MatMul',\n 'Add', 'Sum', 'Reshape', 'Dropout', 'Flatten', 'Constant']\n\n\n# mapping ONNX ops to SAS activations\n_act_map = {\n 'Relu': 'RELU',\n 'Tanh': 'TANH',\n 'LeakyRelu': 'LEAKY',\n 'Log': 'LOGISTIC',\n 'Softmax': 'SOFTMAX',\n 'Identity': 'IDENTITY',\n 'Cos': 'COS',\n 'Sin': 'SIN',\n 'Exp': 'EXP',\n 'Elu': 'ELU',\n 'Softplus': 'SOFTPLUS'\n}\n\n\nclass OnnxParseError(ValueError):\n '''\n Used to indicate an error in parsing ONNX model definition\n\n '''\n\n\ndef onnx_to_sas(model, model_name=None, output_layer=None):\n ''' \n Generate SAS model from ONNX model \n \n Parameters\n ----------\n model : ONNX ModelProto\n Specifies the loaded ONNX model.\n model_name : string, optional\n Specifies the name of the model.\n output_layer : Layer object, optional\n Specifies the output layer of the model. If no output\n layer is specified, the last layer is automatically set\n as :class:`OutputLayer` with SOFTMAX activation.\n\n Returns\n -------\n list\n List of Layers \n\n '''\n # run transforms\n graph_ = OnnxGraph.from_onnx(model.graph)\n transforms = [\n ConstToInitializer(),\n InitReshape(),\n InitUnsqueeze(),\n FuseMulAddBN()\n ]\n\n for transform in transforms:\n transform(graph_)\n model = graph_.make_onnx()\n\n # verify model ops are supported \n for n in model.graph.node:\n if n.op_type not in _onnx_ops + list(_act_map.keys()):\n raise OnnxParseError('Unsupported op: ' + n.op_type)\n\n # get shapes of tensors in graph\n model = infer_shapes(model)\n graph_def = model.graph\n dlpy_layers = []\n\n if model_name is None:\n model_name = graph_def.name\n\n # nodes that correspond to sas deeplearn layers \n sas_computation_nodes = onnx_filter_sas_layers(graph_def)\n\n # initializer: TensorProtos representing values to initialize\n # initialized: A list of names of the initialized tensors\n if graph_def.initializer:\n init_tensors = onnx_initializer_to_tensors(graph_def.initializer)\n initialized = [init.name for init in graph_def.initializer]\n else:\n init_tensors = []\n initialized = []\n\n tensor_dict = dict(init_tensors)\n\n # determine SAS input layers from uninitialized input ValueInfo\n uninitialized = [value_info for value_info in graph_def.input\n if value_info.name not in initialized]\n\n if not uninitialized:\n raise OnnxParseError('Unable to determine input layer.')\n elif len(uninitialized) > 1:\n # TODO: support multipe input layers\n raise OnnxParseError('Unable to determine input layer.')\n else:\n input_layer = onnx_input_layer(uninitialized[0])\n dlpy_layers.append(input_layer)\n\n # create SAS layers from the ONNX nodes \n for node in sas_computation_nodes:\n layer = onnx_extract_sas_layer(graph_def, node, dlpy_layers)\n dlpy_layers.append(layer)\n \n # apply activations\n for node in graph_def.node:\n if node.op_type in _act_map.keys():\n # handle output layer activations separately \n if node.op_type == 'Softmax':\n continue\n previous = onnx_find_previous_compute_layer(graph_def, node)\n if len(previous) != 1:\n print('Warning: Unable to apply activation for node '\n + str(node.name) + '.')\n continue\n for layer in dlpy_layers:\n # TODO: better checks for valid activations \n if layer.name == previous[0].name: \n if 'act' in layer.config.keys():\n layer.config.update(act=_act_map.get(node.op_type))\n else:\n print('Warning: Unable to apply activation for '\n + layer.name + ' layer.')\n\n # apply dropout\n for node in graph_def.node:\n if node.op_type == 'Dropout':\n previous = onnx_find_previous_compute_layer(graph_def, node)\n if len(previous) != 1:\n print('Warning: Unable to apply dropout. '\n 'More than one source layer found.')\n continue\n for layer in dlpy_layers:\n if layer.name == previous[0].name:\n if 'dropout' in layer.config.keys():\n layer.config.update(dropout=node.attribute[0].f)\n else:\n print('Warning: Unable to apply dropout for'\n + layer.name + ' layer')\n\n # write weights hdf5\n hdf5_out = write_weights_hdf5(dlpy_layers, graph_def, tensor_dict, model_name)\n\n # add output layer\n # if output_layer is not specified, output layer defaults to SOFTMAX\n if output_layer is None:\n # if previous layer is fc, we can replace it with output layer\n if dlpy_layers[-1].type == 'fc':\n last_layer = dlpy_layers.pop()\n out_layer = OutputLayer(name=last_layer.name,\n act='SOFTMAX',\n n=last_layer.config['n'],\n src_layers=last_layer.src_layers)\n dlpy_layers.append(out_layer)\n # if previous layer is not fc, default to loss layer only\n else:\n n = dlpy_layers[-1].output_size[-1]\n out_layer = OutputLayer(name='output',\n act='IDENTITY',\n n=n,\n include_bias=False,\n full_connect = False,\n src_layers=[dlpy_layers[-1]])\n dlpy_layers.append(out_layer)\n else:\n # connect output_layer to previous layer\n output_layer.src_layers = [dlpy_layers[-1]]\n if not output_layer.name:\n output_layer.name = 'output'\n dlpy_layers.append(output_layer)\n\n return dlpy_layers\n\n\ndef onnx_initializer_to_tensors(initializer):\n ''' \n Convert ONNX graph initializer to tensors \n \n Parameters\n ----------\n initializer : list of ONNX TensorProto\n Specifies the initializer of the graph.\n\n Returns\n -------\n list of numpy.ndarray\n\n '''\n\n return [(init.name,\n numpy_helper.to_array(init))\n for init in initializer]\n\n\ndef onnx_filter_sas_layers(graph):\n ''' \n Filter nodes that correspond to SAS Deep learning layer types \n \n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n \n Returns\n -------\n list of ONNX NodeProto\n\n '''\n\n sas_layers = [node for node in graph.node\n if is_compute_layer(graph, node)]\n\n return sas_layers\n\n\ndef onnx_input_layer(value_info):\n ''' \n Construct Input Layer \n \n Parameters\n ----------\n value_info : ONNX ValueInfoProto\n Specifies a ValueInfoProto object.\n\n Returns\n -------\n :class:`InputLayer`\n \n '''\n input_layer_name = value_info.name\n dims = tuple(d.dim_value for d in\n value_info.type.tensor_type.shape.dim)\n if len(dims) == 3:\n # Assume single channel image\n N, H, W = dims\n return InputLayer(n_channels=1, width=W, height=H, name=input_layer_name)\n elif len(dims) == 4:\n _, C, H, W = dims\n return InputLayer(n_channels=C, width=W, height=H, name=input_layer_name)\n else:\n raise OnnxParseError('Cannot parse input dimensions, expecting NCHW or NHW.')\n\n\ndef onnx_extract_sas_layer(graph, node, layers):\n '''\n Generate SAS DeepLearn Layer from ONNX node\n\n Parameters\n ----------\n graph : ONNX :class:`GraphProto`\n Specifies the ONNX graph.\n node : ONNX :class:`NodeProto`\n Specifies the ONNX node.\n layers : list of Layers\n The sequential layers of the model.\n\n Returns\n -------\n :class:`Layer`\n Layer object corresponding to the ONNX node.\n\n '''\n if node.op_type == 'Conv':\n return onnx_extract_conv(graph, node, layers)\n elif node.op_type == 'MaxPool':\n return onnx_extract_pool(graph, node, layers, pool='MAX')\n elif node.op_type == 'AveragePool':\n return onnx_extract_pool(graph, node, layers, pool='AVERAGE')\n elif node.op_type == 'BatchNormalization':\n return onnx_extract_batchnormalization(graph, node, layers)\n elif node.op_type == 'Concat':\n return onnx_extract_concat(graph, node, layers)\n elif node.op_type == 'Gemm':\n return onnx_extract_gemm(graph, node, layers)\n elif node.op_type == 'MatMul':\n return onnx_extract_matmul(graph, node, layers)\n elif node.op_type in ['Add', 'Sum']:\n return onnx_extract_residual(graph, node, layers)\n elif node.op_type == 'GlobalAveragePool':\n return onnx_extract_globalpool(graph, node, layers)\n else:\n raise OnnxParseError('Unsupported ONNX op: '\n + str(node.name) + ', '\n + str(node.op_type))\n\n\ndef find_input_layer_name(graph):\n ''' \n Determine the name of the input layer \n \n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies the GraphProto object.\n\n Returns\n -------\n string\n\n '''\n initialized = [init.name for init in graph.initializer]\n uninitialized = [value_info.name for value_info in graph.input\n if value_info.name not in initialized]\n if not uninitialized:\n raise OnnxParseError('Unable to determine input layer.')\n if len(uninitialized) > 1:\n raise OnnxParseError('Unable to determine input layer.')\n return uninitialized[0]\n\n\ndef get_dlpy_layer(layers, name):\n ''' \n Get a layer by name from list of layers \n \n Parameters\n ----------\n layers : list of Layers\n Specifies a list of Layers.\n name : string\n Specifies the name of a Layer.\n\n Returns\n -------\n Layer, or None\n The layer matching the name, or None.\n ''' \n for layer in layers:\n if layer.name == name:\n return layer\n return None\n\n\ndef onnx_extract_conv(graph, node, layers):\n ''' \n Construct convo layer from ONNX op \n\n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n layers : list of Layers\n Specifies the existing layers of a model.\n\n Returns\n -------\n :class:`Conv2d` or 'GroupConv2d'\n\n '''\n previous = onnx_find_previous_compute_layer(graph, node)\n\n if not previous:\n src_names = [find_input_layer_name(graph)]\n else:\n src_names = [p.name for p in previous]\n\n src = [get_dlpy_layer(layers, i) for i in src_names]\n\n height = None\n width = None\n stride = None\n stride_horizontal = None\n stride_vertical = None\n padding = None\n padding_height = None\n padding_width = None\n n_filters = None\n include_bias = False\n act = 'identity'\n group = None\n\n # if padding is not present, default to 0\n is_padding = False\n\n attributes = node.attribute\n for attr in attributes:\n if attr.name == 'kernel_shape':\n height, width = attr.ints\n elif attr.name == 'strides':\n stride_vertical, stride_horizontal = attr.ints\n # only specify one of stride and stride_horizontal\n if stride_horizontal == stride_vertical:\n stride = stride_horizontal\n stride_horizontal = None\n stride_vertical = None\n elif attr.name == 'auto_pad':\n is_padding = True\n attr_s = attr.s.decode('utf8')\n if attr_s == 'SAME_UPPER' or attr_s == 'SAME_LOWER':\n continue\n elif attr_s == 'NOTSET':\n continue\n else: # 'VALID'\n padding = 0\n elif attr.name == 'pads':\n is_padding = True\n padding_height, padding_width, p_h2, p_w2 = attr.ints\n if padding_height != p_h2 or padding_width != p_w2:\n print('Warning: Unequal padding not supported for '\n + node.name + ' setting equal padding instead.')\n padding_height = max(padding_height, p_h2)\n padding_width = max(padding_width, p_w2)\n elif attr.name == 'group':\n group = attr.i\n\n if not is_padding:\n padding = 0\n\n # check if weight tensor is in initializer\n for init in graph.initializer:\n if init.name == node.input[1]:\n n_filters = numpy_helper.to_array(init).shape[0]\n\n # if not in initializer, check inferred shapes in graph\n if n_filters is None:\n for v in graph.value_info:\n if v.name == node.input[1]:\n n_filters = v.type.tensor_type.shape.dim[0].dim_value\n\n # check if bias is specified in conv op\n if len(node.input) == 3:\n include_bias = True\n # check if bias is added by the next op\n else:\n out = onnx_get_out_nodes(graph, node)\n for n in out:\n if is_bias_op(graph, n):\n include_bias = True\n\n if group and group > 1:\n return GroupConv2d(n_groups=group,\n n_filters=n_filters,\n width=width,\n height=height,\n stride=stride,\n name=node.name,\n stride_horizontal=stride_horizontal,\n stride_vertical=stride_vertical,\n padding=padding,\n padding_width=padding_width,\n padding_height=padding_height,\n act=act,\n include_bias=include_bias,\n src_layers=src)\n else:\n return Conv2d(n_filters=n_filters,\n width=width,\n height=height,\n stride=stride,\n name=node.name,\n stride_horizontal=stride_horizontal,\n stride_vertical=stride_vertical,\n padding=padding,\n padding_width=padding_width,\n padding_height=padding_height,\n act=act,\n include_bias=include_bias,\n src_layers=src)\n\n \ndef onnx_extract_pool(graph, node, layers, pool='MAX'):\n ''' \n Construct pool layer from ONNX op \n \n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n layers : list of Layers\n Specifies the existing layers of a model.\n pool : str, optional\n Specifies the type of pooling.\n Default: MAX\n\n Returns\n -------\n :class:`Pooling`\n\n '''\n previous = onnx_find_previous_compute_layer(graph, node)\n \n if not previous:\n src_names = [find_input_layer_name(graph)]\n else:\n src_names = [p.name for p in previous]\n \n src = [get_dlpy_layer(layers, i) for i in src_names]\n\n height = None\n padding = None\n padding_height = None\n padding_width = None\n stride = None\n stride_horizontal = None\n stride_vertical = None\n width = None\n \n # if padding is not present, default to 0\n is_padding = False\n\n for attr in node.attribute:\n if attr.name == 'kernel_shape':\n height, width = attr.ints\n elif attr.name == 'strides':\n stride_vertical, stride_horizontal = attr.ints\n # only specify one of stride and stride_horizontal\n if stride_horizontal == stride_vertical:\n stride = stride_horizontal\n stride_horizontal = None\n stride_vertical = None\n elif attr.name == 'auto_pad':\n is_padding = True\n attr_s = attr.s.decode('utf8')\n if attr_s == 'SAME_UPPER' or attr_s == 'SAME_LOWER':\n continue\n elif attr_s == 'NOTSET':\n continue\n else: # 'VALID'\n padding = 0\n elif attr.name == 'pads':\n is_padding = True\n padding_height, padding_width, p_h2, p_w2 = attr.ints\n if padding_height != p_h2 or padding_width != p_w2:\n print('WARNING: Unequal padding not supported for '\n + node.name + ' Setting auto padding instead.')\n if padding_height == 0 and p_h2 != 0:\n padding_height = None\n else:\n padding_height = max(padding_height, p_h2)\n if padding_width == 0 and p_w2 != 0:\n padding_width = None\n else:\n padding_width = max(padding_width, p_w2)\n\n if not is_padding:\n padding = 0\n \n return Pooling(width=width,\n height=height,\n stride=stride,\n name=node.name,\n stride_horizontal=stride_horizontal,\n stride_vertical=stride_vertical,\n padding=padding,\n padding_width=padding_width,\n padding_height=padding_height,\n pool=pool,\n src_layers=src)\n\n\ndef onnx_extract_globalpool(graph, node, layers):\n ''' \n Construct global pool layer from ONNX op \n\n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n layers : list of Layers\n Specifies the existing layers of a model.\n\n Returns\n -------\n :class:`Pooling`\n \n '''\n previous = onnx_find_previous_compute_layer(graph, node)\n \n if not previous:\n src_names = [find_input_layer_name(graph)]\n else:\n src_names = [p.name for p in previous]\n \n src = [get_dlpy_layer(layers, i) for i in src_names]\n \n # check the shape of the input to pool op\n _, C, height, width = onnx_get_shape(graph, node.input[0])\n \n return Pooling(width=width,\n height=height,\n stride=width,\n name=node.name,\n padding=0,\n pool='AVERAGE',\n src_layers=src)\n\n\ndef onnx_extract_batchnormalization(graph, node, layers):\n ''' \n Construct batchnorm layer from ONNX op \n \n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n layers : list of Layers\n Specifies the existing layers of a model.\n \n Returns\n -------\n :class:`BN`\n\n '''\n previous = onnx_find_previous_compute_layer(graph, node)\n \n if not previous:\n src_names = [find_input_layer_name(graph)]\n else:\n src_names = [p.name for p in previous]\n\n src = [get_dlpy_layer(layers, i) for i in src_names]\n\n return BN(name=node.name,\n act='identity',\n src_layers=src)\n\n\ndef onnx_extract_concat(graph, node, layers):\n ''' \n Construct concat layer from ONNX op \n\n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n layers : list of Layers\n Specifies the existing layers of a model.\n \n Returns\n -------\n :class:`Concat`\n\n '''\n previous = onnx_find_previous_compute_layer(graph, node)\n \n if not previous:\n src_names = [find_input_layer_name(graph)]\n else:\n src_names = [p.name for p in previous]\n\n src = [get_dlpy_layer(layers, i) for i in src_names]\n\n return Concat(name=node.name,\n act='identity',\n src_layers=src)\n\n\ndef onnx_extract_gemm(graph, node, layers):\n ''' \n Construct FC layer from ONNX op \n\n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n layers : list of Layers\n Specifies the existing layers of a model.\n \n Returns\n -------\n :class:`Dense`\n\n '''\n previous = onnx_find_previous_compute_layer(graph, node)\n \n if not previous:\n src_names = [find_input_layer_name(graph)]\n else:\n src_names = [p.name for p in previous]\n\n src = [get_dlpy_layer(layers, i) for i in src_names]\n \n include_bias = True\n act = 'identity'\n neurons = None\n\n # determine dimensions of the multiply \n a_shape = None\n b_shape = None\n # check initializer for weight tensors\n for init in graph.initializer:\n if init.name == node.input[0]:\n a_shape = numpy_helper.to_array(init).shape\n if init.name == node.input[1]:\n b_shape = numpy_helper.to_array(init).shape\n \n # check inferred shapes in graph\n for v in graph.value_info:\n if v.name == node.input[0]:\n try:\n a_shape = (v.type.tensor_type.shape.dim[0].dim_value, \n v.type.tensor_type.shape.dim[1].dim_value)\n except IndexError:\n pass\n if v.name == node.input[1]:\n try:\n b_shape = (v.type.tensor_type.shape.dim[0].dim_value, \n v.type.tensor_type.shape.dim[1].dim_value)\n except IndexError:\n pass\n\n if a_shape is None and b_shape is None:\n raise OnnxParseError('Unable to determine number of neurons '\n 'in FC layer.')\n elif a_shape is None or b_shape is None:\n prev_out = layers[-1].output_size\n if isinstance(prev_out, int):\n fc_input_dim = prev_out\n else:\n fc_input_dim = 1\n for d in prev_out:\n fc_input_dim *= int(d)\n if a_shape is None:\n a_shape = (1, fc_input_dim)\n else:\n b_shape = (1, fc_input_dim)\n \n # check if transpose\n for attr in node.attribute:\n if attr.name == 'transA':\n if attr.i == 1:\n a_shape = (a_shape[1], a_shape[0])\n elif attr.name == 'transB':\n if attr.i == 1:\n b_shape = (b_shape[1], b_shape[0])\n\n # set number of neurons according to shape\n if a_shape[0] == 1:\n neurons = b_shape[1]\n else:\n neurons = a_shape[0]\n \n return Dense(n=neurons,\n name=node.name,\n act=act,\n include_bias=include_bias,\n src_layers=src)\n\n\ndef onnx_extract_matmul(graph, node, layers):\n ''' \n Construct FC layer from ONNX op \n\n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n layers : list of Layers\n Specifies the existing layers of a model.\n \n Returns\n -------\n :class:`Dense`\n\n '''\n previous = onnx_find_previous_compute_layer(graph, node)\n \n if not previous:\n src_names = [find_input_layer_name(graph)]\n else:\n src_names = [p.name for p in previous]\n\n src = [get_dlpy_layer(layers, i) for i in src_names]\n \n include_bias = False\n act = 'identity'\n neurons = None\n\n # check initializer for weight tensors\n for init in graph.initializer:\n if init.name == node.input[1]:\n neurons = numpy_helper.to_array(init).shape[1]\n \n if neurons is None:\n raise OnnxParseError('Unable to determine number of neurons '\n 'in FC layer.')\n \n # check if bias is added by the next op\n out = onnx_get_out_nodes(graph, node) \n for n in out:\n if is_bias_op(graph, n):\n include_bias = True\n\n return Dense(n=neurons,\n name=node.name,\n act=act,\n include_bias=include_bias,\n src_layers=src)\n\n\ndef onnx_extract_residual(graph, node, layers):\n ''' \n Construct residual layer from ONNX op \n\n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n layers : list of Layers\n Specifies the existing layers of a model.\n\n Returns\n -------\n :class:`Res`\n \n '''\n previous = onnx_find_previous_compute_layer(graph, node)\n \n if not previous:\n src_names = [find_input_layer_name(graph)]\n else:\n src_names = [p.name for p in previous]\n\n src = [get_dlpy_layer(layers, i) for i in src_names]\n\n return Res(name=node.name,\n act='identity',\n src_layers=src)\n\n\ndef onnx_get_node(graph, name):\n ''' \n Get ONNX node from graph by name \n \n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n \n Returns\n -------\n NodeProto\n\n '''\n for node in graph.node:\n if node.name == name:\n return node\n\n\ndef onnx_get_input_nodes(graph, node):\n ''' \n Return all nodes that are inputs for a node \n\n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n\n Returns\n -------\n list\n list of NodeProto\n \n '''\n in_nodes = []\n for i in node.input:\n for n in graph.node:\n if i in n.output:\n in_nodes.append(n)\n return in_nodes\n\n\ndef onnx_get_out_nodes(graph, node):\n ''' \n Return all nodes that connect to output \n \n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n\n Returns\n -------\n list\n list of NodeProto\n\n '''\n out_nodes = []\n for i in node.output:\n for n in graph.node:\n if i in n.input:\n out_nodes.append(n)\n return out_nodes\n\n\ndef onnx_find_previous_compute_layer(graph, node):\n ''' \n Determine a node's previous corresponding SAS compute layer \n \n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n\n Returns\n -------\n list\n List of NodeProto \n\n '''\n src = []\n\n def f(graph, node, src_layers):\n in_nodes = onnx_get_input_nodes(graph, node)\n for n in in_nodes:\n if is_compute_layer(graph, n):\n src_layers.append(n)\n else:\n f(graph, n, src_layers) \n\n f(graph, node, src)\n return src\n\n \ndef is_compute_layer(graph, node):\n ''' \n Determine if this ONNX node corresponds to a SAS layer \n \n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n\n Returns\n -------\n bool\n\n '''\n # 'Add' and 'Sum' are handled separately since they may be\n # either a bias op for previous layer, or a SAS residual layer\n # TODO: add reshape \n sas_layers = ['Conv', 'MaxPool', 'AveragePool', 'GlobalAveragePool',\n 'BatchNormalization', 'Concat', 'Gemm', 'MatMul']\n\n if node.op_type in ['Add', 'Sum']:\n if is_residual_layer(graph, node):\n return True\n else:\n if node.op_type in sas_layers:\n return True\n\n return False\n\n\ndef is_residual_layer(graph, node):\n ''' \n Correctly identify add op as residual layer \n \n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n\n Returns\n -------\n bool\n \n '''\n # or add/sum for residual layer\n if node.op_type not in ['Add', 'Sum']:\n return False\n\n # check that an input to add op is not initialized\n # i.e. a bias term\n initialized = [init.name for init in graph.initializer]\n \n # if initializer->reshape->input, return False\n for n in graph.node:\n if n.op_type != 'Reshape':\n continue\n a, b = n.input\n if a in initialized and b in initialized:\n if n.output in node.input:\n return False\n\n # if an input comes from initializer, return False\n for i in node.input:\n if i in initialized:\n return False\n\n return True\n\n\ndef is_bias_op(graph, node):\n ''' \n Correctly identify bias op \n \n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n\n Returns\n -------\n bool\n\n ''' \n if node.op_type not in ['Add', 'Sum']:\n return False\n \n initialized = [init.name for init in graph.initializer]\n\n # if an input comes from initializer, return True \n for i in node.input:\n if i in initialized:\n return True\n\n # if initializer->reshape->input, return True \n for n in graph.node:\n if n.op_type != 'Reshape':\n continue\n a, b = n.input\n if a in initialized and b in initialized:\n if n.output in node.input:\n return True\n\n return False\n\n\ndef onnx_find_next_activation(graph, node):\n ''' \n Check if an activation follows current compute node \n \n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n node : ONNX NodeProto\n Specifies a NodeProto object.\n\n Returns\n -------\n string\n Name of the ONNX activation op\n\n '''\n # if so, return that. Otherwise, return None\n # TODO: use this to find activations during layer generation\n activation_ops = ['Relu', 'Tanh', 'LeakyRelu', 'Log', 'Identity']\n \n out = onnx_get_out_nodes(graph, node)\n \n if len(out) != 1:\n return None\n else:\n if is_compute_layer(graph, out[0]):\n return None\n elif out[0].op_type in activation_ops:\n return out[0]\n else:\n return onnx_find_next_activation(graph, out[0])\n\n\ndef onnx_get_shape(graph, tensor):\n ''' \n Get shape from valueinfo \n \n Parameters\n ----------\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n tensor : ONNX ValueInfoProto \n Specifies a ValueInfoProto object.\n\n Returns\n -------\n list\n list of ints of the dimensions\n\n '''\n for i in graph.value_info:\n if i.name == tensor:\n return [d.dim_value for d in i.type.tensor_type.shape.dim]\n\n\ndef write_weights_hdf5(layers, graph, tensor_dict, name):\n ''' \n Write SAS compatible HDF5 weights file \n \n Parameters\n ----------\n layers : list of Layers\n Specifies the layers of the model.\n graph : ONNX GraphProto\n Specifies a GraphProto object.\n tensor_dict : dict of numpy.ndarray\n Specifies the dictionary of weight tensors.\n name : string\n Specifies the name of the model.\n\n '''\n import os\n temp_HDF5 = os.path.join(os.getcwd(), '{}_weights.onnxmodel.h5'.format(name))\n f_out = h5py.File(temp_HDF5, 'w')\n weight_layers = [l for l in layers if l.type in ['convo', 'fc', 'batchnorm', 'groupconvo']]\n f_out.attrs['layer_names'] = [l.name.encode('utf8') for l in weight_layers]\n for layer in weight_layers:\n new_weight_names = []\n g_out = f_out.create_group(layer.name)\n node = onnx_get_node(graph, layer.name)\n weights = [np.array(tensor_dict[i], dtype=np.float32) for i in node.input\n if tensor_dict.get(i) is not None]\n\n if layer.type in ['convo', 'fc', 'groupconvo']:\n # check bias op following the node\n # to see if we need to include any bias weights\n for n in onnx_get_out_nodes(graph, node):\n if is_bias_op(graph, n):\n for i in n.input:\n if tensor_dict.get(i) is not None:\n weights.append(tensor_dict[i].flatten())\n for w in weights:\n if len(w.shape) > 1:\n dset_name = layer.name + '/' + 'kernel:0'\n # check if need to transpose fc weight\n if len(w.shape) == 2:\n # check if transposed was specified in Gemm op\n if node.op_type == 'Gemm':\n for attr in node.attribute:\n if attr.name == 'transB':\n if attr.i == 1:\n w = np.transpose(w, (1, 0))\n if w.shape[1] == layer.config['n']:\n w = np.transpose(w, (1,0))\n g_out.create_dataset(dset_name.encode('utf8'), data=w)\n new_weight_names.append(dset_name.encode('utf8'))\n else:\n dset_name = layer.name + '/' + 'bias:0'\n g_out.create_dataset(dset_name.encode('utf8'), data=w)\n new_weight_names.append(dset_name.encode('utf8'))\n elif layer.type == 'batchnorm':\n template_names = ['gamma:0', 'beta:0', 'moving_mean:0', \n 'moving_variance:0']\n template_names = [layer.name + '/' + i for i in template_names]\n if len(weights) != 4:\n raise OnnxParseError('Incorrect batchnorm weights') \n for idx, w in enumerate(weights):\n if idx == 3:\n # clip variance to avoid error on cas\n w = np.clip(w, a_min = 1e-12, a_max = 1e10)\n g_out.create_dataset(template_names[idx].encode('utf8'), data=w)\n new_weight_names.append(template_names[idx].encode('utf8'))\n else:\n g_out.create_dataset(template_names[idx].encode('utf8'), data=w)\n new_weight_names.append(template_names[idx].encode('utf8'))\n\n g_out.attrs['weight_names'] = new_weight_names\n\n f_out.close()\n print('NOTE: Successfully written weights file as '\n + temp_HDF5)\n return temp_HDF5\n\n",
"#!/usr/bin/env python\n# encoding: utf-8\n#\n# Copyright SAS Institute\n#\n# Licensed under the Apache License, Version 2.0 (the License);\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n# NOTE: This test requires a running CAS server. You must use an ~/.authinfo\n# file to specify your username and password. The CAS host and port must\n# be specified using the CASHOST and CASPORT environment variables.\n# A specific protocol ('cas', 'http', 'https', or 'auto') can be set using\n# the CASPROTOCOL environment variable.\n\nimport os\nimport swat\nimport swat.utils.testing as tm\nimport dlpy\nfrom swat.cas.table import CASTable\nfrom dlpy.model import Model, Optimizer, AdamSolver, Sequence\nfrom dlpy.sequential import Sequential\nfrom dlpy.timeseries import TimeseriesTable\nfrom dlpy.layers import (InputLayer, Conv2d, Conv1d, Pooling, Dense, OutputLayer,\n Recurrent, Keypoints, BN, Res, Concat, Reshape, GlobalAveragePooling1D)\nfrom dlpy.utils import caslibify, caslibify_context, file_exist_on_server\nfrom dlpy.applications import Tiny_YoloV2\nimport unittest\n\n\nclass TestModel(unittest.TestCase):\n '''\n Please locate the images.sashdat file under the datasources to the DLPY_DATA_DIR.\n '''\n server_type = None\n s = None\n server_sep = '/'\n data_dir = None\n data_dir_local = None\n\n def setUp(self):\n swat.reset_option()\n swat.options.cas.print_messages = False\n swat.options.interactive_mode = False\n\n self.s = swat.CAS()\n self.server_type = tm.get_cas_host_type(self.s)\n self.server_sep = '\\\\'\n if self.server_type.startswith(\"lin\") or self.server_type.startswith(\"osx\"):\n self.server_sep = '/'\n\n if 'DLPY_DATA_DIR' in os.environ:\n self.data_dir = os.environ.get('DLPY_DATA_DIR')\n if self.data_dir.endswith(self.server_sep):\n self.data_dir = self.data_dir[:-1]\n self.data_dir += self.server_sep\n\n if 'DLPY_DATA_DIR_LOCAL' in os.environ:\n self.data_dir_local = os.environ.get('DLPY_DATA_DIR_LOCAL')\n if self.data_dir_local.endswith(self.server_sep):\n self.data_dir_local = self.data_dir_local[:-1]\n self.data_dir_local += self.server_sep\n\n def test_model1(self):\n\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_', lr=0.001)\n if r.severity > 0:\n for msg in r.messages:\n print(msg)\n self.assertTrue(r.severity <= 1)\n \n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n\n def test_model2(self):\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_')\n self.assertTrue(r.severity == 0)\n\n r2 = model1.predict(data='eee')\n self.assertTrue(r2.severity == 0)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_model3(self):\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_')\n self.assertTrue(r.severity == 0)\n\n r1 = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=3)\n self.assertTrue(r1.severity == 0)\n\n r2 = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=2)\n self.assertTrue(r2.severity == 0)\n\n r3 = model1.predict(data='eee')\n self.assertTrue(r3.severity == 0)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_model4(self):\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_')\n self.assertTrue(r.severity == 0)\n\n r2 = model1.evaluate(data='eee')\n self.assertTrue(r2.severity == 0)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_model5(self):\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_')\n self.assertTrue(r.severity == 0)\n\n r1 = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=3)\n self.assertTrue(r1.severity == 0)\n\n r2 = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=2)\n self.assertTrue(r2.severity == 0)\n\n r3 = model1.evaluate(data='eee')\n self.assertTrue(r3.severity == 0)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_model6(self):\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_', save_best_weights=True)\n self.assertTrue(r.severity == 0)\n if r.severity > 0:\n for msg in r.messages:\n print(msg)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_model7(self):\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_', save_best_weights=True)\n self.assertTrue(r.severity == 0)\n\n r2 = model1.predict(data='eee', use_best_weights=True)\n self.assertTrue(r2.severity == 0)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_model8(self):\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_', save_best_weights=True)\n self.assertTrue(r.severity == 0)\n if r.severity > 0:\n for msg in r.messages:\n print(msg)\n\n r2 = model1.predict(data='eee')\n self.assertTrue(r2.severity == 0)\n if r2.severity > 0:\n for msg in r2.messages:\n print(msg)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_model9(self):\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_', save_best_weights=True)\n self.assertTrue(r.severity == 0)\n\n r2 = model1.evaluate(data='eee', use_best_weights=True)\n self.assertTrue(r2.severity == 0)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_model10(self):\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_', save_best_weights=True)\n self.assertTrue(r.severity == 0)\n\n r2 = model1.evaluate(data='eee')\n self.assertTrue(r2.severity == 0)\n\n model1.save_to_table(self.data_dir)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_model11(self):\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_', save_best_weights=True)\n self.assertTrue(r.severity == 0)\n\n r1 = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=3)\n self.assertTrue(r1.severity == 0)\n\n r2 = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=2)\n self.assertTrue(r2.severity == 0)\n\n r3 = model1.evaluate(data='eee', use_best_weights=True)\n self.assertTrue(r3.severity == 0)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_model12(self):\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_', save_best_weights=True)\n self.assertTrue(r.severity == 0)\n\n r1 = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=3)\n self.assertTrue(r1.severity == 0)\n\n r2 = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=2, save_best_weights=True)\n self.assertTrue(r2.severity == 0)\n\n r3 = model1.predict(data='eee', use_best_weights=True)\n self.assertTrue(r3.severity == 0)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_model13(self):\n model = Sequential(self.s, model_table='simple_cnn')\n model.add(InputLayer(3, 224, 224))\n model.add(Conv2d(2, 3))\n model.add(Pooling(2))\n model.add(Dense(4))\n model.add(OutputLayer(n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n model.save_to_table(self.data_dir)\n\n def test_model13a(self):\n model = Sequential(self.s, model_table='simple_cnn')\n model.add(InputLayer(3, 224, 224))\n model.add(Conv2d(2, 3))\n model.add(Pooling(2))\n model.add(Dense(4))\n model.add(OutputLayer(n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n model.save_to_table(self.data_dir)\n\n def test_model13b(self):\n model = Sequential(self.s, model_table='simple_cnn')\n model.add(layer=InputLayer(n_channels=1, height=10, width=10))\n model.add(layer=OutputLayer(n=10, full_connect=False))\n self.assertTrue(model.summary.loc[1, 'Number of Parameters'] == (0, 0))\n\n model1 = Sequential(self.s, model_table='simple_cnn')\n model1.add(layer=InputLayer(n_channels=1, height=10, width=10))\n model1.add(layer=OutputLayer(n=10, full_connect=True))\n self.assertTrue(model1.summary.loc[1, 'Number of Parameters'] == (1000, 10))\n\n model2 = Sequential(self.s, model_table='Simple_CNN')\n model2.add(layer=InputLayer(n_channels=1, height=10, width=10))\n model2.add(layer=OutputLayer(n=10, full_connect=True, include_bias=False))\n self.assertTrue(model2.summary.loc[1, 'Number of Parameters'] == (1000, 0))\n\n model3 = Sequential(self.s, model_table='Simple_CNN')\n model3.add(layer=InputLayer(n_channels=1, height=10, width=10))\n model3.add(layer=Conv2d(4, 3))\n model3.add(layer=OutputLayer(n=10))\n self.assertTrue(model3.summary.loc[2, 'Number of Parameters'] == (4000, 10))\n\n model4 = Sequential(self.s, model_table='Simple_CNN')\n model4.add(layer=InputLayer(n_channels=1, height=10, width=10))\n model4.add(layer=Conv2d(4, 3))\n model4.add(layer=OutputLayer(n=10, full_connect=False))\n self.assertTrue(model4.summary.loc[2, 'Number of Parameters'] == (0, 0))\n\n def test_model14(self):\n model = Sequential(self.s, model_table='Simple_CNN')\n model.add(layer=InputLayer(n_channels=1, height=10, width=10))\n model.add(layer=OutputLayer())\n model.summary\n\n def test_model15(self):\n model = Sequential(self.s, model_table='Simple_CNN')\n model.add(layer=InputLayer(n_channels=1, height=10, width=10))\n model.add(layer=Keypoints())\n self.assertTrue(model.summary.loc[1, 'Number of Parameters'] == (0, 0))\n\n def test_model16(self):\n model = Sequential(self.s, model_table='Simple_CNN')\n model.add(layer=InputLayer(n_channels=1, height=10, width=10))\n model.add(layer=Keypoints(n=10, include_bias=False))\n self.assertTrue(model.summary.loc[1, 'Number of Parameters'] == (1000, 0))\n\n def test_model16(self):\n model = Sequential(self.s, model_table='Simple_CNN')\n model.add(layer=InputLayer(n_channels=1, height=10, width=10))\n model.add(layer=Keypoints(n=10))\n self.assertTrue(model.summary.loc[1, 'Number of Parameters'] == (1000, 10))\n\n def test_model18(self):\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=1)\n self.assertTrue(r.severity == 0)\n\n model1.save_weights_csv(self.data_dir)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_evaluate_obj_det(self):\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path = self.data_dir + 'evaluate_obj_det_det.sashdat', task = 'load')\n\n self.s.table.loadtable(caslib = caslib,\n casout = {'name': 'evaluate_obj_det_det', 'replace': True},\n path = path)\n\n self.s.table.loadtable(caslib = caslib,\n casout = {'name': 'evaluate_obj_det_gt', 'replace': True},\n path = 'evaluate_obj_det_gt.sashdat')\n yolo_anchors = (5.9838598901098905,\n 3.4326923076923075,\n 2.184993862520458,\n 1.9841448445171848,\n 1.0261752136752136,\n 1.2277777777777779)\n yolo_model = Tiny_YoloV2(self.s, grid_number = 17, scale = 1.0 / 255,\n n_classes = 1, height = 544, width = 544,\n predictions_per_grid = 3,\n anchors = yolo_anchors,\n max_boxes = 100,\n coord_type = 'yolo',\n max_label_per_image = 100,\n class_scale = 1.0,\n coord_scale = 2.0,\n prediction_not_a_object_scale = 1,\n object_scale = 5,\n detection_threshold = 0.05,\n iou_threshold = 0.2)\n\n metrics = yolo_model.evaluate_object_detection(ground_truth = 'evaluate_obj_det_gt', coord_type = 'yolo',\n detection_data = 'evaluate_obj_det_det', iou_thresholds=0.5)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n \n def test_model_forecast1(self):\n \n import datetime\n try:\n import pandas as pd\n except:\n unittest.TestCase.skipTest(self, \"pandas not found in the libraries\") \n import numpy as np\n \n filename1 = os.path.join(os.path.dirname(__file__), 'datasources', 'timeseries_exp1.csv')\n importoptions1 = dict(filetype='delimited', delimiter=',')\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n self.table1 = TimeseriesTable.from_localfile(self.s, filename1, importoptions=importoptions1)\n self.table1.timeseries_formatting(timeid='datetime',\n timeseries=['series', 'covar'],\n timeid_informat='ANYDTDTM19.',\n timeid_format='DATETIME19.')\n self.table1.timeseries_accumlation(acc_interval='day',\n groupby=['id1var', 'id2var'])\n self.table1.prepare_subsequences(seq_len=2,\n target='series',\n predictor_timeseries=['series'],\n missing_handling='drop')\n \n valid_start = datetime.date(2015, 1, 4)\n test_start = datetime.date(2015, 1, 7)\n \n traintbl, validtbl, testtbl = self.table1.timeseries_partition(\n validation_start=valid_start, testing_start=test_start)\n \n model1 = Sequential(self.s, model_table='lstm_rnn')\n model1.add(InputLayer(std='STD'))\n model1.add(Recurrent(rnn_type='LSTM', output_type='encoding', n=15, reversed_=False))\n model1.add(OutputLayer(act='IDENTITY'))\n \n optimizer = Optimizer(algorithm=AdamSolver(learning_rate=0.01), mini_batch_size=32, \n seed=1234, max_epochs=10) \n seq_spec = Sequence(**traintbl.sequence_opt)\n result = model1.fit(traintbl, valid_table=validtbl, optimizer=optimizer, \n sequence=seq_spec, **traintbl.inputs_target)\n \n self.assertTrue(result.severity == 0)\n \n resulttbl1 = model1.forecast(horizon=1)\n self.assertTrue(isinstance(resulttbl1, CASTable))\n self.assertTrue(resulttbl1.shape[0]==15)\n \n local_resulttbl1 = resulttbl1.to_frame()\n unique_time = local_resulttbl1.datetime.unique()\n self.assertTrue(len(unique_time)==1)\n self.assertTrue(pd.Timestamp(unique_time[0])==datetime.datetime(2015,1,7))\n\n resulttbl2 = model1.forecast(horizon=3)\n self.assertTrue(isinstance(resulttbl2, CASTable))\n self.assertTrue(resulttbl2.shape[0]==45)\n \n local_resulttbl2 = resulttbl2.to_frame()\n local_resulttbl2.sort_values(by=['id1var', 'id2var', 'datetime'], inplace=True)\n unique_time = local_resulttbl2.datetime.unique()\n self.assertTrue(len(unique_time)==3)\n for i in range(3):\n self.assertTrue(pd.Timestamp(unique_time[i])==datetime.datetime(2015,1,7+i))\n \n series_lag1 = local_resulttbl2.loc[(local_resulttbl2.id1var==1) & (local_resulttbl2.id2var==1), \n 'series_lag1'].values\n \n series_lag2 = local_resulttbl2.loc[(local_resulttbl2.id1var==1) & (local_resulttbl2.id2var==1), \n 'series_lag2'].values\n \n DL_Pred = local_resulttbl2.loc[(local_resulttbl2.id1var==1) & (local_resulttbl2.id2var==1), \n '_DL_Pred_'].values\n \n self.assertTrue(np.array_equal(series_lag1[1:3], DL_Pred[0:2]))\n self.assertTrue(series_lag2[2]==DL_Pred[0]) \n\n def test_model_forecast2(self):\n \n import datetime\n try:\n import pandas as pd\n except:\n unittest.TestCase.skipTest(self, \"pandas not found in the libraries\") \n import numpy as np\n \n filename1 = os.path.join(os.path.dirname(__file__), 'datasources', 'timeseries_exp1.csv')\n importoptions1 = dict(filetype='delimited', delimiter=',')\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n self.table2 = TimeseriesTable.from_localfile(self.s, filename1, importoptions=importoptions1)\n self.table2.timeseries_formatting(timeid='datetime',\n timeseries=['series', 'covar'],\n timeid_informat='ANYDTDTM19.',\n timeid_format='DATETIME19.')\n self.table2.timeseries_accumlation(acc_interval='day',\n groupby=['id1var', 'id2var'])\n self.table2.prepare_subsequences(seq_len=2,\n target='series',\n predictor_timeseries=['series', 'covar'],\n missing_handling='drop')\n \n valid_start = datetime.date(2015, 1, 4)\n test_start = datetime.date(2015, 1, 7)\n \n traintbl, validtbl, testtbl = self.table2.timeseries_partition(\n validation_start=valid_start, testing_start=test_start)\n \n model1 = Sequential(self.s, model_table='lstm_rnn')\n model1.add(InputLayer(std='STD'))\n model1.add(Recurrent(rnn_type='LSTM', output_type='encoding', n=15, reversed_=False))\n model1.add(OutputLayer(act='IDENTITY'))\n \n optimizer = Optimizer(algorithm=AdamSolver(learning_rate=0.01), mini_batch_size=32, \n seed=1234, max_epochs=10) \n seq_spec = Sequence(**traintbl.sequence_opt)\n result = model1.fit(traintbl, valid_table=validtbl, optimizer=optimizer, \n sequence=seq_spec, **traintbl.inputs_target)\n \n self.assertTrue(result.severity == 0)\n \n resulttbl1 = model1.forecast(testtbl, horizon=1)\n self.assertTrue(isinstance(resulttbl1, CASTable))\n self.assertTrue(resulttbl1.shape[0]==testtbl.shape[0])\n \n local_resulttbl1 = resulttbl1.to_frame()\n unique_time = local_resulttbl1.datetime.unique()\n self.assertTrue(len(unique_time)==4)\n for i in range(4):\n self.assertTrue(pd.Timestamp(unique_time[i])==datetime.datetime(2015,1,7+i))\n\n resulttbl2 = model1.forecast(testtbl, horizon=3)\n self.assertTrue(isinstance(resulttbl2, CASTable))\n self.assertTrue(resulttbl2.shape[0]==45)\n \n local_resulttbl2 = resulttbl2.to_frame()\n local_resulttbl2.sort_values(by=['id1var', 'id2var', 'datetime'], inplace=True)\n unique_time = local_resulttbl2.datetime.unique()\n self.assertTrue(len(unique_time)==3)\n for i in range(3):\n self.assertTrue(pd.Timestamp(unique_time[i])==datetime.datetime(2015,1,7+i))\n \n series_lag1 = local_resulttbl2.loc[(local_resulttbl2.id1var==1) & (local_resulttbl2.id2var==1), \n 'series_lag1'].values\n \n series_lag2 = local_resulttbl2.loc[(local_resulttbl2.id1var==1) & (local_resulttbl2.id2var==1), \n 'series_lag2'].values\n \n DL_Pred = local_resulttbl2.loc[(local_resulttbl2.id1var==1) & (local_resulttbl2.id2var==1), \n '_DL_Pred_'].values\n \n self.assertTrue(np.array_equal(series_lag1[1:3], DL_Pred[0:2]))\n self.assertTrue(series_lag2[2]==DL_Pred[0]) \n\n def test_model_forecast3(self):\n \n import datetime\n try:\n import pandas as pd\n except:\n unittest.TestCase.skipTest(self, \"pandas not found in the libraries\") \n import numpy as np\n \n filename1 = os.path.join(os.path.dirname(__file__), 'datasources', 'timeseries_exp1.csv')\n importoptions1 = dict(filetype='delimited', delimiter=',')\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n self.table3 = TimeseriesTable.from_localfile(self.s, filename1, importoptions=importoptions1)\n self.table3.timeseries_formatting(timeid='datetime',\n timeseries=['series', 'covar'],\n timeid_informat='ANYDTDTM19.',\n timeid_format='DATETIME19.')\n self.table3.timeseries_accumlation(acc_interval='day',\n groupby=['id1var', 'id2var'])\n self.table3.prepare_subsequences(seq_len=2,\n target='series',\n predictor_timeseries=['series', 'covar'],\n missing_handling='drop')\n \n valid_start = datetime.date(2015, 1, 4)\n test_start = datetime.date(2015, 1, 7)\n \n traintbl, validtbl, testtbl = self.table3.timeseries_partition(\n validation_start=valid_start, testing_start=test_start)\n \n sascode = '''\n data {};\n set {};\n drop series_lag1;\n run;\n '''.format(validtbl.name, validtbl.name)\n \n self.s.retrieve('dataStep.runCode', _messagelevel='error', code=sascode)\n \n sascode = '''\n data {};\n set {};\n drop series_lag1;\n run;\n '''.format(testtbl.name, testtbl.name)\n \n self.s.retrieve('dataStep.runCode', _messagelevel='error', code=sascode)\n \n model1 = Sequential(self.s, model_table='lstm_rnn')\n model1.add(InputLayer(std='STD'))\n model1.add(Recurrent(rnn_type='LSTM', output_type='encoding', n=15, reversed_=False))\n model1.add(OutputLayer(act='IDENTITY'))\n \n optimizer = Optimizer(algorithm=AdamSolver(learning_rate=0.01), mini_batch_size=32, \n seed=1234, max_epochs=10) \n seq_spec = Sequence(**traintbl.sequence_opt)\n result = model1.fit(traintbl, optimizer=optimizer, \n sequence=seq_spec, **traintbl.inputs_target)\n \n self.assertTrue(result.severity == 0)\n \n resulttbl1 = model1.forecast(validtbl, horizon=1)\n self.assertTrue(isinstance(resulttbl1, CASTable))\n self.assertTrue(resulttbl1.shape[0]==15)\n \n local_resulttbl1 = resulttbl1.to_frame()\n unique_time = local_resulttbl1.datetime.unique()\n self.assertTrue(len(unique_time)==1)\n self.assertTrue(pd.Timestamp(unique_time[0])==datetime.datetime(2015,1,4))\n\n resulttbl2 = model1.forecast(validtbl, horizon=3)\n self.assertTrue(isinstance(resulttbl2, CASTable))\n self.assertTrue(resulttbl2.shape[0]==45)\n \n local_resulttbl2 = resulttbl2.to_frame()\n local_resulttbl2.sort_values(by=['id1var', 'id2var', 'datetime'], inplace=True)\n unique_time = local_resulttbl2.datetime.unique()\n self.assertTrue(len(unique_time)==3)\n for i in range(3):\n self.assertTrue(pd.Timestamp(unique_time[i])==datetime.datetime(2015,1,4+i))\n \n series_lag1 = local_resulttbl2.loc[(local_resulttbl2.id1var==1) & (local_resulttbl2.id2var==1), \n 'series_lag1'].values\n \n series_lag2 = local_resulttbl2.loc[(local_resulttbl2.id1var==1) & (local_resulttbl2.id2var==1), \n 'series_lag2'].values\n \n DL_Pred = local_resulttbl2.loc[(local_resulttbl2.id1var==1) & (local_resulttbl2.id2var==1), \n '_DL_Pred_'].values\n \n self.assertTrue(np.array_equal(series_lag1[1:3], DL_Pred[0:2]))\n self.assertTrue(series_lag2[2]==DL_Pred[0]) \n \n with self.assertRaises(RuntimeError):\n resulttbl3 = model1.forecast(testtbl, horizon=3)\n \n def test_load_reshape_detection(self):\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n yolo_model = Model(self.s)\n yolo_model.load(self.data_dir + 'YOLOV2_MULTISIZE.sashdat')\n model_df = self.s.fetch(table = dict(name = yolo_model.model_name,\n where = '_DLKey0_ eq \"detection1\" or _DLKey0_ eq \"reshape1\"'),\n to = 50).Fetch\n anchors_5 = model_df['_DLNumVal_'][model_df['_DLKey1_'] == 'detectionopts.anchors.8'].tolist()[0]\n self.assertAlmostEqual(anchors_5, 1.0907, 4)\n depth = model_df['_DLNumVal_'][model_df['_DLKey1_'] == 'reshapeopts.depth'].tolist()[0]\n self.assertEqual(depth, 256)\n\n def test_plot_ticks(self):\n\n model1 = Sequential(self.s, model_table='Simple_CNN1')\n model1.add(InputLayer(3, 224, 224))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Conv2d(8, 7))\n model1.add(Pooling(2))\n model1.add(Dense(16))\n model1.add(OutputLayer(act='softmax', n=2))\n\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n\n caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load')\n\n self.s.table.loadtable(caslib=caslib,\n casout={'name': 'eee', 'replace': True},\n path=path)\n\n r = model1.fit(data='eee', inputs='_image_', target='_label_', lr=0.001, max_epochs=5)\n \n # Test default tick_frequency value of 1\n ax = model1.plot_training_history()\n self.assertEqual(len(ax.xaxis.majorTicks), model1.n_epochs)\n\n # Test even\n tick_frequency = 2\n ax = model1.plot_training_history(tick_frequency=tick_frequency)\n self.assertEqual(len(ax.xaxis.majorTicks), model1.n_epochs // tick_frequency + 1)\n\n # Test odd\n tick_frequency = 3\n ax = model1.plot_training_history(tick_frequency=tick_frequency)\n self.assertEqual(len(ax.xaxis.majorTicks), model1.n_epochs // tick_frequency + 1)\n\n # Test max\n tick_frequency = model1.n_epochs\n ax = model1.plot_training_history(tick_frequency=tick_frequency)\n self.assertEqual(len(ax.xaxis.majorTicks), model1.n_epochs // tick_frequency + 1)\n \n # Test 0 \n tick_frequency = 0\n ax = model1.plot_training_history(tick_frequency=tick_frequency)\n self.assertEqual(len(ax.xaxis.majorTicks), model1.n_epochs)\n\n if (caslib is not None) and tmp_caslib:\n self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)\n\n def test_stride(self):\n model = Sequential(self.s, model_table = 'Simple_CNN_3classes_cropped')\n model.add(InputLayer(1, width = 36, height = 144, #offsets = myimage.channel_means,\n name = 'input1',\n random_mutation = 'random',\n random_flip = 'HV'))\n\n model.add(Conv2d(64, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Conv2d(64, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Conv2d(64, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Pooling(height = 2, width = 2, stride_vertical = 2, stride_horizontal = 1, pool = 'max')) # 72, 36\n\n model.add(Conv2d(128, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Conv2d(128, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Conv2d(128, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Pooling(height = 2, width = 2, stride_vertical = 2, stride_horizontal = 1, pool = 'max')) # 36*36\n\n model.add(Conv2d(256, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Conv2d(256, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Conv2d(256, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Pooling(2, pool = 'max')) # 18 * 18\n\n model.add(Conv2d(512, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Conv2d(512, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Conv2d(512, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Pooling(2, pool = 'max')) # 9 * 9\n\n model.add(Conv2d(1024, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Conv2d(1024, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Conv2d(1024, 3, 3, include_bias = False, act = 'identity'))\n model.add(BN(act = 'relu'))\n model.add(Pooling(9))\n\n model.add(Dense(256, dropout = 0.5))\n model.add(OutputLayer(act = 'softmax', n = 3, name = 'output1'))\n self.assertEqual(model.summary['Output Size'].values[-3], (1, 1, 1024))\n model.print_summary()\n # 2d print summary numerical check\n self.assertEqual(model.summary.iloc[1, -1], 2985984)\n\n def test_heat_map_analysis(self):\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, 'DLPY_DATA_DIR is not set in the environment variables')\n if not file_exist_on_server(self.s, self.data_dir + 'ResNet-50-model.caffemodel.h5'):\n unittest.TestCase.skipTest(self, \"File, {}, not found.\".format(self.data_dir\n + 'ResNet-50-model.caffemodel.h5'))\n\n from dlpy.applications import ResNet50_Caffe\n from dlpy.images import ImageTable\n\n pre_train_weight_file = os.path.join(self.data_dir, 'ResNet-50-model.caffemodel.h5')\n my_im = ImageTable.load_files(self.s, self.data_dir+'giraffe_dolphin_small')\n my_im_r = my_im.resize(width=224, inplace=False)\n\n model = ResNet50_Caffe(self.s, model_table='ResNet50_Caffe',\n n_classes=2, n_channels=3, width=224, height=224, scale=1,\n random_flip='none', random_crop='none',\n offsets=my_im_r.channel_means, pre_trained_weights=True,\n pre_trained_weights_file=pre_train_weight_file,\n include_top=False)\n model.fit(data=my_im_r, mini_batch_size=1, max_epochs=1)\n model.heat_map_analysis(data=my_im_r, mask_width=None, mask_height=None, step_size=None,\n max_display=1)\n\n self.assertRaises(ValueError, lambda:model.heat_map_analysis(mask_width=56, mask_height=56,\n step_size=8, display=False))\n\n self.assertRaises(ValueError, lambda:model.heat_map_analysis(data=my_im, mask_width=56,\n mask_height=56, step_size=8, display=False))\n\n try:\n from numpy import array\n except:\n unittest.TestCase.skipTest(self, 'numpy is not installed')\n self.assertRaises(ValueError, lambda:model.heat_map_analysis(data=array([]), mask_width=56,\n mask_height=56, step_size=8, display=False))\n\n def test_load_padding(self):\n if self.data_dir is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR is not set in the environment variables\")\n model5 = Model(self.s)\n model5.load(path = self.data_dir + 'vgg16.sashdat')\n\n def test_conv1d_model(self):\n # a model from https://blog.goodaudience.com/introduction-to-1d-convolutional-neural-networks-in-keras-for-time-sequences-3a7ff801a2cf\n Conv1D = Conv1d\n MaxPooling1D=Pooling\n model_m = Sequential(self.s)\n model_m.add(InputLayer(width=80*3, height=1, n_channels=1))\n model_m.add(Conv1D(100, 10, act='relu'))\n model_m.add(Conv1D(100, 10, act='relu'))\n model_m.add(MaxPooling1D(3))\n model_m.add(Conv1D(160, 10, act='relu'))\n model_m.add(Conv1D(160, 10, act='relu'))\n model_m.add(GlobalAveragePooling1D(dropout=0.5))\n model_m.add(OutputLayer(n=6, act='softmax'))\n # use assertEqual to check whether the layer output size matches the expected value for MaxPooling1D\n self.assertEqual(model_m.layers[3].output_size, (1, 80, 100))\n model_m.print_summary()\n # 1d print summary numerical check\n self.assertEqual(model_m.summary.iloc[1, -1], 240000)\n\n def test_load_weights_attr(self):\n model = Model(self.s)\n model.load(path=self.data_dir+'Simple_CNN1.sashdat')\n # load_weights_attr table from server; expect to be clean\n model.load_weights_attr(self.data_dir+'Simple_CNN1_weights_attr.sashdat')\n\n def test_mobilenetv2(self):\n try:\n import onnx\n from dlpy.model_conversion.onnx_transforms import (Transformer, OpTypePattern,\n ConstToInitializer,\n InitReshape, InitUnsqueeze,\n FuseMulAddBN)\n from dlpy.model_conversion.onnx_graph import OnnxGraph\n from onnx import helper, numpy_helper\n except:\n unittest.TestCase.skipTest(self, 'onnx package not found')\n\n from dlpy.model import Model\n\n if self.data_dir_local is None:\n unittest.TestCase.skipTest(self, \"DLPY_DATA_DIR_LOCAL is not set in the environment variables\")\n\n\n path = os.path.join(self.data_dir_local, 'mobilenetv2-1.0.onnx')\n\n onnx_model = onnx.load_model(path)\n model1 = Model.from_onnx_model(self.s,\n onnx_model,\n output_model_table='mobilenetv2',\n offsets=255*[0.485, 0.456, 0.406],\n norm_stds=255*[0.229, 0.224, 0.225])\n\n def test_model_crnn_bug(self):\n model = Sequential(self.s, model_table='crnn')\n model.add(InputLayer(3,256,16))\n model.add(Reshape(height=16,width=256,depth=3))\n\n model.add(Conv2d(64,3,3,stride=1,padding=1)) # size = 16x256x64\n model.add(Pooling(2,2,2)) # size = 8x128x64\n\n model.add(Conv2d(128,3,3,stride=1,padding=1)) # size = 8x128x128\n model.add(Pooling(2,2,2)) # size = 4x64x128\n\n model.add(Conv2d(256,3,3,stride=1,padding=1,act='IDENTITY')) # size = 4x64x256\n model.add(BN(act='RELU')) # size = 4x64x256\n\n model.add(Conv2d(256,3,3,stride=1,padding=1)) # size = 4x64x256\n\n\n model.add(Pooling(1,2,stride_horizontal=1, stride_vertical=2))\n\n\n\n #, padding=1)) # size = 2x64x256\n #model.add(Pooling(1,2,stride=2,stride_horizontal=1, stride_vertical=2,)) # size = 2x64x256\n\n model.add(Conv2d(512,3,3,stride=1,padding=1, act='IDENTITY')) # size = 2x64x512\n model.add(BN(act='RELU'))\n\n model.add(Conv2d(512,3,3,stride=1,padding=1)) # size = 2x64x512\n model.add(Pooling(1,2,stride_horizontal=1, stride_vertical=2)) #, padding=1)) # size = 1x64x512\n #model.add(Pooling(1,2,stride=2,stride_horizontal=1, stride_vertical=2,)) # size = 1x64x512\n\n model.add(Conv2d(512,3,3,stride=1,padding=1, act='IDENTITY')) # size = 1x64x512\n model.add(BN(act='RELU'))\n\n model.add(Reshape(order='DWH',width=64, height=512, depth=1))\n\n model.add(Recurrent(512,output_type='SAMELENGTH'))\n\n model.add(OutputLayer(error='CTC'))\n\n model.print_summary()\n\n def tearDown(self):\n # tear down tests\n try:\n self.s.terminate()\n except swat.SWATError:\n pass\n del self.s\n swat.reset_option()\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] | [
[
"numpy.array",
"numpy.transpose",
"numpy.clip"
],
[
"numpy.array",
"pandas.Timestamp",
"numpy.array_equal"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jrobertson5151/nba2 | [
"cb62ca73dc098cd7584ef5f3d7b2b50ef3fe9063"
] | [
"src/data/nba_data_player.py"
] | [
"import time\nimport requests\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport re\nfrom datetime import datetime\nimport pandas as pd\nfrom nba_driver import *\nimport numpy as np\nimport string\n\ndef get_player_soup(driver, player_id):\n soup = get_soup(driver,\n 'https://www.basketball-reference.com/players/' +\n player_id[0] + '/' + player_id + '.html')\n for t in soup.find_all('tr', attrs={'class': 'over_header'}):\n t.decompose()\n return soup\n\ndef get_player_df(soup, id_name, playoffs = False):\n if playoffs:\n id_name = 'playoffs_' + id_name\n table = soup.find('table', id=id_name)\n if table is None:\n return None\n df = pd.read_html(str(table))\n if df is None:\n return None\n df = df[0]\n df = df[df['Season'].notna()]\n #df = df[df['Season'].str.contains('-')]\n filter_empty_columns = [col for col in df if col.startswith('Unnamed')]\n df = df.drop(filter_empty_columns, axis=1)\n# if id_name != 'all_salaries' and 'Tm' in df.columns:\n# df = df[df['Tm'] != 'TOT']\n return df\n\ndef get_player_totals(soup, playoffs = False):\n return get_player_df(soup, 'totals', playoffs)\n\ndef get_player_per_game(soup, playoffs = False):\n return get_player_df(soup, 'per_game', playoffs)\n\ndef get_player_per_36(soup, playoffs = False):\n return get_player_df(soup, 'per_minute', playoffs)\n\ndef get_player_per_poss(soup, playoffs = False):\n return get_player_df(soup, 'per_poss', playoffs)\n\ndef get_player_advanced(soup, playoffs = False):\n return get_player_df(soup, 'advanced', playoffs)\n\ndef get_player_shooting(soup, playoffs = False):\n if playoffs:\n table = soup.find('table', id='playoffs_shooting')\n else:\n table = soup.find('table', id='shooting')\n if table is None:\n return None\n df = get_player_df(soup, 'shooting', playoffs)\n if df is None:\n return None\n cols = ['Season', 'Age', 'Tm', 'Lg', 'Pos', 'G', 'MP', 'FG%', 'Dist.',\n '% of 2PA', '% of 0-3', '% of 3-10', '% of 10-16', '% of 16-3pt', '% of 3P',\n '2P %FG', '0-3 %FG', '3-10 %FG', '10-16 %FG', '16-3pt%FG',\n '3P %FG', '2P % Assisted', '% of Dunks', 'Dunks Made',\n '3P % Assisted', '% of 3PA from Corner', 'Corner 3 %FG ',\n 'Heaves Attempted', 'Heaves Made']\n df.columns = cols\n# df = df[df['Tm'] != 'TOT']\n return df\n\ndef get_player_pbp(soup, playoffs = False):\n table = get_player_df(soup, 'pbp', playoffs)\n if table is None:\n return None\n table = table.fillna(value = 0) #position% is na for unplayed positions\n for c in ['PG%', 'SG%', 'SF%', 'PF%', 'C%']:\n table[c] = [int(x[:-1]) if x != 0 else 0 for x in table[c]]\n return table\n \n\ndef get_player_highs(soup, playoffs = False):\n id_name = 'year-and-career-highs'\n if playoffs:\n id_name += '-po'\n return get_player_df(soup, id_name)\n\ndef get_player_id_list(driver):\n def by_letter(letter):\n url = 'https://www.basketball-reference.com/players/' + letter +'/'\n player_page_soup = get_soup(driver, url)\n ths = player_page_soup.find_all('th', attrs={'data-append-csv': True})\n player_pairs = pd.DataFrame([(t['data-append-csv'], t.text)\n for t in ths if t.parent.td is not None],\n columns = ['player_id', 'Player'])\n if letter == 'n':\n player_table = pd.read_html(str(player_page_soup('table')[1]), parse_dates = True)[0]\n else:\n player_table = pd.read_html(str(player_page_soup.table))[0]\n player_table = player_table[player_table.Player != 'Player']\n player_table.index = player_pairs.index\n player_table = player_table.join(player_pairs, how='inner', rsuffix='2')\n player_table.set_index('player_id', inplace = True, drop=False)\n player_table.drop('Player2', axis=1, inplace=True)\n player_table = player_table.astype({'From':'int64','To':'int64', 'Wt': 'float64'})\n return player_table\n rtn = None\n for l in string.ascii_lowercase:\n print('getting ' + l)\n if l != 'x':\n rtn = pd.concat([rtn, by_letter(l)])\n time.sleep(1)\n return rtn\n \ndef get_player_bio(soup, playoffs=False):\n bio = dict()\n bio_div = soup.find('div', itemtype=\"https://schema.org/Person\")\n if bio_div is None:\n return None\n bio_p = bio_div.find_all('p')\n bio['Name'] = bio_div.h1.text\n #untested!!\n if bio['Name'][-1] == '\\*':\n bio['Name'] = bio['Name'][:-1]\n for p in bio_p:\n p_text = p.text.replace(u'\\xa0', u' ')\n p_text = p_text.replace('\\n', '')\n p_text = p_text.strip()\n if 'lb' in p_text and 'cm' in p_text:\n c = re.compile(r'(\\d)-(\\d+), (\\d+)lb \\((\\d+)cm, (\\d+)kg\\)')\n match = c.match(p_text)\n if match:\n bio['height_ft'] = int(match.group(1))\n bio['height_in'] = int(match.group(2))\n bio['weight_lb'] = int(match.group(3))\n bio['height_cm'] = int(match.group(4))\n bio['weight_kg'] = int(match.group(5))\n elif 'Born' in p_text:\n try:\n bio['date_of_birth'] = datetime.strptime(\n p.span['data-birth'], \"%Y-%m-%d\")\n except:\n pass\n elif 'Died' in p_text:\n try:\n bio['date_of_death'] = datetime.strptime(p.span['data-death'], \"%Y-%m-%d\")\n except:\n pass\n elif 'Position' in p_text:\n p_split = re.split(\"▪|:\", p_text)\n if len(p_split) > 1:\n bio['Position'] = p_split[1].strip()\n if len(p_split) > 3:\n bio['Shooting Hand'] = p_split[3].strip()\n elif '▪' in p_text:\n bio['Full Name'] = p_text.split(\"▪\")[0].strip()\n elif \"High School\" in p_text:\n continue\n elif \"Draft\" in p_text:\n p_text = p_text[7:].strip() #remove 'draft'\n match = re.search(\", (\\d+) NBA\", p_text)\n if match:\n bio['Draft Year'] = int(match.group(1))\n p_split = p_text.split(', ')\n bio['Drafting Team'] = p_split[0]\n if len(p_split) > 2:\n bio['Draft Round'] = int(p_split[1][0])\n match = re.match(\"(\\d+)\", p_split[2])\n if match:\n bio['Draft Number'] = int(match.group(1))\n else:\n p_split = p_text.split(\":\")\n if len(p_split) == 2:\n bio[p_split[0].strip()] = p_split[1].strip()\n if 'date_of_death' in bio and 'date_of_birth' in bio:\n bio['age_at_death'] = bio['date_of_death']-bio['date_of_birth']\n elif 'date_of_birth' in bio:\n bio['age'] = datetime.now() - bio['date_of_birth']\n bio_series = pd.Series(bio)\n return pd.DataFrame(data=[list(bio_series)], columns=list(bio_series.index))\n\ndef get_player_salaries(soup, playoffs=None):\n return get_player_df(soup, 'all_salaries')\n"
] | [
[
"pandas.Series",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
nienkebrinkman/Moment_tensor_inversion | [
"f26d8a5a726b9055cfd841f8bf1958a9a828ac72",
"f26d8a5a726b9055cfd841f8bf1958a9a828ac72"
] | [
"Get_Parameters.py",
"Blindtest.py"
] | [
"# ---------------------------------------------------------------------------------------------------------------------#\n# Parameters [edit manually] #\n# ---------------------------------------------------------------------------------------------------------------------#\nimport obspy\nimport numpy as np\nfrom obspy.geodetics import kilometer2degrees\nfrom obspy.geodetics.base import gps2dist_azimuth\n\nfrom Blindtest import Blindtest\n\nclass Get_Paramters:\n def specifications(self):\n ## Returns: Dict {}\n\n # Misfit options for body waves (SURFACE WAVES ALWAYS L2):\n # - 'L2' - L2_Norm\n # - 'CC' - Cross_correlation\n misfit = 'CC'\n\n # MCMC algorithm options:\n # - MCMC = 'MH' - Metropolis Hasting\n # - MCMC = 'M' - Metropolis\n MCMC = 'M'\n # - rnd_one_par = True - Updates only one random parameter each time instead of all at the same time\n # - rnd_one_par = False- Updates all parameters at the same time\n rnd_par = True\n\n # Construct the observed data:\n sdr = True # If True: invert Strike/Dip/Rake, If False: invert m_tt,m_pp,m_rr,m_tp,m_rt,m_rp\n noise = True\n plot_modus = True # If True: you make seismogram plots during your MCMC algorithm\n temperature = 1\n directory = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Final'\n npts = 2000 # The amount of samples of your seismogram\n\n # Blind test Options:\n blind = True\n\n SPEC={\n 'sdr':sdr,\n 'noise':noise,\n 'plot_modus':plot_modus,\n 'misfit':misfit,\n 'MCMC':MCMC,\n 'temperature':temperature,\n 'directory':directory,\n 'npts': npts,\n 'rnd_par':rnd_par,\n 'blind':blind}\n return SPEC\n\n\n def get_prior(self, estimated_epi=45.9233274286):\n ## Returns: Dict {}\n\n # PREDICTED VALUES:\n estimated_epi = estimated_epi # [Degrees]\n\n # SAMPLER contains all the prior information to optimize the inversion\n PRIOR = {\n 'radius':'radius',\n 'la_r': 'la_r',\n 'lo_r': 'lo_r',\n 'M0': 'Mo',\n 'network': 'network',\n 'station': 'station',\n 'filter': 'filter',\n 'freq_filter': 'freq_filter',\n 'az ': 'az',\n 'baz': 'baz',\n 'kind': 'displacement',\n 'kernelwidth': 'kernelwidth',\n 'definition': 'definition',\n 'components': 'components',\n 'alpha': 'alpha',\n 'beta': 'beta',\n 'm_ref': 'm_ref',\n 'VELOC_taup': 'VELOC_taup',\n 'VELOC': 'VELOC',\n 'noise_model': 'noise_model',\n 'strike': {'range_min': 'min', 'range_max': 'max'},\n 'dip': {'range_min': 'min', 'range_max': 'max'},\n 'rake': {'range_min': 'min', 'range_max': 'max', 'spread': 'spread'},\n 'depth': {'range_min': 'min', 'range_max': 'max', 'step': 'spread'},\n 'epi': {'range_min': 'min', 'range_max': 'max', 'spread': 'spread'},\n 'sample_number': 'sample_number',\n 'var_est': 'var_est'}\n\n # - Radius of the body used:\n PRIOR['radius'] = 3389.5 # Mars\n # PRIOR['radius'] = 6371 # Earth\n\n # -Receiver\n PRIOR['la_r'] = 4.5 # Latitude -90 <> 90\n PRIOR['lo_r'] = 136 # Longitude -180 <> 180\n PRIOR['network'] = \"7J\" # Network\n PRIOR['station'] = \"SYNT1\" # Station\n\n # -Source\n PRIOR['M0'] = 1E16 #Mw = 4.6\n PRIOR['components'] = [\"Z\", \"R\", \"T\"]\n\n # -filter\n PRIOR['filter'] = 'highpass'\n PRIOR['freq_filter'] = 1.0\n\n PRIOR['kind'] = 'displacement'\n PRIOR['kernelwidth'] = 12\n PRIOR['definition'] = 'seiscomp'\n\n # -Inversion parameters\n PRIOR['alpha'] = 10 ** (-24)\n PRIOR['beta'] = 10 ** (-23)\n PRIOR['m_ref'] = np.array([1.0000e+16, 1.0000e+16, 1.0000e+16, 1.0000e+16, 1.0000e+16])\n\n # Parameters for velocity model\n # PRIOR['VELOC'] = 'syngine://iasp91_2s'\n # PRIOR['VELOC'] = 'http://instaseis.ethz.ch/marssynthetics/C30VH-BFT13-1s'\n PRIOR['VELOC'] = 'http://instaseis.ethz.ch/blindtest_1s/EH45TcoldCrust1b_1s'\n # PRIOR['VELOC'] = \"/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Database/10s_PREM\"\n PRIOR['VELOC_taup'] = 'EH45TcoldCrust1b.npz'#'iasp91'\n\n # Model used to add noise in seismogram:\n PRIOR['noise_model'] = 'Tcompact' #'STS2' #\n\n # Sample / spread ranges for the different parameters\n PRIOR['strike']['range_min'] = 0\n PRIOR['strike']['range_max'] = 359.9\n PRIOR['dip']['range_min'] = 0\n PRIOR['dip']['range_max'] = 89.9\n PRIOR['angle_spread'] = 5\n PRIOR['rake']['range_min'] = -180\n PRIOR['rake']['range_max'] = 179.9\n PRIOR['rake']['spread'] = 5\n\n PRIOR['depth']['range_min'] = 0\n PRIOR['depth']['range_max'] = 50000\n PRIOR['depth']['spread'] = 1000\n PRIOR['epi']['range_min'] = estimated_epi - 5\n PRIOR['epi']['range_max'] = estimated_epi + 5\n PRIOR['epi']['spread'] = 1\n\n PRIOR['sample_number'] = 1000\n\n return PRIOR\n\n\n def get_unkown(self):\n ## returns Dict {}\n\n # PARAMETERS describe the unkown parameters (The ones we are going to invert)\n # !only use these to create your observed data!\n PARAMETERS = {\n 'la_s': 'la_s',\n 'lo_s': 'lo_s',\n 'depth_s': 'depth_s',\n 'strike': 'strike',\n 'dip': 'dip',\n 'rake': 'rake',\n 'm_rr': 'm_rr',\n 'm_tt': 'm_tt',\n 'm_pp': 'm_pp',\n 'm_rt': 'm_rt',\n 'm_rp': 'm_rp',\n 'm_tp': 'm_tp',\n 'epi': 'epi',\n 'origin_time': 'origin_time',}\n\n # Source parameters\n PARAMETERS['la_s'] = 10\n PARAMETERS['lo_s'] = 90\n\n PARAMETERS['depth_s'] = 10000 # [m]\n PARAMETERS['strike'] = 79 #79\n PARAMETERS['dip'] = 50#50\n PARAMETERS['rake'] = 20#20\n\n PARAMETERS['m_tt'] = 1.81e+22 # 3.81e+15\n PARAMETERS['m_pp'] = -1.74e+24 # -4.74e+17\n PARAMETERS['m_rr'] = 1.71e+24 # 4.71e+17\n PARAMETERS['m_tp'] = -1.230000e+24\n PARAMETERS['m_rt'] = 1.99e+23 # 3.99e+16\n PARAMETERS['m_rp'] = -1.05e+23 # -8.05e+16\n\n PARAMETERS['origin_time'] = obspy.UTCDateTime(2020, 1, 2, 3, 4, 5)\n\n PRIOR = self.get_prior()\n\n\n # -Greens function\n dist, az, baz = gps2dist_azimuth(lat1=PARAMETERS['la_s'],\n lon1=PARAMETERS['lo_s'],\n lat2=PRIOR['la_r'],\n lon2=PRIOR['lo_r'], a=PRIOR['radius'], f=0)\n PARAMETERS['baz'] = baz\n PARAMETERS['az'] = az\n PARAMETERS['epi'] = kilometer2degrees(dist, radius=PRIOR['radius'])\n return PARAMETERS\n",
"# Moment tensor inversion for a Blindtest dataset\n\nimport obspy\nimport instaseis\nimport os\nimport numpy as np\nfrom obspy.signal.filter import envelope\nfrom mqscatalog import filter_by_location_quality, get_phase_picks\nfrom obspy.core.event.event import Event\nfrom obspy.geodetics.base import gps2dist_azimuth\nfrom obspy.geodetics import kilometer2degrees\nfrom obspy.geodetics import degrees2kilometers\nfrom obspy.core.stream import Stream\nfrom obspy.core.trace import Trace\nimport matplotlib.pylab as plt\n\n\nclass Blindtest:\n def get_events(self,filepath_catalog):\n catalog = obspy.read_events(filepath_catalog)\n return catalog.events\n\n def get_qualityA_event(self,filepath_catalog):\n cat =obspy.read_events(filepath_catalog)\n qualityA_catalog = filter_by_location_quality(catalog=cat, quality='A')\n return qualityA_catalog.events\n\n def get_pref_origin(self,event):\n source = Event.preferred_origin(event)\n depth = source.depth\n la_s = source.latitude\n lo_s = source.longitude\n time = source.time\n return time, depth, la_s, lo_s\n\n def get_pref_scalarmoment(self,event):\n magnitude = Event.preferred_magnitude(event)\n Mw = magnitude.mag\n M = self.Magnitude2Scalarmoment(Mw)\n return M\n\n def Magnitude2Scalarmoment(self,Mw):\n M=10**(9.1 + Mw *(3.0/2.0))\n return M\n def Scalarmoment2Magnitude(self,M0):\n Mw = 2.0 / 3.0 * (np.log10(M0) - 9.1)\n return Mw\n\n def pick_sw(self,stream,pick_info,epi,prior,npts, directory,plot_modus=False):\n if plot_modus == True:\n dir_SW = directory + '/Blind_rayleigh'\n if not os.path.exists(dir_SW):\n os.makedirs(dir_SW)\n Rayleigh_st = Stream()\n Love_st = Stream()\n\n dist = degrees2kilometers(epi,prior['radius'])\n phase = 0\n for pick in pick_info:\n if pick['phase_name'] == 'R1':\n if plot_modus == True:\n dir_phases = dir_SW + '/Rayleigh_%.2f_%.2f' % (pick['lower_frequency'],pick['upper_frequency'])\n if not os.path.exists(dir_phases):\n os.makedirs(dir_phases)\n Z_trace = stream.traces[0].copy()\n if plot_modus == True:\n Z_trace.plot(outfile= dir_SW + '/Z_comp.pdf')\n Z_trace.detrend(type=\"demean\")\n if (pick['lower_frequency'] == float(0.0)) and (pick['upper_frequency'] == float(0.0)):\n pass\n else:\n Z_trace.filter('highpass', freq=pick['lower_frequency'], zerophase=True)\n Z_trace.filter('lowpass', freq=pick['upper_frequency'], zerophase=True)\n Z_trace.detrend()\n Z_trace.detrend(type=\"demean\")\n\n\n\n if plot_modus == True:\n start_vline = int(((pick['time'].timestamp-pick['lower_uncertainty'] )- Z_trace.meta.starttime.timestamp) / Z_trace.stats.delta)\n end_vline = int(((pick['time'].timestamp+pick['lower_uncertainty'])-Z_trace.meta.starttime.timestamp) / Z_trace.stats.delta)\n plt.figure()\n ax = plt.subplot(111)\n plt.plot(Z_trace.data, alpha=0.5)\n ymin, ymax = ax.get_ylim()\n plt.plot(Z_trace.data)\n plt.vlines([start_vline, end_vline], ymin, ymax)\n plt.xlabel(Z_trace.meta.starttime.strftime('%Y-%m-%dT%H:%M:%S + sec'))\n plt.tight_layout()\n plt.savefig(dir_phases + '/sw_with_Rayleigh_windows.pdf')\n # plt.show()\n plt.close()\n Period = 1.0 /pick['frequency']\n Z_trace.trim(starttime=pick['time']-Period, endtime=pick['time']+Period)\n zero_trace = Trace(np.zeros(npts),\n header={\"starttime\":pick['time']-Period , 'delta': Z_trace.meta.delta,\n \"station\": Z_trace.meta.station,\n \"network\": Z_trace.meta.network, \"location\": Z_trace.meta.location,\n \"channel\": Z_trace.meta.channel})\n total_trace = zero_trace.__add__(Z_trace, method=0, interpolation_samples=0,\n fill_value=Z_trace.data,\n sanity_checks=False)\n Rayleigh_st.append(total_trace)\n if plot_modus == True:\n plt.figure()\n plt.plot(Z_trace.data, label='%.2f_%.2f' % (pick['lower_frequency'],pick['upper_frequency']))\n plt.legend()\n plt.tight_layout()\n plt.savefig(dir_phases + '/diff_Love_freq.pdf')\n plt.close()\n\n elif pick['phase_name'] == 'G1':\n if plot_modus == True:\n dir_phases = dir_SW + '/Love_%.2f_%.2f' % (pick['lower_frequency'],pick['upper_frequency'])\n if not os.path.exists(dir_phases):\n os.makedirs(dir_phases)\n T_trace = stream.traces[2].copy()\n if plot_modus == True:\n T_trace.plot(outfile= dir_SW + '/T_comp.pdf')\n T_trace.detrend(type=\"demean\")\n if (pick['lower_frequency'] == float(0.0)) and (pick['upper_frequency'] == float(0.0)):\n pass\n else:\n T_trace.filter('highpass', freq=pick['lower_frequency'], zerophase=True)\n T_trace.filter('lowpass', freq=pick['upper_frequency'], zerophase=True)\n T_trace.detrend()\n T_trace.detrend(type=\"demean\")\n\n if plot_modus == True:\n start_vline = int(((pick['time'].timestamp-pick['lower_uncertainty'] )- T_trace.meta.starttime.timestamp) / T_trace.stats.delta)\n end_vline = int(((pick['time'].timestamp+pick['lower_uncertainty'] )- T_trace.meta.starttime.timestamp) / T_trace.stats.delta)\n plt.figure()\n ax = plt.subplot(111)\n plt.plot(T_trace.data, alpha=0.5)\n ymin, ymax = ax.get_ylim()\n plt.plot(T_trace.data)\n plt.vlines([start_vline, end_vline], ymin, ymax)\n plt.xlabel(T_trace.meta.starttime.strftime('%Y-%m-%dT%H:%M:%S + sec'))\n plt.tight_layout()\n plt.savefig(dir_phases + '/sw_with_Love_windows.pdf')\n # plt.show()\n plt.close()\n Period = 1.0 /pick['frequency']\n T_trace.trim(starttime=pick['time']-Period, endtime=pick['time']+Period)\n zero_trace = Trace(np.zeros(npts),\n header={\"starttime\":pick['time']-Period , 'delta': T_trace.meta.delta,\n \"station\": T_trace.meta.station,\n \"network\": T_trace.meta.network, \"location\": T_trace.meta.location,\n \"channel\": T_trace.meta.channel})\n total_trace = zero_trace.__add__(T_trace, method=0, interpolation_samples=0,\n fill_value=T_trace.data,\n sanity_checks=False)\n Love_st.append(total_trace)\n if plot_modus == True:\n plt.figure()\n plt.plot(T_trace.data, label='%.2f_%.2f' % (pick['lower_frequency'],pick['upper_frequency']))\n plt.legend()\n plt.tight_layout()\n plt.savefig(dir_phases + '/diff_Love_freq.pdf')\n plt.close()\n return Rayleigh_st,Love_st\n\n"
] | [
[
"numpy.array"
],
[
"matplotlib.pylab.tight_layout",
"matplotlib.pylab.vlines",
"matplotlib.pylab.subplot",
"numpy.log10",
"matplotlib.pylab.figure",
"matplotlib.pylab.plot",
"matplotlib.pylab.legend",
"matplotlib.pylab.savefig",
"numpy.zeros",
"matplotlib.pylab.close"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Halo1236/Dive-into-DL-PyTorch | [
"586b4e9ca77b2121ce5f5bec8b0a893b33f1b574"
] | [
"mytorch/3.12-l2-regularization.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\ncreated by Halo 2020/10/28 11:28\nhttps://tangshusen.me/Dive-into-DL-PyTorch/#/chapter03_DL-basics/3.12_weight-decay\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport mytorch.d2lzh_pytorch as d2l\n\nn_train, n_test, num_inputs = 20, 100, 200\ntrue_w, true_b = torch.ones(num_inputs, 1) * 0.01, 0.05\n\nfeatures = torch.randn((n_train + n_test, num_inputs))\nlabels = torch.matmul(features, true_w) + true_b\nlabels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)\n\ntrain_features, test_features = features[:n_train, :], features[n_train:, :]\ntrain_labels, test_labels = labels[:n_train], labels[n_train:]\n\n\ndef init_params():\n w = torch.randn((num_inputs, 1), requires_grad=True)\n b = torch.zeros(1, requires_grad=True)\n return [w, b]\n\n\ndef l2_penalty(w):\n return (w ** 2).sum() / 2\n\n\nbatch_size, num_epochs, lr = 1, 100, 0.003\n\nnet, loss = d2l.linreg, d2l.squared_loss\n\ndataset = torch.utils.data.TensorDataset(train_features, train_labels)\ntrain_iter = torch.utils.data.DataLoader(dataset, batch_size, shuffle=True)\n\n\ndef fit_and_plot(lambd):\n w, b = init_params()\n train_ls, test_ls = [], []\n for _ in range(num_epochs):\n for X, y in train_iter:\n l = loss(net(X, w, b), y) + lambd * l2_penalty(w)\n l = l.sum()\n\n if w.grad is not None:\n w.grad.data.zero_()\n b.grad.data.zero_()\n l.backward()\n d2l.sgd([w, b], lr, batch_size)\n train_ls.append(loss(net(train_features, w, b), train_labels).mean().item())\n test_ls.append(loss(net(test_features, w, b), test_labels).mean().item())\n d2l.semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'loss',\n range(1, num_epochs + 1), test_ls, ['train', 'test'])\n print('L2 norm of w:', w.norm().item())\n\n\n# 权重衰减可以通过优化器中的weight_decay超参数来指定。\ndef fit_and_plot_pytorch(wd):\n net = nn.Linear(num_inputs, 1)\n nn.init.normal_(net.weight, mean=0, std=1)\n nn.init.normal_(net.bias, mean=0, std=1)\n optimizer_w = torch.optim.SGD(params=[net.weight], lr=lr, weight_decay=wd) # 对权重参数衰减\n optimizer_b = torch.optim.SGD(params=[net.bias], lr=lr) # 不对偏差参数衰减\n\n train_ls, test_ls = [], []\n for _ in range(num_epochs):\n for X, y in train_iter:\n l = loss(net(X), y).mean()\n optimizer_w.zero_grad()\n\n optimizer_b.zero_grad()\n l.backward()\n\n # 对两个optimizer实例分别调用step函数,从而分别更新权重和偏差\n optimizer_w.step()\n optimizer_b.step()\n train_ls.append(loss(net(train_features), train_labels).mean().item())\n test_ls.append(loss(net(test_features), test_labels).mean().item())\n d2l.semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'loss',\n range(1, num_epochs + 1), test_ls, ['train', 'test'])\n print('L2 norm of w:', net.weight.data.norm().item())\n\n\nfit_and_plot(lambd=0)\nfit_and_plot(lambd=3)\nfit_and_plot_pytorch(0) \nfit_and_plot_pytorch(3)\n"
] | [
[
"torch.ones",
"torch.zeros",
"torch.randn",
"torch.utils.data.TensorDataset",
"torch.utils.data.DataLoader",
"torch.matmul",
"torch.nn.Linear",
"torch.nn.init.normal_",
"torch.optim.SGD"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gohar94/nums | [
"2d8b0d7dd7b48c5b56641d4f03279b5ce2185db5",
"2d8b0d7dd7b48c5b56641d4f03279b5ce2185db5",
"2d8b0d7dd7b48c5b56641d4f03279b5ce2185db5"
] | [
"tests/core/array/test_bop.py",
"nums/core/linalg.py",
"tests/core/array/test_random.py"
] | [
"# coding=utf-8\n# Copyright (C) 2020 NumS Development Team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport itertools\n\n# pylint: disable=wrong-import-order\nimport common # pylint: disable=import-error\nimport numpy as np\nimport pytest\nimport tqdm\n\nfrom nums.core.array.application import ArrayApplication\nfrom nums.core.storage.storage import BimodalGaussian\n\n\ndef test_matmul(app_inst: ArrayApplication):\n real_X, _ = BimodalGaussian.get_dataset(100, 9)\n X = app_inst.array(real_X, block_shape=(100, 1))\n X_sqr = X.T @ X\n assert np.allclose(X_sqr.get(), real_X.T @ real_X)\n\n\ndef test_matvec(app_inst: ArrayApplication):\n X = app_inst.array(np.arange(200).reshape(2, 100), block_shape=(1, 10))\n y1 = app_inst.array(np.arange(100).reshape(100, 1), block_shape=(10, 1))\n assert np.allclose((X @ y1).get(), X.get() @ y1.get())\n y2 = app_inst.array(np.arange(100).reshape(100), block_shape=(10,))\n assert np.allclose((X @ y2).get(), X.get() @ y2.get())\n # This won't trigger optimized routine, but it is rare and strange so not worth addressing.\n # TODO (hme): Apparently this is invalid. Figure out why.\n # y3 = app_inst.array(np.arange(100).reshape((100, 1, 1)), block_shape=(10, 1, 1))\n # assert np.allclose((X @ y3).get(), X.get() @ y3.get())\n\n\ndef test_vecdot(app_inst: ArrayApplication):\n size = 9\n block_size = 3\n y1 = app_inst.array(np.arange(size).reshape(size, 1), block_shape=(block_size, 1))\n y2 = app_inst.array(np.arange(size).reshape(size, 1), block_shape=(block_size, 1))\n assert np.allclose((y1.T @ y2).get(), y1.T.get() @ y2.get())\n y1 = app_inst.array(np.arange(size).reshape(size), block_shape=(block_size,))\n y2 = app_inst.array(np.arange(size).reshape(size), block_shape=(block_size,))\n assert np.allclose((y1.T @ y2).get(), y1.T.get() @ y2.get())\n y1 = app_inst.array(np.arange(size).reshape(size), block_shape=(block_size,))\n y2 = app_inst.array(np.arange(size).reshape(size, 1), block_shape=(block_size, 1))\n assert np.allclose((y1.T @ y2).get(), y1.T.get() @ y2.get())\n assert np.allclose((y2.T @ y1).get(), y2.T.get() @ y1.get())\n y1 = app_inst.array(np.arange(size).reshape(1, size), block_shape=(1, block_size))\n y2 = app_inst.array(np.arange(size).reshape(size, 1), block_shape=(block_size, 1))\n assert np.allclose((y1 @ y2).get(), y1.get() @ y2.get())\n y1 = app_inst.array(np.arange(size).reshape(1, size), block_shape=(1, block_size))\n y2 = app_inst.array(np.arange(size).reshape(1, size), block_shape=(1, block_size))\n assert np.allclose((y1 @ y2.T).get(), y1.get() @ y2.T.get())\n\n\ndef test_tensordot_basic(app_inst: ArrayApplication):\n shape = 2, 4, 10, 15\n npX = np.arange(np.product(shape)).reshape(*shape)\n rX = app_inst.array(npX, block_shape=(1, 2, 10, 3))\n rResult = rX.T.tensordot(rX, axes=1)\n assert np.allclose(rResult.get(), (np.tensordot(npX.T, npX, axes=1)))\n common.check_block_integrity(rResult)\n\n\ndef test_tensordot_large_shape(app_inst: ArrayApplication):\n a = np.arange(4 * 6 * 10 * 90).reshape((90, 10, 6, 4))\n b = np.arange(4 * 6 * 10 * 75).reshape((4, 6, 10, 75))\n c = np.tensordot(a, b, axes=1)\n\n block_a = app_inst.array(a, block_shape=(30, 5, 3, 2))\n block_b = app_inst.array(b, block_shape=(2, 3, 5, 25))\n block_c = block_a.tensordot(block_b, axes=1)\n assert np.allclose(block_c.get(), c)\n common.check_block_integrity(block_c)\n\n\[email protected]\ndef test_tensordot_all_shapes(app_inst: ArrayApplication):\n for axes in [0, 1, 2]:\n if axes == 2:\n a = np.arange(7 * 6 * 4).reshape((7, 6, 4))\n b = np.arange(6 * 4 * 9).reshape((6, 4, 9))\n c = np.tensordot(a, b, axes=axes)\n elif axes in (1, 0):\n a = np.arange(7 * 6 * 4).reshape((7, 6, 4))\n b = np.arange(6 * 4 * 9).reshape((4, 6, 9))\n c = np.tensordot(a, b, axes=axes)\n else:\n raise Exception()\n a_block_shapes = list(\n itertools.product(*list(map(lambda x: list(range(1, x + 1)), a.shape)))\n )\n b_block_shapes = list(\n itertools.product(*list(map(lambda x: list(range(1, x + 1)), b.shape)))\n )\n pbar = tqdm.tqdm(total=np.product([len(a_block_shapes), len(b_block_shapes)]))\n for a_block_shape in a_block_shapes:\n for b_block_shape in b_block_shapes:\n pbar.update(1)\n if a_block_shape[-axes:] != b_block_shape[:axes]:\n continue\n pbar.set_description(\n \"axes=%s %s @ %s\"\n % (str(axes), str(a_block_shape), str(b_block_shape))\n )\n block_a = app_inst.array(a, block_shape=a_block_shape)\n block_b = app_inst.array(b, block_shape=b_block_shape)\n block_c = block_a.tensordot(block_b, axes=axes)\n assert np.allclose(block_c.get(), c)\n common.check_block_integrity(block_c)\n\n\[email protected](scope=\"module\", params=[\"same_dim\", \"broadcasting\", \"scalars\"])\ndef bop_data(request, app_inst):\n def same_dim():\n X_shape = 6, 8\n Y_shape = 6, 8\n npX = np.random.random_sample(np.product(X_shape)).reshape(*X_shape)\n X = app_inst.array(npX, block_shape=(3, 2))\n npY = np.random.random_sample(np.product(Y_shape)).reshape(*Y_shape)\n Y = app_inst.array(npY, block_shape=(3, 2))\n return X, Y, npX, npY\n\n def broadcasting():\n X_shape = 6, 1\n Y_shape = (8,)\n npX = np.random.random_sample(np.product(X_shape)).reshape(*X_shape)\n X = app_inst.array(npX, block_shape=(3, 1))\n npY = np.random.random_sample(np.product(Y_shape)).reshape(*Y_shape)\n Y = app_inst.array(npY, block_shape=(2,))\n return X, Y, npX, npY\n\n def scalars():\n X_shape = 6, 8\n npX = np.random.random_sample(np.product(X_shape)).reshape(*X_shape)\n X = app_inst.array(npX, block_shape=(3, 2))\n npY = 0.5\n Y = app_inst.scalar(npY)\n return X, Y, npX, npY\n\n return {\n \"same_dim\": same_dim,\n \"broadcasting\": broadcasting,\n \"scalars\": scalars,\n }[request.param]()\n\n\ndef test_bops(bop_data: tuple):\n X, Y, npX, npY = bop_data\n\n # Add\n Z = X + Y\n npZ = npX + npY\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n\n # Subtract\n Z = X - Y\n npZ = npX - npY\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n\n # Multiply\n Z = X * Y\n npZ = npX * npY\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n\n # Divide\n Z = X / Y\n npZ = npX / npY\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n\n # Power\n Z = X ** Y\n npZ = npX ** npY\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n\n\[email protected](scope=\"module\", params=[\"scalar\", \"list\", \"ndarray\"])\ndef conversions_data(request, app_inst):\n X_shape = 6, 6\n npX = np.random.random_sample(np.product(X_shape)).reshape(*X_shape)\n X = app_inst.array(npX, block_shape=(3, 3))\n\n if request.param == \"scalar\":\n Y = 1.23\n elif request.param == \"list\":\n Y = list(range(6))\n elif request.param == \"ndarray\":\n Y = np.arange(6)\n else:\n raise Exception(\"impossible.\")\n\n return X, npX, Y\n\n\ndef test_conversions(conversions_data: tuple):\n X, npX, Y = conversions_data\n\n # Add\n Z = X + Y\n npZ = npX + Y\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n if isinstance(Y, np.ndarray):\n with pytest.raises(ValueError):\n Z = Y + X\n else:\n Z = Y + X\n npZ = Y + npX\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n\n # Subtract\n Z = X - Y\n npZ = npX - Y\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n if isinstance(Y, np.ndarray):\n with pytest.raises(ValueError):\n Z = Y - X\n else:\n Z = Y - X\n npZ = Y - npX\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n\n # Multiply\n Z = X * Y\n npZ = npX * Y\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n if isinstance(Y, np.ndarray):\n with pytest.raises(ValueError):\n Z = Y * X\n else:\n Z = Y * X\n npZ = Y * npX\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n\n # Divide\n Z = X / Y\n npZ = npX / Y\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n if isinstance(Y, np.ndarray):\n with pytest.raises(ValueError):\n Z = Y / X\n else:\n Z = Y / X\n npZ = Y / npX\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n\n # Power\n Z = X ** Y\n npZ = npX ** Y\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n if isinstance(Y, np.ndarray):\n with pytest.raises(ValueError):\n Z = Y ** X\n else:\n Z = Y ** X\n npZ = Y ** npX\n assert np.allclose(Z.get(), npZ)\n common.check_block_integrity(Z)\n\n\nif __name__ == \"__main__\":\n # pylint: disable=import-error\n import conftest\n\n app_inst = conftest.get_app(\"ray-cyclic\")\n test_matmul(app_inst)\n # test_matvec(app_inst)\n # test_vecdot(app_inst)\n # test_tensordot_basic(app_inst)\n # test_tensordot_large_shape(app_inst)\n # test_bops(app_inst)\n # test_conversions(conversions_data(None, app_inst))\n",
"# coding=utf-8\n# Copyright (C) 2020 NumS Development Team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport numpy as np\n\nfrom nums.core.array.application import ArrayApplication\nfrom nums.core.array.blockarray import BlockArray\nfrom nums.core.grid.grid import ArrayGrid\n\n\ndef qr(app: ArrayApplication, X: BlockArray):\n return indirect_tsqr(app, X)\n\n\ndef _qr_tree_reduce(\n app: ArrayApplication, oid_list, result_grid_entry, result_grid_shape\n):\n if len(oid_list) == 1:\n return oid_list[0][0]\n q = oid_list\n while len(q) > 1:\n a_oid, a_ge, a_gs = q.pop(0)\n b_oid, _, _ = q.pop(0)\n ge, gs = (result_grid_entry, result_grid_shape) if len(q) == 0 else (a_ge, a_gs)\n c_oid = app.cm.qr(\n a_oid,\n b_oid,\n mode=\"r\",\n axis=0,\n syskwargs={\n \"grid_entry\": ge,\n \"grid_shape\": gs,\n \"options\": {\"num_returns\": 1},\n },\n )\n q.append((c_oid, ge, gs))\n r_oid, r_ge, r_gs = q.pop(0)\n assert r_ge == result_grid_entry\n assert r_gs == result_grid_shape\n return r_oid\n\n\ndef indirect_tsr(app: ArrayApplication, X: BlockArray, reshape_output=True):\n assert len(X.shape) == 2\n # TODO (hme): This assertion is temporary and ensures returned\n # shape of qr of block is correct.\n assert X.block_shape[0] >= X.shape[1]\n # Compute R for each block.\n grid = X.grid\n grid_shape = grid.grid_shape\n shape = X.shape\n block_shape = X.block_shape\n R_oids = []\n # Assume no blocking along second dim.\n for i in range(grid_shape[0]):\n # Select a row according to block_shape.\n row = []\n for j in range(grid_shape[1]):\n row.append(X.blocks[i, j].oid)\n ge, gs = (i, 0), (grid_shape[0], 1)\n oid = app.cm.qr(\n *row,\n mode=\"r\",\n axis=1,\n syskwargs={\n \"grid_entry\": ge,\n \"grid_shape\": gs,\n \"options\": {\"num_returns\": 1},\n }\n )\n R_oids.append((oid, ge, gs))\n\n # Construct R by summing over R blocks.\n # TODO (hme): Communication may be inefficient due to redundancy of data.\n R_shape = (shape[1], shape[1])\n R_block_shape = (block_shape[1], block_shape[1])\n tsR = BlockArray(\n ArrayGrid(shape=R_shape, block_shape=R_shape, dtype=X.dtype.__name__), app.cm\n )\n tsR.blocks[0, 0].oid = _qr_tree_reduce(app, R_oids, (0, 0), (1, 1))\n\n # If blocking is \"tall-skinny,\" then we're done.\n if R_shape != R_block_shape:\n if reshape_output:\n R = tsR.reshape(R_shape, block_shape=R_block_shape)\n else:\n R = tsR\n else:\n R = tsR\n return R\n\n\ndef indirect_tsqr(app: ArrayApplication, X: BlockArray, reshape_output=True):\n shape = X.shape\n block_shape = X.block_shape\n R_shape = (shape[1], shape[1])\n R_block_shape = (block_shape[1], block_shape[1])\n tsR = indirect_tsr(app, X, reshape_output=False)\n\n # Compute inverse of R.\n tsR_inverse = inv(app, tsR)\n # If blocking is \"tall-skinny,\" then we're done.\n if R_shape != R_block_shape:\n R_inverse = tsR_inverse.reshape(R_shape, block_shape=R_block_shape)\n if reshape_output:\n R = tsR.reshape(R_shape, block_shape=R_block_shape)\n else:\n R = tsR\n else:\n R_inverse = tsR_inverse\n R = tsR\n\n Q = X @ R_inverse\n return Q, R\n\n\ndef direct_tsqr(app: ArrayApplication, X, reshape_output=True):\n assert len(X.shape) == 2\n\n # Compute R for each block.\n shape = X.shape\n grid = X.grid\n grid_shape = grid.grid_shape\n block_shape = X.block_shape\n Q_oids = []\n R_oids = []\n QR_dims = []\n Q2_shape = [0, shape[1]]\n for i in range(grid_shape[0]):\n # Select a row according to block_shape.\n row = []\n for j in range(grid_shape[1]):\n row.append(X.blocks[i, j].oid)\n # We invoke \"reduced\", so q, r is returned with dimensions (M, K), (K, N), K = min(M, N)\n M = grid.get_block_shape((i, 0))[0]\n N = shape[1]\n K = min(M, N)\n QR_dims.append(((M, K), (K, N)))\n Q2_shape[0] += K\n # Run each row on separate nodes along first axis.\n # This maintains some data locality.\n Q_oid, R_oid = app.cm.qr(\n *row,\n mode=\"reduced\",\n axis=1,\n syskwargs={\n \"grid_entry\": (i, 0),\n \"grid_shape\": (grid_shape[0], 1),\n \"options\": {\"num_returns\": 2},\n }\n )\n R_oids.append(R_oid)\n Q_oids.append(Q_oid)\n\n # TODO (hme): This pulls several order N^2 R matrices on a single node.\n # A solution is the recursive extension to direct TSQR.\n Q2_oid, R2_oid = app.cm.qr(\n *R_oids,\n mode=\"reduced\",\n axis=0,\n syskwargs={\n \"grid_entry\": (0, 0),\n \"grid_shape\": (1, 1),\n \"options\": {\"num_returns\": 2},\n }\n )\n\n Q2_shape = tuple(Q2_shape)\n Q2_block_shape = (QR_dims[0][1][0], shape[1])\n Q2 = app.vec_from_oids(\n [Q2_oid], shape=Q2_shape, block_shape=Q2_block_shape, dtype=X.dtype\n )\n # The resulting Q's from this operation are N^2 (same size as above R's).\n Q2_oids = list(map(lambda block: block.oid, Q2.blocks.flatten()))\n\n # Construct Q.\n Q = app.zeros(shape=shape, block_shape=(block_shape[0], shape[1]), dtype=X.dtype)\n for i, grid_entry in enumerate(Q.grid.get_entry_iterator()):\n Q.blocks[grid_entry].oid = app.cm.bop(\n \"tensordot\",\n Q_oids[i],\n Q2_oids[i],\n a1_T=False,\n a2_T=False,\n axes=1,\n syskwargs={\"grid_entry\": grid_entry, \"grid_shape\": Q.grid.grid_shape},\n )\n\n # Construct R.\n shape = X.shape\n R_shape = (shape[1], shape[1])\n R_block_shape = (block_shape[1], block_shape[1])\n tsR = app.vec_from_oids([R2_oid], shape=R_shape, block_shape=R_shape, dtype=X.dtype)\n # If blocking is \"tall-skinny,\" then we're done.\n if R_shape == R_block_shape or not reshape_output:\n R = tsR\n else:\n R = tsR.reshape(R_shape, block_shape=R_block_shape)\n\n if Q.shape != block_shape or not reshape_output:\n Q = Q.reshape(shape, block_shape=block_shape)\n\n return Q, R\n\n\ndef svd(app: ArrayApplication, X):\n # TODO(hme): Optimize by merging with direct qr to compute U directly,\n # to avoid wasting space storing intermediate Q.\n # This may not really help until we have operator fusion.\n assert len(X.shape) == 2\n block_shape = X.block_shape\n shape = X.shape\n R_shape = (shape[1], shape[1])\n R_block_shape = (block_shape[1], block_shape[1])\n Q, R = direct_tsqr(app, X, reshape_output=False)\n assert R.shape == R.block_shape\n R_U, S, VT = app.cm.svd(\n R.blocks[(0, 0)].oid, syskwargs={\"grid_entry\": (0, 0), \"grid_shape\": (1, 1)}\n )\n R_U: BlockArray = app.vec_from_oids([R_U], R_shape, R_block_shape, X.dtype)\n S: BlockArray = app.vec_from_oids([S], R_shape[:1], R_block_shape[:1], X.dtype)\n VT = app.vec_from_oids([VT], R_shape, R_block_shape, X.dtype)\n U = Q @ R_U\n\n return U, S, VT\n\n\ndef inv(app: ArrayApplication, X: BlockArray):\n # TODO (hme): Implement scalable version.\n block_shape = X.block_shape\n assert len(X.shape) == 2\n assert X.shape[0] == X.shape[1]\n single_block = X.shape[0] == X.block_shape[0] and X.shape[1] == X.block_shape[1]\n if single_block:\n result = X.copy()\n else:\n result = X.reshape(block_shape=X.shape)\n result.blocks[0, 0].oid = app.cm.inv(\n result.blocks[0, 0].oid, syskwargs={\"grid_entry\": (0, 0), \"grid_shape\": (1, 1)}\n )\n if not single_block:\n result = result.reshape(block_shape=block_shape)\n return result\n\n\ndef cholesky(app: ArrayApplication, X: BlockArray):\n # TODO (hme): Implement scalable version.\n # Note:\n # A = Q, R\n # A.T @ A = R.T @ R\n # A.T @ A = L @ L.T\n # => R == L.T\n block_shape = X.block_shape\n assert len(X.shape) == 2\n assert X.shape[0] == X.shape[1]\n single_block = X.shape[0] == X.block_shape[0] and X.shape[1] == X.block_shape[1]\n if single_block:\n result = X.copy()\n else:\n result = X.reshape(block_shape=X.shape)\n result.blocks[0, 0].oid = app.cm.cholesky(\n result.blocks[0, 0].oid, syskwargs={\"grid_entry\": (0, 0), \"grid_shape\": (1, 1)}\n )\n if not single_block:\n result = result.reshape(block_shape=block_shape)\n return result\n\n\ndef fast_linear_regression(app: ArrayApplication, X: BlockArray, y: BlockArray):\n assert len(X.shape) == 2\n assert len(y.shape) == 1\n block_shape = X.block_shape\n shape = X.shape\n R_shape = (shape[1], shape[1])\n R_block_shape = (block_shape[1], block_shape[1])\n Q, R = indirect_tsqr(app, X, reshape_output=False)\n R_inv = inv(app, R)\n if R_shape != R_block_shape:\n R_inv = R_inv.reshape(R_shape, block_shape=R_block_shape)\n theta = R_inv @ (Q.T @ y)\n return theta\n\n\ndef linear_regression(app: ArrayApplication, X: BlockArray, y: BlockArray):\n assert len(X.shape) == 2\n assert len(y.shape) == 1\n block_shape = X.block_shape\n shape = X.shape\n R_shape = (shape[1], shape[1])\n R_block_shape = (block_shape[1], block_shape[1])\n Q, R = direct_tsqr(app, X, reshape_output=False)\n # Invert R.\n R_inv = inv(app, R)\n if R_shape != R_block_shape:\n R_inv = R_inv.reshape(R_shape, block_shape=R_block_shape)\n theta = R_inv @ (Q.T @ y)\n return theta\n\n\ndef ridge_regression(app: ArrayApplication, X: BlockArray, y: BlockArray, lamb: float):\n assert len(X.shape) == 2\n assert len(y.shape) == 1\n assert lamb >= 0\n block_shape = X.block_shape\n shape = X.shape\n R_shape = (shape[1], shape[1])\n R_block_shape = (block_shape[1], block_shape[1])\n R = indirect_tsr(app, X)\n lamb_vec = app.array(lamb * np.eye(R_shape[0]), block_shape=R_block_shape)\n # TODO (hme): A better solution exists, which inverts R by augmenting X and y.\n # See Murphy 7.5.2.\n theta = inv(app, lamb_vec + R.T @ R) @ (X.T @ y)\n return theta\n",
"# coding=utf-8\n# Copyright (C) 2020 NumS Development Team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport warnings\n\nimport numpy as np\nfrom scipy import stats\n\nfrom nums.core.array.application import ArrayApplication\nfrom nums.core.array.blockarray import BlockArray\nfrom nums.core.array.random import NumsRandomState\n\n\n# pylint: disable=unused-variable\n\n\ndef test_basic(app_inst: ArrayApplication):\n # TODO (hme): Add more comprehensive tests for these distributions.\n\n dists = [\n (\"beta\", (1, 2, (3,), (3,))),\n (\"binomial\", (3, 0.5, (3,), (3,))),\n (\"chisquare\", (2, (3,), (3,))),\n (\"exponential\", (1.0, (3,), (3,))),\n (\"f\", (2, 1.0, (3,), (3,))),\n (\"gamma\", (2, 0.7, (3,), (3,))),\n (\"geometric\", (0.5, (3,), (3,))),\n (\"gumbel\", (0.0, 1.0, (3,), (3,))),\n (\"hypergeometric\", (3, 2, 5, (3,), (3,))),\n (\"laplace\", (0.0, 1.0, (3,), (3,))),\n (\"logistic\", (0.0, 1.0, (3,), (3,))),\n (\"lognormal\", (0.0, 1.0, (3,), (3,))),\n (\"logseries\", (0.5, (3,), (3,))),\n (\"negative_binomial\", (5, 0.5, (3,), (3,))),\n (\"noncentral_chisquare\", (2, 1.0, (3,), (3,))),\n (\"noncentral_f\", (2, 3.0, 1.0, (3,), (3,))),\n (\"pareto\", (2.0, (3,), (3,))),\n (\"poisson\", (1.0, (3,), (3,))),\n (\"power\", (2.0, (3,), (3,))),\n (\"rayleigh\", (1.0, (3,), (3,))),\n (\"standard_cauchy\", ((3,), (3,))),\n (\"standard_t\", (2, (3,), (3,))),\n (\"triangular\", (1, 3, 4, (3,), (3,))),\n (\"vonmises\", (1.0, 3.0, (3,), (3,))),\n (\"wald\", (4.0, 2.0, (3,), (3,))),\n (\"weibull\", (2.0, (3,), (3,))),\n (\"zipf\", (2.0, (3,), (3,))),\n ]\n rs = app_inst.random_state()\n for dist_name, dist_params in dists:\n assert len(rs.__getattribute__(dist_name)(*dist_params).get()) == 3\n\n\ndef test_np_random(app_inst: ArrayApplication):\n\n # Sample a single value.\n sample = app_inst.random_state(1337).random().get()\n assert sample.shape == ()\n assert isinstance(sample.item(), np.float)\n\n shape, block_shape = (15, 10), (5, 5)\n # Probably not equal if pvalue falls below this threshold.\n epsilon = 1e-2\n rs1: NumsRandomState = app_inst.random_state(1337)\n ba1: BlockArray = rs1.random(shape, block_shape)\n # The Kolmogorov–Smirnov test for arbitrary distributions.\n # Under the null hypothesis, the distributions are equal,\n # so we say distributions are neq if pvalue < epsilon.\n stat, pvalue = stats.kstest(ba1.get().flatten(), stats.uniform.cdf)\n assert pvalue > epsilon\n\n rs2: NumsRandomState = app_inst.random_state(1337)\n ba2: BlockArray = rs2.random(shape, block_shape)\n assert app_inst.allclose(ba1, ba2)\n\n rs3: NumsRandomState = app_inst.random_state(1338)\n ba3: BlockArray = rs3.random(shape, block_shape)\n assert not app_inst.allclose(ba2, ba3)\n\n # If block shape differs, so does generated arrays.\n # This is a non-issue since we don't expose block shape as a param.\n rs4: NumsRandomState = app_inst.random_state(1337)\n ba4: BlockArray = rs4.random(shape, block_shape=(6, 7)).reshape(\n block_shape=block_shape\n )\n assert not app_inst.allclose(ba2, ba4)\n\n # dtype tests.\n rs: NumsRandomState = app_inst.random_state(1337)\n ba4: BlockArray = rs.random(shape, block_shape, dtype=np.float32)\n assert ba4.dtype is np.float32\n assert str(ba4.get().dtype) == \"float32\"\n\n\ndef test_np_distributions(app_inst: ArrayApplication):\n shape, block_shape = (15, 10), (5, 5)\n epsilon = 1e-2\n rs: NumsRandomState = app_inst.random_state(1337)\n\n # Type test.\n low, high = -3.2, 5.7\n ba: BlockArray = rs.uniform(low, high, shape, block_shape, dtype=np.float32)\n assert ba.dtype is np.float32\n assert str(ba.get().dtype) == \"float32\"\n\n # Distribution test.\n cdf = lambda x: stats.uniform.cdf(x, loc=low, scale=high - low)\n stat, pvalue = stats.kstest(ba.get().flatten(), cdf)\n assert pvalue > epsilon\n # Also just confirm standard uniform distribution fails test.\n assert stats.kstest(ba.get().flatten(), stats.uniform.cdf)[1] < epsilon\n\n loc, scale = -123, 42\n ba: BlockArray = rs.normal(loc, scale, shape, block_shape)\n cdf = lambda x: stats.norm.cdf(x, loc=loc, scale=scale)\n stat, pvalue = stats.kstest(ba.get().flatten(), cdf)\n assert pvalue > epsilon\n assert stats.kstest(ba.get().flatten(), stats.norm.cdf)[1] < epsilon\n\n\ndef test_np_integer(app_inst: ArrayApplication):\n shape, block_shape = (15, 10), (5, 5)\n sample = app_inst.random_state(1337).integers(100).get()\n assert sample.shape == ()\n assert isinstance(sample.item(), np.int)\n\n rs: NumsRandomState = app_inst.random_state(1337)\n ba: BlockArray = rs.integers(-10, 20, shape, block_shape, np.int32)\n assert ba.get().dtype == \"int32\"\n arr: np.array = ba.get()\n assert -10 <= np.min(arr) <= np.max(arr) < 20\n\n\ndef test_default_random(app_inst: ArrayApplication):\n num1 = app_inst.random_state().random()\n num2 = app_inst.random_state().random()\n num_iters = 0\n max_iters = 10\n while app_inst.allclose(num1, num2) and num_iters < max_iters:\n num_iters += 1\n num2 = app_inst.random_state().random()\n if num_iters > 0:\n warnings.warn(\n \"More than one iteration required to generate unequal random numbers.\"\n )\n assert not app_inst.allclose(num1, num2)\n\n # Test default random seed.\n app_inst.random.seed(1337)\n num1 = app_inst.random.random()\n app_inst.random.seed(1337)\n num2 = app_inst.random.random()\n assert app_inst.allclose(num1, num2)\n\n\ndef test_numpy_random(app_inst: ArrayApplication):\n # Make sure the numpy version of our RNG works properly.\n # This uses the underlying RNG to generate a numpy array instead of a block array.\n # This ensures deterministic behavior when we need random numbers on the driver node.\n app_inst.random.seed(1337)\n nps_num = app_inst.random.random()\n app_inst.random.seed(1337)\n np_num = app_inst.random.numpy().random()\n assert np.allclose(nps_num.get(), np_num)\n\n\nif __name__ == \"__main__\":\n # pylint: disable=import-error\n from tests import conftest\n\n app_inst = conftest.get_app(\"serial\")\n # test_basic(app_inst)\n # test_np_random(app_inst)\n # test_np_distributions(app_inst)\n # test_np_integer(app_inst)\n # test_default_random(app_inst)\n # test_numpy_random(app_inst)\n"
] | [
[
"numpy.arange",
"numpy.product",
"numpy.tensordot"
],
[
"numpy.eye"
],
[
"numpy.max",
"scipy.stats.uniform.cdf",
"scipy.stats.norm.cdf",
"numpy.min"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ph4ge/scikit-learn-mooc | [
"a8d0feded54d987fe88480e7ade7d218be69019e",
"a8d0feded54d987fe88480e7ade7d218be69019e"
] | [
"python_scripts/trees_regression.py",
"python_scripts/trees_sol_02.py"
] | [
"# %% [markdown]\n# # Decision tree for regression\n#\n# In this notebook, we present how decision trees are working in regression\n# problems. We show differences with the decision trees previously presented in\n# a classification setting.\n#\n# First, we load the penguins dataset specifically for solving a regression\n# problem.\n\n# %% [markdown]\n# ```{note}\n# If you want a deeper overview regarding this dataset, you can refer to the\n# Appendix - Datasets description section at the end of this MOOC.\n# ```\n\n# %%\nimport pandas as pd\n\npenguins = pd.read_csv(\"../datasets/penguins_regression.csv\")\n\ndata_columns = [\"Flipper Length (mm)\"]\ntarget_column = \"Body Mass (g)\"\n\ndata_train, target_train = penguins[data_columns], penguins[target_column]\n\n# %% [markdown]\n# To illustrate how decision trees are predicting in a regression setting, we\n# will create a synthetic dataset containing all possible flipper length from\n# the minimum to the maximum of the original data.\n\n# %%\nimport numpy as np\n\ndata_test = pd.DataFrame(np.arange(data_train[data_columns[0]].min(),\n data_train[data_columns[0]].max()),\n columns=data_columns)\n\n# %% [markdown]\n# Using the term \"test\" here refers to data that was not used for training.\n# It should not be confused with data coming from a train-test split, as it\n# was generated in equally-spaced intervals for the visual evaluation of the\n# predictions.\n#\n# Note that this is methodologically valid here because our objective is to get\n# some intuitive understanding on the shape of the decision function of the\n# learned decision trees.\n#\n# However computing an evaluation metric on such a synthetic test set would\n# be meaningless since the synthetic dataset does not follow the same\n# distribution as the real world data on which the model will be deployed.\n\n# %%\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.scatterplot(data=penguins, x=\"Flipper Length (mm)\", y=\"Body Mass (g)\",\n color=\"black\", alpha=0.5)\n_ = plt.title(\"Illustration of the regression dataset used\")\n\n# %% [markdown]\n# We will first illustrate the difference between a linear model and a decision\n# tree.\n\n# %%\nfrom sklearn.linear_model import LinearRegression\n\nlinear_model = LinearRegression()\nlinear_model.fit(data_train, target_train)\ntarget_predicted = linear_model.predict(data_test)\n\n# %%\nsns.scatterplot(data=penguins, x=\"Flipper Length (mm)\", y=\"Body Mass (g)\",\n color=\"black\", alpha=0.5)\nplt.plot(data_test, target_predicted, label=\"Linear regression\")\nplt.legend()\n_ = plt.title(\"Prediction function using a LinearRegression\")\n\n\n# %% [markdown]\n# On the plot above, we see that a non-regularized `LinearRegression` is able\n# to fit the data. A feature of this model is that all new predictions\n# will be on the line.\n\n# %%\nax = sns.scatterplot(data=penguins, x=\"Flipper Length (mm)\", y=\"Body Mass (g)\",\n color=\"black\", alpha=0.5)\nplt.plot(data_test, target_predicted, label=\"Linear regression\",\n linestyle=\"--\")\nplt.scatter(data_test[::3], target_predicted[::3], label=\"Predictions\",\n color=\"tab:orange\")\nplt.legend()\n_ = plt.title(\"Prediction function using a LinearRegression\")\n\n# %% [markdown]\n# Contrary to linear models, decision trees are non-parametric models:\n# they do not make assumptions about the way data is distributed.\n# This will affect the prediction scheme. Repeating the above experiment\n# will highlight the differences.\n\n# %%\nfrom sklearn.tree import DecisionTreeRegressor\n\ntree = DecisionTreeRegressor(max_depth=1)\ntree.fit(data_train, target_train)\ntarget_predicted = tree.predict(data_test)\n\n# %%\nsns.scatterplot(data=penguins, x=\"Flipper Length (mm)\", y=\"Body Mass (g)\",\n color=\"black\", alpha=0.5)\nplt.plot(data_test, target_predicted, label=\"Decision tree\")\nplt.legend()\n_ = plt.title(\"Prediction function using a DecisionTreeRegressor\")\n\n# %% [markdown]\n# We see that the decision tree model does not have an *a priori* distribution\n# for the data and we do not end-up with a straight line to regress flipper\n# length and body mass.\n#\n# Instead, we observe that the predictions of the tree are piecewise constant.\n# Indeed, our feature space was split into two partitions. Let's check the\n# tree structure to see what was the threshold found during the training.\n\n# %%\nfrom sklearn.tree import plot_tree\n\n_, ax = plt.subplots(figsize=(8, 6))\n_ = plot_tree(tree, feature_names=data_columns, ax=ax)\n\n# %% [markdown]\n# The threshold for our feature (flipper length) is 206.5 mm. The predicted\n# values on each side of the split are two constants: 3683.50 g and 5023.62 g.\n# These values corresponds to the mean values of the training samples in each\n# partition.\n#\n# In classification, we saw that increasing the depth of the tree allowed us to\n# get more complex decision boundaries.\n# Let's check the effect of increasing the depth in a regression setting:\n\n# %%\ntree = DecisionTreeRegressor(max_depth=3)\ntree.fit(data_train, target_train)\ntarget_predicted = tree.predict(data_test)\n\n# %%\nsns.scatterplot(data=penguins, x=\"Flipper Length (mm)\", y=\"Body Mass (g)\",\n color=\"black\", alpha=0.5)\nplt.plot(data_test, target_predicted, label=\"Decision tree\")\nplt.legend()\n_ = plt.title(\"Prediction function using a DecisionTreeRegressor\")\n\n# %% [markdown]\n# Increasing the depth of the tree will increase the number of partition and\n# thus the number of constant values that the tree is capable of predicting.\n#\n# In this notebook, we highlighted the differences in behavior of a decision\n# tree used in a classification problem in contrast to a regression problem.\n",
"# %% [markdown]\n# # 📃 Solution for Exercise M5.02\n#\n# The aim of this exercise is to find out whether a decision tree\n# model is able to extrapolate.\n#\n# By extrapolation, we refer to values predicted by a model outside of the\n# range of feature values seen during the training.\n#\n# We will first load the regression data.\n\n# %%\nimport pandas as pd\n\npenguins = pd.read_csv(\"../datasets/penguins_regression.csv\")\n\ndata_columns = [\"Flipper Length (mm)\"]\ntarget_column = \"Body Mass (g)\"\n\ndata_train, target_train = penguins[data_columns], penguins[target_column]\n\n# %% [markdown]\n# ```{note}\n# If you want a deeper overview regarding this dataset, you can refer to the\n# Appendix - Datasets description section at the end of this MOOC.\n# ```\n\n# %% [markdown]\n# First, create two models, a linear regression model and a decision tree\n# regression model, and fit them on the training data. Limit the depth at\n# 3 levels for the decision tree.\n\n# %%\n# solution\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeRegressor\n\nlinear_regression = LinearRegression()\ntree = DecisionTreeRegressor(max_depth=3)\n\nlinear_regression.fit(data_train, target_train)\ntree.fit(data_train, target_train)\n\n# %% [markdown]\n# Create a synthetic dataset containing all possible flipper length from\n# the minimum to the maximum of the training dataset. Get the predictions of\n# each model using this dataset.\n\n# %%\n# solution\nimport numpy as np\n\ndata_test = pd.DataFrame(np.arange(data_train[data_columns[0]].min(),\n data_train[data_columns[0]].max()),\n columns=data_columns)\n\n# %% tags=[\"solution\"]\ntarget_predicted_linear_regression = linear_regression.predict(data_test)\ntarget_predicted_tree = tree.predict(data_test)\n\n# %% [markdown]\n# Create a scatter plot containing the training samples and superimpose the\n# predictions of both models on the top.\n\n# %%\n# solution\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.scatterplot(data=penguins, x=\"Flipper Length (mm)\", y=\"Body Mass (g)\",\n color=\"black\", alpha=0.5)\nplt.plot(data_test, target_predicted_linear_regression,\n label=\"Linear regression\")\nplt.plot(data_test, target_predicted_tree, label=\"Decision tree\")\nplt.legend()\n_ = plt.title(\"Prediction of linear model and a decision tree\")\n\n# %% [markdown] tags=[\"solution\"]\n# The predictions that we got were within the range of feature values seen\n# during training. In some sense, we observe the capabilities of our model to\n# interpolate.\n\n# %% [markdown]\n# Now, we will check the extrapolation capabilities of each model. Create a\n# dataset containing a broader range of values than your previous dataset,\n# in other words, add values below and above the minimum and the maximum of\n# the flipper length seen during training.\n\n# %%\n# solution\noffset = 30\ndata_test = pd.DataFrame(np.arange(data_train[data_columns[0]].min() - offset,\n data_train[data_columns[0]].max() + offset),\n columns=data_columns)\n\n# %% [markdown]\n# Finally, make predictions with both models on this new interval of data.\n# Repeat the plotting of the previous exercise.\n\n# %%\n# solution\ntarget_predicted_linear_regression = linear_regression.predict(data_test)\ntarget_predicted_tree = tree.predict(data_test)\n\n# %% tags=[\"solution\"]\nsns.scatterplot(data=penguins, x=\"Flipper Length (mm)\", y=\"Body Mass (g)\",\n color=\"black\", alpha=0.5)\nplt.plot(data_test, target_predicted_linear_regression,\n label=\"Linear regression\")\nplt.plot(data_test, target_predicted_tree, label=\"Decision tree\")\nplt.legend()\n_ = plt.title(\"Prediction of linear model and a decision tree\")\n\n# %% [markdown] tags=[\"solution\"]\n# The linear model will extrapolate using the fitted model for flipper lengths\n# < 175 mm and > 235 mm. In fact, we are using the model parametrization to\n# make this predictions.\n#\n# As mentioned, decision trees are non-parametric models and we observe that\n# they cannot extrapolate. For flipper lengths below the minimum, the mass of\n# the penguin in the training data with the shortest flipper length will always\n# be predicted. Similarly, for flipper lengths above the maximum, the mass of\n# the penguin in the training data with the longest flipper will always be\n# predicted.\n"
] | [
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"sklearn.tree.DecisionTreeRegressor",
"matplotlib.pyplot.title",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.plot",
"sklearn.linear_model.LinearRegression",
"sklearn.tree.plot_tree"
],
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"sklearn.tree.DecisionTreeRegressor",
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"sklearn.linear_model.LinearRegression"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
L706077/tensorflow_AlexNet | [
"3012d2455e4791c84b463b473a053f58bcf140ad"
] | [
"kaggle_mnist_alexnet_model.py"
] | [
"import tensorflow as tf\nimport ops as op\n\n\ndef input_placeholder(image_size, image_channel, label_cnt):\n with tf.name_scope('inputlayer'):\n inputs = tf.placeholder(\"float\", [None, image_size, image_size, image_channel], 'inputs')\n labels = tf.placeholder(\"float\", [None, label_cnt], 'labels')\n dropout_keep_prob = tf.placeholder(\"float\", None, 'keep_prob')\n learning_rate = tf.placeholder(\"float\", None, name='learning_rate')\n\n return inputs, labels, dropout_keep_prob, learning_rate\n\n\ndef inference(inputs, dropout_keep_prob, label_cnt):\n # todo: change lrn parameters\n # conv layer 1\n with tf.name_scope('conv1layer'):\n conv1 = op.conv(inputs, 7, 96, 3)\n conv1 = op.lrn(conv1)\n conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 1, 1, 1], padding='VALID')\n\n # conv layer 2\n with tf.name_scope('conv2layer'):\n conv2 = op.conv(conv1, 5, 256, 1, 1.0)\n conv2 = op.lrn(conv2)\n conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 1, 1, 1], padding='VALID')\n\n # conv layer 3\n with tf.name_scope('conv3layer'):\n conv3 = op.conv(conv2, 3, 384, 1)\n\n # conv layer 4\n with tf.name_scope('conv4layer'):\n conv4 = op.conv(conv3, 3, 384, 1, 1.0)\n\n # conv layer 5\n with tf.name_scope('conv5layer'):\n conv5 = op.conv(conv4, 3, 256, 1, 1.0)\n conv5 = tf.nn.max_pool(conv5, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n # fc layer 1\n with tf.name_scope('fc1layer'):\n fc1 = op.fc(conv5, 4096, 1.0)\n fc1 = tf.nn.dropout(fc1, dropout_keep_prob)\n\n # fc layer 2\n with tf.name_scope('fc2layer'):\n fc2 = op.fc(fc1, 4096, 1.0)\n fc2 = tf.nn.dropout(fc2, dropout_keep_prob)\n\n # fc layer 3 - output\n with tf.name_scope('fc3layer'):\n return op.fc(fc2, label_cnt, 1.0, None)\n\n\ndef accuracy(logits, labels):\n # accuracy\n with tf.name_scope('accuracy'):\n accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)), tf.float32))\n tf.scalar_summary('accuracy', accuracy)\n return accuracy\n\n\ndef loss(logits, labels):\n with tf.name_scope('loss'):\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, labels))\n tf.scalar_summary('loss', loss)\n return loss\n\n\ndef train_rms_prop(loss, learning_rate, decay=0.9, momentum=0.0, epsilon=1e-10, use_locking=False, name='RMSProp'):\n return tf.train.RMSPropOptimizer(learning_rate, decay, momentum, epsilon, use_locking, name).minimize(loss)\n"
] | [
[
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.train.RMSPropOptimizer",
"tensorflow.nn.max_pool",
"tensorflow.scalar_summary",
"tensorflow.placeholder",
"tensorflow.name_scope",
"tensorflow.argmax",
"tensorflow.nn.dropout"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
gegedenice/self-oa-barometre | [
"556d2ab968a3c59e300c62f238898e904c4d2054"
] | [
"app.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport base64\nimport os\nimport io\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nimport dash_table as dt\nimport dash_bootstrap_components as dbc\nfrom dash_extensions import Download\nfrom dash_extensions.snippets import send_data_frame\nimport pybso.core as core\nimport pybso.charts as charts\n#from plotly.offline import plot\nimport pandas as pd\n\nFA = \"https://use.fontawesome.com/releases/v5.12.1/css/all.css\"\nexternal_stylesheets = [dbc.themes.FLATLY,FA]\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\napp.config['suppress_callback_exceptions'] = True\n\n# STYLES\n## the style arguments for the sidebar. We use position:fixed and a fixed width\nSIDEBAR_STYLE = {\n \"position\": \"fixed\",\n \"top\": 80,\n \"left\": 0,\n \"bottom\": 0,\n \"width\": \"16rem\",\n \"padding\": \"2rem 1rem\",\n \"background-color\": \"#f8f9fa\",\n}\n## the styles for the main content position in data tab\nCONTENT_STYLE_WITH_SIDEBAR = {\n \"margin-left\": \"18rem\",\n \"margin-right\": \"2rem\",\n \"padding\": \"2rem 1rem\",\n}\n## the styles for the main content without sidebar\nCONTENT_STYLE = {\n \"margin-left\": \"2rem\",\n \"margin-right\": \"2rem\",\n \"padding\": \"2rem 1rem\",\n}\nFOOTER_STYLE = {\n \"background-color\": \"grey\",\n\n}\n# COMPONENTS VARIABLES\n## Nav item links\nnav_items = dbc.Nav(\n [\n dbc.NavLink(\"Données\", href=\"/data\", active=\"exact\"),\n dbc.NavLink(\"Visualisations\", href=\"/viz\", active=\"exact\"),\n dbc.NavLink(\"A propos\", href=\"/\", active=\"exact\"),\n ]\n)\n\n## [Unused] sidebar\nsidebar = html.Div(\n [\n html.H2(\"Menu\", className=\"display-4\"),\n html.Hr(),\n html.P(\n \"A simple sidebar layout with navigation links\", className=\"lead\"\n ),\n dbc.Nav(\n [\n dbc.NavLink(\"Data\", href=\"/data\", active=\"exact\"),\n dbc.NavLink(\"Viz\", href=\"/viz\", active=\"exact\"),\n dbc.NavLink(\"About\", href=\"/\", active=\"exact\"),\n ],\n vertical=True,\n pills=True,\n ),\n ],\n style=SIDEBAR_STYLE,\n)\n\n## navbar\nnavbar = dbc.Navbar(children=[dbc.NavbarBrand(\"Self OA Baromètre\"),nav_items], sticky=\"top\",color=\"primary\",dark=True,)\n## footer\nfooter = dbc.Row(\n [\n html.P(\n [\n html.Span('Géraldine Geoffroy', className='mr-4'), \n html.A(html.I(className='fas fa-envelope-square mr-1'), href='mailto:[email protected]'), \n html.A(html.I(className='fab fa-github-square mr-1'), href='https://github.com/gegedenice'), \n ], \n className='lead',\n )\n ],justify=\"center\",align=\"center\",style=FOOTER_STYLE,)\n\n# COMPONENTS FUNCTIONS\n## drag&drop upload div\ndef render_upload(id):\n return dcc.Upload(\n id=id,\n children=html.Div(\n [\"Glisser-déposer ou cliquer pour importer un fichier au format csv (séparateur indifférent), json ou Excel\"]\n ),\n style={\n \"width\": \"100%\",\n \"height\": \"60px\",\n \"lineHeight\": \"60px\",\n \"borderWidth\": \"1px\",\n \"borderStyle\": \"dashed\",\n \"borderRadius\": \"5px\",\n \"textAlign\": \"center\",\n \"margin\": \"10px\",\n },\n multiple=True,\n )\n## datatable\ndef render_datatable(id):\n return html.Div(dt.DataTable(\n id=id,\n sort_action=\"native\",\n sort_mode=\"multi\",\n page_action=\"native\",\n page_current=0,\n page_size=10,\n style_table={'overflowX': 'auto'},\n style_header={'backgroundColor': 'rgb(30, 30, 30)'},\n style_cell={\n 'backgroundColor': 'rgb(50, 50, 50)',\n 'color': 'white',\n 'textAlign': 'left',\n 'overflow': 'hidden',\n 'textOverflow': 'ellipsis',\n 'minWidth': '180px', 'width': '180px', 'maxWidth': '180px',},\n #export_format=\"csv\",\n )\n )\n## card for chart\ndef render_graph_card(id,title):\n return dbc.Card(\n [\n dbc.CardHeader(title),\n dbc.CardBody(\n [\n dcc.Graph(id=id),\n ]\n ),\n dbc.CardFooter(\n\n ),\n ],\n color=\"primary\", inverse=True\n)\n\n# PAGES CONTENT\n## about page \nabout_content = html.Div([html.H3(\"A propos de cette application\"),\n html.Hr(),\n dcc.Markdown('''\n\nCette application est un exemple d'implémentation du package Python [pybso](https://pypi.org/project/pybso/) dans une application web.\nElle permet de construire un baromètre de Science ouverte local avec son propre corpus de DOI, sur le modèle du baromètre national. \n\nLa page [Données](/data) propose d'importer votre fichier source de DOI et de \n- moissonner les caractéristiques OA de chaque DOI via l'API d'Unpaywall. Le résultat renvoie votre fichier en entrée augmenté des données suivantes :\n - données Unpaywall brutes : \"title\", \"genre\" (type de publication), \"published_date\", \"year\", \"journal_name\", \"journal_issn_l\" ,\"journal_is_oa\" , \"journal_is_in_doaj\" ,\"publisher\" ;\n - données reconstruites (voir la [documentation du package]()): \n - \"is_oa_normalized\" : Accès ouvert / Accès fermé\n - \"oa_status_normalized\" : Green, Gold, Bronze, Hybrid\n - \"oa_host_type_normalized\" : Archive ouverte, Editeur, Editeur et archive ouverte\n - \"oa_host_domain\" : les noms de domaines concaténés de tous les plateformes d'hébergement du document\n- récupérer si vous le souhaitez les noms des éditeurs plus homogénéisés en interrogeant [l'API Crossref prefixes]. Le résultat renvoie votre fichier en entrée augmenté des données suivantes :\n - \"doi_prefix\"\n - \"publisher_by_doiprefix\" : le libellé éditeur obtenu à partir des préfixes de DOI\n- télécharger vos résultats en format csv, Json ou Excel.\n\nUne fois les données OA récupérées, la page [Visualisations](/viz) permet d'importer à son tour votre fichier résultat et affiche les graphiques du baromètre.\n\nCette application est réalisée avec le framework Python d'application web Dash, qui est lui-même construit sur Flask, Plotly et React.\n\nPour une installation en local, le code source est accessible ici : [https://github.com/gegedenice/self-oa-barometre](https://github.com/gegedenice/self-oa-barometre)\n'''),])\n## data harvest page\ndata_content = html.Div([html.H3(\"Obtenir les données OA\"),\n html.Hr(),\n dbc.Row(\n [\n dbc.Col(\n html.H4(\"1. Importer un fichier de DOI\"),\n width={\"size\": 9},\n ),\n dbc.Col(\n dbc.Col(dbc.Button(\"Effacer\",color=\"danger\",block=True,id=\"reset\",className=\"mb-3\",href=\"/data\")),\n width={\"size\": 3},\n ),\n ]),\n dbc.FormGroup(\n [#dbc.Label(\"Upload source file\", html_for=\"upload-data\"),\n render_upload(\"upload-data\"),\n dbc.FormText(\n \"Le fichier peut contenir plusieurs colonnes/entrées mais doit avoir au minimum une colonne/entrée de DOI avec l'en-tête 'doi'\",\n color=\"secondary\",\n )\n ]),\n html.Div(id=\"import-error\"),\n render_datatable(\"table-data\"),\n html.Hr(),\n html.H4(\"2. Enrichir les données\"),\n dbc.Row([\n dbc.Button(\"Avec les données OA d'Unpaywall\",color=\"primary\",block=True,id=\"unpaywall_button\",className=\"mb-3\",n_clicks=0),\n ]),\n dbc.Row([html.P(\"OU\")], align=\"center\", justify=\"center\",className=\"h-50\"),\n dbc.Row([\n dbc.Col(dbc.Input(id=\"email\", placeholder=\"Entrer une adresse mail valide...\", type=\"email\"),width=6),\n dbc.Col(dbc.Button(\"Avec les libellés éditeurs de Crossref\",color=\"primary\",block=True,id=\"crossref_button\",className=\"mb-3\"),width=6),\n ]),\n #html.Div(id='intermediate-source-value', style={'display': 'none'}),\n dcc.Store(id=\"intermediate-source-value\"),\n html.Hr(),\n html.H4(\"3. Sauvegarder les résultats\"),\n dbc.Spinner(html.Div(id=\"loading\",\n children=[render_datatable(\"table-result\"),\n #html.Div(id='intermediate-result-value', style={'display': 'none'}),\n dcc.Store(id=\"intermediate-result-value\"),\n dbc.Button(\"Download CSV\", id=\"csvdownload\", color=\"success\", className=\"mr-1\",n_clicks_timestamp='0'),\n dbc.Button(\"Download Excel\", id=\"xlsdownload\", color=\"success\", className=\"mr-1\",n_clicks_timestamp='0'),\n dbc.Button(\"Download Json\", id=\"jsondownload\", color=\"success\", className=\"mr-1\",n_clicks_timestamp='0'),\n Download(id=\"download\")]),\n color=\"primary\",\n )\n ])\n## charts page\nviz_content = html.Div([html.H3(\"Visualisations du baromètre\"),\n html.Hr(),\n dbc.Row(\n [\n dbc.Col(\n dbc.FormGroup(\n [#dbc.Label(\"Upload source file\", html_for=\"upload-data\"),\n render_upload(\"data-all-charts\"),\n dbc.FormText(\n \"Importer un fichier avec les données issues d'Unpaywall. La mention éditeur de Crossref est facultative.\",\n color=\"secondary\",\n )]\n ),\n width={\"size\": 9},\n ),\n dbc.Col(\n dbc.Col(dbc.Button(\"Effacer\",color=\"danger\",block=True,id=\"reset\",className=\"mb-3\",href=\"/viz\")),\n width={\"size\": 3},\n ),\n ]),\n html.Hr(),\n dbc.Row(\n [\n dbc.Col(children=[render_graph_card(\"oa_rate\",\"Proportion des publications en accès ouvert\")],width=12),\n ]\n ),\n html.Hr(),\n dbc.Row(\n [\n dbc.Col(children=[render_graph_card(\"oa_rate_by_year\",\"Evolution du taux d'accès ouvert aux publications\")],width=12),\n ]\n ),\n html.Hr(),\n dbc.Row(\n [\n dbc.Col(children=[render_graph_card(\"oa_by_status\",\"Part Open Access : Evolution du type d'accès ouvert\")],width=6),\n dbc.Col(children=[render_graph_card(\"oa_rate_by_type\",\"Répartition des publications par type de publications et par accès\")],width=6),\n ]\n ),\n html.Hr(),\n dbc.Row(\n [ dbc.Col(\n dbc.FormGroup([\n dbc.Label(\"Source du libellé éditeur\", html_for=\"pub_source\"),\n dbc.RadioItems(options=[\n {\"label\": \"Unpaywall\", \"value\": \"publisher\"},\n {\"label\": \"Crossref (valeurs normalisées)\", \"value\": \"publisher_by_doiprefix\"}],\n value=\"publisher\",\n id=\"pub_source\",\n inline=True)]), width=4),\n dbc.Col(\n dbc.FormGroup([\n dbc.Label(\"Nombre d'éditeurs à afficher : \", html_for=\"n_select\"),\n html.Span(id='slider-output'),\n dcc.Slider(id=\"n_select\", min=1, max=20, step=1, marks={\n 1: '1',\n 5: '5',\n 10: '10',\n 15: '15',\n 20: '20'\n },value=10),\n ]), width=6)\n ]\n ),\n dbc.Row(dbc.Col(children=[render_graph_card(\"oa_rate_by_publisher\",\"Taux d'accès ouvert aux publications par éditeur\")],width=12))\n ])\n\n# LAYOUT\ncontent = html.Div(id=\"page-content\", style=CONTENT_STYLE)\napp.layout = dbc.Container([navbar,dcc.Location(id=\"url\"), content,footer],fluid=True) \n\n# CALLBACKS\[email protected](Output(\"page-content\", \"children\"), [Input(\"url\", \"pathname\")])\ndef render_page_content(pathname):\n if pathname == \"/\":\n return about_content\n elif pathname == \"/data\":\n return data_content\n elif pathname == \"/viz\":\n return viz_content\n # If the user tries to reach a different page, return a 404 message\n return dbc.Jumbotron(\n [\n html.H1(\"404: Non trouvée\", className=\"text-danger\"),\n html.Hr(),\n html.P(f\"L'url {pathname} n'est pas reconnue...\"),\n ]\n )\n\[email protected](Output('table-data', 'columns'),\n Output('table-data', 'data'),\n Output('intermediate-source-value', 'data'),\n Output('import-error','children'),\n [Input('upload-data', 'contents'),\n Input('upload-data', 'filename')],\n prevent_initial_call=True)\ndef update_table(contents, filename):\n if contents is not None:\n content_type, content_string = contents[0].split(',')\n decoded = base64.b64decode(content_string)\n try:\n if 'csv' in filename[0]:\n df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))\n elif (('xlsx' in filename[0]) | ('xls' in filename[0])):\n df = pd.read_excel(io.BytesIO(decoded))\n elif 'json' in filename[0]:\n df = pd.read_json(io.StringIO(decoded.decode('utf-8')))\n try:\n if df['doi'].isnull().sum() != 0:\n return None,None,None,dbc.Alert(\"Votre fichier contient des DOI vides !\", color=\"danger\")\n except:\n pass\n columns = [{\"name\": i, \"id\": i} for i in df.columns]\n data = df.to_dict('records')\n return columns, data, df.to_json(),None\n except Exception as e:\n print(e)\n return None,None,None,dbc.Alert(\"Le format de fichier n'est pas valide !\", color=\"danger\")\n\[email protected](\n Output('table-result', 'columns'),\n Output('table-result', 'data'),\n Output('intermediate-result-value', 'data'),\n [Input('unpaywall_button', 'n_clicks'),Input('crossref_button', 'n_clicks'),Input('email', 'value')],\n [State(\"intermediate-source-value\", \"data\")],\n prevent_initial_call=True)\ndef get_result(n_upw_clicks,n_crf_clicks,email,data):\n if n_upw_clicks != 0:\n dff = pd.read_json(data)\n df_result = core.unpaywall_data(dataframe=dff)\n columns = [{\"name\": i, \"id\": i} for i in df_result.columns]\n data = df_result.to_dict('records')\n return columns, data, df_result.to_json()\n if n_crf_clicks != None:\n dff = pd.read_json(data)\n df_result = core.crossref_publisher_data(dataframe=dff,email=email)\n columns = [{\"name\": i, \"id\": i} for i in df_result.columns]\n data = df_result.to_dict('records')\n return columns, data, df_result.to_json()\n\[email protected](Output('oa_rate', 'figure'),\n Output('oa_rate_by_year', 'figure'),\n Output('oa_by_status', 'figure'),\n Output('oa_rate_by_type', 'figure'),\n Output('oa_rate_by_publisher', 'figure'),\n Output('slider-output', 'children'),\n [Input('data-all-charts', 'contents'),\n Input('data-all-charts', 'filename'),\n Input('pub_source', 'value'),\n Input('n_select', 'value'),],\n prevent_initial_call=True)\ndef all_charts(contents, filename,pub_value,n_value):\n if contents is not None:\n content_type, content_string = contents[0].split(',')\n decoded = base64.b64decode(content_string)\n try:\n if 'csv' in filename[0]:\n df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))\n if (('xls' in filename[0]) | (\"xlsx\" in filename[0])):\n df = pd.read_excel(io.BytesIO(decoded))\n if 'json' in filename[0]:\n df = pd.read_json(io.StringIO(decoded.decode('utf-8')))\n return charts.oa_rate(dataframe=df),charts.oa_rate_by_year(dataframe=df),charts.oa_by_status(dataframe=df),charts.oa_rate_by_type(dataframe=df),charts.oa_rate_by_publisher(dataframe=df,publisher_field=pub_value,n=int(n_value)),n_value\n except Exception as e:\n print(e)\n return dbc.Alert(\"Le format de fichier n'est pas valide !\", color=\"danger\"),None,None,None,None,n_value\n\[email protected](Output(\"download\", \"data\"), \n [Input(\"csvdownload\", \"n_clicks_timestamp\"),\n Input(\"xlsdownload\", \"n_clicks_timestamp\"),\n Input(\"jsondownload\", \"n_clicks_timestamp\")], \n [State(\"intermediate-result-value\", \"data\")],\n prevent_initial_call=True)\ndef download_table(csvdownload, xlsdownload,jsondownload, data):\n df = pd.read_json(data,orient=\"records\")\n if int(csvdownload) > int(xlsdownload) and int(csvdownload) > int(jsondownload):\n return send_data_frame(df.to_csv, \"data.csv\", index=False)\n elif int(xlsdownload) > int(csvdownload) and int(xlsdownload) > int(jsondownload):\n return send_data_frame(df.to_excel, r\"data.xlsx\", index=False)\n elif int(jsondownload) > int(csvdownload) and int(jsondownload) > int(xlsdownload):\n return send_data_frame(df.to_json, \"data.json\", orient=\"records\")\n\nif __name__ == \"__main__\":\n app.run_server(debug=True)"
] | [
[
"pandas.read_json"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
oleurud/aipnd-project | [
"48049e8d30b4c4613884fee8ffebad4a7fdd0bdb"
] | [
"load_data.py"
] | [
"import torch\nfrom torchvision import datasets, transforms\n\n\ntrain_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])])\n\ntest_validation_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])])\n\ndef _get_train_data(data_dir):\n return datasets.ImageFolder(data_dir + '/train', transform=train_transforms)\n\ndef get_train_class_to_idx(data_dir):\n train_data = _get_train_data(data_dir) \n return train_data.class_to_idx\n\ndef get_trainloader(data_dir):\n train_data = _get_train_data(data_dir)\n return torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)\n \ndef get_validationloader(data_dir):\n validation_data = datasets.ImageFolder(data_dir + '/valid', transform=test_validation_transforms)\n return torch.utils.data.DataLoader(validation_data, batch_size=32, shuffle=True)\n\ndef get_testloader(data_dir):\n test_data = datasets.ImageFolder(data_dir + '/test', transform=test_validation_transforms)\n return torch.utils.data.DataLoader(test_data, batch_size=32)\n"
] | [
[
"torch.utils.data.DataLoader"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SupermeLC/PyNeval | [
"2cccfb1af7d97857454e9cbc3515ba75e5d8d4b0"
] | [
"pyneval/metric/utils/klib/glib/Inputer.py"
] | [
"import glob\nimport os\nimport numpy as np\nfrom scipy import ndimage\nfrom PIL import Image\nimport tensorflow as tf\nfrom LabelDefinition import class_d_label\nimport cv2\nimport TiffFile\nimport pims\n\ndef readImageAndLabelFromFolders(paths,\n number=None,\n resized=False,\n new_shape=None):\n '''readImageAndLabelFromFolders\n Args:\n paths (list): List of path.\n number (list): Number of data.\n resized (bool): Whether resize.\n new_shape (2d tuple): New shape if resize.\n Returns:\n images (ndarray): Numpy array 2d image matrix.\n labels (ndarray): Numpy array of int.\n shapes (ndarray): Numpy array of 3d tuple.\n '''\n all_images = []\n all_labels = []\n all_shapes = []\n shapeset = set()\n\n for idx, p in enumerate(paths):\n images, labels, shapes, shape_set = readImageAndLabel(p,\n number=None,\n resized=False,\n new_shape=None)\n print(shape_set)\n if len(shape_set)!=1:\n print('More than two image shapes, exit...')\n quit(code=-1)\n\n all_images.append(images)\n all_labels.append(labels)\n all_shapes.append(shapes)\n shapeset.add(shape_set.pop())\n\n print(shapeset)\n if len(shapeset)!=1:\n print('More than two image shapes, exit...')\n quit(code=-1)\n actual_shape = shapeset.pop()\n\n ret_images = np.array([], np.uint8).reshape(0, actual_shape[0], actual_shape[1], actual_shape[2])\n ret_labels = np.array([], np.uint32)\n ret_shapes = np.array([], np.int64).reshape(0,3)\n\n # import pdb\n # pdb.set_trace()\n for a,b,c in zip(all_images, all_labels, all_shapes):\n ret_images = np.concatenate((ret_images, a), axis=0)\n ret_labels = np.concatenate((ret_labels, b), axis=0)\n ret_shapes = np.concatenate((ret_shapes, c), axis=0)\n\n return ret_images, ret_labels, ret_shapes, shapeset\n\ndef readImageAndLabelFromFolders3D(paths,\n number=None):\n '''readImageAndLabelFromFolders\n Args:\n paths (list): List of path.\n number (list): Number of data.\n resized (bool): Whether resize.\n new_shape (2d tuple): New shape if resize.\n Returns:\n images (ndarray): Numpy array 2d image matrix.\n labels (ndarray): Numpy array of int.\n shapes (ndarray): Numpy array of 3d tuple.\n '''\n all_images = []\n all_labels = []\n all_shapes = []\n shapeset = set()\n\n for idx, p in enumerate(paths):\n images, labels, shapes, shape_set = readImageAndLabel3D(p,number)\n print(shape_set)\n if len(shape_set)!=1:\n print('More than two image shapes, exit...')\n quit(code=-1)\n\n all_images.append(images)\n all_labels.append(labels)\n all_shapes.append(shapes)\n shapeset.add(shape_set.pop())\n\n print(shapeset)\n if len(shapeset)!=1:\n print('More than two image shapes, exit...')\n quit(code=-1)\n actual_shape = shapeset.pop()\n\n ret_images = np.array([], np.uint8).reshape(0,\n actual_shape[0],\n actual_shape[1],\n actual_shape[2],\n actual_shape[3])\n ret_labels = np.array([], np.uint32)\n ret_shapes = np.array([], np.int64).reshape(0,4)\n\n for a,b,c in zip(all_images, all_labels, all_shapes):\n ret_images = np.concatenate((ret_images, a), axis=0)\n ret_labels = np.concatenate((ret_labels, b), axis=0)\n ret_shapes = np.concatenate((ret_shapes, c), axis=0)\n\n return ret_images, ret_labels, ret_shapes, shapeset\n\ndef readImageAndLabel(path, number=None,\n resized=False, new_shape=None):\n '''read images and return image and label array\n '''\n\n # directories = glob.glob(os.path.join(path, '*'))\n # class_names = [os.path.basename(directory) for directory in directories]\n # class_names.sort()\n # num_classes = len(class_names)\n\n file_paths = glob.glob(os.path.join(path, '*/*'))\n # file_paths = sorted(file_paths,\n # key=lambda filename:os.path.basename(filename).split('.')[0])\n np.random.shuffle(file_paths)\n\n images = []\n labels = []\n shapes = []\n shape_set = set()\n for file_name in file_paths[:number]:\n im = Image.open(file_name)\n if resized:\n im = im.resize(new_shape)\n\n im = np.asarray(im, np.uint8)\n if len(im.shape) == 2:\n im = im.reshape(im.shape[0], im.shape[1], 1)\n images.append(im)\n\n im_shape = im.shape\n shapes.append(im_shape) # tuple of 3\n if im_shape not in shape_set:\n shape_set.add(im_shape)\n # image_name = os.path.basename(file_name).split('.')[0]\n\n class_name = os.path.basename(os.path.dirname(file_name))\n label_num = class_d_label[class_name]\n labels.append(np.asarray(label_num, np.uint32))\n\n images = np.array(images)\n labels = np.array(labels)\n shapes = np.array(shapes)\n print('shape set: ', shape_set)\n return images, labels, shapes, shape_set\n\n\ndef readImageAndLabel3D(path, number=None):\n '''read images and return image and label array 3D\n '''\n file_paths = glob.glob(os.path.join(path, '*/*'))\n np.random.shuffle(file_paths)\n\n images = []\n labels = []\n shapes = []\n shape_set = set()\n for file_name in file_paths[:number]:\n im = TiffFile.imread(file_name)\n # im = pims.open(file_name)\n # im = np.asarray(im, np.uint8)\n\n if len(im.shape) == 3:\n im = im.reshape(im.shape[0], im.shape[1], im.shape[2], 1)\n images.append(im)\n\n im_shape = im.shape\n shapes.append(im_shape) # tuple of 4\n if im_shape not in shape_set:\n shape_set.add(im_shape)\n\n class_name = os.path.basename(os.path.dirname(file_name))\n label_num = class_d_label[class_name]\n labels.append(np.asarray(label_num, np.uint32))\n\n images = np.array(images)\n labels = np.array(labels)\n shapes = np.array(shapes)\n print('shape set: ', shape_set)\n return images, labels, shapes, shape_set\n\ndef inputPipeline(filenames,\n batch_size,\n num_epochs,\n num_threads,\n old_shape,\n do_train,\n normalize=False,\n resize_type=0,\n new_shape=None):\n ''' The input pipeline for TensorFlow graph\n '''\n filename_queue = tf.train.string_input_producer(\n filenames, num_epochs=num_epochs, shuffle=True)\n if len(old_shape)==3:\n print('*'*20,'2D inputPipeline', '*'*20)\n example, label = _readImagesFromTFRecordsFile(filename_queue,\n old_shape,\n normalize,\n do_train, # train vs eval, diff preprocess\n resize_type,\n new_shape)\n else:\n print('*'*20,'3D inputPipeline', '*'*20)\n example, label = _readImagesFromTFRecordsFile3D(filename_queue,\n old_shape,\n normalize,\n do_train, # train vs eval, diff preprocess\n resize_type,\n new_shape)\n # min_after_dequeue defines how big a buffer we will randomly sample\n # from -- bigger means better shuffling but slower start up and more\n # memory used.\n # capacity must be larger than min_after_dequeue and the amount larger\n # determines the maximum we will prefetch. Recommendation:\n # min_after_dequeue + (num_threads + a small safety margin) * batch_size\n min_after_dequeue = 1000\n capacity = min_after_dequeue + (num_threads+3) * batch_size\n example_batch, label_batch = \\\n tf.train.shuffle_batch([example, label],\n batch_size=batch_size,\n num_threads=num_threads,\n capacity=capacity,\n # Ensures a minimum amount of shuffling\n min_after_dequeue=min_after_dequeue,\n name='batching_shuffing')\n return example_batch, label_batch\n\ndef _readImagesFromTFRecordsFile(filename_queue,\n old_shape,\n normalize,\n do_train,\n resize_type,\n new_shape):\n\n reader = tf.TFRecordReader()\n key, serialized_example = reader.read(filename_queue)\n\n features = tf.parse_single_example(serialized_example,\n features={'image_raw': tf.FixedLenFeature([], tf.string),\n 'label': tf.FixedLenFeature([], tf.int64)\n })\n\n image = tf.decode_raw(features['image_raw'], tf.uint8)\n image = tf.cast(image, tf.float32)\n label = tf.cast(features['label'], tf.int32)\n image = tf.reshape(image, old_shape)\n image.set_shape(old_shape)\n print('original image shape: ', image.get_shape())\n\n if resize_type == 1: # resize_type default 0, do nothing\n image = tf.image.rgb_to_grayscale(image)\n image = tf.image.crop_to_bounding_box(image, 0, 55, 223, 223)\n image = tf.image.resize_images(image, [new_shape[0], new_shape[1]])\n image = tf.reshape(image, new_shape)\n elif resize_type == 2:\n ''' Random crop 40by40 to 32by32\n Image is default gray\n '''\n # offset_height = np.random.randint(0, 9)\n # offset_width = np.random.randint(0, 9)\n # image = tf.image.crop_to_bounding_box(image,\n # offset_height,\n # offset_width,\n # new_shape[0],\n # new_shape[1])\n image = tf.image.crop_to_bounding_box(image,\n 0,\n 0,\n new_shape[0],\n new_shape[1])\n # print 'TensorFlow random crop'\n # image = tf.random_crop(image, (32, 32, 1))\n image = tf.reshape(image, new_shape)\n elif resize_type == 3:\n # image = tf.image.resize_images(image, [new_shape[0], new_shape[1]])\n # image = tf.image.crop_to_bounding_box(image,\n # 7,\n # 0,\n # new_shape[0],\n # new_shape[1])\n\n print( 'TensorFlow random crop')\n image = tf.random_crop(image, (32, 32, 1))\n image = tf.image.random_flip_up_down(image)\n image = tf.image.random_flip_left_right(image)\n if do_train:\n image = tf.image.random_brightness(image,max_delta=63)\n image = tf.image.random_contrast(image,lower=0.2, upper=1.8)\n image = tf.reshape(image, new_shape)\n\n print('new image shape: ', image.get_shape())\n print('label shape: ', label.get_shape())\n\n processed_example = image\n return processed_example, label\n\ndef preprocess(array):\n # swap_axises = tf.constant([0,1,2])\n # c = tf.random_shuffle(c)\n return ndimage.rotate(array, 45)\n\ndef _readImagesFromTFRecordsFile3D(filename_queue,\n old_shape,\n normalize,\n do_train,\n resize_type,\n new_shape):\n\n reader = tf.TFRecordReader()\n key, serialized_example = reader.read(filename_queue)\n\n features = tf.parse_single_example(serialized_example,\n features={'image_raw': tf.FixedLenFeature([], tf.string),\n 'label': tf.FixedLenFeature([], tf.int64)\n })\n\n image = tf.decode_raw(features['image_raw'], tf.uint8)\n image = tf.cast(image, tf.float32)\n label = tf.cast(features['label'], tf.int32)\n image = tf.reshape(image, old_shape)\n image.set_shape(old_shape)\n print('original image shape:', image.get_shape())\n\n ## Default 0, just resize\n if resize_type == 1: # Just resize\n ## Don't crop, augment and resize\n swap_axises = tf.constant([0,1,2])\n swap_axises = tf.random_shuffle(swap_axises)\n image = tf.transpose(image, perm=[swap_axises[0],\n swap_axises[1],\n swap_axises[2],\n 3])\n image = tf.reshape(image, new_shape)\n elif resize_type == 2:\n ## Random crop , flip\n image = tf.random_crop(image, tuple(new_shape))\n swap_axises = tf.constant([0,1,2])\n swap_axises = tf.random_shuffle(swap_axises)\n image = tf.transpose(image, perm=[swap_axises[0],\n swap_axises[1],\n swap_axises[2],\n 3])\n image = tf.reshape(image, new_shape)\n image.set_shape(new_shape)\n elif resize_type == 3:\n ## Random crop, flip and adjust contrast\n image = tf.random_crop(image, tuple(new_shape))\n swap_axises = tf.constant([0,1,2])\n swap_axises = tf.random_shuffle(swap_axises)\n image = tf.transpose(image, perm=[swap_axises[0],\n swap_axises[1],\n swap_axises[2],\n 3])\n # noise = tf.random_uniform(tuple(new_shape),minval=0,maxval=None,dtype=tf.float32)\n image = tf.image.random_contrast(image,lower=0.3, upper=1.5)\n image = tf.reshape(image, new_shape)\n image.set_shape(new_shape)\n\n processed_example = image\n return processed_example, label\n\ndef getLabelClassMap(base_dir):\n directories = glob.glob(os.path.join(base_dir, '*'))\n class_names = [os.path.basename(directory) for directory in directories]\n class_names.sort()\n label_d_class = dict(zip(range(len(class_names)), class_names))\n class_d_label = dict(zip(class_names, range(len(class_names))))\n return label_d_class, class_d_label\n"
] | [
[
"tensorflow.image.random_contrast",
"tensorflow.FixedLenFeature",
"numpy.asarray",
"tensorflow.cast",
"numpy.concatenate",
"tensorflow.TFRecordReader",
"tensorflow.random_shuffle",
"tensorflow.image.random_flip_left_right",
"tensorflow.decode_raw",
"tensorflow.image.rgb_to_grayscale",
"tensorflow.train.shuffle_batch",
"tensorflow.image.random_brightness",
"tensorflow.image.resize_images",
"scipy.ndimage.rotate",
"tensorflow.train.string_input_producer",
"tensorflow.image.random_flip_up_down",
"numpy.array",
"tensorflow.constant",
"tensorflow.transpose",
"tensorflow.image.crop_to_bounding_box",
"tensorflow.reshape",
"numpy.random.shuffle",
"tensorflow.random_crop"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": [
"1.10"
]
}
] |
nguigs/pylearn-parsimony | [
"f712d2828823d6d55a2470ce060bcaeda2d0589a",
"f712d2828823d6d55a2470ce060bcaeda2d0589a",
"f712d2828823d6d55a2470ce060bcaeda2d0589a"
] | [
"parsimony/functions/neural.py",
"parsimony/utils/plots.py",
"parsimony/datasets/simulate/l1mu_l2_tvmu.py"
] | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nThe :mod:`parsimony.functions.neural` module contains classes for neural\r\nnetworks.\r\n\r\nLoss functions should be stateless. Loss functions may be shared and copied\r\nand should therefore not hold anything that cannot be recomputed the next time\r\nit is called.\r\n\r\nCreated on Tue Feb 14 22:49:28 2017\r\n\r\nCopyright (c) 2013-2017, CEA/DSV/I2BM/Neurospin. All rights reserved.\r\n\r\n@author: Tommy Löfstedt\r\n@email: [email protected]\r\n@license: BSD 3-clause.\r\n\"\"\"\r\nimport abc\r\nfrom six import with_metaclass\r\n\r\nimport numpy as np\r\n\r\ntry:\r\n from . import properties # Only works when imported as a package.\r\nexcept (ValueError, SystemError):\r\n import parsimony.functions.properties as properties # Run as a script.\r\ntry:\r\n from . import step_sizes # Only works when imported as a package.\r\nexcept (ValueError, SystemError):\r\n import parsimony.functions.step_sizes as step_sizes # Run as a script.\r\nfrom parsimony.utils import check_arrays\r\nimport parsimony.utils.consts as consts\r\nimport parsimony.utils as utils\r\n\r\n\r\n__all__ = [\"BaseNetwork\", \"FeedForwardNetwork\",\r\n \"BaseLayer\", \"InputLayer\", \"HiddenLayer\", \"OutputLayer\",\r\n \"SoftmaxCategoricalCrossEntropyOutputLayer\",\r\n \"BaseNode\", \"InputNode\", \"ActivationNode\", \"IdentityNode\",\r\n \"LogisticNode\", \"TanhNode\", \"ReluNode\", \"SoftmaxNode\",\r\n \"BaseLoss\", \"SquaredSumLoss\", \"BinaryCrossEntropyLoss\",\r\n \"CategoricalCrossEntropyLoss\"]\r\n\r\n\r\nclass BaseNetwork(with_metaclass(abc.ABCMeta,\r\n properties.Function,\r\n properties.Gradient,\r\n properties.StepSize)):\r\n \"\"\"This is the base class for all neural networks.\r\n\r\n Parameters\r\n ----------\r\n X : numpy.ndarray, shape (n-by-p)\r\n The training data.\r\n\r\n y : numpy.ndarray, shape (n-by-q)\r\n The example outputs.\r\n\r\n output_nodes : parsimony.neural.BaseNode or list of parsimony.neural.BaseNode\r\n The nodes of the output layer. If passed a BaseNode, then all nodes\r\n of the output layer are of this type; if passed a list of\r\n BaseNodes, then each node's type is given by the corresponding\r\n element in the list.\r\n\r\n loss : parsimony.neural.BaseLoss\r\n The loss function of the network.\r\n\r\n weights : parsimony.utils.weights.BaseWeights\r\n A class to use to generate the initial weights for the output layer and\r\n for any other layer that does not have its own specified weight\r\n generator. Default is\r\n \"\"\"\r\n def __init__(self, X, y, output_nodes, loss,\r\n step_size=step_sizes.ConstantStepSize(0.01), weights=None):\r\n\r\n X, y = check_arrays(X, y)\r\n\r\n self.X = X\r\n self.y = y\r\n self._input = InputLayer(num_nodes=X.shape[1])\r\n self._layers = []\r\n\r\n if self._all_nodes_equal(output_nodes, SoftmaxNode) \\\r\n and isinstance(loss, CategoricalCrossEntropyLoss):\r\n\r\n self._output = SoftmaxCategoricalCrossEntropyOutputLayer(loss,\r\n num_nodes=y.shape[1],\r\n nodes=output_nodes,\r\n weights=weights)\r\n else:\r\n self._output = OutputLayer(loss,\r\n num_nodes=y.shape[1],\r\n nodes=output_nodes,\r\n weights=weights)\r\n\r\n loss.set_target(y.T) # Note: The network outputs column vectors\r\n\r\n self._step_size = step_size\r\n\r\n self.reset()\r\n\r\n def reset(self):\r\n \"\"\"Free any cached computations from previous use of this Function.\r\n\r\n From the interface \"Function\".\r\n \"\"\"\r\n self._input.connect_next(self._output)\r\n self._output.connect_prev(self._input)\r\n self._layers = []\r\n self._step_size.reset()\r\n\r\n def _all_nodes_equal(self, nodes, node_type):\r\n\r\n if isinstance(nodes, list):\r\n equal = True\r\n for node in nodes:\r\n if not isinstance(node, node_type):\r\n equal = False\r\n break\r\n else:\r\n equal = isinstance(nodes, node_type)\r\n\r\n return equal\r\n\r\n def _any_nodes_equal(self, nodes, node_type):\r\n\r\n if isinstance(nodes, list):\r\n equal = False\r\n for node in nodes:\r\n if isinstance(node, node_type):\r\n equal = True\r\n break\r\n else:\r\n equal = isinstance(nodes, node_type)\r\n\r\n return equal\r\n\r\n def add_layer(self, layer):\r\n\r\n if len(self._layers) == 0:\r\n self._input.connect_next(layer) # Connect input to this layer\r\n layer.connect_prev(self._input) # Connect this layer to input\r\n else:\r\n self._layers[-1].connect_next(layer) # Connect last layer to this\r\n layer.connect_prev(self._layers[-1]) # Connect this layer to last\r\n\r\n layer.connect_next(self._output) # Connect this layer to output\r\n self._output.connect_prev(layer) # Connect output to this layer\r\n\r\n self._layers.append(layer)\r\n\r\n def get_weights(self):\r\n\r\n weights = [0] * (len(self._layers) + 1) # Num layers + output layer\r\n for i in range(len(self._layers)):\r\n weights[i] = self._layers[i].get_weights()\r\n\r\n weights[-1] = self._output.get_weights()\r\n\r\n return weights\r\n\r\n def set_weights(self, weights):\r\n\r\n for i in range(len(self._layers)):\r\n self._layers[i].set_weights(weights[i])\r\n\r\n self._output.set_weights(weights[-1])\r\n\r\n @abc.abstractmethod\r\n def _forward(self, X):\r\n raise NotImplementedError('Abstract method \"_forward\" must be '\r\n 'specialised!')\r\n\r\n @abc.abstractmethod\r\n def _backward(self, y):\r\n raise NotImplementedError('Abstract method \"_backward\" must be '\r\n 'specialised!')\r\n\r\n\r\nclass FeedForwardNetwork(BaseNetwork):\r\n\r\n def f(self, W):\r\n \"\"\"The value of the network as a function of its weights.\r\n\r\n From the interface \"Function\".\r\n \"\"\"\r\n self.set_weights(W)\r\n\r\n output = self._output._forward(self.X.T)\r\n E = self._output.get_loss().f(output)\r\n\r\n return E\r\n\r\n def grad(self, W):\r\n \"\"\"The gradient of the network as a function of its weights.\r\n\r\n Parameters\r\n ----------\r\n W : list of numpy.ndarray, num_layers of shape (num_output, num_input)\r\n The point at which to evaluate the gradient.\r\n \"\"\"\r\n self.set_weights(W)\r\n\r\n output = self._forward(self.X.T) # Compute network output\r\n self._backward(output) # Compute deltas (last delta is from loss)\r\n\r\n n_layers = len(self._layers)\r\n grad = [0.0] * (n_layers + 1)\r\n for i in range(n_layers):\r\n grad[i] = self._layers[i].get_grad()\r\n\r\n grad[-1] = self._output.get_grad()\r\n\r\n return grad\r\n\r\n def step(self, W, iteration=None, **kwargs):\r\n\r\n return self._step_size.step(W, iteration=iteration, **kwargs)\r\n\r\n def approx_grad(self, W, eps=1e-4):\r\n \"\"\"Numerical approximation of the gradient.\r\n\r\n Parameters\r\n ----------\r\n W : list of numpy.ndarray, list of shape (num_output, num_input)\r\n The point at which to evaluate the gradient.\r\n\r\n eps : float\r\n Positive float. The precision of the numerical solution. Smaller\r\n is better, but too small may result in floating point precision\r\n errors.\r\n \"\"\"\r\n grad = [0] * len(W)\r\n num_layers = len(self._layers)\r\n for l in range(num_layers + 1):\r\n Wi = W[l].ravel()\r\n gradl = np.zeros(W[l].shape).ravel()\r\n\r\n p = Wi.size\r\n# if isinstance(self, (Penalty, Constraint)):\r\n# start = self.penalty_start\r\n# else:\r\n start = 0\r\n for i in range(start, p):\r\n Wi[i] -= eps\r\n loss1 = self.f(W)\r\n Wi[i] += 2.0 * eps\r\n loss2 = self.f(W)\r\n Wi[i] -= eps\r\n\r\n gradl[i] = (loss2 - loss1) / (2.0 * eps)\r\n\r\n grad[l] = gradl.reshape(W[l].shape)\r\n\r\n return grad\r\n\r\n def _forward(self, X):\r\n \"\"\"Performs a forward pass recursively from the output layer.\r\n\r\n Parameters\r\n ----------\r\n y : numpy.ndarray, shape (num_output_nodes, num_samples)\r\n The output examples.\r\n \"\"\"\r\n y = self._output._forward(X) # Last layer's output\r\n\r\n return y\r\n\r\n def _backward(self, y):\r\n \"\"\"Performs a backwards pass recursively from the first layer.\r\n\r\n Parameters\r\n ----------\r\n y : numpy.ndarray, shape (num_output_nodes, num_samples)\r\n The output examples.\r\n \"\"\"\r\n num_layers = len(self._layers)\r\n if num_layers > 0:\r\n first_layer = self._layers[0]\r\n else:\r\n first_layer = self._output\r\n\r\n first_layer._backward(y) # First layer computes backward step\r\n\r\n\r\nclass BaseLayer(with_metaclass(abc.ABCMeta)):\r\n \"\"\"This is the base class for all layers.\r\n\r\n Parameters\r\n ----------\r\n num_nodes : int\r\n The number of nodes in this layer. Used in conjunction with nodes.\r\n The nodes may be a single node object, in which case num_nodes\r\n determines the number of nodes of copies of nodes in this layer.\r\n Otherwise, the length of nodes determines the number of nodes in the\r\n layer.\r\n\r\n nodes : neural.BaseNode or list of neural.BaseNode\r\n If nodes is a list, then these determine the nodes in this layer.\r\n Otherwise, the layer will constitute num_nodes copies of the nodes node\r\n type.\r\n\r\n weights : numpy.ndarray or utils.weights.BaseWeights\r\n If a numpy.ndarray, these are the actual initial weights of this layer.\r\n If a utils.weights.BaseWeights, this is an object to use to generate\r\n the initial weights.\r\n \"\"\"\r\n def __init__(self, num_nodes=None, nodes=None, weights=None):\r\n\r\n self._set_nodes(nodes, num_nodes)\r\n\r\n if isinstance(weights, utils.weights.BaseWeights):\r\n self.set_weights(None)\r\n self._weight_init = weights\r\n else:\r\n self.set_weights(weights)\r\n self._weight_init = None\r\n\r\n self._all_same = True\r\n if isinstance(nodes, list):\r\n self._all_same = False\r\n\r\n self._prev_layer = None\r\n self._next_layer = None\r\n\r\n def reset(self):\r\n\r\n self._signal = None\r\n self._activation = None\r\n self._derivative = None\r\n self._delta = None\r\n self._grad = None\r\n\r\n def _set_nodes(self, nodes, num_nodes):\r\n\r\n if isinstance(nodes, list):\r\n\r\n if (num_nodes is not None) and (len(nodes) != num_nodes):\r\n raise ValueError(\"num_nodes and len(nodes) do not agree!\")\r\n\r\n has_softmax = False\r\n for node in nodes:\r\n if isinstance(node, SoftmaxNode):\r\n has_softmax = True\r\n break\r\n if has_softmax:\r\n for node in nodes:\r\n if not isinstance(node, SoftmaxNode):\r\n raise ValueError(\"If any node is SoftmaxNode, then all\"\r\n \"nodes must be SoftmaxNode.\")\r\n\r\n self._num_nodes = len(nodes)\r\n self._nodes = nodes\r\n\r\n else:\r\n self._num_nodes = int(num_nodes)\r\n self._nodes = nodes\r\n\r\n def get_num_nodes(self):\r\n\r\n return self._num_nodes\r\n\r\n def connect_next(self, layer):\r\n\r\n self._next_layer = layer\r\n\r\n def connect_prev(self, layer):\r\n\r\n self._prev_layer = layer\r\n\r\n if layer is None:\r\n self._weights = None\r\n elif self._weights is None:\r\n self._weights = self._weight_init.get_weights((self.get_num_nodes(),\r\n layer.get_num_nodes()))\r\n\r\n def get_weights(self):\r\n\r\n return self._weights\r\n\r\n def set_weights(self, weights):\r\n\r\n if weights is not None:\r\n self._weights = np.asarray(weights)\r\n else:\r\n self._weights = weights\r\n\r\n def get_signal(self):\r\n\r\n return self._signal\r\n\r\n def get_activation(self):\r\n\r\n return self._activation\r\n\r\n def get_derivative(self, z=None):\r\n\r\n if z is not None:\r\n if self._all_same:\r\n self._derivative = self._nodes.derivative(z)\r\n else:\r\n self._derivative = np.zeros((self._num_nodes, z.shape[1]))\r\n for i in range(self._num_nodes):\r\n self._derivative[i, :] = self._nodes[i].derivative(z[i, :])\r\n\r\n return self._derivative\r\n\r\n def get_delta(self):\r\n\r\n return self._delta\r\n\r\n def get_grad(self):\r\n\r\n return self._grad\r\n\r\n def _forward(self, X):\r\n\r\n a = self._prev_layer._forward(X)\r\n self._signal = np.dot(self._weights, a)\r\n\r\n if self._all_same:\r\n self._activation = self._nodes.f(self._signal)\r\n else:\r\n self._activation = np.zeros((self._num_nodes, 1))\r\n for i in range(self._num_nodes):\r\n self._activation[i] = self._nodes[i].f(self._signal[i])\r\n\r\n return self._activation\r\n\r\n def _backward(self, y):\r\n\r\n # Compute delta in above layers\r\n delta2 = self._next_layer._backward(y)\r\n\r\n # Compute delta in this layer\r\n z = self.get_signal()\r\n d = self.get_derivative(z)\r\n W = self.get_weights()\r\n self._delta = np.multiply(np.dot(W.T, delta2), d)\r\n\r\n # Compute gradient\r\n aj = self._prev_layer.get_activation() # Activation of previous layer\r\n self._grad = np.dot(self._delta, aj.T)\r\n\r\n return self._delta\r\n\r\n\r\nclass InputLayer(BaseLayer):\r\n \"\"\"Represents an input layer.\r\n \"\"\"\r\n def __init__(self, num_nodes=None):\r\n\r\n super(InputLayer, self).__init__(num_nodes=num_nodes,\r\n nodes=IdentityNode(),\r\n weights=None)\r\n\r\n def connect_prev(self, layer):\r\n\r\n raise ValueError(\"Cannot add a previous layer to the input layer!\")\r\n\r\n def get_signal(self):\r\n\r\n raise ValueError(\"The input layer doesn't have an input signal!\")\r\n\r\n def _forward(self, X):\r\n\r\n self._activation = X\r\n\r\n return self._activation\r\n\r\n def _backward(self):\r\n\r\n raise ValueError(\"The input layer doesn't depend on weights!\")\r\n\r\n\r\nclass HiddenLayer(BaseLayer):\r\n \"\"\"Represents a hidden layer.\r\n \"\"\"\r\n pass\r\n\r\n\r\nclass OutputLayer(BaseLayer):\r\n \"\"\"Represents the output layer.\r\n \"\"\"\r\n def __init__(self, loss, **kwargs):\r\n\r\n super(OutputLayer, self).__init__(**kwargs)\r\n\r\n self.set_loss(loss)\r\n\r\n def connect_next(self, layer):\r\n\r\n raise ValueError(\"Cannot add a next layer to the output layer!\")\r\n\r\n def get_grad(self):\r\n \"\"\"The gradient of the composition of the loss and output layer.\r\n \"\"\"\r\n return super(OutputLayer, self).get_grad()\r\n\r\n def _backward(self, y):\r\n\r\n # Compute delta in the output layer\r\n z = self.get_signal() # z = Wi * aj\r\n d2 = self.get_derivative(z) # g'(z) = g'(Wi * aj)\r\n d1 = self.get_loss().derivative(y) # dL / dz\r\n\r\n if len(d2.shape) == 3: # Full square Jacobian matrices for each sample\r\n\r\n # Warning! This may be very slow when there are many samples!\r\n # In many cases (such as with softmax + cross entropy) it is\r\n # possible to create a specialised output layer for this that\r\n # becomes much more efficient!\r\n self._delta = np.zeros((d1.shape[0], d2.shape[0]))\r\n for i in range(d2.shape[0]):\r\n self._delta[:, i] = np.dot(d1[:, [i]].T, d2[i, :, :]).ravel()\r\n\r\n else: # Simplification/speed-up for diagonal Jacobians\r\n self._delta = np.multiply(d1, d2)\r\n\r\n # Compute gradient\r\n aj = self._prev_layer.get_activation() # Activation of previous layer\r\n self._grad = np.dot(self._delta, aj.T)\r\n\r\n return self._delta\r\n\r\n def get_loss(self):\r\n\r\n return self._loss\r\n\r\n def set_loss(self, loss):\r\n\r\n self._loss = loss\r\n\r\n\r\nclass SoftmaxCategoricalCrossEntropyOutputLayer(OutputLayer):\r\n \"\"\"Represents an output layer with softmax + categorical cross-entropy loss\r\n \"\"\"\r\n def __init__(self, loss, **kwargs):\r\n\r\n if loss is None:\r\n loss = self.set_loss(CategoricalCrossEntropyLoss())\r\n\r\n if not isinstance(loss, CategoricalCrossEntropyLoss):\r\n raise ValueError(\"Loss must be categorical cross-entropy!\")\r\n\r\n super(SoftmaxCategoricalCrossEntropyOutputLayer, self) \\\r\n .__init__(loss, **kwargs)\r\n\r\n def _backward(self, y):\r\n\r\n # Compute delta in the output layer\r\n t = self.get_loss().get_target()\r\n self._delta = y - t\r\n\r\n # Compute gradient\r\n aj = self._prev_layer.get_activation() # Activation of previous layer\r\n self._grad = np.dot(self._delta, aj.T)\r\n\r\n return self._delta\r\n\r\n\r\nclass BaseNode(with_metaclass(abc.ABCMeta,\r\n properties.Function,\r\n properties.Derivative)):\r\n \"\"\"This is the base class for all nodes in the network.\r\n \"\"\"\r\n def __init__(self):\r\n\r\n pass\r\n\r\n def reset(self):\r\n \"\"\"Free any cached computations from previous use of this Function.\r\n\r\n From the interface \"Function\".\r\n \"\"\"\r\n pass\r\n\r\n\r\nclass InputNode(BaseNode):\r\n \"\"\"This is the base class for all nodes in the network that are input\r\n nodes.\r\n \"\"\"\r\n def __init__(self, x):\r\n\r\n self.x = x\r\n\r\n def f(self, x):\r\n\r\n return self.x\r\n\r\n def derivative(self, x):\r\n\r\n return 0.0 # These do not depend on the weights.\r\n\r\n\r\nclass ActivationNode(with_metaclass(abc.ABCMeta, BaseNode)):\r\n \"\"\"This is the base class for all nodes in the network that have activation\r\n functions.\r\n \"\"\"\r\n pass\r\n\r\n\r\nclass IdentityNode(ActivationNode):\r\n \"\"\"A node where the activation function is the identity:\r\n\r\n f(x) = x.\r\n \"\"\"\r\n def f(self, x):\r\n\r\n return x\r\n\r\n def derivative(self, x):\r\n\r\n if isinstance(x, np.ndarray):\r\n return np.ones(x.shape)\r\n else:\r\n return 1.0\r\n\r\n\r\nclass LogisticNode(ActivationNode):\r\n \"\"\"A node where the activation function is the logistic function (soft\r\n step):\r\n\r\n f(x) = 1 / (1 + exp(-x)).\r\n \"\"\"\r\n def f(self, x):\r\n\r\n if isinstance(x, np.ndarray):\r\n return np.reciprocal(1.0 + np.exp(-x))\r\n else:\r\n return 1.0 / (1.0 + np.exp(-x))\r\n\r\n def derivative(self, x):\r\n\r\n f = self.f(x)\r\n if isinstance(x, np.ndarray):\r\n return np.multiply(f, 1.0 - f)\r\n else:\r\n return f * (1.0 - f)\r\n\r\n\r\nclass SoftmaxNode(ActivationNode):\r\n \"\"\"A node where the activation function is the softmax function:\r\n\r\n f(x) = exp(zi) / sum_j exp(zj).\r\n \"\"\"\r\n def f(self, x):\r\n \"\"\"A softmax activation node.\r\n\r\n Parameters\r\n ----------\r\n x : numpy.ndarray, shape (num_outputs, num_samples)\r\n The point at which to evaluate the function. Each column is one\r\n signal, and the rows correspond to output nodes.\r\n \"\"\"\r\n if not isinstance(x, np.ndarray):\r\n raise ValueError(\"Softmax must be applied to a vector!\")\r\n\r\n x_ = x - x.max(axis=0)\r\n x_ = np.exp(x_)\r\n return x_ / np.sum(x_, axis=0)\r\n\r\n def derivative(self, x):\r\n\r\n if len(x.shape) == 1:\r\n x = x[:, np.newaxis]\r\n\r\n S = self.f(x)\r\n\r\n p = S.shape[0] # num_outputs\r\n n = S.shape[1] # num_samples\r\n J = np.zeros((n, p, p))\r\n di = np.diag_indices(p)\r\n for i in range(S.shape[1]):\r\n Si = S[:, [i]]\r\n Ji = np.dot(-Si, Si.T)\r\n Ji[di] += Si.ravel()\r\n\r\n J[i, :, :] = Ji\r\n\r\n return J\r\n\r\n\r\nclass TanhNode(ActivationNode):\r\n \"\"\"A node where the activation function is the hyperbolic tangent function:\r\n\r\n f(x) = tanh(x) = (2 / (1 + exp(-2x))) - 1.\r\n \"\"\"\r\n def f(self, x):\r\n\r\n return np.tanh(x)\r\n\r\n def derivative(self, x):\r\n\r\n a = self.f(x)\r\n return 1.0 - (a ** 2)\r\n\r\n\r\nclass ReluNode(ActivationNode):\r\n \"\"\"A node where the activation function is a rectified linear unit:\r\n\r\n f(x) = max(0, x).\r\n \"\"\"\r\n def f(self, x):\r\n\r\n return np.maximum(0.0, x)\r\n\r\n def derivative(self, x):\r\n\r\n a = self.f(x)\r\n return np.sign(a) # a is non-negative\r\n\r\n\r\nclass BaseLoss(with_metaclass(abc.ABCMeta,\r\n properties.Function,\r\n properties.Derivative)):\r\n \"\"\"This is the base class for all losses in the network.\r\n \"\"\"\r\n def __init__(self, target=None):\r\n\r\n self.set_target(target)\r\n\r\n def set_target(self, target):\r\n\r\n self.target = target\r\n\r\n def get_target(self):\r\n\r\n return self.target\r\n\r\n\r\nclass SquaredSumLoss(BaseLoss):\r\n \"\"\"A squared error loss function\r\n\r\n f(x) = (1 / 2) * \\sum_{i=1}^n (x_i - t_i)².\r\n \"\"\"\r\n def f(self, x):\r\n\r\n return 0.5 * np.sum((x - self.target) ** 2)\r\n\r\n def derivative(self, x):\r\n\r\n return (x - self.target)\r\n\r\n\r\nclass BinaryCrossEntropyLoss(BaseLoss):\r\n \"\"\"A set of independent cross-entropy losses, with function\r\n\r\n f(x) = \\sum_{i=1}^n -t_i * log(x_i) - (1 - t_i) * log(1 - x_i).\r\n \"\"\"\r\n def f(self, x):\r\n\r\n eps = consts.FLOAT_EPSILON\r\n x = np.clip(x, eps, 1.0 - eps)\r\n\r\n return -np.sum(np.multiply(self.target, np.log(x)) +\r\n np.multiply(1.0 - self.target, np.log(1.0 - x)))\r\n\r\n def derivative(self, x):\r\n\r\n return np.divide(x - self.target, np.multiply(x, 1.0 - x))\r\n\r\n\r\nclass CategoricalCrossEntropyLoss(BaseLoss):\r\n \"\"\"A set of dependent outputs in a single cross-entropy loss, with function\r\n\r\n f(x) = -\\sum_{i=1}^n t_i * log(x_i).\r\n \"\"\"\r\n def f(self, x):\r\n\r\n eps = consts.FLOAT_EPSILON\r\n x = np.clip(x, eps, 1.0 - eps)\r\n\r\n return -np.sum(np.multiply(self.target, np.log(x)))\r\n\r\n def derivative(self, x):\r\n\r\n return -np.divide(self.target, x)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import doctest\r\n doctest.testmod()\r\n",
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 6 14:13:42 2014\n\nCopyright (c) 2013-2014, CEA/DSV/I2BM/Neurospin. All rights reserved.\n\n@author: Edouard Duchesnay, Tommy Löfstedt\n@email: [email protected], [email protected]\n@license: BSD 3-clause.\n\"\"\"\nimport numpy as np\nimport scipy.stats as ss\n\n__all__ = [\"map2d\", \"map2d_of_models\", \"classes\", \"errorbars\",\n \"voronoi_tesselation\"]\n\n\nCOLORS = [\"b\", \"g\", \"r\", \"c\", \"m\", \"y\", \"k\", \"w\"]\nCOLORS_FULL = [\"blue\", \"green\", \"red\", \"cyan\", \"magenta\", \"yellow\", \"black\",\n \"white\"]\nMARKERS = [\"+\", \".\", \"o\", \"*\", \"p\", \"s\", \"x\", \"D\", \"h\", \"^\"]\nLINE_STYLE = [\"-\", \"--\", \"--.\", \":\"]\n\n\ndef map2d(map2d, plot=None, title=None, limits=None, center_cmap=True):\n\n import matplotlib.pyplot as plt\n\n if plot is None:\n plot = plt\n\n map2d = map2d.squeeze()\n\n if len(map2d.shape) != 2:\n raise ValueError(\"input map is not 2D\")\n\n if np.asarray(limits).size == 2:\n mx = limits[0]\n mi = limits[1]\n else:\n mx = map2d.max()\n mi = map2d.min()\n\n if center_cmap:\n mx = np.abs([mi, mx]).max()\n mi = -mx\n\n cax = plot.matshow(map2d, cmap=plt.cm.coolwarm)\n frame = plt.gca()\n frame.get_xaxis().set_visible(False)\n frame.get_yaxis().set_visible(False)\n # k = 1\n # while (10 ** k * mx) < 1 and k < 10:\n # k += 1\n # ticks = np.array([-mi, -mi / 4 - mi / 2, 0, mx / 2, mx / 2,\n # mx]).round(k + 2)\n cbar = plt.colorbar(cax) # , ticks=ticks)\n if hasattr(cbar, \"set_clim\"):\n cbar.set_clim(vmin=mi, vmax=mx)\n else:\n cbar.mappable.set_clim(vmin=mi, vmax=mx)\n\n if title is not None:\n plt.title(title)\n\n\ndef map2d_of_models(models_dict, nrow, ncol, shape, title_attr=None):\n \"\"\"Plot 2 weight maps of models.\"\"\"\n import matplotlib.pyplot as plt\n\n ax_i = 1\n for k in list(models_dict.keys()):\n mod = models_dict[k]\n if hasattr(mod, \"beta\"):\n w = mod.beta\n elif hasattr(mod, \"coef_\"): # to work with sklean\n w = mod.coef_\n if (hasattr(mod, \"penalty_start\") and mod.penalty_start != 0):\n w = w[mod.penalty_start:]\n if (title_attr is not None and hasattr(mod, title_attr)):\n title = getattr(mod, title_attr)\n else:\n title = None\n ax = plt.subplot(nrow, ncol, ax_i)\n map2d(w.reshape(shape), ax, title=title)\n ax_i += 1\n plt.show()\n\n\ndef classes(X, classes, title=None, xlabel=None, ylabel=None, show=True):\n\n import matplotlib.pyplot as plt\n\n if isinstance(classes, np.ndarray):\n classes = classes.ravel().tolist()\n\n cls = list(set(classes))\n\n # TODO: Add the other cases.\n if X.shape[1] == 2:\n\n for i in range(len(cls)):\n c = cls[i]\n cl = np.array(classes) == c\n# print cl.shape\n# print X[cl, 0].shape\n# print X[cl, 1].shape\n plt.plot(X[cl, 0], X[cl, 1],\n color=COLORS[i % len(COLORS)],\n marker='.',\n markersize=15,\n linestyle=\"None\")\n\n if title is not None:\n plt.title(title, fontsize=22)\n\n if xlabel is not None:\n plt.xlabel(xlabel, fontsize=16)\n if ylabel is not None:\n plt.ylabel(ylabel, fontsize=16)\n\n if show:\n plt.show()\n\n\ndef errorbars(X, classes=None, means=None, alpha=0.05,\n title=None, xlabel=None, ylabel=None, colors=None,\n new_figure=True, show=True, latex=True, ylim=None):\n\n import matplotlib.pyplot as plt\n\n B, n = X.shape\n if classes is None:\n classes = np.array([1] * n)\n classes = np.array(classes).reshape((n, 1))\n\n if colors is None:\n colors = COLORS\n\n data_mu = np.mean(X, axis=0)\n data_df = np.array([B - 1] * n)\n data_sd = np.std(X, axis=0)\n\n x = np.arange(1, n + 1)\n\n labels, cls_inverse = np.unique(classes, return_inverse=True)\n labels = labels.ravel().tolist()\n\n if new_figure:\n plt.figure()\n if latex:\n plt.rc('text', usetex=True)\n plt.rc('font', family='serif')\n if means is not None:\n plt.plot(x, means, '*',\n markerfacecolor=\"black\", markeredgecolor=\"black\",\n markersize=10)\n\n ci = ss.t.ppf(1.0 - alpha / 2.0, data_df) * data_sd / np.sqrt(B)\n\n for i in range(len(labels)):\n ind = np.where(classes == labels[i])[0]\n\n plt.errorbar(x[ind],\n data_mu[ind],\n yerr=ci[ind],\n fmt='o' + colors[i % len(colors)],\n color=colors[i % len(colors)],\n ecolor=colors[i % len(colors)],\n elinewidth=2,\n markeredgewidth=2,\n markeredgecolor=colors[i % len(colors)],\n capsize=5)\n\n plt.xlim((0, n + 1))\n if ylim is not None:\n plt.ylim(ylim)\n else:\n mn = np.min(data_mu - ci)\n mx = np.max(data_mu + ci)\n d = mx - mn\n plt.ylim((mn - d * 0.05, mx + d * 0.05))\n\n if xlabel is not None:\n plt.xlabel(xlabel)\n if ylabel is not None:\n plt.ylabel(ylabel)\n if title is not None:\n plt.title(title)\n if show:\n plt.show()\n\n\ndef voronoi_tesselation(mu, rect=None, nx=100, ny=100,\n colors=None, alpha=0.3, show=True,\n markersize=10):\n\n import matplotlib.pyplot as plt\n\n mu = np.array(mu) # A 2D data structure -> numpy array\n\n from scipy.spatial import Voronoi\n\n vor = Voronoi(mu) # Compute Voronoi tesselation.\n regions, vertices = _voronoi_finite_polygons_2d(vor)\n\n if colors is None:\n colors = [[0.0, 0.0, 0.0]] * mu.shape[0]\n for i in range(len(colors)):\n colors[i] = [np.random.rand(),\n np.random.rand(),\n np.random.rand()]\n\n for i in range(len(regions)):\n region = regions[i]\n polygon = vertices[region]\n plt.fill(*list(zip(*polygon)), alpha=alpha, color=colors[i])\n plt.plot(mu[i, 0], mu[i, 1], marker='o', color=colors[i],\n markersize=markersize)\n\n if rect is None:\n plt.xlim(vor.min_bound[0] * 0.9, vor.max_bound[0] * 1.1)\n plt.ylim(vor.min_bound[1] * 0.9, vor.max_bound[1] * 1.1)\n else:\n plt.xlim(rect[0], rect[1])\n plt.ylim(rect[2], rect[3])\n\n if show:\n plt.show()\n\n\ndef _voronoi_finite_polygons_2d(vor, radius=None):\n \"\"\"Reconstruct infinite voronoi regions in a 2D diagram to finite regions.\n\n This code is adapted from: https://gist.github.com/pv/8036995\n\n Parameters\n ----------\n vor : Voronoi. Input diagram.\n\n radius : float, optional. Distance to \"points at infinity\".\n\n Returns\n -------\n regions : List of tuples. Indices of vertices in each revised Voronoi\n regions.\n\n vertices : List of tuples. Coordinates for revised Voronoi vertices. Same\n as coordinates of input vertices, with \"points at infinity\"\n appended to the end.\n \"\"\"\n if vor.points.shape[1] != 2:\n raise ValueError(\"Requires 2D input\")\n\n new_regions = []\n new_vertices = vor.vertices.tolist()\n\n center = vor.points.mean(axis=0)\n if radius is None:\n radius = vor.points.ptp().max() * 1000.0\n\n # Construct a map containing all ridges for a given point.\n all_ridges = {}\n for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices):\n all_ridges.setdefault(p1, []).append((p2, v1, v2))\n all_ridges.setdefault(p2, []).append((p1, v1, v2))\n\n # Reconstruct infinite regions.\n for p1, region in enumerate(vor.point_region):\n vertices = vor.regions[region]\n\n if all(v >= 0 for v in vertices):\n # Finite region.\n new_regions.append(vertices)\n continue\n\n # Reconstruct a non-finite region.\n ridges = all_ridges[p1]\n new_region = [v for v in vertices if v >= 0]\n\n for p2, v1, v2 in ridges:\n if v2 < 0:\n v1, v2 = v2, v1\n if v1 >= 0:\n # Finite ridge: already in the region.\n continue\n\n # Compute the missing endpoint of an infinite ridge.\n t = vor.points[p2] - vor.points[p1] # tangent\n t /= np.linalg.norm(t)\n n = np.array([-t[1], t[0]]) # normal\n\n midpoint = vor.points[[p1, p2]].mean(axis=0)\n direction = np.sign(np.dot(midpoint - center, n)) * n\n far_point = vor.vertices[v2] + direction * radius\n\n new_region.append(len(new_vertices))\n new_vertices.append(far_point.tolist())\n\n # Sort region counterclockwise.\n vs = np.asarray([new_vertices[v] for v in new_region])\n c = vs.mean(axis=0)\n angles = np.arctan2(vs[:, 1] - c[1], vs[:, 0] - c[0])\n new_region = np.array(new_region)[np.argsort(angles)]\n\n # Finish.\n new_regions.append(new_region.tolist())\n\n return new_regions, np.asarray(new_vertices)\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n",
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 27 14:47:48 2013\n\nCopyright (c) 2013-2014, CEA/DSV/I2BM/Neurospin. All rights reserved.\n\n@author: Tommy Löfstedt\n@email: [email protected]\n@license: BSD 3-clause.\n\"\"\"\nimport numpy as np\nfrom .grad import grad_l1mu\nfrom .grad import grad_l2_squared\nfrom .grad import grad_tvmu\nfrom .utils import bisection_method\n\n__all__ = ['load']\n\n\ndef load(l, k, g, beta, M, e, mu, snr=None, shape=None):\n \"\"\"Returns data generated such that we know the exact solution.\n\n The data generated by this function is fit to the Linear regression + L1 +\n L2 + Smoothed total variation function, i.e.:\n\n f(b) = (1 / 2).|Xb - y|² + l.L1mu(b) + (k / 2).|b|² + g.TVmu(b),\n\n where L1mu is the smoothed L1 norm, |.|² is the squared L2 norm and TVmu is\n the smoothed total variation penalty.\n\n Parameters\n ----------\n l : The L1 regularisation parameter.\n\n k : The L2 regularisation parameter.\n\n g : The total variation regularisation parameter.\n\n beta : The regression vector to generate data from.\n\n M : The matrix to use when building data. This matrix carries the desired\n correlation structure of the generated data. The generated data\n will be a column-scaled version of this matrix.\n\n e : The error vector e = Xb - y. This vector carries the desired\n distribution of the residual.\n\n mu : The Nesterov smoothing regularisation parameter.\n\n snr : Signal-to-noise ratio between model and residual.\n\n shape : The underlying dimension of the regression vector, beta. E.g. the\n beta may represent an underlying 3D image. In that case the shape\n is a three-tuple with dimensions (Z, Y, X). If shape is not\n provided, the shape is set to (p,) where p is the dimension of\n beta.\n\n Returns\n -------\n X : The generated X matrix.\n\n y : The generated y vector.\n\n beta : The regression vector with the correct snr.\n \"\"\"\n l = float(l)\n k = float(k)\n g = float(g)\n\n if shape is None:\n shape = (beta.shape[0],)\n\n if snr is not None:\n def f(x):\n X, y = _generate(l, k, g, x * beta, M, e, mu, shape)\n\n# print \"norm(beta) = \", np.linalg.norm(beta)\n# print \"norm(Xbeta) = \", np.linalg.norm(np.dot(X, beta))\n# print \"norm(e) = \", np.linalg.norm(e)\n\n print(\"snr = %.5f = %.5f = |X.b| / |e| = %.5f / %.5f\"\n % (snr, np.linalg.norm(np.dot(X, x * beta))\n / np.linalg.norm(e),\n np.linalg.norm(np.dot(X, x * beta)), np.linalg.norm(e)))\n\n return (np.linalg.norm(np.dot(X, x * beta)) / np.linalg.norm(e)) \\\n - snr\n\n snr = bisection_method(f, low=0.0, high=np.sqrt(snr), maxiter=30)\n\n beta = beta * snr\n\n X, y = _generate(l, k, g, beta, M, e, mu, shape)\n\n return X, y, beta\n\n\ndef _generate(l, k, g, beta, M, e, mu, shape):\n\n p = np.prod(shape)\n\n gradL1mu = grad_l1mu(beta, mu)\n gradL2 = grad_l2_squared(beta)\n gradTVmu = grad_tvmu(beta, shape, mu)\n\n alpha = -(l * gradL1mu + k * gradL2 + g * gradTVmu)\n alpha = np.divide(alpha, np.dot(M.T, e))\n\n X = np.zeros(M.shape)\n for i in range(p):\n X[:, i] = M[:, i] * alpha[i, 0]\n\n y = np.dot(X, beta) - e\n\n return X, y\n"
] | [
[
"numpy.dot",
"numpy.log",
"numpy.maximum",
"numpy.multiply",
"numpy.clip",
"numpy.asarray",
"numpy.ones",
"numpy.exp",
"numpy.sign",
"numpy.diag_indices",
"numpy.tanh",
"numpy.zeros",
"numpy.sum",
"numpy.divide"
],
[
"numpy.dot",
"scipy.spatial.Voronoi",
"numpy.sqrt",
"numpy.asarray",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.plot",
"numpy.max",
"numpy.arctan2",
"numpy.mean",
"numpy.where",
"matplotlib.pyplot.gca",
"numpy.unique",
"numpy.arange",
"numpy.std",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"numpy.min",
"matplotlib.pyplot.ylim",
"numpy.random.rand",
"numpy.argsort",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"numpy.abs",
"numpy.linalg.norm",
"scipy.stats.t.ppf",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xlabel"
],
[
"numpy.dot",
"numpy.sqrt",
"numpy.linalg.norm",
"numpy.prod",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
HiPERCAM/hcam_finder | [
"af2d598f56f3c347829d75906a3f37be25f3238c"
] | [
"hcam_finder/shapes.py"
] | [
"import pkg_resources\nimport numpy as np\nfrom astropy import units as u\n\nfrom ginga.util import wcs\nfrom ginga.canvas.types.all import Polygon, Path\nfrom ginga.util.bezier import get_bezier\n\nfrom hcam_widgets.compo.utils import field_stop_centre, gtc_focalplane_equivalencies\n\n\nclass CCDWin(Polygon):\n def __init__(self, ra_ll_deg, dec_ll_deg, xs, ys,\n image, **params):\n \"\"\"\n Shape for drawing ccd window\n\n Parameters\n ----------\n ra_ll_deg : float\n lower left coordinate in ra (deg)\n dec_ll_deg : float\n lower left y coord in dec (deg)\n xs : float\n x size in degrees\n ys : float\n y size in degrees\n image : `~ginga.AstroImage`\n image to plot Window on\n \"\"\"\n points_wcs = (\n (ra_ll_deg, dec_ll_deg),\n wcs.add_offset_radec(ra_ll_deg, dec_ll_deg, xs, 0.0),\n wcs.add_offset_radec(ra_ll_deg, dec_ll_deg, xs, ys),\n wcs.add_offset_radec(ra_ll_deg, dec_ll_deg, 0.0, ys)\n )\n self.points = [image.radectopix(ra, dec) for (ra, dec) in points_wcs]\n super(CCDWin, self).__init__(self.points, **params)\n self.name = params.pop('name', 'window')\n\n\nclass CompoPatrolArc(Path):\n def __init__(self, ra_ctr_deg, dec_ctr_deg, image, **params):\n \"\"\"\n Shape for drawing allowed control arc, made using Bezier curves\n\n Parameters\n ----------\n ra_ctr_deg, dec_ctr_deg : float\n Tel pointing center (deg)\n image : `~ginga.AstroImage`\n image to plot Window on\n \"\"\"\n # assume patrol arc of 90 degrees\n theta = np.linspace(-65, 65, 40)*u.deg\n\n # circular arc, swapping dec sign\n X, Y = field_stop_centre(theta)\n points = u.Quantity([X, -Y])\n # transform to shape (N, 2) and units of degrees\n with u.set_enabled_equivalencies(gtc_focalplane_equivalencies):\n points = points.T.to_value(u.deg)\n # add offsets to pointing center\n points_wcs = [\n wcs.add_offset_radec(ra_ctr_deg, dec_ctr_deg, p[0], p[1])\n for p in points\n ]\n\n self.points = [image.radectopix(ra, dec) for (ra, dec) in points_wcs]\n self.bezier = get_bezier(30, self.points)\n super(CompoPatrolArc, self).__init__(self.points, **params)\n self.name = params.pop('name', 'patrol_arc')\n\n\nclass CompoFreeRegion(Polygon):\n def __init__(self, ra_ctr_deg, dec_ctr_deg, image, **params):\n \"\"\"\n Shape for drawing unvignetted area available to patrol arm\n\n Parameters\n ----------\n ra_ctr_deg, dec_ctr_deg : float\n Tel pointing center (deg)\n image : `~ginga.AstroImage`\n image to plot Window on\n \"\"\"\n guider_file = pkg_resources.resource_filename('hcam_finder',\n 'data/guider_hole_arcseconds.txt')\n points = np.loadtxt(guider_file) / 36000\n points_wcs = [wcs.add_offset_radec(ra_ctr_deg, dec_ctr_deg, p[0], p[1]) for p in points]\n self.points = [image.radectopix(ra, dec) for (ra, dec) in points_wcs]\n self.bezier = get_bezier(30, self.points)\n super(CompoFreeRegion, self).__init__(self.bezier, **params)\n self.name = params.pop('name', 'compo_free_region')\n"
] | [
[
"numpy.loadtxt",
"numpy.linspace"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zysoong/ai-greedy-snake | [
"99e7dde9f623decda1f905cc9c576a011c466b4e",
"99e7dde9f623decda1f905cc9c576a011c466b4e"
] | [
"ddqn.py",
"adhdp.py"
] | [
"from greedysnake import GreedySnake, Direction, Signal\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import backend as K\nimport configparser\nimport sys\nimport warnings\nfrom collections import deque\nimport random\nwarnings.filterwarnings(\"ignore\")\nnp.set_printoptions(threshold=sys.maxsize)\n\nclass Driver:\n\n def __init__(self):\n config = configparser.ConfigParser()\n config.read('ddqn.ini')\n self.env = config['ENV']['env']\n self.greedysnake = GreedySnake()\n self.signal_in = Direction.STRAIGHT\n self.max_epochs = int(config[self.env]['max_epochs'])\n self.max_steps = int(config[self.env]['max_steps'])\n self.batch_size = int(config[self.env]['batch_size'])\n self.memory_size = int(config[self.env]['memory_size'])\n self.mini_batch_size = int(config[self.env]['mini_batch_size'])\n self.critic_net_epochs = int(config[self.env]['critic_net_epochs'])\n self.gamma = float(config[self.env]['gamma'])\n self.epsilon_init = float(config[self.env]['epsilon_init'])\n self.epsilon_decay = float(config[self.env]['epsilon_decay'])\n self.critic_net_learnrate_init = float(config[self.env]['critic_net_learnrate_init'])\n self.critic_net_learnrate_decay = float(config[self.env]['critic_net_learnrate_decay'])\n self.critic_net_clipnorm = float(config[self.env]['critic_net_clipnorm'])\n self.target_update_freq = float(config[self.env]['target_update_freq'])\n self.train_hist_file = config[self.env]['train_hist_file']\n\n # parameters\n self.total_steps = 0\n self.critic_net_learnrate = self.critic_net_learnrate_init * (self.critic_net_learnrate_decay ** self.total_steps)\n self.epsilon = self.epsilon_init * (self.epsilon_decay ** self.total_steps)\n\n def get_action(self, state, critic_model, epsilon):\n\n rand_strategy = np.random.rand()\n # random action\n if 0 <= rand_strategy <= epsilon:\n q = critic_model.predict(np.array(state).reshape((1, 8)))\n sm = np.array(tf.nn.softmax(q)).reshape((4))\n rand = np.random.randint(0, 4)\n action = None\n if rand == 0:\n action = Direction.UP\n elif rand == 1:\n action = Direction.DOWN\n elif rand == 2:\n action = Direction.LEFT\n elif rand == 3:\n action = Direction.RIGHT\n return action, q, sm\n # greedy\n else:\n q = critic_model.predict(np.array(state).reshape((1, 8)))\n sm = np.array(tf.nn.softmax(q)).reshape((4))\n q_np = np.array(q).reshape((4))\n argmax = np.argmax(q_np)\n action = None\n if argmax == 0:\n action = Direction.UP\n elif argmax == 1:\n action = Direction.DOWN\n elif argmax == 2:\n action = Direction.LEFT\n elif argmax == 3:\n action = Direction.RIGHT\n return action, q, sm\n\n def get_action_index(self, action):\n if action == Direction.UP:\n return 0\n elif action == Direction.DOWN:\n return 1\n elif action == Direction.LEFT:\n return 2\n elif action == Direction.RIGHT:\n return 3\n \n def get_ddqn(self):\n\n # critic layers\n critic_model = keras.Sequential([\n keras.layers.Input(shape = (8)), \n keras.layers.Dense(32, activation = 'relu', kernel_initializer='random_normal'),\n keras.layers.Dense(15, activation = 'relu', kernel_initializer='random_normal'),\n keras.layers.Dense(4, activation = 'tanh',kernel_initializer='random_normal')\n ], name = 'critic')\n\n # optimizer\n c_opt = keras.optimizers.Adam(\n lr = self.critic_net_learnrate, \n clipnorm = self.critic_net_clipnorm\n )\n \n # critic model\n critic_model.compile(loss = keras.losses.MSE, optimizer = c_opt)\n\n # target model\n target = keras.models.clone_model(critic_model)\n target.set_weights(critic_model.get_weights())\n return critic_model, target\n\n\n def get_state(self):\n display = ''\n state = np.zeros(shape=(8))\n head = self.greedysnake.snake[0]\n head_up = head + np.array([-1, 0])\n head_down = head + np.array([1, 0])\n head_left = head + np.array([0, -1])\n head_right = head + np.array([0, 1])\n \n if self.greedysnake.is_snake(head_up[0], head_up[1]) != -1 or head_up[0] < 0:\n state[0] = 1.\n if self.greedysnake.is_snake(head_down[0], head_down[1]) != -1 or head_down[0] >= self.greedysnake.SIZE:\n state[1] = 1.\n if self.greedysnake.is_snake(head_left[0], head_left[1]) != -1 or head_left[1] < 0:\n state[2] = 1.\n if self.greedysnake.is_snake(head_right[0], head_right[1]) != -1 or head_right[1] >= self.greedysnake.SIZE:\n state[3] = 1.\n\n food_vec = self.greedysnake.food - head\n food_vec[0] = -food_vec[0]\n x = food_vec[1]\n y = food_vec[0]\n norm_max = np.sqrt(2 * (self.greedysnake.SIZE ** 2))\n norm = 1. - (np.linalg.norm(np.array(x, y)) / norm_max)\n\n if x == 0 and y >= 0:\n state[4] = norm\n elif x == 0 and y < 0:\n state[5] = norm\n elif x > 0 and y >= 0 and y / x <= 1:\n state[7] = norm\n elif x > 0 and y >= 0 and y / x > 1:\n state[4] = norm\n elif x < 0 and y >= 0 and y / x < -1:\n state[4] = norm\n elif x < 0 and y >= 0 and y / x >= -1:\n state[6] = norm\n elif x < 0 and y <= 0 and y / x <= 1:\n state[6] = norm\n elif x < 0 and y <= 0 and y / x > 1:\n state[5] = norm\n elif x > 0 and y <= 0 and y / x < -1:\n state[5] = norm\n elif x > 0 and y <= 0 and y / x >= -1:\n state[7] = norm\n \n\n # generate states for N(s, a)\n for i in range(self.greedysnake.SIZE ** 2):\n row = i // self.greedysnake.SIZE\n col = i % self.greedysnake.SIZE\n snake_index = self.greedysnake.is_snake(row, col)\n\n # snake\n if snake_index > -1:\n\n # snake head\n if snake_index == 0: \n display += '@'\n\n # snake body\n else:\n display += 'O'\n\n # food\n elif (np.array([row, col]) == self.greedysnake.food).all():\n display += '#'\n \n # block\n else: \n display += '-'\n\n # switch line\n if col == self.greedysnake.SIZE - 1:\n display += '\\n'\n\n\n return state, display\n \n def run(self):\n \n # define deep learning network\n critic_model, target = self.get_ddqn()\n \n # statics\n scores = deque(maxlen=1000)\n max_score = 0\n hits = 0\n eats = 0\n\n # model save cold down\n cd = 0\n MAX_CD = 100\n\n for e in range(self.max_epochs):\n\n # execute steps for greedy snake\n s_arr = deque([], maxlen=self.memory_size)\n s_a_future_arr = deque([], maxlen=self.memory_size)\n r_arr = deque([], maxlen=self.memory_size)\n t_arr = deque([], maxlen=self.memory_size)\n q_arr = deque([], maxlen=self.memory_size)\n\n # buffer\n s_current_temp = None\n a_current_temp = None\n \n # start steps\n stamina = 0\n stamina_max = self.greedysnake.SIZE\n for i in range(self.max_steps):\n\n # observe state and action at t = 0\n if i == 0:\n s_current = self.get_state()[0].reshape((1, 8))\n a_current = self.get_action(s_current, critic_model, self.epsilon)[0]\n else: \n s_current = s_current_temp\n a_current = a_current_temp\n s_arr.append(s_current)\n\n # take action via eps greedy, get reward\n signal = self.greedysnake.step(a_current)\n r = None\n\n # signal reward\n if signal == Signal.HIT:\n r = -0.03\n stamina = 0\n hits += 1\n elif signal == Signal.EAT:\n r = 0.03\n stamina = stamina_max\n eats += 1\n elif signal == Signal.NORMAL:\n stamina -= 1\n if stamina < 0:\n stamina = 0\n r = 0.03 * stamina / stamina_max\n\n r_arr.append(r)\n\n # observe state after action\n display = self.get_state()[1]\n s_future = self.get_state()[0].reshape((1, 8))\n s_current_temp = s_future\n s_a_future_arr.append(s_future)\n \n # choose action at t+1\n gares = self.get_action(s_future, critic_model, self.epsilon)\n a_future = gares[0]\n a_current_temp = a_future\n\n # get teacher for critic net (online learning)\n q_current = critic_model.predict(s_current)\n target_sa = target.predict(s_future)\n t = [0,0,0,0]\n index = np.argmax(np.array(target_sa).reshape((4)))\n for j in range(len(t)):\n if j == self.get_action_index(a_current):\n t[j] = r + self.gamma * np.array(target_sa).reshape((4))[index]\n if signal == Signal.HIT and j == self.get_action_index(a_current):\n t[j] = r\n else:\n t[j] = np.array(q_current).reshape((4))[j]\n q_arr.append(q_current)\n t_arr.append(t)\n\n # accumulate index\n self.total_steps += 1\n\n # update learn rate and eps\n self.critic_net_learnrate = self.critic_net_learnrate_init * (self.critic_net_learnrate_decay ** self.total_steps)\n self.epsilon = self.epsilon_init * (self.epsilon_decay ** self.total_steps)\n K.set_value(critic_model.optimizer.learning_rate, self.critic_net_learnrate)\n\n # display information\n a_print = str(a_future)\n r_print = str(float(r))\n t_print = str(np.array(t))\n predict_print = str(q_current)\n diff_print = str(abs(t - q_current))\n\n # calc stats\n scores.append(len(self.greedysnake.snake))\n avg = sum(scores) / len(scores)\n if avg > max_score:\n max_score = avg\n if cd == 0:\n print('models saved')\n critic_model.save('ddqn_critic')\n target.save('ddqn_target')\n cd = MAX_CD\n cd = cd - 1\n if cd < 0:\n cd = 0\n\n # print to debug\n print('Step = ' + str(i) + ' / Epoch = ' + str(e) + ' / Total Steps = ' + str(self.total_steps))\n print('action = ' + a_print + ' / reward = ' + r_print)\n print('teacher(Q) = ' + t_print + ' / predict(Q) = ' + predict_print +' / diff = ' + diff_print)\n print('thousand steps average score = ' + str(avg))\n print('max avg. score = ' + str(max_score))\n print('Hit rate = ' + str(hits / self.total_steps))\n print('Eat rate = ' + str(eats / self.total_steps))\n print(display)\n print(str(np.array(s_future).reshape((2, 4))))\n\n \n if self.total_steps % self.target_update_freq == 0 and self.total_steps != 0:\n print('clone critic weights to target')\n target.set_weights(critic_model.get_weights())\n\n if self.total_steps % 100 == 0:\n f = open(self.train_hist_file, 'a+')\n f.write(str(avg)+'\\n')\n f.close()\n\n # train steps\n if len(s_arr) < self.memory_size:\n s_mini = s_arr\n t_mini = t_arr\n r_mini = r_arr\n else:\n s_mini = random.sample(s_arr, self.mini_batch_size)\n t_mini = random.sample(t_arr, self.mini_batch_size)\n r_mini = random.sample(r_arr, self.mini_batch_size)\n s = np.array(s_mini, dtype=np.float32).reshape((len(s_mini), 8))\n t = np.array(t_mini, dtype=np.float32).reshape((len(t_mini), 4))\n r = np.array(r_mini, dtype=np.float32).reshape((len(r_mini), 1))\n critic_model.fit(s, t, epochs=self.critic_net_epochs, verbose=0, batch_size = self.batch_size)\n\nif __name__ == \"__main__\":\n d = Driver()\n d.run()\n \n",
"from greedysnake import GreedySnake, Direction, Signal\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import backend as K\nimport configparser\nfrom collections import deque\nimport sys\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nnp.set_printoptions(threshold=sys.maxsize)\n\n\nclass ADHDP(keras.Model):\n\n def __init__(self, critic, actor):\n config = configparser.ConfigParser()\n config.read('adhdp.ini')\n self.env = config['ENV']['env']\n super(ADHDP, self).__init__()\n self.critic = critic\n self.actor = actor\n self.batch_size = int(config[self.env]['batch_size'])\n\n def compile(self, optimizer, loss):\n super(ADHDP, self).compile()\n self.actor_optimizer = optimizer\n self.loss = loss\n\n def train_step(self, data):\n\n state, teacher_critic = data\n\n # train actor\n with tf.GradientTape(watch_accessed_variables=True, persistent=True) as tape:\n tape.watch(self.actor.trainable_weights)\n action_map = self.actor(state)\n state_action = tf.concat([state, action_map], 1)\n q = self.critic(state_action)\n t = np.ones((self.batch_size, 1)) \n t.fill(1.0) \n actor_loss = self.loss(t, q)\n actor_grads = tape.gradient(actor_loss, self.actor.trainable_weights)\n\n #print('============= test gradient ===================')\n #tf.print(tape.gradient(actor_loss, action_map))\n\n self.actor_optimizer.apply_gradients(\n zip(actor_grads, self.actor.trainable_weights)\n )\n return {\"ActorLoss\": actor_loss}\n\n def call(self, state):\n return self.actor(state)\n\n def predict_actor(self, state):\n return self.actor(state)\n\n def save_models(self):\n self.critic.save('adhdp_critic')\n self.actor.save('adhdp_actor')\n\nclass Driver:\n\n def __init__(self):\n config = configparser.ConfigParser()\n config.read('adhdp.ini')\n self.env = config['ENV']['env']\n self.greedysnake = GreedySnake()\n self.signal_in = Direction.STRAIGHT\n self.max_epochs = int(config[self.env]['max_epochs'])\n self.max_steps = int(config[self.env]['max_steps'])\n self.batch_size = int(config[self.env]['batch_size'])\n self.memory_size = int(config[self.env]['memory_size'])\n self.critic_net_epochs = int(config[self.env]['critic_net_epochs'])\n self.actor_net_epochs = int(config[self.env]['actor_net_epochs'])\n self.gamma = float(config[self.env]['gamma'])\n self.critic_net_learnrate_init = float(config[self.env]['critic_net_learnrate_init'])\n self.critic_net_learnrate_decay = float(config[self.env]['critic_net_learnrate_decay'])\n self.critic_net_clipnorm = float(config[self.env]['critic_net_clipnorm'])\n self.actor_net_learnrate_init = float(config[self.env]['actor_net_learnrate_init'])\n self.actor_net_learnrate_decay = float(config[self.env]['actor_net_learnrate_decay'])\n self.actor_net_clipnorm = float(config[self.env]['actor_net_clipnorm'])\n self.train_hist_file = config[self.env]['train_hist_file']\n\n # parameters\n self.total_steps = 0\n self.critic_net_learnrate = self.critic_net_learnrate_init * (self.critic_net_learnrate_decay ** self.total_steps)\n self.actor_net_learnrate = self.actor_net_learnrate_init * (self.actor_net_learnrate_decay ** self.total_steps)\n\n def get_action(self, state, adhdp):\n actor_output = adhdp.predict_actor(np.array(state).reshape((1, 8)))\n actor_sm = np.array(tf.nn.softmax(actor_output)).reshape((4))\n rand = np.random.rand()\n action = None\n if 0 <= rand < actor_sm[0]:\n action = Direction.UP\n elif actor_sm[0] <= rand < actor_sm[0] + actor_sm[1]:\n action = Direction.DOWN\n elif actor_sm[0] + actor_sm[1] <= rand < actor_sm[0] + actor_sm[1] + actor_sm[2]:\n action = Direction.LEFT\n else:\n action = Direction.RIGHT\n return action, actor_output\n\n def get_action_index(self, action):\n if action == Direction.UP:\n return 0\n elif action == Direction.DOWN:\n return 1\n elif action == Direction.LEFT:\n return 2\n elif action == Direction.RIGHT:\n return 3\n \n def get_adhdp(self):\n\n # critic layers\n critic_model = keras.Sequential([\n keras.layers.Input(shape = (12)), \n keras.layers.Dense(32, activation = 'relu', kernel_initializer='glorot_normal'),\n keras.layers.Dense(15, activation = 'relu', kernel_initializer='glorot_normal'),\n keras.layers.Dense(1, activation='tanh', kernel_initializer='glorot_normal')\n ], name = 'critic')\n\n # critic layers\n actor_model = keras.Sequential([\n keras.layers.Input(shape = (8)), \n keras.layers.Dense(32, activation = 'relu', kernel_initializer='glorot_normal'),\n keras.layers.Dense(15, activation = 'relu', kernel_initializer='glorot_normal'),\n keras.layers.Dense(4, kernel_initializer='glorot_normal')\n ], name = 'actor')\n\n # optimizer\n c_opt = keras.optimizers.Adam(\n lr = self.critic_net_learnrate, \n clipnorm = self.critic_net_clipnorm\n )\n a_opt = keras.optimizers.Adam(\n lr = self.actor_net_learnrate, \n clipnorm = self.actor_net_clipnorm\n )\n \n # critic model\n critic_model.compile(loss = keras.losses.MSE, optimizer = c_opt)\n\n # actor model\n adhdp = ADHDP(critic=critic_model, actor=actor_model)\n adhdp.compile(loss = keras.losses.MSE, optimizer = a_opt) # loss is MSE to compare the Q values\n return critic_model, adhdp\n\n\n def get_state(self):\n display = ''\n state = np.zeros(shape=(8))\n head = self.greedysnake.snake[0]\n head_up = head + np.array([-1, 0])\n head_down = head + np.array([1, 0])\n head_left = head + np.array([0, -1])\n head_right = head + np.array([0, 1])\n \n if self.greedysnake.is_snake(head_up[0], head_up[1]) != -1 or head_up[0] < 0:\n state[0] = 1.\n if self.greedysnake.is_snake(head_down[0], head_down[1]) != -1 or head_down[0] >= self.greedysnake.SIZE:\n state[1] = 1.\n if self.greedysnake.is_snake(head_left[0], head_left[1]) != -1 or head_left[1] < 0:\n state[2] = 1.\n if self.greedysnake.is_snake(head_right[0], head_right[1]) != -1 or head_right[1] >= self.greedysnake.SIZE:\n state[3] = 1.\n\n food_vec = self.greedysnake.food - head\n food_vec[0] = -food_vec[0]\n x = food_vec[1]\n y = food_vec[0]\n norm_max = np.sqrt(2 * (self.greedysnake.SIZE ** 2))\n norm = 1. - (np.linalg.norm(np.array(x, y)) / norm_max)\n\n if x == 0 and y >= 0:\n state[4] = norm\n elif x == 0 and y < 0:\n state[5] = norm\n elif x > 0 and y >= 0 and y / x <= 1:\n state[7] = norm\n elif x > 0 and y >= 0 and y / x > 1:\n state[4] = norm\n elif x < 0 and y >= 0 and y / x < -1:\n state[4] = norm\n elif x < 0 and y >= 0 and y / x >= -1:\n state[6] = norm\n elif x < 0 and y <= 0 and y / x <= 1:\n state[6] = norm\n elif x < 0 and y <= 0 and y / x > 1:\n state[5] = norm\n elif x > 0 and y <= 0 and y / x < -1:\n state[5] = norm\n elif x > 0 and y <= 0 and y / x >= -1:\n state[7] = norm\n\n for i in range(self.greedysnake.SIZE ** 2):\n row = i // self.greedysnake.SIZE\n col = i % self.greedysnake.SIZE\n snake_index = self.greedysnake.is_snake(row, col)\n\n # snake\n if snake_index > -1:\n\n # snake head\n if snake_index == 0: \n display += '@'\n\n # snake body\n else:\n display += 'O'\n\n # food\n elif (np.array([row, col]) == self.greedysnake.food).all():\n display += '#'\n \n # block\n else: \n display += '-'\n\n # switch line\n if col == self.greedysnake.SIZE - 1:\n display += '\\n'\n return state, display\n \n def run(self):\n \n # define deep learning network\n critic_model, adhdp = self.get_adhdp()\n \n # statics\n scores = deque(maxlen=1000)\n max_score = 0\n hits = 0\n eats = 0\n\n # model save cold down\n cd = 0\n MAX_CD = 100\n\n for e in range(self.max_epochs):\n\n # execute steps for greedy snake\n s_memory = deque()\n s_a_memory = deque()\n r_memory = deque()\n t_memory = deque()\n\n # buffer\n s_current_temp = None\n get_action_result_current_temp = None\n action_current = None\n \n # start steps\n stamina = 0\n stamina_max = self.greedysnake.SIZE\n for i in range(self.max_steps):\n\n # observe state and action at t = 0\n if i == 0:\n s_current = self.get_state()[0].reshape((1, 8))\n get_action_result_current = self.get_action(s_current, adhdp)\n a_current = np.array(get_action_result_current[1]).reshape((1, 4))\n action_current = get_action_result_current[0]\n else: \n s_current = s_current_temp\n get_action_result_current = get_action_result_current_temp\n a_current = np.array(get_action_result_current[1]).reshape((1, 4))\n action_current = get_action_result_current[0]\n s_memory.append(s_current)\n s_a_current = tf.concat([s_current, a_current], axis=1)\n s_a_memory.append(s_a_current)\n\n # take action via eps greedy, get reward\n signal = self.greedysnake.step(action_current)\n r = None\n if signal == Signal.HIT:\n r = -1\n stamina = 0\n hits += 1\n elif signal == Signal.EAT:\n r = 1\n stamina = stamina_max\n eats += 1\n elif signal == Signal.NORMAL:\n stamina -= 1\n if stamina < 0:\n stamina = 0\n r = stamina / stamina_max\n r_memory.append(r)\n\n # observe state after action\n display = self.get_state()[1]\n s_future = self.get_state()[0].reshape((1, 8))\n s_current_temp = s_future\n \n # choose action at t+1\n get_action_result_future = self.get_action(np.array(s_future).reshape((1, 8)), adhdp)\n a_future = get_action_result_future[1]\n get_action_result_current_temp = get_action_result_future\n\n # get teacher for critic net\n s_a_future = tf.concat([np.array(s_future).reshape(1, 8), np.array(a_future).reshape(1, 4)], axis=1)\n q_current = critic_model(np.array(s_a_current).reshape((1, 12)))\n q_future = critic_model(np.array(s_a_future).reshape((1, 12)))\n t = r + self.gamma * q_future\n if signal == Signal.HIT:\n t = r\n t_memory.append(t)\n\n # accumulate index\n self.total_steps += 1\n\n # update learn rate and eps\n self.critic_net_learnrate = self.critic_net_learnrate_init * (self.critic_net_learnrate_decay ** self.total_steps)\n self.actor_net_learnrate = self.actor_net_learnrate_init * (self.actor_net_learnrate_decay ** self.total_steps)\n K.set_value(critic_model.optimizer.learning_rate, self.critic_net_learnrate)\n K.set_value(adhdp.optimizer.learning_rate, self.actor_net_learnrate)\n\n # display information\n a_print = str(a_future)\n r_print = str(float(r))\n t_print = str(np.array(t))\n predict_print = str(q_current)\n diff_print = str(abs(t - q_current))\n\n # calc stats\n scores.append(len(self.greedysnake.snake))\n avg = sum(scores) / len(scores)\n if avg > max_score:\n max_score = avg\n if cd == 0:\n print('models saved')\n adhdp.save_models()\n cd = MAX_CD\n cd = cd - 1\n if cd < 0:\n cd = 0\n \n # print to debug\n print('Step = ' + str(i) + ' / Epoch = ' + str(e) + ' / Total Steps = ' + str(self.total_steps))\n print('action = ' + a_print + ' / reward = ' + r_print)\n print('teacher(Q) = ' + t_print + ' / predict(Q) = ' + predict_print +' / diff = ' + diff_print)\n print('Thousand steps average score = ' + str(avg))\n print('Max average score = ' + str(max_score))\n print('Hit rate = ' + str(hits / self.total_steps))\n print('Eat rate = ' + str(eats / self.total_steps))\n print(display)\n print(s_future.reshape((2, 4)))\n\n # record training history\n if self.total_steps % 100 == 0:\n f = open(self.train_hist_file, 'a+')\n f.write(str(avg)+'\\n')\n f.close()\n \n # train steps\n s = np.array(list(s_memory), dtype=np.float32).reshape((len(list(s_memory)), 8))\n s_a = np.array(list(s_a_memory), dtype=np.float32).reshape((len(list(s_a_memory)), 12))\n t = np.array(list(t_memory), dtype=np.float32).reshape((len(list(t_memory)), 1))\n critic_model.fit(s_a, t, epochs=self.critic_net_epochs, verbose=0, batch_size = self.batch_size)\n adhdp.fit(s, t, epochs=self.actor_net_epochs, verbose=0, batch_size = self.batch_size)\n\n # save model to file\n adhdp.save_models()\n\nif __name__ == \"__main__\":\n d = Driver()\n d.run()\n \n"
] | [
[
"tensorflow.keras.layers.Input",
"tensorflow.keras.backend.set_value",
"tensorflow.keras.models.clone_model",
"numpy.sqrt",
"tensorflow.nn.softmax",
"tensorflow.keras.layers.Dense",
"numpy.set_printoptions",
"tensorflow.keras.optimizers.Adam",
"numpy.argmax",
"numpy.random.rand",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
],
[
"tensorflow.keras.layers.Input",
"tensorflow.concat",
"numpy.sqrt",
"tensorflow.keras.backend.set_value",
"tensorflow.nn.softmax",
"tensorflow.keras.layers.Dense",
"numpy.set_printoptions",
"numpy.ones",
"tensorflow.keras.optimizers.Adam",
"numpy.random.rand",
"numpy.array",
"numpy.zeros",
"tensorflow.GradientTape"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
skesamsetty/User-Data-Analysis | [
"864c619c8c87f2e6f62993da87df20b21de7ff07"
] | [
"Code/user_data_analyzer.py"
] | [
"# Function to send reports\ndef sendReportEmail():\n \"\"\"Based on From EMail ID, Password and To EMail ID from Config files,\n we are trying to send data from the gmail account.\n \"\"\"\n import smtplib\n from email.mime.text import MIMEText\n from email.mime.multipart import MIMEMultipart\n from email.mime.base import MIMEBase\n from email import encoders\n import os.path\n\n from config import from_email, email_password, to_email\n\n email = from_email\n password = email_password\n send_to_email = to_email\n subject = 'Sending User reports'\n message = 'Please find the attachments with Users and Users by States, From Sushma Kesamsetty'\n file1_location = '../Reports/Users.csv'\n file2_location = '../Reports/UsersByState.csv'\n\n msg = MIMEMultipart()\n msg['From'] = from_email\n msg['To'] = to_email\n msg['Subject'] = subject\n\n msg.attach(MIMEText(message, 'plain'))\n\n # Setup the attachment\n filename = os.path.basename(file1_location)\n attachment = open(file1_location, \"rb\")\n part = MIMEBase('application', 'octet-stream')\n part.set_payload(attachment.read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition', \"attachment; filename= %s\" % filename)\n\n # Attach the attachment to the MIMEMultipart object\n msg.attach(part)\n\n # Setup the attachment\n filename = os.path.basename(file2_location)\n attachment = open(file2_location, \"rb\")\n part = MIMEBase('application', 'octet-stream')\n part.set_payload(attachment.read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition', \"attachment; filename= %s\" % filename)\n\n # Attach the attachment to the MIMEMultipart object\n msg.attach(part)\n\n server = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server.ehlo()\n # server.starttls()\n server.login(from_email, password)\n text = msg.as_string()\n server.sendmail(from_email, to_email, text)\n server.quit()\n\n \n# Initial Dependencies\n\nimport pandas as pd\nfrom ast import literal_eval \n\nfrom config import dialect, username, password, host, port, database\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\n# DB Connection\n\nconnection_string = f\"{dialect}://{username}:{password}@{host}:{port}/{database}\"\nengine = create_engine(connection_string)\nconnection = engine.connect()\n\n# reflect an existing database into a new model\nBase = automap_base()\n\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n# Save reference to the tables\nstg_user_data = Base.classes.user_data_stg\nuser_data_tb = Base.classes.user_data\n\n# Clear Staging table before every new load\nsession = Session(engine)\nsession.query(stg_user_data).delete()\nsession.commit()\n\n# File path to load the data\nuser_file_path = \"../Resources/sample_us_users.csv\"\nbase_user_data_df = pd.read_csv(user_file_path)\n\n# Load data into staging table\nbase_user_data_df.to_sql('user_data_stg',connection, if_exists='append', index=False)\nsession.commit()\n\n# In reflection, the table will be visible only when it has primary key.. So I created a temporary key and dropping it here\nstg_base_user_data_df = pd.read_sql_table('user_data_stg', connection)\nstg_base_user_data_df = stg_base_user_data_df.drop(columns = ['index_col'])\n\n# Convert the String Address to Dictionary\nstg_base_user_data_df.iloc[:,1:2]=stg_base_user_data_df.iloc[:,1:2].applymap(literal_eval)\n\n# Normalize the dictionary data\nformatted_address = pd.json_normalize(stg_base_user_data_df.address)\nformatted_address.columns = [f'address_{col}' for col in formatted_address.columns]\n\n# Merge the Normalized address data with to the base data set\nuser_data_normalized_df = pd.concat([stg_base_user_data_df, formatted_address], axis = 1)\n\n# Clean up the normalized data\nformatted_user_data_df = user_data_normalized_df.drop(columns = ['address'])\nformatted_user_data_df.rename(columns = {'address_postCode':'address_postcode'}, inplace = True)\n\n# Clean up null values in the dataframe\nnan_rows = formatted_user_data_df[formatted_user_data_df.isna().any(axis=1)]\nformatted_user_data_df.fillna({'address_state':'US'}, inplace=True)\ncleansed_user_data_df = formatted_user_data_df[formatted_user_data_df.isna().any(axis=1)]\n\n# Load cleansed data to the main table\nformatted_user_data_df.to_sql('user_data',connection, if_exists='append', index=False)\nsession.commit()\n\n# Read complete User data for reporting\ndb_user_data_df = pd.read_sql_table('user_data', connection)\ndb_user_data_df.drop(columns = ['index_col'], inplace = True)\ndb_user_data_df.set_index('id')\n\n# User report\nSQL_Statement = \"SELECT ID, ADDRESS_CITY, ADDRESS_STATE, ADDRESS_COUNTRY, ADDRESS_POSTCODE \\\n FROM user_data \"\nUsersDF = pd.read_sql(SQL_Statement,connection)\nUsersDF.to_csv('../Reports/Users.csv', index=False)\n\n# User count by states\nSQL_Statement = \"SELECT ADDRESS_STATE, count(*) AS USER_COUNT \\\n FROM user_data \\\n GROUP BY ADDRESS_STATE \\\n ORDER BY USER_COUNT DESC\"\nUsersByStateDF = pd.read_sql(SQL_Statement,connection)\nUsersByStateDF.to_csv('../Reports/UsersByState.csv', index=False)\n\n# Send report in an email\nsendReportEmail()\n\n"
] | [
[
"pandas.concat",
"pandas.read_csv",
"pandas.read_sql_table",
"pandas.json_normalize",
"pandas.read_sql"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0"
],
"scipy": [],
"tensorflow": []
}
] |
aleSuglia/py-bottom-up-attention | [
"a97142ad3526c11272c471ee7d610494f1247b7b"
] | [
"detectron2/modeling/postprocessing.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nfrom torch.nn import functional as F\n\nfrom detectron2.layers import paste_masks_in_image\nfrom detectron2.structures import Instances\n\n\ndef detector_postprocess(results, output_height, output_width, mask_threshold=0.5):\n \"\"\"\n Resize the output instances.\n The input images are often resized when entering an object detector.\n As a result, we often need the outputs of the detector in a different\n resolution from its inputs.\n\n This function will resize the raw outputs of an R-CNN detector\n to produce outputs according to the desired output resolution.\n\n Args:\n results (Instances): the raw outputs from the detector.\n `results.image_size` contains the input image resolution the detector sees.\n This object might be modified in-place.\n output_height, output_width: the desired output resolution.\n\n Returns:\n Instances: the resized output from the model, based on the output resolution\n \"\"\"\n scale_x, scale_y = (output_width / results.image_size[1], output_height / results.image_size[0])\n results = Instances((output_height, output_width), **results.get_fields())\n\n if results.has(\"pred_boxes\"):\n output_boxes = results.pred_boxes\n elif results.has(\"proposal_boxes\"):\n output_boxes = results.proposal_boxes\n\n output_boxes.scale(scale_x, scale_y)\n output_boxes.clip(results.image_size)\n\n results = results[output_boxes.nonempty()]\n\n if results.has(\"pred_masks\"):\n results.pred_masks = paste_masks_in_image(\n results.pred_masks[:, 0, :, :], # N, 1, M, M\n results.pred_boxes,\n results.image_size,\n threshold=mask_threshold,\n )\n\n if results.has(\"pred_keypoints\"):\n results.pred_keypoints[:, :, 0] *= scale_x\n results.pred_keypoints[:, :, 1] *= scale_y\n\n return results, output_boxes.nonempty()\n\n\ndef sem_seg_postprocess(result, img_size, output_height, output_width):\n \"\"\"\n Return semantic segmentation predictions in the original resolution.\n\n The input images are often resized when entering semantic segmentor. Moreover, in same\n cases, they also padded inside segmentor to be divisible by maximum network stride.\n As a result, we often need the predictions of the segmentor in a different\n resolution from its inputs.\n\n Args:\n result (Tensor): semantic segmentation prediction logits. A tensor of shape (C, H, W),\n where C is the number of classes, and H, W are the height and width of the prediction.\n img_size (tuple): image size that segmentor is taking as input.\n output_height, output_width: the desired output resolution.\n\n Returns:\n semantic segmentation prediction (Tensor): A tensor of the shape\n (C, output_height, output_width) that contains per-pixel soft predictions.\n \"\"\"\n result = result[:, : img_size[0], : img_size[1]].expand(1, -1, -1, -1)\n result = F.interpolate(\n result, size=(output_height, output_width), mode=\"bilinear\", align_corners=False\n )[0]\n return result\n"
] | [
[
"torch.nn.functional.interpolate"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pyfar/sofar | [
"1f214e02d6e957ee0f56dca0566bb71a5105dd53"
] | [
"tests/test_sofar.py"
] | [
"import sofar as sf\nfrom sofar.sofar import (_update_conventions,\n _get_conventions,\n _format_value_for_netcdf,\n _format_value_from_netcdf,\n _atleast_nd,\n _nd_newaxis,\n _verify_convention_and_version)\nimport os\nfrom tempfile import TemporaryDirectory\nimport pytest\nfrom pytest import raises\nimport numpy as np\nimport numpy.testing as npt\nfrom copy import deepcopy\nfrom netCDF4 import Dataset\nfrom distutils import dir_util\n\n\ndef test_list_conventions(capfd):\n\n # check output to console using pytest default fixture capfd\n sf.list_conventions()\n out, _ = capfd.readouterr()\n assert \"Available SOFA conventions:\" in out\n\n\ndef test_get_conventions(capfd):\n\n # check the return type\n paths = _get_conventions(return_type=\"path\")\n assert isinstance(paths, list)\n assert os.path.isfile(paths[0])\n out, _ = capfd.readouterr()\n assert out == \"\"\n\n names = _get_conventions(return_type=\"name\")\n assert isinstance(names, list)\n assert not os.path.isfile(names[0])\n\n names_versions = _get_conventions(return_type=\"name_version\")\n assert isinstance(names_versions, list)\n assert isinstance(names_versions[0], tuple)\n\n with raises(ValueError, match=\"return_type None is invalid\"):\n _get_conventions(return_type=\"None\")\n\n\ndef test_update_conventions(capfd):\n\n # create temporary directory and copy existing conventions\n temp_dir = TemporaryDirectory()\n dir_util.copy_tree(\n os.path.join(os.path.dirname(__file__), \"..\", \"sofar\", \"conventions\"),\n temp_dir.name)\n\n # modify and delete selected conventions to verbose feedback\n os.remove(os.path.join(temp_dir.name, \"source\", \"GeneralTF_2.0.csv\"))\n with open(os.path.join(\n temp_dir.name, \"source\", \"GeneralFIR_2.0.csv\"), \"w\") as fid:\n fid.write(\"test\")\n\n # first run to test if conventions were updated\n _update_conventions(conventions_path=temp_dir.name)\n out, _ = capfd.readouterr()\n assert \"added new convention: GeneralTF_2.0.csv\" in out\n assert \"updated existing convention: GeneralFIR_2.0.csv\" in out\n\n # second run to make sure that up to date conventions are not overwritten\n _update_conventions(conventions_path=temp_dir.name)\n out, _ = capfd.readouterr()\n assert \"added\" not in out\n assert \"updated\" not in out\n\n\ndef test_create_sofa_object(capfd):\n # test assertion for type of convention parameter\n with raises(TypeError, match=\"Convention must be a string\"):\n sf.Sofa(1)\n # test assertion for invalid conventions\n with raises(ValueError, match=\"Convention 'invalid' not found\"):\n sf.Sofa(\"invalid\")\n\n # test creation with defaults\n sofa = sf.Sofa(\"GeneralTF\")\n assert isinstance(sofa, sf.sofar.Sofa)\n assert sofa.GLOBAL_SOFAConventionsVersion == \"2.0\"\n assert hasattr(sofa, '_convention')\n assert hasattr(sofa, '_dimensions')\n assert hasattr(sofa, '_api')\n\n # assert __repr__\n print(sofa)\n out, _ = capfd.readouterr()\n assert out == \"sofar.SOFA object: GeneralTF 2.0\\n\"\n\n # test returning only mandatory fields\n sofa_all = sf.Sofa(\"GeneralTF\")\n sofa_man = sf.Sofa(\"GeneralTF\", mandatory=True)\n assert len(sofa_all.__dict__) > len(sofa_man.__dict__)\n\n # test version parameter\n sofa = sf.Sofa(\"GeneralTF\", version=\"1.0\")\n assert str(sofa.GLOBAL_SOFAConventionsVersion) == \"1.0\"\n\n # test invalid version\n with raises(ValueError, match=\"Version 0.25 not found. Available\"):\n sf.Sofa(\"GeneralTF\", version=\"0.25\")\n\n # test without updating the api\n sofa = sf.Sofa(\"GeneralTF\", verify=False)\n assert hasattr(sofa, '_convention')\n assert not hasattr(sofa, '_dimensions')\n assert not hasattr(sofa, '_api')\n\n\ndef test_set_attributes_of_sofa_object():\n sofa = sf.Sofa(\"GeneralTF\")\n\n # set attribute\n assert (sofa.ListenerPosition == [0, 0, 0]).all()\n sofa.ListenerPosition = np.array([1, 1, 1])\n assert (sofa.ListenerPosition == [1, 1, 1]).all()\n\n # set read only attribute\n with raises(TypeError, match=\"GLOBAL_Version is a read only\"):\n sofa.GLOBAL_Version = 1\n\n # set non-existing attribute\n with raises(TypeError, match=\"new is an invalid attribute\"):\n sofa.new = 1\n\n\ndef test_sofa_delete_attribute():\n sofa = sf.Sofa(\"GeneralTF\")\n\n # delete optional attribute\n delattr(sofa, \"GLOBAL_ApplicationName\")\n\n # delete mandatory attribute\n with raises(TypeError, match=\"GLOBAL_Version is a mandatory\"):\n delattr(sofa, \"GLOBAL_Version\")\n\n # delete not existing attribute\n with raises(TypeError, match=\"new is not an attribute\"):\n delattr(sofa, \"new\")\n\n\ndef test_copy_sofa_object():\n sofa_org = sf.Sofa(\"GeneralTF\")\n sofa_cp = sofa_org.copy()\n\n assert sf.equals(sofa_org, sofa_cp, verbose=False)\n assert id(sofa_org) != id(sofa_cp)\n\n\ndef test_sofa_verify_version():\n\n # test the default \"latest\"\n sofa = sf.Sofa(\"GeneralTF\", version=\"1.0\")\n assert str(sofa.GLOBAL_SOFAConventionsVersion) == \"1.0\"\n with pytest.warns(UserWarning, match=\"Upgraded\"):\n sofa.verify()\n assert str(sofa.GLOBAL_SOFAConventionsVersion) == \"2.0\"\n\n # test \"match\"\n sofa = sf.Sofa(\"GeneralTF\", version=\"1.0\")\n assert str(sofa.GLOBAL_SOFAConventionsVersion) == \"1.0\"\n sofa.verify(version=\"match\")\n assert str(sofa.GLOBAL_SOFAConventionsVersion) == \"1.0\"\n\n # test downgrading\n sofa = sf.Sofa(\"GeneralTF\")\n assert str(sofa.GLOBAL_SOFAConventionsVersion) == \"2.0\"\n with pytest.warns(UserWarning, match=\"Downgraded\"):\n sofa.verify(version=\"1.0\")\n assert str(sofa.GLOBAL_SOFAConventionsVersion) == \"1.0\"\n\n\ndef test_sofa_verify_missing_default_attributes():\n\n # test missing default attribute\n sofa = sf.Sofa(\"GeneralTF\")\n sofa._protected = False\n delattr(sofa, \"GLOBAL_Conventions\")\n sofa._protected = True\n with pytest.warns(UserWarning, match=\"Added mandatory data with default\"):\n sofa.verify()\n assert sofa.GLOBAL_Conventions == \"SOFA\"\n\n\ndef test_sofa_verify_data_types(capfd):\n\n # test invalid data for netCDF attribute\n sofa = sf.Sofa(\"GeneralFIR\")\n sofa.GLOBAL_Comment = [1, 2, 3]\n with raises(ValueError, match=\"- GLOBAL_Comment must be string\"):\n sofa.verify()\n\n # test invalid data for netCDF double variable\n sofa = sf.Sofa(\"GeneralFIR\")\n sofa.Data_IR = np.array(\"test\")\n with raises(ValueError, match=\"- Data_IR must be int or float\"):\n sofa.verify()\n\n sofa.Data_IR = \"1\"\n with raises(ValueError, match=\"- Data_IR must be int, float\"):\n sofa.verify()\n\n sofa.Data_IR = 1+1j\n with raises(ValueError, match=\"- Data_IR must be int, float\"):\n sofa.verify()\n\n # test invalid data with issue_handling \"print\" and \"return\"\n sofa = sf.Sofa(\"GeneralFIR\")\n sofa.Data_IR = np.array(\"test\")\n out, _ = capfd.readouterr()\n issues = sofa.verify(issue_handling=\"print\")\n out, _ = capfd.readouterr()\n assert issues is None\n assert \"- Data_IR must be int or float\" in out\n\n issues = sofa.verify(issue_handling=\"return\")\n out, _ = capfd.readouterr()\n assert \"- Data_IR must be int or float\" in issues\n assert \"- Data_IR must be int or float\" not in out\n\n # test valid data\n sofa.Data_IR = np.array([1])\n sofa.verify()\n sofa.Data_IR = [1]\n sofa.verify()\n sofa.Data_IR = 1\n sofa.verify()\n\n # test invalid data for netCDF attribute\n sofa = sf.Sofa(\"GeneralFIR\")\n sofa.GLOBAL_History = 1\n with raises(ValueError, match=\"- GLOBAL_History must be string\"):\n sofa.verify()\n\n # test invalid data for netCDF string variable\n sofa = sf.Sofa(\"SimpleHeadphoneIR\")\n sofa.SourceModel = 1\n with raises(ValueError, match=\"- SourceModel must be string\"):\n sofa.verify()\n\n sofa.SourceModel = np.array(1)\n with raises(ValueError, match=\"- SourceModel must be U or S\"):\n sofa.verify()\n\n # test valid data\n sofa.SourceModel = [\"test\"]\n sofa.verify()\n sofa.SourceModel = np.array([\"test\"])\n sofa.verify()\n\n\ndef test_sofa_verify_wrong_shape():\n\n # test attribute with wrong shape\n sofa = sf.Sofa(\"GeneralTF\")\n sofa.ListenerPosition = 1\n with raises(ValueError, match=(\"- ListenerPosition has shape\")):\n sofa.verify()\n\n\ndef test_sofa_verify_wrong_name():\n\n # attribute with missing variable\n sofa = sf.Sofa(\"GeneralTF\")\n sofa._protected = False\n sofa.IR_Type = \"pressure\"\n sofa._custom = {\"IR_Type\": {\"default\": None,\n \"flags\": None,\n \"dimensions\": None,\n \"type\": \"attribute\",\n \"comment\": \"\"}}\n sofa._protected = True\n\n with raises(ValueError, match=\"Detected attributes with missing\"):\n sofa.verify()\n\n # attribute with no underscore\n sofa = sf.Sofa(\"GeneralTF\")\n sofa._protected = False\n sofa.IRType = \"pressure\"\n sofa._custom = {\"IRType\": {\"default\": None,\n \"flags\": None,\n \"dimensions\": None,\n \"type\": \"attribute\",\n \"comment\": \"\"}}\n sofa._protected = True\n\n with raises(ValueError, match=\"Detected attribute names with too many\"):\n sofa.verify()\n\n # variable with underscore\n sofa = sf.Sofa(\"GeneralTF\")\n sofa._protected = False\n sofa.IR_Data = 1\n sofa._custom = {\"IR_Data\": {\"default\": None,\n \"flags\": None,\n \"dimensions\": \"IM\",\n \"type\": \"double\",\n \"comment\": \"\"}}\n sofa._protected = True\n\n with raises(ValueError, match=\"Detected variable names with too many\"):\n sofa.verify()\n\n\n# test everything from sofar._sofa_restrictions explicitly to make sure\n# all possible error in SOFA files are caught\[email protected](\"key,value,msg\", [\n (\"GLOBAL_DataType\", \"image\", \"GLOBAL_DataType is image but must be FIR,\"),\n (\"GLOBAL_SOFAConventions\", \"FIR\", \"\"), # message tested above\n (\"GLOBAL_RoomType\", \"Living room\", \"\"), # message tested above\n (\"ListenerPosition_Type\", \"cylindrical\", \"\"), # message tested above\n (\"ListenerPosition_Units\", \"A\",\n \"ListenerPosition_Units is A but must be metre if ListenerPosition_Type\"),\n (\"ListenerView_Type\", \"cylindrical\", \"\"), # message tested above\n (\"ListenerView_Units\", \"A\", \"\"), # message tested above\n (\"ReceiverPosition_Type\", \"cylindrical\", \"\"), # message tested above\n (\"ReceiverPosition_Units\", \"A\", \"\"), # message tested above\n (\"ReceiverView_Type\", \"cylindrical\", \"\"), # message tested above\n (\"ReceiverView_Units\", \"A\", \"\"), # message tested above\n (\"SourcePosition_Type\", \"cylindrical\", \"\"), # message tested above\n (\"SourcePosition_Units\", \"A\", \"\"), # message tested above\n (\"SourceView_Type\", \"cylindrical\", \"\"), # message tested above\n (\"SourceView_Units\", \"A\", \"\"), # message tested above\n (\"EmitterPosition_Type\", \"cylindrical\", \"\"), # message tested above\n (\"EmitterPosition_Units\", \"A\", \"\"), # message tested above\n (\"EmitterView_Type\", \"cylindrical\", \"\"), # message tested above\n (\"EmitterView_Units\", \"A\", \"\"), # message tested above\n (\"RoomVolume_Units\", \"square metre\", \"\"), # message tested above\n (\"RoomTemperature_Units\", \"Celsius\", \"\"), # message tested above\n])\ndef test_sofa_verify_restrictions_data_wrong_value(key, value, msg):\n \"\"\"\n Test assertions for generally restricted data values.\n \"\"\"\n\n # invalid data type\n sofa = sf.Sofa(\"SingleRoomSRIR\")\n sofa.add_variable(\"RoomVolume\", 200, \"double\", 'II')\n sofa.add_attribute(\"RoomVolume_Units\", \"cubic metre\")\n sofa.add_variable(\"RoomTemperature\", 100, \"double\", 'II')\n sofa.add_attribute(\"RoomTemperature_Units\", \"Kelvin\")\n sofa._protected = False\n setattr(sofa, key, value)\n sofa._protected = True\n with raises(ValueError, match=msg):\n sofa.verify()\n\n\n# can't test everything from sofar._sofa_restrictions explicitly because\n# mandatory fields are added by default\[email protected](\"key,msg\", [\n (\"ReceiverView\", \"ReceiverView must be given if ReceiverUp\"),\n (\"RoomVolume_Units\", \"\"), # message tested above\n (\"RoomTemperature_Units\", \"\"), # message tested above\n])\ndef test_sofa_verify_restrictions_data_missing_attribute(key, msg):\n \"\"\"\n Test assertions for removing optional fields that become mandatory due to\n another field.\n \"\"\"\n\n # invalid data type\n sofa = sf.Sofa(\"SingleRoomSRIR\")\n sofa.add_variable(\"RoomVolume\", 200, \"double\", 'II')\n sofa.add_attribute(\"RoomVolume_Units\", \"cubic metre\")\n sofa.add_variable(\"RoomTemperature\", 100, \"double\", 'II')\n sofa.add_attribute(\"RoomTemperature_Units\", \"Kelvin\")\n sofa._protected = False\n delattr(sofa, key)\n sofa._protected = True\n with raises(ValueError, match=msg):\n sofa.verify()\n\n\n# test everything from sofar._sofa_restrictions explicitly to make sure\n# all possible error in SOFA files are caught\[email protected](\"convention,key,value,msg\", [\n (\"GeneralFIR\", \"Data_SamplingRate_Units\", \"hz\",\n \"Data_SamplingRate_Units is hz but must be hertz\"),\n (\"GeneralTF\", \"N_LongName\", \"f\",\n \"N_LongName is f but must be frequency\"),\n (\"GeneralTF\", \"N_Units\", \"hz\",\n \"N_Units is hz but must be hertz\"),\n])\ndef test_sofa_verify_restrictions_data_type(convention, key, value, msg):\n \"\"\"Test assertions for values that are restricted by GLOBAL_DataType.\"\"\"\n\n sofa = sf.Sofa(convention)\n setattr(sofa, key, value)\n with raises(ValueError, match=msg):\n sofa.verify()\n\n\ndef test_sofa_verify_restrictions_api_spherical_harmonics():\n \"\"\"\n Test assertions for incorrect number of emitters/receiver in case of\n spherical harmonics coordinate systems\n \"\"\"\n\n sofa = sf.Sofa(\"GeneralFIR-E\")\n sofa.ReceiverPosition_Type = \"spherical harmonics\"\n sofa.ReceiverPosition_Units = \"degree, degree, metre\"\n sofa.Data_IR = np.zeros((1, 2, 1, 1))\n sofa.Data_Delay = np.zeros((1, 2, 1))\n with raises(ValueError, match=\"Dimension R is of size 2 but must be\"):\n sofa.verify()\n\n sofa = sf.Sofa(\"GeneralFIR-E\")\n sofa.EmitterPosition_Type = \"spherical harmonics\"\n sofa.EmitterPosition_Units = \"degree, degree, metre\"\n sofa.Data_IR = np.zeros((1, 1, 1, 2))\n sofa.Data_Delay = np.zeros((1, 1, 2))\n with raises(ValueError, match=\"Dimension E is of size 2 but must be\"):\n sofa.verify()\n\n\ndef test_sofa_verify_restrictions_api_second_order_sections():\n \"\"\"\n Test assertions for incorrect number of N in case of\n SOS data type\n \"\"\"\n\n sofa = sf.Sofa(\"SimpleFreeFieldHRSOS\")\n sofa.Data_SOS = np.zeros((1, 2, 1))\n with raises(ValueError, match=\"Dimension N is of size 1 but must be\"):\n sofa.verify()\n\n\[email protected]('convention,kwargs,msg', [\n (\"GeneralFIR\", [(\"GLOBAL_DataType\", \"FIR-E\")], \"GLOBAL_DataType is FIR-E\"),\n (\"GeneralFIR-E\", [(\"GLOBAL_DataType\", \"FIR\")], \"GLOBAL_DataType is FIR\"),\n (\"GeneralFIRE\", [(\"GLOBAL_DataType\", \"FIR\")], \"GLOBAL_DataType is FIR\"),\n (\"GeneralTF\", [(\"GLOBAL_DataType\", \"TF-E\")], \"GLOBAL_DataType is TF-E\"),\n (\"GeneralTF-E\", [(\"GLOBAL_DataType\", \"TF\")], \"GLOBAL_DataType is TF\"),\n\n (\"SimpleFreeFieldHRIR\", [(\"GLOBAL_DataType\", \"FIR-E\")],\n \"GLOBAL_DataType is FIR-E\"),\n (\"SimpleFreeFieldHRIR\", [(\"GLOBAL_RoomType\", \"echoic\")],\n \"GLOBAL_RoomType is echoic\"),\n (\"SimpleFreeFieldHRIR\", [(\"EmitterPosition\", np.zeros((2, 3)))],\n \"Dimension E is of size 2 but must be 1 if GLOBAL\"),\n (\"SimpleFreeFieldHRIR\",\n [(\"EmitterPosition_Type\", \"spherical harmonics\"),\n (\"EmitterPosition_Units\", \"degree, degree, metre\")],\n \"EmitterPosition_Type is spherical harmonics\"),\n\n (\"SimpleFreeFieldHRTF\", [(\"GLOBAL_DataType\", \"TF-E\")],\n \"GLOBAL_DataType is TF-E\"),\n (\"SimpleFreeFieldHRTF\", [(\"GLOBAL_RoomType\", \"echoic\")],\n \"GLOBAL_RoomType is echoic\"),\n (\"SimpleFreeFieldHRTF\", [(\"EmitterPosition\", np.zeros((2, 3)))],\n \"Dimension E is of size 2 but must be 1 if GLOBAL\"),\n (\"SimpleFreeFieldHRTF\",\n [(\"EmitterPosition_Type\", \"spherical harmonics\"),\n (\"EmitterPosition_Units\", \"degree, degree, metre\")],\n \"EmitterPosition_Type is spherical harmonics\"),\n\n # DataType for SimpleFreeFieldHRSOS can not be checked. It raises an error\n # beforehands\n (\"SimpleFreeFieldHRSOS\", [(\"GLOBAL_RoomType\", \"echoic\")],\n \"GLOBAL_RoomType is echoic\"),\n (\"SimpleFreeFieldHRSOS\", [(\"EmitterPosition\", np.zeros((2, 3)))],\n \"Dimension E is of size 2 but must be 1 if GLOBAL\"),\n (\"SimpleFreeFieldHRSOS\",\n [(\"EmitterPosition_Type\", \"spherical harmonics\"),\n (\"EmitterPosition_Units\", \"degree, degree, metre\")],\n \"EmitterPosition_Type is spherical harmonics\"),\n\n # Can not be tested, because it is not yet defined\n # (\"FreeFieldHRIR\", [(\"GLOBAL_DataType\", \"FIR\")],\n # \"GLOBAL_DataType is FIR\"),\n (\"FreeFieldHRTF\", [(\"GLOBAL_DataType\", \"TF\")],\n \"GLOBAL_DataType is TF\"),\n (\"SimpleHeadphoneIR\", [(\"GLOBAL_DataType\", \"FIR-E\")],\n \"GLOBAL_DataType is FIR-E\"),\n (\"SingleRoomSRIR\", [(\"GLOBAL_DataType\", \"FIR-E\")],\n \"GLOBAL_DataType is FIR-E\"),\n (\"SingleRoomMIMOSRIR\", [(\"GLOBAL_DataType\", \"FIR\")],\n \"GLOBAL_DataType is FIR\"),\n (\"FreeFieldDirectivityTF\", [(\"GLOBAL_DataType\", \"TF-E\")],\n \"GLOBAL_DataType is TF-E\"),\n])\ndef test_sofa_verify_restrictions_convention(convention, kwargs, msg):\n\n sofa = sf.Sofa(convention)\n sofa._protected = False\n for key_value in kwargs:\n setattr(sofa, key_value[0], key_value[1])\n with raises(ValueError, match=msg):\n sofa.verify()\n\n\ndef test_verify_value():\n # example alias for testing as returned by sf.sofa._sofa_restrictions()\n unit_aliases = {\"meter\": \"metre\",\n \"degrees\": \"degree\"}\n\n # Simple pass: no restriction on value\n assert sf.Sofa._verify_value(\"meter\", None, unit_aliases)\n\n # simple pass: single unit\n assert sf.Sofa._verify_value(\"meter\", \"metre\", unit_aliases)\n\n # complex pass: list of units\n assert sf.Sofa._verify_value(\"degrees, degrees, meter\",\n \"degree, degree, metre\", unit_aliases)\n\n # simple fail: single unit\n assert not sf.Sofa._verify_value(\"centimetre\", \"metre\", unit_aliases)\n\n # complex fail: list of units\n assert not sf.Sofa._verify_value(\"rad, rad, metre\",\n \"degree, degree, metre\", unit_aliases)\n\n\ndef test_verify_issue_handling(capfd):\n \"\"\"Test different methods for handling issues during verification\"\"\"\n\n error_msg = \"\\nERRORS\\n------\\n\"\n warning_msg = \"\\nWARNINGS\\n--------\\n\"\n\n # no issue\n issue_handling = \"raise\"\n error_occurred, issues = sf.Sofa._verify_handle_issues(\n warning_msg, error_msg, issue_handling)\n assert not error_occurred\n assert issues is None\n\n # raise\n issue_handling = \"raise\"\n with pytest.warns(UserWarning, match=\"warning\"):\n sf.Sofa._verify_handle_issues(\n warning_msg + \"warning\", error_msg, issue_handling)\n with raises(ValueError, match=\"error\"):\n sf.Sofa._verify_handle_issues(\n warning_msg, error_msg + \"error\", issue_handling)\n\n # report warning\n issue_handling = \"report\"\n with pytest.warns(None) as warning:\n _, issues = sf.Sofa._verify_handle_issues(\n warning_msg + \"warning\", error_msg, issue_handling)\n assert \"warning\" in issues\n assert \"ERROR\" not in issues\n assert len(warning) == 0\n # report error\n _, issues = sf.Sofa._verify_handle_issues(\n warning_msg, error_msg + \"error\", issue_handling)\n assert \"error\" in issues\n assert \"WARNING\" not in issues\n\n\ndef test_list_dimensions(capfd):\n\n # test FIR Data\n sofa = sf.Sofa(\"GeneralFIR\")\n sofa.list_dimensions\n out, _ = capfd.readouterr()\n assert \"N = 1 samples (set by Data_IR of dimension MRN)\" in out\n\n # test TF Data\n sofa = sf.Sofa(\"GeneralTF\")\n sofa.list_dimensions\n out, _ = capfd.readouterr()\n assert \"N = 1 frequencies (set by Data_Real of dimension MRN)\" in out\n\n # test SOS Data\n sofa = sf.Sofa(\"SimpleFreeFieldSOS\")\n sofa.list_dimensions\n out, _ = capfd.readouterr()\n assert \"N = 6 SOS coefficients (set by Data_SOS of dimension MRN)\" in out\n\n # test non spherical harmonics data\n sofa = sf.Sofa(\"GeneralFIR\")\n sofa.list_dimensions\n out, _ = capfd.readouterr()\n assert \"E = 1 emitter\" in out\n assert \"R = 1 receiver\" in out\n\n sofa.EmitterPosition_Type = \"spherical harmonics\"\n sofa.ReceiverPosition_Type = \"spherical harmonics\"\n sofa.EmitterPosition_Units = \"degree, degree, metre\"\n sofa.ReceiverPosition_Units = \"degree, degree, metre\"\n sofa.list_dimensions\n out, _ = capfd.readouterr()\n assert \"E = 1 emitter spherical harmonics coefficients\" in out\n assert \"R = 1 receiver spherical harmonics coefficients\" in out\n\n # test assertion in case of variables with wrong type or shape\n sofa = sf.Sofa(\"GeneralFIR\")\n sofa.Data_IR = \"test\"\n with raises(ValueError, match=\"Dimensions can not be shown\"):\n sofa.list_dimensions\n sofa.Data_IR = [1, 2, 3, 4]\n with raises(ValueError, match=\"Dimensions can not be shown\"):\n sofa.list_dimensions\n\n\ndef test_get_dimension():\n \"\"\"Test getting the size of dimensions\"\"\"\n\n # test FIR Data\n sofa = sf.Sofa(\"GeneralFIR\")\n size = sofa.get_dimension(\"N\")\n assert size == 1\n\n # test with wrong dimension\n with raises(ValueError, match=\"Q is not a valid dimension\"):\n size = sofa.get_dimension(\"Q\")\n\n\ndef test_info(capfd):\n\n sofa = sf.Sofa(\"SimpleFreeFieldHRIR\")\n\n # test with wrong info string\n with raises(\n ValueError, match=\"info='invalid' is invalid\"):\n sofa.info(\"invalid\")\n\n # test listing all entry names\n for info in [\"all\", \"mandatory\", \"optional\", \"read only\", \"data\"]:\n sofa.info(info)\n out, _ = capfd.readouterr()\n assert f\"showing {info} entries\" in out\n\n # list information for specific entry\n sofa.info(\"ListenerPosition\")\n out, _ = capfd.readouterr()\n assert \"ListenerPosition\\n type: double\" in out\n assert \"ListenerPosition_Type\\n type: attribute\" in out\n assert \"ListenerPosition_Units\\n type: attribute\" in out\n\n\ndef test_read_sofa():\n\n temp_dir = TemporaryDirectory()\n filename = os.path.join(temp_dir.name, \"test.sofa\")\n sofa = sf.Sofa(\"SimpleFreeFieldHRIR\")\n\n # test defaults\n sf.write_sofa(filename, sofa)\n sofa = sf.read_sofa(filename)\n assert hasattr(sofa, \"_api\")\n\n # reading without updating API\n sofa = sf.read_sofa(filename, verify=False)\n assert not hasattr(sofa, \"_api\")\n\n # read non-existing file\n with raises(ValueError, match=\"test.sofa does not exist\"):\n sf.read_sofa(\"test.sofa\")\n\n # read file of unknown convention\n sofa = sf.Sofa(\"SimpleFreeFieldHRIR\")\n sf.write_sofa(filename, sofa)\n with Dataset(filename, \"r+\", format=\"NETCDF4\") as file:\n setattr(file, \"SOFAConventions\", \"Funky\")\n with raises(ValueError, match=\"File has unknown convention Funky\"):\n sf.read_sofa(filename)\n\n # read file of unknown version\n sofa = sf.Sofa(\"SimpleFreeFieldHRIR\")\n sf.write_sofa(filename, sofa)\n with raises(ValueError, match=\"Version not found\"):\n sf.read_sofa(filename, version=\"0.25\")\n\n # read file containing a variable with wrong shape\n sofa = sf.Sofa(\"SimpleFreeFieldHRIR\")\n sf.write_sofa(filename, sofa)\n # create variable with wrong shape\n with Dataset(filename, \"r+\", format=\"NETCDF4\") as file:\n file.createDimension('A', 10)\n var = file.createVariable(\"Data_IR\", \"f8\", ('I', 'A'))\n var[:] = np.zeros((1, 10)).astype(\"double\")\n # reading data with update API generates an error\n with raises(ValueError, match=\"The SOFA object could not be\"):\n sf.read_sofa(filename)\n # data can be read without updating API\n sf.read_sofa(filename, verify=False)\n\n # test assertion for wrong filename\n with raises(ValueError, match=\"Filename must end with .sofa\"):\n sf.read_sofa('sofa.exe')\n\n\ndef test_read_sofa_custom_data():\n \"\"\"Test if sofa files with custom data are loaded correctly\"\"\"\n\n temp_dir = TemporaryDirectory()\n filename = os.path.join(temp_dir.name, \"test.sofa\")\n sofa = sf.Sofa(\"SimpleFreeFieldHRIR\")\n\n # GLOBAL attribute\n sofa.add_attribute('GLOBAL_Warming', 'critical')\n sf.write_sofa(filename, sofa)\n sofa = sf.read_sofa(filename)\n assert sofa.GLOBAL_Warming == 'critical'\n\n\ndef test_write_sofa_assertion():\n \"\"\"Test assertion for wrong filename ending\"\"\"\n\n sofa = sf.Sofa(\"SimpleFreeFieldHRIR\")\n with raises(ValueError, match=\"Filename must end with .sofa\"):\n sf.write_sofa(\"sofa.exe\", sofa)\n\n\ndef test_write_sofa_compression():\n \"\"\"Test writing SOFA files with compression\"\"\"\n\n # create temporary directory\n temp_dir = TemporaryDirectory()\n\n # create test data\n sofa = sf.Sofa('SimpleFreeFieldHRIR')\n sofa.Data_IR = np.zeros((1, 2, 2048))\n sofa.Data_IR[0, 0] = np.array([1, 0, -1, 0] * 512)\n\n filesize = None\n\n for compression in range(10):\n # write with current compression level\n filename = os.path.join(temp_dir.name, f\"test_{0}.sofa\")\n sf.write_sofa(filename, sofa, compression=compression)\n\n # get and compare the file sizes\n print(f\"Assessing compression level {compression}\")\n if compression > 0:\n assert os.stat(filename).st_size <= filesize\n filesize = os.stat(filename).st_size\n\n\ndef test_roundtrip():\n \"\"\"\"\n Cyclic test of create, write, read functions\n\n 1. create_sofa\n 2. write_sofa\n 3. read_sofa\n 4. compare SOFA from 1. and 3.\n \"\"\"\n\n temp_dir = TemporaryDirectory()\n names = _get_conventions(return_type=\"name\")\n\n for name in names:\n print(f\"Testing: {name}\")\n file = os.path.join(temp_dir.name, name + \".sofa\")\n sofa = sf.Sofa(name)\n sf.write_sofa(file, sofa)\n sofa_r = sf.read_sofa(file)\n identical = sf.equals(sofa, sofa_r, verbose=True, exclude=\"DATE\")\n assert identical\n\n\ndef test_equals_global_parameters():\n\n sofa_a = sf.Sofa(\"SimpleFreeFieldHRIR\")\n\n # check invalid\n with raises(ValueError, match=\"exclude is\"):\n sf.equals(sofa_a, sofa_a, exclude=\"wrong\")\n\n # check identical objects\n assert sf.equals(sofa_a, sofa_a)\n\n # check different number of keys\n sofa_b = deepcopy(sofa_a)\n sofa_b._protected = False\n delattr(sofa_b, \"ReceiverPosition\")\n sofa_b._protected = True\n with pytest.warns(UserWarning, match=\"not identical: sofa_a has\"):\n is_identical = sf.equals(sofa_a, sofa_b)\n assert not is_identical\n\n # check different keys\n sofa_b = deepcopy(sofa_a)\n sofa_b._protected = False\n sofa_b.PositionReceiver = sofa_b.ReceiverPosition\n delattr(sofa_b, \"ReceiverPosition\")\n sofa_b._protected = True\n with pytest.warns(UserWarning, match=\"not identical: sofa_a and sofa_b\"):\n is_identical = sf.equals(sofa_a, sofa_b)\n assert not is_identical\n\n # check mismatching data types\n sofa_b = deepcopy(sofa_a)\n sofa_b._protected = False\n sofa_b._convention[\"ReceiverPosition\"][\"type\"] = \"int\"\n sofa_b._protected = True\n with pytest.warns(UserWarning, match=\"not identical: ReceiverPosition\"):\n is_identical = sf.equals(sofa_a, sofa_b)\n assert not is_identical\n\n # check exclude GLOBAL attributes\n sofa_b = deepcopy(sofa_a)\n sofa_b._protected = False\n delattr(sofa_b, \"GLOBAL_Version\")\n sofa_b._protected = True\n is_identical = sf.equals(sofa_a, sofa_b, exclude=\"GLOBAL\")\n assert is_identical\n\n # check exclude Date attributes\n sofa_b = deepcopy(sofa_a)\n sofa_b._protected = False\n delattr(sofa_b, \"GLOBAL_DateModified\")\n sofa_b._protected = True\n is_identical = sf.equals(sofa_a, sofa_b, exclude=\"DATE\")\n assert is_identical\n\n # check exclude Date attributes\n sofa_b = deepcopy(sofa_a)\n sofa_b._protected = False\n delattr(sofa_b, \"GLOBAL_DateModified\")\n sofa_b._protected = True\n is_identical = sf.equals(sofa_a, sofa_b, exclude=\"ATTR\")\n assert is_identical\n\n\[email protected](\"value_a, value_b, attribute, fails\", [\n (1, \"1\", \"GLOBAL_SOFAConventionsVersion\", False),\n (1, \"1.0\", \"GLOBAL_SOFAConventionsVersion\", False),\n (1., \"1\", \"GLOBAL_SOFAConventionsVersion\", False),\n (\"1\", \"2\", \"GLOBAL_SOFAConventionsVersion\", True),\n ([[1, 2]], [1, 2], \"Data_IR\", False),\n ([[1, 2]], [1, 3], \"Data_IR\", True),\n (\"HD 650\", [\"HD 650\"], \"SourceModel\", False),\n (\"HD 650\", np.array([\"HD 650\"], dtype=\"U\"), \"SourceModel\", False),\n (\"HD 650\", np.array([\"HD 650\"], dtype=\"S\"), \"SourceModel\", False),\n (\"HD 650\", \"HD-650\", \"SourceModel\", True)\n])\ndef test_equals_attribute_values(value_a, value_b, attribute, fails):\n\n # generate SOFA objects (SimpleHeadphoneIR has string variables)\n sofa_a = sf.Sofa(\"SimpleHeadphoneIR\")\n sofa_a._protected = False\n sofa_b = deepcopy(sofa_a)\n\n # set parameters\n setattr(sofa_a, attribute, value_a)\n sofa_a._protected = True\n setattr(sofa_b, attribute, value_b)\n sofa_b._protected = True\n\n # compare\n if fails:\n with pytest.warns(UserWarning):\n assert not sf.equals(sofa_a, sofa_b)\n else:\n assert sf.equals(sofa_a, sofa_b)\n\n\ndef test_add_entry():\n\n sofa = sf.Sofa(\"GeneralTF\")\n\n tmp_dir = TemporaryDirectory()\n\n # test adding a single variable entry\n sofa.add_variable(\"Temperature\", 25.1, \"double\", \"MI\")\n entry = {\"flags\": None, \"dimensions\": \"MI\", \"type\": \"double\",\n \"default\": None, \"comment\": \"\"}\n assert sofa.Temperature == 25.1\n assert sofa._custom[\"Temperature\"] == entry\n assert sofa._convention[\"Temperature\"] == entry\n\n # test adding string variable, global and local attributes\n sofa.add_variable(\"Mood\", \"good\", \"string\", \"MS\")\n assert sofa.Mood == \"good\"\n sofa.add_attribute(\"GLOBAL_Mood\", \"good\")\n assert sofa.GLOBAL_Mood == \"good\"\n sofa.add_attribute(\"Temperature_Units\", \"degree Celsius\")\n assert sofa.Temperature_Units == \"degree Celsius\"\n\n # check if everything can be verified and written, and read correctly\n sf.write_sofa(os.path.join(tmp_dir.name, \"tmp.sofa\"), sofa)\n sofa_read = sf.read_sofa(os.path.join(tmp_dir.name, \"tmp.sofa\"))\n assert sf.equals(sofa, sofa_read)\n\n # test deleting an entry\n delattr(sofa, \"Temperature_Units\")\n assert not hasattr(sofa, \"Temperature_Units\")\n assert \"Temperature_Units\" not in sofa._custom\n\n # test assertions\n # add existing entry\n with raises(ValueError, match=\"Entry Temperature already exists\"):\n sofa.add_variable(\"Temperature\", 25.1, \"double\", \"MI\")\n # entry violating the naming convention\n with raises(ValueError, match=\"underscores '_' in the name\"):\n sofa.add_variable(\"Temperature_Celsius\", 25.1, \"double\", \"MI\")\n with raises(ValueError, match=\"The name of Data\"):\n sofa.add_attribute(\"Data_Time_measured\", \"midnight\")\n # entry with wrong type\n with raises(ValueError, match=\"dtype is float but must be\"):\n sofa.add_variable(\"TemperatureCelsius\", 25.1, \"float\", \"MI\")\n # variable without dimensions\n with raises(ValueError, match=\"dimensions must be provided\"):\n sofa.add_variable(\"TemperatureCelsius\", 25.1, \"double\", None)\n # invalid dimensins\n with pytest.warns(UserWarning, match=\"Added custom dimension T\"):\n sofa.add_variable(\"TemperatureCelsius\", [25.1, 25.2], \"double\", \"T\")\n # attribute with missing variable\n with raises(ValueError, match=\"Adding Attribute Variable\"):\n sofa.add_attribute(\"Variable_Unit\", \"Celsius\")\n\n\ndef test_get_size_and_shape_of_string_var():\n\n # test with string\n S, shape = sf.Sofa._get_size_and_shape_of_string_var(\"four\", \"key\")\n assert S == 4\n assert shape == (1, 1)\n\n # test with single string list\n S, shape = sf.Sofa._get_size_and_shape_of_string_var([\"four\"], \"key\")\n assert S == 4\n assert shape == (1, )\n\n # test with list of strings\n S, shape = sf.Sofa._get_size_and_shape_of_string_var(\n [\"four\", \"fivee\"], \"key\")\n assert S == 5\n assert shape == (2, )\n\n # test with numpy strings array\n S, shape = sf.Sofa._get_size_and_shape_of_string_var(\n np.array([\"four\", \"fivee\"], dtype=\"S256\"), \"key\")\n assert S == 5\n assert shape == (2, )\n\n # test with wrong type\n with raises(TypeError, match=\"key must be a string\"):\n sf.Sofa._get_size_and_shape_of_string_var(1, \"key\")\n\n\ndef test_format_value_for_netcdf():\n\n # string and None dimensions (a.k.a NETCDF attribute)\n value, dtype = _format_value_for_netcdf(\n \"string\", \"test_attr\", \"attribute\", None, 12)\n assert value == \"string\"\n assert dtype == \"attribute\"\n\n # int that should be converted to a string\n value, dtype = _format_value_for_netcdf(\n 1, \"test_attr\", \"attribute\", None, 12)\n assert value == \"1\"\n assert dtype == \"attribute\"\n\n # float that should be converted to a string\n value, dtype = _format_value_for_netcdf(\n 0.2, \"test_attr\", \"attribute\", None, 12)\n assert value == \"0.2\"\n assert dtype == \"attribute\"\n\n # string and IS dimensions\n value, dtype = _format_value_for_netcdf(\n \"string\", \"TestVar\", \"string\", \"IS\", 12)\n assert value == np.array(\"string\", dtype=\"S12\")\n assert dtype == \"S1\"\n assert value.ndim == 2\n\n # single entry array and none Dimensions\n value, dtype = _format_value_for_netcdf(\n [\"string\"], \"TestVar\", \"string\", \"IS\", 12)\n assert value == np.array([\"string\"], dtype=\"S12\")\n assert dtype == \"S1\"\n assert value.ndim == 2\n\n # array of strings\n value, dtype = _format_value_for_netcdf(\n [[\"a\"], [\"bc\"]], \"TestVar\", \"string\", \"MS\", 12)\n assert all(value == np.array([[\"a\"], [\"bc\"]], \"S12\"))\n assert dtype == \"S1\"\n assert value.ndim == 2\n\n # test with list\n value, dtype = _format_value_for_netcdf(\n [0, 0], \"TestVar\", \"double\", \"MR\", 12)\n npt.assert_allclose(value, np.array([0, 0])[np.newaxis, ])\n assert dtype == \"f8\"\n assert value.ndim == 2\n\n # test with numpy array\n value, dtype = _format_value_for_netcdf(\n np.array([0, 0]), \"TestVar\", \"double\", \"MR\", 12)\n npt.assert_allclose(value, np.array([0, 0])[np.newaxis, ])\n assert dtype == \"f8\"\n assert value.ndim == 2\n\n # unkonw data type\n with raises(ValueError, match=\"Unknown type int for TestVar\"):\n value, dtype = _format_value_for_netcdf(1, \"TestVar\", \"int\", \"MR\", 12)\n\n\ndef test_format_value_from_netcdf():\n\n # single string\n value = _format_value_from_netcdf(\n np.array([\"string\"], dtype=\"S6\"), \"Some_Attribute\")\n assert value == \"string\"\n\n # array of strings\n value = _format_value_from_netcdf(\n np.array([\"string1\", \"string2\"], dtype=\"S7\"), \"Some_Attribute\")\n assert all(value == np.array([\"string1\", \"string2\"], dtype=\"U\"))\n\n # numerical array that can be scalar\n value = _format_value_from_netcdf(\n np.array([44100], dtype=\"float\"), \"Data_SamplingRate\")\n assert value == 44100.\n\n # numerical array that can not be scalar\n value = _format_value_from_netcdf(\n np.array([44100], dtype=\"float\"), \"Data_IR\")\n assert value == np.array(44100., dtype=\"float\")\n\n # masked array with missing data\n array = np.ma.masked_array([1, 2], mask=[0, 1], dtype=\"float\")\n with pytest.warns(UserWarning, match=\"Entry Data_IR contains missing\"):\n value = _format_value_from_netcdf(array, \"Data_IR\")\n npt.assert_allclose(value, array)\n\n # test with invalid data dtype\n with raises(TypeError, match=\"Data_IR: value.dtype is complex\"):\n _format_value_from_netcdf(\n np.array([44100], dtype=\"complex\"), \"Data_IR\")\n\n\ndef test_is_mandatory():\n assert sf.Sofa._mandatory(\"rm\")\n assert not sf.Sofa._mandatory(\"r\")\n assert not sf.Sofa._mandatory(None)\n\n\ndef test_is_readonly():\n assert sf.Sofa._read_only(\"rm\")\n assert not sf.Sofa._read_only(\"m\")\n assert not sf.Sofa._read_only(None)\n\n\ndef test_verify_convention_and_version():\n\n # test different possibilities for version\n version = _verify_convention_and_version(\"latest\", \"1.0\", \"GeneralTF\")\n assert version == \"2.0\"\n\n version = _verify_convention_and_version(\"2.0\", \"1.0\", \"GeneralTF\")\n assert version == \"2.0\"\n\n version = _verify_convention_and_version(\"match\", \"1.0\", \"GeneralTF\")\n assert version == \"1.0\"\n\n # test assertions\n with raises(ValueError, match=\"Convention Funky does not exist\"):\n _verify_convention_and_version(\"latest\", \"1.0\", \"Funky\")\n with raises(ValueError, match=\"Version 1.1 does not exist\"):\n _verify_convention_and_version(\"match\", \"1.1\", \"GeneralTF\")\n with raises(ValueError, match=\"Version 1.2 does not exist\"):\n _verify_convention_and_version(\"1.2\", \"1.0\", \"GeneralTF\")\n\n\ndef test_atleast_nd():\n # test with single dimension array\n for ndim in range(1, 6):\n array = _atleast_nd(1, ndim)\n assert array.ndim == ndim\n assert array.flatten() == np.array([1])\n\n # test with two-dimensional array\n for ndim in range(1, 6):\n array = _atleast_nd(np.atleast_2d(1), ndim)\n assert array.ndim == max(2, ndim)\n assert array.flatten() == np.array([1])\n\n\ndef test_nd_newaxis():\n assert _nd_newaxis([1, 2, 3, 4, 5, 6], 2).shape == (6, 1)\n"
] | [
[
"numpy.ma.masked_array",
"numpy.atleast_2d",
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
matcolgit/simulator_sib | [
"8d276d7bcb8a234adb76f64b00116414d355f1d1"
] | [
"sim/lib/settings/town_settings_tirschenreuth.py"
] | [
"import numpy as np\n\n'''\nSettings for town generation\n'''\n\ntown_name = 'Tirschenreuth'\n\n# Make sure to download country-specific population density data\n# from https://data.humdata.org/organization/facebook\npopulation_path='lib/data/population/population_deu_2019-07-01.csv' # Population density file\n\nsites_path='lib/data/queries/' # Directory containing OSM site query details\nbbox = (49.7892, 50.0360, 11.8144, 12.4544) # Coordinate bounding box\n\n# Population per age group in the region (matching the RKI age groups)\n# Source: https://ugeo.urbistat.com/AdminStat/en/de/demografia/eta/tirschenreuth%2c-landkreis/9377/3\n# and adjusted for the RKI age groups\npopulation_per_age_group = np.array([\n 2996, # 0-4\n 6141, # 5-14\n 15785, # 15-34\n 25655, # 35-59\n 16323, # 60-79\n 5831 # 80+\n ], dtype=np.int32)\n\n\nregion_population = population_per_age_group.sum()\ntown_population = region_population \n\n\n# Roughly 100k in total in Germany: https://www.rki.de/DE/Content/Infekt/EpidBull/Archiv/2020/Ausgaben/15_20.pdf?__blob=publicationFile\ndaily_tests_unscaled = int(100000 * (town_population / 83000000))\n\n# Information about household structure (set to None if not available)\n# Source for Germany: https://www.destatis.de/EN/Themes/Society-Environment/Population/Households-Families/Tables/lrbev05.html \nhousehold_info = {\n 'size_dist' : [41.9, 33.8, 11.9, 9.1, 3.4], # distribution of household sizes (1-5 people)\n 'soc_role' : {\n 'children' : [1, 1, 3/20, 0, 0, 0], # age groups 0,1,2 can be children\n 'parents' : [0, 0, 17/20, 1, 0, 0], # age groups 2,3 can be parents\n 'elderly' : [0, 0, 0, 0, 1, 1] # age groups 4,5 are elderly\n }\n}\n\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
drcut/mmediting | [
"e7f13f16dc63f1698d819248ed045983b35c0dbe",
"e7f13f16dc63f1698d819248ed045983b35c0dbe",
"e7f13f16dc63f1698d819248ed045983b35c0dbe"
] | [
"mmedit/models/backbones/sr_backbones/edvr_net.py",
"mmedit/models/backbones/encoder_decoders/decoders/indexnet_decoder.py",
"mmedit/models/backbones/sr_backbones/edsr.py"
] | [
"import torch\nimport torch.nn as nn\nfrom mmcv.cnn import ConvModule, constant_init, kaiming_init\nfrom mmcv.ops import ModulatedDeformConv2d, modulated_deform_conv2d\nfrom mmcv.runner import load_checkpoint\nfrom mmedit.models.common import (PixelShufflePack, ResidualBlockNoBN,\n make_layer)\nfrom mmedit.models.registry import BACKBONES\nfrom mmedit.utils import get_root_logger\nfrom torch.nn.modules.utils import _pair\n\n\nclass ModulatedDCNPack(ModulatedDeformConv2d):\n \"\"\"Modulated Deformable Convolutional Pack.\n\n Different from the official DCN, which generates offsets and masks from\n the preceding features, this ModulatedDCNPack takes another different\n feature to generate masks and offsets.\n\n Args:\n in_channels (int): Same as nn.Conv2d.\n out_channels (int): Same as nn.Conv2d.\n kernel_size (int or tuple[int]): Same as nn.Conv2d.\n stride (int or tuple[int]): Same as nn.Conv2d.\n padding (int or tuple[int]): Same as nn.Conv2d.\n dilation (int or tuple[int]): Same as nn.Conv2d.\n groups (int): Same as nn.Conv2d.\n bias (bool or str): If specified as `auto`, it will be decided by the\n norm_cfg. Bias will be set as True if norm_cfg is None, otherwise\n False.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(ModulatedDCNPack, self).__init__(*args, **kwargs)\n\n self.conv_offset = nn.Conv2d(\n self.in_channels,\n self.deform_groups * 3 * self.kernel_size[0] * self.kernel_size[1],\n kernel_size=self.kernel_size,\n stride=_pair(self.stride),\n padding=_pair(self.padding),\n bias=True)\n self.init_offset()\n\n def init_offset(self):\n constant_init(self.conv_offset, val=0, bias=0)\n\n def forward(self, x, extra_feat):\n out = self.conv_offset(extra_feat)\n o1, o2, mask = torch.chunk(out, 3, dim=1)\n offset = torch.cat((o1, o2), dim=1)\n mask = torch.sigmoid(mask)\n return modulated_deform_conv2d(x, offset, mask, self.weight, self.bias,\n self.stride, self.padding,\n self.dilation, self.groups,\n self.deform_groups)\n\n\nclass PCDAlignment(nn.Module):\n \"\"\"Alignment module using Pyramid, Cascading and Deformable convolution\n (PCD). It is used in EDVRNet.\n\n Args:\n mid_channels (int): Number of the channels of middle features.\n Default: 64.\n deform_groups (int): Deformable groups. Defaults: 8.\n act_cfg (dict): Activation function config for ConvModule.\n Default: LeakyReLU with negative_slope=0.1.\n \"\"\"\n\n def __init__(self,\n mid_channels=64,\n deform_groups=8,\n act_cfg=dict(type='LeakyReLU', negative_slope=0.1)):\n super(PCDAlignment, self).__init__()\n\n # Pyramid has three levels:\n # L3: level 3, 1/4 spatial size\n # L2: level 2, 1/2 spatial size\n # L1: level 1, original spatial size\n self.offset_conv1 = nn.ModuleDict()\n self.offset_conv2 = nn.ModuleDict()\n self.offset_conv3 = nn.ModuleDict()\n self.dcn_pack = nn.ModuleDict()\n self.feat_conv = nn.ModuleDict()\n for i in range(3, 0, -1):\n level = f'l{i}'\n self.offset_conv1[level] = ConvModule(\n mid_channels * 2, mid_channels, 3, padding=1, act_cfg=act_cfg)\n if i == 3:\n self.offset_conv2[level] = ConvModule(\n mid_channels, mid_channels, 3, padding=1, act_cfg=act_cfg)\n else:\n self.offset_conv2[level] = ConvModule(\n mid_channels * 2,\n mid_channels,\n 3,\n padding=1,\n act_cfg=act_cfg)\n self.offset_conv3[level] = ConvModule(\n mid_channels, mid_channels, 3, padding=1, act_cfg=act_cfg)\n self.dcn_pack[level] = ModulatedDCNPack(\n mid_channels,\n mid_channels,\n 3,\n padding=1,\n deform_groups=deform_groups)\n\n if i < 3:\n act_cfg_ = act_cfg if i == 2 else None\n self.feat_conv[level] = ConvModule(\n mid_channels * 2,\n mid_channels,\n 3,\n padding=1,\n act_cfg=act_cfg_)\n\n # Cascading DCN\n self.cas_offset_conv1 = ConvModule(\n mid_channels * 2, mid_channels, 3, padding=1, act_cfg=act_cfg)\n self.cas_offset_conv2 = ConvModule(\n mid_channels, mid_channels, 3, padding=1, act_cfg=act_cfg)\n self.cas_dcnpack = ModulatedDCNPack(\n mid_channels,\n mid_channels,\n 3,\n padding=1,\n deform_groups=deform_groups)\n\n self.upsample = nn.Upsample(\n scale_factor=2, mode='bilinear', align_corners=False)\n self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n\n def forward(self, neighbor_feats, ref_feats):\n \"\"\"Forward function for PCDAlignment.\n\n Align neighboring frames to the reference frame in the feature level.\n\n Args:\n neighbor_feats (list[Tensor]): List of neighboring features. It\n contains three pyramid levels (L1, L2, L3),\n each with shape (n, c, h, w).\n ref_feats (list[Tensor]): List of reference features. It\n contains three pyramid levels (L1, L2, L3),\n each with shape (n, c, h, w).\n\n Returns:\n Tensor: Aligned features.\n \"\"\"\n # The number of pyramid levels is 3.\n assert len(neighbor_feats) == 3 and len(ref_feats) == 3, (\n 'The length of neighbor_feats and ref_feats must be both 3, '\n f'but got {len(neighbor_feats)} and {len(ref_feats)}')\n\n # Pyramids\n upsampled_offset, upsampled_feat = None, None\n for i in range(3, 0, -1):\n level = f'l{i}'\n offset = torch.cat([neighbor_feats[i - 1], ref_feats[i - 1]],\n dim=1)\n offset = self.offset_conv1[level](offset)\n if i == 3:\n offset = self.offset_conv2[level](offset)\n else:\n offset = self.offset_conv2[level](\n torch.cat([offset, upsampled_offset], dim=1))\n offset = self.offset_conv3[level](offset)\n\n feat = self.dcn_pack[level](neighbor_feats[i - 1], offset)\n if i == 3:\n feat = self.lrelu(feat)\n else:\n feat = self.feat_conv[level](\n torch.cat([feat, upsampled_feat], dim=1))\n\n if i > 1:\n # upsample offset and features\n upsampled_offset = self.upsample(offset) * 2\n upsampled_feat = self.upsample(feat)\n\n # Cascading\n offset = torch.cat([feat, ref_feats[0]], dim=1)\n offset = self.cas_offset_conv2(self.cas_offset_conv1(offset))\n feat = self.lrelu(self.cas_dcnpack(feat, offset))\n return feat\n\n\nclass TSAFusion(nn.Module):\n \"\"\"Temporal Spatial Attention (TSA) fusion module. It is used in EDVRNet.\n\n Args:\n mid_channels (int): Number of the channels of middle features.\n Default: 64.\n num_frames (int): Number of frames. Default: 5.\n center_frame_idx (int): The index of center frame. Default: 2.\n act_cfg (dict): Activation function config for ConvModule.\n Default: LeakyReLU with negative_slope=0.1.\n \"\"\"\n\n def __init__(self,\n mid_channels=64,\n num_frames=5,\n center_frame_idx=2,\n act_cfg=dict(type='LeakyReLU', negative_slope=0.1)):\n super(TSAFusion, self).__init__()\n self.center_frame_idx = center_frame_idx\n # temporal attention (before fusion conv)\n self.temporal_attn1 = nn.Conv2d(\n mid_channels, mid_channels, 3, padding=1)\n self.temporal_attn2 = nn.Conv2d(\n mid_channels, mid_channels, 3, padding=1)\n self.feat_fusion = ConvModule(\n num_frames * mid_channels, mid_channels, 1, act_cfg=act_cfg)\n\n # spatial attention (after fusion conv)\n self.max_pool = nn.MaxPool2d(3, stride=2, padding=1)\n self.avg_pool = nn.AvgPool2d(3, stride=2, padding=1)\n self.spatial_attn1 = ConvModule(\n num_frames * mid_channels, mid_channels, 1, act_cfg=act_cfg)\n self.spatial_attn2 = ConvModule(\n mid_channels * 2, mid_channels, 1, act_cfg=act_cfg)\n self.spatial_attn3 = ConvModule(\n mid_channels, mid_channels, 3, padding=1, act_cfg=act_cfg)\n self.spatial_attn4 = ConvModule(\n mid_channels, mid_channels, 1, act_cfg=act_cfg)\n self.spatial_attn5 = nn.Conv2d(\n mid_channels, mid_channels, 3, padding=1)\n self.spatial_attn_l1 = ConvModule(\n mid_channels, mid_channels, 1, act_cfg=act_cfg)\n self.spatial_attn_l2 = ConvModule(\n mid_channels * 2, mid_channels, 3, padding=1, act_cfg=act_cfg)\n self.spatial_attn_l3 = ConvModule(\n mid_channels, mid_channels, 3, padding=1, act_cfg=act_cfg)\n self.spatial_attn_add1 = ConvModule(\n mid_channels, mid_channels, 1, act_cfg=act_cfg)\n self.spatial_attn_add2 = nn.Conv2d(mid_channels, mid_channels, 1)\n\n self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n self.upsample = nn.Upsample(\n scale_factor=2, mode='bilinear', align_corners=False)\n\n def forward(self, aligned_feat):\n \"\"\"Forward function for TSAFusion.\n\n Args:\n aligned_feat (Tensor): Aligned features with shape (n, t, c, h, w).\n\n Returns:\n Tensor: Features after TSA with the shape (n, c, h, w).\n \"\"\"\n n, t, c, h, w = aligned_feat.size()\n # temporal attention\n embedding_ref = self.temporal_attn1(\n aligned_feat[:, self.center_frame_idx, :, :, :].clone())\n emb = self.temporal_attn2(aligned_feat.view(-1, c, h, w))\n emb = emb.view(n, t, -1, h, w) # (n, t, c, h, w)\n\n corr_l = [] # correlation list\n for i in range(t):\n emb_neighbor = emb[:, i, :, :, :]\n corr = torch.sum(emb_neighbor * embedding_ref, 1) # (n, h, w)\n corr_l.append(corr.unsqueeze(1)) # (n, 1, h, w)\n corr_prob = torch.sigmoid(torch.cat(corr_l, dim=1)) # (n, t, h, w)\n corr_prob = corr_prob.unsqueeze(2).expand(n, t, c, h, w)\n corr_prob = corr_prob.contiguous().view(n, -1, h, w) # (n, t*c, h, w)\n aligned_feat = aligned_feat.view(n, -1, h, w) * corr_prob\n\n # fusion\n feat = self.feat_fusion(aligned_feat)\n\n # spatial attention\n attn = self.spatial_attn1(aligned_feat)\n attn_max = self.max_pool(attn)\n attn_avg = self.avg_pool(attn)\n attn = self.spatial_attn2(torch.cat([attn_max, attn_avg], dim=1))\n # pyramid levels\n attn_level = self.spatial_attn_l1(attn)\n attn_max = self.max_pool(attn_level)\n attn_avg = self.avg_pool(attn_level)\n attn_level = self.spatial_attn_l2(\n torch.cat([attn_max, attn_avg], dim=1))\n attn_level = self.spatial_attn_l3(attn_level)\n attn_level = self.upsample(attn_level)\n\n attn = self.spatial_attn3(attn) + attn_level\n attn = self.spatial_attn4(attn)\n attn = self.upsample(attn)\n attn = self.spatial_attn5(attn)\n attn_add = self.spatial_attn_add2(self.spatial_attn_add1(attn))\n attn = torch.sigmoid(attn)\n\n # after initialization, * 2 makes (attn * 2) to be close to 1.\n feat = feat * attn * 2 + attn_add\n return feat\n\n\[email protected]_module()\nclass EDVRNet(nn.Module):\n \"\"\"EDVR network structure for video super-resolution.\n\n Now only support X4 upsampling factor.\n Paper:\n EDVR: Video Restoration with Enhanced Deformable Convolutional Networks.\n\n Args:\n in_channels (int): Channel number of inputs.\n out_channels (int): Channel number of outputs.\n mid_channels (int): Channel number of intermediate features.\n Default: 64.\n num_frames (int): Number of input frames. Default: 5.\n deform_groups (int): Deformable groups. Defaults: 8.\n num_blocks_extraction (int): Number of blocks for feature extraction.\n Default: 5.\n num_blocks_reconstruction (int): Number of blocks for reconstruction.\n Default: 10.\n center_frame_idx (int): The index of center frame. Frame counting from\n 0. Default: 2.\n with_tsa (bool): Whether to use TSA module. Default: True.\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n mid_channels=64,\n num_frames=5,\n deform_groups=8,\n num_blocks_extraction=5,\n num_blocks_reconstruction=10,\n center_frame_idx=2,\n with_tsa=True):\n super(EDVRNet, self).__init__()\n self.center_frame_idx = center_frame_idx\n self.with_tsa = with_tsa\n act_cfg = dict(type='LeakyReLU', negative_slope=0.1)\n\n self.conv_first = nn.Conv2d(in_channels, mid_channels, 3, 1, 1)\n self.feature_extraction = make_layer(\n ResidualBlockNoBN,\n num_blocks_extraction,\n mid_channels=mid_channels)\n\n # generate pyramid features\n self.feat_l2_conv1 = ConvModule(\n mid_channels, mid_channels, 3, 2, 1, act_cfg=act_cfg)\n self.feat_l2_conv2 = ConvModule(\n mid_channels, mid_channels, 3, 1, 1, act_cfg=act_cfg)\n self.feat_l3_conv1 = ConvModule(\n mid_channels, mid_channels, 3, 2, 1, act_cfg=act_cfg)\n self.feat_l3_conv2 = ConvModule(\n mid_channels, mid_channels, 3, 1, 1, act_cfg=act_cfg)\n # pcd alignment\n self.pcd_alignment = PCDAlignment(\n mid_channels=mid_channels, deform_groups=deform_groups)\n # fusion\n if self.with_tsa:\n self.fusion = TSAFusion(\n mid_channels=mid_channels,\n num_frames=num_frames,\n center_frame_idx=self.center_frame_idx)\n else:\n self.fusion = nn.Conv2d(num_frames * mid_channels, mid_channels, 1,\n 1)\n\n # reconstruction\n self.reconstruction = make_layer(\n ResidualBlockNoBN,\n num_blocks_reconstruction,\n mid_channels=mid_channels)\n # upsample\n self.upsample1 = PixelShufflePack(\n mid_channels, mid_channels, 2, upsample_kernel=3)\n self.upsample2 = PixelShufflePack(\n mid_channels, 64, 2, upsample_kernel=3)\n # we fix the output channels in the last few layers to 64.\n self.conv_hr = nn.Conv2d(64, 64, 3, 1, 1)\n self.conv_last = nn.Conv2d(64, 3, 3, 1, 1)\n self.img_upsample = nn.Upsample(\n scale_factor=4, mode='bilinear', align_corners=False)\n # activation function\n self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n\n def forward(self, x):\n \"\"\"Forward function for EDVRNet.\n\n Args:\n x (Tensor): Input tensor with shape (n, t, c, h, w).\n\n Returns:\n Tensor: SR center frame with shape (n, c, h, w).\n \"\"\"\n n, t, c, h, w = x.size()\n assert h % 4 == 0 and w % 4 == 0, (\n 'The height and width of inputs should be a multiple of 4, '\n f'but got {h} and {w}.')\n\n x_center = x[:, self.center_frame_idx, :, :, :].contiguous()\n\n # extract LR features\n # L1\n l1_feat = self.lrelu(self.conv_first(x.view(-1, c, h, w)))\n l1_feat = self.feature_extraction(l1_feat)\n # L2\n l2_feat = self.feat_l2_conv2(self.feat_l2_conv1(l1_feat))\n # L3\n l3_feat = self.feat_l3_conv2(self.feat_l3_conv1(l2_feat))\n\n l1_feat = l1_feat.view(n, t, -1, h, w)\n l2_feat = l2_feat.view(n, t, -1, h // 2, w // 2)\n l3_feat = l3_feat.view(n, t, -1, h // 4, w // 4)\n\n # pcd alignment\n ref_feats = [ # reference feature list\n l1_feat[:, self.center_frame_idx, :, :, :].clone(),\n l2_feat[:, self.center_frame_idx, :, :, :].clone(),\n l3_feat[:, self.center_frame_idx, :, :, :].clone()\n ]\n aligned_feat = []\n for i in range(t):\n neighbor_feats = [\n l1_feat[:, i, :, :, :].clone(), l2_feat[:, i, :, :, :].clone(),\n l3_feat[:, i, :, :, :].clone()\n ]\n aligned_feat.append(self.pcd_alignment(neighbor_feats, ref_feats))\n aligned_feat = torch.stack(aligned_feat, dim=1) # (n, t, c, h, w)\n\n if self.with_tsa:\n feat = self.fusion(aligned_feat)\n else:\n aligned_feat = aligned_feat.view(n, -1, h, w)\n feat = self.fusion(aligned_feat)\n\n # reconstruction\n out = self.reconstruction(feat)\n out = self.lrelu(self.upsample1(out))\n out = self.lrelu(self.upsample2(out))\n out = self.lrelu(self.conv_hr(out))\n out = self.conv_last(out)\n base = self.img_upsample(x_center)\n out += base\n return out\n\n def init_weights(self, pretrained=None, strict=True):\n \"\"\"Init weights for models.\n\n Args:\n pretrained (str, optional): Path for pretrained weights. If given\n None, pretrained weights will not be loaded. Defaults to None.\n strict (boo, optional): Whether strictly load the pretrained model.\n Defaults to True.\n \"\"\"\n if isinstance(pretrained, str):\n logger = get_root_logger()\n load_checkpoint(self, pretrained, strict=strict, logger=logger)\n elif pretrained is None:\n if self.with_tsa:\n for module in [\n self.fusion.feat_fusion, self.fusion.spatial_attn1,\n self.fusion.spatial_attn2, self.fusion.spatial_attn3,\n self.fusion.spatial_attn4, self.fusion.spatial_attn_l1,\n self.fusion.spatial_attn_l2,\n self.fusion.spatial_attn_l3,\n self.fusion.spatial_attn_add1\n ]:\n kaiming_init(\n module.conv,\n a=0.1,\n mode='fan_out',\n nonlinearity='leaky_relu',\n bias=0,\n distribution='uniform')\n else:\n raise TypeError(f'\"pretrained\" must be a str or None. '\n f'But received {type(pretrained)}.')\n",
"import math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom mmcv.cnn import ConvModule, kaiming_init, normal_init\nfrom mmedit.models.common import DepthwiseSeparableConvModule\nfrom mmedit.models.registry import COMPONENTS\n\n\nclass IndexedUpsample(nn.Module):\n \"\"\"Indexed upsample module.\n\n Args:\n in_channels (int): Input channels.\n out_channels (int): Output channels.\n kernel_size (int, optional): Kernel size of the convolution layer.\n Defaults to 5.\n norm_cfg (dict, optional): Config dict for normalization layer.\n Defaults to dict(type='BN').\n conv_module (ConvModule | DepthwiseSeparableConvModule, optional):\n Conv module. Defaults to ConvModule.\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size=5,\n norm_cfg=dict(type='BN'),\n conv_module=ConvModule):\n super(IndexedUpsample, self).__init__()\n\n self.conv = conv_module(\n in_channels,\n out_channels,\n kernel_size,\n padding=(kernel_size - 1) // 2,\n norm_cfg=norm_cfg,\n act_cfg=dict(type='ReLU6'))\n\n self.init_weights()\n\n def init_weights(self):\n \"\"\"Init weights for the module.\n \"\"\"\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n kaiming_init(m, mode='fan_in', nonlinearity='leaky_relu')\n\n def forward(self, x, shortcut, dec_idx_feat=None):\n \"\"\"Forward function.\n\n Args:\n x (Tensor): Input feature map with shape (N, C, H, W).\n shortcut (Tensor): The shorcut connection with shape\n (N, C, H', W').\n dec_idx_feat (Tensor, optional): The decode index feature map with\n shape (N, C, H', W'). Defaults to None.\n\n Returns:\n Tensor: Output tensor with shape (N, C, H', W').\n \"\"\"\n if dec_idx_feat is not None:\n assert shortcut.dim() == 4, (\n 'shortcut must be tensor with 4 dimensions')\n x = dec_idx_feat * F.interpolate(x, size=shortcut.shape[2:])\n out = torch.cat((x, shortcut), dim=1)\n return self.conv(out)\n\n\[email protected]_module()\nclass IndexNetDecoder(nn.Module):\n\n def __init__(self,\n in_channels,\n kernel_size=5,\n norm_cfg=dict(type='BN'),\n separable_conv=False):\n # TODO: remove in_channels argument\n super(IndexNetDecoder, self).__init__()\n\n if separable_conv:\n conv_module = DepthwiseSeparableConvModule\n else:\n conv_module = ConvModule\n\n blocks_in_channels = [\n in_channels * 2, 96 * 2, 64 * 2, 32 * 2, 24 * 2, 16 * 2, 32 * 2\n ]\n blocks_out_channels = [96, 64, 32, 24, 16, 32, 32]\n\n self.decoder_layers = nn.ModuleList()\n for in_channels, out_channels in zip(blocks_in_channels,\n blocks_out_channels):\n self.decoder_layers.append(\n IndexedUpsample(in_channels, out_channels, kernel_size,\n norm_cfg, conv_module))\n\n self.pred = nn.Sequential(\n conv_module(\n 32,\n 1,\n kernel_size,\n padding=(kernel_size - 1) // 2,\n norm_cfg=norm_cfg,\n act_cfg=dict(type='ReLU6')),\n nn.Conv2d(\n 1, 1, kernel_size, padding=(kernel_size - 1) // 2, bias=False))\n\n def init_weights(self):\n \"\"\"Init weights for the module.\n \"\"\"\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n std = math.sqrt(2. / (m.out_channels * m.kernel_size[0]**2))\n normal_init(m, mean=0, std=std)\n\n def forward(self, inputs):\n \"\"\"Forward fucntion.\n\n Args:\n inputs (dict): Output dict of IndexNetEncoder.\n\n Returns:\n Tensor: Predicted alpha matte of the current batch.\n \"\"\"\n shortcuts = reversed(inputs['shortcuts'])\n dec_idx_feat_list = reversed(inputs['dec_idx_feat_list'])\n out = inputs['out']\n\n group = (self.decoder_layers, shortcuts, dec_idx_feat_list)\n for decode_layer, shortcut, dec_idx_feat in zip(*group):\n out = decode_layer(out, shortcut, dec_idx_feat)\n\n out = self.pred(out)\n\n return out\n",
"import math\n\nimport torch\nimport torch.nn as nn\nfrom mmcv.runner import load_checkpoint\nfrom mmedit.models.common import (PixelShufflePack, ResidualBlockNoBN,\n make_layer)\nfrom mmedit.models.registry import BACKBONES\nfrom mmedit.utils import get_root_logger\n\n\nclass UpsampleModule(nn.Sequential):\n \"\"\"Upsample module used in EDSR.\n\n Args:\n scale (int): Scale factor. Supported scales: 2^n and 3.\n mid_channels (int): Channel number of intermediate features.\n \"\"\"\n\n def __init__(self, scale, mid_channels):\n modules = []\n if (scale & (scale - 1)) == 0: # scale = 2^n\n for _ in range(int(math.log(scale, 2))):\n modules.append(\n PixelShufflePack(\n mid_channels, mid_channels, 2, upsample_kernel=3))\n elif scale == 3:\n modules.append(\n PixelShufflePack(\n mid_channels, mid_channels, scale, upsample_kernel=3))\n else:\n raise ValueError(f'scale {scale} is not supported. '\n 'Supported scales: 2^n and 3.')\n\n super(UpsampleModule, self).__init__(*modules)\n\n\[email protected]_module()\nclass EDSR(nn.Module):\n \"\"\"EDSR network structure.\n\n Paper: Enhanced Deep Residual Networks for Single Image Super-Resolution.\n Ref repo: https://github.com/thstkdgus35/EDSR-PyTorch\n\n Args:\n in_channels (int): Channel number of inputs.\n out_channels (int): Channel number of outputs.\n mid_channels (int): Channel number of intermediate features.\n Default: 64.\n num_blocks (int): Block number in the trunk network. Default: 16.\n upscale_factor (int): Upsampling factor. Support 2^n and 3.\n Default: 4.\n res_scale (float): Used to scale the residual in residual block.\n Default: 1.\n rgb_mean (tuple[float]): Image mean in RGB orders.\n Default: (0.4488, 0.4371, 0.4040), calculated from DIV2K dataset.\n rgb_std (tuple[float]): Image std in RGB orders. In EDSR, it uses\n (1.0, 1.0, 1.0). Default: (1.0, 1.0, 1.0).\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n mid_channels=64,\n num_blocks=16,\n upscale_factor=4,\n res_scale=1,\n rgb_mean=(0.4488, 0.4371, 0.4040),\n rgb_std=(1.0, 1.0, 1.0)):\n super(EDSR, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.mid_channels = mid_channels\n self.num_blocks = num_blocks\n self.upscale_factor = upscale_factor\n\n self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1)\n self.std = torch.Tensor(rgb_std).view(1, 3, 1, 1)\n\n self.conv_first = nn.Conv2d(in_channels, mid_channels, 3, padding=1)\n self.body = make_layer(\n ResidualBlockNoBN,\n num_blocks,\n mid_channels=mid_channels,\n res_scale=res_scale)\n self.conv_after_body = nn.Conv2d(mid_channels, mid_channels, 3, 1, 1)\n self.upsample = UpsampleModule(upscale_factor, mid_channels)\n self.conv_last = nn.Conv2d(\n mid_channels, out_channels, 3, 1, 1, bias=True)\n\n def forward(self, x):\n \"\"\"Forward function.\n\n Args:\n x (Tensor): Input tensor with shape (n, c, h, w).\n\n Returns:\n Tensor: Forward results.\n \"\"\"\n\n self.mean = self.mean.to(x)\n self.std = self.std.to(x)\n\n x = (x - self.mean) / self.std\n x = self.conv_first(x)\n res = self.conv_after_body(self.body(x))\n res += x\n\n x = self.conv_last(self.upsample(res))\n x = x * self.std + self.mean\n\n return x\n\n def init_weights(self, pretrained=None, strict=True):\n \"\"\"Init weights for models.\n\n Args:\n pretrained (str, optional): Path for pretrained weights. If given\n None, pretrained weights will not be loaded. Defaults to None.\n strict (boo, optional): Whether strictly load the pretrained model.\n Defaults to True.\n \"\"\"\n if isinstance(pretrained, str):\n logger = get_root_logger()\n load_checkpoint(self, pretrained, strict=strict, logger=logger)\n elif pretrained is None:\n pass # use default initialization\n else:\n raise TypeError('\"pretrained\" must be a str or None. '\n f'But received {type(pretrained)}.')\n"
] | [
[
"torch.sigmoid",
"torch.cat",
"torch.nn.ModuleDict",
"torch.nn.Conv2d",
"torch.sum",
"torch.nn.MaxPool2d",
"torch.nn.AvgPool2d",
"torch.nn.Upsample",
"torch.nn.LeakyReLU",
"torch.nn.modules.utils._pair",
"torch.chunk",
"torch.stack"
],
[
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.functional.interpolate",
"torch.cat"
],
[
"torch.nn.Conv2d",
"torch.Tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
KiriKoppelgaard/NLP-E21 | [
"d5ce2f739b06f3a7eae1825626a134fbc4b2314b"
] | [
"syllabus/classes/class5/neural_network_as_nnmodule.py"
] | [
"\"\"\"\nLogistic regression implemented using the nn.module class\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nfrom sklearn import datasets\n\n\nclass Model(nn.Module):\n def __init__(self, n_input_features=10):\n super().__init__()\n self.linear1 = nn.Linear(n_input_features, 30)\n self.linear2 = nn.Linear(30, 30)\n self.linear3 = nn.Linear(30, 1)\n\n def forward(self, x):\n x = self.linear1(x)\n x = torch.sigmoid(x)\n x = self.linear2(x)\n x = torch.sigmoid(x)\n x = self.linear3(x)\n y_pred = torch.sigmoid(x)\n return y_pred\n\n\n# Create dataset\nX_numpy, y_numpy = datasets.make_classification(\n n_samples=1000, n_features=10, random_state=7\n)\nX = torch.tensor(X_numpy, dtype=torch.float)\ny = torch.tensor(y_numpy, dtype=torch.float)\ny = y.view(y.shape[0], 1)\n\n\n# initialize model\nmodel = Model(n_input_features=10)\n\n# define loss and optimizer\ncriterion = nn.BCELoss()\noptimizer = torch.optim.AdamW(model.parameters())\n\n# train\nepochs = 10000\nfor epoch in range(epochs):\n # forward\n y_hat = model.forward(X) # model(X)\n\n # backward\n loss = criterion(y_hat, y)\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n\n # some print to see that it is running\n if (epoch + 1) % 1000 == 0:\n print(f\"epoch: {epoch+1}, loss = {loss.item():.4f}\")\n "
] | [
[
"torch.sigmoid",
"sklearn.datasets.make_classification",
"torch.nn.BCELoss",
"torch.tensor",
"torch.nn.Linear"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mpc-msri-dev/EzPC | [
"a489c49d5c92f51df0277a7e5751e1b8baeb0bc1",
"a489c49d5c92f51df0277a7e5751e1b8baeb0bc1",
"a489c49d5c92f51df0277a7e5751e1b8baeb0bc1"
] | [
"Athos/Networks/SqueezeNetCIFAR10/Squeezenet_model.py",
"Athos/HelperScripts/FindAccuracy_Porthos.py",
"Athos/tests/tf/unittests/test_non_linear.py"
] | [
"'''\r\n\r\nAuthors: Nishant Kumar.\r\n\r\nCopyright:\r\nCopyright (c) 2020 Microsoft Research\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\r\n** \r\nParts of this code including the model itself, the training code and some other parts\r\nwere taken from https://github.com/kaizouman/tensorsandbox/tree/master/cifar10/models/squeeze\r\n**\r\n\r\n'''\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport os\r\nimport sys\r\nimport Util\r\nimport time\r\nimport numpy\r\nimport matplotlib\r\nimport tensorflow as tf\r\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'TFCompiler'))\r\nimport DumpTFMtData\r\nfrom argparse import ArgumentParser\r\n\r\nclass SqueezeNet1Orig:\r\n\tdef __init__(self):\r\n\t\tself.all_weights = []\r\n\r\n\tdef inference(self, images):\r\n\t\t# conv1\r\n\t\tconv1 = self.conv_layer(images,\r\n\t\t\t\t\t\t\t\tsize=3,\r\n\t\t\t\t\t\t\t\tfilters=64,\r\n\t\t\t\t\t\t\t\tstride=1,\r\n\t\t\t\t\t\t\t\tdecay=False,\r\n\t\t\t\t\t\t\t\tname='conv1')\r\n\r\n\t\t# pool1\r\n\t\tpool1 = self.pool_layer(conv1,\r\n\t\t\t\t\t\t\t\tsize=3,\r\n\t\t\t\t\t\t\t\tstride=2,\r\n\t\t\t\t\t\t\t\tname='pool1')\r\n\r\n\t\t# fire2\r\n\t\tfire2 = self.fire_layer(pool1, 32, 64, 64, decay=False, name='fire2')\r\n\r\n\t\t# fire3\r\n\t\tfire3 = self.fire_layer(fire2, 32, 64, 64, decay=False, name='fire3')\r\n\r\n\t\t# pool2\r\n\t\tpool2 = self.pool_layer(fire3,\r\n\t\t\t\t\t\t\t\tsize=3,\r\n\t\t\t\t\t\t\t\tstride=2,\r\n\t\t\t\t\t\t\t\tname='pool2')\r\n\r\n\t\t# fire4\r\n\t\tfire4 = self.fire_layer(pool2, 32, 128, 128, decay=False, name='fire4')\r\n\r\n\t\t# fire5\r\n\t\tfire5 = self.fire_layer(fire4, 32, 128, 128, decay=False, name='fire5')\r\n\r\n\t\t# Final squeeze to get ten classes\r\n\t\tconv2 = self.conv_layer(fire5,\r\n\t\t\t\t\t\t\t\tsize=1,\r\n\t\t\t\t\t\t\t\tfilters=10,\r\n\t\t\t\t\t\t\t\tstride=1,\r\n\t\t\t\t\t\t\t\tdecay=False,\r\n\t\t\t\t\t\t\t\tname='squeeze')\r\n\r\n\t\t# Average pooling on spatial dimensions\r\n\t\tpredictions = self.avg_layer(conv2, name='avg_pool')\r\n\r\n\t\treturn predictions\r\n\r\n\tdef pool_layer(self, inputs, size, stride, name):\r\n\t\twith tf.variable_scope(name) as scope:\r\n\t\t\toutputs = tf.nn.max_pool(inputs,\r\n\t\t\t\t\t\t\t\t\tksize=[1,size,size,1],\r\n\t\t\t\t\t\t\t\t\tstrides=[1,stride,stride,1],\r\n\t\t\t\t\t\t\t\t\tpadding='SAME',\r\n\t\t\t\t\t\t\t\t\tname=name)\r\n\t\treturn outputs\r\n\r\n\tdef fire_layer(self, inputs, s1x1, e1x1, e3x3, name, decay=False):\r\n\t\twith tf.variable_scope(name) as scope:\r\n\t\t\t# Squeeze sub-layer\r\n\t\t\tsqueezed_inputs = self.conv_layer(inputs,\r\n\t\t\t\t\t\t\t\t\t\t\t size=1,\r\n\t\t\t\t\t\t\t\t\t\t\t filters=s1x1,\r\n\t\t\t\t\t\t\t\t\t\t\t stride=1,\r\n\t\t\t\t\t\t\t\t\t\t\t decay=decay,\r\n\t\t\t\t\t\t\t\t\t\t\t name='s1x1')\r\n\r\n\t\t\t# Expand 1x1 sub-layer\r\n\t\t\te1x1_outputs = self.conv_layer(squeezed_inputs,\r\n\t\t\t\t\t\t\t\t\t\t size=1,\r\n\t\t\t\t\t\t\t\t\t\t filters=e1x1,\r\n\t\t\t\t\t\t\t\t\t\t stride=1,\r\n\t\t\t\t\t\t\t\t\t\t decay=decay,\r\n\t\t\t\t\t\t\t\t\t\t name='e1x1')\r\n\r\n\t\t\t# Expand 3x3 sub-layer\r\n\t\t\te3x3_outputs = self.conv_layer(squeezed_inputs,\r\n\t\t\t\t\t\t\t\t\t\t size=3,\r\n\t\t\t\t\t\t\t\t\t\t filters=e3x3,\r\n\t\t\t\t\t\t\t\t\t\t stride=1,\r\n\t\t\t\t\t\t\t\t\t\t decay=decay,\r\n\t\t\t\t\t\t\t\t\t\t name='e3x3')\r\n\r\n\t\t\t# Concatenate outputs along the last dimension (channel)\r\n\t\t\treturn tf.concat([e1x1_outputs, e3x3_outputs], 3)\r\n\r\n\tdef avg_layer(self, inputs, name):\r\n\t\tw = inputs.get_shape().as_list()[1]\r\n\t\th = inputs.get_shape().as_list()[2]\r\n\t\tc = inputs.get_shape().as_list()[3]\r\n\t\twith tf.variable_scope(name) as scope:\r\n\t\t\t# Use current spatial dimensions as Kernel size to produce a scalar\r\n\t\t\tavg = tf.nn.avg_pool(inputs,\r\n\t\t\t\t\t ksize=[1,w,h,1],\r\n\t\t\t\t\t strides=[1,1,1,1],\r\n\t\t\t\t\t padding='VALID',\r\n\t\t\t\t\t name=scope.name)\r\n\t\t# Reshape output to remove spatial dimensions reduced to one\r\n\t\treturn tf.reshape(avg, shape=[-1,c])\r\n\r\n\tdef conv_layer(self, inputs, size, filters, stride, decay, name):\r\n\t\tchannels = inputs.shape[3]\r\n\t\tshape = [size, size, channels, filters]\r\n\t\twith tf.variable_scope(name + '/conv') as scope:\r\n\t\t\tweights = self._get_weights_var('weights', shape=shape, decay=decay)\r\n\t\t\tbiases = self.get_cons_variable([filters], 0.0)\r\n\t\t\tconv = tf.nn.conv2d(inputs,\r\n\t\t\t\t\tweights,\r\n\t\t\t\t\tstrides=[1,stride,stride,1],\r\n\t\t\tpadding='SAME')\r\n\r\n\t\t\tpre_activation = tf.nn.bias_add(conv, biases)\r\n\r\n\t\t\toutputs= tf.nn.relu(pre_activation, name=scope.name)\r\n\r\n\t\treturn outputs\r\n\r\n\tdef get_cons_variable(self, shape, val):\r\n\t\tinitial = tf.constant(val, shape=shape)\r\n\t\ttemp = tf.Variable(initial)\r\n\t\tself.all_weights.append(temp)\r\n\t\treturn temp\r\n\r\n\tdef _get_weights_var(self, name, shape, decay=False):\r\n\t\t\"\"\"Helper to create an initialized Variable with weight decay.\r\n\r\n\t\tThe Variable is initialized using a normal distribution whose variance\r\n\t\tis provided by the xavier formula (ie inversely proportional to the number\r\n\t\tof inputs)\r\n\r\n\t\tArgs:\r\n\t\t\tname: name of the tensor variable\r\n\t\t\tshape: the tensor shape\r\n\t\t\tdecay: a boolean indicating if we apply decay to the tensor weights\r\n\t\t\tusing a regularization loss\r\n\r\n\t\tReturns:\r\n\t\t\tVariable Tensor\r\n\t\t\"\"\"\r\n\t\t# Declare an initializer for this variable\r\n\t\tinitializer = tf.contrib.layers.xavier_initializer(uniform=False,dtype=tf.float32)\r\n\t\t# Declare variable (it is trainable by default)\r\n\t\tvar = tf.get_variable(name=name,\r\n\t\t\t\t\t\t\t shape=shape,\r\n\t\t\t\t\t\t\t initializer=initializer,\r\n\t\t\t\t\t\t\t dtype=tf.float32)\r\n\t\tif decay:\r\n\t\t\t# We apply a weight decay to this tensor var that is equal to the\r\n\t\t\t# model weight decay divided by the tensor size\r\n\t\t\tweight_decay = self.wd\r\n\t\t\tfor x in shape:\r\n\t\t\t\tweight_decay /= x\r\n\t\t\t# Weight loss is L2 loss multiplied by weight decay\r\n\t\t\tweight_loss = tf.multiply(tf.nn.l2_loss(var),\r\n\t\t\t\t\t\t\t\t\t weight_decay,\r\n\t\t\t\t\t\t\t\t\t name='weight_loss')\r\n\t\t\t# Add weight loss for this variable to the global losses collection\r\n\t\t\ttf.add_to_collection('losses', weight_loss)\r\n\r\n\t\tself.all_weights.append(var)\r\n\t\treturn var\r\n\r\nclass SqueezeNet1:\r\n\tdef __init__(self, use_cons_init):\r\n\t\tself.all_weights = []\r\n\t\tself.debug_weights = []\r\n\t\tself.use_cons_init = use_cons_init\r\n\r\n\tdef inference(self, images):\r\n\t\t# conv1\r\n\t\tconv1 = self.conv_layer(images,\r\n\t\t\t\t\t\t\t\tsize=3,\r\n\t\t\t\t\t\t\t\tfilters=64,\r\n\t\t\t\t\t\t\t\tstride=1,\r\n\t\t\t\t\t\t\t\tdecay=False,\r\n\t\t\t\t\t\t\t\tname='conv1')\r\n\r\n\t\t# pool1\r\n\t\tpool1 = self.pool_layer(conv1,\r\n\t\t\t\t\t\t\t\tsize=3,\r\n\t\t\t\t\t\t\t\tstride=2,\r\n\t\t\t\t\t\t\t\tname='pool1')\r\n\r\n\t\t# fire2\r\n\t\tfire2 = self.fire_layer(pool1, 32, 64, 64, decay=False, name='fire2')\r\n\r\n\t\t# fire3\r\n\t\tfire3 = self.fire_layer(fire2, 32, 64, 64, decay=False, name='fire3')\r\n\r\n\t\t# pool2\r\n\t\tpool2 = self.pool_layer(fire3,\r\n\t\t\t\t\t\t\t\tsize=3,\r\n\t\t\t\t\t\t\t\tstride=2,\r\n\t\t\t\t\t\t\t\tname='pool2')\r\n\r\n\t\t# fire4\r\n\t\tfire4 = self.fire_layer(pool2, 32, 128, 128, decay=False, name='fire4')\r\n\r\n\t\t# fire5\r\n\t\tfire5 = self.fire_layer(fire4, 32, 128, 128, decay=False, name='fire5')\r\n\r\n\t\t# Final squeeze to get ten classes\r\n\t\tconv2 = self.conv_layer(fire5,\r\n\t\t\t\t\t\t\t\tsize=1,\r\n\t\t\t\t\t\t\t\tfilters=10,\r\n\t\t\t\t\t\t\t\tstride=1,\r\n\t\t\t\t\t\t\t\tdecay=False,\r\n\t\t\t\t\t\t\t\tname='squeeze')\r\n\r\n\t\t# Average pooling on spatial dimensions\r\n\t\tpredictions = self.avg_layer(conv2, name='avg_pool')\r\n\r\n\t\treturn predictions\r\n\r\n\tdef pool_layer(self, inputs, size, stride, name):\r\n\t\twith tf.variable_scope(name) as scope:\r\n\t\t\toutputs = tf.nn.max_pool(inputs,\r\n\t\t\t\t\t\t\t\t\tksize=[1,size,size,1],\r\n\t\t\t\t\t\t\t\t\tstrides=[1,stride,stride,1],\r\n\t\t\t\t\t\t\t\t\tpadding='SAME',\r\n\t\t\t\t\t\t\t\t\tname=name)\r\n\t\treturn outputs\r\n\r\n\tdef fire_layer(self, inputs, s1x1, e1x1, e3x3, name, decay=False):\r\n\t\twith tf.variable_scope(name) as scope:\r\n\t\t\t# Squeeze sub-layer\r\n\t\t\tsqueezed_inputs = self.conv_layer(inputs,\r\n\t\t\t\t\t\t\t\t\t\t\t size=1,\r\n\t\t\t\t\t\t\t\t\t\t\t filters=s1x1,\r\n\t\t\t\t\t\t\t\t\t\t\t stride=1,\r\n\t\t\t\t\t\t\t\t\t\t\t decay=decay,\r\n\t\t\t\t\t\t\t\t\t\t\t name='s1x1')\r\n\r\n\t\t\t# Expand 1x1 sub-layer\r\n\t\t\te1x1_outputs = self.conv_layer(squeezed_inputs,\r\n\t\t\t\t\t\t\t\t\t\t size=1,\r\n\t\t\t\t\t\t\t\t\t\t filters=e1x1,\r\n\t\t\t\t\t\t\t\t\t\t stride=1,\r\n\t\t\t\t\t\t\t\t\t\t decay=decay,\r\n\t\t\t\t\t\t\t\t\t\t name='e1x1')\r\n\r\n\t\t\t# Expand 3x3 sub-layer\r\n\t\t\te3x3_outputs = self.conv_layer(squeezed_inputs,\r\n\t\t\t\t\t\t\t\t\t\t size=3,\r\n\t\t\t\t\t\t\t\t\t\t filters=e3x3,\r\n\t\t\t\t\t\t\t\t\t\t stride=1,\r\n\t\t\t\t\t\t\t\t\t\t decay=decay,\r\n\t\t\t\t\t\t\t\t\t\t name='e3x3')\r\n\r\n\t\t\t# Concatenate outputs along the last dimension (channel)\r\n\t\t\treturn tf.concat([e1x1_outputs, e3x3_outputs], 3)\r\n\r\n\tdef avg_layer(self, inputs, name):\r\n\t\tw = inputs.get_shape().as_list()[1]\r\n\t\th = inputs.get_shape().as_list()[2]\r\n\t\tc = inputs.get_shape().as_list()[3]\r\n\t\twith tf.variable_scope(name) as scope:\r\n\t\t\t# Use current spatial dimensions as Kernel size to produce a scalar\r\n\t\t\tavg = tf.nn.avg_pool(inputs,\r\n\t\t\t\t\t ksize=[1,w,h,1],\r\n\t\t\t\t\t strides=[1,1,1,1],\r\n\t\t\t\t\t padding='VALID',\r\n\t\t\t\t\t name=scope.name)\r\n\t\t# Reshape output to remove spatial dimensions reduced to one\r\n\t\treturn tf.reshape(avg, shape=[-1,c])\r\n\r\n\tdef conv_layer(self, inputs, size, filters, stride, decay, name):\r\n\t\tchannels = inputs.shape[3]\r\n\t\tshape = [size, size, channels, filters]\r\n\t\twith tf.variable_scope(name + '/conv') as scope:\r\n\t\t\t# For getting performance numbers, don't need to use the actual activations - just use constant activations\r\n\t\t\tif self.use_cons_init:\r\n\t\t\t\tweights = self.get_cons_variable(shape, 0.01)\r\n\t\t\telse:\r\n\t\t\t\tweights = self._get_weights_var('weights', shape=shape, decay=decay)\r\n\r\n\t\t\tbiases = self.get_cons_variable([filters], 0.0)\r\n\t\t\tconv = tf.nn.conv2d(inputs,\r\n\t\t\t\t\t\t\t\tweights,\r\n\t\t\t\t\t\t\t\tstrides=[1,stride,stride,1],\r\n\t\t\t\t\t\t\t\tpadding='SAME')\r\n\r\n\t\t\tpre_activation = tf.nn.bias_add(conv, biases)\r\n\t\t\toutputs= tf.nn.relu(pre_activation, name=scope.name)\r\n\r\n\t\treturn outputs\r\n\r\n\tdef get_cons_variable(self, shape, val):\r\n\t\tinitial = tf.constant(val, shape=shape)\r\n\t\ttemp = tf.Variable(initial)\r\n\t\tself.all_weights.append(temp)\r\n\t\treturn temp\r\n\r\n\tdef _get_weights_var(self, name, shape, decay=False):\r\n\t\t\"\"\"Helper to create an initialized Variable with weight decay.\r\n\r\n\t\tThe Variable is initialized using a normal distribution whose variance\r\n\t\tis provided by the xavier formula (ie inversely proportional to the number\r\n\t\tof inputs)\r\n\r\n\t\tArgs:\r\n\t\t\tname: name of the tensor variable\r\n\t\t\tshape: the tensor shape\r\n\t\t\tdecay: a boolean indicating if we apply decay to the tensor weights\r\n\t\t\tusing a regularization loss\r\n\r\n\t\tReturns:\r\n\t\t\tVariable Tensor\r\n\t\t\"\"\"\r\n\t\t# Declare an initializer for this variable\r\n\t\tinitializer = tf.contrib.layers.xavier_initializer(uniform=False,dtype=tf.float32)\r\n\t\t# Declare variable (it is trainable by default)\r\n\t\tvar = tf.get_variable(name=name,\r\n\t\t\t\t\t\t\t shape=shape,\r\n\t\t\t\t\t\t\t initializer=initializer,\r\n\t\t\t\t\t\t\t dtype=tf.float32)\r\n\t\tif decay:\r\n\t\t\t# We apply a weight decay to this tensor var that is equal to the\r\n\t\t\t# model weight decay divided by the tensor size\r\n\t\t\tweight_decay = self.wd\r\n\t\t\tfor x in shape:\r\n\t\t\t\tweight_decay /= x\r\n\t\t\t# Weight loss is L2 loss multiplied by weight decay\r\n\t\t\tweight_loss = tf.multiply(tf.nn.l2_loss(var),\r\n\t\t\t\t\t\t\t\t\t weight_decay,\r\n\t\t\t\t\t\t\t\t\t name='weight_loss')\r\n\t\t\t# Add weight loss for this variable to the global losses collection\r\n\t\t\ttf.add_to_collection('losses', weight_loss)\r\n\r\n\t\tself.all_weights.append(var)\r\n\t\treturn var\r\n\r\ndef train(sqn, save_model_path):\r\n\tprint('Starting train...')\r\n\r\n\t# Hyper parameters\r\n\tepochs = 1\r\n\tbatch_size = 128\r\n\tkeep_probability = 0.7\r\n\tlearning_rate = 0.001\r\n\tn_batches = 5 #CIFAR10 dataset in the python version has 5 batches\r\n\r\n\tx = tf.placeholder(tf.float32, shape=(None, 32, 32, 3), name='input_x')\r\n\ty = tf.placeholder(tf.float32, shape=(None, 10), name='output_y')\r\n\tkeep_prob = tf.placeholder(tf.float32, name='keep_prob')\r\n\r\n\tlogits = sqn.inference(x)\r\n\r\n\t# Loss and Optimizer\r\n\tcost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))\r\n\tl2Loss = sum(list(map(lambda x: tf.nn.l2_loss(x), sqn.all_weights)))\r\n\tbeta = 1e-5\r\n\tcost = cost + beta*l2Loss\r\n\toptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\r\n\r\n\t# Accuracy\r\n\tcorrect_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))\r\n\taccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy')\r\n\r\n\tvalid_features, valid_labels = Util.load_preprocess_validation_data()\r\n\ttesting_features, testing_labels = Util.load_preprocess_testing_data()\r\n\r\n\tprint('Training now...')\r\n\twith tf.Session() as sess:\r\n\t\t# Initializing the variables\r\n\t\tsess.run(tf.global_variables_initializer())\r\n\r\n\t\t# Training cycle\r\n\t\tfor epoch in range(epochs):\r\n\t\t\t# Loop over all batches\r\n\t\t\tfor batch_i in range(1, n_batches + 1):\r\n\t\t\t\tfor batch_features, batch_labels in Util.load_preprocess_training_batch(batch_i, batch_size):\r\n\t\t\t\t\tsess.run(optimizer, feed_dict={x: batch_features,\r\n\t\t\t\t\t\t\t\t\t\t\t\t y: batch_labels,\r\n\t\t\t\t\t\t\t\t\t\t\t\t keep_prob: keep_probability\r\n\t\t\t\t\t\t\t\t\t\t\t\t })\r\n\r\n\t\t\t\tprint('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='')\r\n\t\t\t\t\r\n\t\t\t\t# Print stats\r\n\t\t\t\tloss = sess.run(cost, feed_dict={x: batch_features, y: batch_labels, keep_prob: keep_probability})\r\n\t\t\t\ttrain_acc = sess.run(accuracy, feed_dict={x: batch_features, y: batch_labels, keep_prob: keep_probability})\r\n\t\t\t\tvalid_acc = sess.run(accuracy, feed_dict={x: valid_features, y: valid_labels, keep_prob: keep_probability})\r\n\t\t\t\ttesting_acc = sess.run(accuracy, feed_dict={x: testing_features, y: testing_labels, keep_prob: keep_probability})\r\n\t\t\t\tprint('Loss: {:>10.4f} Train Acc: {:.6f} Validation Accuracy: {:.6f} Testing Acc: {:.6f}'.format(loss, train_acc, valid_acc, testing_acc))\r\n\r\n\t\t\tif (epoch % 10 == 0):\r\n\t\t\t\t# Save Model\r\n\t\t\t\tsaver = tf.train.Saver()\r\n\t\t\t\tsave_path = saver.save(sess, save_model_path)\r\n\r\n#outputArgMax should only be used when findAcc is False\r\ndef infer(sqn, sess, images, labels, restoreModelPath, findAccOrArgMaxOrPredVal=0, restoreWeights=True, onlysavegraph=False):\r\n\tassert(findAccOrArgMaxOrPredVal>=0 and findAccOrArgMaxOrPredVal<=2)\r\n\tif restoreWeights: assert(not(onlysavegraph))\r\n\tif onlysavegraph: assert(findAccOrArgMaxOrPredVal==1)\r\n\r\n\tx = tf.placeholder(tf.float32, shape=(None, 32, 32, 3), name='input_x')\r\n\tif (not(onlysavegraph)):\r\n\t\ty = tf.placeholder(tf.int32, shape=(None, 10), name='output_y')\r\n\tlogits = sqn.inference(x)\r\n\r\n\tif findAccOrArgMaxOrPredVal==0:\r\n\t\tcorrect_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))\r\n\t\taccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy')\r\n\telif findAccOrArgMaxOrPredVal==1:\r\n\t\tlogits = tf.argmax(logits, axis=1)\r\n\telif findAccOrArgMaxOrPredVal==2:\r\n\t\tpass\r\n\telse:\r\n\t\tassert False\r\n\r\n\tprint(\"Doing inference on \", len(images), \" images.\")\r\n\tfeed_dict = {x: images}\r\n\tif not(onlysavegraph):\r\n\t\tfeed_dict[y] = labels\r\n\r\n\tsess.run(tf.global_variables_initializer())\r\n\tif onlysavegraph:\r\n\t\toutput_tensor = None\r\n\t\tgg = tf.get_default_graph()\r\n\t\tfor node in gg.as_graph_def().node:\r\n\t\t\tif node.name == 'ArgMax':\r\n\t\t\t\toutput_tensor = gg.get_operation_by_name(node.name).outputs[0]\r\n\t\toptimized_graph_def = DumpTFMtData.save_graph_metadata(output_tensor, sess, feed_dict)\r\n\t\treturn\r\n\r\n\tif restoreWeights:\r\n\t\tsaver = tf.train.Saver(sqn.all_weights)\r\n\t\tsaver.restore(sess, restoreModelPath)\r\n\r\n\tprint(\"*************** Starting Prediction****************\")\r\n\tstart_time = time.time()\r\n\tif findAccOrArgMaxOrPredVal==0:\r\n\t\tpredictions = sess.run([accuracy], feed_dict=feed_dict)\r\n\telse:\r\n\t\tpredictions = sess.run([logits], feed_dict=feed_dict)\r\n\tend_time = time.time()\r\n\tprint(\"*************** Done Prediction****************\")\r\n\tduration = end_time - start_time\r\n\tprint(\"Time taken in prediction : \", duration)\r\n\r\n\tprint(\"Inference result = \", predictions)\r\n\treturn predictions\r\n\r\ndef getTrainedWeightsStrForm(sess, evalTensors, scalingFac):\r\n\tallWeightsStr = ''\r\n\tfinalParameters = map(lambda x : sess.run(x), evalTensors)\r\n\tfor curParameterVal in finalParameters:\r\n\t\tfor xx in numpy.nditer(curParameterVal, order='C'):\r\n\t\t\tallWeightsStr += (str(int(xx * (1<<scalingFac))) + ' ')\r\n\t\tallWeightsStr += '\\n\\n'\r\n\treturn allWeightsStr\r\n\r\ndef findAndSaveCorrectTestImg(pred, features, actualLabels, correctImgFolder, incorrectImgFolder, textFolder, sess, sqn, scalingFac):\r\n\t#Run with findAcc=False and outputArgMax=False\r\n\tassert(len(pred)==1 and len(pred[0].shape)==2)\r\n\tmodelPred = numpy.argmax(pred[0], axis=1)\r\n\ttrueLabel = numpy.argmax(actualLabels, axis=1)\r\n\tprint(\"Pred = \", pred)\r\n\tprint(\"actualLabels = \", actualLabels)\r\n\tprint(\"ModelPred = \", modelPred)\r\n\tprint(\"TrueLabel = \", trueLabel)\r\n\tnumImages = len(features)\r\n\tallWeightsStr = getTrainedWeightsStrForm(sess, sqn.all_weights, scalingFac)\r\n\tfor ii in range(numImages):\r\n\t\tcurImage = features[ii]\r\n\t\tif (modelPred[ii]==trueLabel[ii]):\r\n\t\t\tmatplotlib.image.imsave(os.path.join(correctImgFolder, str(ii)+'-test.png'), curImage)\r\n\t\telse:\r\n\t\t\tmatplotlib.image.imsave(os.path.join(incorrectImgFolder, str(ii)+'-test.png'), curImage)\r\n\t\ttextInpFileName = os.path.join(textFolder, str(ii)+'-test-inp.txt')\r\n\t\tdumpCifar10Image(curImage, textInpFileName, scalingFac, 'w')\r\n\t\twith open(textInpFileName, 'a') as ff:\r\n\t\t\tff.write(allWeightsStr)\r\n\t\tif (ii%10==0):\r\n\t\t\tprint(\"Processing \", ii, \" images done.\")\r\n\r\ndef main():\r\n\tscalingFac = 12\r\n\tfindAccOrArgMaxOrPredVal = 0\r\n\trestoreWeights = True\r\n\tonlysavegraph = False\r\n\tsave_model_path = './TrainedModel/model'\r\n\tdoTraining = False\r\n\r\n\tinp = None\r\n\tif (len(sys.argv) > 1):\r\n\t\tinp = sys.argv[1]\r\n\t\tif (inp == 'train'):\r\n\t\t\tdoTraining = True\r\n\t\telif (inp == 'savegraph'):\r\n\t\t\tfindAccOrArgMaxOrPredVal = 1\r\n\t\t\trestoreWeights = False\r\n\t\t\tonlysavegraph = True\r\n\t\t\ttesting_features, testing_labels = Util.get_sample_points(2, 4555, 4556)\r\n\t\telif (inp == 'testSingleTestInp'):\r\n\t\t\ttestBatchInpNum = int(sys.argv[2])\r\n\t\t\tfindAccOrArgMaxOrPredVal = 1\r\n\t\t\trestoreWeights = True\r\n\t\t\tonlysavegraph = False\r\n\t\t\tall_testing_features, all_testing_labels = Util.load_preprocess_testing_data()\r\n\t\t\ttesting_features, testing_labels = all_testing_features[testBatchInpNum:testBatchInpNum+1], all_testing_labels[testBatchInpNum:testBatchInpNum+1]\r\n\t\telif (inp == 'testSingleTestInpAndSaveData'):\r\n\t\t\ttestBatchInpNum = int(sys.argv[2])\r\n\t\t\tfindAccOrArgMaxOrPredVal = int(sys.argv[3])\r\n\t\t\trestoreWeights = True\r\n\t\t\tonlysavegraph = False\r\n\t\t\tall_testing_features, all_testing_labels = Util.load_preprocess_testing_data()\r\n\t\t\ttesting_features, testing_labels = all_testing_features[testBatchInpNum:testBatchInpNum+1], all_testing_labels[testBatchInpNum:testBatchInpNum+1]\r\n\t\t\t# testing_features, testing_labels = numpy.full((1,32,32,3),0.01), numpy.full((1,10),0.01)\r\n\t\telif (inp == 'savegraphAndDataBatch'):\r\n\t\t\tbatchNum = int(sys.argv[2])\r\n\t\t\timgStartNum = int(sys.argv[3])\r\n\t\t\timgEndNum = int(sys.argv[4])\r\n\t\t\tfindAccOrArgMaxOrPredVal = 1\r\n\t\t\trestoreWeights = False\r\n\t\t\tonlysavegraph = True\r\n\t\t\ttesting_features, testing_labels = Util.get_sample_points(batchNum, imgStartNum, imgEndNum)\r\n\t\telif (inp == 'testBatchInp'):\r\n\t\t\timgStartNum = int(sys.argv[2])\r\n\t\t\timgEndNum = int(sys.argv[3])\r\n\t\t\tfindAccOrArgMaxOrPredVal = 1\r\n\t\t\trestoreWeights = True\r\n\t\t\tonlysavegraph = False\r\n\t\t\tall_testing_features, all_testing_labels = Util.load_preprocess_testing_data()\r\n\t\t\ttesting_features, testing_labels = all_testing_features[imgStartNum:imgEndNum], all_testing_labels[imgStartNum:imgEndNum]\r\n\t\telif (inp == 'findAndSaveCorrectTestImg'):\r\n\t\t\tfindAccOrArgMaxOrPredVal = 2\r\n\t\t\trestoreWeights = True\r\n\t\t\tonlysavegraph = False\r\n\t\t\ttesting_features, testing_labels = Util.load_preprocess_testing_data()\r\n\t\t\ttesting_features, testing_labels = testing_features[0:100], testing_labels[0:100]\r\n\t\telse:\r\n\t\t\tif (inp != \"\"):\r\n\t\t\t\tprint(\"WARNING : Given option didn't match any known value.\")\r\n\t\t\ttesting_features, testing_labels = Util.load_preprocess_testing_data()\r\n\r\n\tsqn = SqueezeNet1(use_cons_init=onlysavegraph)\r\n\tif doTraining:\r\n\t\ttrain(sqn, save_model_path)\r\n\telse:\r\n\t\twith tf.Session() as sess:\r\n\t\t\tpred = infer(sqn, sess, testing_features, testing_labels, save_model_path, findAccOrArgMaxOrPredVal=findAccOrArgMaxOrPredVal, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trestoreWeights=restoreWeights, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tonlysavegraph=onlysavegraph)\r\n\t\t\tif findAccOrArgMaxOrPredVal==1 and not(onlysavegraph): \r\n\t\t\t\tprint(\"Actual labels = \", testing_labels)\r\n\t\t\t\tprint(\"ArgMax in actual label : \", numpy.argmax(testing_labels, axis=1))\r\n\r\n\t\t\tif (inp == 'findAndSaveCorrectTestImg'):\r\n\t\t\t\tprint('Running ' + inp)\r\n\t\t\t\tprint(pred[0].shape)\r\n\t\t\t\tfindAndSaveCorrectTestImg(pred, testing_features, testing_labels, './testPred/CorrectImg/', './testPred/IncorrectImg/', './testPred/TestInputs/', sess, sqn, scalingFac)\r\n\r\n\t\t\tif (inp == 'savegraphAndDataBatch' or inp=='testSingleTestInpAndSaveData'):\r\n\t\t\t\timgFileName = 'SqNet_CIFAR_img.inp'\r\n\t\t\t\tweightsFileName = 'SqNet_CIFAR_weights.inp'\r\n\t\t\t\tfor ii,curFeature in enumerate(testing_features):\r\n\t\t\t\t\tif ii == 0 :\r\n\t\t\t\t\t\tDumpTFMtData.dumpImageDataInt(curFeature, imgFileName, scalingFac, 'w')\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tDumpTFMtData.dumpImageDataInt(curFeature, imgFileName, scalingFac, 'a')\r\n\t\t\t\tDumpTFMtData.dumpTrainedWeightsInt(sess, sqn.all_weights, weightsFileName, scalingFac, 'w')\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n\t\n",
"'''\r\n\r\nAuthors: Nishant Kumar.\r\n\r\nCopyright:\r\nCopyright (c) 2020 Microsoft Research\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\r\n'''\r\n\r\n# Use this script to find accuracy once the full exploration has been done on relevant scale factors.\r\n# NOTE: The ground truth labels are in [1, 1000].\r\n#\t\tResnet outputs labels in [0,1000] -- class 0 is extraneous and is the other category.\r\n#\t\tFor DenseNet and SqueezeNet, the labels after argmax are in [0,999]:\r\n#\t\t\tso either we have to do ground truth labels-1 or while outputing from the code for SqNet/DenseNet,\r\n#\t\t\tadd a +1. Choosing to go with the former.\r\n#\t\tSo, in summary, when running resnet, use the last parameter as 1, while for SqueezeNet/DenseNet use it as 0.\r\n\r\nimport os, sys\r\nimport numpy as np\r\n\r\nif (len(sys.argv) < 4):\r\n\tprint(\"Usage : python3 FindAccuracy_Porthos.py <groundTruthLabelsFileName> <inferenceOutputDirectory> <lowerBoundOfOutputLabels>\")\r\n\texit(1)\r\n\r\n# Change following parameters accordingly\r\nScalesToCheck = [9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]\r\n# ScalesToCheck = [11]\r\nnumImages = 96\r\ntopK = 5\r\n\r\ngroundTruthLabelsFileName = sys.argv[1]\r\ninferenceOutputDirectory = sys.argv[2]\r\nlowerBoundOfOutputLabels = int(sys.argv[3])\r\nif (lowerBoundOfOutputLabels != 0 and lowerBoundOfOutputLabels != 1):\r\n\tprint(\"lowerBoundOfOutputLabels should be either 0 or 1. Exiting.\", file=sys.stderr)\r\n\texit(1)\r\n\r\nwith open(groundTruthLabelsFileName, 'r') as ff:\r\n\tgroundTruthLabels = ff.readlines()\r\n\r\ngroundTruthLabels = list(map(lambda x : int(x.rstrip()), groundTruthLabels)) #For imagenet, this is in [1,1000]\r\nif (lowerBoundOfOutputLabels==0):\r\n\tgroundTruthLabels = list(map(lambda x : x-1, groundTruthLabels)) #If the labels in the output start from 0, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t # subtract 1 from the ground truth labels.\r\n\r\ndef parseInferenceOutputFile(predictions, i, outputFileName):\r\n\twith open(outputFileName, 'r') as ff:\r\n\t\tlines = ff.readlines()\r\n\tlines = list(map(lambda x : x.rstrip(), lines))\r\n\tlines = list(filter(lambda x : x!='', lines))\r\n\tif(len(lines)!=2):\r\n\t\tprint(\"Error in parsing : \"+outputFileName)\r\n\t\tassert(False)\r\n\timgCounter = None\r\n\tfor line in lines:\r\n\t\tif (line.startswith('Answer for')):\r\n\t\t\timgCounter = int(line.split('=')[1].split(':')[0]) #This is assumed to be 0-indexed\r\n\t\telse:\r\n\t\t\tassert(imgCounter is not None)\r\n\t\t\tpreds = line.split()\r\n\t\t\t# print(imgCounter,preds)\r\n\t\t\tpreds = np.array(list(map(lambda x : int(x), preds)))\r\n\t\t\ttopKPredsIdx = np.argpartition(preds, -1*topK)[-1*topK:]\r\n\t\t\ttopKPredsIdx = topKPredsIdx[np.argsort(preds[topKPredsIdx])]\r\n\t\t\tfor i, val in enumerate(topKPredsIdx):\r\n\t\t\t\tpredictions[imgCounter][i] = val\r\n\r\ndef calculateAccuracy(predictions):\r\n\tglobal groundTruthLabels\r\n\ttop1CorrectPred = 0\r\n\ttopKCorrectPred = 0\r\n\tfor i in range(numImages):\r\n\t\tif not(predictions[i][0]):\r\n\t\t\tcontinue\r\n\t\tif (groundTruthLabels[i] == predictions[i][-1]):\r\n\t\t\ttop1CorrectPred += 1\r\n\t\tif (groundTruthLabels[i] in predictions[i]):\r\n\t\t\ttopKCorrectPred += 1\r\n\treturn (top1CorrectPred/(1.0*numImages), topKCorrectPred/(1.0*numImages))\r\n\r\n\r\nfor curScale in ScalesToCheck:\r\n\tpredictions = [[None]*topK for _ in range(numImages)]\r\n\tfor i in range(numImages):\r\n\t\tcurFileName = os.path.join(inferenceOutputDirectory, 'stderr_' + str(curScale) + '_' + str(i) +'_proc_1.outp')\r\n\t\tparseInferenceOutputFile(predictions, i, curFileName)\r\n\tfor i in range(numImages):\r\n\t\tfor j in range(topK):\r\n\t\t\tassert(predictions[i][j] is not None)\r\n\t(top1Acc, topKAcc) = calculateAccuracy(predictions)\r\n\tprint(\"curScale = \" + str(curScale) + \", top1Acc = \" + str(top1Acc) + \", topKAcc = \" + str(topKAcc))\r\n\r\n\r\n",
"'''\n\nAuthors: Pratik Bhatu.\n\nCopyright:\nCopyright (c) 2021 Microsoft Research\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n'''\nimport tensorflow as tf\nimport numpy as np\n\nimport pytest\n\nimport sys\nimport os\n\n# Athos DIR\nsys.path.append(os.path.join(os.path.dirname(__file__), \"..\", \"..\", \"..\"))\nfrom tests.utils import Config, Compiler, assert_almost_equal\n\n\[email protected](reason=\"[non-linear] Haven't made non-linear functionalities public\")\[email protected](\"a_shape\", [[4, 4], [1], []])\[email protected](\"dtype\", [np.single])\[email protected](\n \"tfOp\",\n [\n tf.math.sqrt,\n tf.math.rsqrt,\n tf.math.sigmoid,\n tf.math.tanh,\n tf.nn.relu,\n ],\n)\ndef test_non_linear(test_dir, backend, tfOp, a_shape, dtype):\n graph = tf.Graph()\n a_inp = dtype(np.random.randn(*a_shape))\n with graph.as_default():\n a = tf.compat.v1.placeholder(tf.as_dtype(dtype), shape=a_inp.shape, name=\"a\")\n output = tfOp(a, name=\"output\")\n with tf.compat.v1.Session(graph=graph) as sess:\n expected_output = sess.run(output, feed_dict={a: a_inp})\n assert expected_output is not None\n config = Config(backend).add_input(a).add_output(output)\n compiler = Compiler(graph, config, test_dir)\n mpc_output = compiler.compile_and_run([a_inp])\n assert_almost_equal(tf_output=expected_output, mpc_tensor=mpc_output, precision=2)\n return\n\[email protected](reason=\"[softmax] Haven't made non-linear functionalities public\")\[email protected](\"a_shape, axis\", [([2, 3], 1), ([1], 0)])\[email protected](\"dtype\", [np.single])\ndef test_softmax(test_dir, backend, a_shape, axis, dtype):\n graph = tf.Graph()\n a_inp = dtype(np.random.randn(*a_shape))\n with graph.as_default():\n a = tf.compat.v1.placeholder(tf.as_dtype(dtype), shape=a_inp.shape, name=\"a\")\n output = tf.nn.softmax(a, axis=axis, name=\"output\")\n with tf.compat.v1.Session(graph=graph) as sess:\n expected_output = sess.run(output, feed_dict={a: a_inp})\n assert expected_output is not None\n config = Config(backend).add_input(a).add_output(output)\n compiler = Compiler(graph, config, test_dir)\n mpc_output = compiler.compile_and_run([a_inp])\n assert_almost_equal(tf_output=expected_output, mpc_tensor=mpc_output, precision=2)\n return\n"
] | [
[
"tensorflow.get_variable",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.concat",
"tensorflow.nn.max_pool",
"tensorflow.cast",
"tensorflow.nn.l2_loss",
"tensorflow.train.AdamOptimizer",
"tensorflow.get_default_graph",
"tensorflow.nn.conv2d",
"tensorflow.Variable",
"numpy.argmax",
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.Session",
"tensorflow.train.Saver",
"tensorflow.argmax",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.nn.avg_pool",
"tensorflow.add_to_collection",
"tensorflow.nn.bias_add",
"tensorflow.nn.relu",
"tensorflow.constant",
"numpy.nditer",
"tensorflow.reshape",
"tensorflow.variable_scope"
],
[
"numpy.argsort",
"numpy.argpartition"
],
[
"tensorflow.Graph",
"tensorflow.nn.softmax",
"tensorflow.as_dtype",
"tensorflow.compat.v1.Session",
"numpy.random.randn"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
KunyFox/MRTv2 | [
"7b7a156be6f99082964227babd9e157708255b2c"
] | [
"mxmrt/from_tensorflow.py"
] | [
"from tensorflow_parser import TFParser\nfrom tensorflow.core.framework import tensor_pb2 as tpb2\nfrom tensorflow.core.framework import tensor_shape_pb2 as tspb2\nfrom tensorflow.core.framework import attr_value_pb2 as apb2\nfrom tensorflow.python.framework import dtypes\nimport mxnet as mx\nfrom mxnet import nd\nimport numpy as np\n\nimport os\nimport logging\nimport utils\nimport cvm_op as cvm\nimport numpy as np\nfrom tfm_pass import infer_shape\n# from python.tvm.relay.op import op as _op\n\n# import heapq\nimport sym_utils as sutils\nimport sym_pass as spass\n\ndef _queue_dequeue(inputs, attrs, params):\n return inputs[0]\n\ndef _argmax(inputs, attrs, params):\n cname = inputs[1].attr('name')\n axis = params[cname].asnumpy()\n return mx.sym.argmax(inputs[0], axis=axis, keepdims=False)\n\ndef _bias_add(inputs, attrs, params):\n input_eids = attrs[\"_input_eids\"]\n infer_shapes = attrs[\"_infer_shapes\"]\n data_shp = infer_shapes[inputs[0].attr('name')][input_eids[0]]\n bias_shp = infer_shapes[inputs[1].attr('name')][input_eids[1]]\n data_format = attrs[\"data_format\"].decode(\"utf-8\")\n if data_format == \"NCHW\":\n inputs[1] = mx.sym.reshape(inputs[1], (1, bias_shp[0], 1, 1))\n return mx.sym.broadcast_add(*inputs)\n\ndef _identity(inputs, attrs, params):\n return inputs[0]\n\ndef _matmul(inputs, attrs, params):\n input_eids = attrs[\"_input_eids\"]\n infer_shapes = attrs[\"_infer_shapes\"]\n bshp = infer_shapes[inputs[1].attr('name')][input_eids[1]]\n if attrs[\"transpose_a\"]:\n inputs[0] = mx.sym.transpose(inputs[0], axes=(1, 0))\n if not attrs[\"transpose_b\"]:\n inputs[1] = mx.sym.transpose(inputs[1], axes=(1, 0))\n bshp = (bshp[1], bshp[0])\n dense_attr = {\n 'no_bias': len(inputs) == 2,\n 'num_hidden': bshp[0],\n }\n return mx.sym.FullyConnected(*inputs, **dense_attr)\n\ndef _mean(inputs, attrs, params):\n input_eids = attrs[\"_input_eids\"]\n infer_shapes = attrs[\"_infer_shapes\"]\n data_shp = infer_shapes[inputs[0].attr('name')][input_eids[0]]\n axis = params.pop(inputs[1].attr('name')).asnumpy().astype('int')\n sym = mx.sym.sum(inputs[0],\n axis=tuple(axis),\n keepdims=attrs[\"keep_dims\"])\n scalar = 1. / np.product([data_shp[ii] for ii in axis])\n scale = mx.sym.var(sym.attr('name') + \"_scale\", shape=(1,))\n params[scale.attr('name')] = nd.array([scalar])\n sym = mx.sym.broadcast_mul(sym, scale)\n return sym\n\ndef _pad(inputs, attrs, params):\n padding = params[inputs[1].attr('name')]\n sym = mx.sym.Custom(inputs[0],\n padding=padding.asnumpy().astype(attrs['Tpaddings']).tolist(),\n op_type=\"cvm_pad\")\n return sym\n\ndef _relu6(inputs, attrs, params):\n return mx.sym.clip(inputs[0], a_min=0, a_max=6)\n\ndef _shape(inputs, attr, params):\n name = sutils.gen_name('shape')\n infer_shapes, input_eids = attr['_infer_shapes'], attr['_input_eids']\n params[name] = nd.array(\n infer_shapes[inputs[0].attr('name')][input_eids[0]], dtype='int32')\n return mx.sym.var(name=name, shape=params[name].shape)\n\ndef _softmax(inputs, attrs, params):\n axis = attrs.get(\"axis\", -1)\n return mx.sym.softmax(*inputs, axis=axis)\n\ndef _get_pad_pair(input1d, kernel1d, stride1d):\n # pl + pr + i = n*s + kd\n # when `padding` in tensorflow is SAME\n # mxnet's intepretation: o = n+1 = ceil(i/s)\n # or o=n+1=floor(i/s) ?\n if input1d % stride1d == 0:\n pad = max(kernel1d - stride1d, 0)\n else:\n pad = max(kernel1d - (input1d % stride1d), 0)\n\n pad_before = pad // 2\n pad_after = pad - pad_before\n\n return [pad_before, pad_after]\n\ndef _conv2d(opname):\n def _impl(inputs, attrs, params):\n data_format = attrs['data_format'].decode(\"utf-8\")\n input_eids = attrs['_input_eids']\n infer_shapes = attrs['_infer_shapes']\n\n assert data_format in [\"NCHW\", \"NHWC\"]\n\n data_shp = infer_shapes[inputs[0].attr('name')][input_eids[0]]\n weight_shp = infer_shapes[inputs[1].attr('name')][input_eids[1]]\n\n if data_format == \"NHWC\":\n inputs[0] = mx.sym.transpose(inputs[0], axes=(0, 3, 1, 2))\n data_shp = [data_shp[ii] for ii in (0, 3, 1, 2)]\n\n # Transpose weight format into \"OIHW\"\n # Note if op is depthwise, original weight format is \"HWOI\" \n # instead of \"HWIO\".\n if opname == 'conv':\n inputs[1] = mx.sym.transpose(inputs[1], axes=(3, 2, 0, 1))\n weight_shp = [weight_shp[ii] for ii in (3, 2, 0, 1)]\n else:\n inputs[1] = mx.sym.transpose(inputs[1], axes=(2, 3, 0, 1))\n weight_shp = [weight_shp[ii] for ii in (2, 3, 0, 1)]\n\n H_idx, W_idx = data_format.find(\"H\"), data_format.find(\"W\")\n dilations = attrs.get('dilations', (1, 1))\n if isinstance(dilations, int):\n dilations = (dilations, dilations)\n elif len(dilations) == 4:\n dilations = (dilations[H_idx], dilations[W_idx])\n\n strides = attrs.get('strides')\n if isinstance(strides, int):\n strides = (strides, strides)\n elif len(strides) == 4:\n strides = (strides[H_idx], strides[W_idx])\n\n padding = attrs['padding'].decode(\"utf-8\")\n if padding == 'VALID':\n padding = (0, 0)\n elif padding == 'SAME':\n stride_h, stride_w = strides\n kernel_h, kernel_w = weight_shp[2:]\n in_h, in_w = data_shp[2], data_shp[3]\n dilation_h, dilation_w = dilations\n dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n pad_v = _get_pad_pair(in_h, dilated_kernel_h, stride_h)\n pad_h = _get_pad_pair(in_w, dilated_kernel_w, stride_w)\n # TODO(wlt): mxnet not supported four-dimension padding\n # padding = (max(pad_v), max(pad_h))\n # assert pad_v[0] == pad_v[1], pad_v\n # assert pad_h[0] == pad_h[1], pad_h\n # padding = (pad_v[0], pad_h[0])\n if pad_v[0] != pad_v[1] or pad_h[0] != pad_h[1]:\n node = mx.sym.pad(\n inputs[0], mode=\"constant\", constant_value=0,\n pad_width=(0, 0, 0, 0, pad_v[0], pad_v[1], pad_h[0], pad_h[1]))\n inputs[0] = node\n padding = (0,0)\n else:\n padding = (pad_v[0], pad_h[0])\n\n assert data_shp[1] % weight_shp[1] == 0\n groups = data_shp[1] // weight_shp[1]\n conv_attr = {\n 'no_bias': (len(inputs) == 2),\n 'dilate': dilations,\n 'kernel': weight_shp[2:],\n 'stride': strides,\n 'pad': padding,\n 'layout': 'NCHW',\n 'num_filter': weight_shp[0],\n 'num_group': groups,\n }\n sym = mx.sym.Convolution(*inputs, **conv_attr)\n\n if data_format == \"NHWC\":\n sym = mx.sym.transpose(sym, axes=(0, 2, 3, 1))\n return sym\n return _impl\n\ndef _elemwise(name):\n def _impl(inputs, attrs, params):\n assert len(inputs) == 2, \\\n \"{} take 2 inputs, {} given\".format(name, len(inputs))\n return sutils.get_mxnet_op(name)(*inputs)\n return _impl\n\ndef _pool2d(pool_type):\n def _impl(inputs, attrs, params):\n data_format = attrs['data_format'].decode(\"utf-8\")\n input_eids = attrs['_input_eids']\n infer_shapes = attrs['_infer_shapes']\n\n assert data_format in [\"NCHW\", \"NHWC\"]\n assert attrs['T'] in [dtypes.float32, dtypes.float16, dtypes.float64]\n\n data_shp = infer_shapes[inputs[0].attr('name')][input_eids[0]]\n\n if data_format == \"NHWC\":\n inputs[0] = mx.sym.transpose(inputs[0], axes=(0, 3, 1, 2))\n data_shp = [data_shp[ii] for ii in (0, 3, 1, 2)]\n\n H_idx, W_idx = data_format.find(\"H\"), data_format.find(\"W\")\n dilations = attrs.get('dilations', (1, 1))\n if isinstance(dilations, int):\n dilations = (dilations, dilations)\n elif len(dilations) == 4:\n dilations = (dilations[H_idx], dilations[W_idx])\n strides = attrs.get('strides')\n if isinstance(strides, int):\n strides = (strides, strides)\n elif len(strides) == 4:\n strides = (strides[H_idx], strides[W_idx])\n\n kernel_size = attrs['ksize']\n if isinstance(kernel_size, int):\n kernel_size = (kernel_size, kernel_size)\n elif len(kernel_size) == 4:\n kernel_size = (kernel_size[H_idx], kernel_size[W_idx])\n\n padding = attrs['padding'].decode(\"utf-8\")\n if padding == 'VALID':\n padding = (0, 0)\n elif padding == 'SAME':\n stride_h, stride_w = strides\n kernel_h, kernel_w = kernel_size\n in_h, in_w = data_shp[2], data_shp[3]\n dilation_h, dilation_w = dilations\n dilated_kernel_h = (kernel_h - 1) * dilation_h + 1\n dilated_kernel_w = (kernel_w - 1) * dilation_w + 1\n pad_v = _get_pad_pair(in_h, dilated_kernel_h, stride_h)\n pad_h = _get_pad_pair(in_w, dilated_kernel_w, stride_w)\n # assert pad_v[0] == pad_v[1]\n # assert pad_h[0] == pad_h[1]\n # padding = (pad_v[0], pad_h[0])\n if pad_v[0] != pad_v[1] or pad_h[0] != pad_h[1]:\n node = mx.sym.pad(\n inputs[0], mode=\"edge\",\n pad_width=(0, 0, 0, 0, pad_v[0], pad_v[1], pad_h[0], pad_h[1]))\n inputs[0] = node\n padding = (0, 0)\n else:\n padding = (pad_v[0], pad_h[0])\n\n pool_attr = {\n 'pool_type': pool_type,\n 'stride': strides,\n 'pad': padding,\n 'kernel': kernel_size,\n }\n\n if pool_type == \"avg\":\n # TODO(wlt): this actually should be count_include_pad False\n # refer to: https://github.com/CortexFoundation/tvm-cvm/pull/57\n pool_attr['count_include_pad'] = True\n # pool_attr['count_include_pad'] = False\n\n sym = mx.sym.Pooling(*inputs, **pool_attr)\n if data_format == \"NHWC\":\n sym = mx.sym.transpose(sym, axes=(0, 2, 3, 1))\n return sym\n return _impl\n\ndef _batch_normalization(inputs, attrs, params):\n data_format = attrs['data_format'].decode(\"utf-8\")\n input_eids = attrs['_input_eids']\n infer_shapes = attrs['_infer_shapes']\n\n assert data_format in [\"NCHW\", \"NHWC\"]\n assert attrs['T'] in [dtypes.float32, dtypes.float16, dtypes.float64]\n assert attrs[\"is_training\"] == False\n\n data_shp = infer_shapes[inputs[0].attr('name')][input_eids[0]]\n\n if data_format == \"NHWC\":\n inputs[0] = mx.sym.transpose(inputs[0], axes=(0, 3, 1, 2))\n data_shp = [data_shp[ii] for ii in (0, 3, 1, 2)]\n\n bn_attr = {\n 'eps': attrs[\"epsilon\"],\n # 'use_global_stats': True,\n 'fix_gamma': False, # TODO: the attribute is requisite, why?\n }\n sym = mx.sym.BatchNorm(*inputs, **bn_attr, name=attrs['name'])\n\n if data_format == \"NHWC\":\n sym = mx.sym.transpose(sym, axes=(0, 2, 3, 1))\n return sym\n\ndef _relu(inputs, attrs, params):\n return mx.sym.relu(*inputs, name=attrs['name'])\n\ndef _concat_v2(inputs, attrs, params):\n axis_sym = inputs.pop(len(inputs) - 1)\n axis = params.pop(axis_sym.attr('name'))\n sym = mx.sym.concat(*inputs, dim=int(axis.reshape((1,)).asscalar()))\n return sym\n\ndef _strided_slice(inputs, attrs, params):\n input_eids, infer_shapes = attrs['_input_eids'], attrs['_infer_shapes']\n begin = params[inputs[1].attr('name')].asnumpy().astype('int').tolist()\n end = params[inputs[2].attr('name')].asnumpy().astype('int').tolist()\n stride = params[inputs[3].attr('name')].asnumpy().astype('int').tolist()\n\n begin_mask = attrs.get('begin_mask', 0)\n end_mask = attrs.get('end_mask', 0)\n ellipsis_mask = attrs.get('ellipsis_mask', 0)\n new_axis_mask = attrs.get('new_axis_mask', 0)\n shrink_axis_mask = attrs.get('shrink_axis_mask', 0)\n\n data_shape = infer_shapes[inputs[0].attr('name')][input_eids[0]]\n data_dim, stride_dim = len(data_shape), len(stride)\n\n def _transform_mask(stride_dim, ellipsis_mask):\n \"\"\"Handle mask inputs to create new begin, end, stride and output shape\"\"\"\n m_begin = [0] * data_dim\n m_end = [0] * data_dim\n m_stride = [0] * data_dim\n fshape_indices = []\n #Count new axis after ellipsis_mask, consider while applying ellipsis_mask.\n ellipsis_seen = False\n new_axes_after_ellipsis = 0\n for i in range(stride_dim):\n mask = 1 << i\n if ellipsis_seen and (mask & new_axis_mask) != 0:\n new_axes_after_ellipsis += 1\n if (mask & ellipsis_mask) != 0:\n ellipsis_seen = True\n if not ellipsis_seen:\n #Used later for extending the stride attributes in the below loop.\n ellipsis_mask |= (1 << stride_dim)\n stride_dim += 1\n final_index = 0\n for index in range(stride_dim):\n mask = 1 << index\n if mask & ellipsis_mask:\n #Identify the end index for applying ellipsis_mask\n to_index = min(((data_dim - (stride_dim-index)) + 1 \\\n + new_axes_after_ellipsis), data_dim)\n for i in range(final_index, to_index):\n m_begin[final_index] = 0\n m_end[final_index] = data_shape[final_index]\n m_stride[final_index] = 1\n fshape_indices.append(final_index)\n final_index += 1\n elif mask &new_axis_mask:\n fshape_indices.append(-1)\n elif not mask & new_axis_mask:\n if final_index == len(m_begin):\n break\n if mask & begin_mask:\n m_begin[final_index] = data_shape[final_index] \\\n if stride[index] < 0 else 0\n elif begin[index]:\n m_begin[final_index] = begin[index]\n if mask & end_mask:\n m_end[final_index] = 0 if stride[index] < 0 \\\n else data_shape[final_index]\n elif end[index]:\n m_end[final_index] = end[index]\n m_stride[final_index] = stride[index]\n if mask & shrink_axis_mask:\n #Tensorflow make axis with shrink_axis_mask as dimension 1\n m_begin[final_index] = data_shape[final_index] + begin[index] \\\n if begin[index] < 0 else begin[index]\n m_end[final_index] = begin[index] + 1\n m_stride[final_index] = 1\n fshape_indices.append(-2)\n else:\n fshape_indices.append(final_index)\n\n final_index += 1\n return m_begin, m_end, m_stride, fshape_indices\n\n fshape_indices = None\n if begin_mask or end_mask or ellipsis_mask or new_axis_mask or shrink_axis_mask:\n begin, end, stride, fshape_indices = _transform_mask(stride_dim, ellipsis_mask)\n\n out = mx.sym.slice(inputs[0], begin=begin, end=end, step=stride)\n _, out_shape, _ = out.infer_shape()\n out_shape = out_shape[0]\n\n if not fshape_indices:\n fshape_indices = range(len(out_shape))\n\n #Create final output shape.\n final_output = []\n for gather_index in fshape_indices:\n if gather_index == -1:\n final_output.append(1)\n elif gather_index == -2:\n pass\n else:\n final_output.append(out_shape[gather_index])\n\n if tuple(final_output) == out_shape:\n return out\n return mx.sym.reshape(out, shape=final_output)\n\ndef _pack(inputs, attrs, params):\n axis = attrs['axis']\n inputs_reshped = []\n for s in inputs:\n if sutils.is_params(s, params):\n name = s.attr('name')\n new_name = name + '_const'\n if params[name].shape == ():\n assert axis == 0\n params[new_name] = nd.array([params[name].asnumpy()],\n dtype=params[name].dtype)\n else:\n params[new_name] = nd.expand_dims(params[name], axis=axis)\n inputs_reshped.append(\n mx.sym.var(new_name, shape=params[new_name].shape))\n else:\n inputs_reshped.append(mx.sym.expand_dims(s, axis=axis))\n\n # inputs_reshped = [mx.sym.expand_dims(i, axis=axis) for i in inputs]\n op = mx.sym.concat(*inputs_reshped, dim=axis)\n return mx.sym.cast(op, attrs['T'])\n\ndef _reshape(inputs, attrs, params):\n X, shape = inputs\n\n graph = {}\n for op in sutils.topo_sort(shape):\n name, op_name = op.attr('name'), op.attr('op_name')\n childs, attr = sutils.sym_iter(op.get_children()), op.list_attr()\n if childs is not None:\n childs = [graph[c.attr('name')] for c in childs]\n\n if sutils.is_var(op, params):\n pass\n elif childs is None:\n params[name] = sutils.get_nd_op(op_name)(**attr)\n op = mx.sym.var(name, shape=params[name].shape)\n else:\n childs = [graph[c.attr('name')] for c in childs]\n assert all([sutils.is_params(c, params) for c in childs])\n in_params = [params[c.attr('name')] for c in childs]\n if op_name == \"expand_dims\" and in_params[0].shape == ():\n params[name] = nd.array([in_params[0].asnumpy()],\n dtype=in_params[0].dtype)\n elif op_name == \"Reshape\" and sutils.get_attr(attr, 'shape') == []:\n assert in_params[0].shape == (1,)\n params[name] = nd.array(in_params[0].asnumpy()[0],\n dtype=in_params[0].dtype)\n else:\n params[name] = sutils.get_nd_op(op_name)(*in_params, **attr)\n op = mx.sym.var(name, shape=params[name].shape)\n graph[name] = op\n\n assert sutils.is_params(graph[shape.attr('name')], params)\n shape = params[shape.attr('name')].asnumpy().tolist()\n shape[0] = -1 # since dim zero is batch, set -1 for flexiblity.\n return mx.sym.reshape(X, shape)\n\ndef _squeeze(inputs, attrs, params):\n new_attrs = {}\n if len(attrs['squeeze_dims']) == 0:\n new_attrs['axis'] = None\n else:\n new_attrs['axis'] = attrs['squeeze_dims']\n return mx.sym.squeeze(*inputs, **new_attrs)\n\n\n_convert_map = {\n 'QueueDequeueManyV2' : _queue_dequeue,\n 'ArgMax' : _argmax,\n 'Add' : _elemwise('elemwise_add'),\n 'AvgPool' : _pool2d(\"avg\"),\n 'BiasAdd' : _bias_add,\n 'ConcatV2' : _concat_v2,\n 'Conv2D' : _conv2d('conv'),\n 'DepthwiseConv2dNative' : _conv2d('depthwise'),\n 'FusedBatchNorm' : _batch_normalization,\n 'Identity' : _identity,\n 'MatMul' : _matmul,\n 'MaxPool' : _pool2d(\"max\"),\n 'Maximum' : _elemwise('maximum'),\n 'Mean' : _mean,\n 'Minimum' : _elemwise('minimum'),\n 'Mul' : _elemwise('multiply'),\n 'Pack' : _pack,\n 'Pad' : _pad,\n 'Pow' : _elemwise('power'),\n 'RealDiv' : _elemwise('divide'),\n 'Relu' : _relu,\n 'Relu6' : _relu6,\n 'Reshape' : _reshape,\n 'Shape' : _shape,\n 'Softmax' : _softmax,\n 'Squeeze' : _squeeze,\n 'Sub' : _elemwise('subtract'),\n 'StridedSlice' : _strided_slice,\n}\n\nfieldOrgTypes = (int, bool, float, bytes)\n\ndef convert_field(attrFields, logger=logging):\n fields = attrFields.ListFields()\n if len(fields) > 1:\n logger.error(\"Multiple AttrValue fields found.\")\n exit()\n elif not len(fields):\n logger.error(\"Null AttrValue field found.\")\n exit()\n _, fieldValue = fields[0]\n if isinstance(fieldValue, fieldOrgTypes):\n return fieldValue\n elif isinstance(fieldValue, tspb2.TensorShapeProto):\n return tuple([dim.size for dim in \\\n fieldValue.ListFields()[0][1]])\n elif isinstance(fieldValue, tpb2.TensorProto):\n # the length of ffields must be 3\n # which is respectively: num, shape, tensor\n ffields = fieldValue.ListFields()\n ff = ffields[1][1].ListFields()\n # the length of ff must be \n if len(ff) == 1:\n shapes = tuple([dim.size for dim in ffields[1][1].ListFields()[0][1]])\n data = ffields[2][1]\n if isinstance(data, bytes):\n return (ffields[0][1], shapes, data)\n elif str(type(data)) == \"<class 'google.protobuf.pyext._message.RepeatedScalarContainer'>\":\n return (ffields[0][1], shapes, data[0])\n else:\n logger.error(\"data error 2\")\n exit()\n elif not len(ff):\n return (ffields[0][1], None, ffields[2][1][0])\n else:\n logger.error(\"data error 1\")\n exit()\n elif isinstance(fieldValue, apb2.AttrValue.ListValue):\n return tuple(fieldValue.ListFields()[0][1])\n else:\n logger.error(\"Unsupported field type '%s'\", type(fieldValue))\n exit()\n\ndef _parse_attr(attrs):\n fields = [\"s\", \"i\", \"f\", \"b\", \"type\", \"shape\", \"tensor\", \"func\"]\n new_attrs = {}\n for k, v in attrs.items():\n ret = []\n if v.HasField(\"list\"):\n for f in fields:\n if getattr(v.list, f):\n if f == \"type\":\n ret += [tensor_util.tensor_type_to_numpy(x) \\\n for x in list(getattr(v.list, f))]\n else:\n ret += list(getattr(v.list, f))\n else:\n for f in fields:\n if v.HasField(f):\n if f == \"type\":\n ret = tensor_util.tensor_type_to_numpy(getattr(v, f))\n else:\n ret = getattr(v, f)\n new_attrs[k] = ret\n return new_attrs\n\n\ndef convert_operator(op_name, inputs, attrs, params, logger=logging):\n if op_name not in _convert_map:\n raise NotImplementedError(\"Operator {} not implemented.\".format(op_name))\n '''\n elif op_name == 'Pad':\n padding = params[inputs[1].attr('name')]\n # print (padding.asnumpy(), padding.shape)\n cusPad = cvm.Pad(padding=padding)\n sym = cusPad(inputs[0])\n '''\n sym = _convert_map[op_name](inputs, attrs, params)\n # attr = { k: convert_field(v) for k, v in attrs.items() }\n return sym\n\ncurrSupportedOps = {\n 'FIFOQueueV2', 'QueueDequeueManyV2',\n 'ArgMax',\n 'Const',\n 'Pad',\n 'Identity',\n 'FusedBatchNorm',\n 'MatMul',\n 'Relu', 'Relu6',\n 'Softmax', 'Mean',\n 'MaxPool', 'AvgPool',\n 'BiasAdd', 'Add', 'Placeholder',\n 'Conv2D', 'DepthwiseConv2dNative',\n 'Shape', 'Reshape',\n 'Fill',\n 'ConcatV2',\n 'StridedSlice',\n 'Pack',\n 'Squeeze',\n }\n\nimport tensor_util\n\nfrom tensorflow.core.framework import types_pb2\ndefault_tf_dtype = types_pb2.DT_FLOAT\ndefault_tf_start_types = {'Placeholder', 'PlaceholderWithDefault', 'FIFOQueueV2'}\n\ndef convert_tfnode(tfnode, graph, params, infer_shapes,\n logger=logging, default_input_shape=(1,224,224,3)):\n name, op_name = tfnode.name, tfnode.op\n attr, org_inputs = tfnode.attr, tfnode.input\n\n if op_name not in currSupportedOps:\n logger.critical(\"Not supported op '%s'\", tfnode.op)\n exit()\n\n if op_name == 'Const':\n for k, v in attr.items():\n if k == 'value':\n np_array = tensor_util.tensor_to_numpy(v.tensor)\n params[name] = nd.array(np_array, dtype=np_array.dtype)\n graph[name] = [mx.sym.var(name,\n shape=params[name].shape,\n dtype=params[name].dtype)]\n infer_shapes[name] = [tuple(np_array.shape)]\n elif k not in ('dtype', '_output_shapes', '_class'):\n raise NotImplementedError \\\n (\"Other attributes for a Const(param) Node {} ? .\".format(k))\n elif op_name in ['Placeholder', 'PlaceholderWithDefault', 'FIFOQueueV2']:\n input_shape = \\\n tensor_util.tensor_shape_proto_to_list(attr['shape'].shape)\n if not input_shape:\n input_shape = list(default_input_shape)\n try:\n dtype = tensor_util.tensor_type_to_numpy(attr['dtype'].type)\n except TypeError:\n # TODO(wlt): FIFOQueueV2, QueueDequeueManyV2 that brings into DT_INVALID problem\n dtype = tensor_util.tensor_type_to_numpy(default_tf_dtype)\n graph[name] = [mx.sym.var(\"data\", shape=input_shape, dtype=dtype)]\n assert \"data\" not in infer_shapes\n infer_shapes[\"data\"] = [tuple(input_shape)]\n else:\n inputs, input_eids = [], []\n for in_name in org_inputs:\n input_entry = in_name.split(\":\")\n node_name = input_entry[0]\n assert node_name in graph, \"toposort error: input '%s', node '%s'.\" % (node_name, name)\n child = graph[node_name]\n if len(child) > 1 and len(input_entry) > 1:\n eid = int(input_entry[1])\n else:\n eid = 0\n inputs.append(child[eid])\n input_eids.append(eid)\n\n parsed_attrs = _parse_attr(attr)\n parsed_attrs[\"_input_eids\"] = input_eids\n parsed_attrs[\"_infer_shapes\"] = infer_shapes\n parsed_attrs[\"name\"] = name\n sym = convert_operator(op_name, inputs, parsed_attrs, params)\n graph[name] = [sym]\n _, infer_shapes[sym.attr('name')], _ = sym.infer_shape()\n return graph[name]\n\ndef topo_sort(tfgraph, logger=logging):\n node_map = {}\n deps, ninps, res = {}, [], {}\n for node in tfgraph.node:\n node_map[node.name] = node\n # TODO(ryt): input name may concat output index such as:\n # 'Model/cell_0/RnnCell' and 'Model/cell_0/RnnCell:0'\n for inp in node.input:\n inp = inp.split(\":\")[0]\n if inp not in deps:\n deps[inp] = set()\n deps[inp].add(node.name)\n if not len(node.input):\n ninps.append(node.name)\n else:\n res[node.name] = len(node.input)\n\n # topo sort\n topos = []\n while len(ninps):\n cname = ninps.pop()\n topos.append(node_map[cname])\n if cname not in deps:\n continue\n for name in deps[cname]:\n if res[name] > 1:\n res[name] -= 1\n else:\n res.pop(name)\n ninps.append(name)\n if res:\n logger.critical(\"deps cannot reduce -> %s\", res)\n exit()\n return topos\n\ndef convert_model(pbfile, layout=\"NHWC\", outputs=None, default_input_shape=(1,224,224,3)):\n # load the original model\n logger = logging.getLogger(\"Loading Original Model\")\n tfparser = TFParser(pbfile)\n tfgraph = tfparser.parse()\n logger.info(\"Model successfully loaded from path [%s].\", pbfile)\n\n ops = {n.op for n in topo_sort(tfgraph)}\n print (\"Ops\", ops)\n\n graph, params, infer_shapes = {}, {}, {}\n for tfnode in topo_sort(tfgraph):\n # print(\"name: {}, op: {}, inputs: {}\".format(tfnode.name, tfnode.op, tfnode.input))\n convert_tfnode(tfnode, graph, params, infer_shapes, default_tf_dtype=default_input_shape)\n\n logger.info(\"Operators successfully converted.\")\n\n # The last node of tfgraph is assumed as output by default.\n # Ambiguity occurs in the model `densenet_lite` since multiple outputs exist\n # Thus, we'd better specify the outputs for the model with multiple outputs\n # Fill in the variable `outputs_list`\n if outputs is None:\n outputs = [tfgraph.node[-1].name]\n nodes = []\n for oname in outputs:\n if \":\" in oname:\n oname, onum = oname.split(\":\")\n eid = int(onum)\n nodes.append(graph[oname][eid])\n else:\n nodes.append(graph[oname][0])\n symbol = mx.sym.Group(nodes) if len(nodes) > 1 else nodes[0]\n\n if layout == \"NHWC\":\n symbol, params = spass.convert_input_format(symbol, params)\n\n return symbol, params\n\ndef _fuse_pad(sym, params):\n infer_shapes = infer_shape(sym, params)\n\n def is_pad_op(sym):\n attrs = sym.list_attr()\n return sym.attr('op_name') == \"Custom\" and \\\n attrs.get(\"op_type\", \"\") == \"cvm_pad\"\n\n def _fuse_custom_pad_transpose(sym, params, **kwargs):\n name, op_name = sym.attr('name'), sym.attr('op_name')\n attr, childs = sym.list_attr(), sutils.sym_iter(sym.get_children())\n\n ret = sym\n if op_name != 'transpose' or not is_pad_op(childs[0]):\n return ret, params\n\n cattr = childs[0].list_attr()\n padding = sutils.get_attr(cattr, 'padding')\n axes = sutils.get_attr(attr, 'axes')\n cchilds = sutils.sym_iter(childs[0].get_children())\n X = mx.sym.transpose(*cchilds, axes=axes)\n ret = mx.sym.Custom(X, padding=[padding[r] for r in axes],\n op_type=\"cvm_pad\")\n return ret, params\n\n def _fuse_custom_pad(sym, params, **kwargs):\n name, op_name = sym.attr('name'), sym.attr('op_name')\n attr, childs = sym.list_attr(), sutils.sym_iter(sym.get_children())\n\n ret = sym\n if op_name != 'Custom' or 'op_type' not in attr or \\\n attr['op_type'] != 'cvm_pad':\n return ret, params\n\n padding = nd.array(sutils.get_attr(attr, 'padding'))\n padding = padding.reshape((-1,)).asnumpy().astype(np.int32).tolist()\n ret = mx.sym.pad(*childs, mode='constant',\n pad_width=tuple(padding))\n\n return ret, params\n\n def _fuse_pad_eq(sym, params, **kwargs):\n name, op_name = sym.attr('name'), sym.attr('op_name')\n attr, childs = sym.list_attr(), sutils.sym_iter(sym.get_children())\n\n ret = sym\n if op_name not in ['Convolution', 'Pooling'] or \\\n childs[0].attr('op_name') != 'Pad':\n return ret, params\n\n if 'pad' in attr:\n assert sutils.get_attr(attr, 'pad') == (0, 0)\n\n cattr = childs[0].list_attr()\n pad_width = sutils.get_attr(cattr, 'pad_width')\n if len(pad_width) != 8 or pad_width[4] != pad_width[5] or \\\n pad_width[6] != pad_width[7]:\n return ret, params\n\n attr['pad'] = (pad_width[4], pad_width[6])\n X = sutils.sym_iter(childs[0].get_children()) + childs[1:]\n ret = sutils.get_mxnet_op(op_name)(*X, **attr)\n\n return ret, params\n\n sym, params = sutils.topo_visit_transformer(sym, params,\n _fuse_custom_pad_transpose, infer_shapes=infer_shapes)\n sym, params = sutils.topo_visit_transformer(sym, params, _fuse_custom_pad,\n infer_shapes=infer_shapes)\n # sym, params = sutils.topo_visit_transformer(sym, params, _fuse_pad_eq,\n # infer_shapes=infer_shapes)\n return sym, params\n\nmodel_outs_revise = {\n \"densenet_lite\",\n \"inception_v3_lite\",\n \"mobilenet_v1_0.25_128_lite\",\n \"mobilenet_v1_0.25_224_lite\",\n \"mobilenet_v1_0.50_128_lite\",\n \"mobilenet_v1_0.50_192_lite\",\n \"mobilenet_v1_1.0_224_lite\",\n \"mobilenet_v2_1.0_224_lite\",\n \"resnet_v2_101_lite\",\n}\n\ndef _revise_output(modelname, symbol, params):\n if modelname not in model_outs_revise:\n return symbol, params\n # single outputs is assumed\n symbol = mx.sym.slice_axis(symbol, axis=1, begin=1, end=None)\n # symbol = mx.sym.argmax(symbol, axis=1)\n # name = \"revise_outs\"\n # symbol = mx.sym.broadcast_sub(symbol, mx.sym.var(name))\n # params[name] = mx.nd.array([1])\n return symbol, params\n\ndef dump(model, symbol, params):\n logger = logging.getLogger('model dump')\n prefix = \"./data/tf_%s\" % (model)\n sym_file, params_file = utils.extend_fname(prefix)\n with open(sym_file, \"w\") as f:\n f.write(symbol.tojson())\n\n snames = [s.attr('name') for s in sutils.topo_sort(symbol)]\n items = dict(params.items())\n for k, v in items.items():\n if v.shape == ():\n print (\"%40s \\t%s %s\" % (k, type(v), v.shape),\n k in snames)\n assert k not in snames\n del params[k]\n nd.save(params_file, params)\n logger.info(\"Model successfully dumped to '%s'\", sym_file)\n\ndef tf_dump_model(modelname, revise_outs=True, default_input_shape=(1,224,224,3)):\n utils.log_init()\n model_path = modelfile[modelname]\n outputs = outputs_list[modelname]\n sym, params = convert_model(\n model_path, outputs=outputs, default_input_shape=default_input_shape)\n sym, params = _fuse_pad(sym, params)\n if revise_outs:\n sym, params = _revise_output(modelname, sym, params)\n dump(modelname, sym, params)\n\nmodelfile = {\n \"resnet50_v1_new\": \"/data/tfmodels/resnet50_v1_new/model.pb\",\n \"inception_v3\": \"/data/tfmodels/inception_v3/model.pb\",\n \"mobilenet\": \"/data/tfmodels/mobilenet/model.pb\",\n \"densenet_lite\": \"/data/tfmodels/lite/DenseNet/densenet.pb\",\n \"inception_v3_lite\": \"/data/tfmodels/lite/Inception_V3/inception_v3.pb\",\n \"mobilenet_v1_0.25_128_lite\": \"/data/tfmodels/lite/Mobilenet_V1_0.25_128/mobilenet_v1_0.25_128_frozen.pb\",\n \"mobilenet_v1_0.25_224_lite\": \"/data/tfmodels/lite/Mobilenet_V1_0.25_224/mobilenet_v1_0.25_224_frozen.pb\",\n \"mobilenet_v1_0.50_128_lite\": \"/data/tfmodels/lite/Mobilenet_V1_0.50_128/mobilenet_v1_0.5_128_frozen.pb\",\n \"mobilenet_v1_0.50_192_lite\": \"/data/tfmodels/lite/Mobilenet_V1_0.50_192/mobilenet_v1_0.5_192_frozen.pb\",\n \"mobilenet_v1_1.0_224_lite\": \"/data/tfmodels/lite/Mobilenet_V1_1.0_224/mobilenet_v1_1.0_224_frozen.pb\",\n \"mobilenet_v2_1.0_224_lite\": \"/data/tfmodels/lite/Mobilenet_V2_1.0_224/mobilenet_v2_1.0_224_frozen.pb\",\n \"resnet_v2_101_lite\": \"/data/tfmodels/lite/ResNet_V2_101/resnet_v2_101_299_frozen.pb\",\n \"ssd_mobilenet_v2_coco\": \"/data/tfmodels/ssd_mobilenet/ssd_mobilenet_v2_coco_2018_03_29/frozen_inference_graph.pb\",\n }\n\noutputs_list = {\n \"resnet50_v1_new\": [\"fc1000_1/Softmax\"],\n \"inception_v3\": [\"predictions_1/Softmax\"],\n \"mobilenet\": ['act_softmax_1/Softmax'],\n \"densenet_lite\": [\"softmax_tensor\"],\n # \"densenet_lite\": [\"ArgMax\"],\n \"inception_v3_lite\": None,\n \"mobilenet_v1_0.25_128_lite\": None,\n \"mobilenet_v1_0.25_224_lite\": None,\n \"mobilenet_v1_0.50_128_lite\": None,\n \"mobilenet_v1_0.50_192_lite\": None,\n \"mobilenet_v1_1.0_224_lite\": None,\n \"mobilenet_v2_1.0_224_lite\": [\"MobilenetV2/Predictions/Reshape_1\"],\n \"resnet_v2_101_lite\": None,\n \"ssd_mobilenet_v2_coco\": [\"resnet_v2_101/SpatialSqueeze\"],\n}\n\nimport sys\n\nif __name__ == '__main__':\n utils.log_init()\n assert len(sys.argv) >= 2, \"Please enter at least 2 python arguments.\"\n modelname = sys.argv[1]\n revise_outs = False if len(sys.argv) > 2 and sys.argv[2] == 'False' else True\n tf_dump_model(modelname, revise_outs=revise_outs)\n\n"
] | [
[
"numpy.product"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
magenta/midi-ddsp | [
"3ff97496b42becead5289b349524b38f5b55d530"
] | [
"midi_ddsp/modules/ddsp_inference.py"
] | [
"# Copyright 2022 The MIDI-DDSP Authors.\n# #\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# #\n# http://www.apache.org/licenses/LICENSE-2.0\n# #\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Model class for DDSP Inference module used in MIDI-DDSP.\"\"\"\n\nimport tensorflow as tf\nimport ddsp\nfrom midi_ddsp.utils.audio_io import tf_log_mel\nfrom midi_ddsp.data_handling.instrument_name_utils import NUM_INST\nfrom ddsp.training import nn\nfrom ddsp.spectral_ops import F0_RANGE, DB_RANGE\n\ntfk = tf.keras\ntfkl = tfk.layers\n\n\nclass MelF0LDEncoder(tfkl.Layer):\n \"\"\"The encoder in DDSP Inference.\n The MelF0LDEncoder takes input of audio, loudness and f0.\n The MelF0LDEncoder extract features from audio using an 8-layer CNN,\n and extract features from loudness and f0 using fully-connected layers.\n Then, a bi-lstm is used to extract contextual features from the extracted\n features.\n \"\"\"\n\n def __init__(self, cnn, nhid, sample_rate, win_length, hop_length, n_fft,\n num_mels, fmin):\n super().__init__()\n self.nhid = nhid\n self.cnn = cnn\n self.z_fc = tfkl.Dense(nhid)\n self.f0_ld_fc = tfkl.Dense(nhid)\n self.rnn = tfkl.Bidirectional(\n tfkl.LSTM(units=nhid, return_sequences=True), name='bilstm'\n )\n # TODO(yusongwu): change emb dim to 64\n self.instrument_emb = tfkl.Embedding(NUM_INST, 128)\n\n # mel-spec parameters\n self.sample_rate = sample_rate\n self.win_length = win_length\n self.hop_length = hop_length\n self.n_fft = n_fft\n self.num_mels = num_mels\n self.fmin = fmin\n\n def call(self, inputs, training=False):\n mel = tf_log_mel(inputs['audio'],\n self.sample_rate,\n self.win_length,\n self.hop_length,\n self.n_fft,\n self.num_mels,\n self.fmin)\n z_cnn = self.cnn(mel, training=training)\n z_reduce = self.z_fc(z_cnn)\n instrument_z = tf.tile(\n self.instrument_emb(inputs['instrument_id'])[:, tf.newaxis, :],\n [1, z_cnn.shape[1], 1])\n x = tf.concat([ddsp.core.hz_to_midi(inputs['f0_hz']) / F0_RANGE,\n inputs['loudness_db'] / DB_RANGE], -1)\n x_z = self.f0_ld_fc(x)\n z_out = self.rnn(tf.concat([x_z, z_reduce, instrument_z], -1))\n return z_out\n\n\nclass FCHarmonicDecoder(tfkl.Layer):\n \"\"\"The decoder in DDSP Inference.\n The FCHarmonicDecoder takes input of a feature sequence,\n and output the synthesis parameters for DDSP through fully-connected layers.\n \"\"\"\n\n def __init__(self, nhramonic=100, nnoise=65):\n super().__init__()\n\n self.harmonic_amp_fc = tfkl.Dense(1, bias_initializer='ones')\n self.harmonic_distribution_fc = tfkl.Dense(nhramonic)\n\n self.noise_mag_fc = tfkl.Dense(nnoise)\n\n def get_synth_params(self, inputs):\n z, data = inputs\n\n harmonic_amp = self.harmonic_amp_fc(z)\n harmonic_distribution = self.harmonic_distribution_fc(z)\n noise_mag = self.noise_mag_fc(z)\n\n synth_params = {\n 'f0_hz': data['f0_hz'],\n 'amplitudes': harmonic_amp,\n 'harmonic_distribution': harmonic_distribution,\n 'noise_magnitudes': noise_mag,\n }\n\n return synth_params\n\n def call(self, inputs):\n synth_params = self.get_synth_params(inputs)\n\n return synth_params\n\n\nclass F0LDEncoder(tfkl.Layer):\n \"\"\"The encoder of original DDSP autoencoder.\"\"\"\n\n # TODO: (yusongwu) To be removed and use the decoders.RnnFcDecoder\n def __init__(self):\n super().__init__()\n self.nhid = 512\n self.f0_fc = nn.FcStack(self.nhid, layers=3)\n self.ld_fc = nn.FcStack(self.nhid, layers=3)\n self.instrument_emb = tfkl.Embedding(NUM_INST, 128)\n self.rnn = tfkl.GRU(\n units=self.nhid, return_sequences=True, # dropout=0.2,\n )\n\n def call(self, inputs, training=False):\n z_f0 = self.f0_fc(ddsp.core.hz_to_midi(inputs['f0_hz']) / F0_RANGE)\n z_ld = self.ld_fc(inputs['loudness_db'] / DB_RANGE)\n instrument_z = tf.tile(\n self.instrument_emb(inputs['instrument_id'])[:, tf.newaxis, :],\n [1, z_ld.shape[1], 1])\n x_z = tf.concat([z_f0, z_ld, instrument_z], -1)\n z_out = self.rnn(x_z)\n z_out = tf.concat([x_z, z_out], -1)\n return z_out\n\n\nclass FCStackHarmonicDecoder(tfkl.Layer):\n \"\"\"The decoder original DDSP autoencoder.\n The FCStackHarmonicDecoder takes input of a feature sequence,\n and output the synthesis parameters for DDSP through stacked MLP.\n \"\"\"\n\n def __init__(self, nharmonic=100, nnoise=65):\n super().__init__()\n\n self.output_splits = (\n ('amplitudes', 1), ('harmonic_distribution', nharmonic),\n ('noise_magnitudes', nnoise))\n self.n_out = sum([v[1] for v in self.output_splits])\n self.out_stack = nn.FcStack(512, layers=3)\n self.dense_out = tfkl.Dense(self.n_out)\n\n def get_synth_params(self, inputs):\n z, data = inputs\n\n z_output = self.out_stack(z)\n synth_params = nn.split_to_dict(self.dense_out(z_output),\n self.output_splits)\n\n synth_params['f0_hz'] = data['f0_hz']\n\n return synth_params\n\n def call(self, inputs):\n synth_params = self.get_synth_params(inputs)\n return synth_params\n\n\nclass ConvBlock(tfkl.Layer):\n \"\"\"\n A tensorflow implementation of ConvBlock used in audioset classification.\n This CNN has better performance when used in spectrogram feature\n extraction for audio tagging. Adapted from pytorch implementation:\n https://github.com/qiuqiangkong/audioset_tagging_cnn.\n paper: https://arxiv.org/abs/1912.10211.\n Args:\n out_channels: number of output channels.\n pool_size: size of pooling, in height and width.\n \"\"\"\n\n def __init__(self, out_channels, pool_size=(2, 2)):\n super().__init__()\n\n self.conv1 = tfkl.Conv2D(filters=out_channels,\n kernel_size=(3, 3), strides=(1, 1),\n padding='same', use_bias=False,\n kernel_initializer=\n tf.keras.initializers.GlorotUniform())\n\n self.conv2 = tfkl.Conv2D(filters=out_channels,\n kernel_size=(3, 3), strides=(1, 1),\n padding='same', use_bias=False,\n kernel_initializer=\n tf.keras.initializers.GlorotUniform())\n\n self.bn1 = tfkl.BatchNormalization(beta_initializer='zeros',\n gamma_initializer='ones')\n self.bn2 = tfkl.BatchNormalization(beta_initializer='zeros',\n gamma_initializer='ones')\n\n self.max_pool = tfkl.MaxPool2D(pool_size=pool_size, padding='same')\n self.avg_pool = tfkl.AveragePooling2D(pool_size=pool_size, padding='same')\n\n def call(self, inputs, training=None, pool_type='avg'):\n x = inputs\n x = tf.nn.relu(self.bn1(self.conv1(x), training=training))\n x = tf.nn.relu(self.bn2(self.conv2(x), training=training))\n if pool_type == 'max':\n x = self.max_pool(x)\n elif pool_type == 'avg':\n x = self.avg_pool(x)\n elif pool_type == 'avg+max':\n x1 = self.avg_pool(x)\n x2 = self.max_pool(x)\n x = x1 + x2\n else:\n raise Exception('Incorrect argument!')\n\n return x\n\n\nclass Cnn8(tfkl.Layer):\n \"\"\"\n A tensorflow implementation of CNN8 used in audioset classification.\n This CNN has better performance when used in spectrogram feature\n extraction for audio tagging. Adapted from pytorch implementation:\n https://github.com/qiuqiangkong/audioset_tagging_cnn.\n paper: https://arxiv.org/abs/1912.10211.\n \"\"\"\n\n def __init__(self, pool_size=(2, 2), dropout=0.2):\n super().__init__()\n\n self.conv_block1 = ConvBlock(out_channels=64, pool_size=pool_size)\n self.conv_block2 = ConvBlock(out_channels=128, pool_size=pool_size)\n self.conv_block3 = ConvBlock(out_channels=256, pool_size=pool_size)\n self.conv_block4 = ConvBlock(out_channels=512, pool_size=pool_size)\n\n self.dropout = tfkl.Dropout(rate=dropout)\n\n def call(self, x, training=None):\n x = x[..., tf.newaxis]\n\n x = self.conv_block1(x, pool_type='avg', training=training)\n x = self.dropout(x, training=training)\n x = self.conv_block2(x, pool_type='avg', training=training)\n x = self.dropout(x, training=training)\n x = self.conv_block3(x, pool_type='avg', training=training)\n x = self.dropout(x, training=training)\n x = self.conv_block4(x, pool_type='avg', training=training)\n x = self.dropout(x, training=training)\n x = tf.reshape(x, [x.shape[0], x.shape[1], -1])\n\n return x\n"
] | [
[
"tensorflow.reshape",
"tensorflow.concat",
"tensorflow.keras.initializers.GlorotUniform"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
bandarads/video_emotion_prediction | [
"65c4c6bfd9ee81375f1b26d62e59e64f736aae48"
] | [
"GB/ExtractwMASKGB.py"
] | [
"import numpy as np\r\nfrom cv2 import cv2\r\nimport os.path\r\nimport boundingbox\r\nimport CropMaskOverlay\r\nfrom pathlib import Path\r\nimport datetime\r\nimport uuid\r\n\r\nVIDEO_NUMBER = 266\r\n\r\n\r\n\r\nLM_FOLDER_PATH = \"\\\\Users\\\\George\\\\Documents\\\\Python\\\\ADS CapStone\\\\aff_wild_annotations_bboxes_landmarks_new\"\r\nLANDMARK_PATH = \"\\\\Users\\\\George\\\\Documents\\\\Python\\\\ADS CapStone\\\\aff_wild_annotations_bboxes_landmarks_new\\\\landmarks\\\\train\"\r\n\r\nFOLDER_PATH = \"\\\\Users\\\\George\\\\Documents\\\\Python\\\\ADS CapStone\\\\aff_wild_annotations_bboxes_landmarks_new\"\r\nBOUNDING_BOX_PATH = \"\\\\Users\\\\George\\\\Documents\\\\Python\\\\ADS CapStone\\\\aff_wild_annotations_bboxes_landmarks_new\\\\bboxes\\\\train\"\r\nANNOTATIONS_PATH = \"\\\\Users\\\\George\\\\Documents\\\\Python\\\\ADS CapStone\\\\aff_wild_annotations_bboxes_landmarks_new\\\\annotations\\\\train\"\r\n\r\ndef main():\r\n #load annotations\r\n valence_annotations = boundingbox.load_annotations(ANNOTATIONS_PATH +\"\\\\valence\\\\\"+ str(VIDEO_NUMBER)+\".txt\")\r\n arousal_annotations = boundingbox.load_annotations(ANNOTATIONS_PATH +\"\\\\arousal\\\\\"+ str(VIDEO_NUMBER)+\".txt\")\r\n\r\n frame_number = 0\r\n \r\n\r\n cap = cv2.VideoCapture(\"\\\\Users\\\\George\\\\Documents\\\\Python\\\\ADS CapStone\\\\aff_wild_annotations_bboxes_landmarks_new\\\\videos\\\\train\\\\\"+str(VIDEO_NUMBER)+\".mp4\")\r\n \r\n \r\n while(cap.isOpened()):\r\n frame_number += 1\r\n\r\n #load bounding box coords\r\n bounding_box = boundingbox.load_points(BOUNDING_BOX_PATH +\"\\\\\"+ str(VIDEO_NUMBER)+\"\\\\\"+str(frame_number)+\".pts\")\r\n landmarks = boundingbox.load_points(LANDMARK_PATH +\"\\\\\"+ str(VIDEO_NUMBER)+\"\\\\\"+str(frame_number)+\".pts\")\r\n if not bounding_box:\r\n if frame_number > 10000:\r\n break\r\n print(VIDEO_NUMBER,\"Failed to retrieve BB Points\", frame_number)\r\n continue\r\n ret, frame = cap.read()\r\n \r\n if ret == False:\r\n print(VIDEO_NUMBER,\"Failed to retrieve ret\")\r\n break \r\n \r\n if frame is None:\r\n print(VIDEO_NUMBER,\"Failed to retrieve frame\")\r\n break \r\n \r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n \r\n maskpts = np.array(landmarks, np.int32)\r\n maskpts = maskpts.reshape((-1,1,2))\r\n \r\n \r\n # dst = CropMaskOverlay.CROPMASK(gray,maskpts,'bottomhalf',175)\r\n # dst = CropMaskOverlay.POINTMASK(gray,maskpts,'all',1)\r\n # dst = CropMaskOverlay.OUTLINERECTMASK(gray,maskpts,'all',1)\r\n dst = CropMaskOverlay.RECTMASK(gray,maskpts,'all',1)\r\n mask_img = dst\r\n\r\n pts = np.array([[bounding_box[0][0],bounding_box[0][1]],[bounding_box[1][0],bounding_box[1][1]],[bounding_box[2][0],bounding_box[2][1]],[bounding_box[3][0],bounding_box[3][1]]], np.int32)\r\n pts = pts.reshape((-1,1,2))\r\n img = cv2.polylines(mask_img,[pts],True,(0,255,255))\r\n crop_img = img[ int(bounding_box[0][1]):int(bounding_box[1][1]),int(bounding_box[0][0]):int(bounding_box[2][0]),]\r\n \r\n\r\n\r\n cv2.imshow(\"cropped\", crop_img)\r\n\r\n \r\n try:\r\n valence_value = float(valence_annotations[frame_number])\r\n except:\r\n print(VIDEO_NUMBER, \"Broke via valence value index error\")\r\n break\r\n \r\n try:\r\n arousal_value = float(arousal_annotations[frame_number])\r\n except:\r\n print(VIDEO_NUMBER, \"Broke via arousal value index error\")\r\n break\r\n \r\n \r\n #save crop to path based on valence value\r\n if valence_value >= -1 and valence_value < -0.5:\r\n Path(FOLDER_PATH+\"\\\\landmarkimg\"+\"\\\\valence\\\\low\\\\\").mkdir(parents=True, exist_ok=True)#create directory path if it doesnt exist\r\n cv2.imwrite(FOLDER_PATH+\"\\\\landmarkimg\"+\"\\\\valence\\\\low\\\\\"+str(uuid.uuid4())+\".png\",crop_img)\r\n \r\n elif valence_value >= -0.5 and valence_value < 0.5:\r\n Path(FOLDER_PATH+\"\\\\landmarkimg\"+\"\\\\valence\\\\neutral\\\\\").mkdir(parents=True, exist_ok=True)\r\n cv2.imwrite(FOLDER_PATH+\"\\\\landmarkimg\"+\"\\\\valence\\\\neutral\\\\\"+str(uuid.uuid4())+\".png\",crop_img)\r\n \r\n elif valence_value >= 0.5 and valence_value <= 1:\r\n Path(FOLDER_PATH+\"\\\\landmarkimg\"+\"\\\\valence\\\\high\\\\\").mkdir(parents=True, exist_ok=True)\r\n cv2.imwrite(FOLDER_PATH+\"\\\\landmarkimg\"+\"\\\\valence\\\\high\\\\\"+str(uuid.uuid4())+\".png\",crop_img)\r\n else:\r\n print(\"error writing valence image crop\")\r\n \r\n #save crop to path based on arousal value\r\n if arousal_value >= -1 and arousal_value < -0.5:\r\n Path(FOLDER_PATH+\"\\\\landmarkimg\"+\"\\\\arousal\\\\low\\\\\").mkdir(parents=True, exist_ok=True)\r\n cv2.imwrite(FOLDER_PATH+\"\\\\landmarkimg\"+\"\\\\arousal\\\\low\\\\\"+str(uuid.uuid4())+\".png\",crop_img)\r\n \r\n elif arousal_value >= -0.5 and arousal_value < 0.5:\r\n Path(FOLDER_PATH+\"\\\\landmarkimg\"+\"\\\\arousal\\\\neutral\\\\\").mkdir(parents=True, exist_ok=True)\r\n cv2.imwrite(FOLDER_PATH+\"\\\\landmarkimg\"+\"\\\\arousal\\\\neutral\\\\\"+str(uuid.uuid4())+\".png\",crop_img)\r\n \r\n elif arousal_value >= 0.5 and arousal_value <= 1:\r\n Path(FOLDER_PATH+\"\\\\landmarkimg\"+\"\\\\arousal\\\\high\\\\\").mkdir(parents=True, exist_ok=True)\r\n cv2.imwrite(FOLDER_PATH+\"\\\\landmarkimg\"+\"\\\\arousal\\\\high\\\\\"+str(uuid.uuid4())+\".png\",crop_img)\r\n \r\n else:\r\n print(\"error writing arousal image crop\")\r\n \r\n \r\n \r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n \r\n cap.release()\r\n cv2.destroyAllWindows()\r\n\r\n\r\nwhile VIDEO_NUMBER < 450:\r\n main()\r\n print(VIDEO_NUMBER, \"Completed at\", datetime.datetime.now())\r\n VIDEO_NUMBER = VIDEO_NUMBER+1\r\n \r\n "
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ajmal017/amp | [
"8de7e3b88be87605ec3bad03c139ac64eb460e5c",
"8de7e3b88be87605ec3bad03c139ac64eb460e5c",
"8de7e3b88be87605ec3bad03c139ac64eb460e5c",
"8de7e3b88be87605ec3bad03c139ac64eb460e5c",
"8de7e3b88be87605ec3bad03c139ac64eb460e5c",
"8de7e3b88be87605ec3bad03c139ac64eb460e5c"
] | [
"im/kibot/notebooks/kibot_data_analysis.py",
"core/feature_analyzer.py",
"dev_scripts/to_clean/gen_utils.py",
"core/dataflow/nodes/volatility_models.py",
"core/notebooks/gallery_timeseries_study.py",
"im/ib/data/extract/gateway/download_realtime_data.py"
] | [
"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.5.1\n# kernelspec:\n# display_name: Python [conda env:.conda-develop] *\n# language: python\n# name: conda-env-.conda-develop-py\n# ---\n\n# %%\n# %load_ext autoreload\n# %autoreload 2\n\n\nimport pandas as pd\n\nimport helpers.pd_helpers as pdhelp\nimport helpers.s3 as hs3\n\n# %%\nS3_BUCKET = hs3.get_bucket()\nfile_name = f\"s3://{S3_BUCKET}/data/kibot/sp_500_1min/AAPL.csv.gz\"\n\ns3fs = hs3.get_s3fs(\"am\")\ndf = pdhelp.read_csv(file_name, s3fs=s3fs)\ndf.head(5)\n\n# %%\nfile_name = f\"s3://{S3_BUCKET}/data/kibot/pq/sp_500_1min/AAPL.pq\"\n# TODO(gp): Create a `pdhelp.read_parquet()`.\npd.read_parquet(file_name)\n",
"import collections\nimport logging\nfrom typing import Dict, List, Tuple, Union\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nimport statsmodels.api as sm\n\nimport helpers.dbg as dbg\nimport helpers.printing as pri\n\n_LOG = logging.getLogger(__name__)\n\n\ndef _analyze_feature(\n df: pd.DataFrame,\n y_var: str,\n x_var: str,\n use_intercept: bool,\n nan_mode: str,\n x_shift: int,\n report_stats: bool,\n) -> collections.OrderedDict:\n _LOG.debug(\"df=\\n%s\", df.head(3))\n _LOG.debug(\n \"y_var=%s, x_var=%s, use_intercept=%s, nan_mode=%s, x_shift=%s\",\n y_var,\n x_var,\n use_intercept,\n nan_mode,\n x_shift,\n )\n dbg.dassert_isinstance(y_var, str)\n dbg.dassert_isinstance(x_var, str)\n #\n res = collections.OrderedDict()\n res[\"y_var\"] = y_var\n res[\"x_var\"] = x_var\n df_tmp = df[[y_var, x_var]].copy()\n #\n res[\"x_shift\"] = x_shift\n if x_shift != 0:\n df_tmp[x_var] = df_tmp[x_var].shift(x_shift)\n #\n if nan_mode == \"drop\":\n df_tmp.dropna(inplace=True)\n elif nan_mode == \"fill_with_zeros\":\n df_tmp.fillna(0.0, inplace=True)\n else:\n raise ValueError(\"Invalid nan_mode='%s'\" % nan_mode)\n res[\"nan_mode\"] = nan_mode\n #\n regr_x_vars = [x_var]\n if use_intercept:\n df_tmp = sm.add_constant(df_tmp)\n regr_x_vars.insert(0, \"const\")\n res[\"use_intercept\"] = use_intercept\n # Fit.\n reg = sm.OLS(df_tmp[y_var], df_tmp[regr_x_vars])\n model = reg.fit()\n if use_intercept:\n dbg.dassert_eq(len(model.params), 2)\n res[\"params_const\"] = model.params[0]\n res[\"pvalues_const\"] = model.pvalues[0]\n res[\"params_var\"] = model.params[1]\n res[\"pvalues_var\"] = model.pvalues[1]\n else:\n dbg.dassert_eq(len(model.params), 1)\n res[\"params_var\"] = model.params[0]\n res[\"pvalues_var\"] = model.pvalues[0]\n res[\"nobs\"] = model.nobs\n res[\"condition_number\"] = model.condition_number\n res[\"rsquared\"] = model.rsquared\n res[\"rsquared_adj\"] = model.rsquared_adj\n # TODO(gp): Add pnl, correlation, hitrate.\n #\n if report_stats:\n txt = pri.frame(\n \"y_var=%s, x_var=%s, use_intercept=%s, nan_mode=%s, x_shift=%s\"\n % (y_var, x_var, use_intercept, nan_mode, x_shift)\n )\n _LOG.info(\"\\n%s\", txt)\n _LOG.info(\"model.summary()=\\n%s\", model.summary())\n sns.regplot(x=df[x_var], y=df[y_var])\n plt.show()\n return res\n\n\ndef analyze_features(\n df: pd.DataFrame,\n y_var: str,\n x_vars: List[str],\n use_intercept: bool,\n nan_mode: str = \"drop\",\n x_shifts: Union[None, List[int]] = None,\n report_stats: bool = False,\n) -> pd.DataFrame:\n if x_shifts is None:\n x_shifts = [0]\n res_df = []\n for x_var in x_vars:\n _LOG.debug(\"x_var=%s\", x_var)\n for x_shift in x_shifts:\n _LOG.debug(\"x_shifts=%s\", x_shift)\n res_tmp = _analyze_feature(\n df, y_var, x_var, use_intercept, nan_mode, x_shift, report_stats\n )\n res_df.append(res_tmp)\n return pd.DataFrame(res_df)\n\n\n# #############################################################################\n\n\nclass Reporter:\n \"\"\"\n Report results from `analyze_features()` in a heatmap with coefficient\n values and p-values.\n \"\"\"\n\n def __init__(self, res_df: pd.DataFrame):\n self.res_df = res_df\n\n def plot(self) -> pd.DataFrame:\n # Reshape the results in terms of coeff values and pvalues.\n coeff_df = self.res_df[\n [\"x_var\", \"x_shift\", \"params_var\", \"pvalues_var\"]\n ].pivot(index=\"x_shift\", columns=\"x_var\", values=\"params_var\")\n pvals_df = self.res_df[\n [\"x_var\", \"x_shift\", \"params_var\", \"pvalues_var\"]\n ].pivot(index=\"x_shift\", columns=\"x_var\", values=\"pvalues_var\")\n min_val = coeff_df.min(axis=0).min()\n max_val = coeff_df.max(axis=0).max()\n # Df storing the results.\n coeff_df_tmp = coeff_df.copy()\n # Map from cell text in coeff_df_map to color.\n coeff_color_map = {}\n #\n for i in range(coeff_df_tmp.shape[0]):\n for j in range(coeff_df_tmp.shape[1]):\n coeff = coeff_df.iloc[i, j]\n _LOG.debug(\"i=%s j=%s -> coeff=%s\", i, j, coeff)\n # Compute color.\n color = self._assign_color(coeff, min_val, max_val)\n # Present coeff and pval.\n coeff = \"%.3f\" % coeff\n pval = pvals_df.iloc[i, j]\n if pval < 0.001:\n # 0.1%\n coeff += \" (***)\"\n elif pval < 0.01:\n # 1%\n coeff += \" (**)\"\n elif pval < 0.05:\n # 5%\n coeff += \" (*)\"\n else:\n # coeff = \"\"\n pass\n coeff_df_tmp.iloc[i, j] = coeff\n coeff_color_map[coeff] = color\n # Style df by assigning colors.\n decorate_with_color = lambda val: self._decorate_with_color(\n val, coeff_color_map\n )\n coeff_df_tmp = coeff_df_tmp.style.applymap(decorate_with_color)\n return coeff_df_tmp\n\n @staticmethod\n def _interpolate(\n val: float, max_val: float, min_col: float, max_col: float\n ) -> int:\n \"\"\"\n Interpolate intensity in [min_col, max_col] based on val in 0,\n max_val].\n\n :return: float value in [0, 1]\n \"\"\"\n dbg.dassert_lte(0, val)\n dbg.dassert_lte(val, max_val)\n res = min_col + (val / max_val * (max_col - min_col))\n return int(res)\n\n @staticmethod\n def _interpolate_rgb(\n val: float,\n max_val: float,\n min_rgb: Tuple[int, int, int],\n max_rgb: Tuple[int, int, int],\n ) -> List[int]:\n \"\"\"\n Interpolate val in [0, max_val] in terms of the rgb colors.\n\n [min_rgb, max_rgb] by interpolating the 3 color channels.\n :return: triple representing the interpolated color\n \"\"\"\n res = []\n for min_, max_ in zip(min_rgb, max_rgb):\n res.append(Reporter._interpolate(val, max_val, min_, max_))\n return res\n\n @staticmethod\n def _assign_color(val: float, min_val: float, max_val: float) -> str:\n if val < 0:\n min_rgb = (255, 255, 255)\n max_rgb = (96, 96, 255)\n rgb = Reporter._interpolate_rgb(-val, -min_val, min_rgb, max_rgb)\n else:\n min_rgb = (255, 255, 255)\n max_rgb = (255, 96, 96)\n rgb = Reporter._interpolate_rgb(val, max_val, min_rgb, max_rgb)\n # E.g., color = '#FF0000'\n color = \"#{:02x}{:02x}{:02x}\".format(*rgb)\n _LOG.debug(\n \"val=%s in [%s, %s] -> rgb=%s %s\", val, min_val, max_val, rgb, color\n )\n return color\n\n @staticmethod\n def _decorate_with_color(txt: str, color_map: Dict[str, str]) -> str:\n dbg.dassert_in(txt, color_map)\n color = color_map[txt]\n return \"background-color: %s\" % color\n\n\n# TODO(gp): Add unit test.\n# print(color_negative_red(val=2, min_val=-2, max_val=2))\n# print(color_negative_red(val=-2, min_val=-2, max_val=2))\n# print(color_negative_red(val=0.001, min_val=-2, max_val=2))\n",
"import bisect\nimport datetime\nimport logging\nimport os\nimport pprint\n\nimport IPython.core.display\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scipy\nimport seaborn as sns\nimport statsmodels\nimport utils.debug as dbg\nimport utils.jos\nimport utils.jstats\nimport utils.memoize as memoize\nimport utils.sorted\nimport utils.stats\n\nfrom helpers.csv import to_typed_csv\n\n_LOG = logging.getLogger(__name__)\n\n# #############################################################################\n# Python.\n# #############################################################################\n\n# def apply_to_one_column_df(f):\n# def wrapper(*args, **kwargs):\n# func_name = f.__name__\n# obj, args_tmp = *args[0], *\n# if isinstance(*args[0], pd.Series):\n# v = f(*args, **kwargs)\n# else:\n# dbg.dassert_type_is(\n# return v\n# return wrapper\n\n\ndef apply_to_dict_panel(\n obj, f, func_name=None, timed=False, progress_bar=False, report_func=False\n):\n if report_func:\n _LOG.info(\"# %s\", func_name)\n if timed:\n timer = utils.timer.dtimer_start(0, func_name)\n #\n if func_name is None:\n func_name = f.__name__\n if isinstance(obj, pd.Panel):\n type_ = \"panel\"\n elif isinstance(obj, dict):\n type_ = \"dict\"\n else:\n raise ValueError(\"Invalid type='%s' for %s\" % (type(obj), str(f)))\n #\n res = {}\n if progress_bar:\n pb = utils.timer.ProgressBar(0, len(obj), descr=func_name, verbosity=0)\n for k, v in obj.items():\n _LOG.debug(\"Execute for k=%s\", k)\n res[k] = f(v)\n if progress_bar:\n next(pb)\n #\n if type_ == \"panel\":\n res = pd.Panel(res)\n if timed:\n utils.timer.dtimer_stop(timer)\n return res\n\n\n# Store the keys for which the execution was parallel in the last invocation.\n_keys_for_parallel = None\n\n\n# TODO(gp): When we run apply_to_dict_panel_parallel() with a lambda func\n# filling some arguments for a memoized function, we need to know if the\n# memoized function will need eval. So we need to pass the intrinsic function\n# and the args to this wrapper.\ndef apply_to_dict_panel_parallel(\n obj, f, args, func_name=None, timed=False, n_jobs=None, verbose=0\n):\n import dill\n from joblib import Parallel, delayed\n\n if timed:\n timer = utils.timer.dtimer_start(0, func_name)\n dbg.dassert_isinstance(f, utils.memoize.memoized)\n memoized_f = f\n f = f.func\n # Default params.\n if func_name is None:\n func_name = f.__name__\n if n_jobs is None:\n n_jobs = -1\n # Consider the type of the input.\n if isinstance(obj, pd.Panel):\n type_ = \"panel\"\n elif isinstance(obj, dict):\n type_ = \"dict\"\n else:\n raise ValueError(\"Invalid type='%s' for %s\" % (type(obj), str(f)))\n #\n res = {}\n keys = list(obj.keys())\n # Execute locally functions already cached.\n _LOG.info(\"# Execute locally what was cached\")\n keys_for_parallel = []\n for k in keys:\n v = obj[k]\n all_args = [v] + args\n needs_eval = memoized_f.needs_eval(*all_args)\n _LOG.debug(\"k=%s -> needs_eval=%s\", k, needs_eval)\n if not needs_eval:\n # Execute locally, since it is already cache.\n _LOG.debug(\"Execute k=%s locally\", k)\n res[k] = memoized_f(*all_args)\n else:\n _LOG.debug(\"k=%s needs remote execution\", k)\n keys_for_parallel.append(k)\n # Execution remotely functions that are not cached.\n _LOG.info(\n \"# Execute remotely what was not cached (%s) %s\",\n len(keys_for_parallel),\n str(keys_for_parallel),\n )\n global _keys_for_parallel\n _keys_for_parallel = keys_for_parallel[:]\n if keys_for_parallel:\n _LOG.info(\n \"Parallel exec starting (len(obj)=%d n_jobs=%d)\", len(obj), n_jobs\n )\n f_dill = dill.dumps(f)\n caches = Parallel(n_jobs=n_jobs, max_nbytes=None, verbose=verbose)(\n delayed(memoize.execute_remote_function)(f_dill, *([obj[k]] + args))\n for k in keys_for_parallel\n )\n _LOG.info(\"Parallel exec ending\")\n # Update local cache from remote execution.\n for cache in caches:\n memoize.update_cache(cache)\n # Update results from remote execution.\n _LOG.info(\"Update results from remote execution\")\n for k in keys_for_parallel:\n all_args = [obj[k]] + args\n need_eval = memoized_f.needs_eval(*all_args)\n if utils.memoize.is_memoization_enabled():\n dbg.dassert(not need_eval)\n res[k] = memoized_f(*all_args)\n #\n if type_ == \"panel\":\n res = pd.Panel(res)\n if timed:\n utils.timer.dtimer_stop(timer)\n return res\n\n\n# #############################################################################\n# Basic python data structures (e.g., dict, set, list) utils.\n# #############################################################################\n\n\ndef print_dict(dict_, num_values=5, sort=True):\n dbg.dassert_isinstance(dict_, dict)\n keys = list(dict_.keys())\n if sort:\n keys = sorted(keys)\n if num_values is not None:\n dbg.dassert_lte(1, num_values)\n keys = keys[:num_values]\n pprint.pprint({k: dict_[k] for k in keys})\n print(\"...\")\n\n\ndef pick_first(obj):\n \"\"\"\n Pick first df from dict of dfs or panel.\n \"\"\"\n dbg.dassert_in(type(obj), (dict, pd.Panel))\n key = sorted(obj.keys())[0]\n return obj[key]\n\n\ndef head(obj, key=None, max_n=2, tag=None):\n \"\"\"\n Show head of dict or panel.\n \"\"\"\n txt = \"\"\n txt += \"# %s\\n\" % str(type(obj))\n if isinstance(obj, dict):\n txt += \"keys=%s\\n\" % format_list(list(obj.keys()), tag=tag)\n if key is None:\n key = sorted(obj.keys())[0]\n txt += \"# key=%s\\n\" % key\n txt += dbg.space(head(obj[key], key=None, max_n=max_n, tag=\"value\"))\n elif isinstance(obj, pd.Panel):\n txt += describe(obj, max_n=max_n) + \"\\n\"\n txt += \"# head=\\n\"\n txt += dbg.space(str(obj[obj.items[0]].head(max_n)))\n elif isinstance(obj, pd.Series) or isinstance(obj, pd.DataFrame):\n txt += str(obj.head(max_n))\n else:\n raise ValueError(\"Invalid object %s\" % str(obj))\n return txt\n\n\ndef analyze_object(locals_tmp, obj, tag=\"\", max_string_len=1000):\n locals().update(locals_tmp)\n print(\"obj=\", tag)\n print(\"type(obj)=\", type(obj))\n print(\"str(obj)=\", str(obj)[:max_string_len])\n data = []\n for x in dir(obj):\n try:\n val = getattr(obj, x)\n type_ = type(val)\n val = str(val)\n except Exception as e:\n type_ = \"exception\"\n val = str(e)\n data.append((x, type_, val))\n data = pd.DataFrame(data, columns=[\"key\", \"type(val)\", \"val\"])\n data.set_index(\"key\", inplace=True)\n IPython.core.display.display(IPython.core.display.HTML(data.to_html()))\n\n\n# #############################################################################\n# Pandas data structure utils.\n# #############################################################################\n\n# /////////////////////////////////////////////////////////////////////////////\n# Printing.\n# /////////////////////////////////////////////////////////////////////////////\n\n\ndef describe(obj, tag=None, max_n=None):\n txt = \"\"\n if tag is not None:\n txt += \"%s=\\n\" % tag\n if isinstance(obj, pd.Panel):\n txt += \"type=pd.Panel\\n\"\n txt += format_list(obj.axes[0], max_n=max_n, tag=\"items\") + \"\\n\"\n txt += format_list(obj.axes[1], max_n=2, tag=\"major\") + \"\\n\"\n txt += format_list(obj.axes[2], max_n=max_n, tag=\"minor\") + \"\\n\"\n elif isinstance(obj, pd.DataFrame):\n txt += \"type=pd.DataFrame\\n\"\n txt += format_list(obj.columns, max_n=max_n, tag=\"columns\") + \"\\n\"\n txt += format_list(obj.index, max_n=2, tag=\"index\") + \"\\n\"\n elif isinstance(obj, pd.Series):\n txt += \"type=pd.Series\\n\"\n txt += \"name=%s\" % obj.name + \"\\n\"\n txt += format_list(obj.index, max_n=2, tag=\"index\") + \"\\n\"\n elif isinstance(obj, list):\n txt += \"type=list\\n\"\n if tag is None:\n tag = \"\"\n txt += print_list(tag, obj, to_string=True)\n else:\n raise ValueError(str(obj))\n txt = txt.rstrip(\"\\n\")\n return txt\n\n\ndef head_tail(df, num_rows=2, as_txt=False):\n # TODO(gp): concat head and tail and add an empty row with all ...\n head = df.head(num_rows)\n head.index.name = \"head\"\n display_df(head, inline_index=True, as_txt=as_txt)\n #\n print()\n #\n tail = df.tail(num_rows)\n tail.index.name = \"tail\"\n display_df(tail, inline_index=True, as_txt=as_txt)\n\n\ndef find_common_columns(df):\n cols_cnt = {}\n for c in df.columns:\n cols_cnt[c] = cols_cnt.get(c, 0) + 1\n cols = [c for c in df.columns if cols_cnt[c] > 1]\n return cols\n\n\ndef min_max_index(obj, tag=None):\n index = get_index(obj)\n dbg.dassert(index.is_unique)\n dbg.dassert(index.is_monotonic)\n txt = \"\"\n if tag:\n txt += \"%s: \" % tag\n txt += \"[%s, %s], count=%s\" % (\n pd.to_datetime(index.values[0]),\n pd.to_datetime(index.values[-1]),\n len(index),\n )\n return txt\n\n\ndef min_max(obj, tag=None):\n # dbg.dassert_in(type(obj), (list, tuple))\n txt = \"\"\n if tag:\n txt += \"%s: \" % tag\n if len(obj) > 0:\n if hasattr(obj, \"is_monotonic\"):\n min_, max_ = obj.values[0], obj.values[-1]\n else:\n min_, max_ = min(obj), max(obj)\n txt += \"[%s, %s], count=%s\" % (min_, max_, len(obj))\n else:\n txt += \"empty\"\n return txt\n\n\ndef columns(df):\n \"\"\"\n Print df columns vertically.\n \"\"\"\n dbg.dassert_type_is(df, pd.DataFrame)\n print(\"columns=\")\n print(dbg.space(\"\\n\".join(df.columns)))\n\n\ndef exact_rename_df(df, rename_map, axis):\n \"\"\"\n Same as df.rename() but checking that all columns / index are replaced.\n \"\"\"\n dbg.dassert_type_is(df, pd.DataFrame)\n if axis == 0:\n vals = df.index\n elif axis == 1:\n vals = df.columns\n else:\n raise ValueError(\"Invalid axis=%s\" % axis)\n dbg.dassert_set_eq(vals, list(rename_map.keys()))\n if axis == 0:\n df = df.rename(index=rename_map)\n elif axis == 1:\n df = df.rename(columns=rename_map)\n else:\n raise ValueError(\"Invalid axis=%s\" % axis)\n return df\n\n\n# /////////////////////////////////////////////////////////////////////////////\n# General and helpers.\n# /////////////////////////////////////////////////////////////////////////////\n\n\ndef get_index(obj):\n if isinstance(obj, pd.Index):\n pass\n elif isinstance(obj, pd.DataFrame):\n index = obj.index\n elif isinstance(obj, pd.Series):\n index = obj.index\n elif isinstance(obj, pd.Panel):\n index = obj.axes[1]\n else:\n dbg.dfatal(\"Invalid type(obj)=%s\" % type(obj))\n return index\n\n\ndef check_index_type(series):\n exp_type = None\n for s in series:\n dbg.dassert_type_is(s, pd.Series)\n curr_type = series.index\n # curr_type = type(series.index[0])\n if exp_type is None:\n exp_type = curr_type\n else:\n dbg.dassert_eq(\n exp_type,\n curr_type,\n msg=\"series '%s' has different index type\" % s.name,\n )\n return True\n\n\n# /////////////////////////////////////////////////////////////////////////////\n# Filtering.\n# /////////////////////////////////////////////////////////////////////////////\n\n\ndef filter_by_period(\n obj, start_time, end_time, axis=None, mode=None, verbosity=logging.DEBUG\n):\n \"\"\"\n Filter an obj that can be sliced with [start_time:end_time] reporting\n stats.\n \"\"\"\n _LOG.log(verbosity, \"# Filtering in [%s, %s]\", start_time, end_time)\n if isinstance(obj, pd.Panel) or isinstance(obj, pd.Panel4D):\n dbg.dassert_is_not(axis, None)\n index = obj.axes[axis]\n elif isinstance(obj, pd.DataFrame):\n index = obj.index\n else:\n raise ValueError(\"Invalid type(obj)=%s\" % type(obj))\n _LOG.log(verbosity, \"before=%s\", min_max(index))\n # Slice index.\n index_tmp = slice_index(index, start_time, end_time, mode=mode)\n dbg.dassert_lte(1, len(index_tmp))\n # Assign.\n _LOG.log(verbosity, \"after=%s\", min_max(index_tmp))\n # TODO(gp): Find out how to do it systematically.\n if isinstance(obj, pd.DataFrame):\n if axis == 0:\n obj = obj.loc[index_tmp, :]\n elif axis == 1:\n obj = obj.loc[:, index_tmp]\n else:\n raise ValueError(\"Invalid axis=%s\" % axis)\n elif isinstance(obj, pd.Panel):\n if axis == 0:\n obj = obj.loc[index_tmp, :, :]\n elif axis == 1:\n obj = obj.loc[:, index_tmp, :]\n elif axis == 2:\n obj = obj.loc[:, :, index_tmp]\n else:\n raise ValueError(\"Invalid axis=%s\" % axis)\n elif isinstance(obj, pd.Panel4D):\n if axis == 0:\n obj = obj.loc[index_tmp, :, :, :]\n elif axis == 1:\n obj = obj.loc[:, index_tmp, :, :]\n elif axis == 2:\n obj = obj.loc[:, :, index_tmp, :]\n elif axis == 3:\n obj = obj.loc[:, :, :, index_tmp]\n else:\n raise ValueError(\"Invalid axis=%s\" % axis)\n else:\n raise ValueError(\"Invalid type(obj)=%s\" % type(obj))\n return obj\n\n\ndef filter_on_times(df, start_time, end_time, reverse=False):\n \"\"\"\n Filter df keeping rows with index times in [start_time, end_times].\n\n - reverse: reverse the filtering\n \"\"\"\n dbg.dassert_type_is(df, pd.DataFrame)\n dbg.dassert_type_is(start_time, datetime.time)\n dbg.dassert_type_is(end_time, datetime.time)\n mask = [start_time <= dt.time() <= end_time for dt in df.index]\n if reverse:\n mask = ~mask\n return df[mask]\n\n\n# def drop_zeros(srs):\n# is_df = False\n# if isinstance(srs, pd.DataFrame):\n# srs = cast_df_to_series(srs)\n# is_df = True\n# dbg.dassert_type_is(srs, pd.Series)\n# mask = srs != 0\n# srs = srs[mask]\n#\n# return srs\n#\n#\n# def drop_not_finite(srs):\n# dbg.dassert_type_is(srs, pd.Series)\n# return srs[np.isfinite(srs)]\n\n\ndef sample_index_times(obj, time):\n \"\"\"\n Sample a pandas obj on a given time.\n \"\"\"\n dbg.dassert_type_is(time, datetime.time)\n index = get_index(obj)\n # dbg.dassert_type_is(index.values[0].time(), datetime.time)\n mask = [pd.to_datetime(dt).time() == time for dt in index]\n ret = obj[mask].copy()\n dbg.dassert_lte(1, ret.shape[0])\n return ret\n\n\ndef drop_before_first_row_without_nans(df):\n \"\"\"\n Filter df before the first row without nans.\n \"\"\"\n return df[df.dropna().index[0] :]\n\n\n# TODO(gp): -> remove_non_finite()?\n# TODO(gp): Extend to work for a general value (e.g., 0.0)\ndef filter_non_finite(obj, col_names=None, keep_finite=True, print_stats=False):\n \"\"\"\n Return the filtered obj (data frame, series, numpy array) removing non-\n finite values in any column in col_names.\n \"\"\"\n\n # Select what we want to keep.\n def _build_mask(mask, keep_finite):\n if keep_finite:\n mask = finite_mask\n else:\n mask = ~finite_mask\n return mask\n\n if isinstance(obj, pd.DataFrame):\n # Data frame.\n if col_names is None:\n col_names = obj.columns\n if isinstance(col_names, str):\n col_names = [col_names]\n dbg.dassert_is_subset(col_names, obj.columns)\n finite_mask = np.all(np.isfinite(obj[col_names]), axis=1)\n mask = _build_mask(finite_mask, keep_finite)\n # Save the removed values.\n vals = obj[~mask].values.flatten()\n elif isinstance(obj, pd.Series):\n # Series.\n dbg.dassert_is(col_names, None)\n finite_mask = np.isfinite(obj)\n mask = _build_mask(finite_mask, keep_finite)\n vals = obj[~mask].values.tolist()\n elif isinstance(obj, np.ndarray):\n # Numpy array.\n finite_mask = np.isfinite(obj)\n mask = _build_mask(finite_mask, keep_finite)\n vals = obj[~finite_mask]\n else:\n raise ValueError(\"Invalid type='%s'\" % type(obj))\n # Select what we want to keep.\n obj_tmp = obj[mask]\n # Report stats, if needed.\n if print_stats:\n before_num_cols = obj.shape[0]\n after_num_cols = obj_tmp.shape[0]\n print(\"filter_non_finite (keep_finite=%s):\" % keep_finite)\n print(\n \"\\tkept rows=%s\"\n % dbg.perc(after_num_cols, before_num_cols, printAll=True)\n )\n\n def _count_non_finite(vals):\n count = {\"nan\": 0, \"-inf\": 0, \"+inf\": 0}\n for v in vals:\n if np.isnan(v):\n count[\"nan\"] += 1\n elif np.isposinf(v):\n count[\"+inf\"] += 1\n elif np.isneginf(v):\n count[\"-inf\"] += 1\n return count\n\n print(\"\\tvals=%s\" % pprint.pformat(_count_non_finite(vals)))\n # Convert back to the correct type.\n if isinstance(obj_tmp, pd.DataFrame):\n dbg.dassert_lte(1, obj_tmp.shape[0])\n elif isinstance(obj_tmp, pd.Series) or isinstance(obj_tmp, np.ndarray):\n dbg.dassert_lte(1, len(obj_tmp))\n else:\n raise ValueError(\"Invalid type='%s'\" % type(obj_tmp))\n return obj_tmp\n\n\n# /////////////////////////////////////////////////////////////////////////////\n# Transform.\n# /////////////////////////////////////////////////////////////////////////////\n\n\ndef prepend_df_columns(df, prefix, copy=True):\n if copy:\n df = df.copy()\n df.columns = [prefix + c for c in df.columns]\n return df\n\n\ndef align_to_dt_index(idx, dt):\n dbg.dassert_type_is(idx, pd.DatetimeIndex)\n dbg.dassert(idx.is_monotonic)\n utc = idx.tz is not None\n dt = pd.to_datetime(dt, utc=utc)\n dt_aligned = idx[bisect.bisect_left(idx, dt)]\n return dt_aligned\n\n\ndef align_to_index(obj, dt):\n idx = get_index(obj)\n return align_to_dt_index(idx, dt)\n\n\ndef slice_index(idx, start_dt, end_dt, mode=None):\n \"\"\"\n - None means no bound\n \"\"\"\n dbg.dassert_type_is(idx, pd.DatetimeIndex)\n dbg.dassert(idx.is_monotonic)\n if mode is None:\n mode = \"close\"\n utc = idx.tz is not None\n #\n if start_dt is not None:\n start_dt = pd.to_datetime(start_dt, utc=utc)\n else:\n start_dt = idx[0]\n if end_dt is not None:\n end_dt = pd.to_datetime(end_dt, utc=utc)\n else:\n end_dt = idx[-1]\n dbg.dassert_lte(start_dt, end_dt)\n # TODO(gp): Fix this.\n if mode == \"open\":\n start_idx = bisect.bisect_left(idx, start_dt)\n end_idx = bisect.bisect_left(idx, end_dt)\n elif mode == \"close\":\n start_idx = bisect.bisect_right(idx, start_dt)\n end_idx = bisect.bisect_right(idx, end_dt)\n else:\n raise ValueError(\"Invalid mode=%s\" % mode)\n return idx[start_idx:end_idx]\n\n\ndef concat_series(series, cols=None, join=\"outer\"):\n dbg.dassert(check_index_type(series))\n if cols is None:\n cols = [srs.name for srs in series]\n dbg.dassert_eq(len(series), len(cols))\n dbg.dassert_no_duplicates(cols)\n srs_tmp = []\n for srs, col in zip(series, cols):\n if isinstance(srs, pd.DataFrame):\n dbg.dassert_eq(len(srs.columns), 1)\n srs = srs[srs.columns[0]]\n srs = srs.copy()\n srs.name = col\n srs_tmp.append(srs)\n df = pd.concat(srs_tmp, join=join, axis=1)\n return df\n\n\n# TODO(gp): merge with merge().\ndef concat_to_df(df, obj, overwrite=False):\n \"\"\"\n Concat df and obj by column.\n \"\"\"\n if isinstance(obj, pd.Series):\n obj = pd.DataFrame(obj)\n dbg.dassert_type_is(obj, pd.DataFrame)\n #\n if set(obj.columns).issubset(df.columns):\n # df overlaps with obj.\n dbg.dassert(overwrite, msg=\"Columns already present: one must overwrite\")\n df.drop(obj.columns, axis=1, inplace=True)\n # Merge.\n dbg.dassert(not set(df.columns).intersection(set(obj.columns)))\n df = df.merge(obj, how=\"outer\", left_index=True, right_index=True)\n return df\n\n\ndef merge(df1, df2, tag1=\"1\", tag2=\"2\", *args, **kwargs):\n \"\"\"\n Wrapper around pd.merge() that prepends the name of the columns.\n \"\"\"\n df1 = prepend_df_columns(df1, tag1 + \".\")\n df2 = prepend_df_columns(df2, tag2 + \".\")\n df = pd.merge(df1, df2, *args, **kwargs)\n return df\n\n\ndef shuffle_df(df, mode, seed, axis=0):\n df = df.copy()\n np.random.seed(seed)\n idx = df.index.copy()\n if mode == \"shuffle_index\":\n loc_idx = np.arange(len(idx))\n np.random.shuffle(loc_idx)\n df = df.iloc[loc_idx]\n df.index = idx\n else:\n dbg.dassert_eq(mode, \"shuffle_all\")\n df.apply(np.random.shuffle, axis=axis)\n dbg.dassert(np.all(df.index == idx))\n return df\n\n\ndef shuffle(obj, mode, seed):\n \"\"\"\n Shuffle predictors in a dict tag -> feature.\n \"\"\"\n dbg.dassert_in(type(obj), [dict, pd.Panel])\n for c in list(obj.keys()):\n obj[c] = shuffle_df(obj[c], mode, seed, axis=0)\n return obj\n\n\ndef random(obj, seed):\n dbg.dassert_in(type(obj), [dict, pd.Panel])\n np.random.seed(seed)\n for c in list(obj.keys()):\n idx = obj[c].index\n cols = obj[c].columns\n obj[c] = pd.DataFrame(\n np.random.rand(*obj[c].shape) * 2 - 1.0, index=idx, columns=cols\n )\n return obj\n\n\ndef remove_outliers(\n obj,\n lower_quantile,\n upper_quantile=None,\n mode=None,\n inplace=False,\n print_stats=True,\n):\n \"\"\"\n Remove / winsorize outliers (according to \"mode\") given lower / upper\n quantile in df[col_name].\n \"\"\"\n if upper_quantile is None:\n upper_quantile = 1.0 - lower_quantile\n if mode is None:\n mode = \"winsorize\"\n _LOG.debug(\"Removing outliers with mode=%s\", mode)\n bounds = utils.jstats.get_quantile_bounds(obj, lower_quantile, upper_quantile)\n if print_stats:\n _LOG.debug(\"bounds=%s\", str(bounds))\n if inplace:\n ret = obj\n else:\n ret = obj.copy()\n if mode == \"winsorize\":\n ret[obj <= bounds[0]] = bounds[0]\n ret[bounds[1] <= obj] = bounds[1]\n if print_stats:\n num = np.sum(obj <= bounds[0]) + np.sum(bounds[1] <= obj)\n _LOG.debug(\n \"winsorize: to_process=%s\", dbg.perc(num, len(ret), printAll=True)\n )\n else:\n mask = (bounds[0] <= obj) & (obj <= bounds[1])\n if print_stats:\n num = np.sum(mask)\n _LOG.debug(\n \"%s: to_process=%s\", mode, dbg.perc(num, len(ret), printAll=True)\n )\n if mode == \"set_to_nan\":\n ret[~mask] = np.nan\n _LOG.debug(\n \"overwritten %s / %s elems with nan\",\n np.sum(~np.isfinite(ret)),\n np.sum(np.isfinite(obj)),\n )\n elif mode == \"set_to_zero\":\n ret[~mask] = 0.0\n _LOG.debug(\n \"overwritten %s / %s elems with 0\", np.sum(~mask), obj.shape[0]\n )\n elif mode == \"filter\":\n ret = ret[mask].copy()\n else:\n dbg.dfatal(\"Invalid mode='%s'\" % mode)\n return ret, bounds\n\n\ndef remove_outlier_rows_from_df(\n df, lower_quantile, upper_quantile=None, col_names=None, mode=None\n):\n \"\"\"\n Remove outlier rows, i.e., rows where there is at least one outlier in each\n column.\n \"\"\"\n dbg.dassert_type_is(df, pd.DataFrame)\n num_cols = df.shape[0]\n if col_names is None:\n col_names_to_trim = df.columns\n else:\n col_names_to_trim = col_names\n _LOG.debug(\"Trimming based on col_names=%s\", str(col_names_to_trim))\n # Scan and trim columns.\n trimmed_cols = []\n for col in df.columns:\n if col in col_names_to_trim:\n _LOG.debug(\"Trimming col %s\", col)\n trimmed_col, _ = remove_outliers(\n df[col], lower_quantile, upper_quantile=upper_quantile, mode=mode\n )\n else:\n _LOG.debug(\"Skipping col %s\", col)\n trimmed_col = df[col]\n trimmed_cols.append(trimmed_col)\n ret = pd.concat(trimmed_cols, join=\"outer\", axis=1)\n _LOG.debug(\"Trimmed %s rows out of %s\", num_cols - ret.shape[0], num_cols)\n return ret\n\n\ndef scale_by_std(df, demean=False):\n \"\"\"\n Align the columns of the df to the last value.\n \"\"\"\n df = df.copy()\n if demean:\n df -= df.dropna().mean()\n scale = np.abs(df.dropna().std())\n return df / scale\n\n\ndef align_df_to_last_value(df):\n \"\"\"\n Align the columns of the df to the last value.\n \"\"\"\n df = df.dropna()\n # df -= df.min()\n df /= df.iloc[-1]\n return df\n\n\n# /////////////////////////////////////////////////////////////////////////////\n# Query and report.\n# /////////////////////////////////////////////////////////////////////////////\n\n\ndef get_times(obj):\n index = get_index(obj)\n times = set(dt.time() for dt in index)\n return sorted(times)\n\n\ndef get_time_interval(times):\n \"\"\"\n Given a set of intervals (e.g., where there are returns, from get_times())\n compute first, last, and count.\n \"\"\"\n times = sorted(list(times))\n return min(times), max(times), len(times)\n\n\ndef report_nan_nums_for_columns(\n df, display=True, fmt_pct=True, plot=False, title=None, figsize=None\n):\n dbg.dassert_type_is(df, pd.DataFrame)\n print(\"columns=(%s) %s\" % (len(df.columns), \" \".join(df.columns)))\n print(\"dates=[%s, %s]\" % (df.index[0], df.index[-1]))\n print(\"num_dates=\", df.shape[0])\n # Count nans.\n count = pd.DataFrame(np.isnan(df).sum(axis=0), columns=[\"nans\"])\n col_name = \"pct_nans [%]\"\n count[col_name] = count[\"nans\"] / df.shape[0] * 100.0\n if fmt_pct:\n count[col_name] = [float(\"%.1f\" % x) for x in count[col_name]]\n # Count zeros.\n count[\"zeros\"] = (df == 0).sum(axis=0)\n col_name = \"pct_zeros [%]\"\n count[col_name] = count[\"zeros\"] / df.shape[0] * 100.0\n if fmt_pct:\n count[col_name] = [float(\"%.1f\" % x) for x in count[col_name]]\n if plot:\n count_tmp = count.sort(columns=[\"pct\"])\n count_tmp[[\"pct\"]].plot(kind=\"bar\", title=title, figsize=figsize)\n if display:\n display_df(count, as_txt=True)\n\n\ndef report_intraday_stats(rets):\n \"\"\"\n Assume data frame with datestamps on index and instruments on the columns\n and report for each instrument.\n min_hour max_hour min_date max_date\n inst\n ...\n \"\"\"\n dbg.dassert_type_is(rets, pd.DataFrame)\n stats_df = []\n count_by_hour = rets.groupby(lambda x: x.time).count()\n for inst_name in count_by_hour.columns:\n row = [inst_name]\n # Find non-null times.\n hours_non_null = count_by_hour[inst_name].nonzero()[0]\n dbg.dassert_lte(1, len(hours_non_null))\n first_non_zero = hours_non_null[0]\n row.append(count_by_hour[inst_name].index[first_non_zero])\n #\n last_non_zero = hours_non_null[-1]\n row.append(count_by_hour[inst_name].index[last_non_zero])\n # Find first non-null dates.\n dates_non_null = rets[inst_name].notnull().nonzero()[0]\n dbg.dassert_lte(1, len(dates_non_null))\n min_date = rets.index[dates_non_null[0]].date()\n row.append(min_date)\n #\n max_date = rets.index[dates_non_null[-1]].date()\n row.append(max_date)\n #\n stats_df.append(row)\n stats_df = pd.DataFrame(\n stats_df, columns=[\"inst\", \"min_hour\", \"max_hour\", \"min_date\", \"max_date\"]\n )\n stats_df.set_index(\"inst\", drop=True, inplace=True)\n return stats_df\n\n\ndef plot_intraday_stats(rets):\n inst_names = rets.columns\n plt.figure(figsize=(20, 3 * len(inst_names)))\n for i, inst_name in enumerate(inst_names):\n ax = plt.subplot(len(inst_names) + 1, 1, i + 1)\n rets_tmp = rets[inst_name].astype(float)\n rets_tmp.groupby(lambda x: x.time).count().plot(ax=ax, title=inst_name)\n plt.plot()\n\n\n# /////////////////////////////////////////////////////////////////////////////\n# Conversion.\n# /////////////////////////////////////////////////////////////////////////////\n\n\ndef cast_df_to_series(df):\n \"\"\"\n Convert one column df into a series.\n \"\"\"\n dbg.dassert_type_is(df, pd.DataFrame)\n dbg.dassert_eq(df.shape[1], 1)\n return df[df.columns[0]]\n\n\ndef to_pd_timestamp(obj):\n \"\"\"\n Cast index of a df or srs through pd.to_datetime().\n \"\"\"\n dbg.dassert_type_in(obj, (pd.DataFrame, pd.Series))\n obj = obj.copy()\n # TODO(gp): Maybe apply or map is faster.\n obj.index = [pd.to_datetime(dt) for dt in obj.index]\n return obj\n\n\ndef to_date(obj, axis=None):\n \"\"\"\n Cast index of a df or srs through pd.to_datetime().\n \"\"\"\n dbg.dassert_type_in(obj, (pd.Panel, pd.DataFrame, pd.Series))\n obj = obj.copy()\n if isinstance(obj, pd.Panel):\n dbg.dassert_is_not(axis, None)\n # For some reason .axes[axis] doesn't work for writing but only for\n # reading.\n transform = lambda obj: [dt.date() for dt in obj.axes[axis]]\n if axis == 0:\n obj.items = transform(obj)\n elif axis == 1:\n obj.major_axis = transform(obj)\n elif axis == 2:\n obj.minor_axis = transform(obj)\n else:\n raise ValueError(\"Invalid axis=%s\" % axis)\n else:\n # TODO(gp): Maybe apply or map is faster.\n obj.index = [dt.date() for dt in obj.index]\n return obj\n\n\n# /////////////////////////////////////////////////////////////////////////////\n# Misc.\n# /////////////////////////////////////////////////////////////////////////////\n\n\ndef safe_div(x1, x2):\n return x1 / np.where(x2 != 0, x2, 1)\n\n\ndef to_csv(model_df, file_name, overwrite_if_present):\n # Make the path linux friendly and absolute.\n dir_name = os.path.dirname(file_name)\n base_name = os.path.basename(file_name).replace(\"/\", \"_\")\n file_name = os.path.abspath(\"%s/%s\" % (dir_name, base_name))\n dbg.dassert(\n file_name.endswith(\".csv\"), msg=\"Invalid file_name='%s'\" % file_name\n )\n # Create dir, if needed.\n utils.jio.create_enclosing_dir(file_name, incremental=True)\n if not overwrite_if_present:\n dbg.dassert(\n not os.path.exists(file_name),\n msg=\"don't want to overwrite '%s'\" % file_name,\n )\n # Save data.\n to_typed_csv(model_df, file_name)\n print(\"File saved to: %s\" % file_name)\n\n\ndef plot_rolling_correlation(df, vmin=-1, vmax=1):\n col_pairs = []\n for i in range(len(df.columns)):\n for j in range(i + 1, len(df.columns)):\n col_pairs.append((df.columns[i], df.columns[j]))\n # Compute the correlations.\n df_corr = []\n df = df.dropna()\n for lbl1, lbl2 in col_pairs:\n srs = pd.rolling_corr(df[lbl1], df[lbl2], window=252)\n srs.name = \"%s vs %s\" % (lbl1, lbl2)\n df_corr.append(srs)\n df_corr = pd.concat(df_corr, join=\"outer\", axis=1)\n # Plot.\n ax = df_corr.plot(ylim=(vmin, vmax), cmap=\"rainbow\")\n #\n ax.axhline(0, color=\"gray\", linestyle=\"--\", lw=2)\n #\n ax.axhline(-0.5, color=\"green\", linestyle=\"--\", alpha=0.5)\n ax.axhline(0.5, color=\"green\", linestyle=\"--\", alpha=0.5)\n\n\ndef compare_price_timeseries(\n df,\n col_name1,\n col_name2,\n col_names_to_trim=None,\n outliers_thr=None,\n plot_ts=True,\n plot_regress=True,\n print_model_stats=False,\n):\n df = df.dropna()\n df = df[[col_name1, col_name2]]\n # Remove outliers based on returns.\n if outliers_thr is not None:\n dbg.dassert_is_not(col_names_to_trim, None)\n mode = \"set_to_nan\"\n # mode = \"set_to_zero\"\n df = df.dropna()\n num_cols = df.shape[0]\n col_names_to_trim_tmp = []\n for col_name in col_names_to_trim:\n df[col_name + \".ret\"] = df[col_name1].pct_change()\n col_names_to_trim_tmp.append(col_name + \".ret\")\n df = remove_outlier_rows_from_df(\n df, outliers_thr, col_names=col_names_to_trim_tmp, mode=mode\n )\n df = df.dropna()\n df = df[[col_name1, col_name2]]\n _LOG.debug(\"Removed %s out of %s rows\", num_cols - df.shape[0], num_cols)\n df = df.dropna()\n df = scale_by_std(df)\n df -= df.min()\n if plot_ts:\n df.plot()\n if plot_regress:\n _ = regress(\n df.pct_change(),\n col_name1,\n col_name2,\n use_intercept=True,\n print_model_stats=print_model_stats,\n )\n\n\n# #############################################################################\n# Plot.\n# #############################################################################\n\n\ndef config_matplotlib():\n matplotlib.rcParams.update(\n {\n \"axes.labelsize\": 15,\n \"axes.titlesize\": 20,\n #'figure.figsize': [15, 10],\n \"figure.figsize\": [15, 5],\n \"font.size\": 12,\n \"image.cmap\": \"rainbow\",\n \"legend.fontsize\": 15,\n \"xtick.labelsize\": 12,\n \"ytick.labelsize\": 12,\n }\n )\n\n\nsmall_fig = (15, 2)\n\n\ndef set_same_fig_limits(use_ylim, use_xlim, fig=None):\n if fig is None:\n fig = plt.gcf()\n # Find limits.\n ylim = None\n xlim = None\n for ax in fig.get_axes():\n curr_ylim = ax.get_ylim()\n if ylim is None:\n ylim = curr_ylim\n else:\n ylim = (min(ylim[0], curr_ylim[0]), max(ylim[1], curr_ylim[1]))\n #\n curr_xlim = ax.get_xlim()\n if xlim is None:\n xlim = curr_xlim\n else:\n xlim = (min(xlim[0], curr_xlim[0]), max(xlim[1], curr_xlim[1]))\n # Apply limits.\n for ax in fig.get_axes():\n if use_ylim:\n ax.set_ylim(ylim)\n if use_xlim:\n ax.set_xlim(xlim)\n\n\ndef plot_density(data, color=\"m\", ax=None, figsize=None, title=\"\"):\n if len(data) <= 1:\n _LOG.error(\"Can't plot density with %s elements\", len(data))\n return\n dbg.dassert_lte(1, len(data))\n dbg.dassert_type_is(color, str)\n if isinstance(data, (list, tuple)):\n data = np.array(data)\n data = data[np.isfinite(data)]\n if ax is None:\n _, ax = plt.subplots(figsize=figsize)\n ax.set_title(title)\n sns.distplot(data, color=color, ax=ax)\n\n\n# It can't accept ax.\ndef jointplot(\n df,\n predicted_var,\n predictor_var,\n color=\"r\",\n # TODO(gp): -> figsize?\n size=7,\n kind=\"reg\",\n fit_reg=True,\n intercept=True,\n):\n dbg.dassert_in(predicted_var, df.columns)\n dbg.dassert_in(predictor_var, df.columns)\n if not intercept:\n _LOG.error(\"Can't plot without intercept\")\n return\n df = df[[predicted_var, predictor_var]]\n # Remove non-finite values.\n mask = np.all(np.isfinite(df.values), axis=1)\n df = df[mask]\n # Plot.\n sns.jointplot(\n predictor_var,\n predicted_var,\n df,\n kind=kind,\n color=color,\n size=size,\n fit_reg=fit_reg,\n )\n\n\ndef regplot(df, predicted_var, predictor_var, color=\"r\", ax=None):\n \"\"\"\n Do not show the marginal distributions and pearson coefficient.\n \"\"\"\n dbg.dassert_in(predicted_var, df.columns)\n dbg.dassert_in(predictor_var, df.columns)\n df = df[[predicted_var, predictor_var]]\n # Remove non-finite values.\n mask = np.all(np.isfinite(df.values), axis=1)\n df = df[mask]\n # Plot.\n ax = sns.regplot(predicted_var, predictor_var, df, color=color, ax=ax)\n # Add info about the fit.\n slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(\n df[predictor_var].values, df[predicted_var].values\n )\n _ = slope, intercept, std_err\n label = \"rho=%.2f pval=%.2f\" % (r_value, p_value)\n ax.text(\n 0.9,\n 0.9,\n label,\n fontsize=20,\n horizontalalignment=\"right\",\n verticalalignment=\"top\",\n transform=ax.transAxes,\n )\n return ax\n\n\ndef plot_acf(data, lags=10, remove_nans=False, figsize=None):\n \"\"\"\n - autocorrelation is the correlation coefficient of a time series with\n itself at different lags\n - partial autocorrelation controls for values at previous lags\n \"\"\"\n dbg.dassert_type_is(data, pd.Series)\n if remove_nans:\n mask = np.isnan(data)\n print(\n \"Removed %s nans\"\n % (dbg.perc(np.sum(mask), len(data), numDigits=2, printAll=True))\n )\n data = data[~mask]\n dbg.dassert_eq(sum(np.isnan(data)), 0, msg=\"data has nans\")\n if figsize is None:\n figsize = (16, 6)\n _, axes = plt.subplots(3, figsize=figsize, sharex=True)\n #\n acf = statsmodels.tsa.stattools.acf(data)[:lags]\n srs = pd.Series(acf, index=list(range(0, lags)))\n srs.name = \"acf\"\n print(\"acf=\\n%s\" % srs.to_string())\n #\n statsmodels.api.graphics.tsa.plot_acf(data, lags=lags, ax=axes[0])\n statsmodels.api.graphics.tsa.plot_pacf(data, lags=lags, ax=axes[1])\n #\n acf_tmp = acf\n acf_tmp[0] = 0.0\n axes[2].plot(np.cumsum(acf_tmp), marker=\"o\")\n axes[2].set_title(\"Cumsum of acf[1:]\")\n\n\ndef plot_ccf(\n data,\n col_name1,\n col_name2,\n min_lag=-3,\n max_lag=10,\n cumsum=False,\n title=None,\n figsize=None,\n max_nrows=None,\n):\n if max_nrows is not None and data.shape[0] > max_nrows:\n _LOG.warning(\"Skipping since df has %s rows\", data.shape[0])\n return\n # Sanity check for params.\n dbg.dassert_lte(min_lag, max_lag)\n dbg.dassert_lte(0, max_lag)\n # dbg.dassert_ne(col_name1, col_name2)\n dbg.dassert_in(col_name1, data.columns)\n dbg.dassert_in(col_name2, data.columns)\n suffix = \" (cumsum)\" if cumsum else \"\"\n if title is None:\n title = \"%s ~ %s\" % (col_name1, col_name2)\n title += suffix\n if figsize is None:\n figsize = (16, 4)\n # Extract and prepare the data.\n # data = data[[col_name1, col_name2]].copy()\n # data[col_name2] = data[col_name2].shift(min_lag)\n # data = filter_non_finite(data, [col_name1, col_name2])\n # Compute cross-correlation.\n dbg.dassert_lte(1, data.shape[0])\n ccf = []\n lags = list(range(min_lag, max_lag + 1))\n for lag in lags:\n # Filter non-finite values.\n data_tmp = data[[col_name1, col_name2]].copy()\n data_tmp[col_name2] = data_tmp[col_name2].shift(min_lag)\n # Filter non-finite values.\n data = filter_non_finite(data_tmp, [col_name1, col_name2])\n if lag == 0:\n corr = 1.0\n else:\n corr = data_tmp[col_name1].corr(data_tmp[col_name2])\n ccf.append(corr)\n # ccf = statsmodels.tsa.stattools.ccf(data[col_name1], data[col_name2])\n # print ccf\n # ccf = ccf[:((abs(min_lag) + max_lag))]\n if cumsum:\n ccf = np.cumsum(ccf)\n # Report results.\n df = pd.DataFrame(ccf, columns=[\"ccf\" + suffix], index=lags)\n print(df.to_string())\n # Plot.\n plt.figure(figsize=figsize)\n plt.title(title)\n plt.xlabel(\"Num lags\")\n plt.ylabel(\"Cross correlation\" + suffix)\n dbg.dassert(np.all(np.isfinite(ccf)))\n dbg.dassert_eq(len(lags), len(ccf))\n plt.axhline(0, color=\"k\", linestyle=\"--\")\n plt.plot(lags, ccf, marker=\"o\")\n # - Show all xticks.\n plt.xlim(min_lag, max_lag)\n plt.xticks(list(range(min_lag, max_lag)))\n # Print some stats.\n argmin = lags[np.argmin(ccf)]\n argmax = lags[np.argmax(ccf)]\n print(\n \"min: lag=%s (val=%.2f), max: lag=%s val=%.2f\"\n % (argmin, ccf[argmin], argmax, ccf[argmax])\n )\n\n\ndef plot_bootstrap_ccf(\n x_to_lag,\n x_fixed,\n label=\"\",\n color=None,\n min_lags=-20,\n max_lags=20,\n conf_int=False,\n samples=200,\n ax=None,\n):\n \"\"\"\n lags describes how many days before / after today should we lag for\n Plot*CrossCorrelation.\n \"\"\"\n dbg.dassert_eq(\n len(x_to_lag),\n len(x_fixed),\n msg=\"x_to_lag and x_fixed should have the same shape.\",\n )\n dbg.dassert_lt(min_lags, max_lags)\n # We create confidence intervals by computing the correlation\n # over bootstrap samples.\n correlations = []\n # Make sure we have enough samples that we have 10 on either\n # side of the 95% CI.\n BOOTSTRAP_SAMPLES = samples\n lags = max_lags - min_lags\n for bootstrap in range(BOOTSTRAP_SAMPLES):\n N = x_to_lag.shape[0]\n samples = []\n for lag in range(min_lags, max_lags):\n bootstrap = np.random.randint(0, N - 2 * lags, size=N - 2 * lags)\n x1_window = x_to_lag[(lags + lag) : ((lags + lag) + (N - 2 * lags))][\n bootstrap\n ]\n x2_window = x_fixed[lags : (N - lags)][bootstrap]\n samples.append(\n utils.stats.Cor(np.ravel(x1_window), np.ravel(x2_window))\n )\n correlations.append(samples)\n correlations = np.array(correlations)\n means = np.mean(correlations, axis=0)\n if conf_int:\n if False:\n cis = []\n for i in range(correlations.shape[1]):\n ci = utils.stats.Quantile(\n correlations[:, i], probs=[0.025, 0.5, 0.975]\n )\n # ci = np.std(correlations[:, i]) * 1.96\n cis.append(ci)\n cis = np.std(correlations, axis=0) * 1.96\n cis = np.array(cis)\n else:\n cis = None\n xx = np.array([x for x in range(min_lags, max_lags)])\n # Finally, create a plot with error bars showing confidence intervals on\n # either side.\n if ax is None:\n _, ax = plt.subplots(figsize=(20, 6))\n ax.errorbar(\n xx,\n means, # (cis[:, 2] + cis[:, 0]) / 2.0,\n marker=\"o\", # ms=8,\n yerr=cis, # (cis[:, 2] - cis[:, 0]) / 2.0,\n color=color,\n )\n title = \"Cross correlation\"\n if label != \"\":\n title = \"%s\" % (label,)\n ax.set_title(title)\n plt.axhline(0, color=\"k\", linestyle=\"--\")\n plt.xlabel(\"Lags\")\n ax.set_ylabel(\"Correlation\")\n # ax.grid()\n # Leave it up to the user to plt.show() in case they want to modify the\n # plot.\n return # (cis[:, 0] + cis[:, 2]) / 2.\n\n\ndef plot_signal_with_envelope(df, col_name, span, n_std, ax=None):\n dbg.dassert_in(col_name, df.columns)\n if ax is None:\n _, ax = plt.subplots(figsize=(20, 6))\n df = df.copy()\n df[col_name + \"_ewma\"] = pd.ewma(df[col_name], span=span)\n df[col_name + \"_ewmstd\"] = pd.ewmstd(df[col_name], span=span)\n df[col_name + \"_lb\"] = (\n df[col_name + \"_ewma\"] - n_std * df[col_name + \"_ewmstd\"]\n )\n df[col_name + \"_ub\"] = (\n df[col_name + \"_ewma\"] + n_std * df[col_name + \"_ewmstd\"]\n )\n #\n df[[col_name]].plot(rot=45, color=\"gray\", ax=ax)\n df[col_name + \"_ewma\"].plot(rot=45, color=\"r\", ax=ax)\n df[col_name + \"_lb\"].plot(rot=45, color=\"b\", ls=\"--\", ax=ax)\n df[col_name + \"_ub\"].plot(rot=45, color=\"b\", ls=\"--\", ax=ax)\n\n\ndef compute_correlation(\n df,\n y_col_name,\n x_col_name,\n remove_non_finite=False,\n standardize=False,\n print_stats=False,\n):\n tot_num_samples = df.shape[0]\n col_names = [y_col_name, x_col_name]\n dbg.dassert_is_subset(col_names, df.columns.tolist())\n df = df[col_names]\n if remove_non_finite:\n df = filter_non_finite(df, print_stats=print_stats)\n x, y = df[x_col_name], df[y_col_name]\n if standardize:\n x = (x - x.mean()) / x.std()\n y = (y - y.mean()) / y.std()\n rho, p_val = scipy.stats.stats.pearsonr(x, y)\n if print_stats:\n print(\"num_samples=%s\" % dbg.perc(len(x), tot_num_samples, printAll=True))\n print(\"rho=%.4f\" % rho)\n print(\n \"2-tailed pvalue=%.4f (%s)\"\n % (p_val, utils.jstats.pvalue_to_stars(p_val))\n )\n return rho, p_val\n",
"import collections\nimport datetime\nimport logging\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nimport sklearn as sklear\n\nimport core.config as cconfig\nimport core.data_adapters as cdataa\nimport core.dataflow.utils as cdu\nimport core.finance as cfinan\nimport core.signal_processing as csigna\nimport core.statistics as cstati\nimport helpers.dbg as dbg\nfrom core.dataflow.core import DAG, Node\nfrom core.dataflow.nodes.base import (\n ColModeMixin,\n FitPredictNode,\n SeriesToDfColProcessor,\n)\nfrom core.dataflow.nodes.sources import ReadDataFromDf\nfrom core.dataflow.nodes.transformers import ColumnTransformer\nfrom core.dataflow.visitors import extract_info\n\n_LOG = logging.getLogger(__name__)\n\n\n_COL_TYPE = Union[int, str]\n_PANDAS_DATE_TYPE = Union[str, pd.Timestamp, datetime.datetime]\n_TO_LIST_MIXIN_TYPE = Union[List[_COL_TYPE], Callable[[], List[_COL_TYPE]]]\n\n\nclass SmaModel(FitPredictNode, ColModeMixin):\n \"\"\"\n Fit and predict a smooth moving average (SMA) model.\n \"\"\"\n\n def __init__(\n self,\n nid: str,\n col: _TO_LIST_MIXIN_TYPE,\n steps_ahead: int,\n tau: Optional[float] = None,\n min_tau_periods: Optional[float] = 2,\n col_mode: Optional[str] = None,\n nan_mode: Optional[str] = None,\n ) -> None:\n \"\"\"\n Specify the data and SMA modeling parameters.\n\n :param nid: unique node id\n :param col: name of column to model\n :param steps_ahead: as in `ContinuousSkLearnModel`\n :param tau: as in `csigna.compute_smooth_moving_average`. If `None`,\n learn this parameter. Will be re-learned on each `fit` call.\n :param min_tau_periods: similar to `min_periods` as in\n `csigna.compute_smooth_moving_average`, but expressed in units of\n tau\n :param col_mode: `merge_all` or `replace_all`, as in `ColumnTransformer()`\n :param nan_mode: as in `ContinuousSkLearnModel`\n \"\"\"\n super().__init__(nid)\n self._col = cdu.convert_to_list(col)\n dbg.dassert_eq(len(self._col), 1)\n self._steps_ahead = steps_ahead\n dbg.dassert_lte(\n 0, self._steps_ahead, \"Non-causal prediction attempted! Aborting...\"\n )\n if nan_mode is None:\n self._nan_mode = \"raise\"\n else:\n self._nan_mode = nan_mode\n self._col_mode = col_mode or \"replace_all\"\n dbg.dassert_in(self._col_mode, [\"replace_all\", \"merge_all\"])\n # Smooth moving average model parameters to learn.\n self._must_learn_tau = tau is None\n self._tau = tau\n self._min_tau_periods = min_tau_periods or 0\n self._min_depth = 1\n self._max_depth = 1\n self._metric = sklear.metrics.mean_absolute_error\n\n def fit(self, df_in: pd.DataFrame) -> Dict[str, pd.DataFrame]:\n idx = df_in.index[: -self._steps_ahead]\n x_vars = self._col\n y_vars = self._col\n df = cdu.get_x_and_forward_y_fit_df(\n df_in, x_vars, y_vars, self._steps_ahead\n )\n forward_y_cols = df.drop(x_vars, axis=1).columns\n # Handle presence of NaNs according to `nan_mode`.\n self._handle_nans(idx, df.index)\n # Define and fit model.\n if self._must_learn_tau:\n forward_y_df = df[forward_y_cols]\n # Prepare forward y_vars in sklearn format.\n forward_y_fit = cdataa.transform_to_sklearn(\n forward_y_df, forward_y_df.columns.tolist()\n )\n # Prepare `x_vars` in sklearn format.\n x_fit = cdataa.transform_to_sklearn(df, self._col)\n self._tau = self._learn_tau(x_fit, forward_y_fit)\n _LOG.debug(\"tau=%s\", self._tau)\n return self._predict_and_package_results(df_in, idx, df.index, fit=True)\n\n def predict(self, df_in: pd.DataFrame) -> Dict[str, pd.DataFrame]:\n cdu.validate_df_indices(df_in)\n df = df_in.copy()\n idx = df.index\n # Restrict to times where col has no NaNs.\n non_nan_idx = df.loc[idx][self._col].dropna().index\n # Handle presence of NaNs according to `nan_mode`.\n self._handle_nans(idx, non_nan_idx)\n # Use trained model to generate predictions.\n dbg.dassert_is_not(\n self._tau,\n None,\n \"Parameter tau not found! Check if `fit` has been run.\",\n )\n return self._predict_and_package_results(\n df_in, idx, non_nan_idx, fit=False\n )\n\n def get_fit_state(self) -> Dict[str, Any]:\n fit_state = {\"_tau\": self._tau, \"_info['fit']\": self._info[\"fit\"]}\n return fit_state\n\n def set_fit_state(self, fit_state: Dict[str, Any]) -> None:\n self._tau = fit_state[\"_tau\"]\n self._info[\"fit\"] = fit_state[\"_info['fit']\"]\n\n def _predict_and_package_results(\n self,\n df_in: pd.DataFrame,\n idx: pd.Index,\n non_nan_idx: pd.Index,\n fit: bool = True,\n ) -> Dict[str, pd.DataFrame]:\n data = cdataa.transform_to_sklearn(df_in.loc[non_nan_idx], self._col)\n fwd_y_hat = self._predict(data)\n forward_y_df = cdu.get_forward_cols(df_in, self._col, self._steps_ahead)\n forward_y_df = forward_y_df.loc[non_nan_idx]\n # Put predictions in dataflow dataframe format.\n fwd_y_hat_vars = [f\"{y}_hat\" for y in forward_y_df.columns]\n fwd_y_hat = cdataa.transform_from_sklearn(\n non_nan_idx, fwd_y_hat_vars, fwd_y_hat\n )\n # Return targets and predictions.\n df_out = forward_y_df.reindex(idx).merge(\n fwd_y_hat.reindex(idx), left_index=True, right_index=True\n )\n dbg.dassert_no_duplicates(df_out.columns)\n # Select columns for output.\n df_out = self._apply_col_mode(\n df_in, df_out, cols=self._col, col_mode=self._col_mode\n )\n # Update `info`.\n info = collections.OrderedDict()\n info[\"tau\"] = self._tau\n info[\"min_periods\"] = self._get_min_periods(self._tau)\n info[\"df_out_info\"] = cdu.get_df_info_as_string(df_out)\n method = \"fit\" if fit else \"predict\"\n self._set_info(method, info)\n return {\"df_out\": df_out}\n\n def _handle_nans(\n self, idx: pd.DataFrame.index, non_nan_idx: pd.DataFrame.index\n ) -> None:\n if self._nan_mode == \"raise\":\n if idx.shape[0] != non_nan_idx.shape[0]:\n nan_idx = idx.difference(non_nan_idx)\n raise ValueError(f\"NaNs detected at {nan_idx}\")\n elif self._nan_mode == \"drop\":\n pass\n elif self._nan_mode == \"leave_unchanged\":\n pass\n else:\n raise ValueError(f\"Unrecognized nan_mode `{self._nan_mode}`\")\n\n def _learn_tau(self, x: np.array, y: np.array) -> float:\n def score(tau: float) -> float:\n x_srs = pd.DataFrame(x.flatten())\n sma = csigna.compute_smooth_moving_average(\n x_srs,\n tau=tau,\n min_periods=0,\n min_depth=self._min_depth,\n max_depth=self._max_depth,\n )\n min_periods = self._get_min_periods(tau)\n return self._metric(sma[min_periods:], y[min_periods:])\n\n tau_lb, tau_ub = 1, 1000\n # Satisfy 2 * tau_ub * min_tau_periods = len(x).\n # This ensures that no more than half of the `fit` series is burned.\n if self._min_tau_periods > 0:\n tau_ub = int(len(x) / (2 * self._min_tau_periods))\n opt_results = sp.optimize.minimize_scalar(\n score, method=\"bounded\", bounds=[tau_lb, tau_ub]\n )\n return opt_results.x\n\n def _get_min_periods(self, tau: float) -> int:\n \"\"\"\n Return burn-in period.\n\n Multiplies `tau` by `min_tau_periods` and converts to an integer.\n\n :param tau: kernel tau (approximately equal to center of mass)\n :return: minimum number of periods required to generate a prediction\n \"\"\"\n return int(np.rint(self._min_tau_periods * tau))\n\n def _predict(self, x: np.array) -> np.array:\n x_srs = pd.DataFrame(x.flatten())\n # TODO(*): Make `min_periods` configurable.\n min_periods = int(np.rint(self._min_tau_periods * self._tau))\n _LOG.debug(\"min_periods=%f\", min_periods)\n x_sma = csigna.compute_smooth_moving_average(\n x_srs,\n tau=self._tau,\n min_periods=min_periods,\n min_depth=self._min_depth,\n max_depth=self._max_depth,\n )\n return x_sma.values\n\n\nclass SingleColumnVolatilityModel(FitPredictNode):\n def __init__(\n self,\n nid: str,\n steps_ahead: int,\n col: _COL_TYPE,\n p_moment: float = 2,\n progress_bar: bool = False,\n tau: Optional[float] = None,\n nan_mode: Optional[str] = None,\n out_col_prefix: Optional[str] = None,\n ) -> None:\n \"\"\"\n Parameters have the same meaning as `SmaModel`.\n \"\"\"\n super().__init__(nid)\n self._col = col\n self._steps_ahead = steps_ahead\n dbg.dassert_lte(1, p_moment)\n self._p_moment = p_moment\n self._progress_bar = progress_bar\n self._tau = tau\n self._learn_tau_on_fit = tau is None\n self._nan_mode = nan_mode\n self._out_col_prefix = out_col_prefix\n\n def get_fit_state(self) -> Dict[str, Any]:\n fit_state = {\n \"_col\": self._col,\n \"_tau\": self._tau,\n \"_info['fit']\": self._info[\"fit\"],\n \"_out_col_prefix\": self._out_col_prefix,\n }\n return fit_state\n\n def set_fit_state(self, fit_state: Dict[str, Any]):\n self._col = fit_state[\"_col\"]\n self._tau = fit_state[\"_tau\"]\n self._info[\"fit\"] = fit_state[\"_info['fit']\"]\n self._out_col_prefix = fit_state[\"_out_col_prefix\"]\n\n def fit(self, df_in: pd.DataFrame) -> Dict[str, pd.DataFrame]:\n return {\"df_out\": self._fit_predict_helper(df_in, fit=True)}\n\n def predict(self, df_in: pd.DataFrame) -> Dict[str, pd.DataFrame]:\n return {\"df_out\": self._fit_predict_helper(df_in, fit=False)}\n\n def _fit_predict_helper(self, df_in: pd.DataFrame, fit: bool) -> pd.DataFrame:\n info = collections.OrderedDict()\n name = self._out_col_prefix or self._col\n name = str(name)\n dbg.dassert_not_in(name + \"_vol\", df_in.columns)\n if self._learn_tau_on_fit and fit:\n tau = None\n else:\n tau = self._tau\n config = self._get_config(col=self._col, out_col_prefix=name, tau=tau)\n dag = self._get_dag(df_in[[self._col]], config)\n mode = \"fit\" if fit else \"predict\"\n df_out = dag.run_leq_node(\n \"demodulate_using_vol_pred\", mode, progress_bar=self._progress_bar\n )[\"df_out\"]\n info[self._col] = extract_info(dag, [mode])\n if self._learn_tau_on_fit and fit:\n self._tau = info[self._col][\"compute_smooth_moving_average\"][\"fit\"][\n \"tau\"\n ]\n df_out = df_out.reindex(df_in.index)\n self._set_info(mode, info)\n return df_out\n\n def _get_config(\n self,\n col: _COL_TYPE,\n out_col_prefix: _COL_TYPE,\n tau: Optional[float] = None,\n ) -> cconfig.Config:\n \"\"\"\n Generate a DAG config.\n\n :param col: column whose volatility is to be modeled\n :param tau: tau for SMA; if `None`, then to be learned\n :return: a complete config to be used with `_get_dag()`\n \"\"\"\n config = cconfig.get_config_from_nested_dict(\n {\n \"calculate_vol_pth_power\": {\n \"cols\": [col],\n \"col_rename_func\": lambda x: out_col_prefix + \"_vol\",\n \"col_mode\": \"merge_all\",\n },\n \"compute_smooth_moving_average\": {\n \"col\": [out_col_prefix + \"_vol\"],\n \"steps_ahead\": self._steps_ahead,\n \"tau\": tau,\n \"col_mode\": \"merge_all\",\n \"nan_mode\": self._nan_mode,\n },\n \"calculate_vol_pth_root\": {\n \"cols\": [\n out_col_prefix + \"_vol\",\n out_col_prefix + \"_vol_\" + str(self._steps_ahead),\n out_col_prefix\n + \"_vol_\"\n + str(self._steps_ahead)\n + \"_hat\",\n ],\n \"col_mode\": \"replace_selected\",\n },\n \"demodulate_using_vol_pred\": {\n \"signal_cols\": [col],\n \"volatility_col\": out_col_prefix\n + \"_vol_\"\n + str(self._steps_ahead)\n + \"_hat\",\n \"signal_steps_ahead\": 0,\n \"volatility_steps_ahead\": self._steps_ahead,\n \"col_rename_func\": lambda x: out_col_prefix + \"_vol_adj\",\n \"col_mode\": \"replace_selected\",\n \"nan_mode\": self._nan_mode,\n },\n }\n )\n return config\n\n def _get_dag(self, df_in: pd.DataFrame, config: cconfig.Config) -> DAG:\n \"\"\"\n Build a DAG from data and config.\n\n :param df_in: data over which to run DAG\n :param config: config for configuring DAG nodes\n :return: ready-to-run DAG\n \"\"\"\n dag = DAG(mode=\"strict\")\n _LOG.debug(\"%s\", config)\n # Load `df_in`.\n nid = \"load_data\"\n node = ReadDataFromDf(nid, df_in)\n tail_nid = self._append(dag, None, node)\n # Raise volatility columns to pth power.\n nid = \"calculate_vol_pth_power\"\n node = ColumnTransformer(\n nid,\n transformer_func=lambda x: np.abs(x) ** self._p_moment,\n **config[nid].to_dict(),\n )\n tail_nid = self._append(dag, tail_nid, node)\n # Predict pth power of volatility using smooth moving average.\n nid = \"compute_smooth_moving_average\"\n node = SmaModel(nid, **config[nid].to_dict())\n tail_nid = self._append(dag, tail_nid, node)\n # Calculate the pth root of volatility columns.\n nid = \"calculate_vol_pth_root\"\n node = ColumnTransformer(\n nid,\n transformer_func=lambda x: np.abs(x) ** (1.0 / self._p_moment),\n **config[nid].to_dict(),\n )\n tail_nid = self._append(dag, tail_nid, node)\n # Divide returns by volatilty prediction.\n nid = \"demodulate_using_vol_pred\"\n node = VolatilityModulator(\n nid, mode=\"demodulate\", **config[nid].to_dict()\n )\n self._append(dag, tail_nid, node)\n return dag\n\n # TODO(gp): This code has several copies. Move it to the base class.\n @staticmethod\n def _append(dag: DAG, tail_nid: Optional[str], node: Node) -> str:\n dag.add_node(node)\n if tail_nid is not None:\n dag.connect(tail_nid, node.nid)\n return node.nid\n\n\nclass _MultiColVolatilityModelMixin:\n def _fit_predict_volatility_model(\n self, df: pd.DataFrame, fit: bool, out_col_prefix: Optional[str] = None\n ) -> Tuple[Dict[str, pd.DataFrame], collections.OrderedDict]:\n dfs = {}\n info = collections.OrderedDict()\n for col in df.columns:\n local_out_col_prefix = out_col_prefix or col\n scvm = SingleColumnVolatilityModel(\n \"volatility\",\n steps_ahead=self._steps_ahead,\n col=col,\n p_moment=self._p_moment,\n progress_bar=self._progress_bar,\n tau=self._tau,\n nan_mode=self._nan_mode,\n out_col_prefix=local_out_col_prefix,\n )\n if fit:\n df_out = scvm.fit(df[[col]])[\"df_out\"]\n info_out = scvm.get_info(\"fit\")\n self._col_fit_state[col] = scvm.get_fit_state()\n else:\n scvm.set_fit_state(self._col_fit_state[col])\n df_out = scvm.predict(df[[col]])[\"df_out\"]\n info_out = scvm.get_info(\"predict\")\n dfs[col] = df_out\n info[col] = info_out\n return dfs, info\n\n\nclass VolatilityModel(\n FitPredictNode,\n ColModeMixin,\n _MultiColVolatilityModelMixin,\n):\n \"\"\"\n Fit and predict a smooth moving average volatility model.\n\n Wraps `SmaModel` internally, handling calculation of volatility from\n returns and column appends.\n \"\"\"\n\n def __init__(\n self,\n nid: str,\n steps_ahead: int,\n cols: Optional[_TO_LIST_MIXIN_TYPE] = None,\n p_moment: float = 2,\n progress_bar: bool = False,\n tau: Optional[float] = None,\n col_rename_func: Callable[[Any], Any] = lambda x: f\"{x}_zscored\",\n col_mode: Optional[str] = None,\n nan_mode: Optional[str] = None,\n ) -> None:\n \"\"\"\n Specify the data and smooth moving average (SMA) modeling parameters.\n\n :param nid: unique node id\n :param cols: name of columns to model\n :param steps_ahead: as in ContinuousSkLearnModel\n :param p_moment: exponent to apply to the absolute value of returns\n :param tau: as in `csigna.compute_smooth_moving_average`. If `None`,\n learn this parameter\n :param col_rename_func: renaming function for z-scored column\n :param col_mode:\n - If \"merge_all\" (default), merge all columns from input dataframe and\n transformed columns\n - If \"replace_selected\", merge unselected columns from input dataframe\n and transformed selected columns\n - If \"replace_all\", leave only transformed selected columns\n :param nan_mode: as in ContinuousSkLearnModel\n \"\"\"\n super().__init__(nid)\n self._cols = cols\n self._steps_ahead = steps_ahead\n #\n dbg.dassert_lte(1, p_moment)\n self._p_moment = p_moment\n #\n self._progress_bar = progress_bar\n #\n dbg.dassert(tau is None or tau > 0)\n self._tau = tau\n self._col_rename_func = col_rename_func\n self._col_mode = col_mode or \"merge_all\"\n self._nan_mode = nan_mode\n # State of the model to serialize/deserialize.\n self._fit_cols: List[_COL_TYPE] = []\n self._col_fit_state = {}\n\n def fit(self, df_in: pd.DataFrame) -> Dict[str, pd.DataFrame]:\n return self._fit_predict_helper(df_in, fit=True)\n\n def predict(self, df_in: pd.DataFrame) -> Dict[str, pd.DataFrame]:\n return self._fit_predict_helper(df_in, fit=False)\n\n def get_fit_state(self) -> Dict[str, Any]:\n fit_state = {\n \"_fit_cols\": self._fit_cols,\n \"_col_fit_state\": self._col_fit_state,\n \"_info['fit']\": self._info[\"fit\"],\n }\n return fit_state\n\n def set_fit_state(self, fit_state: Dict[str, Any]):\n self._fit_cols = fit_state[\"_fit_cols\"]\n self._col_fit_state = fit_state[\"_col_fit_state\"]\n self._info[\"fit\"] = fit_state[\"_info['fit']\"]\n\n def _fit_predict_helper(self, df_in: pd.DataFrame, fit: bool):\n cdu.validate_df_indices(df_in)\n # Get the columns.\n self._fit_cols = cdu.convert_to_list(self._cols or df_in.columns.tolist())\n df = df_in[self._fit_cols]\n dfs, info = self._fit_predict_volatility_model(df, fit=fit)\n df_out = pd.concat(dfs.values(), axis=1)\n df_out = self._apply_col_mode(\n df_in.drop(df_out.columns.intersection(df_in.columns), 1),\n df_out,\n cols=self._fit_cols,\n col_mode=self._col_mode,\n )\n method = \"fit\" if fit else \"predict\"\n self._set_info(method, info)\n return {\"df_out\": df_out}\n\n\nclass MultiindexVolatilityModel(FitPredictNode, _MultiColVolatilityModelMixin):\n \"\"\"\n Fit and predict a smooth moving average volatility model.\n\n Wraps SmaModel internally, handling calculation of volatility from\n returns and column appends.\n \"\"\"\n\n def __init__(\n self,\n nid: str,\n in_col_group: Tuple[_COL_TYPE],\n steps_ahead: int,\n p_moment: float = 2,\n progress_bar: bool = False,\n tau: Optional[float] = None,\n nan_mode: Optional[str] = None,\n ) -> None:\n \"\"\"\n Specify the data and sma modeling parameters.\n\n :param nid: unique node id\n :param steps_ahead: as in ContinuousSkLearnModel\n :param p_moment: exponent to apply to the absolute value of returns\n :param tau: as in `csigna.compute_smooth_moving_average`. If `None`,\n learn this parameter\n :param nan_mode: as in ContinuousSkLearnModel\n \"\"\"\n super().__init__(nid)\n dbg.dassert_isinstance(in_col_group, tuple)\n self._in_col_group = in_col_group\n self._out_col_group = in_col_group[:-1]\n self._out_col_prefix = str(in_col_group[-1])\n #\n self._steps_ahead = steps_ahead\n dbg.dassert_lte(1, p_moment)\n self._p_moment = p_moment\n #\n self._progress_bar = progress_bar\n #\n self._tau = tau\n self._nan_mode = nan_mode\n #\n self._col_fit_state = {}\n\n def fit(self, df_in: pd.DataFrame) -> Dict[str, pd.DataFrame]:\n return self._fit_predict_helper(df_in, fit=True)\n\n def predict(self, df_in: pd.DataFrame) -> Dict[str, pd.DataFrame]:\n return self._fit_predict_helper(df_in, fit=False)\n\n def get_fit_state(self) -> Dict[str, Any]:\n fit_state = {\n \"_col_fit_state\": self._col_fit_state,\n \"_info['fit']\": self._info[\"fit\"],\n }\n return fit_state\n\n def set_fit_state(self, fit_state: Dict[str, Any]):\n self._col_fit_state = fit_state[\"_col_fit_state\"]\n self._info[\"fit\"] = fit_state[\"_info['fit']\"]\n\n def _fit_predict_helper(self, df_in: pd.DataFrame, fit: bool):\n cdu.validate_df_indices(df_in)\n df = SeriesToDfColProcessor.preprocess(df_in, self._in_col_group)\n dfs, info = self._fit_predict_volatility_model(\n df, fit=fit, out_col_prefix=self._out_col_prefix\n )\n df_out = SeriesToDfColProcessor.postprocess(dfs, self._out_col_group)\n df_out = cdu.merge_dataframes(df_in, df_out)\n method = \"fit\" if fit else \"predict\"\n self._set_info(method, info)\n return {\"df_out\": df_out}\n\n\nclass VolatilityModulator(FitPredictNode, ColModeMixin):\n \"\"\"\n Modulate or demodulate signal by volatility.\n\n Processing steps:\n - shift volatility to align it with signal\n - multiply/divide signal by volatility\n\n Usage examples:\n - Z-scoring\n - to obtain volatility prediction, pass in returns into `SmaModel` with\n a `steps_ahead` parameter\n - to z-score, pass in signal, volatility prediction, `signal_steps_ahead=0`,\n `volatility_steps_ahead=steps_ahead`, `mode='demodulate'`\n - Undoing z-scoring\n - Let's say we have\n - forward volatility prediction `n` steps ahead\n - prediction of forward z-scored returns `m` steps ahead. Z-scoring\n for the target has been done using the volatility prediction above\n - To undo z-scoring, we need to pass in the prediction of forward\n z-scored returns, forward volatility prediction, `signal_steps_ahead=n`,\n `volatility_steps_ahead=m`, `mode='modulate'`\n \"\"\"\n\n def __init__(\n self,\n nid: str,\n signal_cols: _TO_LIST_MIXIN_TYPE,\n volatility_col: _COL_TYPE,\n signal_steps_ahead: int,\n volatility_steps_ahead: int,\n mode: str,\n col_rename_func: Optional[Callable[[Any], Any]] = None,\n col_mode: Optional[str] = None,\n nan_mode: Optional[str] = None,\n ) -> None:\n \"\"\"\n :param nid: node identifier\n :param signal_cols: names of columns to (de)modulate\n :param volatility_col: name of volatility column\n :param signal_steps_ahead: steps ahead of the signal columns. If signal\n is at `t_0`, this value should be `0`. If signal is a forward\n prediction of z-scored returns indexed by knowledge time, this\n value should be equal to the number of steps of the prediction\n :param volatility_steps_ahead: steps ahead of the volatility column. If\n volatility column is an output of `SmaModel`, this corresponds to\n the `steps_ahead` parameter\n :param mode: \"modulate\" or \"demodulate\"\n :param col_rename_func: as in `ColumnTransformer`\n :param col_mode: as in `ColumnTransformer`\n \"\"\"\n super().__init__(nid)\n self._signal_cols = cdu.convert_to_list(signal_cols)\n self._volatility_col = volatility_col\n dbg.dassert_lte(0, signal_steps_ahead)\n self._signal_steps_ahead = signal_steps_ahead\n dbg.dassert_lte(0, volatility_steps_ahead)\n self._volatility_steps_ahead = volatility_steps_ahead\n dbg.dassert_in(mode, [\"modulate\", \"demodulate\"])\n self._mode = mode\n self._col_rename_func = col_rename_func or (lambda x: x)\n self._col_mode = col_mode or \"replace_all\"\n self._nan_mode = nan_mode or \"leave_unchanged\"\n\n def fit(self, df_in: pd.DataFrame) -> Dict[str, pd.DataFrame]:\n df_out = self._process_signal(df_in)\n info = collections.OrderedDict()\n info[\"df_out_info\"] = cdu.get_df_info_as_string(df_out)\n self._set_info(\"fit\", info)\n return {\"df_out\": df_out}\n\n def predict(self, df_in: pd.DataFrame) -> Dict[str, pd.DataFrame]:\n df_out = self._process_signal(df_in)\n info = collections.OrderedDict()\n info[\"df_out_info\"] = cdu.get_df_info_as_string(df_out)\n self._set_info(\"predict\", info)\n return {\"df_out\": df_out}\n\n def _process_signal(self, df_in: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Modulate or demodulate signal by volatility prediction.\n\n :param df_in: dataframe with `self._signal_cols` and\n `self._volatility_col` columns\n :return: adjusted signal indexed in the same way as the input signal\n \"\"\"\n dbg.dassert_is_subset(self._signal_cols, df_in.columns.tolist())\n dbg.dassert_in(self._volatility_col, df_in.columns)\n fwd_signal = df_in[self._signal_cols]\n fwd_volatility = df_in[self._volatility_col]\n # Shift volatility to align it with signal.\n volatility_shift = self._volatility_steps_ahead - self._signal_steps_ahead\n if self._nan_mode == \"drop\":\n fwd_volatility = fwd_volatility.dropna()\n elif self._nan_mode == \"leave_unchanged\":\n pass\n else:\n raise ValueError(f\"Unrecognized `nan_mode` {self._nan_mode}\")\n volatility_aligned = fwd_volatility.shift(volatility_shift)\n # Adjust signal by volatility.\n if self._mode == \"demodulate\":\n adjusted_signal = fwd_signal.divide(volatility_aligned, axis=0)\n elif self._mode == \"modulate\":\n adjusted_signal = fwd_signal.multiply(volatility_aligned, axis=0)\n else:\n raise ValueError(f\"Invalid mode=`{self._mode}`\")\n df_out = self._apply_col_mode(\n df_in,\n adjusted_signal,\n cols=self._signal_cols,\n col_rename_func=self._col_rename_func,\n col_mode=self._col_mode,\n )\n return df_out\n\n\nclass VolatilityNormalizer(FitPredictNode, ColModeMixin):\n def __init__(\n self,\n nid: str,\n col: str,\n target_volatility: float,\n col_mode: Optional[str] = None,\n ) -> None:\n \"\"\"\n Normalize series to target annual volatility.\n\n :param nid: node identifier\n :param col: name of column to rescale\n :param target_volatility: target volatility as a proportion\n :param col_mode: `merge_all` or `replace_all`. If `replace_all`, return\n only the rescaled column, if `merge_all`, append the rescaled\n column to input dataframe\n \"\"\"\n super().__init__(nid)\n self._col = col\n self._target_volatility = target_volatility\n self._col_mode = col_mode or \"merge_all\"\n dbg.dassert_in(\n self._col_mode,\n [\"merge_all\", \"replace_all\"],\n \"Invalid `col_mode`='%s'\",\n self._col_mode,\n )\n self._scale_factor: Optional[float] = None\n\n def fit(self, df_in: pd.DataFrame) -> Dict[str, pd.DataFrame]:\n dbg.dassert_in(self._col, df_in.columns)\n self._scale_factor = cfinan.compute_volatility_normalization_factor(\n df_in[self._col], self._target_volatility\n )\n rescaled_y_hat = self._scale_factor * df_in[self._col]\n df_out = self._apply_col_mode(\n df_in,\n rescaled_y_hat.to_frame(),\n cols=[self._col],\n col_rename_func=lambda x: f\"rescaled_{x}\",\n col_mode=self._col_mode,\n )\n # Store info.\n info = collections.OrderedDict()\n info[\"scale_factor\"] = self._scale_factor\n self._set_info(\"fit\", info)\n return {\"df_out\": df_out}\n\n def predict(self, df_in: pd.DataFrame) -> Dict[str, pd.DataFrame]:\n dbg.dassert_in(self._col, df_in.columns)\n rescaled_y_hat = self._scale_factor * df_in[self._col]\n df_out = self._apply_col_mode(\n df_in,\n rescaled_y_hat.to_frame(),\n cols=[self._col],\n col_rename_func=lambda x: f\"rescaled_{x}\",\n col_mode=self._col_mode,\n )\n return {\"df_out\": df_out}\n",
"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.2'\n# jupytext_version: 1.2.4\n# kernelspec:\n# display_name: Python [conda env:.conda-develop] *\n# language: python\n# name: conda-env-.conda-develop-py\n# ---\n\n# %% [markdown]\n# ## Imports\n\n# %%\n# %load_ext autoreload\n# %autoreload 2\nimport logging\n\nimport numpy as np\nimport pandas as pd\n\nimport core.timeseries_study as tss\nimport helpers.dbg as dbg\nimport helpers.env as env\nimport helpers.printing as pri\n\n# %%\nprint(env.get_system_signature())\npri.config_notebook()\ndbg.init_logger(verbosity=logging.INFO)\n_LOG = logging.getLogger(__name__)\n\n# %% [markdown]\n# # Generate time series\n\n# %% [markdown]\n# ## Daily\n\n# %%\nidx = pd.date_range(\"2018-12-31\", \"2019-01-31\")\nvals = np.random.randn(len(idx))\nts_daily = pd.Series(vals, index=idx)\nts_daily.name = \"ts\"\nts_daily.head()\n\n# %%\nts_daily.plot()\n\n# %% [markdown]\n# ## Minutely\n\n# %%\nidx = pd.date_range(\"2018-12-31\", \"2019-01-31\", freq=\"5T\")\nvals = np.random.randn(len(idx))\nts_minutely = pd.Series(vals, index=idx)\nts_minutely.name = \"ts\"\nts_minutely.head()\n\n# %%\nts_minutely.plot()\n\n# %% [markdown]\n# # Examples\n\n# %% [markdown]\n# ## Daily\n\n# %%\ntsds = tss.TimeSeriesDailyStudy(ts_daily)\ntsds.execute()\n\n# %% [markdown]\n# ## Minutely\n\n# %%\ntsms = tss.TimeSeriesMinutelyStudy(ts_minutely)\ntsms.execute()\n\n# %%\n",
"#!/usr/bin/env python\n\nimport argparse\nimport logging\n\nimport pandas as pd\n\nimport helpers.dbg as dbg\nimport helpers.parser as hparse\nimport im.ib.data.extract.gateway.utils as iidegu\n\n# from tqdm.notebook import tqdm\n\n_LOG = logging.getLogger(__name__)\n\n\ndef on_bar_update(bars, has_new_bar):\n print(has_new_bar)\n print(bars)\n\n\ndef _main(parser: argparse.ArgumentParser) -> None:\n args = parser.parse_args()\n dbg.init_logger(verbosity=args.log_level, use_exec_path=True)\n dbg.shutup_chatty_modules()\n #\n if False:\n target = \"forex\"\n frequency = \"intraday\"\n symbols = [\"EURUSD\"]\n elif False:\n target = \"futures\"\n frequency = \"intraday\"\n symbols = [\"ES\"]\n elif True:\n target = \"continuous_futures\"\n frequency = \"intraday\"\n symbols = [\"ES\"]\n currency = \"USD\"\n symbols = \"ES CL NG\".split()\n try:\n ib = iidegu.ib_connect(0, is_notebook=False)\n bars = ib.reqRealTimeBars(contract, 5, \"MIDPOINT\", False)\n bars.updateEvent += onBarUpdate\n finally:\n ib.disconnect()\n use_rth = False\n start_ts = None\n # start_ts = pd.Timestamp(\"2020-12-13 18:00:00-05:00\")\n end_ts = None\n # end_ts = pd.Timestamp(\"2020-12-23 18:00:00-05:00\")\n tasks = iidegu.get_tasks(\n ib=ib,\n target=target,\n frequency=frequency,\n currency=currency,\n symbols=symbols,\n start_ts=start_ts,\n end_ts=end_ts,\n use_rth=use_rth,\n )\n num_threads = 3\n num_threads = \"serial\"\n dst_dir = args.dst_dir\n incremental = not args.not_incremental\n client_id_base = 5\n file_names = iidegu.download_ib_data(\n client_id_base, tasks, incremental, dst_dir, num_threads\n )\n _LOG.info(\"file_names=%s\", file_names)\n\n\ndef _parse() -> argparse.ArgumentParser:\n parser = argparse.ArgumentParser(\n description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter\n )\n parser.add_argument(\"positional\", nargs=\"*\", help=\"...\")\n parser.add_argument(\n \"--dst_dir\",\n action=\"store\",\n default=\"./tmp.download_data\",\n help=\"Destination dir\",\n )\n parser.add_argument(\"--not_incremental\", action=\"store_true\", default=False)\n hparse.add_verbosity_arg(parser)\n return parser\n\n\nif __name__ == \"__main__\":\n user_start_ts = pd.Timestamp(\"2018-02-01\")\n user_end_ts = pd.Timestamp(\"2019-06-01\")\n _main(_parse())\n"
] | [
[
"pandas.read_parquet"
],
[
"matplotlib.pyplot.show",
"pandas.DataFrame"
],
[
"pandas.merge",
"pandas.to_datetime",
"pandas.ewmstd",
"numpy.cumsum",
"pandas.DataFrame",
"matplotlib.pyplot.plot",
"numpy.all",
"numpy.isneginf",
"numpy.mean",
"numpy.argmin",
"numpy.where",
"pandas.rolling_corr",
"numpy.random.randint",
"pandas.ewma",
"pandas.Panel",
"scipy.stats.stats.pearsonr",
"matplotlib.pyplot.gcf",
"numpy.std",
"numpy.argmax",
"numpy.ravel",
"matplotlib.pyplot.figure",
"pandas.concat",
"matplotlib.pyplot.title",
"numpy.isnan",
"scipy.stats.linregress",
"matplotlib.rcParams.update",
"numpy.random.rand",
"numpy.array",
"numpy.sum",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.axhline",
"numpy.random.seed",
"numpy.isfinite",
"numpy.isposinf",
"matplotlib.pyplot.subplots",
"numpy.random.shuffle",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xlabel"
],
[
"numpy.rint",
"scipy.optimize.minimize_scalar",
"numpy.abs"
],
[
"pandas.Series",
"pandas.date_range"
],
[
"pandas.Timestamp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"0.24",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.21",
"0.20",
"0.19"
],
"scipy": [
"0.13",
"1.6",
"0.14",
"0.15",
"1.4",
"1.3",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sokazaki/mmediting | [
"e1b544ed524892edc10f273805f920ecab2f5ff3",
"e1b544ed524892edc10f273805f920ecab2f5ff3"
] | [
"mmedit/models/losses/perceptual_loss.py",
"tests/test_search_transformer.py"
] | [
"import torch\nimport torch.nn as nn\nimport torchvision.models.vgg as vgg\nfrom mmcv.runner import load_checkpoint\n\nfrom mmedit.utils import get_root_logger\nfrom ..registry import LOSSES\n\n\nclass PerceptualVGG(nn.Module):\n \"\"\"VGG network used in calculating perceptual loss.\n\n In this implementation, we allow users to choose whether use normalization\n in the input feature and the type of vgg network. Note that the pretrained\n path must fit the vgg type.\n\n Args:\n layer_name_list (list[str]): According to the name in this list,\n forward function will return the corresponding features. This\n list contains the name each layer in `vgg.feature`. An example\n of this list is ['4', '10'].\n vgg_type (str): Set the type of vgg network. Default: 'vgg19'.\n use_input_norm (bool): If True, normalize the input image.\n Importantly, the input feature must in the range [0, 1].\n Default: True.\n pretrained (str): Path for pretrained weights. Default:\n 'torchvision://vgg19'\n \"\"\"\n\n def __init__(self,\n layer_name_list,\n vgg_type='vgg19',\n use_input_norm=True,\n pretrained='torchvision://vgg19'):\n super().__init__()\n if pretrained.startswith('torchvision://'):\n assert vgg_type in pretrained\n self.layer_name_list = layer_name_list\n self.use_input_norm = use_input_norm\n\n # get vgg model and load pretrained vgg weight\n # remove _vgg from attributes to avoid `find_unused_parameters` bug\n _vgg = getattr(vgg, vgg_type)()\n self.init_weights(_vgg, pretrained)\n num_layers = max(map(int, layer_name_list)) + 1\n assert len(_vgg.features) >= num_layers\n # only borrow layers that will be used from _vgg to avoid unused params\n self.vgg_layers = _vgg.features[:num_layers]\n\n if self.use_input_norm:\n # the mean is for image with range [0, 1]\n self.register_buffer(\n 'mean',\n torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))\n # the std is for image with range [-1, 1]\n self.register_buffer(\n 'std',\n torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))\n\n for v in self.vgg_layers.parameters():\n v.requires_grad = False\n\n def forward(self, x):\n \"\"\"Forward function.\n\n Args:\n x (Tensor): Input tensor with shape (n, c, h, w).\n\n Returns:\n Tensor: Forward results.\n \"\"\"\n\n if self.use_input_norm:\n x = (x - self.mean) / self.std\n output = {}\n\n for name, module in self.vgg_layers.named_children():\n x = module(x)\n if name in self.layer_name_list:\n output[name] = x.clone()\n return output\n\n def init_weights(self, model, pretrained):\n \"\"\"Init weights.\n\n Args:\n model (nn.Module): Models to be inited.\n pretrained (str): Path for pretrained weights.\n \"\"\"\n logger = get_root_logger()\n load_checkpoint(model, pretrained, logger=logger)\n\n\[email protected]_module()\nclass PerceptualLoss(nn.Module):\n \"\"\"Perceptual loss with commonly used style loss.\n\n Args:\n layers_weights (dict): The weight for each layer of vgg feature.\n Here is an example: {'4': 1., '9': 1., '18': 1.}, which means the\n 5th, 10th and 18th feature layer will be extracted with weight 1.0\n in calculting losses.\n vgg_type (str): The type of vgg network used as feature extractor.\n Default: 'vgg19'.\n use_input_norm (bool): If True, normalize the input image in vgg.\n Default: True.\n perceptual_weight (float): If `perceptual_weight > 0`, the perceptual\n loss will be calculated and the loss will multiplied by the\n weight. Default: 1.0.\n style_weight (float): If `style_weight > 0`, the style loss will be\n calculated and the loss will multiplied by the weight.\n Default: 1.0.\n norm_img (bool): If True, the image will be normed to [0, 1]. Note that\n this is different from the `use_input_norm` which norm the input in\n in forward function of vgg according to the statistics of dataset.\n Importantly, the input image must be in range [-1, 1].\n pretrained (str): Path for pretrained weights. Default:\n 'torchvision://vgg19'\n \"\"\"\n\n def __init__(self,\n layer_weights,\n vgg_type='vgg19',\n use_input_norm=True,\n perceptual_weight=1.0,\n style_weight=1.0,\n norm_img=True,\n pretrained='torchvision://vgg19',\n criterion='l1'):\n super().__init__()\n self.norm_img = norm_img\n self.perceptual_weight = perceptual_weight\n self.style_weight = style_weight\n self.layer_weights = layer_weights\n self.vgg = PerceptualVGG(\n layer_name_list=list(layer_weights.keys()),\n vgg_type=vgg_type,\n use_input_norm=use_input_norm,\n pretrained=pretrained)\n\n if criterion == 'l1':\n self.criterion = torch.nn.L1Loss()\n elif criterion == 'mse':\n self.criterion = torch.nn.MSELoss()\n else:\n raise NotImplementedError(\n f'{criterion} criterion has not been supported in'\n ' this version.')\n\n def forward(self, x, gt):\n \"\"\"Forward function.\n\n Args:\n x (Tensor): Input tensor with shape (n, c, h, w).\n gt (Tensor): Ground-truth tensor with shape (n, c, h, w).\n\n Returns:\n Tensor: Forward results.\n \"\"\"\n\n if self.norm_img:\n x = (x + 1.) * 0.5\n gt = (gt + 1.) * 0.5\n # extract vgg features\n x_features = self.vgg(x)\n gt_features = self.vgg(gt.detach())\n\n # calculate perceptual loss\n if self.perceptual_weight > 0:\n percep_loss = 0\n for k in x_features.keys():\n percep_loss += self.criterion(\n x_features[k], gt_features[k]) * self.layer_weights[k]\n percep_loss *= self.perceptual_weight\n else:\n percep_loss = None\n\n # calculate style loss\n if self.style_weight > 0:\n style_loss = 0\n for k in x_features.keys():\n style_loss += self.criterion(\n self._gram_mat(x_features[k]),\n self._gram_mat(gt_features[k])) * self.layer_weights[k]\n style_loss *= self.style_weight\n else:\n style_loss = None\n\n return percep_loss, style_loss\n\n def _gram_mat(self, x):\n \"\"\"Calculate Gram matrix.\n\n Args:\n x (torch.Tensor): Tensor with shape of (n, c, h, w).\n\n Returns:\n torch.Tensor: Gram matrix.\n \"\"\"\n (n, c, h, w) = x.size()\n features = x.view(n, c, w * h)\n features_t = features.transpose(1, 2)\n gram = features.bmm(features_t) / (c * h * w)\n return gram\n",
"import torch\n\nfrom mmedit.models import build_component\n\n\ndef test_search_transformer():\n model_cfg = dict(type='SearchTransformer')\n model = build_component(model_cfg)\n\n lr_pad_level3 = torch.randn((2, 32, 32, 32))\n ref_pad_level3 = torch.randn((2, 32, 32, 32))\n ref_level3 = torch.randn((2, 32, 32, 32))\n ref_level2 = torch.randn((2, 16, 64, 64))\n ref_level1 = torch.randn((2, 8, 128, 128))\n\n s, t_level3, t_level2, t_level1 = model(lr_pad_level3, ref_pad_level3,\n ref_level1, ref_level2, ref_level3)\n\n assert s.shape == (2, 1, 32, 32)\n assert t_level3.shape == (2, 32, 32, 32)\n assert t_level2.shape == (2, 16, 64, 64)\n assert t_level1.shape == (2, 8, 128, 128)\n"
] | [
[
"torch.nn.MSELoss",
"torch.nn.L1Loss",
"torch.Tensor"
],
[
"torch.randn"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Rohan-Chaudhury/aimet | [
"1c38cac8cc0fd32dca40ce5e39940805d29f7a4a",
"1c38cac8cc0fd32dca40ce5e39940805d29f7a4a",
"1c38cac8cc0fd32dca40ce5e39940805d29f7a4a",
"1c38cac8cc0fd32dca40ce5e39940805d29f7a4a"
] | [
"TrainingExtensions/tensorflow/test/python/test_spatial_svd.py",
"TrainingExtensions/torch/test/python/test_elementwise_ops.py",
"NightlyTests/torch/test_cross_layer_equalization.py",
"TrainingExtensions/torch/test/python/test_quantizer_GPU.py"
] | [
"# /usr/bin/env python3.5\n# -*- mode: python -*-\n# =============================================================================\n# @@-COPYRIGHT-START-@@\n#\n# Copyright (c) 2019, Qualcomm Innovation Center, Inc. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# @@-COPYRIGHT-END-@@\n# =============================================================================\n\nimport pytest\nimport unittest\nimport copy\nimport shutil\nfrom decimal import Decimal\nimport numpy as np\n\nimport os\nimport tensorflow as tf\ntf.compat.v1.logging.set_verbosity(tf.logging.WARN)\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n\nfrom aimet_common.utils import AimetLogger\nfrom aimet_common.defs import CostMetric, LayerCompRatioPair\n\nfrom aimet_tensorflow import layer_database as lad\nfrom aimet_tensorflow.layer_database import LayerDatabase\nfrom aimet_tensorflow.common.connectedgraph import ConnectedGraph\nfrom aimet_tensorflow.examples import mnist_tf_model\nfrom aimet_tensorflow.examples.test_models import tf_slim_basic_model\nfrom aimet_tensorflow.svd_spiltter import SpatialSvdModuleSplitter\nfrom aimet_tensorflow.svd_pruner import SpatialSvdPruner\nfrom aimet_tensorflow.utils.common import get_succeeding_bias_op\nfrom aimet_tensorflow.utils.graph_saver import save_and_load_graph\nfrom aimet_tensorflow.utils.op.conv import WeightTensorUtils, BiasUtils\nlogger = AimetLogger.get_area_logger(AimetLogger.LogAreas.Test)\n\n\nclass TestSpatialSvdLayerSplit(unittest.TestCase):\n\n def test_split_layer(self):\n \"\"\" test the output after and before the split_module call\"\"\"\n\n num_examples = 2000\n g = tf.Graph()\n\n with g.as_default():\n\n inp_tensor = tf.compat.v1.get_variable('inp_tensor', shape=[num_examples, 5, 5, 20],\n initializer=tf.random_normal_initializer())\n filter_tensor = tf.compat.v1.get_variable('filter_tensor', shape=[5, 5, 20, 50],\n initializer=tf.random_normal_initializer())\n\n conv1 = tf.nn.conv2d(input=inp_tensor, filter=filter_tensor, strides=[1, 1, 1, 1], padding='VALID',\n data_format=\"NHWC\", name='Conv2D_1')\n\n bias_tensor = tf.compat.v1.get_variable('bias_tensor', shape=[50], initializer=tf.random_normal_initializer())\n\n bias = tf.nn.bias_add(value=conv1, bias=bias_tensor, data_format=\"NHWC\")\n\n init = tf.compat.v1.global_variables_initializer()\n\n orig_conv_op = g.get_operation_by_name('Conv2D_1')\n\n # output shape in NCHW format\n shape = orig_conv_op.outputs[0].get_shape().as_list()\n self.assertEqual(shape, [num_examples, 1, 1, 50])\n\n sess = tf.compat.v1.Session(graph=g)\n\n # initialize all the variables in the graph\n sess.run(init)\n\n orig_conv_output = sess.run(orig_conv_op.outputs[0])\n\n layer1 = lad.Layer(model=sess, op=orig_conv_op, output_shape=shape)\n\n split_conv_op1, split_conv_op2 = SpatialSvdModuleSplitter.split_module(layer=layer1, rank=100)\n\n split_conv_output = sess.run(split_conv_op2.outputs[0])\n\n self.assertTrue(np.allclose(split_conv_output, orig_conv_output, atol=1e-4))\n\n # check the output after bias\n for consumer in orig_conv_op.outputs[0].consumers():\n orig_bias_out = sess.run(consumer.outputs[0])\n\n for consumer in split_conv_op2.outputs[0].consumers():\n split_bias_out = sess.run(consumer.outputs[0])\n\n self.assertTrue(np.allclose(orig_bias_out, split_bias_out, atol=1e-4))\n\n tf.compat.v1.reset_default_graph()\n sess.close()\n\n def test_split_layer_channels_last(self):\n \"\"\" test the split after and before split_module call with channel last\"\"\"\n\n num_examples = 2000\n g = tf.Graph()\n\n with g.as_default():\n\n inp_tensor = tf.compat.v1.get_variable('inp_tensor', shape=[num_examples, 5, 5, 20],\n initializer=tf.random_normal_initializer())\n filter_tensor = tf.compat.v1.get_variable('filter_tensor', shape=[5, 5, 20, 50],\n initializer=tf.random_normal_initializer())\n\n conv1 = tf.nn.conv2d(input=inp_tensor, filter=filter_tensor, strides=[1, 1, 1, 1], padding='VALID',\n data_format=\"NHWC\", name='Conv2D_1')\n\n bias_tensor = tf.compat.v1.get_variable('bias_tensor', shape=[50], initializer=tf.random_normal_initializer())\n\n bias = tf.nn.bias_add(value=conv1, bias=bias_tensor, data_format=\"NHWC\")\n\n init = tf.compat.v1.global_variables_initializer()\n\n orig_conv_op = g.get_operation_by_name('Conv2D_1')\n\n shape = orig_conv_op.outputs[0].get_shape().as_list()\n self.assertEqual(shape, [num_examples, 1, 1, 50])\n\n sess = tf.compat.v1.Session(graph=g)\n\n # initialize all the variables in the graph\n sess.run(init)\n orig_conv_output = sess.run(orig_conv_op.outputs[0])\n\n # but layer expects output shape in NCHW format similar to PyTorch\n shape = (shape[0], shape[3], shape[1], shape[2])\n layer1 = lad.Layer(model=sess, op=orig_conv_op, output_shape=shape)\n\n split_conv_op1, split_conv_op2 = SpatialSvdModuleSplitter.split_module(layer=layer1, rank=100)\n\n split_conv_output = sess.run(split_conv_op2.outputs[0])\n\n self.assertTrue(np.allclose(split_conv_output, orig_conv_output, atol=1e-4))\n\n # check the output after bias\n for consumer in orig_conv_op.outputs[0].consumers():\n orig_bias_out = sess.run(consumer.outputs[0])\n\n for consumer in split_conv_op2.outputs[0].consumers():\n split_bias_out = sess.run(consumer.outputs[0])\n\n self.assertTrue(np.allclose(orig_bias_out, split_bias_out, atol=1e-4))\n\n tf.compat.v1.reset_default_graph()\n sess.close()\n\n @pytest.mark.cuda\n def test_split_layer_with_stride(self):\n \"\"\"test the conv2d split after and before split_module call with stride option \"\"\"\n \"\"\"Conv NCHW not allowed on CPU\"\"\"\n\n num_examples = 2000\n g = tf.Graph()\n\n with g.as_default():\n\n inp_tensor = tf.compat.v1.get_variable('inp_tensor', shape=[num_examples, 20, 5 + 2, 5 + 2],\n initializer=tf.random_normal_initializer())\n\n filter_tensor = tf.compat.v1.get_variable('filter_tensor', shape=[5, 5, 20, 50],\n initializer=tf.random_normal_initializer())\n\n conv1 = tf.nn.conv2d(input=inp_tensor, filter=filter_tensor, strides=[1, 1, 2, 2], padding='VALID',\n data_format=\"NCHW\", name='Conv2D_1')\n\n bias_tensor = tf.compat.v1.get_variable('bias_tensor', shape=[50], initializer=tf.random_normal_initializer())\n\n bias = tf.nn.bias_add(value=conv1, bias=bias_tensor, data_format=\"NCHW\")\n\n init = tf.compat.v1.global_variables_initializer()\n\n orig_conv_op = g.get_operation_by_name('Conv2D_1')\n\n # output shape in NCHW format\n shape = orig_conv_op.outputs[0].get_shape().as_list()\n\n self.assertEqual(shape, [num_examples, 50, 2, 2])\n\n sess = tf.compat.v1.Session(graph=g)\n\n # initialize all the variables in the graph\n sess.run(init)\n\n orig_conv_output = sess.run(orig_conv_op.outputs[0])\n\n layer1 = lad.Layer(model=sess, op=orig_conv_op, output_shape=shape)\n\n split_conv_op1, split_conv_op2 = SpatialSvdModuleSplitter.split_module(layer=layer1, rank=100)\n\n split_conv_output = sess.run(split_conv_op2.outputs[0])\n\n self.assertTrue(np.allclose(split_conv_output, orig_conv_output, atol=1e-4))\n\n # check the output after bias\n for consumer in orig_conv_op.outputs[0].consumers():\n orig_bias_out = sess.run(consumer.outputs[0])\n\n for consumer in split_conv_op2.outputs[0].consumers():\n split_bias_out = sess.run(consumer.outputs[0])\n\n self.assertTrue(np.allclose(orig_bias_out, split_bias_out, atol=1e-4))\n\n tf.compat.v1.reset_default_graph()\n sess.close()\n\n def test_split_layer_with_stirde_channels_last(self):\n \"\"\"test the conv2d split after and before split_module call with stride option and channel last\"\"\"\n\n num_examples = 2000\n g = tf.Graph()\n\n with g.as_default():\n\n inp_tensor = tf.compat.v1.get_variable('inp_tensor', shape=[num_examples, 5 + 2, 5 + 2, 20],\n initializer=tf.random_normal_initializer())\n\n filter_tensor = tf.compat.v1.get_variable('filter_tensor', shape=[5, 5, 20, 50],\n initializer=tf.random_normal_initializer())\n\n conv1 = tf.nn.conv2d(input=inp_tensor, filter=filter_tensor, strides=[1, 2, 2, 1], padding='VALID',\n data_format=\"NHWC\", name='Conv2D_1')\n\n bias_tensor = tf.compat.v1.get_variable('bias_tensor', shape=[50], initializer=tf.random_normal_initializer())\n\n bias = tf.nn.bias_add(value=conv1, bias=bias_tensor, data_format=\"NHWC\")\n\n init = tf.compat.v1.global_variables_initializer()\n\n orig_conv_op = g.get_operation_by_name('Conv2D_1')\n\n shape = orig_conv_op.outputs[0].get_shape().as_list()\n self.assertEqual(shape, [num_examples, 2, 2, 50])\n\n sess = tf.compat.v1.Session(graph=g)\n\n # initialize all the variables in the graph\n sess.run(init)\n\n orig_conv_output = sess.run(orig_conv_op.outputs[0])\n\n # but layer expects output shape in NCHW format similar to PyTorch\n shape = (shape[0], shape[3], shape[1], shape[2])\n\n layer1 = lad.Layer(model=sess, op=orig_conv_op, output_shape=shape)\n\n split_conv_op1, split_conv_op2 = SpatialSvdModuleSplitter.split_module(layer=layer1, rank=100)\n\n split_conv_output = sess.run(split_conv_op2.outputs[0])\n\n self.assertTrue(np.allclose(split_conv_output, orig_conv_output, atol=1e-4))\n\n # check the output after bias\n for consumer in orig_conv_op.outputs[0].consumers():\n orig_bias_out = sess.run(consumer.outputs[0])\n\n for consumer in split_conv_op2.outputs[0].consumers():\n split_bias_out = sess.run(consumer.outputs[0])\n\n self.assertTrue(np.allclose(orig_bias_out, split_bias_out, atol=1e-4))\n\n tf.compat.v1.reset_default_graph()\n sess.close()\n\n def test_split_layer_rank_reduced(self):\n \"\"\" test the conv2d split after and before split_module call with reduced rank 100 --> 96\"\"\"\n\n num_examples = 2000\n g = tf.Graph()\n with g.as_default():\n\n inp_tensor = tf.compat.v1.get_variable('inp_tensor', shape=[num_examples, 5, 5, 20],\n initializer=tf.random_normal_initializer())\n\n filter_tensor = tf.compat.v1.get_variable('filter_tensor', shape=[5, 5, 20, 50],\n initializer=tf.random_normal_initializer())\n\n conv1 = tf.nn.conv2d(input=inp_tensor, filter=filter_tensor, strides=[1, 1, 1, 1], padding='VALID',\n data_format=\"NHWC\", name='Conv2D_1')\n\n bias_tensor = tf.compat.v1.get_variable('bias_tensor', shape=[50], initializer=tf.random_normal_initializer())\n\n bias = tf.nn.bias_add(value=conv1, bias=bias_tensor, data_format=\"NHWC\")\n\n init = tf.compat.v1.global_variables_initializer()\n\n orig_conv_op = g.get_operation_by_name('Conv2D_1')\n\n shape = orig_conv_op.outputs[0].get_shape().as_list()\n self.assertEqual(shape, [num_examples, 1, 1, 50])\n\n sess = tf.compat.v1.Session(graph=g)\n\n # initialize all the variables in the graph\n sess.run(init)\n\n orig_conv_output = sess.run(orig_conv_op.outputs[0])\n\n layer1 = lad.Layer(model=sess, op=orig_conv_op, output_shape=shape)\n\n split_conv_op1, split_conv_op2 = SpatialSvdModuleSplitter.split_module(layer=layer1, rank=96)\n\n split_conv_output = sess.run(split_conv_op2.outputs[0])\n\n # relaxed absolute tolerance\n self.assertTrue(np.allclose(split_conv_output, orig_conv_output, atol=1e+2))\n\n # check the output after bias\n for consumer in orig_conv_op.outputs[0].consumers():\n orig_bias_out = sess.run(consumer.outputs[0])\n\n for consumer in split_conv_op2.outputs[0].consumers():\n split_bias_out = sess.run(consumer.outputs[0])\n\n # relaxed absolute tolerance\n self.assertTrue(np.allclose(orig_bias_out, split_bias_out, atol=1e+2))\n\n tf.compat.v1.reset_default_graph()\n sess.close()\n\n\nclass TestSpatialSvdPruning(unittest.TestCase):\n\n def test_prune_layer(self):\n \"\"\" Pruning single layer with 0.5 comp-ratio in MNIST\"\"\"\n\n # create tf.compat.v1.Session and initialize the weights and biases with zeros\n config = tf.compat.v1.ConfigProto()\n config.gpu_options.allow_growth = True\n\n # create session with graph\n sess = tf.compat.v1.Session(graph=tf.Graph(), config=config)\n\n with sess.graph.as_default():\n # by default, model will be constructed in default graph\n _ = mnist_tf_model.create_model(data_format='channels_last')\n sess.run(tf.compat.v1.global_variables_initializer())\n\n # Create a layer database\n orig_layer_db = LayerDatabase(model=sess, input_shape=(1, 28, 28, 1), working_dir=None)\n # Copy the db\n comp_layer_db = copy.deepcopy(orig_layer_db)\n conv1 = comp_layer_db.find_layer_by_name('conv2d/Conv2D')\n\n # before the splitting\n bias_op = get_succeeding_bias_op(conv1.module)\n for consumer in bias_op.outputs[0].consumers():\n self.assertEqual(consumer.name, \"conv2d/Relu\")\n\n spatial_svd_pruner = SpatialSvdPruner()\n spatial_svd_pruner._prune_layer(orig_layer_db, comp_layer_db, conv1, 0.5, CostMetric.mac)\n conv2d_a_op = comp_layer_db.model.graph.get_operation_by_name('conv2d_a/Conv2D')\n conv2d_b_op = comp_layer_db.model.graph.get_operation_by_name('conv2d_b/Conv2D')\n conv2d_a_weight = WeightTensorUtils.get_tensor_as_numpy_data(comp_layer_db.model, conv2d_a_op)\n conv2d_b_weight = WeightTensorUtils.get_tensor_as_numpy_data(comp_layer_db.model, conv2d_b_op)\n\n conv1_a = comp_layer_db.find_layer_by_name('conv2d_a/Conv2D')\n conv1_b = comp_layer_db.find_layer_by_name('conv2d_b/Conv2D')\n\n # [Noc, Nic, kh, kw]\n self.assertEqual([2, 1, 5, 1], conv1_a.weight_shape)\n self.assertEqual([32, 2, 1, 5], conv1_b.weight_shape)\n\n # after the splitting\n bias_op = get_succeeding_bias_op(conv1_b.module)\n\n for consumer in bias_op.outputs[0].consumers():\n self.assertEqual(consumer.name, \"conv2d/Relu\")\n\n # original layer should be not there in the database\n self.assertRaises(KeyError, lambda: comp_layer_db.find_layer_by_name('conv2d/Conv2D'))\n\n # check if the layer replacement is done correctly\n orig_conv_op = comp_layer_db.model.graph.get_operation_by_name('conv2d/Conv2D')\n bias_op = get_succeeding_bias_op(orig_conv_op)\n\n # consumers list should be empty\n consumers = [consumer for consumer in bias_op.outputs[0].consumers()]\n self.assertEqual(len(consumers), 0)\n\n # Check that weights loaded during svd pruning will stick after save and load\n new_sess = save_and_load_graph('./temp_meta/', comp_layer_db.model)\n conv2d_a_op = comp_layer_db.model.graph.get_operation_by_name('conv2d_a/Conv2D')\n conv2d_b_op = comp_layer_db.model.graph.get_operation_by_name('conv2d_b/Conv2D')\n conv2d_a_weight_after_save_load = WeightTensorUtils.get_tensor_as_numpy_data(comp_layer_db.model, conv2d_a_op)\n conv2d_b_weight_after_save_load = WeightTensorUtils.get_tensor_as_numpy_data(comp_layer_db.model, conv2d_b_op)\n self.assertTrue(np.array_equal(conv2d_a_weight, conv2d_a_weight_after_save_load))\n self.assertTrue(np.array_equal(conv2d_b_weight, conv2d_b_weight_after_save_load))\n\n tf.compat.v1.reset_default_graph()\n sess.close()\n new_sess.close()\n # delete temp directory\n shutil.rmtree(str('./temp_meta/'))\n\n def test_prune_model_2_layers(self):\n \"\"\" Punning two layers with 0.5 comp-ratio in MNIST\"\"\"\n\n # create tf.compat.v1.Session and initialize the weights and biases with zeros\n config = tf.compat.v1.ConfigProto()\n config.gpu_options.allow_growth = True\n\n # create session with graph\n sess = tf.compat.v1.Session(graph=tf.Graph(), config=config)\n\n with sess.graph.as_default():\n # by default, model will be constructed in default graph\n _ = mnist_tf_model.create_model(data_format='channels_last')\n sess.run(tf.compat.v1.global_variables_initializer())\n\n # Create a layer database\n orig_layer_db = LayerDatabase(model=sess, input_shape=(1, 28, 28, 1), working_dir=None)\n conv1 = orig_layer_db.find_layer_by_name('conv2d/Conv2D')\n conv2 = orig_layer_db.find_layer_by_name('conv2d_1/Conv2D')\n\n layer_comp_ratio_list = [LayerCompRatioPair(conv1, Decimal(0.5)),\n LayerCompRatioPair(conv2, Decimal(0.5))]\n\n spatial_svd_pruner = SpatialSvdPruner()\n comp_layer_db = spatial_svd_pruner.prune_model(orig_layer_db, layer_comp_ratio_list, CostMetric.mac,\n trainer=None)\n\n conv1_a = comp_layer_db.find_layer_by_name('conv2d_a/Conv2D')\n conv1_b = comp_layer_db.find_layer_by_name('conv2d_b/Conv2D')\n\n # Weights shape [kh, kw, Nic, Noc]\n self.assertEqual([5, 1, 1, 2], conv1_a.module.inputs[1].get_shape().as_list())\n self.assertEqual([1, 5, 2, 32], conv1_b.module.inputs[1].get_shape().as_list())\n\n conv2_a = comp_layer_db.find_layer_by_name('conv2d_1_a/Conv2D')\n conv2_b = comp_layer_db.find_layer_by_name('conv2d_1_b/Conv2D')\n\n self.assertEqual([5, 1, 32, 53], conv2_a.module.inputs[1].get_shape().as_list())\n self.assertEqual([1, 5, 53, 64], conv2_b.module.inputs[1].get_shape().as_list())\n\n for layer in comp_layer_db:\n print(\"Layer: \" + layer.name)\n print(\" Module: \" + str(layer.module.name))\n\n tf.compat.v1.reset_default_graph()\n sess.close()\n # delete temp directory\n shutil.rmtree(str('./temp_meta/'))\n\n def test_prune_model_tf_slim(self):\n \"\"\" Punning a model with tf slim api \"\"\"\n\n # create tf.compat.v1.Session and initialize the weights and biases with zeros\n config = tf.compat.v1.ConfigProto()\n config.gpu_options.allow_growth = True\n\n # create session with graph\n sess = tf.compat.v1.Session(graph=tf.Graph(), config=config)\n\n with sess.graph.as_default():\n # by default, model will be constructed in default graph\n x = tf.compat.v1.placeholder(tf.float32, [1, 32, 32, 3])\n _ = tf_slim_basic_model(x)\n sess.run(tf.compat.v1.global_variables_initializer())\n\n conn_graph_orig = ConnectedGraph(sess.graph, ['Placeholder'], ['tf_slim_model/Softmax'])\n num_ops_orig = len(conn_graph_orig.get_all_ops())\n\n # Create a layer database\n orig_layer_db = LayerDatabase(model=sess, input_shape=(1, 32, 32, 3), working_dir=None)\n conv1 = orig_layer_db.find_layer_by_name('Conv_1/Conv2D')\n conv1_bias = BiasUtils.get_bias_as_numpy_data(orig_layer_db.model, conv1.module)\n\n layer_comp_ratio_list = [LayerCompRatioPair(conv1, Decimal(0.5))]\n\n spatial_svd_pruner = SpatialSvdPruner()\n comp_layer_db = spatial_svd_pruner.prune_model(orig_layer_db, layer_comp_ratio_list, CostMetric.mac,\n trainer=None)\n # Check that svd added these ops\n _ = comp_layer_db.model.graph.get_operation_by_name('Conv_1_a/Conv2D')\n _ = comp_layer_db.model.graph.get_operation_by_name('Conv_1_b/Conv2D')\n\n conn_graph_new = ConnectedGraph(comp_layer_db.model.graph, ['Placeholder'], ['tf_slim_model/Softmax'])\n num_ops_new = len(conn_graph_new.get_all_ops())\n self.assertEqual(num_ops_orig + 1, num_ops_new)\n bias_add_op = comp_layer_db.model.graph.get_operation_by_name('Conv_1_b/BiasAdd')\n conv_1_b_op = comp_layer_db.model.graph.get_operation_by_name('Conv_1_b/Conv2D')\n self.assertEqual(conn_graph_new._module_identifier.get_op_info(bias_add_op),\n conn_graph_new._module_identifier.get_op_info(conv_1_b_op))\n self.assertTrue(np.array_equal(conv1_bias, BiasUtils.get_bias_as_numpy_data(comp_layer_db.model, conv_1_b_op)))\n\n def test_prune_conv_no_bias(self):\n \"\"\" Test spatial svd on a conv layer with no bias \"\"\"\n # create tf.compat.v1.Session and initialize the weights and biases with zeros\n config = tf.compat.v1.ConfigProto()\n config.gpu_options.allow_growth = True\n\n # create session with graph\n sess = tf.compat.v1.Session(graph=tf.Graph(), config=config)\n\n with sess.graph.as_default():\n # by default, model will be constructed in default graph\n inputs = tf.keras.Input(shape=(32, 32, 3,))\n x = tf.keras.layers.Conv2D(32, (3, 3), use_bias=False)(inputs)\n _ = tf.keras.layers.Flatten()(x)\n sess.run(tf.compat.v1.global_variables_initializer())\n\n # Create a layer database\n orig_layer_db = LayerDatabase(model=sess, input_shape=(1, 32, 32, 3), working_dir=None)\n conv_op = orig_layer_db.find_layer_by_name('conv2d/Conv2D')\n\n layer_comp_ratio_list = [LayerCompRatioPair(conv_op, Decimal(0.5))]\n\n spatial_svd_pruner = SpatialSvdPruner()\n comp_layer_db = spatial_svd_pruner.prune_model(orig_layer_db, layer_comp_ratio_list, CostMetric.mac,\n trainer=None)\n # Check that svd added these ops\n _ = comp_layer_db.model.graph.get_operation_by_name('conv2d_a/Conv2D')\n conv2d_b_op = comp_layer_db.model.graph.get_operation_by_name('conv2d_b/Conv2D')\n reshape_op = comp_layer_db.model.graph.get_operation_by_name('flatten/Reshape')\n self.assertEqual(conv2d_b_op, reshape_op.inputs[0].op)\n",
"# /usr/bin/env python3.5\n# -*- mode: python -*-\n# =============================================================================\n# @@-COPYRIGHT-START-@@\n#\n# Copyright (c) 2021, Qualcomm Innovation Center, Inc. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# @@-COPYRIGHT-END-@@\n# =============================================================================\n\nimport json\nimport unittest.mock\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom aimet_torch.elementwise_ops import Add, Subtract, Multiply, Divide, Concat\nfrom aimet_torch.quantsim import QuantizationSimModel\nimport libpymo\n\n\nclass Model(nn.Module):\n def __init__(self, op):\n super(Model, self).__init__()\n self.op1 = op\n\n def forward(self, input1, input2):\n x = self.op1(input1, input2)\n return x\n\n\nclass Model2(nn.Module):\n def __init__(self, op):\n super(Model2, self).__init__()\n self.conv1 = nn.Conv2d(10, 10, 5, padding=2)\n self.op1 = op\n\n def forward(self, input):\n x = self.conv1(input)\n x = self.op1(x, input)\n return x\n\n\ndef forward_pass(model, iterations):\n return torch.rand(1)\n\nclass TestTrainingExtensionElementwiseOps(unittest.TestCase):\n def test_add_op(self):\n torch.manual_seed(10)\n model = Model(Add())\n input1 = torch.rand((5, 10, 10, 20))\n input2 = torch.rand((5, 10, 10, 20))\n out = model(input1, input2)\n out1 = input1 + input2\n self.assertTrue(np.allclose(out, out1))\n\n def test_quantsim_export(self):\n torch.manual_seed(10)\n model = Model2(Add())\n dummy_input = torch.randn(5, 10, 10, 20)\n sim = QuantizationSimModel(model, dummy_input)\n encodings = libpymo.TfEncoding()\n encodings.bw = 8\n encodings.max = 5\n encodings.min = -5\n encodings.delta = 1\n encodings.offset = 0.2\n sim.model.op1.output_quantizer.encoding = encodings\n sim.model.conv1.output_quantizer.encoding = encodings\n sim.model.conv1.param_quantizers['weight'].encoding = encodings\n sim.export(path='./data', filename_prefix='quant_model', dummy_input=dummy_input)\n\n with open('./data/quant_model.encodings') as f:\n data = json.load(f)\n\n self.assertTrue(isinstance(data['activation_encodings']['3'], list))\n self.assertTrue(isinstance(data['activation_encodings']['4'], list))\n\n\n def test_subtract_op(self):\n torch.manual_seed(10)\n model = Model(Subtract())\n input1 = torch.rand((5, 10, 10, 20))\n input2 = torch.rand((5, 10, 10, 20))\n out = model(input1, input2)\n out1 = input1 - input2\n self.assertTrue(np.allclose(out, out1))\n\n def test_multiply_op(self):\n torch.manual_seed(10)\n model = Model(Multiply())\n input1 = torch.rand((5, 10, 10, 20))\n input2 = torch.rand((5, 10, 10, 20))\n out = model(input1, input2)\n out1 = input1 * input2\n self.assertTrue(np.allclose(out, out1))\n\n def test_divide_op(self):\n torch.manual_seed(10)\n model = Model(Divide())\n input1 = torch.rand((5, 10, 10, 20))\n input2 = torch.rand((5, 10, 10, 20))\n out = model(input1, input2)\n out1 = torch.div(input1, input2)\n self.assertTrue(np.allclose(out, out1))\n\n def test_concat_op(self):\n torch.manual_seed(10)\n model = Model(Concat(axis=0))\n input1 = torch.rand((5, 10, 10, 20))\n input2 = torch.rand((5, 10, 10, 20))\n out = model(input1, input2)\n out1 = torch.cat((input1, input2), 0)\n self.assertTrue(np.allclose(out, out1))\n",
"# /usr/bin/env python3.5\n# -*- mode: python -*-\n# =============================================================================\n# @@-COPYRIGHT-START-@@\n# \n# Copyright (c) 2017-2018, Qualcomm Innovation Center, Inc. All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without \n# modification, are permitted provided that the following conditions are met:\n# \n# 1. Redistributions of source code must retain the above copyright notice, \n# this list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright notice, \n# this list of conditions and the following disclaimer in the documentation \n# and/or other materials provided with the distribution.\n# \n# 3. Neither the name of the copyright holder nor the names of its contributors \n# may be used to endorse or promote products derived from this software \n# without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE \n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n# \n# SPDX-License-Identifier: BSD-3-Clause\n# \n# @@-COPYRIGHT-END-@@\n# =============================================================================\n\"\"\" Cross Layer Equalization acceptance tests for ResNet model. \"\"\"\n\nimport os\nimport signal\nimport unittest\nimport copy\nimport torch\nimport numpy as np\nimport math\nimport torch.nn as nn\nfrom torchvision import models\nfrom aimet_torch import batch_norm_fold\nfrom aimet_torch.cross_layer_equalization import CrossLayerScaling, HighBiasFold, equalize_model\nfrom aimet_common.utils import start_bokeh_server_session\nfrom aimet_common.bokeh_plots import BokehServerSession\nfrom aimet_torch import visualize_model\nfrom aimet_torch.examples.mobilenet import MobileNetV2\n\n\nclass TestCrossLayerEqualization(unittest.TestCase):\n \"\"\" Acceptance tests related to winnowing ResNet models. \"\"\"\n\n def test_cross_layer_equalization_resnet(self):\n\n torch.manual_seed(10)\n model = models.resnet18(pretrained=True)\n\n model = model.eval()\n\n folded_pairs = batch_norm_fold.fold_all_batch_norms(model, (1, 3, 224, 224))\n bn_dict = {}\n for conv_bn in folded_pairs:\n bn_dict[conv_bn[0]] = conv_bn[1]\n\n self.assertFalse(isinstance(model.layer2[0].bn1, torch.nn.BatchNorm2d))\n\n w1 = model.layer1[0].conv1.weight.detach().numpy()\n w2 = model.layer1[0].conv2.weight.detach().numpy()\n w3 = model.layer1[1].conv1.weight.detach().numpy()\n\n cls_set_info_list = CrossLayerScaling.scale_model(model, (1, 3, 224, 224))\n\n # check if weights are updating\n assert not np.allclose(model.layer1[0].conv1.weight.detach().numpy(), w1)\n assert not np.allclose(model.layer1[0].conv2.weight.detach().numpy(), w2)\n assert not np.allclose(model.layer1[1].conv1.weight.detach().numpy(), w3)\n\n b1 = model.layer1[0].conv1.bias.data\n b2 = model.layer1[1].conv2.bias.data\n\n HighBiasFold.bias_fold(cls_set_info_list, bn_dict)\n\n for i in range(len(model.layer1[0].conv1.bias.data)):\n self.assertTrue(model.layer1[0].conv1.bias.data[i] <= b1[i])\n\n for i in range(len(model.layer1[1].conv2.bias.data)):\n self.assertTrue(model.layer1[1].conv2.bias.data[i] <= b2[i])\n\n def test_cross_layer_equalization_mobilenet_v2(self):\n torch.manual_seed(10)\n\n model = MobileNetV2().to(torch.device('cpu'))\n print(model)\n\n model = model.eval()\n equalize_model(model, (1, 3, 224, 224))\n\n def test_cross_layer_equalization_vgg(self):\n torch.manual_seed(10)\n model = models.vgg16().to(torch.device('cpu'))\n model = model.eval()\n equalize_model(model, (1, 3, 224, 224))\n\n @unittest.skip(\"Takes 1 min 42 secs to run\")\n def test_cross_layer_equalization_mobilenet_v2_visualize_after_optimization(self):\n bokeh_visualizations_url, process = start_bokeh_server_session(8006)\n torch.manual_seed(10)\n model = MobileNetV2().to(torch.device('cpu'))\n bokeh_session = BokehServerSession(bokeh_visualizations_url, session_id=\"cle\")\n model = model.eval()\n model_copy = copy.deepcopy(model)\n\n # model_copy_again = copy.deepcopy(model)\n batch_norm_fold.fold_all_batch_norms(model_copy, (1, 3, 224, 224))\n equalize_model(model, (1, 3, 224, 224))\n visualize_model.visualize_changes_after_optimization(model_copy, model, bokeh_visualizations_url)\n bokeh_session.server_session.close(\"test complete\")\n os.killpg(os.getpgid(process.pid), signal.SIGTERM)\n\n def test_cross_layer_equalization_resnet18_visualize_to_identify_problem_layers(self):\n bokeh_visualizations_url, process = start_bokeh_server_session(6008)\n torch.manual_seed(10)\n model = models.resnet18()\n model = model.eval()\n\n batch_norm_fold.fold_all_batch_norms(model, (1, 3, 224, 224))\n\n bokeh_server_session = \\\n visualize_model.visualize_relative_weight_ranges_to_identify_problematic_layers(model,\n bokeh_visualizations_url)\n bokeh_server_session.server_session.close(\"test complete\")\n os.killpg(os.getpgid(process.pid), signal.SIGTERM)\n\n def test_cle_transposed_conv2D(self):\n class TransposedConvModel(torch.nn.Module):\n def __init__(self):\n super(TransposedConvModel, self).__init__()\n self.conv1 = torch.nn.ConvTranspose2d(20, 10, 3)\n self.bn1 = torch.nn.BatchNorm2d(10)\n self.relu1 = torch.nn.ReLU()\n self.conv2 = torch.nn.ConvTranspose2d(10, 15, 3)\n self.bn2 = torch.nn.BatchNorm2d(15)\n\n def forward(self, x):\n # Regular case - conv followed by bn\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu1(x)\n x = self.conv2(x)\n x = self.bn2(x)\n return x\n\n torch.manual_seed(10)\n model = TransposedConvModel()\n\n w_shape_1 = copy.deepcopy(model.conv1.weight.shape)\n w_shape_2 = copy.deepcopy(model.conv2.weight.shape)\n model = model.eval()\n\n input_shapes = (1, 20, 3, 4)\n random_input = torch.rand(input_shapes)\n output_before_cle = model(random_input).detach().numpy()\n\n folded_pairs = batch_norm_fold.fold_all_batch_norms(model, input_shapes)\n bn_dict = {}\n for conv_bn in folded_pairs:\n bn_dict[conv_bn[0]] = conv_bn[1]\n\n cls_set_info_list = CrossLayerScaling.scale_model(model, input_shapes)\n HighBiasFold.bias_fold(cls_set_info_list, bn_dict)\n\n self.assertEqual(w_shape_1, model.conv1.weight.shape)\n self.assertEqual(w_shape_2, model.conv2.weight.shape)\n\n output_after_cle = model(random_input).detach().numpy()\n self.assertTrue(np.allclose(output_before_cle, output_after_cle, rtol=1.e-2))\n\n def test_cle_depthwise_transposed_conv2D(self):\n\n class TransposedConvModel(torch.nn.Module):\n def __init__(self):\n super(TransposedConvModel, self).__init__()\n self.conv = torch.nn.Conv2d(20, 10, 3)\n self.bn = torch.nn.BatchNorm2d(10)\n self.relu = torch.nn.ReLU()\n self.conv1 = torch.nn.ConvTranspose2d(10, 10, 3, groups=10)\n self.bn1 = torch.nn.BatchNorm2d(10)\n self.relu1 = torch.nn.ReLU()\n self.conv2 = torch.nn.ConvTranspose2d(10, 15, 3)\n self.bn2 = torch.nn.BatchNorm2d(15)\n\n def forward(self, x):\n # Regular case - conv followed by bn\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu1(x)\n x = self.conv2(x)\n x = self.bn2(x)\n return x\n\n torch.manual_seed(10)\n model = TransposedConvModel()\n\n w_shape_1 = copy.deepcopy(model.conv1.weight.shape)\n w_shape_2 = copy.deepcopy(model.conv2.weight.shape)\n model = model.eval()\n\n input_shapes = (1, 20, 3, 4)\n random_input = torch.rand(input_shapes)\n output_before_cle = model(random_input).detach().numpy()\n\n folded_pairs = batch_norm_fold.fold_all_batch_norms(model, input_shapes)\n bn_dict = {}\n for conv_bn in folded_pairs:\n bn_dict[conv_bn[0]] = conv_bn[1]\n\n cls_set_info_list = CrossLayerScaling.scale_model(model, input_shapes)\n HighBiasFold.bias_fold(cls_set_info_list, bn_dict)\n\n self.assertEqual(w_shape_1, model.conv1.weight.shape)\n self.assertEqual(w_shape_2, model.conv2.weight.shape)\n\n output_after_cle = model(random_input).detach().numpy()\n self.assertTrue(np.allclose(output_before_cle, output_after_cle, rtol=1.e-2))\n\n\n",
"# -*- mode: python -*-\n# =============================================================================\n# @@-COPYRIGHT-START-@@\n#\n# Copyright (c) 2017-2018, Qualcomm Innovation Center, Inc. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# @@-COPYRIGHT-END-@@\n# =============================================================================\n\nimport pytest\nimport unittest\nimport copy\nimport time\n\nimport torch\nfrom aimet_torch.quantsim import QuantizationSimModel\nfrom aimet_common.utils import AimetLogger\nimport aimet_torch.examples.mnist_torch_model as mnist_model\n\nlogger = AimetLogger.get_area_logger(AimetLogger.LogAreas.Test)\n\n\ndef forward_pass(model, args):\n torch.manual_seed(1)\n device = next(model.parameters()).device\n\n rand_input = torch.randn((10, 1, 28, 28)).to(device)\n model(rand_input)\n\n\nclass QuantizerCpuGpu(unittest.TestCase):\n\n @pytest.mark.cuda\n def test_and_compare_quantizer_no_fine_tuning_CPU_and_GPU(self):\n\n torch.manual_seed(1)\n torch.backends.cudnn.deterministic = True\n dummy_input = torch.rand(1, 1, 28, 28)\n dummy_input_cuda = dummy_input.cuda()\n\n start_time = time.time()\n\n # create model on CPU\n model_cpu = mnist_model.Net().to('cpu')\n model_gpu = copy.deepcopy(model_cpu).to('cuda')\n cpu_sim_model = QuantizationSimModel(model_cpu, quant_scheme='tf', in_place=True,\n dummy_input=dummy_input)\n # Quantize\n cpu_sim_model.compute_encodings(forward_pass, None)\n\n print(\"Encodings for cpu model calculated\")\n print(\"Took {} secs\".format(time.time() - start_time))\n start_time = time.time()\n\n # create model on GPU\n gpu_sim_model = QuantizationSimModel(model_gpu, quant_scheme='tf', in_place=True,\n dummy_input=dummy_input_cuda)\n # Quantize\n gpu_sim_model.compute_encodings(forward_pass, None)\n\n print(\"Encodings for gpu model calculated\")\n print(\"Took {} secs\".format(time.time() - start_time))\n\n # check the encodings only min and max\n # Test that first and second are approximately (or not approximately)\n # equal by computing the difference, rounding to the given number of\n # decimal places (default 7), and comparing to zero. Note that these\n # methods round the values to the given number of decimal places\n # (i.e. like the round() function) and not significant digits\n # excluding fc1 since it is part of Matmul->Relu supergroup\n # can't use assertEqual for FC2, so using assertAlmostEquals for FC2\n self.assertAlmostEqual(model_gpu.conv1.output_quantizers[0].encoding.min,\n model_cpu.conv1.output_quantizers[0].encoding.min, delta=0.001)\n self.assertAlmostEqual(model_gpu.conv1.output_quantizers[0].encoding.max,\n model_cpu.conv1.output_quantizers[0].encoding.max, delta=0.001)\n\n self.assertAlmostEqual(model_gpu.conv2.output_quantizers[0].encoding.min,\n model_cpu.conv2.output_quantizers[0].encoding.min, delta=0.001)\n self.assertAlmostEqual(model_gpu.conv2.output_quantizers[0].encoding.max,\n model_cpu.conv2.output_quantizers[0].encoding.max, delta=0.001)\n\n self.assertAlmostEqual(model_gpu.fc2.output_quantizers[0].encoding.min,\n model_cpu.fc2.output_quantizers[0].encoding.min, delta=0.001)\n self.assertAlmostEqual(model_gpu.fc2.output_quantizers[0].encoding.max,\n model_cpu.fc2.output_quantizers[0].encoding.max, delta=0.001)\n\n gpu_sim_model.export(\"./data/\", \"quantizer_no_fine_tuning__GPU\", dummy_input)\n cpu_sim_model.export(\"./data/\", \"quantizer_no_fine_tuning__CPU\", dummy_input)\n\n self.assertEqual(torch.device('cuda:0'), next(model_gpu.parameters()).device)\n self.assertEqual(torch.device('cpu'), next(model_cpu.parameters()).device)\n\n"
] | [
[
"tensorflow.nn.bias_add",
"tensorflow.Graph",
"tensorflow.compat.v1.ConfigProto",
"numpy.allclose",
"numpy.array_equal",
"tensorflow.keras.Input",
"tensorflow.keras.layers.Conv2D",
"tensorflow.compat.v1.logging.set_verbosity",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.placeholder",
"tensorflow.random_normal_initializer",
"tensorflow.compat.v1.reset_default_graph",
"tensorflow.keras.layers.Flatten",
"tensorflow.nn.conv2d"
],
[
"torch.div",
"numpy.allclose",
"torch.cat",
"torch.manual_seed",
"torch.randn",
"torch.nn.Conv2d",
"torch.rand"
],
[
"numpy.allclose",
"torch.nn.ConvTranspose2d",
"torch.manual_seed",
"torch.nn.Conv2d",
"torch.rand",
"torch.nn.BatchNorm2d",
"torch.device",
"torch.nn.ReLU"
],
[
"torch.device",
"torch.manual_seed",
"torch.rand",
"torch.randn"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jichangjichang/Paddle | [
"4fa3cee5499c6df0ad6043b0cfa220d09f2034e8",
"4fa3cee5499c6df0ad6043b0cfa220d09f2034e8",
"4fa3cee5499c6df0ad6043b0cfa220d09f2034e8",
"4fa3cee5499c6df0ad6043b0cfa220d09f2034e8"
] | [
"python/paddle/fluid/transpiler/inference_transpiler.py",
"python/paddle/fluid/tests/unittests/test_dist_train.py",
"python/paddle/fluid/tests/unittests/test_rpn_target_assign_op.py",
"python/paddle/fluid/tests/book/high-level-api/word2vec/test_word2vec_new_api.py"
] | [
"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport os\nimport numpy as np\nfrom .. import core\nfrom ..framework import Program\nfrom ..executor import global_scope\n\n\nclass InferenceTranspiler(object):\n '''\n Convert the fluid program to optimized inference program.\n\n There are several optimizations:\n\n - fuse convolution and batch normalization\n - fuse batch normalization and relu (MKLDNN only)\n\n Examples:\n\n .. code-block:: python\n\n # As InferenceTranspiler will modify the original program,\n # please clone before use it.\n inference_transpiler_program = program.clone()\n t = fluid.InferenceTranspiler()\n t.transpile(inference_transpiler_program, place)\n '''\n\n def transpile(self, program, place, scope=None):\n '''\n Run the transpiler.\n\n Args:\n program (Program): program to transpile\n place (Place): inference place\n scope (Scope|None): inference Scope\n '''\n if not isinstance(program, Program):\n raise TypeError(\"program should be as Program type\")\n if not isinstance(place, core.CPUPlace) and not isinstance(\n place, core.CUDAPlace):\n raise TypeError(\"place should be as CPUPlace/CUDAPlace type\")\n if scope is None:\n scope = global_scope()\n if not isinstance(scope, core.Scope):\n raise TypeError(\"scope should be as Scope type or None\")\n use_mkldnn = bool(os.getenv(\"FLAGS_use_mkldnn\", False))\n if use_mkldnn:\n self._fuse_relu_mkldnn(program)\n self._fuse_conv_bias_mkldnn(program)\n else:\n self._fuse_batch_norm(program, place, scope)\n\n def _fuse_relu_mkldnn(self, program):\n '''\n Transpile the program by fused relu activation for MKLDNN program.\n\n Relu activation following batch norm OP can be fused by adding\n :math:`fuse_with_relu` attribute to batch norm OP.\n\n The result of fuse is:\n\n - before:\n\n - batch_norm->relu->any_other_op\n\n - after:\n\n - batch_norm->any_other_op\n\n :param program: program to transpile\n :type program: Program\n '''\n self.block = program.block(0)\n\n i = 0\n while i < len(self.block.ops) - 1:\n current_op = self.block.ops[i]\n if current_op.type in ['batch_norm']:\n next_op = self.block.ops[i + 1]\n if next_op.type == 'relu':\n # modify bnorm OP to include relu\n current_op.set_attr(\"fuse_with_relu\", True)\n # remove relu OP\n self.block._remove_op(i + 1)\n i = i + 1\n\n self._remove_unused_var()\n # TODO(luotao): use clone() method to flush the program.desc in force,\n # since some large program.desc will not be flushed immediately.\n # And a better solution will be considered later.\n program = program.clone()\n\n def _fuse_conv_bias_mkldnn(self, program):\n '''\n Transpile the program by fused convolution and elementwise_add.\n\n Replace conv2d and elementwise_add ops with a new conv2d op\n based on an old conv2d op and the :math:`Bias` taken from\n elementwise_add.\n\n For input :math:`X`:\n\n - Conv process: :math:`X = input * W`\n - Elementwise_add process: :math` X = X + bias`\n\n After fuse into one operation:\n\n .. math::\n\n X = input * W + bias\n\n The operator transformation is:\n\n - before:\n\n - conv->elementwise_add->any_other_op\n\n - after:\n\n - conv->any_other_op\n\n The transpile stages are:\n\n 1. Extract bias and output variables from elementwise_add.\n 2. Extract Input, Weight and attributes from conv op.\n 3. Create a new convolution op based on extracted params.\n 4. Remove old conv op.\n 5. Remove elementwise_add.\n 5. Remove unused variables.\n\n Args:\n program (Program): program to transpile\n\n '''\n self.block = program.block(0)\n\n i = 0\n while i < len(self.block.ops) - 2:\n current_op = self.block.ops[i]\n next_op = self.block.ops[i + 1]\n # conv2d with bias\n if current_op.type in ['conv2d'] and \\\n next_op.type in ['elementwise_add']:\n self._fuse_conv_bias(i, current_op, next_op)\n self.block._remove_op(i + 1) # Remove old conv\n self.block._remove_op(i + 1) # Remove elementwise_add\n i = i + 1\n i = i + 1\n\n self._remove_unused_var()\n # TODO(luotao): use clone() method to flush the program.desc in force,\n # since some large program.desc will not be flushed immediately.\n # And a better solution will be considered later.\n program = program.clone()\n\n def _fuse_batch_norm(self, program, place, scope):\n '''\n Transpile the program by fused batch normalization.\n\n The batch normalization followed the convolution or fully connected layer\n can be integrated with them. Doing so will give us a forward acceleration,\n especially in environments like mobile or embedded.\n\n For input :math:`X`:\n\n - Conv process: :math:`X = input * W + bias`\n - Batch norm process: :math:`X' = (X - mean) / std`\n - Scale Process: :math:`Y = a * X' + b`\n\n After fuse into one operation:\n\n .. math::\n\n Y &= (input * W + bias - mean) / std * a + b \\\\\\\\\n &= input * a * W / std + ((bias - mean) / std * a + b)\n\n The operator transformation is:\n\n - before:\n\n - conv->batch_norm->any_other_op (bias == 0)\n - conv->elementwise_add->batch_norm->any_other_op (bias != 0)\n\n - after:\n\n - conv->elementwise_add->any_other_op\n\n The transpile stages are:\n\n 1. insert elementwise_add op when bias == 0.\n 2. fuse the batch_norm's parameters to conv and elementwise_add operators.\n 3. remove batch_norm ops which are not used in any other ops.\n 4. adjust the input of any_other_op to be the output of elementwise_add operator.\n 5. remove unused variables.\n\n Args:\n program (Program): program to transpile\n place (Place): inference place\n scope (Scope): inference Scope\n\n '''\n self.scope = scope\n self.place = place\n self.block = program.block(0)\n self.input_map = {} # store the input names should be adjusted\n\n i = 0\n while i < len(self.block.ops) - 2:\n current_op = self.block.ops[i]\n # TODO(luotao1): consider only conv2d now. fc would be delt later.\n if current_op.type in ['conv2d']:\n # TODO(luotao1): consider single chain network now.\n # For branch network, we counldn't use block.ops[i + 1] as\n # the judgment condition.\n next_op = self.block.ops[i + 1]\n # conv2d without bias\n if (next_op.type == 'batch_norm'):\n # insert bias op\n bias_op = self._insert_bias_op(i + 1, current_op, next_op)\n # fuse batch_norm\n self._fuse_param(current_op, next_op, bias_op, 0)\n # remove batch_norm_op\n self.block._remove_op(i + 2)\n i = i + 1\n # conv2d with bias, the next_op.type is elementwise_add\n elif (next_op.type == 'elementwise_add'):\n next_next_op = self.block.ops[i + 2]\n if (next_next_op.type == 'batch_norm'):\n # fuse batch_norm\n self._fuse_param(current_op, next_next_op, next_op, 1)\n # remove batch_norm_op\n self.block._remove_op(i + 2)\n i = i + 1\n i = i + 1\n self._adjust_input()\n self._remove_unused_var()\n # TODO(luotao): use clone() method to flush the program.desc in force,\n # since some large program.desc will not be flushed immediately.\n # And a better solution will be considered later.\n program = program.clone()\n\n # ====================== private transpiler functions =====================\n def _insert_bias_op(self, index, current_op, bn_op):\n '''\n Construct elementwise_add operator for adding bias\n and insert it into program.\n\n :param index: insert location of bias_op\n :type index: Int\n :param current_op: current operator (conv or fc)\n :type current_op: Operator\n :param bn_op: batch norm operator\n :type bn_op: Operator\n :return: bias_op\n :rtype: Operator\n '''\n # The input of bias_op is current_op's output and Bias of bn_op\n # The output of bias_op is bn_op's output\n x_var = self.block.var(current_op.output(\"Output\")[0])\n y_var = self.block.var(bn_op.input(\"Bias\")[0])\n out_var = self.block.var(bn_op.output(\"Y\")[0])\n\n bias_op = self.block._insert_op(\n index,\n type=\"elementwise_add\",\n inputs={\"X\": x_var,\n \"Y\": y_var},\n outputs={\"Out\": out_var},\n attrs={\"axis\": 1}) # dim_start=1\n return bias_op\n\n def _fuse_param(self, current_op, bn_op, bias_op, with_bias):\n '''\n fuse the batch_norm_op' parameters to current_op (conv or fc)\n\n :param current_op: current operator (conv or fc)\n :type current_op: Operator\n :param bn_op: batch norm operator\n :type bn_op: Operator\n :param bias_op: elementwise_add operator for adding bias\n :type bias_op: Operator\n :param with_bias: If current operator has bias, with_bias = 1; otherwise 0.\n :type with_bias: Int\n '''\n\n def _update_param(op, old_param_name, new_param):\n # For the sake of remaining the original variables the same as before,\n # create new variables in scope to store the new parameters.\n old_param_name = old_param_name[0]\n old_var = self.block.vars[old_param_name]\n new_param_name = old_param_name + '_fuse_bn'\n new_var = self.block.create_parameter(\n name=new_param_name.encode('ascii'),\n type=old_var.type,\n dtype=old_var.dtype,\n shape=old_var.shape)\n op.rename_input(old_param_name, new_param_name)\n self.scope.var(new_param_name)\n\n tensor = self.scope.find_var(new_param_name).get_tensor()\n tensor.set(np.array(new_param), self.place)\n\n def _load_param(param_name):\n return np.array(self.scope.find_var(param_name[0]).get_tensor())\n\n bias_bn = _load_param(bn_op.input(\"Bias\")) #Bias\n scale_bn = _load_param(bn_op.input(\"Scale\")) #Scale\n mean_bn = _load_param(bn_op.input(\"Mean\")) #Mean\n var_bn = _load_param(bn_op.input(\"Variance\")) #Variance\n\n # TODO(luotao1): consider only conv2d now. fc would be delt later.\n current_param = _load_param(current_op.input(\"Filter\"))\n std_bn = np.float32(np.sqrt(np.add(var_bn, 1e-5)))\n tmp = np.float32(np.divide(scale_bn, std_bn))\n\n # add bias of batch_norm_op to conv2d\n if with_bias:\n bias = _load_param(bias_op.input(\"Y\"))\n else:\n bias = np.zeros(bias_bn.shape)\n bias = np.float32(\n np.add(np.multiply(np.subtract(bias, mean_bn), tmp), bias_bn))\n\n # re-compute weight of conv2d\n tmp = tmp.reshape(tmp.shape[0], -1)\n dst_param = current_param.reshape((tmp.shape[0], -1))\n dst_param = np.float32(np.multiply(dst_param, tmp))\n dst_param = dst_param.reshape(current_param.shape)\n\n # update parameters\n _update_param(current_op, current_op.input(\"Filter\"), dst_param)\n _update_param(bias_op, bias_op.input(\"Y\"), bias)\n\n # collect the renamed input\n self.input_map[bn_op.output(\"Y\")[0]] = bias_op.output(\"Out\")[0]\n\n def _fuse_conv_bias(self, index, conv_op, elementwise_add_op):\n '''\n fuse the conv op with elementwise_add\n\n :param index: index of the conv_op in ops list\n :type index: Int\n :param conv_op: convolution operator\n :type conv_op: Operator\n :param elementwise_add_op: convolution's bias operator\n :type elementwise_add_op: Operator\n '''\n\n bias_var = self.block.var(elementwise_add_op.input(\"Y\")[0])\n out_var = self.block.var(elementwise_add_op.output(\"Out\")[0])\n filter_var = self.block.var(conv_op.input(\"Filter\")[0])\n in_var = self.block.var(conv_op.input(\"Input\")[0])\n attrs = {name: conv_op.attr(name) for name in conv_op.attr_names}\n\n self.block._insert_op(\n index,\n type=\"conv2d\",\n inputs={\"Input\": in_var,\n \"Filter\": filter_var,\n \"Bias\": bias_var},\n outputs={\"Output\": out_var},\n attrs=attrs)\n\n def _adjust_input(self):\n for i in range(len(self.block.ops)):\n current_op = self.block.ops[i]\n for input_arg in current_op.input_arg_names:\n if input_arg in self.input_map:\n current_op.rename_input(input_arg,\n self.input_map[input_arg])\n\n def _remove_unused_var(self):\n '''\n remove unused varibles in program\n '''\n args = []\n for i in range(len(self.block.ops)):\n current_op = self.block.ops[i]\n args += current_op.input_arg_names\n args += current_op.output_arg_names\n args = list(set(args)) # unique the input and output arguments\n\n for var in list(self.block.vars.keys()):\n if var not in args:\n self.block._remove_var(var)\n",
"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport os\nimport time\nimport unittest\nfrom multiprocessing import Process\nimport signal\n\nimport numpy\n\nimport paddle.fluid as fluid\nimport paddle.fluid.layers as layers\nfrom paddle.fluid.layers.io import ListenAndServ\nfrom paddle.fluid.layers.io import Recv\nfrom paddle.fluid.layers.io import Send\n\nfrom paddle.fluid import core\n\nRPC_OP_ROLE_ATTR_NAME = op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName(\n)\nRPC_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.RPC\n\n\nclass TestSendOp(unittest.TestCase):\n def test_send(self):\n # Run init_serv in a thread\n place = fluid.CPUPlace()\n # NOTE: python thread will not work here due to GIL.\n p = Process(target=self.init_serv, args=(place, ))\n p.daemon = True\n p.start()\n\n self.ps_timeout = 5\n self._wait_ps_ready(p.pid)\n\n with open(\"/tmp/paddle.%d.port\" % p.pid, \"r\") as fn:\n selected_port = int(fn.readlines()[0])\n self.init_client(place, selected_port)\n\n self.run_local(place)\n self.assertTrue(numpy.allclose(self.local_out, self.dist_out))\n\n # FIXME(typhoonzero): find a way to gracefully shutdown the server.\n os.kill(p.pid, signal.SIGKILL)\n p.join()\n\n def _wait_ps_ready(self, pid):\n start_left_time = self.ps_timeout\n sleep_time = 0.5\n while True:\n assert start_left_time >= 0, \"wait ps ready failed\"\n time.sleep(sleep_time)\n try:\n # the listen_and_serv_op would touch a file which contains the listen port\n # on the /tmp directory until it was ready to process all the RPC call.\n os.stat(\"/tmp/paddle.%d.port\" % pid)\n return\n except os.error:\n start_left_time -= sleep_time\n\n def init_serv(self, place):\n main = fluid.Program()\n\n with fluid.program_guard(main):\n serv = ListenAndServ(\"127.0.0.1:0\", [\"X\"], optimizer_mode=False)\n with serv.do():\n out_var = main.global_block().create_var(\n name=\"scale_0.tmp_0\",\n psersistable=True,\n dtype=\"float32\",\n shape=[32, 32])\n x = layers.data(\n shape=[32, 32],\n dtype='float32',\n name=\"X\",\n append_batch_size=False)\n fluid.initializer.Constant(value=1.0)(x, main.global_block())\n layers.scale(x=x, scale=10.0, out=out_var)\n\n self.server_exe = fluid.Executor(place)\n self.server_exe.run(main)\n\n def init_client(self, place, port):\n main = fluid.Program()\n with fluid.program_guard(main):\n main.global_block().append_op(\n type=\"fetch_barrier\",\n inputs={},\n outputs={\"Out\": []},\n attrs={\n \"endpoints\": [\"127.0.0.1:{0}\".format(port)],\n RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE\n })\n\n x = layers.data(\n shape=[32, 32],\n dtype='float32',\n name='X',\n append_batch_size=False)\n fluid.initializer.Constant(value=2.3)(x, main.global_block())\n\n get_var = main.global_block().create_var(\n name=\"scale_0.tmp_0\", # server side var\n dtype=\"float32\",\n persistable=False,\n shape=[32, 32])\n fluid.initializer.Constant(value=2.3)(get_var, main.global_block())\n\n Send(\"127.0.0.1:%d\" % port, [x])\n o = Recv(\"127.0.0.1:%d\" % port, [get_var])\n\n exe = fluid.Executor(place)\n self.dist_out = exe.run(main, fetch_list=o) # o is a list\n\n def run_local(self, place):\n main = fluid.Program()\n with fluid.program_guard(main):\n x = layers.data(\n shape=[32, 32],\n dtype='float32',\n name='X',\n append_batch_size=False)\n fluid.initializer.Constant(value=2.3)(x, main.global_block())\n o = layers.scale(x=x, scale=10.0)\n exe = fluid.Executor(place)\n self.local_out = exe.run(main, fetch_list=[o])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport paddle.fluid.core as core\nfrom op_test import OpTest\n\n\ndef rpn_target_assign(iou, rpn_batch_size_per_im, rpn_positive_overlap,\n rpn_negative_overlap, fg_fraction):\n iou = np.transpose(iou)\n anchor_to_gt_max = iou.max(axis=1)\n gt_to_anchor_argmax = iou.argmax(axis=0)\n gt_to_anchor_max = iou[gt_to_anchor_argmax, np.arange(iou.shape[1])]\n anchors_with_max_overlap = np.where(iou == gt_to_anchor_max)[0]\n\n tgt_lbl = np.ones((iou.shape[0], ), dtype=np.int32) * -1\n tgt_lbl[anchors_with_max_overlap] = 1\n tgt_lbl[anchor_to_gt_max >= rpn_positive_overlap] = 1\n\n num_fg = int(fg_fraction * rpn_batch_size_per_im)\n fg_inds = np.where(tgt_lbl == 1)[0]\n if len(fg_inds) > num_fg:\n disable_inds = np.random.choice(\n fg_inds, size=(len(fg_inds) - num_fg), replace=False)\n tgt_lbl[disable_inds] = -1\n fg_inds = np.where(tgt_lbl == 1)[0]\n\n num_bg = rpn_batch_size_per_im - np.sum(tgt_lbl == 1)\n bg_inds = np.where(anchor_to_gt_max < rpn_negative_overlap)[0]\n if len(bg_inds) > num_bg:\n enable_inds = bg_inds[np.random.randint(len(bg_inds), size=num_bg)]\n tgt_lbl[enable_inds] = 0\n bg_inds = np.where(tgt_lbl == 0)[0]\n\n loc_index = fg_inds\n score_index = np.hstack((fg_inds, bg_inds))\n tgt_lbl = np.expand_dims(tgt_lbl, axis=1)\n return loc_index, score_index, tgt_lbl\n\n\nclass TestRpnTargetAssignOp(OpTest):\n def setUp(self):\n iou = np.random.random((10, 8)).astype(\"float32\")\n self.op_type = \"rpn_target_assign\"\n self.inputs = {'DistMat': iou}\n self.attrs = {\n 'rpn_batch_size_per_im': 256,\n 'rpn_positive_overlap': 0.95,\n 'rpn_negative_overlap': 0.3,\n 'fg_fraction': 0.25,\n 'fix_seed': True\n }\n loc_index, score_index, tgt_lbl = rpn_target_assign(iou, 256, 0.95, 0.3,\n 0.25)\n self.outputs = {\n 'LocationIndex': loc_index,\n 'ScoreIndex': score_index,\n 'TargetLabel': tgt_lbl,\n }\n\n def test_check_output(self):\n self.check_output()\n\n\nclass TestRpnTargetAssignOp2(OpTest):\n def setUp(self):\n iou = np.random.random((10, 20)).astype(\"float32\")\n self.op_type = \"rpn_target_assign\"\n self.inputs = {'DistMat': iou}\n self.attrs = {\n 'rpn_batch_size_per_im': 128,\n 'rpn_positive_overlap': 0.5,\n 'rpn_negative_overlap': 0.5,\n 'fg_fraction': 0.5,\n 'fix_seed': True\n }\n loc_index, score_index, tgt_lbl = rpn_target_assign(iou, 128, 0.5, 0.5,\n 0.5)\n self.outputs = {\n 'LocationIndex': loc_index,\n 'ScoreIndex': score_index,\n 'TargetLabel': tgt_lbl,\n }\n\n def test_check_output(self):\n self.check_output()\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport paddle\nimport paddle.fluid as fluid\nimport numpy as np\nimport math\nimport sys\nfrom functools import partial\n\nPASS_NUM = 100\nEMBED_SIZE = 32\nHIDDEN_SIZE = 256\nN = 5\nBATCH_SIZE = 32\n\nword_dict = paddle.dataset.imikolov.build_dict()\ndict_size = len(word_dict)\n\n\ndef inference_program(is_sparse):\n first_word = fluid.layers.data(name='firstw', shape=[1], dtype='int64')\n second_word = fluid.layers.data(name='secondw', shape=[1], dtype='int64')\n third_word = fluid.layers.data(name='thirdw', shape=[1], dtype='int64')\n forth_word = fluid.layers.data(name='forthw', shape=[1], dtype='int64')\n\n embed_first = fluid.layers.embedding(\n input=first_word,\n size=[dict_size, EMBED_SIZE],\n dtype='float32',\n is_sparse=is_sparse,\n param_attr='shared_w')\n embed_second = fluid.layers.embedding(\n input=second_word,\n size=[dict_size, EMBED_SIZE],\n dtype='float32',\n is_sparse=is_sparse,\n param_attr='shared_w')\n embed_third = fluid.layers.embedding(\n input=third_word,\n size=[dict_size, EMBED_SIZE],\n dtype='float32',\n is_sparse=is_sparse,\n param_attr='shared_w')\n embed_forth = fluid.layers.embedding(\n input=forth_word,\n size=[dict_size, EMBED_SIZE],\n dtype='float32',\n is_sparse=is_sparse,\n param_attr='shared_w')\n\n concat_embed = fluid.layers.concat(\n input=[embed_first, embed_second, embed_third, embed_forth], axis=1)\n hidden1 = fluid.layers.fc(input=concat_embed,\n size=HIDDEN_SIZE,\n act='sigmoid')\n predict_word = fluid.layers.fc(input=hidden1, size=dict_size, act='softmax')\n return predict_word\n\n\ndef train_program(is_sparse):\n # The declaration of 'next_word' must be after the invoking of inference_program,\n # or the data input order of train program would be [next_word, firstw, secondw,\n # thirdw, forthw], which is not correct.\n predict_word = inference_program(is_sparse)\n next_word = fluid.layers.data(name='nextw', shape=[1], dtype='int64')\n cost = fluid.layers.cross_entropy(input=predict_word, label=next_word)\n avg_cost = fluid.layers.mean(cost)\n return avg_cost\n\n\ndef optimizer_func():\n return fluid.optimizer.SGD(learning_rate=0.001)\n\n\ndef train(use_cuda, train_program, params_dirname):\n train_reader = paddle.batch(\n paddle.dataset.imikolov.train(word_dict, N), BATCH_SIZE)\n test_reader = paddle.batch(\n paddle.dataset.imikolov.test(word_dict, N), BATCH_SIZE)\n\n place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()\n\n def event_handler(event):\n if isinstance(event, fluid.EndStepEvent):\n outs = trainer.test(\n reader=test_reader,\n feed_order=['firstw', 'secondw', 'thirdw', 'forthw', 'nextw'])\n avg_cost = outs[0]\n print(\"loss= \", avg_cost)\n\n if avg_cost < 10.0:\n trainer.save_params(params_dirname)\n trainer.stop()\n\n if math.isnan(avg_cost):\n sys.exit(\"got NaN loss, training failed.\")\n\n trainer = fluid.Trainer(\n train_func=train_program, optimizer_func=optimizer_func, place=place)\n\n trainer.train(\n reader=train_reader,\n num_epochs=1,\n event_handler=event_handler,\n feed_order=['firstw', 'secondw', 'thirdw', 'forthw', 'nextw'])\n\n\ndef infer(use_cuda, inference_program, params_dirname=None):\n place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()\n inferencer = fluid.Inferencer(\n infer_func=inference_program, param_path=params_dirname, place=place)\n\n # Setup inputs by creating 4 LoDTensors representing 4 words. Here each word \n # is simply an index to look up for the corresponding word vector and hence \n # the shape of word (base_shape) should be [1]. The recursive_sequence_lengths, \n # which is length-based level of detail (lod) of each LoDTensor, should be [[1]] \n # meaning there is only one level of detail and there is only one sequence of \n # one word on this level.\n # Note that recursive_sequence_lengths should be a list of lists.\n recursive_seq_lens = [[1]]\n base_shape = [1]\n # The range of random integers is [low, high]\n first_word = fluid.create_random_int_lodtensor(\n recursive_seq_lens, base_shape, place, low=0, high=dict_size - 1)\n second_word = fluid.create_random_int_lodtensor(\n recursive_seq_lens, base_shape, place, low=0, high=dict_size - 1)\n third_word = fluid.create_random_int_lodtensor(\n recursive_seq_lens, base_shape, place, low=0, high=dict_size - 1)\n fourth_word = fluid.create_random_int_lodtensor(\n recursive_seq_lens, base_shape, place, low=0, high=dict_size - 1)\n\n result = inferencer.infer(\n {\n 'firstw': first_word,\n 'secondw': second_word,\n 'thirdw': third_word,\n 'forthw': fourth_word\n },\n return_numpy=False)\n print(np.array(result[0]))\n\n\ndef main(use_cuda, is_sparse):\n if use_cuda and not fluid.core.is_compiled_with_cuda():\n return\n\n params_dirname = \"word2vec.inference.model\"\n\n train(\n use_cuda=use_cuda,\n train_program=partial(train_program, is_sparse),\n params_dirname=params_dirname)\n\n infer(\n use_cuda=use_cuda,\n inference_program=partial(inference_program, is_sparse),\n params_dirname=params_dirname)\n\n\nif __name__ == '__main__':\n for use_cuda in (False, True):\n for is_sparse in (False, True):\n main(use_cuda=use_cuda, is_sparse=is_sparse)\n"
] | [
[
"numpy.multiply",
"numpy.subtract",
"numpy.add",
"numpy.array",
"numpy.zeros",
"numpy.divide"
],
[
"numpy.allclose"
],
[
"numpy.hstack",
"numpy.expand_dims",
"numpy.random.random",
"numpy.arange",
"numpy.ones",
"numpy.transpose",
"numpy.where",
"numpy.sum"
],
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
shangliy/ee660 | [
"c1345d61ddcc1122472358d55ac87ffc03441339"
] | [
"python/demos/ch02/bernoulliEntropyFig.py"
] | [
"#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pylab as pl\n\n\ndef entropy(p):\n \"\"\"calculate the entropy\"\"\"\n h = -p * np.log2(p) - (1 - p) * np.log2(1 - p)\n return h\n\nx = np.linspace(0.01, 0.99, 100)\ny = entropy(x)\n\npl.plot(x, y)\npl.xlabel('p(X=1)')\npl.ylabel('H(X)')\npl.savefig('bernoulliEntropyFig.png')\npl.show()\n"
] | [
[
"matplotlib.pylab.show",
"numpy.log2",
"numpy.linspace",
"matplotlib.pylab.ylabel",
"matplotlib.pylab.plot",
"matplotlib.pylab.savefig",
"matplotlib.pylab.xlabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cabelo/depthai-experiments | [
"c90962aef58ab58a4326e068979e92aeec7e2f03"
] | [
"gen2_examples/02_mono_preview.py"
] | [
"#!/usr/bin/env python3\n\nimport cv2\nimport depthai as dai\nimport numpy as np\n\n# Start defining a pipeline\npipeline = dai.Pipeline()\n\n# Define a source - two mono (grayscale) cameras\ncam_left = pipeline.createMonoCamera()\ncam_left.setCamId(1)\ncam_left.setResolution(dai.MonoCameraProperties.SensorResolution.THE_720_P)\n\ncam_right = pipeline.createMonoCamera()\ncam_right.setCamId(2)\ncam_right.setResolution(dai.MonoCameraProperties.SensorResolution.THE_720_P)\n\n# Create outputs\nxout_left = pipeline.createXLinkOut()\nxout_left.setStreamName('left')\ncam_left.out.link(xout_left.input)\nxout_right = pipeline.createXLinkOut()\nxout_right.setStreamName('right')\ncam_right.out.link(xout_right.input)\n\n# Pipeline defined, now the device is assigned and pipeline is started\ndevice = dai.Device(pipeline)\ndevice.startPipeline()\n\n# Output queues will be used to get the grayscale frames from the outputs defined above\nq_left = device.getOutputQueue(name=\"left\", maxSize=4, overwrite=True)\nq_right = device.getOutputQueue(name=\"right\", maxSize=4, overwrite=True)\n\nframe_left = None\nframe_right = None\n\nwhile True:\n # instead of get (blocking) used tryGet (nonblocking) which will return the available data or None otherwise\n in_left = q_left.tryGet()\n in_right = q_right.tryGet()\n\n if in_left is not None:\n # if the data from the left camera is available, transform the 1D data into a frame\n frame_left = in_left.getData().reshape((in_left.getHeight(), in_left.getWidth())).astype(np.uint8)\n frame_left = np.ascontiguousarray(frame_left)\n\n if in_right is not None:\n # if the data from the right camera is available, transform the 1D data into a frame\n frame_right = in_right.getData().reshape((in_right.getHeight(), in_right.getWidth())).astype(np.uint8)\n frame_right = np.ascontiguousarray(frame_right)\n\n # show the frames if available\n if frame_left is not None:\n cv2.imshow(\"left\", frame_left)\n if frame_right is not None:\n cv2.imshow(\"right\", frame_right)\n\n if cv2.waitKey(1) == ord('q'):\n break\n"
] | [
[
"numpy.ascontiguousarray"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Pverheijen/airflow | [
"dfe8337ca2d3ed173d9ecc112938271519792c40"
] | [
"airflow/providers/apache/hive/hooks/hive.py"
] | [
"#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport contextlib\nimport os\nimport re\nimport socket\nimport subprocess\nimport time\nfrom collections import OrderedDict\nfrom tempfile import NamedTemporaryFile, TemporaryDirectory\n\nimport unicodecsv as csv\n\nfrom airflow.configuration import conf\nfrom airflow.exceptions import AirflowException\nfrom airflow.hooks.base_hook import BaseHook\nfrom airflow.hooks.dbapi_hook import DbApiHook\nfrom airflow.security import utils\nfrom airflow.utils.helpers import as_flattened_list\nfrom airflow.utils.operator_helpers import AIRFLOW_VAR_NAME_FORMAT_MAPPING\n\nHIVE_QUEUE_PRIORITIES = ['VERY_HIGH', 'HIGH', 'NORMAL', 'LOW', 'VERY_LOW']\n\n\ndef get_context_from_env_var():\n \"\"\"\n Extract context from env variable, e.g. dag_id, task_id and execution_date,\n so that they can be used inside BashOperator and PythonOperator.\n\n :return: The context of interest.\n \"\"\"\n return {format_map['default']: os.environ.get(format_map['env_var_format'], '')\n for format_map in AIRFLOW_VAR_NAME_FORMAT_MAPPING.values()}\n\n\nclass HiveCliHook(BaseHook):\n \"\"\"Simple wrapper around the hive CLI.\n\n It also supports the ``beeline``\n a lighter CLI that runs JDBC and is replacing the heavier\n traditional CLI. To enable ``beeline``, set the use_beeline param in the\n extra field of your connection as in ``{ \"use_beeline\": true }``\n\n Note that you can also set default hive CLI parameters using the\n ``hive_cli_params`` to be used in your connection as in\n ``{\"hive_cli_params\": \"-hiveconf mapred.job.tracker=some.jobtracker:444\"}``\n Parameters passed here can be overridden by run_cli's hive_conf param\n\n The extra connection parameter ``auth`` gets passed as in the ``jdbc``\n connection string as is.\n\n :param mapred_queue: queue used by the Hadoop Scheduler (Capacity or Fair)\n :type mapred_queue: str\n :param mapred_queue_priority: priority within the job queue.\n Possible settings include: VERY_HIGH, HIGH, NORMAL, LOW, VERY_LOW\n :type mapred_queue_priority: str\n :param mapred_job_name: This name will appear in the jobtracker.\n This can make monitoring easier.\n :type mapred_job_name: str\n \"\"\"\n\n def __init__(\n self,\n hive_cli_conn_id=\"hive_cli_default\",\n run_as=None,\n mapred_queue=None,\n mapred_queue_priority=None,\n mapred_job_name=None):\n super().__init__()\n conn = self.get_connection(hive_cli_conn_id)\n self.hive_cli_params = conn.extra_dejson.get('hive_cli_params', '')\n self.use_beeline = conn.extra_dejson.get('use_beeline', False)\n self.auth = conn.extra_dejson.get('auth', 'noSasl')\n self.conn = conn\n self.run_as = run_as\n self.sub_process = None\n\n if mapred_queue_priority:\n mapred_queue_priority = mapred_queue_priority.upper()\n if mapred_queue_priority not in HIVE_QUEUE_PRIORITIES:\n raise AirflowException(\n \"Invalid Mapred Queue Priority. Valid values are: \"\n \"{}\".format(', '.join(HIVE_QUEUE_PRIORITIES)))\n\n self.mapred_queue = mapred_queue or conf.get('hive',\n 'default_hive_mapred_queue')\n self.mapred_queue_priority = mapred_queue_priority\n self.mapred_job_name = mapred_job_name\n\n def _get_proxy_user(self):\n \"\"\"\n This function set the proper proxy_user value in case the user overwtire the default.\n \"\"\"\n conn = self.conn\n\n proxy_user_value = conn.extra_dejson.get('proxy_user', \"\")\n if proxy_user_value == \"login\" and conn.login:\n return \"hive.server2.proxy.user={0}\".format(conn.login)\n if proxy_user_value == \"owner\" and self.run_as:\n return \"hive.server2.proxy.user={0}\".format(self.run_as)\n if proxy_user_value != \"\": # There is a custom proxy user\n return \"hive.server2.proxy.user={0}\".format(proxy_user_value)\n return proxy_user_value # The default proxy user (undefined)\n\n def _prepare_cli_cmd(self):\n \"\"\"\n This function creates the command list from available information\n \"\"\"\n conn = self.conn\n hive_bin = 'hive'\n cmd_extra = []\n\n if self.use_beeline:\n hive_bin = 'beeline'\n jdbc_url = \"jdbc:hive2://{host}:{port}/{schema}\".format(\n host=conn.host, port=conn.port, schema=conn.schema)\n if conf.get('core', 'security') == 'kerberos':\n template = conn.extra_dejson.get(\n 'principal', \"hive/[email protected]\")\n if \"_HOST\" in template:\n template = utils.replace_hostname_pattern(\n utils.get_components(template))\n\n proxy_user = self._get_proxy_user()\n\n jdbc_url += \";principal={template};{proxy_user}\".format(\n template=template, proxy_user=proxy_user)\n elif self.auth:\n jdbc_url += \";auth=\" + self.auth\n\n jdbc_url = '\"{}\"'.format(jdbc_url)\n\n cmd_extra += ['-u', jdbc_url]\n if conn.login:\n cmd_extra += ['-n', conn.login]\n if conn.password:\n cmd_extra += ['-p', conn.password]\n\n hive_params_list = self.hive_cli_params.split()\n\n return [hive_bin] + cmd_extra + hive_params_list\n\n @staticmethod\n def _prepare_hiveconf(d):\n \"\"\"\n This function prepares a list of hiveconf params\n from a dictionary of key value pairs.\n\n :param d:\n :type d: dict\n\n >>> hh = HiveCliHook()\n >>> hive_conf = {\"hive.exec.dynamic.partition\": \"true\",\n ... \"hive.exec.dynamic.partition.mode\": \"nonstrict\"}\n >>> hh._prepare_hiveconf(hive_conf)\n [\"-hiveconf\", \"hive.exec.dynamic.partition=true\",\\\n \"-hiveconf\", \"hive.exec.dynamic.partition.mode=nonstrict\"]\n \"\"\"\n if not d:\n return []\n return as_flattened_list(\n zip([\"-hiveconf\"] * len(d),\n [\"{}={}\".format(k, v) for k, v in d.items()])\n )\n\n def run_cli(self, hql, schema=None, verbose=True, hive_conf=None):\n \"\"\"\n Run an hql statement using the hive cli. If hive_conf is specified\n it should be a dict and the entries will be set as key/value pairs\n in HiveConf\n\n\n :param hive_conf: if specified these key value pairs will be passed\n to hive as ``-hiveconf \"key\"=\"value\"``. Note that they will be\n passed after the ``hive_cli_params`` and thus will override\n whatever values are specified in the database.\n :type hive_conf: dict\n\n >>> hh = HiveCliHook()\n >>> result = hh.run_cli(\"USE airflow;\")\n >>> (\"OK\" in result)\n True\n \"\"\"\n conn = self.conn\n schema = schema or conn.schema\n if schema:\n hql = \"USE {schema};\\n{hql}\".format(schema=schema, hql=hql)\n\n with TemporaryDirectory(prefix='airflow_hiveop_') as tmp_dir:\n with NamedTemporaryFile(dir=tmp_dir) as f:\n hql = hql + '\\n'\n f.write(hql.encode('UTF-8'))\n f.flush()\n hive_cmd = self._prepare_cli_cmd()\n env_context = get_context_from_env_var()\n # Only extend the hive_conf if it is defined.\n if hive_conf:\n env_context.update(hive_conf)\n hive_conf_params = self._prepare_hiveconf(env_context)\n if self.mapred_queue:\n hive_conf_params.extend(\n ['-hiveconf',\n 'mapreduce.job.queuename={}'\n .format(self.mapred_queue),\n '-hiveconf',\n 'mapred.job.queue.name={}'\n .format(self.mapred_queue),\n '-hiveconf',\n 'tez.queue.name={}'\n .format(self.mapred_queue)\n ])\n\n if self.mapred_queue_priority:\n hive_conf_params.extend(\n ['-hiveconf',\n 'mapreduce.job.priority={}'\n .format(self.mapred_queue_priority)])\n\n if self.mapred_job_name:\n hive_conf_params.extend(\n ['-hiveconf',\n 'mapred.job.name={}'\n .format(self.mapred_job_name)])\n\n hive_cmd.extend(hive_conf_params)\n hive_cmd.extend(['-f', f.name])\n\n if verbose:\n self.log.info(\"%s\", \" \".join(hive_cmd))\n sub_process = subprocess.Popen(\n hive_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n cwd=tmp_dir,\n close_fds=True)\n self.sub_process = sub_process\n stdout = ''\n while True:\n line = sub_process.stdout.readline()\n if not line:\n break\n stdout += line.decode('UTF-8')\n if verbose:\n self.log.info(line.decode('UTF-8').strip())\n sub_process.wait()\n\n if sub_process.returncode:\n raise AirflowException(stdout)\n\n return stdout\n\n def test_hql(self, hql):\n \"\"\"\n Test an hql statement using the hive cli and EXPLAIN\n\n \"\"\"\n create, insert, other = [], [], []\n for query in hql.split(';'): # naive\n query_original = query\n query = query.lower().strip()\n\n if query.startswith('create table'):\n create.append(query_original)\n elif query.startswith(('set ',\n 'add jar ',\n 'create temporary function')):\n other.append(query_original)\n elif query.startswith('insert'):\n insert.append(query_original)\n other = ';'.join(other)\n for query_set in [create, insert]:\n for query in query_set:\n\n query_preview = ' '.join(query.split())[:50]\n self.log.info(\"Testing HQL [%s (...)]\", query_preview)\n if query_set == insert:\n query = other + '; explain ' + query\n else:\n query = 'explain ' + query\n try:\n self.run_cli(query, verbose=False)\n except AirflowException as e:\n message = e.args[0].split('\\n')[-2]\n self.log.info(message)\n error_loc = re.search(r'(\\d+):(\\d+)', message)\n if error_loc and error_loc.group(1).isdigit():\n lst = int(error_loc.group(1))\n begin = max(lst - 2, 0)\n end = min(lst + 3, len(query.split('\\n')))\n context = '\\n'.join(query.split('\\n')[begin:end])\n self.log.info(\"Context :\\n %s\", context)\n else:\n self.log.info(\"SUCCESS\")\n\n def load_df(\n self,\n df,\n table,\n field_dict=None,\n delimiter=',',\n encoding='utf8',\n pandas_kwargs=None, **kwargs):\n \"\"\"\n Loads a pandas DataFrame into hive.\n\n Hive data types will be inferred if not passed but column names will\n not be sanitized.\n\n :param df: DataFrame to load into a Hive table\n :type df: pandas.DataFrame\n :param table: target Hive table, use dot notation to target a\n specific database\n :type table: str\n :param field_dict: mapping from column name to hive data type.\n Note that it must be OrderedDict so as to keep columns' order.\n :type field_dict: collections.OrderedDict\n :param delimiter: field delimiter in the file\n :type delimiter: str\n :param encoding: str encoding to use when writing DataFrame to file\n :type encoding: str\n :param pandas_kwargs: passed to DataFrame.to_csv\n :type pandas_kwargs: dict\n :param kwargs: passed to self.load_file\n \"\"\"\n\n def _infer_field_types_from_df(df):\n dtype_kind_hive_type = {\n 'b': 'BOOLEAN', # boolean\n 'i': 'BIGINT', # signed integer\n 'u': 'BIGINT', # unsigned integer\n 'f': 'DOUBLE', # floating-point\n 'c': 'STRING', # complex floating-point\n 'M': 'TIMESTAMP', # datetime\n 'O': 'STRING', # object\n 'S': 'STRING', # (byte-)string\n 'U': 'STRING', # Unicode\n 'V': 'STRING' # void\n }\n\n order_type = OrderedDict()\n for col, dtype in df.dtypes.iteritems():\n order_type[col] = dtype_kind_hive_type[dtype.kind]\n return order_type\n\n if pandas_kwargs is None:\n pandas_kwargs = {}\n\n with TemporaryDirectory(prefix='airflow_hiveop_') as tmp_dir:\n with NamedTemporaryFile(dir=tmp_dir, mode=\"w\") as f:\n\n if field_dict is None:\n field_dict = _infer_field_types_from_df(df)\n\n df.to_csv(path_or_buf=f,\n sep=delimiter,\n header=False,\n index=False,\n encoding=encoding,\n date_format=\"%Y-%m-%d %H:%M:%S\",\n **pandas_kwargs)\n f.flush()\n\n return self.load_file(filepath=f.name,\n table=table,\n delimiter=delimiter,\n field_dict=field_dict,\n **kwargs)\n\n def load_file(\n self,\n filepath,\n table,\n delimiter=\",\",\n field_dict=None,\n create=True,\n overwrite=True,\n partition=None,\n recreate=False,\n tblproperties=None):\n \"\"\"\n Loads a local file into Hive\n\n Note that the table generated in Hive uses ``STORED AS textfile``\n which isn't the most efficient serialization format. If a\n large amount of data is loaded and/or if the tables gets\n queried considerably, you may want to use this operator only to\n stage the data into a temporary table before loading it into its\n final destination using a ``HiveOperator``.\n\n :param filepath: local filepath of the file to load\n :type filepath: str\n :param table: target Hive table, use dot notation to target a\n specific database\n :type table: str\n :param delimiter: field delimiter in the file\n :type delimiter: str\n :param field_dict: A dictionary of the fields name in the file\n as keys and their Hive types as values.\n Note that it must be OrderedDict so as to keep columns' order.\n :type field_dict: collections.OrderedDict\n :param create: whether to create the table if it doesn't exist\n :type create: bool\n :param overwrite: whether to overwrite the data in table or partition\n :type overwrite: bool\n :param partition: target partition as a dict of partition columns\n and values\n :type partition: dict\n :param recreate: whether to drop and recreate the table at every\n execution\n :type recreate: bool\n :param tblproperties: TBLPROPERTIES of the hive table being created\n :type tblproperties: dict\n \"\"\"\n hql = ''\n if recreate:\n hql += \"DROP TABLE IF EXISTS {table};\\n\".format(table=table)\n if create or recreate:\n if field_dict is None:\n raise ValueError(\"Must provide a field dict when creating a table\")\n fields = \",\\n \".join(\n ['`{k}` {v}'.format(k=k.strip('`'), v=v) for k, v in field_dict.items()])\n hql += \"CREATE TABLE IF NOT EXISTS {table} (\\n{fields})\\n\".format(\n table=table, fields=fields)\n if partition:\n pfields = \",\\n \".join(\n [p + \" STRING\" for p in partition])\n hql += \"PARTITIONED BY ({pfields})\\n\".format(pfields=pfields)\n hql += \"ROW FORMAT DELIMITED\\n\"\n hql += \"FIELDS TERMINATED BY '{delimiter}'\\n\".format(delimiter=delimiter)\n hql += \"STORED AS textfile\\n\"\n if tblproperties is not None:\n tprops = \", \".join(\n [\"'{0}'='{1}'\".format(k, v) for k, v in tblproperties.items()])\n hql += \"TBLPROPERTIES({tprops})\\n\".format(tprops=tprops)\n hql += \";\"\n self.log.info(hql)\n self.run_cli(hql)\n hql = \"LOAD DATA LOCAL INPATH '{filepath}' \".format(filepath=filepath)\n if overwrite:\n hql += \"OVERWRITE \"\n hql += \"INTO TABLE {table} \".format(table=table)\n if partition:\n pvals = \", \".join(\n [\"{0}='{1}'\".format(k, v) for k, v in partition.items()])\n hql += \"PARTITION ({pvals})\".format(pvals=pvals)\n\n # As a workaround for HIVE-10541, add a newline character\n # at the end of hql (AIRFLOW-2412).\n hql += ';\\n'\n\n self.log.info(hql)\n self.run_cli(hql)\n\n def kill(self):\n \"\"\"\n Kill Hive cli command\n \"\"\"\n if hasattr(self, 'sp'):\n if self.sub_process.poll() is None:\n print(\"Killing the Hive job\")\n self.sub_process.terminate()\n time.sleep(60)\n self.sub_process.kill()\n\n\nclass HiveMetastoreHook(BaseHook):\n \"\"\" Wrapper to interact with the Hive Metastore\"\"\"\n\n # java short max val\n MAX_PART_COUNT = 32767\n\n def __init__(self, metastore_conn_id='metastore_default'):\n super().__init__()\n self.conn_id = metastore_conn_id\n self.metastore = self.get_metastore_client()\n\n def __getstate__(self):\n # This is for pickling to work despite the thirft hive client not\n # being pickable\n state = dict(self.__dict__)\n del state['metastore']\n return state\n\n def __setstate__(self, d):\n self.__dict__.update(d)\n self.__dict__['metastore'] = self.get_metastore_client()\n\n def get_metastore_client(self):\n \"\"\"\n Returns a Hive thrift client.\n \"\"\"\n import hmsclient\n from thrift.protocol import TBinaryProtocol\n from thrift.transport import TSocket, TTransport\n\n conn = self._find_valid_server()\n\n if not conn:\n raise AirflowException(\"Failed to locate the valid server.\")\n\n auth_mechanism = conn.extra_dejson.get('authMechanism', 'NOSASL')\n\n if conf.get('core', 'security') == 'kerberos':\n auth_mechanism = conn.extra_dejson.get('authMechanism', 'GSSAPI')\n kerberos_service_name = conn.extra_dejson.get('kerberos_service_name', 'hive')\n\n conn_socket = TSocket.TSocket(conn.host, conn.port)\n\n if conf.get('core', 'security') == 'kerberos' \\\n and auth_mechanism == 'GSSAPI':\n try:\n import saslwrapper as sasl\n except ImportError:\n import sasl\n\n def sasl_factory():\n sasl_client = sasl.Client()\n sasl_client.setAttr(\"host\", conn.host)\n sasl_client.setAttr(\"service\", kerberos_service_name)\n sasl_client.init()\n return sasl_client\n\n from thrift_sasl import TSaslClientTransport\n transport = TSaslClientTransport(sasl_factory, \"GSSAPI\", conn_socket)\n else:\n transport = TTransport.TBufferedTransport(conn_socket)\n\n protocol = TBinaryProtocol.TBinaryProtocol(transport)\n\n return hmsclient.HMSClient(iprot=protocol)\n\n def _find_valid_server(self):\n conns = self.get_connections(self.conn_id)\n for conn in conns:\n host_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.log.info(\"Trying to connect to %s:%s\", conn.host, conn.port)\n if host_socket.connect_ex((conn.host, conn.port)) == 0:\n self.log.info(\"Connected to %s:%s\", conn.host, conn.port)\n host_socket.close()\n return conn\n else:\n self.log.error(\"Could not connect to %s:%s\", conn.host, conn.port)\n return None\n\n def get_conn(self):\n return self.metastore\n\n def check_for_partition(self, schema, table, partition):\n \"\"\"\n Checks whether a partition exists\n\n :param schema: Name of hive schema (database) @table belongs to\n :type schema: str\n :param table: Name of hive table @partition belongs to\n :type schema: str\n :partition: Expression that matches the partitions to check for\n (eg `a = 'b' AND c = 'd'`)\n :type schema: str\n :rtype: bool\n\n >>> hh = HiveMetastoreHook()\n >>> t = 'static_babynames_partitioned'\n >>> hh.check_for_partition('airflow', t, \"ds='2015-01-01'\")\n True\n \"\"\"\n with self.metastore as client:\n partitions = client.get_partitions_by_filter(\n schema, table, partition, 1)\n\n return bool(partitions)\n\n def check_for_named_partition(self, schema, table, partition_name):\n \"\"\"\n Checks whether a partition with a given name exists\n\n :param schema: Name of hive schema (database) @table belongs to\n :type schema: str\n :param table: Name of hive table @partition belongs to\n :type schema: str\n :partition: Name of the partitions to check for (eg `a=b/c=d`)\n :type schema: str\n :rtype: bool\n\n >>> hh = HiveMetastoreHook()\n >>> t = 'static_babynames_partitioned'\n >>> hh.check_for_named_partition('airflow', t, \"ds=2015-01-01\")\n True\n >>> hh.check_for_named_partition('airflow', t, \"ds=xxx\")\n False\n \"\"\"\n with self.metastore as client:\n return client.check_for_named_partition(schema, table, partition_name)\n\n def get_table(self, table_name, db='default'):\n \"\"\"Get a metastore table object\n\n >>> hh = HiveMetastoreHook()\n >>> t = hh.get_table(db='airflow', table_name='static_babynames')\n >>> t.tableName\n 'static_babynames'\n >>> [col.name for col in t.sd.cols]\n ['state', 'year', 'name', 'gender', 'num']\n \"\"\"\n if db == 'default' and '.' in table_name:\n db, table_name = table_name.split('.')[:2]\n with self.metastore as client:\n return client.get_table(dbname=db, tbl_name=table_name)\n\n def get_tables(self, db, pattern='*'):\n \"\"\"\n Get a metastore table object\n \"\"\"\n with self.metastore as client:\n tables = client.get_tables(db_name=db, pattern=pattern)\n return client.get_table_objects_by_name(db, tables)\n\n def get_databases(self, pattern='*'):\n \"\"\"\n Get a metastore table object\n \"\"\"\n with self.metastore as client:\n return client.get_databases(pattern)\n\n def get_partitions(self, schema, table_name, partition_filter=None):\n \"\"\"\n Returns a list of all partitions in a table. Works only\n for tables with less than 32767 (java short max val).\n For subpartitioned table, the number might easily exceed this.\n\n >>> hh = HiveMetastoreHook()\n >>> t = 'static_babynames_partitioned'\n >>> parts = hh.get_partitions(schema='airflow', table_name=t)\n >>> len(parts)\n 1\n >>> parts\n [{'ds': '2015-01-01'}]\n \"\"\"\n with self.metastore as client:\n table = client.get_table(dbname=schema, tbl_name=table_name)\n if len(table.partitionKeys) == 0:\n raise AirflowException(\"The table isn't partitioned\")\n else:\n if partition_filter:\n parts = client.get_partitions_by_filter(\n db_name=schema, tbl_name=table_name,\n filter=partition_filter, max_parts=HiveMetastoreHook.MAX_PART_COUNT)\n else:\n parts = client.get_partitions(\n db_name=schema, tbl_name=table_name,\n max_parts=HiveMetastoreHook.MAX_PART_COUNT)\n\n pnames = [p.name for p in table.partitionKeys]\n return [dict(zip(pnames, p.values)) for p in parts]\n\n @staticmethod\n def _get_max_partition_from_part_specs(part_specs, partition_key, filter_map):\n \"\"\"\n Helper method to get max partition of partitions with partition_key\n from part specs. key:value pair in filter_map will be used to\n filter out partitions.\n\n :param part_specs: list of partition specs.\n :type part_specs: list\n :param partition_key: partition key name.\n :type partition_key: str\n :param filter_map: partition_key:partition_value map used for partition filtering,\n e.g. {'key1': 'value1', 'key2': 'value2'}.\n Only partitions matching all partition_key:partition_value\n pairs will be considered as candidates of max partition.\n :type filter_map: map\n :return: Max partition or None if part_specs is empty.\n :rtype: basestring\n \"\"\"\n if not part_specs:\n return None\n\n # Assuming all specs have the same keys.\n if partition_key not in part_specs[0].keys():\n raise AirflowException(\"Provided partition_key {} \"\n \"is not in part_specs.\".format(partition_key))\n if filter_map:\n is_subset = set(filter_map.keys()).issubset(set(part_specs[0].keys()))\n if filter_map and not is_subset:\n raise AirflowException(\"Keys in provided filter_map {} \"\n \"are not subset of part_spec keys: {}\"\n .format(', '.join(filter_map.keys()),\n ', '.join(part_specs[0].keys())))\n\n candidates = [p_dict[partition_key] for p_dict in part_specs\n if filter_map is None or\n all(item in p_dict.items() for item in filter_map.items())]\n\n if not candidates:\n return None\n else:\n return max(candidates)\n\n def max_partition(self, schema, table_name, field=None, filter_map=None):\n \"\"\"\n Returns the maximum value for all partitions with given field in a table.\n If only one partition key exist in the table, the key will be used as field.\n filter_map should be a partition_key:partition_value map and will be used to\n filter out partitions.\n\n :param schema: schema name.\n :type schema: str\n :param table_name: table name.\n :type table_name: str\n :param field: partition key to get max partition from.\n :type field: str\n :param filter_map: partition_key:partition_value map used for partition filtering.\n :type filter_map: map\n\n >>> hh = HiveMetastoreHook()\n >>> filter_map = {'ds': '2015-01-01', 'ds': '2014-01-01'}\n >>> t = 'static_babynames_partitioned'\n >>> hh.max_partition(schema='airflow',\\\n ... table_name=t, field='ds', filter_map=filter_map)\n '2015-01-01'\n \"\"\"\n with self.metastore as client:\n table = client.get_table(dbname=schema, tbl_name=table_name)\n key_name_set = {key.name for key in table.partitionKeys}\n if len(table.partitionKeys) == 1:\n field = table.partitionKeys[0].name\n elif not field:\n raise AirflowException(\"Please specify the field you want the max \"\n \"value for.\")\n elif field not in key_name_set:\n raise AirflowException(\"Provided field is not a partition key.\")\n\n if filter_map and not set(filter_map.keys()).issubset(key_name_set):\n raise AirflowException(\"Provided filter_map contains keys \"\n \"that are not partition key.\")\n\n part_names = \\\n client.get_partition_names(schema,\n table_name,\n max_parts=HiveMetastoreHook.MAX_PART_COUNT)\n part_specs = [client.partition_name_to_spec(part_name)\n for part_name in part_names]\n\n return HiveMetastoreHook._get_max_partition_from_part_specs(part_specs,\n field,\n filter_map)\n\n def table_exists(self, table_name, db='default'):\n \"\"\"\n Check if table exists\n\n >>> hh = HiveMetastoreHook()\n >>> hh.table_exists(db='airflow', table_name='static_babynames')\n True\n >>> hh.table_exists(db='airflow', table_name='does_not_exist')\n False\n \"\"\"\n try:\n self.get_table(table_name, db)\n return True\n except Exception: # pylint: disable=broad-except\n return False\n\n\nclass HiveServer2Hook(DbApiHook):\n \"\"\"\n Wrapper around the pyhive library\n\n Notes:\n * the default authMechanism is PLAIN, to override it you\n can specify it in the ``extra`` of your connection in the UI\n * the default for run_set_variable_statements is true, if you\n are using impala you may need to set it to false in the\n ``extra`` of your connection in the UI\n \"\"\"\n conn_name_attr = 'hiveserver2_conn_id'\n default_conn_name = 'hiveserver2_default'\n supports_autocommit = False\n\n def get_conn(self, schema=None):\n \"\"\"\n Returns a Hive connection object.\n \"\"\"\n db = self.get_connection(self.hiveserver2_conn_id) # pylint: disable=no-member\n auth_mechanism = db.extra_dejson.get('authMechanism', 'NONE')\n if auth_mechanism == 'NONE' and db.login is None:\n # we need to give a username\n username = 'airflow'\n kerberos_service_name = None\n if conf.get('core', 'security') == 'kerberos':\n auth_mechanism = db.extra_dejson.get('authMechanism', 'KERBEROS')\n kerberos_service_name = db.extra_dejson.get('kerberos_service_name', 'hive')\n\n # pyhive uses GSSAPI instead of KERBEROS as a auth_mechanism identifier\n if auth_mechanism == 'GSSAPI':\n self.log.warning(\n \"Detected deprecated 'GSSAPI' for authMechanism \"\n \"for %s. Please use 'KERBEROS' instead\",\n self.hiveserver2_conn_id # pylint: disable=no-member\n )\n auth_mechanism = 'KERBEROS'\n\n from pyhive.hive import connect\n return connect(\n host=db.host,\n port=db.port,\n auth=auth_mechanism,\n kerberos_service_name=kerberos_service_name,\n username=db.login or username,\n password=db.password,\n database=schema or db.schema or 'default')\n\n def _get_results(self, hql, schema='default', fetch_size=None, hive_conf=None):\n from pyhive.exc import ProgrammingError\n if isinstance(hql, str):\n hql = [hql]\n previous_description = None\n with contextlib.closing(self.get_conn(schema)) as conn, \\\n contextlib.closing(conn.cursor()) as cur:\n cur.arraysize = fetch_size or 1000\n\n # not all query services (e.g. impala AIRFLOW-4434) support the set command\n db = self.get_connection(self.hiveserver2_conn_id) # pylint: disable=no-member\n if db.extra_dejson.get('run_set_variable_statements', True):\n env_context = get_context_from_env_var()\n if hive_conf:\n env_context.update(hive_conf)\n for k, v in env_context.items():\n cur.execute(\"set {}={}\".format(k, v))\n\n for statement in hql:\n cur.execute(statement)\n # we only get results of statements that returns\n lowered_statement = statement.lower().strip()\n if (lowered_statement.startswith('select') or\n lowered_statement.startswith('with') or\n lowered_statement.startswith('show') or\n (lowered_statement.startswith('set') and\n '=' not in lowered_statement)):\n description = cur.description\n if previous_description and previous_description != description:\n message = '''The statements are producing different descriptions:\n Current: {}\n Previous: {}'''.format(repr(description),\n repr(previous_description))\n raise ValueError(message)\n elif not previous_description:\n previous_description = description\n yield description\n try:\n # DB API 2 raises when no results are returned\n # we're silencing here as some statements in the list\n # may be `SET` or DDL\n yield from cur\n except ProgrammingError:\n self.log.debug(\"get_results returned no records\")\n\n def get_results(self, hql, schema='default', fetch_size=None, hive_conf=None):\n \"\"\"\n Get results of the provided hql in target schema.\n\n :param hql: hql to be executed.\n :type hql: str or list\n :param schema: target schema, default to 'default'.\n :type schema: str\n :param fetch_size: max size of result to fetch.\n :type fetch_size: int\n :param hive_conf: hive_conf to execute alone with the hql.\n :type hive_conf: dict\n :return: results of hql execution, dict with data (list of results) and header\n :rtype: dict\n \"\"\"\n results_iter = self._get_results(hql, schema,\n fetch_size=fetch_size, hive_conf=hive_conf)\n header = next(results_iter)\n results = {\n 'data': list(results_iter),\n 'header': header\n }\n return results\n\n def to_csv(\n self,\n hql,\n csv_filepath,\n schema='default',\n delimiter=',',\n lineterminator='\\r\\n',\n output_header=True,\n fetch_size=1000,\n hive_conf=None):\n \"\"\"\n Execute hql in target schema and write results to a csv file.\n\n :param hql: hql to be executed.\n :type hql: str or list\n :param csv_filepath: filepath of csv to write results into.\n :type csv_filepath: str\n :param schema: target schema, default to 'default'.\n :type schema: str\n :param delimiter: delimiter of the csv file, default to ','.\n :type delimiter: str\n :param lineterminator: lineterminator of the csv file.\n :type lineterminator: str\n :param output_header: header of the csv file, default to True.\n :type output_header: bool\n :param fetch_size: number of result rows to write into the csv file, default to 1000.\n :type fetch_size: int\n :param hive_conf: hive_conf to execute alone with the hql.\n :type hive_conf: dict\n\n \"\"\"\n\n results_iter = self._get_results(hql, schema,\n fetch_size=fetch_size, hive_conf=hive_conf)\n header = next(results_iter)\n message = None\n\n i = 0\n with open(csv_filepath, 'wb') as file:\n writer = csv.writer(file,\n delimiter=delimiter,\n lineterminator=lineterminator,\n encoding='utf-8')\n try:\n if output_header:\n self.log.debug('Cursor description is %s', header)\n writer.writerow([c[0] for c in header])\n\n for i, row in enumerate(results_iter, 1):\n writer.writerow(row)\n if i % fetch_size == 0:\n self.log.info(\"Written %s rows so far.\", i)\n except ValueError as exception:\n message = str(exception)\n\n if message:\n # need to clean up the file first\n os.remove(csv_filepath)\n raise ValueError(message)\n\n self.log.info(\"Done. Loaded a total of %s rows.\", i)\n\n def get_records(self, hql, schema='default', hive_conf=None):\n \"\"\"\n Get a set of records from a Hive query.\n\n :param hql: hql to be executed.\n :type hql: str or list\n :param schema: target schema, default to 'default'.\n :type schema: str\n :param hive_conf: hive_conf to execute alone with the hql.\n :type hive_conf: dict\n :return: result of hive execution\n :rtype: list\n\n >>> hh = HiveServer2Hook()\n >>> sql = \"SELECT * FROM airflow.static_babynames LIMIT 100\"\n >>> len(hh.get_records(sql))\n 100\n \"\"\"\n return self.get_results(hql, schema=schema, hive_conf=hive_conf)['data']\n\n def get_pandas_df(self, hql, schema='default', hive_conf=None):\n \"\"\"\n Get a pandas dataframe from a Hive query\n\n :param hql: hql to be executed.\n :type hql: str or list\n :param schema: target schema, default to 'default'.\n :type schema: str\n :param hive_conf: hive_conf to execute alone with the hql.\n :type hive_conf: dict\n :return: result of hive execution\n :rtype: DataFrame\n\n >>> hh = HiveServer2Hook()\n >>> sql = \"SELECT * FROM airflow.static_babynames LIMIT 100\"\n >>> df = hh.get_pandas_df(sql)\n >>> len(df.index)\n 100\n\n :return: pandas.DateFrame\n \"\"\"\n import pandas as pd\n res = self.get_results(hql, schema=schema, hive_conf=hive_conf)\n df = pd.DataFrame(res['data'])\n df.columns = [c[0] for c in res['header']]\n return df\n"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
schwieni/acados | [
"a8aad1db6917739227c3da436f6f8e729e2872aa"
] | [
"interfaces/acados_template/acados_template/acados_sim_solver.py"
] | [
"# -*- coding: future_fstrings -*-\n#\n# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren,\n# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor,\n# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan,\n# Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl\n#\n# This file is part of acados.\n#\n# The 2-Clause BSD License\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.;\n#\n\nimport sys, os, json\n\nimport numpy as np\n\nfrom ctypes import *\nfrom copy import deepcopy\n\nfrom .generate_c_code_explicit_ode import generate_c_code_explicit_ode\nfrom .generate_c_code_implicit_ode import generate_c_code_implicit_ode\nfrom .generate_c_code_gnsf import generate_c_code_gnsf\nfrom .acados_sim import AcadosSim\nfrom .acados_ocp import AcadosOcp\nfrom .acados_model import acados_model_strip_casadi_symbolics\nfrom .utils import is_column, render_template, format_class_dict, np_array_to_list,\\\n make_model_consistent, set_up_imported_gnsf_model, get_python_interface_path\n\n\ndef make_sim_dims_consistent(acados_sim):\n dims = acados_sim.dims\n model = acados_sim.model\n # nx\n if is_column(model.x):\n dims.nx = model.x.shape[0]\n else:\n raise Exception(\"model.x should be column vector!\")\n\n # nu\n if is_column(model.u):\n dims.nu = model.u.shape[0]\n elif model.u == None or model.u == []:\n dims.nu = 0\n else:\n raise Exception(\"model.u should be column vector or None!\")\n\n # nz\n if is_column(model.z):\n dims.nz = model.z.shape[0]\n elif model.z == None or model.z == []:\n dims.nz = 0\n else:\n raise Exception(\"model.z should be column vector or None!\")\n\n # np\n if is_column(model.p):\n dims.np = model.p.shape[0]\n elif model.p == None or model.p == []:\n dims.np = 0\n else:\n raise Exception(\"model.p should be column vector or None!\")\n\n\ndef get_sim_layout():\n python_interface_path = get_python_interface_path()\n abs_path = os.path.join(python_interface_path, 'acados_sim_layout.json')\n with open(abs_path, 'r') as f:\n sim_layout = json.load(f)\n return sim_layout\n\n\ndef sim_formulation_json_dump(acados_sim, json_file='acados_sim.json'):\n # Load acados_sim structure description\n sim_layout = get_sim_layout()\n\n # Copy input sim object dictionary\n sim_dict = dict(deepcopy(acados_sim).__dict__)\n\n for key, v in sim_layout.items():\n # skip non dict attributes\n if not isinstance(v, dict): continue\n # Copy sim object attributes dictionaries\n sim_dict[key]=dict(getattr(acados_sim, key).__dict__)\n\n sim_dict['model'] = acados_model_strip_casadi_symbolics(sim_dict['model'])\n sim_json = format_class_dict(sim_dict)\n\n with open(json_file, 'w') as f:\n json.dump(sim_json, f, default=np_array_to_list, indent=4, sort_keys=True)\n\n\ndef sim_render_templates(json_file, model_name, code_export_dir):\n # setting up loader and environment\n json_path = os.path.join(os.getcwd(), json_file)\n\n if not os.path.exists(json_path):\n raise Exception(f\"{json_path} not found!\")\n\n template_dir = code_export_dir\n\n ## Render templates\n in_file = 'acados_sim_solver.in.c'\n out_file = f'acados_sim_solver_{model_name}.c'\n render_template(in_file, out_file, template_dir, json_path)\n\n in_file = 'acados_sim_solver.in.h'\n out_file = f'acados_sim_solver_{model_name}.h'\n render_template(in_file, out_file, template_dir, json_path)\n\n in_file = 'Makefile.in'\n out_file = f'Makefile'\n render_template(in_file, out_file, template_dir, json_path)\n\n in_file = 'main_sim.in.c'\n out_file = f'main_sim_{model_name}.c'\n render_template(in_file, out_file, template_dir, json_path)\n\n ## folder model\n template_dir = os.path.join(code_export_dir, model_name + '_model')\n\n in_file = 'model.in.h'\n out_file = f'{model_name}_model.h'\n render_template(in_file, out_file, template_dir, json_path)\n\n\ndef sim_generate_casadi_functions(acados_sim):\n model = acados_sim.model\n model = make_model_consistent(model)\n\n integrator_type = acados_sim.solver_options.integrator_type\n\n opts = dict(generate_hess = acados_sim.solver_options.sens_hess,\n code_export_directory = acados_sim.code_export_directory)\n # generate external functions\n if integrator_type == 'ERK':\n generate_c_code_explicit_ode(model, opts)\n elif integrator_type == 'IRK':\n generate_c_code_implicit_ode(model, opts)\n elif integrator_type == 'GNSF':\n generate_c_code_gnsf(model, opts)\n\nclass AcadosSimSolver:\n \"\"\"\n Class to interact with the acados integrator C object.\n\n :param acados_sim: type :py:class:`acados_template.acados_ocp.AcadosOcp` (takes values to generate an instance :py:class:`acados_template.acados_sim.AcadosSim`) or :py:class:`acados_template.acados_sim.AcadosSim`\n :param json_file: Default: 'acados_sim.json'\n :param build: Default: True\n \"\"\"\n def __init__(self, acados_sim_, json_file='acados_sim.json', build=True):\n\n self.solver_created = False\n\n if isinstance(acados_sim_, AcadosOcp):\n # set up acados_sim_\n acados_sim = AcadosSim()\n acados_sim.model = acados_sim_.model\n acados_sim.dims.nx = acados_sim_.dims.nx\n acados_sim.dims.nu = acados_sim_.dims.nu\n acados_sim.dims.nz = acados_sim_.dims.nz\n acados_sim.dims.np = acados_sim_.dims.np\n acados_sim.solver_options.integrator_type = acados_sim_.solver_options.integrator_type\n acados_sim.code_export_directory = acados_sim_.code_export_directory\n\n elif isinstance(acados_sim_, AcadosSim):\n acados_sim = acados_sim_\n\n acados_sim.__problem_class = 'SIM'\n\n model_name = acados_sim.model.name\n make_sim_dims_consistent(acados_sim)\n\n # reuse existing json and casadi functions, when creating integrator from ocp\n if isinstance(acados_sim_, AcadosSim):\n if acados_sim.solver_options.integrator_type == 'GNSF':\n set_up_imported_gnsf_model(acados_sim)\n\n sim_generate_casadi_functions(acados_sim)\n sim_formulation_json_dump(acados_sim, json_file)\n\n if build:\n # render templates\n code_export_dir = acados_sim.code_export_directory\n sim_render_templates(json_file, model_name, code_export_dir)\n\n ## Compile solver\n cwd = os.getcwd()\n os.chdir(code_export_dir)\n os.system('make sim_shared_lib')\n os.chdir(cwd)\n\n self.sim_struct = acados_sim\n model_name = self.sim_struct.model.name\n self.model_name = model_name\n\n # Ctypes\n shared_lib = f'{code_export_dir}/libacados_sim_solver_{model_name}.so'\n self.shared_lib = CDLL(shared_lib)\n\n\n # create capsule\n getattr(self.shared_lib, f\"{model_name}_acados_sim_solver_create_capsule\").restype = c_void_p\n self.capsule = getattr(self.shared_lib, f\"{model_name}_acados_sim_solver_create_capsule\")()\n\n # create solver\n getattr(self.shared_lib, f\"{model_name}_acados_sim_create\").argtypes = [c_void_p]\n getattr(self.shared_lib, f\"{model_name}_acados_sim_create\").restype = c_int\n assert getattr(self.shared_lib, f\"{model_name}_acados_sim_create\")(self.capsule)==0\n self.solver_created = True\n\n getattr(self.shared_lib, f\"{model_name}_acados_get_sim_opts\").argtypes = [c_void_p]\n getattr(self.shared_lib, f\"{model_name}_acados_get_sim_opts\").restype = c_void_p\n self.sim_opts = getattr(self.shared_lib, f\"{model_name}_acados_get_sim_opts\")(self.capsule)\n\n getattr(self.shared_lib, f\"{model_name}_acados_get_sim_dims\").argtypes = [c_void_p]\n getattr(self.shared_lib, f\"{model_name}_acados_get_sim_dims\").restype = c_void_p\n self.sim_dims = getattr(self.shared_lib, f\"{model_name}_acados_get_sim_dims\")(self.capsule)\n\n getattr(self.shared_lib, f\"{model_name}_acados_get_sim_config\").argtypes = [c_void_p]\n getattr(self.shared_lib, f\"{model_name}_acados_get_sim_config\").restype = c_void_p\n self.sim_config = getattr(self.shared_lib, f\"{model_name}_acados_get_sim_config\")(self.capsule)\n\n getattr(self.shared_lib, f\"{model_name}_acados_get_sim_out\").argtypes = [c_void_p]\n getattr(self.shared_lib, f\"{model_name}_acados_get_sim_out\").restype = c_void_p\n self.sim_out = getattr(self.shared_lib, f\"{model_name}_acados_get_sim_out\")(self.capsule)\n\n getattr(self.shared_lib, f\"{model_name}_acados_get_sim_in\").argtypes = [c_void_p]\n getattr(self.shared_lib, f\"{model_name}_acados_get_sim_in\").restype = c_void_p\n self.sim_in = getattr(self.shared_lib, f\"{model_name}_acados_get_sim_in\")(self.capsule)\n\n getattr(self.shared_lib, f\"{model_name}_acados_get_sim_solver\").argtypes = [c_void_p]\n getattr(self.shared_lib, f\"{model_name}_acados_get_sim_solver\").restype = c_void_p\n self.sim_solver = getattr(self.shared_lib, f\"{model_name}_acados_get_sim_solver\")(self.capsule)\n\n nu = self.sim_struct.dims.nu\n nx = self.sim_struct.dims.nx\n nz = self.sim_struct.dims.nz\n self.gettable = {\n 'x': nx,\n 'xn': nx,\n 'u': nu,\n 'z': nz,\n 'S_forw': nx*(nx+nu),\n 'Sx': nx*nx,\n 'Su': nx*nu,\n 'S_adj': nx+nu,\n 'S_hess': (nx+nu)*(nx+nu),\n 'S_algebraic': (nz)*(nx+nu),\n }\n\n self.settable = ['S_adj', 'T', 'x', 'u', 'xdot', 'z', 'p'] # S_forw\n\n\n def solve(self):\n \"\"\"\n Solve the simulation problem with current input.\n \"\"\"\n getattr(self.shared_lib, f\"{self.model_name}_acados_sim_solve\").argtypes = [c_void_p]\n getattr(self.shared_lib, f\"{self.model_name}_acados_sim_solve\").restype = c_int\n\n status = getattr(self.shared_lib, f\"{self.model_name}_acados_sim_solve\")(self.capsule)\n return status\n\n\n def get(self, field_):\n \"\"\"\n Get the last solution of the solver.\n\n :param str field: string in ['x', 'u', 'z', 'S_forw', 'Sx', 'Su', 'S_adj', 'S_hess', 'S_algebraic']\n \"\"\"\n field = field_\n field = field.encode('utf-8')\n\n if field_ in self.gettable.keys():\n\n # allocate array\n dims = self.gettable[field_]\n out = np.ascontiguousarray(np.zeros((dims,)), dtype=np.float64)\n out_data = cast(out.ctypes.data, POINTER(c_double))\n\n self.shared_lib.sim_out_get.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p, c_void_p]\n self.shared_lib.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, out_data)\n\n if field_ == 'S_forw':\n nu = self.sim_struct.dims.nu\n nx = self.sim_struct.dims.nx\n out = out.reshape(nx, nx+nu, order='F')\n elif field_ == 'Sx':\n nx = self.sim_struct.dims.nx\n out = out.reshape(nx, nx, order='F')\n elif field_ == 'Su':\n nx = self.sim_struct.dims.nx\n nu = self.sim_struct.dims.nu\n out = out.reshape(nx, nu, order='F')\n elif field_ == 'S_hess':\n nx = self.sim_struct.dims.nx\n nu = self.sim_struct.dims.nu\n out = out.reshape(nx+nu, nx+nu, order='F')\n elif field_ == 'S_algebraic':\n nx = self.sim_struct.dims.nx\n nu = self.sim_struct.dims.nu\n nz = self.sim_struct.dims.nz\n out = out.reshape(nz, nx+nu, order='F')\n else:\n raise Exception(f'AcadosSimSolver.get(): Unknown field {field_},' \\\n f' available fields are {\", \".join(self.gettable.keys())}')\n\n return out\n\n\n def set(self, field_, value_):\n \"\"\"\n Set numerical data inside the solver.\n\n :param field: string in ['p', 'S_adj', 'T', 'x', 'u', 'xdot', 'z']\n :param value: the value with appropriate size.\n \"\"\"\n # cast value_ to avoid conversion issues\n if isinstance(value_, (float, int)):\n value_ = np.array([value_])\n\n value_ = value_.astype(float)\n value_data = cast(value_.ctypes.data, POINTER(c_double))\n value_data_p = cast((value_data), c_void_p)\n\n field = field_\n field = field.encode('utf-8')\n\n # treat parameters separately\n if field_ == 'p':\n model_name = self.sim_struct.model.name\n getattr(self.shared_lib, f\"{model_name}_acados_sim_update_params\").argtypes = [c_void_p, POINTER(c_double), c_int]\n value_data = cast(value_.ctypes.data, POINTER(c_double))\n getattr(self.shared_lib, f\"{model_name}_acados_sim_update_params\")(self.capsule, value_data, value_.shape[0])\n return\n else:\n # dimension check\n dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc)\n dims_data = cast(dims.ctypes.data, POINTER(c_int))\n\n self.shared_lib.sim_dims_get_from_attr.argtypes = [c_void_p, c_void_p, c_char_p, POINTER(c_int)]\n self.shared_lib.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, dims_data)\n\n value_ = np.ravel(value_, order='F')\n\n value_shape = value_.shape\n if len(value_shape) == 1:\n value_shape = (value_shape[0], 0)\n\n if value_shape != tuple(dims):\n raise Exception('AcadosSimSolver.set(): mismatching dimension' \\\n ' for field \"{}\" with dimension {} (you have {})'.format(field_, tuple(dims), value_shape))\n\n # set\n if field_ in ['xdot', 'z']:\n self.shared_lib.sim_solver_set.argtypes = [c_void_p, c_char_p, c_void_p]\n self.shared_lib.sim_solver_set(self.sim_solver, field, value_data_p)\n elif field_ in self.settable:\n self.shared_lib.sim_in_set.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p, c_void_p]\n self.shared_lib.sim_in_set(self.sim_config, self.sim_dims, self.sim_in, field, value_data_p)\n else:\n raise Exception(f'AcadosSimSolver.set(): Unknown field {field_},' \\\n f' available fields are {\", \".join(self.settable)}')\n\n return\n\n\n def __del__(self):\n\n if self.solver_created:\n getattr(self.shared_lib, f\"{self.model_name}_acados_sim_free\").argtypes = [c_void_p]\n getattr(self.shared_lib, f\"{self.model_name}_acados_sim_free\").restype = c_int\n getattr(self.shared_lib, f\"{self.model_name}_acados_sim_free\")(self.capsule)\n\n getattr(self.shared_lib, f\"{self.model_name}_acados_sim_solver_free_capsule\").argtypes = [c_void_p]\n getattr(self.shared_lib, f\"{self.model_name}_acados_sim_solver_free_capsule\").restype = c_int\n getattr(self.shared_lib, f\"{self.model_name}_acados_sim_solver_free_capsule\")(self.capsule)\n\n try:\n self.dlclose(self.shared_lib._handle)\n except:\n pass\n"
] | [
[
"numpy.ravel",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
xr0038/jasmine_warpfield | [
"d3dc8306c30c955eea997e7cb69c1910df6a9515"
] | [
"challenge/case1/generate_case1.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom argparse import ArgumentParser as ap\nfrom astropy.table import QTable\nfrom astropy.coordinates import SkyCoord, Longitude, Latitude, Angle\nimport numpy as np\nimport astropy.units as u\nimport warpfield as w\nfrom warpfield.DUMMY import get_jasmine\n\ndescription='''\nThis script generates Case-1 astrometry challenges. The telescope used\nin this challenge is distortion-free. Sources are retrieved from the\nGaia EDR3 catalog. A list of source positions on the focal plane and\nICRS coordinates is provided. Solve the field center and the position angle.\n'''.strip()\n\n\n\nseed = 42\nnp.random.seed(seed)\n\n\ndef generate_challenge(filename):\n lon = Longitude(np.random.uniform(0,360)*u.deg)\n lat = Latitude(np.random.uniform(-90,90)*u.deg)\n pa = Angle(np.random.uniform(0,360)*u.deg)\n\n pointing = SkyCoord(lon, lat, frame='icrs')\n jasmine = get_jasmine(pointing, pa)\n\n radius = Angle(0.3*u.deg)\n sources = w.retrieve_gaia_sources(pointing,radius)\n\n position = jasmine.observe(sources)[0]\n\n table = QTable(\n [\n position.x.array*u.um,\n position.y.array*u.um,\n position.ra.array*u.deg,\n position.dec.array*u.deg,\n ],\n names = ('x','y','ra','dec'),\n meta = {\n 'keywords': {\n 'pointing_ra' : {'value': lon.deg},\n 'pointing_dec' : {'value': lat.deg},\n 'position_angle': {'value': pa.deg},\n },\n 'comments': [description,]\n })\n print(table)\n table.write(filename, format='ascii.ipac', overwrite=True)\n\n\nif __name__ == '__main__':\n parser = ap(description='Generate Case-1 challenges')\n parser.add_argument(\n '-n', '--num', type=int, default=5,\n help='the number of challenges')\n\n args = parser.parse_args()\n\n for n in range(args.num):\n filename=f'case1_challenge_{n:02d}.txt'\n generate_challenge(filename)\n"
] | [
[
"numpy.random.uniform",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Kammerlo/keras-yolo3-serving | [
"9cc134388aa6f325f3b35f0a05e9cab380f81bb3"
] | [
"utils/letterboxlayer.py"
] | [
"from keras.engine import Layer\r\nimport tensorflow as tf\r\n\r\nclass LetterBoxLayer(Layer):\r\n\r\n def __init__(self,net_size,**kwargs):\r\n super(LetterBoxLayer, self).__init__(**kwargs)\r\n self.net_size = net_size\r\n\r\n # save config to save and load the keras model correctly\r\n def get_config(self):\r\n config = {\r\n 'net_size': self.net_size\r\n }\r\n base_config = super(LetterBoxLayer, self).get_config()\r\n return dict(list(base_config.items()) + list(config.items()))\r\n\r\n # this will work only for single images passed to the layer\r\n def call(self,img):\r\n ## This is just compatible with tf.__version__ >= 1.13\r\n # resized = tf.image.resize_images(\r\n # img,\r\n # (self.net_size,self.net_size),\r\n # preserve_aspect_ratio=True,method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\r\n\r\n\r\n ## For older versions use this\r\n prev_shape = tf.shape(img)\r\n max_ = tf.maximum(prev_shape[0],prev_shape[1])\r\n ratio = tf.cast(max_,tf.float32) / tf.constant(self.net_size,dtype=tf.float32)\r\n new_width = tf.cast(tf.cast(prev_shape[1],tf.float32) / ratio,tf.int32)\r\n new_height = tf.cast(tf.cast(prev_shape[0],tf.float32) / ratio,tf.int32)\r\n resized = tf.image.resize_images(img,(new_height,new_width))\r\n\r\n\r\n img_shape = tf.shape(resized)\r\n height_offset = (self.net_size - img_shape[0]) / 2\r\n width_offset = (self.net_size - img_shape[1]) / 2\r\n padded = tf.image.pad_to_bounding_box(\r\n image=resized,\r\n offset_height=tf.cast(height_offset,dtype=tf.int32),\r\n offset_width=tf.cast(width_offset,dtype=tf.int32),\r\n target_height=self.net_size,\r\n target_width=self.net_size) / 255.0\r\n expanded = tf.expand_dims(padded,0)\r\n\r\n return [expanded,prev_shape]\r\n\r\n\r\n\r\n\r\n def compute_output_shape(self,input_shape):\r\n return [(1,self.net_size,self.net_size,3),(None,2)]"
] | [
[
"tensorflow.constant",
"tensorflow.shape",
"tensorflow.maximum",
"tensorflow.image.resize_images",
"tensorflow.cast",
"tensorflow.expand_dims"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
zhut19/straxen | [
"25b92dd4f18b51700e6df83b230e58ec3bbb7163",
"ffcf06ad86471caf11cc831f2ff68d70b59464af"
] | [
"tests/test_peaklet_processing.py",
"tests/test_channel_split.py"
] | [
"import numpy as np\nfrom hypothesis import given, settings\nimport hypothesis.strategies as strat\n\nimport strax\nfrom strax.testutils import fake_hits\nimport straxen\nfrom straxen.plugins.peaklet_processing import get_tight_coin\n\n\n@settings(deadline=None)\n@given(strat.lists(strat.integers(min_value=0, max_value=10),\n min_size=8, max_size=8, unique=True),\n )\ndef test_create_outside_peaks_region(time):\n time = np.sort(time)\n time_intervals = np.zeros(len(time)//2, strax.time_dt_fields)\n time_intervals['time'] = time[::2]\n time_intervals['length'] = time[1::2] - time[::2]\n time_intervals['dt'] = 1\n\n st = straxen.contexts.demo()\n p = st.get_single_plugin('0', 'peaklets')\n outside = p.create_outside_peaks_region(time_intervals, 0, np.max(time))\n\n touching = strax.touching_windows(outside, time_intervals, window=0)\n\n for tw in touching:\n print(tw)\n assert np.diff(tw) == 0, 'Intervals overlap although they should not!'\n\n\ndef test_n_hits():\n if not straxen.utilix_is_configured():\n return\n records = np.zeros(2, dtype=strax.record_dtype())\n records['length'] = 5\n records['pulse_length'] = 5\n records['dt'] = 1\n records['channel'] = [0, 1]\n records['data'][0, :5] = [0, 1, 1, 0, 1]\n records['data'][1, :5] = [0, 1, 0, 0, 0]\n\n st = straxen.contexts.xenonnt_online()\n st.set_config({'hit_min_amplitude': 1})\n p = st.get_single_plugin('0', 'peaklets')\n res = p.compute(records, 0, 999)\n peaklets = res['peaklets']\n assert peaklets['n_hits'] == 3, f\"Peaklet has the wrong number of hits!\"\n\n\n@given(fake_hits,\n strat.lists(elements=strat.integers(0, 9), min_size=20))\n@settings(deadline=None)\ndef test_tight_coincidence(hits, channel):\n hits['area'] = 1\n hits['channel'] = channel[:len(hits)] # In case there are less channel then hits (unlikely)\n gap_threshold = 10\n peaks = strax.find_peaks(hits,\n adc_to_pe=np.ones(10),\n right_extension=0, left_extension=0,\n gap_threshold=gap_threshold,\n min_channels=1,\n min_area=0)\n\n peaks_max_time = peaks['time'] + peaks['length']//2\n hits_max_time = hits['time'] + hits['length']//2\n\n left = 5\n right = 5\n tight_coin, tight_coin_channel = get_tight_coin(hits_max_time,\n hits['channel'],\n peaks_max_time,\n left,\n right,\n )\n for ind, p_max_t in enumerate(peaks_max_time):\n m_hits_in_peak = (hits_max_time >= (p_max_t - left))\n m_hits_in_peak &= (hits_max_time <= (p_max_t + right))\n n_hits = np.sum(m_hits_in_peak)\n n_channel = len(np.unique(hits[m_hits_in_peak]['channel']))\n assert n_hits == tight_coin[ind], 'Wrong number of tight hits'\n assert n_channel == tight_coin_channel[ind], f'Wrong number of tight channel got {tight_coin_channel[ind]}, but expectd {n_channel}' # noqa\n",
"import numpy as np\nimport hypothesis\n\nimport strax.testutils\nimport straxen\n\n\ndef channel_split_naive(r, channel_ranges):\n \"\"\"Slower but simpler implementation of straxen.split_channel_ranges\"\"\"\n results = []\n for left, right in channel_ranges:\n results.append(r[np.in1d(r['channel'], np.arange(left, right + 1))])\n return results\n\n\[email protected](deadline=None)\[email protected](strax.testutils.several_fake_records)\ndef test_channel_split(records):\n channel_range = np.asarray([[0, 0], [1, 2], [3, 3], [4, 999]])\n result = list(straxen.split_channel_ranges(records, channel_range))\n result_2 = channel_split_naive(records, channel_range)\n\n assert len(result) == len(result_2)\n for i, _ in enumerate(result):\n np.testing.assert_array_equal(\n np.unique(result[i]['channel']),\n np.unique(result_2[i]['channel']))\n np.testing.assert_array_equal(result[i], result_2[i])\n"
] | [
[
"numpy.unique",
"numpy.sort",
"numpy.ones",
"numpy.max",
"numpy.diff",
"numpy.sum"
],
[
"numpy.asarray",
"numpy.arange",
"numpy.testing.assert_array_equal",
"numpy.unique"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jacobtomlinson/cuxfilter | [
"0b88a6b609d993b8d11629763c35dfb2b2581927"
] | [
"python/cuxfilter/tests/test_dashboard.py"
] | [
"import pytest\n\nimport cuxfilter\nimport cudf\nimport pandas as pd\nimport numpy as np\n\n\nclass TestDashBoard:\n\n df = cudf.DataFrame(\n {\"key\": [0, 1, 2, 3, 4], \"val\": [float(i + 10) for i in range(5)]}\n )\n cux_df = cuxfilter.DataFrame.from_dataframe(df)\n dashboard = cux_df.dashboard(charts=[], title=\"test_title\")\n\n def test_variables(self):\n assert self.dashboard._data.equals(self.df)\n assert self.dashboard.title == \"test_title\"\n assert (\n self.dashboard._dashboard.__class__\n == cuxfilter.layouts.single_feature\n )\n assert self.dashboard._theme == cuxfilter.themes.light\n assert self.dashboard.data_size_widget is True\n assert list(self.dashboard._charts.keys()) == [\"_datasize_indicator\"]\n assert self.dashboard._data_tiles == {}\n assert self.dashboard._query_str_dict == {}\n assert self.dashboard._active_view == \"\"\n\n def test_add_charts(self):\n bac = cuxfilter.charts.bokeh.bar(\"key\")\n bac.chart_type = \"chart_1\"\n for _ in range(3):\n bac = cuxfilter.charts.bokeh.bar(\"key\")\n bac.chart_type = \"chart_\" + str(_ + 1)\n self.dashboard.add_charts([bac])\n\n assert list(self.dashboard._charts.keys()) == [\n \"_datasize_indicator\",\n \"key_chart_1\",\n \"key_chart_2\",\n \"key_chart_3\",\n ]\n\n @pytest.mark.parametrize(\n \"query, inplace, result1, result2\",\n [\n (\n \"key<3\",\n True,\n None,\n \" key val\\n0 0 10.0\\n1 1 11.0\\n2 2 12.0\",\n ),\n (\n \"key<3\",\n False,\n \" key val\\n0 0 10.0\\n1 1 11.0\\n2 2 12.0\",\n None,\n ),\n ],\n )\n def test__query(self, query, inplace, result1, result2):\n df = cudf.DataFrame(\n {\"key\": [0, 1, 2, 3, 4], \"val\": [float(i + 10) for i in range(5)]}\n )\n cux_df = cuxfilter.DataFrame.from_dataframe(df.copy())\n dashboard = cux_df.dashboard(charts=[], title=\"test_title\")\n query_res = dashboard._query(query_str=query, inplace=inplace)\n\n if query_res is not None:\n assert query_res.to_string() == result1\n else:\n assert query_res == result1\n\n if result2 is not None:\n assert dashboard._data.to_string() == result2\n else:\n assert dashboard._data.equals(df)\n\n @pytest.mark.parametrize(\n \"query_dict, query_str\",\n [({\"col_1_chart\": \"6<=col_1<=9\"}, \"6<=col_1<=9\"), ({}, \"\")],\n )\n def test__generate_query_str(self, query_dict, query_str):\n self.dashboard._query_str_dict = query_dict\n assert self.dashboard._generate_query_str() == query_str\n\n @pytest.mark.parametrize(\n \"active_view, result\",\n [\n (\n \"\",\n (\n \" key val\\n0 0 10.0\\n1 1 11.0\\n2\"\n \" 2 12.0\\n3 3 13.0\\n4 4 14.0\"\n ),\n ),\n (\n \"key_chart_1\",\n (\n \" key val\\n0 0 10.0\\n1 1 11.0\\n2\"\n \" 2 12.0\\n3 3 13.0\"\n ),\n ),\n ],\n )\n def test_export(self, active_view, result):\n bac = cuxfilter.charts.bokeh.bar(\"key\")\n bac.chart_type = \"chart_1\"\n self.dashboard.add_charts([bac])\n self.dashboard._query_str_dict = {\"key_chart_1\": \"0<=key<=3\"}\n self.dashboard._active_view = active_view\n\n assert self.dashboard.export().to_string() == result\n\n # unit tests for datatile and query functions are already\n # present in core_aggregate and core_non_aggregate test files\n\n # integrated tests\n @pytest.mark.parametrize(\n \"active_view, passive_view, result\",\n [\n (\n \"key_line\",\n \"val_bar\",\n pd.DataFrame(\n {\n 0: {0: 1.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0},\n 1: {0: 1.0, 1: 1.0, 2: 0.0, 3: 0.0, 4: 0.0},\n 2: {0: 1.0, 1: 1.0, 2: 1.0, 3: 0.0, 4: 0.0},\n 3: {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 0.0},\n 4: {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0},\n }\n ),\n ),\n (\"val_bar\", \"key_line\", None),\n ],\n )\n def test_calc_data_tiles(self, active_view, passive_view, result):\n df = cudf.DataFrame(\n {\"key\": [0, 1, 2, 3, 4], \"val\": [float(i + 10) for i in range(5)]}\n )\n cux_df = cuxfilter.DataFrame.from_dataframe(df)\n bac = cuxfilter.charts.bokeh.line(\"key\", \"val\")\n bac.use_data_tiles = False\n bac1 = cuxfilter.charts.bokeh.bar(\"val\")\n dashboard = cux_df.dashboard(\n charts=[bac, bac1],\n title=\"test_title\",\n layout=cuxfilter.layouts.double_feature,\n )\n dashboard._active_view = active_view\n dashboard._calc_data_tiles()\n\n if result is None:\n assert dashboard._data_tiles[passive_view] is result\n else:\n assert dashboard._data_tiles[passive_view].equals(result)\n\n assert (\n dashboard._charts[dashboard._active_view].datatile_loaded_state\n is True\n )\n\n @pytest.mark.parametrize(\n \"query_tuple, result\",\n [\n ((2, 4), [0, 0, 1, 1]),\n ((2, 2), [0, 0, 1, 0]),\n ((0, 0), [1, 0, 0, 0]),\n ((0, 4), [1, 1, 1, 1]),\n ],\n )\n def test_query_datatiles_by_range(self, query_tuple, result):\n df = cudf.DataFrame(\n {\"key\": [0, 1, 2, 3, 4], \"val\": [float(i + 10) for i in range(5)]}\n )\n cux_df = cuxfilter.DataFrame.from_dataframe(df)\n bac = cuxfilter.charts.bokeh.line(\"key\", \"val\")\n bac1 = cuxfilter.charts.bokeh.bar(\"val\")\n dashboard = cux_df.dashboard(\n charts=[bac, bac1],\n title=\"test_title\",\n layout=cuxfilter.layouts.double_feature,\n )\n dashboard._active_view = bac.name\n dashboard._calc_data_tiles()\n dashboard._query_datatiles_by_range(query_tuple=query_tuple)\n\n assert all(bac1.source.data[\"top\"] == result)\n\n @pytest.mark.parametrize(\n \"old_indices, new_indices, prev_result, result\",\n [\n ([], [1], [1, 1, 1, 2], [0, 1, 0, 0]),\n ([1], [1], [0, 1, 0, 0], [0, 1, 0, 0]),\n ([1], [1, 2], [0, 1, 0, 0], [0, 1, 1, 0]),\n ([1, 2], [2], [0, 1, 1, 0], [0, 0, 1, 0]),\n ],\n )\n def test_query_datatiles_by_indices(\n self, old_indices, new_indices, prev_result, result\n ):\n df = cudf.DataFrame(\n {\"key\": [0, 1, 2, 3, 4], \"val\": [float(i + 10) for i in range(5)]}\n )\n cux_df = cuxfilter.DataFrame.from_dataframe(df)\n bac = cuxfilter.charts.bokeh.line(\"key\", \"val\")\n bac1 = cuxfilter.charts.bokeh.bar(\"val\")\n dashboard = cux_df.dashboard(\n charts=[bac, bac1],\n title=\"test_title\",\n layout=cuxfilter.layouts.double_feature,\n )\n dashboard._active_view = bac.name\n dashboard._calc_data_tiles(cumsum=False)\n\n bac1.source.data[\"top\"] = np.array(prev_result)\n dashboard._query_datatiles_by_indices(\n old_indices=old_indices, new_indices=new_indices\n )\n\n assert all(bac1.source.data[\"top\"] == result)\n\n def test_reset_current_view(self):\n df = cudf.DataFrame(\n {\"key\": [0, 1, 2, 3, 4], \"val\": [float(i + 10) for i in range(5)]}\n )\n cux_df = cuxfilter.DataFrame.from_dataframe(df)\n bac = cuxfilter.charts.bokeh.line(\"key\", \"val\")\n bac1 = cuxfilter.charts.bokeh.bar(\"val\")\n dashboard = cux_df.dashboard(\n charts=[bac, bac1],\n title=\"test_title\",\n layout=cuxfilter.layouts.double_feature,\n )\n dashboard._active_view = bac.name\n dashboard._calc_data_tiles()\n dashboard._query_datatiles_by_range(query_tuple=(1, 2))\n bac.filter_widget.value = (1, 2)\n\n # reset active view\n dashboard._reset_current_view(new_active_view=bac1)\n\n assert dashboard._active_view == bac1.name\n assert dashboard._query_str_dict == {\"key_line\": \"1<=key<=2\"}\n assert dashboard._charts[bac.name].datatile_loaded_state is False\n assert bac1.name not in dashboard._query_str_dict\n assert dashboard._data.equals(\n df.query(dashboard._query_str_dict[\"key_line\"])\n )\n"
] | [
[
"numpy.array",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
archettialberto/neural_weighted_a_star | [
"a7172f1de81ad5cc7e301031f271ded3e93a2283",
"a7172f1de81ad5cc7e301031f271ded3e93a2283"
] | [
"model/dnwa.py",
"model/feature_extractor/combresnet18_pad.py"
] | [
"import torch\n\nfrom a_star.neighbor_utils import NeighborUtils\nfrom model.feature_extractor.fe_factory import get_feature_extractor\nfrom model.wh_model import WHModel\nfrom utils.collections import ModelSolution\n\n\nclass DNWA(WHModel):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.w_extractor = get_feature_extractor(\n kwargs[\"weights_extractor\"][\"name\"],\n kwargs[\"weights_extractor\"][\"params\"]\n )\n self.h_extractor = get_feature_extractor(\n kwargs[\"heuristic_extractor\"][\"name\"],\n kwargs[\"heuristic_extractor\"][\"params\"]\n )\n self.nu = None\n self.epsilon = kwargs[\"epsilon\"]\n self._range = kwargs[\"range\"]\n assert self.epsilon >= 0.0, self.epsilon\n\n def set_range(self, x):\n max, min = self._range\n return x * (max - min) + min\n\n def extract_wh(self, x, s, t, rand_epsilon=False) -> ModelSolution:\n\n s1 = torch.cuda.Stream()\n s2 = torch.cuda.Stream()\n\n torch.cuda.synchronize()\n with torch.cuda.stream(s1):\n w = self.w_extractor(x, s, t)[:, :, :, 0]\n\n with torch.cuda.stream(s2):\n h = self.h_extractor(x, s, t)[:, :, :, 0]\n\n torch.cuda.synchronize()\n\n w = self.activation(w)\n w = self.set_range(w)\n\n if rand_epsilon:\n epsilon = torch.rand((w.shape[0], 1, 1)).to(w.device) * 9.0\n else:\n epsilon = self.epsilon\n\n if self.nu is None:\n x_max, y_max = w.shape[1], w.shape[2]\n self.nu = NeighborUtils(x_max, y_max)\n\n\n h = self.nu.get_euclidean_heuristic(w.detach(), t) * (1.0 + self.activation(h) * epsilon)\n\n return ModelSolution(\n weights=w,\n heuristic=h\n )\n",
"import torch\nimport torch.nn as nn\n\nfrom model.feature_extractor.feature_extractor import FeatureExtractor\nfrom model.feature_extractor.resnet_builder import resnet18\n\n\nclass CombResnet18Pad(FeatureExtractor):\n def __init__(self, in_channels, out_channels, x_max=12, y_max=12, mean_features=False):\n super().__init__(in_channels, out_channels)\n self.resnet_model = resnet18(\n pretrained=False,\n num_classes=x_max * y_max\n )\n self.resnet_model.conv1 = nn.Conv2d(in_channels, 64, kernel_size=7, stride=2, padding=3, bias=False)\n self.out_conv = nn.Conv2d(256, out_channels, kernel_size=1, stride=1, padding=0)\n self.mean_features = mean_features\n if self.mean_features:\n assert out_channels == 1, out_channels\n\n def extract_features(self, x, s, t):\n x = x.permute(0, 3, 1, 2)\n x = self.resnet_model.conv1(x)\n x = self.resnet_model.bn1(x)\n x = self.resnet_model.relu(x)\n x = self.resnet_model.maxpool(x)\n x = self.resnet_model.layer1(x)\n x = self.resnet_model.layer2(x)\n x = self.resnet_model.layer3(x)\n if self.mean_features:\n x = torch.mean(x, dim=1, keepdim=True)\n else:\n x = self.out_conv(x)\n return x.permute(0, 2, 3, 1)\n"
] | [
[
"torch.cuda.synchronize",
"torch.rand",
"torch.cuda.Stream",
"torch.cuda.stream"
],
[
"torch.mean",
"torch.nn.Conv2d"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
emolinaro/UCloud-Reports | [
"52eee04dee6db4cb67194aa9c88b261cfef2bcf5"
] | [
"2020/1/main.py"
] | [
"import pandas as pd\nimport streamlit as st\nimport plotly.express as px\nfrom PIL import Image\n\n\[email protected]\ndef load_data(file):\n data = pd.read_csv(file)\n return data\n\n\n#####################\n### HTML SETTINGS ###\n#####################\n\nucloud_color = '#006AFF'\npwrai_color = 'red'\ndgx1_color = 'green'\ndgx2_color = 'gold'\nbody_color = '#F5FFFA'\nheader_color = 'black'\nsubheader_color = '#c00'\ncode_color = '#c00'\nplt_bkg_color = body_color\n\nheader = '<style>h1{color: %s;}</style>' % (header_color)\nsubheader = '<style>h2{color: %s;}</style>' % (subheader_color)\nbody = '<style>body{background-color: %s;}</style>' % (body_color)\ncode = '<style>code{color: %s; }</style>' % (code_color)\n\nsidebar = \"\"\"\n <style>\n # .reportview-container {\n # flex-direction: row-reverse;\n # }\n\n # header > .toolbar {\n # flex-direction: row-reverse;\n # left: 1rem;\n # right: auto;\n # }\n\n # .sidebar .sidebar-collapse-control,\n # .sidebar.--collapsed .sidebar-collapse-control {\n # left: auto;\n # right: 0.5rem;\n # }\n \n .sidebar .sidebar-content {\n transition: margin-right .3s, box-shadow .3s;\n background-image: linear-gradient(180deg,%s,%s);\n width: 20rem;\n }\n \n # .sidebar.--collapsed .sidebar-content {\n # margin-left: auto;\n # margin-right: -20rem;\n # }\n\n @media (max-width: 991.98px) {\n .sidebar .sidebar-content {\n margin-left: auto;\n }\n }\n </style>\n\"\"\" % (ucloud_color, body_color)\n\nst.markdown(header, unsafe_allow_html=True)\nst.markdown(subheader, unsafe_allow_html=True)\nst.markdown(body, unsafe_allow_html=True)\nst.markdown(code, unsafe_allow_html=True)\nst.markdown(sidebar, unsafe_allow_html=True)\n\n#############\n### TITLE ###\n#############\n\n\"\"\"\n# UCloud Report\n\n## Deep Learning Benchmark Tests\n\"\"\"\n\nst.write(\"-------\")\n\n###################\n### DESCRIPTION ###\n###################\n\ndescription = \"\"\"\n### Last update:\nJuly 31, 2020\n\n### Report:\n2020-1\n\n### Author:\nEmiliano Molinaro (<[email protected]>)\\n\nComputational Scientist \\n\neScience Center \\n\nSyddansk Universitet\n\n### Description:\n\nThis report summarizes the results of _single-node data-parallel training_ tests done on the UCloud interactive HPC \nplatform and the IBM PowerAI system, based on [MLPerf training benchmarks](https://mlperf.org/training-overview/#overview). \nEach benchmark measures the wallclock time required to train a model on the specified dataset to achieve the \nspecified quality target. \n\nThe tests are done using the NVIDIA CUDA-X software stack running on NVIDIA Volta GPUs. The latter leverage the built-in \nNVIDIA [Tensor Cores](https://www.nvidia.com/en-us/data-center/tensor-cores/) technology to accelerate single- and \n[mixed-precision](https://developer.nvidia.com/automatic-mixed-precision) computing. \n\nThe results are compared with the performance of NVIDIA DGX-1/DGX-2 systems reported \n[here](https://github.com/NVIDIA/DeepLearningExamples).\n\n### Specs:\n\nThe runtime system used on UCloud is the `u1-gpu-4` machine type: \n- 4 NVIDIA Volta GPUs \n- 63 CPU cores\n- 180 GB of memory\n\n\"\"\"\n\n#################\n### SIDE MENU ###\n#################\n\n# logo = Image.open('figs/logo_esc.png')\n# st.sidebar.image(logo, format='PNG', width=50)\nst.sidebar.title(\"Benchmark Models\")\n\nradio = st.sidebar.radio(label=\"\", options=[\"Description\",\n \"Benchmark 1\",\n \"Benchmark 2\",\n \"Benchmark 3\",\n \"Benchmark 4\",\n \"Benchmark 5\"])\n\nif radio == \"Benchmark 1\":\n\n ###############################\n st.subheader(\"**Benchmark 1**\")\n ###############################\n\n st.markdown(\"\"\"\n **Category:** \n Recommender Systems\n\n **Model:**\n [Neural Collaborative Filtering](https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/Recommendation/NCF)\n\n **Framework:**\n PyTorch\n\n \"\"\")\n\n path_to_file = \"training/PyTorch/Recommendation/NCF/results.csv\"\n\n df1 = load_data(path_to_file)\n cols1 = list(df1.columns.values)\n\n if st.checkbox(\"Show data benchmark 1\"):\n st.table(df1)\n\n dfp1 = df1.loc[:, [cols1[0], cols1[1], cols1[4], cols1[6]]]\n dfp1 = dfp1.rename(columns={cols1[4]: 'Time to train (s)'})\n dfp1 = dfp1.rename(columns={cols1[6]: 'Throughput (samples/s)'})\n dfp1['Training type'] = 'FP32'\n\n dfp2 = df1.loc[:, [cols1[0], cols1[1], cols1[5], cols1[7]]]\n dfp2 = dfp2.rename(columns={cols1[5]: 'Time to train (s)'})\n dfp2 = dfp2.rename(columns={cols1[7]: 'Throughput (samples/s)'})\n dfp2['Training type'] = 'Mixed precision'\n\n dff = pd.concat([dfp1, dfp2])\n\n # st.table(dff)\n\n cols = list(dff.columns.values)\n\n fig1 = px.bar(dff,\n y=cols[3],\n x=cols[1],\n color=cols[0],\n barmode=\"group\",\n color_discrete_map={'UCloud': ucloud_color,\n 'IBM PowerAI': pwrai_color,\n 'NVIDIA DGX-1': dgx1_color,\n 'NVIDIA DGX-2': dgx2_color\n },\n hover_data=[cols[1], cols[3]],\n facet_col=cols[4]\n )\n\n fig1.update_xaxes(tickvals=[1, 2, 3, 4, 8, 16], title_text=\"Number of GPUs\", linecolor='black')\n fig1.update_yaxes(linecolor='black', showgrid=True, gridwidth=1, gridcolor='LightGrey')\n fig1.update_layout({'paper_bgcolor': plt_bkg_color, 'plot_bgcolor': plt_bkg_color})\n\n fig2 = px.bar(dff,\n y=cols[2],\n x=cols[1],\n color=cols[0],\n barmode=\"group\",\n color_discrete_map={'UCloud': ucloud_color,\n 'IBM PowerAI': pwrai_color,\n 'NVIDIA DGX-1': dgx1_color,\n 'NVIDIA DGX-2': dgx2_color\n },\n hover_data=[cols[1], cols[2]],\n facet_col=cols[4]\n )\n\n fig2.update_xaxes(tickvals=[1, 2, 3, 4, 8, 16], title_text=\"Number of GPUs\", linecolor='black')\n fig2.update_yaxes(linecolor='black', showgrid=True, gridwidth=1, gridcolor='LightGrey')\n fig2.update_layout({'paper_bgcolor': plt_bkg_color, 'plot_bgcolor': plt_bkg_color})\n\n st.plotly_chart(fig1)\n st.plotly_chart(fig2)\n\nelif radio == \"Benchmark 2\":\n\n ###############################\n st.subheader(\"**Benchmark 2**\")\n ###############################\n\n st.markdown(\"\"\"\n **Category:** \n Computer Vision\n\n **Model:**\n [SSD300 v1.1](https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/Detection/SSD)\n\n **Framework:**\n PyTorch\n\n \"\"\")\n\n path_to_file = \"training/PyTorch/Detection/SSD/results.csv\"\n\n df2 = load_data(path_to_file)\n cols2 = list(df2.columns.values)\n\n if st.checkbox(\"Show data benchmark 2\"):\n st.table(df2)\n\n dfp1 = df2.loc[:, [cols2[0], cols2[1], cols2[3], cols2[5]]]\n dfp1 = dfp1.rename(columns={cols2[3]: 'Time to train (s)'})\n dfp1 = dfp1.rename(columns={cols2[5]: 'Throughput (images/s)'})\n dfp1['Training type'] = 'FP32'\n\n dfp2 = df2.loc[:, [cols2[0], cols2[1], cols2[4], cols2[6]]]\n dfp2 = dfp2.rename(columns={cols2[4]: 'Time to train (s)'})\n dfp2 = dfp2.rename(columns={cols2[6]: 'Throughput (images/s)'})\n dfp2['Training type'] = 'Mixed precision'\n\n dff = pd.concat([dfp1, dfp2])\n\n # st.table(dff)\n\n cols = list(dff.columns.values)\n\n fig1 = px.bar(dff,\n y=cols[3],\n x=cols[1],\n color=cols[0],\n barmode=\"group\",\n color_discrete_map={'UCloud': ucloud_color,\n 'IBM PowerAI': pwrai_color,\n 'NVIDIA DGX-1': dgx1_color,\n },\n hover_data=[cols[1], cols[3]],\n facet_col=cols[4]\n )\n\n fig1.update_xaxes(tickvals=[1, 2, 4, 8], title_text=\"Number of GPUs\", linecolor='black')\n fig1.update_yaxes(linecolor='black', showgrid=True, gridwidth=1, gridcolor='LightGrey')\n fig1.update_layout({'paper_bgcolor': plt_bkg_color, 'plot_bgcolor': plt_bkg_color})\n\n fig2 = px.bar(dff,\n y=cols[2],\n x=cols[1],\n color=cols[0],\n barmode=\"group\",\n color_discrete_map={'UCloud': ucloud_color,\n 'IBM PowerAI': pwrai_color,\n 'NVIDIA DGX-1': dgx1_color,\n },\n hover_data=[cols[1], cols[2]],\n orientation='v',\n facet_col=cols[4]\n )\n\n fig2.update_xaxes(tickvals=[1, 2, 4, 8], title_text=\"Number of GPUs\", linecolor='black')\n fig2.update_yaxes(linecolor='black', showgrid=True, gridwidth=1, gridcolor='LightGrey')\n fig2.update_layout({'paper_bgcolor': plt_bkg_color, 'plot_bgcolor': plt_bkg_color})\n\n st.plotly_chart(fig1)\n st.plotly_chart(fig2)\n\nelif radio == \"Benchmark 3\":\n\n ###############################\n st.subheader(\"**Benchmark 3**\")\n ###############################\n\n st.markdown(\"\"\"\n **Category:** \n Natural Language Processing\n\n **Model:**\n [GNMT v2](https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/Translation/GNMT)\n\n **Framework:**\n PyTorch\n\n \"\"\")\n\n path_to_file = \"training/PyTorch/Translation/GNMT/results.csv\"\n\n df3 = load_data(path_to_file)\n cols3 = list(df3.columns.values)\n\n if st.checkbox(\"Show data benchmark 3\"):\n st.table(df3)\n\n dfp1 = df3.loc[:, [cols3[0], cols3[1], cols3[5], cols3[7]]]\n dfp1 = dfp1.rename(columns={cols3[5]: 'Time to train (min)'})\n dfp1 = dfp1.rename(columns={cols3[7]: 'Throughput (tok/s)'})\n dfp1['Training type'] = 'FP32'\n\n dfp2 = df3.loc[:, [cols3[0], cols3[1], cols3[6], cols3[8]]]\n dfp2 = dfp2.rename(columns={cols3[6]: 'Time to train (min)'})\n dfp2 = dfp2.rename(columns={cols3[8]: 'Throughput (tok/s)'})\n dfp2['Training type'] = 'Mixed precision'\n\n dff = pd.concat([dfp1, dfp2])\n\n # st.table(dff)\n\n cols = list(dff.columns.values)\n\n fig1 = px.bar(dff,\n y=cols[3],\n x=cols[1],\n color=cols[0],\n barmode=\"group\",\n color_discrete_map={'UCloud': ucloud_color,\n 'IBM PowerAI': pwrai_color,\n 'NVIDIA DGX-1': dgx1_color,\n 'NVIDIA DGX-2': dgx2_color\n },\n hover_data=[cols[1], cols[3]],\n facet_col=cols[4]\n )\n\n fig1.update_xaxes(tickvals=[1, 2, 4, 8, 16], title_text=\"Number of GPUs\", linecolor='black')\n fig1.update_yaxes(linecolor='black', showgrid=True, gridwidth=1, gridcolor='LightGrey')\n fig1.update_layout({'paper_bgcolor': plt_bkg_color, 'plot_bgcolor': plt_bkg_color})\n\n fig2 = px.bar(dff,\n y=cols[2],\n x=cols[1],\n color=cols[0],\n barmode=\"group\",\n color_discrete_map={'UCloud': ucloud_color,\n 'IBM PowerAI': pwrai_color,\n 'NVIDIA DGX-1': dgx1_color,\n 'NVIDIA DGX-2': dgx2_color\n },\n hover_data=[cols[1], cols[2]],\n facet_col=cols[4]\n )\n\n fig2.update_xaxes(tickvals=[1, 2, 4, 8, 16], title_text=\"Number of GPUs\", linecolor='black')\n fig2.update_yaxes(linecolor='black', showgrid=True, gridwidth=1, gridcolor='LightGrey')\n fig2.update_layout({'paper_bgcolor': plt_bkg_color, 'plot_bgcolor': plt_bkg_color})\n\n st.plotly_chart(fig1)\n st.plotly_chart(fig2)\n\nelif radio == \"Benchmark 4\":\n\n ###############################\n st.subheader(\"**Benchmark 4**\")\n ###############################\n\n st.markdown(\"\"\"\n **Category:** \n Speech Synthesis\n\n **Model:**\n [Tacotron 2](https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/SpeechSynthesis/Tacotron2)\n\n **Framework:**\n PyTorch\n\n \"\"\")\n\n path_to_file = \"training/PyTorch/SpeechSynthesis/Tacotron2/results.csv\"\n\n df4 = load_data(path_to_file)\n cols4 = list(df4.columns.values)\n\n if st.checkbox(\"Show data benchmark 4\"):\n st.table(df4)\n\n dfp1 = df4.loc[:, [cols4[0], cols4[1], cols4[4], cols4[6]]]\n dfp1 = dfp1.rename(columns={cols4[4]: 'Time to train (h)'})\n dfp1 = dfp1.rename(columns={cols4[6]: 'Throughput (mels/s)'})\n dfp1['Training type'] = 'FP32'\n\n dfp2 = df4.loc[:, [cols4[0], cols4[1], cols4[5], cols4[7]]]\n dfp2 = dfp2.rename(columns={cols4[5]: 'Time to train (h)'})\n dfp2 = dfp2.rename(columns={cols4[7]: 'Throughput (mels/s)'})\n dfp2['Training type'] = 'Mixed precision'\n\n dff = pd.concat([dfp1, dfp2])\n\n # st.table(dff)\n\n cols = list(dff.columns.values)\n\n fig1 = px.bar(dff,\n y=cols[3],\n x=cols[1],\n color=cols[0],\n barmode=\"group\",\n color_discrete_map={'UCloud': ucloud_color,\n 'IBM PowerAI': pwrai_color,\n },\n hover_data=[cols[1], cols[3]],\n facet_col=cols[4]\n )\n\n fig1.update_xaxes(tickvals=[1, 2, 4], title_text=\"Number of GPUs\", linecolor='black')\n fig1.update_yaxes(linecolor='black', showgrid=True, gridwidth=1, gridcolor='LightGrey')\n fig1.update_layout({'paper_bgcolor': plt_bkg_color, 'plot_bgcolor': plt_bkg_color})\n\n fig2 = px.bar(dff,\n y=cols[2],\n x=cols[1],\n color=cols[0],\n barmode=\"group\",\n color_discrete_map={'UCloud': ucloud_color,\n 'IBM PowerAI': pwrai_color,\n },\n hover_data=[cols[1], cols[2]],\n facet_col=cols[4]\n )\n\n fig2.update_xaxes(tickvals=[1, 2, 4], title_text=\"Number of GPUs\", linecolor='black')\n fig2.update_yaxes(linecolor='black', showgrid=True, gridwidth=1, gridcolor='LightGrey')\n fig2.update_layout({'paper_bgcolor': plt_bkg_color, 'plot_bgcolor': plt_bkg_color})\n\n st.plotly_chart(fig1)\n st.plotly_chart(fig2)\n\nelif radio == \"Benchmark 5\":\n\n ###############################\n st.subheader(\"**Benchmark 5**\")\n ###############################\n\n st.markdown(\"\"\"\n **Category:** \n Natural Language Processing\n\n **Model:**\n [Transformer-XL](https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/LanguageModeling/Transformer-XL)\n\n **Framework:**\n PyTorch\n\n \"\"\")\n\n path_to_file = \"training/PyTorch/LanguageModeling/Transformer-XL/results.csv\"\n\n df5 = load_data(path_to_file)\n cols5 = list(df5.columns.values)\n\n if st.checkbox(\"Show data benchmark 5\"):\n st.table(df5)\n\n dfp1 = df5.loc[:, [cols5[0], cols5[1], cols5[5], cols5[7]]]\n dfp1 = dfp1.rename(columns={cols5[5]: 'Time to train (min)'})\n dfp1 = dfp1.rename(columns={cols5[7]: 'Throughput (tok/s)'})\n dfp1['Training type'] = 'FP32'\n\n dfp2 = df5.loc[:, [cols5[0], cols5[1], cols5[6], cols5[8]]]\n dfp2 = dfp2.rename(columns={cols5[6]: 'Time to train (min)'})\n dfp2 = dfp2.rename(columns={cols5[8]: 'Throughput (tok/s)'})\n dfp2['Training type'] = 'Mixed precision'\n\n dff = pd.concat([dfp1, dfp2])\n\n # st.table(dff)\n\n cols = list(dff.columns.values)\n\n fig1 = px.bar(dff,\n y=cols[3],\n x=cols[1],\n color=cols[0],\n barmode=\"group\",\n color_discrete_map={'UCloud': ucloud_color,\n 'IBM PowerAI': pwrai_color,\n 'NVIDIA DGX-1': dgx1_color,\n 'NVIDIA DGX-2': dgx2_color\n },\n hover_data=[cols[1], cols[3]],\n facet_col=cols[4]\n )\n\n fig1.update_xaxes(tickvals=[1, 2, 4, 8, 16], title_text=\"Number of GPUs\", linecolor='black')\n fig1.update_yaxes(linecolor='black', showgrid=True, gridwidth=1, gridcolor='LightGrey')\n fig1.update_layout({'paper_bgcolor': plt_bkg_color, 'plot_bgcolor': plt_bkg_color})\n\n st.plotly_chart(fig1)\n\nelse:\n description\n"
] | [
[
"pandas.concat",
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
eubchain/tfdistributedtestcase | [
"a81f99e051537fcd860de28587f0ab2bd9b1b5d4",
"a81f99e051537fcd860de28587f0ab2bd9b1b5d4"
] | [
"4_nlp_processing/1_cnn_text_classify/text_cnn.py",
"4_nlp_processing/1_cnn_text_classify/train_mul.py"
] | [
"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\nimport numpy as np\n\n\nclass TextCNN(object):\n \"\"\"\n A CNN for text classification.\n Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.\n \"\"\"\n def __init__(\n self, sequence_length, num_classes, vocab_size,\n embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0):\n\n # Placeholders for input, output and dropout\n self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name=\"input_x\")\n self.input_y = tf.placeholder(tf.float32, [None, num_classes], name=\"input_y\")\n self.dropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\")\n\n # Keeping track of l2 regularization loss (optional)\n l2_loss = tf.constant(0.0)\n\n # Embedding layer\n with tf.name_scope(\"embedding\"):\n self.W = tf.Variable(\n tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),\n name=\"W\")\n self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)\n self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)\n\n # Create a convolution + maxpool layer for each filter size\n pooled_outputs = []\n for i, filter_size in enumerate(filter_sizes):\n with tf.name_scope(\"conv-maxpool-%s\" % filter_size):\n # Convolution Layer\n filter_shape = [filter_size, embedding_size, 1, num_filters]\n W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name=\"W\")\n b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name=\"b\")\n conv = tf.nn.conv2d(\n self.embedded_chars_expanded,\n W,\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n name=\"conv\")\n # Apply nonlinearity\n h = tf.nn.relu(tf.nn.bias_add(conv, b), name=\"relu\")\n # Maxpooling over the outputs\n pooled = tf.nn.max_pool(\n h,\n ksize=[1, sequence_length - filter_size + 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding='VALID',\n name=\"pool\")\n pooled_outputs.append(pooled)\n\n # Combine all the pooled features\n num_filters_total = num_filters * len(filter_sizes)\n self.h_pool = tf.concat(pooled_outputs, 3)\n self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])\n\n # Add dropout\n with tf.name_scope(\"dropout\"):\n self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)\n\n # Final (unnormalized) scores and predictions\n with tf.name_scope(\"output\"):\n W = tf.get_variable(\n \"W\",\n shape=[num_filters_total, num_classes],\n initializer=tf.contrib.layers.xavier_initializer())\n b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name=\"b\")\n l2_loss += tf.nn.l2_loss(W)\n l2_loss += tf.nn.l2_loss(b)\n self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name=\"scores\")\n self.predictions = tf.argmax(self.scores, 1, name=\"predictions\")\n\n # CalculateMean cross-entropy loss\n with tf.name_scope(\"loss\"):\n losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)\n self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss\n\n # Accuracy\n with tf.name_scope(\"accuracy\"):\n correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))\n self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"), name=\"accuracy\")\n",
"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport time\nimport datetime\nimport tempfile\nimport shutil\n\nimport data_helpers\nfrom text_cnn import TextCNN\nfrom tensorflow.contrib import learn\n\n\n# Parameters\n# ==================================================\n\n# Data loading params\ntf.flags.DEFINE_float(\"dev_sample_percentage\", .1, \"Percentage of the training data to use for validation\")\n\ntf.flags.DEFINE_string(\"data_file\", \"./data/train-all.txt\", \"Data source for the training data.\")\ntf.flags.DEFINE_string(\"out_dir\", \"./output\", \"Data source for the training data.\")\n\n# Model Hyperparameters\ntf.flags.DEFINE_integer(\"embedding_dim\", 128, \"Dimensionality of character embedding (default: 128)\")\ntf.flags.DEFINE_string(\"filter_sizes\", \"3,4,5\", \"Comma-separated filter sizes (default: '3,4,5')\")\ntf.flags.DEFINE_integer(\"num_filters\", 128, \"Number of filters per filter size (default: 128)\")\ntf.flags.DEFINE_float(\"dropout_keep_prob\", 0.5, \"Dropout keep probability (default: 0.5)\")\ntf.flags.DEFINE_float(\"l2_reg_lambda\", 0.0, \"L2 regularization lambda (default: 0.0)\")\n\n# Training parameters\ntf.flags.DEFINE_integer(\"batch_size\", 1024, \"Batch Size (default: 64)\")\ntf.flags.DEFINE_integer(\"num_epochs\", 100, \"Number of training epochs (default: 200)\")\ntf.flags.DEFINE_integer(\"evaluate_every\", 100, \"Evaluate model on dev set after this many steps (default: 100)\")\ntf.flags.DEFINE_integer(\"checkpoint_every\", 100, \"Save model after this many steps (default: 100)\")\ntf.flags.DEFINE_integer(\"num_checkpoints\", 5, \"Number of checkpoints to store (default: 5)\")\n# Misc Parameters\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\ntf.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\n\ntf.flags.DEFINE_string('ps_hosts', '', 'Comma-separated list of hostname:port pairs')\ntf.flags.DEFINE_string('worker_hosts', '','Comma-separated list of hostname:port pairs')\ntf.flags.DEFINE_string('job_name', None, 'job name: worker or ps')\ntf.flags.DEFINE_integer('task_index', None, 'Index of task within the job')\ntf.flags.DEFINE_integer(\"issync\", None, \"是否采用分布式的同步模式,1表示同步模式,0表示异步模式\")\n\nFLAGS = tf.flags.FLAGS\nFLAGS.flag_values_dict()\nprint(\"\\nParameters:\")\nfor attr, value in sorted(FLAGS.__flags.items()):\n print(\"{}={}\".format(attr.upper(), value))\n\n\n\ndef main(unused_argv):\n\n if FLAGS.job_name is None or FLAGS.job_name == '':\n raise ValueError('Must specify an explicit job_name !')\n else:\n print ('job_name : ' + FLAGS.job_name)\n if FLAGS.task_index is None or FLAGS.task_index == '':\n raise ValueError('Must specify an explicit task_index!')\n else:\n print ('task_index : ' + str(FLAGS.task_index))\n\n ps_spec = FLAGS.ps_hosts.split(',')\n worker_spec = FLAGS.worker_hosts.split(',')\n\n num_worker = len(worker_spec)\n print (\"Number of worker = \" + str(num_worker))\n print (\"ps_spec = \")\n print(*ps_spec)\n print (\"worker_spec = \")\n print(*worker_spec)\n cluster = tf.train.ClusterSpec({'ps': ps_spec, 'worker': worker_spec})\n print (\"After defining Cluster\")\n print (\"Job name = \" + FLAGS.job_name)\n print (\"task index = \" + str(FLAGS.task_index))\n # try:\n server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index)\n\n print (\"After defining server\")\n if FLAGS.job_name == 'ps':\n print(\"Parameter Server is executed\")\n server.join()\n elif FLAGS.job_name == \"worker\":\n print(\"Parameter Server is executed\")\n with tf.device(tf.train.replica_device_setter(\n worker_device=\"/job:worker/task:%d\"% FLAGS.task_index,\n cluster=cluster)):\n is_chief = (FLAGS.task_index == 0)\n # Data Preparation\n # ==================================================\n \n # Load data\n print(\"Loading data...\")\n \n x_text, y_label = data_helpers.load_data_and_labels(FLAGS.data_file)\n \n # Build vocabulary\n max_document_length = max([len(x.split(\" \")) for x in x_text])\n \n vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)\n x = np.array(list(vocab_processor.fit_transform(x_text)))\n y = np.array(y_label)\n \n # Randomly shuffle data\n np.random.seed(10)\n shuffle_indices = np.random.permutation(np.arange(len(y)))\n print(type(x),type(y))\n \n x_shuffled = x[shuffle_indices]\n y_shuffled = y[shuffle_indices]\n \n # Split train/test set\n # TODO: This is very crude, should use cross-validation\n dev_sample_index = -1 * int(FLAGS.dev_sample_percentage * float(len(y)))\n x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]\n y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]\n print (y_train.shape)\n print(\"Vocabulary Size: {:d}\".format(len(vocab_processor.vocabulary_)))\n print(\"Train/Dev split: {:d}/{:d}\".format(len(y_train), len(y_dev)))\n \n # Training\n # ==================================================\n tf.MaxAcc = 0.1\n \n def copymax(path):\n shutil.copy(path, \"{}.backup\".format(path))\n \n \n cnn = TextCNN(\n sequence_length=x_train.shape[1],\n num_classes=y_train.shape[1],\n vocab_size=len(vocab_processor.vocabulary_),\n embedding_size=FLAGS.embedding_dim,\n filter_sizes=list(map(int, FLAGS.filter_sizes.split(\",\"))),\n num_filters=FLAGS.num_filters,\n l2_reg_lambda=FLAGS.l2_reg_lambda)\n \n # Define Training procedure\n global_step = tf.train.get_or_create_global_step()\n optimizer = tf.train.AdamOptimizer(1e-3)\n grads_and_vars = optimizer.compute_gradients(cnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)\n\n # Keep track of gradient values and sparsity (optional)\n\n # Output directory for models and summaries\n timestamp = str(int(time.time()))\n out_dir = FLAGS.out_dir\n print(\"Writing to {}\\n\".format(out_dir))\n \n # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, \"checkpoints\"))\n checkpoint_prefix = os.path.join(checkpoint_dir, \"model\")\n MaxAcc_prefi=os.path.join(checkpoint_dir, \"MAXACCmodel\")\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints)\n\n \n # Write vocabulary\n vocab_processor.save(os.path.join(out_dir, \"vocab\"))\n \n # Initialize all variables\n session_conf = tf.ConfigProto(\n allow_soft_placement=FLAGS.allow_soft_placement,\n log_device_placement=FLAGS.log_device_placement)\n\n init_op=tf.global_variables_initializer()\n sv = tf.train.Supervisor(is_chief=(FLAGS.task_index == 0),\n logdir=out_dir,\n init_op=init_op,\n saver=saver,\n global_step=global_step\n )\n sess = sv.prepare_or_wait_for_session(server.target, config=session_conf)\n \n # Generate batches\n batches = data_helpers.batch_iter(\n list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs)\n # Training loop. For each batch...\n for batch in batches:\n x_batch, y_batch = zip(*batch)\n\n _, current_step, loss, accuracy = sess.run(\n [train_op, global_step, cnn.loss, cnn.accuracy],\n feed_dict={cnn.input_x: x_batch,cnn.input_y: y_batch,cnn.dropout_keep_prob: FLAGS.dropout_keep_prob})\n time_str = datetime.datetime.now().isoformat()\n if current_step % 10 ==0:\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, current_step, loss, accuracy))\n\n if current_step % FLAGS.evaluate_every == 0:\n print(\"\\nEvaluation:\")\n\n loss, accuracy = sess.run(\n [cnn.loss, cnn.accuracy],\n feed_dict={cnn.input_x: x_batch,cnn.input_y: y_batch,cnn.dropout_keep_prob: 1.0})\n time_str = datetime.datetime.now().isoformat()\n result = \"{}: step {}, loss {:g}, acc {:g}\".format(time_str, current_step, loss, accuracy)\n print(result)\n\n with open(os.path.join(out_dir, \"result\"), 'a+') as f:\n f.write(\"{}\\n\".format(result))\n\n if tf.MaxAcc<accuracy:\n tf.MaxAcc=accuracy\n ifsave=True\n else:\n ifsave=False\n print(\"Max acc:{}\".format(tf.MaxAcc))\n\n print(\"\")\n if current_step % FLAGS.checkpoint_every == 0:\n path = saver.save(sess, checkpoint_prefix, global_step=current_step)\n print(\"Saved model checkpoint to {}\\n\".format(path))\n if ifsave:\n path = saver.save(sess, MaxAcc_prefi, None)\n copymax(\"{}.data-00000-of-00001\".format(path))\n copymax(\"{}.index\".format(path))\n copymax(\"{}.meta\".format(path))\n\n\nif __name__ == '__main__':\n tf.app.run()"
] | [
[
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.concat",
"tensorflow.nn.max_pool",
"tensorflow.cast",
"tensorflow.nn.l2_loss",
"tensorflow.nn.conv2d",
"tensorflow.name_scope",
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.argmax",
"tensorflow.nn.dropout",
"tensorflow.nn.xw_plus_b",
"tensorflow.truncated_normal",
"tensorflow.placeholder",
"tensorflow.nn.embedding_lookup",
"tensorflow.nn.bias_add",
"tensorflow.constant",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.random_uniform"
],
[
"tensorflow.flags.DEFINE_boolean",
"tensorflow.train.Server",
"numpy.random.seed",
"tensorflow.flags.DEFINE_string",
"tensorflow.global_variables",
"tensorflow.train.ClusterSpec",
"tensorflow.train.get_or_create_global_step",
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.train.replica_device_setter",
"tensorflow.train.Supervisor",
"tensorflow.train.AdamOptimizer",
"tensorflow.flags.DEFINE_float",
"numpy.array",
"tensorflow.contrib.learn.preprocessing.VocabularyProcessor",
"tensorflow.flags.DEFINE_integer",
"tensorflow.app.run"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
MuellerDominik/P5-AIonFPGA | [
"13fc60fb973a4a87a4af1b49c17d5dd1fd239ed5"
] | [
"doc/report/graphics/originals/threshold.py"
] | [
"#!/usr/bin/env python3\n\n'''aionfpga ~ threshold graphic\nCopyright (C) 2020 Dominik Müller and Nico Canzani\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef y(t):\n return 0.4*np.sin(2*np.pi/4*t + np.pi/6) + 1.7\n\nt1 = np.linspace(-0.5, 8.5, 1001)\ny1 = y(t1)\n\nt2 = np.linspace(1, 8, 8)\ny2 = y(t2)\n\nt3 = np.linspace(0, 8, 9)\ny3 = y(t3)\n\ndiff = [abs(y3[i+1] - y3[i]) for i in range(8)]\ndiff = np.asarray(diff)+1.7\n\navg = np.sum(diff)/8\n\nfig, ax1 = plt.subplots(figsize=[8, 4])\nax1.grid(b=True, which='major', color='#666666', linestyle='-')\nax1.grid(b=True, which='minor', color='#bbbbbb', linestyle='-')\nplt.xlim(-0.5, 8.5)\nax1.set_xticks([])\nax1.set_yticks([])\nax2 = ax1.twinx()\nax1.axis('equal')\nax1.set_ylim(-0.5, 3)\nax2.axis('equal')\nax2.set_yticks([])\n# ax1.plot(t1, y1, color=(0.8500, 0.3250, 0.0980))\nax2.scatter(t2, diff, color=(0, 0.4470, 0.7410))\nax2.set_ylim(-0.5, 3)\n\ncut_height = 1.1\nax1.arrow(-0.5, 0, 9, 0, color='black', head_width=0.1, head_length=0.2)\nax1.text(8.8, -0.1, 'FID', ha='center', va='top')\nax1.arrow(0, -0.5, 0, cut_height+0.5, color='black', head_width=0, head_length=0)\nax1.arrow(0, cut_height+0.1, 0, 3-cut_height-0.1, color='black', head_width=0.1, head_length=0.2)\nax1.text(-0.3, 3.4, '$\\\\overline{MD}$', ha='center', va='top')\n\nax1.arrow(-0.1, cut_height-0.1, 0.2, 0.2, color='black', head_width=0, head_length=0)\nax1.arrow(-0.1, cut_height, 0.2, 0.2, color='black', head_width=0, head_length=0)\n\nax1.hlines(avg, -0.5, 8.5, color='gray', linestyles='dashed')\nax1.text(3, avg+0.1, 'AVG. DIFF', ha='center',)\nax1.hlines(2.6, -0.5, 8.5, color='gray', linestyles='dashed')\nax1.text(3, 2.7, 'THRESHOLD = 1.1 $\\\\cdot$ AVG. DIFF', ha='center')\n\nax1.text(0.1, -0.1, 0, ha='left', va='top')\nfor i in range(1, 9):\n ax1.vlines(i, 0, diff[i-1], color='gray', linestyles='dotted')\n ax1.text(i, -0.1, i, ha='center', va='top')\n\nfor ax in [ax1, ax2]:\n for key in ['left', 'right', 'top', 'bottom']:\n ax.spines[key].set_visible(False)\n\nplt.savefig('threshold.pdf', transparent=True, bbox_inches='tight', pad_inches=0)\nplt.show()\n"
] | [
[
"numpy.linspace",
"numpy.asarray",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"numpy.sin",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
deepface/caffe-face | [
"1add78b01945e64da96aeac3459c2f116866538d"
] | [
"testFLW/testFLW.py"
] | [
"import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\npair = open('pair.txt', 'r').readlines()\npic1= []\nnum1 = []\npic2_num2 = []\nnum2 = []\nfor i in range(len(pair)):\n d = pair[i].split()\n if 0<len(d):\n pic1.append(d[0])\n else:\n pic1.append(None)\n if 1<len(d):\n num1.append(d[1])\n else:\n num1.append(None)\n if 2<len(d):\n pic2_num2.append(d[2])\n else:\n pic2_num2.append(None) \n if 3<len(d):\n num2.append(d[3])\n else:\n num2.append(None)\n\nimport scipy.io as sio\nLFW_Feature = sio.loadmat(\"/home/deepinsight/caffe-face/LFW_Feature.mat\")\n\nsimilarsame = []\nsimilardiff = []\nfor i in range(2,len(pair)):\n str1 = ''\n str2 = ''\n if len(pic2_num2[i]) < 4:\n str1 = \"%s_%04d.jpg\" % (pic1[i], int(num1[i]))\n str2 = \"%s_%04d.jpg\" % (pic1[i], int(pic2_num2[i]))\n else:\n str1 = \"%s_%04d.jpg\" % (pic1[i], int(num1[i]))\n str2 = \"%s_%04d.jpg\" % (pic2_num2[i], int(num2[i]))\n \n import numpy as np \n numnum1 = np.where(LFW_Feature['list']==str1)[0][0]\n numnum2 = np.where(LFW_Feature['list']==str2)[0][0]\n #import pdb;pdb.set_trace()\n norm1 = 1e-8 + np.sqrt((LFW_Feature['feature'][numnum1] ** 2).sum())\n norm2 = 1e-8 + np.sqrt((LFW_Feature['feature'][numnum2] ** 2).sum())\n similar = np.dot(LFW_Feature['feature'][numnum1],LFW_Feature['feature'][numnum2]) / norm1 / norm2\n \n if len(pic2_num2[i]) < 4:\n similarsame.append(similar)\n else:\n similardiff.append(similar)\n \nplt.figure(1)\nx = np.linspace(0, 3000, 3000)\nplt.plot(x, similarsame)\nplt.savefig(\"1.jpg\")\n\nplt.figure(2)\nx = np.linspace(0, 3000, 3000)\nplt.plot(x, similarsame)\nplt.savefig(\"2.jpg\")\n\nratioall = []\n\nfor threshold in np.arange(0.1, 1, 0.001):\n numpos = 0\n numneg = 0\n for i in range(len(similarsame)):\n if similarsame[i] >= threshold:\n numpos += 1\n else:\n numneg += 1\n if similardiff[i] < threshold:\n numpos += 1\n else:\n numneg += 1\n ratio = float(numpos) / (numpos + numneg)\n ratioall.append(ratio)\n\n\nplt.figure(2)\nx = np.linspace(0, 1, 1000)\nplt.plot(x, ratioall)\nplt.savefig(\"3.jpg\")\n"
] | [
[
"numpy.dot",
"numpy.linspace",
"matplotlib.use",
"numpy.arange",
"scipy.io.loadmat",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"numpy.where",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
RAPNet/RAP | [
"83662d8d44190f2f32cb2a455881b74a76e782c0"
] | [
"panoptic_benchmark/utils/model_serialization.py"
] | [
"from collections import OrderedDict\nimport logging\n\nimport torch\n\nfrom panoptic_benchmark.utils.imports import import_file\n\n\ndef align_and_update_state_dicts(model_state_dict, loaded_state_dict):\n \"\"\"\n Strategy: suppose that the models that we will create will have prefixes appended\n to each of its keys, for example due to an extra level of nesting that the original\n pre-trained weights from ImageNet won't contain. For example, model.state_dict()\n might return backbone[0].body.res2.conv1.weight, while the pre-trained model contains\n res2.conv1.weight. We thus want to match both parameters together.\n For that, we look for each model weight, look among all loaded keys if there is one\n that is a suffix of the current weight name, and use it if that's the case.\n If multiple matches exist, take the one with longest size\n of the corresponding name. For example, for the same model as before, the pretrained\n weight file can contain both res2.conv1.weight, as well as conv1.weight. In this case,\n we want to match backbone[0].body.conv1.weight to conv1.weight, and\n backbone[0].body.res2.conv1.weight to res2.conv1.weight.\n \"\"\"\n current_keys = sorted(list(model_state_dict.keys()))\n loaded_keys = sorted(list(loaded_state_dict.keys()))\n # get a matrix of string matches, where each (i, j) entry correspond to the size of the\n # loaded_key string, if it matches\n match_matrix = [\n len(j) if i.endswith(j) else 0 for i in current_keys for j in loaded_keys\n ]\n match_matrix = torch.as_tensor(match_matrix).view(\n len(current_keys), len(loaded_keys)\n )\n max_match_size, idxs = match_matrix.max(1)\n # remove indices that correspond to no-match\n idxs[max_match_size == 0] = -1\n\n # used for logging\n max_size = max([len(key) for key in current_keys]) if current_keys else 1\n max_size_loaded = max([len(key) for key in loaded_keys]) if loaded_keys else 1\n log_str_template = \"{: <{}} loaded from {: <{}} of shape {}\"\n logger = logging.getLogger(__name__)\n for idx_new, idx_old in enumerate(idxs.tolist()):\n if idx_old == -1:\n continue\n key = current_keys[idx_new]\n key_old = loaded_keys[idx_old]\n model_state_dict[key] = loaded_state_dict[key_old]\n logger.info(\n log_str_template.format(\n key,\n max_size,\n key_old,\n max_size_loaded,\n tuple(loaded_state_dict[key_old].shape),\n )\n )\n\n\ndef strip_prefix_if_present(state_dict, prefix):\n keys = sorted(state_dict.keys())\n if not all(key.startswith(prefix) for key in keys):\n return state_dict\n stripped_state_dict = OrderedDict()\n for key, value in state_dict.items():\n stripped_state_dict[key.replace(prefix, \"\")] = value\n return stripped_state_dict\n\n\ndef load_state_dict(model, loaded_state_dict):\n model_state_dict = model.state_dict()\n # if the state_dict comes from a model that was wrapped in a\n # DataParallel or DistributedDataParallel during serialization,\n # remove the \"module\" prefix before performing the matching\n loaded_state_dict = strip_prefix_if_present(loaded_state_dict, prefix=\"module.\")\n align_and_update_state_dicts(model_state_dict, loaded_state_dict)\n\n # use strict loading\n model.load_state_dict(model_state_dict)\n"
] | [
[
"torch.as_tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vikua/time-series-experiments | [
"2f9d3fa842866c39c8c1a9906c8c5d4870a6f7da",
"2f9d3fa842866c39c8c1a9906c8c5d4870a6f7da"
] | [
"time_series_experiments/pipeline/tasks.py",
"tests/nbeats/test_stacks.py"
] | [
"import abc\n\nimport attr\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.base import BaseEstimator\n\nfrom .data import TaskData, ColumnType\nfrom .dataset import VarType\n\n\nclass Task(abc.ABC):\n @abc.abstractmethod\n def fit(self, data: TaskData):\n pass\n\n @abc.abstractmethod\n def transform(self, data: TaskData) -> TaskData:\n pass\n\n def fit_transform(self, data: TaskData) -> TaskData:\n return self.fit(data).transform(data)\n\n\nclass Wrap(Task):\n def __init__(self, task: BaseEstimator, type_override: VarType = None):\n self._task = task\n self._type_override = type_override\n\n def fit(self, data: TaskData) -> Task:\n self._task.fit(data.X, data.y)\n return self\n\n def transform(self, data: TaskData) -> TaskData:\n _X = self._task.transform(data.X)\n\n column_names = data.column_names\n column_types = data.column_types\n\n new_cols = _X.shape[1] - data.X.shape[1]\n if new_cols != 0:\n column_names = [\n \"{}-{}\".format(type(self._task).__name__, i) for i in range(_X.shape[1])\n ]\n column_types = [ColumnType(VarType.NUM)] * len(column_names)\n\n if self._type_override is not None:\n column_types = [ColumnType(self._type_override) for _ in column_types]\n\n return attr.evolve(\n data, X=_X, column_types=column_types, column_names=column_names\n )\n\n\nclass OrdCat(Task):\n def __init__(\n self,\n min_support=5,\n use_other=True,\n ordering=\"lexografical\",\n handle_unknown=\"missing\",\n ):\n self._min_suppoort = min_support\n self._use_other = use_other\n self._ordering = ordering\n self._handle_unknown = handle_unknown\n\n self._missing_category = 0\n self._other_category = 0\n if self._use_other:\n self._other_category = 1\n\n if self._ordering not in [\"lexografical\", \"frequency\"]:\n raise ValueError(\"Unknown value {} for ordering\".format(self._ordering))\n\n if self._handle_unknown not in [\"error\", \"missing\"]:\n raise ValueError(\n \"Unknown value {} for handle_unknown\".format(self._handle_unknown)\n )\n\n self.mapping_ = dict()\n self.levels_ = dict()\n\n def fit(self, data: TaskData) -> Task:\n for i in range(data.X.shape[1]):\n vals, counts = np.unique(data.X[:, i], return_counts=True)\n\n if self._ordering == \"frequency\":\n order = np.argsort(counts)\n else:\n order = np.argsort(vals)\n\n vals = vals[order]\n counts = counts[order]\n\n categories = np.arange(vals.shape[0]) + self._other_category + 1\n\n categories[counts < self._min_suppoort] = self._other_category\n self.mapping_[i] = {val: cat for val, cat in zip(vals, categories)}\n\n categories = set(list(categories) + [0] + [self._other_category])\n self.levels_[i] = list(sorted(categories))\n\n return self\n\n def transform(self, data: TaskData) -> TaskData:\n if len(self.mapping_.keys()) != data.X.shape[1]:\n raise ValueError(\"Unexpected number of columns\")\n\n _X = []\n levels = []\n for i in range(data.X.shape[1]):\n cats = self.mapping_[i].copy()\n arr = data.X[:, i]\n\n vals = np.unique(arr)\n unknown_categories = {\n v: self._missing_category for v in vals if v not in cats\n }\n if unknown_categories and self._handle_unknown == \"error\":\n raise ValueError(\"Found unknown categories\")\n\n cats.update(unknown_categories)\n keys = list(cats.keys())\n values = list(cats.values())\n\n sort_idx = np.argsort(keys)\n idx = np.searchsorted(keys, arr, sorter=sort_idx)\n out = np.asarray(values)[sort_idx][idx]\n\n _X.append(out)\n levels.append(len(self.levels_[i]))\n\n _X = np.vstack(_X).T\n\n column_types = [ColumnType(VarType.CAT, level=x) for x in levels]\n return attr.evolve(data, X=_X, column_types=column_types)\n\n\nclass OneHot(Task):\n def __init__(self, handle_unknown=\"error\"):\n self._handle_unknown = handle_unknown\n self._enc = None\n\n def fit(self, data: TaskData) -> Task:\n self._enc = OneHotEncoder(handle_unknown=self._handle_unknown)\n self._enc.fit(data.X)\n return self\n\n def transform(self, data: TaskData) -> TaskData:\n _X = self._enc.transform(data.X)\n column_names = []\n for col, categories in zip(data.column_names, self._enc.categories_):\n new_cols = [\"{}_{}\".format(col, i) for i in range(len(categories))]\n column_names.extend(new_cols)\n column_types = [ColumnType(VarType.NUM) for _ in column_names]\n return attr.evolve(\n data, X=_X, column_names=column_names, column_types=column_types\n )\n\n\nclass DateFeatures(Task):\n COMPONENTS = {\n \"year\": VarType.NUM,\n \"month\": VarType.CAT,\n \"week\": VarType.CAT,\n \"day_of_month\": VarType.CAT,\n \"day_of_week\": VarType.CAT,\n \"hour\": VarType.CAT,\n \"minute\": VarType.CAT,\n \"second\": VarType.CAT,\n }\n\n EXTRACTORS = {\n \"year\": np.vectorize(lambda x: x.year),\n \"month\": np.vectorize(lambda x: x.month),\n \"week\": np.vectorize(lambda x: x.week),\n \"day_of_month\": np.vectorize(lambda x: x.day),\n \"day_of_week\": np.vectorize(lambda x: x.dayofweek),\n \"hour\": np.vectorize(lambda x: x.hour),\n \"minute\": np.vectorize(lambda x: x.minute),\n \"second\": np.vectorize(lambda x: x.second),\n }\n\n PATTERN = \"{} - {}\"\n\n def __init__(self, components=None):\n if not components:\n components = list(self.COMPONENTS.keys())\n\n unknown = set(components) - set(self.COMPONENTS.keys())\n if unknown:\n raise ValueError(\"Unknown datetime components {}\".format(unknown))\n\n self._components = components\n\n def fit(self, data: TaskData) -> Task:\n return self\n\n def transform(self, data: TaskData) -> TaskData:\n X = data.X\n converter = np.vectorize(lambda x: pd.Timestamp(x))\n X = converter(X)\n\n _X = []\n column_names = []\n column_types = []\n for component in self._components:\n func = self.EXTRACTORS[component]\n _X.append(func(X))\n column_names.extend(\n [self.PATTERN.format(c, component) for c in data.column_names]\n )\n column_types.extend(\n [ColumnType(self.COMPONENTS[component]) for _ in range(X.shape[1])]\n )\n\n _X = np.concatenate(_X, axis=1)\n return attr.evolve(\n data, X=_X, column_names=column_names, column_types=column_types\n )\n\n\nclass TargetLag(Task):\n PATTERN = \"lag_{}\"\n\n def __init__(self, order=1, handle_nan=\"drop\"):\n self._order = order\n self._handle_nan = handle_nan\n\n if self._handle_nan not in [\"drop\", \"impute\"]:\n raise ValueError(\n \"Unknown value {} for handle_nan param\".format(self._handle_nan)\n )\n\n self._impute_val = None\n\n def fit(self, data: TaskData) -> Task:\n self._impute_val = np.mean(data.y)\n return self\n\n def transform(self, data: TaskData) -> TaskData:\n X = data.X\n y = data.y\n\n lag = np.roll(y, self._order)\n np.put(lag, range(self._order), np.nan)\n\n mask = np.isnan(lag)\n if self._handle_nan == \"drop\":\n X = X[~mask]\n y = y[~mask]\n lag = lag[~mask]\n elif self._handle_nan == \"impute\":\n lag[mask] = self._impute_val\n\n column_names = data.column_names + [self.PATTERN.format(self._order)]\n column_types = data.column_types + [ColumnType(VarType.LAG)]\n lag = np.reshape(lag, (-1, 1))\n if len(X.shape) == 1:\n X = np.reshape(X, (-1, 1))\n X = np.concatenate([X, lag], axis=1)\n\n return attr.evolve(\n data, X=X, y=y, column_names=column_names, column_types=column_types\n )\n",
"import random\n\nimport pytest\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom time_series_experiments.nbeats.blocks import BlockTypes\nfrom time_series_experiments.nbeats.stacks import (\n DRESSStack,\n ParallelStack,\n NoResidualStack,\n LastForwardStack,\n NoResidualLastForwardStack,\n ResidualInputStack,\n)\nfrom time_series_experiments.utils import get_initializer\nfrom time_series_experiments.utils.metrics import rmse\n\nfrom ..conftest import simple_seq_data, RANDOM_SEED\n\n\[email protected](scope=\"function\", autouse=True)\ndef clear_session():\n tf.keras.backend.clear_session()\n tf.random.set_seed(RANDOM_SEED)\n np.random.seed(RANDOM_SEED)\n random.seed(RANDOM_SEED)\n\n\[email protected](\n \"stack_cls, block_types, expected_rmse\",\n [\n (DRESSStack, [BlockTypes.GENERIC], 0.5),\n (DRESSStack, [BlockTypes.GENERIC, BlockTypes.TREND], 0.3),\n (DRESSStack, [BlockTypes.GENERIC, BlockTypes.TREND, BlockTypes.SEASONAL], 0.25),\n (ParallelStack, [BlockTypes.TREND], 0.4),\n (ParallelStack, [BlockTypes.SEASONAL, BlockTypes.TREND], 0.5),\n (\n ParallelStack,\n [BlockTypes.SEASONAL, BlockTypes.TREND, BlockTypes.GENERIC],\n 0.4,\n ),\n (NoResidualStack, [BlockTypes.GENERIC], 0.5),\n (NoResidualStack, [BlockTypes.GENERIC, BlockTypes.TREND], 0.6),\n (\n NoResidualStack,\n [BlockTypes.GENERIC, BlockTypes.TREND, BlockTypes.SEASONAL],\n 0.4,\n ),\n (LastForwardStack, [BlockTypes.GENERIC], 0.45),\n (LastForwardStack, [BlockTypes.GENERIC, BlockTypes.TREND], 0.4),\n (\n LastForwardStack,\n [BlockTypes.GENERIC, BlockTypes.TREND, BlockTypes.SEASONAL],\n 0.45,\n ),\n (NoResidualLastForwardStack, [BlockTypes.GENERIC], 0.45),\n (NoResidualLastForwardStack, [BlockTypes.GENERIC, BlockTypes.TREND], 0.3),\n (\n NoResidualLastForwardStack,\n [BlockTypes.GENERIC, BlockTypes.TREND, BlockTypes.SEASONAL],\n 0.45,\n ),\n (ResidualInputStack, [BlockTypes.GENERIC], 0.45),\n (ResidualInputStack, [BlockTypes.GENERIC, BlockTypes.TREND], 0.3),\n (\n ResidualInputStack,\n [BlockTypes.GENERIC, BlockTypes.TREND, BlockTypes.SEASONAL],\n 0.3,\n ),\n ],\n)\ndef test_stacks(stack_cls, block_types, expected_rmse):\n fdw = 28\n fw = 7\n\n x_train, y_train, x_test, y_test = simple_seq_data(\n nrows=1000, freq=\"1H\", fdw=fdw, fw=fw, test_size=0.2\n )\n\n inputs = keras.Input(shape=(fdw, 1))\n outputs = keras.layers.Reshape((fdw,))(inputs)\n stack = stack_cls(\n fdw=fdw,\n fw=fw,\n block_types=block_types,\n block_units=8,\n block_theta_units=8,\n block_kernel_initializer=get_initializer(\"glorot_uniform\", RANDOM_SEED),\n )\n if stack_cls == ResidualInputStack:\n _, forecast = stack([outputs, outputs])\n else:\n _, forecast = stack(outputs)\n model = keras.Model(inputs=inputs, outputs=forecast)\n\n model.compile(\n optimizer=keras.optimizers.Adam(0.01), loss=keras.losses.MeanSquaredError()\n )\n model.fit(x_train, y_train, epochs=5, batch_size=32, shuffle=False)\n\n y_pred = model.predict(x_test)\n assert np.all(np.isfinite(y_pred))\n error = rmse(y_test, y_pred)\n assert error < expected_rmse\n"
] | [
[
"numpy.unique",
"numpy.isnan",
"numpy.reshape",
"numpy.arange",
"sklearn.preprocessing.OneHotEncoder",
"numpy.asarray",
"numpy.concatenate",
"numpy.vectorize",
"numpy.mean",
"numpy.searchsorted",
"numpy.argsort",
"pandas.Timestamp",
"numpy.roll",
"numpy.vstack"
],
[
"tensorflow.keras.Input",
"numpy.random.seed",
"numpy.isfinite",
"tensorflow.keras.losses.MeanSquaredError",
"tensorflow.keras.Model",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.backend.clear_session",
"tensorflow.keras.layers.Reshape",
"tensorflow.random.set_seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Stihotvor/rattlesnake | [
"3affaa5df6b661c4b1d2799d58608f69d668d6e9"
] | [
"app.py"
] | [
"import time\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport pyaudio\nimport numpy as np\n\nmatplotlib.use('Agg')\n# https://stackoverflow.com/questions/7088672/pyaudio-working-but-spits-out-error-messages-each-time\n\n\nclass Plotter:\n def __init__(self):\n self.count = 0\n self.x = []\n self.y = []\n self.limit = 100\n plt.figure(figsize=(10, 7))\n plt.xlim(0, self.limit)\n plt.ylim(-1000, 1000)\n\n def plot(self, y):\n self.x.append(self.count)\n self.y.append(y)\n self.count += 1\n\n def save(self):\n plt.plot(self.x, self.y, 'o-k', linewidth=1)\n plt.savefig('fig.png')\n\n\nclass ANC:\n WIDTH = 2\n CHANNELS = 2\n RATE = 44100\n CHUNK = int(RATE / 20) # RATE / number of updates per second\n\n def __init__(self, plotter):\n self.plotter = plotter\n self.pa = pyaudio.PyAudio()\n\n def callback(self, in_data, frame_count, time_info, status):\n # self.plotter.plot(in_data)\n invert_data = self.invert(in_data)\n return invert_data, pyaudio.paContinue\n\n def run(self):\n stream = self.pa.open(\n format=self.pa.get_format_from_width(self.WIDTH),\n channels=self.CHANNELS,\n rate=self.RATE,\n input=True,\n output=True,\n # frames_per_buffer=CHUNK,\n stream_callback=self.callback\n )\n\n stream.start_stream()\n\n while stream.is_active() and self.plotter.count <= self.plotter.limit:\n time.sleep(0.1)\n\n self.plotter.save()\n stream.stop_stream()\n stream.close()\n self.pa.terminate()\n\n def invert(self, data):\n \"\"\"\n Inverts the byte data it received utilizing an XOR operation.\n\n :param data: A chunk of byte data\n :return inverted: The same size of chunked data inverted bitwise\n \"\"\"\n\n # Convert the bytestring into an integer\n intwave = np.frombuffer(data, dtype=np.int16)\n peak = np.average(np.abs(intwave)) * 2\n self.plotter.plot(peak)\n\n # Invert the integer\n invintwave = np.invert(intwave)\n\n # Convert the integer back into a bytestring\n inverted = np.frombuffer(invintwave, dtype=np.byte)\n\n # Return the inverted audio data\n return inverted\n\n\nif __name__ == '__main__':\n plotter = Plotter()\n anc = ANC(plotter=plotter)\n anc.run()\n"
] | [
[
"numpy.abs",
"numpy.invert",
"matplotlib.pyplot.ylim",
"matplotlib.use",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"numpy.frombuffer",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
twj2417/srf | [
"63365cfd75199d70eea2273214a4fa580a9fdf2a",
"63365cfd75199d70eea2273214a4fa580a9fdf2a"
] | [
"srfnef/functions/crystal_to_id.py",
"srfnef/functions/data_transform/pet_cylindrical.py"
] | [
"# encoding: utf-8\n'''\n@author: Minghao Guo\n@contact: [email protected]\n@software: nef\n@file: crystal_to_id.py\n@date: 6/14/2019\n@desc:\n'''\n\nimport numpy as np\nfrom srfnef import nef_class\nfrom srfnef.geometry import PetEcatScanner\n\n\n@nef_class\nclass CrystalToId:\n def __call__(self, crystal_pos: np.ndarray, scanner: PetEcatScanner):\n iblock1 = _position_to_block_index(crystal_pos, scanner)\n iring1 = _position_to_ring_index(crystal_pos, scanner)\n _fst = _rotate_to_block0(crystal_pos, scanner, iblock1)\n iy1 = _position_to_y_index_per_block(_fst, scanner)\n iz1 = _position_to_z_index_per_block(_fst, scanner)\n return iy1 + iz1 * scanner.blocks.shape[\n 1] + iblock1 * scanner.nb_crystals_per_block + scanner.nb_crystals_per_ring * iring1\n\n\ndef _position_to_block_index(pos, scanner: PetEcatScanner):\n xc, yc = pos[:, 0], pos[:, 1]\n return np.round(np.arctan2(yc, xc) / scanner.angle_per_block).astype(\n int) % scanner.nb_blocks_per_ring\n\n\ndef _position_to_thin_ring_index(pos, scanner: PetEcatScanner):\n zc = pos[:, 2]\n n_gap = (zc + scanner.axial_length /\n 2) // (scanner.blocks.size[2] + scanner.gap)\n\n return np.floor(\n (zc + scanner.axial_length / 2 - n_gap * scanner.gap) / scanner.blocks.unit_size[\n 2]).astype(int)\n\n\ndef _position_to_ring_index(pos, scanner: PetEcatScanner):\n zc = pos[:, 2]\n n_gap = (zc + scanner.axial_length /\n 2) // (scanner.blocks.size[2] + scanner.gap)\n\n return np.floor(\n (zc + scanner.axial_length / 2 - n_gap * scanner.gap) / scanner.blocks.size[2]).astype(int)\n\n\ndef _rotate_to_block0(pos, scanner: PetEcatScanner, iblock):\n angle = iblock * scanner.angle_per_block\n _pos = np.zeros(pos.shape)\n xc, yc = pos[:, 0], pos[:, 1]\n _pos[:, 0] = xc * np.cos(angle) + yc * np.sin(angle)\n _pos[:, 1] = -xc * np.sin(angle) + yc * np.cos(angle)\n _pos[:, 2] = pos[:, 2]\n return _pos\n\n\ndef _position_to_y_index_per_block(pos, scanner: PetEcatScanner):\n return np.round(\n (pos[:, 1] + scanner.blocks.size[1] / 2) // scanner.blocks.unit_size[1]).astype(\n int)\n\n\ndef _position_to_z_index_per_block(pos, scanner: PetEcatScanner):\n z_corr = (pos[:, 2] + scanner.axial_length / 2) % scanner.blocks.size[2]\n return np.round(z_corr // scanner.blocks.unit_size[2]).astype(int)\n",
"# encoding: utf-8\n'''\n@author: Minghao Guo\n@contact: [email protected]\n@software: nef\n@file: pet_cylindrical.py\n@date: 9/18/2019\n@desc:\n'''\nfrom srfnef.functions.geometry.pet_cylindrical_scanner import CylindricalCrystalPosToIndex, \\\n CylindricalIndexToCrystalPos\nfrom srfnef import PetCylindricalScanner, nef_class, Listmode, Sinogram, Lors\nimport numpy as np\nfrom scipy.sparse import coo_matrix\n\n\n@nef_class\nclass PetCylindricalSinogramToListmode:\n scanner: PetCylindricalScanner\n\n def __call__(self, sino: Sinogram) -> Listmode:\n irow_, icol_ = sino.data.nonzero()\n data_ = sino.data.data\n pos1 = CylindricalIndexToCrystalPos(self.scanner)(irow_)\n pos2 = CylindricalIndexToCrystalPos(self.scanner)(icol_)\n lors_data = np.hstack((pos1, pos2))\n return Listmode(data_, Lors(lors_data))\n\n\n@nef_class\nclass PetCylindricalListmodeToSinogram:\n scanner: PetCylindricalScanner\n\n def __call__(self, listmode: Listmode) -> Sinogram:\n pos1 = listmode.lors.data[:, :3]\n pos2 = listmode.lors.data[:, 3:6]\n irow_ = CylindricalCrystalPosToIndex(self.scanner)(pos1)\n icol_ = CylindricalCrystalPosToIndex(self.scanner)(pos2)\n N = self.scanner.nb_all_crystal\n sino_data = coo_matrix((listmode.data, (irow_, icol_)), shape = (N, N))\n return Sinogram(sino_data, self.scanner)\n\n\n@nef_class\nclass PetCylindricalListmodeTrans:\n scanner: PetCylindricalScanner\n\n def __call__(self, listmode: Listmode) -> Listmode:\n pos1 = listmode.lors.data[:, :3]\n pos2 = listmode.lors.data[:, 3:6]\n ind1 = CylindricalCrystalPosToIndex(self.scanner)(pos1)\n ind2 = CylindricalCrystalPosToIndex(self.scanner)(pos2)\n pos1_new = CylindricalIndexToCrystalPos(self.scanner)(ind1)\n pos2_new = CylindricalIndexToCrystalPos(self.scanner)(ind2)\n if listmode.lors.data.shape[1] == 6:\n lors_data_new = np.hstack((pos1_new, pos2_new)).astype(np.float32)\n else:\n tof_val = listmode.lors.data[:, -1]\n lors_data_new = np.hstack((pos1_new, pos2_new, tof_val.reshape(-1, 1))).astype(\n np.float32)\n return listmode.update(lors = Lors(lors_data_new))\n"
] | [
[
"numpy.cos",
"numpy.sin",
"numpy.round",
"numpy.arctan2",
"numpy.floor",
"numpy.zeros"
],
[
"numpy.hstack",
"scipy.sparse.coo_matrix"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
KevinMusgrave/pytorch-adapt | [
"947b9f1b748d2078cecbf4a00c34f73108d9ecde",
"ff1491e1bfcc586afb8ee619712c8816ddf10358",
"947b9f1b748d2078cecbf4a00c34f73108d9ecde",
"ff1491e1bfcc586afb8ee619712c8816ddf10358"
] | [
"tests/datasets/test_mnistm.py",
"src/pytorch_adapt/hooks/domain_confusion.py",
"tests/layers/test_randomized_dot_product.py",
"tests/hooks/test_itl.py"
] | [
"import unittest\n\nimport torch\nimport tqdm\nfrom torchvision import transforms as torch_transforms\n\nfrom pytorch_adapt.datasets import MNISTM\nfrom pytorch_adapt.utils.constants import IMAGENET_MEAN, IMAGENET_STD\n\nfrom .. import DATASET_FOLDER, RUN_DATASET_TESTS\nfrom .utils import skip_reason\n\n\nclass TestMNISTM(unittest.TestCase):\n @unittest.skipIf(not RUN_DATASET_TESTS, skip_reason)\n def test_mnistm(self):\n transform = torch_transforms.Compose(\n [\n torch_transforms.ToTensor(),\n torch_transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),\n ]\n )\n\n for train, length in [(True, 59001), (False, 9001)]:\n dataset = MNISTM(DATASET_FOLDER, train, transform)\n self.assertTrue(len(dataset) == length)\n dataloader = torch.utils.data.DataLoader(\n dataset, batch_size=128, num_workers=4\n )\n for _ in tqdm.tqdm(dataloader):\n pass\n\n train = MNISTM(DATASET_FOLDER, True, transform)\n test = MNISTM(DATASET_FOLDER, False, transform)\n self.assertTrue(set(train.img_paths).isdisjoint(set(test.img_paths)))\n",
"import torch\n\nfrom ..layers import UniformDistributionLoss\nfrom .gan import GANHook\n\n\nclass DomainConfusionHook(GANHook):\n \"\"\"\n Implementation of\n [Simultaneous Deep Transfer Across Domains and Tasks](https://arxiv.org/abs/1510.02192)\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(\n disc_domain_loss_fn=torch.nn.CrossEntropyLoss(reduction=\"none\"),\n gen_domain_loss_fn=UniformDistributionLoss(),\n **kwargs,\n )\n",
"import unittest\n\nimport torch\n\nfrom pytorch_adapt.layers import RandomizedDotProduct\n\nfrom .. import TEST_DEVICE, TEST_DTYPES\n\n\nclass TestRandomizedDotProduct(unittest.TestCase):\n def test_randomized_dot_product(self):\n for dtype in TEST_DTYPES:\n in_dims = [512, 128]\n out_dim = 1234\n fn = RandomizedDotProduct(in_dims, out_dim)\n batch_size = 32\n x = torch.randn(batch_size, in_dims[0], device=TEST_DEVICE).type(dtype)\n y = torch.randn(batch_size, in_dims[1], device=TEST_DEVICE).type(dtype)\n combined = fn(x, y)\n\n correct = torch.mm(x, fn.rand_mat0) * torch.mm(y, fn.rand_mat1)\n correct /= torch.sqrt(torch.tensor(out_dim, device=TEST_DEVICE).type(dtype))\n\n self.assertTrue(torch.all(torch.isclose(combined, correct, rtol=1e-2)))\n self.assertTrue(combined.shape == torch.Size([batch_size, out_dim]))\n",
"import unittest\n\nimport torch\n\nfrom pytorch_adapt.hooks import ISTLossHook\nfrom pytorch_adapt.layers import ISTLoss\n\nfrom .utils import assertRequiresGrad, get_models_and_data\n\n\nclass TestITL(unittest.TestCase):\n def test_ist_loss_hook(self):\n torch.manual_seed(334)\n h = ISTLossHook()\n (\n G,\n _,\n _,\n src_imgs,\n _,\n target_imgs,\n src_domain,\n target_domain,\n ) = get_models_and_data()\n\n outputs, losses = h(locals())\n self.assertTrue(G.count == 2)\n assertRequiresGrad(self, outputs)\n\n outputs, losses2 = h({**locals(), **outputs})\n assertRequiresGrad(self, outputs)\n self.assertTrue(G.count == 2)\n self.assertTrue(losses == losses2)\n\n src_features = G(src_imgs)\n target_features = G(target_imgs)\n\n loss_fn = ISTLoss()\n self.assertTrue(\n losses[\"ist_loss\"]\n == loss_fn(\n torch.cat([src_features, target_features], dim=0),\n torch.cat([src_domain, target_domain], dim=0),\n )\n )\n"
] | [
[
"torch.utils.data.DataLoader"
],
[
"torch.nn.CrossEntropyLoss"
],
[
"torch.Size",
"torch.mm",
"torch.randn",
"torch.tensor",
"torch.isclose"
],
[
"torch.manual_seed",
"torch.cat"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
CornsSalinas/corns-dicompyler-core | [
"3c88b713fa167fa90541de2040bf5672a93ac9c8"
] | [
"dicompylercore/dicomparser.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# dicomparser.py\n\"\"\"Class that parses and returns formatted DICOM RT data.\"\"\"\n# Copyright (c) 2009-2016 Aditya Panchal\n# Copyright (c) 2009-2010 Roy Keyes\n# This file is part of dicompyler-core, released under a BSD license.\n# See the file license.txt included with this distribution, also\n# available at https://github.com/dicompyler/dicompyler-core/\n\n\nimport logging\nimport numpy as np\ntry:\n from pydicom.dicomio import read_file\n from pydicom.dataset import Dataset\n from pydicom.pixel_data_handlers.util import pixel_dtype\nexcept ImportError:\n from dicom import read_file\n from dicom.dataset import Dataset\nimport random\nfrom numbers import Number\nfrom six import PY2, iterkeys, string_types, BytesIO\nfrom six.moves import range\nfrom dicompylercore import dvh, util\nfrom dicompylercore.config import pil_available, shapely_available\n\nif pil_available:\n from PIL import Image\nif shapely_available:\n from shapely.geometry import Polygon\n\nlogger = logging.getLogger('dicompylercore.dicomparser')\n\nclass DicomParser:\n \"\"\"Parses DICOM / DICOM RT files.\"\"\"\n def __init__(self, dataset, memmap_pixel_array=False):\n self.memmap_pixel_array = memmap_pixel_array\n if isinstance(dataset, Dataset):\n self.ds = dataset\n elif isinstance(dataset, (string_types, BytesIO)):\n try:\n with open(dataset, \"rb\") as fp:\n self.ds = read_file(fp, defer_size=100, force=True,\n stop_before_pixels=memmap_pixel_array)\n if memmap_pixel_array:\n self.offset = fp.tell() + 8\n except:\n # Raise the error for the calling method to handle\n raise\n else:\n # Sometimes DICOM files may not have headers,\n # but they should always have a SOPClassUID\n # to declare what type of file it is.\n # If the file doesn't have a SOPClassUID,\n # then it probably isn't DICOM.\n if not \"SOPClassUID\" in self.ds:\n raise AttributeError\n else:\n raise AttributeError\n # Remove the PixelData attribute if it is not set.\n # i.e. RTStruct does not contain PixelData and its presence can confuse\n # the parser\n if \"PixelData\" in self.ds and self.ds.PixelData is None:\n delattr(self.ds, 'PixelData')\n if memmap_pixel_array:\n self.filename = dataset\n self.pixel_array = self.get_pixel_array\n else:\n if \"PixelData\" in self.ds:\n self.pixel_array = self.ds.pixel_array\n\n######################## SOP Class and Instance Methods #######################\n\n def GetSOPClassUID(self):\n \"\"\"Determine the SOP Class UID of the current file.\"\"\"\n\n uid = getattr(self.ds, 'SOPClassUID', None)\n\n if (uid == '1.2.840.10008.5.1.4.1.1.481.2'):\n return 'rtdose'\n elif (uid == '1.2.840.10008.5.1.4.1.1.481.3'):\n return 'rtss'\n elif (uid == '1.2.840.10008.5.1.4.1.1.481.5'):\n return 'rtplan'\n elif (uid == '1.2.840.10008.5.1.4.1.1.2'):\n return 'ct'\n else:\n return None\n\n def GetSOPInstanceUID(self):\n \"\"\"Determine the SOP Class UID of the current file.\"\"\"\n\n return getattr(self.ds, 'SOPInstanceUID', None)\n\n def GetStudyInfo(self):\n \"\"\"Return the study information of the current file.\"\"\"\n\n return {'description': getattr(self.ds, 'StudyDescription',\n 'No description'),\n 'date': getattr(self.ds, 'StudyDate', None),\n 'time': getattr(self.ds, 'StudyTime', None),\n 'id': getattr(self.ds, 'StudyInstanceUID',\n str(random.randint(0, 65535)))}\n\n def GetSeriesDateTime(self):\n \"\"\"Return the series date/time information.\"\"\"\n dt = {'date': getattr(self.ds, 'SeriesDate', None),\n 'time': getattr(self.ds, 'SeriesTime', None)}\n\n if dt['date'] is None:\n dt['date'] = getattr(self.ds, 'InstanceCreationDate', None)\n if dt['time'] is None:\n dt['time'] = getattr(self.ds, 'InstanceCreationTime', None)\n\n return dt\n\n def GetSeriesInfo(self):\n \"\"\"Return the series information of the current file.\"\"\"\n\n series = {'description': getattr(self.ds, 'SeriesDescription',\n 'No description'),\n 'id': getattr(self.ds, 'SeriesInstanceUID', None),\n 'study': getattr(self.ds, 'SeriesInstanceUID', None),\n 'referenceframe': getattr(self.ds, 'FrameOfReferenceUID',\n str(random.randint(0, 65535))),\n 'modality': getattr(self.ds, 'Modality', 'OT')}\n series.update(self.GetSeriesDateTime())\n\n series['study'] = getattr(self.ds, 'StudyInstanceUID', series['study'])\n\n return series\n\n def GetReferencedSeries(self):\n \"\"\"Return the SOP Class UID of the referenced series.\"\"\"\n\n if \"ReferencedFrameOfReferenceSequence\" in self.ds:\n frame = self.ds.ReferencedFrameOfReferenceSequence\n if \"RTReferencedStudySequence\" in frame[0]:\n study = frame[0].RTReferencedStudySequence[0]\n if \"RTReferencedSeriesSequence\" in study:\n if \"SeriesInstanceUID\" in \\\n study.RTReferencedSeriesSequence[0]:\n series = study.RTReferencedSeriesSequence[0]\n return series.SeriesInstanceUID\n else:\n return ''\n\n def GetFrameOfReferenceUID(self):\n \"\"\"Determine the Frame of Reference UID of the current file.\"\"\"\n\n if 'FrameOfReferenceUID' in self.ds:\n # Some Files contain a Ref FoR but do not contain an FoR themselves\n if not self.ds.FrameOfReferenceUID == '':\n return self.ds.FrameOfReferenceUID\n if 'ReferencedFrameOfReferenceSequence' in self.ds:\n return self.ds.ReferencedFrameOfReferenceSequence[0].FrameOfReferenceUID\n else:\n return ''\n\n def GetReferencedStructureSet(self):\n \"\"\"Return the SOP Class UID of the referenced structure set.\"\"\"\n\n if \"ReferencedStructureSetSequence\" in self.ds:\n return self.ds.ReferencedStructureSetSequence[0].ReferencedSOPInstanceUID\n else:\n return ''\n\n def GetReferencedRTPlan(self):\n \"\"\"Return the SOP Class UID of the referenced RT plan.\"\"\"\n\n if \"ReferencedRTPlanSequence\" in self.ds:\n return self.ds.ReferencedRTPlanSequence[0].ReferencedSOPInstanceUID\n else:\n return ''\n\n def GetDemographics(self):\n \"\"\"Return the patient demographics from a DICOM file.\"\"\"\n\n # Set up some sensible defaults for demographics\n patient = {'name': 'None',\n 'id': 'None',\n 'birth_date': None,\n 'gender': 'Other'}\n if 'PatientName' in self.ds:\n if PY2:\n self.ds.decode()\n name = self.ds.PatientName\n patient['name'] = str(name)\n patient['given_name'] = name.given_name\n patient['middle_name'] = name.middle_name\n patient['family_name'] = name.family_name\n if 'PatientID' in self.ds:\n patient['id'] = self.ds.PatientID\n if 'PatientSex' in self.ds:\n if (self.ds.PatientSex == 'M'):\n patient['gender'] = 'M'\n elif (self.ds.PatientSex == 'F'):\n patient['gender'] = 'F'\n else:\n patient['gender'] = 'O'\n if 'PatientBirthDate' in self.ds:\n if len(self.ds.PatientBirthDate):\n patient['birth_date'] = str(self.ds.PatientBirthDate)\n\n return patient\n\n\n############################### Image Methods #################################\n\n def GetImageData(self):\n \"\"\"Return the image data from a DICOM file.\"\"\"\n\n data = {}\n\n if 'ImagePositionPatient' in self.ds:\n data['position'] = self.ds.ImagePositionPatient\n if 'ImageOrientationPatient' in self.ds:\n data['orientation'] = self.ds.ImageOrientationPatient\n if 'PixelSpacing' in self.ds:\n data['pixelspacing'] = self.ds.PixelSpacing\n else:\n data['pixelspacing'] = [1, 1]\n data['rows'] = self.ds.Rows\n data['columns'] = self.ds.Columns\n data['samplesperpixel'] = self.ds.SamplesPerPixel\n data['photometricinterpretation'] = self.ds.PhotometricInterpretation\n data['littlendian'] = \\\n self.ds.file_meta.TransferSyntaxUID.is_little_endian\n if 'PatientPosition' in self.ds:\n data['patientposition'] = self.ds.PatientPosition\n data['frames'] = self.GetNumberOfFrames()\n\n return data\n\n def GetPixelArray(self):\n \"\"\"Generate a memory mapped numpy accessor to the pixel array.\"\"\"\n if self.memmap_pixel_array is False:\n return self.pixel_array\n data = self.GetImageData()\n filename = self.filename\n dtype = pixel_dtype(self.ds)\n offset = self.offset\n frames = int(data['frames'])\n shape = (int(self.GetNumberOfFrames()),\n data['rows'], data['columns']) if frames > 1 \\\n else (data['rows'], data['columns'])\n\n def get_pixel_array(filename, dtype, offset, shape):\n array = np.memmap(\n filename,\n dtype=dtype,\n mode=\"r\",\n offset=offset,\n shape=shape\n )\n yield array\n del array\n return list(get_pixel_array(filename, dtype, offset, shape))[0]\n\n get_pixel_array = property(GetPixelArray)\n\n def GetImageLocation(self):\n \"\"\"Calculate the location of the current image slice.\"\"\"\n\n ipp = self.ds.ImagePositionPatient\n iop = self.ds.ImageOrientationPatient\n\n normal = []\n normal.append(iop[1] * iop[5] - iop[2] * iop[4])\n normal.append(iop[2] * iop[3] - iop[0] * iop[5])\n normal.append(iop[0] * iop[4] - iop[1] * iop[3])\n\n loc = 0\n for i in range(0, len(normal)):\n loc += normal[i] * ipp[i]\n\n # The image location is inverted for Feet First images\n if 'PatientPosition' in self.ds:\n if ('ff' in self.ds.PatientPosition.lower()):\n loc = loc * -1\n\n return loc\n\n def GetImageOrientationType(self):\n \"\"\"Get the orientation of the current image slice.\"\"\"\n\n if 'ImageOrientationPatient' in self.ds:\n iop = np.array(self.ds.ImageOrientationPatient)\n\n orientations = [\n [\"SA\", np.array([1, 0, 0, 0, 1, 0])], # supine axial\n [\"PA\", np.array([-1, 0, 0, 0, -1, 0])], # prone axial\n [\"SS\", np.array([0, 1, 0, 0, 0, -1])], # supine sagittal\n [\"PS\", np.array([0, -1, 0, 0, 0, -1])], # prone sagittal\n [\"SC\", np.array([1, 0, 0, 0, 0, -1])], # supine coronal\n [\"PC\", np.array([-1, 0, 0, 0, 0, -1])] # prone coronal\n ]\n\n for o in orientations:\n if (not np.any(np.array(np.round(iop - o[1]), dtype=np.int32))):\n return o[0]\n # Return N/A if the orientation was not found or could not be determined\n return \"NA\"\n\n def GetNumberOfFrames(self):\n \"\"\"Return the number of frames in a DICOM image file.\"\"\"\n\n frames = 1\n if 'NumberOfFrames' in self.ds:\n frames = self.ds.NumberOfFrames.real\n else:\n if \"PixelData\" not in self.ds:\n return 0\n else:\n if (self.pixel_array.ndim > 2):\n if (self.ds.SamplesPerPixel == 1) and not \\\n (self.ds.PhotometricInterpretation == 'RGB'):\n frames = self.pixel_array.shape[0]\n return frames\n\n def GetRescaleInterceptSlope(self):\n \"\"\"Return the rescale intercept and slope if present.\"\"\"\n\n intercept, slope = 0, 1\n if ('RescaleIntercept' in self.ds and 'RescaleSlope' in self.ds):\n intercept = self.ds.RescaleIntercept if \\\n isinstance(self.ds.RescaleIntercept, Number) else 0\n slope = self.ds.RescaleSlope if \\\n isinstance(self.ds.RescaleSlope, Number) else 1\n\n return intercept, slope\n\n def GetImage(self, window=0, level=0, size=None, background=False,\n frames=0):\n \"\"\"Return the image from a DICOM image storage file.\"\"\"\n\n if not pil_available:\n print(\"Python imaging library not available.\" + \\\n \" Cannot generate images.\")\n return\n\n # Return a black image if the Numpy pixel array cannot be accessed\n try:\n self.pixel_array\n except:\n return Image.new('L', size)\n\n # Samples per pixel are > 1 & RGB format\n if (self.ds.SamplesPerPixel > 1) and \\\n (self.ds.PhotometricInterpretation == 'RGB'):\n\n # Little Endian\n if self.ds.file_meta.TransferSyntaxUID.is_little_endian:\n im = Image.frombuffer('RGB', (self.ds.Columns, self.ds.Rows),\n self.ds.PixelData, 'raw', 'RGB', 0, 1)\n # Big Endian\n else:\n im = Image.fromarray(np.rollaxis(\n self.pixel_array.transpose(), 0, 2))\n\n # Otherwise the image is monochrome\n else:\n if ((window == 0) and (level == 0)):\n window, level = self.GetDefaultImageWindowLevel()\n # Rescale the slope and intercept of the image if present\n intercept, slope = self.GetRescaleInterceptSlope()\n # Get the requested frame if multi-frame\n if (frames > 0):\n pixel_array = self.pixel_array[frames]\n else:\n pixel_array = self.pixel_array\n\n rescaled_image = pixel_array * slope + intercept\n\n image = self.GetLUTValue(rescaled_image, window, level)\n im = Image.fromarray(image).convert('L')\n\n # Resize the image if a size is provided\n if size:\n im.thumbnail(size, Image.ANTIALIAS)\n\n # Add a black background if requested\n if background:\n bg = Image.new('RGBA', size, (0, 0, 0, 255))\n bg.paste(im, ((size[0] - im.size[0]) // 2,\n (size[1] - im.size[1]) // 2))\n return bg\n\n return im\n\n def GetDefaultImageWindowLevel(self):\n \"\"\"Determine the default window/level for the DICOM image.\"\"\"\n\n window, level = 0, 0\n if ('WindowWidth' in self.ds) and ('WindowCenter' in self.ds):\n if isinstance(self.ds.WindowWidth, float):\n window = self.ds.WindowWidth\n elif isinstance(self.ds.WindowWidth, list):\n if (len(self.ds.WindowWidth) > 1):\n window = self.ds.WindowWidth[1]\n if isinstance(self.ds.WindowCenter, float):\n level = self.ds.WindowCenter\n elif isinstance(self.ds.WindowCenter, list):\n if (len(self.ds.WindowCenter) > 1):\n level = self.ds.WindowCenter[1]\n\n if ((window, level) == (0, 0)):\n wmax = 0\n wmin = 0\n # Rescale the slope and intercept of the image if present\n intercept, slope = self.GetRescaleInterceptSlope()\n pixel_array = self.pixel_array * slope + intercept\n\n if (pixel_array.max() > wmax):\n wmax = pixel_array.max()\n if (pixel_array.min() < wmin):\n wmin = pixel_array.min()\n # Default window is the range of the data array\n window = int(wmax - wmin)\n # Default level is the range midpoint minus the window minimum\n level = int(window / 2 - abs(wmin))\n return window, level\n\n def GetLUTValue(self, data, window, level):\n \"\"\"Apply the RGB Look-Up Table for the data and window/level value.\"\"\"\n\n lutvalue = util.piecewise(data,\n [data <= (level - 0.5 - (window - 1) / 2),\n data > (level - 0.5 + (window - 1) / 2)],\n [0, 255, lambda data:\n ((data - (level - 0.5)) / (window-1) + 0.5) *\n (255 - 0)])\n # Convert the resultant array to an unsigned 8-bit array to create\n # an 8-bit grayscale LUT since the range is only from 0 to 255\n return np.array(lutvalue, dtype=np.uint8)\n\n def GetPatientToPixelLUT(self):\n \"\"\"Get the image transformation matrix from the DICOM standard Part 3\n Section C.7.6.2.1.1\"\"\"\n\n di = self.ds.PixelSpacing[0]\n dj = self.ds.PixelSpacing[1]\n orientation = self.ds.ImageOrientationPatient\n position = self.ds.ImagePositionPatient\n\n m = np.matrix(\n [[orientation[0]*di, orientation[3]*dj, 0, position[0]],\n [orientation[1]*di, orientation[4]*dj, 0, position[1]],\n [orientation[2]*di, orientation[5]*dj, 0, position[2]],\n [0, 0, 0, 1]])\n\n x = []\n y = []\n for i in range(0, self.ds.Columns):\n imat = m * np.matrix([[i], [0], [0], [1]])\n x.append(float(imat[0]))\n for j in range(0, self.ds.Rows):\n jmat = m * np.matrix([[0], [j], [0], [1]])\n y.append(float(jmat[1]))\n\n return (np.array(x), np.array(y))\n\n########################## RT Structure Set Methods ###########################\n\n def GetStructureInfo(self):\n \"\"\"Return the patient demographics from a DICOM file.\"\"\"\n\n structure = {}\n structure['label'] = getattr(self.ds, 'StructureSetLabel', '')\n structure['date'] = getattr(self.ds, 'StructureSetDate', '')\n structure['time'] = getattr(self.ds, 'StructureSetTime', '')\n structure['numcontours'] = len(self.ds.ROIContourSequence)\n\n return structure\n\n def GetStructures(self):\n \"\"\"Returns a dictionary of structures (ROIs).\"\"\"\n\n structures = {}\n\n # Determine whether this is RT Structure Set file\n if not (self.GetSOPClassUID() == 'rtss'):\n return structures\n\n # Locate the name and number of each ROI\n if 'StructureSetROISequence' in self.ds:\n for item in self.ds.StructureSetROISequence:\n data = {}\n number = int(item.ROINumber)\n data['id'] = number\n data['name'] = item.ROIName\n logger.debug(\"Found ROI #%s: %s\", str(number), data['name'])\n structures[number] = data\n\n # Determine the type of each structure (PTV, organ, external, etc)\n if 'RTROIObservationsSequence' in self.ds:\n for item in self.ds.RTROIObservationsSequence:\n number = item.ReferencedROINumber\n if number in structures:\n structures[number]['type'] = item.RTROIInterpretedType\n\n # The coordinate data of each ROI is stored within ROIContourSequence\n if 'ROIContourSequence' in self.ds:\n for roi in self.ds.ROIContourSequence:\n number = roi.ReferencedROINumber\n\n # Generate a random color for the current ROI\n structures[number]['color'] = np.array((\n random.randint(0, 255),\n random.randint(0, 255),\n random.randint(0, 255)), dtype=int)\n # Get the RGB color triplet for the current ROI if it exists\n if 'ROIDisplayColor' in roi:\n # Make sure the color is not none\n if not (roi.ROIDisplayColor is None):\n color = roi.ROIDisplayColor\n # Otherwise decode values separated by forward slashes\n else:\n value = roi[0x3006, 0x002a].repval\n color = value.strip(\"'\").split(\"/\")\n # Try to convert the detected value to a color triplet\n try:\n structures[number]['color'] = \\\n np.array(color, dtype=int)\n # Otherwise fail and fallback on the random color\n except:\n logger.debug(\n \"Unable to decode display color for ROI #%s\",\n str(number))\n\n # Determine whether the ROI has any contours present\n if 'ContourSequence' in roi:\n structures[number]['empty'] = False\n else:\n structures[number]['empty'] = True\n\n return structures\n\n def GetStructureCoordinates(self, roi_number):\n \"\"\"Get the list of coordinates for each plane of the structure.\"\"\"\n\n planes = {}\n # The coordinate data of each ROI is stored within ROIContourSequence\n if 'ROIContourSequence' in self.ds:\n for roi in self.ds.ROIContourSequence:\n if (roi.ReferencedROINumber == int(roi_number)):\n if 'ContourSequence' in roi:\n # Locate the contour sequence for each referenced ROI\n for c in roi.ContourSequence:\n # For each plane, initialize a new plane dict\n plane = dict()\n\n # Determine all the plane properties\n plane['type'] = c.ContourGeometricType\n plane['num_points'] = int(c.NumberOfContourPoints)\n plane['data'] = \\\n self.GetContourPoints(c.ContourData)\n\n # Add each plane to the planes dict\n # of the current ROI\n z = str(round(plane['data'][0][2], 2)) + '0'\n if z not in planes:\n planes[z] = []\n planes[z].append(plane)\n\n return planes\n\n def GetContourPoints(self, array):\n \"\"\"Parses an array of xyz points & returns a array of point dicts.\"\"\"\n\n n = 3\n return [array[i:i+n] for i in range(0, len(array), n)]\n\n def CalculatePlaneThickness(self, planesDict):\n \"\"\"Calculates the plane thickness for each structure.\"\"\"\n\n planes = []\n\n # Iterate over each plane in the structure\n for z in iterkeys(planesDict):\n planes.append(float(z))\n planes.sort()\n\n # Determine the thickness\n thickness = 10000\n for n in range(0, len(planes)):\n if (n > 0):\n newThickness = planes[n] - planes[n-1]\n if (newThickness < thickness):\n thickness = newThickness\n\n # If the thickness was not detected, set it to 0\n if (thickness == 10000):\n thickness = 0\n\n return thickness\n\n def CalculateStructureVolume(self, coords, thickness):\n \"\"\"Calculates the volume of the given structure.\n\n Parameters\n ----------\n coords : dict\n Coordinates of each plane of the structure\n thickness : float\n Thickness of the structure\n \"\"\"\n\n if not shapely_available:\n print(\"Shapely library not available.\" +\n \" Please install to calculate.\")\n return 0\n\n class Within(Polygon):\n def __init__(self, o):\n self.o = o\n\n def __lt__(self, other):\n return self.o.within(other.o)\n\n s = 0\n for i, z in enumerate(sorted(coords.items())):\n # Skip contour data if it is not CLOSED_PLANAR\n if z[1][0]['type'] != 'CLOSED_PLANAR':\n continue\n polygons = []\n contours = [[x[0:2] for x in c['data']] for c in z[1]]\n for contour in contours:\n p = Polygon(contour)\n polygons.append(p)\n # Sort polygons according whether they are contained\n # by the previous polygon\n if len(polygons) > 1:\n ordered_polygons = sorted(polygons, key=Within, reverse=True)\n else:\n ordered_polygons = polygons\n for ip, p in enumerate(ordered_polygons):\n pa = 0\n if ((i == 0) or (i == len(coords.items()) - 1)) and \\\n not (len(coords.items()) == 1):\n pa += (p.area // 2)\n else:\n pa += p.area\n # Subtract the volume if polygon is contained within the parent\n # and is not the parent itself\n if p.within(ordered_polygons[0]) and \\\n (p != ordered_polygons[0]):\n s -= pa\n else:\n s += pa\n vol = s * thickness / 1000\n return vol\n\n############################## RT Dose Methods ###############################\n\n def HasDVHs(self):\n \"\"\"Returns whether dose-volume histograms (DVHs) exist.\"\"\"\n\n if not \"DVHSequence\" in self.ds:\n return False\n else:\n return True\n\n def GetDVHs(self):\n \"\"\"Returns cumulative dose-volume histograms (DVHs).\"\"\"\n\n self.dvhs = {}\n\n if self.HasDVHs():\n for item in self.ds.DVHSequence:\n # Make sure that the DVH has a referenced structure / ROI\n if not 'DVHReferencedROISequence' in item:\n continue\n number = item.DVHReferencedROISequence[0].ReferencedROINumber\n logger.debug(\"Found DVH for ROI #%s\", str(number))\n self.dvhs[number] = dvh.DVH.from_dicom_dvh(self.ds, number)\n\n return self.dvhs\n\n def GetDoseGrid(self, z=0, threshold=0.5):\n \"\"\"Return the 2d dose grid for the given slice position (mm).\n\n Parameters\n ----------\n z : int, optional\n Slice position in mm, by default 0\n threshold : float, optional\n Threshold in mm to determine the max difference from z\n to the closest dose slice without using interpolation,\n by default 0.5\n\n Returns\n -------\n np.array\n An numpy 2d array of dose points\n \"\"\"\n\n # If this is a multi-frame dose pixel array,\n # determine the offset for each frame\n if 'GridFrameOffsetVector' in self.ds:\n pixel_array = self.GetPixelArray()\n z = float(z)\n # Get the initial dose grid position (z) in patient coordinates\n ipp = self.ds.ImagePositionPatient\n iop = self.ds.ImageOrientationPatient\n gfov = self.ds.GridFrameOffsetVector\n # Add the position to the offset vector to determine the\n # z coordinate of each dose plane\n planes = (iop[0] * iop[4] * np.array(gfov)) + ipp[2]\n frame = -1\n # Check to see if the requested plane exists in the array\n if (np.amin(np.fabs(planes - z)) < threshold):\n frame = np.argmin(np.fabs(planes - z))\n # Return the requested dose plane, since it was found\n if not (frame == -1):\n return pixel_array[frame]\n # Check if the requested plane is within the dose grid boundaries\n elif ((z < np.amin(planes)) or (z > np.amax(planes))):\n return np.array([])\n # The requested plane was not found, so interpolate between planes\n else:\n # Determine the upper and lower bounds\n umin = np.fabs(planes - z)\n ub = np.argmin(umin)\n lmin = umin.copy()\n # Change the min value to the max so we can find the 2nd min\n lmin[ub] = np.amax(umin)\n lb = np.argmin(lmin)\n # Fractional distance of dose plane between upper & lower bound\n fz = (z - planes[lb]) / (planes[ub] - planes[lb])\n plane = self.InterpolateDosePlanes(\n pixel_array[ub], pixel_array[lb], fz)\n return plane\n else:\n return np.array([])\n\n def InterpolateDosePlanes(self, uplane, lplane, fz):\n \"\"\"Interpolates a dose plane between two bounding planes at the given\n relative location.\n\n :param uplane: Upper dose plane boundary.\n :param uplane: Lower dose plane boundary.\n :param fz: Fractional distance from the bottom to the top,\n where the new plane is located.\n E.g. if fz = 1, the plane is at the upper plane,\n fz = 0, it is at the lower plane.\n :return: An numpy 2d array of the interpolated dose plane.\n \"\"\"\n\n # A simple linear interpolation\n doseplane = fz*uplane + (1.0 - fz)*lplane\n\n return doseplane\n\n def GetIsodosePoints(self, z=0, level=100, threshold=0.5):\n \"\"\"Return points for the given isodose level and slice position\n from the dose grid.\n\n :param z: Slice position in mm.\n :param threshold: Threshold in mm to determine the max difference\n from z to the closest dose slice without\n using interpolation.\n :param level: Isodose level in scaled form\n (multiplied by self.ds.DoseGridScaling)\n :return: An array of tuples representing isodose points.\n \"\"\"\n\n plane = self.GetDoseGrid(z, threshold)\n isodose = (plane >= level).nonzero()\n return list(zip(isodose[1].tolist(), isodose[0].tolist()))\n\n def GetDoseData(self):\n \"\"\"Return the dose data from a DICOM RT Dose file.\"\"\"\n\n data = self.GetImageData()\n data['doseunits'] = getattr(self.ds, 'DoseUnits', '')\n data['dosetype'] = getattr(self.ds, 'DoseType', '')\n data['dosecomment'] = getattr(self.ds, 'DoseComment', '')\n data['dosesummationtype'] = getattr(self.ds, 'DoseSummationType', '')\n data['dosegridscaling'] = getattr(self.ds, 'DoseGridScaling', '')\n dosemax = 0\n for x in range(data[\"frames\"]):\n pixel_array = self.GetPixelArray()\n newmax = pixel_array[x].max()\n dosemax = newmax if newmax > dosemax else dosemax\n if self.memmap_pixel_array:\n del pixel_array\n data['dosemax'] = float(dosemax)\n data['lut'] = self.GetPatientToPixelLUT()\n data['fraction'] = ''\n if \"ReferencedRTPlanSequence\" in self.ds:\n plan = self.ds.ReferencedRTPlanSequence[0]\n if \"ReferencedFractionGroupSequence\" in plan:\n data['fraction'] = \\\n plan.ReferencedFractionGroupSequence[0].ReferencedFractionGroupNumber\n\n return data\n\n def GetReferencedBeamNumber(self):\n \"\"\"Return the referenced beam number (if it exists) from RT Dose.\"\"\"\n\n beam = None\n if \"ReferencedRTPlanSequence\" in self.ds:\n rp = self.ds.ReferencedRTPlanSequence[0]\n if \"ReferencedFractionGroupSequence\" in rp:\n rf = rp.ReferencedFractionGroupSequence[0]\n if \"ReferencedBeamSequence\" in rf:\n if \"ReferencedBeamNumber\" in rf.ReferencedBeamSequence[0]:\n beam = \\\n rf.ReferencedBeamSequence[0].ReferencedBeamNumber\n\n return beam\n\n############################## RT Plan Methods ###############################\n\n def GetPlan(self):\n \"\"\"Returns the plan information.\"\"\"\n\n self.plan = {}\n\n self.plan['label'] = getattr(self.ds, 'RTPlanLabel', '')\n self.plan['date'] = getattr(self.ds, 'RTPlanDate', '')\n self.plan['time'] = getattr(self.ds, 'RTPlanTime', '')\n self.plan['name'] = ''\n self.plan['rxdose'] = 0\n if \"DoseReferenceSequence\" in self.ds:\n for item in self.ds.DoseReferenceSequence:\n if item.DoseReferenceStructureType == 'SITE':\n self.plan['name'] = \"N/A\"\n if \"DoseReferenceDescription\" in item:\n self.plan['name'] = item.DoseReferenceDescription\n if 'TargetPrescriptionDose' in item:\n rxdose = item.TargetPrescriptionDose * 100\n if (rxdose > self.plan['rxdose']):\n self.plan['rxdose'] = rxdose\n elif item.DoseReferenceStructureType == 'VOLUME':\n if 'TargetPrescriptionDose' in item:\n self.plan['rxdose'] = item.TargetPrescriptionDose * 100\n if ((\"FractionGroupSequence\" in self.ds) and (self.plan['rxdose'] == 0)):\n fg = self.ds.FractionGroupSequence[0]\n if (\"ReferencedBeamSequence\" in fg) and \\\n (\"NumberOfFractionsPlanned\" in fg):\n beams = fg.ReferencedBeamSequence\n fx = fg.NumberOfFractionsPlanned\n for beam in beams:\n if \"BeamDose\" in beam:\n self.plan['rxdose'] += beam.BeamDose * fx * 100\n self.plan['rxdose'] = round(self.plan['rxdose'])\n self.plan['brachy'] = False\n if (\"BrachyTreatmentTechnique\" in self.ds) or \\\n (\"BrachyTreatmentType\" in self.ds):\n self.plan['brachy'] = True\n return self.plan\n\n def GetReferencedBeamsInFraction(self, fx=0):\n \"\"\"Return the referenced beams from the specified fraction.\"\"\"\n\n beams = {}\n if (\"BeamSequence\" in self.ds):\n bdict = self.ds.BeamSequence\n elif (\"IonBeamSequence\" in self.ds):\n bdict = self.ds.IonBeamSequence\n else:\n return beams\n\n # Obtain the beam information\n for b in bdict:\n beam = {}\n beam['name'] = b.BeamName if \"BeamName\" in b else \"\"\n beam['description'] = b.BeamDescription \\\n if \"BeamDescription\" in b else \"\"\n beams[b.BeamNumber.real] = beam\n\n # Obtain the referenced beam info from the fraction info\n if (\"FractionGroupSequence\" in self.ds):\n fg = self.ds.FractionGroupSequence[fx]\n if (\"ReferencedBeamSequence\" in fg):\n rb = fg.ReferencedBeamSequence\n nfx = fg.NumberOfFractionsPlanned\n for b in rb:\n if \"BeamDose\" in b:\n beams[b.ReferencedBeamNumber]['dose'] = \\\n b.BeamDose * nfx * 100\n return beams\n"
] | [
[
"numpy.matrix",
"numpy.amax",
"numpy.amin",
"numpy.memmap",
"numpy.round",
"numpy.argmin",
"numpy.array",
"numpy.fabs"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ioannis-vm/RESSPyLab | [
"306fc24d5f8ece8f2f2de274b56b80ba2019f605",
"306fc24d5f8ece8f2f2de274b56b80ba2019f605",
"306fc24d5f8ece8f2f2de274b56b80ba2019f605",
"306fc24d5f8ece8f2f2de274b56b80ba2019f605",
"306fc24d5f8ece8f2f2de274b56b80ba2019f605",
"306fc24d5f8ece8f2f2de274b56b80ba2019f605"
] | [
"RESSPyLab/model_minimizer.py",
"RESSPyLab/sqp_solver.py",
"RESSPyLab/uvc_model.py",
"RESSPyLab/vc_parameter_identification.py",
"examples/sample_multi_run.py",
"RESSPyLab/uvc_limited_info_opt.py"
] | [
"\"\"\"@package model_minimizer\nModel minimizer method to solve the trust-region subproblem.\n\"\"\"\nimport numpy as np\nfrom numpy import linalg as la\n\nfrom .posdef_check import posdef_check\n\nTOL = np.sqrt(np.finfo(float).eps)\n\n\ndef h_lambda(evals, evecs, lam):\n \"\"\" Returns the positive definite H by adding a factor of the left-most eigenvalue.\n\n H(\\lambda) = Q^T (H_bar + \\lambda I) Q\n\n :param np.array evals: (n,) Eigenvalues.\n :param np.array evecs: (n, n) Eigenvectors, Q.\n :param float lam: Factor to multiply to the identity matrix.\n :return np.array: positive definite matrix.\n \"\"\"\n n, _ = np.shape(evecs)\n i = np.identity(int(n))\n h_bar = np.diag(evals) + lam * i\n h_lam = np.matmul(evecs.transpose(), np.matmul(h_bar, evecs))\n return h_lam\n\n\ndef eig_decomp(h):\n \"\"\" Returns the elements of the eigendecomposition and the minimum eigenvalue/vector for the model minimizer.\n\n The eigendecomposition is defined as h = Q^T \\Lambda Q\n\n :param np.array h: (n, n) Matrix to be decomposed.\n :return list:\n - evals np.array: (n, ) Unsorted eigenvalues of h, \\Lambda = diag(evals)\n - evecs np.array: (n, n) Unsorted eigenvectors of h, provides the matrix Q\n - left_eval float: A value slightly less than the minimum eigenvalue\n - left_evec np.array: (n, 1) Eigenvector corresponding to the minimum eigenvalue\n \"\"\"\n [evals, evecs] = la.eig(h)\n i = np.argmin(evals)\n left_eval = evals[i]\n evecs = evecs.transpose()\n left_evec = evecs[:, i]\n\n slightly_less_factor = (1. + np.abs(left_eval)) * TOL # to make the Hessian positive definite\n left_eval = left_eval - slightly_less_factor\n return [evals, evecs, left_eval, left_evec]\n\n\ndef trust_region_intersect(d_c, d, Delta):\n \"\"\" Returns the factor such that the search direction reaches the edge of the trust radius.\n\n :param np.array d_c: (n, 1) Starting point.\n :param np.array d: (n, 1) Direction.\n :param float Delta: Trust-region radius.\n :return float: Minimum multiplier lam, such that ||s + lam * d||_2 = Delta.\n\n - s and d are assumed to be column vectors.\n \"\"\"\n a = np.dot(d.transpose(), d)\n b = 2 * np.dot(d_c.transpose(), d)\n c = np.dot(d_c.transpose(), d_c) - Delta ** 2\n lam = (-b + np.sqrt(b ** 2 - 4. * a * c)) / (2 * a)\n return float(lam)\n\n\ndef model_minimizer(h, g, Delta):\n \"\"\" Returns the step to the current model minimizer point.\n\n :param np.array h: Hessian matrix.\n :param np.array g: Gradient column vector.\n :param float Delta: Trust-region radius.\n :return np.array: Step to the model minimizer.\n\n\n We are solving the minimization problem of a quadratic function subjected to a trust-region constraint\n\n minimize q(s) = g^T . s + 1/2 * s^T . h . s\n s\n subject to ||s||_2 <= Delta\n\n where g = grad[f(x)], h = hess[f(x)], and Delta is the trust-region radius. The model minimizer method finds the\n nearly exact minimum of this problem using an eigendecomposition. This function is based on Alg 7.3.6 [1], pg. 199.\n This method should only be used when the eigendecomposition of h is cheap (i.e,. h is small or tridiagonal), and\n additionally note that the implementation below is likely not very efficient at the moment.\n\n References:\n [1] Conn et al. (2000) \"Trust Region Methods\"\n \"\"\"\n k_easy = 0.001 # we don't need to solve the problem TOO precisely since the model itself is an approx. in any case\n maximum_iterations = 25\n stop = False\n\n # Step 1\n [evals, evecs, lam_1, u_1] = eig_decomp(h)\n if lam_1 >= 0:\n # Positive definite Hessian\n lam = 0.\n h_mod = h_lambda(evals, evecs, 0.)\n else:\n # Indefinite Hessian\n lam = -lam_1\n h_mod = h_lambda(evals, evecs, lam)\n\n # Step 2\n s = la.solve(h_mod, -g.reshape(-1, 1))\n\n # Step 3\n norm_s = la.norm(s)\n if norm_s <= Delta:\n if lam == 0. or np.abs(norm_s - Delta) <= TOL:\n stop = True\n else:\n # Hard case\n alpha = trust_region_intersect(s, u_1, Delta)\n s = s + alpha * u_1.reshape(-1, 1)\n stop = True\n\n # Step 4\n iteration_number = 0\n while stop is False and np.abs(norm_s - Delta) > k_easy * Delta and iteration_number < maximum_iterations:\n # Easy case\n iteration_number += 1\n\n # Step 5\n l_chol = la.cholesky(h_mod)\n s = la.solve(h_mod, -g)\n w = la.solve(l_chol, s)\n\n norm_s = la.norm(s)\n lam = lam + (norm_s - Delta) / Delta * (norm_s / la.norm(w)) ** 2\n h_mod = h_lambda(evals, evecs, lam)\n if not posdef_check(h_mod) or lam < -lam_1:\n [_, _, lam_check, _] = eig_decomp(h_mod)\n raise ValueError(\"lam = {0}, lam_min = {1}, lam_1 = {2}, phi(lam) = {2}\".format(lam, lam_check, lam_1,\n 1 / norm_s - 1 / Delta))\n\n # print \"Model min. its = {0}\".format(iteration_number)\n return s\n",
"\"\"\"@package sqp_linsearch\nAbstract class for RESSPyLab SQP solvers.\n\"\"\"\nimport numpy as np\n\n\nclass SqpSolver:\n\n def __init__(self, objective_function, constraint, dumper=None):\n \"\"\" Abstract class to define SQP solvers given the objective function to minimize and the constraints to apply.\n\n :param MatModelErrorNda objective_function: Provides the objective function, and gradient / Hessian of it.\n :param AugLagConstraint constraint: Provides the constraints, and gradients / Hessians of them.\n :param Dumper dumper: Used to output information to the screen and/or to a file.\n\n The problem to be solved is to minimize an objective function, f(x), subjected to some constraints. Formally,\n\n minimize f(x)\n x\n subjected to g_i(x) <= 0\n\n where g_i(x) are nonlinear (possibly linear) constraint functions, i = 1, 2, ..., m are the number of\n constraints. The SQP method solves this problem by linearizing the constraints and solving a quadratic model of\n f(x) at each iteration k:\n\n minimize q(x) = grad[f(x_k)]^T . x_k + 1/2 x_k^T . H_k . x_k\n x\n subjected to grad[g(x_k)]^T . x_k + g(x_k) <= 0,\n\n where H_k is an approximation of the Hessian of f(x_k). For additional details see the references below.\n\n References:\n [1] Bierlaire (2015) \"Optimization: Principles and Algorithms\"\n [2] Nocedal and Wright (2006) \"Numerical optimization\"\n \"\"\"\n self.total_iterations = 0\n self.maximum_iterations = 3000\n self.precision = np.sqrt(np.finfo(float).eps)\n self.constraint = constraint\n self.objective_fun = objective_function\n if dumper is None:\n self.use_dumper = False\n else:\n self.use_dumper = True\n self.dumper = dumper\n\n # Used to let the all parts of the solver be aware of the active constraints\n self.active_constraints_index = 0\n self.active_constraints_set = False\n\n # Used for exit information\n self.convergence_reached_tag = 1\n self.maximum_iterations_reached_tag = 2\n self.unknown_exit = 99\n return\n\n def reset_solver(self):\n \"\"\" Sets the internal iteration count and active constraints to their starting values. \"\"\"\n self.total_iterations = 0\n self.active_constraints_index = 0\n self.active_constraints_set = False\n return\n\n def set_maximum_iterations(self, n):\n \"\"\" Sets the maximum iterations to n. \"\"\"\n self.maximum_iterations = n\n return\n\n def set_tolerance(self, tol):\n \"\"\" Sets the precision to tol. \"\"\"\n self.precision = tol\n return\n\n def merit_fun(self, x, c):\n \"\"\" Merit function used to ensure global convergence. \"\"\"\n raise Exception(\"Not implemented in {0}\".format(self))\n\n def globalized_sqp(self, x_0, dual_x_0):\n \"\"\" Pure virtual method for solving the globalized SQP problem. \"\"\"\n raise Exception(\"Not implemented in {0}\".format(self))\n\n def hess_xx_lagrangian(self, x, hess_f, dual_x):\n \"\"\" Returns the Hessian of the Lagrangian only with respect to xx.\n\n :param np.array x: (n, 1) Primal variables.\n :param np.array hess_f: (n, n) Hessian of the objective function.\n :param np.array dual_x: (m, 1) Dual variables.\n :return np.array: (n, n) Hessian of the Lagrangian wrt. xx.\n\n Note returned Hessian is only the \"upper left corner\" of the Hessian of the problem.\n \"\"\"\n hess = hess_f\n constraint_hessians = self.constraint.get_hessian(x)\n for i, hi in enumerate(constraint_hessians):\n hess = hess + dual_x[i] * hi\n return hess\n\n def grad_lagrangian(self, x, grad_f, dual_x, constraint_array, active_constraints=None):\n \"\"\" Returns the gradient of the problem.\n\n :param np.array x: (n, 1) Primal variables.\n :param np.array grad_f: (n, 1) Gradient of the objective function.\n :param np.array dual_x: (m, 1) Dual variables.\n :param np.array constraint_array: (m, 1) Values of each of the constraints.\n :param np.array active_constraints: (m, 1) Bool values, True if active, False if inactive. If None, then all\n are assumed to be active.\n :return np.array: (n + p, 1) Gradient of the Lagrangian of the problem, p is the number of active constraints.\n \"\"\"\n grad = grad_f\n constraint_grads = self.constraint.get_gradient(x)\n dual_2 = dual_x * 1.0\n dual_2[np.logical_not(constraint_array)] = 0.\n for i, gi in enumerate(constraint_grads):\n grad = grad + float(dual_x[i]) * gi\n if active_constraints is None:\n ca_active = constraint_array\n else:\n # Don't consider any of the constraint values if the are inactive (i.e., g(x)_i <= 0)\n ca_active = (constraint_array[active_constraints]).reshape(-1, 1)\n if len(ca_active) != 0:\n grad = np.row_stack((grad, ca_active))\n return grad\n\n def get_constraint_array(self, x):\n \"\"\" Returns the column vector of constraint values. \"\"\"\n return np.array(self.constraint.get_g(x)).reshape((-1, 1))\n\n def get_constraint_gradient_array(self, x):\n \"\"\" Returns the column stack of the gradients of each constraint.\n\n :param np.array x: (n, 1) Primal variables.\n :return np.array: (n, m) Gradients of all the constraint functions.\n\n The returned array is equivalent with the transpose of the Jacobian of the constraint vector function.\n \"\"\"\n all_constraint_grads = self.constraint.get_gradient(x)\n constraint_grads = 1. * all_constraint_grads[0]\n for i in range(1, len(all_constraint_grads)):\n constraint_grads = np.column_stack((constraint_grads, 1. * all_constraint_grads[i]))\n return constraint_grads\n\n def solve(self, x_0, dual_x_0):\n \"\"\" Returns the variables and dual variables that minimize the objective function s.t. the constraints.\n\n :param np.array x_0: (n, 1) Initial guess at primal variables.\n :param np.array dual_x_0: (m, 1) Initial guess at dual variables, m is the number of constraints specified.\n :return list: Solution to the optimization problem.\n \"\"\"\n # Sanitize the inputs\n if type(x_0) is not np.ndarray or type(dual_x_0) is not np.ndarray:\n x_0 = np.array(x_0)\n dual_x_0 = np.array(dual_x_0)\n # Make sure that the arrays are column vectors\n x_0 = x_0.reshape(-1, 1)\n dual_x_0 = dual_x_0.reshape(-1, 1)\n\n print (\"Starting SQP minimization...\")\n [x, dual_x, exit_info] = self.globalized_sqp(x_0, dual_x_0)\n conv_criteria = exit_info['val']\n\n print (exit_info['msg'])\n print (\"Exiting with ||grad[L]|| = {0:e}\".format(conv_criteria))\n print (\"x = {0}\".format(x.reshape(-1)))\n print (\"dual_x = {0}\".format(dual_x.reshape(-1)))\n\n return [x, dual_x]\n\n def solve_return_conv(self, x_0, dual_x_0):\n \"\"\" Returns the variables and dual variables that minimize the objective function s.t. the constraints.\n\n :param np.array x_0: (n, 1) Initial guess at primal variables.\n :param np.array dual_x_0: (m, 1) Initial guess at dual variables, m is the number of constraints specified.\n :return list: Solution to the optimization problem, also returns the convergence criteria at exit.\n \"\"\"\n # Sanitize the inputs\n if type(x_0) is not np.ndarray or type(dual_x_0) is not np.ndarray:\n x_0 = np.array(x_0)\n dual_x_0 = np.array(dual_x_0)\n # Make sure that the arrays are column vectors\n x_0 = x_0.reshape(-1, 1)\n dual_x_0 = dual_x_0.reshape(-1, 1)\n\n print (\"Starting SQP minimization...\")\n [x, dual_x, exit_info] = self.globalized_sqp(x_0, dual_x_0)\n convergence_criteria = exit_info['val']\n\n print (exit_info['msg'])\n print (\"Exiting with ||grad[L]|| = {0:e}\".format(convergence_criteria))\n print (\"x = {0}\".format(x.reshape(-1)))\n print (\"dual_x = {0}\".format(dual_x.reshape(-1)))\n\n return [x, dual_x, convergence_criteria]\n",
"\"\"\"@package vc_updated\nFunctions to implement the updated Voce-Chaboche material model and measure its error.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom numdifftools import nd_algopy as nda\n\n\ndef uvc_return_mapping(x_sol, data, tol=1.0e-8, maximum_iterations=1000):\n \"\"\" Implements the time integration of the updated Voce-Chaboche material model.\n\n :param np.array x_sol: Updated Voce-Chaboche model parameters.\n :param pd.DataFrame data: stress-strain data.\n :param float tol: Local Newton tolerance.\n :param int maximum_iterations: maximum iterations in local Newton procedure, raises RuntimeError if exceeded.\n :return dict: History of: stress ('stress'), strain ('strain'), the total error ('error') calculated by the\n updated Voce-Chaboche model, number of iterations for convergence at each increment ('num_its').\n \"\"\"\n\n if len(x_sol) < 8:\n raise RuntimeError(\"No backstresses or using original V-C params.\")\n n_param_per_back = 2\n n_basic_param = 6\n\n # Get material properties\n E = x_sol[0] * 1.0\n sy_0 = x_sol[1] * 1.0\n Q = x_sol[2] * 1.0\n b = x_sol[3] * 1.0\n D = x_sol[4] * 1.0\n a = x_sol[5] * 1.0\n\n # Set up backstresses\n n_backstresses = int((len(x_sol) - n_basic_param) / n_param_per_back)\n c_k = []\n gamma_k = []\n for i in range(0, n_backstresses):\n c_k.append(x_sol[n_basic_param + n_param_per_back * i])\n gamma_k.append(x_sol[n_basic_param + 1 + n_param_per_back * i])\n\n # Initialize parameters\n alpha_components = np.zeros(n_backstresses, dtype=object) # backstress components\n strain = 0.\n stress = 0.\n ep_eq = 0. # equivalent plastic strain\n\n error = 0. # error measure\n sum_abs_de = 0. # total strain\n stress_sim = 0.0\n stress_test = 0.0\n area_test = 0.0\n\n stress_track = []\n strain_track = []\n strain_inc_track = []\n iteration_track = []\n\n loading = np.diff(data['e_true'])\n for increment_number, strain_inc in enumerate(loading):\n strain += strain_inc\n alpha = np.sum(alpha_components)\n yield_stress = sy_0 + Q * (1. - np.exp(-b * ep_eq)) - D * (1. - np.exp(-a * ep_eq))\n\n trial_stress = stress + E * strain_inc\n relative_stress = trial_stress - alpha\n flow_dir = np.sign(relative_stress)\n\n yield_condition = np.abs(relative_stress) - yield_stress\n if yield_condition > tol:\n is_converged = False\n else:\n is_converged = True\n\n # For error\n stress_sim_1 = stress_sim * 1.0\n stress_test_1 = stress_test * 1.0\n\n # Return mapping if plastic loading\n ep_eq_init = ep_eq\n alpha_init = alpha\n consist_param = 0.\n number_of_iterations = 0\n while is_converged is False and number_of_iterations < maximum_iterations:\n number_of_iterations += 1\n # Isotropic hardening and isotropic modulus\n yield_stress = sy_0 + Q * (1. - np.exp(-b * ep_eq)) - D * (1. - np.exp(-a * ep_eq))\n iso_modulus = Q * b * np.exp(-b * ep_eq) - D * a * np.exp(-a * ep_eq)\n\n # Kinematic hardening and kinematic modulus\n alpha = 0.\n kin_modulus = 0.\n for i in range(0, n_backstresses):\n e_k = np.exp(-gamma_k[i] * (ep_eq - ep_eq_init))\n alpha += flow_dir * c_k[i] / gamma_k[i] + (alpha_components[i] - flow_dir * c_k[i] / gamma_k[i]) * e_k\n kin_modulus += c_k[i] * e_k - flow_dir * gamma_k[i] * e_k * alpha_components[i]\n delta_alpha = alpha - alpha_init\n\n # Local Newton step\n numerator = np.abs(relative_stress) - (consist_param * E + yield_stress + flow_dir * delta_alpha)\n denominator = -(E + iso_modulus + kin_modulus)\n consist_param = consist_param - numerator / denominator\n ep_eq = ep_eq_init + consist_param\n\n if np.abs(numerator) < tol:\n is_converged = True\n\n # Update the variables\n stress = trial_stress - E * flow_dir * consist_param\n for i in range(0, n_backstresses):\n e_k = np.exp(-gamma_k[i] * (ep_eq - ep_eq_init))\n alpha_components[i] = flow_dir * c_k[i] / gamma_k[i] \\\n + (alpha_components[i] - flow_dir * c_k[i] / gamma_k[i]) * e_k\n\n stress_track.append(stress)\n strain_track.append(strain)\n strain_inc_track.append(strain_inc)\n iteration_track.append(number_of_iterations)\n\n # Calculate the error\n stress_sim = stress * 1.0\n stress_test = data['Sigma_true'].iloc[increment_number + 1]\n\n sum_abs_de += np.abs(strain_inc)\n area_test += np.abs(strain_inc) * ((stress_test) ** 2 + (stress_test_1) ** 2) / 2.\n error += np.abs(strain_inc) * ((stress_sim - stress_test) ** 2 + (stress_sim_1 - stress_test_1) ** 2) / 2.\n\n if number_of_iterations >= maximum_iterations:\n print (\"Increment number = \", increment_number)\n print (\"Parameters = \", x_sol)\n print (\"Numerator = \", numerator)\n raise RuntimeError('Return mapping did not converge in ' + str(maximum_iterations) + ' iterations.')\n\n area = area_test / sum_abs_de\n error = error / sum_abs_de\n return {'stress': stress_track, 'strain': strain_track, 'error': error, 'num_its': iteration_track,\n 'area': area}\n\n\ndef sim_curve_uvc(x_sol, test_clean):\n \"\"\" Returns the stress-strain approximation of the updated Voce-Chaboche material model to a given strain input.\n\n :param np.array x_sol: Voce-Chaboche model parameters\n :param DataFrame test_clean: stress-strain data\n :return DataFrame: Voce-Chaboche approximation\n\n The strain column in the DataFrame is labeled \"e_true\" and the stress column is labeled \"Sigma_true\".\n \"\"\"\n\n model_output = uvc_return_mapping(x_sol, test_clean)\n strain = np.append([0.], model_output['strain'])\n stress = np.append([0.], model_output['stress'])\n\n sim_curve = pd.DataFrame(np.array([strain, stress]).transpose(), columns=['e_true', 'Sigma_true'])\n return sim_curve\n\n\ndef error_single_test_uvc(x_sol, test_clean):\n \"\"\" Returns the relative error between a test and its approximation using the updated Voce-Chaboche material model.\n\n :param np.array x_sol: Voce-Chaboche model parameters\n :param DataFrame test_clean: stress-strain data\n :return float: relative error\n\n The strain column in the DataFrame is labeled \"e_true\" and the stress column is labeled \"Sigma_true\".\n \"\"\"\n\n model_output = uvc_return_mapping(x_sol, test_clean)\n return model_output['error']\n\n\ndef normalized_error_single_test_uvc(x_sol, test_clean):\n \"\"\" Returns the error and the total area of a test and its approximation using the updated Voce-Chaboche\n material model.\n\n :param np.array x_sol: Voce-Chaboche model parameters\n :param DataFrame test_clean: stress-strain data\n :return list: (float) total error, (float) total area\n\n The strain column in the DataFrame is labeled \"e_true\" and the stress column is labeled \"Sigma_true\".\n \"\"\"\n\n model_output = uvc_return_mapping(x_sol, test_clean)\n return [model_output['error'], model_output['area']]\n\n\ndef calc_phi_total(x, data):\n \"\"\" Returns the sum of the normalized relative error of the updated Voce-Chaboche material model given x.\n\n :param np.array x: Updated Voce-Chaboche material model parameters.\n :param list data: (pd.DataFrame) Stress-strain history for each test considered.\n :return float: Normalized error value expressed as a percent (raw value * 100).\n\n The normalized error is defined in de Sousa and Lignos (2017).\n \"\"\"\n error_total = 0.\n area_total = 0.\n for d in data:\n error, area = normalized_error_single_test_uvc(x, d)\n error_total += error\n area_total += area\n\n return np.sqrt(error_total / area_total) * 100.\n\n\ndef test_total_area(x, data):\n \"\"\" Returns the total squared area underneath all the tests.\n\n :param np.array x: Updated Voce-Chaboche material model parameters.\n :param list data: (pd.DataFrame) Stress-strain history for each test considered.\n :return float: Total squared area.\n \"\"\"\n area_total = 0.\n for d in data:\n _, area = normalized_error_single_test_uvc(x, d)\n area_total += area\n return area_total\n\n\ndef uvc_get_hessian(x, data):\n \"\"\" Returns the Hessian of the material model error function for a given set of test data evaluated at x.\n\n :param np.array x: Updated Voce-Chaboche material model parameters.\n :param list data: (pd.DataFrame) Stress-strain history for each test considered.\n :return np.array: Hessian matrix of the error function.\n \"\"\"\n\n def f(xi):\n val = 0.\n for d in data:\n val += error_single_test_uvc(xi, d)\n return val\n\n hess_fun = nda.Hessian(f)\n return hess_fun(x)\n\n\ndef uvc_consistency_metric(x_base, x_sample, data):\n \"\"\" Returns the xi_2 consistency metric from de Sousa and Lignos 2019 using the updated Voce-Chaboche model.\n\n :param np.array x_base: Updated Voce-Chaboche material model parameters from the base case.\n :param np.array x_sample: Updated Voce-Chaboche material model parameters from the sample case.\n :param list data: (pd.DataFrame) Stress-strain history for each test considered.\n :return float: Increase in quadratic approximation from the base to the sample case.\n \"\"\"\n x_diff = x_sample - x_base\n hess_base = uvc_get_hessian(x_base, data)\n numerator = np.dot(x_diff, hess_base.dot(x_diff))\n denominator = test_total_area(x_base, data)\n return np.sqrt(numerator / denominator)\n\n\ndef uvc_tangent_modulus(x_sol, data, tol=1.0e-8, maximum_iterations=1000):\n \"\"\" Returns the tangent modulus at each strain step.\n\n :param np.array x_sol: Updated Voce-Chaboche model parameters.\n :param pd.DataFrame data: stress-strain data.\n :param float tol: Local Newton tolerance.\n :param int maximum_iterations: maximum iterations in local Newton procedure, raises RuntimeError if exceeded.\n :return np.ndarray: Tangent modulus array.\n \"\"\"\n\n if len(x_sol) < 8:\n raise RuntimeError(\"No backstresses or using original V-C params.\")\n n_param_per_back = 2\n n_basic_param = 6\n\n # Get material properties\n E = x_sol[0] * 1.0\n sy_0 = x_sol[1] * 1.0\n Q = x_sol[2] * 1.0\n b = x_sol[3] * 1.0\n D = x_sol[4] * 1.0\n a = x_sol[5] * 1.0\n\n # Set up backstresses\n n_backstresses = int((len(x_sol) - n_basic_param) / n_param_per_back)\n c_k = []\n gamma_k = []\n for i in range(0, n_backstresses):\n c_k.append(x_sol[n_basic_param + n_param_per_back * i])\n gamma_k.append(x_sol[n_basic_param + 1 + n_param_per_back * i])\n\n # Initialize parameters\n alpha_components = np.zeros(n_backstresses, dtype=object) # backstress components\n strain = 0.\n stress = 0.\n ep_eq = 0. # equivalent plastic strain\n\n stress_track = []\n strain_track = []\n strain_inc_track = []\n iteration_track = []\n tangent_track = []\n\n loading = np.diff(data['e_true'])\n for increment_number, strain_inc in enumerate(loading):\n strain += strain_inc\n alpha = np.sum(alpha_components)\n yield_stress = sy_0 + Q * (1. - np.exp(-b * ep_eq)) - D * (1. - np.exp(-a * ep_eq))\n\n trial_stress = stress + E * strain_inc\n relative_stress = trial_stress - alpha\n flow_dir = np.sign(relative_stress)\n\n yield_condition = np.abs(relative_stress) - yield_stress\n if yield_condition > tol:\n is_converged = False\n else:\n is_converged = True\n\n # Return mapping if plastic loading\n ep_eq_init = ep_eq\n alpha_init = alpha\n consist_param = 0.\n number_of_iterations = 0\n while is_converged is False and number_of_iterations < maximum_iterations:\n number_of_iterations += 1\n # Isotropic hardening and isotropic modulus\n yield_stress = sy_0 + Q * (1. - np.exp(-b * ep_eq)) - D * (1. - np.exp(-a * ep_eq))\n iso_modulus = Q * b * np.exp(-b * ep_eq) - D * a * np.exp(-a * ep_eq)\n\n # Kinematic hardening and kinematic modulus\n alpha = 0.\n kin_modulus = 0.\n for i in range(0, n_backstresses):\n e_k = np.exp(-gamma_k[i] * (ep_eq - ep_eq_init))\n alpha += flow_dir * c_k[i] / gamma_k[i] + (alpha_components[i] - flow_dir * c_k[i] / gamma_k[i]) * e_k\n kin_modulus += c_k[i] * e_k - flow_dir * gamma_k[i] * e_k * alpha_components[i]\n delta_alpha = alpha - alpha_init\n\n # Local Newton step\n numerator = np.abs(relative_stress) - (consist_param * E + yield_stress + flow_dir * delta_alpha)\n denominator = -(E + iso_modulus + kin_modulus)\n consist_param = consist_param - numerator / denominator\n ep_eq = ep_eq_init + consist_param\n\n if np.abs(numerator) < tol:\n is_converged = True\n\n # Update the variables\n stress = trial_stress - E * flow_dir * consist_param\n for i in range(0, n_backstresses):\n e_k = np.exp(-gamma_k[i] * (ep_eq - ep_eq_init))\n alpha_components[i] = flow_dir * c_k[i] / gamma_k[i] \\\n + (alpha_components[i] - flow_dir * c_k[i] / gamma_k[i]) * e_k\n\n stress_track.append(stress)\n strain_track.append(strain)\n strain_inc_track.append(strain_inc)\n iteration_track.append(number_of_iterations)\n\n # Calculate the tangent modulus\n if number_of_iterations > 0:\n h_prime = 0.\n for i in range(0, n_backstresses):\n h_prime += c_k[i] - flow_dir * gamma_k[i] * alpha_components[i]\n k_prime = Q * b * np.exp(-b * ep_eq) - D * a * np.exp(-a * ep_eq)\n tangent_track.append(E * (k_prime + h_prime) / (E + k_prime + h_prime))\n else:\n # Elastic loading\n tangent_track.append(E)\n\n return np.append([0.], np.array(tangent_track))\n",
"\"\"\"\nTop level function for calibration of the original Voce-Chaboche model.\n\"\"\"\nimport numpy as np\nfrom numdifftools import nd_algopy as nda\nfrom .auglag_factory import auglag_factory, constrained_auglag_opt\nfrom .data_readers import load_and_filter_data_set, load_data_set\nfrom .uvc_model import test_total_area\nfrom .RESSPyLab import errorTest_scl\n\n\ndef vc_param_opt(x_0, file_list, x_log_file, fxn_log_file, filter_data=True):\n \"\"\" Returns the best-fit parameters to the Voce-Chaboche model for a given set of stress-strain data.\n\n :param list x_0: Initial solution point.\n :param list file_list: [str] Paths to the data files to use in the optimization procedure.\n :param str x_log_file: File to track x values at each increment, if empty then don't track.\n :param str fxn_log_file: File to track objective function values at each increment, if empty then don't track.\n :param bool filter_data: If True then apply a filter to the data, else use the raw import.\n :return np.array: Solution point.\n\n Notes:\n - This function uses the augmented Lagrangian method without any constraints, therefore the method reduces to the\n Newton trust-region method.\n \"\"\"\n if filter_data:\n filtered_data = load_and_filter_data_set(file_list)\n else:\n filtered_data = load_data_set(file_list)\n\n solver = auglag_factory(filtered_data, x_log_file, fxn_log_file, 'original', 'steihaug', 'reciprocal', False)\n constraints = {'constants': [], 'variables': [], 'functions': [], 'gradients': [], 'hessians': [],\n 'updater': None}\n x_sol = constrained_auglag_opt(x_0, constraints, solver)\n return x_sol\n\n\ndef vc_get_hessian(x, data):\n \"\"\" Returns the Hessian of the material model error function for a given set of test data evaluated at x.\n\n :param np.array x: Original Voce-Chaboche material model parameters.\n :param list data: (pd.DataFrame) Stress-strain history for each test considered.\n :return np.array: Hessian matrix of the error function.\n \"\"\"\n\n def f(xi):\n val = 0.\n for d in data:\n val += errorTest_scl(xi, d)\n return val\n\n hess_fun = nda.Hessian(f)\n return hess_fun(x)\n\n\ndef vc_consistency_metric(x_base, x_sample, data):\n \"\"\" Returns the xi_2 consistency metric from de Sousa and Lignos 2019 using the original Voce-Chaboche model.\n\n :param np.array x_base: Original Voce-Chaboche material model parameters from the base case.\n :param np.array x_sample: Original Voce-Chaboche material model parameters from the sample case.\n :param list data: (pd.DataFrame) Stress-strain history for each test considered.\n :return float: Increase in quadratic approximation from the base to the sample case.\n \"\"\"\n x_diff = x_sample - x_base\n hess_base = vc_get_hessian(x_base, data)\n numerator = np.dot(x_diff, hess_base.dot(x_diff))\n # Total area is independent of the x choice, just need to run this\n denominator = test_total_area(np.insert(x_base, 4, [0., 1.]), data)\n return np.sqrt(numerator / denominator)\n",
"import numpy as np\nimport os\nfrom RESSPyLab import opt_multi_run\n\n# NOTE: THIS IS JUST A SAMPLE FILE TO ILLUSTRATE THE SET-UP OF THE opt_multi_run FUNCTION AND DOES NOT ACTUALLY RUN\n\n# Locations of data sets\n# opt_multi_run will load all the .csv files in each of the data directories\n# The only .csv files in these directories should be those that contain stress-strain data\ndata_dirs = ['dir1/my_data1/', 'dir1/my_data2/', 'dir1/my_data3/']\n\n# Should use the \"filter_data\" option for each data set\nfilter_list = [False, False, False]\n\n# Directory where output directories will be created\nout_root = 'dir4/out_root_dir/'\n# Get the names and set the output directory paths\nnames = [os.path.basename(os.path.normpath(s)) for s in data_dirs]\noutput_dirs = [os.path.join(out_root, n) for n in names]\n\n# Set the initial point and run the optimizations\nx_0 = np.array([200000., 355.0, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])\nx_0_all = [x_0 for d in data_dirs]\nopt_multi_run(data_dirs, output_dirs, names, filter_list, x_0_all, model_type='UVC')\n",
"\"\"\"@package vcu_limited_info_opt\nFunctions for limited information optimization using the updated Voce-Chaboche model.\n\"\"\"\nimport scipy.optimize as opt\n\nfrom .vc_limited_info_opt import GWrapper, DummyResults\nfrom .uvc_model import error_single_test_uvc\nfrom .mat_model_error_nda import MatModelErrorNda\nfrom .scipy_dumper import ScipyBasicDumper\nfrom .uvc_constraints import *\nfrom .uvc_li_opt_constraints import *\nfrom .scipy_constr_opt_factory import g1_scipy, grad1_scipy, hess1_scipy, g2_scipy, grad2_scipy, hess2_scipy\nfrom .auglag_factory import constrained_auglag_opt, auglag_factory\nfrom .data_readers import load_and_filter_data_set, load_data_set\n\n\ndef uvc_tensile_opt_scipy(x_0, file_list, rho_iso_inf, rho_iso_sup, rho_yield_inf, rho_yield_sup,\n rho_gamma_b_inf, rho_gamma_b_sup, rho_gamma_12_inf, rho_gamma_12_sup,\n rho_d_inf, rho_d_sup,\n x_log_file='', fun_log_file='', filter_data=True,\n max_its=600, tol=1.e-8, make_x0_feasible=True):\n \"\"\" Return parameters based on a single tensile test for the updated VC model using the trust-constr method.\n\n USE OF THIS METHOD IS STRONGLY DISCOURAGED, USE THE ORIGINAL MODEL.\n \"\"\"\n # Load the data\n if filter_data:\n filtered_data = load_and_filter_data_set(file_list)\n else:\n filtered_data = load_data_set(file_list)\n\n # Define the objective function\n objective_function = MatModelErrorNda(error_single_test_uvc, filtered_data, use_cols=False)\n fun = objective_function.value\n jac = objective_function.grad\n hess = objective_function.hess\n\n # Set up the constraints for the optimization\n # Minimum value for any x_i\n min_x_bound = 0.01\n x_lb = [min_x_bound for i in range(len(x_0))]\n x_ub = [np.inf for i in range(len(x_0))]\n bounds = opt.Bounds(x_lb, x_ub, keep_feasible=True)\n # Bounds on inequality constraints\n constr_lb = -np.inf\n constr_ub = 0.\n\n # The constraint functions in scipy format\n g_constants = {'rho_yield_inf': rho_yield_inf, 'rho_yield_sup': rho_yield_sup,\n 'rho_iso_inf': rho_iso_inf, 'rho_iso_sup': rho_iso_sup,\n 'rho_gamma_b_inf': rho_gamma_b_inf, 'rho_gamma_b_sup': rho_gamma_b_sup,\n 'rho_gamma_12_inf': rho_gamma_12_inf, 'rho_gamma_12_sup': rho_gamma_12_sup,\n 'rho_d_inf': rho_d_inf, 'rho_d_sup': rho_d_sup}\n # Updated model hardening constraints\n g1 = opt.NonlinearConstraint(g1_scipy, -np.inf, 0., jac=grad1_scipy, hess=hess1_scipy)\n g2 = opt.NonlinearConstraint(g2_scipy, -np.inf, 0., jac=grad2_scipy, hess=hess2_scipy)\n # g_3\n g3_low = GWrapper(g3_lower, g3_lower_gradient, g3_lower_hessian, g_constants)\n g3_high = GWrapper(g3_upper, g3_upper_gradient, g3_upper_hessian, g_constants)\n g3_inf_constr = opt.NonlinearConstraint(g3_low.f, -np.inf, 0., jac=g3_low.gf, hess=g3_low.hf)\n g3_sup_constr = opt.NonlinearConstraint(g3_high.f, -np.inf, 0., jac=g3_high.gf, hess=g3_high.hf)\n # g_4\n g4_low = GWrapper(g4_lower, g4_lower_gradient, g4_lower_hessian, g_constants)\n g4_high = GWrapper(g4_upper, g4_upper_gradient, g4_upper_hessian, g_constants)\n g4_inf_constr = opt.NonlinearConstraint(g4_low.f, -np.inf, 0., jac=g4_low.gf, hess=g4_low.hf)\n g4_sup_constr = opt.NonlinearConstraint(g4_high.f, -np.inf, 0., jac=g4_high.gf, hess=g4_high.hf)\n # g_5\n g5_low = GWrapper(g5_lower, g5_lower_gradient, g5_lower_hessian, g_constants)\n g5_high = GWrapper(g5_upper, g5_upper_gradient, g5_upper_hessian, g_constants)\n g5_inf_constr = opt.NonlinearConstraint(g5_low.f, -np.inf, 0., jac=g5_low.gf, hess=g5_low.hf)\n g5_sup_constr = opt.NonlinearConstraint(g5_high.f, -np.inf, 0., jac=g5_high.gf, hess=g5_high.hf)\n # g_6\n g_6_low = GWrapper(g6_lower, g6_lower_gradient, g6_lower_hessian, g_constants)\n g_6_high = GWrapper(g6_upper, g6_upper_gradient, g6_upper_hessian, g_constants)\n g6_inf_constr = opt.NonlinearConstraint(g_6_low.f, -np.inf, 0., jac=g_6_low.gf, hess=g_6_low.hf)\n g6_sup_constr = opt.NonlinearConstraint(g_6_high.f, -np.inf, 0., jac=g_6_high.gf, hess=g_6_high.hf)\n # g_7\n g_7_low = GWrapper(g7_lower, g7_lower_gradient, g7_lower_hessian, g_constants)\n g_7_high = GWrapper(g7_upper, g7_upper_gradient, g7_upper_hessian, g_constants)\n g7_inf_constr = opt.NonlinearConstraint(g_7_low.f, -np.inf, 0., jac=g_7_low.gf, hess=g_7_low.hf)\n g7_sup_constr = opt.NonlinearConstraint(g_7_high.f, -np.inf, 0., jac=g_7_high.gf, hess=g_7_high.hf)\n\n # Make the tuple of constraints\n n_backstresses = int((len(x_0) - 6) / 2)\n if n_backstresses >= 2:\n constraints = (g1, g2, g3_inf_constr, g3_sup_constr, g4_inf_constr, g4_sup_constr, g5_inf_constr, g5_sup_constr,\n g6_inf_constr, g6_sup_constr, g7_inf_constr, g7_sup_constr)\n elif n_backstresses == 1:\n constraints = (g1, g2, g3_inf_constr, g3_sup_constr, g4_inf_constr, g4_sup_constr, g5_inf_constr, g5_sup_constr,\n g7_inf_constr, g7_sup_constr)\n\n # Create a new dumper if None is provided\n dumper = ScipyBasicDumper(x_log_file, fun_log_file)\n\n # Make the point feasible\n if make_x0_feasible:\n x_0 = make_feasible_uvc(x_0, g_constants)\n\n # Run the minimization\n scipy_sol = opt.minimize(fun, np.array(x_0), method='trust-constr', jac=jac, hess=hess, bounds=bounds,\n constraints=constraints, callback=dumper.dump,\n options={'maxiter': max_its, 'verbose': 2, 'gtol': tol})\n # Check if the constraints were satisfied\n uvc_constraint_check(scipy_sol.x, rho_iso_inf, rho_iso_sup, rho_yield_inf, rho_yield_sup, rho_gamma_b_inf,\n rho_gamma_b_sup, rho_d_inf, rho_d_sup)\n return [scipy_sol, dumper]\n\n\ndef uvc_limited_info_opt_auglag(x_0, data, rho_iso_inf, rho_iso_sup, rho_yield_inf, rho_yield_sup,\n rho_gamma_inf, rho_gamma_sup, rho_gamma_12_inf, rho_gamma_12_sup,\n rho_d_inf, rho_d_sup,\n x_log_file='', fun_log_file='',\n max_its=200, tol=1.e-8, make_x0_feasible=True):\n \"\"\" Return parameters based on a single tensile test for the original VC model using the augmented Lagrangian\n method.\n\n USE OF THIS METHOD IS STRONGLY DISCOURAGED, USE THE ORIGINAL MODEL.\"\"\"\n\n # The constants for the constraint functions\n g_constants = {'rho_yield_inf': rho_yield_inf, 'rho_yield_sup': rho_yield_sup,\n 'rho_iso_inf': rho_iso_inf, 'rho_iso_sup': rho_iso_sup,\n 'rho_gamma_inf': rho_gamma_inf, 'rho_gamma_sup': rho_gamma_sup,\n 'rho_gamma_12_inf': rho_gamma_12_inf, 'rho_gamma_12_sup': rho_gamma_12_sup,\n 'rho_d_inf': rho_d_inf, 'rho_d_sup': rho_d_sup}\n\n # Set-up constraints\n n_backstresses = int((len(x_0) - 6) / 2)\n if n_backstresses == 1:\n constraint_dict = {'constants': g_constants, 'variables': {},\n 'functions': [g1_constraint, g2_constraint,\n g3_lower, g3_upper, g4_lower, g4_upper,\n g5_lower, g5_upper, g7_lower, g7_upper],\n 'gradients': [g1_gradient, g2_gradient,\n g3_lower_gradient, g3_upper_gradient, g4_lower_gradient,\n g4_upper_gradient, g5_lower_gradient, g5_upper_gradient,\n g7_lower_gradient, g7_upper_gradient],\n 'hessians': [g1_hessian, g2_hessian,\n g3_lower_hessian, g3_upper_hessian, g4_lower_hessian,\n g4_upper_hessian, g5_lower_hessian, g5_upper_hessian,\n g7_lower_hessian, g7_upper_hessian],\n 'updater': None}\n else:\n constraint_dict = {'constants': g_constants, 'variables': {},\n 'functions': [g1_constraint, g2_constraint,\n g3_lower, g3_upper, g4_lower, g4_upper,\n g5_lower, g5_upper, g6_lower, g6_upper, g7_lower, g7_upper],\n 'gradients': [g1_gradient, g2_gradient,\n g3_lower_gradient, g3_upper_gradient, g4_lower_gradient,\n g4_upper_gradient, g5_lower_gradient, g5_upper_gradient,\n g6_lower_gradient, g6_upper_gradient, g7_lower_gradient, g7_upper_gradient],\n 'hessians': [g1_hessian, g2_hessian,\n g3_lower_hessian, g3_upper_hessian, g4_lower_hessian,\n g4_upper_hessian, g5_lower_hessian, g5_upper_hessian,\n g6_lower_hessian, g6_upper_hessian, g7_lower_hessian, g7_upper_hessian],\n 'updater': None}\n\n # Make the point feasible\n if make_x0_feasible:\n x_0 = make_feasible_uvc(x_0, g_constants)\n # Create the solver and run\n solver = auglag_factory(data, x_log_file, fun_log_file, 'updated', 'steihaug', 'reciprocal', False)\n x_opt = constrained_auglag_opt(x_0, constraint_dict, solver)\n return [DummyResults(x_opt), None]\n\n\ndef make_feasible_uvc(x_0, c):\n \"\"\" Returns a feasible x with respect to the constraints g_3, g_4, g_5, and g_6.\n\n :param np.array x_0: (n,) Initial, infeasible point.\n :param dict c: Constants defining the constraints.\n :return np.array: (n,) Initial, feasible point.\n \"\"\"\n n_backstresses = int((len(x_0) - 6) / 2)\n # Get the average of the bounds\n rho_yield_avg = 0.5 * (c['rho_yield_inf'] + c['rho_yield_sup'])\n rho_iso_avg = 0.5 * (c['rho_iso_inf'] + c['rho_iso_sup'])\n rho_gamma_avg = 0.5 * (c['rho_gamma_b_inf'] + c['rho_gamma_b_sup'])\n rho_d_avg = 0.5 * (c['rho_d_inf'] + c['rho_d_sup'])\n # Calculate the feasible set (considering only 1 backstress)\n gamma2_0 = 1. / rho_gamma_avg * x_0[7]\n c1_0 = -x_0[7] * (-1. + rho_iso_avg) * (-1 + rho_yield_avg) * x_0[1]\n q_inf_0 = -c1_0 * rho_iso_avg / (x_0[7] * (-1. + rho_iso_avg))\n b_0 = 1. / rho_gamma_avg * x_0[7]\n d_0 = rho_d_avg * (q_inf_0 + c1_0 / x_0[7])\n if n_backstresses == 2:\n x_0[[2, 3, 4, 6, 9]] = [q_inf_0, b_0, d_0, c1_0, gamma2_0]\n elif n_backstresses == 1:\n x_0[[2, 3, 4, 6]] = [q_inf_0, b_0, d_0, c1_0]\n return x_0\n\n\ndef uvc_constraint_check(x_opt, rho_iso_inf, rho_iso_sup, rho_yield_inf, rho_yield_sup, rho_gamma_b_inf,\n rho_gamma_b_sup, rho_d_inf, rho_d_sup):\n \"\"\" Checks if each of g_3, g_4, and g_5 were satisfied. \"\"\"\n n_backstresses = int((len(x_opt) - 6) // 2)\n sum_c_gamma = 0.\n for i in range(n_backstresses):\n sum_c_gamma += x_opt[6 + 2 * i] / x_opt[7 + 2 * i]\n rho_yield_ratio = (x_opt[1] + x_opt[2] + sum_c_gamma) / x_opt[1]\n rho_iso_ratio = x_opt[2] / (x_opt[2] + sum_c_gamma)\n rho_gamma_b_ratio = x_opt[7] / x_opt[3]\n rho_d_ratio = x_opt[4] / (x_opt[2] + sum_c_gamma)\n print('The rho_iso ratio is = {0}'.format(rho_iso_ratio))\n print('The rho_yield ratio is = {0}'.format(rho_yield_ratio))\n print('The rho_gamma_b ratio is = {0}'.format(rho_gamma_b_ratio))\n print('The rho_d ratio is = {0}'.format(rho_d_ratio))\n\n if not (rho_iso_inf <= rho_iso_ratio <= rho_iso_sup):\n print('Constraint on rho_iso violated!')\n if not (rho_yield_inf <= rho_yield_ratio <= rho_yield_sup):\n print('Constraint on rho_yield violated!')\n if not (rho_gamma_b_inf <= rho_gamma_b_ratio <= rho_gamma_b_sup):\n print('Constraint on rho_gamma violated!')\n if not (rho_d_inf <= rho_d_ratio <= rho_d_sup):\n print('Constraint on rho_d violated!')\n return\n"
] | [
[
"numpy.diag",
"numpy.linalg.solve",
"numpy.abs",
"numpy.sqrt",
"numpy.linalg.eig",
"numpy.matmul",
"numpy.linalg.norm",
"numpy.finfo",
"numpy.shape",
"numpy.argmin",
"numpy.linalg.cholesky"
],
[
"numpy.logical_not",
"numpy.finfo",
"numpy.row_stack",
"numpy.column_stack",
"numpy.array"
],
[
"numpy.sqrt",
"numpy.abs",
"numpy.sign",
"numpy.append",
"numpy.diff",
"numpy.exp",
"numpy.array",
"numpy.zeros",
"numpy.sum"
],
[
"numpy.insert",
"numpy.sqrt"
],
[
"numpy.array"
],
[
"scipy.optimize.NonlinearConstraint",
"scipy.optimize.Bounds"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.3",
"1.9",
"1.5",
"1.7",
"1.2",
"1.8"
],
"tensorflow": []
}
] |
vinoo999/alpha-zero-general | [
"01bd6ac40d7b1fed97a84e37f7a549be8d50f668"
] | [
"Arena.py"
] | [
"from pytorch_classification.utils import Bar, AverageMeter\nimport multiprocessing as mp\nimport numpy as np\nimport time, copy\nfrom utils import *\n\nclass Arena():\n \"\"\"\n An Arena class where any 2 agents can be pit against each other.\n \"\"\"\n def __init__(self, player1, player2, game, display=None, num_workers=1, result_queue=None):\n \"\"\"\n Input:\n player 1,2: two functions that takes board as input, return action\n game: Game object\n display: a function that takes board as input and prints it (e.g.\n display in othello/OthelloGame). Is necessary for verbose\n mode.\n\n see othello/OthelloPlayers.py for an example. See pit.py for pitting\n human players/other baselines with each other.\n \"\"\"\n self.player1 = player1\n self.player2 = player2\n self.game = game\n self.display = display\n self.num_workers = num_workers\n self.result_queue = result_queue\n\n\n # DEPRICATED -- use arena_worker instead\n def playGame(self, verbose=False):\n \"\"\"\n Executes one episode of a game.\n\n Returns:\n either\n winner: player who won the game (1 if player1, -1 if player2)\n or\n draw result returned from the game that is neither 1, -1, nor 0.\n \"\"\"\n players = [self.player2, None, self.player1]\n curPlayer = 1\n board = self.game.getInitBoard()\n it = 0\n while self.game.getGameEnded(board, curPlayer)==0:\n it+=1\n if verbose:\n assert(self.display)\n print(\"Turn \", str(it), \"Player \", str(curPlayer))\n self.display(board)\n action = players[curPlayer+1](self.game.getCanonicalForm(board, curPlayer))\n\n valids = self.game.getValidMoves(self.game.getCanonicalForm(board, curPlayer),1)\n\n if valids[action]==0:\n print(\"**********************\")\n print(action)\n print(np.where(valids>0))\n assert valids[action] >0\n board, curPlayer = self.game.getNextState(board, curPlayer, action)\n if self.result_queue is not None: \n res = self.game.getGameEnded(board, 1)\n self.result_queue.put(None if res == 0 else res)\n\n res = self.game.getGameEnded(board, 1)\n\n if verbose:\n assert(self.display)\n print(\"Game over: Turn \", str(it), \"Result \", str(res))\n if self.result_queue is not None: self.result_queue.put(res)\n self.display(board)\n\n return res\n\n\n # PARALLELISM NOT IMPLEMENTED FOR ARENA\n # def arena_worker(self, work_queue, done_queue, i, player1, player2):\n # print(\"[Worker \" + str(i) + \"] Started!\")\n\n # while True:\n # data = work_queue.get()\n # player = data[\"player\"]\n # game = data[\"game\"]\n # verbose = data[\"verbose\"]\n # eps = data[\"i\"]\n\n # start = time.time()\n\n # players = [player2, None, player1] if player == 1 else [player1, None, player2]\n # board = game.getInitBoard()\n # curPlayer = 1\n # it = 0\n\n # while game.getGameEnded(board, curPlayer) == 0:\n # it += 1\n # if verbose:\n # print(\"Turn \", str(it), \"Player \", str(curPlayer))\n # self.display(board)\n\n # action = players[curPlayer + 1](game.getCanonicalForm(board, curPlayer))\n # valids = game.getValidMoves(game.getCanonicalForm(board, curPlayer), 1) # TODO: Is this check necessary?\n\n # if valids[action] == 0:\n # print(\"<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ERROR >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n # print(action)\n # print(np.where(valids > 0))\n # assert valids[action] > 0\n\n # # The action is valid\n # board, curPlayer = game.getNextState(board, curPlayer, action)\n\n # res = game.getGameEnded(board, 1)\n\n # if verbose:\n # print(\"Game over: Turn \", str(it), \"Result \", str(res))\n # self.display(board)\n\n # # Return the result of the game from the HUMAN (player 1) perspective\n # # NOTE: This is not the same thing as game.getGameEnded(board, curPlayer)\n # done_queue.put((time.time() - start, res))\n\n\n def playGames(self, num, verbose=False):\n \"\"\"\n Plays num games in which player1 starts num/2 games and player2 starts\n num/2 games.\n\n Returns:\n oneWon: games won by player1\n twoWon: games won by player2\n draws: games won by nobody\n \"\"\"\n tracker = ParallelRuntimes(self.num_workers)\n bar = Bar('Arena.playGames', max=num)\n\n oneWon = 0\n twoWon = 0\n draws = 0\n\n # # Multiprocess pitting\n # proccesses = []\n # work_queue = mp.Queue()\n # done_queue = mp.Queue()\n\n # print(\"[Master] Spawning Workers...\")\n\n # # Spawn workers\n # for i in range(self.num_workers):\n # tup = (work_queue, done_queue, i, self.player1, self.player2)\n # proc = mp.Process(target=self.arena_worker, args=tup)\n # proc.start()\n\n # proccesses.append(proc)\n\n # print(\"[Master] Adding work...\")\n\n # # Add work to queue\n # first_half = int(num / 2)\n # for i in range(first_half):\n # data = dict()\n # data[\"i\"] = i\n # data[\"player\"] = 1\n # data[\"game\"] = copy.deepcopy(self.game)\n # data[\"verbose\"] = verbose\n\n # work_queue.put(data)\n\n # second_half = num - first_half\n # for i in range(second_half):\n # data = dict()\n # data[\"i\"] = i\n # data[\"player\"] = -1 # Switch players\n # data[\"game\"] = copy.deepcopy(self.game)\n # data[\"verbose\"] = verbose\n\n # work_queue.put(data)\n\n # print(\"[Master] Waiting for results...\")\n\n # Wait for results to come in\n first_half = int(num / 2)\n for i in range(first_half):\n start = time.time()\n \n gameResult = self.playGame(verbose=verbose)\n\n if gameResult == 1:\n oneWon += 1\n elif gameResult == -1:\n twoWon += 1\n else:\n draws += 1\n\n # bookkeeping + plot progress\n tracker.update(time.time() - start)\n bar.suffix = '({eps}/{maxeps}) Eps Time: {et:.3f}s | Total: {total:} | ETA: {eta:}'.format(\n eps=i + 1, maxeps=num, et=tracker.avg(), total=bar.elapsed_td, \n eta=tracker.eta(i + 1, num))\n bar.next()\n\n self.player1, self.player2 = self.player2, self.player1\n\n second_half = num - first_half\n for i in range(second_half):\n start = time.time()\n \n gameResult = self.playGame(verbose=verbose)\n\n if gameResult == -1:\n oneWon += 1\n elif gameResult == 1:\n twoWon += 1\n else:\n draws += 1\n\n # bookkeeping + plot progress\n tracker.update(time.time() - start)\n bar.suffix = '({eps}/{maxeps}) Eps Time: {et:.3f}s | Total: {total:} | ETA: {eta:}'.format(\n eps=i + first_half + 1, maxeps=num, et=tracker.avg(), total=bar.elapsed_td, \n eta=tracker.eta(i + 1, num))\n bar.next()\n\n # print(\"[Master] Killing workers...\")\n\n # # Kill workers\n # for p in proccesses:\n # p.terminate()\n # p.join()\n\n bar.finish()\n\n print(\"Player 1 Won: \" + str(oneWon) + \", Player 2 Won: \"+str(twoWon)+\", Draws: \"+str(draws))\n return oneWon, twoWon, draws\n"
] | [
[
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
opimentel-github/sne-lightcurves-synthetic | [
"4273ac6dc8defd25d257f9ef6a1115510a71b3d2"
] | [
"synthsne/generators/time_meshs.py"
] | [
"from __future__ import print_function\nfrom __future__ import division\nfrom . import _C\n\nimport numpy as np\n\n###################################################################################################################################################\n\ndef get_random_time_mesh(ti, tf, min_dt):\n\tif tf<=ti:\n\t\treturn []\n\tt0 = ti+np.random.uniform(0, min_dt)\n\tnew_times = []\n\twhile t0<tf:\n\t\tnew_times.append(t0)\n\t\tt0 += min_dt\n\treturn new_times\n\t\ndef get_augmented_time_mesh(times, ti, tf, min_dt, extra_times,\n\tdropout_p=0.0,\n\t):\n\tassert dropout_p>=0 and dropout_p<=1\n\tassert tf>=ti\n\tif tf==ti:\n\t\treturn [ti]\n\tif tf-ti<min_dt:\n\t\treturn np.random.uniform(ti, tf, size=1)\n\n\tnew_times = [ti-min_dt]+[t for t in np.sort(times) if t>=ti and t<=tf]+[tf+min_dt]\n\tpossible_times = []\n\tfor i in range(0, len(new_times)-1):\n\t\tti_ = new_times[i]\n\t\ttf_ = new_times[i+1]\n\t\tassert tf_>=ti_\n\t\ttimes_ = get_random_time_mesh(ti_+min_dt, tf_-min_dt, min_dt)\n\t\t#print(ti_+min_dt, tf_-min_dt, times_)\n\t\tpossible_times += times_\n\t\n\tpossible_times = np.array(possible_times) if extra_times is None else np.random.permutation(possible_times)[:extra_times]\n\tvalid_indexs = np.random.uniform(size=len(possible_times))>=dropout_p\n\tpossible_times = possible_times[valid_indexs]\n\taugmented_time_mesh = np.sort(np.concatenate([times, possible_times])) # sort\n\treturn augmented_time_mesh"
] | [
[
"numpy.sort",
"numpy.concatenate",
"numpy.random.permutation",
"numpy.random.uniform",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
daeseoklee/DeepPocket | [
"a20904e3c9ab8acbb498aa40aee91ac99149dc66"
] | [
"segment_pockets.py"
] | [
"'''\nSegment out pocket shapes from top ranked pockets\n'''\nimport torch\nimport torch.nn as nn\nfrom unet import Unet\nimport numpy as np\nimport logging\nimport argparse\nimport wandb\nimport sys\nimport os\nimport molgrid\nfrom skimage.morphology import binary_dilation\nfrom skimage.morphology import cube\nfrom skimage.morphology import closing\nfrom skimage.segmentation import clear_border\nfrom skimage.measure import label\nfrom scipy.spatial.distance import cdist\nfrom prody import *\n\ndef preprocess_output(input, threshold):\n input[input>=threshold]=1\n input[input!=1]=0\n input=input.numpy()\n bw = closing(input).any(axis=0)\n # remove artifacts connected to border\n cleared = clear_border(bw)\n\n # label regions\n label_image, num_labels = label(cleared, return_num=True)\n largest=0\n for i in range(1, num_labels + 1):\n pocket_idx = (label_image == i)\n pocket_size = pocket_idx.sum()\n if pocket_size >largest:\n largest=pocket_size\n for i in range(1, num_labels + 1):\n pocket_idx = (label_image == i)\n pocket_size = pocket_idx.sum()\n if pocket_size <largest:\n label_image[np.where(pocket_idx)] = 0\n label_image[label_image>0]=1\n return torch.tensor(label_image,dtype=torch.float32)\n\ndef get_model_gmaker_eproviders(args):\n # test example provider\n eptest = molgrid.ExampleProvider(shuffle=False, stratify_receptor=False,iteration_scheme=molgrid.IterationScheme.LargeEpoch,default_batch_size=1)\n eptest.populate(args.test_types)\n # gridmaker with defaults\n gmaker_img = molgrid.GridMaker(dimension=32)\n\n return gmaker_img, eptest\n\ndef Output_Coordinates(tensor,center,dimension=16.25,resolution=0.5):\n #get coordinates of mask from predicted mask\n tensor=tensor.numpy()\n indices = np.argwhere(tensor>0).astype('float32')\n indices *= resolution\n center=np.array([float(center[0]), float(center[1]), float(center[2])])\n indices += center\n indices -= dimension\n return indices\n\ndef predicted_AA(indices,prot_prody,distance):\n #amino acids from mask distance thresholds\n prot_coords = prot_prody.getCoords()\n ligand_dist = cdist(indices, prot_coords)\n binding_indices = np.where(np.any(ligand_dist <= distance, axis=0))\n #get predicted protein residue indices involved in binding site\n prot_resin = prot_prody.getResindices()\n prot_binding_indices = prot_resin[binding_indices]\n prot_binding_indices = sorted(list(set(prot_binding_indices)))\n return prot_binding_indices\n\ndef output_pocket_pdb(pocket_name,prot_prody,pred_AA):\n #output pocket pdb\n #skip if no amino acids predicted\n if len(pred_AA)==0:\n return\n sel_str= 'resindex '\n for i in pred_AA:\n sel_str+= str(i)+' or resindex '\n sel_str=' '.join(sel_str.split()[:-2])\n pocket=prot_prody.select(sel_str)\n writePDB(pocket_name,pocket)\n\ndef parse_args(argv=None):\n '''Return argument namespace and commandline'''\n parser = argparse.ArgumentParser(description='Train neural net on .types data.')\n parser.add_argument('--test_types', type=str, required=True,\n help=\"test types file\")\n parser.add_argument('--model_weights', type=str, required=True,\n help=\"weights for UNET\")\n parser.add_argument('-t', '--threshold', type=float, required=False,\n help=\"threshold for segmentation\", default=0.5)\n parser.add_argument('-r', '--rank', type=int, required=False,\n help=\"number of pockets to segment\", default=1)\n parser.add_argument('--upsample', type=str, required=False,\n help=\"Type of Upsampling\", default=None)\n parser.add_argument('--num_classes', type=int, required=False,\n help=\"Output channels for predicted masks, default 1\", default=1)\n parser.add_argument('--dx_name', type=str, required=True,\n help=\"dx file name\")\n parser.add_argument('-p','--protein', type=str, required=False, help=\"pdb file for predicting binding sites\")\n parser.add_argument('--mask_dist', type=float, required=False,\n help=\"distance from mask to residues\", default=3.5)\n args = parser.parse_args(argv)\n\n argdict = vars(args)\n line = ''\n for (name, val) in list(argdict.items()):\n if val != parser.get_default(name):\n line += ' --%s=%s' % (name, val)\n\n return (args, line)\n\ndef test(model, test_loader, gmaker_img, device, seg_output_dir, args):\n if args.rank==0:\n return\n model.eval()\n dims = gmaker_img.grid_dimensions(test_loader.num_types())\n tensor_shape = (1,) + dims\n #create tensor for input, centers and indices\n input_tensor = torch.zeros(tensor_shape, dtype=torch.float32, device=device, requires_grad=True)\n float_labels = torch.zeros((1, 4), dtype=torch.float32, device=device)\n prot_prody=parsePDB(args.protein)\n for count, batch in enumerate(test_loader, start=1):\n # update float_labels with center and index values\n batch.extract_labels(float_labels)\n centers = float_labels[:, 1:]\n for b in range(1):\n center = molgrid.float3(float(centers[b][0]), float(centers[b][1]), float(centers[b][2]))\n # Update input tensor with b'th datapoint of the batch \n gmaker_img.forward(center, batch[b].coord_sets[0], input_tensor[b])\n # Take only the first 14 channels as that is for proteins, other 14 are ligands and will remain 0.\n masks_pred = model(input_tensor[:, :14])\n masks_pred=masks_pred.detach().cpu()\n masks_pred=preprocess_output(masks_pred[0], args.threshold)\n # predict binding site residues\n pred_coords = Output_Coordinates(masks_pred, center)\n pred_aa = predicted_AA(pred_coords, prot_prody, args.mask_dist)\n output_pocket_pdb(os.path.join(seg_output_dir, f'pocket{count}.pdb'), prot_prody,pred_aa)\n masks_pred=masks_pred.cpu()\n # Output predicted mask in .dx format \n masks_pred=molgrid.Grid3f(masks_pred)\n molgrid.write_dx(os.path.join(seg_output_dir, f'pocket{count}.dx'), masks_pred,center,0.5,1.0)\n if count>=args.rank:\n break\n\nif __name__ == \"__main__\":\n (args, cmdline) = parse_args()\n gmaker_img, eptest = get_model_gmaker_eproviders(args)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = Unet(args.num_classes, args.upsample)\n model.to(device)\n checkpoint = torch.load(args.model_weights)\n model.cuda()\n model = nn.DataParallel(model)\n model.load_state_dict(checkpoint['model_state_dict'])\n dx_name=args.dx_name\n test(model, eptest, gmaker_img,device,dx_name, args)\n"
] | [
[
"torch.zeros",
"torch.load",
"scipy.spatial.distance.cdist",
"torch.tensor",
"numpy.argwhere",
"numpy.any",
"torch.cuda.is_available",
"torch.nn.DataParallel",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
npucino/hylite | [
"dff1314a2a0c281fd2fc1a5ee03bdba3e0c49f28",
"dff1314a2a0c281fd2fc1a5ee03bdba3e0c49f28"
] | [
"hylite/correct/panel.py",
"hylite/project/basic.py"
] | [
"import matplotlib.pyplot as plt\nfrom matplotlib import path\nimport numpy as np\nfrom scipy.optimize import least_squares\nimport matplotlib.patches as patches\nimport cv2\n\nimport hylite\nfrom hylite.reference.features import HyFeature\nfrom hylite import HyData\nfrom hylite.project import pix_to_ray_pano, pix_to_ray_persp\n\n\nclass Panel( HyData ):\n \"\"\"\n A class for identifying calibration reference in images and storing\n the observed pixel radiances and known target reflectance values. This is used\n by, e.g., empirical line calibration procedures.\n \"\"\"\n\n def __init__(self, material, radiance, **kwds):\n \"\"\"\n Generic constructor. Can be of the following forms:\n\n *Arguments*:\n - material = a hylite.reference.Target instance containing target reflectance data for this panel.\n - radiance = either a HyImage object (which contains some reference pixels) or a\n NxM numpy array containing radiance values for N pixels across M bands.\n\n *Keywords*:\n - wavelengths = wavelengths corresponding to the radiance values (if radiance is an array rather than a HyImage\n object).\n - method = 'manual' (default) to manually pick reference in image (using an interactive plot). Can also be\n 'sobel' or 'laplace' to use the corresponding edge detectors to automatically identify the\n calibration target (using OpenCV contouring).\n - bands = list of band indices (integer) or wavelengths (float) to use when selecting the target.\n - edge_thresh = the edge threshold (as percentile of gradient values) used when automatically identifying reference.\n Default is 95.\n - area_thresh = the minimum area (in pixels) of candidate panels. Used to discard small/bright areas. Default is 100.\n - shrink = a shrink factor to reduce the size of reference identified automatically (and so remove dodgy pixels\n near the target edge/frame. Default is 0.4.\n - db = If True, visualisation of the edge detection layers will be plotted for debug purposes. Default is false.\n \"\"\"\n\n super().__init__(None) # initialise header etc.\n self.source_image = None # init defaults\n self.outline = None\n self.normal = None\n\n if isinstance(radiance, np.ndarray): # radiance is a list of pixels\n\n # check and copy radiance data\n if len(radiance.shape) == 1: # we've been given mean radiances\n radiance = radiance[np.newaxis, :]\n assert len(radiance.shape) == 2, \"Error, radiance must be a 2-D array (N pixels by M bands).\"\n self.data = radiance.copy()\n\n # check and copy wavelength data\n assert 'wavelengths' in kwds, \"Error - wavelengths must be provided for pixel array.\"\n self.set_wavelengths(np.array(kwds[\"wavelengths\"]))\n\n elif radiance.is_image(): # radiance is a hyimage\n\n self.source_image = radiance # store reference to original image\n\n method = kwds.get(\"method\", 'manual') # what method to use to pick target?\n bands = kwds.get(\"bands\", 428.0)\n\n # select target region\n if 'manual' in method.lower(): # pick region using interactive plot\n verts = radiance.pickPolygons(region_names=['Target'], bands=bands)[0]\n verts = np.vstack([verts, verts[0][None, :]]) # add return to first point\n self.outline = path.Path(verts) # make matplotlib path from selected region\n\n else:\n db = kwds.get('db', False) # draw plots?\n\n # calculate greyscale image\n if isinstance(bands, tuple) or isinstance(bands, list):\n bands = [radiance.get_band_index(b) for b in bands] # convert to indices\n gray = np.sum(radiance.data[:, :, bands], axis=2) / np.nanmax(radiance.data[:, :, bands])\n else:\n bands = radiance.get_band_index(bands)\n gray = radiance.data[:, :, bands] / np.nanmax(radiance.data[:, :, bands])\n gray = cv2.GaussianBlur(gray, (3, 3), 0) # apply slight blur to improve edge detection\n\n if db:\n plt.figure(figsize=(20, 10))\n plt.imshow(gray.T, cmap='gray')\n plt.title(\"Greyscale\")\n plt.show()\n\n # extract edges\n if 'sobel' in method.lower() or 'auto' in method.lower(): # pick edges using sobel filter\n sobelx = cv2.Sobel(gray.astype(np.float32), cv2.CV_64F, 1, 0, ksize=5) # x\n sobely = cv2.Sobel(gray.astype(np.float32), cv2.CV_64F, 0, 1, ksize=5) # y\n sobel = np.sqrt(sobelx ** 2 + sobely ** 2)\n thresh = np.nanpercentile(sobel, kwds.get('edge_thresh', 95))\n edge = sobel > thresh\n elif 'laplace' in method.lower(): # pick edges using laplace filter\n laplacian = cv2.Laplacian(gray.astype(np.float32), cv2.CV_32F)\n thresh = np.nanpercentile(laplacian, kwds.get('edge_thresh', 95))\n edge = laplacian > thresh\n else:\n assert False, \"Error - %s is not a recognised extraction method. Try 'sobel' or 'laplace'.\" % method\n\n if db:\n plt.figure(figsize=(20, 10))\n plt.imshow(edge.T)\n plt.title(\"Edge\")\n plt.show()\n\n # contour and find object contours\n _, threshold = cv2.threshold(edge.astype(np.uint8) * 254, 240, 255, cv2.THRESH_BINARY)\n _, contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n # find brightest quadrilateral with area above threshold\n maxCtr = None\n maxBright = -1\n area_thresh = kwds.get(\"area_thresh\", 100)\n for cnt in contours:\n\n # simplify/approximate contour\n approx = cv2.approxPolyDP(cnt, 0.1 * cv2.arcLength(cnt, True), True)\n\n # is it a quadrilateral?\n if approx.shape[0] == 4:\n # calculate area\n area = cv2.contourArea(approx)\n if area > area_thresh: # large enough?\n # calculate approx brightness (by summing bounding box)\n verts = np.array([approx[:, 0, 1], approx[:, 0, 0]]).T\n xmin, xmax = np.min(verts[..., 0]), np.max(verts[..., 0])\n ymin, ymax = np.min(verts[..., 1]), np.max(verts[..., 1])\n patch = gray[xmin:xmax, ymin:ymax]\n bright = np.nanmedian(patch)\n\n if db:\n plt.imshow(gray.T, cmap='gray')\n plt.title(\"Candidate panel\")\n plt.axvline(xmin, color='r')\n plt.axvline(xmax, color='r')\n plt.axhline(ymin, color='r')\n plt.axhline(ymax, color='r')\n plt.show()\n\n # store?\n if maxBright < bright:\n maxCtr = approx\n maxBright = bright\n\n # convert to maplotlib path\n verts = np.array([maxCtr[:, 0, 1], maxCtr[:, 0, 0]]).T\n verts = np.vstack([verts, verts[0][None, :]]) # add return to first point\n self.outline = path.Path(verts, closed=True) # make matplotlib path from selected region\n\n # shrink to 40% of original size (to remove frame and dodgy edge pixels)\n centroid = np.mean(self.outline.vertices[1::, :], axis=0)\n verts = kwds.get(\"shrink\", 0.4) * (self.outline.vertices - centroid) + centroid\n self.outline = path.Path(verts, closed=True)\n\n # calculate pixels within selected region\n xx, yy = np.meshgrid(np.arange(radiance.xdim()), np.arange(radiance.ydim()))\n xx = xx.flatten()\n yy = yy.flatten()\n points = np.vstack([xx, yy]).T # coordinates of each pixel\n mask = self.outline.contains_points(points) # identify points within path\n mask = mask.reshape((radiance.ydim(), radiance.xdim())).T # reshape to pixel mask\n\n # extract pixel reflectance values based on this mask\n self.data = np.array([radiance.data[:, :, b][mask] for b in range(radiance.band_count())]).T\n\n # also copy across wavelength info\n assert radiance.has_wavelengths(), \"Error - radiance image must have wavelength information.\"\n self.set_wavelengths(radiance.get_wavelengths()) # get wavelength data\n\n else:\n assert False, \"Error: radiance argument must be a HyImage instance or a numpy array of pixels.\"\n\n # if we have lots of target pixels (we don't need that many), only keep top 50% [as darker ones likely result from\n # dodgy border effects\n if self.data.shape[0] > 30:\n brightness = np.nanmean(self.data, axis=1)\n mask = brightness > np.nanpercentile(brightness, 50)\n self.data = self.data[mask, :]\n\n # extract reflectance data from target\n target_bands = material.get_wavelengths()\n assert np.nanmin(target_bands) <= np.nanmin(\n self.get_wavelengths()), \"Error - calibration range does not cover pixel range. \" \\\n \"Radiance data starts at %.1f nm but calibration data starts %.1f nm.\" % (\n np.nanmin(self.get_wavelengths()), np.nanmin(target_bands))\n assert np.nanmax(target_bands) >= np.nanmax(\n self.get_wavelengths()), \"Error - calibration range does not cover pixel range. \" \\\n \"Radiance data ends at %.1f nm but calibration data ends %.1f nm.\" % (\n np.nanmax(self.get_wavelengths()), np.nanmax(target_bands))\n idx = [np.argmin(np.abs(target_bands - w)) for w in self.get_wavelengths()] # matching wavelengths\n self.reflectance = material.get_reflectance()[idx]\n self.material = material\n\n def copy(self):\n \"\"\"\n Make a deep copy of this panel instance.\n\n *Returns*\n - a new Panel instance.\n \"\"\"\n return Panel( self.material, self.data, wavelengths=self.get_wavelengths() )\n\n def get_mean_radiance(self):\n \"\"\"\n Calculate and return the mean radiance for each band of all the pixels in this calibration region.\n \"\"\"\n return np.nanmean(self.data, axis=0)\n\n def get_reflectance(self):\n \"\"\"\n Get the known (reference) reflectance of this panel.\n \"\"\"\n return self.reflectance\n\n def get_normal(self, cam=None, recalc=False):\n \"\"\"\n Get the normal vector of this panel by assuming its outline is square (prior to projection onto the camera).\n\n *Arguments*:\n - cam = a Camera object describing the pose of the camera from which the panel is viewed. Default is None (to retrieve\n previously stored normals)\n - recalc = True if a precomputed (or otherwise defined) normal vector should be recalculated. Default is False.\n *Returns*:\n - norm = the normal vector of the panel (in world coordinates). This is also stored as self.normal.\n \"\"\"\n\n if recalc or self.normal is None:\n\n # check outline is available\n assert cam is not None, \"Error - normal vector not previously defined. Please specify a camera object (cam) to estimate normal.\"\n assert self.outline is not None, \"Error - self.outline must contain four points to estimate this panels normal vector...\"\n\n # get corners of panel and convert to rays\n corners = np.array([self.outline.vertices[i, :] for i in range(4)])\n\n if cam.is_panoramic():\n ray1 = pix_to_ray_pano(corners[0, 0], corners[0, 1], cam.fov, cam.step, cam.dims)\n ray2 = pix_to_ray_pano(corners[1, 0], corners[1, 1], cam.fov, cam.step, cam.dims)\n ray3 = pix_to_ray_pano(corners[2, 0], corners[2, 1], cam.fov, cam.step, cam.dims)\n ray4 = pix_to_ray_pano(corners[3, 0], corners[3, 1], cam.fov, cam.step, cam.dims)\n else:\n ray1 = pix_to_ray_persp(corners[0, 0], corners[0, 1], cam.fov, cam.dims)\n ray2 = pix_to_ray_persp(corners[1, 0], corners[1, 1], cam.fov, cam.dims)\n ray3 = pix_to_ray_persp(corners[2, 0], corners[2, 1], cam.fov, cam.dims)\n ray4 = pix_to_ray_persp(corners[3, 0], corners[3, 1], cam.fov, cam.dims)\n\n a = 1.0 # length of each square (in arbitrary coordinates)\n h = np.sqrt(2) # length of hypot relative to sides\n\n def opt(x, sol=False):\n # get test depths\n z1, z2, z3, z4 = x\n\n # calculate edge coordinates\n A = ray1 * z1\n B = ray2 * z2\n C = ray3 * z3\n D = ray4 * z4\n\n # and errors with edge lengths\n AB = np.linalg.norm(B - A)\n BC = np.linalg.norm(C - B)\n CD = np.linalg.norm(D - C)\n DA = np.linalg.norm(A - D)\n AC = np.linalg.norm(C - A)\n BD = np.linalg.norm(D - B)\n\n if not sol:\n return [AB - a, BC - a, CD - a, DA - a, AC - h, BD - h] # return for optimiser\n else: # return solution (normal vector)\n AB = (B - A) / AB\n BC = (C - B) / BC\n return np.cross(AB, BC)\n\n # get normal vector in camera coords\n sol = least_squares(opt, (10.0, 10.0, 10.0, 10.0))\n norm = opt(sol.x, sol=True)\n\n # rotate to world coords\n norm = np.dot(cam.get_rotation_matrix(), norm)\n self.set_normal(norm)\n\n return self.normal\n\n def set_normal(self, n ):\n \"\"\"\n Set panel normal vector to a known vector.\n\n *Arguments*:\n - n = a (3,) numpy array containing the normal vector in world coordinates.\n \"\"\"\n if n is None:\n self.normal = None # remove normal\n else:\n assert len(n) == 3, \"Error - n must be a (3,) normal vector.\"\n self.normal = np.array(n) / np.linalg.norm(n) # enforce n has length 1.0\n if self.normal[2] < 0:\n self.normal *= -1 # panel always points upwards\n\n def get_skyview(self, hori_elev=0.0, up=np.array([0, 0, 1])):\n \"\"\"\n Get this panels skyview factor. Normal vector must be defined, otherwise an error will be thrown.\n\n *Arguments*:\n - hori_elev = the angle from the panel to the horizon (perpendicular to the panel's orientation) in degrees.\n Used to reduce the sky view factor if the panel is below the horizon (e.g. in an open pit mine).\n Default is 0.0 (i.e. assume a flat horizon). Can also be negative if sky is visible below the\n (flat) horizon.\n - up = the vertical (up) vector. Default is [0,0,1].\n *Returns*:\n - this panels sky view factor (assuming the panel is relatively unoccluded and the horizon is flat).\n \"\"\"\n\n # proportion of sky visible assuming horizontal horizon\n s = (np.pi - np.arccos(np.dot(up, self.normal))) / np.pi\n\n # adjust according to hori_elev [ and enforce range from 0 - 1.0\n return min(max(0, s - (np.deg2rad(hori_elev) / np.pi)), 1.0)\n\n def get_alpha(self, illudir):\n \"\"\"\n Return the reflected light fraction of this panel based on the specified illumination direction using\n Lamberts' cosine law.\n \"\"\"\n assert len(illudir) == 3, \"Error - illudir must be a (3,) numpy array.\"\n if illudir[2] > 0: # check illudir is pointing downwards\n illudir = illudir * -1\n return max( 0, np.dot( -self.normal, illudir ) )\n\n def quick_plot(self, bands=hylite.RGB, **kwds):\n\n \"\"\"\n Quickly plot the outline of this calibration target for quality checking etc.\n\n *Arguments*:\n - bands = the image bands to plot as a preview. Default is io.HyImage.RGB.\n *Keywords*:\n - keywords are passed to HyData.plot_spectra( ... ).\n \"\"\"\n if self.source_image is not None: # plot including preview of panel\n fig, ax = plt.subplots(1, 2, figsize=(15, 5), gridspec_kw={'width_ratios': [1, 3]})\n\n # plot base image\n self.source_image.quick_plot(bands, ax=ax[0])\n ax[0].set_xticks([])\n ax[0].set_yticks([])\n\n # plot target on image and set extents\n patch = patches.PathPatch(self.outline, edgecolor='orange', fill=False, lw=2)\n bbox = self.outline.get_extents()\n padx = (bbox.max[0] - bbox.min[0]) * 1.5\n pady = (bbox.max[1] - bbox.min[1]) * 1.5\n ax[0].add_patch(patch)\n ax[0].set_xlim(bbox.min[0] - padx, bbox.max[0] + padx)\n ax[0].set_ylim(bbox.max[1] + pady, bbox.min[1] - pady)\n\n # plot spectra\n kwds['labels'] = kwds.get('labels', HyFeature.Themes.ATMOSPHERE)\n self.plot_spectra( ax=ax[1], **kwds )\n else: # no image data, just plot spectra\n kwds['labels'] = kwds.get('labels', HyFeature.Themes.ATMOSPHERE)\n fig, ax = self.plot_spectra(**kwds)\n ax.set_ylabel('Downwelling Radiance')\n return fig, ax\n\n def plot_ratio(self, ax = None):\n\n \"\"\"\n Plots the ratio between known reflectance and observed radiance for each band in this target.\n\n *Arguments*:\n - ax = the axes to plot on. If None (default) then a new axes is created.\n *Returns*:\n -fig, ax = the figure and axes objects containing the plot.\n \"\"\"\n\n if ax is None:\n fig, ax = plt.subplots(figsize=(15, 10))\n\n # calculate ratio\n ratio = self.get_mean_radiance() / self.get_reflectance()\n\n # plot\n ax.plot( self.get_wavelengths(), ratio )\n ax.set_ylabel(\"radiance / reflectance\" )\n ax.set_xlabel(\"Wavelength (nm)\")\n\n return fig, ax\n\n",
"import numpy as np\nfrom scipy import spatial\nimport cv2\n\ndef proj_persp( xyz, C, a, fov, dims, normals=None):\n \"\"\"\n Project 3d point xyz based on a pinhole camera model.\n\n *Arguments*:\n - xyz = a nx3 numpy array with a position vector (x,y,z) in each column.\n - C = the position of the camera.\n - a = the three camera rotatation euler angles (appled around x, then y, then z == pitch, roll, yaw). In DEGREES.\n - fov = the vertical field of view.\n - dims = the image dimensions (width, height)\n - normals = per-point normals. Used to do backface culling if specified. Default is None (not used).\n \"\"\"\n\n #transform origin to camera position\n xyz = xyz - C[None,:]\n\n # backface culling\n vis = np.full(xyz.shape[0],True,dtype=np.bool)\n if not normals is None:\n ndv = np.einsum('ij, ij->i', normals, xyz) #calculate dot product between each normal and vector from camera to point\n #(which is the point position vector in this coordinate system)\n vis = ndv < 0 #normal is pointing towards the camera (in opposite direction to view)\n\n #apply camera rotation to get to coordinate system\n # where y is camera up and z distance along the view axis\n R = spatial.transform.Rotation.from_euler('XYZ',-a,degrees=True).as_matrix()\n #xyz = np.dot(xyz, R)\n xyz = xyz@R\n\n #calculate image plane width/height in projected coords\n h = 2 * np.tan( np.deg2rad( fov / 2 ) )\n w = h * dims[0] / float(dims[1])\n\n #do project and re-map to image coordinates such that (0,0) = lower left, (1,1) = top right)\n px = ((w/2.0) + (xyz[:,0] / -xyz[:,2])) / w\n py = ((h/2.0) + (xyz[:,1] / xyz[:,2])) / h\n pz = -xyz[:,2] #return positive depths for convenience\n\n #calculate mask showing 'visible' points based on image dimensions\n vis = vis & (pz > 0) & (px > 0) & (px < 1) & (py > 0) & (py < 1)\n\n #convert to pixels\n px *= dims[0]\n py *= dims[1]\n\n return np.array([px,py,pz]).T, vis\n\ndef proj_pano(xyz, C, a, fov, dims, step=None, normals=None):\n \"\"\"\n Project 3d point xyz based on a pinhole camera model.\n\n *Arguments*:\n - xyz = a nx3 numpy array with a position vector (x,y,z) in each column.\n - C = the position of the camera.\n - a = the three camera rotatation euler angles (appled around x, then y, then z == pitch, roll, yaw). In DEGREES.\n - fov = the vertical field of view.\n - dims = the image dimensions (width, height)\n - step = the angular step (degrees) between pixels in x. If None, this is calculated to ensure square pixels.\n - normals = per-point normals. Used to do backface culling if specified. Default is None (not used).\n \"\"\"\n\n # transform origin to camera position\n xyz = xyz - C[None, :]\n\n # backface culling\n vis = np.full(xyz.shape[0], True, dtype=np.bool)\n if not normals is None:\n ndv = np.einsum('ij, ij->i', normals,\n xyz) # calculate dot product between each normal and vector from camera to point\n # (which is the point position vector in this coordinate system)\n vis = ndv < 0 # normal is pointing towards the camera (in opposite direction to view)\n\n # apply camera rotation to get to coordinate system\n # where y is camera up and z distance along the view axis\n R = spatial.transform.Rotation.from_euler('XYZ', -a, degrees=True).as_matrix()\n #xyz = np.dot(xyz, R)\n xyz = xyz@R\n\n # calculate image height (in projected coords) for vertical perspective project\n h = 2 * np.tan(np.deg2rad(fov / 2))\n\n # calculate position in spherical coords\n pz = np.sqrt(xyz[:, 0] ** 2 + xyz[:, 2] ** 2) # distance from axis of rotation (world units)\n py = ((h / 2.0) + (xyz[:, 1] / -pz)) / h # perspective project vertically (0 - 1; pin-hole camera model)\n px = np.arctan2(xyz[:, 0], -xyz[:, 2]) # rotation left/right of view axis (in radians)\n\n # convert x to pixels (slightly tricky)\n if step is None:\n step = fov / dims[1] # angular pixel size in y = angular pixel size in x, assuming pixels are square...\n px = px / np.deg2rad(step) + (dims[0] / 2)\n\n # convert y to pixels (easy)\n py *= dims[1]\n\n # calculate mask showing 'visible' points based on image dimensions\n vis = vis & (px > 0) & (px < dims[0]) & (py > 0) & (py < dims[1])\n\n return np.array([px, py, pz]).T, vis\n\ndef proj_ortho( xyz, C, V, s=1.0 ):\n \"\"\"\n Project points onto a plane (orthographic projection).\n\n *Arguments*:\n - xyz = a nx3 numpy array with a position vector (x,y,z) in each column.\n - C = the position of the viewing plane origin (will become pixel 0,0).\n - V = the [x,y,z] viewing/projection vector (normal to the projection plane).\n - s = the scale factor to transform world coordinates into image coordinates. Default is 1.0 (keep world coords).\n *Returns*:\n - px,py,pz = projected point coordinates (x,y,depth)\n - vis = array containing True if each point is visible and False for points behind the viewing plane.\n \"\"\"\n\n xyz = xyz - C[None, :] # center origin on camera\n #pz = np.dot(xyz, V) # calculate depths (distances from plane)\n pz = xyz@V\n xyz -= (V[None, :] * pz[:, None]) # project onto plane (by removing depth)\n return s*np.array([ xyz[:,0], xyz[:,1], pz]).T, pz > 0\n\ndef rasterize(points, vis, vals, dims, s=1):\n \"\"\"\n Rasterizes projected points onto an image grid.\n\n *Arguments*:\n - points = the points (px,py,depth) to rasterise,\n as returned by proj_persp or proj_pano.\n - vis = a boolean array that is True if the points are visible (as returned by\n proj_persp or proj_pano).\n - vals = Nxm array of (m) additional point values (e.g. position, normals, colour) to add to rasterize. Alternatively\n a list of Nxm numpy arrays can be passed (these will be concatentated).\n - dims = the size of the image grid.\n - s = the size of the points in pixels. Default is 1.\n *Returns*:\n - raster = rasterised image with m bands corresponding to vals.\n - depth = the depth buffer.\n \"\"\"\n\n #vals is a list of numpy arrays - stack them\n if isinstance(vals, list):\n if len(vals[0].shape) == 1: #list of 1-d arrays; need to v-stack\n vals = np.vstack(vals).T\n else: #list of n-d arrays; need to h-stack\n vals = np.hstack(vals)\n\n #shoulder case - vals is a 1D numpy array, so we need to add second axis\n if len(np.array(vals).shape) == 1:\n vals = vals[None, :].T\n\n # create image arrays\n out = np.full((dims[0], dims[1], vals.shape[1]), np.nan)\n depth = np.full((dims[0], dims[1]), np.inf)\n\n # cull invisible points\n points = points[vis, :]\n vals = vals[vis, :]\n\n # loop through points\n assert points.shape[1] == 3, \"Error - points array should have shape (N,3).\"\n assert isinstance(s, int), \"Error - size (s) must be an integer.\"\n if s > 0: s -= 1 #reduce s by one due to how numpy does indexing.\n for i, p in enumerate(points):\n x = int(p[0])\n y = int(p[1])\n z = p[2]\n\n # double check point in the image\n if x < 0 or x >= dims[0] or y < 0 or y > dims[1]:\n continue # skip\n\n if z < depth[x, y]: # in front of depth buffer?\n out[(x - s):(x + s + 1), (y - s):(y + s + 1), :] = vals[None, None, i]\n depth[(x - s):(x + s + 1), (y - s):(y + s + 1)] = z\n\n return out, depth\n\ndef pix_to_ray_persp(x, y, fov, dims):\n \"\"\"\n Transform pixel coordinates to a unit direction (ray) in camera coordinates using a\n perspective pinhole camera model.\n\n *Arguments*:\n - x = the pixel x-coordinate. Cannot be array (only works for single pixels).\n - y = the pixel y-coordinate. Cannot be array (only works for single pixels).\n - fov = the camera's vertical field of view (degrees)\n - dims = the dimensions of the image the pixels are contained in.\n\n *Returns*:\n - numpy array with the components of the light ray in camera coordinates (z == view direction, y == up)\n \"\"\"\n\n aspx = dims[0] / float(dims[1])\n h = 2 * np.tan(np.deg2rad(fov / 2))\n Px = (2 * (x / dims[0]) - 1) * h / 2 * aspx\n Py = (2 * (y / dims[1]) - 1) * h / 2\n ray = np.array([Px, -Py, -1])\n return ray / np.linalg.norm(ray) # return normalized ray\n\ndef pix_to_ray_pano(x, y, fov, step, dims):\n \"\"\"\n Transform pixel coordinates to a unit direction (ray) in camera coordinates using a\n panoramic camera model.\n\n *Arguments*:\n - px = the pixel x-coordinate. Cannot be array (only works for single pixels).\n - py = the pixel y-coordinate. Cannot be array (only works for single pixels).\n - fov = the camera's vertical field of view (degrees)\n - step = the angular step between pixels in the x-direction.\n - dims = the dimensions of the image the pixels are contained in.\n\n *Returns*:\n - numpy array with the components of the light ray in camera coordinates (z == view direction, y == up)\n \"\"\"\n\n # calculate image plane properties\n h = 2 * np.tan(np.deg2rad(fov / 2))\n\n # calculate ray in y-z plane\n Py = (2 * (y / dims[1]) - 1) * h / 2 # transform y pixels to camera coords\n ray = np.array([0, -Py, -1]) # construct ray vector\n ray = ray / np.linalg.norm(ray)\n\n # rotate it around y based on x\n alpha = (x - (dims[0] / 2.0)) * step # map to angle coords (-180 to 180 degrees)\n R = spatial.transform.Rotation.from_euler('Y', alpha, degrees=True).as_matrix()\n\n return np.dot(ray, R) # return rotated ray\n\ndef pano_to_persp(x, y, fov, step, dims):\n \"\"\"\n Transforms pixels in a panoramic image to pixel coordinates as though they had been captured using a\n perspective camera with the same dimensions.\n\n *Arguments*:\n - x = array of pixel x-coordinates. These will be projected onto the image plane.\n - y = array of pixel y-coordinate.\n - fov = the camera's vertical field of view (degrees)\n - step = the angular step between pixels in the x-direction.\n - dims = the dimensions of the image the pixels are contained in.\n\n *Returns*:\n - px, py = numpy array with the projected pixel coordinates.\n \"\"\"\n # are px and py lists?\n if isinstance(x, np.ndarray) or isinstance(x, list):\n\n # do housekeeping to make sure arrays/lists are proper and good :)\n assert (isinstance(y, np.ndarray) or isinstance(y, list)), \"Error both x and y must be lists or arrays.\"\n if isinstance(x, np.ndarray):\n x = x.ravel()\n y = y.ravel()\n\n assert len(x) == len(y), \"Error, px and py must have identical dimensions.\"\n\n out = []\n for i in range(len(x)):\n out.append(pano_to_persp(x[i], y[i], fov, step, dims).ravel())\n return np.array(out)\n\n else: # no - individual pixels :)\n\n # convert pixel to ray\n xyz = pix_to_ray_pano(x, y, fov, step, dims)\n\n # project ray to pixel using pinhole model\n pp, vis = proj_persp(xyz, C=np.array([0, 0, 0]),\n a=np.array([0, 0, 0]),\n fov=fov, dims=dims)\n\n return pp[:, 0:2] # return pixel coords\n\ndef pnp(kxyz, kxy, fov, dims, ransac=True, **kwds):\n \"\"\"\n Solves the pnp problem to locate a camera given keypoints that are known in world and pixel coordinates using opencv.\n\n *Arguments*:\n - kxyz = Nx3 array of keypoint positions in world coordinates.\n - kxy = Nx2 array of corresponding keypoint positions in pixel coordinates.\n - fov = the (vertical) field of view of the camera.\n - dims = the dimensions of the image in pixels\n - ransac = true if ransac should be used to filter outliers. Default is True.\n\n *Keywords*:\n - optical_centre = the pixel coordinates (cx,cy) of the optical centre to use. By default the\n middle pixel of the image is used.\n - other keyword arguments are passed to cv2.solvePnP(...) or cv2.solvePnPRansac(...).\n\n Additionally a custom optical center can be passed as (cx,cy)\n *Returns*:\n - p = the camera position in world coordinates\n - r = the camera orientation (as XYZ euler angle).\n - inl = list of Ransac inlier indices used to estimate the position, or None if ransac == False.\n \"\"\"\n # normalize keypoints so that origin is at mean\n mean = np.mean(kxyz, axis=0)\n kxyz = kxyz - mean\n\n # flip kxy coords to match opencv coord system\n # kxy[:, 1] = dims[1] - kxy[:, 1]\n # kxy[:, 0] = dims[0] - kxy[:, 0]\n\n # compute camera matrix\n tanfov = np.tan(np.deg2rad(fov / 2))\n aspx = dims[0] / dims[1]\n fx = dims[0] / (2 * tanfov * aspx)\n fy = dims[1] / (2 * tanfov)\n cx, cy = kwds.get(\"optical_centre\", (0.5 * dims[0] - 0.5, 0.5 * dims[1] - 0.5))\n if 'optical_centre' in kwds: del kwds['optical_centre'] # remove keyword\n cameraMatrix = np.array([[fx, 0, cx],\n [0, fy, cy],\n [0, 0, 1]])\n\n # distortion free lens\n dist_coef = np.zeros(4)\n\n # use opencv to solve pnp problem and hence camera position\n if ransac:\n suc, rot, pos, inl = cv2.solvePnPRansac(objectPoints=kxyz[:, :3].copy(), # points in world coords\n imagePoints=kxy[:, :2].copy(), # points in img coords\n cameraMatrix=cameraMatrix, # camera matrix\n distCoeffs=dist_coef,\n **kwds)\n else:\n inl = None\n suc, rot, pos = cv2.solvePnP(objectPoints=kxyz[:, :3].copy(), # points in world coords\n imagePoints=kxy[:, :2].copy(), # points in img coords\n cameraMatrix=cameraMatrix, # camera matrix\n distCoeffs=dist_coef,\n **kwds)\n\n assert suc, \"Error - no solution found to pnp problem.\"\n\n # get first solution\n if not inl is None:\n inl = inl[:, 0]\n pos = np.array(pos[:, 0])\n rot = np.array(rot[:, 0])\n\n # apply rotation position vector\n p = -np.dot(pos, spatial.transform.Rotation.from_rotvec(rot).as_matrix())\n\n # convert rot from axis-angle to euler\n r = spatial.transform.Rotation.from_rotvec(rot).as_euler('xyz', degrees=True)\n\n # apply dodgy correction to r (some coordinate system shift)\n r = np.array([r[0] - 180, -r[1], -r[2]])\n\n return p + mean, r, inl\n"
] | [
[
"numpy.nanmax",
"numpy.dot",
"matplotlib.pyplot.imshow",
"numpy.nanmedian",
"numpy.sqrt",
"numpy.nanmin",
"numpy.max",
"numpy.mean",
"numpy.nanmean",
"numpy.cross",
"matplotlib.patches.PathPatch",
"scipy.optimize.least_squares",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"numpy.min",
"matplotlib.path.Path",
"numpy.deg2rad",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.sum",
"numpy.nanpercentile",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.axhline",
"numpy.abs",
"matplotlib.pyplot.subplots",
"numpy.linalg.norm",
"numpy.vstack"
],
[
"numpy.dot",
"numpy.hstack",
"scipy.spatial.transform.Rotation.from_rotvec",
"numpy.sqrt",
"numpy.einsum",
"numpy.linalg.norm",
"numpy.full",
"numpy.arctan2",
"numpy.deg2rad",
"numpy.mean",
"scipy.spatial.transform.Rotation.from_euler",
"numpy.array",
"numpy.zeros",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.5",
"1.3",
"1.2",
"1.4"
],
"tensorflow": []
}
] |
miiklay/pymapd | [
"4665ea704eb7ffabf72048f1cb3519b4497b8830",
"4665ea704eb7ffabf72048f1cb3519b4497b8830"
] | [
"tests/test_ipc.py",
"pymapd/_parsers.py"
] | [
"import os\nimport pytest\n\npa = pytest.importorskip(\"pyarrow\")\npd = pytest.importorskip(\"pandas\")\n\nimport numpy as np # noqa\nimport pandas.util.testing as tm # noqa\nfrom pymapd._parsers import _load_schema, _load_data # noqa\n\nHERE = os.path.dirname(__file__)\n\n\ndef make_data_batch():\n arrow_version = pa.__version__\n np.random.seed(1234)\n depdelay = np.random.randint(-5, 30, size=10, dtype=np.int16)\n arrdelay = np.random.randint(-15, 30, size=10, dtype=np.int16)\n depdelay_ = pa.array(depdelay)\n arrdelay_ = pa.array(arrdelay)\n if arrow_version == '0.7.1':\n depdelay_ = depdelay_.cast(pa.int16())\n arrdelay_ = arrdelay_.cast(pa.int16())\n batch = pa.RecordBatch.from_arrays([depdelay_, arrdelay_],\n ['depdelay', 'arrdelay'])\n return (depdelay, arrdelay), batch\n\n\n(depdelay, arrdelay), batch = make_data_batch()\nschema_data = batch.schema.serialize().to_pybytes()\ndata_data = batch.serialize().to_pybytes()\n\n\nclass TestIPC:\n def test_parse_schema(self):\n buf = pa.frombuffer(schema_data)\n result = _load_schema(buf)\n expected = pa.schema([\n pa.field(\"depdelay\", pa.int16()),\n pa.field(\"arrdelay\", pa.int16())\n ])\n assert result.equals(expected)\n\n def test_parse_data(self):\n buf = pa.frombuffer(data_data)\n schema = pa.schema([\n pa.field(\"depdelay\", pa.int16()),\n pa.field(\"arrdelay\", pa.int16())\n ])\n result = _load_data(buf, schema)\n expected = pd.DataFrame({\n \"depdelay\": depdelay,\n \"arrdelay\": arrdelay,\n })[['depdelay', 'arrdelay']]\n tm.assert_frame_equal(result, expected)\n",
"\"\"\"\nUtility methods for parsing data returned from MapD\n\"\"\"\nimport datetime\nfrom collections import namedtuple\nfrom sqlalchemy import text\nimport mapd.ttypes as T\nfrom types import MethodType\nfrom ._mutators import set_tdf, get_tdf\n\nfrom ._utils import seconds_to_time\n\n\nDescription = namedtuple(\"Description\", [\"name\", \"type_code\", \"display_size\",\n \"internal_size\", \"precision\", \"scale\",\n \"null_ok\"])\nColumnDetails = namedtuple(\"ColumnDetails\", [\"name\", \"type\", \"nullable\",\n \"precision\", \"scale\",\n \"comp_param\"])\n\n_typeattr = {\n 'SMALLINT': 'int',\n 'INT': 'int',\n 'BIGINT': 'int',\n 'TIME': 'int',\n 'TIMESTAMP': 'int',\n 'DATE': 'int',\n 'BOOL': 'int',\n 'FLOAT': 'real',\n 'DECIMAL': 'real',\n 'DOUBLE': 'real',\n 'STR': 'str',\n 'POINT': 'str',\n 'LINESTRING': 'str',\n 'POLYGON': 'str',\n 'MULTIPOLYGON': 'str',\n 'TINYINT': 'int',\n 'GEOMETRY': 'str',\n 'GEOGRAPHY': 'str',\n}\n_thrift_types_to_values = T.TDatumType._NAMES_TO_VALUES\n_thrift_values_to_types = T.TDatumType._VALUES_TO_NAMES\n\n\ndef _extract_row_val(desc, val):\n # type: (T.TColumnType, T.TDatum) -> Any\n typename = T.TDatumType._VALUES_TO_NAMES[desc.col_type.type]\n if val.is_null:\n return None\n val = getattr(val.val, _typeattr[typename] + '_val')\n base = datetime.datetime(1970, 1, 1)\n if typename == 'TIMESTAMP':\n val = (base + datetime.timedelta(seconds=val))\n elif typename == 'DATE':\n val = (base + datetime.timedelta(seconds=val)).date()\n elif typename == 'TIME':\n val = seconds_to_time(val)\n return val\n\n\ndef _extract_col_vals(desc, val):\n # type: (T.TColumnType, T.TColumn) -> Any\n typename = T.TDatumType._VALUES_TO_NAMES[desc.col_type.type]\n nulls = val.nulls\n\n vals = getattr(val.data, _typeattr[typename] + '_col')\n vals = [None if null else v\n for null, v in zip(nulls, vals)]\n\n base = datetime.datetime(1970, 1, 1)\n if typename == 'TIMESTAMP':\n vals = [None if v is None else base + datetime.timedelta(seconds=v)\n for v in vals]\n elif typename == 'DATE':\n vals = [None if v is None else (base +\n datetime.timedelta(seconds=v)).date()\n for v in vals]\n elif typename == 'TIME':\n vals = [None if v is None else seconds_to_time(v) for v in vals]\n\n return vals\n\n\ndef _extract_description(row_desc):\n # type: (List[T.TColumnType]) -> List[Description]\n \"\"\"\n Return a tuple of (name, type_code, display_size, internal_size,\n precision, scale, null_ok)\n\n https://www.python.org/dev/peps/pep-0249/#description\n \"\"\"\n return [Description(col.col_name, col.col_type.type,\n None, None, None, None,\n col.col_type.nullable)\n for col in row_desc]\n\n\ndef _extract_column_details(row_desc):\n # For Connection.get_table_details\n return [\n ColumnDetails(x.col_name, _thrift_values_to_types[x.col_type.type],\n x.col_type.nullable, x.col_type.precision,\n x.col_type.scale, x.col_type.comp_param)\n for x in row_desc\n ]\n\n\ndef _is_columnar(data):\n # type: (T.TQueryResult) -> bool\n return data.row_set.is_columnar\n\n\ndef _load_schema(buf):\n \"\"\"\n Load a `pyarrow.Schema` from a buffer written to shared memory\n\n Parameters\n ----------\n buf : pyarrow.Buffer\n\n Returns\n -------\n schema : pyarrow.Schema\n \"\"\"\n import pyarrow as pa\n\n reader = pa.RecordBatchStreamReader(buf)\n return reader.schema\n\n\ndef _load_data(buf, schema, tdf=None):\n \"\"\"\n Load a `pandas.DataFrame` from a buffer written to shared memory\n\n Parameters\n ----------\n buf : pyarrow.Buffer\n shcema : pyarrow.Schema\n tdf(optional) : TDataFrame\n\n Returns\n -------\n df : pandas.DataFrame\n \"\"\"\n import pyarrow as pa\n\n message = pa.read_message(buf)\n rb = pa.read_record_batch(message, schema)\n df = rb.to_pandas()\n df.set_tdf = MethodType(set_tdf, df)\n df.get_tdf = MethodType(get_tdf, df)\n df.set_tdf(tdf)\n return df\n\n\ndef _parse_tdf_gpu(tdf):\n \"\"\"\n Parse the results of a select ipc_gpu into a GpuDataFrame\n\n Parameters\n ----------\n tdf : TDataFrame\n\n Returns\n -------\n gdf : GpuDataFrame\n \"\"\"\n import numpy as np\n from pygdf.gpuarrow import GpuArrowReader\n from pygdf.dataframe import DataFrame\n from numba import cuda\n from numba.cuda.cudadrv import drvapi\n\n from .shm import load_buffer\n\n ipc_handle = drvapi.cu_ipc_mem_handle(*tdf.df_handle)\n ipch = cuda.driver.IpcHandle(None, ipc_handle, size=tdf.df_size)\n ctx = cuda.current_context()\n dptr = ipch.open(ctx)\n\n schema_buffer = load_buffer(tdf.sm_handle, tdf.sm_size)\n # TODO: extra copy.\n schema_buffer = np.frombuffer(schema_buffer.to_pybytes(), dtype=np.uint8)\n\n dtype = np.dtype(np.byte)\n darr = cuda.devicearray.DeviceNDArray(shape=dptr.size,\n strides=dtype.itemsize,\n dtype=dtype,\n gpu_data=dptr)\n reader = GpuArrowReader(schema_buffer, darr)\n df = DataFrame()\n df.set_tdf = MethodType(set_tdf, df)\n df.get_tdf = MethodType(get_tdf, df)\n\n for k, v in reader.to_dict().items():\n df[k] = v\n\n df.set_tdf(tdf)\n return df\n\n\ndef _bind_parameters(operation, parameters):\n return (text(operation)\n .bindparams(**parameters)\n .compile(compile_kwargs={\"literal_binds\": True}))\n"
] | [
[
"pandas.util.testing.assert_frame_equal",
"numpy.random.seed",
"numpy.random.randint"
],
[
"numpy.dtype"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
yvesnana/rxnaamapper | [
"48fb6a6f45f5ec087f99cedbac34eda2a65e14a3"
] | [
"src/rxn_aa_mapper/training.py"
] | [
"\"\"\"Training utilities.\"\"\"\nimport os\nfrom typing import Any, Dict, Union\n\nimport pytorch_lightning as pl\nimport torch\nfrom loguru import logger\nfrom pytorch_lightning.callbacks.base import Callback\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\nfrom pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint\nfrom pytorch_lightning.loggers import WandbLogger\n\nfrom .dataset import (\n DATASETS,\n EnzymaticReactionDataset,\n EnzymaticReactionLightningDataModule,\n)\nfrom .model import EnzymaticReactionLightningModule\n\n\ndef get_data_module(\n dataset_args: Dict[str, Union[float, str, int]],\n) -> EnzymaticReactionLightningDataModule:\n \"\"\"\n Get a data module for enzymatic reactions.\n\n Args:\n dataset_args: dictionary containing all the necessary parameters for the dataset creation.\n\n Returns:\n data module for enzymatic reactions.\n \"\"\"\n return EnzymaticReactionLightningDataModule(\n dataset_args,\n DATASETS.get(\n str(dataset_args.get(\"dataset_type\", \"enzymatic\")), EnzymaticReactionDataset\n ),\n )\n\n\ndef train(\n model_args: Dict[str, Union[float, str, int]],\n model_architecture: Dict[str, Union[float, str, int]],\n dataset_args: Dict[str, Union[float, str, int]],\n trainer_args: Dict[str, Any],\n) -> None:\n \"\"\"\n Train a model.\n\n Args:\n model_args: dictionary containing all the parameters for the mode configuration.\n model_architecture: dictionary containing the information related to the architecture of the model.\n dataset_args: dictionary containing all the necessary parameters for the dataset creation.\n training_args: dictionary containing all the necessary parameters for the training routine.\n \"\"\"\n data_module = get_data_module(dataset_args)\n model_architecture[\"vocab_size\"] = data_module.train_dataset.tokenizer.vocab_size\n model = EnzymaticReactionLightningModule(model_args, model_architecture)\n\n log_dir = trainer_args[\"log_dir\"]\n os.makedirs(log_dir, exist_ok=True)\n\n del trainer_args[\"log_dir\"]\n lightning_logger = WandbLogger(\n name=\"mlm-logger\", save_dir=log_dir, log_model=True, project=\"rxn-aa-mapper\"\n )\n trainer_args[\"logger\"] = lightning_logger\n if not torch.cuda.is_available():\n del trainer_args[\"gpus\"]\n\n if not isinstance(trainer_args[\"val_check_interval\"], int):\n trainer_args[\"val_check_interval\"] = 10000\n logger.warning(\n f\"please set trainer['val_check_interval'] to an integer value, defaulting to {trainer_args['val_check_interval']}\"\n )\n if (\n \"accelerator\" not in trainer_args\n or trainer_args.get(\"accelerator\", \"ddp\") == \"ddp_spawn\"\n ):\n trainer_args[\"accelerator\"] = \"ddp\"\n logger.warning(\n f\"ddp_spawn not supported because of pickle issues, defaulting to {trainer_args['accelerator']}\"\n )\n\n # gather the callbacks\n trainer_args[\"callbacks\"] = []\n if \"early_stopping_callback\" in trainer_args:\n callback: Callback = EarlyStopping(**trainer_args[\"early_stopping_callback\"])\n del trainer_args[\"early_stopping_callback\"]\n trainer_args[\"callbacks\"].append(callback)\n\n if \"model_checkpoint_callback\" in trainer_args:\n callback = ModelCheckpoint(**trainer_args[\"model_checkpoint_callback\"])\n del trainer_args[\"model_checkpoint_callback\"]\n trainer_args[\"callbacks\"].append(callback)\n\n trainer = pl.Trainer(**trainer_args)\n trainer.fit(model, data_module)\n\n\ndef checkpoint_to_module(\n input_checkpoint: str,\n model_args: Dict[str, Union[float, str, int]],\n model_architecture: Dict[str, Union[float, str, int]],\n) -> EnzymaticReactionLightningModule:\n \"\"\"\n Transform a checkpoint into a module.\n\n Args:\n input_checkpoint: model checkpoint.\n model_args: dictionary containing all the parameters for the mode configuration.\n model_architecture: dictionary containing the information related to the architecture of the model.\n\n Returns:\n the ligthining module.\n \"\"\"\n return EnzymaticReactionLightningModule.load_from_checkpoint(\n checkpoint_path=input_checkpoint,\n model_args=model_args,\n model_architecture=model_architecture,\n )\n"
] | [
[
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sash-a/Mava | [
"976d0863e058fd92f066d8a8fabe2f5e2f3f60ce",
"976d0863e058fd92f066d8a8fabe2f5e2f3f60ce"
] | [
"tests/adders/episode_adders_test_data.py",
"mava/utils/environments/RoboCup_env/robocup_utils/trainer.py"
] | [
"import dm_env\nimport numpy as np\n\nfrom mava.adders.reverb import base\nfrom mava.utils.wrapper_utils import parameterized_restart, parameterized_termination\nfrom tests.adders.adders_utils import make_sequence, make_trajectory\n\nagents = {\"agent_0\", \"agent_1\", \"agent_2\"}\nreward_step1 = {\"agent_0\": 0.0, \"agent_1\": 0.0, \"agent_2\": 1.0}\nreward_step2 = {\"agent_0\": 1.0, \"agent_1\": 0.0, \"agent_2\": 0.0}\nreward_step3 = {\"agent_0\": 0.0, \"agent_1\": 1.0, \"agent_2\": 0.0}\nreward_step4 = {\"agent_0\": 1.0, \"agent_1\": 1.0, \"agent_2\": 1.0}\nreward_step5 = {\"agent_0\": -1.0, \"agent_1\": -1.0, \"agent_2\": -1.0}\nreward_step6 = {\"agent_0\": 0.5, \"agent_1\": -5.0, \"agent_2\": 1.0}\nreward_step7 = {\"agent_0\": 1.0, \"agent_1\": 3.0, \"agent_2\": 1.0}\n\nobs_first = {agent: np.array([0.0, 1.0]) for agent in agents}\nobs_step1 = {agent: np.array([1.0, 2.0]) for agent in agents}\nobs_step2 = {agent: np.array([2.0, 3.0]) for agent in agents}\nobs_step3 = {agent: np.array([3.0, 4.0]) for agent in agents}\nobs_step4 = {agent: np.array([4.0, 5.0]) for agent in agents}\nobs_step5 = {agent: np.array([5.0, 6.0]) for agent in agents}\nobs_step6 = {agent: np.array([6.0, 7.0]) for agent in agents}\nobs_step7 = {agent: np.array([7.0, 8.0]) for agent in agents}\n\ndefault_discount = {agent: 1.0 for agent in agents}\ndefault_action = {agent: 0.0 for agent in agents}\nenv_restart = parameterized_restart(\n reward={agent: 0.0 for agent in agents},\n discount=default_discount,\n observation=obs_first,\n)\n\nfinal_step_discount = {agent: 0.0 for agent in agents}\n\n# Long Episode\nmax_sequence_length = 50\nobservation_dims = 5\nobservations = np.random.random_sample((max_sequence_length, observation_dims))\nfirst_longepisode, steps_longepisode = make_trajectory(observations, agents)\n\nTEST_CASES = [\n dict(\n testcase_name=\"ShortEps\",\n max_sequence_length=2, # nsteps +1\n first=env_restart,\n steps=(\n (\n default_action,\n parameterized_termination(\n reward=reward_step1,\n observation=obs_step1,\n discount=final_step_discount,\n ),\n ),\n ),\n expected_sequences=(\n # (observation, action, reward, discount, start_of_episode, next_extras)\n [\n base.Trajectory(\n obs_first,\n default_action,\n reward_step1,\n final_step_discount,\n True,\n {},\n ),\n base.Trajectory(\n obs_step1,\n default_action,\n {agent: 0.0 for agent in agents},\n {agent: 0.0 for agent in agents},\n False,\n {},\n ),\n ],\n ),\n agents=agents,\n ),\n dict(\n testcase_name=\"ShortEpsWithExtras\",\n max_sequence_length=2, # nsteps +1\n first=(env_restart, {\"state\": -1}),\n steps=(\n (\n default_action,\n parameterized_termination(\n reward=reward_step1,\n observation=obs_step1,\n discount=final_step_discount,\n ),\n {\"state\": 0},\n ),\n ),\n expected_sequences=(\n # (observation, action, reward, discount, start_of_episode, next_extras)\n [\n base.Trajectory(\n obs_first,\n default_action,\n reward_step1,\n final_step_discount,\n True,\n {\"state\": -1},\n ),\n base.Trajectory(\n obs_step1,\n default_action,\n {agent: 0.0 for agent in agents},\n {agent: 0.0 for agent in agents},\n False,\n {\"state\": 0},\n ),\n ],\n ),\n agents=agents,\n ),\n dict(\n testcase_name=\"MediumEps\",\n max_sequence_length=5, # nsteps +1\n first=env_restart,\n steps=(\n (\n default_action,\n dm_env.transition(\n reward=reward_step1,\n observation=obs_step1,\n discount=default_discount,\n ),\n ),\n (\n default_action,\n dm_env.transition(\n reward=reward_step2,\n observation=obs_step2,\n discount=default_discount,\n ),\n ),\n (\n default_action,\n dm_env.transition(\n reward=reward_step3,\n observation=obs_step3,\n discount=default_discount,\n ),\n ),\n (\n default_action,\n parameterized_termination(\n reward=reward_step4,\n observation=obs_step4,\n discount=final_step_discount,\n ),\n ),\n ),\n expected_sequences=(\n # (observation, action, reward, discount, start_of_episode, next_extras)\n [\n base.Trajectory(\n obs_first, default_action, reward_step1, default_discount, True, {}\n ),\n base.Trajectory(\n obs_step1, default_action, reward_step2, default_discount, False, {}\n ),\n base.Trajectory(\n obs_step2, default_action, reward_step3, default_discount, False, {}\n ),\n base.Trajectory(\n obs_step3,\n default_action,\n reward_step4,\n final_step_discount,\n False,\n {},\n ),\n base.Trajectory(\n obs_step4,\n default_action,\n {agent: 0.0 for agent in agents},\n final_step_discount,\n False,\n {},\n ),\n ],\n ),\n agents=agents,\n ),\n dict(\n testcase_name=\"LargeEps\",\n max_sequence_length=50, # nsteps +1\n first=first_longepisode,\n steps=steps_longepisode,\n expected_sequences=[make_sequence(observations)],\n agents=agents,\n ),\n]\n",
"# !/usr/bin/env python3\n# Copyright 2021 InstaDeep Ltd. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# type: ignore\n\nimport random\nimport threading\nimport time\n\nimport numpy as np\n\nfrom mava.utils.environments.RoboCup_env.robocup_utils import (\n handler,\n sock,\n sp_exceptions,\n)\nfrom mava.utils.environments.RoboCup_env.robocup_utils.game_object import Flag\nfrom mava.utils.environments.RoboCup_env.robocup_utils.trainer_world_model import (\n WorldModel,\n)\n\nmax_x_rand = Flag.out_x\nmax_y_rand = Flag.out_y\n\n# Define some colours\ngreen = (0, 255, 50)\nlight_blue = (0, 255, 255)\nblue = (0, 0, 255)\nred = (255, 0, 0)\nyellow = (255, 255, 0)\nwhite = (255, 255, 255)\n\n# R G B\nfield_col = (0, 200, 50)\nteam_player = blue\nopp_player = light_blue\nown_goal = (255, 140, 0)\nopp_goal = (128, 0, 128)\n\n\nclass Trainer:\n def __init__(self):\n # whether we're connected to a server yet or not\n self.__connected = False\n\n # set all variables and important objects to appropriate values for\n # pre-connect state.\n\n # the socket used to communicate with the server\n self.__sock = None\n\n # models and the message handler for parsing and storing information\n self.wm = None\n self.msg_handler = None\n\n # parse thread and control variable\n self.__parsing = False\n self.__msg_thread = None\n\n self.__thinking = False # think thread and control variable\n self.__think_thread = None\n\n # whether we should run the think method\n self.__should_think_on_data = False\n\n # whether we should send commands\n self.__send_commands = True\n\n # adding goal post markers\n self.enemy_goal_pos = None\n self.own_goal_pos = None\n\n def connect(self, host, port, version=11):\n \"\"\"\n Gives us a connection to the server as one player on a team. This\n immediately connects the agent to the server and starts receiving and\n parsing the information it sends.\n \"\"\"\n\n # if already connected, raise an error since user may have wanted to\n # connect again to a different server.\n if self.__connected:\n msg = \"Cannot connect while already connected, disconnect first.\"\n raise sp_exceptions.AgentConnectionStateError(msg)\n\n # the pipe through which all of our communication takes place\n self.__sock = sock.Socket(host, port)\n\n # our models of the world and our body\n self.wm = WorldModel(handler.ActionHandler(self.__sock))\n\n # handles all messages received from the server\n self.msg_handler = handler.MessageHandler(self.wm)\n\n # set up our threaded message receiving system\n self.__parsing = True # tell thread that we're currently running\n self.__msg_thread = threading.Thread(\n target=self.__message_loop, name=\"message_loop\"\n )\n self.__msg_thread.daemon = True # dies when parent thread dies\n\n # start processing received messages. this will catch the initial server\n # response and all subsequent communication.\n self.__msg_thread.start()\n\n # send the init message and allow the message handler to handle further\n # responses.\n # init_address = self.__sock.address\n # teamname = \"John\"\n init_msg = \"(init (version %d))\"\n self.__sock.send(init_msg % (version))\n\n # # wait until the socket receives a response from the server and gets its\n # # assigned port.\n # while self.__sock.address == init_address:\n # time.sleep(0.0001)\n\n # create our thinking thread. this will perform the actions necessary\n # to play a game of robo-soccer.\n self.__thinking = False\n # self.__think_thread = threading.Thread(target=self.__think_loop,\n # name=\"think_loop\")\n # self.__think_thread.daemon = True\n\n # set connected state. done last to prevent state inconsistency if\n # something goes wrong beforehand.\n self.__connected = True\n time.sleep(1)\n self.__sock.send(\"(eye on)\")\n self.__sock.send(\"(ear on)\")\n\n def run(self):\n \"\"\"\n Kicks off the thread that does the agent's thinking, allowing it to play\n during the game. Throws an exception if called while the agent is\n already playing.\n \"\"\"\n\n # ensure we're connected before doing anything\n if not self.__connected:\n msg = \"Must be connected to a server to begin play.\"\n raise sp_exceptions.AgentConnectionStateError(msg)\n\n # throw exception if called while thread is already running\n if self.__thinking:\n raise sp_exceptions.AgentAlreadyPlayingError(\"Agent is already playing.\")\n\n # run the method that sets up the agent's persistant variables\n self.setup_environment()\n\n # tell the thread that it should be running, then start it\n self.__thinking = True\n self.__should_think_on_data = True\n self.__think_loop()\n\n # def disconnect(self):\n # \"\"\"\n # Tell the loop threads to stop and signal the server that we're\n # disconnecting, then join the loop threads and destroy all our inner\n # methods.\n\n # Since the message loop thread can conceiveably block indefinitely while\n # waiting for the server to respond, we only allow it (and the think loop\n # for good measure) a short time to finish before simply giving up.\n\n # Once an agent has been disconnected, it is 'dead' and cannot be used\n # again. All of its methods get replaced by a method that raises an\n # exception every time it is called.\n # \"\"\"\n\n # # don't do anything if not connected\n # if not self.__connected:\n # return\n\n # # tell the loops to terminate\n # self.__parsing = False\n # self.__thinking = False\n\n # # tell the server that we're quitting\n # self.__sock.send(\"(bye)\")\n\n # # tell our threads to join, but only wait breifly for them to do so.\n # # don't join them if they haven't been started (this can happen if\n # # disconnect is called very quickly after connect).\n # if self.__msg_thread.is_alive():\n # self.__msg_thread.join(0.01)\n\n # # if self.__think_thread.is_alive():\n # # self.__think_thread.join(0.01)\n\n # # reset all standard variables in this object. self.__connected gets\n # # reset here, along with all other non-user defined internal variables.\n # Agent.__init__(self)\n\n def __message_loop(self):\n \"\"\"\n Handles messages received from the server.\n\n This SHOULD NOT be called externally, since it's used as a threaded loop\n internally by this object. Calling it externally is a BAD THING!\n \"\"\"\n\n # loop until we're told to stop\n while self.__parsing:\n # receive message data from the server and pass it along to the\n # world model as-is. the world model parses it and stores it within\n # itself for perusal at our leisure.\n raw_msg = self.__sock.recv()\n\n msg_type = self.msg_handler.handle_message(raw_msg)\n\n # if b'goal_l' in raw_msg or b'goal_r' in raw_msg:\n # print(\"Trainer message: '\" , raw_msg,\n # \". Scores: \", self.wm.score_l, self.wm.score_r)\n # exit()\n\n # if msg_type is not None:\n # print(type(raw_msg))\n\n # we send commands all at once every cycle, ie. whenever a\n # 'sense_body' command is received\n if msg_type == handler.ActionHandler.CommandType.SENSE_BODY:\n self.__send_commands = True\n\n # flag new data as needing the think loop's attention\n self.__should_think_on_data = True\n\n # def __think_loop(self):\n # \"\"\"\n # Performs world model analysis and sends appropriate commands to the\n # server to allow the agent to participate in the current game.\n #\n # Like the message loop, this SHOULD NOT be called externally. Use the\n # play method to start play, and the disconnect method to end it.\n # \"\"\"\n #\n # while self.__thinking:\n # # tell the ActionHandler to send its enqueued messages if it is time\n # if self.__send_commands:\n # self.__send_commands = False\n # self.wm.ah.send_commands()\n #\n # # only think if new data has arrived\n # if self.__should_think_on_data:\n # # flag that data has been processed. this shouldn't be a race\n # # condition, since the only change would be to make it True\n # # before changing it to False again, and we're already going to\n # # process data, so it doesn't make any difference.\n # self.__should_think_on_data = False\n #\n # self.think()\n # else:\n # # prevent from burning up all the cpu time while waiting for data\n # time.sleep(0.0001)\n\n def setup_environment(self):\n \"\"\"\n Called before the think loop starts, this allows the user to store any\n variables/objects they'll want access to across subsequent calls to the\n think method.\n \"\"\"\n\n self.in_kick_off_formation = False\n\n def send_done(self):\n self.__sock.send(\"(done)\")\n\n def reset_game(\n self,\n players_per_team,\n team_names,\n game_setting,\n game_diff=None,\n reset_stamina=True,\n ):\n self.__sock.send(\"(change_mode before_kick_off)\")\n if reset_stamina:\n self.__sock.send(\"(recover)\")\n # github.com/rcsoccersim/rcssserver/blob/master/src/coach.cpp\n\n # game_easy = 1 - game_diff\n if game_setting == \"domain_randomisation\":\n # print(\"game_diff: \", game_diff)\n assert game_diff is not None\n\n # Move the ball\n\n if players_per_team[0] > 0 and players_per_team[1] > 0:\n rand_side = random.randint(0, 1) * 2 - 1\n elif players_per_team[0] > 0:\n rand_side = 1\n else:\n rand_side = 0\n s_x = 52\n # TODONE: Change this back to the harder setting!\n x = str(\n np.random.randint(\n s_x - (s_x + max_x_rand) * game_diff,\n s_x - (s_x - max_x_rand) * game_diff + 1,\n )\n * rand_side\n )\n # str(np.random.randint(s_x - (s_x + max_x_rand)*game_diff,\n # s_x - (s_x - max_x_rand)*game_diff + 1)*rand_side)\n # str(s_x*rand_side)\n y = str(\n np.random.randint(-max_y_rand * game_diff, 1 + max_y_rand * game_diff)\n )\n # str(np.random.randint(-max_y_rand*game_diff, 1 + max_y_rand*game_diff))\n # str(0) #\n self.__sock.send(\"(move (ball) \" + x + \" \" + y + \")\")\n for t_i in range(len(players_per_team)):\n for p_i in range(1, players_per_team[t_i] + 1):\n s_x = 51\n x = str(\n np.random.randint(\n s_x - (s_x + max_x_rand) * game_diff,\n s_x - (s_x - max_x_rand) * game_diff + 1,\n )\n * (1 - t_i * 2)\n )\n y = str(\n np.random.randint(\n -max_y_rand * game_diff, 1 + max_y_rand * game_diff\n )\n )\n ang = str(np.random.randint(-180 * game_diff, 1 + 180 * game_diff))\n\n command = (\n \"(move (player \"\n + team_names[t_i]\n + \" \"\n + str(p_i)\n + \") \"\n + str(x)\n + \" \"\n + str(y)\n + \" \"\n + str(ang)\n + \" 0 0)\"\n )\n self.__sock.send(command)\n elif game_setting == \"reward_shaping\":\n # Move the ball\n x = str(np.random.randint(-max_x_rand, max_x_rand + 1))\n y = str(np.random.randint(-max_y_rand, max_y_rand + 1))\n self.__sock.send(\"(move (ball) \" + x + \" \" + y + \")\")\n\n for t, team_name in enumerate(team_names):\n omt = 1 - t\n for p_i in range(1, players_per_team[0] + 1):\n x = str(np.random.randint(-51 * omt, 51 * t + 1))\n y = str(np.random.randint(-max_y_rand, max_y_rand + 1))\n ang = str(np.random.randint(-180, 180 + 1))\n\n command = (\n \"(move (player \"\n + team_name\n + \" \"\n + str(p_i)\n + \") \"\n + str(x)\n + \" \"\n + str(y)\n + \" \"\n + str(ang)\n + \" 0 0)\"\n )\n self.__sock.send(command)\n\n else:\n raise NotImplementedError(\n \"Game setting not implemented in trainer: \", game_setting\n )\n self.__sock.send(\"(change_mode play_on)\")\n self.__sock.send(\"(start)\")\n self.__sock.send(\"(done)\")\n\n def get_state_dict(self):\n return self.wm.get_state()\n"
] | [
[
"numpy.array",
"numpy.random.random_sample"
],
[
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
willu47/energy_demand | [
"59a2712f353f47e3dc237479cc6cc46666b7d0f1",
"59a2712f353f47e3dc237479cc6cc46666b7d0f1"
] | [
"energy_demand/geography/WeatherRegion.py",
"energy_demand/charts/figure_HHD_gas_demand.py"
] | [
"\"\"\"\nWeather Region\n===============\nDepending on the number of weather stations, a ``WeatherRegion``\nis generated per weather station. Within this regions,\nregional load profiles are calculated.\n\n\"\"\"\nfrom datetime import date\nimport uuid\nimport numpy as np\nfrom energy_demand.technologies import technological_stock\nfrom energy_demand.basic import date_handling\nfrom energy_demand.profiles import load_profile\nfrom energy_demand.profiles import hdd_cdd\n'''# pylint: disable=I0011,C0321,C0301,C0103,C0325,no-member'''\n\nclass WeatherRegion(object):\n \"\"\"WeaterRegion\n\n Parameters\n ----------\n weather_region_name : str\n Unique identifyer of region_name\n data : dict\n Dictionary containing data\n modeltype : str\n Model type\n\n Note\n ----\n - For each region_name, a technology stock is defined with help of\n regional temperature data technology specific\n - regional specific fuel shapes are assigned to technologies\n \"\"\"\n def __init__(self, weather_region_name, data, modeltype):\n \"\"\"Constructor\n \"\"\"\n self.weather_region_name = weather_region_name\n\n # Temperatures\n temp_by = data['temperature_data'][weather_region_name][data['sim_param']['base_yr']]\n temp_cy = data['temperature_data'][weather_region_name][data['sim_param']['curr_yr']]\n\n rs_t_base_heating_cy = hdd_cdd.sigm_temp(\n data['sim_param'], data['assumptions'], 'rs_t_base_heating')\n rs_t_base_cooling_cy = hdd_cdd.sigm_temp(\n data['sim_param'], data['assumptions'], 'rs_t_base_cooling')\n rs_t_base_heating_by = hdd_cdd.sigm_temp(\n data['sim_param'], data['assumptions'], 'rs_t_base_heating')\n rs_t_base_cooling_by = hdd_cdd.sigm_temp(\n data['sim_param'], data['assumptions'], 'rs_t_base_cooling')\n ss_t_base_heating_cy = hdd_cdd.sigm_temp(\n data['sim_param'], data['assumptions'], 'ss_t_base_heating')\n ss_t_base_cooling_cy = hdd_cdd.sigm_temp(\n data['sim_param'], data['assumptions'], 'ss_t_base_cooling')\n ss_t_base_heating_by = hdd_cdd.sigm_temp(\n data['sim_param'], data['assumptions'], 'ss_t_base_heating')\n ss_t_base_cooling_by = hdd_cdd.sigm_temp(\n data['sim_param'], data['assumptions'], 'ss_t_base_cooling')\n\n # -------------------\n # Technology stock\n # -------------------\n if modeltype == 'is_submodel':\n self.is_tech_stock = technological_stock.TechStock(\n 'is_tech_stock',\n data,\n temp_by,\n temp_cy,\n data['assumptions']['ss_t_base_heating']['base_yr'],\n data['is_all_enduses'],\n ss_t_base_heating_cy,\n data['assumptions']['is_specified_tech_enduse_by']\n )\n elif modeltype == 'rs_submodel':\n self.rs_tech_stock = technological_stock.TechStock(\n 'rs_tech_stock',\n data,\n temp_by,\n temp_cy,\n data['assumptions']['rs_t_base_heating']['base_yr'],\n data['rs_all_enduses'],\n rs_t_base_heating_cy,\n data['assumptions']['rs_specified_tech_enduse_by']\n )\n elif modeltype == 'ss_submodel':\n self.ss_tech_stock = technological_stock.TechStock(\n 'ss_tech_stock',\n data,\n temp_by,\n temp_cy,\n data['assumptions']['ss_t_base_heating']['base_yr'],\n data['ss_all_enduses'],\n ss_t_base_heating_cy,\n data['assumptions']['ss_specified_tech_enduse_by']\n )\n\n # -------------------\n # Load profiles\n # -------------------\n if modeltype == 'rs_submodel':\n\n # --------Profiles\n self.rs_load_profiles = load_profile.LoadProfileStock(\"rs_load_profiles\")\n\n # --------HDD/CDD\n rs_hdd_by, _ = hdd_cdd.get_reg_hdd(temp_by, rs_t_base_heating_by)\n rs_cdd_by, _ = hdd_cdd.get_reg_cdd(temp_by, rs_t_base_cooling_by)\n rs_hdd_cy, rs_fuel_shape_heating_yd = hdd_cdd.get_reg_hdd(temp_cy, rs_t_base_heating_cy)\n rs_cdd_cy, _ = hdd_cdd.get_reg_cdd(temp_cy, rs_t_base_cooling_cy)\n\n # Climate change correction factors\n # (Assumption: Demand for heat correlates directly with fuel)\n try:\n self.rs_heating_factor_y = np.nan_to_num(\n 1.0 / float(np.sum(rs_hdd_by))) * np.sum(rs_hdd_cy)\n self.rs_cooling_factor_y = np.nan_to_num(\n 1.0 / float(np.sum(rs_cdd_by))) * np.sum(rs_cdd_cy)\n except ZeroDivisionError:\n self.rs_heating_factor_y = 1\n self.rs_cooling_factor_y = 1\n\n # yd peak factors for heating and cooling\n rs_peak_yd_heating_factor = self.get_shape_peak_yd_factor(rs_hdd_cy)\n #rs_peak_yd_cooling_factor = self.get_shape_peak_yd_factor(rs_cdd_cy)\n\n # --Specific heating technologies for residential sector\n rs_profile_storage_heater_yh, _ = self.get_shape_heating_boilers_yh(\n data, rs_fuel_shape_heating_yd, 'rs_profile_heating_storage_dh')\n rs_profile_elec_heater_yh, _ = self.get_shape_heating_boilers_yh(\n data, rs_fuel_shape_heating_yd, 'rs_profile_heating_second_heating_dh')\n # boiler, non-peak\n rs_profile_boilers_yh, rs_profile_boilers_y_dh = self.get_shape_heating_boilers_yh(\n data, rs_fuel_shape_heating_yd, 'rs_shapes_heating_boilers_dh')\n # heat pumps, non-peak\n rs_fuel_shape_hp_yh, rs_fuel_shape_hp_y_dh = self.get_fuel_shape_heating_hp_yh(\n data, self.rs_tech_stock, rs_hdd_cy, 'rs_shapes_heating_heat_pump_dh')\n\n rs_fuel_shape_hybrid_tech_yh = self.get_shape_heating_hybrid_yh(\n self.rs_tech_stock,\n 'rs_space_heating',\n rs_profile_boilers_y_dh,\n rs_fuel_shape_hp_y_dh,\n rs_fuel_shape_heating_yd,\n 'hybrid_gas_electricity'\n )\n\n # Cooling residential\n #rs_fuel_shape_cooling_yh = self.get_shape_cooling_yh(\n # data, rs_fuel_shape_cooling_yd, 'rs_shapes_cooling_dh')\n\n # Heating boiler\n self.rs_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['tech_heating_const'],\n enduses=['rs_space_heating', 'rs_water_heating'],\n shape_yd=rs_fuel_shape_heating_yd,\n shape_yh=rs_profile_boilers_yh,\n enduse_peak_yd_factor=rs_peak_yd_heating_factor,\n shape_peak_dh=data['rs_shapes_heating_boilers_dh']['peakday']\n )\n\n # Electric heating, primary...(storage)\n self.rs_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['primary_heating_electricity'],\n enduses=['rs_space_heating'],\n shape_yd=rs_fuel_shape_heating_yd,\n shape_yh=rs_profile_storage_heater_yh,\n enduse_peak_yd_factor=rs_peak_yd_heating_factor,\n shape_peak_dh=data['rs_profile_heating_storage_dh']['peakday']\n )\n\n # Electric heating, secondary...\n self.rs_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['secondary_heating_electricity'],\n enduses=['rs_space_heating', 'rs_water_heating'],\n shape_yd=rs_fuel_shape_heating_yd,\n shape_yh=rs_profile_elec_heater_yh,\n enduse_peak_yd_factor=rs_peak_yd_heating_factor,\n shape_peak_dh=data['rs_profile_heating_second_heating_dh']['peakday']\n )\n\n # Hybrid heating\n self.rs_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['tech_heating_hybrid'],\n enduses=['rs_space_heating', 'rs_water_heating'],\n shape_yd=rs_fuel_shape_heating_yd,\n shape_yh=rs_fuel_shape_hybrid_tech_yh,\n enduse_peak_yd_factor=rs_peak_yd_heating_factor\n )\n\n # Heat pump heating\n self.rs_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['tech_heating_temp_dep'],\n enduses=['rs_space_heating', 'rs_water_heating'],\n shape_yd=rs_fuel_shape_heating_yd,\n shape_yh=rs_fuel_shape_hp_yh,\n enduse_peak_yd_factor=rs_peak_yd_heating_factor,\n shape_peak_dh=data['rs_shapes_heating_heat_pump_dh']['peakday']\n )\n\n elif modeltype == 'ss_submodel':\n\n # --------Profiles\n self.ss_load_profiles = load_profile.LoadProfileStock(\"ss_load_profiles\")\n\n # --------HDD/CDD\n ss_hdd_by, _ = hdd_cdd.get_reg_hdd(temp_by, ss_t_base_heating_by)\n ss_cdd_by, _ = hdd_cdd.get_reg_cdd(temp_by, ss_t_base_cooling_by)\n\n ss_hdd_cy, ss_fuel_shape_heating_yd = hdd_cdd.get_reg_hdd(temp_cy, rs_t_base_heating_cy)\n ss_cdd_cy, _ = hdd_cdd.get_reg_cdd(temp_cy, ss_t_base_cooling_cy)\n\n try:\n self.ss_heating_factor_y = np.nan_to_num(\n 1.0 / float(np.sum(ss_hdd_by))) * np.sum(ss_hdd_cy)\n self.ss_cooling_factor_y = np.nan_to_num(\n 1.0 / float(np.sum(ss_cdd_by))) * np.sum(ss_cdd_cy)\n except ZeroDivisionError:\n self.ss_heating_factor_y = 1\n self.ss_cooling_factor_y = 1\n\n ss_peak_yd_heating_factor = self.get_shape_peak_yd_factor(ss_hdd_cy)\n #ss_peak_yd_cooling_factor = self.get_shape_peak_yd_factor(ss_cdd_cy)\n\n # --Heating technologies for service sector\n # (the heating shape follows the gas shape of aggregated sectors)\n ss_fuel_shape_any_tech, ss_fuel_shape = self.ss_get_sector_enduse_shape(\n data, ss_fuel_shape_heating_yd, 'ss_space_heating')\n\n # Cooling service\n #ss_fuel_shape_cooling_yh = self.get_shape_cooling_yh(data, ss_fuel_shape_cooling_yd, 'ss_shapes_cooling_dh') # Service cooling\n #ss_fuel_shape_cooling_yh = self.get_shape_cooling_yh(data, ss_fuel_shape_heating_yd, 'ss_shapes_cooling_dh') # Service cooling #USE HEAT YD BUT COOLING SHAPE\n #ss_fuel_shape_cooling_yh = self.get_shape_cooling_yh(data, load_profile.absolute_to_relative(ss_hdd_cy + ss_cdd_cy), 'ss_shapes_cooling_dh') # hdd & cdd\n\n # Hybrid\n ss_profile_hybrid_gas_elec_yh = self.get_shape_heating_hybrid_yh(\n self.ss_tech_stock,\n 'ss_space_heating',\n ss_fuel_shape,\n ss_fuel_shape,\n ss_fuel_shape_heating_yd,\n 'hybrid_gas_electricity')\n\n self.ss_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['tech_heating_const'],\n enduses=['ss_space_heating', 'ss_water_heating'],\n sectors=data['ss_sectors'],\n shape_yd=ss_fuel_shape_heating_yd,\n shape_yh=ss_fuel_shape_any_tech,\n enduse_peak_yd_factor=ss_peak_yd_heating_factor,\n shape_peak_dh=data['ss_shapes_dh']\n )\n\n self.ss_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['primary_heating_electricity'],\n enduses=['ss_space_heating'],\n sectors=data['ss_sectors'],\n shape_yd=ss_fuel_shape_heating_yd,\n shape_yh=ss_fuel_shape_any_tech,\n enduse_peak_yd_factor=ss_peak_yd_heating_factor,\n shape_peak_dh=data['rs_profile_heating_storage_dh']['peakday']\n )\n\n self.ss_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['secondary_heating_electricity'],\n enduses=['rs_space_heating', 'rs_water_heating'],\n sectors=data['ss_sectors'],\n shape_yd=ss_fuel_shape_heating_yd,\n shape_yh=ss_fuel_shape_any_tech,\n enduse_peak_yd_factor=ss_peak_yd_heating_factor\n )\n\n self.ss_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['tech_heating_hybrid'],\n enduses=['ss_space_heating', 'ss_water_heating'],\n sectors=data['ss_sectors'],\n shape_yd=ss_fuel_shape_heating_yd,\n shape_yh=ss_profile_hybrid_gas_elec_yh,\n enduse_peak_yd_factor=ss_peak_yd_heating_factor,\n )\n\n self.ss_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['tech_heating_temp_dep'],\n enduses=['ss_space_heating', 'ss_water_heating'],\n sectors=data['ss_sectors'],\n shape_yd=ss_fuel_shape_heating_yd,\n shape_yh=ss_fuel_shape_any_tech,\n enduse_peak_yd_factor=ss_peak_yd_heating_factor\n )\n\n elif modeltype == 'is_submodel':\n\n # --------Profiles\n self.is_load_profiles = load_profile.LoadProfileStock(\"is_load_profiles\")\n\n # --------HDD/CDD\n is_hdd_by, _ = hdd_cdd.get_reg_hdd(temp_by, ss_t_base_heating_by)\n is_cdd_by, _ = hdd_cdd.get_reg_cdd(temp_by, ss_t_base_cooling_by)\n\n # Take same base temperature as for service sector\n is_hdd_cy, is_fuel_shape_heating_yd = hdd_cdd.get_reg_hdd(temp_cy, ss_t_base_heating_cy)\n is_cdd_cy, _ = hdd_cdd.get_reg_cdd(temp_cy, ss_t_base_cooling_cy)\n\n try:\n self.is_heating_factor_y = np.nan_to_num(1.0 / float(np.sum(is_hdd_by))) * np.sum(is_hdd_cy)\n self.is_cooling_factor_y = np.nan_to_num(1.0 / float(np.sum(is_cdd_by))) * np.sum(is_cdd_cy)\n except ZeroDivisionError:\n self.is_heating_factor_y = 1\n self.is_cooling_factor_y = 1\n\n is_peak_yd_heating_factor = self.get_shape_peak_yd_factor(is_hdd_cy)\n #is_peak_yd_cooling_factor = self.get_shape_peak_yd_factor(is_cdd_cy)\n\n # --Heating technologies for service sector (the heating shape follows\n # the gas shape of aggregated sectors)\n #Take from service sector\n is_fuel_shape_any_tech, _ = self.ss_get_sector_enduse_shape(\n data, is_fuel_shape_heating_yd, 'ss_space_heating')\n\n self.is_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['tech_heating_const'],\n enduses=['is_space_heating'],\n sectors=data['is_sectors'],\n shape_yd=is_fuel_shape_heating_yd,\n shape_yh=is_fuel_shape_any_tech,\n enduse_peak_yd_factor=is_peak_yd_heating_factor\n )\n\n self.is_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['primary_heating_electricity'],\n enduses=['is_space_heating'],\n sectors=data['is_sectors'],\n shape_yd=is_fuel_shape_heating_yd,\n enduse_peak_yd_factor=is_peak_yd_heating_factor,\n shape_yh=is_fuel_shape_any_tech\n )\n\n self.is_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['secondary_heating_electricity'],\n enduses=['is_space_heating'],\n sectors=data['is_sectors'],\n shape_yd=is_fuel_shape_heating_yd,\n shape_yh=is_fuel_shape_any_tech,\n enduse_peak_yd_factor=is_peak_yd_heating_factor,\n )\n\n self.is_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['tech_heating_hybrid'],\n enduses=['is_space_heating'],\n sectors=data['is_sectors'],\n shape_yd=is_fuel_shape_heating_yd,\n shape_yh=is_fuel_shape_any_tech,\n enduse_peak_yd_factor=is_peak_yd_heating_factor,\n )\n\n self.is_load_profiles.add_load_profile(\n unique_identifier=uuid.uuid4(),\n technologies=data['assumptions']['technology_list']['tech_heating_temp_dep'],\n enduses=['is_space_heating'],\n sectors=data['is_sectors'],\n shape_yd=is_fuel_shape_heating_yd,\n shape_yh=is_fuel_shape_any_tech,\n enduse_peak_yd_factor=is_peak_yd_heating_factor\n )\n\n @classmethod\n def get_shape_heating_hybrid_yh(cls, tech_stock, enduse, fuel_shape_boilers_y_dh, fuel_shape_hp_y_dh, fuel_shape_heating_yd, hybrid_tech):\n \"\"\"Use yd shapes and dh shapes of hybrid technologies to generate yh shape\n\n Parameters\n ----------\n tech_stock : TODO\n enduse :\n fuel_shape_boilers_y_dh : array\n Fuel shape of boilers (dh) for evey day in a year\n fuel_shape_hp_y_dh : array\n Fuel shape of heat pumps (dh) for every day in a year\n fuel_shape_heating_yd : array\n Fuel shape for assign demand to day in a year (yd)\n tech_low_temp : string\n Low temperature technology\n tech_high_temp : string\n High temperature technology\n\n Return\n -------\n fuel_shape_yh : array\n Share of yearly fuel for hybrid technology\n\n Note\n -----\n This is for hybrid_gas_elec technology\n\n The shapes are the same for any hybrid technology with boiler and heat pump\n \"\"\"\n # Create dh shapes for every day from relative dh shape of hybrid technologies\n fuel_shape_hybrid_y_dh = load_profile.get_hybrid_fuel_shapes_y_dh(\n fuel_shape_boilers_y_dh=fuel_shape_boilers_y_dh,\n fuel_shape_hp_y_dh=fuel_shape_hp_y_dh,\n tech_low_high_p=tech_stock.get_tech_attr(\n enduse, hybrid_tech, 'service_distr_hybrid_h_p')\n )\n\n # Calculate yh fuel shape\n fuel_shape_yh = fuel_shape_hybrid_y_dh * fuel_shape_heating_yd[:, np.newaxis]\n\n return fuel_shape_yh\n\n @classmethod\n def get_shape_peak_yd_factor(cls, demand_yd):\n \"\"\"From yd shape calculate maximum relative yearly service demand which is provided in a day\n\n Parameters\n ----------\n demand_yd : shape\n Demand for energy service for every day in year\n\n Return\n ------\n max_factor_yd : float\n yd maximum factor\n\n Note\n -----\n If the shape is taken from heat and cooling demand the assumption is made that\n HDD and CDD are directly proportional to fuel usage\n \"\"\"\n tot_demand_y = np.sum(demand_yd) # Total yearly demand\n max_demand_d = np.max(demand_yd) # Maximum daily demand\n max_factor_yd = (1.0 / tot_demand_y) * max_demand_d\n\n return max_factor_yd\n\n @classmethod\n def get_fuel_shape_heating_hp_yh(cls, data, tech_stock, rs_hdd_cy, tech):\n \"\"\"Convert daily shapes to houly based on robert sansom daily load for heatpump TODO\n\n This is for non-peak.\n\n Parameters\n ---------\n data : dict\n data\n tech_stock : object\n Technology stock\n rs_hdd_cy : array\n Heating Degree Days (365, 1)\n tech : str\n Technology to get profile\n\n Returns\n -------\n hp_shape : array\n Daily shape how yearly fuel can be distributed to hourly\n shape_y_dh : array\n Shape of fuel shape for every day in a year (total sum = 365)\n\n Note\n ----\n The service is calculated based on the efficiency of gas\n heat pumps ``av_heat_pump_gas``\n\n The daily heat demand is converted to daily fuel depending on efficiency of\n heatpumps (assume if 100% heat pumps). In a final step the hourly fuel\n is converted to percentage of yearly fuel demand.\n\n Furthermore the assumption is made that the shape is the same for all fueltypes.\n\n The daily fuel demand curve for heat pumps taken from:\n *Sansom, R. (2014). Decarbonising low grade heat for low carbon future.\n Dissertation, Imperial College London.*\n \"\"\"\n shape_yh_hp = np.zeros((365, 24))\n shape_y_dh = np.zeros((365, 24))\n\n daily_fuel_profile_holiday = data[tech]['holiday'] / np.sum(data[tech]['holiday'])\n daily_fuel_profile_workday = data[tech]['workday'] / np.sum(data[tech]['workday'])\n\n tech_eff = tech_stock.get_tech_attr('rs_space_heating', 'heat_pumps_gas', 'eff_cy')\n\n for day, date_gasday in enumerate(data['sim_param']['list_dates']):\n\n # Take respectve daily fuel curve depending on weekday or weekend\n # from Robert Sansom for heat pumps\n if date_handling.get_weekday_type(date_gasday) == 'holiday':\n daily_fuel_profile = daily_fuel_profile_holiday\n else:\n daily_fuel_profile = daily_fuel_profile_workday\n\n # Calculate weighted average daily efficiency of heat pump\n average_eff_d = 0\n for hour, heat_share_h in enumerate(daily_fuel_profile):\n # Hourly heat demand * heat pump efficiency\n average_eff_d += heat_share_h * tech_eff[day][hour]\n\n # Convert daily service demand to fuel (Heat demand / efficiency = fuel)\n hp_daily_fuel = rs_hdd_cy[day] / average_eff_d\n\n # Fuel distribution within day\n fuel_shape_d = hp_daily_fuel * daily_fuel_profile\n\n # Distribute fuel of day according to fuel load curve\n shape_yh_hp[day] = fuel_shape_d\n\n # Add normalised daily fuel curve\n shape_y_dh[day] = load_profile.absolute_to_relative_without_nan(fuel_shape_d)\n\n # Convert absolute hourly fuel demand to relative fuel demand within a year\n shape_yh = load_profile.absolute_to_relative(shape_yh_hp)\n\n return shape_yh, shape_y_dh\n\n @classmethod\n def get_shape_cooling_yh(cls, data, cooling_shape, tech):\n \"\"\"Convert daily shape to hourly based on robert sansom daily load for boilers\n\n Parameters\n ---------\n data : dict\n data\n cooling_shape : array\n Cooling profile\n tech : str\n Technology to get profile\n\n Returns\n -------\n shape_yd_cooling_tech : array\n Shape of cooling devices\n\n Note\n ----\n The daily cooling demand (calculated with cdd) is distributed within the day\n fuel demand curve from:\n\n - **Residential**: Taken from *Denholm, P., Ong, S., & Booten, C. (2012).\n Using Utility Load Data to Estimate Demand for Space Cooling and\n Potential for Shiftable Loads, (May), 23.\n Retrieved from http://www.nrel.gov/docs/fy12osti/54509.pdf*\n\n - **Service**: *Knight, Dunn, Environments Carbon and Cooling in\n Uk Office Environments*\n \"\"\"\n shape_yd_cooling_tech = data[tech] * cooling_shape[:, np.newaxis]\n\n return shape_yd_cooling_tech\n\n @classmethod\n def ss_get_sector_enduse_shape(cls, data, heating_shape, enduse):\n \"\"\"Read generic shape for all technologies in a service sector enduse\n\n Parameters\n ---------\n data : dict\n data\n heating_shape : array\n Daily (yd) service demand shape for heat (percentage of yearly\n heat demand for every day)\n enduse : str\n Enduse where technology is used\n\n Returns\n -------\n shape_boilers_yh : array\n Shape how yearly fuel can be distributed to hourly (yh) (total sum == 1)\n shape_boilers_y_dh : array\n Shape of distribution of fuel within every day of a year (total sum == 365)\n \"\"\"\n shape_yh_generic_tech = np.zeros((365, 24))\n\n if enduse not in data['ss_all_tech_shapes_dh']:\n pass\n else:\n shape_non_peak_y_dh = data['ss_all_tech_shapes_dh'][enduse]['shape_non_peak_y_dh']\n\n shape_yh_generic_tech = heating_shape[:, np.newaxis] * shape_non_peak_y_dh\n shape_y_dh_generic_tech = shape_non_peak_y_dh\n\n return shape_yh_generic_tech, shape_y_dh_generic_tech\n\n @classmethod\n def get_shape_heating_boilers_yh(cls, data, heating_shape, tech_to_get_shape):\n \"\"\"Convert daily fuel shape to hourly based on robert sansom daily load for boilers\n\n Parameters\n ---------\n data : dict\n data\n heating_shape : array\n Profile (yh) for heat (percentage of yearly heat demand for every day)\n tech_to_get_shape : str\n Technology\n\n Returns\n -------\n shape_boilers_yh : array\n Shape how yearly fuel can be distributed to hourly (yh) (total sum == 1)\n shape_boilers_y_dh : array\n Shape of distribution of fuel within every day of a year (total sum == 365)\n\n Note\n ----\n - The assumption is made that boilers have constant efficiency for every hour in a year.\n Therefore the fuel demand correlates directly with the heat service demand.\n\n - Furthermore the assumption is made that the profile is the same for all fueltypes.\n\n The daily heat demand (calculated with hdd) is distributed within the day\n fuel demand curve for boilers from:\n\n *Sansom, R. (2014). Decarbonising low grade heat for low carbon\n future. Dissertation, Imperial College London.*\n \"\"\"\n shape_boilers_yh = np.zeros((365, 24))\n shape_boilers_y_dh = np.zeros((365, 24))\n\n list_dates = date_handling.fullyear_dates(\n start=date(data['sim_param']['base_yr'], 1, 1),\n end=date(data['sim_param']['base_yr'], 12, 31)\n )\n\n for day, date_gasday in enumerate(list_dates):\n weekday_type = date_handling.get_weekday_type(date_gasday)\n\n # Take respectve daily fuel curve depending on weekday or weekend\n if weekday_type == 'holiday': # Wkend Hourly gas shape.\n shape_boilers_yh[day] = heating_shape[day] * data[tech_to_get_shape]['holiday']\n shape_boilers_y_dh[day] = data[tech_to_get_shape]['holiday']\n else: # Wkday Hourly gas shape.\n shape_boilers_yh[day] = heating_shape[day] * data[tech_to_get_shape]['workday'] #yd\n shape_boilers_y_dh[day] = data[tech_to_get_shape]['workday'] #dh\n\n return shape_boilers_yh, shape_boilers_y_dh\n",
"\"\"\"Create chart of correlating HDD with gas demand\n\nCalculate HDD with weather data from a asingle weather station for the whole of the UK.abs\nCorrelate HDD with national gas data.\n\nNational gas data source: National Grid (2015) Seasonal Normal Demand Forecasts\n\"\"\"\nimport os\nimport numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nfrom energy_demand.profiles import hdd_cdd\nfrom energy_demand.read_write import read_weather_data\nfrom energy_demand.plotting import plotting_program\n\n# ----------------------------------\n# Read temp data and weather station\n# ----------------------------------\npath_data_temp = os.path.join(r'Z:\\01-Data_NISMOD\\data_energy_demand', r'16-Met_office_weather_data\\midas_wxhrly_201501-201512.csv')\npath_data_stations = os.path.join(r'Z:\\01-Data_NISMOD\\data_energy_demand', r'16-Met_office_weather_data\\excel_list_station_details.csv')\n\n# Read temp data\nprint(\"...read temp\")\ntemperature_data_raw = read_weather_data.read_weather_data_raw(path_data_temp, 9999)\n\n# Clean raw temperature data\nprint(\"...clean temp\")\ntemperature_data = read_weather_data.clean_weather_data_raw(temperature_data_raw, 9999)\n\n# Weather stations\nprint(\"...weatherstations\")\nweather_stations = read_weather_data.read_weather_stations_raw(path_data_stations, temperature_data.keys())\n\n# Temperature weather data weater station \n# 595\tCHURCH\tLAWFORD\tWARWICKSHIRE\tCOUNTY\t01/01/1983\tCurrent\t52.3584\t-1.32987\tCV23\t9\n#593\tELMDON\tWEST\tMIDLANDS\tCOUNTY\t01/01/1949\tCurrent\t52.4524\t-1.74099\tB26\t3\t\t\t\t--> slightly better correlation\nstation_ID_ELMDON = 593 #593\ntemperatures = temperature_data[station_ID_ELMDON]\n\n\n# Calculate average day temp\naverag_day_temp = []\nfor day in temperatures:\n averag_day_temp.append(np.mean(day))\n\n# ----------------------------------\n# Calculate HDD\n# ----------------------------------\nprint(\"...calc hdd\")\nprint(temperatures.shape)\n\nt_base_heating = 15.5 # Heating t_base temp\n\n# HDD\nhdd_reg = hdd_cdd.calc_hdd(t_base_heating, temperatures)\nprint(\"shape hdd \" + str(hdd_reg.shape))\n'''\nhdd_reg = np.zeros((365))\nfor weaterstaion in temperature_data.keys():\n print(\"Station: \" + str(weaterstaion))\n print(temperature_data[weaterstaion][:1])\n hdd_reg += hdd_cdd.calc_hdd(t_base_heating, temperature_data[weaterstaion])\n'''\n# Test if correlation with mean temp is better than with HDd\n#hdd_reg = averag_day_temp\n\n# Data\n\n# -- Non daily metered gas demand in mcm == Residential heating gas demand for year 2015 (Jan - Dez --> Across two excel in orig file)\ngas_demand_NDM_2015_2016 = [\n 2059.3346672,\n 2170.0185108,\n 2098.5700609,\n 2129.0042078,\n 2183.3908583,\n 2183.3755211,\n 2181.77478289999,\n 2180.2661608,\n 2171.9539465,\n 2093.1630535,\n 2123.4248103,\n 2177.2511151,\n 2177.4395409,\n 2177.4392085,\n 2175.2222323,\n 2166.6139387,\n 2087.285658,\n 2115.1954239,\n 2167.4317226,\n 2166.5545797,\n 2164.694753,\n 2163.4837384,\n 2157.386435,\n 2080.9887003,\n 2111.8947958,\n 2166.0717924,\n 2162.6456414,\n 2159.295252,\n 2155.8334129,\n 2145.8472366,\n 2061.1717803,\n 2082.3903686,\n 2127.0822845,\n 2118.2712922,\n 2113.193853,\n 2107.8898595,\n 2095.8412092,\n 2014.9440596,\n 2049.2258347,\n 2107.0791469,\n 2112.1583269,\n 2117.2396604,\n 2123.0313351,\n 2122.1358234,\n 2051.7066905,\n 2087.3670451,\n 2136.4535688,\n 2132.1460485,\n 2128.3906968,\n 2124.2843977,\n 2105.6629196,\n 2019.1113801,\n 2036.5569675,\n 2077.2039557,\n 2061.8101344,\n 2046.7869234,\n 2031.4318873,\n 2005.2602169,\n 1914.0892568,\n 1922.9069295,\n 1954.9594171,\n 1933.6480271,\n 1912.3061523,\n 1890.5476499,\n 1862.3706414,\n 1775.6671805,\n 1783.4502818,\n 1814.9200643,\n 1796.8545889,\n 1784.4710306,\n 1771.6500082,\n 1752.3369114,\n 1674.0247522,\n 1687.99816,\n 1726.2909774,\n 1715.8915875,\n 1705.7032311,\n 1692.0716697,\n 1671.1552101,\n 1594.1241588,\n 1603.713891,\n 1636.247885,\n 1620.6947572,\n 1605.2659081,\n 1590.0104955,\n 1569.4656755,\n 1494.5719877,\n 1502.5278704,\n 1535.2362037,\n 1526.2747126,\n 1513.4608687,\n 1504.8484041,\n 1490.7666095,\n 1325.9250159,\n 1316.9165572,\n 1462.4932465,\n 1458.1802196,\n 1442.6262542,\n 1426.8417784,\n 1411.3589019,\n 1335.8538668,\n 1333.6755582,\n 1356.6697705,\n 1334.994619,\n 1313.3468669,\n 1291.2764263,\n 1261.7044342,\n 1187.3254679,\n 1182.7090036,\n 1206.201116,\n 1187.9607269,\n 1169.0975458,\n 1150.8622665,\n 1125.7570188,\n 1059.6150794,\n 1057.5077396,\n 1081.4643041,\n 1065.2552632,\n 1049.0529795,\n 1032.9539024,\n 1007.1793016,\n 914.58361712,\n 897.87864486,\n 880.61178046,\n 909.11557166,\n 890.86945346,\n 871.96514751,\n 853.8612021,\n 791.8538562,\n 775.11686001,\n 832.03363633,\n 814.21901615,\n 799.58233329,\n 784.71165334,\n 761.63725303,\n 707.19260431,\n 704.66692408,\n 729.32567359,\n 716.8394616,\n 704.16329367,\n 692.60720982,\n 673.62744381,\n 625.16539826,\n 616.31467523,\n 606.17192685,\n 636.72436643,\n 625.93400599,\n 615.10886486,\n 605.22026297,\n 557.46992056,\n 551.34168138,\n 578.47909485,\n 570.13253752,\n 561.78823047,\n 553.3654021,\n 538.91778989,\n 498.94506464,\n 500.61103512,\n 529.17638846,\n 522.76561207,\n 516.42800386,\n 510.56638091,\n 496.03207692,\n 456.62523814,\n 456.93248186,\n 484.57825041,\n 478.35283027,\n 472.67018165,\n 467.07413108,\n 452.94073995,\n 415.61047941,\n 417.54936646,\n 447.87992936,\n 444.32552312,\n 440.34388174,\n 436.93497309,\n 425.39778941,\n 390.98147195,\n 393.27803263,\n 422.2499116,\n 418.01587597,\n 413.61939995,\n 409.40057065,\n 397.24314025,\n 362.84744615,\n 363.93696426,\n 393.56430501,\n 390.46598983,\n 387.50245828,\n 384.08572436,\n 373.79849944,\n 341.87745791,\n 344.96303388,\n 375.65480602,\n 374.49215286,\n 372.75648874,\n 371.74226978,\n 361.8690835,\n 331.52439876,\n 335.15290392,\n 366.77742567,\n 365.12052235,\n 364.02193295,\n 362.52261752,\n 352.52451205,\n 322.45011946,\n 326.07034766,\n 357.85885375,\n 357.46873061,\n 356.17585959,\n 356.18529447,\n 347.76795445,\n 318.87093053,\n 323.44991194,\n 357.14307241,\n 358.48343406,\n 359.41495,\n 360.13619174,\n 352.30573134,\n 323.75524954,\n 328.47959503,\n 361.26301948,\n 361.91381511,\n 362.52822042,\n 363.04084256,\n 354.83105903,\n 327.4003489,\n 333.7913569,\n 367.75844026,\n 369.11519087,\n 372.6949059,\n 375.8462941,\n 371.01068634,\n 344.6986732,\n 353.4825506,\n 390.13714534,\n 393.84951909,\n 397.83499025,\n 401.57927692,\n 396.97028525,\n 370.21486247,\n 379.29129941,\n 416.16743945,\n 420.07485221,\n 423.97519461,\n 429.74321627,\n 427.2986801,\n 401.46194542,\n 413.22870233,\n 456.07775396,\n 465.3295712,\n 474.21723331,\n 483.12391875,\n 484.18266475,\n 461.009664,\n 476.92695202,\n 521.59453157,\n 530.84505032,\n 540.18546168,\n 549.72258375,\n 551.25306059,\n 525.45532919,\n 542.29079386,\n 587.07994975,\n 596.34233521,\n 607.50869098,\n 618.97893781,\n 622.86393906,\n 597.19837803,\n 621.39030489,\n 674.41691171,\n 690.65537739,\n 706.66602486,\n 750.44401705,\n 761.5020047,\n 735.3577927,\n 758.94313283,\n 820.97761046,\n 841.64549132,\n 862.82785312,\n 882.73942176,\n 895.8174329,\n 867.22285798,\n 895.86950089,\n 962.4264397,\n 986.21496809,\n 1010.5025124,\n 1034.947993,\n 1049.36376,\n 1016.2553526,\n 1045.7292098,\n 1113.1746337,\n 1125.8164178,\n 1141.3139762,\n 1159.7889682,\n 1167.2284687,\n 1125.5987857,\n 1158.1749163,\n 1228.6271493,\n 1250.8619219,\n 1276.6254017,\n 1300.3160004,\n 1317.8170358,\n 1282.8879339,\n 1320.3942354,\n 1394.2587548,\n 1416.5190559,\n 1438.5435458,\n 1461.7634807,\n 1479.7562971,\n 1438.8539543,\n 1478.9216764,\n 1557.1207719,\n 1573.4090718,\n 1587.6655331,\n 1603.6341589,\n 1613.333634,\n 1562.3586478,\n 1600.277806,\n 1679.9344601,\n 1697.4619665,\n 1712.8552817,\n 1724.7516139,\n 1724.0138982,\n 1657.0594241,\n 1682.3440925,\n 1748.5809406,\n 1752.9203251,\n 1763.9782637,\n 1775.1642524,\n 1782.4227695,\n 1722.1387718,\n 1761.2175743,\n 1843.516748,\n 1861.6814774,\n 1873.721509,\n 1884.7695907,\n 1889.1761128,\n 1820.2893554,\n 1849.3759024,\n 1927.6865797,\n 1941.1637845,\n 1949.9179591,\n 1955.9424808,\n 1956.9521671,\n 1880.0208367,\n 1906.0644726,\n 1980.6623416,\n 1988.0433795,\n 1992.2170495,\n 2003.9919664,\n 2009.5777063,\n 1937.9896745,\n 1964.8414739,\n 2036.894857,\n 2044.9981179,\n 2053.3450878,\n 1974.8040044,\n 1814.6135915,\n 1904.8874509,\n 1909.229843,\n 1911.2513971,\n 1995.545462,\n 1995.3479943,\n 1997.4328038\n ]\n\n\n# ----------------\n# Linear regression\n# ----------------\ndef lin_func(x, slope, intercept):\n y = slope * x + intercept\n return y\n\nprint(\"...regression\")\nslope, intercept, r_value, p_value, std_err = stats.linregress(gas_demand_NDM_2015_2016, hdd_reg)\n\nprint(\"Slope: \" + str(slope))\nprint(\"intercept: \" + str(intercept))\nprint(\"r_value: \" + str(r_value))\nprint(\"p_value: \" + str(p_value))\nprint(\"std_err: \" + str(std_err))\n\n# Set figure size in cm\nplt.figure(figsize=plotting_program.cm2inch(8, 8))\n\n# plot points\nplt.plot(gas_demand_NDM_2015_2016, hdd_reg, 'ro', markersize=5, color='gray')\n\n# plot line\n#plt.plot(gas_demand_NDM_2015_2016, hdd_reg, 'ro')\n\n# Plot regression line\nX_plot = np.linspace(300, 2250, 500)\n\nY_plot = []\nfor x in X_plot:\n Y_plot.append(lin_func(x, slope, intercept))\n\nplt.plot(X_plot, Y_plot, color='k')\n#plt.axis([0, 6, 0, 20])\n\n\n\nplt.xlabel(\"National gas demand [GWh / h]\")\nplt.ylabel(\"Heating degree days\")\nplt.title(\"Correlation between national gas demand and hdd (r_value: {}\".format(r_value))\nplt.show()\n"
] | [
[
"numpy.max",
"numpy.zeros",
"numpy.sum"
],
[
"numpy.linspace",
"matplotlib.pyplot.plot",
"scipy.stats.linregress",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
dstarkey23/vessel_detection_satellite_imagery | [
"f00faee230499f094e0df50f5985a3f6422ed0be"
] | [
"vessel_detection.py"
] | [
"#image analysis project from vtx\n#add training dataset from kaggle project\n#https://www.kaggle.com/rhammell/ships-in-satellite-imagery\n#paper https://www.irjet.net/archives/V6/i9/IRJET-V6I9291.pdf\n\nimport numpy as np\nimport matplotlib.pylab as plt\nimport json\nfrom sklearn.model_selection import train_test_split\nimport keras\nimport pickle\nimport os\nfrom sklearn import metrics\nfrom PIL import Image\nfrom keras_sequential_ascii import keras2ascii\n\ndef load_data_from_json(file = './data/shipsnet.json'):\n '''\n load input data and target labels from json at location specified by\n file argument.\n :return:\n X[N, img_width, img_height, color channels]: image pixels\n target[N]: 1 / 0 labels\n :return:\n '''\n # download dataset from json object\n f = open(file)\n data = json.load(f)\n f.close()\n\n # Ingest images and labels\n input_data = np.array(data['data']).astype('uint8')\n output_data = np.array(data['labels']).astype('uint8')\n\n # Json input images are all 1D. Need to convert into (80, 80, 3)\n # final 3rd dim colour channel (RGB)\n X = input_data.reshape([-1, 3, 80, 80])\n # reorder indices for required keras input format\n X = np.transpose(X, (0, 2, 3, 1))\n return X, output_data\n\n\ndef plot_example_rgb(pic, savefile=None):\n '''\n Plot all channels of input image\n :return:\n '''\n plt.close()\n labels = ['Red','Greed','Blue']\n fig = plt.figure()\n for i in range(np.shape(pic)[2]):\n pixels = pic[:,:,i]\n ax1 = fig.add_subplot(3,1,i+1)\n ax1.imshow(pixels,cmap='Blues')\n ax1.set_title(labels[i])\n plt.tight_layout()\n if savefile is None:\n plt.show()\n else:\n plt.savefig(savefile)\n plt.close()\n\n\n\ndef conv_pool_dropout_block(modelin,\n input_shape = None,\n Nfilters = 32,\n filtersize = (3, 3),\n poolsize = (2, 2),\n padding = 'same',\n activation = 'relu',\n dropout_frac = 0.3):\n '''\n Sequential conv, pooling and dropout layers tend to perform well\n in classification problems\n :param modelin:\n :param filtersize:\n :param poolsize:\n :param padding:\n :return:\n '''\n model = modelin\n if input_shape is not None:\n model.add(keras.layers.Conv2D(Nfilters, filtersize,\n padding=padding,\n input_shape=input_shape,\n activation=activation))\n else:\n model.add(keras.layers.Conv2D(Nfilters, filtersize,\n padding=padding,\n activation=activation))\n model.add(keras.layers.MaxPooling2D(pool_size=poolsize)) # 40x40\n model.add(keras.layers.Dropout(dropout_frac))\n return model\n\n\ndef define_custom_convnet(image_dim = (80,80,3)):\n '''\n convnet with 4 sequential conv, max-pool, dropout layers\n :return:\n '''\n\n # network design\n model = keras.Sequential()\n\n #apply 4 conv blocks\n for i in range(4):\n if i == 0:\n input_shape = image_dim\n else:\n input_shape = None\n model = conv_pool_dropout_block(model,\n input_shape = input_shape,\n Nfilters=32,\n filtersize=(3, 3),\n poolsize=(2, 2),\n padding='same',\n activation='relu',\n dropout_frac=0.3)\n\n #apply ouptput classifier layers\n model.add(keras.layers.Flatten())\n model.add(keras.layers.Dense(32, activation='relu'))\n model.add(keras.layers.Dropout(0.5))\n model.add(keras.layers.Dense(2, activation='softmax'))\n\n # optimization setup\n sgd = keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True)\n model.compile(\n loss='categorical_crossentropy',\n optimizer=sgd,\n metrics=['accuracy'])\n return model\n\n\ndef diagnostic_plots(y_pred_probs,y_test_probs,\n labels_in = None,\n diagnostic_file = './images/roc_plot.png',\n max_fpr_tollerance = 0.01):\n '''\n\n :return:\n '''\n # fit model on test data\n fpr, tpr, thresholds = metrics.roc_curve(y_test_probs[:, 0], y_pred_probs[:, 0], pos_label=1)\n auc = metrics.auc(fpr, tpr)\n idx = np.argsort(fpr)\n fpr = fpr[idx]\n tpr = tpr[idx]\n thresholds = thresholds[idx]\n idx_threshold = np.where(fpr > max_fpr_tollerance)[0][0]\n threshold_tollerance = thresholds[idx_threshold]\n print('ROC curve AUC = ' + str(auc))\n fig = plt.figure()\n ax1 = fig.add_subplot(211)\n ax1.set_xlabel('False Positive Rate')\n ax1.set_ylabel('True Positive Rate')\n ann = 'threshold probability P(FPR=' + str(max_fpr_tollerance) + ') = ' \\\n + str(np.round(threshold_tollerance, 2)) + \\\n '\\n TPR = ' + str(np.round(tpr[idx_threshold], 2))\n ax1.axvline(fpr[idx_threshold], label=ann, color='b')\n ax1.plot(fpr, tpr, label='AUC = ' + str(np.round(auc, 2)), color='r')\n ax1.set_title('model ROC curve')\n ax1.legend()\n\n # now add confusion matrix for tollerance result\n cm = metrics.confusion_matrix(np.argmax(y_test, axis=1), np.argmax(y_pred, axis=1))\n cmn = cm / cm.sum(axis=1)[:, np.newaxis]\n ax2 = fig.add_subplot(2, 2, 3)\n b = ax2.imshow(cmn, cmap='Blues')\n cbar = fig.colorbar(b)\n cbar.set_label('Normalised Counts')\n if labels_in is None:\n labels = list(np.array(np.unique(y_test), dtype=str))\n else:\n labels = labels_in\n ax2.set_xlabel('Predicted')\n ax2.set_ylabel('Actual')\n ax2.set_title('Confusion Matrix \\nP(FPR=' + str(max_fpr_tollerance) + ')')\n ax2.set_xticks = np.arange(len(labels))\n ax2.set_xticklabels = labels\n ax2.set_yticks = np.arange(len(labels))\n ax2.set_yticklabels = labels\n plt.tight_layout()\n plt.savefig(diagnostic_file)\n\n\ndef fit_load_model(X_train_norm, y_train,\n new_model=False,\n picklefile='./models/custom_convnet.pickle',\n input_model=None):\n '''\n fit or load a new model from file\n :return:\n '''\n if new_model is True:\n model = input_model\n # fit the model\n model.fit(X_train_norm, y_train,\n batch_size=32,\n epochs=18,\n validation_split=0.2,\n shuffle=True,\n verbose=2)\n # pickle the fitted model\n os.system('rm ' + picklefile)\n pickle_out = open(picklefile, \"wb\")\n pickle.dump({'model': model}, pickle_out)\n pickle_out.close()\n else:\n model = pickle.load(open(picklefile, \"rb\"))['model']\n return model\n\n\ndef plot_example_classes(X, y_pred=None, y_test=None, N_examples = 3, filename='./images/examples.png',\n idx_custom = None, labels_custom = None):\n '''\n show some example classifications demonstrating where the CNN\n got it both right and wrong\n :param y_pred:\n :param y_test:\n :param N_examples:\n :param filename:\n :return:\n '''\n if y_pred is None and idx_custom is None:\n raise Exception('one of y_pred or idx_custom must not be None')\n if y_pred is not None:\n pred_class = np.argmax(y_pred, axis=1)\n if y_test is not None:\n test_class = np.argmax(y_test, axis=1)\n if idx_custom is None:\n idx_FP = np.where((pred_class == 1) & (test_class == 0))[0]\n idx_FN = np.where((pred_class == 0) & (test_class == 1))[0]\n idx_TP = np.where((pred_class == 1) & (test_class == 1))[0]\n idx_TN = np.where((pred_class == 0) & (test_class == 0))[0]\n idx_groups = [idx_TP, idx_TN, idx_FP, idx_FN]\n else:\n idx_groups = idx_custom\n if labels_custom is None:\n labels = ['True Positives', 'True Negatives', 'False Positives', 'False Negatives']\n else:\n labels = labels_custom\n i = 0\n fig, big_axes = plt.subplots(figsize=(15.0, 15.0), nrows=len(labels), ncols=1, sharey=True)\n itemp = 0\n for row, big_ax in enumerate(big_axes, start=1):\n big_ax.set_title(labels[itemp], fontsize=24)\n big_ax.tick_params(labelcolor=(1., 1., 1., 0.0), top='off', bottom='off', left='off', right='off')\n big_ax._frameon = False\n itemp += 1\n for idx in idx_groups:\n n = min(len(idx), N_examples)\n for i2 in range(n):\n ax1 = fig.add_subplot(len(idx_groups), N_examples, i * N_examples + i2 + 1)\n x = np.array(X[idx[i2], :, :, :])\n xn = np.uint8(x / x.max() * 255)\n img = Image.fromarray(xn, mode='RGB')\n ax1.imshow(img)\n i += 1\n fig.set_facecolor('w')\n plt.tight_layout()\n plt.savefig(filename)\n\nif __name__ == '__main__':\n\n # download dataset from json object\n X, target = load_data_from_json(file = './data/shipsnet.json')\n\n # the target is a 2d array of the probability\n # that the image is a ship or isnt a ship\n # need to construct this 2d prob array\n y = keras.utils.np_utils.to_categorical(target)\n\n # plot image file\n plot_example_rgb(X[0], savefile = './images/example_input.png')\n\n # split into train test data\n X_train, X_test, y_train, y_test = train_test_split(X, y,\n test_size = 0.33,\n random_state = 42)\n\n #transform by dividing through by minimum value\n norm = X_train.max()\n X_train_norm = X_train/norm\n X_test_norm = X_test/norm\n\n # define the model\n model = define_custom_convnet()\n\n #summarise\n keras2ascii(model)\n\n #fit or load pre-trained model\n model = fit_load_model(X_train_norm, y_train,\n new_model=False,\n picklefile='./models/custom_convnet.pickle',\n input_model=model)\n\n # score model on test data\n y_pred = model.predict(X_test_norm)\n diagnostic_plots(y_pred, y_test,\n labels_in=None,\n diagnostic_file='./images/roc_plot.png',\n max_fpr_tollerance=0.01)\n\n # show examples of false positives and negatives\n plot_example_classes(X_test_norm, y_pred, y_test,\n N_examples=3, filename='./images/examples.png',\n idx_custom=None, labels_custom=None)\n\n # just plot some of the original samples\n plot_example_classes(X_test_norm,\n None, None,\n idx_custom=[[1,2,3],[4,5,6],[7,8,9]],\n labels_custom=['','',''],\n N_examples = 3,\n filename='./images/input_examples.png')\n\n\n\n\n\n"
] | [
[
"matplotlib.pylab.tight_layout",
"matplotlib.pylab.show",
"numpy.unique",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.roc_curve",
"numpy.round",
"numpy.argmax",
"matplotlib.pylab.figure",
"numpy.shape",
"numpy.transpose",
"numpy.argsort",
"sklearn.metrics.auc",
"matplotlib.pylab.savefig",
"numpy.array",
"numpy.where",
"matplotlib.pylab.close"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nevaan9/Python-Data-Cleaning-Cookbook | [
"c40322673ad93f59a3fe183fcd881e61053001f2",
"c40322673ad93f59a3fe183fcd881e61053001f2",
"c40322673ad93f59a3fe183fcd881e61053001f2"
] | [
"06 - Cleaning and Exploring data with Series/1. series_basics.py",
"07 - Fixing Messy Data When Aggregating/1. row_iteration.py",
"09 - Tidying and Reshaping/2. many_to_many_reshape.py"
] | [
"# import pandas and load nls data\nimport pandas as pd\npd.set_option('display.width', 78)\npd.set_option('display.max_columns', 7)\npd.set_option('display.max_rows', 200)\npd.options.display.float_format = '{:,.2f}'.format\nnls97 = pd.read_csv(\"data/nls97b.csv\")\nnls97.set_index(\"personid\", inplace=True)\n\n# create a series from the GPA column\ngpaoverall = nls97.gpaoverall\ntype(gpaoverall)\ngpaoverall.head()\ngpaoverall.index\n\n# select gpa values using bracket notation\ngpaoverall[:5]\ngpaoverall.tail()\ngpaoverall[-5:]\n\n# select values using loc\ngpaoverall.loc[100061]\ngpaoverall.loc[[100061]]\ngpaoverall.loc[[100061,100139,100284]]\ngpaoverall.loc[100061:100833]\n\n# select values using iloc\ngpaoverall.iloc[[0]]\ngpaoverall.iloc[[0,1,2,3,4]]\ngpaoverall.iloc[:5]\ngpaoverall.iloc[-5:]\n\n",
"# import pandas and numpy, and load the covid data\nimport pandas as pd\nimport numpy as np\npd.set_option('display.width', 200)\npd.set_option('display.max_columns', 35)\npd.set_option('display.max_rows', 200)\npd.options.display.float_format = '{:,.2f}'.format\ncoviddaily = pd.read_csv(\"data/coviddaily720.csv\", parse_dates=[\"casedate\"])\nltbrazil = pd.read_csv(\"data/ltbrazil.csv\")\n\n# sort the covid data by location and case date in ascending order\ncoviddaily = coviddaily.sort_values(['location','casedate'])\n\n# iterate over rows with itertuples, append to list with each change of group\nprevloc = 'ZZZ'\nrowlist = []\nfor row in coviddaily.itertuples():\n if (prevloc!=row.location):\n if (prevloc!='ZZZ'):\n rowlist.append({'location':prevloc, 'casecnt':casecnt})\n casecnt = 0\n prevloc = row.location\n casecnt += row.new_cases\n \nrowlist.append({'location':prevloc, 'casecnt':casecnt})\nlen(rowlist)\nrowlist[0:4]\n\n# create a dataframe from the rowlist\ncovidtotals = pd.DataFrame(rowlist)\ncovidtotals.head()\n\n# sort the land temperatures data and drop rows with missing values for temperature\nltbrazil = ltbrazil.sort_values(['station','month'])\nltbrazil = ltbrazil.dropna(subset=['temperature'])\n\n# iterate over rows with itertuples, append to list with each change of group\nprevstation = 'ZZZ'\nprevtemp = 0\nrowlist = []\nfor row in ltbrazil.itertuples():\n if (prevstation!=row.station):\n if (prevstation!='ZZZ'):\n rowlist.append({'station':prevstation, 'avgtemp':tempcnt/stationcnt, 'stationcnt':stationcnt})\n tempcnt = 0\n stationcnt = 0\n prevstation = row.station\n\n # choose only rows that are within 3 degrees of the previous temperature \n if ((0 <= abs(row.temperature-prevtemp) <= 3) or (stationcnt==0)):\n tempcnt += row.temperature\n stationcnt += 1\n \n prevtemp = row.temperature\n\nrowlist.append({'station':prevstation, 'avgtemp':tempcnt/stationcnt, 'stationcnt':stationcnt})\nrowlist[0:5]\nltbrazilavgs = pd.DataFrame(rowlist)\nltbrazilavgs.head()\n\n\n",
"# import pandas and the CMA collections data\nimport pandas as pd\npd.options.display.float_format = '{:,.0f}'.format\ncma = pd.read_csv(\"data/cmacollections.csv\")\n\n# show the cma collections data\ncma.shape\ncma.head(2).T\ncma.id.nunique()\ncma.drop_duplicates(['id','citation']).id.count()\ncma.drop_duplicates(['id','creator']).id.count()\n\n# show a collection item with duplicated citations and creators\ncma.set_index(['id'], inplace=True)\ncma.loc[124733, ['title','citation','creator','birth_year']].head(14)\n\n# create a collections data frame\ncollectionsvars = ['title','collection','type']\ncmacollections = cma[collectionsvars].\\\n reset_index().\\\n drop_duplicates(['id']).\\\n set_index(['id'])\ncmacollections.shape\ncmacollections.head()\ncmacollections.loc[124733]\n\n# create a citations data frame\ncmacitations = cma[['citation']].\\\n reset_index().\\\n drop_duplicates(['id','citation']).\\\n set_index(['id'])\ncmacitations.loc[124733]\n\n# create a creators data frame\ncreatorsvars = ['creator','birth_year','death_year']\ncmacreators = cma[creatorsvars].\\\n reset_index().\\\n drop_duplicates(['id','creator']).\\\n set_index(['id'])\ncmacreators.loc[124733]\n\n# count the number of collection items with a creator born after 1950\ncmacreators['birth_year'] = cmacreators.birth_year.str.findall(\"\\d+\").str[0].astype(float)\nyoungartists = cmacreators.loc[cmacreators.birth_year>1950, ['creator']].assign(creatorbornafter1950='Y')\nyoungartists.shape[0]==youngartists.index.nunique()\nyoungartists\ncmacollections = pd.merge(cmacollections, youngartists, left_on=['id'], right_on=['id'], how='left')\ncmacollections.creatorbornafter1950.fillna(\"N\", inplace=True)\ncmacollections.shape\ncmacollections.creatorbornafter1950.value_counts()\n"
] | [
[
"pandas.set_option",
"pandas.read_csv"
],
[
"pandas.set_option",
"pandas.read_csv",
"pandas.DataFrame"
],
[
"pandas.merge",
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
BingqingCheng/ASAP | [
"d34a064cd7e409ad8b5ae0dec4f1c0a621717773",
"d34a064cd7e409ad8b5ae0dec4f1c0a621717773",
"d34a064cd7e409ad8b5ae0dec4f1c0a621717773",
"d34a064cd7e409ad8b5ae0dec4f1c0a621717773"
] | [
"asaplib/compressor/sparsifier.py",
"deprecated/frame_select_deprecated.py",
"tests/test_frame_select.py",
"deprecated/gen_LMBTR_descriptors_deprecated.py"
] | [
"\"\"\"\nsparsifier class\n\"\"\"\n\nfrom asaplib.compressor import random_split, fps, CUR_deterministic\n\nclass Sparsifier:\n def __init__(self, sparse_mode):\n \"\"\"\n Object handing the sparsification of data\n Parameters\n ----------\n sparse_mode: str\n Type of the sparse mode\n \"\"\"\n self._possible_modes = ['fps', 'cur', 'random', 'sequential']\n if sparse_mode.lower() not in self._possible_modes:\n raise NotImplementedError(\"Do not recognize the selected sparsification mode. \\\n Use ([cur], [fps], [random],[sequential]).\")\n else:\n self.sparse_mode = sparse_mode.lower()\n\n def _check(self, n_sparse, n_total):\n # sanity check\n if n_sparse > n_total:\n print(\"the number of representative structure is too large, please select n <= \", n_total)\n\n def sparsify(self, desc_or_ntotal, n_or_ratio, sparse_param=0):\n \"\"\"\n Function handing the sparsification of data\n Parameters\n ----------\n desc_or_ntotal: np.matrix or int\n Either a design matrix [n_sample, n_desc],\n or simply the total number of samples\n n_or_ratio: int or float \n Either the number or the fraction of sparsified points\n sparse_param: int\n additional parameter that may be needed for the specific sparsifier used\n\n Returns\n ----------\n sbs: list\n a list of the indexes for the sparsified points\n \"\"\"\n if isinstance(desc_or_ntotal, int):\n n_total = desc_or_ntotal\n input_desc = False\n else:\n desc = desc_or_ntotal\n n_total = len(desc_or_ntotal)\n input_desc = True\n\n if n_or_ratio == 1 or isinstance(n_or_ratio, float):\n n_sparse = n_total * n_or_ratio\n elif isinstance(n_or_ratio, int):\n n_sparse = n_or_ratio\n else:\n raise ValueError(\"the sparsification ratio/number should be a float or int.\")\n \n self._check(n_sparse, n_total)\n\n if self.sparse_mode == 'fps':\n if not input_desc: \n raise ValueError(\"fps needs design matrix\")\n sbs, _ = fps(desc, n_sparse, int(sparse_param))\n elif self.sparse_mode == 'cur':\n if not input_desc:\n raise ValueError(\"cur needs design matrix\")\n import numpy as np\n cov = np.dot(np.asmatrix(desc), np.asmatrix(desc).T)\n sbs, _ = CUR_deterministic(cov, n_sparse)\n elif self.sparse_mode == 'random':\n _, sbs = random_split(n_total, n_sparse/n_total)\n elif self.sparse_mode == 'sequential':\n sbs = range(n_sparse)\n else:\n raise ValueError(\"sparse mode not right\")\n\n return sbs\n",
"#!/usr/bin/python3\n\"\"\"\nTODO: Module-level description\n\"\"\"\n\nimport argparse\nimport os\n\nimport numpy as np\n\nfrom asaplib.compressor import fps, CUR_deterministic\nfrom asaplib.data import ASAPXYZ\n\n\ndef main(fxyz, fy, prefix, nkeep, algorithm, fmat, fkde, reweight_lambda):\n \"\"\"\n Select frames from the supplied xyz file (fxyz) using one of the following algorithms:\n\n 1. random: random selection\n 2. fps: farthest point sampling selection. Need to supply a kernel matrix or descriptor matrix using -fmat\n 3. sortmin/sortmax: select the frames with the largest/smallest value. Need to supply the vector of properties using\n -fy\n 4. CUR decomposition\n 5. Reweight according to the re-weighted distribution exp(-f/\\lambda),\n where exp(-f) is the precomputed kernel density estimation of the original samples.\n\n Parameters\n ----------\n fxyz: Path to xyz file.\n fy: Path to the list of properties (N floats) or name of the tags in ase xyz file\n prefix: Filename prefix, default is ASAP\n nkeep: The number of representative samples to select\n algorithm: 'the algorithm for selecting frames ([random], [fps], [sort], [reweight])')\n fmat: Location of descriptor or kernel matrix file. Needed if you select [fps].\n You can use gen_kmat.py to compute it.\n reweight_lambda: select samples according to the re-weighted distribution exp(-f/\\lambda),\n where exp(-f) is the kernel density estimation of the original samples.\n \"\"\"\n\n # read the xyz file\n asapxyz = ASAPXYZ(fxyz)\n nframes = asapxyz.get_num_frames()\n\n if nkeep == 0:\n nkeep = nframes\n\n if fy != 'none':\n y_all = []\n try:\n y_all = np.genfromtxt(fy, dtype=float)\n except:\n y_all = asapxyz.get_property(fy)\n if len(y_all) != nframes:\n raise ValueError('Length of the vector of properties is not the same as number of samples')\n\n if algorithm == 'random' or algorithm == 'RANDOM':\n idx = np.asarray(range(nframes))\n sbs = np.random.choice(idx, nkeep, replace=False)\n\n elif algorithm == 'sortmax' or algorithm == 'sortmin':\n if fy == 'none':\n raise ValueError('must supply the vector of properties for sorting')\n\n idx = np.asarray(range(nframes))\n if algorithm == 'sortmax':\n sbs = [x for _, x in sorted(zip(y_all, idx))][:nkeep]\n elif algorithm == 'sortmin':\n sbs = [x for _, x in sorted(zip(y_all, idx))][nkeep:]\n\n elif algorithm == 'fps' or algorithm == 'FPS' or algorithm == 'cur' or algorithm == 'CUR':\n # for both algo we read in the descriptor matrix\n desc, _ = asapxyz.get_descriptors(fmat)\n if os.path.isfile(fmat):\n try:\n desc = np.genfromtxt(fmat, dtype=float)\n except:\n raise ValueError('Cannot load the kernel matrix')\n print(\"shape of the descriptor matrix: \", np.shape(desc), \"number of descriptors: \", np.shape(desc[0]))\n\n # FPS\n if algorithm == 'fps' or algorithm == 'FPS':\n sbs, dmax_remain = fps(desc, nkeep, 0)\n print(\"Making farthest point sampling selection\")\n np.savetxt(prefix + \"-\" + algorithm + \"-n-\" + str(nkeep) + '.error', dmax_remain, fmt='%4.8f',\n header='the maximum remaining distance in FPS')\n # CUR decomposition\n if algorithm == 'cur' or algorithm == 'CUR':\n desc = np.asmatrix(desc)\n cov = np.dot(desc, desc.T)\n print(\"Making CUR selection\")\n print(\"shape of the covariance matrix:\", np.shape(cov))\n sbs, rcov_error = CUR_deterministic(cov, nkeep)\n np.savetxt(prefix + \"-\" + algorithm + \"-n-\" + str(nkeep) + '.error', rcov_error, fmt='%4.8f',\n header='the remaining error of the covariance matrix')\n\n elif algorithm == 'reweight':\n if os.path.isfile(fkde):\n try:\n logkde = np.genfromtxt(fkde, dtype=float)[:, 1]\n except:\n raise IOError('Cannot load the (log of) kernel density for each sample')\n if len(logkde) != nframes: raise ValueError('mismatch of number of frames and kernel densities')\n else:\n raise ValueError('must suply the (log of) kernel density for each sample')\n\n new_kde = np.zeros(nframes)\n for i in range(nframes):\n new_kde[i] = np.exp(logkde[i] / reweight_lambda) / np.exp(logkde[i])\n # compute the normalization factor so we expect to select n samples in the end\n normalization = nkeep / np.sum(new_kde)\n new_kde *= normalization\n sbs = []\n randomchoice = np.random.rand(nframes)\n for i in range(nframes):\n if randomchoice[i] < new_kde[i]:\n sbs.append(i)\n algorithm = algorithm + \"-lambda-\" + str(reweight_lambda)\n # save\n selection = np.zeros(nframes, dtype=int)\n for i in sbs:\n selection[i] = 1\n np.savetxt(prefix + \"-\" + algorithm + \"-n-\" + str(nkeep) + '.index', selection, fmt='%d')\n if fy != 'none':\n np.savetxt(prefix + \"-\" + algorithm + \"-n-\" + str(nkeep) + '-' + fy, np.asarray(y_all)[sbs], fmt='%4.8f')\n asapxyz.write(prefix + \"-\" + algorithm + \"-n-\" + str(nkeep), sbs)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-fxyz', type=str, required=True, help='Location of xyz file')\n parser.add_argument('-y', type=str, default='none',\n help='Location of the list of properties (N floats) or name of the tags in ase xyz file')\n parser.add_argument('--prefix', type=str, default='ASAP', help='Filename prefix')\n parser.add_argument('--n', type=int, default=0, help='number of the representative samples to select')\n parser.add_argument('--algo', type=str, default='random',\n help='the algorithm for selecting frames ([random], [fps], [cur], [sortmax], [sortmin],[reweight])')\n parser.add_argument('-fmat', type=str, required=False,\n help='Location of descriptor or kernel matrix file. Needed if you select [fps]. You can use gen_kmat.py to compute it.')\n parser.add_argument('-fkde', type=str, required=False,\n help='Location of the (log of) kernel density for each sample. Needed if you select [reweight]. You can use kernel_density_estimation.py to compute it.')\n parser.add_argument('--reweight_lambda', type=float, default=1,\n help='select samples according to the re-weighted distribution exp(-\\lambda*f)')\n args = parser.parse_args()\n\n main(args.fxyz, args.y, args.prefix, args.n, args.algo, args.fmat, args.fkde, args.reweight_lambda)\n",
"#!/usr/bin/python3\n\nimport os\n\nimport numpy as np\n\nfrom asaplib.compressor import Sparsifier\nfrom asaplib.data import ASAPXYZ\n\n\ndef main():\n \"\"\"\n Select frames from the supplied xyz file (fxyz) using one of the following algorithms:\n\n 1. random: random selection\n 2. fps: farthest point sampling selection. Need to supply a kernel matrix or descriptor matrix using -fmat\n 4. CUR decomposition\n\n Parameters\n ----------\n fxyz: Path to xyz file.\n fmat: Path to the design matrix or name of the tags in ase xyz file\n prefix: Filename prefix, default is ASAP\n nkeep: The number of representative samples to select\n algorithm: 'the algorithm for selecting frames ([random], [fps], [cur])')\n fmat: Location of descriptor or kernel matrix file. Needed if you select [fps] or [cur].\n \"\"\"\n\n fxyz = os.path.join(os.path.split(__file__)[0], 'small_molecules-SOAP.xyz')\n fmat = ['SOAP-n4-l3-c1.9-g0.23']\n nkeep = 10\n prefix = \"test-frame-select\"\n\n # read the xyz file\n asapxyz = ASAPXYZ(fxyz)\n # for both algo we read in the descriptor matrix\n desc, _ = asapxyz.get_descriptors(fmat)\n print(\"shape of the descriptor matrix: \", np.shape(desc), \"number of descriptors: \", np.shape(desc[0]))\n\n for algorithm in ['random', 'cur', 'fps']:\n sparsifier = Sparsifier(algorithm)\n sbs = sparsifier.sparsify(desc, nkeep)\n # save\n selection = np.zeros(asapxyz.get_num_frames(), dtype=int)\n for i in sbs:\n selection[i] = 1\n np.savetxt(prefix + \"-\" + algorithm + \"-n-\" + str(nkeep) + '.index', selection, fmt='%d')\n asapxyz.write(prefix + \"-\" + algorithm + \"-n-\" + str(nkeep), sbs)\n\n\ndef test_gen(tmpdir):\n \"\"\"Test the generation using pytest\"\"\"\n main()\n\n\nif __name__ == '__main__':\n main()\n",
"#!/usr/bin/python3\nimport argparse\nimport json\nimport os\nimport sys\n\nimport numpy as np\nfrom ase.io import read, write\nfrom dscribe.descriptors import LMBTR\n\nfrom asaplib.io import str2bool\n\n\ndef main(fxyz, dictxyz, prefix, output, per_atom, config_path, periodic, stride):\n \"\"\"\n\n Generate the LMBTR Representation.\n\n Parameters\n ----------\n fxyz: string giving location of xyz file\n dictxyz: string giving location of xyz file that is used as a dictionary\n prefix: string giving the filename prefix\n output: [xyz]: append the representations to extended xyz file; [mat] output as a standlone matrix\n param_path': string Specify the Kn parameters using a json file. (see https://singroup.github.io/dscribe/tutorials/lmbtr.html)\n periodic: string (True or False) indicating whether the system is periodic\n stride: compute descriptor each X frames\n \"\"\"\n\n periodic = bool(periodic)\n per_atom = bool(per_atom)\n fframes = []\n dictframes = []\n\n # read frames\n if fxyz != 'none':\n fframes = read(fxyz, slice(0, None, stride))\n nfframes = len(fframes)\n print(\"read xyz file:\", fxyz, \", a total of\", nfframes, \"frames\")\n # read frames in the dictionary\n if dictxyz != 'none':\n dictframes = read(dictxyz, ':')\n ndictframes = len(dictframes)\n print(\"read xyz file used for a dictionary:\", dictxyz, \", a total of\",\n ndictframes, \"frames\")\n\n frames = dictframes + fframes\n nframes = len(frames)\n global_species = []\n for frame in frames:\n global_species.extend(frame.get_atomic_numbers())\n if not periodic:\n frame.set_pbc([False, False, False])\n global_species = np.unique(global_species)\n print(\"a total of\", nframes, \"frames, with elements: \", global_species)\n if config_path:\n try:\n with open(config_path, 'r') as config_file:\n config = json.load(config_file)\n except Exception:\n raise IOError('Cannot load the json file for parameters')\n\n if config_path:\n rep_atomic = LMBTR(species=global_species, periodic=periodic, flatten=True, **config)\n else:\n rep_atomic = LMBTR(species=global_species, flatten=True, periodic=periodic)\n if config_path:\n foutput = prefix + '-' + config_path\n desc_name = \"LMBTR\" + '-' + config_path\n else:\n foutput = prefix\n desc_name = \"LMBTR\"\n\n # prepare for the output\n if os.path.isfile(foutput + \".xyz\"): os.rename(foutput + \".xyz\", \"bck.\" + foutput + \".xyz\")\n if os.path.isfile(foutput + \".desc\"): os.rename(foutput + \".desc\", \"bck.\" + foutput + \".desc\")\n\n for i, frame in enumerate(frames):\n fnow = rep_atomic.create(frame)\n frame.info[desc_name] = fnow.mean(axis=0)\n\n # save\n if output == 'matrix':\n with open(foutput + \".desc\", \"ab\") as f:\n np.savetxt(f, frame.info[desc_name][None])\n if per_atom or nframes == 1:\n with open(foutput + \".atomic-desc\", \"ab\") as fatomic:\n np.savetxt(fatomic, fnow)\n elif output == 'xyz':\n # output per-atom info\n if per_atom:\n frame.new_array(desc_name, fnow)\n # write xyze\n write(foutput + \".xyz\", frame, append=True)\n else:\n raise ValueError('Cannot find the output format')\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-fxyz', type=str, required=True, help='Location of xyz file')\n parser.add_argument('-fdict', type=str, default='none', help='Location of xyz file '\n 'that is used for a dictionary')\n parser.add_argument('--prefix', type=str, default='ASAP', help='Filename prefix')\n parser.add_argument('--output', type=str, default='xyz', help='The format for output files ([xyz], [matrix])')\n parser.add_argument('--per_atom', type=str2bool, nargs='?', const=True, default=False,\n help='Do you want to output per atom descriptors for multiple frames (True/False)?')\n\n parser.add_argument('-param_path', type=str, default=False,\n help='Specify the hyper parameters using a json file. (see https://singroup.github.io/dscribe/tutorials/lmbtr.html)')\n parser.add_argument('--periodic', type=str2bool, nargs='?', const=True, default=False,\n help='Is the system periodic (True/False)?')\n parser.add_argument('--stride', type=int, default=1,\n help='Read in the xyz trajectory with X stide. Default: read/compute all frames')\n\n if len(sys.argv) == 1:\n parser.print_help(sys.stderr)\n sys.exit(1)\n args = parser.parse_args()\n\n main(args.fxyz, args.fdict, args.prefix, args.output, args.per_atom, args.param_path, args.periodic, args.stride)\n"
] | [
[
"numpy.asmatrix"
],
[
"numpy.dot",
"numpy.random.choice",
"numpy.asarray",
"numpy.genfromtxt",
"numpy.asmatrix",
"numpy.shape",
"numpy.random.rand",
"numpy.exp",
"numpy.zeros",
"numpy.sum"
],
[
"numpy.shape"
],
[
"numpy.savetxt",
"numpy.unique"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tere-valdivia/icy_tower_tarea | [
"8f5def11bda593c181b140b97fcb452828c84dd6"
] | [
"Fondo.py"
] | [
"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 12 11:46:51 2017\n\n@author: terevaldivia\n\"\"\"\nimport os\nfrom CC3501Utils_personal import *\nimport numpy as np\n\nclass Fondo(Figura):\n \n def __init__(self, pos=Vector(0, 0), rgb=(1.0, 1.0, 1.0)):\n super(Fondo, self).__init__(pos, rgb)\n \n def figura(self):\n glBegin(GL_QUADS)\n glColor3f(80 / 255.0, 80 / 255.0, 80 / 255.0) #gris oscuro\n glVertex2f(0,0)\n glVertex2f(0, 600)\n glVertex2f(800, 600)\n glVertex2f(800, 0)\n glEnd()\n \n numx = np.linspace(0., 700., 5)\n numy = np.linspace(0., 500., 5)\n altura = 30.\n ancho = 50.\n \n for x in numx:\n for y in numy:\n glBegin(GL_QUADS)\n glColor3f(66 / 255.0, 74 / 255.0, 65 / 255.0) #gris oscuro\n glVertex2f(x, y)\n glVertex2f(x, y + altura)\n glVertex2f(x + ancho, y + altura)\n glVertex2f(x + ancho, y)\n glEnd()\n glBegin(GL_QUADS)\n glColor3f(50 / 255.0, 50 / 255.0, 50 / 255.0) #gris oscuro\n glVertex2f(x+20, y+30)\n glVertex2f(x+20, y +30 + altura)\n glVertex2f(x+20 + ancho, y+30 + altura)\n glVertex2f(x+20 + ancho, y+30)\n glEnd()\n "
] | [
[
"numpy.linspace"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
douglascoenen/cbsyst | [
"79b9a1b549d598c10739129afecea4e0269020c8"
] | [
"cbsyst/cbsyst.py"
] | [
"import numpy as np\nfrom cbsyst.helpers import Bunch, maxL\nfrom cbsyst.MyAMI_V2 import MyAMI_K_calc, MyAMI_K_calc_multi\nfrom cbsyst.carbon_fns import *\nfrom cbsyst.boron_fns import *\nfrom cbsyst.helpers import ch, cp, NnotNone, calc_TF, calc_TS, calc_TB, calc_pH_scales\nfrom cbsyst.non_MyAMI_constants import *\n\n\n# Helper functions\n# ----------------\ndef calc_Ks(T, S, P, Mg, Ca, TS, TF, Ks=None):\n \"\"\"\n Helper function to calculate Ks.\n\n If Ks is a dict, those Ks are used\n transparrently (i.e. no pressure modification).\n \"\"\"\n if isinstance(Ks, dict):\n Ks = Bunch(Ks)\n else:\n if maxL(Mg, Ca) == 1:\n if Mg is None:\n Mg = 0.0528171\n if Ca is None:\n Ca = 0.0102821\n Ks = MyAMI_K_calc(TempC=T, Sal=S, P=P,\n Mg=Mg, Ca=Ca)\n else:\n # if only Ca or Mg provided, fill in other with modern\n if Mg is None:\n Mg = 0.0528171\n if Ca is None:\n Ca = 0.0102821\n # calculate Ca and Mg specific Ks\n Ks = MyAMI_K_calc_multi(TempC=T, Sal=S, P=P,\n Ca=Ca, Mg=Mg)\n\n # non-MyAMI Constants\n Ks.update(calc_KPs(T, S, P))\n Ks.update(calc_KF(T, S, P))\n Ks.update(calc_KSi(T, S, P))\n\n # pH conversions to total scale.\n # - KP1, KP2, KP3 are all on SWS\n # - KSi is on SWS\n # - MyAMI KW is on SWS... DOES THIS MATTER?\n\n SWStoTOT = (1 + TS / Ks.KSO4) / (1 + TS / Ks.KSO4 + TF / Ks.KF)\n # FREEtoTOT = 1 + 'T_' + mode]S / Ks.KSO4\n conv = ['KP1', 'KP2', 'KP3', 'KSi', 'KW']\n for c in conv:\n Ks[c] *= SWStoTOT\n\n return Ks\n\n\n# C Speciation\n# ------------\ndef Csys(pHtot=None, DIC=None, CO2=None,\n HCO3=None, CO3=None, TA=None,\n fCO2=None, pCO2=None,\n BT=None, Ca=None, Mg=None,\n T_in=25., S_in=35., P_in=None,\n T_out=None, S_out=None, P_out=None,\n TP=0., TSi=0.,\n pHsws=None, pHfree=None, pHNBS=None,\n Ks=None, pdict=None, unit='umol'):\n \"\"\"\n Calculate the carbon chemistry of seawater from a minimal parameter set.\n\n Constants calculated by MyAMI model (Hain et al, 2015; doi:10.1002/2014GB004986).\n Speciation calculations from Zeebe & Wolf-Gladrow (2001; ISBN:9780444509468) Appendix B\n\n pH is Total scale.\n\n Inputs must either be single values, arrays of equal length or a mixture of both.\n If you use arrays of unequal length, it won't work.\n\n Error propagation:\n If inputs are ufloat or uarray (from uncertainties package) errors will\n be propagated through all calculations, but:\n\n **WARNING** Error propagation NOT IMPLEMENTED for carbon system calculations\n with zero-finders (i.e. when pH is not given; cases 2-5 and 10-15).\n\n Concentration Units\n +++++++++++++++++++\n * Ca and Mg must be in molar units.\n * All other units must be the same, and can be specified in the 'unit' variable. Defaults to umolar.\n\n Parameters\n ----------\n pH, DIC, CO2, HCO3, CO3, TA : array-like\n Carbon system parameters. Two of these must be provided.\n BT : array-like\n Total B at Salinity = 35, used in Alkalinity calculations.\n Ca, Mg : arra-like\n The [Ca] and [Mg] of the seawater, in mol / kg.\n Used in calculating MyAMI constants.\n T_in, S_in : array-like\n Temperature in Celcius and Salinity in PSU that the\n measurements were conducted under.\n Used in calculating constants.\n P_in : array-like\n Pressure in Bar that the measurements were conducted under.\n Used in pressure-correcting constants.\n T_out, S_out : array-like\n Temperature in Celcius and Salinity in PSU of the desired\n output conditions.\n Used in calculating constants.\n P_in : array-like\n Pressure in Bar of the desired output conditions.\n Used in pressure-correcting constants.\n unit : str\n Concentration units of C and B parameters (all must be in\n the same units).\n Can be 'mol', 'mmol', 'umol', 'nmol', 'pmol' or 'fmol'.\n Used in calculating Alkalinity. Default is 'umol'.\n Ks : dict\n A dictionary of constants. Must contain keys\n 'K1', 'K2', 'KB' and 'KW'.\n If None, Ks are calculated using MyAMI model.\n pdict : dict\n Optionally, you can provide some or all parameters as a dict,\n with keys the same as the parameter names above. Any parameters\n included in the dict will overwrite manually specified\n parameters. This is particularly useful if you're including\n this in other code.\n\n Returns\n -------\n dict(/Bunch) containing all calculated parameters.\n \"\"\"\n\n # Bunch inputs\n ps = Bunch(locals())\n if isinstance(pdict, dict):\n ps.update(pdict)\n\n # convert unit to multiplier\n udict = {'mol': 1.,\n 'mmol': 1.e3,\n 'umol': 1.e6,\n 'nmol': 1.e9,\n 'pmol': 1.e12,\n 'fmol': 1.e15}\n if isinstance(ps.unit, str):\n ps.unit = udict[ps.unit]\n # elif isinstance(ps.unit, (int, float)):\n # ps.unit = ps.unit\n\n if ps.unit != 1:\n upar = ['DIC', 'TA', 'CO2', 'HCO3', 'CO3',\n 'BT', 'fCO2', 'pCO2', 'TP', 'TSi']\n for p in upar:\n if ps[p] is not None:\n ps[p] = np.divide(ps[p], ps.unit) # convert to molar\n\n # Conserved seawater chemistry\n if 'TS' not in ps:\n ps.TS = calc_TS(ps.S_in)\n if 'TF' not in ps:\n ps.TF = calc_TF(ps.S_in)\n if ps.BT is None:\n ps.BT = calc_TB(ps.S_in)\n # elif isinstance(BT, (int, float)):\n # ps.BT = ps.BT * ps.S_in / 35.\n\n # Calculate Ks at input conditions\n ps.Ks = calc_Ks(ps.T_in, ps.S_in, ps.P_in,\n ps.Mg, ps.Ca, ps.TS, ps.TF, ps.Ks)\n\n # Calculate pH scales at input conditions (does nothing if no pH given)\n ps.update(calc_pH_scales(ps.pHtot, ps.pHfree, ps.pHsws, ps.pHNBS,\n ps.TS, ps.TF, ps.T_in + 273.15, ps.S_in, ps.Ks))\n\n # calculate C system at input conditions\n ps.update(calc_C_species(pHtot=ps.pHtot, DIC=ps.DIC, CO2=ps.CO2,\n HCO3=ps.HCO3, CO3=ps.CO3, TA=ps.TA,\n fCO2=ps.fCO2, pCO2=ps.pCO2,\n T_in=ps.T_in, BT=ps.BT, TP=ps.TP, TSi=ps.TSi,\n TS=ps.TS, TF=ps.TF, Ks=ps.Ks))\n\n # clean up output\n for k in ['BT', 'CO2', 'CO3', 'Ca', 'DIC', 'H',\n 'HCO3', 'Mg', 'S_in', 'T_in', 'TA',\n 'CAlk', 'PAlk', 'SiAlk', 'OH']:\n if not isinstance(ps[k], np.ndarray):\n # convert all outputs to (min) 1D numpy arrays.\n ps[k] = np.array(ps[k], ndmin=1)\n if ps.unit != 1:\n for p in upar + ['CAlk', 'BAlk', 'PAlk', 'SiAlk',\n 'OH', 'HSO4', 'HF', 'Hfree']:\n ps[p] *= ps.unit # convert back to input units\n\n # Calculate Output Conditions\n # ===========================\n if ps.T_out is not None or ps.S_out is not None or ps.P_out is not None:\n if ps.T_out is None:\n ps.T_out = ps.T_in\n if ps.S_out is None:\n ps.S_out = ps.S_in\n if ps.P_out is None:\n ps.P_out = ps.P_in\n # assumes conserved alkalinity and DIC\n out_cond = Csys(TA=ps.TA, DIC=ps.DIC, \n T_in=ps.T_out,\n S_in=ps.S_out,\n P_in=ps.P_out,\n unit=ps.unit)\n # Calculate pH scales at output conditions (does nothing if no pH given)\n out_cond.update(calc_pH_scales(out_cond.pHtot, out_cond.pHfree, out_cond.pHsws, out_cond.pHNBS,\n out_cond.TS, out_cond.TF, out_cond.T_in + 273.15, out_cond.S_in, out_cond.Ks))\n\n # rename parameters in output conditions\n outputs = ['BAlk', 'BT', 'CAlk', 'CO2', 'CO3',\n 'DIC', 'H', 'HCO3', 'HF',\n 'HSO4', 'Hfree', 'Ks', 'OH',\n 'PAlk', 'SiAlk', 'TA', 'TF', 'TP',\n 'TS', 'TSi', 'fCO2', 'pCO2',\n 'pHfree', 'pHsws', 'pHtot', 'pHNBS']\n\n ps.update({k + '_out': out_cond[k] for k in outputs})\n\n # remove some superfluous outputs\n rem = ['pdict']\n for r in rem:\n if r in ps:\n del ps[r]\n\n return ps\n\n\n# B Speciation\n# ------------\ndef Bsys(pHtot=None, BT=None, BO3=None, BO4=None,\n ABT=None, ABO3=None, ABO4=None,\n dBT=None, dBO3=None, dBO4=None,\n alphaB=None,\n T_in=25., S_in=35., P_in=None,\n T_out=None, S_out=None, P_out=None,\n Ca=None, Mg=None,\n pHsws=None, pHfree=None, pHNBS=None,\n Ks=None, pdict=None):\n \"\"\"\n Calculate the boron chemistry of seawater from a minimal parameter set.\n\n Constants calculated by MyAMI model (Hain et al, 2015; doi:10.1002/2014GB004986).\n Speciation calculations from Zeebe & Wolf-Gladrow (2001; ISBN:9780444509468).\n\n pH is Total scale.\n\n Inputs must either be single values, arrays of equal length or a mixture of both.\n If you use arrays of unequal length, it won't work.\n\n Error propagation:\n If inputs are ufloat or uarray (from uncertainties package) errors will\n be propagated through all calculations.\n\n Concentration Units\n +++++++++++++++++++\n * All concentrations must be in the same units. Returned in the same units as inputs.\n\n Parameters\n ----------\n pH, BT, BO3, BO4 : array-like\n Boron system parameters. Two of these must be provided.\n T, S : array-like\n Temperature in Celcius and Salinity in PSU.\n Used in calculating MyAMI constants.\n P : array-like\n Pressure in Bar.\n Used in calculating MyAMI constants.\n Ca, Mg : arra-like\n The [Ca] and [Mg] of the seawater, in mol / kg.\n Used in calculating MyAMI constants.\n Ks : dict\n A dictionary of constants. Must contain keys\n 'K1', 'K2', 'KB' and 'KW'.\n If None, Ks are calculated using MyAMI model.\n pdict : dict\n Optionally, you can provide some or all parameters as a dict,\n with keys the same as the parameter names above. Any parameters\n included in the dict will overwrite manually specified\n parameters. This is particularly useful if you're including\n this in other code.\n\n Returns\n -------\n dict(/Bunch) containing all calculated parameters.\n \"\"\"\n\n # Bunch inputs\n ps = Bunch(locals())\n if isinstance(pdict, dict):\n ps.update(pdict)\n\n # Conserved seawater chemistry\n if 'TS' not in ps:\n ps.TS = calc_TS(ps.S_in)\n if 'TF' not in ps:\n ps.TF = calc_TF(ps.S_in)\n\n # Calculate Ks\n ps.Ks = calc_Ks(ps.T_in, ps.S_in, ps.P_in,\n ps.Mg, ps.Ca, ps.TS, ps.TF, ps.Ks)\n\n # Calculate pH scales (does nothing if none pH given)\n ps.update(calc_pH_scales(ps.pHtot, ps.pHfree, ps.pHsws, ps.pHNBS,\n ps.TS, ps.TF, ps.T_in + 273.15, ps.S_in, ps.Ks))\n\n ps.update(calc_B_species(pHtot=ps.pHtot, BT=ps.BT, BO3=ps.BO3, BO4=ps.BO4, Ks=ps.Ks))\n\n # If pH not calced yet, calculate on all scales\n if ps.pHtot is None:\n ps.pHtot = np.array(cp(ps.H), ndmin=1)\n # Calculate other pH scales\n ps.update(calc_pH_scales(ps.pHtot, ps.pHfree, ps.pHsws, ps.pHNBS,\n ps.TS, ps.TF, ps.T_in + 273.15, ps.S_in, ps.Ks))\n\n # If any isotope parameter specified, calculate the isotope systen.\n if NnotNone(ps.ABT, ps.ABO3, ps.ABO4, ps.dBT, ps.dBO3, ps.dBO4) != 0:\n ps.update(ABsys(pdict=ps))\n\n for k in ['BT', 'H', 'BO3', 'BO4',\n 'Ca', 'Mg', 'S_in', 'T_in']:\n # convert all outputs to (min) 1D numpy arrays.\n if not isinstance(ps[k], np.ndarray):\n # convert all outputs to (min) 1D numpy arrays.\n ps[k] = np.array(ps[k], ndmin=1)\n\n # remove some superfluous outputs\n rem = ['pdict']\n for r in rem:\n if r in ps:\n del ps[r]\n\n return ps\n\n\n# B Isotopes\n# ----------\ndef ABsys(pHtot=None,\n ABT=None, ABO3=None, ABO4=None,\n dBT=None, dBO3=None, dBO4=None,\n alphaB=None,\n T_in=25., S_in=35., P_in=None,\n Ca=None, Mg=None,\n pHsws=None, pHfree=None, pHNBS=None,\n Ks=None, pdict=None):\n \"\"\"\n Calculate the boron isotope chemistry of seawater from a minimal parameter set.\n\n Constants calculated by MyAMI model (Hain et al, 2015; doi:10.1002/2014GB004986).\n Speciation calculations from Zeebe & Wolf-Gladrow (2001; ISBN:9780444509468).\n\n pH is Total scale.\n\n Inputs must either be single values, arrays of equal length or a mixture of both.\n If you use arrays of unequal length, it won't work.\n\n Error propagation:\n If inputs are ufloat or uarray (from uncertainties package) errors will\n be propagated through all calculations.\n\n Concentration Units\n +++++++++++++++++++\n * 'A' is fractional abundance (11B / BT)\n * 'd' are delta values\n Either specified, both returned.\n\n Parameters\n ----------\n pH, ABT, ABO3, ABO4, dBT, dBO3, dBO4 : array-like\n Boron isotope system parameters. pH and one other\n parameter must be provided.\n alphaB : array-like\n Alpha value describing B fractionation (1.0XXX).\n If missing, it's calculated using the temperature\n sensitive formulation of Honisch et al (2008)\n T, S : array-like\n Temperature in Celcius and Salinity in PSU.\n Used in calculating MyAMI constants.\n P : array-like\n Pressure in Bar.\n Used in calculating MyAMI constants.\n Ca, Mg : arra-like\n The [Ca] and [Mg] of the seawater, in mol / kg.\n Used in calculating MyAMI constants.\n Ks : dict\n A dictionary of constants. Must contain keys\n 'K1', 'K2', 'KB' and 'KW'.\n If None, Ks are calculated using MyAMI model.\n pdict : dict\n Optionally, you can provide some or all parameters as a dict,\n with keys the same as the parameter names above. Any parameters\n included in the dict will overwrite manually specified\n parameters. This is particularly useful if you're including\n this in other code.\n\n Returns\n -------\n dict(/Bunch) containing all calculated parameters.\n \"\"\"\n\n # Bunch inputs\n ps = Bunch(locals())\n if isinstance(pdict, dict):\n ps.update(pdict)\n\n # Conserved seawater chemistry\n if 'TS' not in ps:\n ps.TS = calc_TS(ps.S_in)\n if 'TF' not in ps:\n ps.TF = calc_TF(ps.S_in)\n\n # Calculate Ks\n ps.Ks = calc_Ks(ps.T_in, ps.S_in, ps.P_in,\n ps.Mg, ps.Ca, ps.TS, ps.TF, ps.Ks)\n\n # Calculate pH scales (does nothing if none pH given)\n ps.update(calc_pH_scales(ps.pHtot, ps.pHfree, ps.pHsws, ps.pHNBS,\n ps.TS, ps.TF, ps.T_in + 273.15, ps.S_in, ps.Ks))\n\n # if deltas provided, calculate corresponding As\n if ps.dBT is not None:\n ps.ABT = d11_2_A11(ps.dBT)\n if ps.dBO3 is not None:\n ps.ABO3 = d11_2_A11(ps.dBO3)\n if ps.dBO4 is not None:\n ps.ABO4 = d11_2_A11(ps.dBO4)\n\n # calculate alpha\n ps.alphaB = alphaB_calc(ps.T)\n\n if ps.pHtot is not None and ps.ABT is not None:\n ps.H = ch(ps.pHtot)\n elif ps.pHtot is not None and ps.ABO3 is not None:\n ps.ABT = pH_ABO3(ps.pHtot, ps.ABO3, ps.Ks, ps.alphaB)\n elif ps.pHtot is not None and ps.ABO4 is not None:\n ps.ABT = pH_ABO3(ps.pHtot, ps.ABO4, ps.Ks, ps.alphaB)\n else:\n raise ValueError('pH must be determined to calculate isotopes.')\n\n if ps.ABO3 is None:\n ps.ABO3 = cABO3(ps.H, ps.ABT, ps.Ks, ps.alphaB)\n if ps.ABO4 is None:\n ps.ABO4 = cABO4(ps.H, ps.ABT, ps.Ks, ps.alphaB)\n\n if ps.dBT is None:\n ps.dBT = A11_2_d11(ps.ABT)\n if ps.dBO3 is None:\n ps.dBO3 = A11_2_d11(ps.ABO3)\n if ps.dBO4 is None:\n ps.dBO4 = A11_2_d11(ps.ABO4)\n\n for k in ['ABO3', 'ABO4', 'ABT', 'Ca',\n 'H', 'Mg', 'S', 'T', 'alphaB',\n 'dBO3', 'dBO4', 'dBT', 'pHtot']:\n if not isinstance(ps[k], np.ndarray):\n # convert all outputs to (min) 1D numpy arrays.\n ps[k] = np.array(ps[k], ndmin=1)\n\n # remove some superfluous outputs\n rem = ['pdict']\n for r in rem:\n if r in ps:\n del ps[r]\n\n return ps\n\n\n# Whole C-B-Isotope System\n# ------------------------\ndef CBsys(pHtot=None, DIC=None, CO2=None, HCO3=None, CO3=None, TA=None, fCO2=None, pCO2=None,\n BT=None, BO3=None, BO4=None,\n ABT=None, ABO3=None, ABO4=None, dBT=None, dBO3=None, dBO4=None,\n alphaB=None,\n T_in=25., S_in=35., P_in=None,\n T_out=None, S_out=None, P_out=None,\n Ca=None, Mg=None, TP=0., TSi=0.,\n pHsws=None, pHfree=None, pHNBS=None,\n Ks=None, pdict=None, unit='umol'):\n \"\"\"\n Calculate carbon, boron and boron isotope chemistry of seawater from a minimal parameter set.\n\n Constants calculated by MyAMI model (Hain et al, 2015; doi:10.1002/2014GB004986).\n Speciation calculations from Zeebe & Wolf-Gladrow (2001; ISBN:9780444509468) Appendix B\n\n pH is Total scale.\n\n Inputs must either be single values, arrays of equal length or a mixture of both.\n If you use arrays of unequal length, it won't work.\n\n Note: Special Case! If pH is not known, you must provide either:\n - Two of [DIC, CO2, HCO3, CO3], and one of [BT, BO3, BO4]\n - One of [DIC, CO2, HCO3, CO3], and TA and BT\n - Two of [BT, BO3, BO4] and one of [DIC, CO2, HCO3, CO3]\n\n Isotopes will only be calculated if one of [ABT, ABO3, ABO4, dBT, dBO3, dBO4]\n is provided.\n\n Error propagation:\n If inputs are ufloat or uarray (from uncertainties package) errors will\n be propagated through all calculations, but:\n\n **WARNING** Error propagation NOT IMPLEMENTED for carbon system calculations\n with zero-finders (i.e. when pH is not given; cases 2-5 and 10-15).\n\n Concentration Units\n +++++++++++++++++++\n * Ca and Mg must be in molar units.\n * All other units must be the same, and can be specified in the 'unit' variable. Defaults to umolar.\n * Isotopes can be in A (11B / BT) or d (delta). Either specified, both returned.\n\n Parameters\n ----------\n pH, DIC, CO2, HCO3, CO3, TA : array-like\n Carbon system parameters. Two of these must be provided.\n If TA is specified, a B species must also be specified.\n pH, BT, BO3, BO4 : array-like\n Boron system parameters. Two of these must be provided.\n pH, ABT, ABO3, ABO4, dBT, dBO3, dBO4 : array-like\n Boron isotope system parameters. pH and one other\n parameter must be provided.\n alphaB : array-like\n Alpha value describing B fractionation (1.0XXX).\n If missing, it's calculated using the temperature\n sensitive formulation of Honisch et al (2008)\n T, S : array-like\n Temperature in Celcius and Salinity in PSU.\n Used in calculating MyAMI constants.\n P : array-like\n Pressure in Bar.\n Used in calculating MyAMI constants.\n unit : str\n Concentration units of C and B parameters (all must be in\n the same units).\n Can be 'mol', 'mmol', 'umol', 'nmol', 'pmol' or 'fmol'.\n Used in calculating Alkalinity. Default is 'umol'.\n Ca, Mg : arra-like\n The [Ca] and [Mg] of the seawater, * in mol / kg *.\n Used in calculating MyAMI constants.\n Ks : dict\n A dictionary of constants. Must contain keys\n 'K1', 'K2', 'KB' and 'KW'.\n If None, Ks are calculated using MyAMI model.\n pdict : dict\n Optionally, you can provide some or all parameters as a dict,\n with keys the same as the parameter names above. Any parameters\n included in the dict will overwrite manually specified\n parameters. This is particularly useful if you're including\n this in other code.\n\n Returns\n -------\n dict(/Bunch) containing all calculated parameters.\n \"\"\"\n # Bunch inputs\n ps = Bunch(locals())\n if isinstance(pdict, dict):\n ps.update(pdict)\n\n # convert unit to multiplier\n udict = {'mol': 1.,\n 'mmol': 1.e3,\n 'umol': 1.e6,\n 'nmol': 1.e9,\n 'pmol': 1.e12,\n 'fmol': 1.e15}\n if isinstance(ps.unit, str):\n ps.unit = udict[ps.unit]\n elif isinstance(ps.unit, (int, float)):\n ps.unit = unit\n\n upar = ['DIC', 'CO2', 'HCO3', 'CO3', 'TA', 'fCO2', 'pCO2',\n 'BT', 'BO3', 'BO4', 'TP', 'TSi']\n for p in upar:\n if ps[p] is not None:\n ps[p] = np.divide(ps[p], ps.unit) # convert to molar\n\n # reassign unit, convert back at end\n orig_unit = ps.unit\n ps.unit = 1.\n\n # Conserved seawater chemistry\n if 'TS' not in ps:\n ps.TS = calc_TS(ps.S_in)\n if 'TF' not in ps:\n ps.TF = calc_TF(ps.S_in)\n\n # Calculate Ks\n ps.Ks = calc_Ks(ps.T_in, ps.S_in, ps.P_in,\n ps.Mg, ps.Ca, ps.TS, ps.TF, ps.Ks)\n\n # Calculate pH scales (does nothing if none pH given)\n ps.update(calc_pH_scales(ps.pHtot, ps.pHfree, ps.pHsws, ps.pHNBS,\n ps.TS, ps.TF, ps.T_in + 273.15, ps.S_in, ps.Ks))\n\n # if fCO2 is given but CO2 is not, calculate CO2\n if ps.CO2 is None:\n if ps.fCO2 is not None:\n ps.CO2 = fCO2_to_CO2(ps.fCO2, ps.Ks)\n elif ps.pCO2 is not None:\n ps.CO2 = fCO2_to_CO2(pCO2_to_fCO2(ps.pCO2, ps.T_in), ps.Ks)\n\n # if no B info provided, assume modern conc.\n nBspec = NnotNone(ps.BT, ps.BO3, ps.BO4)\n if nBspec == 0:\n ps.BT = calc_TB(ps.S_in)\n elif isinstance(BT, (int, float)):\n ps.BT = ps.BT * ps.S_in / 35.\n # count number of not None C parameters\n nCspec = NnotNone(ps.DIC, ps.CO2, ps.HCO3, ps.CO3) # used below\n\n # if pH is given, it's easy\n if ps.pHtot is not None or nBspec == 2:\n ps.update(calc_B_species(pHtot=ps.pHtot, BT=ps.BT, BO3=ps.BO3, BO4=ps.BO4, Ks=ps.Ks))\n ps.update(calc_C_species(pHtot=ps.pHtot, DIC=ps.DIC, CO2=ps.CO2,\n HCO3=ps.HCO3, CO3=ps.CO3, TA=ps.TA,\n fCO2=ps.fCO2, pCO2=ps.pCO2,\n T_in=ps.T_in, BT=ps.BT, TP=ps.TP, TSi=ps.TSi,\n TS=ps.TS, TF=ps.TF, Ks=ps.Ks))\n # if not, this section works out the order that things should be calculated in.\n # Special case: if pH is missing, must have:\n # a) two C or one C and both TA and BT\n # b) two B (above)\n # c) one pH-dependent B, one pH-dependent C... But that's cray...\n # (c not implemented!)\n elif ((nCspec == 2) | ((nCspec == 1) & (NnotNone(ps.TA, ps.BT) == 2))): # case A\n ps.update(calc_C_species(pHtot=ps.pHtot, DIC=ps.DIC, CO2=ps.CO2,\n HCO3=ps.HCO3, CO3=ps.CO3, TA=ps.TA,\n fCO2=ps.fCO2, pCO2=ps.pCO2,\n T_in=ps.T_in, BT=ps.BT, TP=ps.TP, TSi=ps.TSi,\n TS=ps.TS, TF=ps.TF, Ks=ps.Ks))\n ps.update(calc_B_species(pHtot=ps.pHtot, BT=ps.BT, BO3=ps.BO3, BO4=ps.BO4, Ks=ps.Ks))\n # elif nBspec == 2: # case B -- moved up\n # ps.update(calc_B_species(pHtot=ps.pHtot, BT=ps.BT, BO3=ps.BO3, BO4=ps.BO4, Ks=ps.Ks))\n # ps.update(calc_C_species(pHtot=ps.pHtot, DIC=ps.DIC, CO2=ps.CO2,\n # HCO3=ps.HCO3, CO3=ps.CO3, TA=ps.TA,\n # fCO2=ps.fCO2, pCO2=ps.pCO2,\n # T_in=ps.T_in, BT=ps.BT, TP=ps.TP, TSi=ps.TSi,\n # TS=ps.TS, TF=ps.TF, Ks=ps.Ks)) # then C\n else: # if neither condition is met, throw an error\n raise ValueError((\"Impossible! You haven't provided enough parameters.\\n\" +\n \"If you don't know pH, you must provide either:\\n\" +\n \" - Two of [DIC, CO2, HCO3, CO3], and one of [BT, BO3, BO4]\\n\" +\n \" - One of [DIC, CO2, HCO3, CO3], and TA and BT\\n\" +\n \" - Two of [BT, BO3, BO4] and one of [DIC, CO2, HCO3, CO3]\"))\n\n for p in upar + ['CAlk', 'BAlk', 'PAlk', 'SiAlk', 'OH', 'HSO4', 'HF', 'Hfree']:\n ps[p] *= orig_unit # convert back to input units\n\n # Recursive approach to calculate output params.\n # if output conditions specified, calculate outputs.\n if ps.T_out is not None or ps.S_out is not None or ps.P_out is not None:\n if ps.T_out is None:\n ps.T_out = ps.T_in\n if ps.S_out is None:\n ps.S_out = ps.S_in\n if ps.P_out is None:\n ps.P_out = ps.P_in\n # assumes conserved alkalinity\n out_cond = CBsys(TA=ps.TA, DIC=ps.DIC, BT=ps.BT, T_in=ps.T_out,\n S_in=ps.S_out, P_in=ps.P_out, unit=ps.unit)\n # Calculate pH scales (does nothing if no pH given)\n out_cond.update(calc_pH_scales(out_cond.pHtot, out_cond.pHfree, out_cond.pHsws, out_cond.pHNBS,\n out_cond.TS, out_cond.TF, out_cond.T_in + 273.15, out_cond.S_in, out_cond.Ks))\n # rename parameters in output conditions\n outputs = ['BAlk', 'BT', 'CAlk', 'CO2', 'CO3',\n 'DIC', 'H', 'HCO3', 'HF',\n 'HSO4', 'Hfree', 'Ks', 'OH',\n 'PAlk', 'SiAlk', 'TA', 'TF', 'TP',\n 'TS', 'TSi', 'fCO2', 'pCO2',\n 'pHfree', 'pHsws', 'pHtot', 'pHNBS', 'BO3', 'BO4',\n 'ABO3', 'ABO4', 'dBO3', 'dBO4']\n\n ps.update({k + '_out': out_cond[k] for k in outputs})\n\n # remove some superfluous outputs\n rem = ['pdict', 'unit']\n for r in rem:\n if r in ps:\n del ps[r]\n return ps\n"
] | [
[
"numpy.array",
"numpy.divide"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
CUAI/Non-Homophily-Benchmarks | [
"af14a88470d30b1dadd3803d911dfc1064bcf172"
] | [
"dataset.py"
] | [
"from collections import defaultdict\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport scipy\nimport scipy.io\nfrom sklearn.preprocessing import label_binarize\nfrom ogb.nodeproppred import NodePropPredDataset\n\nfrom load_data import load_twitch, load_fb100, DATAPATH\nfrom data_utils import rand_train_test_idx, even_quantile_labels, to_sparse_tensor, dataset_drive_url\n\nfrom torch_geometric.datasets import Planetoid\nfrom torch_geometric.transforms import NormalizeFeatures\nfrom os import path\n\nfrom torch_sparse import SparseTensor\nfrom google_drive_downloader import GoogleDriveDownloader as gdd\n\n\n\nclass NCDataset(object):\n def __init__(self, name, root=f'{DATAPATH}'):\n \"\"\"\n based off of ogb NodePropPredDataset\n https://github.com/snap-stanford/ogb/blob/master/ogb/nodeproppred/dataset.py\n Gives torch tensors instead of numpy arrays\n - name (str): name of the dataset\n - root (str): root directory to store the dataset folder\n - meta_dict: dictionary that stores all the meta-information about data. Default is None, \n but when something is passed, it uses its information. Useful for debugging for external contributers.\n \n Usage after construction: \n \n split_idx = dataset.get_idx_split()\n train_idx, valid_idx, test_idx = split_idx[\"train\"], split_idx[\"valid\"], split_idx[\"test\"]\n graph, label = dataset[0]\n \n Where the graph is a dictionary of the following form: \n dataset.graph = {'edge_index': edge_index,\n 'edge_feat': None,\n 'node_feat': node_feat,\n 'num_nodes': num_nodes}\n For additional documentation, see OGB Library-Agnostic Loader https://ogb.stanford.edu/docs/nodeprop/\n \n \"\"\"\n\n self.name = name # original name, e.g., ogbn-proteins\n self.graph = {}\n self.label = None\n\n def get_idx_split(self, split_type='random', train_prop=.5, valid_prop=.25):\n \"\"\"\n train_prop: The proportion of dataset for train split. Between 0 and 1.\n valid_prop: The proportion of dataset for validation split. Between 0 and 1.\n \"\"\"\n \n if split_type == 'random':\n ignore_negative = False if self.name == 'ogbn-proteins' else True\n train_idx, valid_idx, test_idx = rand_train_test_idx(\n self.label, train_prop=train_prop, valid_prop=valid_prop, ignore_negative=ignore_negative)\n split_idx = {'train': train_idx,\n 'valid': valid_idx,\n 'test': test_idx}\n return split_idx\n\n def __getitem__(self, idx):\n assert idx == 0, 'This dataset has only one graph'\n return self.graph, self.label\n\n def __len__(self):\n return 1\n\n def __repr__(self): \n return '{}({})'.format(self.__class__.__name__, len(self))\n\n\ndef load_nc_dataset(dataname, sub_dataname=''):\n \"\"\" Loader for NCDataset \n Returns NCDataset \n \"\"\"\n if dataname == 'twitch-e':\n # twitch-explicit graph\n if sub_dataname not in ('DE', 'ENGB', 'ES', 'FR', 'PTBR', 'RU', 'TW'):\n print('Invalid sub_dataname, deferring to DE graph')\n sub_dataname = 'DE'\n dataset = load_twitch_dataset(sub_dataname)\n elif dataname == 'fb100':\n if sub_dataname not in ('Penn94', 'Amherst41', 'Cornell5', 'Johns Hopkins55', 'Reed98'):\n print('Invalid sub_dataname, deferring to Penn94 graph')\n sub_dataname = 'Penn94'\n dataset = load_fb100_dataset(sub_dataname)\n elif dataname == 'ogbn-proteins':\n dataset = load_proteins_dataset()\n elif dataname == 'deezer-europe':\n dataset = load_deezer_dataset()\n elif dataname == 'arxiv-year':\n dataset = load_arxiv_year_dataset()\n elif dataname == 'pokec':\n dataset = load_pokec_mat()\n elif dataname == 'snap-patents':\n dataset = load_snap_patents_mat()\n elif dataname == 'yelp-chi':\n dataset = load_yelpchi_dataset()\n elif dataname in ('ogbn-arxiv', 'ogbn-products'):\n dataset = load_ogb_dataset(dataname)\n elif dataname in ('Cora', 'CiteSeer', 'PubMed'):\n dataset = load_planetoid_dataset(dataname)\n elif dataname in ('chameleon', 'cornell', 'film', 'squirrel', 'texas', 'wisconsin'):\n dataset = load_geom_gcn_dataset(dataname)\n else:\n raise ValueError('Invalid dataname')\n return dataset\n\n\ndef load_twitch_dataset(lang):\n assert lang in ('DE', 'ENGB', 'ES', 'FR', 'PTBR', 'RU', 'TW'), 'Invalid dataset'\n A, label, features = load_twitch(lang)\n dataset = NCDataset(lang)\n edge_index = torch.tensor(A.nonzero(), dtype=torch.long)\n node_feat = torch.tensor(features, dtype=torch.float)\n num_nodes = node_feat.shape[0]\n dataset.graph = {'edge_index': edge_index,\n 'edge_feat': None,\n 'node_feat': node_feat,\n 'num_nodes': num_nodes}\n dataset.label = torch.tensor(label)\n return dataset\n\n\ndef load_fb100_dataset(filename):\n A, metadata = load_fb100(filename)\n dataset = NCDataset(filename)\n edge_index = torch.tensor(A.nonzero(), dtype=torch.long)\n metadata = metadata.astype(np.int)\n label = metadata[:, 1] - 1 # gender label, -1 means unlabeled\n\n # make features into one-hot encodings\n feature_vals = np.hstack(\n (np.expand_dims(metadata[:, 0], 1), metadata[:, 2:]))\n features = np.empty((A.shape[0], 0))\n for col in range(feature_vals.shape[1]):\n feat_col = feature_vals[:, col]\n feat_onehot = label_binarize(feat_col, classes=np.unique(feat_col))\n features = np.hstack((features, feat_onehot))\n\n node_feat = torch.tensor(features, dtype=torch.float)\n num_nodes = metadata.shape[0]\n dataset.graph = {'edge_index': edge_index,\n 'edge_feat': None,\n 'node_feat': node_feat,\n 'num_nodes': num_nodes}\n dataset.label = torch.tensor(label)\n return dataset\n\ndef load_deezer_dataset():\n \n filename = 'deezer-europe'\n dataset = NCDataset(filename)\n deezer = scipy.io.loadmat(f'{DATAPATH}deezer-europe.mat')\n\n A, label, features = deezer['A'], deezer['label'], deezer['features']\n edge_index = torch.tensor(A.nonzero(), dtype=torch.long)\n node_feat = torch.tensor(features.todense(), dtype=torch.float)\n label = torch.tensor(label, dtype=torch.long).squeeze()\n num_nodes = label.shape[0]\n\n dataset.graph = {'edge_index': edge_index,\n 'edge_feat': None,\n 'node_feat': node_feat,\n 'num_nodes': num_nodes}\n dataset.label = label\n return dataset\n\n\ndef load_arxiv_year_dataset(nclass=5):\n filename = 'arxiv-year'\n dataset = NCDataset(filename)\n ogb_dataset = NodePropPredDataset(name='ogbn-arxiv')\n dataset.graph = ogb_dataset.graph\n dataset.graph['edge_index'] = torch.as_tensor(dataset.graph['edge_index'])\n dataset.graph['node_feat'] = torch.as_tensor(dataset.graph['node_feat'])\n\n label = even_quantile_labels(\n dataset.graph['node_year'].flatten(), nclass, verbose=False)\n dataset.label = torch.as_tensor(label).reshape(-1, 1)\n return dataset\n\n\ndef load_proteins_dataset():\n ogb_dataset = NodePropPredDataset(name='ogbn-proteins')\n dataset = NCDataset('ogbn-proteins')\n def protein_orig_split(**kwargs):\n split_idx = ogb_dataset.get_idx_split()\n return {'train': torch.as_tensor(split_idx['train']),\n 'valid': torch.as_tensor(split_idx['valid']),\n 'test': torch.as_tensor(split_idx['test'])}\n dataset.get_idx_split = protein_orig_split\n dataset.graph, dataset.label = ogb_dataset.graph, ogb_dataset.labels\n \n dataset.graph['edge_index'] = torch.as_tensor(dataset.graph['edge_index'])\n dataset.graph['edge_feat'] = torch.as_tensor(dataset.graph['edge_feat'])\n dataset.label = torch.as_tensor(dataset.label)\n return dataset\n\n\ndef load_ogb_dataset(name):\n dataset = NCDataset(name)\n ogb_dataset = NodePropPredDataset(name=name)\n dataset.graph = ogb_dataset.graph\n dataset.graph['edge_index'] = torch.as_tensor(dataset.graph['edge_index'])\n dataset.graph['node_feat'] = torch.as_tensor(dataset.graph['node_feat'])\n\n def ogb_idx_to_tensor():\n split_idx = ogb_dataset.get_idx_split()\n tensor_split_idx = {key: torch.as_tensor(\n split_idx[key]) for key in split_idx}\n return tensor_split_idx\n dataset.get_idx_split = ogb_idx_to_tensor # ogb_dataset.get_idx_split\n dataset.label = torch.as_tensor(ogb_dataset.labels).reshape(-1, 1)\n return dataset\n\n\ndef load_pokec_mat():\n \"\"\" requires pokec.mat \"\"\"\n if not path.exists(f'{DATAPATH}pokec.mat'):\n gdd.download_file_from_google_drive(\n file_id= dataset_drive_url['pokec'], \\\n dest_path=f'{DATAPATH}pokec.mat', showsize=True) \n\n fulldata = scipy.io.loadmat(f'{DATAPATH}pokec.mat')\n\n dataset = NCDataset('pokec')\n edge_index = torch.tensor(fulldata['edge_index'], dtype=torch.long)\n node_feat = torch.tensor(fulldata['node_feat']).float()\n num_nodes = int(fulldata['num_nodes'])\n dataset.graph = {'edge_index': edge_index,\n 'edge_feat': None,\n 'node_feat': node_feat,\n 'num_nodes': num_nodes}\n\n label = fulldata['label'].flatten()\n dataset.label = torch.tensor(label, dtype=torch.long)\n\n return dataset\n\n\ndef load_snap_patents_mat(nclass=5):\n if not path.exists(f'{DATAPATH}snap_patents.mat'):\n p = dataset_drive_url['snap-patents']\n print(f\"Snap patents url: {p}\")\n gdd.download_file_from_google_drive(\n file_id= dataset_drive_url['snap-patents'], \\\n dest_path=f'{DATAPATH}snap_patents.mat', showsize=True) \n\n fulldata = scipy.io.loadmat(f'{DATAPATH}snap_patents.mat')\n\n dataset = NCDataset('snap_patents')\n edge_index = torch.tensor(fulldata['edge_index'], dtype=torch.long)\n node_feat = torch.tensor(\n fulldata['node_feat'].todense(), dtype=torch.float)\n num_nodes = int(fulldata['num_nodes'])\n dataset.graph = {'edge_index': edge_index,\n 'edge_feat': None,\n 'node_feat': node_feat,\n 'num_nodes': num_nodes}\n\n years = fulldata['years'].flatten()\n label = even_quantile_labels(years, nclass, verbose=False)\n dataset.label = torch.tensor(label, dtype=torch.long)\n\n return dataset\n\n\ndef load_yelpchi_dataset():\n if not path.exists(f'{DATAPATH}YelpChi.mat'):\n gdd.download_file_from_google_drive(\n file_id= dataset_drive_url['yelp-chi'], \\\n dest_path=f'{DATAPATH}YelpChi.mat', showsize=True) \n fulldata = scipy.io.loadmat(f'{DATAPATH}YelpChi.mat')\n A = fulldata['homo']\n edge_index = np.array(A.nonzero())\n node_feat = fulldata['features']\n label = np.array(fulldata['label'], dtype=np.int).flatten()\n num_nodes = node_feat.shape[0]\n\n dataset = NCDataset('YelpChi')\n edge_index = torch.tensor(edge_index, dtype=torch.long)\n node_feat = torch.tensor(node_feat.todense(), dtype=torch.float)\n dataset.graph = {'edge_index': edge_index,\n 'node_feat': node_feat,\n 'edge_feat': None,\n 'num_nodes': num_nodes}\n label = torch.tensor(label, dtype=torch.long)\n dataset.label = label\n return dataset\n\n\ndef load_planetoid_dataset(name):\n torch_dataset = Planetoid(root=f'{DATAPATH}/Planetoid',\n name=name)\n data = torch_dataset[0]\n\n edge_index = data.edge_index\n node_feat = data.x\n label = data.y\n num_nodes = data.num_nodes\n print(f\"Num nodes: {num_nodes}\")\n\n dataset = NCDataset(name)\n\n dataset.train_idx = torch.where(data.train_mask)[0]\n dataset.valid_idx = torch.where(data.val_mask)[0]\n dataset.test_idx = torch.where(data.test_mask)[0]\n\n dataset.graph = {'edge_index': edge_index,\n 'node_feat': node_feat,\n 'edge_feat': None,\n 'num_nodes': num_nodes}\n def planetoid_orig_split(**kwargs):\n return {'train': torch.as_tensor(dataset.train_idx),\n 'valid': torch.as_tensor(dataset.valid_idx),\n 'test': torch.as_tensor(dataset.test_idx)}\n\n dataset.get_idx_split = planetoid_orig_split\n dataset.label = label\n\n return dataset\n\ndef load_geom_gcn_dataset(name):\n fulldata = scipy.io.loadmat(f'{DATAPATH}/{name}.mat')\n edge_index = fulldata['edge_index']\n node_feat = fulldata['node_feat']\n label = np.array(fulldata['label'], dtype=np.int).flatten()\n num_nodes = node_feat.shape[0]\n\n dataset = NCDataset(name)\n edge_index = torch.tensor(edge_index, dtype=torch.long)\n node_feat = torch.tensor(node_feat, dtype=torch.float)\n dataset.graph = {'edge_index': edge_index,\n 'node_feat': node_feat,\n 'edge_feat': None,\n 'num_nodes': num_nodes}\n label = torch.tensor(label, dtype=torch.long)\n dataset.label = label\n return dataset\n\n"
] | [
[
"numpy.hstack",
"numpy.expand_dims",
"numpy.unique",
"scipy.io.loadmat",
"torch.tensor",
"torch.where",
"numpy.array",
"numpy.empty",
"torch.as_tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
sherwyn11/Sudoku-AI | [
"41166fd51337090eb1d86b3715bd57b538643a5d"
] | [
"recognition/recognition.py"
] | [
"import numpy as np\nimport cv2\n\nfrom helpers.constants import MODEL_PATH, DIGITS_PATH, DIGIT_RECOGNIZER_MODEL_NAME\nfrom helpers.helpers import preprocess_image, check_if_white\nfrom keras.models import load_model\n\n\nclass DigitRecognition:\n\n def __init__(self):\n '''\n Init function\n '''\n\n self.digits = []\n self.model = None\n\n\n def load_keras_model(self):\n '''\n Load the trained Keras model for Digit Recognition\n '''\n\n self.model = load_model(MODEL_PATH + DIGIT_RECOGNIZER_MODEL_NAME)\n\n\n def get_digits(self, cells):\n '''\n Extract the digits from each cell of the Sudoku board\n '''\n\n for img in cells:\n image = preprocess_image(img)\n does_image_contain_white = check_if_white(image)\n\n if does_image_contain_white:\n image = image.reshape((1, 28, 28, 1))\n number = self.model.predict(image)\n number = np.argmax(number)\n self.digits.append(number)\n else:\n self.digits.append(0)\n\n return self.digits"
] | [
[
"numpy.argmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
konyul/monovideo | [
"f50db55c324c2ab4a66d414b47f0558b72a3a009",
"f50db55c324c2ab4a66d414b47f0558b72a3a009",
"f50db55c324c2ab4a66d414b47f0558b72a3a009",
"f50db55c324c2ab4a66d414b47f0558b72a3a009"
] | [
"tests/test_data/test_datasets/test_lyft_dataset.py",
"mmdet3d/ops/knn/knn.py",
"mmdet3d/datasets/kitti_mono_dataset.py",
"mmdet3d/core/bbox/coders/monoflex_bbox_coder.py"
] | [
"# Copyright (c) OpenMMLab. All rights reserved.\nimport mmcv\nimport numpy as np\nimport tempfile\nimport torch\n\nfrom mmdet3d.core import limit_period\nfrom mmdet3d.datasets import LyftDataset\n\n\ndef test_getitem():\n np.random.seed(0)\n torch.manual_seed(0)\n root_path = './tests/data/lyft'\n # in coordinate system refactor, this test file is modified\n ann_file = './tests/data/lyft/lyft_infos.pkl'\n class_names = ('car', 'truck', 'bus', 'emergency_vehicle', 'other_vehicle',\n 'motorcycle', 'bicycle', 'pedestrian', 'animal')\n point_cloud_range = [-80, -80, -10, 80, 80, 10]\n pipelines = [\n dict(\n type='LoadPointsFromFile',\n coord_type='LIDAR',\n load_dim=5,\n use_dim=5,\n file_client_args=dict(backend='disk')),\n dict(\n type='LoadPointsFromMultiSweeps',\n sweeps_num=2,\n file_client_args=dict(backend='disk')),\n dict(type='LoadAnnotations3D', with_bbox_3d=True, with_label_3d=True),\n dict(\n type='GlobalRotScaleTrans',\n rot_range=[-0.523599, 0.523599],\n scale_ratio_range=[0.85, 1.15],\n translation_std=[0, 0, 0]),\n dict(type='RandomFlip3D', flip_ratio_bev_horizontal=0.5),\n dict(type='PointsRangeFilter', point_cloud_range=point_cloud_range),\n dict(type='ObjectRangeFilter', point_cloud_range=point_cloud_range),\n dict(type='PointShuffle'),\n dict(type='DefaultFormatBundle3D', class_names=class_names),\n dict(\n type='Collect3D', keys=['points', 'gt_bboxes_3d', 'gt_labels_3d'])\n ]\n lyft_dataset = LyftDataset(ann_file, pipelines, root_path)\n data = lyft_dataset[0]\n points = data['points']._data\n gt_bboxes_3d = data['gt_bboxes_3d']._data\n gt_labels_3d = data['gt_labels_3d']._data\n pts_filename = data['img_metas']._data['pts_filename']\n pcd_horizontal_flip = data['img_metas']._data['pcd_horizontal_flip']\n pcd_scale_factor = data['img_metas']._data['pcd_scale_factor']\n pcd_rotation = data['img_metas']._data['pcd_rotation']\n pcd_rotation_angle = data['img_metas']._data['pcd_rotation_angle']\n sample_idx = data['img_metas']._data['sample_idx']\n # coord sys refactor\n pcd_rotation_expected = np.array([[0.99869376, 0.05109515, 0.],\n [-0.05109515, 0.99869376, 0.],\n [0., 0., 1.]])\n assert pts_filename == \\\n 'tests/data/lyft/lidar/host-a017_lidar1_1236118886901125926.bin'\n assert pcd_horizontal_flip is True\n assert abs(pcd_scale_factor - 1.0645568099117257) < 1e-5\n assert np.allclose(pcd_rotation, pcd_rotation_expected, 1e-3)\n assert sample_idx == \\\n 'b98a05255ba2632e957884758cb31f0e6fcc8d3cd6ee76b6d0ba55b72f08fc54'\n expected_points = torch.tensor([[61.4785, -3.7393, 6.7699, 0.4001],\n [47.7904, -3.9887, 6.0926, 0.0000],\n [52.5683, -4.2178, 6.7179, 0.0000],\n [52.4867, -4.0315, 6.7057, 0.0000],\n [59.8372, -1.7366, 6.5864, 0.4001],\n [53.0842, -3.7064, 6.7811, 0.0000],\n [60.5549, -3.4978, 6.6578, 0.4001],\n [59.1695, -1.2910, 7.0296, 0.2000],\n [53.0702, -3.8868, 6.7807, 0.0000],\n [47.9579, -4.1648, 5.6219, 0.2000],\n [59.8226, -1.5522, 6.5867, 0.4001],\n [61.2858, -4.2254, 7.3089, 0.2000],\n [49.9896, -4.5202, 5.8823, 0.2000],\n [61.4597, -4.6402, 7.3340, 0.2000],\n [59.8244, -1.3499, 6.5895, 0.4001]])\n expected_gt_bboxes_3d = torch.tensor(\n [[63.2257, 17.5206, -0.6307, 2.0109, 5.1652, 1.9471, -1.5868],\n [-25.3804, 27.4598, -2.3297, 2.7412, 8.4792, 3.4343, -1.5939],\n [-15.2098, -7.0109, -2.2566, 0.7931, 0.8410, 1.7916, 1.5090]])\n expected_gt_labels = np.array([0, 4, 7])\n original_classes = lyft_dataset.CLASSES\n\n # manually go through pipeline\n expected_points[:, :3] = (\n (expected_points[:, :3] * torch.tensor([1, -1, 1]))\n @ pcd_rotation_expected @ pcd_rotation_expected) * torch.tensor(\n [1, -1, 1])\n expected_gt_bboxes_3d[:, :3] = (\n (expected_gt_bboxes_3d[:, :3] * torch.tensor([1, -1, 1]))\n @ pcd_rotation_expected @ pcd_rotation_expected) * torch.tensor(\n [1, -1, 1])\n expected_gt_bboxes_3d[:, 3:6] = expected_gt_bboxes_3d[:, [4, 3, 5]]\n expected_gt_bboxes_3d[:, 6:] = -expected_gt_bboxes_3d[:, 6:] \\\n - np.pi / 2 - pcd_rotation_angle * 2\n expected_gt_bboxes_3d[:, 6:] = limit_period(\n expected_gt_bboxes_3d[:, 6:], period=np.pi * 2)\n\n assert torch.allclose(points, expected_points, 1e-2)\n assert torch.allclose(gt_bboxes_3d.tensor, expected_gt_bboxes_3d, 1e-3)\n assert np.all(gt_labels_3d.numpy() == expected_gt_labels)\n assert original_classes == class_names\n\n lyft_dataset = LyftDataset(\n ann_file, None, root_path, classes=['car', 'pedestrian'])\n assert lyft_dataset.CLASSES != original_classes\n assert lyft_dataset.CLASSES == ['car', 'pedestrian']\n\n lyft_dataset = LyftDataset(\n ann_file, None, root_path, classes=('car', 'pedestrian'))\n assert lyft_dataset.CLASSES != original_classes\n assert lyft_dataset.CLASSES == ('car', 'pedestrian')\n\n import tempfile\n tmp_file = tempfile.NamedTemporaryFile()\n with open(tmp_file.name, 'w') as f:\n f.write('car\\npedestrian\\n')\n\n lyft_dataset = LyftDataset(\n ann_file, None, root_path, classes=tmp_file.name)\n assert lyft_dataset.CLASSES != original_classes\n assert lyft_dataset.CLASSES == ['car', 'pedestrian']\n\n\ndef test_evaluate():\n root_path = './tests/data/lyft'\n # in coordinate system refactor, this test file is modified\n ann_file = './tests/data/lyft/lyft_infos_val.pkl'\n lyft_dataset = LyftDataset(ann_file, None, root_path)\n # in coordinate system refactor, this test file is modified\n results = mmcv.load('./tests/data/lyft/sample_results.pkl')\n ap_dict = lyft_dataset.evaluate(results, 'bbox')\n car_precision = ap_dict['pts_bbox_Lyft/car_AP']\n assert car_precision == 0.6\n\n\ndef test_show():\n import mmcv\n from os import path as osp\n\n from mmdet3d.core.bbox import LiDARInstance3DBoxes\n tmp_dir = tempfile.TemporaryDirectory()\n temp_dir = tmp_dir.name\n root_path = './tests/data/lyft'\n ann_file = './tests/data/lyft/lyft_infos.pkl'\n class_names = ('car', 'truck', 'bus', 'emergency_vehicle', 'other_vehicle',\n 'motorcycle', 'bicycle', 'pedestrian', 'animal')\n eval_pipeline = [\n dict(\n type='LoadPointsFromFile',\n coord_type='LIDAR',\n load_dim=5,\n use_dim=5,\n file_client_args=dict(backend='disk')),\n dict(\n type='LoadPointsFromMultiSweeps',\n sweeps_num=10,\n file_client_args=dict(backend='disk')),\n dict(\n type='DefaultFormatBundle3D',\n class_names=class_names,\n with_label=False),\n dict(type='Collect3D', keys=['points'])\n ]\n kitti_dataset = LyftDataset(ann_file, None, root_path)\n boxes_3d = LiDARInstance3DBoxes(\n torch.tensor(\n [[46.1218, -4.6496, -0.9275, 1.4442, 0.5316, 1.7450, -2.7457],\n [33.3189, 0.1981, 0.3136, 1.2301, 0.5656, 1.7985, 3.1401],\n [46.1366, -4.6404, -0.9510, 1.6501, 0.5162, 1.7540, -2.9486],\n [33.2646, 0.2297, 0.3446, 1.3365, 0.5746, 1.7947, -3.1138],\n [58.9079, 16.6272, -1.5829, 3.9313, 1.5656, 1.4899, -3.1213]]))\n scores_3d = torch.tensor([0.1815, 0.1663, 0.5792, 0.2194, 0.2780])\n labels_3d = torch.tensor([0, 0, 1, 1, 2])\n result = dict(boxes_3d=boxes_3d, scores_3d=scores_3d, labels_3d=labels_3d)\n results = [dict(pts_bbox=result)]\n kitti_dataset.show(results, temp_dir, show=False, pipeline=eval_pipeline)\n file_name = 'host-a017_lidar1_1236118886901125926'\n pts_file_path = osp.join(temp_dir, file_name, f'{file_name}_points.obj')\n gt_file_path = osp.join(temp_dir, file_name, f'{file_name}_gt.obj')\n pred_file_path = osp.join(temp_dir, file_name, f'{file_name}_pred.obj')\n mmcv.check_file_exist(pts_file_path)\n mmcv.check_file_exist(gt_file_path)\n mmcv.check_file_exist(pred_file_path)\n tmp_dir.cleanup()\n",
"import torch\nfrom torch.autograd import Function\n\nfrom . import knn_ext\n\n\nclass KNN(Function):\n r\"\"\"KNN (CUDA) based on heap data structure.\n Modified from `PAConv <https://github.com/CVMI-Lab/PAConv/tree/main/\n scene_seg/lib/pointops/src/knnquery_heap>`_.\n\n Find k-nearest points.\n \"\"\"\n\n @staticmethod\n def forward(ctx,\n k: int,\n xyz: torch.Tensor,\n center_xyz: torch.Tensor = None,\n transposed: bool = False) -> torch.Tensor:\n \"\"\"Forward.\n\n Args:\n k (int): number of nearest neighbors.\n xyz (Tensor): (B, N, 3) if transposed == False, else (B, 3, N).\n xyz coordinates of the features.\n center_xyz (Tensor): (B, npoint, 3) if transposed == False,\n else (B, 3, npoint). centers of the knn query.\n transposed (bool): whether the input tensors are transposed.\n defaults to False. Should not explicitly use this keyword\n when calling knn (=KNN.apply), just add the fourth param.\n\n Returns:\n Tensor: (B, k, npoint) tensor with the indices of\n the features that form k-nearest neighbours.\n \"\"\"\n assert k > 0\n\n if center_xyz is None:\n center_xyz = xyz\n\n if transposed:\n xyz = xyz.transpose(2, 1).contiguous()\n center_xyz = center_xyz.transpose(2, 1).contiguous()\n\n assert xyz.is_contiguous() # [B, N, 3]\n assert center_xyz.is_contiguous() # [B, npoint, 3]\n\n center_xyz_device = center_xyz.get_device()\n assert center_xyz_device == xyz.get_device(), \\\n 'center_xyz and xyz should be put on the same device'\n if torch.cuda.current_device() != center_xyz_device:\n torch.cuda.set_device(center_xyz_device)\n\n B, npoint, _ = center_xyz.shape\n N = xyz.shape[1]\n\n idx = center_xyz.new_zeros((B, npoint, k)).int()\n dist2 = center_xyz.new_zeros((B, npoint, k)).float()\n\n knn_ext.knn_wrapper(B, N, npoint, k, xyz, center_xyz, idx, dist2)\n # idx shape to [B, k, npoint]\n idx = idx.transpose(2, 1).contiguous()\n ctx.mark_non_differentiable(idx)\n return idx\n\n @staticmethod\n def backward(ctx, a=None):\n return None, None, None\n\n\nknn = KNN.apply\n",
"# Copyright (c) OpenMMLab. All rights reserved.\nimport copy\nimport mmcv\nimport numpy as np\nimport tempfile\nimport torch\nfrom mmcv.utils import print_log\nfrom os import path as osp\n\nfrom mmdet.datasets import DATASETS\nfrom ..core.bbox import Box3DMode, CameraInstance3DBoxes, points_cam2img\nfrom .nuscenes_mono_dataset import NuScenesMonoDataset\n\n\[email protected]_module()\nclass KittiMonoDataset(NuScenesMonoDataset):\n \"\"\"Monocular 3D detection on KITTI Dataset.\n\n Args:\n data_root (str): Path of dataset root.\n info_file (str): Path of info file.\n load_interval (int, optional): Interval of loading the dataset. It is\n used to uniformly sample the dataset. Defaults to 1.\n with_velocity (bool, optional): Whether include velocity prediction\n into the experiments. Defaults to False.\n eval_version (str, optional): Configuration version of evaluation.\n Defaults to None.\n version (str, optional): Dataset version. Defaults to None.\n kwargs (dict): Other arguments are the same of NuScenesMonoDataset.\n \"\"\"\n\n CLASSES = ('Pedestrian', 'Cyclist', 'Car')\n\n def __init__(self,\n data_root,\n info_file,\n load_interval=1,\n with_velocity=False,\n eval_version=None,\n version=None,\n **kwargs):\n super().__init__(\n data_root=data_root,\n load_interval=load_interval,\n with_velocity=with_velocity,\n eval_version=eval_version,\n version=version,\n **kwargs)\n self.anno_infos = mmcv.load(info_file)\n self.bbox_code_size = 7\n\n def _parse_ann_info(self, img_info, ann_info):\n \"\"\"Parse bbox and mask annotation.\n\n Args:\n ann_info (list[dict]): Annotation info of an image.\n with_mask (bool): Whether to parse mask annotations.\n\n Returns:\n dict: A dict containing the following keys: bboxes, bboxes_ignore,\n labels, masks, seg_map. \"masks\" are raw annotations and not\n decoded into binary masks.\n \"\"\"\n gt_bboxes = []\n gt_labels = []\n gt_bboxes_ignore = []\n gt_masks_ann = []\n gt_bboxes_cam3d = []\n centers2d = []\n depths = []\n for i, ann in enumerate(ann_info):\n if ann.get('ignore', False):\n continue\n x1, y1, w, h = ann['bbox']\n inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0))\n inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0))\n if inter_w * inter_h == 0:\n continue\n if ann['area'] <= 0 or w < 1 or h < 1:\n continue\n if ann['category_id'] not in self.cat_ids:\n continue\n bbox = [x1, y1, x1 + w, y1 + h]\n if ann.get('iscrowd', False):\n gt_bboxes_ignore.append(bbox)\n else:\n gt_bboxes.append(bbox)\n gt_labels.append(self.cat2label[ann['category_id']])\n gt_masks_ann.append(ann.get('segmentation', None))\n # 3D annotations in camera coordinates\n bbox_cam3d = np.array(ann['bbox_cam3d']).reshape(-1, )\n gt_bboxes_cam3d.append(bbox_cam3d)\n # 2.5D annotations in camera coordinates\n center2d = ann['center2d'][:2]\n depth = ann['center2d'][2]\n centers2d.append(center2d)\n depths.append(depth)\n\n if gt_bboxes:\n gt_bboxes = np.array(gt_bboxes, dtype=np.float32)\n gt_labels = np.array(gt_labels, dtype=np.int64)\n else:\n gt_bboxes = np.zeros((0, 4), dtype=np.float32)\n gt_labels = np.array([], dtype=np.int64)\n\n if gt_bboxes_cam3d:\n gt_bboxes_cam3d = np.array(gt_bboxes_cam3d, dtype=np.float32)\n centers2d = np.array(centers2d, dtype=np.float32)\n depths = np.array(depths, dtype=np.float32)\n else:\n gt_bboxes_cam3d = np.zeros((0, self.bbox_code_size),\n dtype=np.float32)\n centers2d = np.zeros((0, 2), dtype=np.float32)\n depths = np.zeros((0), dtype=np.float32)\n\n gt_bboxes_cam3d = CameraInstance3DBoxes(\n gt_bboxes_cam3d,\n box_dim=gt_bboxes_cam3d.shape[-1],\n origin=(0.5, 0.5, 0.5))\n gt_labels_3d = copy.deepcopy(gt_labels)\n\n if gt_bboxes_ignore:\n gt_bboxes_ignore = np.array(gt_bboxes_ignore, dtype=np.float32)\n else:\n gt_bboxes_ignore = np.zeros((0, 4), dtype=np.float32)\n\n seg_map = img_info['filename'].replace('jpg', 'png')\n\n ann = dict(\n bboxes=gt_bboxes,\n labels=gt_labels,\n gt_bboxes_3d=gt_bboxes_cam3d,\n gt_labels_3d=gt_labels_3d,\n centers2d=centers2d,\n depths=depths,\n bboxes_ignore=gt_bboxes_ignore,\n masks=gt_masks_ann,\n seg_map=seg_map)\n\n return ann\n\n def format_results(self,\n outputs,\n pklfile_prefix=None,\n submission_prefix=None):\n \"\"\"Format the results to pkl file.\n\n Args:\n outputs (list[dict]): Testing results of the dataset.\n pklfile_prefix (str): The prefix of pkl files. It includes\n the file path and the prefix of filename, e.g., \"a/b/prefix\".\n If not specified, a temp file will be created. Default: None.\n submission_prefix (str): The prefix of submitted files. It\n includes the file path and the prefix of filename, e.g.,\n \"a/b/prefix\". If not specified, a temp file will be created.\n Default: None.\n\n Returns:\n tuple: (result_files, tmp_dir), result_files is a dict containing\n the json filepaths, tmp_dir is the temporal directory created\n for saving json files when jsonfile_prefix is not specified.\n \"\"\"\n if pklfile_prefix is None:\n tmp_dir = tempfile.TemporaryDirectory()\n pklfile_prefix = osp.join(tmp_dir.name, 'results')\n else:\n tmp_dir = None\n\n if not isinstance(outputs[0], dict):\n result_files = self.bbox2result_kitti2d(outputs, self.CLASSES,\n pklfile_prefix,\n submission_prefix)\n elif 'pts_bbox' in outputs[0] or 'img_bbox' in outputs[0] or \\\n 'img_bbox2d' in outputs[0]:\n result_files = dict()\n for name in outputs[0]:\n results_ = [out[name] for out in outputs]\n pklfile_prefix_ = pklfile_prefix + name\n if submission_prefix is not None:\n submission_prefix_ = submission_prefix + name\n else:\n submission_prefix_ = None\n if '2d' in name:\n result_files_ = self.bbox2result_kitti2d(\n results_, self.CLASSES, pklfile_prefix_,\n submission_prefix_)\n else:\n result_files_ = self.bbox2result_kitti(\n results_, self.CLASSES, pklfile_prefix_,\n submission_prefix_)\n result_files[name] = result_files_\n else:\n result_files = self.bbox2result_kitti(outputs, self.CLASSES,\n pklfile_prefix,\n submission_prefix)\n return result_files, tmp_dir\n\n def evaluate(self,\n results,\n metric=None,\n logger=None,\n pklfile_prefix=None,\n submission_prefix=None,\n show=False,\n out_dir=None,\n pipeline=None):\n \"\"\"Evaluation in KITTI protocol.\n\n Args:\n results (list[dict]): Testing results of the dataset.\n metric (str | list[str], optional): Metrics to be evaluated.\n Defaults to None.\n logger (logging.Logger | str, optional): Logger used for printing\n related information during evaluation. Default: None.\n pklfile_prefix (str, optional): The prefix of pkl files, including\n the file path and the prefix of filename, e.g., \"a/b/prefix\".\n If not specified, a temp file will be created. Default: None.\n submission_prefix (str, optional): The prefix of submission data.\n If not specified, the submission data will not be generated.\n show (bool, optional): Whether to visualize.\n Default: False.\n out_dir (str, optional): Path to save the visualization results.\n Default: None.\n pipeline (list[dict], optional): raw data loading for showing.\n Default: None.\n\n Returns:\n dict[str, float]: Results of each evaluation metric.\n \"\"\"\n result_files, tmp_dir = self.format_results(results, pklfile_prefix)\n from mmdet3d.core.evaluation import kitti_eval\n gt_annos = [info['annos'] for info in self.anno_infos]\n\n if isinstance(result_files, dict):\n ap_dict = dict()\n for name, result_files_ in result_files.items():\n eval_types = ['bbox', 'bev', '3d']\n if '2d' in name:\n eval_types = ['bbox']\n ap_result_str, ap_dict_ = kitti_eval(\n gt_annos,\n result_files_,\n self.CLASSES,\n eval_types=eval_types)\n for ap_type, ap in ap_dict_.items():\n ap_dict[f'{name}/{ap_type}'] = float('{:.4f}'.format(ap))\n\n print_log(\n f'Results of {name}:\\n' + ap_result_str, logger=logger)\n\n else:\n if metric == 'img_bbox2d':\n ap_result_str, ap_dict = kitti_eval(\n gt_annos, result_files, self.CLASSES, eval_types=['bbox'])\n else:\n ap_result_str, ap_dict = kitti_eval(gt_annos, result_files,\n self.CLASSES)\n print_log('\\n' + ap_result_str, logger=logger)\n\n if tmp_dir is not None:\n tmp_dir.cleanup()\n if show or out_dir:\n self.show(results, out_dir, show=show, pipeline=pipeline)\n return ap_dict\n\n def bbox2result_kitti(self,\n net_outputs,\n class_names,\n pklfile_prefix=None,\n submission_prefix=None):\n \"\"\"Convert 3D detection results to kitti format for evaluation and test\n submission.\n\n Args:\n net_outputs (list[np.ndarray]): List of array storing the\n inferenced bounding boxes and scores.\n class_names (list[String]): A list of class names.\n pklfile_prefix (str): The prefix of pkl file.\n submission_prefix (str): The prefix of submission file.\n\n Returns:\n list[dict]: A list of dictionaries with the kitti format.\n \"\"\"\n assert len(net_outputs) == len(self.anno_infos)\n if submission_prefix is not None:\n mmcv.mkdir_or_exist(submission_prefix)\n\n det_annos = []\n print('\\nConverting prediction to KITTI format')\n for idx, pred_dicts in enumerate(\n mmcv.track_iter_progress(net_outputs)):\n annos = []\n info = self.anno_infos[idx]\n sample_idx = info['image']['image_idx']\n image_shape = info['image']['image_shape'][:2]\n\n box_dict = self.convert_valid_bboxes(pred_dicts, info)\n anno = {\n 'name': [],\n 'truncated': [],\n 'occluded': [],\n 'alpha': [],\n 'bbox': [],\n 'dimensions': [],\n 'location': [],\n 'rotation_y': [],\n 'score': []\n }\n if len(box_dict['bbox']) > 0:\n box_2d_preds = box_dict['bbox']\n box_preds = box_dict['box3d_camera']\n scores = box_dict['scores']\n box_preds_lidar = box_dict['box3d_lidar']\n label_preds = box_dict['label_preds']\n\n for box, box_lidar, bbox, score, label in zip(\n box_preds, box_preds_lidar, box_2d_preds, scores,\n label_preds):\n bbox[2:] = np.minimum(bbox[2:], image_shape[::-1])\n bbox[:2] = np.maximum(bbox[:2], [0, 0])\n anno['name'].append(class_names[int(label)])\n anno['truncated'].append(0.0)\n anno['occluded'].append(0)\n anno['alpha'].append(-np.arctan2(box[0], box[2]) + box[6])\n anno['bbox'].append(bbox)\n anno['dimensions'].append(box[3:6])\n anno['location'].append(box[:3])\n anno['rotation_y'].append(box[6])\n anno['score'].append(score)\n\n anno = {k: np.stack(v) for k, v in anno.items()}\n annos.append(anno)\n\n else:\n anno = {\n 'name': np.array([]),\n 'truncated': np.array([]),\n 'occluded': np.array([]),\n 'alpha': np.array([]),\n 'bbox': np.zeros([0, 4]),\n 'dimensions': np.zeros([0, 3]),\n 'location': np.zeros([0, 3]),\n 'rotation_y': np.array([]),\n 'score': np.array([]),\n }\n annos.append(anno)\n\n if submission_prefix is not None:\n curr_file = f'{submission_prefix}/{sample_idx:06d}.txt'\n with open(curr_file, 'w') as f:\n bbox = anno['bbox']\n loc = anno['location']\n dims = anno['dimensions'] # lhw -> hwl\n\n for idx in range(len(bbox)):\n print(\n '{} -1 -1 {:.4f} {:.4f} {:.4f} {:.4f} '\n '{:.4f} {:.4f} {:.4f} '\n '{:.4f} {:.4f} {:.4f} {:.4f} {:.4f} {:.4f}'.format(\n anno['name'][idx], anno['alpha'][idx],\n bbox[idx][0], bbox[idx][1], bbox[idx][2],\n bbox[idx][3], dims[idx][1], dims[idx][2],\n dims[idx][0], loc[idx][0], loc[idx][1],\n loc[idx][2], anno['rotation_y'][idx],\n anno['score'][idx]),\n file=f)\n\n annos[-1]['sample_idx'] = np.array(\n [sample_idx] * len(annos[-1]['score']), dtype=np.int64)\n\n det_annos += annos\n\n if pklfile_prefix is not None:\n if not pklfile_prefix.endswith(('.pkl', '.pickle')):\n out = f'{pklfile_prefix}.pkl'\n mmcv.dump(det_annos, out)\n print('Result is saved to %s' % out)\n\n return det_annos\n\n def bbox2result_kitti2d(self,\n net_outputs,\n class_names,\n pklfile_prefix=None,\n submission_prefix=None):\n \"\"\"Convert 2D detection results to kitti format for evaluation and test\n submission.\n\n Args:\n net_outputs (list[np.ndarray]): List of array storing the\n inferenced bounding boxes and scores.\n class_names (list[String]): A list of class names.\n pklfile_prefix (str): The prefix of pkl file.\n submission_prefix (str): The prefix of submission file.\n\n Returns:\n list[dict]: A list of dictionaries have the kitti format\n \"\"\"\n assert len(net_outputs) == len(self.anno_infos)\n\n det_annos = []\n print('\\nConverting prediction to KITTI format')\n for i, bboxes_per_sample in enumerate(\n mmcv.track_iter_progress(net_outputs)):\n annos = []\n anno = dict(\n name=[],\n truncated=[],\n occluded=[],\n alpha=[],\n bbox=[],\n dimensions=[],\n location=[],\n rotation_y=[],\n score=[])\n sample_idx = self.anno_infos[i]['image']['image_idx']\n\n num_example = 0\n for label in range(len(bboxes_per_sample)):\n bbox = bboxes_per_sample[label]\n for i in range(bbox.shape[0]):\n anno['name'].append(class_names[int(label)])\n anno['truncated'].append(0.0)\n anno['occluded'].append(0)\n anno['alpha'].append(-10)\n anno['bbox'].append(bbox[i, :4])\n # set dimensions (height, width, length) to zero\n anno['dimensions'].append(\n np.zeros(shape=[3], dtype=np.float32))\n # set the 3D translation to (-1000, -1000, -1000)\n anno['location'].append(\n np.ones(shape=[3], dtype=np.float32) * (-1000.0))\n anno['rotation_y'].append(0.0)\n anno['score'].append(bbox[i, 4])\n num_example += 1\n\n if num_example == 0:\n annos.append(\n dict(\n name=np.array([]),\n truncated=np.array([]),\n occluded=np.array([]),\n alpha=np.array([]),\n bbox=np.zeros([0, 4]),\n dimensions=np.zeros([0, 3]),\n location=np.zeros([0, 3]),\n rotation_y=np.array([]),\n score=np.array([]),\n ))\n else:\n anno = {k: np.stack(v) for k, v in anno.items()}\n annos.append(anno)\n\n annos[-1]['sample_idx'] = np.array(\n [sample_idx] * num_example, dtype=np.int64)\n det_annos += annos\n\n if pklfile_prefix is not None:\n if not pklfile_prefix.endswith(('.pkl', '.pickle')):\n out = f'{pklfile_prefix}.pkl'\n mmcv.dump(det_annos, out)\n print('Result is saved to %s' % out)\n\n if submission_prefix is not None:\n # save file in submission format\n mmcv.mkdir_or_exist(submission_prefix)\n print(f'Saving KITTI submission to {submission_prefix}')\n for i, anno in enumerate(det_annos):\n sample_idx = self.anno_infos[i]['image']['image_idx']\n cur_det_file = f'{submission_prefix}/{sample_idx:06d}.txt'\n with open(cur_det_file, 'w') as f:\n bbox = anno['bbox']\n loc = anno['location']\n dims = anno['dimensions'][::-1] # lhw -> hwl\n for idx in range(len(bbox)):\n print(\n '{} -1 -1 {:4f} {:4f} {:4f} {:4f} {:4f} {:4f} '\n '{:4f} {:4f} {:4f} {:4f} {:4f} {:4f} {:4f}'.format(\n anno['name'][idx],\n anno['alpha'][idx],\n *bbox[idx], # 4 float\n *dims[idx], # 3 float\n *loc[idx], # 3 float\n anno['rotation_y'][idx],\n anno['score'][idx]),\n file=f,\n )\n print(f'Result is saved to {submission_prefix}')\n\n return det_annos\n\n def convert_valid_bboxes(self, box_dict, info):\n \"\"\"Convert the predicted boxes into valid ones.\n\n Args:\n box_dict (dict): Box dictionaries to be converted.\n - boxes_3d (:obj:`CameraInstance3DBoxes`): 3D bounding boxes.\n - scores_3d (torch.Tensor): Scores of boxes.\n - labels_3d (torch.Tensor): Class labels of boxes.\n info (dict): Data info.\n\n Returns:\n dict: Valid predicted boxes.\n - bbox (np.ndarray): 2D bounding boxes.\n - box3d_camera (np.ndarray): 3D bounding boxes in\n camera coordinate.\n - scores (np.ndarray): Scores of boxes.\n - label_preds (np.ndarray): Class label predictions.\n - sample_idx (int): Sample index.\n \"\"\"\n box_preds = box_dict['boxes_3d']\n scores = box_dict['scores_3d']\n labels = box_dict['labels_3d']\n sample_idx = info['image']['image_idx']\n\n if len(box_preds) == 0:\n return dict(\n bbox=np.zeros([0, 4]),\n box3d_camera=np.zeros([0, 7]),\n scores=np.zeros([0]),\n label_preds=np.zeros([0, 4]),\n sample_idx=sample_idx)\n\n rect = info['calib']['R0_rect'].astype(np.float32)\n Trv2c = info['calib']['Tr_velo_to_cam'].astype(np.float32)\n P2 = info['calib']['P2'].astype(np.float32)\n img_shape = info['image']['image_shape']\n P2 = box_preds.tensor.new_tensor(P2)\n\n box_preds_camera = box_preds\n box_preds_lidar = box_preds.convert_to(Box3DMode.LIDAR,\n np.linalg.inv(rect @ Trv2c))\n\n box_corners = box_preds_camera.corners\n box_corners_in_image = points_cam2img(box_corners, P2)\n # box_corners_in_image: [N, 8, 2]\n minxy = torch.min(box_corners_in_image, dim=1)[0]\n maxxy = torch.max(box_corners_in_image, dim=1)[0]\n box_2d_preds = torch.cat([minxy, maxxy], dim=1)\n # Post-processing\n # check box_preds_camera\n image_shape = box_preds.tensor.new_tensor(img_shape)\n valid_cam_inds = ((box_2d_preds[:, 0] < image_shape[1]) &\n (box_2d_preds[:, 1] < image_shape[0]) &\n (box_2d_preds[:, 2] > 0) & (box_2d_preds[:, 3] > 0))\n # check box_preds\n valid_inds = valid_cam_inds\n\n if valid_inds.sum() > 0:\n return dict(\n bbox=box_2d_preds[valid_inds, :].numpy(),\n box3d_camera=box_preds_camera[valid_inds].tensor.numpy(),\n box3d_lidar=box_preds_lidar[valid_inds].tensor.numpy(),\n scores=scores[valid_inds].numpy(),\n label_preds=labels[valid_inds].numpy(),\n sample_idx=sample_idx)\n else:\n return dict(\n bbox=np.zeros([0, 4]),\n box3d_camera=np.zeros([0, 7]),\n box3d_lidar=np.zeros([0, 7]),\n scores=np.zeros([0]),\n label_preds=np.zeros([0, 4]),\n sample_idx=sample_idx)\n",
"import numpy as np\nimport torch\nfrom torch.nn import functional as F\n\nfrom mmdet.core.bbox import BaseBBoxCoder\nfrom mmdet.core.bbox.builder import BBOX_CODERS\n\n\n@BBOX_CODERS.register_module()\nclass MonoFlexCoder(BaseBBoxCoder):\n \"\"\"Bbox Coder for MonoFlex.\n\n Args:\n depth_mode (str): The mode for depth calculation.\n Available options are \"linear\", \"inv_sigmoid\", and \"exp\".\n base_depth (tuple[float]): References for decoding box depth.\n depth_range (list): Depth range of predicted depth.\n combine_depth (bool): Whether to use combined depth (direct depth\n and depth from keypoints) or use direct depth only.\n uncertainty_range (list): Uncertainty range of predicted depth.\n base_dims (tuple[tuple[float]]): Dimensions mean and std of decode bbox\n dimensions [l, h, w] for each category.\n dims_mode (str): The mode for dimension calculation.\n Available options are \"linear\" and \"exp\".\n multibin (bool): Whether to use multibin representation.\n num_dir_bins (int): Number of Number of bins to encode\n direction angle.\n bin_centers (list[float]): Local yaw centers while using multibin\n representations.\n bin_margin (float): Margin of multibin representations.\n code_size (int): The dimension of boxes to be encoded.\n eps (float, optional): A value added to the denominator for numerical\n stability. Default 1e-3.\n \"\"\"\n\n def __init__(self,\n depth_mode,\n base_depth,\n depth_range,\n combine_depth,\n uncertainty_range,\n base_dims,\n dims_mode,\n multibin,\n num_dir_bins,\n bin_centers,\n bin_margin,\n code_size,\n eps=1e-3):\n super(MonoFlexCoder, self).__init__()\n\n # depth related\n self.depth_mode = depth_mode\n self.base_depth = base_depth\n self.depth_range = depth_range\n self.combine_depth = combine_depth\n self.uncertainty_range = uncertainty_range\n\n # dimensions related\n self.base_dims = base_dims\n self.dims_mode = dims_mode\n\n # orientation related\n self.multibin = multibin\n self.num_dir_bins = num_dir_bins\n self.bin_centers = bin_centers\n self.bin_margin = bin_margin\n\n # output related\n self.bbox_code_size = code_size\n self.eps = eps\n\n def encode(self, gt_bboxes_3d):\n \"\"\"Encode ground truth to prediction targets.\n\n Args:\n gt_bboxes_3d (`BaseInstance3DBoxes`): Ground truth 3D bboxes.\n shape: (N, 7).\n\n Returns:\n torch.Tensor: Targets of orientations.\n \"\"\"\n local_yaw = gt_bboxes_3d.local_yaw\n\n # encode local yaw (-pi ~ pi) to multibin format\n encode_local_yaw = np.zeros(self.num_dir_bins * 2)\n bin_size = 2 * np.pi / self.num_dir_bins\n margin_size = bin_size * self.bin_margin\n\n bin_centers = self.bin_centers\n range_size = bin_size / 2 + margin_size\n\n offsets = local_yaw - bin_centers.unsqueeze(0)\n offsets[offsets > np.pi] = offsets[offsets > np.pi] - 2 * np.pi\n offsets[offsets < -np.pi] = offsets[offsets < -np.pi] + 2 * np.pi\n\n for i in range(self.num_dir_bins):\n offset = offsets[:, i]\n inds = abs(offset) < range_size\n encode_local_yaw[inds, i] = 1\n encode_local_yaw[inds, i + self.num_dir_bins] = offset\n\n orientation_target = encode_local_yaw\n\n return orientation_target\n\n def decode(self, bbox, base_centers2d, labels, downsample_ratio, cam2imgs):\n \"\"\"Decode bounding box regression into 3D predictions.\n\n Args:\n bbox (Tensor): Raw bounding box predictions for each\n predict center2d point.\n shape: (N, C)\n base_centers2d (torch.Tensor): Base centers2d for 3D bboxes.\n shape: (N, 2).\n labels (Tensor): Batch predict class label for each predict\n center2d point.\n shape: (N, )\n downsample_ratio (int): The stride of feature map.\n cam2imgs (Tensor): Batch images' camera intrinsic matrix.\n shape: kitti (N, 4, 4) nuscenes (N, 3, 3)\n\n Return:\n dict: The 3D prediction dict decoded from regression map.\n the dict has components below:\n - bboxes2d (torch.Tensor): Decoded [x1, y1, x2, y2] format\n 2D bboxes.\n - dimensions (torch.Tensor): Decoded dimensions for each\n object.\n - offsets2d (torch.Tenosr): Offsets between base centers2d\n and real centers2d.\n - direct_depth (torch.Tensor): Decoded directly regressed\n depth.\n - keypoints2d (torch.Tensor): Keypoints of each projected\n 3D box on image.\n - keypoints_depth (torch.Tensor): Decoded depth from keypoints.\n - combined_depth (torch.Tensor): Combined depth using direct\n depth and keypoints depth with depth uncertainty.\n - orientations (torch.Tensor): Multibin format orientations\n (local yaw) for each objects.\n \"\"\"\n\n # 4 dimensions for FCOS style regression\n pred_bboxes2d = bbox[:, 0:4]\n\n # change FCOS style to [x1, y1, x2, y2] format for IOU Loss\n pred_bboxes2d = self.decode_bboxes2d(pred_bboxes2d, base_centers2d)\n\n # 2 dimensions for projected centers2d offsets\n pred_offsets2d = bbox[:, 4:6]\n\n # 3 dimensions for 3D bbox dimensions offsets\n pred_dimensions_offsets3d = bbox[:, 29:32]\n\n # the first 8 dimensions are for orientation bin classification\n # and the second 8 dimensions are for orientation offsets.\n pred_orientations = torch.cat((bbox[:, 32:40], bbox[:, 40:48]), dim=1)\n\n # 3 dimensions for the uncertainties of the solved depths from\n # groups of keypoints\n pred_keypoints_depth_uncertainty = bbox[:, 26:29]\n\n # 1 dimension for the uncertainty of directly regressed depth\n pred_direct_depth_uncertainty = bbox[:, 49:50].squeeze(-1)\n\n # 2 dimension of offsets x keypoints (8 corners + top/bottom center)\n pred_keypoints2d = bbox[:, 6:26]\n\n # 1 dimension for depth offsets\n pred_direct_depth_offsets = bbox[:, 48:49].squeeze(-1)\n\n # decode the pred residual dimensions to real dimensions\n pred_dimensions = self.decode_dims(labels, pred_dimensions_offsets3d)\n pred_direct_depth = self.decode_direct_depth(pred_direct_depth_offsets)\n pred_keypoints_depth = self.keypoints2depth(pred_keypoints2d,\n pred_dimensions, cam2imgs,\n downsample_ratio)\n\n pred_direct_depth_uncertainty = torch.clamp(\n pred_direct_depth_uncertainty, self.uncertainty_range[0],\n self.uncertainty_range[1])\n pred_keypoints_depth_uncertainty = torch.clamp(\n pred_keypoints_depth_uncertainty, self.uncertainty_range[0],\n self.uncertainty_range[1])\n\n if self.combine_depth:\n pred_depth_uncertainty = torch.cat(\n (pred_direct_depth_uncertainty.unsqueeze(-1),\n pred_keypoints_depth_uncertainty),\n dim=1).exp()\n pred_depth = torch.cat(\n (pred_direct_depth.unsqueeze(-1), pred_keypoints_depth), dim=1)\n pred_combined_depth = \\\n self.combine_depths(pred_depth, pred_depth_uncertainty)\n else:\n pred_combined_depth = None\n\n preds = dict(\n bboxes2d=pred_bboxes2d,\n dimensions=pred_dimensions,\n offsets2d=pred_offsets2d,\n keypoints2d=pred_keypoints2d,\n orientations=pred_orientations,\n direct_depth=pred_direct_depth,\n keypoints_depth=pred_keypoints_depth,\n combined_depth=pred_combined_depth,\n direct_depth_uncertainty=pred_direct_depth_uncertainty,\n keypoints_depth_uncertainty=pred_keypoints_depth_uncertainty,\n )\n\n return preds\n\n def decode_direct_depth(self, depth_offsets):\n \"\"\"Transform depth offset to directly regressed depth.\n\n Args:\n depth_offsets (torch.Tensor): Predicted depth offsets.\n shape: (N, )\n\n Return:\n torch.Tensor: Directly regressed depth.\n shape: (N, )\n \"\"\"\n if self.depth_mode == 'exp':\n direct_depth = depth_offsets.exp()\n elif self.depth_mode == 'linear':\n base_depth = depth_offsets.new_tensor(self.base_depth)\n direct_depth = depth_offsets * base_depth[1] + base_depth[0]\n elif self.depth_mode == 'inv_sigmoid':\n direct_depth = 1 / torch.sigmoid(depth_offsets) - 1\n else:\n raise ValueError\n\n if self.depth_range is not None:\n direct_depth = torch.clamp(\n direct_depth, min=self.depth_range[0], max=self.depth_range[1])\n\n return direct_depth\n\n def decode_location(self,\n base_centers2d,\n offsets2d,\n depths,\n cam2imgs,\n downsample_ratio,\n pad_mode='default'):\n \"\"\"Retrieve object location.\n\n Args:\n base_centers2d (torch.Tensor): predicted base centers2d.\n shape: (N, 2)\n offsets2d (torch.Tensor): The offsets between real centers2d\n and base centers2d.\n shape: (N , 2)\n depths (torch.Tensor): Depths of objects.\n shape: (N, )\n cam2imgs (torch.Tensor): Batch images' camera intrinsic matrix.\n shape: kitti (N, 4, 4) nuscenes (N, 3, 3)\n downsample_ratio (int): The stride of feature map.\n pad_mode (str, optional): Padding mode used in\n training data augmentation.\n\n Return:\n tuple(torch.Tensor): Centers of 3D boxes.\n shape: (N, 3)\n \"\"\"\n N = cam2imgs.shape[0]\n # (N, 4, 4)\n cam2imgs_inv = cam2imgs.inverse()\n if pad_mode == 'default':\n centers2d_img = (base_centers2d + offsets2d) * downsample_ratio\n else:\n raise NotImplementedError\n # (N, 3)\n centers2d_img = \\\n torch.cat(centers2d_img, depths.unsqueeze(-1), dim=1)\n # (N, 4, 1)\n centers2d_extend = \\\n torch.cat((centers2d_img, centers2d_img.new_ones(N, 1)),\n dim=1).unqueeze(-1)\n locations = torch.matmul(cam2imgs_inv, centers2d_extend).squeeze(-1)\n\n return locations[:, :3]\n\n def keypoints2depth(self,\n keypoints2d,\n dimensions,\n cam2imgs,\n downsample_ratio=4,\n group0_index=[(7, 3), (0, 4)],\n group1_index=[(2, 6), (1, 5)]):\n \"\"\"Decode depth form three groups of keypoints and geometry projection\n model. 2D keypoints inlucding 8 coreners and top/bottom centers will be\n divided into three groups which will be used to calculate three depths\n of object.\n\n .. code-block:: none\n\n Group center keypoints:\n\n + --------------- +\n /| top center /|\n / | . / |\n / | | / |\n + ---------|----- + +\n | / | | /\n | / . | /\n |/ bottom center |/\n + --------------- +\n\n Group 0 keypoints:\n\n 0\n + -------------- +\n /| /|\n / | / |\n / | 5/ |\n + -------------- + +\n | /3 | /\n | / | /\n |/ |/\n + -------------- + 6\n\n Group 1 keypoints:\n\n 4\n + -------------- +\n /| /|\n / | / |\n / | / |\n 1 + -------------- + + 7\n | / | /\n | / | /\n |/ |/\n 2 + -------------- +\n\n\n Args:\n keypoints2d (torch.Tensor): Keypoints of objects.\n 8 vertices + top/bottom center.\n shape: (N, 10, 2)\n dimensions (torch.Tensor): Dimensions of objetcts.\n shape: (N, 3)\n cam2imgs (torch.Tensor): Batch images' camera intrinsic matrix.\n shape: kitti (N, 4, 4) nuscenes (N, 3, 3)\n downsample_ratio (int, opitonal): The stride of feature map.\n Defaults: 4.\n group0_index(list[tuple[int]], optional): Keypoints group 0\n of index to calculate the depth.\n Defaults: [0, 3, 4, 7].\n group1_index(list[tuple[int]], optional): Keypoints group 1\n of index to calculate the depth.\n Defaults: [1, 2, 5, 6]\n\n Return:\n tuple(torch.Tensor): Depth computed from three groups of\n keypoints (top/bottom, group0, group1)\n shape: (N, 3)\n \"\"\"\n\n pred_height_3d = dimensions[:, 1].clone()\n f_u = cam2imgs[:, 0, 0]\n center_height = keypoints2d[:, -2, 1] - keypoints2d[:, -1, 1]\n corner_group0_height = keypoints2d[:, group0_index[0], 1] \\\n - keypoints2d[:, group0_index[1], 1]\n corner_group1_height = keypoints2d[:, group1_index[0], 1] \\\n - keypoints2d[:, group1_index[1], 1]\n center_depth = f_u * pred_height_3d / (\n F.relu(center_height) * downsample_ratio + self.eps)\n corner_group0_depth = (f_u * pred_height_3d).unsqueeze(-1) / (\n F.relu(corner_group0_height) * downsample_ratio + self.eps)\n corner_group1_depth = (f_u * pred_height_3d).unsqueeze(-1) / (\n F.relu(corner_group1_height) * downsample_ratio + self.eps)\n\n corner_group0_depth = corner_group0_depth.mean(dim=1)\n corner_group1_depth = corner_group1_depth.mean(dim=1)\n\n keypoints_depth = torch.stack(\n (center_depth, corner_group0_depth, corner_group1_depth), dim=1)\n keypoints_depth = torch.clamp(\n keypoints_depth, min=self.depth_range[0], max=self.depth_range[1])\n\n return keypoints_depth\n\n def decode_dims(self, labels, dims_offset):\n \"\"\"Retrieve object dimensions.\n\n Args:\n labels (torch.Tensor): Each points' category id.\n shape: (N, K)\n dims_offset (torch.Tensor): Dimension offsets.\n shape: (N, 3)\n\n Returns:\n torch.Tensor: Shape (N, 3)\n \"\"\"\n\n if self.dims_mode == 'exp':\n dims_offset = dims_offset.exp()\n elif self.dims_mode == 'linear':\n labels = labels.long()\n base_dims = dims_offset.new_tensor(self.base_dims)\n dims_mean = base_dims[:, :3]\n dims_std = base_dims[:, 3:6]\n cls_dimension_mean = dims_mean[labels, :]\n cls_dimension_std = dims_std[labels, :]\n dimensions = dims_offset * cls_dimension_mean + cls_dimension_std\n else:\n raise ValueError\n\n return dimensions\n\n def decode_orientation(self, ori_vector, locations):\n \"\"\"Retrieve object orientation.\n\n Args:\n ori_vector (torch.Tensor): Local orientation vector\n in [axis_cls, head_cls, sin, cos] format.\n shape: (N, num_dir_bins * 4)\n locations (torch.Tensor): Object location.\n shape: (N, 3)\n\n Returns:\n tuple[torch.Tensor]: yaws and local yaws of 3d bboxes.\n \"\"\"\n if self.multibin:\n pred_bin_cls = ori_vector[:, :self.num_dir_bins * 2].view(\n -1, self.num_dir_bins, 2)\n pred_bin_cls = pred_bin_cls.softmax(dim=2)[..., 1]\n orientations = ori_vector.new_zeros(ori_vector.shape[0])\n for i in range(self.num_dir_bins):\n mask_i = (pred_bin_cls.argmax(dim=1) == i)\n start_bin = self.num_dir_bins * 2 + i * 2\n end_bin = start_bin + 2\n pred_bin_offset = ori_vector[mask_i, start_bin:end_bin]\n orientations[mask_i] = pred_bin_offset[:, 0].atan2(\n pred_bin_offset[:, 1]) + self.bin_centers[i]\n else:\n axis_cls = ori_vector[:, :2].softmax(dim=1)\n axis_cls = axis_cls[:, 0] < axis_cls[:, 1]\n head_cls = ori_vector[:, 2:4].softmax(dim=1)\n head_cls = head_cls[:, 0] < head_cls[:, 1]\n # cls axis\n orientations = self.bin_centers[axis_cls + head_cls * 2]\n sin_cos_offset = F.normalize(ori_vector[:, 4:])\n orientations += sin_cos_offset[:, 0].atan(sin_cos_offset[:, 1])\n\n locations = locations.view(-1, 3)\n rays = locations[:, 0].atan2(locations[:, 2])\n local_yaws = orientations\n yaws = local_yaws + rays\n\n larger_idx = (yaws > np.pi).nonzero()\n small_idx = (yaws < -np.pi).nonzero()\n if len(larger_idx) != 0:\n yaws[larger_idx] -= 2 * np.pi\n if len(small_idx) != 0:\n yaws[small_idx] += 2 * np.pi\n\n larger_idx = (local_yaws > np.pi).nonzero()\n small_idx = (local_yaws < -np.pi).nonzero()\n if len(larger_idx) != 0:\n local_yaws[larger_idx] -= 2 * np.pi\n if len(small_idx) != 0:\n local_yaws[small_idx] += 2 * np.pi\n\n return yaws, local_yaws\n\n def decode_bboxes2d(self, reg_bboxes2d, base_centers2d):\n \"\"\"Retrieve [x1, y1, x2, y2] format 2D bboxes.\n\n Args:\n reg_bboxes2d (torch.Tensor): Predicted FCOS style\n 2D bboxes.\n shape: (N, 4)\n base_centers2d (torch.Tensor): predicted base centers2d.\n shape: (N, 2)\n\n Returns:\n torch.Tenosr: [x1, y1, x2, y2] format 2D bboxes.\n \"\"\"\n centers_x = base_centers2d[:, 0]\n centers_y = base_centers2d[:, 1]\n\n xs_min = centers_x - reg_bboxes2d[..., 0]\n ys_min = centers_y - reg_bboxes2d[..., 1]\n xs_max = centers_x + reg_bboxes2d[..., 2]\n ys_max = centers_y + reg_bboxes2d[..., 3]\n\n bboxes2d = torch.stack([xs_min, ys_min, xs_max, ys_max], dim=-1)\n\n return bboxes2d\n\n def combine_depths(depth, depth_uncertainty):\n \"\"\"Combine all the prediced depths with depth uncertainty.\n\n Args:\n depth (torch.Tensor): Predicted depths of each object.\n 2D bboxes.\n shape: (N, 4)\n depth_uncertainty (torch.Tensor): Depth uncertainty for\n each depth of each object.\n shape: (N, 4)\n\n Returns:\n torch.Tenosr: combined depth.\n \"\"\"\n uncertainty_weights = 1 / depth_uncertainty\n uncertainty_weights = \\\n uncertainty_weights / \\\n uncertainty_weights.sum(dim=1, keepdim=True)\n combined_depth = torch.sum(depth * uncertainty_weights, dim=1)\n\n return combined_depth\n"
] | [
[
"numpy.allclose",
"numpy.random.seed",
"torch.manual_seed",
"torch.tensor",
"torch.allclose",
"numpy.array"
],
[
"torch.cuda.set_device",
"torch.cuda.current_device"
],
[
"numpy.minimum",
"torch.max",
"numpy.maximum",
"torch.cat",
"numpy.linalg.inv",
"torch.min",
"numpy.stack",
"numpy.ones",
"numpy.arctan2",
"numpy.array",
"numpy.zeros"
],
[
"torch.nn.functional.normalize",
"torch.sigmoid",
"torch.cat",
"torch.sum",
"torch.matmul",
"torch.nn.functional.relu",
"torch.stack",
"torch.clamp",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kwonsungil/Faster-RCNN | [
"673879871a87f60d992eae24e0d8c6a6c0a22cec",
"673879871a87f60d992eae24e0d8c6a6c0a22cec"
] | [
"models/Faster_RCNN_backup.py",
"utils/faster_rcnn/roi.py"
] | [
"import tensorflow as tf\r\nimport numpy as np\r\nimport os\r\nfrom config.config_Faster_RCNN import cfg\r\nimport cv2\r\nfrom utils.faster_rcnn.anchors import *\r\nfrom utils.faster_rcnn.roi import proposal_target\r\nimport time\r\nfrom utils.faster_rcnn.load_coco import preprocess\r\n\r\n\r\n# from utils.faster_rcnn.anchors_target_layer import anchor_target_layer\r\n\r\n\r\nclass Faster_RCNN:\r\n def __init__(self, model='Faster_RCNN', backbone='resnet101', is_train=True):\r\n ################\r\n self._proposal_targets = {}\r\n self._predictions = {}\r\n ###############\r\n out_dir = os.path.join(cfg.ROOT, 'logs', model)\r\n now = time.time()\r\n self.summary_dir = os.path.join(out_dir, str(now), \"summaries\")\r\n self.checkpoint_dir = os.path.join(out_dir, str(now), \"checkpoints\")\r\n\r\n self.is_train = is_train\r\n self.pre_train = True\r\n\r\n self.graph = tf.Graph()\r\n ConfigProto = tf.ConfigProto(gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.8))\r\n ConfigProto.gpu_options.allow_growth = True\r\n self.sess = tf.Session(config=ConfigProto, graph=self.graph)\r\n\r\n # 각각의 backbone 마다 bottleneck 개수\r\n if backbone == 'resnet50':\r\n self.num_blocks = [3, 4, 6, 3]\r\n elif backbone == 'resnet101':\r\n self.num_blocks = [3, 4, 23, 3]\r\n elif backbone == 'resnet152':\r\n self.num_blocks = [3, 8, 36, 3]\r\n else:\r\n raise NotImplementedError\r\n\r\n with self.graph.as_default():\r\n\r\n # self.image, self.gt_boxes, self.image_height, self.image_width = iterator.get_next()\r\n\r\n if self.is_train:\r\n dataset = preprocess()\r\n train_data = dataset.build_dataset(cfg.batch_size)\r\n iterator = train_data.make_one_shot_iterator()\r\n # self.image, self.gt_boxes, self.gt_cls, self.image_height, self.image_width = iterator.get_next()\r\n self.image, self.gt_boxes, self.gt_cls, self.image_height, self.image_width, \\\r\n self.positive_labels, self.positive_negative_labels, self.gt_positive_labels_bbox, self.gt_positive_negative_labels, self.anchors = iterator.get_next()\r\n\r\n self.gt_boxes = tf.squeeze(self.gt_boxes, axis=0)\r\n self.gt_cls = tf.squeeze(self.gt_cls, axis=0)\r\n else:\r\n self.image = tf.placeholder(tf.float32, [1, None, None, 3])\r\n\r\n\r\n #################################################################################\r\n self.cls_score, self.cls_pred, self.cls_prob, self.bbox_pred = self.build_network()\r\n\r\n self.sess.run(tf.global_variables_initializer())\r\n\r\n save_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)\r\n self.saver = tf.train.Saver(var_list=save_vars, max_to_keep=20)\r\n\r\n if os.path.exists(out_dir) and len(os.listdir(out_dir)) > 0:\r\n logs = os.listdir(out_dir)\r\n logs.sort()\r\n pre_ckpt_dir = logs.pop()\r\n print('out_dir : ', out_dir)\r\n print('pre_ckpt_dir : ', pre_ckpt_dir)\r\n filename = tf.train.latest_checkpoint(os.path.join(out_dir, pre_ckpt_dir, 'checkpoints'))\r\n else:\r\n filename = None\r\n\r\n if self.is_train:\r\n self.global_step = tf.Variable(0, name='global_step', trainable=False)\r\n self.learning_rate = tf.train.exponential_decay(\r\n cfg.initial_learning_rate, self.global_step, cfg.decay_steps,\r\n cfg.decay_rate, cfg.staircase, name='learning_rate')\r\n\r\n self.loss_box, self.l_loss_sum = self.compute_rpn_loss()\r\n self.log_loss, self.reg_loss = self.compute_head_loss()\r\n tf.summary.scalar(\"rpn/class_loss\", self.l_loss_sum)\r\n tf.summary.scalar(\"rpn/reg_loss\", self.loss_box)\r\n tf.summary.scalar(\"head/class_loss\", self.log_loss)\r\n tf.summary.scalar(\"head/reg_loss\", self.reg_loss)\r\n\r\n self.total_loss = self.loss_box + self.l_loss_sum + self.log_loss + self.reg_loss\r\n\r\n self.summary_writer = tf.summary.FileWriter(self.summary_dir, graph=self.sess.graph)\r\n with tf.control_dependencies(save_vars):\r\n self.train_op = tf.train.AdamOptimizer(self.learning_rate).minimize(self.total_loss,\r\n global_step=self.global_step,\r\n name='optimizer')\r\n # tf.summary.scalar(\"acc\", self.accuracy)\r\n tf.summary.scalar('total_loss', self.total_loss)\r\n tf.summary.scalar(\"lr\", self.learning_rate)\r\n self.summary_op = tf.summary.merge_all()\r\n\r\n os.makedirs(self.summary_dir, exist_ok=True)\r\n os.makedirs(self.checkpoint_dir, exist_ok=True)\r\n\r\n self.sess.run(tf.global_variables_initializer())\r\n\r\n # if filename is not None:\r\n # print('restore from : ', filename)\r\n # self.saver.restore(self.sess, filename)\r\n # else:\r\n # if self.pre_train:\r\n # print('restore resnet.....')\r\n # filename = tf.train.latest_checkpoint(\r\n # 'F:\\\\kwon\\\\image-classification-master\\\\logs\\\\resnet101\\\\1568089766.742705\\\\checkpoints')\r\n # print(filename)\r\n # restore_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"ResNet\")\r\n # self.restore = tf.train.Saver(var_list=restore_vars)\r\n # self.restore.restore(self.sess, filename)\r\n # else:\r\n # print('initialize....')\r\n\r\n def compute_head_loss(self):\r\n #self.cls_score, self.labels, self.bbox_pred, self.bbox_targets, self.bbox_inside_weights, self.bbox_outside_weights\r\n labels = tf.reshape(self.labels, [-1])\r\n cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.cls_score, labels=labels))\r\n sigma_2 = cfg.head_sigma ** 2\r\n box_diff = self.bbox_pred - self.bbox_targets\r\n in_box_diff = self.bbox_inside_weights * box_diff\r\n abs_in_box_diff = tf.abs(in_box_diff)\r\n smoothL1_sign = tf.stop_gradient(tf.to_float(tf.less(abs_in_box_diff, 1. / sigma_2)))\r\n in_loss_box = tf.pow(in_box_diff, 2) * (sigma_2 / 2.) * smoothL1_sign \\\r\n + (abs_in_box_diff - (0.5 / sigma_2)) * (1. - smoothL1_sign)\r\n out_loss_box = self.bbox_outside_weights * in_loss_box\r\n loss_box = tf.reduce_mean(tf.reduce_sum(out_loss_box, axis=cfg.head_dim))\r\n\r\n return cross_entropy, loss_box\r\n\r\n\r\n def compute_rpn_loss(self):\r\n # label은 총 1764개의 anchor 에 대해서 iou가 0.3 미만은 0 0.7 이상은, 나머지 -1\r\n # anchor_obj 실제 5개 object가 있는 곳만 1 이고 나머지 -1\r\n # 1, 0 , -1 label 중에서 1,0 만 가져옴 ( 0 = bg )\r\n useful_label = tf.reshape(tf.where(tf.not_equal(self.rpn_labels, -1)), [-1])\r\n reg_loss_nor = tf.cast(tf.shape(self.rpn_labels)[0] / 9, tf.float32)\r\n # 1764개 acnhor들 중에서 object가 있는것과 bg\r\n label_gather = tf.gather(self.rpn_labels, useful_label)\r\n label_gather = tf.cast(label_gather, dtype=tf.int32)\r\n # 1764개의 anchor들 중에서 object가 있는것과 bg\r\n # label_gt_order = 1764개 중 gt랑 가증 큰 anchor만 1로 되어 있는데, usfule_label 중 5개만 1이고 나머진 0 이겠지\r\n label_gt_order = tf.gather(self.anchor_obj, useful_label)\r\n # 전체 acnhor 중에서 object가 있는것과 bg\r\n anchor = tf.gather(self.anchors, useful_label)\r\n\r\n # self.probability = self.cls\r\n # self.probability = tf.squeeze(self.probability)\r\n # self.probability = tf.reshape(self.probability, [-1, 9 * 2])\r\n # 모델이 object가 있다고 예측한 것과 gt를 비교\r\n # [batch, 14, 14 , 18] 에서 1번째 idx가 object가 있다\r\n # 14 * 14 * 9 = 1764\r\n self.probability = tf.reshape(self.cls, [-1, 2])\r\n self.probability_gather = tf.gather(self.probability, useful_label)\r\n self.probability_gather = tf.cast(self.probability_gather, dtype=tf.float32)\r\n\r\n # gather the prediction_bbox to be computed in reg_loss\r\n # self.prediction_bbox = tf.squeeze(self.prediction_bbox)\r\n # self.prediction_bbox = tf.reshape(self.prediction_bbox, [-1, 9 * 4])\r\n self.prediction_bbox = tf.reshape(self.bbox, [-1, 4])\r\n self.prediction_bbox_gather = tf.gather(self.prediction_bbox, useful_label)\r\n\r\n # reconsitution_coords\r\n # anchor_x1 = anchor[:, 0]\r\n # anchor_y1 = anchor[:, 1]\r\n # anchor_x2 = anchor[:, 2]\r\n # anchor_y2 = anchor[:, 3]\r\n anchor_x1 = anchor[:, 0]\r\n anchor_y1 = anchor[:, 1]\r\n anchor_x2 = anchor[:, 2]\r\n anchor_y2 = anchor[:, 3]\r\n\r\n\r\n re_anchor_0 = tf.cast((anchor_x2 + anchor_x1) / 2.0, dtype=tf.float32)\r\n re_anchor_1 = tf.cast((anchor_y2 + anchor_y1) / 2.0, dtype=tf.float32)\r\n re_anchor_2 = tf.cast((anchor_x2 - anchor_x1), dtype=tf.float32)\r\n re_anchor_3 = tf.cast((anchor_y2 - anchor_y1), dtype=tf.float32)\r\n re_anchor = tf.squeeze(tf.stack(\r\n [re_anchor_0, re_anchor_1, re_anchor_2, re_anchor_3], axis=1))\r\n\r\n ground_truth_x1 = self.gt_boxes[:, 0]\r\n ground_truth_y1 = self.gt_boxes[:, 1]\r\n ground_truth_x2 = self.gt_boxes[:, 2]\r\n ground_truth_y2 = self.gt_boxes[:, 3]\r\n\r\n re_ground_truth_0 = tf.expand_dims(tf.cast((ground_truth_x1 + ground_truth_x2) / 2.0, dtype=tf.float32), -1)\r\n re_ground_truth_1 = tf.expand_dims(tf.cast((ground_truth_y1 + ground_truth_y2) / 2.0, dtype=tf.float32), -1)\r\n re_ground_truth_2 = tf.expand_dims(tf.cast((ground_truth_x2 - ground_truth_x1 + 1.0), dtype=tf.float32), -1)\r\n re_ground_truth_3 = tf.expand_dims(tf.cast((ground_truth_y2 - ground_truth_y1 + 1.0), dtype=tf.float32), -1)\r\n re_ground_truth = tf.concat([re_ground_truth_0, re_ground_truth_1, re_ground_truth_2, re_ground_truth_3],\r\n axis=1)\r\n\r\n # self.gt_map=tf.one_hot(self.label_gt_order,self.size)\r\n # self.re_label_gt_order=tf.matmul(self.gt_map,self.re_ground_truth)\r\n # self.re_label_gt_order=tf.cast(self.re_label_gt_order,dtype=tf.float32)\r\n\r\n # 실제 object가 일정 이상 겹친 acnhor들 = label_gt_order\r\n # re_ground_truth는 실제 object에 대해서 x,y,w,h\r\n #TODO\r\n # object가 5개 일때 re_ground_truth 크기는 5개, label_gt_order 는 좀 클 텐데???\r\n self.re_label_gt_order = tf.gather(re_ground_truth, label_gt_order)\r\n\r\n # chosse which rpn_box to be computed in reg_loss, for label is positive ie, 1\r\n # label_gather는 1764개중 label이 backround나 존재하는 것들\r\n # label_weight_c는 object라 0.7 이상 겹치는 애들\r\n self.label_weight_c = tf.cast((label_gather > 0), tf.float32)\r\n # label_weight_c는 bg가 아닌 실제 object가 있는 것들\r\n self.label_weight_c = tf.expand_dims(self.label_weight_c, axis=1)\r\n\r\n # object가 있는지 없는지에 대한 loss\r\n l_loss_sum = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.probability_gather, labels=label_gather))\r\n\r\n # bbox_predicted = prediction_bbox_gather\r\n # bbox_ground_truth = self.re_label_gt_order\r\n # weight = self.label_weight_c\r\n\r\n sigma_1 = cfg.rpn_sigma ** 2\r\n bbox_ground_truth_0 = tf.cast((self.re_label_gt_order[:, 0] - re_anchor_0) / re_anchor_2, dtype=tf.float32)\r\n bbox_ground_truth_1 = tf.cast((self.re_label_gt_order[:, 1] - re_anchor_1) / re_anchor_3, dtype=tf.float32)\r\n bbox_ground_truth_2 = tf.cast(tf.log(self.re_label_gt_order[:, 2] / re_anchor_2), dtype=tf.float32)\r\n bbox_ground_truth_3 = tf.cast(tf.log(self.re_label_gt_order[:, 3] / re_anchor_3), dtype=tf.float32)\r\n re_bbox_ground_truth = tf.stack(\r\n [bbox_ground_truth_0, bbox_ground_truth_1, bbox_ground_truth_2, bbox_ground_truth_3], axis=1)\r\n # re_bbox_predicted = bbox_predicted\r\n bbox_diff = self.prediction_bbox_gather - re_bbox_ground_truth\r\n t_diff = bbox_diff * self.label_weight_c\r\n t_diff_abs = tf.abs(t_diff)\r\n compare_1 = tf.stop_gradient(tf.to_float(tf.less(t_diff_abs, 1.0 / sigma_1)))\r\n # compare_1 = tf.to_float(tf.less(t_diff_abs, 1.0/sigma_1))\r\n sl_loss_box = (sigma_1 / 2.0) * compare_1 * tf.pow(t_diff_abs, 2) + (1.0 - compare_1) * (\r\n t_diff_abs - 0.5 / sigma_1)\r\n sum_loss_box = tf.reduce_sum(sl_loss_box)\r\n loss_box = sum_loss_box * cfg.rpn_lmd / cfg.anchor_batch\r\n\r\n return loss_box, l_loss_sum\r\n\r\n\r\n def build_network(self):\r\n with tf.variable_scope('ResNet'):\r\n model = tf.layers.conv2d(inputs=self.image, filters=64, kernel_size=(7, 7), strides=(2, 2),\r\n padding='SAME', name='conv_1',\r\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\r\n kernel_regularizer=tf.contrib.layers.l2_regularizer(cfg.weight_decay))\r\n model = tf.layers.batch_normalization(inputs=model, trainable=True, training=self.is_train)\r\n model = tf.nn.relu(model)\r\n model = tf.layers.max_pooling2d(model, pool_size=(3, 3), strides=(2, 2), padding='same', name='max_pooling')\r\n print(model)\r\n\r\n with tf.variable_scope('layers_2n'):\r\n for idx in range(self.num_blocks[0]):\r\n block_name = 'layers_2n_{}'.format(idx)\r\n model = self.residual_bottleneck(block_name, model, filters=64, kernel_size=3, stride=1)\r\n print(block_name, model)\r\n with tf.variable_scope('layers_4n'):\r\n for idx in range(self.num_blocks[1]):\r\n block_name = 'layers_4n_{}'.format(idx)\r\n # 첫번째 block에서 down sampling\r\n if idx == 0:\r\n model = self.residual_bottleneck(block_name, model, filters=128, kernel_size=3, stride=2)\r\n else:\r\n model = self.residual_bottleneck(block_name, model, filters=128, kernel_size=3, stride=1)\r\n print(block_name, model)\r\n with tf.variable_scope('layers_6n'):\r\n for idx in range(self.num_blocks[2]):\r\n block_name = 'layers_6n_{}'.format(idx)\r\n if idx == 0:\r\n model = self.residual_bottleneck(block_name, model, filters=256, kernel_size=3, stride=2)\r\n else:\r\n model = self.residual_bottleneck(block_name, model, filters=256, kernel_size=3, stride=1)\r\n print(block_name, model)\r\n # with tf.variable_scope('layers_8n'):\r\n # for idx in range(self.num_blocks[3]):\r\n # block_name = 'layers_8n_{}'.format(idx)\r\n # if idx == 0:\r\n # model = self.residual_bottleneck(block_name, model, filters=512, kernel_size=3, stride=2)\r\n # else:\r\n # model = self.residual_bottleneck(block_name, model, filters=512, kernel_size=3, stride=1)\r\n # print(block_name, model)\r\n\r\n\r\n with tf.variable_scope('RPN'):\r\n # 14 * 14* 1024\r\n rpn = tf.layers.conv2d(inputs=model, filters=512, kernel_size=(3, 3), strides=(1, 1), padding='SAME',\r\n name='intermediate', activation=tf.nn.relu)\r\n print(model)\r\n with tf.variable_scope('cls'):\r\n self.cls = tf.layers.conv2d(inputs=rpn, filters=cfg.num_anchors * 2, kernel_size=(1, 1), strides=(1, 1),\r\n padding='SAME', activation=None)\r\n with tf.variable_scope('bbox'):\r\n self.bbox = tf.layers.conv2d(inputs=rpn, filters=cfg.num_anchors * 4, kernel_size=(1, 1), strides=(1, 1),\r\n padding='SAME', activation=None)\r\n print('cls : ', self.cls)\r\n print('bbox : ', self.bbox)\r\n # self.anchors = tf.py_func(all_anchor_conner, [self.image_width, self.image_height, cfg.feat_stride],\r\n self.anchors = tf.py_func(all_anchor_conner, [self.image_width, self.image_height, cfg.anchor_scales, cfg.anchor_ratios, cfg.feat_stride],\r\n tf.float32)\r\n # self.labels, self.anchor_obj = anchor_labels_process(self.gt_boxes, self.anchors, cfg.anchor_batch, cfg.overlaps_max, cfg.overlaps_min, self.image_width, self.image_height)\r\n\r\n if self.is_train:\r\n self.rpn_labels, self.anchor_obj = tf.py_func(anchor_labels_process,\r\n [self.gt_boxes, self.anchors, cfg.anchor_batch,\r\n cfg.overlaps_max, cfg.overlaps_min, self.image_width,\r\n self.image_height], [tf.float32, tf.int32])\r\n print('self.labels : ', self.rpn_labels)\r\n print('self.anchor_obj : ', self.anchor_obj)\r\n # [batch, 7 ,7, 2*9] => [batch * 7 * 7, 2*9]\r\n # bbox = tf.squeeze(bbox)\r\n # bbox = tf.reshape(bbox, [-1, cfg.num_anchors * 4])\r\n bbox = tf.reshape(self.bbox, [-1, 4])\r\n\r\n # cls = tf.squeeze(cls)\r\n # cls = tf.reshape(cls, [-1, cfg.num_anchors * 2])\r\n cls = tf.reshape(self.cls, [-1, 2])\r\n print('cls : ', cls)\r\n print('bbox : ', bbox)\r\n\r\n with tf.variable_scope('ROI'):\r\n if self.is_train:\r\n post_nms_topN = cfg.max_nms_num\r\n else:\r\n post_nms_topN = cfg.test_max_nms_num\r\n\r\n nms_thresh = cfg.nms_thresh\r\n # idx 0 : object가 없다\r\n # idx 1 : object가 있다\r\n scores = cls[:, 1]\r\n rpn_bbox_pred = bbox\r\n\r\n # anchor는 feature map ^ 2 * num anchors, (x1, y1, x2, y2)\r\n # anchors_x = x1 + x2 / 2\r\n # anchors_y = y1 + y2 / 2\r\n\r\n # all_anchor_conners: (196 * 9, 4)\r\n print(self.anchors)\r\n anchor_x = tf.add(self.anchors[:, 2], self.anchors[:, 0]) * 0.5\r\n anchor_y = tf.add(self.anchors[:, 3], self.anchors[:, 1]) * 0.5\r\n acnhor_w = tf.subtract(self.anchors[:, 2], self.anchors[:, 0]) + 1.0\r\n acnhor_h = tf.subtract(self.anchors[:, 3], self.anchors[:, 1]) + 1.0\r\n\r\n # 기존 앵커 값들은 다 정해져있으니, model이 내뱉는 값을에 acnhor 값을 곱해줌\r\n # 모델이 각 anchor마다 예측하는 4개의 좌표가 나옴\r\n # cood 값은 gt bbox 처럼 이미지 전체에서 좌표 값들임 (open cv2가 rectangle 그리듯이)\r\n bbox_x = bbox[:, 0] * acnhor_w + anchor_x\r\n bbox_y = bbox[:, 1] * acnhor_h + anchor_y\r\n bbox_w = tf.exp(bbox[:, 2]) * acnhor_w\r\n bbox_h = tf.exp(bbox[:, 3]) * acnhor_h\r\n\r\n # model이 예측한 bbox으 좌표\r\n coord_x1 = bbox_x - bbox_w * 0.5\r\n coord_y1 = bbox_y - bbox_h * 0.5\r\n coord_x2 = bbox_x + bbox_w * 0.5\r\n coord_y2 = bbox_y + bbox_h * 0.5\r\n coord_result = tf.stack([coord_x1, coord_y1, coord_x2, coord_y2], axis=1)\r\n print('coord_result : ', coord_result)\r\n # coord result는 model이 예측한 값을 anchor에 맞게 값을 변환 한 값임\r\n # 원본 이미지에서 각각의 앵커에 대해서 예측한 좌표값들\r\n\r\n # 좌표에서 min max 보정\r\n b0 = tf.maximum(tf.minimum(coord_result[:, 0], tf.cast((self.image_width - 1), tf.float32)), 0.0)\r\n b1 = tf.maximum(tf.minimum(coord_result[:, 1], tf.cast((self.image_height - 1), tf.float32)), 0.0)\r\n b2 = tf.maximum(tf.minimum(coord_result[:, 2], tf.cast((self.image_width - 1), tf.float32)), 0.0)\r\n b3 = tf.maximum(tf.minimum(coord_result[:, 3], tf.cast((self.image_height - 1), tf.float32)), 0.0)\r\n coord_result = tf.stack([b0, b1, b2, b3], axis=1)\r\n print('coord_result : ', coord_result)\r\n print('scores : ', scores)\r\n\r\n # 1764 개에 대해서 NMS 해줌\r\n # [1764, 4]\r\n # [1764, 1]\r\n inds = tf.image.non_max_suppression(coord_result, scores, max_output_size=post_nms_topN,\r\n iou_threshold=nms_thresh)\r\n # 1764, 1]\r\n boxes = tf.gather(coord_result, inds)\r\n boxes = tf.to_float(boxes)\r\n roi_scores = tf.gather(scores, inds)\r\n # roi_scores = tf.reshape(scores, shape=(-1, 1))\r\n batch_inds = tf.zeros((tf.shape(inds)[0], 1), dtype=tf.float32)\r\n # 모델이 예측한 좌표값에 대해서 NMS 한 결과 = RoI\r\n rois = tf.concat([batch_inds, boxes], 1)\r\n print('roi_scores : ', roi_scores)\r\n print('batch_inds : ', batch_inds)\r\n print('rois : ', rois)\r\n # rois_coord = rois\r\n # rios_scroe_process = roi_scores\r\n\r\n # 학습 할 때는 target layer에 대해서 proposal\r\n # RoI 중에서 256 batch 에 대해서 positive와 negative sample을 만듦\r\n if self.is_train:\r\n with tf.variable_scope('process'):\r\n rois, roi_scores, labels, bbox_targets, bbox_inside_weights, bbox_outside_weights = tf.py_func(\r\n proposal_target,\r\n [rois, roi_scores, self.gt_boxes, cfg.num_classes, self.gt_cls],\r\n [tf.float32, tf.float32, tf.float32, tf.float32, tf.float32, tf.float32],\r\n name=\"proposal_target\")\r\n rois.set_shape([cfg.dect_train_batch, 5])\r\n roi_scores.set_shape([cfg.dect_train_batch])\r\n labels.set_shape([cfg.dect_train_batch, 1])\r\n bbox_targets.set_shape([cfg.dect_train_batch, cfg.num_classes * 4])\r\n bbox_inside_weights.set_shape([cfg.dect_train_batch, cfg.num_classes * 4])\r\n bbox_outside_weights.set_shape([cfg.dect_train_batch, cfg.num_classes * 4])\r\n\r\n # self._proposal_targets['rois'] = rois\r\n # self._proposal_targets['labels'] = tf.to_int32(labels, name=\"to_int32\")\r\n # self._proposal_targets['bbox_targets'] = bbox_targets\r\n # self._proposal_targets['bbox_inside_weights'] = bbox_inside_weights\r\n # self._proposal_targets['bbox_outside_weights'] = bbox_outside_weights,\r\n\r\n self.labels = tf.to_int32(labels, name=\"to_int32\")\r\n self.bbox_targets = bbox_targets\r\n self.bbox_inside_weights = bbox_inside_weights\r\n self.bbox_outside_weights = bbox_outside_weights\r\n self.rois = rois\r\n\r\n ########################################\r\n # train 에서는 256개 대해서\r\n # infernce에서는 전체 roi 대해서\r\n with tf.variable_scope('roi_pooing'):\r\n batch_ids = tf.squeeze(tf.slice(rois, [0, 0], [-1, 1], name=\"batch_id\"), [1])\r\n print('batch_ids : ', batch_ids)\r\n bottom_shape = tf.shape(model)\r\n height = (tf.to_float(bottom_shape[1]) - 1.) * np.float32(cfg.feat_stride)\r\n width = (tf.to_float(bottom_shape[2]) - 1.) * np.float32(cfg.feat_stride)\r\n # RoI는 원본이미지에서 모델이 예측한 좌표 값들임\r\n x1 = tf.slice(rois, [0, 1], [-1, 1], name=\"x1\") / width\r\n y1 = tf.slice(rois, [0, 2], [-1, 1], name=\"y1\") / height\r\n x2 = tf.slice(rois, [0, 3], [-1, 1], name=\"x2\") / width\r\n y2 = tf.slice(rois, [0, 4], [-1, 1], name=\"y2\") / height\r\n # Won't be back-propagated to rois anyway, but to save time\r\n bboxes = tf.stop_gradient(tf.concat([y1, x1, y2, x2], axis=1))\r\n pre_pool_size = cfg.POOLING_SIZE * 2 # 7*2\r\n print('bboxes : ', bboxes)\r\n print('model : ', model)\r\n print('pre_pool_size : ', pre_pool_size)\r\n print('batch_ids : ', batch_ids)\r\n\r\n # http://incredible.ai/deep-learning/2018/03/17/Faster-R-CNN/\r\n # Fixed-size Resize instead of ROI Pooling\r\n crops = tf.image.crop_and_resize(model, bboxes, tf.to_int32(batch_ids), [pre_pool_size, pre_pool_size], method=\"bilinear\",\r\n name=\"crops\")\r\n print('crops : ', crops)\r\n crops = tf.layers.max_pooling2d(crops, pool_size=(2, 2), strides=(2, 2), padding='VALID')\r\n print('crops : ', crops)\r\n\r\n with tf.variable_scope('head'):\r\n crops = tf.layers.flatten(crops)\r\n model = tf.layers.dense(crops, 2048)\r\n print(model)\r\n\r\n with tf.variable_scope('classification'):\r\n cls_score = tf.layers.dense(model, cfg.num_classes,\r\n kernel_initializer=tf.random_normal_initializer(mean=0.0, stddev=0.01),\r\n kernel_regularizer=tf.contrib.layers.l2_regularizer(cfg.weight_decay),\r\n activation=None, name='cls_score')\r\n\r\n cls_prob = tf.nn.softmax(cls_score, name=\"cls_prob\")\r\n cls_pred = tf.argmax(cls_score, axis=1, name=\"cls_pred\")\r\n\r\n bbox_pred = tf.layers.dense(model, cfg.num_classes * 4,\r\n kernel_initializer=tf.random_normal_initializer(mean=0.0, stddev=0.01),\r\n kernel_regularizer=tf.contrib.layers.l2_regularizer(cfg.weight_decay),\r\n activation=None, name='bbox_pred')\r\n\r\n # self._predictions[\"cls_score\"] = cls_score\r\n # self._predictions[\"cls_pred\"] = cls_pred\r\n # self._predictions[\"cls_prob\"] = cls_prob\r\n # self._predictions[\"bbox_pred\"] = bbox_pred\r\n return cls_score, cls_pred, cls_prob, bbox_pred\r\n\r\n def residual_bottleneck(self, name, inputs, kernel_size, filters, stride):\r\n # orginal resnet은 stride가 첫 번째 convolution\r\n # 추후에는 정보량 손실로 인해 두 번재 convolution에 stride\r\n with tf.variable_scope(name):\r\n # 1x1\r\n block = tf.layers.conv2d(inputs=inputs, filters=filters, kernel_size=(1, 1), strides=(1, 1),\r\n padding='SAME',\r\n name='conv_1', kernel_initializer=tf.contrib.layers.xavier_initializer(),\r\n kernel_regularizer=tf.contrib.layers.l2_regularizer(cfg.weight_decay))\r\n block = tf.layers.batch_normalization(inputs=block, trainable=True, training=self.is_train)\r\n block = tf.nn.relu(block)\r\n\r\n # 3x3\r\n block = tf.layers.conv2d(inputs=block, filters=filters, kernel_size=(kernel_size, kernel_size),\r\n strides=(stride, stride),\r\n padding='SAME',\r\n name='conv_2', kernel_initializer=tf.contrib.layers.xavier_initializer(),\r\n kernel_regularizer=tf.contrib.layers.l2_regularizer(cfg.weight_decay))\r\n block = tf.layers.batch_normalization(inputs=block, trainable=True, training=self.is_train)\r\n block = tf.nn.relu(block)\r\n\r\n # 1*1\r\n block = tf.layers.conv2d(inputs=block, filters=filters * 4, kernel_size=(1, 1), strides=(1, 1),\r\n padding='SAME',\r\n name='conv_3', kernel_initializer=tf.contrib.layers.xavier_initializer(),\r\n kernel_regularizer=tf.contrib.layers.l2_regularizer(cfg.weight_decay))\r\n block = tf.layers.batch_normalization(inputs=block, trainable=True, training=self.is_train)\r\n block = tf.nn.relu(block)\r\n\r\n # shortcut\r\n if int(block.shape[3]) != int(inputs.shape[3]):\r\n # inputs = tf.pad(inputs, np.array([[0, 0], [1, 1], [1, 1], [0, 0]]), name='pad_1')\r\n inputs = tf.layers.conv2d(inputs, filters=filters * 4, kernel_size=(1, 1),\r\n strides=stride, padding='VALID')\r\n\r\n return tf.nn.relu(block + inputs)\r\n\r\n def train(self, save=False):\r\n with self.graph.as_default():\r\n # feed_dict = {self.input_x: batch_x,\r\n # self.label: batch_y}\r\n _, global_step, summary_str, loss, lr = self.sess.run(\r\n [self.train_op, self.global_step, self.summary_op, self.total_loss, self.learning_rate],\r\n )\r\n if save:\r\n self.summary_writer.add_summary(summary_str, global_step=global_step)\r\n self.saver.save(self.sess, os.path.join(self.checkpoint_dir, 'model.ckpt'), global_step=global_step)\r\n\r\n return global_step, loss, acc, lr\r\n\r\n\r\nif __name__ == '__main__':\r\n net = Faster_RCNN('Faster_RCNN', 'resnet101', True)\r\n\r\n for epoch in range(cfg.epochs):\r\n loss = 0\r\n acc = 0\r\n for step in range(int(cfg.train_num / cfg.batch_size)):\r\n start_time = time.time()\r\n if step % 200 == 0 and step != 0:\r\n global_step, train_loss, train_acc, lr = net.train(True)\r\n else:\r\n global_step, train_loss, train_acc, lr = net.train(False)\r\n end_time = time.time()\r\n print('Epoch {} step {}, loss = {}, acc = {} , processing time = {} lr = {}'.format(epoch, global_step,\r\n train_loss, train_acc,\r\n end_time - start_time,\r\n lr))\r\n loss += train_loss\r\n acc += train_acc\r\n\r\n print('Epoch {} step {}, loss = {}, acc = {}'.format(epoch, global_step, loss / step, acc / step))\r\n",
"from config.config_Faster_RCNN import cfg\r\nimport numpy as np\r\nimport numpy.random as npr\r\nfrom utils.faster_rcnn.anchors import calculate_IOU\r\n\r\n\r\n# def calculate_IOU(target_boxes, gt_boxes): # gt_boxes[num_obj,4] targer_boxes[w*h*k,4]\r\n# num_gt = gt_boxes.shape[0]\r\n# num_tr = target_boxes.shape[0]\r\n# IOU_s = np.zeros((num_gt, num_tr), dtype=np.float)\r\n# for ix in range(num_gt):\r\n# gt_area = (gt_boxes[ix, 2] - gt_boxes[ix, 0]) * (gt_boxes[ix, 3] - gt_boxes[ix, 1])\r\n# # print (gt_area)\r\n# for iy in range(num_tr):\r\n# iw = min(gt_boxes[ix, 2], target_boxes[iy, 2]) - max(gt_boxes[ix, 0], target_boxes[iy, 0])\r\n# # print (iw)\r\n# if iw > 0:\r\n# ih = min(gt_boxes[ix, 3], target_boxes[iy, 3]) - max(gt_boxes[ix, 1], target_boxes[iy, 1])\r\n# # print (ih)\r\n# if ih > 0:\r\n# tar_area = (target_boxes[iy, 2] - target_boxes[iy, 0]) * (target_boxes[iy, 3] - target_boxes[iy, 1])\r\n# # print (tar_area)\r\n# i_area = iw * ih\r\n# iou = i_area / float((gt_area + tar_area - i_area))\r\n# IOU_s[ix, iy] = iou\r\n# IOU_s = np.transpose(IOU_s)\r\n# return IOU_s\r\n\r\n\r\ndef proposal_target(rois, rois_score, gt_boxes, _num_classes, gt_cls):\r\n num_images = 1\r\n rois_per_image = cfg.dect_train_batch / num_images\r\n # 배경이 아닌 것에 대한 비율\r\n # rois_per_image = 256\r\n # dect_fg_rate = 0.25\r\n # fg_rois_per_image\r\n fg_rois_per_image = np.round(cfg.dect_fg_rate * rois_per_image)\r\n labels, rois, roi_scores, bbox_targets, bbox_inside_weights = sample_rois( \\\r\n rois, rois_score, gt_boxes, fg_rois_per_image, \\\r\n rois_per_image, _num_classes, gt_cls)\r\n # rois = rois.reshape(-1, 5)\r\n rois = rois.reshape(-1, 4)\r\n roi_scores = roi_scores.reshape(-1)\r\n labels = labels.reshape(-1, 1)\r\n bbox_targets = bbox_targets.reshape(-1, _num_classes * 4)\r\n bbox_inside_weights = bbox_inside_weights.reshape(-1, _num_classes * 4)\r\n bbox_outside_weights = np.array(bbox_inside_weights > 0).astype(np.float32)\r\n return rois, roi_scores, labels, bbox_targets, bbox_inside_weights, bbox_outside_weights\r\n\r\n\r\ndef _get_bbox_regression_labels(bbox_target_data, num_classes):\r\n \"\"\" compute the bbox_targets and bbox_inside_weights\r\n ie, tx*,ty*,tw*,th* and which bbox_target to be used in loss compute\"\"\"\r\n clss = bbox_target_data[:, 0]\r\n bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32)\r\n bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32)\r\n inds = np.where(clss > 0)[0]\r\n for ind in inds:\r\n cls = clss[ind]\r\n start = int(4 * cls)\r\n end = start + 4\r\n bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]\r\n bbox_inside_weights[ind, start:end] = cfg.roi_input_inside_weight\r\n return bbox_targets, bbox_inside_weights\r\n\r\n\r\ndef sample_rois(rois, rois_score, gt_boxes, fg_rois_per_image, rois_per_image, num_classes, gt_cls):\r\n \"\"\" rois sample process: clip to the image boundary, nms, bg_fg sample\"\"\"\r\n # 300개의 RoI가 있고 5개의 GT 가 있을 때\r\n # (300, 5)\r\n # overlaps = calculate_IOU(rois[:, 1:5], gt_boxes)\r\n overlaps = calculate_IOU(rois, gt_boxes)\r\n # RoI에서 GT와 가장 크게 겹치는 박스\r\n gt_assignment = overlaps.argmax(axis=1)\r\n max_overlaps = overlaps.max(axis=1)\r\n\r\n # gt cls는 5개의 object[0, 4, 6, 2, 9]\r\n labels = gt_cls[gt_assignment]\r\n # labels = 300개의 RoI 중에서 가장 큰 값에 argmax에 대한 cls 값을 가짐\r\n # 300개의 RoI가 각각 class label 을 갖게 됨\r\n\r\n\r\n # IOU가 0.5 이상인 애들\r\n fg_inds = np.where(max_overlaps >= cfg.fg_thresh)[0]\r\n # IOU가 0.5 보다 작고 0보다 큰 애들\r\n bg_inds = np.where((max_overlaps < cfg.bg_thresh_hi) & (max_overlaps >= cfg.bg_thresh_lo))[0]\r\n # print(np.sum(fg_inds), np.sum(bg_inds))\r\n if fg_inds.size > 0 and bg_inds.size > 0:\r\n # 일단 256 * 1/4 만틈 positive를 가져오지만 그게 안될 경우 nehative로 채움\r\n fg_rois_per_image = min(fg_rois_per_image, fg_inds.size)\r\n fg_inds = npr.choice(fg_inds, size=int(fg_rois_per_image), replace=False)\r\n bg_rois_per_image = rois_per_image - fg_rois_per_image\r\n # 만양 negative도 batch 보다 작다면 중복해서 batch를 만듦\r\n to_replace = bg_inds.size < bg_rois_per_image\r\n bg_inds = npr.choice(bg_inds, size=int(bg_rois_per_image), replace=to_replace)\r\n elif fg_inds.size > 0:\r\n # 만약 negative가 없을 경우 positive로 batch를 채움\r\n to_replace = fg_inds.size < rois_per_image\r\n fg_inds = npr.choice(fg_inds, size=int(rois_per_image), replace=to_replace)\r\n fg_rois_per_image = rois_per_image\r\n elif bg_inds.size > 0:\r\n # 만약 positive가 없을 경우 negative로 채움\r\n to_replace = bg_inds.size < rois_per_image\r\n bg_inds = npr.choice(bg_inds, size=int(rois_per_image), replace=to_replace)\r\n fg_rois_per_image = 0\r\n else:\r\n import pdb\r\n pdb.set_trace()\r\n keep_inds = np.append(fg_inds, bg_inds)\r\n #labels은 300개의 target ROI에 대한 class 들\r\n labels = labels[keep_inds]\r\n # positive anchor가 아닌 label은 0으로 바꿈\r\n # 0 = background\r\n labels[int(fg_rois_per_image):] = 0\r\n # 모든 roi 중 bath에 들어가는 256 roi\r\n rois = rois[keep_inds]\r\n roi_scores = rois_score[keep_inds]\r\n # 256개 roi, gt_boxes는 x1, x2, y1 ,y2\r\n # 현재 bbox는 좌표 값임\r\n # bbox_target_data = compute_targets(rois[:, 1:5], gt_boxes[gt_assignment[keep_inds], :], labels)\r\n bbox_target_data = compute_targets(rois, gt_boxes[gt_assignment[keep_inds], :], labels)\r\n\r\n bbox_targets, bbox_inside_weights = _get_bbox_regression_labels(bbox_target_data, num_classes)\r\n return labels, rois, roi_scores, bbox_targets, bbox_inside_weights\r\n\r\n\r\ndef compute_targets(ex_rois, gt_rois, labels):\r\n\r\n assert ex_rois.shape[0] == gt_rois.shape[0]\r\n assert ex_rois.shape[1] == 4\r\n assert gt_rois.shape[1] == 4\r\n\r\n targets = bbox_transform(ex_rois, gt_rois)\r\n # 이것은 아직 모르겠당\r\n if cfg.bbox_nor_target_pre:\r\n targets = ((targets - np.array(cfg.bbox_nor_mean)) / np.array(cfg.bbox_nor_stdv))\r\n return np.hstack((labels[:, np.newaxis], targets)).astype(np.float32, copy=False)\r\n\r\n\r\ndef bbox_transform(ex_rois, gt_rois):\r\n \"\"\" convert the coordinate of gt_rois into targets form using ex_rois \"\"\"\r\n\r\n ex_widths = ex_rois[:, 2] - ex_rois[:, 0] + 1.0\r\n ex_heights = ex_rois[:, 3] - ex_rois[:, 1] + 1.0\r\n ex_ctr_x = ex_rois[:, 0] + 0.5 * ex_widths\r\n ex_ctr_y = ex_rois[:, 1] + 0.5 * ex_heights\r\n\r\n gt_widths = gt_rois[:, 2] - gt_rois[:, 0] + 1.0\r\n gt_heights = gt_rois[:, 3] - gt_rois[:, 1] + 1.0\r\n gt_ctr_x = gt_rois[:, 0] + 0.5 * gt_widths\r\n gt_ctr_y = gt_rois[:, 1] + 0.5 * gt_heights\r\n\r\n targets_dx = (gt_ctr_x - ex_ctr_x) / ex_widths\r\n targets_dy = (gt_ctr_y - ex_ctr_y) / ex_heights\r\n targets_dw = np.log(gt_widths / ex_widths)\r\n targets_dh = np.log(gt_heights / ex_heights)\r\n\r\n targets = np.vstack(\r\n (targets_dx, targets_dy, targets_dw, targets_dh)).transpose()\r\n return targets\r\n"
] | [
[
"tensorflow.concat",
"tensorflow.control_dependencies",
"tensorflow.stack",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.image.non_max_suppression",
"tensorflow.GPUOptions",
"tensorflow.train.AdamOptimizer",
"tensorflow.to_int32",
"tensorflow.summary.scalar",
"tensorflow.py_func",
"tensorflow.Graph",
"tensorflow.layers.batch_normalization",
"tensorflow.Variable",
"tensorflow.get_collection",
"tensorflow.layers.dense",
"tensorflow.squeeze",
"tensorflow.train.exponential_decay",
"tensorflow.subtract",
"tensorflow.gather",
"tensorflow.add",
"tensorflow.to_float",
"tensorflow.Session",
"numpy.float32",
"tensorflow.train.Saver",
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.argmax",
"tensorflow.random_normal_initializer",
"tensorflow.layers.conv2d",
"tensorflow.shape",
"tensorflow.less",
"tensorflow.pow",
"tensorflow.placeholder",
"tensorflow.exp",
"tensorflow.global_variables_initializer",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.summary.merge_all",
"tensorflow.nn.relu",
"tensorflow.layers.flatten",
"tensorflow.nn.softmax",
"tensorflow.summary.FileWriter",
"tensorflow.not_equal",
"tensorflow.slice",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.layers.max_pooling2d",
"tensorflow.log",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.variable_scope",
"tensorflow.abs"
],
[
"numpy.hstack",
"numpy.log",
"numpy.vstack",
"numpy.round",
"numpy.append",
"numpy.array",
"numpy.where",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
featherineaugustus/Traffic-Flow-Prediction | [
"d49a74795f61c4ae47b6559b68a555c5f12b92a8"
] | [
"main_forcasting.py"
] | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 26 09:40:28 2022\r\n\r\n@author: Featherine\r\n\"\"\"\r\n\r\nimport pandas as pd\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.dates as md\r\n\r\nimport numpy as np\r\n\r\nimport sklearn\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\nfrom sklearn.preprocessing import scale\r\nfrom sklearn.feature_selection import RFE\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.pipeline import make_pipeline\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\n\r\n\r\ndf = pd.read_csv('features - Final.csv')\r\ndf = df.fillna(0)\r\n\r\n# df = df[0:48]\r\n\r\ndf['DateTime'] = pd.to_datetime(df['DateTime'], format='%Y-%m-%d %H:%M:%S')\r\n\r\n\r\n# Get average per hour\r\ndf['hour'] = df['DateTime'].dt.hour\r\n# df[['1006', 'Temp']] = df[['1006', 'Temp']].groupby(df['hour']).transform('mean')\r\n\r\ndf = df.drop(['DateTime'], axis=1)\r\n\r\n\r\ny = np.array(df['1006'])\r\nX = np.array(df['hour']).reshape((-1,1))\r\n\r\n\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, \r\n train_size = 0.7, \r\n test_size = 0.3, \r\n random_state = 10)\r\nprint(X_train.shape, y_train.shape)\r\nprint(X_test.shape, y_test.shape)\r\n\r\nscaler = MinMaxScaler()\r\nX_train = scaler.fit_transform(X_train)\r\nX_test = scaler.transform(X_test)\r\n\r\n\r\ndegrees = [1, 2, 3, 6, 10, 15, 20]\r\n\r\n\r\n\r\ny_train_pred = np.zeros((len(X_train), len(degrees)))\r\ny_test_pred = np.zeros((len(X_test), len(degrees)))\r\n\r\nfor i, degree in enumerate(degrees):\r\n \r\n # make pipeline: create features, then feed them to linear_reg model\r\n model = make_pipeline(PolynomialFeatures(degree), LinearRegression())\r\n model.fit(X_train, y_train)\r\n \r\n # predict on test and train data\r\n # store the predictions of each degree in the corresponding column\r\n y_train_pred[:, i] = model.predict(X_train)\r\n y_test_pred[:, i] = model.predict(X_test)\r\n \r\n \r\n \r\nplt.figure(figsize=(16, 8))\r\n\r\nX_train = scaler.inverse_transform(X_train)\r\nX_test = scaler.inverse_transform(X_test)\r\n\r\ny_max = np.max(y_train)*1.1\r\ny_min = np.min(y_train)*0.9\r\n\r\n# train data\r\nplt.subplot(121)\r\nplt.scatter(X_train, y_train)\r\n# plt.yscale('log')\r\nplt.title(\"Training data\")\r\nfor i, degree in enumerate(degrees):\r\n \r\n dummy = np.concatenate((X_train, y_train_pred[:, i].reshape((-1,1))), axis=1)\r\n dummy = pd.DataFrame(dummy)\r\n dummy = dummy.drop_duplicates(keep='last')\r\n dummy = dummy.sort_values(by=[0])\r\n plt.plot(dummy[0], dummy[1], label=str(degree))\r\n plt.legend(loc='upper left')\r\n plt.ylim([y_min, y_max])\r\n \r\n# test data\r\nplt.subplot(122)\r\nplt.scatter(X_test, y_test)\r\n# plt.yscale('log')\r\nplt.title(\"Testing data\")\r\nfor i, degree in enumerate(degrees): \r\n \r\n dummy = np.concatenate((X_test, y_test_pred[:, i].reshape((-1,1))), axis=1)\r\n dummy = pd.DataFrame(dummy)\r\n dummy = dummy.drop_duplicates(keep='last')\r\n dummy = dummy.sort_values(by=[0])\r\n plt.plot(dummy[0], dummy[1], label=str(degree))\r\n plt.legend(loc='upper left')\r\n plt.ylim([y_min, y_max])\r\n \r\nplt.savefig('Forcasting_Time.png')\r\n \r\n# compare r2 for train and test sets (for all polynomial fits)\r\nprint(\"R-squared values: \\n\")\r\n\r\nfor i, degree in enumerate(degrees):\r\n train_r2 = round(sklearn.metrics.r2_score(y_train, y_train_pred[:, i]), 2)\r\n test_r2 = round(sklearn.metrics.r2_score(y_test, y_test_pred[:, i]), 2)\r\n print(\"Polynomial degree {0}: train score={1}, test score={2}\".format(degree, \r\n train_r2, \r\n test_r2))\r\n \r\ninput_hour = 5\r\ninput_hour = np.array(input_hour).reshape((-1,1))\r\ninput_hour = scaler.transform(input_hour)\r\npredict = model.predict(input_hour)\r\nprint('The predicted number of cars is: ' + str(predict))\r\n\r\n"
] | [
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"pandas.to_datetime",
"sklearn.metrics.r2_score",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"numpy.min",
"matplotlib.pyplot.ylim",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.savefig",
"pandas.DataFrame",
"sklearn.preprocessing.PolynomialFeatures",
"numpy.max",
"matplotlib.pyplot.subplot",
"sklearn.linear_model.LinearRegression",
"numpy.array",
"sklearn.preprocessing.MinMaxScaler",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
MKLab-ITI/pygrank | [
"dc1793374d11f0b51c86a92cd5f40b34d5eb42ae"
] | [
"pygrank/core/backend/numpy.py"
] | [
"import numpy as np\nfrom numpy import abs, sum, exp, log, copy, repeat, min, max, dot, mean, diag, ones\nfrom scipy.sparse import eye\n\n\ndef backend_init():\n pass\n\n\ndef graph_dropout(M, _):\n return M\n\n\ndef separate_cols(x):\n return [x[:, col_num] for col_num in range(x.shape[1])]\n\n\ndef combine_cols(cols):\n return np.column_stack(cols)\n\n\ndef backend_name():\n return \"numpy\"\n\n\ndef scipy_sparse_to_backend(M):\n return M\n\n\ndef to_array(obj, copy_array=False):\n if isinstance(obj, np.ndarray):\n if copy_array:\n return np.copy(obj).ravel()\n if len(obj.shape) > 1:\n return obj.ravel()\n return obj\n return np.array(obj)\n\n\ndef to_primitive(obj):\n return np.array(obj)\n\n\ndef is_array(obj):\n return isinstance(obj, list) or isinstance(obj, np.ndarray)\n\n\ndef self_normalize(obj):\n np_sum = obj.__abs__().sum()\n if np_sum != 0:\n obj = obj / np_sum\n return obj\n\n\ndef conv(signal, M):\n return signal * M\n\n\ndef length(x):\n if isinstance(x, np.ndarray):\n if len(x.shape) > 1:\n return x.shape[0]*x.shape[1]\n return x.shape[0]\n return len(x)\n\n\ndef degrees(M):\n return np.asarray(sum(M, axis=1)).ravel()\n\n\ndef filter_out(x, exclude):\n return x[exclude == 0]\n\n\ndef epsilon():\n #return np.finfo(np.float32).eps\n return np.finfo(float).eps\n"
] | [
[
"numpy.finfo",
"numpy.copy",
"numpy.column_stack",
"numpy.array",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hiflyin/Advanced-Feature-Processing-Lib | [
"f14df8d5cdb10f6a166e08353f3830233a22447b"
] | [
"feature_stuff/categorical.py"
] | [
"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import LabelEncoder\nimport gc\n\n\ndef encode_labels(df, cols = None):\n '''\n Inputs:\n df: a pandas dataframe containing the column for which to calculate target encoding (categ_col)\n cols: all columns' names for which to do label encoding . If is None (default) then all object columns are taken.\n Output: df with cols replaced the coresponding label encodings while maintaining all existing None values at their positions.\n '''\n\n le = LabelEncoder()\n for col in cols:\n # pick some random value from the col - will make it null back at the end anyway\n null_replacement = df[col].values[0]\n # save col null positions and set ones for the rest\n nan_col = np.array([1 if not pd.isnull(x) else x for x in df[col]])\n # replace nulls in the original array, and fit on it\n a = np.array([x if not pd.isnull(x) else null_replacement for x in df[col]])\n le.fit(a)\n # transform the data and add the nulls back\n df[col] = le.transform(a) * nan_col\n\n return(df)\n\n\ndef add_dummies(df, cols = None, drop = True):\n '''\n Inputs:\n df: a pandas Dataframe containing the columns to add dummies for.\n cols: a list or array of the names of the columns to dummy. If is None (default) then all object columns are taken.\n drop: if the categorical columns are to be dropped after adding the dummies. Default = True.\n\n Output: the dataframe with the added dummies. NaNs will be ignored rather than considered a distinct category.\n\n TO DO: TypeErrors?\n '''\n\n if cols is None:\n cols = [col for col in df.columns if df[col].dtype == 'object']\n\n for col in cols:\n dummies = pd.get_dummies(df[col], prefix=col).astype(np.int8)\n df = pd.concat([df, dummies], axis=1)\n if drop:\n df.drop([col], inplace=True, axis=1)\n\n del dummies\n gc.collect()\n return(df)\n\n\ndef add_dummies_selected_cat(col, df, categs, drop = True):\n '''\n Inputs:\n col: the name of column to be considered.\n df: a pandas Dataframe containing the columns to add dummies for.\n categs: the names of the categories in col to add dummies for.\n drop: if the categorical columns are to be dropped after adding the dummies. Default = True.\n\n Output: the dataframe with the added dummies. NaNs will be ignored rather than considered a distinct category.\n '''\n\n aux = df[col]\n df.loc[~df[col].isin(categs), col] = None\n dummies = pd.get_dummies(df[col], prefix=col).astype(np.int8)\n df = pd.concat([df, dummies], axis=1)\n\n if drop:\n df.drop([col], inplace=True, axis=1)\n else:\n df[col] = aux\n del dummies\n gc.collect()\n return(df)\n\n\n"
] | [
[
"pandas.concat",
"sklearn.preprocessing.LabelEncoder",
"pandas.isnull",
"pandas.get_dummies"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
mikepm35/biopython | [
"120616cf0d28cb8e581898afd6604e5a2065a137"
] | [
"Tests/test_SVDSuperimposer.py"
] | [
"# Copyright 2017 by Maximilian Greil. All rights reserved.\n# This code is part of the Biopython distribution and governed by its\n# license. Please see the LICENSE file that should have been included\n# as part of this package.\n\n\"\"\"Tests for SVDSuperimposer module.\"\"\"\n\nimport unittest\n\ntry:\n from numpy import array\n from numpy import dot # missing in old PyPy's micronumpy\n from numpy import array_equal\n from numpy import around\n from numpy.linalg import svd, det # Missing in PyPy 2.0 numpypy\nexcept ImportError:\n from Bio import MissingPythonDependencyError\n raise MissingPythonDependencyError(\n \"Install NumPy if you want to use Bio.SVDSuperimposer.\")\n\nfrom Bio.SVDSuperimposer import SVDSuperimposer\n\n\nclass SVDSuperimposerTest(unittest.TestCase):\n\n def setUp(self):\n self.x = array([[51.65, -1.90, 50.07],\n [50.40, -1.23, 50.65],\n [50.68, -0.04, 51.54],\n [50.22, -0.02, 52.85]])\n\n self.y = array([[51.30, -2.99, 46.54],\n [51.09, -1.88, 47.58],\n [52.36, -1.20, 48.03],\n [52.71, -1.18, 49.38]])\n\n self.sup = SVDSuperimposer()\n self.sup.set(self.x, self.y)\n\n def test_get_init_rms(self):\n x = array([[1.19, 1.28, 1.37],\n [1.46, 1.55, 1.64],\n [1.73, 1.82, 1.91]])\n y = array([[1.91, 1.82, 1.73],\n [1.64, 1.55, 1.46],\n [1.37, 1.28, 1.19]])\n self.sup.set(x, y)\n self.assertIsNone(self.sup.init_rms)\n init_rms = 0.8049844719\n self.assertTrue(\n float('%.3f' % self.sup.get_init_rms()), float('%.3f' % init_rms))\n\n def test_oldTest(self):\n self.assertTrue(\n array_equal(around(self.sup.reference_coords, decimals=3), around(self.x, decimals=3)))\n self.assertTrue(\n array_equal(around(self.sup.coords, decimals=3), around(self.y, decimals=3)))\n self.assertIsNone(self.sup.rot)\n self.assertIsNone(self.sup.tran)\n self.assertIsNone(self.sup.rms)\n self.assertIsNone(self.sup.init_rms)\n\n self.sup.run()\n self.assertTrue(\n array_equal(around(self.sup.reference_coords, decimals=3), around(self.x, decimals=3)))\n self.assertTrue(\n array_equal(around(self.sup.coords, decimals=3), around(self.y, decimals=3)))\n rot = array([[0.68304983, 0.53664371, 0.49543563],\n [-0.52277295, 0.83293229, -0.18147242],\n [-0.51005037, -0.13504564, 0.84947707]])\n tran = array([38.78608157, -20.65451334, -15.42227366])\n self.assertTrue(\n array_equal(around(self.sup.rot, decimals=3), around(rot, decimals=3)))\n self.assertTrue(\n array_equal(around(self.sup.tran, decimals=3), around(tran, decimals=3)))\n self.assertIsNone(self.sup.rms)\n self.assertIsNone(self.sup.init_rms)\n\n rms = 0.00304266526014\n self.assertEqual(\n float('%.3f' % self.sup.get_rms()), float('%.3f' % rms))\n\n rot_get, tran_get = self.sup.get_rotran()\n self.assertTrue(\n array_equal(around(rot_get, decimals=3), around(rot, decimals=3)))\n self.assertTrue(\n array_equal(around(tran_get, decimals=3), around(tran, decimals=3)))\n\n y_on_x1 = dot(self.y, rot) + tran\n y_x_solution = array(\n [[5.16518846e+01, -1.90018270e+00, 5.00708397e+01],\n [5.03977138e+01, -1.22877050e+00, 5.06488200e+01],\n [5.06801788e+01, -4.16095666e-02, 5.15368866e+01],\n [5.02202228e+01, -1.94372374e-02, 5.28534537e+01]])\n self.assertTrue(\n array_equal(around(y_on_x1, decimals=3), around(y_x_solution, decimals=3)))\n\n y_on_x2 = self.sup.get_transformed()\n self.assertTrue(\n array_equal(around(y_on_x2, decimals=3), around(y_x_solution, decimals=3)))\n\n\nif __name__ == \"__main__\":\n runner = unittest.TextTestRunner(verbosity=2)\n unittest.main(testRunner=runner)\n"
] | [
[
"numpy.dot",
"numpy.array",
"numpy.around"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Alanapiereid/Streamlit_KERAS_LSTM_Fake_News | [
"4e2b88eb7b9f13ccf95d87a70afb946211db0059"
] | [
"Streamlit_app.py"
] | [
"import streamlit as st\nimport tensorflow as tf\nfrom tensorflow.keras.models import model_from_json\nfrom tensorflow.keras.losses import BinaryCrossentropy\nimport numpy as np\nfrom tensorflow.keras.preprocessing import text\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.optimizers import Adam\nfrom keras.models import load_model\nfrom keras import backend as K\nimport pickle\n\n\nclass Predict_Bias:\n def __init__(self):\n self.new_text = None\n\n @st.cache(allow_output_mutation=True)\n def get_model(self):\n saved_model = load_model(\"fake_n_model.h5\") \n return saved_model\n \n def preprocess(self, text):\n new_text = text\n num_d_words = 50000\n maxlen = 300\n with open('tokenizer.pickle', 'rb') as handle:\n tokenizer = pickle.load(handle)\n new_text = tokenizer.texts_to_sequences(new_text)\n self.new_text = pad_sequences(new_text, maxlen=maxlen)\n #preprocessed = pad_sequences(new_text, maxlen=maxlen)\n return self.new_text\n\n def get_pred(self, text):\n model = self.get_model()\n pred = model.predict(self.preprocess(text))\n if pred >= 0.5:\n return str(f'This text is biased news with {pred[0][0]} certainty.')\n else:\n return str(f'This text is balanced news with {100 - pred[0][0]} certainty')\n\n\n\n\nif __name__ == '__main__':\n st.title(\"Biased News Article Predictor\")\n st.text(\"By Alan Reid | https://github.com/Alanapiereid\")\n st.text(\"Trained on Keras LSTM\")\n st.header(\"Is your news biased?\")\n text = st.text_input('Paste a news article into the field below to get a prediction')\n text_array = [text] \n trigger = st.button('Get Prediction')\n model = Predict_Bias()\n if trigger:\n result = model.get_pred(text_array)\n st.text(result)\n\n"
] | [
[
"tensorflow.keras.preprocessing.sequence.pad_sequences"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
brooklynbagel/Voice-Cloning-App | [
"6e0034dc0b4e21f669d28753b5f30b32cca382ad"
] | [
"glow.py"
] | [
"# *****************************************************************************\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the NVIDIA CORPORATION nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# *****************************************************************************\n\n# This file has been modified to enable CPU inference!\n\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\n\ndef fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):\n n_channels_int = n_channels[0]\n in_act = input_a + input_b\n t_act = torch.tanh(in_act[:, :n_channels_int, :])\n s_act = torch.sigmoid(in_act[:, n_channels_int:, :])\n acts = t_act * s_act\n return acts\n\n\nclass WaveGlowLoss(torch.nn.Module):\n def __init__(self, sigma=1.0):\n super(WaveGlowLoss, self).__init__()\n self.sigma = sigma\n\n def forward(self, model_output):\n z, log_s_list, log_det_W_list = model_output\n for i, log_s in enumerate(log_s_list):\n if i == 0:\n log_s_total = torch.sum(log_s)\n log_det_W_total = log_det_W_list[i]\n else:\n log_s_total = log_s_total + torch.sum(log_s)\n log_det_W_total += log_det_W_list[i]\n\n loss = torch.sum(z * z) / (2 * self.sigma * self.sigma) - log_s_total - log_det_W_total\n return loss / (z.size(0) * z.size(1) * z.size(2))\n\n\nclass Invertible1x1Conv(torch.nn.Module):\n \"\"\"\n The layer outputs both the convolution, and the log determinant\n of its weight matrix. If reverse=True it does convolution with\n inverse\n \"\"\"\n\n def __init__(self, c):\n super(Invertible1x1Conv, self).__init__()\n self.conv = torch.nn.Conv1d(c, c, kernel_size=1, stride=1, padding=0, bias=False)\n\n # Sample a random orthonormal matrix to initialize weights\n W = torch.qr(torch.FloatTensor(c, c).normal_())[0]\n\n # Ensure determinant is 1.0 not -1.0\n if torch.det(W) < 0:\n W[:, 0] = -1 * W[:, 0]\n W = W.view(c, c, 1)\n self.conv.weight.data = W\n\n def forward(self, z, reverse=False):\n # shape\n batch_size, group_size, n_of_groups = z.size()\n\n W = self.conv.weight.squeeze()\n\n if reverse:\n if not hasattr(self, \"W_inverse\"):\n # Reverse computation\n W_inverse = W.float().inverse()\n W_inverse = Variable(W_inverse[..., None])\n if z.type() == \"torch.cuda.HalfTensor\":\n W_inverse = W_inverse.half()\n self.W_inverse = W_inverse\n z = F.conv1d(z, self.W_inverse, bias=None, stride=1, padding=0)\n return z\n else:\n # Forward computation\n log_det_W = batch_size * n_of_groups * torch.logdet(W)\n z = self.conv(z)\n return z, log_det_W\n\n\nclass WN(torch.nn.Module):\n \"\"\"\n This is the WaveNet like layer for the affine coupling. The primary difference\n from WaveNet is the convolutions need not be causal. There is also no dilation\n size reset. The dilation only doubles on each layer\n \"\"\"\n\n def __init__(self, n_in_channels, n_mel_channels, n_layers, n_channels, kernel_size):\n super(WN, self).__init__()\n assert kernel_size % 2 == 1\n assert n_channels % 2 == 0\n self.n_layers = n_layers\n self.n_channels = n_channels\n self.in_layers = torch.nn.ModuleList()\n self.res_skip_layers = torch.nn.ModuleList()\n\n start = torch.nn.Conv1d(n_in_channels, n_channels, 1)\n start = torch.nn.utils.weight_norm(start, name=\"weight\")\n self.start = start\n\n # Initializing last layer to 0 makes the affine coupling layers\n # do nothing at first. This helps with training stability\n end = torch.nn.Conv1d(n_channels, 2 * n_in_channels, 1)\n end.weight.data.zero_()\n end.bias.data.zero_()\n self.end = end\n\n cond_layer = torch.nn.Conv1d(n_mel_channels, 2 * n_channels * n_layers, 1)\n self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name=\"weight\")\n\n for i in range(n_layers):\n dilation = 2 ** i\n padding = int((kernel_size * dilation - dilation) / 2)\n in_layer = torch.nn.Conv1d(n_channels, 2 * n_channels, kernel_size, dilation=dilation, padding=padding)\n in_layer = torch.nn.utils.weight_norm(in_layer, name=\"weight\")\n self.in_layers.append(in_layer)\n\n # last one is not necessary\n if i < n_layers - 1:\n res_skip_channels = 2 * n_channels\n else:\n res_skip_channels = n_channels\n res_skip_layer = torch.nn.Conv1d(n_channels, res_skip_channels, 1)\n res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name=\"weight\")\n self.res_skip_layers.append(res_skip_layer)\n\n def forward(self, forward_input):\n audio, spect = forward_input\n audio = self.start(audio)\n output = torch.zeros_like(audio)\n n_channels_tensor = torch.IntTensor([self.n_channels])\n\n spect = self.cond_layer(spect)\n\n for i in range(self.n_layers):\n spect_offset = i * 2 * self.n_channels\n acts = fused_add_tanh_sigmoid_multiply(\n self.in_layers[i](audio),\n spect[:, spect_offset : spect_offset + 2 * self.n_channels, :],\n n_channels_tensor,\n )\n\n res_skip_acts = self.res_skip_layers[i](acts)\n if i < self.n_layers - 1:\n audio = audio + res_skip_acts[:, : self.n_channels, :]\n output = output + res_skip_acts[:, self.n_channels :, :]\n else:\n output = output + res_skip_acts\n\n return self.end(output)\n\n\nclass WaveGlow(torch.nn.Module):\n def __init__(self, n_mel_channels, n_flows, n_group, n_early_every, n_early_size, WN_config):\n super(WaveGlow, self).__init__()\n\n self.upsample = torch.nn.ConvTranspose1d(n_mel_channels, n_mel_channels, 1024, stride=256)\n assert n_group % 2 == 0\n self.n_flows = n_flows\n self.n_group = n_group\n self.n_early_every = n_early_every\n self.n_early_size = n_early_size\n self.WN = torch.nn.ModuleList()\n self.convinv = torch.nn.ModuleList()\n\n n_half = int(n_group / 2)\n\n # Set up layers with the right sizes based on how many dimensions\n # have been output already\n n_remaining_channels = n_group\n for k in range(n_flows):\n if k % self.n_early_every == 0 and k > 0:\n n_half = n_half - int(self.n_early_size / 2)\n n_remaining_channels = n_remaining_channels - self.n_early_size\n self.convinv.append(Invertible1x1Conv(n_remaining_channels))\n self.WN.append(WN(n_half, n_mel_channels * n_group, **WN_config))\n self.n_remaining_channels = n_remaining_channels # Useful during inference\n\n def forward(self, forward_input):\n \"\"\"\n forward_input[0] = mel_spectrogram: batch x n_mel_channels x frames\n forward_input[1] = audio: batch x time\n \"\"\"\n spect, audio = forward_input\n\n # Upsample spectrogram to size of audio\n spect = self.upsample(spect)\n assert spect.size(2) >= audio.size(1)\n if spect.size(2) > audio.size(1):\n spect = spect[:, :, : audio.size(1)]\n\n spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3)\n spect = spect.contiguous().view(spect.size(0), spect.size(1), -1).permute(0, 2, 1)\n\n audio = audio.unfold(1, self.n_group, self.n_group).permute(0, 2, 1)\n output_audio = []\n log_s_list = []\n log_det_W_list = []\n\n for k in range(self.n_flows):\n if k % self.n_early_every == 0 and k > 0:\n output_audio.append(audio[:, : self.n_early_size, :])\n audio = audio[:, self.n_early_size :, :]\n\n audio, log_det_W = self.convinv[k](audio)\n log_det_W_list.append(log_det_W)\n\n n_half = int(audio.size(1) / 2)\n audio_0 = audio[:, :n_half, :]\n audio_1 = audio[:, n_half:, :]\n\n output = self.WN[k]((audio_0, spect))\n log_s = output[:, n_half:, :]\n b = output[:, :n_half, :]\n audio_1 = torch.exp(log_s) * audio_1 + b\n log_s_list.append(log_s)\n\n audio = torch.cat([audio_0, audio_1], 1)\n\n output_audio.append(audio)\n return torch.cat(output_audio, 1), log_s_list, log_det_W_list\n\n def infer(self, spect, sigma=1.0):\n spect = self.upsample(spect)\n # trim conv artifacts. maybe pad spec to kernel multiple\n time_cutoff = self.upsample.kernel_size[0] - self.upsample.stride[0]\n spect = spect[:, :, :-time_cutoff]\n\n spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3)\n spect = spect.contiguous().view(spect.size(0), spect.size(1), -1).permute(0, 2, 1)\n\n if spect.type() == \"torch.cuda.HalfTensor\":\n audio = torch.cuda.HalfTensor(spect.size(0), self.n_remaining_channels, spect.size(2)).normal_()\n else:\n if torch.cuda.is_available():\n audio = torch.cuda.FloatTensor(spect.size(0), self.n_remaining_channels, spect.size(2)).normal_()\n else:\n audio = torch.FloatTensor(spect.size(0), self.n_remaining_channels, spect.size(2)).normal_()\n\n audio = torch.autograd.Variable(sigma * audio)\n\n for k in reversed(range(self.n_flows)):\n n_half = int(audio.size(1) / 2)\n audio_0 = audio[:, :n_half, :]\n audio_1 = audio[:, n_half:, :]\n\n output = self.WN[k]((audio_0, spect))\n\n s = output[:, n_half:, :]\n b = output[:, :n_half, :]\n audio_1 = (audio_1 - b) / torch.exp(s)\n audio = torch.cat([audio_0, audio_1], 1)\n\n audio = self.convinv[k](audio, reverse=True)\n\n if k % self.n_early_every == 0 and k > 0:\n if spect.type() == \"torch.cuda.HalfTensor\":\n z = torch.cuda.HalfTensor(spect.size(0), self.n_early_size, spect.size(2)).normal_()\n else:\n if torch.cuda.is_available():\n z = torch.cuda.FloatTensor(spect.size(0), self.n_early_size, spect.size(2)).normal_()\n else:\n z = torch.FloatTensor(spect.size(0), self.n_early_size, spect.size(2)).normal_()\n\n audio = torch.cat((sigma * z, audio), 1)\n\n audio = audio.permute(0, 2, 1).contiguous().view(audio.size(0), -1).data\n return audio\n\n @staticmethod\n def remove_weightnorm(model):\n waveglow = model\n for WN in waveglow.WN:\n WN.start = torch.nn.utils.remove_weight_norm(WN.start)\n WN.in_layers = remove(WN.in_layers)\n WN.cond_layer = torch.nn.utils.remove_weight_norm(WN.cond_layer)\n WN.res_skip_layers = remove(WN.res_skip_layers)\n return waveglow\n\n\ndef remove(conv_list):\n new_conv_list = torch.nn.ModuleList()\n for old_conv in conv_list:\n old_conv = torch.nn.utils.remove_weight_norm(old_conv)\n new_conv_list.append(old_conv)\n return new_conv_list\n"
] | [
[
"torch.sigmoid",
"torch.cat",
"torch.nn.utils.weight_norm",
"torch.nn.ModuleList",
"torch.IntTensor",
"torch.zeros_like",
"torch.det",
"torch.nn.utils.remove_weight_norm",
"torch.nn.functional.conv1d",
"torch.tanh",
"torch.sum",
"torch.logdet",
"torch.exp",
"torch.FloatTensor",
"torch.cuda.is_available",
"torch.nn.Conv1d",
"torch.nn.ConvTranspose1d",
"torch.autograd.Variable"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lzcn/torchutils | [
"8dc78ddcde72f27758e9774f3d1f5f6172e1a5e9"
] | [
"tests/torchutils/io/test_saver.py"
] | [
"import os\n\nimport torch.nn as nn\nfrom torchutils.io import ModelSaver\n\nmodel = nn.Linear(1, 1)\n\n\ndef test_saver_epoch(tmp_path):\n n_saved = 5\n num_epochs = 10\n saver = ModelSaver(tmp_path, filename_prefix=\"net\", score_name=\"score\", n_saved=n_saved)\n for epoch in range(num_epochs):\n score = 1.0 * epoch\n saver.save(model, 1.0 * epoch, epoch)\n d = tmp_path / f\"net_score_{score:.4f}_epoch_{epoch}.pt\"\n assert os.path.isfile(d)\n for epoch in range(num_epochs - n_saved):\n score = 1.0 * epoch\n d = tmp_path / f\"net_score_{score:.4f}_epoch_{epoch}.pt\"\n assert not os.path.isfile(d)\n assert saver.last_checkpoint == f\"net_score_{num_epochs-1:.4f}_epoch_{num_epochs-1}.pt\"\n"
] | [
[
"torch.nn.Linear"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
aniqueakhtar/PointCloudUpsampling | [
"21fcb829e2ed0a1ade5e9f887f4a6231efa6425a"
] | [
"pre_post_processing/test_results_GPU.py"
] | [
"import glob\nimport open3d as o3d\nimport numpy as np\nimport os\nfrom utils.pc_error_wrapper import pc_error\nfrom pytorch3d.loss import chamfer_distance\nimport torch\nimport pandas as pd\n\norig_pc = '/home/anique/Upsampling_3/Data/8i_test/orig/'\ninput_pc = '../Data/8i_test/8x/'\noutput_pc = 'results/8x_0x_ks5/'\ncsv_name = 'test_8x_ks5.csv'\n\nfiles = sorted(glob.glob(input_pc+'*.ply'))\nreso = 1024\n\ndevice = torch.device('cuda')\nfor i, m in enumerate(files):\n print(\"!!!!!!!!==========!!!!!!!!!! FILE NUMBER: \", i)\n results = {}\n file_name = os.path.basename(m)\n pcd = o3d.io.read_point_cloud(m)\n xyz_in = np.asarray(pcd.points)\n infile = m\n \n pcd = o3d.io.read_point_cloud(output_pc + file_name)\n xyz_out = np.asarray(pcd.points)\n outfile = output_pc + file_name\n \n GTfile = orig_pc + file_name\n pcd = o3d.io.read_point_cloud(GTfile)\n xyz_GT = np.asarray(pcd.points)\n \n \n print(\"Number of points in input point cloud : \", xyz_in.shape[0])\n print(\"Number of points in output rec point cloud : \", xyz_out.shape[0])\n print(\"Number of points in GT point cloud : \", xyz_GT.shape[0])\n \n \n print('========== Measuring PSNR')\n \n pc_error_metrics_in = pc_error(infile1=GTfile, infile2=infile, res=reso)\n print(pc_error_metrics_in[\"mseF,PSNR (p2point)\"][0])\n \n pc_error_metrics_out = pc_error(infile1=GTfile, infile2=outfile, res=reso)\n print(pc_error_metrics_out[\"mseF,PSNR (p2point)\"][0])\n \n print('========== Measuring CD')\n \n pc_out = torch.tensor(xyz_out).unsqueeze(0).float().to(device)\n pc_in = torch.tensor(xyz_in).unsqueeze(0).float().to(device)\n pc_GT = torch.tensor(xyz_GT).unsqueeze(0).float().to(device)\n \n loss_chamfer_out, _ = chamfer_distance(pc_GT, pc_out)\n print(loss_chamfer_out)\n\n loss_chamfer_in, _ = chamfer_distance(pc_GT, pc_in)\n print(loss_chamfer_in)\n \n \n results[\"MSE_F_in\"] = pc_error_metrics_in[\"mseF (p2point)\"][0]\n results[\"MSE_F_out\"] = pc_error_metrics_out[\"mseF (p2point)\"][0]\n results[\"MSE_F, PSNR_in\"] = pc_error_metrics_in[\"mseF,PSNR (p2point)\"][0]\n results[\"MSE_F, PSNR_out\"] = pc_error_metrics_out[\"mseF,PSNR (p2point)\"][0]\n results[\"Hausdorff_F_in\"] = pc_error_metrics_in[\"h. (p2point)\"][0]\n results[\"Hausdorff_F_out\"] = pc_error_metrics_out[\"h. (p2point)\"][0]\n results[\"Hausdorff_F, PSNR_in\"] = pc_error_metrics_in[\"h.,PSNR (p2point)\"][0]\n results[\"Hausdorff_F, PSNR_out\"] = pc_error_metrics_out[\"h.,PSNR (p2point)\"][0]\n results[\"Chamfer_in\"] = loss_chamfer_in.cpu().numpy()\n results[\"Chamfer_out\"] = loss_chamfer_out.cpu().numpy()\n \n results = pd.DataFrame([results])\n \n if i == 0:\n all_results = results.copy(deep=True)\n else:\n all_results = all_results.append(results, ignore_index=True)\n \nos.system('rm *.ply')\nall_results.to_csv(csv_name, index=False)\n\n"
] | [
[
"torch.device",
"numpy.asarray",
"pandas.DataFrame",
"torch.tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
mackelab/pyloric | [
"ff0fa2f0838e732f83823a7ff9c4d19e89483994"
] | [
"pyloric/utils/circuit_parameters.py"
] | [
"import numpy as np\nfrom typing import Dict, Tuple, Optional, List\nimport pandas as pd\nfrom torch import Tensor\nfrom typing import Union\n\n\ndef create_neurons(neuron_list):\n prinz_neurons = {\n \"LP\": {\n \"LP_0\": [100, 0, 8, 40, 5, 75, 0.05, 0.02], # this3 g_CaS g_A g_Kd\n \"LP_1\": [100, 0, 6, 30, 5, 50, 0.05, 0.02], # this2 # KCa, H # this3\n \"LP_2\": [100, 0, 10, 50, 5, 100, 0.0, 0.03],\n \"LP_3\": [100, 0, 4, 20, 0, 25, 0.05, 0.03],\n \"LP_4\": [100, 0, 6, 30, 0, 50, 0.03, 0.02], # this2\n },\n \"PY\": {\n \"PY_1\": [200, 7.5, 0, 50, 0, 75, 0.05, 0.0],\n # this3 # this3 g_Na, g_CaT, g_CaS\n \"PY_0\": [100, 2.5, 2, 50, 0, 125, 0.05, 0.01], # this3\n \"PY_3\": [400, 2.5, 2, 50, 0, 75, 0.05, 0.0],\n # this3 # this3 g_leak, g_Kd, g_Na\n \"PY_5\": [500, 2.5, 2, 40, 0, 125, 0.0, 0.02], # this2 # g_H, g_leak\n \"PY_2\": [200, 10.0, 0, 50, 0, 100, 0.03, 0.0], # this3 # CaT Kd H\n \"PY_4\": [500, 2.5, 2, 40, 0, 125, 0.01, 0.03], # this2\n },\n \"PM\": {\n \"PM_0\": [400, 2.5, 6, 50, 10, 100, 0.01, 0.0], # this2 g_Na, KCa\n \"PM_3\": [200, 5.0, 4, 40, 5, 125, 0.01, 0.0], # this3 CaT, g_A, g_Kd\n \"PM_4\": [300, 2.5, 2, 10, 5, 125, 0.01, 0.0],\n \"PM_1\": [100, 2.5, 6, 50, 5, 100, 0.01, 0.0], # this2\n \"PM_2\": [200, 2.5, 4, 50, 5, 50, 0.01, 0.0], # this3\n },\n }\n # Note (PM_0 or PM_1) / (LP_2) / (PY_0) is figure 5a in Prinz 2004.\n # Note (PM_4) / (LP_3) / (PY_4) is figure 5b in Prinz 2004.\n\n ret = []\n for n in neuron_list:\n membrane_area = np.asarray(n[2], dtype=np.float64)\n pn = np.asarray(prinz_neurons[n[0]][n[1]], dtype=np.float64)\n neuron = pn * membrane_area\n ret.append(neuron)\n return np.asarray(ret)\n\n\ndef membrane_conductances_replaced_with_defaults(circuit_parameters, defaults_dict):\n default_neurons = create_neurons(defaults_dict[\"membrane_gbar\"])\n default_neurons = np.reshape(default_neurons, (1, 24))\n type_names, cond_names = select_names()\n type_names = type_names[:24]\n cond_names = cond_names[:24]\n default_neurons_pd = pd.DataFrame(default_neurons, columns=[type_names, cond_names])\n for tn, cn in zip(type_names, cond_names):\n if (tn, cn) in circuit_parameters:\n default_neurons_pd.loc[0][tn, cn] = circuit_parameters[tn, cn] * 0.628e-3\n return default_neurons_pd\n\n\ndef synapses_replaced_with_defaults(circuit_parameters, defaults_dict):\n type_names, cond_names = select_names()\n type_names = type_names[24:]\n cond_names = cond_names[24:]\n data_array = []\n for tn, cn in zip(type_names, cond_names):\n if (tn, cn) in circuit_parameters:\n data_array.append(circuit_parameters[tn, cn])\n data_array = np.asarray([data_array])\n default_synapse_values = pd.DataFrame(data_array, columns=[type_names, cond_names])\n return default_synapse_values\n\n\ndef q10s_replaced_with_defaults(circuit_parameters, defaults_dict):\n q10_dict = {\n \"membrane_gbar\": [\n [False, False, False, False, False, False, False, False],\n [False, False, False, False, False, False, False, False],\n [False, False, False, False, False, False, False, False],\n ],\n \"synapses\": [False, False, False, False, False, False, False],\n \"Q10_gbar_mem\": [True, True, True, True, True, True, True, True],\n \"Q10_gbar_syn\": [True, True], # first for glutamate, second for choline\n \"Q10_tau_m\": [True],\n \"Q10_tau_h\": [True],\n \"Q10_tau_CaBuff\": [True],\n \"Q10_tau_syn\": [True, True], # first for glutamate, second for choline\n }\n type_names, cond_names = select_names(q10_dict)\n\n defaults_pd = dict_to_pd(q10_dict, defaults_dict)\n\n for tn, cn in zip(type_names, cond_names):\n if (tn, cn) in circuit_parameters:\n defaults_pd.loc[0][tn, cn] = circuit_parameters[tn, cn]\n\n return defaults_pd\n\n\ndef dict_to_pd(bool_dict, value_dict):\n data = []\n for key in bool_dict.keys():\n for i, entry in enumerate(bool_dict[key]):\n if entry and not isinstance(entry, List):\n data.append(value_dict[key][i])\n data_np = np.asarray([data])\n type_names, cond_names = select_names(bool_dict)\n data_pd = pd.DataFrame(data_np, columns=[type_names, cond_names])\n return data_pd\n\n\ndef build_synapse_q10s(vec):\n \"\"\"From values of gluatemate and choline, build a 7D vector.\"\"\"\n return np.asarray([vec[0], vec[1], vec[0], vec[1], vec[0], vec[0], vec[0]])\n\n\ndef build_conns(params):\n\n # Reversal voltages and dissipation time constants for the synapses, taken from\n # Prinz 2004, p. 1351\n Esglut = -70 # mV\n kminusglut = 40 # ms\n\n Eschol = -80 # mV\n kminuschol = 100 # ms\n\n return np.asarray(\n [\n [1, 0, params[0], Esglut, kminusglut],\n [1, 0, params[1], Eschol, kminuschol],\n [2, 0, params[2], Esglut, kminusglut],\n [2, 0, params[3], Eschol, kminuschol],\n [0, 1, params[4], Esglut, kminusglut],\n [2, 1, params[5], Esglut, kminusglut],\n [1, 2, params[6], Esglut, kminusglut],\n ]\n )\n\n\ndef ensure_array_not_scalar(selector):\n if isinstance(selector, bool) or isinstance(selector, float):\n selector = np.asarray([selector])\n return np.asarray(selector)\n\n\ndef select_names(setup: Dict = {}) -> Tuple[List, np.ndarray]:\n \"\"\"\n Returns the names of all parameters that are selected in the `setup` dictionary.\n \"\"\"\n default_setup = {\n \"membrane_gbar\": [\n [True, True, True, True, True, True, True, True],\n [True, True, True, True, True, True, True, True],\n [True, True, True, True, True, True, True, True],\n ],\n \"synapses\": [True, True, True, True, True, True, True],\n \"Q10_gbar_mem\": [False, False, False, False, False, False, False, False],\n \"Q10_gbar_syn\": [False, False], # first for glutamate, second for choline\n \"Q10_tau_m\": [False],\n \"Q10_tau_h\": [False],\n \"Q10_tau_CaBuff\": [False],\n \"Q10_tau_syn\": [False, False], # first for glutamate, second for choline\n }\n default_setup.update(setup)\n setup = default_setup\n\n gbar = np.asarray([_channel_names()[c] for c in setup[\"membrane_gbar\"]]).flatten()\n syn = _synapse_names()[setup[\"synapses\"]]\n q10_mem_gbar = _q10_mem_gbar_names()[setup[\"Q10_gbar_mem\"]]\n q10_syn_gbar = _q10_syn_gbar_names()[setup[\"Q10_gbar_syn\"]]\n tau_setups = np.concatenate(\n (\n setup[\"Q10_tau_m\"],\n setup[\"Q10_tau_h\"],\n setup[\"Q10_tau_CaBuff\"],\n setup[\"Q10_tau_syn\"],\n )\n )\n q10_tau = _q10_tau_names()[tau_setups]\n\n type_names = [\"AB/PD\"] * sum(setup[\"membrane_gbar\"][0])\n type_names += [\"LP\"] * sum(setup[\"membrane_gbar\"][1])\n type_names += [\"PY\"] * sum(setup[\"membrane_gbar\"][2])\n type_names += [\"Synapses\"] * sum(setup[\"synapses\"])\n type_names += [\"Q10 gbar\"] * (\n sum(setup[\"Q10_gbar_mem\"]) + sum(setup[\"Q10_gbar_syn\"])\n )\n type_names += [\"Q10 tau\"] * (\n sum(setup[\"Q10_tau_m\"])\n + sum(setup[\"Q10_tau_h\"])\n + sum(setup[\"Q10_tau_CaBuff\"])\n + sum(setup[\"Q10_tau_syn\"])\n )\n return type_names, np.concatenate((gbar, syn, q10_mem_gbar, q10_syn_gbar, q10_tau))\n\n\ndef _channel_names():\n return np.asarray([\"Na\", \"CaT\", \"CaS\", \"A\", \"KCa\", \"Kd\", \"H\", \"Leak\"])\n\n\ndef _synapse_names():\n return np.asarray([\"AB-LP\", \"PD-LP\", \"AB-PY\", \"PD-PY\", \"LP-PD\", \"LP-PY\", \"PY-LP\"])\n\n\ndef _q10_mem_gbar_names():\n return np.asarray([\"Na\", \"CaT\", \"CaS\", \"A\", \"KCa\", \"Kd\", \"H\", \"Leak\"])\n\n\ndef _q10_syn_gbar_names():\n return np.asarray([\"Glut\", \"Chol\"])\n\n\ndef _q10_tau_names():\n return np.asarray([\"m\", \"h\", \"CaBuff\", \"Glut\", \"Chol\"])\n\n\ndef to_pyloric_pd(circuit_parameters: Union[Tensor, np.ndarray]):\n \"\"\"\n Take an array and return the pandas DataFrame that can be passed to `simulate()`.\n\n This function will only work if `circuit_parameters` contains the 31 most basic\n parameters (8*3 membrane conductances and 7 synaptic conductances).\n \"\"\"\n columns = (\n (\"AB/PD\", \"Na\"),\n (\"AB/PD\", \"CaT\"),\n (\"AB/PD\", \"CaS\"),\n (\"AB/PD\", \"A\"),\n (\"AB/PD\", \"KCa\"),\n (\"AB/PD\", \"Kd\"),\n (\"AB/PD\", \"H\"),\n (\"AB/PD\", \"Leak\"),\n (\"LP\", \"Na\"),\n (\"LP\", \"CaT\"),\n (\"LP\", \"CaS\"),\n (\"LP\", \"A\"),\n (\"LP\", \"KCa\"),\n (\"LP\", \"Kd\"),\n (\"LP\", \"H\"),\n (\"LP\", \"Leak\"),\n (\"PY\", \"Na\"),\n (\"PY\", \"CaT\"),\n (\"PY\", \"CaS\"),\n (\"PY\", \"A\"),\n (\"PY\", \"KCa\"),\n (\"PY\", \"Kd\"),\n (\"PY\", \"H\"),\n (\"PY\", \"Leak\"),\n (\"Synapses\", \"AB-LP\"),\n (\"Synapses\", \"PD-LP\"),\n (\"Synapses\", \"AB-PY\"),\n (\"Synapses\", \"PD-PY\"),\n (\"Synapses\", \"LP-PD\"),\n (\"Synapses\", \"LP-PY\"),\n (\"Synapses\", \"PY-LP\"),\n )\n\n if isinstance(circuit_parameters, Tensor):\n pd_params = pd.DataFrame(circuit_parameters.detach().numpy(), columns=columns)\n else:\n circuit_parameters = np.asarray(circuit_parameters)\n if circuit_parameters.ndim == 1:\n circuit_parameters = np.asarray([circuit_parameters])\n pd_params = pd.DataFrame(circuit_parameters, columns=columns)\n\n return pd_params\n"
] | [
[
"numpy.asarray",
"numpy.concatenate",
"numpy.reshape",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
BiancaMT25/darts | [
"bb550dede6d8927a45aea0d9f3df53de32a6eee2"
] | [
"darts/metrics/metrics.py"
] | [
"\"\"\"\nMetrics\n-------\n\nSome metrics to compare time series.\n\"\"\"\n\nimport numpy as np\nfrom ..timeseries import TimeSeries\nfrom ..utils import _parallel_apply, _build_tqdm_iterator\nfrom ..utils.statistics import check_seasonality\nfrom ..logging import raise_if_not, get_logger, raise_log\nfrom warnings import warn\nfrom typing import Optional, Callable, Sequence, Union, Tuple\nfrom inspect import signature\nfrom functools import wraps\n\n\nlogger = get_logger(__name__)\n\n\n\"\"\"\nNote: for new metrics added to this module to be able to leverage the two decorators, it is required both having\nthe `actual_series` and `pred_series` parameters, and not having other `Sequence` as args (since these decorators\ndon't “unpack“ parameters different from `actual_series` and `pred_series`). In those cases, the new metric must take\ncare of dealing with Sequence[TimeSeries] and multivariate TimeSeries on its own (See mase() implementation).\n\"\"\"\n\n\ndef multi_ts_support(func):\n \"\"\"\n This decorator further adapts the metrics that took as input two univariate/multivariate `TimeSeries` instances,\n adding support for equally-sized sequences of `TimeSeries` instances. The decorator computes the pairwise metric for\n `TimeSeries` with the same indices, and returns a float value that is computed as a function of all the\n pairwise metrics using a `inter_reduction` subroutine passed as argument to the metric function.\n\n If a 'Sequence[TimeSeries]' is passed as input, this decorator provides also parallelisation of the metric\n evaluation regarding different `TimeSeries` (if the `n_jobs` parameter is not set 1).\n \"\"\"\n\n @wraps(func)\n def wrapper_multi_ts_support(*args, **kwargs):\n actual_series = kwargs['actual_series'] if 'actual_series' in kwargs else args[0]\n pred_series = kwargs['pred_series'] if 'pred_series' in kwargs else args[0] if 'actual_series' in kwargs \\\n else args[1]\n\n n_jobs = kwargs.pop('n_jobs', signature(func).parameters['n_jobs'].default)\n verbose = kwargs.pop('verbose', signature(func).parameters['verbose'].default)\n\n raise_if_not(isinstance(n_jobs, int), \"n_jobs must be an integer\")\n raise_if_not(isinstance(verbose, bool), \"verbose must be a bool\")\n\n actual_series = [actual_series] if not isinstance(actual_series, Sequence) else actual_series\n pred_series = [pred_series] if not isinstance(pred_series, Sequence) else pred_series\n\n raise_if_not(len(actual_series) == len(pred_series),\n \"The two TimeSeries sequences must have the same length.\", logger)\n\n num_series_in_args = int('actual_series' not in kwargs) + int('pred_series' not in kwargs)\n kwargs.pop('actual_series', 0)\n kwargs.pop('pred_series', 0)\n\n iterator = _build_tqdm_iterator(iterable=zip(actual_series, pred_series),\n verbose=verbose,\n total=len(actual_series))\n\n value_list = _parallel_apply(iterator=iterator,\n fn=func,\n n_jobs=n_jobs,\n fn_args=args[num_series_in_args:],\n fn_kwargs=kwargs)\n\n # in case the reduction is not reducing the metrics sequence to a single value, e.g., if returning the\n # np.ndarray of values with the identity function, we must handle the single TS case, where we should\n # return a single value instead of a np.array of len 1\n\n if len(value_list) == 1:\n value_list = value_list[0]\n\n if 'inter_reduction' in kwargs:\n return kwargs['inter_reduction'](value_list)\n else:\n return signature(func).parameters['inter_reduction'].default(value_list)\n\n return wrapper_multi_ts_support\n\n\ndef multivariate_support(func):\n \"\"\"\n This decorator transforms a metric function that takes as input two univariate TimeSeries instances\n into a function that takes two equally-sized multivariate TimeSeries instances, computes the pairwise univariate\n metrics for components with the same indices, and returns a float value that is computed as a function of all the\n univariate metrics using a `reduction` subroutine passed as argument to the metric function.\n \"\"\"\n @wraps(func)\n def wrapper_multivariate_support(*args, **kwargs):\n # we can avoid checks about args and kwargs since the input is adjusted by the previous decorator\n actual_series = args[0]\n pred_series = args[1]\n\n raise_if_not(actual_series.width == pred_series.width,\n \"The two TimeSeries instances must have the same width.\", logger)\n\n value_list = []\n for i in range(actual_series.width):\n value_list.append(func(actual_series.univariate_component(i), pred_series.univariate_component(i),\n *args[2:], **kwargs)) # [2:] since we already know the first two arguments are the series\n if 'reduction' in kwargs:\n return kwargs['reduction'](value_list)\n else:\n return signature(func).parameters['reduction'].default(value_list)\n return wrapper_multivariate_support\n\n\ndef _get_values_or_raise(series_a: TimeSeries,\n series_b: TimeSeries,\n intersect: bool) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Returns the numpy values of two time series. If intersect is true, considers only their time intersection.\n Raises a ValueError if the two time series (or their intersection) do not have the same time index.\n \"\"\"\n raise_if_not(series_a.width == series_b.width, \" The two time series must have the same number of components\",\n logger)\n\n raise_if_not(isinstance(intersect, bool), \"The intersect parameter must be a bool\")\n\n series_a_common = series_a.slice_intersect(series_b) if intersect else series_a\n series_b_common = series_b.slice_intersect(series_a) if intersect else series_b\n\n raise_if_not(series_a_common.has_same_time_as(series_b_common), 'The two time series (or their intersection) '\n 'must have the same time index.'\n '\\nFirst series: {}\\nSecond series: {}'.format(\n series_a.time_index(), series_b.time_index()),\n logger)\n\n return series_a_common.univariate_values(), series_b_common.univariate_values()\n\n\ndef _remove_nan_union(array_a: np.ndarray,\n array_b: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Returns the two inputs arrays where all elements are deleted that have an index that corresponds to\n a NaN value in either of the two input arrays.\n \"\"\"\n\n isnan_mask = np.logical_or(np.isnan(array_a), np.isnan(array_b))\n return np.delete(array_a, isnan_mask), np.delete(array_b, isnan_mask)\n\n\n@multi_ts_support\n@multivariate_support\ndef mae(actual_series: Union[TimeSeries, Sequence[TimeSeries]],\n pred_series: Union[TimeSeries, Sequence[TimeSeries]],\n intersect: bool = True,\n *,\n reduction: Callable[[np.ndarray], float] = np.mean,\n inter_reduction: Callable[[np.ndarray], Union[float, np.ndarray]] = lambda x: x,\n n_jobs: int = 1,\n verbose: bool = False) -> Union[float, np.ndarray]:\n \"\"\" Mean Absolute Error (MAE).\n\n For two time series :math:`y^1` and :math:`y^2` of length :math:`T`, it is computed as\n\n .. math:: \\\\frac{1}{T}\\\\sum_{t=1}^T{(|y^1_t - y^2_t|)}.\n\n Parameters\n ----------\n actual_series\n The `TimeSeries` or `Sequence[TimeSeries]` of actual values.\n pred_series\n The `TimeSeries` or `Sequence[TimeSeries]` of predicted values.\n intersect\n For time series that are overlapping in time without having the same time index, setting `intersect=True`\n will consider the values only over their common time interval (intersection in time).\n reduction\n Function taking as input a `np.ndarray` and returning a scalar value. This function is used to aggregate\n the metrics of different components in case of multivariate `TimeSeries` instances.\n inter_reduction\n Function taking as input a `np.ndarray` and returning either a scalar value or a `np.ndarray`.\n This function can be used to aggregate the metrics of different series in case the metric is evaluated on a\n `Sequence[TimeSeries]`. Defaults to the identity function, which returns the pairwise metrics for each pair\n of `TimeSeries` received in input. Example: `inter_reduction=np.mean`, will return the average of the pairwise\n metrics.\n n_jobs\n The number of jobs to run in parallel. Parallel jobs are created only when a `Sequence[TimeSeries]` is\n passed as input, parallelising operations regarding different `TimeSeries`. Defaults to `1`\n (sequential). Setting the parameter to `-1` means using all the available processors.\n verbose\n Optionally, whether to print operations progress\n\n Returns\n -------\n float\n The Mean Absolute Error (MAE)\n\n\"\"\"\n\n y1, y2 = _get_values_or_raise(actual_series, pred_series, intersect)\n y1, y2 = _remove_nan_union(y1, y2)\n return np.mean(np.abs(y1 - y2))\n\n\n@multi_ts_support\n@multivariate_support\ndef mse(actual_series: Union[TimeSeries, Sequence[TimeSeries]],\n pred_series: Union[TimeSeries, Sequence[TimeSeries]],\n intersect: bool = True,\n *,\n reduction: Callable[[np.ndarray], float] = np.mean,\n inter_reduction: Callable[[np.ndarray], Union[float, np.ndarray]] = lambda x: x,\n n_jobs: int = 1,\n verbose: bool = False) -> Union[float, np.ndarray]:\n \"\"\" Mean Squared Error (MSE).\n\n For two time series :math:`y^1` and :math:`y^2` of length :math:`T`, it is computed as\n\n .. math:: \\\\frac{1}{T}\\\\sum_{t=1}^T{(y^1_t - y^2_t)^2}.\n\n Parameters\n ----------\n actual_series\n The `TimeSeries` or `Sequence[TimeSeries]` of actual values.\n pred_series\n The `TimeSeries` or `Sequence[TimeSeries]` of predicted values.\n intersect\n For time series that are overlapping in time without having the same time index, setting `intersect=True`\n will consider the values only over their common time interval (intersection in time).\n reduction\n Function taking as input a `np.ndarray` and returning a scalar value. This function is used to aggregate\n the metrics of different components in case of multivariate `TimeSeries` instances.\n inter_reduction\n Function taking as input a `np.ndarray` and returning either a scalar value or a `np.ndarray`.\n This function can be used to aggregate the metrics of different series in case the metric is evaluated on a\n `Sequence[TimeSeries]`. Defaults to the identity function, which returns the pairwise metrics for each pair\n of `TimeSeries` received in input. Example: `inter_reduction=np.mean`, will return the average of the pairwise\n metrics.\n n_jobs\n The number of jobs to run in parallel. Parallel jobs are created only when a `Sequence[TimeSeries]` is\n passed as input, parallelising operations regarding different `TimeSeries`. Defaults to `1`\n (sequential). Setting the parameter to `-1` means using all the available processors.\n verbose\n Optionally, whether to print operations progress\n\n Returns\n -------\n float\n The Mean Squared Error (MSE)\n \"\"\"\n\n y_true, y_pred = _get_values_or_raise(actual_series, pred_series, intersect)\n y_true, y_pred = _remove_nan_union(y_true, y_pred)\n return np.mean((y_true - y_pred)**2)\n\n\n@multi_ts_support\n@multivariate_support\ndef rmse(actual_series: Union[TimeSeries, Sequence[TimeSeries]],\n pred_series: Union[TimeSeries, Sequence[TimeSeries]],\n intersect: bool = True,\n *,\n reduction: Callable[[np.ndarray], float] = np.mean,\n inter_reduction: Callable[[np.ndarray], Union[float, np.ndarray]] = lambda x: x,\n n_jobs: int = 1,\n verbose: bool = False) -> Union[float, np.ndarray]:\n \"\"\" Root Mean Squared Error (RMSE).\n\n For two time series :math:`y^1` and :math:`y^2` of length :math:`T`, it is computed as\n\n .. math:: \\\\sqrt{\\\\frac{1}{T}\\\\sum_{t=1}^T{(y^1_t - y^2_t)^2}}.\n\n Parameters\n ----------\n actual_series\n The `TimeSeries` or `Sequence[TimeSeries]` of actual values.\n pred_series\n The `TimeSeries` or `Sequence[TimeSeries]` of predicted values.\n intersect\n For time series that are overlapping in time without having the same time index, setting `intersect=True`\n will consider the values only over their common time interval (intersection in time).\n reduction\n Function taking as input a `np.ndarray` and returning a scalar value. This function is used to aggregate\n the metrics of different components in case of multivariate `TimeSeries` instances.\n inter_reduction\n Function taking as input a `np.ndarray` and returning either a scalar value or a `np.ndarray`.\n This function can be used to aggregate the metrics of different series in case the metric is evaluated on a\n `Sequence[TimeSeries]`. Defaults to the identity function, which returns the pairwise metrics for each pair\n of `TimeSeries` received in input. Example: `inter_reduction=np.mean`, will return the average of the pairwise\n metrics.\n n_jobs\n The number of jobs to run in parallel. Parallel jobs are created only when a `Sequence[TimeSeries]` is\n passed as input, parallelising operations regarding different `TimeSeries`. Defaults to `1`\n (sequential). Setting the parameter to `-1` means using all the available processors.\n verbose\n Optionally, whether to print operations progress\n\n Returns\n -------\n float\n The Root Mean Squared Error (RMSE)\n \"\"\"\n return np.sqrt(mse(actual_series, pred_series, intersect))\n\n\n@multi_ts_support\n@multivariate_support\ndef rmsle(actual_series: Union[TimeSeries, Sequence[TimeSeries]],\n pred_series: Union[TimeSeries, Sequence[TimeSeries]],\n intersect: bool = True,\n *,\n reduction: Callable[[np.ndarray], float] = np.mean,\n inter_reduction: Callable[[np.ndarray], Union[float, np.ndarray]] = lambda x: x,\n n_jobs: int = 1,\n verbose: bool = False) -> Union[float, np.ndarray]:\n \"\"\" Root Mean Squared Log Error (RMSLE).\n\n For two time series :math:`y^1` and :math:`y^2` of length :math:`T`, it is computed as\n\n .. math:: \\\\sqrt{\\\\frac{1}{T}\\\\sum_{t=1}^T{\\\\left(\\\\log{(y^1_t + 1)} - \\\\log{(y^2_t + 1)}\\\\right)^2}},\n\n using the natural logarithm.\n\n Parameters\n ----------\n actual_series\n The `TimeSeries` or `Sequence[TimeSeries]` of actual values.\n pred_series\n The `TimeSeries` or `Sequence[TimeSeries]` of predicted values.\n intersect\n For time series that are overlapping in time without having the same time index, setting `intersect=True`\n will consider the values only over their common time interval (intersection in time).\n reduction\n Function taking as input a `np.ndarray` and returning a scalar value. This function is used to aggregate\n the metrics of different components in case of multivariate `TimeSeries` instances.\n inter_reduction\n Function taking as input a `np.ndarray` and returning either a scalar value or a `np.ndarray`.\n This function can be used to aggregate the metrics of different series in case the metric is evaluated on a\n `Sequence[TimeSeries]`. Defaults to the identity function, which returns the pairwise metrics for each pair\n of `TimeSeries` received in input. Example: `inter_reduction=np.mean`, will return the average of the pairwise\n metrics.\n n_jobs\n The number of jobs to run in parallel. Parallel jobs are created only when a `Sequence[TimeSeries]` is\n passed as input, parallelising operations regarding different `TimeSeries`. Defaults to `1`\n (sequential). Setting the parameter to `-1` means using all the available processors.\n verbose\n Optionally, whether to print operations progress\n\n Returns\n -------\n float\n The Root Mean Squared Log Error (RMSLE)\n \"\"\"\n\n y1, y2 = _get_values_or_raise(actual_series, pred_series, intersect)\n y1, y2 = _remove_nan_union(y1, y2)\n y1, y2 = np.log(y1 + 1), np.log(y2 + 1)\n return np.sqrt(np.mean((y1 - y2)**2))\n\n\n@multi_ts_support\n@multivariate_support\ndef coefficient_of_variation(actual_series: Union[TimeSeries, Sequence[TimeSeries]],\n pred_series: Union[TimeSeries, Sequence[TimeSeries]],\n intersect: bool = True,\n *,\n reduction: Callable[[np.ndarray], float] = np.mean,\n inter_reduction: Callable[[np.ndarray], Union[float, np.ndarray]] = lambda x: x,\n n_jobs: int = 1,\n verbose: bool = False) -> Union[float, np.ndarray]:\n \"\"\" Coefficient of Variation (percentage).\n\n Given a time series of actual values :math:`y_t` and a time series of predicted values :math:`\\\\hat{y}_t`,\n it is a percentage value, computed as\n\n .. math:: 100 \\\\cdot \\\\text{RMSE}(y_t, \\\\hat{y}_t) / \\\\bar{y_t},\n\n where :math:`\\\\text{RMSE}()` denotes the root mean squared error, and\n :math:`\\\\bar{y_t}` is the average of :math:`y_t`.\n\n Parameters\n ----------\n actual_series\n The `TimeSeries` or `Sequence[TimeSeries]` of actual values.\n pred_series\n The `TimeSeries` or `Sequence[TimeSeries]` of predicted values.\n intersect\n For time series that are overlapping in time without having the same time index, setting `intersect=True`\n will consider the values only over their common time interval (intersection in time).\n reduction\n Function taking as input a `np.ndarray` and returning a scalar value. This function is used to aggregate\n the metrics of different components in case of multivariate `TimeSeries` instances.\n inter_reduction\n Function taking as input a `np.ndarray` and returning either a scalar value or a `np.ndarray`.\n This function can be used to aggregate the metrics of different series in case the metric is evaluated on a\n `Sequence[TimeSeries]`. Defaults to the identity function, which returns the pairwise metrics for each pair\n of `TimeSeries` received in input. Example: `inter_reduction=np.mean`, will return the average of the pairwise\n metrics.\n n_jobs\n The number of jobs to run in parallel. Parallel jobs are created only when a `Sequence[TimeSeries]` is\n passed as input, parallelising operations regarding different `TimeSeries`. Defaults to `1`\n (sequential). Setting the parameter to `-1` means using all the available processors.\n verbose\n Optionally, whether to print operations progress\n\n Returns\n -------\n float\n The Coefficient of Variation\n \"\"\"\n\n return 100 * rmse(actual_series, pred_series, intersect) / actual_series.mean().mean()\n\n\n@multi_ts_support\n@multivariate_support\ndef mape(actual_series: Union[TimeSeries, Sequence[TimeSeries]],\n pred_series: Union[TimeSeries, Sequence[TimeSeries]],\n intersect: bool = True,\n *,\n reduction: Callable[[np.ndarray], float] = np.mean,\n inter_reduction: Callable[[np.ndarray], Union[float, np.ndarray]] = lambda x: x,\n n_jobs: int = 1,\n verbose: bool = False) -> Union[float, np.ndarray]:\n \"\"\" Mean Absolute Percentage Error (MAPE).\n\n Given a time series of actual values :math:`y_t` and a time series of predicted values :math:`\\\\hat{y}_t`\n both of length :math:`T`, it is a percentage value computed as\n\n .. math:: 100 \\\\cdot \\\\frac{1}{T} \\\\sum_{t=1}^{T}{\\\\left| \\\\frac{y_t - \\\\hat{y}_t}{y_t} \\\\right|}.\n\n Note that it will raise a `ValueError` if :math:`y_t = 0` for some :math:`t`. Consider using\n the Mean Absolute Scaled Error (MASE) in these cases.\n\n Parameters\n ----------\n actual_series\n The `TimeSeries` or `Sequence[TimeSeries]` of actual values.\n pred_series\n The `TimeSeries` or `Sequence[TimeSeries]` of predicted values.\n intersect\n For time series that are overlapping in time without having the same time index, setting `intersect=True`\n will consider the values only over their common time interval (intersection in time).\n reduction\n Function taking as input a `np.ndarray` and returning a scalar value. This function is used to aggregate\n the metrics of different components in case of multivariate `TimeSeries` instances.\n inter_reduction\n Function taking as input a `np.ndarray` and returning either a scalar value or a `np.ndarray`.\n This function can be used to aggregate the metrics of different series in case the metric is evaluated on a\n `Sequence[TimeSeries]`. Defaults to the identity function, which returns the pairwise metrics for each pair\n of `TimeSeries` received in input. Example: `inter_reduction=np.mean`, will return the average of the pairwise\n metrics.\n n_jobs\n The number of jobs to run in parallel. Parallel jobs are created only when a `Sequence[TimeSeries]` is\n passed as input, parallelising operations regarding different `TimeSeries`. Defaults to `1`\n (sequential). Setting the parameter to `-1` means using all the available processors.\n verbose\n Optionally, whether to print operations progress\n\n Raises\n ------\n ValueError\n If the actual series contains some zeros.\n\n Returns\n -------\n float\n The Mean Absolute Percentage Error (MAPE)\n \"\"\"\n\n y_true, y_hat = _get_values_or_raise(actual_series, pred_series, intersect)\n y_true, y_hat = _remove_nan_union(y_true, y_hat)\n raise_if_not((y_true != 0).all(), 'The actual series must be strictly positive to compute the MAPE.', logger)\n return 100. * np.mean(np.abs((y_true - y_hat) / y_true))\n\n\n@multi_ts_support\n@multivariate_support\ndef smape(actual_series: Union[TimeSeries, Sequence[TimeSeries]],\n pred_series: Union[TimeSeries, Sequence[TimeSeries]],\n intersect: bool = True,\n *,\n reduction: Callable[[np.ndarray], float] = np.mean,\n inter_reduction: Callable[[np.ndarray], Union[float, np.ndarray]] = lambda x: x,\n n_jobs: int = 1,\n verbose: bool = False) -> Union[float, np.ndarray]:\n \"\"\" symmetric Mean Absolute Percentage Error (sMAPE).\n\n Given a time series of actual values :math:`y_t` and a time series of predicted values :math:`\\\\hat{y}_t`\n both of length :math:`T`, it is a percentage value computed as\n\n .. math::\n 200 \\\\cdot \\\\frac{1}{T}\n \\\\sum_{t=1}^{T}{\\\\frac{\\\\left| y_t - \\\\hat{y}_t \\\\right|}{\\\\left| y_t \\\\right| + \\\\left| \\\\hat{y}_t \\\\right|} }.\n\n Note that it will raise a `ValueError` if :math:`\\\\left| y_t \\\\right| + \\\\left| \\\\hat{y}_t \\\\right| = 0`\n for some :math:`t`. Consider using the Mean Absolute Scaled Error (MASE) in these cases.\n\n Parameters\n ----------\n actual_series\n The `TimeSeries` or `Sequence[TimeSeries]` of actual values.\n pred_series\n The `TimeSeries` or `Sequence[TimeSeries]` of predicted values.\n intersect\n For time series that are overlapping in time without having the same time index, setting `intersect=True`\n will consider the values only over their common time interval (intersection in time).\n reduction\n Function taking as input a `np.ndarray` and returning a scalar value. This function is used to aggregate\n the metrics of different components in case of multivariate `TimeSeries` instances.\n inter_reduction\n Function taking as input a `np.ndarray` and returning either a scalar value or a `np.ndarray`.\n This function can be used to aggregate the metrics of different series in case the metric is evaluated on a\n `Sequence[TimeSeries]`. Defaults to the identity function, which returns the pairwise metrics for each pair\n of `TimeSeries` received in input. Example: `inter_reduction=np.mean`, will return the average of the pairwise\n metrics.\n n_jobs\n The number of jobs to run in parallel. Parallel jobs are created only when a `Sequence[TimeSeries]` is\n passed as input, parallelising operations regarding different `TimeSeries`. Defaults to `1`\n (sequential). Setting the parameter to `-1` means using all the available processors.\n verbose\n Optionally, whether to print operations progress\n\n Raises\n ------\n ValueError\n If the actual series and the pred series contains some zeros at the same time index.\n\n Returns\n -------\n float\n The symmetric Mean Absolute Percentage Error (sMAPE)\n \"\"\"\n\n y_true, y_hat = _get_values_or_raise(actual_series, pred_series, intersect)\n y_true, y_hat = _remove_nan_union(y_true, y_hat)\n raise_if_not(np.logical_or(y_true != 0, y_hat != 0).all(),\n 'The actual series must be strictly positive to compute the sMAPE.', logger)\n return 200. * np.mean(np.abs(y_true - y_hat) / (np.abs(y_true) + np.abs(y_hat)))\n\n\n# mase cannot leverage multivariate and multi_ts with the decorator since also the `insample` is a Sequence[TimeSeries]\ndef mase(actual_series: Union[TimeSeries, Sequence[TimeSeries]],\n pred_series: Union[TimeSeries, Sequence[TimeSeries]],\n insample: Union[TimeSeries, Sequence[TimeSeries]],\n m: Optional[int] = 1,\n intersect: bool = True,\n *,\n reduction: Callable[[np.ndarray], float] = np.mean,\n inter_reduction: Callable[[np.ndarray], Union[float, np.ndarray]] = lambda x: x,\n n_jobs: int = 1,\n verbose: bool = False) -> Union[float, np.ndarray]:\n \"\"\" Mean Absolute Scaled Error (MASE).\n\n See `Mean absolute scaled error wikipedia page <https://en.wikipedia.org/wiki/Mean_absolute_scaled_error>`_\n for details about the MASE and how it is computed.\n\n Parameters\n ----------\n actual_series\n The `TimeSeries` or `Sequence[TimeSeries]` of actual values.\n pred_series\n The `TimeSeries` or `Sequence[TimeSeries]` of predicted values.\n insample\n The training series used to forecast `pred_series` .\n This series serves to compute the scale of the error obtained by a naive forecaster on the training data.\n m\n Optionally, the seasonality to use for differencing.\n `m=1` corresponds to the non-seasonal MASE, whereas `m>1` corresponds to seasonal MASE.\n If `m=None`, it will be tentatively inferred\n from the auto-correlation function (ACF). It will fall back to a value of 1 if this fails.\n intersect\n For time series that are overlapping in time without having the same time index, setting `intersect=True`\n will consider the values only over their common time interval (intersection in time).\n reduction\n Function taking as input a `np.ndarray` and returning a scalar value. This function is used to aggregate\n the metrics of different components in case of multivariate `TimeSeries` instances.\n inter_reduction\n Function taking as input a `np.ndarray` and returning either a scalar value or a `np.ndarray`.\n This function can be used to aggregate the metrics of different series in case the metric is evaluated on a\n `Sequence[TimeSeries]`. Defaults to the identity function, which returns the pairwise metrics for each pair\n of `TimeSeries` received in input. Example: `inter_reduction=np.mean`, will return the average of the pairwise\n metrics.\n n_jobs\n The number of jobs to run in parallel. Parallel jobs are created only when a `Sequence[TimeSeries]` is\n passed as input, parallelising operations regarding different `TimeSeries`. Defaults to `1`\n (sequential). Setting the parameter to `-1` means using all the available processors.\n verbose\n Optionally, whether to print operations progress\n\n Raises\n ------\n ValueError\n If the `insample` series is periodic ( :math:`X_t = X_{t-m}` )\n\n Returns\n -------\n float\n The Mean Absolute Scaled Error (MASE)\n \"\"\"\n\n def _multivariate_mase(actual_series: TimeSeries,\n pred_series: TimeSeries,\n insample: Union[TimeSeries, Sequence[TimeSeries]],\n m: int,\n intersect: bool,\n reduction: Callable[[np.ndarray], float]):\n\n raise_if_not(actual_series.width == pred_series.width,\n \"The two TimeSeries instances must have the same width.\", logger)\n raise_if_not(actual_series.width == insample.width,\n \"The insample TimeSeries must have the same width as the other series.\", logger)\n raise_if_not(insample.end_time() + insample.freq() == pred_series.start_time(),\n \"The pred_series must be the forecast of the insample series\", logger)\n\n value_list = []\n for i in range(actual_series.width):\n # old implementation of mase on univariate TimeSeries\n if m is None:\n test_season, m = check_seasonality(insample)\n if not test_season:\n warn(\"No seasonality found when computing MASE. Fixing the period to 1.\", UserWarning)\n m = 1\n\n y_true, y_hat = _get_values_or_raise(actual_series.univariate_component(i),\n pred_series.univariate_component(i),\n intersect)\n\n x_t = insample.univariate_component(i).values()\n errors = np.abs(y_true - y_hat)\n scale = np.mean(np.abs(x_t[m:] - x_t[:-m]))\n raise_if_not(not np.isclose(scale, 0), \"cannot use MASE with periodical signals\", logger)\n value_list.append(np.mean(errors / scale))\n\n return reduction(value_list)\n\n if isinstance(actual_series, TimeSeries):\n raise_if_not(isinstance(pred_series, TimeSeries), \"Expecting pred_series to be TimeSeries\")\n raise_if_not(isinstance(insample, TimeSeries), \"Expecting insample to be TimeSeries\")\n return _multivariate_mase(actual_series=actual_series,\n pred_series=pred_series,\n insample=insample,\n m=m,\n intersect=intersect,\n reduction=reduction)\n\n elif isinstance(actual_series, Sequence) and isinstance(actual_series[0], TimeSeries):\n\n raise_if_not(isinstance(pred_series, Sequence) and isinstance(pred_series[0], TimeSeries),\n \"Expecting pred_series to be a Sequence[TimeSeries]\")\n raise_if_not(isinstance(insample, Sequence) and isinstance(insample[0], TimeSeries),\n \"Expecting insample to be a Sequence[TimeSeries]\")\n raise_if_not(len(pred_series) == len(actual_series) and len(pred_series) == len(insample),\n \"The TimeSeries sequences must have the same length.\", logger)\n\n raise_if_not(isinstance(n_jobs, int), \"n_jobs must be an integer\")\n raise_if_not(isinstance(verbose, bool), \"verbose must be a bool\")\n\n iterator = _build_tqdm_iterator(iterable=zip(actual_series, pred_series, insample),\n verbose=verbose,\n total=len(actual_series))\n\n value_list = _parallel_apply(iterator=iterator,\n fn=_multivariate_mase,\n n_jobs=n_jobs,\n fn_args=dict(),\n fn_kwargs={\n \"m\": m,\n \"intersect\": intersect,\n \"reduction\": reduction\n })\n return inter_reduction(value_list)\n else:\n raise_log(ValueError(\"Input type not supported, only TimeSeries and Sequence[TimeSeries] are accepted.\"))\n\n\n@multi_ts_support\n@multivariate_support\ndef ope(actual_series: Union[TimeSeries, Sequence[TimeSeries]],\n pred_series: Union[TimeSeries, Sequence[TimeSeries]],\n intersect: bool = True,\n *,\n reduction: Callable[[np.ndarray], float] = np.mean,\n inter_reduction: Callable[[np.ndarray], Union[float, np.ndarray]] = lambda x: x,\n n_jobs: int = 1,\n verbose: bool = False) -> Union[float, np.ndarray]:\n \"\"\" Overall Percentage Error (OPE).\n\n Given a time series of actual values :math:`y_t` and a time series of predicted values :math:`\\\\hat{y}_t`\n both of length :math:`T`, it is a percentage value computed as\n\n .. math:: 100 \\\\cdot \\\\left| \\\\frac{\\\\sum_{t=1}^{T}{y_t}\n - \\\\sum_{t=1}^{T}{\\\\hat{y}_t}}{\\\\sum_{t=1}^{T}{y_t}} \\\\right|.\n\n Parameters\n ----------\n actual_series\n The `TimeSeries` or `Sequence[TimeSeries]` of actual values.\n pred_series\n The `TimeSeries` or `Sequence[TimeSeries]` of predicted values.\n intersect\n For time series that are overlapping in time without having the same time index, setting `intersect=True`\n will consider the values only over their common time interval (intersection in time).\n reduction\n Function taking as input a `np.ndarray` and returning a scalar value. This function is used to aggregate\n the metrics of different components in case of multivariate `TimeSeries` instances.\n inter_reduction\n Function taking as input a `np.ndarray` and returning either a scalar value or a `np.ndarray`.\n This function can be used to aggregate the metrics of different series in case the metric is evaluated on a\n `Sequence[TimeSeries]`. Defaults to the identity function, which returns the pairwise metrics for each pair\n of `TimeSeries` received in input. Example: `inter_reduction=np.mean`, will return the average of the pairwise\n metrics.\n n_jobs\n The number of jobs to run in parallel. Parallel jobs are created only when a `Sequence[TimeSeries]` is\n passed as input, parallelising operations regarding different `TimeSeries`. Defaults to `1`\n (sequential). Setting the parameter to `-1` means using all the available processors.\n verbose\n Optionally, whether to print operations progress\n\n Raises\n ------\n ValueError\n If :math:`\\\\sum_{t=1}^{T}{y_t} = 0`.\n\n Returns\n -------\n float\n The Overall Percentage Error (OPE)\n \"\"\"\n\n y_true, y_pred = _get_values_or_raise(actual_series, pred_series, intersect)\n y_true, y_pred = _remove_nan_union(y_true, y_pred)\n y_true_sum, y_pred_sum = np.sum(y_true), np.sum(y_pred)\n raise_if_not(y_true_sum > 0, 'The series of actual value cannot sum to zero when computing OPE.', logger)\n return np.abs((y_true_sum - y_pred_sum) / y_true_sum) * 100.\n\n\n@multi_ts_support\n@multivariate_support\ndef marre(actual_series: Union[TimeSeries, Sequence[TimeSeries]],\n pred_series: Union[TimeSeries, Sequence[TimeSeries]],\n intersect: bool = True,\n *,\n reduction: Callable[[np.ndarray], float] = np.mean,\n inter_reduction: Callable[[np.ndarray], Union[float, np.ndarray]] = lambda x: x,\n n_jobs: int = 1,\n verbose: bool = False) -> Union[float, np.ndarray]:\n \"\"\" Mean Absolute Ranged Relative Error (MARRE).\n\n Given a time series of actual values :math:`y_t` and a time series of predicted values :math:`\\\\hat{y}_t`\n both of length :math:`T`, it is a percentage value computed as\n\n .. math:: 100 \\\\cdot \\\\frac{1}{T} \\\\sum_{t=1}^{T} {\\\\left| \\\\frac{y_t - \\\\hat{y}_t} {\\\\max_t{y_t} -\n \\\\min_t{y_t}} \\\\right|}\n\n Parameters\n ----------\n actual_series\n The `TimeSeries` or `Sequence[TimeSeries]` of actual values.\n pred_series\n The `TimeSeries` or `Sequence[TimeSeries]` of predicted values.\n intersect\n For time series that are overlapping in time without having the same time index, setting `intersect=True`\n will consider the values only over their common time interval (intersection in time).\n reduction\n Function taking as input a `np.ndarray` and returning a scalar value. This function is used to aggregate\n the metrics of different components in case of multivariate `TimeSeries` instances.\n inter_reduction\n Function taking as input a `np.ndarray` and returning either a scalar value or a `np.ndarray`.\n This function can be used to aggregate the metrics of different series in case the metric is evaluated on a\n `Sequence[TimeSeries]`. Defaults to the identity function, which returns the pairwise metrics for each pair\n of `TimeSeries` received in input. Example: `inter_reduction=np.mean`, will return the average of the pairwise\n metrics.\n n_jobs\n The number of jobs to run in parallel. Parallel jobs are created only when a `Sequence[TimeSeries]` is\n passed as input, parallelising operations regarding different `TimeSeries`. Defaults to `1`\n (sequential). Setting the parameter to `-1` means using all the available processors.\n verbose\n Optionally, whether to print operations progress\n\n Raises\n ------\n ValueError\n If :math:`\\\\max_t{y_t} = \\\\min_t{y_t}`.\n\n Returns\n -------\n float\n The Mean Absolute Ranged Relative Error (MARRE)\n \"\"\"\n\n y_true, y_hat = _get_values_or_raise(actual_series, pred_series, intersect)\n y_true, y_hat = _remove_nan_union(y_true, y_hat)\n raise_if_not(y_true.max() > y_true.min(), 'The difference between the max and min values must be strictly'\n 'positive to compute the MARRE.', logger)\n true_range = y_true.max() - y_true.min()\n return 100. * np.mean(np.abs((y_true - y_hat) / true_range))\n\n\n@multi_ts_support\n@multivariate_support\ndef r2_score(actual_series: Union[TimeSeries, Sequence[TimeSeries]],\n pred_series: Union[TimeSeries, Sequence[TimeSeries]],\n intersect: bool = True,\n *,\n reduction: Callable[[np.ndarray], float] = np.mean,\n inter_reduction: Callable[[np.ndarray], Union[float, np.ndarray]] = lambda x: x,\n n_jobs: int = 1,\n verbose: bool = False) -> Union[float, np.ndarray]:\n \"\"\" Coefficient of Determination :math:`R^2`.\n\n See `Coefficient of determination wikipedia page <https://en.wikipedia.org/wiki/Coefficient_of_determination>`_\n for details about the :math:`R^2` score and how it is computed.\n Please note that this metric is not symmetric, `series1` should correspond to the ground truth series,\n whereas `series2` should correspond to the predicted series.\n\n Parameters\n ----------\n actual_series\n The `TimeSeries` or `Sequence[TimeSeries]` of actual values.\n pred_series\n The `TimeSeries` or `Sequence[TimeSeries]` of predicted values.\n intersect\n For time series that are overlapping in time without having the same time index, setting `intersect=True`\n will consider the values only over their common time interval (intersection in time).\n reduction\n Function taking as input a `np.ndarray` and returning a scalar value. This function is used to aggregate\n the metrics of different components in case of multivariate `TimeSeries` instances.\n inter_reduction\n Function taking as input a `np.ndarray` and returning either a scalar value or a `np.ndarray`.\n This function can be used to aggregate the metrics of different series in case the metric is evaluated on a\n `Sequence[TimeSeries]`. Defaults to the identity function, which returns the pairwise metrics for each pair\n of `TimeSeries` received in input. Example: `inter_reduction=np.mean`, will return the average of the pairwise\n metrics.\n n_jobs\n The number of jobs to run in parallel. Parallel jobs are created only when a `Sequence[TimeSeries]` is\n passed as input, parallelising operations regarding different `TimeSeries`. Defaults to `1`\n (sequential). Setting the parameter to `-1` means using all the available processors.\n verbose\n Optionally, whether to print operations progress\n\n Returns\n -------\n float\n The Coefficient of Determination :math:`R^2`\n \"\"\"\n y1, y2 = _get_values_or_raise(actual_series, pred_series, intersect)\n y1, y2 = _remove_nan_union(y1, y2)\n ss_errors = np.sum((y1 - y2) ** 2)\n y_hat = y1.mean()\n ss_tot = np.sum((y1 - y_hat) ** 2)\n return 1 - ss_errors / ss_tot\n"
] | [
[
"numpy.log",
"numpy.abs",
"numpy.isnan",
"numpy.logical_or",
"numpy.delete",
"numpy.mean",
"numpy.sum",
"numpy.isclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
benmaier/DigCT | [
"62fc3fddb7600e2a43761e08618b2e3df423569c",
"62fc3fddb7600e2a43761e08618b2e3df423569c"
] | [
"analysis_collection/tracing_sim/results_deleting_edges_30_N_meas_100/FigS7_1.py",
"analysis_collection/tracing_sim/results_smallworld_withQ_halfreact_NMEAS_100_ONLYSAVETIME_False/simulation.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as pl\nimport pickle\nfrom epipack.plottools import plot\nimport qsuite_config as cf\nimport matplotlib.ticker as mtick\n\nwith open('_qsuite/results_deleting_edges_30_N_meas_100/results_mean_std.p','rb') as f:\n data = pickle.load(f)\n\nmeans = data['means']\nstds = data['stds']\n\ndef sumres(result,compartments):\n return sum([result[C] for C in compartments])\n\ndef sumstd(result,compartments):\n return np.sqrt(sum([result[C]**2 for C in compartments]))\n\nia00 = 0\nia30 = 1\nia50 = 2\nt = np.arange(len(means[0][0]['S']))\nal = 0.3\nfc = np.sqrt(cf.N_measurements)\n\nplot_errors = False\n\nfor iph, phase in enumerate(cf.phases):\n\n fig2, ax2 = pl.subplots(1,4,figsize=(15,4),sharex=True)\n\n ax = ax2[0]\n\n for ia in range(len(cf.a_s)):\n\n I = means[iph][ia]['Itot']\n StdI = stds[iph][ia]['Itot']/fc\n _p, = ax.plot(t, sumres(means[iph][ia],['I_P','I_Pa','I_S','I_Sa','I_A','I_Aa']), label = f\"a = {cf.a_s[ia]}\")\n if plot_errors:\n ax.fill_between(t, I-StdI, I+StdI,color=_p.get_color(),alpha=al,edgecolor='None')\n if phase == 'periodic lockdown':\n x = cf.phases_definitions[phase][\"tmaxs\"]\n ax.axvspan(x[0], x[0]*2, alpha=0.3, color='grey')\n ax.axvspan(x[0]*3, max(t), alpha=0.3, color='grey')\n\n ax.set_xlim([0,t[-1]*0.55])\n ax.set_ylim([0,ax.get_ylim()[1]])\n ax.set_xlabel('time [days]')\n ax.set_ylabel('prevalence')\n ax.legend()\n\n\n Omeg0 = cf.N - means[iph][ia00]['Stot']\n StdOmeg0 = stds[iph][ia00]['Stot']/fc\n\n ax = ax2[1:]\n\n if phase == 'periodic lockdown':\n for i in range(3):\n x = cf.phases_definitions['periodic lockdown'][\"tmaxs\"]\n ax[i].axvspan(x[0], x[0]*2, alpha=0.3, color='grey')\n ax[i].axvspan(x[0]*3, max(t), alpha=0.3, color='grey')\n\n ax[0].plot(t,Omeg0,label='$\\Omega(0)$',lw=3)\n\n for ia, a in enumerate(cf.a_s):\n if ia == 0:\n continue\n\n Omeg_a = cf.N - means[iph][ia]['Stot']\n StdOmeg_a = stds[iph][ia]['Stot']/fc\n dOm = Omeg0 - Omeg_a\n StdOm = sumstd({'0': StdOmeg0, '1': StdOmeg_a}, '01')\n\n relOm = 1 - Omeg_a/Omeg0\n StdRelOm = np.sqrt((StdOmeg_a/Omeg0)**2 + (StdOmeg0*Omeg_a/Omeg0**2)**2)\n\n ddOmdt = np.diff(dOm)\n\n Cov = np.cov(dOm[1:], dOm[:-1])\n\n StdddOmdt = np.sqrt(StdOm[1:]**2 + StdOm[:-1]**2 - 2*Cov[0,1])\n\n _p, = ax[0].plot(t,Omeg_a,label=f'$\\Omega({a})$')\n if plot_errors:\n ax[0].fill_between(t, Omeg_a-StdOmeg_a, Omeg_a+StdOmeg_a,color=_p.get_color(),alpha=al,edgecolor='None')\n\n _p, = ax[0].plot(t,dOm,'--',label=f'$\\Omega(0) - \\Omega({a})$')\n if plot_errors:\n ax[0].fill_between(t, dOm-StdOm, dOm+StdOm,color=_p.get_color(),alpha=al,edgecolor='None')\n\n _p, = ax[1].plot(t,relOm,label=f'a={a}')\n if plot_errors:\n ax[1].fill_between(t, relOm-StdRelOm, relOm+StdRelOm,color=_p.get_color(),alpha=al,edgecolor='None')\n\n _p, = ax[2].plot(t[:-1],ddOmdt,label=f'a={a}')\n if plot_errors:\n pass\n\n ax[0].set_xlabel('time [days]')\n ax[1].set_xlabel('time [days]')\n ax[2].set_xlabel('time [days]')\n\n ax[0].set_ylabel('cumulative infections')\n ax[1].set_ylabel('relative averted infections (cumulative)')\n ax[2].set_ylabel('averted infections per day')\n\n\n ax[1].yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1,decimals=0))\n for col in range(4):\n ax2[col].set_xlim([0,180])\n ax2[col].legend()\n\n fig2.tight_layout()\n\npl.show()\n",
"import epipack\nimport numpy as np\nfrom epipack.stochastic_epi_models import StochasticEpiModel\nfrom math import exp\nfrom numpy import random\nimport networkx as nx\nfrom smallworld import get_smallworld_graph\nfrom scipy.stats import expon\nimport numpy as np\nimport networkx as nx\n\ndef _edge(i,j):\n if i > j:\n return (j,i)\n elif j > i:\n return (i,j)\n else:\n raise ValueError('self-loop')\ndef get_expon_small_world(N,k0,more_lattice_like=False,node_creation_order='random'):\n\n G = nx.empty_graph(N)\n\n degree_seq = [ int(k) for k in expon.rvs(scale=k0,size=N)]\n stubs = list(degree_seq)\n if sum(stubs) % 2 == 1:\n stubs[np.random.randint(0,N-1)] += 1\n\n if node_creation_order == 'random':\n # generates small world but locally clustered\n order = np.random.permutation(N)\n elif node_creation_order == 'desc':\n # generates locally clustered\n order = np.argsort(stubs)[::-1]\n elif node_creation_order == 'asc':\n # generates locally clustered with short paths\n order = np.argsort(stubs)\n else:\n raise ValueError(\"`node_creation_order` must be 'random', 'desc', or 'asc', not \" + node_creation_order)\n\n edges = []\n cnt = 0\n for i in order:\n d = 1\n up = True\n while stubs[i] > 0:\n if up:\n j = (i+d) % N\n else:\n j = (i-d) % N\n d += 1\n if i == j:\n break\n if stubs[j] > 0:#and not G.has_edge(i,j):\n edges.append(_edge(int(i),int(j)))\n #G.add_edge(i,j)\n stubs[i] -= 1\n stubs[j] -= 1\n up = not up\n if d >= N//2:\n break\n #f d > N // 2:\n # print(stubs[i], np.mean(stubs), np.min(stubs),np.max(stubs),cnt)\n # raise ValueError('Couldn''t find stub')\n cnt += 1\n #print(\"leftover stubs:\",sum(stubs))\n #print(\"number of nodes with leftover stubs:\",np.count_nonzero(stubs))\n\n #print(\"len(edges) = \", len(edges), \"len(set(edges)) = \", len(set(edges)), \"difference = \", len(edges) - len(set(edges)))\n G.add_edges_from(edges)\n\n return G\ndef confignetwork(N, parameter,**kwargs):\n p = parameter\n k0 = p['number_of_contacts']\n def expodegree(x):\n return 1/k0*exp(-x/k0)\n P = []\n k_i = []\n for i in range(N-1):\n p_k = expodegree(i)\n P.append(p_k)\n k_i.append(i)\n P = np.array(P)\n P /= P.sum()\n def seq(k_i,P):\n expected_degree_sequence = np.linspace(0,1,2)\n while sum(expected_degree_sequence) % 2 != 0:\n expected_degree_sequence = np.random.choice(\n k_i,\n N,\n p = P\n )\n\n return expected_degree_sequence\n\n expected_degree_sequence = seq(k_i,P)\n G = nx.configuration_model(expected_degree_sequence,create_using = nx.Graph())\n G.remove_edges_from(nx.selfloop_edges(G))\n edge_weight_tuples = [ (e[0], e[1], 1.0) for e in G.edges() ]\n k_norm = 2*len(edge_weight_tuples) / N\n del G\n return edge_weight_tuples, k_norm\n\ndef swnetwork(N, parameter,**kwargs):\n p = parameter\n k_over_2 = int(p['number_of_contacts']/2)\n beta = 10e-7 #for k = 20, N = 200_000 or k0=10\n #beta = 1\n G = get_smallworld_graph(N,k_over_2,beta)\n edge_weight_tuples = [ (e[0], e[1], 1.0) for e in G.edges() ]\n k_norm = 2*len(edge_weight_tuples) / N\n del G\n return edge_weight_tuples, k_norm\n\ndef exp_sw_network(N,parameter,**kwargs):\n p = parameter\n k0 = p['number_of_contacts']\n G = get_expon_small_world(N,k0,node_creation_order='random')\n edge_weight_tuples = [ (e[0], e[1], 1.0) for e in G.edges() ]\n k_norm = 2*len(edge_weight_tuples) / N\n del G\n print(k_norm)\n return edge_weight_tuples, k_norm\n\ndef simulation_code(kwargs):\n\n def mixed(N, parameter, time, sampling_dt,quarantiningS, a, q, y, **kwargs):\n p = parameter\n #edge_weight_tuples, k_norm = confignetwork(N,parameter)\n edge_weight_tuples, k_norm = swnetwork(N, parameter)\n kappa = (q*p['recovery_rate'])/(1-q)\n IPa0 = int(random.binomial(p['I_0'], a, 1))\n IP0 = int(p['I_0'] - IPa0)\n Sa0 = int(random.binomial(N-p['I_0'], a, 1))\n S0 = int(N - p['I_0'] - Sa0)\n if quarantiningS == True:\n model = epipack.StochasticEpiModel(['S','E','I_P','I_S','I_A','R','T','X','Sa','Ea','I_Pa','I_Sa','I_Aa','Ra','Ta','Xa','Qa','C'],N, edge_weight_tuples ,directed=False)\n model.set_conditional_link_transmission_processes({\n (\"Ta\", \"->\", \"Xa\") : [\n (\"Xa\", \"I_Pa\", y*0.5, \"Xa\", \"Ta\" ),\n (\"Xa\", \"I_Sa\", y*0.5, \"Xa\", \"Ta\" ),\n (\"Xa\", \"I_Aa\", y*0.5, \"Xa\", \"Ta\" ),\n (\"Xa\", \"Ea\", y*0.5, \"Xa\", \"Ta\" ),\n (\"Xa\", \"Sa\", 0.5, \"Xa\", \"Qa\" ),\n (\"Xa\", \"I_Pa\", (1-y)*0.5, \"Xa\", \"C\" ),\n (\"Xa\", \"I_Sa\", (1-y)*0.5, \"Xa\", \"C\" ),\n (\"Xa\", \"I_Aa\", (1-y)*0.5, \"Xa\", \"C\" ),\n (\"Xa\", \"Ea\", (1-y)*0.5, \"Xa\", \"C\" )]\n })\n model.set_node_transition_processes([\n ('E',p['alpha'],'I_P'),\n ('I_P',(1-p['x'])*p['beta'],'I_S'),\n ('I_P',p['x']*p['beta'],'I_A'),\n ('I_A',p['recovery_rate'],'R'),\n ('I_S',p['recovery_rate'],'R'),\n ('I_S',kappa,'T'),\n ('T',p['chi'],'X'),\n ('Qa',p['omega'],'Sa'),\n ('Ea',p['alpha'],'I_Pa'),\n ('I_Pa',(1-p['x'])*p['beta'],'I_Sa'),\n ('I_Pa',p['x']*p['beta'],'I_Aa'),\n ('I_Aa',p['recovery_rate'],'Ra'),\n ('I_Sa',p['recovery_rate'],'Ra'),\n ('I_Sa',kappa,'Ta'),\n ('Ta',p[\"z\"]*p['chi'],'Xa'),\n ('Ta',(1-p[\"z\"])*p['chi'],'X')])\n\n elif quarantiningS == False:\n model = epipack.StochasticEpiModel(['S','E','I_P','I_S','I_A','R','T','X','Sa','Ea','I_Pa','I_Sa','I_Aa','Ra','Ta','Xa','C'],N, edge_weight_tuples ,directed=False)\n model.set_conditional_link_transmission_processes({\n (\"Ta\", \"->\", \"Xa\") : [\n (\"Xa\", \"I_Pa\", y, \"Xa\", \"Ta\" ),\n (\"Xa\", \"I_Sa\", y, \"Xa\", \"Ta\" ),\n (\"Xa\", \"I_Aa\", y, \"Xa\", \"Ta\" ),\n (\"Xa\", \"Ea\", y, \"Xa\", \"Ta\" ),\n (\"Xa\", \"I_Pa\", (1-y), \"Xa\", \"C\" ),\n (\"Xa\", \"I_Sa\", (1-y), \"Xa\", \"C\" ),\n (\"Xa\", \"I_Aa\", (1-y), \"Xa\", \"C\" ),\n (\"Xa\", \"Ea\", (1-y), \"Xa\", \"C\" )]\n })\n model.set_node_transition_processes([\n ('E',p['alpha'],'I_P'),\n ('I_P',(1-p['x'])*p['beta'],'I_S'),\n ('I_P',p['x']*p['beta'],'I_A'),\n ('I_A',p['recovery_rate'],'R'),\n ('I_S',p['recovery_rate'],'R'),\n ('I_S',kappa,'T'),\n ('T',p['chi'],'X'),\n ('Ea',p['alpha'],'I_Pa'),\n ('I_Pa',(1-p['x'])*p['beta'],'I_Sa'),\n ('I_Pa',p['x']*p['beta'],'I_Aa'),\n ('I_Aa',p['recovery_rate'],'Ra'),\n ('I_Sa',p['recovery_rate'],'Ra'),\n ('I_Sa',kappa,'Ta'),\n ('Ta',p[\"z\"]*p['chi'],'Xa'),\n ('Ta',(1-p[\"z\"])*p['chi'],'X')])\n model.set_link_transmission_processes([\n\n ('I_Pa','S',p[\"R0\"]/k_norm*p['beta']/2,'I_Pa','E'),\n ('I_Aa','S',p[\"R0\"]/k_norm*p['recovery_rate']/2,'I_Aa','E'),\n ('I_Sa','S',p[\"R0\"]/k_norm*p['recovery_rate']/2,'I_Sa','E'),\n\n ('I_P','Sa',p[\"R0\"]/k_norm*p['beta']/2,'I_P','Ea'),\n ('I_A','Sa',p[\"R0\"]/k_norm*p['recovery_rate']/2,'I_A','Ea'),\n ('I_S','Sa',p[\"R0\"]/k_norm*p['recovery_rate']/2,'I_S','Ea'),\n\n ('I_Pa','Sa',p[\"R0\"]/k_norm*p['beta']/2,'I_Pa','Ea'),\n ('I_Aa','Sa',p[\"R0\"]/k_norm*p['recovery_rate']/2,'I_Aa','Ea'),\n ('I_Sa','Sa',p[\"R0\"]/k_norm*p['recovery_rate']/2,'I_Sa','Ea'),\n\n ('I_P','S',p[\"R0\"]/k_norm*p['beta']/2,'I_P','E'),\n ('I_A','S',p[\"R0\"]/k_norm*p['recovery_rate']/2,'I_A','E'),\n ('I_S','S',p[\"R0\"]/k_norm*p['recovery_rate']/2,'I_S','E')])\n model.set_network(N, edge_weight_tuples)\n\n del edge_weight_tuples\n\n model.set_random_initial_conditions({ 'Sa': Sa0, 'S': S0, 'I_P': IP0, 'I_Pa': IPa0})\n\n del p\n del a\n del q\n del N\n\n t, result = model.simulate(tmax = time , sampling_dt = sampling_dt)\n\n del model\n del t\n del time\n del sampling_dt\n\n results = max(result['R']),max(result['Ra']),max(result['X']),max(result['Xa']),max(result['C'])\n\n del result\n\n return results\n results = mixed(**kwargs)\n\n return results\n"
] | [
[
"numpy.sqrt",
"matplotlib.pyplot.subplots",
"numpy.cov",
"numpy.diff",
"matplotlib.pyplot.show",
"matplotlib.ticker.PercentFormatter"
],
[
"scipy.stats.expon.rvs",
"numpy.linspace",
"numpy.random.choice",
"numpy.random.permutation",
"numpy.random.binomial",
"numpy.argsort",
"numpy.array",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
laobadao/TF_VS_Caffe | [
"943b47daefa42f07db285a331647d09669085f9f",
"943b47daefa42f07db285a331647d09669085f9f",
"943b47daefa42f07db285a331647d09669085f9f"
] | [
"processor/utils/label_map_util.py",
"np_processor/processor/np_utils/visualization_utils.py",
"lib_pro/processor/utils/grid_anchor_generator.py"
] | [
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Label map utility functions.\"\"\"\n\nimport logging\n\nimport tensorflow as tf\nfrom google.protobuf import text_format\nfrom ..utils import string_int_label_map_pb2\n\n\ndef _validate_label_map(label_map):\n \"\"\"Checks if a label map is valid.\n\n Args:\n label_map: StringIntLabelMap to validate.\n\n Raises:\n ValueError: if label map is invalid.\n \"\"\"\n for item in label_map.item:\n if item.id < 0:\n raise ValueError('Label map ids should be >= 0.')\n if (item.id == 0 and item.name != 'background' and\n item.display_name != 'background'):\n raise ValueError('Label map id 0 is reserved for the background label')\n\n\ndef create_category_index(categories):\n \"\"\"Creates dictionary of COCO compatible categories keyed by category id.\n\n Args:\n categories: a list of dicts, each of which has the following keys:\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name\n e.g., 'cat', 'dog', 'pizza'.\n\n Returns:\n category_index: a dict containing the same entries as categories, but keyed\n by the 'id' field of each category.\n \"\"\"\n category_index = {}\n for cat in categories:\n category_index[cat['id']] = cat\n return category_index\n\n\ndef get_max_label_map_index(label_map):\n \"\"\"Get maximum index in label map.\n\n Args:\n label_map: a StringIntLabelMapProto\n\n Returns:\n an integer\n \"\"\"\n return max([item.id for item in label_map.item])\n\n\ndef convert_label_map_to_categories(label_map,\n max_num_classes,\n use_display_name=True):\n \"\"\"Loads label map proto and returns categories list compatible with eval.\n\n This function loads a label map and returns a list of dicts, each of which\n has the following keys:\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name\n e.g., 'cat', 'dog', 'pizza'.\n We only allow class into the list if its id-label_id_offset is\n between 0 (inclusive) and max_num_classes (exclusive).\n If there are several items mapping to the same id in the label map,\n we will only keep the first one in the categories list.\n\n Args:\n label_map: a StringIntLabelMapProto or None. If None, a default categories\n list is created with max_num_classes categories.\n max_num_classes: maximum number of (consecutive) label indices to include.\n use_display_name: (boolean) choose whether to load 'display_name' field\n as category name. If False or if the display_name field does not exist,\n uses 'name' field as category names instead.\n Returns:\n categories: a list of dictionaries representing all possible categories.\n \"\"\"\n categories = []\n list_of_ids_already_added = []\n if not label_map:\n label_id_offset = 1\n for class_id in range(max_num_classes):\n categories.append({\n 'id': class_id + label_id_offset,\n 'name': 'category_{}'.format(class_id + label_id_offset)\n })\n return categories\n for item in label_map.item:\n if not 0 < item.id <= max_num_classes:\n logging.info('Ignore item %d since it falls outside of requested '\n 'label range.', item.id)\n continue\n if use_display_name and item.HasField('display_name'):\n name = item.display_name\n else:\n name = item.name\n if item.id not in list_of_ids_already_added:\n list_of_ids_already_added.append(item.id)\n categories.append({'id': item.id, 'name': name})\n return categories\n\n\ndef load_labelmap(path):\n \"\"\"Loads label map proto.\n\n Args:\n path: path to StringIntLabelMap proto text file.\n Returns:\n a StringIntLabelMapProto\n \"\"\"\n with tf.gfile.GFile(path, 'r') as fid:\n label_map_string = fid.read()\n label_map = string_int_label_map_pb2.StringIntLabelMap()\n try:\n text_format.Merge(label_map_string, label_map)\n except text_format.ParseError:\n label_map.ParseFromString(label_map_string)\n _validate_label_map(label_map)\n return label_map\n\n\ndef get_label_map_dict(label_map_path, use_display_name=False):\n \"\"\"Reads a label map and returns a dictionary of label names to id.\n\n Args:\n label_map_path: path to label_map.\n use_display_name: whether to use the label map items' display names as keys.\n\n Returns:\n A dictionary mapping label names to id.\n \"\"\"\n label_map = load_labelmap(label_map_path)\n label_map_dict = {}\n for item in label_map.item:\n if use_display_name:\n label_map_dict[item.display_name] = item.id\n else:\n label_map_dict[item.name] = item.id\n return label_map_dict\n\n\ndef create_category_index_from_labelmap(label_map_path):\n \"\"\"Reads a label map and returns a category index.\n\n Args:\n label_map_path: Path to `StringIntLabelMap` proto text file.\n\n Returns:\n A category index, which is a dictionary that maps integer ids to dicts\n containing categories, e.g.\n {1: {'id': 1, 'name': 'dog'}, 2: {'id': 2, 'name': 'cat'}, ...}\n \"\"\"\n label_map = load_labelmap(label_map_path)\n max_num_classes = max(item.id for item in label_map.item)\n categories = convert_label_map_to_categories(label_map, max_num_classes)\n return create_category_index(categories)\n\n\ndef create_class_agnostic_category_index():\n \"\"\"Creates a category index with a single `object` class.\"\"\"\n return {1: {'id': 1, 'name': 'object'}}\n",
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"A set of functions that are used for visualization.\n\nThese functions often receive an image, perform some visualization on the image.\nThe functions do not return a value, instead they modify the image itself.\n\n\"\"\"\nimport collections\nimport functools\n# Set headless-friendly backend.\nimport matplotlib; matplotlib.use('Agg') # pylint: disable=multiple-statements\nimport matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top\nimport numpy as np\nimport PIL.Image as Image\nimport PIL.ImageColor as ImageColor\nimport PIL.ImageDraw as ImageDraw\nimport PIL.ImageFont as ImageFont\nimport six\nimport tensorflow as tf\n\nfrom platformx.plat_tensorflow.tools.processor.np_utils import standard_fields as fields\n\n\n_TITLE_LEFT_MARGIN = 10\n_TITLE_TOP_MARGIN = 10\nSTANDARD_COLORS = [\n 'AliceBlue', 'Chartreuse', 'Aqua', 'Aquamarine', 'Azure', 'Beige', 'Bisque',\n 'BlanchedAlmond', 'BlueViolet', 'BurlyWood', 'CadetBlue', 'AntiqueWhite',\n 'Chocolate', 'Coral', 'CornflowerBlue', 'Cornsilk', 'Crimson', 'Cyan',\n 'DarkCyan', 'DarkGoldenRod', 'DarkGrey', 'DarkKhaki', 'DarkOrange',\n 'DarkOrchid', 'DarkSalmon', 'DarkSeaGreen', 'DarkTurquoise', 'DarkViolet',\n 'DeepPink', 'DeepSkyBlue', 'DodgerBlue', 'FireBrick', 'FloralWhite',\n 'ForestGreen', 'Fuchsia', 'Gainsboro', 'GhostWhite', 'Gold', 'GoldenRod',\n 'Salmon', 'Tan', 'HoneyDew', 'HotPink', 'IndianRed', 'Ivory', 'Khaki',\n 'Lavender', 'LavenderBlush', 'LawnGreen', 'LemonChiffon', 'LightBlue',\n 'LightCoral', 'LightCyan', 'LightGoldenRodYellow', 'LightGray', 'LightGrey',\n 'LightGreen', 'LightPink', 'LightSalmon', 'LightSeaGreen', 'LightSkyBlue',\n 'LightSlateGray', 'LightSlateGrey', 'LightSteelBlue', 'LightYellow', 'Lime',\n 'LimeGreen', 'Linen', 'Magenta', 'MediumAquaMarine', 'MediumOrchid',\n 'MediumPurple', 'MediumSeaGreen', 'MediumSlateBlue', 'MediumSpringGreen',\n 'MediumTurquoise', 'MediumVioletRed', 'MintCream', 'MistyRose', 'Moccasin',\n 'NavajoWhite', 'OldLace', 'Olive', 'OliveDrab', 'Orange', 'OrangeRed',\n 'Orchid', 'PaleGoldenRod', 'PaleGreen', 'PaleTurquoise', 'PaleVioletRed',\n 'PapayaWhip', 'PeachPuff', 'Peru', 'Pink', 'Plum', 'PowderBlue', 'Purple',\n 'Red', 'RosyBrown', 'RoyalBlue', 'SaddleBrown', 'Green', 'SandyBrown',\n 'SeaGreen', 'SeaShell', 'Sienna', 'Silver', 'SkyBlue', 'SlateBlue',\n 'SlateGray', 'SlateGrey', 'Snow', 'SpringGreen', 'SteelBlue', 'GreenYellow',\n 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat', 'White',\n 'WhiteSmoke', 'Yellow', 'YellowGreen'\n]\n\n\ndef save_image_array_as_png(image, output_path):\n \"\"\"Saves an image (represented as a numpy array) to PNG.\n\n Args:\n image: a numpy array with shape [height, width, 3].\n output_path: path to which image should be written.\n \"\"\"\n image_pil = Image.fromarray(np.uint8(image)).convert('RGB')\n with tf.gfile.Open(output_path, 'w') as fid:\n image_pil.save(fid, 'PNG')\n\n\ndef encode_image_array_as_png_str(image):\n \"\"\"Encodes a numpy array into a PNG string.\n\n Args:\n image: a numpy array with shape [height, width, 3].\n\n Returns:\n PNG encoded image string.\n \"\"\"\n image_pil = Image.fromarray(np.uint8(image))\n output = six.BytesIO()\n image_pil.save(output, format='PNG')\n png_string = output.getvalue()\n output.close()\n return png_string\n\n\ndef draw_bounding_box_on_image_array(image,\n ymin,\n xmin,\n ymax,\n xmax,\n color='red',\n thickness=4,\n display_str_list=(),\n use_normalized_coordinates=True):\n \"\"\"Adds a bounding box to an image (numpy array).\n\n Bounding box coordinates can be specified in either absolute (pixel) or\n normalized coordinates by setting the use_normalized_coordinates argument.\n\n Args:\n image: a numpy array with shape [height, width, 3].\n ymin: ymin of bounding box.\n xmin: xmin of bounding box.\n ymax: ymax of bounding box.\n xmax: xmax of bounding box.\n color: color to draw bounding box. Default is red.\n thickness: line thickness. Default value is 4.\n display_str_list: list of strings to display in box\n (each to be shown on its own line).\n use_normalized_coordinates: If True (default), treat coordinates\n ymin, xmin, ymax, xmax as relative to the image. Otherwise treat\n coordinates as absolute.\n \"\"\"\n image_pil = Image.fromarray(np.uint8(image)).convert('RGB')\n draw_bounding_box_on_image(image_pil, ymin, xmin, ymax, xmax, color,\n thickness, display_str_list,\n use_normalized_coordinates)\n np.copyto(image, np.array(image_pil))\n\n\ndef draw_bounding_box_on_image(image,\n ymin,\n xmin,\n ymax,\n xmax,\n color='red',\n thickness=4,\n display_str_list=(),\n use_normalized_coordinates=True):\n \"\"\"Adds a bounding box to an image.\n\n Bounding box coordinates can be specified in either absolute (pixel) or\n normalized coordinates by setting the use_normalized_coordinates argument.\n\n Each string in display_str_list is displayed on a separate line above the\n bounding box in black text on a rectangle filled with the input 'color'.\n If the top of the bounding box extends to the edge of the image, the strings\n are displayed below the bounding box.\n\n Args:\n image: a PIL.Image object.\n ymin: ymin of bounding box.\n xmin: xmin of bounding box.\n ymax: ymax of bounding box.\n xmax: xmax of bounding box.\n color: color to draw bounding box. Default is red.\n thickness: line thickness. Default value is 4.\n display_str_list: list of strings to display in box\n (each to be shown on its own line).\n use_normalized_coordinates: If True (default), treat coordinates\n ymin, xmin, ymax, xmax as relative to the image. Otherwise treat\n coordinates as absolute.\n \"\"\"\n draw = ImageDraw.Draw(image)\n im_width, im_height = image.size\n if use_normalized_coordinates:\n (left, right, top, bottom) = (xmin * im_width, xmax * im_width,\n ymin * im_height, ymax * im_height)\n else:\n (left, right, top, bottom) = (xmin, xmax, ymin, ymax)\n draw.line([(left, top), (left, bottom), (right, bottom),\n (right, top), (left, top)], width=thickness, fill=color)\n try:\n font = ImageFont.truetype('arial.ttf', 24)\n except IOError:\n font = ImageFont.load_default()\n\n # If the total height of the display strings added to the top of the bounding\n # box exceeds the top of the image, stack the strings below the bounding box\n # instead of above.\n display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]\n # Each display_str has a top and bottom margin of 0.05x.\n total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)\n\n if top > total_display_str_height:\n text_bottom = top\n else:\n text_bottom = bottom + total_display_str_height\n # Reverse list and print from bottom to top.\n for display_str in display_str_list[::-1]:\n text_width, text_height = font.getsize(display_str)\n margin = np.ceil(0.05 * text_height)\n draw.rectangle(\n [(left, text_bottom - text_height - 2 * margin), (left + text_width,\n text_bottom)],\n fill=color)\n draw.text(\n (left + margin, text_bottom - text_height - margin),\n display_str,\n fill='black',\n font=font)\n text_bottom -= text_height - 2 * margin\n\n\ndef draw_bounding_boxes_on_image_array(image,\n boxes,\n color='red',\n thickness=4,\n display_str_list_list=()):\n \"\"\"Draws bounding boxes on image (numpy array).\n\n Args:\n image: a numpy array object.\n boxes: a 2 dimensional numpy array of [N, 4]: (ymin, xmin, ymax, xmax).\n The coordinates are in normalized format between [0, 1].\n color: color to draw bounding box. Default is red.\n thickness: line thickness. Default value is 4.\n display_str_list_list: list of list of strings.\n a list of strings for each bounding box.\n The reason to pass a list of strings for a\n bounding box is that it might contain\n multiple labels.\n\n Raises:\n ValueError: if boxes is not a [N, 4] array\n \"\"\"\n image_pil = Image.fromarray(image)\n draw_bounding_boxes_on_image(image_pil, boxes, color, thickness,\n display_str_list_list)\n np.copyto(image, np.array(image_pil))\n\n\ndef draw_bounding_boxes_on_image(image,\n boxes,\n color='red',\n thickness=4,\n display_str_list_list=()):\n \"\"\"Draws bounding boxes on image.\n\n Args:\n image: a PIL.Image object.\n boxes: a 2 dimensional numpy array of [N, 4]: (ymin, xmin, ymax, xmax).\n The coordinates are in normalized format between [0, 1].\n color: color to draw bounding box. Default is red.\n thickness: line thickness. Default value is 4.\n display_str_list_list: list of list of strings.\n a list of strings for each bounding box.\n The reason to pass a list of strings for a\n bounding box is that it might contain\n multiple labels.\n\n Raises:\n ValueError: if boxes is not a [N, 4] array\n \"\"\"\n boxes_shape = boxes.shape\n if not boxes_shape:\n return\n if len(boxes_shape) != 2 or boxes_shape[1] != 4:\n raise ValueError('Input must be of size [N, 4]')\n for i in range(boxes_shape[0]):\n display_str_list = ()\n if display_str_list_list:\n display_str_list = display_str_list_list[i]\n draw_bounding_box_on_image(image, boxes[i, 0], boxes[i, 1], boxes[i, 2],\n boxes[i, 3], color, thickness, display_str_list)\n\n\ndef _visualize_boxes(image, boxes, classes, scores, category_index, **kwargs):\n return visualize_boxes_and_labels_on_image_array(\n image, boxes, classes, scores, category_index=category_index, **kwargs)\n\n\ndef _visualize_boxes_and_masks(image, boxes, classes, scores, masks,\n category_index, **kwargs):\n return visualize_boxes_and_labels_on_image_array(\n image,\n boxes,\n classes,\n scores,\n category_index=category_index,\n instance_masks=masks,\n **kwargs)\n\n\ndef _visualize_boxes_and_keypoints(image, boxes, classes, scores, keypoints,\n category_index, **kwargs):\n return visualize_boxes_and_labels_on_image_array(\n image,\n boxes,\n classes,\n scores,\n category_index=category_index,\n keypoints=keypoints,\n **kwargs)\n\n\ndef _visualize_boxes_and_masks_and_keypoints(\n image, boxes, classes, scores, masks, keypoints, category_index, **kwargs):\n return visualize_boxes_and_labels_on_image_array(\n image,\n boxes,\n classes,\n scores,\n category_index=category_index,\n instance_masks=masks,\n keypoints=keypoints,\n **kwargs)\n\n\ndef draw_bounding_boxes_on_image_tensors(images,\n boxes,\n classes,\n scores,\n category_index,\n instance_masks=None,\n keypoints=None,\n max_boxes_to_draw=20,\n min_score_thresh=0.2,\n use_normalized_coordinates=True):\n \"\"\"Draws bounding boxes, masks, and keypoints on batch of image tensors.\n\n Args:\n images: A 4D uint8 image tensor of shape [N, H, W, C]. If C > 3, additional\n channels will be ignored.\n boxes: [N, max_detections, 4] float32 tensor of detection boxes.\n classes: [N, max_detections] int tensor of detection classes. Note that\n classes are 1-indexed.\n scores: [N, max_detections] float32 tensor of detection scores.\n category_index: a dict that maps integer ids to category dicts. e.g.\n {1: {1: 'dog'}, 2: {2: 'cat'}, ...}\n instance_masks: A 4D uint8 tensor of shape [N, max_detection, H, W] with\n instance masks.\n keypoints: A 4D float32 tensor of shape [N, max_detection, num_keypoints, 2]\n with keypoints.\n max_boxes_to_draw: Maximum number of boxes to draw on an image. Default 20.\n min_score_thresh: Minimum score threshold for visualization. Default 0.2.\n use_normalized_coordinates: Whether to assume boxes and kepoints are in\n normalized coordinates (as opposed to absolute coordiantes).\n Default is True.\n\n Returns:\n 4D image tensor of type uint8, with boxes drawn on top.\n \"\"\"\n # Additional channels are being ignored.\n images = images[:, :, :, 0:3]\n visualization_keyword_args = {\n 'use_normalized_coordinates': use_normalized_coordinates,\n 'max_boxes_to_draw': max_boxes_to_draw,\n 'min_score_thresh': min_score_thresh,\n 'agnostic_mode': False,\n 'line_thickness': 4\n }\n\n if instance_masks is not None and keypoints is None:\n visualize_boxes_fn = functools.partial(\n _visualize_boxes_and_masks,\n category_index=category_index,\n **visualization_keyword_args)\n elems = [images, boxes, classes, scores, instance_masks]\n elif instance_masks is None and keypoints is not None:\n visualize_boxes_fn = functools.partial(\n _visualize_boxes_and_keypoints,\n category_index=category_index,\n **visualization_keyword_args)\n elems = [images, boxes, classes, scores, keypoints]\n elif instance_masks is not None and keypoints is not None:\n visualize_boxes_fn = functools.partial(\n _visualize_boxes_and_masks_and_keypoints,\n category_index=category_index,\n **visualization_keyword_args)\n elems = [images, boxes, classes, scores, instance_masks, keypoints]\n else:\n visualize_boxes_fn = functools.partial(\n _visualize_boxes,\n category_index=category_index,\n **visualization_keyword_args)\n elems = [images, boxes, classes, scores]\n\n def draw_boxes(image_and_detections):\n \"\"\"Draws boxes on image.\"\"\"\n image_with_boxes = tf.py_func(visualize_boxes_fn, image_and_detections,\n tf.uint8)\n return image_with_boxes\n\n images = tf.map_fn(draw_boxes, elems, dtype=tf.uint8, back_prop=False)\n return images\n\n\ndef draw_side_by_side_evaluation_image(eval_dict,\n category_index,\n max_boxes_to_draw=20,\n min_score_thresh=0.2,\n use_normalized_coordinates=True):\n \"\"\"Creates a side-by-side image with detections and groundtruth.\n\n Bounding boxes (and instance masks, if available) are visualized on both\n subimages.\n\n Args:\n eval_dict: The evaluation dictionary returned by\n eval_util.result_dict_for_single_example().\n category_index: A category index (dictionary) produced from a labelmap.\n max_boxes_to_draw: The maximum number of boxes to draw for detections.\n min_score_thresh: The minimum score threshold for showing detections.\n use_normalized_coordinates: Whether to assume boxes and kepoints are in\n normalized coordinates (as opposed to absolute coordiantes).\n Default is True.\n\n Returns:\n A [1, H, 2 * W, C] uint8 tensor. The subimage on the left corresponds to\n detections, while the subimage on the right corresponds to groundtruth.\n \"\"\"\n detection_fields = fields.DetectionResultFields()\n input_data_fields = fields.InputDataFields()\n instance_masks = None\n if detection_fields.detection_masks in eval_dict:\n instance_masks = tf.cast(\n tf.expand_dims(eval_dict[detection_fields.detection_masks], axis=0),\n tf.uint8)\n keypoints = None\n if detection_fields.detection_keypoints in eval_dict:\n keypoints = tf.expand_dims(\n eval_dict[detection_fields.detection_keypoints], axis=0)\n groundtruth_instance_masks = None\n if input_data_fields.groundtruth_instance_masks in eval_dict:\n groundtruth_instance_masks = tf.cast(\n tf.expand_dims(\n eval_dict[input_data_fields.groundtruth_instance_masks], axis=0),\n tf.uint8)\n images_with_detections = draw_bounding_boxes_on_image_tensors(\n eval_dict[input_data_fields.original_image],\n tf.expand_dims(eval_dict[detection_fields.detection_boxes], axis=0),\n tf.expand_dims(eval_dict[detection_fields.detection_classes], axis=0),\n tf.expand_dims(eval_dict[detection_fields.detection_scores], axis=0),\n category_index,\n instance_masks=instance_masks,\n keypoints=keypoints,\n max_boxes_to_draw=max_boxes_to_draw,\n min_score_thresh=min_score_thresh,\n use_normalized_coordinates=use_normalized_coordinates)\n images_with_groundtruth = draw_bounding_boxes_on_image_tensors(\n eval_dict[input_data_fields.original_image],\n tf.expand_dims(eval_dict[input_data_fields.groundtruth_boxes], axis=0),\n tf.expand_dims(eval_dict[input_data_fields.groundtruth_classes], axis=0),\n tf.expand_dims(\n tf.ones_like(\n eval_dict[input_data_fields.groundtruth_classes],\n dtype=tf.float32),\n axis=0),\n category_index,\n instance_masks=groundtruth_instance_masks,\n keypoints=None,\n max_boxes_to_draw=None,\n min_score_thresh=0.0,\n use_normalized_coordinates=use_normalized_coordinates)\n return tf.concat([images_with_detections, images_with_groundtruth], axis=2)\n\n\ndef draw_keypoints_on_image_array(image,\n keypoints,\n color='red',\n radius=2,\n use_normalized_coordinates=True):\n \"\"\"Draws keypoints on an image (numpy array).\n\n Args:\n image: a numpy array with shape [height, width, 3].\n keypoints: a numpy array with shape [num_keypoints, 2].\n color: color to draw the keypoints with. Default is red.\n radius: keypoint radius. Default value is 2.\n use_normalized_coordinates: if True (default), treat keypoint values as\n relative to the image. Otherwise treat them as absolute.\n \"\"\"\n image_pil = Image.fromarray(np.uint8(image)).convert('RGB')\n draw_keypoints_on_image(image_pil, keypoints, color, radius,\n use_normalized_coordinates)\n np.copyto(image, np.array(image_pil))\n\n\ndef draw_keypoints_on_image(image,\n keypoints,\n color='red',\n radius=2,\n use_normalized_coordinates=True):\n \"\"\"Draws keypoints on an image.\n\n Args:\n image: a PIL.Image object.\n keypoints: a numpy array with shape [num_keypoints, 2].\n color: color to draw the keypoints with. Default is red.\n radius: keypoint radius. Default value is 2.\n use_normalized_coordinates: if True (default), treat keypoint values as\n relative to the image. Otherwise treat them as absolute.\n \"\"\"\n draw = ImageDraw.Draw(image)\n im_width, im_height = image.size\n keypoints_x = [k[1] for k in keypoints]\n keypoints_y = [k[0] for k in keypoints]\n if use_normalized_coordinates:\n keypoints_x = tuple([im_width * x for x in keypoints_x])\n keypoints_y = tuple([im_height * y for y in keypoints_y])\n for keypoint_x, keypoint_y in zip(keypoints_x, keypoints_y):\n draw.ellipse([(keypoint_x - radius, keypoint_y - radius),\n (keypoint_x + radius, keypoint_y + radius)],\n outline=color, fill=color)\n\n\ndef draw_mask_on_image_array(image, mask, color='red', alpha=0.4):\n \"\"\"Draws mask on an image.\n\n Args:\n image: uint8 numpy array with shape (img_height, img_height, 3)\n mask: a uint8 numpy array of shape (img_height, img_height) with\n values between either 0 or 1.\n color: color to draw the keypoints with. Default is red.\n alpha: transparency value between 0 and 1. (default: 0.4)\n\n Raises:\n ValueError: On incorrect data type for image or masks.\n \"\"\"\n if image.dtype != np.uint8:\n raise ValueError('`image` not of type np.uint8')\n if mask.dtype != np.uint8:\n raise ValueError('`mask` not of type np.uint8')\n if np.any(np.logical_and(mask != 1, mask != 0)):\n raise ValueError('`mask` elements should be in [0, 1]')\n if image.shape[:2] != mask.shape:\n raise ValueError('The image has spatial dimensions %s but the mask has '\n 'dimensions %s' % (image.shape[:2], mask.shape))\n rgb = ImageColor.getrgb(color)\n pil_image = Image.fromarray(image)\n\n solid_color = np.expand_dims(\n np.ones_like(mask), axis=2) * np.reshape(list(rgb), [1, 1, 3])\n pil_solid_color = Image.fromarray(np.uint8(solid_color)).convert('RGBA')\n pil_mask = Image.fromarray(np.uint8(255.0*alpha*mask)).convert('L')\n pil_image = Image.composite(pil_solid_color, pil_image, pil_mask)\n np.copyto(image, np.array(pil_image.convert('RGB')))\n\n\ndef visualize_boxes_and_labels_on_image_array(\n image,\n boxes,\n classes,\n scores,\n category_index,\n instance_masks=None,\n instance_boundaries=None,\n keypoints=None,\n use_normalized_coordinates=False,\n max_boxes_to_draw=20,\n min_score_thresh=.5,\n agnostic_mode=False,\n line_thickness=4,\n groundtruth_box_visualization_color='black',\n skip_scores=False,\n skip_labels=False):\n \"\"\"Overlay labeled boxes on an image with formatted scores and label names.\n\n This function groups boxes that correspond to the same location\n and creates a display string for each detection and overlays these\n on the image. Note that this function modifies the image in place, and returns\n that same image.\n\n Args:\n image: uint8 numpy array with shape (img_height, img_width, 3)\n boxes: a numpy array of shape [N, 4]\n classes: a numpy array of shape [N]. Note that class indices are 1-based,\n and match the keys in the label map.\n scores: a numpy array of shape [N] or None. If scores=None, then\n this function assumes that the boxes to be plotted are groundtruth\n boxes and plot all boxes as black with no classes or scores.\n category_index: a dict containing category dictionaries (each holding\n category index `id` and category name `name`) keyed by category indices.\n instance_masks: a numpy array of shape [N, image_height, image_width] with\n values ranging between 0 and 1, can be None.\n instance_boundaries: a numpy array of shape [N, image_height, image_width]\n with values ranging between 0 and 1, can be None.\n keypoints: a numpy array of shape [N, num_keypoints, 2], can\n be None\n use_normalized_coordinates: whether boxes is to be interpreted as\n normalized coordinates or not.\n max_boxes_to_draw: maximum number of boxes to visualize. If None, draw\n all boxes.\n min_score_thresh: minimum score threshold for a box to be visualized\n agnostic_mode: boolean (default: False) controlling whether to evaluate in\n class-agnostic mode or not. This mode will display scores but ignore\n classes.\n line_thickness: integer (default: 4) controlling line width of the boxes.\n groundtruth_box_visualization_color: box color for visualizing groundtruth\n boxes\n skip_scores: whether to skip score when drawing a single detection\n skip_labels: whether to skip label when drawing a single detection\n\n Returns:\n uint8 numpy array with shape (img_height, img_width, 3) with overlaid boxes.\n \"\"\"\n # Create a display string (and color) for every box location, group any boxes\n # that correspond to the same location.\n box_to_display_str_map = collections.defaultdict(list)\n box_to_color_map = collections.defaultdict(str)\n box_to_instance_masks_map = {}\n box_to_instance_boundaries_map = {}\n box_to_keypoints_map = collections.defaultdict(list)\n if not max_boxes_to_draw:\n max_boxes_to_draw = boxes.shape[0]\n for i in range(min(max_boxes_to_draw, boxes.shape[0])):\n if scores is None or scores[i] > min_score_thresh:\n box = tuple(boxes[i].tolist())\n if instance_masks is not None:\n box_to_instance_masks_map[box] = instance_masks[i]\n if instance_boundaries is not None:\n box_to_instance_boundaries_map[box] = instance_boundaries[i]\n if keypoints is not None:\n box_to_keypoints_map[box].extend(keypoints[i])\n if scores is None:\n box_to_color_map[box] = groundtruth_box_visualization_color\n else:\n display_str = ''\n if not skip_labels:\n if not agnostic_mode:\n if classes[i] in category_index.keys():\n class_name = category_index[classes[i]]['name']\n else:\n class_name = 'N/A'\n display_str = str(class_name)\n if not skip_scores:\n if not display_str:\n display_str = '{}%'.format(int(100*scores[i]))\n else:\n display_str = '{}: {}%'.format(display_str, int(100*scores[i]))\n box_to_display_str_map[box].append(display_str)\n if agnostic_mode:\n box_to_color_map[box] = 'DarkOrange'\n else:\n box_to_color_map[box] = STANDARD_COLORS[\n classes[i] % len(STANDARD_COLORS)]\n\n # Draw all boxes onto image.\n for box, color in box_to_color_map.items():\n ymin, xmin, ymax, xmax = box\n if instance_masks is not None:\n draw_mask_on_image_array(\n image,\n box_to_instance_masks_map[box],\n color=color\n )\n if instance_boundaries is not None:\n draw_mask_on_image_array(\n image,\n box_to_instance_boundaries_map[box],\n color='red',\n alpha=1.0\n )\n draw_bounding_box_on_image_array(\n image,\n ymin,\n xmin,\n ymax,\n xmax,\n color=color,\n thickness=line_thickness,\n display_str_list=box_to_display_str_map[box],\n use_normalized_coordinates=use_normalized_coordinates)\n if keypoints is not None:\n draw_keypoints_on_image_array(\n image,\n box_to_keypoints_map[box],\n color=color,\n radius=line_thickness / 2,\n use_normalized_coordinates=use_normalized_coordinates)\n\n return image\n\n\ndef add_cdf_image_summary(values, name):\n \"\"\"Adds a tf.summary.image for a CDF plot of the values.\n\n Normalizes `values` such that they sum to 1, plots the cumulative distribution\n function and creates a tf image summary.\n\n Args:\n values: a 1-D float32 tensor containing the values.\n name: name for the image summary.\n \"\"\"\n def cdf_plot(values):\n \"\"\"Numpy function to plot CDF.\"\"\"\n normalized_values = values / np.sum(values)\n sorted_values = np.sort(normalized_values)\n cumulative_values = np.cumsum(sorted_values)\n fraction_of_examples = (np.arange(cumulative_values.size, dtype=np.float32)\n / cumulative_values.size)\n fig = plt.figure(frameon=False)\n ax = fig.add_subplot('111')\n ax.plot(fraction_of_examples, cumulative_values)\n ax.set_ylabel('cumulative normalized values')\n ax.set_xlabel('fraction of examples')\n fig.canvas.draw()\n width, height = fig.get_size_inches() * fig.get_dpi()\n image = np.fromstring(fig.canvas.tostring_rgb(), dtype='uint8').reshape(\n 1, int(height), int(width), 3)\n return image\n cdf_plot = tf.py_func(cdf_plot, [values], tf.uint8)\n tf.summary.image(name, cdf_plot)\n\n\ndef add_hist_image_summary(values, bins, name):\n \"\"\"Adds a tf.summary.image for a histogram plot of the values.\n\n Plots the histogram of values and creates a tf image summary.\n\n Args:\n values: a 1-D float32 tensor containing the values.\n bins: bin edges which will be directly passed to np.histogram.\n name: name for the image summary.\n \"\"\"\n\n def hist_plot(values, bins):\n \"\"\"Numpy function to plot hist.\"\"\"\n fig = plt.figure(frameon=False)\n ax = fig.add_subplot('111')\n y, x = np.histogram(values, bins=bins)\n ax.plot(x[:-1], y)\n ax.set_ylabel('count')\n ax.set_xlabel('value')\n fig.canvas.draw()\n width, height = fig.get_size_inches() * fig.get_dpi()\n image = np.fromstring(\n fig.canvas.tostring_rgb(), dtype='uint8').reshape(\n 1, int(height), int(width), 3)\n return image\n hist_plot = tf.py_func(hist_plot, [values, bins], tf.uint8)\n tf.summary.image(name, hist_plot)\n",
"\"\"\"Generates grid anchors on the fly as used in Faster RCNN.\n\nGenerates grid anchors on the fly as described in:\n\"Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks\"\nShaoqing Ren, Kaiming He, Ross Girshick, and Jian Sun.\n\"\"\"\n\nimport tensorflow as tf\n\nfrom ..utils import ops, box_list, anchor_generator\n\n\nclass GridAnchorGenerator(anchor_generator.AnchorGenerator):\n \"\"\"Generates a grid of anchors at given scales and aspect ratios.\"\"\"\n\n def __init__(self,\n scales=(0.5, 1.0, 2.0),\n aspect_ratios=(0.5, 1.0, 2.0),\n base_anchor_size=None,\n anchor_stride=None,\n anchor_offset=None):\n \"\"\"Constructs a GridAnchorGenerator.\n\n Args:\n scales: a list of (float) scales, default=(0.5, 1.0, 2.0)\n aspect_ratios: a list of (float) aspect ratios, default=(0.5, 1.0, 2.0)\n base_anchor_size: base anchor size as height, width (\n (length-2 float32 list or tensor, default=[256, 256])\n anchor_stride: difference in centers between base anchors for adjacent\n grid positions (length-2 float32 list or tensor,\n default=[16, 16])\n anchor_offset: center of the anchor with scale and aspect ratio 1 for the\n upper left element of the grid, this should be zero for\n feature networks with only VALID padding and even receptive\n field size, but may need additional calculation if other\n padding is used (length-2 float32 list or tensor,\n default=[0, 0])\n \"\"\"\n # Handle argument defaults\n if base_anchor_size is None:\n base_anchor_size = [256, 256]\n base_anchor_size = tf.to_float(tf.convert_to_tensor(base_anchor_size))\n if anchor_stride is None:\n anchor_stride = [16, 16]\n anchor_stride = tf.to_float(tf.convert_to_tensor(anchor_stride))\n if anchor_offset is None:\n anchor_offset = [0, 0]\n anchor_offset = tf.to_float(tf.convert_to_tensor(anchor_offset))\n\n self._scales = scales\n self._aspect_ratios = aspect_ratios\n self._base_anchor_size = base_anchor_size\n self._anchor_stride = anchor_stride\n self._anchor_offset = anchor_offset\n\n def name_scope(self):\n return 'GridAnchorGenerator'\n\n def num_anchors_per_location(self):\n \"\"\"Returns the number of anchors per spatial location.\n\n Returns:\n a list of integers, one for each expected feature map to be passed to\n the `generate` function.\n \"\"\"\n return [len(self._scales) * len(self._aspect_ratios)]\n\n def _generate(self, feature_map_shape_list):\n \"\"\"Generates a collection of bounding boxes to be used as anchors.\n\n Args:\n feature_map_shape_list: list of pairs of convnet layer resolutions in the\n format [(height_0, width_0)]. For example, setting\n feature_map_shape_list=[(8, 8)] asks for anchors that correspond\n to an 8x8 layer. For this anchor generator, only lists of length 1 are\n allowed.\n\n Returns:\n boxes_list: a list of BoxLists each holding anchor boxes corresponding to\n the input feature map shapes.\n\n Raises:\n ValueError: if feature_map_shape_list, box_specs_list do not have the same\n length.\n ValueError: if feature_map_shape_list does not consist of pairs of\n integers\n \"\"\"\n if not (isinstance(feature_map_shape_list, list)\n and len(feature_map_shape_list) == 1):\n raise ValueError('feature_map_shape_list must be a list of length 1.')\n if not all([isinstance(list_item, tuple) and len(list_item) == 2\n for list_item in feature_map_shape_list]):\n raise ValueError('feature_map_shape_list must be a list of pairs.')\n grid_height, grid_width = feature_map_shape_list[0]\n scales_grid, aspect_ratios_grid = ops.meshgrid(self._scales,\n self._aspect_ratios)\n scales_grid = tf.reshape(scales_grid, [-1])\n aspect_ratios_grid = tf.reshape(aspect_ratios_grid, [-1])\n anchors = tile_anchors(grid_height,\n grid_width,\n scales_grid,\n aspect_ratios_grid,\n self._base_anchor_size,\n self._anchor_stride,\n self._anchor_offset)\n\n num_anchors = anchors.num_boxes_static()\n if num_anchors is None:\n num_anchors = anchors.num_boxes()\n anchor_indices = tf.zeros([num_anchors])\n anchors.add_field('feature_map_index', anchor_indices)\n return [anchors]\n\n\ndef tile_anchors(grid_height,\n grid_width,\n scales,\n aspect_ratios,\n base_anchor_size,\n anchor_stride,\n anchor_offset):\n \"\"\"Create a tiled set of anchors strided along a grid in image space.\n\n This op creates a set of anchor boxes by placing a \"basis\" collection of\n boxes with user-specified scales and aspect ratios centered at evenly\n distributed points along a grid. The basis collection is specified via the\n scale and aspect_ratios arguments. For example, setting scales=[.1, .2, .2]\n and aspect ratios = [2,2,1/2] means that we create three boxes: one with scale\n .1, aspect ratio 2, one with scale .2, aspect ratio 2, and one with scale .2\n and aspect ratio 1/2. Each box is multiplied by \"base_anchor_size\" before\n placing it over its respective center.\n\n Grid points are specified via grid_height, grid_width parameters as well as\n the anchor_stride and anchor_offset parameters.\n\n Args:\n grid_height: size of the grid in the y direction (int or int scalar tensor)\n grid_width: size of the grid in the x direction (int or int scalar tensor)\n scales: a 1-d (float) tensor representing the scale of each box in the\n basis set.\n aspect_ratios: a 1-d (float) tensor representing the aspect ratio of each\n box in the basis set. The length of the scales and aspect_ratios tensors\n must be equal.\n base_anchor_size: base anchor size as [height, width]\n (float tensor of shape [2])\n anchor_stride: difference in centers between base anchors for adjacent grid\n positions (float tensor of shape [2])\n anchor_offset: center of the anchor with scale and aspect ratio 1 for the\n upper left element of the grid, this should be zero for\n feature networks with only VALID padding and even receptive\n field size, but may need some additional calculation if other\n padding is used (float tensor of shape [2])\n Returns:\n a BoxList holding a collection of N anchor boxes\n \"\"\"\n ratio_sqrts = tf.sqrt(aspect_ratios)\n heights = scales / ratio_sqrts * base_anchor_size[0]\n widths = scales * ratio_sqrts * base_anchor_size[1]\n\n # Get a grid of box centers\n y_centers = tf.to_float(tf.range(grid_height))\n y_centers = y_centers * anchor_stride[0] + anchor_offset[0]\n x_centers = tf.to_float(tf.range(grid_width))\n x_centers = x_centers * anchor_stride[1] + anchor_offset[1]\n x_centers, y_centers = ops.meshgrid(x_centers, y_centers)\n\n widths_grid, x_centers_grid = ops.meshgrid(widths, x_centers)\n heights_grid, y_centers_grid = ops.meshgrid(heights, y_centers)\n bbox_centers = tf.stack([y_centers_grid, x_centers_grid], axis=3)\n bbox_sizes = tf.stack([heights_grid, widths_grid], axis=3)\n bbox_centers = tf.reshape(bbox_centers, [-1, 2])\n bbox_sizes = tf.reshape(bbox_sizes, [-1, 2])\n bbox_corners = _center_size_bbox_to_corners_bbox(bbox_centers, bbox_sizes)\n return box_list.BoxList(bbox_corners)\n\n\ndef _center_size_bbox_to_corners_bbox(centers, sizes):\n \"\"\"Converts bbox center-size representation to corners representation.\n\n Args:\n centers: a tensor with shape [N, 2] representing bounding box centers\n sizes: a tensor with shape [N, 2] representing bounding boxes\n\n Returns:\n corners: tensor with shape [N, 4] representing bounding boxes in corners\n representation\n \"\"\"\n return tf.concat([centers - .5 * sizes, centers + .5 * sizes], 1)\n"
] | [
[
"tensorflow.gfile.GFile"
],
[
"tensorflow.concat",
"numpy.cumsum",
"tensorflow.map_fn",
"numpy.histogram",
"tensorflow.py_func",
"numpy.ones_like",
"tensorflow.summary.image",
"numpy.uint8",
"numpy.arange",
"numpy.ceil",
"matplotlib.pyplot.figure",
"tensorflow.gfile.Open",
"numpy.logical_and",
"numpy.array",
"numpy.sum",
"matplotlib.use",
"tensorflow.ones_like",
"tensorflow.expand_dims",
"numpy.sort"
],
[
"tensorflow.convert_to_tensor",
"tensorflow.concat",
"tensorflow.range",
"tensorflow.zeros",
"tensorflow.stack",
"tensorflow.reshape",
"tensorflow.sqrt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
sirdr/magenta | [
"a1a78f08eff27951146196cc772296520a44f57b"
] | [
"magenta/models/nsynth/reader.py"
] | [
"# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Module to load the Dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom magenta.models.nsynth import utils\n\n\n# FFT Specgram Shapes\nSPECGRAM_REGISTRY = {\n (nfft, hop): shape for nfft, hop, shape in zip(\n [256, 256, 512, 512, 1024, 1024],\n [64, 128, 128, 256, 256, 512],\n [[129, 1001, 2], [129, 501, 2], [257, 501, 2],\n [257, 251, 2], [513, 251, 2], [513, 126, 2]])\n}\n\n\nclass NSynthDataset(object):\n \"\"\"Dataset object to help manage the TFRecord loading.\"\"\"\n\n def __init__(self, tfrecord_path, sample_length=64000, problem='nsynth',is_training=True):\n self.is_training = is_training\n self.record_path = tfrecord_path\n self.sample_length = sample_length\n self.problem = problem\n\n def get_example(self, batch_size):\n \"\"\"Get a single example from the tfrecord file.\n\n Args:\n batch_size: Int, minibatch size.\n\n Returns:\n tf.Example protobuf parsed from tfrecord.\n \"\"\"\n reader = tf.TFRecordReader()\n num_epochs = None if self.is_training else 1\n capacity = batch_size\n path_queue = tf.train.input_producer(\n [self.record_path],\n num_epochs=num_epochs,\n shuffle=self.is_training,\n capacity=capacity)\n unused_key, serialized_example = reader.read(path_queue)\n if self.problem=='nsynth':\n features = {\n \"note_str\": tf.FixedLenFeature([], dtype=tf.string),\n \"pitch\": tf.FixedLenFeature([1], dtype=tf.int64),\n \"velocity\": tf.FixedLenFeature([1], dtype=tf.int64),\n \"audio\": tf.FixedLenFeature([self.sample_length], dtype=tf.float32),\n \"qualities\": tf.FixedLenFeature([10], dtype=tf.int64),\n \"instrument_source\": tf.FixedLenFeature([1], dtype=tf.int64),\n \"instrument_family\": tf.FixedLenFeature([1], dtype=tf.int64),\n }\n elif self.problem=='dx7':\n features = {\n \"audio\": tf.FixedLenFeature([self.sample_length], dtype=tf.float32),\n \"parameters\": tf.FixedLenFeature([4], dtype=tf.float32)\n }\n\n example = tf.parse_single_example(serialized_example, features)\n return example\n\n def get_wavenet_batch(self, batch_size, length=64000):\n \"\"\"Get the Tensor expressions from the reader.\n\n Args:\n batch_size: The integer batch size.\n length: Number of timesteps of a cropped sample to produce.\n\n Returns:\n A dict of key:tensor pairs. This includes \"pitch\", \"wav\", and \"key\".\n \"\"\"\n length = min(length, self.sample_length)\n example = self.get_example(batch_size)\n wav = example[\"audio\"]\n wav = tf.slice(wav, [0], [self.sample_length])\n if self.problem=='nsynth':\n pitch = tf.squeeze(example[\"pitch\"])\n key = tf.squeeze(example[\"note_str\"])\n elif self.problem == 'dx7':\n parameters = tf.squeeze(example[\"parameters\"])\n\n if self.is_training:\n # random crop\n crop = tf.random_crop(wav, [length])\n crop = tf.reshape(crop, [1, length])\n if self.problem=='nsynth':\n key, crop, pitch = tf.train.shuffle_batch(\n [key, crop, pitch],\n batch_size,\n num_threads=4,\n capacity=500 * batch_size,\n min_after_dequeue=200 * batch_size)\n elif self.problem=='dx7':\n crop, parameters= tf.train.shuffle_batch(\n [crop, parameters],\n batch_size,\n num_threads=4,\n capacity=500 * batch_size,\n min_after_dequeue=200 * batch_size)\n else:\n # fixed center crop\n offset = (self.sample_length - length) // 2 # 24320\n crop = tf.slice(wav, [offset], [length])\n crop = tf.reshape(crop, [1, length])\n if self.problem=='nsynth':\n key, crop, pitch = tf.train.shuffle_batch(\n [key, crop, pitch],\n batch_size,\n num_threads=4,\n capacity=500 * batch_size,\n min_after_dequeue=200 * batch_size)\n elif self.problem=='dx7':\n crop, parameters = tf.train.shuffle_batch(\n [crop, parameters],\n batch_size,\n num_threads=4,\n capacity=500 * batch_size,\n min_after_dequeue=200 * batch_size)\n\n crop = tf.reshape(tf.cast(crop, tf.float32), [batch_size, length])\n if self.problem=='nsynth':\n pitch = tf.cast(pitch, tf.int32)\n return {\"pitch\": pitch, \"wav\": crop, \"key\": key}\n elif self.problem=='dx7':\n return {\"wav\": crop, \"parameters\": parameters}\n else:\n pitch = tf.cast(pitch, tf.int32)\n return {\"pitch\": pitch, \"wav\": crop, \"key\": key}\n\n\n def get_baseline_batch(self, hparams):\n \"\"\"Get the Tensor expressions from the reader.\n\n Args:\n hparams: Hyperparameters object with specgram parameters.\n\n Returns:\n A dict of key:tensor pairs. This includes \"pitch\", \"wav\", and \"key\".\n \"\"\"\n example = self.get_example(hparams.batch_size)\n audio = tf.slice(example[\"audio\"], [0], [64000])\n audio = tf.reshape(audio, [1, 64000])\n pitch = tf.slice(example[\"pitch\"], [0], [1])\n velocity = tf.slice(example[\"velocity\"], [0], [1])\n instrument_source = tf.slice(example[\"instrument_source\"], [0], [1])\n instrument_family = tf.slice(example[\"instrument_family\"], [0], [1])\n qualities = tf.slice(example[\"qualities\"], [0], [10])\n qualities = tf.reshape(qualities, [1, 10])\n\n # Get Specgrams\n hop_length = hparams.hop_length\n n_fft = hparams.n_fft\n if hop_length and n_fft:\n specgram = utils.tf_specgram(\n audio,\n n_fft=n_fft,\n hop_length=hop_length,\n mask=hparams.mask,\n log_mag=hparams.log_mag,\n re_im=hparams.re_im,\n dphase=hparams.dphase,\n mag_only=hparams.mag_only)\n shape = [1] + SPECGRAM_REGISTRY[(n_fft, hop_length)]\n if hparams.mag_only:\n shape[-1] = 1\n specgram = tf.reshape(specgram, shape)\n tf.logging.info(\"SPECGRAM BEFORE PADDING\", specgram)\n\n if hparams.pad:\n # Pad and crop specgram to 256x256\n num_padding = 2**int(np.ceil(np.log(shape[2]) / np.log(2))) - shape[2]\n tf.logging.info(\"num_pading: %d\" % num_padding)\n specgram = tf.reshape(specgram, shape)\n specgram = tf.pad(specgram, [[0, 0], [0, 0], [0, num_padding], [0, 0]])\n specgram = tf.slice(specgram, [0, 0, 0, 0], [-1, shape[1] - 1, -1, -1])\n tf.logging.info(\"SPECGRAM AFTER PADDING\", specgram)\n\n # Form a Batch\n if self.is_training:\n (audio, velocity, pitch, specgram,\n instrument_source, instrument_family,\n qualities) = tf.train.shuffle_batch(\n [\n audio, velocity, pitch, specgram,\n instrument_source, instrument_family, qualities\n ],\n batch_size=hparams.batch_size,\n capacity=20 * hparams.batch_size,\n min_after_dequeue=10 * hparams.batch_size,\n enqueue_many=True)\n elif hparams.batch_size > 1:\n (audio, velocity, pitch, specgram,\n instrument_source, instrument_family, qualities) = tf.train.batch(\n [\n audio, velocity, pitch, specgram,\n instrument_source, instrument_family, qualities\n ],\n batch_size=hparams.batch_size,\n capacity=10 * hparams.batch_size,\n enqueue_many=True)\n\n audio.set_shape([hparams.batch_size, 64000])\n\n batch = dict(\n pitch=pitch,\n velocity=velocity,\n audio=audio,\n instrument_source=instrument_source,\n instrument_family=instrument_family,\n qualities=qualities,\n spectrogram=specgram)\n\n return batch\n"
] | [
[
"numpy.log",
"tensorflow.FixedLenFeature",
"tensorflow.slice",
"tensorflow.reshape",
"tensorflow.cast",
"tensorflow.squeeze",
"tensorflow.random_crop",
"tensorflow.logging.info",
"tensorflow.pad",
"tensorflow.TFRecordReader",
"tensorflow.train.batch",
"tensorflow.parse_single_example",
"tensorflow.train.input_producer",
"tensorflow.train.shuffle_batch"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
agrippa/hpc-bootcamp | [
"7db008557a48e7a6d9eae2df2371a3c7b9f0678c"
] | [
"src/14_tf_regress/linear_regression.py"
] | [
"'''\nA linear regression learning algorithm example using TensorFlow library.\n\nThis example constructs a simple linear model of Y = W * X + b, using a gradient\ndescent optimizer to minize model error.\n\nAuthor: Aymeric Damien\nProject: https://github.com/aymericdamien/TensorFlow-Examples/\n'''\n\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy\nimport matplotlib.pyplot as plt\nrng = numpy.random\n\n# Parameters\n\n# The learning rate controls how large a step the optimizer can take through the\n# parameter space while exploring for a minimima.\nlearning_rate = 0.4\n\n# How many times to pass the training data through the model while updating\n# trainable variables. We perform many epochs to give the optimizer a chance to\n# minimize the model error.\ntraining_epochs = 40000\n\n# How often to display a summary of our model's current accuracy during training\ndisplay_step = 100\n\n# Load our data from a binary file on disk\ninput_X = numpy.fromfile('X.bin').reshape((-1, 3))\ninput_Y = numpy.fromfile('Y.bin')\n\nprint('Loaded ' + str(len(input_X)) + ' samples')\n\n# Split our data into 80% training data, 20% testing data\ntrain_ratio = 0.8\nn_samples = int(train_ratio * len(input_X))\n\n# Training Data\ntrain_X = input_X[:n_samples, :]\ntrain_Y = input_Y[:n_samples]\n\n# Model parameters. These placeholders are fed into the model by our application.\nX1 = tf.placeholder(\"float\")\nX2 = tf.placeholder(\"float\")\nY = tf.placeholder(\"float\")\n\n# Model weights. These weights are initialized to a random number, and then\n# tuned by the optimizer to improve model accuracy.\nW1 = tf.Variable(rng.randn(), name=\"weight1\")\nW2 = tf.Variable(rng.randn(), name=\"weight2\")\n\n# Construct a linear model that matches the structure of the original 1D\n# iterative averaging example: X1*W1 + X2*W2\n#\n# Note that while the structure is the same, it is up to Tensorflow to learn the\n# weights of the equation.\npred = tf.add(tf.multiply(X1, W1),\n tf.multiply(X2, W2))\n\n# Mean squared error measures the difference between the expected values for\n# each sample and the value computed by the model.\ncost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)\n\n# Gradient descent, our optimizer for this problem.\n# Note, minimize() knows to modify W and b because Variable objects are\n# trainable by default\n#\n# This code configures the optimizer with a learning rate (i.e. how large its\n# updates to the model variables can be), and then points it to the value we\n# would like it to minimize: the cost of the model.\noptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n\n# An operation that initializes our weights (i.e. assigns their default values)\ninit = tf.global_variables_initializer()\n\n# Start training\nwith tf.Session() as sess:\n\n # Run the initializer\n sess.run(init)\n\n # Show what weights our model is initialized with\n print(\"Initialized: W=\", sess.run(W1), sess.run(W2))\n\n # Execute several training epochs\n for epoch in range(training_epochs):\n # Pass the training data through the optimizer, allowing it to update\n # the variables in our model to reduce 'cost'\n sess.run(optimizer, feed_dict={X1: train_X[:, 0],\n X2: train_X[:, 2],\n Y: train_Y})\n\n # Display logs every 'display_step' steps, with information on our\n # current model weights and cost.\n if (epoch+1) % display_step == 0:\n c = sess.run(cost, feed_dict={X1: train_X[:, 0], X2: train_X[:, 2], Y: train_Y})\n print(\"Epoch:\", '%04d' % (epoch+1), \"cost=\", \"{:.9f}\".format(c), \\\n \"W=\", sess.run(W1), sess.run(W2))\n\n print(\"Optimization Finished!\")\n training_cost = sess.run(cost, feed_dict={X1: train_X[:, 0], X2: train_X[:, 2], Y: train_Y})\n print(\"Training cost=\", training_cost, \"W=\", sess.run(W1), sess.run(W2), '\\n')\n\n # Testing data, to validate the accuracy of our model against unseen samples.\n test_X = input_X[n_samples:, :]\n test_Y = input_Y[n_samples:]\n\n # Compute our cost/error against the testing samples\n print(\"Testing... (Mean square loss Comparison)\")\n testing_cost = sess.run(\n tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * test_X.shape[0]),\n feed_dict={X1: test_X[:, 0], X2: test_X[:, 2], Y: test_Y}) # same function as cost above\n print(\"Testing cost=\", testing_cost)\n print(\"Absolute mean square loss difference:\", abs(\n training_cost - testing_cost))\n"
] | [
[
"numpy.fromfile",
"tensorflow.multiply",
"tensorflow.pow",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.Session"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
mmagnuski/sarna | [
"0b4b7a5a9d4747724ff739c4e11bbbda1b286e92",
"0b4b7a5a9d4747724ff739c4e11bbbda1b286e92"
] | [
"sarna/edu.py",
"sarna/freq.py"
] | [
"import os\nimport platform\nimport importlib\n\nimport numpy as np\n\n\ndef test_system():\n '''Print simple system info and some other junk, just to see if\n system has been set up and homeworks are from different machines.'''\n\n try:\n import mne\n except ImportError:\n raise ImportError('Nie masz biblioteki `mne`!')\n mne.sys_info()\n\n modules = ['seaborn', 'borsar', 'sarna']\n longest_str = max(map(len, modules)) + 8\n txt = '\\n{} {}\\n{}\\n'.format(platform.system(), platform.machine(),\n platform.processor())\n\n # check module presence and versions\n for module in modules:\n txt += '\\n{}: '.format(module)\n try:\n mdl = importlib.import_module(module)\n base_txt = '{:>%d}' % (longest_str - len(module))\n txt += base_txt.format(mdl.__version__)\n except ImportError:\n txt += 'BRAK :('\n if module in ('borsar', 'sarna'):\n txt += \"; instalacja z git'a\" if is_git_installed(mdl) \\\n else \"; zwykła instalacja\"\n\n # print some random junk\n values = np.random.randint(0, 1001, (2, 3))\n txt += '\\n\\nTwoje szczęśliwe liczby to:\\n{}'.format(values)\n print(txt)\n\n\ndef is_git_installed(module):\n '''Simple check for whether module is git-installed.\n\n Tests for the presence of a ``.git`` directory and some other relevant git\n subdirectories.\n '''\n sep = os.path.sep\n module_dir = sep.join(module.__file__.split(sep)[:-2])\n has_all_dirs = False\n if '.git' in os.listdir(module_dir):\n subdirs = ['hooks', 'info', 'logs', 'objects', 'refs']\n git_dir_contents = os.listdir(os.path.join(module_dir, '.git'))\n has_all_dirs = all([x in git_dir_contents for x in subdirs])\n return has_all_dirs\n\n\ndef plot_matrix(matrix, colors=False, bgcolor=None, fmt='.2g'):\n '''Plot 2d matrix.\n\n Parameters\n ----------\n matrix : numpy.ndarray\n 2d numpy array to plot.\n colors : bool\n Whether to color the matrix cells according to their values.\n bgcolor : rgb | None\n Cell color if ``colors`` is ``False`` (all cells have uniform color\n then). List of ``[r, g, b]`` values.\n fmt : string, optional\n String formatting code to when writing matrix values.\n\n Returns\n -------\n ax : matplotlib.Axes\n Axes with the heatmap.\n '''\n import seaborn as sns\n\n if matrix.ndim == 1:\n matrix = matrix[np.newaxis, :]\n\n # set default parameters\n longest = max(matrix.shape)\n base_fonsize = 16 if matrix.dtype == 'int' else 14\n fontsize = (base_fonsize if longest <= 8 else\n max(round(base_fonsize - (longest - 8) / 2), 2))\n fontprops = {'fontsize': fontsize}\n if not colors:\n fontprops['color'] = 'k'\n bgcolor = [[0.9, 0.9, 0.6]] if bgcolor is None else [bgcolor]\n\n # use seaborn to plot the heatmap\n ax = sns.heatmap(matrix, annot=True, annot_kws=fontprops, cbar=colors,\n linewidths=1, xticklabels=[], yticklabels=[], fmt=fmt)\n\n # modify seaborn plot to have uniform background color\n if not colors:\n qmesh = ax.get_children()[0]\n color_array = np.ones((25, 4))\n color_array[:, :3] = bgcolor\n qmesh.set_facecolors(color_array)\n\n # change figure size\n dim1, dim2 = matrix.shape\n dim1, dim2 = min(dim2, 8), min(dim1, 8)\n fig = ax.figure\n fig.set_size_inches((dim1, dim2))\n\n return ax\n\n\ndef spectral_reconstruction(raw, ch_name='Oz', tmin=5., tmax=None):\n \"\"\"Simple interface showing how adding sinusoids with frequency and\n phase taken from the fft of the signal leads to reconstructiong the\n original signal in the time domain.\n\n Parameters\n ----------\n raw : mne.Raw\n Mne instance of Raw object. The signal to use in plotting and\n reconstruction.\n ch_name : str\n Name of the channel chosen to visualise.\n tmin : int | float\n Start of the time segment to investigate in seconds.\n tmax : int | float | None\n End of the time segment to investigate in seconds. Default is None\n which calculates ``tmax`` based on ``tmin`` as ``tmin + 2``.\n \"\"\"\n from functools import partial\n import matplotlib.pyplot as plt\n from scipy.fftpack import fft\n\n # select data\n ch_index = raw.ch_names.index(ch_name)\n tmax = tmin + 2. if tmin is None else tmax\n sfreq = raw.info['sfreq']\n start, stop = (np.array([tmin, tmax]) * sfreq).astype('int')\n signal = raw._data[ch_index, start:stop]\n\n # calculate spectrum and freqs\n n_fft = len(signal)\n n_freqs = n_fft // 2 + 1\n freqs = np.arange(n_freqs, dtype=float) * (sfreq / n_fft)\n spectrum = fft(signal)\n\n fig, ax = plt.subplots(nrows=2)\n\n time = np.linspace(tmin, tmax, num=len(signal))\n d = dict(fig=fig, upto=0, ax=ax, freqs=freqs, n_freqs=n_freqs,\n spectrum=spectrum, time=time)\n\n sim, spect = _create_sim(spectrum, 0, n_freqs)\n ax[0].plot(time, signal)\n sim_line = ax[0].plot(time, sim, color='r')[0]\n\n plot_spect = np.abs(spect[:n_freqs])\n plot_spect[plot_spect == 0] = np.nan\n ax[1].plot(freqs, np.abs(spectrum[:n_freqs]))\n spect_scatter = ax[1].scatter(freqs, plot_spect, color='r')\n\n d['sim_line'] = sim_line\n d['spect_scatter'] = spect_scatter\n\n change_lines_prt = partial(_spect_recon_change_lines, dc=d)\n fig.canvas.mpl_connect('key_press_event', change_lines_prt)\n\n\ndef _spect_recon_change_lines(event, dc=None):\n '''Temporary function to update ``spectral_reconstruction`` figure.'''\n\n upto = dc['upto']\n if event.key == 'up':\n upto += 1\n upto = min([dc['n_freqs'], upto])\n elif event.key == 'down':\n upto -= 1\n upto = max([0, upto])\n\n simi, spect = _create_sim(dc['spectrum'], upto, dc['n_freqs'])\n dc['sim_line'].set_data(dc['time'], simi)\n dc['spect_scatter'].remove()\n plot_spect = np.abs(spect[:dc['n_freqs']])\n plot_spect[plot_spect == 0] = np.nan\n dc['spect_scatter'] = dc['ax'][1].scatter(dc['freqs'], plot_spect,\n color='r')\n dc['upto'] = upto\n dc['fig'].canvas.draw()\n\n\ndef _create_sim(spectrum, upto, mx):\n from scipy.fftpack import ifft\n\n upto = min([max([0, upto]), mx])\n spect = np.zeros(len(spectrum), dtype='complex')\n all_inds = np.argsort(np.abs(spectrum[:mx]))[::-1]\n\n # TODO: vectorize\n for ind in all_inds[:upto]:\n spect[ind] = spectrum[ind]\n spect[-ind] = spectrum[-ind]\n\n return ifft(spect), spect\n",
"import numpy as np\nimport mne\nfrom warnings import warn\nfrom sarna.utils import group, _invert_selection, _transfer_selection_to_raw\n# from numba import jit\n\n\ndef dB(x):\n return 10 * np.log10(x)\n\n\n# - [ ] add detrending (1 + x + 1/x) or FOOOF cooperation\ndef transform_spectrum(spectrum, dB=False, normalize=False, detrend=False):\n \"\"\"Common spectrum transformations.\n\n Parameters\n ----------\n spectrum : numpy array\n channels x frequencies\n \"\"\"\n\n if dB:\n spectrum = 10 * np.log10(spectrum)\n if normalize:\n if dB:\n # move whole spectrum up, so that normalization\n # does not return weird results\n min_val = spectrum.min() - 0.01\n spectrum -= min_val\n spectrum /= spectrum.sum(axis=1)[:, np.newaxis]\n return spectrum\n\n\n# - [ ] consider moving to utils\n# - [x] warn if sfreq not given and some values are float\n# - [x] treat floats as time and int as samples\n# - [ ] maybe a smarter API or a class...\ndef window_steps(window_length, window_step, signal_len, sfreq=None):\n is_float = [isinstance(x, float)\n for x in [window_length, window_step, signal_len]]\n any_float = any(is_float)\n if any_float and sfreq is None:\n raise TypeError('Some variables are float but sfreq was not given.')\n\n if any_float and sfreq is not None:\n if is_float[0]:\n window_length = int(np.round(window_length * sfreq))\n if is_float[1]:\n window_step = int(np.round(window_step * sfreq))\n if is_float[2]:\n signal_len = int(np.round(signal_len * sfreq))\n\n num_steps = int(np.floor((signal_len - window_length) / window_step)) + 1\n for w in range(num_steps):\n yield slice(w * window_step, window_length + w * window_step)\n\n\ndef plot_topo_and_psd(inst, mean_psd, freqs, channels):\n from matplotlib import gridspec\n import matplotlib.pyplot as plt\n from mne.viz.topomap import plot_psds_topomap\n\n fig = plt.figure(figsize=(8, 3))\n gs = gridspec.GridSpec(1, 2, width_ratios=[1, 2])\n ax = [plt.subplot(g) for g in gs]\n\n plot_psds_topomap(psds=mean_psd, freqs=freqs, pos=inst.info,\n dB=False, axes=[ax[0]], bands=[(4., 8., 'Theta')],\n normalize=False, cmap='inferno', show=False)\n\n # highlight channels\n circles = ax[0].findobj(plt.Circle)\n for ch in channels:\n circles[ch].set_color('r')\n circles[ch].set_radius(0.025)\n\n plot_freq = (freqs > 1.) & (freqs < 15.)\n ax[1].plot(freqs[plot_freq], mean_psd[channels, :][:, plot_freq].T)\n chan_avg = mean_psd[channels, :].mean(axis=0)\n ax[1].plot(freqs[plot_freq], chan_avg[plot_freq], color='k', lw=2)\n return fig\n\n\ndef _correct_overlap(periods):\n '''\n\n Parameters\n ----------\n periods : np.ndarray\n Numpy array of (n_periods, 3) shape. The columns are: epoch index,\n within-epoch sample index of period start, within-epoch sample index of\n period end.\n\n Returns\n -------\n periods : np.ndarray\n Corrected numpy array of (n_periods, 3) shape. The columns are: epoch\n index, within-epoch sample index of period start, within-epoch sample\n index of period end.\n\n '''\n n_rows = periods.shape[0]\n current_period = periods[0, :].copy()\n correct = list()\n\n for idx in range(1, n_rows):\n overlap = ((periods[idx, 0] == current_period[0])\n and (periods[idx, 1] <= current_period[2]))\n\n if overlap:\n current_period[-1] = periods[idx, -1]\n else:\n correct.append(current_period)\n current_period = periods[idx, :].copy()\n\n correct.append(current_period)\n periods = np.stack(correct, axis=0)\n\n return periods\n\n\ndef _find_high_amplitude_periods(epochs, threshold=2.5, min_period=0.1,\n extend=None):\n '''\n Find segments of high amplitude in filtered, hilbert-transformed signal.\n\n Parameters\n ----------\n epochs : mne.Epochs\n Epoched data. Must be filtered and hilbert-transformed.\n threshold : float, str\n Threshold defining high amplitude periods to select: if float, it\n is interpreted as a z value threshold; if str, as percentage of\n fragments with in the highest amplitude in form of ``'xx%'``\n (for example with ``'25%'`` 25% of singal with highest amplitude will\n be selected ). Defaults to ``2.5``.\n min_period : float\n Minimum length of high amplitude period in seconds.\n Defaults to ``0.1``.\n extend : float | None\n Extend each period by this many seconds on both sides (before and\n after). Defaults to ``None`` which does not extend the periods.\n\n Returns\n -------\n periods : np.ndarray\n Numpy array of (n_periods, 3) shape. The columns are: epoch index,\n within-epoch sample index of period start, within-epoch sample index of\n period end.\n '''\n from scipy.stats import zscore\n\n # amplitude periods\n n_epochs, n_channels, n_samples = epochs._data.shape\n comp_data = epochs._data.transpose([1, 0, 2]).reshape((n_channels, -1))\n\n # find segments with elevated amplitude\n envelope = np.nanmean(comp_data, axis=0)\n\n if isinstance(threshold, str) and '%' in threshold:\n perc = 100 - float(threshold.replace('%', ''))\n threshold = np.nanpercentile(envelope, perc)\n else:\n envelope = zscore(envelope, nan_policy='omit')\n\n grp = group(envelope > threshold)\n\n if len(grp) == 0:\n raise ValueError('No high amplitude periods were found.')\n # check if there are some segments that start at one epoch\n # and end in another\n # -> if so, they could be split, but we will ignore them for now\n epoch_idx = np.floor(grp / n_samples)\n epoch_diff = np.diff(epoch_idx, axis=0)\n epochs_joint = epoch_diff > 0\n if epochs_joint.any():\n msg = ('{:d} high-amplitude segments will be ignored because'\n ' the developer was lazy.')\n warn(msg.format(epochs_joint.sum()))\n epoch_diff = epoch_diff[~epochs_joint]\n\n segment_len = np.diff(grp, axis=1)\n good_length = segment_len[:, 0] * (1 / data.info['sfreq']) > min_period\n grp = grp[good_length, :]\n epoch_idx = np.floor(grp[:, [0]] / n_samples).astype('int')\n grp -= epoch_idx * n_samples\n\n if extend is not None:\n extend_samples = int(np.round(extend * data.info['sfreq']))\n extend_samples = np.array([-extend_samples, extend_samples])\n grp += extend_samples[np.newaxis, :]\n\n # check for limits\n msk1 = grp[:, 0] < 0\n msk2 = grp[:, 1] >= n_samples\n grp[msk1, 0] = 0\n grp[msk2, 1] = n_samples - 1\n\n periods = np.append(epoch_idx, grp, axis=1)\n periods = periods if extend is None else _correct_overlap(periods)\n\n return periods\n\n\ndef create_amplitude_annotations(raw, freq=None, events=None, event_id=None,\n picks=None, tmin=-0.2, tmax=0.5,\n threshold=2., min_period=0.1,\n extend=None):\n '''\n Parameters\n ----------\n raw : mne.Raw\n Raw file to use.\n events: numpy array | None\n Mne events array of shape (n_events, 3). If None (default) `tmin` and\n `tmax` are not calculated with respect to events but the whole time\n range of the `raw` file.\n event_id: list | numpy array\n Event types (IDs) to use in defining segments for which psd is\n computed. If None (default) and events were passed all event types are\n used.\n freq : list | numpy array\n Frequency limits defining a range for which low amplitude periods will\n be calculated.\n picks : list\n List of channels for which low amplitude periods will be calculated.\n tmin : float\n Start time before event.\n tmax : float\n End time after event.\n threshold : float, str\n Threshold defining high amplitude periods to select: if float, it\n is interpreted as a z value threshold; if str, as percentage of\n fragments with in the highest amplitude in form of ``'xx%'``\n (for example with ``'25%'`` 25% of singal with highest amplitude will\n be selected ). Defaults to ``2.5``.\n min_period : float\n Minimum length of high amplitude period in seconds.\n Defaults to ``0.1``.\n extend : float | None\n Extend each period by this many seconds on both sides (before and\n after). Defaults to ``None`` which does not extend the periods.\n\n Returns\n -------\n raw_annot : mne.Raw\n Raw files with annotations.\n '''\n\n if freq is None:\n raise TypeError('Frequencies have to be defined')\n if events is None:\n raise TypeError('Events have to be defined')\n if event_id is None:\n event_id = np.unique(events[:, 2]).tolist()\n\n filt_raw = raw.copy().filter(freq[0], freq[1])\n\n filt_raw_nan = filt_raw.copy()\n filt_raw_nan._data = raw.get_data(reject_by_annotation='NaN')\n epochs_nan = mne.Epochs(filt_raw_nan, events=events, event_id=event_id,\n tmin=tmin, tmax=tmax, baseline=None, preload=True,\n reject_by_annotation=False)\n\n epochs = mne.Epochs(filt_raw, events=events, event_id=event_id, tmin=tmin,\n tmax=tmax, baseline=None, preload=True,\n reject_by_annotation=False)\n\n del filt_raw_nan\n\n filt_hilb_data = np.abs(epochs.copy().pick(picks).apply_hilbert()._data)\n filt_hilb_data[np.isnan(epochs_nan._data)] = np.nan\n epochs_nan._data = filt_hilb_data\n\n hi_amp_epochs = _find_high_amplitude_periods(epochs_nan,\n threshold=threshold,\n min_period=min_period,\n extend=extend)\n\n hi_amp_raw = _transfer_selection_to_raw(epochs, raw,\n selection=hi_amp_epochs)\n amp_inv_samples = _invert_selection(raw, selection=hi_amp_raw)\n\n sfreq = raw.info['sfreq']\n amp_inv_annot_sec = amp_inv_samples / sfreq\n\n n_segments = amp_inv_samples.shape[0]\n amp_annot = mne.Annotations(amp_inv_annot_sec[:, 0],\n amp_inv_annot_sec[:, 1],\n ['BAD_lowamp'] * n_segments)\n\n return amp_annot\n\n\ndef grand_average_psd(psd_list):\n '''Perform grand average on a list of PSD objects.\n\n Parameters\n ----------\n psd_list : list\n List of ``borsar.freq.PSD`` objects.\n\n Returns\n -------\n grand_psd : borsar.freq.PSD\n Grand averaged spectrum.\n '''\n assert isinstance(psd_list, list)\n\n # make sure that all psds have the same number and order of channels\n # and the same frequencies\n freq1 = psd_list[0].freqs\n ch_names1 = psd_list[0].ch_names\n n_channels = len(ch_names1)\n for psd in psd_list:\n assert len(psd.freqs) == len(freq1)\n assert (psd.freqs == freq1).all()\n assert len(psd.ch_names) == n_channels\n assert all([ch_names1[idx] == psd.ch_names[idx]\n for idx in range(n_channels)])\n\n all_psds = list()\n for this_psd in psd_list:\n # upewniamy się, że epoki są uśrednione\n this_psd = this_psd.copy().average()\n all_psds.append(this_psd.data)\n\n # łączymy widma w macierz (osoby x kanały x częstotliwości)\n all_psds = np.stack(all_psds, axis=0)\n\n # uśredniamy wymiar osób, zostają nam kanały x częstotliwości\n all_psds = all_psds.mean(axis=0)\n\n # kopiujemy wybrane psd z listy\n grand_psd = this_psd.copy()\n # i wypełniamy wartościamy średniej po osobach\n grand_psd._data = all_psds\n\n return grand_psd\n"
] | [
[
"scipy.fftpack.ifft",
"numpy.abs",
"numpy.arange",
"matplotlib.pyplot.subplots",
"numpy.ones",
"scipy.fftpack.fft",
"numpy.array",
"numpy.random.randint"
],
[
"numpy.nanpercentile",
"numpy.unique",
"numpy.isnan",
"scipy.stats.zscore",
"numpy.stack",
"numpy.round",
"numpy.append",
"numpy.log10",
"numpy.diff",
"numpy.nanmean",
"numpy.floor",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.subplot",
"numpy.array",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
elviswf/pytorch_cv | [
"a7f11f857a0c1d5e5a807aeed5e594659212fba0",
"a7f11f857a0c1d5e5a807aeed5e594659212fba0",
"a7f11f857a0c1d5e5a807aeed5e594659212fba0"
] | [
"models/focalLoss.py",
"cub_attr1.py",
"cub_deepRIS.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2018/2/9 16:18\n@Author : Elvis\n\"\"\"\n\"\"\"\n focalLoss.py\n \n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n\nclass FocalLoss(nn.Module):\n \"\"\"\n This criterion is a implemenation of Focal Loss, which is proposed in\n Focal Loss for Dense Object Detection.\n\n Loss(x, class) = - \\alpha (1-softmax(x)[class])^gamma \\log(softmax(x)[class])\n\n The losses are averaged across observations for each minibatch.\n\n Args:\n alpha(1D Tensor, Variable) : the scalar factor for this criterion\n gamma(float, double) : gamma > 0; reduces the relative loss for well-classified examples (p > .5),\n putting more focus on hard, misclassified examples\n size_average(bool): By default, the losses are averaged over observations for each minibatch.\n If set to False, the losses are summed for each minibatch.\n \"\"\"\n\n def __init__(self, class_num, alpha=None, gamma=2, size_average=True):\n super(FocalLoss, self).__init__()\n if alpha is None:\n self.alpha = Variable(torch.ones(class_num, 1))\n else:\n if isinstance(alpha, Variable):\n self.alpha = alpha\n else:\n self.alpha = Variable(alpha)\n self.gamma = gamma\n self.class_num = class_num\n self.size_average = size_average\n\n def forward(self, inputs, targets):\n N = inputs.size(0)\n C = inputs.size(1)\n P = F.softmax(inputs, dim=1)\n\n class_mask = inputs.data.new(N, C).fill_(0)\n ids = targets.view(-1, 1)\n class_mask.scatter_(1, ids.data, 1.)\n class_mask = Variable(class_mask)\n # print(class_mask)\n\n if inputs.is_cuda and not self.alpha.is_cuda:\n self.alpha = self.alpha.cuda()\n alpha = self.alpha[ids.data.view(-1)]\n\n probs = (P * class_mask).sum(1).view(-1, 1)\n\n log_p = probs.log()\n # print('probs size= {}'.format(probs.size()))\n # print(probs)\n\n batch_loss = -alpha * (torch.pow((1 - probs), self.gamma)) * log_p\n # print('-----bacth_loss------')\n # print(batch_loss)\n\n if self.size_average:\n loss = batch_loss.mean()\n else:\n loss = batch_loss.sum()\n return loss\n",
"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2017/12/4 15:42\n@Author : Elvis\n\n cub.py\nwatch --color -n1 gpustat -cpu\nCUDA_VISIBLE_DEVICES=3 python cub_attr1.py\n\nzsl_resnet18_fc00 : Sigmoid + dropout 0.5 74.789% (1329/1777) ZSL_Acc: 53.354% (1583/2967) 200 epoch\nzsl_resnet18_fc01 : Sigmoid with fc pretrain Acc: 73.044% (1298/1777) ZSL_Acc: 24.537% (728/2967)\nzsl_resnet18_fc02 : Sigmoid with fc pretrain + dropout 0.5 full 150 60 epoch: Acc: 50.792% (1507/2967)\nzsl_resnet18_fc03 : Sigmoid + dropout 0.5 weight_decay=0.005 full 150 60 epoch: Acc: 50.792% (1507/2967)\n 100 epoch: Acc: 53.758% (1595/2967) 192 epoch: Acc: 54.803% (1626/2967)\n\nzsl_resnet50_fc00 : Sigmoid + dropout 0.5 weight_decay=0.005 full 150 44epoch Acc: 57.162% (1696/2967)\n Acc: 75.842% (6690/8821) | Test Acc: 95.948% (1705/1777)\nzsl_resnet50_fc01 : Sigmoid + dropout 0.5 weight_decay=0.005 half100\nzsl_resnet50_fc02 : Sigmoid + dropout 0.5 weight_decay=0.005 full dropout 0.4 Acc: 58.140% (1725/2967) 24\nzsl_resnet50_fc03 : Sigmoid + dropout 0.5 weight_decay=0.005 full dropout 0.25 Acc: 56.421% (1674/2967)\nzsl_resnet50_fc04 : BN + Sigmoid + norm weight\n\"\"\"\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.backends import cudnn\nfrom torch.autograd import Variable\nimport os\nimport argparse\nfrom data.data_loader import DataLoader\nfrom models.zsl_resnet import attrCNN\nfrom utils.logger import progress_bar\n\n# from utils.param_count import torch_summarize, lr_scheduler\n# import pickle\n\n# Learning rate parameters\nBASE_LR = 0.01\nNUM_CLASSES = 150 # set the number of classes in your dataset\nNUM_ATTR = 312\nDATA_DIR = \"/home/elvis/data/attribute/CUB_200_2011/zsl/trainval0\"\nBATCH_SIZE = 64\nIMAGE_SIZE = 224\n# MODEL_NAME = \"zsl_resnet18_fc1\"\n# MODEL_NAME = \"zsl_resnet18_fc1_end\"\nMODEL_NAME = \"zsl_resnet50_fc04\"\nUSE_GPU = torch.cuda.is_available()\nMODEL_SAVE_FILE = MODEL_NAME + '.pth'\n\nparser = argparse.ArgumentParser(description='PyTorch zsl_resnet18_attr1 Training')\nparser.add_argument('--lr', default=BASE_LR, type=float, help='learning rate')\nparser.add_argument('--resume', '-r', action='store_true', default=False, help='resume from checkpoint')\nparser.add_argument('--data', default=DATA_DIR, type=str, help='file path of the dataset')\nargs = parser.parse_args()\n\nbest_acc = 0.\nstart_epoch = 0\nprint(\"Model: \" + MODEL_NAME)\nif args.resume:\n print(\"==> Resuming from checkpoint...\")\n checkpoint = torch.load(\"./checkpoints/\" + MODEL_SAVE_FILE)\n net = checkpoint[\"net\"]\n best_acc = checkpoint[\"acc\"]\n start_epoch = checkpoint[\"epoch\"]\n optimizer = checkpoint[\"optimizer\"]\nelse:\n print(\"==> Building model...\")\n net = attrCNN(num_attr=312, num_classes=150)\n\n# optimizer = optim.Adam(net.parameters())\n# optimizer = optim.SGD(net.get_config_optim(BASE_LR / 10.),\n# lr=BASE_LR,\n# momentum=0.9,\n# weight_decay=0.0005)\n# print(torch_summarize(net))\n# print(net)\nif USE_GPU:\n net.cuda()\n # net = torch.nn.DataParallel(net.module, device_ids=range(torch.cuda.device_count()))\n cudnn.benchmark = True\n\nlog = open(\"./log/\" + MODEL_NAME + '_cub.txt', 'a')\nprint(\"==> Preparing data...\")\ndata_loader = DataLoader(data_dir=args.data, image_size=IMAGE_SIZE, batch_size=BATCH_SIZE)\ninputs, classes = next(iter(data_loader.load_data()))\n# out = torchvision.utils.make_grid(inputs)\n# data_loader.show_image(out, title=[data_loader.data_classes[c] for c in classes])\ntrain_loader = data_loader.load_data(data_set='train')\ntest_loader = data_loader.load_data(data_set='val')\ncriterion = nn.CrossEntropyLoss()\n\n\n# def one_hot_emb(batch, depth=NUM_CLASSES):\n# emb = nn.Embedding(depth, depth)\n# emb.weight.data = torch.eye(depth)\n# return emb(batch).data\ndef one_hot_emb(y, depth=NUM_CLASSES):\n y = y.view((-1, 1))\n one_hot = torch.FloatTensor(y.size(0), depth).zero_()\n one_hot.scatter_(1, y, 1)\n return one_hot\n\n\ndef train(epoch, net, optimizer):\n print(\"\\nEpoch: %d\" % epoch)\n net.train()\n train_loss = 0\n correct = 0\n total = 0\n # optimizer = lr_scheduler(optimizer, epoch, init_lr=0.002, decay_epoch=start_epoch)\n for batch_idx, (inputs, targets) in enumerate(train_loader):\n if USE_GPU:\n inputs, targets = inputs.cuda(), targets.cuda()\n inputs, targets = Variable(inputs), Variable(targets)\n optimizer.zero_grad()\n\n out, attr = net(inputs)\n loss = criterion(out, targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.data[0]\n _, predicted = torch.max(out.data, 1)\n total += targets.size(0)\n correct += predicted.eq(targets.data).cpu().sum()\n\n progress_bar(batch_idx, len(train_loader), \"Loss: %.3f | Acc: %.3f%% (%d/%d)\"\n % (train_loss / (batch_idx + 1), 100. * correct / total, correct, total))\n\n log.write(str(epoch) + ' ' + str(correct / total) + ' ')\n\n\ndef test(epoch, net):\n global best_acc\n net.eval()\n test_loss, correct, total, loss = 0, 0, 0, 0\n for batch_idx, (inputs, targets) in enumerate(test_loader):\n if USE_GPU:\n inputs, targets = inputs.cuda(), targets.cuda()\n inputs, targets = Variable(inputs, volatile=True), Variable(targets)\n out, attr = net(inputs)\n loss = criterion(out, targets)\n\n test_loss = loss.data[0]\n _, predicted = torch.max(out.data, 1)\n total += targets.size(0)\n correct += predicted.eq(targets.data).cpu().sum()\n\n acc = 100. * correct / total\n progress_bar(batch_idx, len(test_loader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss / (batch_idx + 1), acc, correct, total))\n\n log.write(str(correct / total) + ' ' + str(test_loss) + '\\n')\n log.flush()\n\n acc = 100. * correct / total\n if epoch > 9 and acc > best_acc:\n print(\"Saving checkpoint\")\n state = {\n 'net': net,\n 'acc': acc,\n 'epoch': epoch,\n 'optimizer': optimizer\n }\n if not os.path.isdir(\"checkpoints\"):\n os.mkdir('checkpoints')\n torch.save(state, \"./checkpoints/\" + MODEL_SAVE_FILE)\n best_acc = acc\n\n\nfor param in net.parameters():\n param.requires_grad = False\n\noptim_params = list(net.cnn.fc.parameters())\nfor param in optim_params:\n param.requires_grad = True\n\nepoch1 = 15\n# optimizer = optim.Adagrad(optim_params, lr=0.001, weight_decay=0.005)\noptimizer = optim.Adam(optim_params, weight_decay=0.005)\nif start_epoch < epoch1:\n for epoch in range(start_epoch, epoch1):\n train(epoch, net, optimizer)\n test(epoch, net)\n start_epoch = epoch1\n\nfor param in net.cnn.parameters():\n param.requires_grad = True\n\n# fc_params = list(map(id, net.cnn.fc.parameters()))\n# base_params = list(filter(lambda p: id(p) not in fc_params, net.cnn.parameters()))\n# optimizer = optim.Adagrad([{'params': base_params},\n# {'params': net.cnn.fc.parameters(), 'lr': 0.005}\n# ], lr=0.0005, weight_decay=0.005)\n# start_epoch = 0\n# optimizer = optim.Adam(net.cnn.fc.parameters(), weight_decay=0.0005)\n# optimizer = torch.optim.SGD([\n# {'params': base_params},\n# {'params': net.cnn.fc.parameters(), 'lr': 1}\n# ], lr=1e-4, momentum=0.9, weight_decay=0.0005)\nfrom zeroshot.cub_test import zsl_test, gzsl_test\nimport copy\n\noptimizer = optim.Adagrad(net.cnn.parameters(), lr=0.001, weight_decay=0.005)\nfor epoch in range(start_epoch, 500):\n train(epoch, net, optimizer)\n test(epoch, net)\n if epoch > 10:\n net1 = copy.deepcopy(net)\n zsl_test(epoch, net1, optimizer)\n del net1\n # net2 = copy.deepcopy(net)\n # gzsl_test(epoch, net2, optimizer)\n # del net2\nlog.close()\n",
"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2017/12/4 15:42\n@Author : Elvis\n\n cub.py\nwatch --color -n1 gpustat -cpu\nCUDA_VISIBLE_DEVICES=3 python cub_attr1.py\n\nzsl_resnet18_fc00 : Sigmoid + dropout 0.5 74.789% (1329/1777) ZSL_Acc: 53.354% (1583/2967) 200 epoch\nzsl_resnet18_fc01 : Sigmoid with fc pretrain Acc: 73.044% (1298/1777) ZSL_Acc: 24.537% (728/2967)\nzsl_resnet18_fc02 : Sigmoid with fc pretrain + dropout 0.5 full 150 60 epoch: Acc: 50.792% (1507/2967)\nzsl_resnet18_fc03 : Sigmoid + dropout 0.5 weight_decay=0.005 full 150 60 epoch: Acc: 50.792% (1507/2967)\n 100 epoch: Acc: 53.758% (1595/2967) 192 epoch: Acc: 54.803% (1626/2967)\n\nzsl_resnet50_fc00 : Sigmoid + dropout 0.5 weight_decay=0.005 full 150 44epoch Acc: 57.162% (1696/2967)\n Acc: 75.842% (6690/8821) | Test Acc: 95.948% (1705/1777)\ngzsl_resnet50_fc01 : Sigmoid + dropout 0.5\n Step: 246ms | Tot: 40s814ms | Loss: 0.068 | Acc: 98.764% (8712/8821)\n Step: 73ms | Tot: 3s593ms | Loss: 0.000 | Acc: 100.000% (1777/1777)\n Step: 36ms | Tot: 6s308ms | Loss: 0.026 | Acc: 66.903% (1985/2967) Epoch: 26\n\ngzsl_resnet50_fc03 : fc2 drop sigmoid Acc: 67.914% (2015/2967) gzsl: Acc: 76.044% (4406/5794)\ngzsl_resnet50_fc04 : fc2 dropout no good Acc: 64.948% (1927/2967) Acc: 65.285% (1937/2967)\ngzsl_resnet50_fc05: fc2 drop sigmoid gzsl Acc: 32.652% (1549/4744) no sigmoid Acc: 61.139% (1814/2967)\n\"\"\"\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.backends import cudnn\nfrom torch.autograd import Variable\nimport os\nimport argparse\nfrom data.data_loader import DataLoader\nfrom models.zsl_resnet import deepRIS\nfrom utils.logger import progress_bar\n\n# from utils.param_count import torch_summarize, lr_scheduler\n# import pickle\n\n# Learning rate parameters\nBASE_LR = 0.01\nNUM_CLASSES = 200 # set the number of classes in your dataset\nNUM_ATTR = 312\nDATA_DIR = \"/home/elvis/data/attribute/CUB_200_2011/zsl/trainval0\"\nBATCH_SIZE = 64\nIMAGE_SIZE = 224\n# MODEL_NAME = \"zsl_resnet18_fc1\"\n# MODEL_NAME = \"zsl_resnet18_fc1_end\"\nMODEL_NAME = \"gzsl_resnet50_fc0310\"\nUSE_GPU = torch.cuda.is_available()\nMODEL_SAVE_FILE = MODEL_NAME + '.pth'\n\nparser = argparse.ArgumentParser(description='PyTorch zsl_resnet18_attr1 Training')\nparser.add_argument('--lr', default=BASE_LR, type=float, help='learning rate')\nparser.add_argument('--resume', '-r', action='store_true', default=False, help='resume from checkpoint')\nparser.add_argument('--data', default=DATA_DIR, type=str, help='file path of the dataset')\nargs = parser.parse_args()\n\nbest_acc = 0.\nstart_epoch = 0\nprint(\"Model: \" + MODEL_NAME)\nif args.resume:\n print(\"==> Resuming from checkpoint...\")\n checkpoint = torch.load(\"./checkpoints/\" + MODEL_SAVE_FILE)\n net = checkpoint[\"net\"]\n best_acc = checkpoint[\"acc\"]\n start_epoch = checkpoint[\"epoch\"]\n optimizer = checkpoint[\"optimizer\"]\nelse:\n print(\"==> Building model...\")\n net = attrWCNNg(num_attr=312, num_classes=NUM_CLASSES)\n\n# print(torch_summarize(net))\n# print(net)\nif USE_GPU:\n net.cuda()\n # net = torch.nn.DataParallel(net.module, device_ids=range(torch.cuda.device_count()))\n cudnn.benchmark = True\n\nlog = open(\"./log/\" + MODEL_NAME + '_cub.txt', 'a')\nprint(\"==> Preparing data...\")\ndata_loader = DataLoader(data_dir=args.data, image_size=IMAGE_SIZE, batch_size=BATCH_SIZE)\ninputs, classes = next(iter(data_loader.load_data()))\n# out = torchvision.utils.make_grid(inputs)\n# data_loader.show_image(out, title=[data_loader.data_classes[c] for c in classes])\ntrain_loader = data_loader.load_data(data_set='train')\ntest_loader = data_loader.load_data(data_set='val')\ncriterion = nn.CrossEntropyLoss()\n\n\n# def one_hot_emb(batch, depth=NUM_CLASSES):\n# emb = nn.Embedding(depth, depth)\n# emb.weight.data = torch.eye(depth)\n# return emb(batch).data\ndef one_hot_emb(y, depth=NUM_CLASSES):\n y = y.view((-1, 1))\n one_hot = torch.FloatTensor(y.size(0), depth).zero_()\n one_hot.scatter_(1, y, 1)\n return one_hot\n\n\ndef train(epoch, net, optimizer):\n print(\"\\nEpoch: %d\" % epoch)\n net.train()\n train_loss = 0\n correct = 0\n total = 0\n # optimizer = lr_scheduler(optimizer, epoch, init_lr=0.002, decay_epoch=start_epoch)\n for batch_idx, (inputs, targets) in enumerate(train_loader):\n if USE_GPU:\n inputs, targets = inputs.cuda(), targets.cuda()\n inputs, targets = Variable(inputs), Variable(targets)\n optimizer.zero_grad()\n\n out, attr = net(inputs)\n loss = criterion(out, targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.data[0]\n _, predicted = torch.max(out.data, 1)\n total += targets.size(0)\n correct += predicted.eq(targets.data).cpu().sum()\n\n progress_bar(batch_idx, len(train_loader), \"Loss: %.3f | Acc: %.3f%% (%d/%d)\"\n % (train_loss / (batch_idx + 1), 100. * correct / total, correct, total))\n\n log.write(str(epoch) + ' ' + str(correct / total) + ' ')\n\n\ndef test(epoch, net):\n global best_acc\n net.eval()\n test_loss, correct, total, loss = 0, 0, 0, 0\n for batch_idx, (inputs, targets) in enumerate(test_loader):\n if USE_GPU:\n inputs, targets = inputs.cuda(), targets.cuda()\n inputs, targets = Variable(inputs, volatile=True), Variable(targets)\n out, attr = net(inputs)\n loss = criterion(out, targets)\n\n test_loss = loss.data[0]\n _, predicted = torch.max(out.data, 1)\n total += targets.size(0)\n correct += predicted.eq(targets.data).cpu().sum()\n\n acc = 100. * correct / total\n progress_bar(batch_idx, len(test_loader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss / (batch_idx + 1), acc, correct, total))\n\n log.write(str(correct / total) + ' ' + str(test_loss) + '\\n')\n log.flush()\n\n acc = 100. * correct / total\n if epoch > 9 and acc > best_acc:\n print(\"Saving checkpoint\")\n state = {\n 'net': net,\n 'acc': acc,\n 'epoch': epoch,\n 'optimizer': optimizer\n }\n if not os.path.isdir(\"checkpoints\"):\n os.mkdir('checkpoints')\n torch.save(state, \"./checkpoints/\" + MODEL_SAVE_FILE)\n best_acc = acc\n\n\nepoch1 = 12\n# optimizer = optim.Adagrad(optim_params, lr=0.001, weight_decay=0.005)\nif start_epoch < epoch1:\n for param in net.parameters():\n param.requires_grad = False\n # optim_params = list(net.fc0.parameters()) + list(net.fc1.parameters())\n optim_params = list(net.fc0.parameters()) + list(net.fc1.parameters())\n for param in optim_params:\n param.requires_grad = True\n optimizer = optim.Adam(optim_params, weight_decay=0.005)\n for epoch in range(start_epoch, epoch1):\n train(epoch, net, optimizer)\n test(epoch, net)\n start_epoch = epoch1\n\nfc_params = list(map(id, net.fc2.parameters()))\nbase_params = list(filter(lambda p: id(p) not in fc_params, net.parameters()))\n\nfor param in base_params:\n param.requires_grad = True\n\noptimizer = optim.Adagrad(base_params, lr=0.001, weight_decay=0.005)\nfrom zeroshot.cub_test import zsl_test, gzsl_test, gzsl_test0\nimport copy\n\nfor epoch in range(start_epoch, 100):\n train(epoch, net, optimizer)\n test(epoch, net)\n if epoch > 10:\n net1 = copy.deepcopy(net)\n zsl_test(epoch, net1, optimizer)\n del net1\n # net2 = copy.deepcopy(net)\n # gzsl_test(epoch, net2, optimizer)\n # del net2\nlog.close()\n"
] | [
[
"torch.nn.functional.softmax",
"torch.ones",
"torch.pow",
"torch.autograd.Variable"
],
[
"torch.optim.Adam",
"torch.nn.CrossEntropyLoss",
"torch.max",
"torch.load",
"torch.autograd.Variable",
"torch.cuda.is_available",
"torch.save"
],
[
"torch.optim.Adam",
"torch.nn.CrossEntropyLoss",
"torch.optim.Adagrad",
"torch.max",
"torch.load",
"torch.autograd.Variable",
"torch.cuda.is_available",
"torch.save"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
BitShifter88/DeepLearning | [
"921048b2529911b44dfec98da640fb623f2dfd80"
] | [
"src/chartNN/model/multi_scale_one5x5.py"
] | [
"import torch.nn as nn\r\nimport math\r\nimport torch.utils.model_zoo as model_zoo\r\n\r\nimport torch\r\n\r\ndef conv3x3(in_planes, out_planes, stride=1):\r\n \"\"\"3x3 convolution with padding\"\"\"\r\n return nn.Conv1d(in_planes, out_planes, kernel_size=3, stride=stride,\r\n padding=1, bias=False)\r\n\r\ndef conv5x5(in_planes, out_planes, stride=1):\r\n return nn.Conv1d(in_planes, out_planes, kernel_size=5, stride=stride,\r\n padding=1, bias=False)\r\n\r\ndef conv7x7(in_planes, out_planes, stride=1):\r\n return nn.Conv1d(in_planes, out_planes, kernel_size=7, stride=stride,\r\n padding=1, bias=False)\r\n\r\n\r\n\r\nclass BasicBlock5x5_1(nn.Module):\r\n expansion = 1\r\n\r\n def __init__(self, inplanes5_1, planes, stride=1, downsample=None):\r\n super(BasicBlock5x5_1, self).__init__()\r\n self.conv1 = conv5x5(inplanes5_1, planes, stride)\r\n self.bn1 = nn.BatchNorm1d(planes)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.conv2 = conv5x5(planes, planes)\r\n self.bn2 = nn.BatchNorm1d(planes)\r\n self.downsample = downsample\r\n self.stride = stride\r\n\r\n def forward(self, x):\r\n residual = x\r\n\r\n out = self.conv1(x)\r\n out = self.bn1(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv2(out)\r\n out = self.bn2(out)\r\n\r\n if self.downsample is not None:\r\n residual = self.downsample(x)\r\n\r\n d = residual.shape[2] - out.shape[2]\r\n out1 = residual[:,:,0:-d] + out\r\n out1 = self.relu(out1)\r\n # out += residual\r\n\r\n return out1\r\n\r\n\r\nclass BasicBlock5x5_2(nn.Module):\r\n expansion = 1\r\n\r\n def __init__(self, inplanes5_2, planes, stride=1, downsample=None):\r\n super(BasicBlock5x5_2, self).__init__()\r\n self.conv1 = conv5x5(inplanes5_2, planes, stride)\r\n self.bn1 = nn.BatchNorm1d(planes)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.conv2 = conv5x5(planes, planes)\r\n self.bn2 = nn.BatchNorm1d(planes)\r\n self.downsample = downsample\r\n self.stride = stride\r\n\r\n def forward(self, x):\r\n residual = x\r\n\r\n out = self.conv1(x)\r\n out = self.bn1(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv2(out)\r\n out = self.bn2(out)\r\n\r\n if self.downsample is not None:\r\n residual = self.downsample(x)\r\n\r\n d = residual.shape[2] - out.shape[2]\r\n out1 = residual[:,:,0:-d] + out\r\n out1 = self.relu(out1)\r\n # out += residual\r\n\r\n return out1\r\n\r\nclass BasicBlock5x5_3(nn.Module):\r\n expansion = 1\r\n\r\n def __init__(self, inplanes5_3, planes, stride=1, downsample=None):\r\n super(BasicBlock5x5_3, self).__init__()\r\n self.conv1 = conv5x5(inplanes5_3, planes, stride)\r\n self.bn1 = nn.BatchNorm1d(planes)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.conv2 = conv5x5(planes, planes)\r\n self.bn2 = nn.BatchNorm1d(planes)\r\n self.downsample = downsample\r\n self.stride = stride\r\n\r\n def forward(self, x):\r\n residual = x\r\n\r\n out = self.conv1(x)\r\n out = self.bn1(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv2(out)\r\n out = self.bn2(out)\r\n\r\n if self.downsample is not None:\r\n residual = self.downsample(x)\r\n\r\n d = residual.shape[2] - out.shape[2]\r\n out1 = residual[:,:,0:-d] + out\r\n out1 = self.relu(out1)\r\n # out += residual\r\n\r\n return out1\r\n\r\nclass MSResNet(nn.Module):\r\n def __init__(self, input_channel, layers=[1, 1, 1, 1], num_classes=10):\r\n self.inplanes5_1 = 64\r\n self.inplanes5_2 = 64\r\n self.inplanes5_3 = 64\r\n\r\n super(MSResNet, self).__init__()\r\n\r\n self.conv1 = nn.Conv1d(input_channel, 64, kernel_size=7, stride=2, padding=3,\r\n bias=False)\r\n self.bn1 = nn.BatchNorm1d(64)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.maxpool = nn.MaxPool1d(kernel_size=3, stride=2, padding=1)\r\n\r\n\r\n self.layer5x5_11 = self._make_layer5_1(BasicBlock5x5_1, 64, layers[0], stride=2)\r\n self.layer5x5_12 = self._make_layer5_1(BasicBlock5x5_1, 128, layers[1], stride=2)\r\n self.layer5x5_13 = self._make_layer5_1(BasicBlock5x5_1, 256, layers[2], stride=2)\r\n # self.layer3x3_4 = self._make_layer3(BasicBlock3x3, 512, layers[3], stride=2)\r\n # maxplooing kernel size: 16, 11, 6\r\n self.maxpool5_1 = nn.AvgPool1d(kernel_size=11, stride=1, padding=0)\r\n\r\n\r\n self.layer5x5_21 = self._make_layer5_2(BasicBlock5x5_2, 64, layers[0], stride=2)\r\n self.layer5x5_22 = self._make_layer5_2(BasicBlock5x5_2, 128, layers[1], stride=2)\r\n self.layer5x5_23 = self._make_layer5_2(BasicBlock5x5_2, 256, layers[2], stride=2)\r\n # self.layer3x3_4 = self._make_layer3(BasicBlock3x3, 512, layers[3], stride=2)\r\n\r\n # maxplooing kernel size: 16, 11, 6\r\n self.maxpool5_2 = nn.AvgPool1d(kernel_size=11, stride=1, padding=0)\r\n\r\n self.layer5x5_31 = self._make_layer5_3(BasicBlock5x5_3, 64, layers[0], stride=2)\r\n self.layer5x5_32 = self._make_layer5_3(BasicBlock5x5_3, 128, layers[1], stride=2)\r\n self.layer5x5_33 = self._make_layer5_3(BasicBlock5x5_3, 256, layers[2], stride=2)\r\n # self.layer3x3_4 = self._make_layer3(BasicBlock3x3, 512, layers[3], stride=2)\r\n\r\n # maxplooing kernel size: 16, 11, 6\r\n self.maxpool5_3 = nn.AvgPool1d(kernel_size=11, stride=1, padding=0)\r\n\r\n # self.drop = nn.Dropout(p=0.2)\r\n self.fc = nn.Linear(256*3, num_classes)\r\n\r\n # todo: modify the initialization\r\n # for m in self.modules():\r\n # if isinstance(m, nn.Conv1d):\r\n # n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\r\n # m.weight.data.normal_(0, math.sqrt(2. / n))\r\n # elif isinstance(m, nn.BatchNorm1d):\r\n # m.weight.data.fill_(1)\r\n # m.bias.data.zero_()\r\n\r\n def _make_layer3(self, block, planes, blocks, stride=2):\r\n downsample = None\r\n if stride != 1 or self.inplanes3 != planes * block.expansion:\r\n downsample = nn.Sequential(\r\n nn.Conv1d(self.inplanes3, planes * block.expansion,\r\n kernel_size=1, stride=stride, bias=False),\r\n nn.BatchNorm1d(planes * block.expansion),\r\n )\r\n\r\n layers = []\r\n layers.append(block(self.inplanes3, planes, stride, downsample))\r\n self.inplanes3 = planes * block.expansion\r\n for i in range(1, blocks):\r\n layers.append(block(self.inplanes3, planes))\r\n\r\n return nn.Sequential(*layers)\r\n\r\n def _make_layer5_1(self, block, planes, blocks, stride=2):\r\n downsample = None\r\n if stride != 1 or self.inplanes5_1 != planes * block.expansion:\r\n downsample = nn.Sequential(\r\n nn.Conv1d(self.inplanes5_1, planes * block.expansion,\r\n kernel_size=1, stride=stride, bias=False),\r\n nn.BatchNorm1d(planes * block.expansion),\r\n )\r\n\r\n layers = []\r\n layers.append(block(self.inplanes5_1, planes, stride, downsample))\r\n self.inplanes5_1 = planes * block.expansion\r\n for i in range(1, blocks):\r\n layers.append(block(self.inplanes5_1, planes))\r\n\r\n return nn.Sequential(*layers)\r\n\r\n def _make_layer5_2(self, block, planes, blocks, stride=2):\r\n downsample = None\r\n if stride != 1 or self.inplanes5_2 != planes * block.expansion:\r\n downsample = nn.Sequential(\r\n nn.Conv1d(self.inplanes5_2, planes * block.expansion,\r\n kernel_size=1, stride=stride, bias=False),\r\n nn.BatchNorm1d(planes * block.expansion),\r\n )\r\n\r\n layers = []\r\n layers.append(block(self.inplanes5_2, planes, stride, downsample))\r\n self.inplanes5_2 = planes * block.expansion\r\n for i in range(1, blocks):\r\n layers.append(block(self.inplanes5_2, planes))\r\n\r\n return nn.Sequential(*layers)\r\n\r\n def _make_layer5_3(self, block, planes, blocks, stride=2):\r\n downsample = None\r\n if stride != 1 or self.inplanes5_3 != planes * block.expansion:\r\n downsample = nn.Sequential(\r\n nn.Conv1d(self.inplanes5_3, planes * block.expansion,\r\n kernel_size=1, stride=stride, bias=False),\r\n nn.BatchNorm1d(planes * block.expansion),\r\n )\r\n\r\n layers = []\r\n layers.append(block(self.inplanes5_3, planes, stride, downsample))\r\n self.inplanes5_3 = planes * block.expansion\r\n for i in range(1, blocks):\r\n layers.append(block(self.inplanes5_3, planes))\r\n\r\n return nn.Sequential(*layers)\r\n\r\n\r\n def _make_layer7(self, block, planes, blocks, stride=2):\r\n downsample = None\r\n if stride != 1 or self.inplanes7 != planes * block.expansion:\r\n downsample = nn.Sequential(\r\n nn.Conv1d(self.inplanes7, planes * block.expansion,\r\n kernel_size=1, stride=stride, bias=False),\r\n nn.BatchNorm1d(planes * block.expansion),\r\n )\r\n\r\n layers = []\r\n layers.append(block(self.inplanes7, planes, stride, downsample))\r\n self.inplanes7 = planes * block.expansion\r\n for i in range(1, blocks):\r\n layers.append(block(self.inplanes7, planes))\r\n\r\n return nn.Sequential(*layers)\r\n\r\n def forward(self, x0):\r\n x0 = self.conv1(x0)\r\n x0 = self.bn1(x0)\r\n x0 = self.relu(x0)\r\n x0 = self.maxpool(x0)\r\n\r\n x = self.layer5x5_11(x0)\r\n x = self.layer5x5_12(x)\r\n x = self.layer5x5_13(x)\r\n # x = self.layer3x3_4(x)\r\n x = self.maxpool5_1(x)\r\n\r\n y = self.layer5x5_21(x0)\r\n y = self.layer5x5_22(y)\r\n y = self.layer5x5_23(y)\r\n # y = self.layer5x5_4(y)\r\n y = self.maxpool5_2(y)\r\n\r\n z = self.layer5x5_31(x0)\r\n z = self.layer5x5_32(z)\r\n z = self.layer5x5_33(z)\r\n # z = self.layer7x7_4(z)\r\n z = self.maxpool5_3(z)\r\n\r\n out = torch.cat([x, y, z], dim=1)\r\n\r\n out = out.squeeze()\r\n # out = self.drop(out)\r\n out1 = self.fc(out)\r\n\r\n return out1, out\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
] | [
[
"torch.nn.BatchNorm1d",
"torch.nn.Sequential",
"torch.cat",
"torch.nn.MaxPool1d",
"torch.nn.Linear",
"torch.nn.Conv1d",
"torch.nn.ReLU",
"torch.nn.AvgPool1d"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
andycasey/sick | [
"6c37686182794c4cafea45abf7062b30b789b1a2"
] | [
"sick/models/create.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" Create models for *sick* \"\"\"\n\nfrom __future__ import division, print_function\n\n__all__ = (\"create\", )\n__author__ = \"Andy Casey <[email protected]>\"\n\nimport cPickle as pickle\nimport logging\nimport os\nimport yaml\nfrom time import strftime\n\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy.table import Table\n\nfrom sick import __version__ as sick_version\n\nlogger = logging.getLogger(\"sick\")\n\n\ndef load_simple_data(filename, **kwargs):\n # parse a txt/fits file with ease.\n\n logger.debug(\"Opening {}\".format(filename))\n fits_extensions = (\".fit\", \".fits\", \".fit.gz\", \".fits.gz\")\n if any(map(lambda _: filename.endswith(_), fits_extensions)):\n # laod as fits.\n with fits.open(filename) as image:\n extension_index = kwargs.pop(\"extension\", None)\n if extension_index is None:\n # Get first extension with data.\n for extension_index, extension in enumerate(image):\n if extension.data is not None: break\n else:\n raise IOError(\"no valid data in {}\".format(filename))\n\n data = image[extension_index].data\n return data\n\n else:\n return np.loadtxt(filename, **kwargs)\n\n\ndef create(output_prefix, grid_flux_filename, wavelength_filenames,\n clobber=False, grid_flux_filename_format=\"csv\", **kwargs):\n \"\"\"\n Create a new *sick* model from files describing the parameter names, fluxes,\n and wavelengths.\n \"\"\"\n\n if not clobber:\n # Check to make sure the output files won't exist already.\n output_suffixes = (\".yaml\", \".pkl\", \"-wavelengths.memmap\",\n \"-intensities.memmap\")\n for path in [output_prefix + suffix for suffix in output_suffixes]:\n if os.path.exists(path):\n raise IOError(\"output filename {} already exists\".format(path))\n\n # Read the grid_flux filename.\n # param1 param2 param3 param4 channelname1 channelname2\n kwds = kwargs.pop(\"__grid_flux_filename_kwargs\", {})\n kwds.update({\"format\": grid_flux_filename_format})\n grid_flux_tbl = Table.read(grid_flux_filename, **kwds)\n\n # Distinguish column names between parameters (real numbers) and filenames\n str_columns = \\\n np.array([_[1].startswith(\"|S\") for _ in grid_flux_tbl.dtype.descr])\n\n # Check the number of channels provided.\n if str_columns.sum() != len(wavelength_filenames):\n raise ValueError(\"expected {0} wavelength filenames because {1} has {0}\"\n \" string columns ({2}) but found {3} wavelength filenames\".format(\n sum(str_columns), grid_flux_filename, \n \", \".join(np.array(grid_flux_tbl.colnames)[str_columns]), \n len(wavelength_filenames)))\n\n # Create a record array of the grid points.\n grid_points = \\\n grid_flux_tbl.as_array()[np.array(grid_flux_tbl.colnames)[~str_columns]]\n\n # To-do: make sure they are all floats.\n\n # Sort the grid points.\n grid_indices = grid_points.argsort(order=grid_points.dtype.names)\n grid_points = grid_points[grid_indices]\n grid_flux_tbl = grid_flux_tbl[grid_indices]\n\n # Check the wavelength filenames.\n channel_wavelengths = np.array(map(load_simple_data, wavelength_filenames))\n\n # Sort the channels by starting wavelength.\n c_indices = np.argsort([each.min() for each in channel_wavelengths])\n channel_names = np.array(grid_flux_tbl.colnames)[str_columns][c_indices]\n channel_wavelengths = channel_wavelengths[c_indices]\n channel_sizes = [len(_) for _ in channel_wavelengths]\n num_pixels = sum(channel_sizes)\n\n # Create the model YAML file.\n with open(output_prefix + \".yaml\", \"w\") as fp:\n header = \"\\n\".join([\n \"# Model created on {0}\".format(strftime(\"%Y-%m-%d %H:%M:%S\")),\n \"# Grid parameters: {0}\".format(\", \".join(grid_points.dtype.names)),\n \"# Channel names: {0}\".format(\", \".join(channel_names))\n ])\n fp.write(header + \"\\n\" + yaml.safe_dump({ \"model_grid\": {\n \"grid_points\": output_prefix + \".pkl\",\n \"intensities\": output_prefix + \"-intensities.memmap\",\n \"wavelengths\": output_prefix + \"-wavelengths.memmap\"\n }}, stream=None, allow_unicode=True, default_flow_style=False))\n\n # Create the pickled model file, with meta data.\n metadata = {\n \"grid_flux_filename\": grid_flux_filename,\n \"wavelength_filenames\": wavelength_filenames,\n \"channel_names\": channel_names,\n \"channel_sizes\": channel_sizes,\n \"channel_resolutions\": [float(\"inf\")] * len(channel_names),\n \"sick_version\": sick_version\n }\n logger.debug(\"Dumping grid points and metadata to file\")\n with open(output_prefix + \".pkl\", \"wb\") as fp:\n pickle.dump((grid_points, metadata), fp, -1)\n\n # Create the memory-mapped dispersion file.\n logger.debug(\"Creating memory-mapped dispersion file.\")\n wavelengths_memmap = np.memmap(output_prefix + \"-wavelengths.memmap\",\n dtype=\"float32\", mode=\"w+\", shape=(num_pixels, ))\n wavelengths_memmap[:] = np.hstack(channel_wavelengths)\n wavelengths_memmap.flush()\n del wavelengths_memmap\n\n # Create the memory-mapped intensities file.\n logger.debug(\"Creating memory-mapped intensities file.\")\n intensities_memmap = np.memmap(output_prefix + \"-intensities.memmap\",\n shape=(grid_points.size, num_pixels), dtype=\"float32\",\n mode=\"w+\")\n \n n = len(grid_flux_tbl)\n for i, row in enumerate(grid_flux_tbl):\n logger.debug(\"Loading point {0}/{1} into the intensities map\"\\\n .format(i + 1, n))\n j = 0\n for channel_name in channel_names:\n try:\n data = load_simple_data(row[channel_name])\n except:\n logger.exception(\"Could not load data from {0} for channel {1}\"\\\n .format(row[channel_name], channel_name))\n raise\n intensities_memmap[i, j:j + data.size] = data\n j += data.size\n\n intensities_memmap.flush()\n del intensities_memmap\n\n return True\n"
] | [
[
"numpy.hstack",
"numpy.memmap",
"numpy.array",
"numpy.loadtxt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gwaygenomics/nf1_inactivation | [
"09c6292448cb121b3077a3df1399fc6d4d56d5d8"
] | [
"scripts/util/cancer_cv.py"
] | [
"'''\n(C) Gregory Way 2016\nNF1 Inactivation Classifier for Glioblastoma\ncancer_cv.py\n\nDescription:\nClasses to perform cross validation on pancan datasets\n\nUsage:\nImport only\n'''\n\n\nclass cancer_cv(object):\n \"\"\"\n A class to determine cross validation intervals for pancancer tissues with\n careful consideration to split cv folds with equal number of mutations and\n tissues if applicable.\n \"\"\"\n\n def __init__(self, y_dict, fold, hold, min_samples, seed, tissues='auto'):\n \"\"\"\n :param y_dict: keys are tissue types, values are pandas DataFrame\n holding mutation status for each sample\n :param fold: integer of how many cross validation folds to extract\n :param hold: boolean of whether or not to extract holdout set\n :param seed: set a random seed for reproducibility\n :param tissues: a list of tissues to use in analysis\n (defaults to auto-detect tissues)\n :return: a dictionary holding y matrices for each fold\n \"\"\"\n\n self.y_dictionary = y_dict\n self.num_folds = fold\n self.seed = seed\n self.holdout = hold\n self.percent_held = None\n self.cv_folds = None\n self.x_folds = None\n\n if tissues == 'auto':\n # Determine the appropriate tissues to use since not all tissues\n # will have enough mutations\n self.tissues = []\n for tissue in y_dict.keys():\n tissue_DF = y_dict[tissue]\n mut_samples = tissue_DF[tissue_DF['Status'] == 1]\n if mut_samples.shape[0] > min_samples:\n self.tissues.append(tissue)\n else:\n self.tissues = tissues\n\n def holdout_samples(self, fraction_held):\n self.fraction_held = fraction_held\n\n def assign_folds(self):\n \"\"\"\n Subsets X and Y matrices to implement cross validation logic.\n self.holdout_samples must be called prior if self.holdout = T\n\n Output:\n a dictionary holding evenly distributed sample names\n \"\"\"\n\n import random\n import numpy as np\n import pandas as pd\n\n random.seed(self.seed)\n\n cv_folds = dict.fromkeys(range(0, self.num_folds))\n if self.holdout:\n cv_folds['holdout'] = pd.DataFrame(columns=['Status', 'Samples',\n 'Tissue'])\n for fold in cv_folds.keys():\n cv_folds[fold] = pd.DataFrame(columns=['Status', 'Samples',\n 'Tissue'])\n tissue_idx = 0\n for tissue in self.tissues:\n tissue_DF = self.y_dictionary[tissue]\n\n # Determine how many samples\n mut_samples = tissue_DF[tissue_DF['Status'] == 1]\n mut_samples = mut_samples['Samples'].tolist()\n not_mut_samples = tissue_DF[tissue_DF['Status'] == 0]\n not_mut_samples = not_mut_samples['Samples'].tolist()\n num_mut = len(mut_samples)\n num_not_mut = len(not_mut_samples)\n\n if self.holdout:\n # For hold out 3/4 are not mutated\n num_held = int(num_mut * self.fraction_held)\n hold_ix_mut = random.sample(range(0, num_mut), num_held)\n\n num_held = int(num_not_mut * self.fraction_held)\n hold_ix_not_mut = random.sample(range(0, num_not_mut),\n num_held)\n\n # Get the holdout samples\n mut_hold = [mut_samples[i] for i in hold_ix_mut]\n not_mut_hold = [not_mut_samples[i] for i in hold_ix_not_mut]\n accept = mut_hold + not_mut_hold\n hold_sam = tissue_DF[tissue_DF['Samples'].isin(accept)]\n\n # Randomly shuffle the rows\n hold_sam = hold_sam.iloc[np.random.permutation(len(hold_sam))]\n\n # Append them to the holdout key\n if tissue_idx == 0:\n cv_folds['holdout'] = hold_sam\n else:\n cv_folds['holdout'] = pd.concat([cv_folds['holdout'],\n hold_sam])\n\n # Remove from tissue_DF\n tissue_DF = tissue_DF[~tissue_DF['Samples'].isin(accept)]\n\n # Now determine folds for the remaining samples\n mut_samples = tissue_DF[tissue_DF['Status'] == 1]\n mut_samples = mut_samples['Samples'].tolist()\n not_mut_samples = tissue_DF[tissue_DF['Status'] == 0]\n not_mut_samples = not_mut_samples['Samples'].tolist()\n num_mut = len(mut_samples)\n num_not_mut = len(not_mut_samples)\n\n # Because there are much less mutated samples than not, shuffle the\n # samples and assign manually to each fold\n range_folds = list(range(0, self.num_folds))\n random.shuffle(mut_samples)\n random.shuffle(range_folds)\n cv_fold_ix = 0\n samp_iter = 0\n cv_fold_samples = dict.fromkeys(range_folds)\n for key in cv_fold_samples.keys():\n cv_fold_samples[key] = []\n\n for samp in mut_samples:\n cur_fold = range_folds[cv_fold_ix]\n cv_fold_samples[cur_fold].append(samp)\n samp_iter += 1\n if samp_iter == int(num_mut / self.num_folds):\n samp_iter = 0\n cv_fold_ix += 1\n if cv_fold_ix > max(range_folds):\n cv_fold_ix = range_folds[random.sample(range_folds, 1)[0]]\n\n # Non mutated samples are more prevalent, so assign randomly\n # without worrying too much about uneven numbers between folds\n fold_index = np.random.choice(range_folds, num_not_mut)\n for samp_idx in range(0, num_not_mut):\n fold = fold_index[samp_idx]\n samp = not_mut_samples[samp_idx]\n cv_fold_samples[fold].append(samp)\n\n # Reassign each of these samples to the actual sample information\n for key in cv_fold_samples.keys():\n cur_samples = cv_fold_samples[key]\n y_subset = tissue_DF[tissue_DF['Samples'].isin(cur_samples)]\n if tissue_idx == 0:\n cv_folds[key] = y_subset\n else:\n cv_folds[key] = pd.concat([cv_folds[key], y_subset])\n\n tissue_idx += 1\n\n self.cv_folds = cv_folds\n\n def assign_x_matrix_folds(self, full_x):\n \"\"\"\n Uses previously established cross validation intervals to split full x\n \"\"\"\n\n # Initialize the x_folds constructor\n self.x_folds = dict.fromkeys(self.cv_folds.keys())\n\n # Assign the x_matrix to each of the folds\n for cv_key in self.x_folds.keys():\n # Get the current fold\n cur_fold = self.cv_folds[cv_key]\n\n # Subset x matrix\n y_samples = cur_fold['Samples'].tolist()\n x_subset = full_x[y_samples]\n\n # Assign to dictionary\n self.x_folds[cv_key] = x_subset\n\n def split_train_test(self, fold):\n \"\"\"\n Will partition x and y into training and testing sets with equal parts\n\n :param fold: the given fold to extract test set\n\n Output:\n training and testing x's and y's according to the subset fold\n \"\"\"\n\n import pandas as pd\n\n # The test set is the holdout set if the fold == 'all'\n if fold == 'all':\n num_fold_iter = 0\n for f in range(self.num_folds):\n x_fold = self.x_folds[f]\n y_fold = self.cv_folds[f]\n if f != 'holdout':\n if num_fold_iter == 0:\n x_train = x_fold\n y_train = y_fold['Status']\n num_fold_iter += 1\n else:\n x_train = pd.concat([x_train, x_fold], axis=1)\n y_train = pd.concat([y_train, y_fold['Status']])\n\n x_test = self.x_folds['holdout']\n y_test = self.cv_folds['holdout']['Status']\n\n # Remove a fold for the test set if fold not 'all'\n else:\n remain_folds = list(range(self.num_folds))\n remain_folds.remove(fold)\n\n # Concatenate the remaining x's and y's\n num_fold_iter = 0\n for f in remain_folds:\n x_fold = self.x_folds[f]\n y_fold = self.cv_folds[f]\n if num_fold_iter == 0:\n x_train = x_fold\n y_train = y_fold['Status']\n num_fold_iter += 1\n else:\n x_train = pd.concat([x_train, x_fold], axis=1)\n y_train = pd.concat([y_train, y_fold['Status']])\n\n x_test = self.x_folds[fold]\n y_test = self.cv_folds[fold]['Status']\n\n return x_train.T, x_test.T, y_train, y_test\n"
] | [
[
"pandas.concat",
"pandas.DataFrame",
"numpy.random.choice"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
NCAR/solar-forcing | [
"5e7baf7656bd5b7b89672fc9d7ad5011b06bb722"
] | [
"solarforcing/calc.py"
] | [
"import numpy as np\nfrom numba import jit, jit_module\nimport pydantic\nfrom datetime import datetime\nfrom scipy import integrate\nimport xarray as xr\n\n@jit(nopython=True)\ndef gen_energy_grid(nbins, min_e=30., max_e=1000.):\n \"\"\"Generate a grid of energies for the flux spectrum\n \n This function generates an energy grid given a number of grids\n \n Parameters\n ----------\n nbins: `float`\n The number of logarithmically spaced grid points\n \n min_e: `float`, optional\n Minimum energy range, defaults to 30 keV\n \n max_e: `float`, optional\n Maximum energy range, defaults to 1000 keV\n \n Returns\n -------\n `numpy.array`\n Resultant energy grid given the parameters specified\n\n \"\"\"\n\n e1 = np.log10(min_e)\n e2 = np.log10(max_e)\n e = 10**(e1 + (e2-e1)*np.arange(nbins)/(nbins-1))\n \n return e\n\n@jit(nopython=True)\ndef vdk2016(e, l, Ap):\n \"\"\"A routine (vdk2016) to return an energy spectrum for a specific l-shell and Ap\n \n Calculations here are defined by van de Kamp et al. 2016 (doi:10.1002/2015JD024212)\n \n Parameters\n ----------\n e: `numpy.array`\n An energy grid, as defined in gen_energy_grid\n \n l: `float`\n Lshell value\n \n Ap: `float`\n Ap value\n \n Returns\n -------\n `numpy.array`\n Flux spectral density with the same shape as e\n\n \"\"\"\n\n lpp = -0.7430*np.log(Ap) + 6.5257\n Spp = l - lpp\n\n # vdK2016 eqn.(8)\n\n A = 8.2091*Ap**0.16255\n b = 1.3754*Ap**0.33042\n c = 0.13334*Ap**0.42616\n s = 2.2833*Ap**-0.22990\n d = 2.7563e-4*Ap**2.6116\n\n # integral flux >30 keV (F30) electrons / (cm2 sr s)\n F30 = np.exp(A) / (np.exp(-b*(Spp-s)) + np.exp(c*(Spp-s)) + d)\n\n # vdK2016 eqn.(9)\n\n E = 3.3777*Ap**-1.7038 + 0.15\n bk = 3.7632*Ap**-0.16034\n sk = 12.184*Ap**-0.30111\n\n k = -1.0 / (E*np.exp(-bk*Spp) + 0.30450*np.cosh(0.20098*(Spp-sk))) - 1\n \n # solve eqn 3 for C\n # C is an offset, and k is the spectral gradient\n x=k+1\n c = F30*x/(1e3**x-30.**x)\n \n # calcualte the spectral density of the flux S(E) = CE^k\n # in electrons / (cm2 sr s keV)\n flux_spectral_density = e**k*c\n \n return flux_spectral_density\n\n@jit(nopython=True)\ndef calculate_flux(lshell, aps, e, angle=80.):\n \"\"\"Calculates a solar flux using vdk2016\n \n Uses lshell, ap values, and e to calculate a flux\n \n Parameters\n ----------\n lshell: `numpy.array`\n Lshell values, one dimensional.\n \n aps: `numpy.array`\n Ap values, one dimensional.\n \n e: `numpy.array`\n Energy grid, two dimensional.\n \n angle: `float`, optional\n Angle to use when coverting to per steradian, if not given defaults\n to 80 degrees.\n \n Returns\n -------\n `numpy.array`\n Energy flux, using vdk2016 calculation\n\n \"\"\"\n flux = np.empty(shape=(len(lshell),len(aps), len(e)))\n for i in range(len(lshell)):\n for j in range(len(aps)):\n # calculate the top of the atmosphere energetic electron energy spectrum\n \n if aps[j] != 0:\n flux_sd = vdk2016(e, lshell[i], aps[j])\n \n else:\n flux_sd = np.nan * e\n \n # van de Kamp is per steradian (electrons / (cm2 sr s keV))\n # assume flux is isotropic inside a nominal bounce loss cone (BLC) angle\n # of 80˚. The area of the BLC in sr is 2pi(1-cosd(66.3))\n flux[i, j, :] = 2.*np.pi*(1-np.cos(np.radians(angle))) * flux_sd\n \n return flux\n\n# Convert from lshell to glat\n@jit(nopython=True)\ndef lshell_to_glat(lshell):\n \"\"\"Converts lshell to geomagnetic latitude\n \n Parameters\n ----------\n lshell: `float`, `numpy.array`\n Lshell value\n \n Returns\n -------\n `numpy.array`\n Geomagnetic latitude\n \n \"\"\"\n return np.arccos((2.02/lshell) - 1) * (90./np.pi)\n\n@jit(nopython=True)\ndef glat_to_lshell(glat):\n \"\"\"Converts geomagnetic latitude to lshell\n \n Parameters\n ----------\n glat: `float`, `numpy.array`\n Geomagnetic latitude\n \n Returns\n -------\n `numpy.array`\n Lshell\n \n \"\"\"\n return 1.01 / np.cos(glat*np.pi/180.)**2\n\n@jit(nopython=True)\ndef fang(y, Emono):\n# Input: \n# y - normalized atmospheric column mass as a function of vertical location (z)\n# Emono - is incident electron energy (keV)\n# Output:\n# f - quanity calculated by eqn. (4)\n\n # Table 1.\n p1 = np.array([(1.24616E+0, 1.45903E+0, -2.42269E-1, 5.95459E-2), \n (2.23976E+0, -4.22918E-7, 1.36458E-2, 2.53332E-3),\n (1.41754E+0, 1.44597E-1, 1.70433E-2, 6.39717E-4),\n (2.48775E-1, -1.50890E-1, 6.30894E-9, 1.23707E-3),\n (-4.65119E-1, -1.05081E-1, -8.95701E-2, 1.22450E-2),\n (3.86019E-1, 1.75430E-3, -7.42960E-4, 4.60881E-4),\n (-6.45454E-1, 8.49555E-4, -4.28581E-2, -2.99302E-3),\n (9.48930E-1, 1.97385E-1, -2.50660E-3, -2.06938E-3)])\n\n # terms in eq. (5)\n lne = np.log(Emono)\n lne2 = lne*lne\n lne3 = lne*lne2\n\n # step 2. calculate the C array in (5)\n c = np.empty((8))\n for i in range(8):\n c[i] = np.exp(p1[i,0] + p1[i,1]*lne + p1[i,2]*lne2 + p1[i,3]*lne3)\n \n # eq. (4) - Normalized energy deposition\n f = c[0]*y**c[1]*np.exp(-c[2]*y**c[3]) + c[4]*y**c[5]*np.exp(-c[6]*y**c[7])\n \n return f\n\n@jit(nopython=True)\ndef iprmono(e, flux, rho, H):\n # assign constants\n epsilon = 0.035 # keV \n\n ipr = np.empty((e.size,rho.size))\n\n for i,energy in enumerate(e): # loop over energy index\n\n # step 1. (eq. 1) \n y = (2/energy)*(rho*H/6.0e-6)**0.7\n f = np.empty(y.size)\n\n for j,yy in enumerate(y):\n f[j] = fang(yy, energy)\n\n # calculate ipr (qtot) using eq. (3) for a specified flux at ea. energy\n Qmono = flux[i]*energy # (keV cm−2 s−1)\n ipr[i,:] = f*Qmono/(epsilon*H)\n\n return ipr\n\n@jit(nopython=True)\ndef calculate_ipr(fluxes, glats, aps, alt, rho, H, e):\n ipr_vals = np.empty(shape=(len(aps),len(glats), len(e), len(alt)))\n for i in range(len(aps)):\n for j in range(len(glats)):\n flux = fluxes[j, i, :]\n\n # calculate the IPR as a function f height and energy\n ipr = iprmono(e, flux, rho, H)\n\n # Add the results to the ipr array\n ipr_vals[i, j, :, :] = ipr\n \n \n return ipr_vals\n\njit_module(nopython=True, error_model=\"numpy\")\n\ndef calculate_iprm(fluxes, glats, aps, times, alt, rho, H, e):\n \"\"\"\n Calculates iprm from a dataset\n \n Parameters\n ----------\n fluxes: numpy.array\n Array of flux data\n glats: numpy.array\n Array of geomagnetic latitudes\n aps: numpy.array\n Array of AP values\n times: list\n List of times corresponding to ap values\n alt: numpy.array\n Array of altitude values\n rho: numpy.array\n Array of density values\n H: numpy.array\n Array of scaling height values\n e: numpy.array\n Energy grid used for this calcualtion\n\n Returns\n -------\n xarray.Dataset with IPRM values\n\n \"\"\"\n \n ipr = calculate_ipr(fluxes, glats, aps, alt, rho, H, e)\n \n # calculate ipr total by integrating across the energy spectrum\n ipr_tot = integrate.simps(ipr, e, axis=2)\n \n # calculate iprm\n iprm = ipr_tot/rho\n \n # Calculate pressure levels\n plevs = 1013.*np.exp(-alt/6.8)\n \n # Build a dataset for the output\n out_ds = xr.Dataset(data_vars=dict(iprm=(['time', 'glat', 'pressure'], iprm),\n ap = (['time'], aps),\n glat = glats,\n pressure = plevs,\n time=('time', times)))\n \n print(out_ds)\n if 'date' in out_ds.dims:\n out_ds.drop(dim='date')\n \n out_ds = out_ds.transpose(\"time\", \"pressure\", \"glat\")\n \n return out_ds.sortby('pressure')\n\n"
] | [
[
"numpy.log",
"numpy.radians",
"numpy.cosh",
"numpy.arange",
"numpy.arccos",
"numpy.cos",
"numpy.exp",
"numpy.log10",
"scipy.integrate.simps",
"numpy.array",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
mdiephuis/pytorch_sparse | [
"328aaf2f92cdc37c8daa2d38c53c995ffbd743c8"
] | [
"torch_sparse/diag.py"
] | [
"import warnings\nimport os.path as osp\nfrom typing import Optional\n\nimport torch\nfrom torch_sparse.storage import SparseStorage\nfrom torch_sparse.tensor import SparseTensor\n\ntry:\n torch.ops.load_library(\n osp.join(osp.dirname(osp.abspath(__file__)), '_diag.so'))\nexcept OSError:\n warnings.warn('Failed to load `diag` binaries.')\n\n def non_diag_mask_placeholder(row: torch.Tensor, col: torch.Tensor, M: int,\n N: int, k: int) -> torch.Tensor:\n raise ImportError\n return row\n\n torch.ops.torch_sparse.non_diag_mask = non_diag_mask_placeholder\n\n\[email protected]\ndef remove_diag(src: SparseTensor, k: int = 0) -> SparseTensor:\n row, col, value = src.coo()\n inv_mask = row != col if k == 0 else row != (col - k)\n new_row, new_col = row[inv_mask], col[inv_mask]\n\n if value is not None:\n value = value[inv_mask]\n\n rowcount = src.storage._rowcount\n colcount = src.storage._colcount\n if rowcount is not None or colcount is not None:\n mask = ~inv_mask\n if rowcount is not None:\n rowcount = rowcount.clone()\n rowcount[row[mask]] -= 1\n if colcount is not None:\n colcount = colcount.clone()\n colcount[col[mask]] -= 1\n\n storage = SparseStorage(row=new_row, rowptr=None, col=new_col, value=value,\n sparse_sizes=src.sparse_sizes(), rowcount=rowcount,\n colptr=None, colcount=colcount, csr2csc=None,\n csc2csr=None, is_sorted=True)\n return src.from_storage(storage)\n\n\[email protected]\ndef set_diag(src: SparseTensor, values: Optional[torch.Tensor] = None,\n k: int = 0) -> SparseTensor:\n src = remove_diag(src, k=k)\n row, col, value = src.coo()\n\n mask = torch.ops.torch_sparse.non_diag_mask(row, col, src.size(0),\n src.size(1), k)\n inv_mask = ~mask\n\n start, num_diag = -k if k < 0 else 0, mask.numel() - row.numel()\n diag = torch.arange(start, start + num_diag, device=row.device)\n\n new_row = row.new_empty(mask.size(0))\n new_row[mask] = row\n new_row[inv_mask] = diag\n\n new_col = col.new_empty(mask.size(0))\n new_col[mask] = col\n new_col[inv_mask] = diag.add_(k)\n\n new_value: Optional[torch.Tensor] = None\n if value is not None:\n new_value = value.new_empty((mask.size(0), ) + value.size()[1:])\n new_value[mask] = value\n if values is not None:\n new_value[inv_mask] = values\n else:\n new_value[inv_mask] = torch.ones((num_diag, ), dtype=value.dtype,\n device=value.device)\n\n rowcount = src.storage._rowcount\n if rowcount is not None:\n rowcount = rowcount.clone()\n rowcount[start:start + num_diag] += 1\n\n colcount = src.storage._colcount\n if colcount is not None:\n colcount = colcount.clone()\n colcount[start + k:start + num_diag + k] += 1\n\n storage = SparseStorage(row=new_row, rowptr=None, col=new_col,\n value=new_value, sparse_sizes=src.sparse_sizes(),\n rowcount=rowcount, colptr=None, colcount=colcount,\n csr2csc=None, csc2csr=None, is_sorted=True)\n return src.from_storage(storage)\n\n\[email protected]\ndef fill_diag(src: SparseTensor, fill_value: int, k: int = 0) -> SparseTensor:\n num_diag = min(src.sparse_size(0), src.sparse_size(1) - k)\n if k < 0:\n num_diag = min(src.sparse_size(0) + k, src.sparse_size(1))\n\n value = src.storage.value()\n if value is not None:\n sizes = [num_diag] + src.sizes()[2:]\n return set_diag(src, value.new_full(sizes, fill_value), k)\n else:\n return set_diag(src, None, k)\n\n\nSparseTensor.remove_diag = lambda self, k=0: remove_diag(self, k)\nSparseTensor.set_diag = lambda self, values=None, k=0: set_diag(\n self, values, k)\nSparseTensor.fill_diag = lambda self, fill_value, k=0: fill_diag(\n self, fill_value, k)\n"
] | [
[
"torch.ones",
"torch.arange"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
OpenSO2/so2eval | [
"0bc896360f8021e930bdadc707540220fe6b0f9e"
] | [
"alignimages.py"
] | [
"# coding: utf-8\n\"\"\"Align two images.\n\nTry to automatically calculate the warp matrix between two images and align\nthose images accordingly.\n\"\"\"\nimport cv2\nimport numpy as np\n\n\ndef alignimages(im1, im2):\n\t\"\"\"Automatically align two images.\"\"\"\n\t# Find size of image1\n\tsz = im1.shape\n\n\t# Define the motion model\n\t# warp_mode = cv2.MOTION_TRANSLATION # translation\n\twarp_mode = cv2.MOTION_EUCLIDEAN # translation + rotation\n\t# warp_mode = cv2.MOTION_AFFINE # translation + rotation + skew\n\n\t# Define 2x3 matrix and initialize the matrix to identity\n\twarp_matrix = np.eye(2, 3, dtype=np.float32)\n\n\t# Specify the number of iterations.\n\tnumber_of_iterations = 200\n\n\t# Specify the threshold of the increment\n\t# in the correlation coefficient between two iterations\n\ttermination_eps = 1e-10\n\n\t# Define termination criteria\n\tcriteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,\n\t\tnumber_of_iterations, termination_eps)\n\n\t# Run the ECC algorithm. The results are stored in warp_matrix.\n\t# FIXME: use image depth to calc the scaling factor (this assumes 16bit)\n\tim1_8 = (im1 / 256).astype('uint8')\n\tim2_8 = (im2 / 256).astype('uint8')\n\t(_, warp_matrix) = cv2.findTransformECC(im1_8, im2_8, warp_matrix,\n\t\twarp_mode, criteria)\n\n\t# Use warpAffine for Translation, Euclidean and Affine\n\tim2_aligned = cv2.warpAffine(im2, warp_matrix, (sz[1], sz[0]),\n\t\tflags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)\n\n\treturn im2_aligned, warp_matrix\n"
] | [
[
"numpy.eye"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ajfriend/cyscs | [
"3ad1bb2fe18ac2789786003f5c6e76d9f5d66b13"
] | [
"cyscs/test/test_solve.py"
] | [
"import cyscs as scs\nimport pytest\nimport cyscs.examples as ex\n\nimport scipy.sparse as sp\nimport numpy as np\n\ndef test_simple_lp():\n data, cone = ex.simple_lp()\n sol = scs.solve(data, cone)\n\ndef test_extra_arg():\n data, cone = ex.simple_lp()\n sol = scs.solve(data, cone, eps=1e-9, alpha=.1, nonsense_arg='nonsense')\n\ndef test_simple_indirect():\n data, cone = ex.simple_lp()\n sol = scs.solve(data, cone, use_indirect=True)\n\ndef test_simple_direct():\n data, cone = ex.simple_lp()\n sol = scs.solve(data, cone, use_indirect=False)\n\ndef test_cone_size():\n # test that the solve method recognizes that the length of the cone\n # does not match the number of rows of A\n data, cone = ex.simple_lp()\n cone['l'] = 5\n\n with pytest.raises(ValueError):\n sol = scs.solve(data, cone)\n\ndef test_simple_ecp():\n data, cone, true_x = ex.simple_ecp()\n sol = scs.solve(data, cone, eps=1e-6)\n\n assert np.allclose(sol['x'], true_x)\n\ndef test_simple_socp():\n data, cone, true_x = ex.simple_socp()\n sol = scs.solve(data, cone, eps=1e-6)\n\n assert np.allclose(sol['x'], true_x)\n\ndef test_simple_sdp():\n data, cone, true_x = ex.simple_sdp()\n sol = scs.solve(data, cone, eps=1e-6)\n\n assert np.allclose(sol['x'], true_x)\n\ndef test_simple_pcp():\n data, cone, true_x = ex.simple_pcp()\n sol = scs.solve(data, cone, eps=1e-6)\n\n assert np.allclose(sol['x'], true_x)\n\n\ndef test_str_output():\n data, cone = ex.simple_lp()\n sol = scs.solve(data, cone)\n\n assert sol['info']['status'] == 'Solved'"
] | [
[
"numpy.allclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ashwinvin/Visionlib | [
"f7d55778c6951ed5d436bc8010ddf282d4af00cc"
] | [
"visionlib/object/detection/detection.py"
] | [
"import numpy as np\nimport cv2\nimport os\nimport sys\nimport logging\nfrom visionlib.utils.webutils import web\nfrom visionlib.utils.imgutils import Image\n\nclass ODetection:\n \"\"\"This class contains all functions to detect objects from an image.\n . . .\n\n Methods:\n\n detect_objects():\n\n Used to detect objects from an image. Returns the bounding\n boxes, labels and confidence. Uses detector set by set_detector() method.\n\n draw_box():\n\n Used to draw the bounding box, labels and confidence in an image. Returns\n the frame with bounding boxes. Uses detector set by set_detector() method.\n\n set_detector():\n\n Used to set detector to used by detect_objects() method. If not set\n will use tiny yolo as default.\n\n \"\"\"\n\n def __init__(self):\n self.model = None\n self.model_ln = None\n np.random.seed(62)\n self.web_util = web()\n self.img_util = Image()\n self.min_confindence = 0.5\n self.threshold = 0.3\n\n def set_detector(self, model_name='tiny_yolo', model_path=None, cfg_path=None,\n label_path=None):\n '''Set's the detector to use. Can be tiny-yolo or yolo.\n Setting to tiny-yolo will use Tiny-yolov3.\n Setting to yolo will use Yolov3.\n\n Args:\n model_name (str):\n The model to use. If the given model is\n not present in pc, it will download and use it.\n model_path (str):\n Set this to path where the custom model You want\n to load is.\n cfg_path (str):\n Set this to path where the config file for custom model,\n You want to load is.\n label_path (str):\n Set this to path where the labels file for custom model,\n You want to load is.\n '''\n\n if model_path is not None and cfg_path is not None:\n if os.path.exists(model_path) & os.path.exists(cfg_path):\n model = model_path\n cfg = cfg_path\n if label_path is not None:\n labels = label_path\n else:\n raise Exception(\"Provided label path does not exist\")\n else:\n raise Exception(\"Provided model path or config path does not exist\")\n\n elif model_name == \"Tiny-yolov3\":\n model, cfg, labels = self.web_util.download_file(model_name, labels=True)\n\n elif model_name == \"Yolov3\":\n model, cfg, labels = self.web_util.download_file(model_name, labels=True)\n\n else:\n raise Exception(\"Invalid model name\")\n\n if model and cfg is not None:\n\n with open(labels, 'r') as file:\n self.labels = file.read().strip().split(\"\\n\")\n self.colours = np.random.randint(0, 255, size=(len(self.labels), 3), dtype=\"uint8\")\n\n self.model = cv2.dnn.readNetFromDarknet(cfg, model)\n self.model_ln = self.model.getLayerNames()\n self.model_ln = [\n self.model_ln[i[0] - 1] for i in self.model.getUnconnectedOutLayers()\n ]\n\n def detect_objects(self, frame, enable_gpu=False):\n '''This method is used to detect objects in an image.\n\n Args:\n frame (np.array):\n Image to detect objects from.\n\n enable_gpu (bool):\n Set to true if You want to use gpu.\n\n Returns:\n list :\n The detected bounding box.\n\n list :\n The detected class.\n\n list :\n Confidence for each detected class\n\n '''\n (H, W) = frame.shape[:2]\n blob = cv2.dnn.blobFromImage(\n frame, 1 / 255.0, (416, 416), swapRB=True, crop=False\n )\n\n if enable_gpu:\n self.model.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\n self.model.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\n\n self.model.setInput(blob)\n layerOutputs = self.model.forward(self.model_ln)\n boxes, confidences, classIDs = [], [], []\n\n for output in layerOutputs:\n\n for detection in output:\n scores = detection[5:]\n classID = np.argmax(scores)\n confidence = scores[classID]\n\n if confidence > self.min_confindence:\n box = detection[0:4] * np.array([W, H, W, H])\n (centerX, centerY, width, height) = box.astype(\"int\")\n x = int(centerX - (width / 2))\n y = int(centerY - (height / 2))\n boxes.append([x, y, int(width), int(height)])\n confidences.append(float(confidence))\n classIDs.append(classID)\n\n idxs = cv2.dnn.NMSBoxes(\n boxes, confidences, self.min_confindence, self.threshold\n )\n bbox = []\n label = []\n conf = []\n if len(idxs) > 0:\n for ix in idxs:\n ix = ix[0]\n box = boxes[ix]\n x = box[0]\n y = box[1]\n w = box[2]\n h = box[3]\n bbox.append([int(x), int(y), int(x + w), int(y + h)])\n label.append(str(self.labels[classIDs[ix]]))\n conf.append(confidences[ix])\n return bbox, label, conf\n\n def draw_bbox(self, img, bbox, labels, confidence):\n '''Draw's Box around the detected objects.\n\n Args\n img (numpy.array):\n The image to draw bounding boxes\n bbox (list):\n bounding boxes given detect_objects function.\n labels (list):\n labels given detect_objects function.\n confidence (list):\n Confidence for the detected label.\n\n Returns\n numpy.array :\n The image with bounding boxes and labels.\n '''\n\n for i, label in enumerate(labels):\n color = self.colours[self.labels.index(label)]\n color = [int(x) for x in color]\n conf = round(confidence[i] * 100, 2)\n label = label + \" \" + str(conf)\n cv2.rectangle(img, (bbox[i][0], bbox[i][1]), (bbox[i][2], bbox[i][3]), color, 2)\n cv2.putText(img, label, (bbox[i][0], bbox[i][1] - 10),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)\n\n return img\n\n def extract_objects(self, img=None, boxes=None, sdir=None, labels=None):\n i = 0\n if img is not None and boxes is not None:\n if labels is not None:\n for box, label in zip(boxes, labels):\n ex_img = self.img_util.crop(img, box)\n if sdir is not None:\n save_name = \"extracted_object_{0}_{1}.jpg\".format(label, i)\n save_dir = os.path.join(sdir, save_name)\n logging.info(\"Writing image to {0}\".format(save_dir))\n cv2.imwrite(save_dir, ex_img)\n i += 1\n yield ex_img\n else:\n for box in boxes:\n ex_img = self.img_util.crop(img, box)\n if sdir is not None:\n save_name = \"extracted_object_{0}.jpg\".format(i)\n save_dir = os.path.join(sdir, save_name)\n logging.info(\"Writing image to\", sdir + save_name)\n cv2.imwrite(save_dir, ex_img)\n i += 1\n yield ex_img\n"
] | [
[
"numpy.array",
"numpy.argmax",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
darpa-l2m/l2metrics | [
"5df0731646582aabd5072e30a1346bd19151747d"
] | [
"l2metrics/recovery_time.py"
] | [
"\"\"\"\nCopyright © 2021-2022 The Johns Hopkins University Applied Physics Laboratory LLC\n\nPermission is hereby granted, free of charge, to any person obtaining a copy \nof this software and associated documentation files (the “Software”), to \ndeal in the Software without restriction, including without limitation the \nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or \nsell copies of the Software, and to permit persons to whom the Software is \nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in \nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, \nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR \nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\nimport logging\nfrom collections import defaultdict\nfrom typing import Tuple\n\nimport pandas as pd\n\nfrom ._localutil import fill_metrics_df, get_terminal_perf\nfrom .core import Metric\n\nlogger = logging.getLogger(__name__)\n\n\nclass RecoveryTime(Metric):\n name = \"Recovery Time\"\n capability = \"adapt_to_new_tasks\"\n requires = {\"syllabus_type\": \"agent\"}\n description = \"Calculates whether the system recovers after a change of task or parameters and \\\n calculate how long it takes if recovery is achieved\"\n\n def __init__(self, perf_measure: str) -> None:\n super().__init__()\n self.perf_measure = perf_measure\n\n def validate(self, block_info: pd.DataFrame) -> Tuple[dict, dict]:\n # Get unique tasks\n unique_tasks = block_info.loc[:, \"task_name\"].unique()\n\n # Determine where we need to assess recovery time for each task\n ref_indices = defaultdict(list)\n assess_indices = defaultdict(list)\n\n for task in unique_tasks:\n # Get train blocks in order of appearance\n tr_block_info = block_info.sort_index().loc[\n (block_info[\"block_type\"] == \"train\")\n & (block_info[\"block_subtype\"] == \"wake\")\n & (block_info[\"task_name\"] == task),\n [\"task_name\"],\n ]\n tr_indices = tr_block_info.index\n\n # Regimes are defined as new combinations of tasks and params, but can repeat,\n # so check for changes across regimes\n first = True\n for idx, block_idx in enumerate(tr_indices):\n if first:\n first = False\n continue\n assess_indices[task].append(block_idx)\n ref_indices[task].append(tr_indices[idx - 1])\n\n if not (ref_indices and assess_indices):\n raise ValueError(\"Not enough blocks to assess recovery time\")\n\n return ref_indices, assess_indices\n\n def calculate(\n self,\n dataframe: pd.DataFrame,\n block_info: pd.DataFrame,\n metrics_df: pd.DataFrame,\n ) -> pd.DataFrame:\n try:\n # Get the places where we should calculate recovery time\n ref_indices, assess_indices = self.validate(block_info)\n\n # Initialize metric dictionary\n recovery_time = {}\n\n # Iterate over indices for computing recovery time\n for (_, ref_vals), (_, assess_vals) in zip(\n ref_indices.items(), assess_indices.items()\n ):\n for ref_ind, assess_ind in zip(ref_vals, assess_vals):\n prev_val = metrics_df[\"term_perf\"][ref_ind]\n block_data = dataframe.loc[assess_ind]\n\n # Check for proper number of rows in block data\n if block_data.ndim == 1:\n block_data = pd.DataFrame(block_data).T\n\n _, _, exp_to_rec = get_terminal_perf(\n block_data, col_to_use=self.perf_measure, prev_val=prev_val\n )\n recovery_time[assess_ind] = exp_to_rec\n\n return fill_metrics_df(recovery_time, \"recovery_time\", metrics_df)\n except ValueError as e:\n logger.warning(f\"Cannot compute {self.name} - {e}\")\n return metrics_df\n"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
i18MAME/image-analysis | [
"857cb5f2e9ff254361a1fc01fad7ec2165b06fb1"
] | [
"train.py"
] | [
"\"\"\"\nRetrain the YOLO model for your own dataset.\n\"\"\"\n\nimport numpy as np\nimport keras.backend as K\nfrom keras.layers import Input, Lambda\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\n\nfrom yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss\nfrom yolo3.utils import get_random_data\n\n\ndef _main():\n annotation_path = '2007_train.txt'\n log_dir = 'logs/000/'\n classes_path = 'model_data/my_classes.txt'\n anchors_path = 'model_data/yolo_anchors.txt'\n class_names = get_classes(classes_path)\n num_classes = len(class_names)\n anchors = get_anchors(anchors_path)\n\n input_shape = (416,416) # multiple of 32, hw\n\n is_tiny_version = len(anchors)==6 # default setting\n if is_tiny_version:\n model = create_tiny_model(input_shape, anchors, num_classes,\n freeze_body=2, weights_path='model_data/tiny_yolo_weights.h5')\n else:\n model = create_model(input_shape, anchors, num_classes,\n freeze_body=2, weights_path='model_data/yolo_weights.h5') # make sure you know what you freeze\n\n logging = TensorBoard(log_dir=log_dir)\n checkpoint = ModelCheckpoint(log_dir + 'ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5',\n monitor='val_loss', save_weights_only=True, save_best_only=True, period=3)\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1)\n early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1)\n\n val_split = 0.1\n with open(annotation_path) as f:\n lines = f.readlines()\n np.random.seed(10101)\n np.random.shuffle(lines)\n np.random.seed(None)\n num_val = int(len(lines)*val_split)\n num_train = len(lines) - num_val\n\n # Train with frozen layers first, to get a stable loss.\n # Adjust num epochs to your dataset. This step is enough to obtain a not bad model.\n if True:\n model.compile(optimizer=Adam(lr=1e-3), loss={\n # use custom yolo_loss Lambda layer.\n 'yolo_loss': lambda y_true, y_pred: y_pred})\n\n batch_size = 6\n print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))\n model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),\n steps_per_epoch=max(1, num_train//batch_size),\n validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),\n validation_steps=max(1, num_val//batch_size),\n epochs=35,\n initial_epoch=0,\n callbacks=[logging, checkpoint])\n model.save_weights(log_dir + 'trained_weights_stage_1.h5')\n\n # Unfreeze and continue training, to fine-tune.\n # Train longer if the result is not good.\n if True:\n for i in range(len(model.layers)):\n model.layers[i].trainable = True\n model.compile(optimizer=Adam(lr=1e-4), loss={'yolo_loss': lambda y_true, y_pred: y_pred}) # recompile to apply the change\n print('Unfreeze all of the layers.')\n\n batch_size = 6 # note that more GPU memory is required after unfreezing the body\n print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))\n model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),\n steps_per_epoch=max(1, num_train//batch_size),\n validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),\n validation_steps=max(1, num_val//batch_size),\n epochs=70,\n initial_epoch=35,\n callbacks=[logging, checkpoint, reduce_lr, early_stopping])\n model.save_weights(log_dir + 'trained_weights_final.h5')\n\n # Further training if needed.\n\n\ndef get_classes(classes_path):\n '''loads the classes'''\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\ndef get_anchors(anchors_path):\n '''loads the anchors from a file'''\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n\n\ndef create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,\n weights_path='model_data/yolo_weights.h5'):\n '''create the training model'''\n K.clear_session() # get a new session\n image_input = Input(shape=(None, None, 3))\n h, w = input_shape\n num_anchors = len(anchors)\n\n y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \\\n num_anchors//3, num_classes+5)) for l in range(3)]\n\n model_body = yolo_body(image_input, num_anchors//3, num_classes)\n print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))\n\n if load_pretrained:\n model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)\n print('Load weights {}.'.format(weights_path))\n if freeze_body in [1, 2]:\n # Freeze darknet53 body or freeze all but 3 output layers.\n num = (185, len(model_body.layers)-3)[freeze_body-1]\n for i in range(num): model_body.layers[i].trainable = False\n print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))\n\n model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',\n arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})(\n [*model_body.output, *y_true])\n model = Model([model_body.input, *y_true], model_loss)\n\n return model\n\ndef create_tiny_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,\n weights_path='model_data/tiny_yolo_weights.h5'):\n '''create the training model, for Tiny YOLOv3'''\n K.clear_session() # get a new session\n image_input = Input(shape=(None, None, 3))\n h, w = input_shape\n num_anchors = len(anchors)\n\n y_true = [Input(shape=(h//{0:32, 1:16}[l], w//{0:32, 1:16}[l], \\\n num_anchors//2, num_classes+5)) for l in range(2)]\n\n model_body = tiny_yolo_body(image_input, num_anchors//2, num_classes)\n print('Create Tiny YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))\n\n if load_pretrained:\n model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)\n print('Load weights {}.'.format(weights_path))\n if freeze_body in [1, 2]:\n # Freeze the darknet body or freeze all but 2 output layers.\n num = (20, len(model_body.layers)-2)[freeze_body-1]\n for i in range(num): model_body.layers[i].trainable = False\n print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))\n\n model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',\n arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.7})(\n [*model_body.output, *y_true])\n model = Model([model_body.input, *y_true], model_loss)\n\n return model\n\ndef data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):\n '''data generator for fit_generator'''\n n = len(annotation_lines)\n i = 0\n while True:\n image_data = []\n box_data = []\n for b in range(batch_size):\n if i==0:\n np.random.shuffle(annotation_lines)\n image, box = get_random_data(annotation_lines[i], input_shape, random=True)\n image_data.append(image)\n box_data.append(box)\n i = (i+1) % n\n image_data = np.array(image_data)\n box_data = np.array(box_data)\n y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)\n yield [image_data, *y_true], np.zeros(batch_size)\n\ndef data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes):\n n = len(annotation_lines)\n if n==0 or batch_size<=0: return None\n return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)\n\nif __name__ == '__main__':\n _main()\n"
] | [
[
"numpy.random.shuffle",
"numpy.array",
"numpy.zeros",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
antoinediez/Sisyphe | [
"f6bb067cd8898450174c5d97bb0f3f0cb5db8b87"
] | [
"sisyphe/initial.py"
] | [
"import math\nimport torch\nfrom .sampling import vonmises_quat_rand, quat_mult\n# from display import bo_display\n\n\ndef cyclotron_twist_z(N,L,k,kappa,dtype):\n pos = torch.tensor(L).type(dtype)*torch.rand(N,3).type(dtype)\n \n if type(L)==float or type(L)==int:\n qtarget = torch.cat((\n torch.cos((2*math.pi*k/L)*pos[:,2]/2).reshape(N,1),\n torch.sin((2*math.pi*k/L)*pos[:,2]/2).reshape(N,1),\n torch.zeros(N,1).type(dtype),\n torch.zeros(N,1).type(dtype)),dim=1).type(dtype)\n else:\n qtarget = torch.cat((\n torch.cos((2*math.pi*k/L[2])*pos[:,2]/2).reshape(N,1),\n torch.sin((2*math.pi*k/L[2])*pos[:,2]/2).reshape(N,1),\n torch.zeros(N,1).type(dtype),\n torch.zeros(N,1).type(dtype)),dim=1).type(dtype) \n bo = vonmises_quat_rand(qtarget, torch.tensor([kappa]).type(dtype))\n \n return pos, bo\n\n\ndef inverted_cyclotron_twist_z(N,L,k,kappa,dtype):\n pos = torch.tensor(L).type(dtype)*torch.rand(N,3).type(dtype)\n bo = torch.zeros(N,4).type(dtype)\n \n if type(L)==float or type(L)==int:\n N1 = torch.sum(pos[:,2]<L/2.).int()\n N2 = torch.sum(pos[:,2]>=L/2.).int()\n qtarget1 = torch.cat((\n torch.cos((2*math.pi*k/L)*pos[pos[:,2]<L/2.,2]/2).reshape(N1,1),\n torch.sin((2*math.pi*k/L)*pos[pos[:,2]<L/2.,2]/2).reshape(N1,1),\n torch.zeros(N1,1).type(dtype),\n torch.zeros(N1,1).type(dtype)),dim=1).type(dtype)\n bo[pos[:,2]<L/2.,:] = vonmises_quat_rand(qtarget1, torch.tensor([kappa]).type(dtype))\n \n qtarget2 = torch.cat((\n torch.cos((2*math.pi*k/L)*pos[pos[:,2]>=L/2.,2]/2).reshape(N2,1),\n -torch.sin((2*math.pi*k/L)*pos[pos[:,2]>=L/2.,2]/2).reshape(N2,1),\n torch.zeros(N2,1).type(dtype),\n torch.zeros(N2,1).type(dtype)),dim=1).type(dtype)\n bo[pos[:,2]>=L/2.,:] = vonmises_quat_rand(qtarget2, torch.tensor([kappa]).type(dtype))\n else:\n N1 = torch.sum(pos[:,2]<L[2]/2.).int()\n N2 = torch.sum(pos[:,2]>=L[2]/2.).int()\n qtarget1 = torch.cat((\n torch.cos((2*math.pi*k/L[2])*pos[pos[:,2]<L[2]/2.,2]/2).reshape(N1,1),\n torch.sin((2*math.pi*k/L[2])*pos[pos[:,2]<L[2]/2.,2]/2).reshape(N1,1),\n torch.zeros(N1,1).type(dtype),\n torch.zeros(N1,1).type(dtype)),dim=1).type(dtype)\n bo[pos[:,2]<L[2]/2.,:] = vonmises_quat_rand(qtarget1, torch.tensor([kappa]).type(dtype))\n \n qtarget2 = torch.cat((\n torch.cos((2*math.pi*k/L[2])*pos[pos[:,2]>=L[2]/2.,2]/2).reshape(N2,1),\n -torch.sin((2*math.pi*k/L[2])*pos[pos[:,2]>=L[2]/2.,2]/2).reshape(N2,1),\n torch.zeros(N2,1).type(dtype),\n torch.zeros(N2,1).type(dtype)),dim=1).type(dtype)\n bo[pos[:,2]>=L[2]/2.,:] = vonmises_quat_rand(qtarget2, torch.tensor([kappa]).type(dtype))\n \n return pos, bo\n\ndef helical_twist_x(N,L,k,kappa,dtype):\n pos = torch.tensor(L).type(dtype)*torch.rand(N,3).type(dtype)\n \n if type(L)==float or type(L)==int:\n qtarget = torch.cat((\n torch.cos((2*math.pi*k/L)*pos[:,0]/2).reshape(N,1),\n torch.sin((2*math.pi*k/L)*pos[:,0]/2).reshape(N,1),\n torch.zeros(N,1).type(dtype),\n torch.zeros(N,1).type(dtype)),dim=1).type(dtype)\n else:\n qtarget = torch.cat((\n torch.cos((2*math.pi*k/L[0])*pos[:,0]/2).reshape(N,1),\n torch.sin((2*math.pi*k/L[0])*pos[:,0]/2).reshape(N,1),\n torch.zeros(N,1).type(dtype),\n torch.zeros(N,1).type(dtype)),dim=1).type(dtype) \n bo = vonmises_quat_rand(qtarget, torch.tensor([kappa]).type(dtype))\n \n return pos, bo\n\n\ndef inverted_helical_twist_x(N,L,k,kappa,dtype):\n pos = torch.tensor(L).type(dtype)*torch.rand(N,3).type(dtype)\n bo = torch.zeros(N,4).type(dtype)\n \n if type(L)==float or type(L)==int:\n N1 = torch.sum(pos[:,0]<L/2.).int()\n N2 = torch.sum(pos[:,0]>=L/2.).int()\n qtarget1 = torch.cat((\n torch.cos((2*math.pi*k/L)*pos[pos[:,0]<L/2.,0]/2).reshape(N1,1),\n torch.sin((2*math.pi*k/L)*pos[pos[:,0]<L/2.,0]/2).reshape(N1,1),\n torch.zeros(N1,1).type(dtype),\n torch.zeros(N1,1).type(dtype)),dim=1).type(dtype)\n bo[pos[:,0]<L/2.,:] = vonmises_quat_rand(qtarget1, torch.tensor([kappa]).type(dtype))\n \n qtarget2 = torch.cat((\n torch.cos((2*math.pi*k/L)*pos[pos[:,0]>=L/2.,0]/2).reshape(N2,1),\n -torch.sin((2*math.pi*k/L)*pos[pos[:,0]>=L/2.,0]/2).reshape(N2,1),\n torch.zeros(N2,1).type(dtype),\n torch.zeros(N2,1).type(dtype)),dim=1).type(dtype)\n bo[pos[:,0]>=L/2.,:] = vonmises_quat_rand(qtarget2, torch.tensor([kappa]).type(dtype))\n else:\n N1 = torch.sum(pos[:,0]<L[0]/2.).int()\n N2 = torch.sum(pos[:,0]>=L[0]/2.).int()\n qtarget1 = torch.cat((\n torch.cos((2*math.pi*k/L[0])*pos[pos[:,0]<L[0]/2.,0]/2).reshape(N1,1),\n torch.sin((2*math.pi*k/L[0])*pos[pos[:,0]<L[0]/2.,0]/2).reshape(N1,1),\n torch.zeros(N1,1).type(dtype),\n torch.zeros(N1,1).type(dtype)),dim=1).type(dtype)\n bo[pos[:,0]<L[0]/2.,:] = vonmises_quat_rand(qtarget1, torch.tensor([kappa]).type(dtype))\n \n qtarget2 = torch.cat((\n torch.cos((2*math.pi*k/L[0])*pos[pos[:,0]>=L[0]/2.,0]/2).reshape(N2,1),\n -torch.sin((2*math.pi*k/L[0])*pos[pos[:,0]>=L[0]/2.,0]/2).reshape(N2,1),\n torch.zeros(N2,1).type(dtype),\n torch.zeros(N2,1).type(dtype)),dim=1).type(dtype)\n bo[pos[:,0]>=L[0]/2.,:] = vonmises_quat_rand(qtarget2, torch.tensor([kappa]).type(dtype))\n \n return pos, bo"
] | [
[
"torch.zeros",
"torch.sin",
"torch.sum",
"torch.tensor",
"torch.rand",
"torch.cos"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AI4Bharat/OpenHands | [
"a3c2c416395d70c7eb63294d955a84d1c8ea4410"
] | [
"openhands/models/decoder/bert_hf.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport transformers\nfrom .utils import AttentionBlock\n\n\nclass PositionEmbedding(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.position_embeddings = nn.Embedding(\n config.max_position_embeddings, config.hidden_size\n )\n self.LayerNorm = nn.LayerNorm(\n config.hidden_size, eps=float(config.layer_norm_eps)\n )\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.register_buffer(\n \"position_ids\", torch.arange(config.max_position_embeddings).expand((1, -1))\n )\n self.position_embedding_type = getattr(\n config, \"position_embedding_type\", \"absolute\"\n )\n\n def forward(self, x):\n input_shape = x.size()\n seq_length = input_shape[1]\n position_ids = self.position_ids[:, :seq_length]\n\n position_embeddings = self.position_embeddings(position_ids)\n embeddings = x + position_embeddings\n embeddings = self.LayerNorm(embeddings)\n embeddings = self.dropout(embeddings)\n return embeddings\n\n\nclass BERT(nn.Module):\n \"\"\"\n BERT decoder module. \n\n Args:\n n_features (int): Number of features in the input.\n num_class (int): Number of class for classification.\n config (dict): Configuration set for BERT layer.\n \n \"\"\"\n def __init__(self, n_features, num_class, config):\n \"\"\"\n pooling_type -> [\"max\",\"avg\",\"att\",\"cls\"]\n \"\"\"\n super().__init__()\n self.cls_token = config[\"cls_token\"]\n\n if self.cls_token:\n self.pooling_type = \"cls\"\n self.cls_param = nn.Parameter(torch.randn(config.hidden_size))\n else:\n self.pooling_type = config[\"pooling_type\"]\n\n self.l1 = nn.Linear(in_features=n_features, out_features=config.hidden_size)\n\n self.embedding = PositionEmbedding(config)\n model_config = transformers.BertConfig(\n hidden_size=config.hidden_size,\n num_attention_heads=config.num_attention_heads,\n num_hidden_layers=config.num_hidden_layers,\n )\n self.layers = nn.ModuleList(\n [\n transformers.BertLayer(model_config)\n for _ in range(config.num_hidden_layers)\n ]\n )\n\n if self.pooling_type == \"att\":\n self.attn_block = AttentionBlock(config.hidden_size)\n\n # self.bert = transformers.BertModel(model_config)\n self.l2 = nn.Linear(in_features=config.hidden_size, out_features=num_class)\n\n def forward(self, x):\n \"\"\"\n Args:\n x (torch.Tensor): Input tensor of shape: (batch_size, T, n_features)\n \n returns:\n torch.Tensor: logits for classification.\n \"\"\"\n x = self.l1(x)\n if self.cls_token:\n cls_embed = self.cls_param.unsqueeze(0).repeat(x.shape[0], 1, 1)\n x = torch.cat((cls_embed, x), dim=1)\n x = self.embedding(x)\n for layer in self.layers:\n x = layer(x)[0]\n\n if self.pooling_type == \"cls\":\n x = x[:, 0]\n elif self.pooling_type == \"max\":\n x = torch.max(x, dim=1).values\n elif self.pooling_type == \"avg\":\n x = torch.mean(x, dim=1)\n elif self.pooling_type == \"att\":\n x = self.attn_block(x)\n\n x = F.dropout(x, p=0.2)\n x = self.l2(x)\n return x\n"
] | [
[
"torch.mean",
"torch.nn.Dropout",
"torch.max",
"torch.cat",
"torch.nn.functional.dropout",
"torch.randn",
"torch.nn.Embedding",
"torch.nn.Linear",
"torch.arange"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kim5284/qiskit-metal | [
"f39270b3b620a7560c43b07dd8b669692accc926"
] | [
"qiskit_metal/analyses/em/kappa_calculation.py"
] | [
"\"\"\"\r\nThis code calculates the photon loss (kappa) due to the capacitive coupling between CPWs\r\nand input/output transmission lines in a quantum circuit. \r\n\r\nTwo cases are treated: In the first case, three arguments are passed to the function kappa_in\r\nand the resonant frequency of the CPW is input as a float. In the second case, six arguments\r\nare passed to kappa_in and the frequency of the CPW is calculated assuming an ideal CPW. \r\n\r\nKey References:\r\n\r\nD. Schuster, Ph.D. Thesis, Yale University (2007)\r\nhttps://rsl.yale.edu/sites/default/files/files/RSL_Theses/SchusterThesis.pdf\r\n\r\nT. McConkey, Ph.D. Thesis, University of Waterloo (2018)\r\nhttps://uwspace.uwaterloo.ca/bitstream/handle/10012/13464/McConkey_Thomas.pdf?sequence=3&isAllowed=y\r\n\r\nMohebbi and Majedi, Superconducting Science and Technology 22, 125028 (2009)\r\nhttps://iopscience.iop.org/article/10.1088/0953-2048/22/12/125028/meta\r\n\r\nP. Krantz, et al. Physical Review Applied 6, 021318 (2019)\r\nhttps://aip.scitation.org/doi/10.1063/1.5089550\r\n\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom math import *\r\nfrom scipy.special import ellipk\r\n\r\n__all__ = ['kappa_in']\r\n\r\n\r\ndef kappa_in(*argv):\r\n \"\"\"\r\n A simple calculator for the kappa value of a readout resonator.\r\n\r\n Args:\r\n freq (float): The frequency of interest, in Hz\r\n C_in (float): Effective capacitance between CPW and environment (from Q3D), in Farads\r\n freq_res (float): Lowest resonant frequency of a CPW (from HFSS), in Hz \r\n length (float): Length of the CPW readout resonator, in meters\r\n res_width (float): Width of the resonator trace (center) line, in meters\r\n res_gap (float): Width of resonator gap (dielectric space), in meters \r\n eta (float): 2.0 for half-wavelength resonator; 4.0 for quarter-wavelength resonator\r\n\r\n Returns:\r\n float: Kappa value\r\n \"\"\"\r\n\r\n # Effective impedance of the CPW transmission line, in Ohms\r\n Z_tran = 50.0\r\n\r\n # Effective impedance of the readout resonator, in Ohms\r\n Z_res = 50.0\r\n\r\n # If three arguments are passed to kappa_in, then the lowest resonator frequency is assumed to be an input\r\n if len(argv) == 3:\r\n for i in argv:\r\n freq = argv[0]\r\n C_in = argv[1]\r\n freq_res = argv[2]\r\n\r\n # Calculation of kappa\r\n kappa = (2 / pi) * (freq**2.0) * (C_in**2.0) * (Z_tran**\r\n 2.0) * (freq_res)\r\n\r\n return kappa\r\n\r\n # If six arguments are passed to kappa_in, the lowest resonator frequency of the resonator is calculated in the ideal case\r\n elif len(argv) == 6:\r\n for i in argv:\r\n freq = argv[0]\r\n C_in = argv[1]\r\n length = argv[2]\r\n res_width = argv[3]\r\n res_gap = argv[4]\r\n eta = argv[5]\r\n\r\n # Arguments for elliptic integrals\r\n k0 = (res_width) / (res_width + 2.0 * res_gap)\r\n k01 = (1.0 - k0**2.0)**(0.5)\r\n\r\n # Calculation of the first resonant frequency of an ideal resonator\r\n freq_res = (Z_res) * (ellipk(k0)) / (15.0 * eta * length * ellipk(k01))\r\n\r\n # Calculation of kappa\r\n kappa = (2 / pi) * (freq**2.0) * (C_in**2.0) * (Z_tran**\r\n 2.0) * (freq_res)\r\n return kappa\r\n\r\n # Only three or six arguments accepted by kappa_in, otherwise the calculation in invalid.\r\n else:\r\n kappa = \"Invalid number of arguments passed for kappa_in\"\r\n"
] | [
[
"scipy.special.ellipk"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"0.16",
"0.19",
"0.18",
"1.2",
"0.12",
"1.0",
"0.17",
"1.3"
],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.