repo_name
stringlengths 8
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence |
---|---|---|---|---|
slavslav/tensorflow | [
"e29e704c9c8d68113fc407243b75a09325c86d08"
] | [
"tensorflow/python/distribute/distribute_lib.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\"\"\"Library for running a computation across multiple devices.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nimport enum\nimport threading\nimport weakref\nimport six\n\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.distribute import device_util\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.distribute import numpy_dataset\nfrom tensorflow.python.distribute import reduce_util\nfrom tensorflow.python.eager import context as eager_context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import custom_gradient\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.platform import tf_logging\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util.tf_export import tf_export\nfrom tensorflow.tools.docs import doc_controls\n\n\n# ------------------------------------------------------------------------------\n# Context tracking whether in a strategy.update() or .update_non_slot() call.\n\n\n_update_device = threading.local()\n\n\ndef get_update_device():\n \"\"\"Get the current device if in a `tf.distribute.Strategy.update()` call.\"\"\"\n try:\n return _update_device.current\n except AttributeError:\n return None\n\n\nclass UpdateContext(object):\n \"\"\"Context manager when you are in `update()` or `update_non_slot()`.\"\"\"\n\n def __init__(self, device):\n self._device = device\n self._old_device = None\n\n def __enter__(self):\n self._old_device = get_update_device()\n _update_device.current = self._device\n\n def __exit__(self, exception_type, exception_value, traceback):\n del exception_type, exception_value, traceback\n _update_device.current = self._old_device\n\n\n# ------------------------------------------------------------------------------\n# Public utility functions.\n\n\n@tf_export(v1=[\"distribute.get_loss_reduction\"])\ndef get_loss_reduction():\n \"\"\"DEPRECATED: Now always returns `tf.distribute.ReduceOp.SUM`.\n\n We now always make the complete adjustment when computing the loss, so\n code should always add gradients/losses across replicas, never average.\n \"\"\"\n return reduce_util.ReduceOp.SUM\n\n\n# ------------------------------------------------------------------------------\n# Internal API for validating the current thread mode\n\n\ndef _require_cross_replica_or_default_context_extended(extended):\n \"\"\"Verify in cross-replica context.\"\"\"\n context = _get_per_thread_mode()\n cross_replica = context.cross_replica_context\n if cross_replica is not None and cross_replica.extended is extended:\n return\n if context is _get_default_replica_mode():\n return\n strategy = extended._container_strategy() # pylint: disable=protected-access\n # We have an error to report, figure out the right message.\n if context.strategy is not strategy:\n _wrong_strategy_scope(strategy, context)\n assert cross_replica is None\n raise RuntimeError(\"Method requires being in cross-replica context, use \"\n \"get_replica_context().merge_call()\")\n\n\ndef _wrong_strategy_scope(strategy, context):\n # Figure out the right error message.\n if not distribution_strategy_context.has_strategy():\n raise RuntimeError(\n 'Need to be inside \"with strategy.scope()\" for %s' %\n (strategy,))\n else:\n raise RuntimeError(\n \"Mixing different tf.distribute.Strategy objects: %s is not %s\" %\n (context.strategy, strategy))\n\n\ndef require_replica_context(replica_ctx):\n \"\"\"Verify in `replica_ctx` replica context.\"\"\"\n context = _get_per_thread_mode()\n if context.replica_context is replica_ctx: return\n # We have an error to report, figure out the right message.\n if context.replica_context is None:\n raise RuntimeError(\"Need to be inside `call_for_each_replica()`\")\n if context.strategy is replica_ctx.strategy:\n # Two different ReplicaContexts with the same tf.distribute.Strategy.\n raise RuntimeError(\"Mismatching ReplicaContext.\")\n raise RuntimeError(\n \"Mismatching tf.distribute.Strategy objects: %s is not %s.\" %\n (context.strategy, replica_ctx.strategy))\n\n\ndef _require_strategy_scope_strategy(strategy):\n \"\"\"Verify in a `strategy.scope()` in this thread.\"\"\"\n context = _get_per_thread_mode()\n if context.strategy is strategy: return\n _wrong_strategy_scope(strategy, context)\n\n\ndef _require_strategy_scope_extended(extended):\n \"\"\"Verify in a `distribution_strategy.scope()` in this thread.\"\"\"\n context = _get_per_thread_mode()\n if context.strategy.extended is extended: return\n # Report error.\n strategy = extended._container_strategy() # pylint: disable=protected-access\n _wrong_strategy_scope(strategy, context)\n\n\n# ------------------------------------------------------------------------------\n# Internal context managers used to implement the DistributionStrategy\n# base class\n\n\nclass _CurrentDistributionContext(object):\n \"\"\"Context manager setting the current `tf.distribute.Strategy`.\n\n Also: overrides the variable creator and optionally the current device.\n \"\"\"\n\n def __init__(self,\n strategy,\n var_creator_scope,\n var_scope=None,\n default_device=None):\n self._context = distribution_strategy_context._CrossReplicaThreadMode( # pylint: disable=protected-access\n strategy)\n self._var_creator_scope = var_creator_scope\n self._var_scope = var_scope\n if default_device:\n self._device_scope = ops.device(default_device)\n else:\n self._device_scope = None\n self._same_scope_again_count = 0\n\n def __enter__(self):\n # Allow this scope to be entered if this strategy is already in scope.\n if distribution_strategy_context.has_strategy():\n _require_cross_replica_or_default_context_extended(\n self._context.strategy.extended)\n self._same_scope_again_count += 1\n else:\n _push_per_thread_mode(self._context)\n if self._var_scope:\n self._var_scope.__enter__()\n self._var_creator_scope.__enter__()\n if self._device_scope:\n self._device_scope.__enter__()\n return self._context.strategy\n\n def __exit__(self, exception_type, exception_value, traceback):\n if self._same_scope_again_count > 0:\n self._same_scope_again_count -= 1\n return\n if self._device_scope:\n try:\n self._device_scope.__exit__(exception_type, exception_value, traceback)\n except RuntimeError as e:\n six.raise_from(\n RuntimeError(\"Device scope nesting error: move call to \"\n \"tf.distribute.set_strategy() out of `with` scope.\"),\n e)\n\n try:\n self._var_creator_scope.__exit__(\n exception_type, exception_value, traceback)\n except RuntimeError as e:\n six.raise_from(\n RuntimeError(\"Variable creator scope nesting error: move call to \"\n \"tf.distribute.set_strategy() out of `with` scope.\"),\n e)\n\n if self._var_scope:\n try:\n self._var_scope.__exit__(exception_type, exception_value, traceback)\n except RuntimeError as e:\n six.raise_from(\n RuntimeError(\"Variable scope nesting error: move call to \"\n \"tf.distribute.set_strategy() out of `with` scope.\"),\n e)\n _pop_per_thread_mode()\n\n\n# TODO(yuefengz): add more replication modes.\n@tf_export(\"distribute.InputReplicationMode\")\nclass InputReplicationMode(enum.Enum):\n \"\"\"Replication mode for input function.\n\n * `PER_WORKER`: The input function will be called on each worker\n independently, creating as many input pipelines as number of workers.\n Replicas will dequeue from the local Dataset on their worker.\n `tf.distribute.Strategy` doesn't manage any state sharing between such\n separate input pipelines.\n \"\"\"\n PER_WORKER = \"PER_WORKER\"\n\n\n@tf_export(\"distribute.InputContext\")\nclass InputContext(object):\n \"\"\"A class wrapping information needed by an input function.\n\n This is a context class that is passed to the user's input fn and contains\n information about the compute replicas and input pipelines. The number of\n compute replicas (in sync training) helps compute per input pipeline batch\n size from the desired global batch size. Input pipeline information can be\n used to return a different subset of the input in each input pipeline (for\n e.g. shard the input pipeline, use a different input source etc).\n \"\"\"\n\n def __init__(self,\n num_input_pipelines=1,\n input_pipeline_id=0,\n num_replicas_in_sync=1):\n \"\"\"Initializes an InputContext object.\n\n Args:\n num_input_pipelines: the number of input pipelines in a cluster.\n input_pipeline_id: the current input pipeline id, should be an int in\n [0,`num_input_pipelines`).\n num_replicas_in_sync: the number of replicas that are in sync.\n \"\"\"\n self._num_input_pipelines = num_input_pipelines\n self._input_pipeline_id = input_pipeline_id\n self._num_replicas_in_sync = num_replicas_in_sync\n\n @property\n def num_replicas_in_sync(self):\n \"\"\"Returns the number of compute replicas in sync.\"\"\"\n return self._num_replicas_in_sync\n\n @property\n def input_pipeline_id(self):\n \"\"\"Returns the input pipeline ID.\"\"\"\n return self._input_pipeline_id\n\n @property\n def num_input_pipelines(self):\n \"\"\"Returns the number of input pipelines.\"\"\"\n return self._num_input_pipelines\n\n def get_per_replica_batch_size(self, global_batch_size):\n \"\"\"Returns the per-replica batch size.\n\n Args:\n global_batch_size: the global batch size which should be divisible by\n `num_replicas_in_sync`.\n\n Returns:\n the per-replica batch size.\n\n Raises:\n ValueError: if `global_batch_size` not divisible by\n `num_replicas_in_sync`.\n \"\"\"\n if global_batch_size % self._num_replicas_in_sync != 0:\n raise ValueError(\"The `global_batch_size` %r is not divisible by \"\n \"`num_replicas_in_sync` %r \" %\n (global_batch_size, self._num_replicas_in_sync))\n return global_batch_size // self._num_replicas_in_sync\n\n\n# ------------------------------------------------------------------------------\n# Base classes for all distribution strategies.\n\n\n@tf_export(\"distribute.Strategy\")\nclass DistributionStrategy(object):\n \"\"\"A list of devices with a state & compute distribution policy.\n\n See [tensorflow/contrib/distribute/README.md](\n https://www.tensorflow.org/code/tensorflow/contrib/distribute/README.md)\n for overview and examples.\n \"\"\"\n\n # TODO(josh11b): Raise an exception if variable partitioning requested before\n # we add support.\n # TODO(josh11b): Also `parameter_device_index` property?\n # TODO(josh11b): `map()`\n # TODO(josh11b): ClusterSpec/ClusterResolver\n # TODO(josh11b): Partitioned computations, state; sharding\n # TODO(josh11b): Model parallelism: \"replicas\" with multiple devices; shuffling\n # TODO(josh11b): List of replicas with their worker and parameter devices\n # (where the parameter devices may overlap in the ps case).\n\n def __init__(self, extended):\n self._extended = extended\n\n @property\n def extended(self):\n \"\"\"`tf.distribute.StrategyExtended` with additional methods.\"\"\"\n return self._extended\n\n def scope(self):\n \"\"\"Returns a context manager selecting this Strategy as current.\n\n Inside a `with strategy.scope():` code block, this thread\n will use a variable creator set by `strategy`, and will\n enter its \"cross-replica context\".\n\n Returns:\n A context manager.\n \"\"\"\n return self._extended._scope(self) # pylint: disable=protected-access\n\n @doc_controls.do_not_generate_docs # DEPRECATED, moving to `extended`\n def colocate_vars_with(self, colocate_with_variable):\n \"\"\"DEPRECATED: use extended.colocate_vars_with() instead.\"\"\"\n return self._extended.colocate_vars_with(colocate_with_variable)\n\n def make_dataset_iterator(self, dataset):\n \"\"\"Makes an iterator for input provided via `dataset`.\n\n Data from the given dataset will be distributed evenly across all the\n compute replicas. We will assume that the input dataset is batched by the\n global batch size. With this assumption, we will make a best effort to\n divide each batch across all the replicas (one or more workers).\n If this effort fails, an error will be thrown, and the user should instead\n use `make_input_fn_iterator` which provides more control to the user, and\n does not try to divide a batch across replicas.\n\n The user could also use `make_input_fn_iterator` if they want to\n customize which input is fed to which replica/worker etc.\n\n Args:\n dataset: `tf.data.Dataset` that will be distributed evenly across all\n replicas.\n\n Returns:\n An `tf.distribute.InputIterator` which returns inputs for each step of the\n computation. User should call `initialize` on the returned iterator.\n \"\"\"\n return self._extended._make_dataset_iterator(dataset) # pylint: disable=protected-access\n\n def make_input_fn_iterator(self,\n input_fn,\n replication_mode=InputReplicationMode.PER_WORKER):\n \"\"\"Returns an iterator split across replicas created from an input function.\n\n The `input_fn` should take an `tf.distribute.InputContext` object where\n information about batching and input sharding can be accessed:\n\n ```\n def input_fn(input_context):\n batch_size = input_context.get_per_replica_batch_size(global_batch_size)\n d = tf.data.Dataset.from_tensors([[1.]]).repeat().batch(batch_size)\n return d.shard(input_context.num_input_pipelines,\n input_context.input_pipeline_id)\n with strategy.scope():\n iterator = strategy.make_input_fn_iterator(input_fn)\n replica_results = strategy.experimental_run(replica_fn, iterator)\n ```\n\n The `tf.data.Dataset` returned by `input_fn` should have a per-replica\n batch size, which may be computed using\n `input_context.get_per_replica_batch_size`.\n\n Args:\n input_fn: A function taking a `tf.distribute.InputContext` object and\n returning a `tf.data.Dataset`.\n replication_mode: an enum value of `tf.distribute.InputReplicationMode`.\n Only `PER_WORKER` is supported currently, which means there will be\n a single call to `input_fn` per worker. Replicas will dequeue from the\n local `tf.data.Dataset` on their worker.\n\n Returns:\n An iterator object that should first be `.initialize()`-ed. It may then\n either be passed to `strategy.experimental_run()` or you can\n `iterator.get_next()` to get the next value to pass to\n `strategy.extended.call_for_each_replica()`.\n \"\"\"\n if replication_mode != InputReplicationMode.PER_WORKER:\n raise ValueError(\n \"Input replication mode not supported: %r\" % replication_mode)\n with self.scope():\n return self.extended._make_input_fn_iterator( # pylint: disable=protected-access\n input_fn, replication_mode=replication_mode)\n\n @doc_controls.do_not_generate_docs # DEPRECATED\n def experimental_make_numpy_iterator(\n self, numpy_input, batch_size, num_epochs=1, shuffle=1024, session=None):\n \"\"\"Makes an iterator for input provided via a nest of numpy arrays.\n\n DEPRECATED: Use `extended.experimental_make_numpy_dataset` instead.\n\n Args:\n numpy_input: A nest of NumPy input arrays that will be distributed evenly\n across all replicas. Note that lists of Numpy arrays are stacked,\n as that is normal `tf.data.Dataset` behavior.\n batch_size: The number of entries from the array we should consume in one\n step of the computation, across all replicas. This is the global batch\n size. It should be divisible by `num_replicas_in_sync`.\n num_epochs: The number of times to iterate through the examples. A value\n of `None` means repeat forever.\n shuffle: Size of buffer to use for shuffling the input examples.\n Use `None` to disable shuffling.\n session: (TensorFlow v1.x graph execution only) A session used for\n initialization.\n\n Returns:\n An `tf.distribute.InputIterator` which returns inputs for each step of the\n computation. User should call `initialize` on the returned iterator.\n \"\"\"\n ds = self.extended.experimental_make_numpy_dataset(\n numpy_input, session=session)\n if shuffle:\n ds = ds.shuffle(shuffle)\n if num_epochs != 1:\n ds = ds.repeat(num_epochs)\n # We need to use the drop_remainder argument to get a known static\n # input shape which is required for TPUs.\n drop_remainder = self.extended.experimental_require_static_shapes\n ds = ds.batch(batch_size, drop_remainder=drop_remainder)\n return self.make_dataset_iterator(ds)\n\n def experimental_run(self, fn, input_iterator=None):\n \"\"\"Runs ops in `fn` on each replica, with inputs from `input_iterator`.\n\n When eager execution is enabled, executes ops specified by `fn` on each\n replica. Otherwise, builds a graph to execute the ops on each replica.\n\n Each replica will take a single, different input from the inputs provided by\n one `get_next` call on the input iterator.\n\n `fn` may call `tf.distribute.get_replica_context()` to access members such\n as `replica_id_in_sync_group`.\n\n IMPORTANT: Depending on the `tf.distribute.Strategy` implementation being\n used, and whether eager execution is enabled, `fn` may be called one or more\n times (once for each replica).\n\n Args:\n fn: The function to run. The inputs to the function must match the outputs\n of `input_iterator.get_next()`. The output must be a `tf.nest` of\n `Tensor`s.\n input_iterator: (Optional) input iterator from which the inputs are taken.\n\n Returns:\n Merged return value of `fn` across replicas. The structure of the return\n value is the same as the return value from `fn`. Each element in the\n structure can either be `PerReplica` (if the values are unsynchronized),\n `Mirrored` (if the values are kept in sync), or `Tensor` (if running on a\n single replica).\n \"\"\"\n with self.scope():\n args = (input_iterator.get_next(),) if input_iterator is not None else ()\n return self.experimental_run_v2(fn, args=args)\n\n def experimental_run_v2(self, fn, args=(), kwargs=None):\n \"\"\"Runs ops in `fn` on each replica, with the given arguments.\n\n When eager execution is enabled, executes ops specified by `fn` on each\n replica. Otherwise, builds a graph to execute the ops on each replica.\n\n `fn` may call `tf.distribute.get_replica_context()` to access members such\n as `replica_id_in_sync_group`.\n\n IMPORTANT: Depending on the `tf.distribute.Strategy` implementation being\n used, and whether eager execution is enabled, `fn` may be called one or more\n times (once for each replica).\n\n Args:\n fn: The function to run. The output must be a `tf.nest` of `Tensor`s.\n args: (Optional) Positional arguments to `fn`.\n kwargs: (Optional) Keyword arguments to `fn`.\n\n Returns:\n Merged return value of `fn` across replicas. The structure of the return\n value is the same as the return value from `fn`. Each element in the\n structure can either be `PerReplica` (if the values are unsynchronized),\n `Mirrored` (if the values are kept in sync), or `Tensor` (if running on a\n single replica).\n \"\"\"\n with self.scope():\n return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)\n\n def reduce(self, reduce_op, value):\n \"\"\"Reduce `value` across replicas.\n\n Args:\n reduce_op: A `tf.distribute.ReduceOp` value specifying how values should\n be combined.\n value: A \"per replica\" value to be combined into a single tensor.\n\n Returns:\n A `Tensor`.\n \"\"\"\n _require_cross_replica_or_default_context_extended(self._extended)\n return self._extended._reduce(reduce_op, value) # pylint: disable=protected-access\n\n @doc_controls.do_not_generate_docs # DEPRECATED\n def unwrap(self, value):\n \"\"\"Returns the list of all local per-replica values contained in `value`.\n\n DEPRECATED: Please use `experimental_local_results` instead.\n\n Note: This only returns values on the workers initiated by this client.\n When using a `Strategy` like\n `tf.distribute.experimental.MultiWorkerMirroredStrategy`, each worker\n will be its own client, and this function will only return values\n computed on that worker.\n\n Args:\n value: A value returned by `experimental_run()`,\n `extended.call_for_each_replica()`, or a variable created in `scope`.\n\n Returns:\n A tuple of values contained in `value`. If `value` represents a single\n value, this returns `(value,).`\n \"\"\"\n return self._extended._local_results(value) # pylint: disable=protected-access\n\n def experimental_local_results(self, value):\n \"\"\"Returns the list of all local per-replica values contained in `value`.\n\n Note: This only returns values on the workers initiated by this client.\n When using a `Strategy` like\n `tf.distribute.experimental.MultiWorkerMirroredStrategy`, each worker\n will be its own client, and this function will only return values\n computed on that worker.\n\n Args:\n value: A value returned by `experimental_run()`, `experimental_run_v2()`,\n `extended.call_for_each_replica()`, or a variable created in `scope`.\n\n Returns:\n A tuple of values contained in `value`. If `value` represents a single\n value, this returns `(value,).`\n \"\"\"\n return self._extended._local_results(value) # pylint: disable=protected-access\n\n @doc_controls.do_not_generate_docs # DEPRECATED: TF v1.x only\n def group(self, value, name=None):\n \"\"\"Shortcut for `tf.group(self.experimental_local_results(value))`.\"\"\"\n return self._extended._group(value, name) # pylint: disable=protected-access\n\n @property\n def num_replicas_in_sync(self):\n \"\"\"Returns number of replicas over which gradients are aggregated.\"\"\"\n return self._extended._num_replicas_in_sync # pylint: disable=protected-access\n\n @doc_controls.do_not_generate_docs # DEPRECATED, being replaced by a new API.\n def configure(self,\n session_config=None,\n cluster_spec=None,\n task_type=None,\n task_id=None):\n # pylint: disable=g-doc-return-or-yield,g-doc-args\n \"\"\"DEPRECATED: use `update_config_proto` instead.\n\n Configures the strategy class.\n\n DEPRECATED: This method's functionality has been split into the strategy\n constructor and `update_config_proto`. In the future, we will allow passing\n cluster and config_proto to the constructor to configure the strategy. And\n `update_config_proto` can be used to update the config_proto based on the\n specific strategy.\n \"\"\"\n return self._extended._configure( # pylint: disable=protected-access\n session_config, cluster_spec, task_type, task_id)\n\n def update_config_proto(self, config_proto):\n \"\"\"Returns a copy of `config_proto` modified for use with this strategy.\n\n The updated config has something needed to run a strategy, e.g.\n configuration to run collective ops, or device filters to improve\n distributed training performance.\n\n Args:\n config_proto: a `tf.ConfigProto` object.\n\n Returns:\n The updated copy of the `config_proto`.\n \"\"\"\n return self._extended._update_config_proto(config_proto) # pylint: disable=protected-access\n\n def __deepcopy__(self, memo):\n # First do a regular deepcopy of `self`.\n cls = self.__class__\n result = cls.__new__(cls)\n memo[id(self)] = result\n for k, v in self.__dict__.items():\n setattr(result, k, copy.deepcopy(v, memo))\n # One little fix-up: we want `result._extended` to reference `result`\n # instead of `self`.\n result._extended._container_strategy_weakref = weakref.ref(result) # pylint: disable=protected-access\n return result\n\n def __copy__(self):\n raise RuntimeError(\"Must only deepcopy DistributionStrategy.\")\n\n\n@tf_export(\"distribute.StrategyExtended\")\nclass DistributionStrategyExtended(object):\n \"\"\"Additional APIs for algorithms that need to be distribution-aware.\n\n The intent is that you can write an algorithm in a stylized way and\n it will be usable with a variety of different\n `tf.distribute.Strategy`\n implementations. Each descendant will implement a different strategy\n for distributing the algorithm across multiple devices/machines.\n Furthermore, these changes can be hidden inside the specific layers\n and other library classes that need special treatment to run in a\n distributed setting, so that most users' model definition code can\n run unchanged. The `tf.distribute.Strategy` API works the same way\n with eager and graph execution.\n\n First let's introduce a few high-level concepts:\n\n * _Data parallelism_ is where we run multiple copies of the model\n on different slices of the input data. This is in contrast to\n _model parallelism_ where we divide up a single copy of a model\n across multiple devices.\n Note: we only support data parallelism for now, but\n hope to add support for model parallelism in the future.\n * A _replica_ is one copy of the model, running on one slice of the\n input data.\n * _Synchronous_, or more commonly _sync_, training is where the\n updates from each replica are aggregated together before updating\n the model variables. This is in contrast to _asynchronous_, or\n _async_ training, where each replica updates the model variables\n independently.\n * Furthermore you might run your computation on multiple devices\n on one machine (or \"host\"), or on multiple machines/hosts.\n If you are running on multiple machines, you might have a\n single master host that drives computation across all of them,\n or you might have multiple clients driving the computation\n asynchronously.\n\n To distribute an algorithm, we might use some of these ingredients:\n\n * Parameter servers: These are hosts that hold a single copy of\n parameters/variables. All replicas that want to operate on a variable\n retrieve it at the beginning of a step and send an update to be\n applied at the end of the step. Can support either sync or async\n training.\n * Mirrored variables: These are variables that are copied to multiple\n devices, where we keep the copies in sync by applying the same\n updates to every copy. Normally would only be used with sync training.\n * Reductions and Allreduce: A _reduction_ is some method of\n aggregating multiple values into one value, like \"sum\" or\n \"mean\". If doing sync training, we will perform a reduction on the\n gradients to a parameter from all replicas before applying the\n update. Allreduce is an algorithm for performing a reduction on\n values from multiple devices and making the result available on\n all of those devices.\n * In the future we will have support for TensorFlow's partitioned\n variables, where a single variable is split across multiple\n devices.\n\n We have then a few approaches we want to support:\n\n * Code written (as if) with no knowledge of class `tf.distribute.Strategy`.\n This code should work as before, even if some of the layers, etc.\n used by that code are written to be distribution-aware. This is done\n by having a default `tf.distribute.Strategy` that gives ordinary behavior,\n and by default being in a single replica context.\n * Ordinary model code that you want to run using a specific\n `tf.distribute.Strategy`. This can be as simple as:\n\n ```\n with my_strategy.scope():\n iterator = my_strategy.make_dataset_iterator(dataset)\n session.run(iterator.initialize())\n replica_train_ops = my_strategy.extended.call_for_each_replica(\n replica_fn, args=(iterator.get_next(),))\n train_op = my_strategy.group(replica_train_ops)\n ```\n\n This takes an ordinary `dataset` and `replica_fn` and runs it\n distributed using a particular `tf.distribute.Strategy` in\n `my_strategy`. Any variables created in `replica_fn` are created\n using `my_strategy`'s policy, and library functions called by\n `replica_fn` can use the `get_replica_context()` API to get enhanced\n behavior in this case.\n\n * If you want to write a distributed algorithm, you may use any of\n the `tf.distribute.Strategy` APIs inside a\n `with my_strategy.scope():` block of code.\n\n Lower-level concepts:\n\n * Wrapped values: In order to represent values parallel across devices\n (either replicas or the devices associated with a particular value), we\n wrap them in a \"PerReplica\" or \"Mirrored\" object that contains a map\n from device to values. \"PerReplica\" is used when the value may be\n different across replicas, and \"Mirrored\" when the value are the same.\n * Unwrapping and merging: Consider calling a function `fn` on multiple\n replicas, like `extended.call_for_each_replica(fn, args=[w])` with an\n argument `w` that is a wrapped value. This means `w` will have a map taking\n replica device `d0` to `w0`, replica device `d1` to `w1`,\n etc. `extended.call_for_each_replica()` unwraps `w` before calling `fn`, so\n it calls `fn(w0)` on `d0`, `fn(w1)` on `d1`, etc. It then merges the return\n values from `fn()`, which can possibly result in wrapped values. For\n example, let's say `fn()` returns a tuple with three components: `(x, a,\n v0)` from replica 0, `(x, b, v1)` on replica 1, etc. If the first component\n is the same object `x` from every replica, then the first component of the\n merged result will also be `x`. If the second component is different (`a`,\n `b`, ...) from each replica, then the merged value will have a wrapped map\n from replica device to the different values. If the third component is the\n members of a mirrored variable (`v` maps `d0` to `v0`, `d1` to `v1`, etc.),\n then the merged result will be that mirrored variable (`v`).\n * Replica context vs. Cross-replica context: _replica context_ is when we\n are in some function that is being called once for each replica.\n Otherwise we are in cross-replica context, which is useful for\n calling `tf.distribute.Strategy` methods which operate across the\n replicas (like `reduce_to()`). By default you start in a replica context\n (the default \"single replica context\") and then some methods can\n switch you back and forth, as described below.\n * Worker devices vs. parameter devices: Most replica computations will\n happen on worker devices. Since we don't yet support model\n parallelism, there will be one worker device per replica. When using\n parameter servers (see above), the set of devices holding\n variables may be different, otherwise the parameter devices might\n match the worker devices.\n * Non-slot devices are some subset of the parameter devices where we\n put all the non-slot variables. We need to ensure that all\n non-slot variables are allocated on the same device, or mirrored\n across the same set of devices. If you have some variable you want\n to colocate all the non-slot variables with, you can use\n `colocate_vars_with()` to get the remaining non-slot variables on\n the same device. Otherwise you can use `non_slot_devices()` to\n pick a consistent set of devices to pass to both\n `colocate_vars_with()` and `update_non_slot()`.\n\n When using a `tf.distribute.Strategy`, we have a new type dimension\n called _locality_ that says what values are compatible with which\n APIs:\n\n * T: different value for each replica (e.g. a PerReplica-wrapped value).\n * M: value is \"mirrored\" across replicas, i.e. there are copies with the\n same value on each replica (e.g. a Mirrored-wrapped value).\n * V(`v`): value is \"mirrored\" across all the devices which have a\n copy of variable `v` (also a Mirrored-wrapped value, but over\n parameter devices instead of worker devices).\n * N: value is \"mirrored\" across all the \"non-slot\" devices\n\n Rules for methods with respect to locality and single-replica vs.\n cross-replica context:\n\n * `with d.scope()`: default single-replica context -> cross-replica context\n for `d`\n * `with d.extended.colocate_vars_with(v)`: in replica/cross-replica context,\n variables will be created with locality V(`v`). That is, if we write\n `with d.extended.colocate_vars_with(v1): v2 = tf.get_variable(...)`,\n then `v2` will have locality V(`v1`), i.e. locality V(`v2`) will equal\n V(`v1`).\n * `with d.extended.colocate_vars_with(d.extended.non_slot_devices(...))`: in\n replica/cross-replica context, variables will be created with locality N\n * `v = tf.get_variable(...)`: in replica/cross-replica context, creates\n a variable (which by definition will have locality V(`v`), though\n will match another locality if inside a `colocate_vars_with`\n scope).\n * `d.make_dataset_iterator(dataset)`: in cross-replica\n context, produces an iterator with locality T\n * `d.extended.broadcast_to(t, v)`: in cross-replica context, produces a value\n with locality V(`v`)\n * `d.extended.call_for_each_replica(fn, ...)`: in cross-replica context, runs\n `fn()` in a replica context (and so may call `get_replica_context()` and\n use its API, including `merge_call()` to get back to cross-replica\n context), once for each replica. May use values with locality T or\n M, and any variable.\n * `d.extended.reduce_to(m, t, t)`: in cross-replica context, accepts t with\n locality T and produces a value with locality M.\n * `d.extended.reduce_to(m, t, v)`: in cross-replica context, accepts t with\n locality T and produces a value with locality V(`v`).\n * `d.extended.batch_reduce_to(m, [(t, v)]): see `d.extended.reduce_to()`\n * `d.extended.update(v, fn, ...)`: in cross-replica context, runs `fn()` once\n for each device `v` is copied to, all inputs should have locality\n V(`v`), output will have locality V(`v`) as well.\n * `d.extended.update_non_slot(d.extended.non_slot_devices(), fn)`: in\n cross-replica context, like `d.extended.update()` except with locality N.\n * `d.extended.read_var(v)`: Gets the (read-only) value of the variable `v` (on\n the device determined by the current device scope), aggregating\n across replicas for replica-local variables. Frequently, this will be\n done automatically when using `v` in an expression or fetching it in\n a cross-replica context, but this function can be used to force that\n conversion happens at a particular point in time (for example, to\n add the result of the conversion to a graph collection).\n\n The standard pattern for updating variables is to:\n\n 1. Create an input iterator with `d.make_dataset_iterator()`.\n 2. Define each replica `d.extended.call_for_each_replica()` up to the point of\n getting a list of gradient, variable pairs.\n 3. Call `d.extended.reduce_to(VariableAggregation.SUM, t, v)` or\n `d.extended.batch_reduce_to()` to sum the gradients (with locality T)\n into values with locality V(`v`).\n 4. Call `d.extended.update(v)` for each variable to update its value.\n\n Steps 3 and 4 are done automatically by class `Optimizer` if you call\n its `apply_gradients` method in a replica context. Otherwise you can\n manually call its `_distributed_apply` method in a cross-replica context.\n\n Another thing you might want to do in the middle of your replica function is\n an all-reduce of some intermediate value, using `d.extended.reduce_to()` or\n `d.extended.batch_reduce_to()`. You simply provide the same tensor as the\n input and destination.\n\n Layers should expect to be called in a replica context, and can use\n the `tf.distribute.get_replica_context` function to get a\n `tf.distribute.ReplicaContext` object. The\n `ReplicaContext` object has a `merge_call()` method for entering\n cross-replica context where you can use `reduce_to()` (or\n `batch_reduce_to()`) and then optionally `update()` to update state.\n\n You may use this API whether or not a `tf.distribute.Strategy` is\n being used, since there is a default implementation of\n `ReplicaContext` and `tf.distribute.Strategy`.\n\n NOTE for new `tf.distribute.Strategy` implementations: Please put all logic\n in a subclass of `tf.distribute.StrategyExtended`. The only code needed for\n the `tf.distribute.Strategy` subclass is for instantiating your subclass of\n `tf.distribute.StrategyExtended` in the `__init__` method.\n \"\"\"\n\n def __init__(self, container_strategy):\n self._container_strategy_weakref = weakref.ref(container_strategy)\n self._default_device = None\n # This property is used to determine if we should set drop_remainder=True\n # when creating Datasets from numpy array inputs.\n self._require_static_shapes = False\n\n def _container_strategy(self):\n \"\"\"Get the containing `DistributionStrategy`.\n\n This should not generally be needed except when creating a new\n `ReplicaContext` and to validate that the caller is in the correct\n `scope()`.\n\n Returns:\n The `DistributionStrategy` such that `strategy.extended` is `self`.\n \"\"\"\n container_strategy = self._container_strategy_weakref()\n assert container_strategy is not None\n return container_strategy\n\n def _scope(self, strategy):\n \"\"\"Implementation of DistributionStrategy.scope().\"\"\"\n def creator_with_resource_vars(*args, **kwargs):\n _require_strategy_scope_extended(self)\n kwargs[\"use_resource\"] = True\n kwargs[\"distribute_strategy\"] = strategy\n return self._create_variable(*args, **kwargs)\n\n def distributed_getter(getter, *args, **kwargs):\n if not self._allow_variable_partition():\n if kwargs.pop(\"partitioner\", None) is not None:\n tf_logging.log_first_n(\n tf_logging.WARN, \"Partitioned variables are disabled when using \"\n \"current tf.distribute.Strategy.\", 1)\n return getter(*args, **kwargs)\n\n return _CurrentDistributionContext(\n strategy,\n variable_scope.variable_creator_scope(creator_with_resource_vars),\n variable_scope.variable_scope(\n variable_scope.get_variable_scope(),\n custom_getter=distributed_getter), self._default_device)\n\n def _allow_variable_partition(self):\n return False\n\n def _create_variable(self, next_creator, *args, **kwargs):\n # Note: should support \"colocate_with\" argument.\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def variable_created_in_scope(self, v):\n \"\"\"Tests whether `v` was created while this strategy scope was active.\n\n Variables created inside the strategy scope are \"owned\" by it:\n\n >>> with strategy.scope():\n ... v = tf.Variable(1.)\n >>> strategy.variable_created_in_scope(v)\n True\n\n Variables created outside the strategy are not owned by it:\n\n >>> v = tf.Variable(1.)\n >>> strategy.variable_created_in_scope(v)\n False\n\n Args:\n v: A `tf.Variable` instance.\n\n Returns:\n True if `v` was created inside the scope, False if not.\n \"\"\"\n return v._distribute_strategy == self._container_strategy_weakref() # pylint: disable=protected-access\n\n def read_var(self, v):\n \"\"\"Reads the value of a variable.\n\n Returns the aggregate value of a replica-local variable, or the\n (read-only) value of any other variable.\n\n Args:\n v: A variable allocated within the scope of this `tf.distribute.Strategy`.\n\n Returns:\n A tensor representing the value of `v`, aggregated across replicas if\n necessary.\n \"\"\"\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def colocate_vars_with(self, colocate_with_variable):\n \"\"\"Scope that controls which devices variables will be created on.\n\n No operations should be added to the graph inside this scope, it\n should only be used when creating variables (some implementations\n work by changing variable creation, others work by using a\n tf.colocate_with() scope).\n\n This may only be used inside `self.scope()`.\n\n Example usage:\n\n ```\n with strategy.scope():\n var1 = tf.get_variable(...)\n with strategy.extended.colocate_vars_with(var1):\n # var2 and var3 will be created on the same device(s) as var1\n var2 = tf.get_variable(...)\n var3 = tf.get_variable(...)\n\n def fn(v1, v2, v3):\n # operates on v1 from var1, v2 from var2, and v3 from var3\n\n # `fn` runs on every device `var1` is on, `var2` and `var3` will be there\n # too.\n strategy.extended.update(var1, fn, args=(var2, var3))\n ```\n\n Args:\n colocate_with_variable: A variable created in this strategy's `scope()`.\n Variables created while in the returned context manager will be on the\n same set of devices as `colocate_with_variable`.\n\n Returns:\n A context manager.\n \"\"\"\n def create_colocated_variable(next_creator, *args, **kwargs):\n _require_strategy_scope_extended(self)\n kwargs[\"use_resource\"] = True\n kwargs[\"colocate_with\"] = colocate_with_variable\n return next_creator(*args, **kwargs)\n\n _require_strategy_scope_extended(self)\n self._validate_colocate_with_variable(colocate_with_variable)\n return variable_scope.variable_creator_scope(create_colocated_variable)\n\n def _validate_colocate_with_variable(self, colocate_with_variable):\n \"\"\"Validate `colocate_with_variable` argument to `colocate_vars_with`.\"\"\"\n pass\n\n def _make_dataset_iterator(self, dataset):\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def _make_input_fn_iterator(self, input_fn, replication_mode):\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def experimental_make_numpy_dataset(self, numpy_input, session=None):\n \"\"\"Makes a dataset for input provided via a numpy array.\n\n This avoids adding `numpy_input` as a large constant in the graph,\n and copies the data to the machine or machines that will be processing\n the input.\n\n Args:\n numpy_input: A nest of NumPy input arrays that will be distributed evenly\n across all replicas. Note that lists of Numpy arrays are stacked,\n as that is normal `tf.data.Dataset` behavior.\n session: (TensorFlow v1.x graph execution only) A session used for\n initialization.\n\n Returns:\n A `tf.data.Dataset` representing `numpy_input`.\n \"\"\"\n _require_cross_replica_or_default_context_extended(self)\n return self._experimental_make_numpy_dataset(numpy_input, session=session)\n\n def _experimental_make_numpy_dataset(self, numpy_input, session):\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def broadcast_to(self, tensor, destinations):\n \"\"\"Mirror a tensor on one device to all worker devices.\n\n Args:\n tensor: A Tensor value to broadcast.\n destinations: A mirrored variable or device string specifying the\n destination devices to copy `tensor` to.\n\n Returns:\n A value mirrored to `destinations` devices.\n \"\"\"\n assert destinations is not None # from old strategy.broadcast()\n # TODO(josh11b): More docstring\n _require_cross_replica_or_default_context_extended(self)\n assert not isinstance(destinations, (list, tuple))\n return self._broadcast_to(tensor, destinations)\n\n def _broadcast_to(self, tensor, destinations):\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def experimental_run_steps_on_iterator(self, fn, iterator, iterations=1,\n initial_loop_values=None):\n \"\"\"Run `fn` with input from `iterator` for `iterations` times.\n\n This method can be used to run a step function for training a number of\n times using input from a dataset.\n\n Args:\n fn: function to run using this distribution strategy. The function must\n have the following signature: `def fn(context, inputs)`.\n `context` is an instance of `MultiStepContext` that will be passed when\n `fn` is run. `context` can be used to specify the outputs to be returned\n from `fn` by calling `context.set_last_step_output`. It can also be used\n to capture non tensor outputs by `context.set_non_tensor_output`.\n See `MultiStepContext` documentation for more information.\n `inputs` will have same type/structure as `iterator.get_next()`.\n Typically, `fn` will use `call_for_each_replica` method of the strategy\n to distribute the computation over multiple replicas.\n iterator: Iterator of a dataset that represents the input for `fn`. The\n caller is responsible for initializing the iterator as needed.\n iterations: (Optional) Number of iterations that `fn` should be run.\n Defaults to 1.\n initial_loop_values: (Optional) Initial values to be passed into the\n loop that runs `fn`. Defaults to `None`. # TODO(priyag): Remove\n initial_loop_values argument when we have a mechanism to infer the\n outputs of `fn`.\n\n Returns:\n Returns the `MultiStepContext` object which has the following properties,\n among other things:\n - run_op: An op that runs `fn` `iterations` times.\n - last_step_outputs: A dictionary containing tensors set using\n `context.set_last_step_output`. Evaluating this returns the value of\n the tensors after the last iteration.\n - non_tensor_outputs: A dictionatry containing anything that was set by\n `fn` by calling `context.set_non_tensor_output`.\n \"\"\"\n _require_cross_replica_or_default_context_extended(self)\n with self._container_strategy().scope():\n return self._experimental_run_steps_on_iterator(\n fn, iterator, iterations, initial_loop_values)\n\n def _experimental_run_steps_on_iterator(self, fn, iterator, iterations,\n initial_loop_values):\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def call_for_each_replica(self, fn, args=(), kwargs=None):\n \"\"\"Run `fn` once per replica.\n\n `fn` may call `tf.get_replica_context()` to access methods such as\n `replica_id_in_sync_group` and `merge_call()`.\n\n `merge_call()` is used to communicate between the replicas and\n re-enter the cross-replica context. All replicas pause their execution\n having encountered a `merge_call()` call. After that the\n `merge_fn`-function is executed. Its results are then unwrapped and\n given back to each replica call. After that execution resumes until\n `fn` is complete or encounters another `merge_call()`. Example:\n\n ```python\n # Called once in \"cross-replica\" context.\n def merge_fn(distribution, three_plus_replica_id):\n # sum the values across replicas\n return sum(distribution.experimental_local_results(three_plus_replica_id))\n\n # Called once per replica in `distribution`, in a \"replica\" context.\n def fn(three):\n replica_ctx = tf.get_replica_context()\n v = three + replica_ctx.replica_id_in_sync_group\n # Computes the sum of the `v` values across all replicas.\n s = replica_ctx.merge_call(merge_fn, args=(v,))\n return s + v\n\n with distribution.scope():\n # in \"cross-replica\" context\n ...\n merged_results = distribution.call_for_each_replica(fn, args=[3])\n # merged_results has the values from every replica execution of `fn`.\n # This statement prints a list:\n print(distribution.experimental_local_results(merged_results))\n ```\n\n Args:\n fn: function to run (will be run once per replica).\n args: Tuple or list with positional arguments for `fn`.\n kwargs: Dict with keyword arguments for `fn`.\n\n Returns:\n Merged return value of `fn` across all replicas.\n \"\"\"\n _require_cross_replica_or_default_context_extended(self)\n if kwargs is None:\n kwargs = {}\n with self._container_strategy().scope():\n return self._call_for_each_replica(fn, args, kwargs)\n\n def _call_for_each_replica(self, fn, args, kwargs):\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def _reduce(self, reduce_op, value):\n # Default implementation until we have an implementation for each strategy.\n return self._local_results(\n self._reduce_to(reduce_op, value,\n device_util.current() or \"/device:CPU:0\"))[0]\n\n def reduce_to(self, reduce_op, value, destinations):\n \"\"\"Combine (via e.g. sum or mean) values across replicas.\n\n Args:\n reduce_op: Reduction type, an instance of `tf.distribute.ReduceOp` enum.\n value: A per-replica value with one value per replica.\n destinations: A mirrored variable, a per-replica tensor, or a device\n string. The return value will be copied to all destination devices (or\n all the devices where the `destinations` value resides). To perform an\n all-reduction, pass `value` to `destinations`.\n\n Returns:\n A value mirrored to `destinations`.\n \"\"\"\n # TODO(josh11b): More docstring\n _require_cross_replica_or_default_context_extended(self)\n assert not isinstance(destinations, (list, tuple))\n assert not isinstance(reduce_op, variable_scope.VariableAggregation)\n assert (reduce_op == reduce_util.ReduceOp.SUM or\n reduce_op == reduce_util.ReduceOp.MEAN)\n return self._reduce_to(reduce_op, value, destinations)\n\n def _reduce_to(self, reduce_op, value, destinations):\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def batch_reduce_to(self, reduce_op, value_destination_pairs):\n \"\"\"Combine multiple `reduce_to` calls into one for faster execution.\n\n Args:\n reduce_op: Reduction type, an instance of `tf.distribute.ReduceOp` enum.\n value_destination_pairs: A sequence of (value, destinations)\n pairs. See `reduce_to()` for a description.\n\n Returns:\n A list of mirrored values, one per pair in `value_destination_pairs`.\n \"\"\"\n # TODO(josh11b): More docstring\n _require_cross_replica_or_default_context_extended(self)\n assert not isinstance(reduce_op, variable_scope.VariableAggregation)\n return self._batch_reduce_to(reduce_op, value_destination_pairs)\n\n def _batch_reduce_to(self, reduce_op, value_destination_pairs):\n return [\n self.reduce_to(reduce_op, t, destinations=v)\n for t, v in value_destination_pairs\n ]\n\n def update(self, var, fn, args=(), kwargs=None, group=True):\n \"\"\"Run `fn` to update `var` using inputs mirrored to the same devices.\n\n If `var` is mirrored across multiple devices, then this implements\n logic like:\n\n ```\n results = {}\n for device, v in var:\n with tf.device(device):\n # args and kwargs will be unwrapped if they are mirrored.\n results[device] = fn(v, *args, **kwargs)\n return merged(results)\n ```\n\n Otherwise this returns `fn(var, *args, **kwargs)` colocated with `var`.\n\n Neither `args` nor `kwargs` may contain per-replica values.\n If they contain mirrored values, they will be unwrapped before\n calling `fn`.\n\n Args:\n var: Variable, possibly mirrored to multiple devices, to operate on.\n fn: Function to call. Should take the variable as the first argument.\n args: Tuple or list. Additional positional arguments to pass to `fn()`.\n kwargs: Dict with keyword arguments to pass to `fn()`.\n group: Boolean. Defaults to True. If False, the return value will be\n unwrapped.\n\n Returns:\n By default, the merged return value of `fn` across all replicas. The\n merged result has dependencies to make sure that if it is evaluated at\n all, the side effects (updates) will happen on every replica. If instead\n \"group=False\" is specified, this function will return a nest of lists\n where each list has an element per replica, and the caller is responsible\n for ensuring all elements are executed.\n \"\"\"\n _require_cross_replica_or_default_context_extended(self)\n if kwargs is None:\n kwargs = {}\n with self._container_strategy().scope():\n return self._update(var, fn, args, kwargs, group)\n\n def _update(self, var, fn, args, kwargs, group):\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def update_non_slot(\n self, colocate_with, fn, args=(), kwargs=None, group=True):\n \"\"\"Runs `fn(*args, **kwargs)` on `colocate_with` devices.\n\n Args:\n colocate_with: The return value of `non_slot_devices()`.\n fn: Function to execute.\n args: Tuple or list. Positional arguments to pass to `fn()`.\n kwargs: Dict with keyword arguments to pass to `fn()`.\n group: Boolean. Defaults to True. If False, the return value will be\n unwrapped.\n\n Returns:\n Return value of `fn`, possibly merged across devices.\n \"\"\"\n _require_cross_replica_or_default_context_extended(self)\n if kwargs is None:\n kwargs = {}\n with self._container_strategy().scope():\n return self._update_non_slot(colocate_with, fn, args, kwargs, group)\n\n def _update_non_slot(self, colocate_with, fn, args, kwargs, group):\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def _local_results(self, distributed_value):\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def value_container(self, value):\n \"\"\"Returns the container that this per-replica `value` belongs to.\n\n Args:\n value: A value returned by `call_for_each_replica()` or a variable\n created in `scope()`.\n\n Returns:\n A container that `value` belongs to.\n If value does not belong to any container (including the case of\n container having been destroyed), returns the value itself.\n `value in experimental_local_results(value_container(value))` will\n always be true.\n \"\"\"\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def _group(self, value, name=None):\n \"\"\"Implementation of `group`.\"\"\"\n value = nest.flatten(self._local_results(value))\n\n if len(value) != 1 or name is not None:\n return control_flow_ops.group(value, name=name)\n # Special handling for the common case of one op.\n v, = value\n if hasattr(v, \"op\"):\n v = v.op\n return v\n\n @property\n def experimental_require_static_shapes(self):\n return self._require_static_shapes\n\n @property\n def _num_replicas_in_sync(self):\n \"\"\"Returns number of replicas over which gradients are aggregated.\"\"\"\n raise NotImplementedError(\"must be implemented in descendants\")\n\n @property\n def worker_devices(self):\n \"\"\"Returns the tuple of all devices used to for compute replica execution.\n \"\"\"\n # TODO(josh11b): More docstring\n raise NotImplementedError(\"must be implemented in descendants\")\n\n @property\n def parameter_devices(self):\n \"\"\"Returns the tuple of all devices used to place variables.\"\"\"\n # TODO(josh11b): More docstring\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def non_slot_devices(self, var_list):\n \"\"\"Device(s) for non-slot variables.\n\n Create variables on these devices in a\n `with colocate_vars_with(non_slot_devices(...)):` block.\n Update those using `update_non_slot()`.\n\n Args:\n var_list: The list of variables being optimized, needed with the\n default `tf.distribute.Strategy`.\n \"\"\"\n raise NotImplementedError(\"must be implemented in descendants\")\n\n @property\n def experimental_between_graph(self):\n \"\"\"Whether the strategy uses between-graph replication or not.\n\n This is expected to return a constant value that will not be changed\n throughout its life cycle.\n \"\"\"\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def _configure(self,\n session_config=None,\n cluster_spec=None,\n task_type=None,\n task_id=None):\n \"\"\"Configures the strategy class.\"\"\"\n del session_config, cluster_spec, task_type, task_id\n\n def _update_config_proto(self, config_proto):\n return copy.deepcopy(config_proto)\n\n @property\n def experimental_should_init(self):\n \"\"\"Whether initialization is needed.\"\"\"\n raise NotImplementedError(\"must be implemented in descendants\")\n\n @property\n def should_checkpoint(self):\n \"\"\"Whether checkpointing is needed.\"\"\"\n raise NotImplementedError(\"must be implemented in descendants\")\n\n @property\n def should_save_summary(self):\n \"\"\"Whether saving summaries is needed.\"\"\"\n raise NotImplementedError(\"must be implemented in descendants\")\n\n\n# A note about the difference between the context managers\n# `ReplicaContext` (defined here) and `_CurrentDistributionContext`\n# (defined above) used by `DistributionStrategy.scope()`:\n#\n# * a ReplicaContext is only present during a `call_for_each_replica()`\n# call (except during a `merge_run` call) and in such a scope it\n# will be returned by calls to `get_replica_context()`. Implementers of new\n# DistributionStrategy descendants will frequently also need to\n# define a descendant of ReplicaContext, and are responsible for\n# entering and exiting this context.\n#\n# * DistributionStrategy.scope() sets up a variable_creator scope that\n# changes variable creation calls (e.g. to make mirrored\n# variables). This is intended as an outer scope that users enter once\n# around their model creation and graph definition. There is no\n# anticipated need to define descendants of _CurrentDistributionContext.\n# It sets the current DistributionStrategy for purposes of\n# `get_strategy()` and `has_strategy()`\n# and switches the thread mode to a \"cross-replica context\".\n@tf_export(\"distribute.ReplicaContext\")\nclass ReplicaContext(object):\n \"\"\"`tf.distribute.Strategy` API when in a replica context.\n\n To be used inside your replicated step function, such as in a\n `tf.distribute.StrategyExtended.call_for_each_replica` call.\n \"\"\"\n\n def __init__(self, strategy, replica_id_in_sync_group):\n self._strategy = strategy\n self._thread_context = distribution_strategy_context._InReplicaThreadMode( # pylint: disable=protected-access\n self)\n self._replica_id_in_sync_group = replica_id_in_sync_group\n self._summary_recording_distribution_strategy = None\n\n def __enter__(self):\n _push_per_thread_mode(self._thread_context)\n ctx = eager_context.context()\n\n def replica_id_is_zero():\n return math_ops.equal(self._replica_id_in_sync_group,\n constant_op.constant(0))\n\n self._summary_recording_distribution_strategy = (\n ctx.summary_recording_distribution_strategy)\n ctx.summary_recording_distribution_strategy = replica_id_is_zero\n\n def __exit__(self, exception_type, exception_value, traceback):\n ctx = eager_context.context()\n ctx.summary_recording_distribution_strategy = (\n self._summary_recording_distribution_strategy)\n _pop_per_thread_mode()\n\n def merge_call(self, merge_fn, args=(), kwargs=None):\n \"\"\"Merge args across replicas and run `merge_fn` in a cross-replica context.\n\n This allows communication and coordination when there are multiple calls\n to a model function triggered by a call to\n `strategy.extended.call_for_each_replica(model_fn, ...)`.\n\n See `tf.distribute.StrategyExtended.call_for_each_replica` for an\n explanation.\n\n If not inside a distributed scope, this is equivalent to:\n\n ```\n strategy = tf.distribute.get_strategy()\n with cross-replica-context(strategy):\n return merge_fn(strategy, *args, **kwargs)\n ```\n\n Args:\n merge_fn: function that joins arguments from threads that are given as\n PerReplica. It accepts `tf.distribute.Strategy` object as\n the first argument.\n args: List or tuple with positional per-thread arguments for `merge_fn`.\n kwargs: Dict with keyword per-thread arguments for `merge_fn`.\n\n Returns:\n The return value of `merge_fn`, except for `PerReplica` values which are\n unpacked.\n \"\"\"\n require_replica_context(self)\n if kwargs is None:\n kwargs = {}\n return self._merge_call(merge_fn, args, kwargs)\n\n def _merge_call(self, merge_fn, args, kwargs):\n \"\"\"Default implementation for single replica.\"\"\"\n _push_per_thread_mode( # thread-local, so not needed with multiple threads\n distribution_strategy_context._CrossReplicaThreadMode(self._strategy)) # pylint: disable=protected-access\n try:\n return merge_fn(self._strategy, *args, **kwargs)\n finally:\n _pop_per_thread_mode()\n\n @property\n def num_replicas_in_sync(self):\n \"\"\"Returns number of replicas over which gradients are aggregated.\"\"\"\n return self._strategy.num_replicas_in_sync\n\n @property\n def replica_id_in_sync_group(self):\n \"\"\"Which replica is being defined, from 0 to `num_replicas_in_sync - 1`.\"\"\"\n require_replica_context(self)\n return self._replica_id_in_sync_group\n\n @property\n def strategy(self):\n \"\"\"The current `tf.distribute.Strategy` object.\"\"\"\n return self._strategy\n\n @property\n def devices(self):\n \"\"\"The devices this replica is to be executed on, as a tuple of strings.\"\"\"\n require_replica_context(self)\n return (device_util.current(),)\n\n def all_reduce(self, reduce_op, value):\n \"\"\"All-reduces the given `Tensor` nest across replicas.\n\n If `all_reduce` is called in any replica, it must be called in all replicas.\n The nested structure and `Tensor` shapes must be identical in all replicas.\n\n IMPORTANT: The ordering of communications must be identical in all replicas.\n\n Example with two replicas:\n Replica 0 `value`: {'a': 1, 'b': [40, 1]}\n Replica 1 `value`: {'a': 3, 'b': [ 2, 98]}\n\n If `reduce_op` == `SUM`:\n Result (on all replicas): {'a': 4, 'b': [42, 99]}\n\n If `reduce_op` == `MEAN`:\n Result (on all replicas): {'a': 2, 'b': [21, 49.5]}\n\n Args:\n reduce_op: Reduction type, an instance of `tf.distribute.ReduceOp` enum.\n value: The nested structure of `Tensor`s to all-reduced.\n The structure must be compatible with `tf.nest`.\n\n Returns:\n A `Tensor` nest with the reduced `value`s from each replica.\n \"\"\"\n def batch_all_reduce(strategy, *value_flat):\n return strategy.extended.batch_reduce_to(\n reduce_op, [(v, _batch_reduce_destination(v)) for v in value_flat])\n\n if reduce_op in [reduce_util.ReduceOp.SUM, reduce_util.ReduceOp.MEAN]:\n # TODO(cjfj): Work out why `batch_reduce` doesn't return the correct grad.\n @custom_gradient.custom_gradient\n def grad_wrapper(*xs):\n ys = self.merge_call(batch_all_reduce, args=xs)\n # The gradient of an all-sum is itself an all-sum (all-mean, likewise).\n return ys, lambda *dy_s: self.all_reduce(reduce_op, dy_s)\n return nest.pack_sequence_as(value, grad_wrapper(*nest.flatten(value)))\n else:\n # TODO(cjfj): Implement gradients for other reductions.\n reduced = nest.pack_sequence_as(\n value, self.merge_call(batch_all_reduce, args=nest.flatten(value)))\n return nest.map_structure(array_ops.prevent_gradient, reduced)\n\n # TODO(josh11b): Implement `start_all_reduce(method, t)` for efficient\n # all-reduce. It would return a function returning the result of reducing `t`\n # across all replicas. The caller would wait to call this function until they\n # needed the reduce result, allowing an efficient implementation:\n # * With eager execution, the reduction could be performed asynchronously\n # in the background, not blocking until the result was needed.\n # * When constructing a graph, it could batch up all reduction requests up\n # to that point that the first result is needed. Most likely this can be\n # implemented in terms of `merge_call()` and `batch_reduce_to()`.\n\n\ndef _batch_reduce_destination(x):\n \"\"\"Returns the destinations for batch all-reduce.\"\"\"\n if isinstance(x, ops.Tensor): # One device strategies.\n return x.device\n else:\n return x\n\n\n# ------------------------------------------------------------------------------\n\n\nclass _DefaultDistributionStrategy(DistributionStrategy):\n \"\"\"Default `tf.distribute.Strategy` if none is explicitly selected.\"\"\"\n\n def __init__(self):\n super(_DefaultDistributionStrategy, self).__init__(\n _DefaultDistributionExtended(self))\n\n\nclass _DefaultDistributionExtended(DistributionStrategyExtended):\n \"\"\"Implementation of _DefaultDistributionStrategy.\"\"\"\n\n def _scope(self, strategy):\n \"\"\"Context manager setting a variable creator and `self` as current.\"\"\"\n if distribution_strategy_context.has_strategy():\n raise RuntimeError(\"Must not nest tf.distribute.Strategy scopes.\")\n\n def creator(next_creator, *args, **kwargs):\n _require_strategy_scope_strategy(strategy)\n return next_creator(*args, **kwargs)\n\n return _CurrentDistributionContext(\n strategy, variable_scope.variable_creator_scope(creator))\n\n def colocate_vars_with(self, colocate_with_variable):\n \"\"\"Does not require `self.scope`.\"\"\"\n _require_strategy_scope_extended(self)\n return ops.colocate_with(colocate_with_variable)\n\n def variable_created_in_scope(self, v):\n return v._distribute_strategy is None # pylint: disable=protected-access\n\n def _make_dataset_iterator(self, dataset):\n return _DefaultDistributionExtended.DefaultInputIterator(dataset)\n\n def _make_input_fn_iterator(self,\n input_fn,\n replication_mode=InputReplicationMode.PER_WORKER):\n dataset = input_fn(InputContext())\n return _DefaultDistributionExtended.DefaultInputIterator(dataset)\n\n def _experimental_make_numpy_dataset(self, numpy_input, session):\n numpy_flat = nest.flatten(numpy_input)\n vars_flat = tuple(\n variable_scope.variable(array_ops.zeros(i.shape, i.dtype),\n trainable=False, use_resource=True)\n for i in numpy_flat\n )\n for v, i in zip(vars_flat, numpy_flat):\n numpy_dataset.init_var_from_numpy(v, i, session)\n vars_nested = nest.pack_sequence_as(numpy_input, vars_flat)\n return dataset_ops.Dataset.from_tensor_slices(vars_nested)\n\n def _broadcast_to(self, tensor, destinations):\n if destinations is None:\n return tensor\n else:\n raise NotImplementedError(\"TODO\")\n\n def _call_for_each_replica(self, fn, args, kwargs):\n with ReplicaContext(\n self._container_strategy(),\n replica_id_in_sync_group=constant_op.constant(0, dtypes.int32)):\n return fn(*args, **kwargs)\n\n def _reduce_to(self, reduce_op, value, destinations):\n # TODO(josh11b): Use destinations?\n del reduce_op, destinations\n return value\n\n def _update(self, var, fn, args, kwargs, group):\n # The implementations of _update() and _update_non_slot() are identical\n # except _update() passes `var` as the first argument to `fn()`.\n return self._update_non_slot(var, fn, (var,) + tuple(args), kwargs, group)\n\n def _update_non_slot(self, colocate_with, fn, args, kwargs, should_group):\n # TODO(josh11b): Figure out what we should be passing to UpdateContext()\n # once that value is used for something.\n with ops.colocate_with(colocate_with), UpdateContext(colocate_with):\n result = fn(*args, **kwargs)\n if should_group:\n return result\n else:\n return nest.map_structure(self._local_results, result)\n\n def read_var(self, replica_local_var):\n return array_ops.identity(replica_local_var)\n\n def _local_results(self, distributed_value):\n return (distributed_value,)\n\n def value_container(self, value):\n return value\n\n @property\n def _num_replicas_in_sync(self):\n return 1\n\n @property\n def worker_devices(self):\n raise RuntimeError(\"worker_devices() method unsupported by default \"\n \"tf.distribute.Strategy.\")\n\n @property\n def parameter_devices(self):\n raise RuntimeError(\"parameter_devices() method unsupported by default \"\n \"tf.distribute.Strategy.\")\n\n def non_slot_devices(self, var_list):\n return min(var_list, key=lambda x: x.name)\n\n # TODO(priyag): This should inherit from `InputIterator`, once dependency\n # issues have been resolved.\n class DefaultInputIterator(object):\n \"\"\"Default implementation of `InputIterator` for default strategy.\"\"\"\n\n def __init__(self, dataset):\n self._dataset = dataset\n if eager_context.executing_eagerly():\n self._iterator = dataset.make_one_shot_iterator()\n else:\n self._iterator = dataset.make_initializable_iterator()\n\n def get_next(self):\n return self._iterator.get_next()\n\n def initialize(self):\n if eager_context.executing_eagerly():\n self._iterator = self._dataset.make_one_shot_iterator()\n return []\n else:\n return [self._iterator.initializer]\n\n # TODO(priyag): Delete this once all strategies use global batch size.\n @property\n def _global_batch_size(self):\n \"\"\"Global and per-replica batching are equivalent for this strategy.\"\"\"\n return True\n\n\n# ------------------------------------------------------------------------------\n# We haven't yet implemented deserialization for DistributedVariables.\n# So here we catch any attempts to deserialize variables\n# when using distribution strategies.\n# pylint: disable=protected-access\n_original_from_proto = resource_variable_ops._from_proto_fn\n\n\ndef _from_proto_fn(v, import_scope=None):\n if distribution_strategy_context.has_strategy():\n raise NotImplementedError(\n \"Deserialization of variables is not yet supported when using a \"\n \"tf.distribute.Strategy.\")\n else:\n return _original_from_proto(v, import_scope=import_scope)\n\nresource_variable_ops._from_proto_fn = _from_proto_fn\n# pylint: enable=protected-access\n\n\n#-------------------------------------------------------------------------------\n# Shorthand for some methods from distribution_strategy_context.\n_push_per_thread_mode = distribution_strategy_context._push_per_thread_mode # pylint: disable=protected-access\n_get_per_thread_mode = distribution_strategy_context._get_per_thread_mode # pylint: disable=protected-access\n_pop_per_thread_mode = distribution_strategy_context._pop_per_thread_mode # pylint: disable=protected-access\n_get_default_replica_mode = (\n distribution_strategy_context._get_default_replica_mode) # pylint: disable=protected-access\n"
] | [
[
"tensorflow.python.framework.ops.colocate_with",
"tensorflow.python.distribute.device_util.current",
"tensorflow.python.util.nest.flatten",
"tensorflow.python.framework.constant_op.constant",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.platform.tf_logging.log_first_n",
"tensorflow.python.ops.control_flow_ops.group",
"tensorflow.python.distribute.distribution_strategy_context.has_strategy",
"tensorflow.python.framework.ops.device",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices",
"tensorflow.python.ops.array_ops.identity",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.distribute.distribution_strategy_context._InReplicaThreadMode",
"tensorflow.python.eager.context.context",
"tensorflow.python.distribute.numpy_dataset.init_var_from_numpy",
"tensorflow.python.ops.variable_scope.get_variable_scope",
"tensorflow.python.distribute.distribution_strategy_context._CrossReplicaThreadMode",
"tensorflow.python.ops.variable_scope.variable_creator_scope",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.util.nest.map_structure",
"tensorflow.python.util.nest.pack_sequence_as"
]
] |
Naqu6/jax | [
"6411f8a03388ce63eb365188f2e2880815745125"
] | [
"tests/lax_test.py"
] | [
"# Copyright 2018 Google LLC\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# https://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 collections\nfrom functools import partial\nimport itertools\nimport operator\nimport unittest\nfrom unittest import SkipTest\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n\nimport numpy as np\n\nimport jax\nimport jax.numpy as jnp\nfrom jax import core\nfrom jax._src import dtypes\nfrom jax import lax\nfrom jax._src import test_util as jtu\nfrom jax import tree_util\nfrom jax._src import lax_reference\nfrom jax.test_util import check_grads\nimport jax.util\nfrom jax._src.util import prod\n\nfrom jax._src.lax.lax import _device_put_raw\n\n\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n\n\n### lax tests\n\n# For standard unops and binops, we can generate a large number of tests on\n# arguments of appropriate shapes and dtypes using the following table.\n\nfloat_dtypes = jtu.dtypes.all_floating\ncomplex_elem_dtypes = jtu.dtypes.floating\ncomplex_dtypes = jtu.dtypes.complex\ninexact_dtypes = jtu.dtypes.all_inexact\nint_dtypes = jtu.dtypes.all_integer\nuint_dtypes = jtu.dtypes.all_unsigned\nbool_dtypes = jtu.dtypes.boolean\ndefault_dtypes = float_dtypes + int_dtypes\nall_dtypes = float_dtypes + complex_dtypes + int_dtypes + uint_dtypes + bool_dtypes\npython_scalar_types = [bool, int, float, complex]\n\ncompatible_shapes = [[(3,)], [(3, 4), (3, 1), (1, 4)], [(2, 3, 4), (2, 1, 4)]]\n\n# We check cases where the preferred type is at least as wide as the input\n# type and where both are either both floating-point or both integral,\n# which are the only supported configurations.\npreferred_type_combinations = [\n (np.float16, np.float16), (np.float16, np.float32), (np.float16, np.float64),\n (dtypes.bfloat16, dtypes.bfloat16), (dtypes.bfloat16, np.float32),\n (dtypes.bfloat16, np.float64), (np.float32, np.float32), (np.float32, np.float64),\n (np.float64, np.float64), (np.int8, np.int8), (np.int8, np.int16), (np.int8, np.int32),\n (np.int8, np.int64), (np.int16, np.int16), (np.int16, np.int32), (np.int16, np.int64),\n (np.int32, np.int32), (np.int32, np.int64), (np.int64, np.int64),\n (np.complex64, np.complex64), (np.complex64, np.complex128), (np.complex128, np.complex128)]\n\n\nOpRecord = collections.namedtuple(\n \"OpRecord\", [\"op\", \"nargs\", \"dtypes\", \"rng_factory\", \"tol\"])\n\ndef op_record(op, nargs, dtypes, rng_factory, tol=None):\n return OpRecord(op, nargs, dtypes, rng_factory, tol)\n\nLAX_OPS = [\n op_record(\"neg\", 1, default_dtypes + complex_dtypes, jtu.rand_small),\n op_record(\"sign\", 1, default_dtypes + uint_dtypes, jtu.rand_small),\n op_record(\"floor\", 1, float_dtypes, jtu.rand_small),\n op_record(\"ceil\", 1, float_dtypes, jtu.rand_small),\n op_record(\"round\", 1, float_dtypes, jtu.rand_default),\n op_record(\"nextafter\", 2, [f for f in float_dtypes if f != dtypes.bfloat16],\n jtu.rand_default, tol=0),\n\n op_record(\"is_finite\", 1, float_dtypes, jtu.rand_small),\n\n op_record(\"exp\", 1, float_dtypes + complex_dtypes, jtu.rand_small),\n # TODO(b/142975473): on CPU, expm1 for float64 is only accurate to ~float32\n # precision.\n op_record(\"expm1\", 1, float_dtypes + complex_dtypes, jtu.rand_small,\n {np.float64: 1e-8}),\n op_record(\"log\", 1, float_dtypes + complex_dtypes, jtu.rand_positive),\n op_record(\"log1p\", 1, float_dtypes + complex_dtypes, jtu.rand_positive),\n # TODO(b/142975473): on CPU, tanh for complex128 is only accurate to\n # ~float32 precision.\n # TODO(b/143135720): on GPU, tanh has only ~float32 precision.\n op_record(\"tanh\", 1, float_dtypes + complex_dtypes, jtu.rand_small,\n {np.float64: 1e-9, np.complex128: 1e-7}),\n op_record(\"sin\", 1, float_dtypes + complex_dtypes, jtu.rand_default),\n op_record(\"cos\", 1, float_dtypes + complex_dtypes, jtu.rand_default),\n op_record(\"atan2\", 2, float_dtypes, jtu.rand_default),\n\n op_record(\"sqrt\", 1, float_dtypes, jtu.rand_positive),\n op_record(\"sqrt\", 1, complex_dtypes, jtu.rand_default),\n op_record(\"rsqrt\", 1, float_dtypes, jtu.rand_positive),\n op_record(\"rsqrt\", 1, complex_dtypes, jtu.rand_default),\n op_record(\"cbrt\", 1, float_dtypes, jtu.rand_default),\n op_record(\"square\", 1, float_dtypes + complex_dtypes, jtu.rand_default),\n op_record(\"reciprocal\", 1, float_dtypes + complex_dtypes, jtu.rand_positive),\n op_record(\"tan\", 1, float_dtypes + complex_dtypes, jtu.rand_default, {np.float32: 3e-5}),\n op_record(\"asin\", 1, float_dtypes + complex_dtypes, jtu.rand_small),\n op_record(\"acos\", 1, float_dtypes + complex_dtypes, jtu.rand_small),\n op_record(\"atan\", 1, float_dtypes + complex_dtypes, jtu.rand_small),\n op_record(\"asinh\", 1, float_dtypes + complex_dtypes, jtu.rand_default,\n tol={np.complex64: 1E-4, np.complex128: 1E-5}),\n op_record(\"acosh\", 1, float_dtypes + complex_dtypes, jtu.rand_positive),\n # TODO(b/155331781): atanh has only ~float precision\n op_record(\"atanh\", 1, float_dtypes + complex_dtypes, jtu.rand_small, {np.float64: 1e-9}),\n op_record(\"sinh\", 1, float_dtypes + complex_dtypes, jtu.rand_default),\n op_record(\"cosh\", 1, float_dtypes + complex_dtypes, jtu.rand_default),\n op_record(\"lgamma\", 1, float_dtypes, jtu.rand_positive,\n {np.float32: 1e-3 if jtu.device_under_test() == \"tpu\" else 1e-5,\n np.float64: 1e-14}),\n op_record(\"digamma\", 1, float_dtypes, jtu.rand_positive,\n {np.float64: 1e-14}),\n op_record(\"betainc\", 3, float_dtypes, jtu.rand_positive,\n {np.float64: 1e-14}),\n op_record(\"igamma\", 2,\n [f for f in float_dtypes if f not in [dtypes.bfloat16, np.float16]],\n jtu.rand_positive, {np.float64: 1e-14}),\n op_record(\"igammac\", 2,\n [f for f in float_dtypes if f not in [dtypes.bfloat16, np.float16]],\n jtu.rand_positive, {np.float64: 1e-14}),\n op_record(\"erf\", 1, float_dtypes, jtu.rand_small),\n op_record(\"erfc\", 1, float_dtypes, jtu.rand_small),\n # TODO(b/142976030): the approximation of erfinf used by XLA is only\n # accurate to float32 precision.\n op_record(\"erf_inv\", 1, float_dtypes, jtu.rand_small,\n {np.float64: 1e-9}),\n op_record(\"bessel_i0e\", 1, float_dtypes, jtu.rand_default),\n op_record(\"bessel_i1e\", 1, float_dtypes, jtu.rand_default),\n\n op_record(\"real\", 1, complex_dtypes, jtu.rand_default),\n op_record(\"imag\", 1, complex_dtypes, jtu.rand_default),\n op_record(\"complex\", 2, complex_elem_dtypes, jtu.rand_default),\n op_record(\"conj\", 1, complex_elem_dtypes + complex_dtypes,\n jtu.rand_default),\n op_record(\"abs\", 1, default_dtypes + complex_dtypes, jtu.rand_default),\n op_record(\"pow\", 2, float_dtypes + complex_dtypes, jtu.rand_positive),\n\n op_record(\"bitwise_and\", 2, bool_dtypes, jtu.rand_small),\n op_record(\"bitwise_not\", 1, bool_dtypes, jtu.rand_small),\n op_record(\"bitwise_or\", 2, bool_dtypes, jtu.rand_small),\n op_record(\"bitwise_xor\", 2, bool_dtypes, jtu.rand_small),\n op_record(\"population_count\", 1, int_dtypes + uint_dtypes, jtu.rand_int),\n op_record(\"clz\", 1, int_dtypes + uint_dtypes, jtu.rand_int),\n\n op_record(\"add\", 2, default_dtypes + complex_dtypes, jtu.rand_small),\n op_record(\"sub\", 2, default_dtypes + complex_dtypes, jtu.rand_small),\n op_record(\"mul\", 2, default_dtypes + complex_dtypes, jtu.rand_small),\n op_record(\"div\", 2, default_dtypes + complex_dtypes, jtu.rand_nonzero),\n op_record(\"rem\", 2, default_dtypes, jtu.rand_nonzero),\n\n op_record(\"max\", 2, all_dtypes, jtu.rand_small),\n op_record(\"min\", 2, all_dtypes, jtu.rand_small),\n\n op_record(\"eq\", 2, all_dtypes, jtu.rand_some_equal),\n op_record(\"ne\", 2, all_dtypes, jtu.rand_small),\n op_record(\"ge\", 2, default_dtypes, jtu.rand_small),\n op_record(\"gt\", 2, default_dtypes, jtu.rand_small),\n op_record(\"le\", 2, default_dtypes, jtu.rand_small),\n op_record(\"lt\", 2, default_dtypes, jtu.rand_small),\n]\n\n\nclass LaxTest(jtu.JaxTestCase):\n \"\"\"Numerical tests for LAX operations.\"\"\"\n\n @parameterized.named_parameters(itertools.chain.from_iterable(\n jtu.cases_from_list(\n {\"testcase_name\": jtu.format_test_name_suffix(\n rec.op, shapes, itertools.repeat(dtype)),\n \"op_name\": rec.op, \"rng_factory\": rec.rng_factory, \"shapes\": shapes,\n \"dtype\": dtype}\n for shape_group in compatible_shapes\n for shapes in itertools.combinations_with_replacement(shape_group, rec.nargs)\n for dtype in rec.dtypes)\n for rec in LAX_OPS))\n def testOp(self, op_name, rng_factory, shapes, dtype):\n rng = rng_factory(self.rng())\n args_maker = lambda: [rng(shape, dtype) for shape in shapes]\n op = getattr(lax, op_name)\n self._CompileAndCheck(op, args_maker)\n\n @parameterized.named_parameters(itertools.chain.from_iterable(\n jtu.cases_from_list(\n {\"testcase_name\": jtu.format_test_name_suffix(\n rec.op, shapes, itertools.repeat(dtype)),\n \"op_name\": rec.op, \"rng_factory\": rec.rng_factory, \"shapes\": shapes,\n \"dtype\": dtype, \"tol\": rec.tol}\n for shape_group in compatible_shapes\n for shapes in itertools.combinations_with_replacement(shape_group, rec.nargs)\n for dtype in rec.dtypes)\n for rec in LAX_OPS))\n def testOpAgainstNumpy(self, op_name, rng_factory, shapes, dtype, tol):\n if (not config.x64_enabled and op_name == \"nextafter\"\n and dtype == np.float64):\n raise SkipTest(\"64-bit mode disabled\")\n rng = rng_factory(self.rng())\n args_maker = lambda: [rng(shape, dtype) for shape in shapes]\n op = getattr(lax, op_name)\n numpy_op = getattr(lax_reference, op_name)\n self._CheckAgainstNumpy(numpy_op, op, args_maker, tol=tol)\n\n # TODO test shift_left, shift_right_arithmetic, shift_right_logical\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_from_dtype={}_to_dtype={}_weak_type={}\".format(\n from_dtype, to_dtype, weak_type),\n \"from_dtype\": from_dtype, \"to_dtype\": to_dtype, \"weak_type\": weak_type}\n for from_dtype, to_dtype in itertools.product(\n [None, np.float32, np.int32, \"float32\", \"int32\"], repeat=2)\n for weak_type in [True, False]))\n def testConvertElementType(self, from_dtype, to_dtype, weak_type):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng((2, 3), from_dtype)]\n op = lambda x: lax._convert_element_type(x, to_dtype, weak_type)\n self._CompileAndCheck(op, args_maker)\n\n x = rng((1,), from_dtype)\n out = op(x)\n self.assertEqual(out.dtype, dtypes.canonicalize_dtype(to_dtype or x.dtype))\n self.assertEqual(out.aval.weak_type, weak_type)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_from_dtype={}_to_dtype={}\"\n .format(from_dtype, to_dtype),\n \"from_dtype\": from_dtype, \"to_dtype\": to_dtype}\n for from_dtype, to_dtype in itertools.product(\n [np.float32, np.int32, \"float32\", \"int32\"], repeat=2)))\n def testConvertElementTypeAgainstNumpy(self, from_dtype, to_dtype):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng((2, 3), from_dtype)]\n op = lambda x: lax.convert_element_type(x, to_dtype)\n numpy_op = lambda x: lax_reference.convert_element_type(x, to_dtype)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_from_dtype={}_to_dtype={}\"\n .format(from_dtype, to_dtype),\n \"from_dtype\": from_dtype, \"to_dtype\": to_dtype}\n for from_dtype, to_dtype in itertools.product(\n [np.float32, np.int32, \"float32\", \"int32\"], repeat=2)))\n def testBitcastConvertType(self, from_dtype, to_dtype):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng((2, 3), from_dtype)]\n op = lambda x: lax.bitcast_convert_type(x, to_dtype)\n self._CompileAndCheck(op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_from_dtype={}_to_dtype={}\"\n .format(from_dtype, to_dtype),\n \"from_dtype\": from_dtype, \"to_dtype\": to_dtype}\n for from_dtype, to_dtype in itertools.product(\n [np.float32, np.int32, \"float32\", \"int32\"], repeat=2)))\n def testBitcastConvertTypeAgainstNumpy(self, from_dtype, to_dtype):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng((2, 3), from_dtype)]\n op = lambda x: lax.bitcast_convert_type(x, to_dtype)\n numpy_op = lambda x: lax_reference.bitcast_convert_type(x, to_dtype)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_from_dtype={}_to_dtype={}_weak_type={}\"\n .format(from_dtype, to_dtype, weak_type),\n \"from_dtype\": from_dtype, \"to_dtype\": to_dtype, \"weak_type\": weak_type}\n for from_dtype, to_dtype in itertools.product(\n [np.float32, np.int32, \"float32\", \"int32\"], repeat=2)\n for weak_type in [True, False]))\n def testBitcastConvertWeakType(self, from_dtype, to_dtype, weak_type):\n rng = jtu.rand_default(self.rng())\n x_in = lax._convert_element_type(rng((2, 3), from_dtype),\n weak_type=weak_type)\n op = lambda x: lax.bitcast_convert_type(x, to_dtype)\n self.assertEqual(dtypes.is_weakly_typed(x_in), weak_type)\n x_out = op(x_in)\n self.assertEqual(dtypes.is_weakly_typed(x_out), False)\n x_out_jit = jax.jit(op)(x_in)\n self.assertEqual(dtypes.is_weakly_typed(x_out_jit), False)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_min_shape={}_operand_shape={}_max_shape={}\".format(\n jtu.format_shape_dtype_string(min_shape, dtype),\n jtu.format_shape_dtype_string(operand_shape, dtype),\n jtu.format_shape_dtype_string(max_shape, dtype)),\n \"min_shape\": min_shape, \"operand_shape\": operand_shape,\n \"max_shape\": max_shape, \"dtype\": dtype}\n for min_shape, operand_shape, max_shape in [\n [(), (2, 3), ()],\n [(2, 3), (2, 3), ()],\n [(), (2, 3), (2, 3)],\n [(2, 3), (2, 3), (2, 3)],\n ]\n for dtype in default_dtypes))\n def testClamp(self, min_shape, operand_shape, max_shape, dtype):\n rng = jtu.rand_default(self.rng())\n shapes = [min_shape, operand_shape, max_shape]\n args_maker = lambda: [rng(shape, dtype) for shape in shapes]\n self._CompileAndCheck(lax.clamp, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_min_shape={}_operand_shape={}_max_shape={}\".format(\n jtu.format_shape_dtype_string(min_shape, dtype),\n jtu.format_shape_dtype_string(operand_shape, dtype),\n jtu.format_shape_dtype_string(max_shape, dtype)),\n \"min_shape\": min_shape, \"operand_shape\": operand_shape,\n \"max_shape\": max_shape, \"dtype\": dtype}\n for min_shape, operand_shape, max_shape in [\n [(), (2, 3), ()],\n [(2, 3), (2, 3), ()],\n [(), (2, 3), (2, 3)],\n [(2, 3), (2, 3), (2, 3)],\n ]\n for dtype in default_dtypes))\n def testClampAgainstNumpy(self, min_shape, operand_shape, max_shape, dtype):\n rng = jtu.rand_default(self.rng())\n shapes = [min_shape, operand_shape, max_shape]\n args_maker = lambda: [rng(shape, dtype) for shape in shapes]\n self._CheckAgainstNumpy(lax_reference.clamp, lax.clamp, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_dim={}_baseshape=[{}]_dtype={}_narrs={}\".format(\n dim, \",\".join(str(d) for d in base_shape), np.dtype(dtype).name,\n num_arrs),\n \"dim\": dim, \"base_shape\": base_shape, \"dtype\": dtype, \"num_arrs\": num_arrs}\n for num_arrs in [3]\n for dtype in default_dtypes\n for base_shape in [(4,), (3, 4), (2, 3, 4)]\n for dim in range(len(base_shape))))\n def testConcatenate(self, dim, base_shape, dtype, num_arrs):\n rng = jtu.rand_default(self.rng())\n shapes = [base_shape[:dim] + (size,) + base_shape[dim+1:]\n for size, _ in zip(itertools.cycle([3, 1, 4]), range(num_arrs))]\n args_maker = lambda: [rng(shape, dtype) for shape in shapes]\n op = lambda *args: lax.concatenate(args, dim)\n self._CompileAndCheck(op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_dim={}_baseshape=[{}]_dtype={}_narrs={}\".format(\n dim, \",\".join(str(d) for d in base_shape), np.dtype(dtype).name,\n num_arrs),\n \"dim\": dim, \"base_shape\": base_shape, \"dtype\": dtype, \"num_arrs\": num_arrs}\n for num_arrs in [3]\n for dtype in default_dtypes\n for base_shape in [(4,), (3, 4), (2, 3, 4)]\n for dim in range(len(base_shape))))\n def testConcatenateAgainstNumpy(self, dim, base_shape, dtype, num_arrs):\n rng = jtu.rand_default(self.rng())\n shapes = [base_shape[:dim] + (size,) + base_shape[dim+1:]\n for size, _ in zip(itertools.cycle([3, 1, 4]), range(num_arrs))]\n args_maker = lambda: [rng(shape, dtype) for shape in shapes]\n op = lambda *args: lax.concatenate(args, dim)\n numpy_op = lambda *args: lax_reference.concatenate(args, dim)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype), strides, padding),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"strides\": strides, \"padding\": padding}\n for lhs_shape, rhs_shape in [\n ((b, i, 9, 10), (j, i, 4, 5))\n for b, i, j in itertools.product([2, 3], repeat=3)]\n for dtype in float_dtypes\n for strides in [(1, 1), (1, 2), (2, 1)]\n for padding in [\"VALID\", \"SAME\"]))\n def testConv(self, lhs_shape, rhs_shape, dtype, strides, padding):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n\n def fun(lhs, rhs):\n return lax.conv(lhs, rhs, strides, padding)\n\n self._CompileAndCheck(fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_lhs_shape={}_rhs_shape={}_preferred_element_type={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype),\n preferred_element_type.__name__),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"preferred_element_type\": preferred_element_type}\n for lhs_shape, rhs_shape in [\n ((b, i, 9, 10), (j, i, 4, 5))\n for b, i, j in itertools.product([2, 3], repeat=3)]\n for dtype, preferred_element_type in preferred_type_combinations))\n def testConvPreferredElement(self, lhs_shape, rhs_shape, dtype, preferred_element_type):\n if (not config.x64_enabled and\n (dtype == np.float64 or preferred_element_type == np.float64\n or dtype == np.int64 or preferred_element_type == np.int64\n or dtype == np.complex128 or preferred_element_type == np.complex128)):\n raise SkipTest(\"64-bit mode disabled\")\n if jtu.device_under_test() == \"gpu\" and np.issubdtype(dtype, np.integer):\n # TODO(b/183565702): Support integer convolutions on CPU/GPU.\n raise SkipTest(\"Integer convolution not yet supported on GPU\")\n if (jtu.device_under_test() == \"tpu\" and\n (dtype == np.complex128 or preferred_element_type == np.complex128)):\n raise SkipTest(\"np.complex128 is not yet supported on TPU\")\n # x64 implementation is only accurate to ~float32 precision for this case.\n if dtype == np.complex64 and preferred_element_type == np.complex128:\n tol = 1e-5\n else:\n tol = {np.float64: 1e-14}\n rng = jtu.rand_default(self.rng())\n x = rng(lhs_shape, dtype)\n y = rng(rhs_shape, dtype)\n # We first compute the conv when both inputs are a lower-precision type and\n # preferred_element_type is a higher-precision type. We then compute results\n # where the inputs are first upcast to the higher-precision type and no\n # `preferred_element_type` is given. We expect the result to be extremely\n # similar given the semantics of `preferred_element_type`.\n result_with_preferred_type = lax.conv(\n x, y, (1, 1), \"VALID\",\n preferred_element_type=preferred_element_type)\n result_with_upcast_inputs = lax.conv(\n x.astype(preferred_element_type),\n y.astype(preferred_element_type),\n (1, 1), \"VALID\")\n self.assertArraysAllClose(\n result_with_preferred_type, result_with_upcast_inputs, rtol=tol, atol=tol)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype), strides, padding),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"strides\": strides, \"padding\": padding}\n for lhs_shape, rhs_shape in [\n ((b, i, 9, 10), (j, i, 4, 5))\n for b, i, j in itertools.product([2, 3], repeat=3)]\n for dtype in float_dtypes\n for strides in [(1, 1), (1, 2), (2, 1)]\n for padding in [\"VALID\", \"SAME\"]))\n def testConvAgainstNumpy(self, lhs_shape, rhs_shape, dtype, strides, padding):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n op = lambda lhs, rhs: lax.conv(lhs, rhs, strides, padding)\n numpy_op = lambda lhs, rhs: lax_reference.conv(lhs, rhs, strides, padding)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}\"\n \"_lhs_dilation={}_rhs_dilation={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype),\n strides, padding, lhs_dilation, rhs_dilation),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"strides\": strides, \"padding\": padding, \"lhs_dilation\": lhs_dilation,\n \"rhs_dilation\": rhs_dilation}\n for lhs_shape, rhs_shape in [\n ((b, i, 9, 10), (j, i, 4, 5))\n for b, i, j in itertools.product([1, 2, 3], repeat=3)]\n for dtype in float_dtypes\n for strides in [(1, 1), (1, 2), (2, 1)]\n for padding in [((0, 0), (0, 0)), ((1, 2), (2, 0))]\n for lhs_dilation, rhs_dilation in itertools.product(\n [(1, 1), (1, 2), (2, 2)], repeat=2)))\n def testConvWithGeneralPadding(self, lhs_shape, rhs_shape, dtype, strides,\n padding, lhs_dilation, rhs_dilation):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n\n def fun(lhs, rhs):\n return lax.conv_with_general_padding(\n lhs, rhs, strides, padding, lhs_dilation, rhs_dilation)\n\n self._CompileAndCheck(fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}\"\n \"_lhs_dilation={}_rhs_dilation={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype),\n strides, padding, lhs_dilation, rhs_dilation),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"strides\": strides, \"padding\": padding, \"lhs_dilation\": lhs_dilation,\n \"rhs_dilation\": rhs_dilation}\n for lhs_shape, rhs_shape in [\n ((b, i, 9, 10), (j, i, 4, 5))\n for b, i, j in itertools.product([1, 2, 3], repeat=3)]\n for dtype in [np.float32] for strides in [(1, 1), (1, 2), (2, 1)]\n for padding in [((0, 0), (0, 0)), ((1, 2), (2, 0))]\n for lhs_dilation, rhs_dilation in itertools.product(\n [(1, 1), (1, 2), (2, 2)], repeat=2)))\n def testConvWithGeneralPaddingAgainstNumpy(\n self, lhs_shape, rhs_shape, dtype, strides, padding, lhs_dilation,\n rhs_dilation):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n\n def fun(lhs, rhs):\n return lax.conv_with_general_padding(\n lhs, rhs, strides, padding, lhs_dilation, rhs_dilation,\n precision=lax.Precision.HIGHEST)\n\n def numpy_fun(lhs, rhs):\n return lax_reference.conv_with_general_padding(\n lhs, rhs, strides, padding, lhs_dilation, rhs_dilation)\n\n self._CheckAgainstNumpy(numpy_fun, fun, args_maker)\n\n @parameterized.named_parameters(jtu.named_cases_from_sampler(lambda s: ({\n \"testcase_name\": \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}\"\n \"_lhs_dilation={}_rhs_dilation={}\"\n \"_dims={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype),\n strides, padding, lhs_dilation, rhs_dilation,\n \",\".join(dim_nums)),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"strides\": strides, \"padding\": padding, \"lhs_dilation\": lhs_dilation,\n \"rhs_dilation\": rhs_dilation, \"dimension_numbers\": dim_nums,\n \"feature_group_count\": feature_group_count,\n \"batch_group_count\": batch_group_count, \"perms\": perms\n } for batch_group_count, feature_group_count in s([(1, 1), (2, 1), (1, 2)])\n for lhs_shape, rhs_shape in s([\n ((b * batch_group_count, i * feature_group_count, 9, w),\n (j * feature_group_count * batch_group_count, i, 4, 5))\n for w in [0, 10]\n for b, i, j in itertools.product([2, 3], repeat=3)])\n for dtype in s(all_dtypes)\n for strides in s([(1, 1), (2, 1)])\n for padding in s([((1, 2), (2, 0)), ((10, 8), (7, 13))])\n for lhs_dilation, rhs_dilation in s(itertools.product(\n [(1, 1), (1, 2), (1, 4)], repeat=2))\n for dim_nums, perms in s([\n ((\"NCHW\", \"OIHW\", \"NCHW\"), ([0, 1, 2, 3], [0, 1, 2, 3])),\n ((\"NHWC\", \"HWIO\", \"NHWC\"), ([0, 2, 3, 1], [2, 3, 1, 0])),\n ((\"NCHW\", \"HWIO\", \"NHWC\"), ([0, 1, 2, 3], [2, 3, 1, 0])),\n ]))))\n def testConvGeneralDilated(self, lhs_shape, rhs_shape, dtype, strides,\n padding, lhs_dilation, rhs_dilation,\n feature_group_count, batch_group_count,\n dimension_numbers, perms):\n if np.issubdtype(dtype, np.integer) or np.issubdtype(dtype, np.bool_):\n # TODO(b/183565702): Support integer convolutions on CPU/GPU.\n if jtu.device_under_test() == \"gpu\":\n raise SkipTest(\"Integer convolution not yet supported on GPU\")\n rng = jtu.rand_small(self.rng())\n lhs_perm, rhs_perm = perms # permute to compatible shapes\n\n def args_maker():\n return [lax.transpose(rng(lhs_shape, dtype), lhs_perm),\n lax.transpose(rng(rhs_shape, dtype), rhs_perm)]\n\n def fun(lhs, rhs):\n return lax.conv_general_dilated(\n lhs, rhs, strides, padding, lhs_dilation, rhs_dilation,\n dimension_numbers, feature_group_count=feature_group_count,\n batch_group_count=batch_group_count)\n\n self._CompileAndCheck(fun, args_maker)\n\n def testConvGeneralDilatedPatchesOverlapping1D(self):\n lhs = np.array([[1]], np.float32).reshape((1, 1))\n patches = lax.conv_general_dilated_patches(\n lhs=lhs,\n filter_shape=(),\n window_strides=(),\n padding='SAME'\n )\n self.assertAllClose(lhs, patches)\n\n dn = ('NHC', 'OIH', 'NHC')\n lhs = np.array([1, 2, 3, 4, 5], np.float32).reshape((1, -1, 1))\n\n patches = lax.conv_general_dilated_patches(\n lhs=lhs,\n filter_shape=(2,),\n window_strides=(2,),\n padding='VALID',\n dimension_numbers=dn\n )\n self.assertAllClose(\n np.array([[1, 2],\n [3, 4]], np.float32).reshape((1, 2, 2)), patches)\n\n patches = lax.conv_general_dilated_patches(\n lhs=lhs,\n filter_shape=(3,),\n window_strides=(1,),\n padding='SAME',\n dimension_numbers=dn\n )\n self.assertAllClose(\n np.array([[0, 1, 2],\n [1, 2, 3],\n [2, 3, 4],\n [3, 4, 5],\n [4, 5, 0]], np.float32).reshape((1, 5, 3)), patches)\n\n patches = lax.conv_general_dilated_patches(\n lhs=lhs,\n filter_shape=(3,),\n window_strides=(1,),\n padding='SAME',\n rhs_dilation=(2,),\n dimension_numbers=dn\n )\n self.assertAllClose(\n np.array([[0, 1, 3],\n [0, 2, 4],\n [1, 3, 5],\n [2, 4, 0],\n [3, 5, 0]], np.float32).reshape((1, 5, 3)), patches)\n\n def testConvGeneralDilatedPatchesOverlapping2D(self):\n lhs = np.array([[1, 2, 3],\n [4, 5, 6]], np.float32).reshape((1, 2, 3, 1))\n patches = lax.conv_general_dilated_patches(\n lhs=lhs,\n filter_shape=(2, 2),\n window_strides=(1, 1),\n padding='SAME',\n dimension_numbers=('NHWC', 'OIHW', 'NHWC')\n )\n self.assertAllClose(np.array([[1, 2, 4, 5],\n [2, 3, 5, 6],\n [3, 0, 6, 0],\n [4, 5, 0, 0],\n [5, 6, 0, 0],\n [6, 0, 0, 0]],\n np.float32).reshape((1, 2, 3, 4)), patches)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_lhs_shape={}_filter_shape={}_strides={}_padding={}\"\n \"_dims={}_precision={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(filter_shape, dtype),\n strides,\n padding,\n \"None\" if dim_nums is None else \",\".join(dim_nums),\n precision\n ),\n \"lhs_shape\": lhs_shape,\n \"filter_shape\": filter_shape,\n \"dtype\": dtype,\n \"strides\": strides,\n \"padding\": padding,\n \"dimension_numbers\": dim_nums,\n \"precision\": precision\n }\n for dtype in all_dtypes\n for lhs_shape, filter_shape, strides, padding, dim_nums in [\n ((2, 5), (), (), [], (\"NC\", \"OI\", \"CN\")),\n ((2, 3, 4), (2,), (2,), [(0, 2)], (\"CNH\", \"OHI\", \"HNC\")),\n ((3, 1, 4, 5), (1, 3), (1, 3), [(3, 1), (2, 2)],\n (\"NCHW\", \"OIHW\", \"NCHW\")),\n ((3, 2, 5, 6), (4, 3), (4, 3), [(5, 2), (2, 4)],\n None),\n ((1, 2, 3, 4), (1, 1), (1, 1), [(0, 0), (0, 0)],\n (\"NCWH\", \"OHWI\", \"CNHW\")),\n ((1, 2, 3, 4), (3, 2), (1, 1), [(0, 0), (0, 0)],\n (\"CWHN\", \"HOWI\", \"NCHW\")),\n ((2, 3, 4, 5, 6), (2, 1, 3), (2, 1, 3), [(1, 2), (5, 3), (3, 5)],\n (\"NHWDC\", \"HDIWO\", \"DCWNH\"))\n ]\n for precision in [None,\n lax.Precision.DEFAULT,\n lax.Precision.HIGH,\n lax.Precision.HIGHEST]\n ))\n def testConvGeneralDilatedPatchesNonOverlapping(self,\n lhs_shape,\n filter_shape,\n dtype,\n strides,\n padding,\n dimension_numbers,\n precision):\n if np.issubdtype(dtype, np.integer) or np.issubdtype(dtype, np.bool_):\n # TODO(b/183565702): Support integer convolutions on CPU/GPU.\n if jtu.device_under_test() == \"gpu\":\n raise SkipTest(\"Integer convolution not yet supported on GPU\")\n rng = jtu.rand_small(self.rng())\n lhs = rng(lhs_shape, dtype)\n\n if dimension_numbers is None:\n lhs_spec, rhs_spec, out_spec = \"NCHW\", \"OIHW\", \"NCHW\"\n else:\n lhs_spec, rhs_spec, out_spec = dimension_numbers\n\n filter_spec = ''.join(c for c in rhs_spec if c not in ('I', 'O'))\n patches_spec = out_spec.replace('C', 'C' + filter_spec.lower())\n\n full_padding = []\n for c in lhs_spec:\n if c in ('N', 'C'):\n full_padding += [(0, 0)]\n else:\n full_padding += [padding[filter_spec.index(c)]]\n\n lhs_padded = np.pad(lhs, full_padding, 'constant')\n out = lax.transpose(lhs_padded, [lhs_spec.index(c) for c in out_spec])\n\n patches = lax.conv_general_dilated_patches(\n lhs=lhs,\n filter_shape=filter_shape,\n window_strides=strides,\n padding=padding,\n dimension_numbers=dimension_numbers,\n precision=precision\n )\n\n source = []\n\n # Test that output spatial shape is factored into `#patches x patch_size`.\n for c in out_spec:\n out_c = out.shape[out_spec.index(c)]\n patch_c = patches.shape[out_spec.index(c)]\n\n if c == 'N':\n self.assertEqual(out_c, patch_c)\n elif c == 'C':\n self.assertEqual(out_c * np.prod(filter_shape), patch_c)\n else:\n self.assertEqual(out_c, patch_c * filter_shape[filter_spec.index(c)])\n\n source += [patches_spec.index(c), patches_spec.index(c.lower())]\n\n # Test that stacking patches together gives the source image, padded.\n c = out_spec.index('C')\n patches = patches.reshape(patches.shape[:c] +\n (lhs_shape[lhs_spec.index('C')],) +\n filter_shape +\n patches.shape[c + 1:]\n )\n patches = np.moveaxis(patches, source, range(len(source)))\n for i in range(len(filter_shape)):\n patches = patches.reshape(patches.shape[:i] + (-1,) +\n patches.shape[2 + i:])\n patches = np.moveaxis(\n patches,\n range(len(filter_shape)),\n [out_spec.index(c) for c in out_spec if c not in ('N', 'C')])\n self.assertAllClose(out, patches)\n\n # TODO(mattjj): test conv_general_dilated against numpy\n\n def testConv0DIsDot(self):\n rng = jtu.rand_default(self.rng())\n def args_maker():\n return [rng((10, 5), np.float32), rng((5, 7), np.float32)]\n jnp_fun = partial(lax.conv_general_dilated, window_strides=(),\n padding='VALID', dimension_numbers=('NC', 'IO', 'NC'))\n self._CompileAndCheck(jnp_fun, args_maker)\n self._CheckAgainstNumpy(np.dot, jnp_fun, args_maker, tol=.1)\n\n def testGradConv0D(self):\n # Reproduces a failure in neural_tangents not caught in our presubmit tests\n # See cl/367416742.\n lhs = np.ones((2, 5), dtype=np.float32)\n rhs = np.ones((5, 10), dtype=np.float32)\n\n def f_jax(lhs, rhs):\n return lax.conv_general_dilated(\n lhs, rhs, window_strides=(),\n padding=(), lhs_dilation=(), rhs_dilation=(),\n dimension_numbers=lax.ConvDimensionNumbers((0, 1), (1, 0), (0, 1)),\n batch_group_count=1, feature_group_count=1, precision=None,\n preferred_element_type=None)\n res, pullback = jax.vjp(f_jax, lhs, rhs)\n grad = pullback(np.ones_like(res))\n self.assertAllClose((lhs * 10., rhs * 2.), grad)\n\n @staticmethod\n def _conv_transpose_via_grad(data, kernel, strides, padding,\n rhs_dilation=None, dimension_numbers=None):\n \"\"\"Helper method: calculates conv transpose via grad for testing.\"\"\"\n assert len(data.shape) == len(kernel.shape)\n nspatial = len(data.shape) - 2\n one = (1,) * nspatial\n rhs_dilation = rhs_dilation or one\n dn = lax.conv_dimension_numbers(data.shape, kernel.shape,\n dimension_numbers)\n in_shape = np.take(data.shape, dn.lhs_spec)\n in_sdims = in_shape[2:]\n k_shape = np.take(kernel.shape, dn.rhs_spec)\n k_sdims = k_shape[2:]\n e_k_sdims = [(k-1) * r + 1 for k, r in zip(k_sdims, rhs_dilation)]\n if padding == 'VALID':\n o_sdims = [in_sdims[i]*strides[i] + max(e_k_sdims[i]-strides[i],0)\n for i in range(nspatial)]\n elif padding == 'SAME':\n o_sdims = [in_sdims[i]*strides[i] for i in range(nspatial)]\n o_shape = [in_shape[0], k_shape[1]] + o_sdims\n out_spec_inv = [x[0] for x in\n sorted(enumerate(dn.out_spec), key=lambda x: x[1])]\n o_layout = np.take(np.array(o_shape), out_spec_inv)\n placeholder = np.ones(o_layout, data.dtype)\n conv = lambda x: lax.conv_general_dilated(x, kernel, strides, padding,\n one, rhs_dilation, dn)\n _, g = jax.vjp(conv, placeholder)\n return g(data)[0]\n\n @staticmethod\n def _transpose_conv_kernel(data, kernel, dimension_numbers):\n dn = lax.conv_dimension_numbers(data.shape, kernel.shape,\n dimension_numbers)\n spatial_axes = np.array(dn.rhs_spec)[2:]\n for axis in spatial_axes:\n kernel = np.flip(kernel, axis)\n kernel = np.swapaxes(kernel, dn.rhs_spec[0], dn.rhs_spec[1])\n return kernel\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}_rhs_dilation={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype), strides, padding, rhs_dilation),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"strides\": strides, \"padding\": padding, \"rhs_dilation\": rhs_dilation,\n \"dspec\": dspec}\n for lhs_shape, rhs_shape in [\n ((b, 9, 10, i), (k, k, j, i)) # NB: i,j flipped in RHS for transpose\n for b, i, j, k in itertools.product([2,3],[2,3],[2,3],[3,4,5])]\n for dtype in float_dtypes\n for strides in [(1, 1), (1, 2), (2, 1), (2, 2), (3, 3)]\n for padding in [\"VALID\", \"SAME\"]\n for dspec in [('NHWC', 'HWIO', 'NHWC'),]\n for rhs_dilation in [None, (2, 2)]))\n @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n def testConvTranspose2DT(self, lhs_shape, rhs_shape, dtype, strides,\n padding, dspec, rhs_dilation):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n\n # NB: this test calculates conv_transpose performing identically to the\n # lhs-grad of conv.\n def fun(lhs, rhs):\n return lax.conv_transpose(lhs, rhs, strides, padding,\n rhs_dilation=rhs_dilation,\n dimension_numbers=dspec,\n transpose_kernel=True)\n\n def fun_via_grad(lhs, rhs):\n return self._conv_transpose_via_grad(lhs, rhs, strides, padding,\n rhs_dilation=rhs_dilation,\n dimension_numbers=dspec)\n\n # NB: below just checks for agreement, we're not calling numpy.\n self._CheckAgainstNumpy(fun_via_grad, fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}_rhs_dilation={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype), strides, padding, rhs_dilation),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"strides\": strides, \"padding\": padding, \"rhs_dilation\": rhs_dilation,\n \"dspec\": dspec}\n for lhs_shape, rhs_shape in [\n ((b, 9, 10, i), (k, k, i, j))\n for b, i, j, k in itertools.product([2,3],[2,3],[2,3],[3,4,5])]\n for dtype in float_dtypes\n for strides in [(1, 1), (1, 2), (2, 1), (2, 2), (3, 3)]\n for padding in [\"VALID\", \"SAME\"]\n for dspec in [('NHWC', 'HWIO', 'NHWC'),]\n for rhs_dilation in [None, (2, 2)]))\n @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n def testConvTranspose2D(self, lhs_shape, rhs_shape, dtype, strides,\n padding, dspec, rhs_dilation):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n\n def fun(lhs, rhs):\n return lax.conv_transpose(lhs, rhs, strides, padding,\n rhs_dilation=rhs_dilation,\n dimension_numbers=dspec,\n transpose_kernel=False)\n\n def fun_via_grad(lhs, rhs):\n rhs_t = self._transpose_conv_kernel(lhs, rhs, dimension_numbers=dspec)\n return self._conv_transpose_via_grad(lhs, rhs_t, strides, padding,\n rhs_dilation=rhs_dilation,\n dimension_numbers=dspec)\n\n # NB: below just checks for agreement, we're not calling numpy.\n self._CheckAgainstNumpy(fun_via_grad, fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}_rhs_dilation={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype), strides, padding, rhs_dilation),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"strides\": strides, \"padding\": padding, \"rhs_dilation\": rhs_dilation,\n \"dspec\": dspec}\n for lhs_shape, rhs_shape in [\n ((b, 10, i), (k, i, j))\n for b, i, j, k in itertools.product([2,3],[2,3],[2,3],[3,4,5])]\n for dtype in float_dtypes\n for strides in [(1,), (2,), (3,)]\n for padding in [\"VALID\", \"SAME\"]\n for dspec in [('NHC', 'HIO', 'NHC'),]\n for rhs_dilation in [None, (2,)]))\n def testConvTranspose1D(self, lhs_shape, rhs_shape, dtype, strides,\n padding, dspec, rhs_dilation):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n\n def fun(lhs, rhs):\n return lax.conv_transpose(lhs, rhs, strides, padding,\n dimension_numbers=dspec,\n rhs_dilation=rhs_dilation,\n transpose_kernel=False)\n\n def fun_via_grad(lhs, rhs):\n rhs_t = self._transpose_conv_kernel(lhs, rhs, dimension_numbers=dspec)\n return self._conv_transpose_via_grad(lhs, rhs_t, strides, padding,\n rhs_dilation=rhs_dilation,\n dimension_numbers=dspec)\n\n # NB: below just checks for agreement, we're not calling numpy.\n self._CheckAgainstNumpy(fun_via_grad, fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}_rhs_dilation={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype), strides, padding, rhs_dilation),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"strides\": strides, \"padding\": padding, \"rhs_dilation\": rhs_dilation,\n \"dspec\": dspec}\n for lhs_shape, rhs_shape in [\n ((b, i), (i, j))\n for b, i, j in itertools.product([2,3],[2,3],[2,3])]\n for dtype in float_dtypes\n for strides in [()]\n for padding in [\"VALID\", \"SAME\"]\n for dspec in [('NC', 'IO', 'NC'),]\n for rhs_dilation in [None, ()]))\n def testConvTranspose0D(self, lhs_shape, rhs_shape, dtype, strides,\n padding, dspec, rhs_dilation):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n\n def fun(lhs, rhs):\n return lax.conv_transpose(lhs, rhs, strides, padding,\n dimension_numbers=dspec,\n rhs_dilation=rhs_dilation,\n transpose_kernel=False)\n\n def fun_via_grad(lhs, rhs):\n rhs_t = self._transpose_conv_kernel(lhs, rhs, dimension_numbers=dspec)\n return self._conv_transpose_via_grad(lhs, rhs_t, strides, padding,\n rhs_dilation=rhs_dilation,\n dimension_numbers=dspec)\n\n # NB: below just checks for agreement, we're not calling numpy.\n self._CheckAgainstNumpy(fun_via_grad, fun, args_maker)\n\n def testConvTransposePaddingList(self):\n # Regression test for https://github.com/google/jax/discussions/8695\n a = jnp.ones((28,28))\n b = jnp.ones((3,3))\n c = lax.conv_general_dilated(a[None, None], b[None, None], (1,1), [(0,0),(0,0)], (1,1))\n self.assertArraysEqual(c, 9 * jnp.ones((1, 1, 26, 26)))\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_lhs_shape={}_rhs_shape={}_precision={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype),\n precision),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"precision\": precision}\n for lhs_shape in [(3,), (4, 3)] for rhs_shape in [(3,), (3, 6)]\n for dtype in all_dtypes\n for precision in [None, lax.Precision.DEFAULT, lax.Precision.HIGH,\n lax.Precision.HIGHEST,\n (lax.Precision.DEFAULT, lax.Precision.HIGHEST)]))\n def testDot(self, lhs_shape, rhs_shape, dtype, precision):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n self._CompileAndCheck(partial(lax.dot, precision=precision), args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_lhs_shape={}_rhs_shape={}_preferred_element_type={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype),\n jtu.format_shape_dtype_string((), preferred_element_type)\n ),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype, \"preferred_element_type\": preferred_element_type\n }\n for lhs_shape in [(3,), (4, 3)] for rhs_shape in [(3,), (3, 6)]\n for dtype, preferred_element_type in preferred_type_combinations))\n def testDotPreferredElement(self, lhs_shape, rhs_shape, dtype, preferred_element_type):\n if (not config.x64_enabled and\n (dtype == np.float64 or preferred_element_type == np.float64\n or dtype == np.int64 or preferred_element_type == np.int64)):\n raise SkipTest(\"64-bit mode disabled\")\n if (jtu.device_under_test() == \"tpu\" and\n (dtype == np.complex128 or preferred_element_type == np.complex128)):\n raise SkipTest(\"np.complex128 is not yet supported on TPU\")\n if jtu.device_under_test() == \"gpu\":\n # TODO(b/189287598)\n raise SkipTest(\"dot_general with preferred_element_type returns NaN non-deterministically on GPU\")\n rng = jtu.rand_default(self.rng())\n x = rng(lhs_shape, dtype)\n y = rng(rhs_shape, dtype)\n # We first compute the dot when both inputs are a lower-precision type and\n # preferred_element_type is a higher-precision type. We then compute results\n # where the inputs are first upcast to the higher-precision type and no\n # `preferred_element_type` is given. We expect the result to be extremely\n # similar given the semantics of `preferred_element_type`.\n result_with_preferred_type = lax.dot(x, y, preferred_element_type=preferred_element_type)\n result_with_upcast_inputs = lax.dot(\n x.astype(preferred_element_type),\n y.astype(preferred_element_type))\n self.assertArraysAllClose(result_with_preferred_type, result_with_upcast_inputs)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_lhs_shape={}_rhs_shape={}\".format(\n jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype)),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype}\n for lhs_shape in [(3,), (4, 3)] for rhs_shape in [(3,), (3, 6)]\n for dtype in all_dtypes))\n def testDotAgainstNumpy(self, lhs_shape, rhs_shape, dtype):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n tol = {\n np.float16: 1e-2,\n np.float64: max(jtu.default_tolerance()[np.dtype(np.float64)], 1e-14),\n np.complex128: max(jtu.default_tolerance()[np.dtype(np.complex128)],\n 1e-14)\n }\n lax_op = partial(lax.dot, precision=lax.Precision.HIGHEST)\n self._CheckAgainstNumpy(lax_reference.dot, lax_op, args_maker, tol=tol)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_lhs_shape={}_rhs_shape={}_lhs_contracting={}_rhs_contracting={}\"\n .format(jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype),\n lhs_contracting, rhs_contracting),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"lhs_contracting\": lhs_contracting, \"rhs_contracting\": rhs_contracting}\n for lhs_shape, rhs_shape, lhs_contracting, rhs_contracting in [\n [(5,), (5,), [0], [0]],\n [(5, 7), (5,), [0], [0]],\n [(7, 5), (5,), [1], [0]],\n [(3, 5), (2, 5), [1], [1]],\n [(5, 3), (5, 2), [0], [0]],\n [(5, 3, 2), (5, 2, 4), [0], [0]],\n [(5, 3, 2), (5, 2, 4), [0,2], [0,1]],\n [(5, 3, 2), (3, 5, 2, 4), [0,2], [1,2]],\n [(1, 2, 2, 3), (1, 2, 3, 1), [1], [1]],\n [(3, 2), (2, 4), [1], [0]],\n ]\n for dtype in all_dtypes))\n def testDotGeneralContractOnly(self, lhs_shape, rhs_shape, dtype,\n lhs_contracting, rhs_contracting):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n dimension_numbers = ((lhs_contracting, rhs_contracting), ([], []))\n\n def fun(lhs, rhs):\n return lax.dot_general(lhs, rhs, dimension_numbers)\n\n self._CompileAndCheck(fun, args_maker, check_dtypes=False)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_lhs_shape={}_rhs_shape={}_dimension_numbers={}\"\n .format(jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype),\n dimension_numbers),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"dimension_numbers\": dimension_numbers}\n for lhs_shape, rhs_shape, dimension_numbers in [\n ((3, 3, 2), (3, 2, 4), (([2], [1]), ([0], [0]))),\n ((3, 3, 2), (2, 3, 4), (([2], [0]), ([0], [1]))),\n ((3, 4, 2, 4), (3, 4, 3, 2), (([2], [3]), ([0, 1], [0, 1]))),\n ]\n for dtype in all_dtypes))\n def testDotGeneralContractAndBatch(self, lhs_shape, rhs_shape, dtype,\n dimension_numbers):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n\n def fun(lhs, rhs):\n return lax.dot_general(lhs, rhs, dimension_numbers)\n\n self._CompileAndCheck(fun, args_maker, check_dtypes=False)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_lhs_shape={}_rhs_shape={}_dimension_numbers={}\"\n .format(jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype),\n dimension_numbers),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n \"dimension_numbers\": dimension_numbers}\n for lhs_shape, rhs_shape, dimension_numbers in [\n ((3, 3, 2), (3, 2, 4), (([2], [1]), ([0], [0]))),\n ((3, 3, 2), (2, 3, 4), (([2], [0]), ([0], [1]))),\n ((3, 4, 2, 4), (3, 4, 3, 2), (([2], [3]), ([0, 1], [0, 1]))),\n ]\n for dtype in all_dtypes))\n def testDotGeneralAgainstNumpy(self, lhs_shape, rhs_shape, dtype,\n dimension_numbers):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n op = lambda x, y: lax.dot_general(x, y, dimension_numbers)\n numpy_op = lambda x, y: lax_reference.dot_general(x, y, dimension_numbers)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_dtype={}_broadcast_sizes={}\".format(\n shape, np.dtype(dtype).name, broadcast_sizes),\n \"shape\": shape, \"dtype\": dtype, \"broadcast_sizes\": broadcast_sizes}\n for shape in [(), (2, 3)]\n for dtype in default_dtypes\n for broadcast_sizes in [(), (2,), (1, 2)]))\n def testBroadcast(self, shape, dtype, broadcast_sizes):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(shape, dtype)]\n op = lambda x: lax.broadcast(x, broadcast_sizes)\n self._CompileAndCheck(op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_broadcast_sizes={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), broadcast_sizes),\n \"shape\": shape, \"dtype\": dtype, \"broadcast_sizes\": broadcast_sizes}\n for shape in [(), (2, 3)]\n for dtype in default_dtypes\n for broadcast_sizes in [(), (2,), (1, 2)]))\n def testBroadcastAgainstNumpy(self, shape, dtype, broadcast_sizes):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(shape, dtype)]\n op = lambda x: lax.broadcast(x, broadcast_sizes)\n numpy_op = lambda x: lax_reference.broadcast(x, broadcast_sizes)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_outshape={}_bcdims={}\".format(\n jtu.format_shape_dtype_string(inshape, dtype),\n outshape, broadcast_dimensions),\n \"inshape\": inshape, \"dtype\": dtype, \"outshape\": outshape,\n \"dimensions\": broadcast_dimensions}\n for inshape, outshape, broadcast_dimensions in [\n ([2], [2, 2], [0]),\n ([2], [2, 2], [1]),\n ([2], [2, 3], [0]),\n ([], [2, 3], []),\n ([1], [2, 3], [1]),\n ]\n for dtype in default_dtypes))\n def testBroadcastInDim(self, inshape, dtype, outshape, dimensions):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(inshape, dtype)]\n op = lambda x: lax.broadcast_in_dim(x, outshape, dimensions)\n self._CompileAndCheck(op, args_maker)\n\n def testBroadcastInDimOperandShapeTranspose(self):\n # Regression test for https://github.com/google/jax/issues/5276\n def f(x):\n return lax.broadcast_in_dim(x, (2, 3, 4), broadcast_dimensions=(0, 1, 2)).sum()\n def g(x):\n return lax.broadcast_in_dim(x.reshape((3,)), (2, 3, 4), broadcast_dimensions=(1,)).sum()\n x = np.ones((1, 3, 1))\n self.assertArraysEqual(jax.grad(f)(x), jax.grad(g)(x))\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_outshape={}_bcdims={}\".format(\n jtu.format_shape_dtype_string(inshape, np.float32),\n outshape, broadcast_dimensions),\n \"inshape\": inshape, \"outshape\": outshape,\n \"broadcast_dimensions\": broadcast_dimensions, \"err_msg\": err_msg}\n for inshape, outshape, broadcast_dimensions, err_msg in [\n ([2], [2, 2], [0, 1], ('broadcast_dimensions must have length equal to '\n 'operand ndim')),\n ([2, 2], [2], [0, 1], ('target broadcast shape must have equal or higher rank '\n 'to the operand shape')),\n ([2], [2, 3], [2], ('broadcast_in_dim broadcast_dimensions must be a subset of output '\n 'dimensions')),\n ([2], [3], [0], ('operand dimension sizes must either be 1, or be '\n 'equal to their corresponding dimensions in the target broadcast shape')),\n ([2, 2], [2, 2], [1, 0], ('broadcast_dimensions must be strictly increasing')),\n ]))\n def testBroadcastInDimShapeCheck(self, inshape, outshape, broadcast_dimensions, err_msg):\n rng = jtu.rand_default(self.rng())\n x = rng(inshape, np.float32)\n with self.assertRaisesRegex(TypeError, err_msg):\n lax.broadcast_in_dim(x, shape=outshape, broadcast_dimensions=broadcast_dimensions)\n\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_outshape={}_bcdims={}\".format(\n jtu.format_shape_dtype_string(inshape, dtype),\n outshape, broadcast_dimensions),\n \"inshape\": inshape, \"dtype\": dtype, \"outshape\": outshape,\n \"dimensions\": broadcast_dimensions}\n for inshape, outshape, broadcast_dimensions in [\n ([2], [2, 2], [0]),\n ([2], [2, 2], [1]),\n ([2], [2, 3], [0]),\n ([], [2, 3], []),\n ([1], [2, 3], [1]),\n ]\n for dtype in default_dtypes))\n def testBroadcastInDimAgainstNumpy(self, inshape, dtype, outshape, dimensions):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(inshape, dtype)]\n op = lambda x: lax.broadcast_in_dim(x, outshape, dimensions)\n numpy_op = lambda x: lax_reference.broadcast_in_dim(x, outshape, dimensions)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_dimensions={}\".format(\n jtu.format_shape_dtype_string(inshape, np.float32), dimensions),\n \"inshape\": inshape, \"dimensions\": dimensions, \"error_type\": error_type,\n \"err_msg\": err_msg}\n for inshape, dimensions, error_type, err_msg in [\n ((1, 2, 3), (0, 0), ValueError, 'dimensions are not unique'),\n ((1, 2, 3), (3,), ValueError, 'axis 3 is out of bounds'),\n ((1, 2, 3), (-4,), ValueError, 'axis -4 is out of bounds'),\n ((1, 2, 3), (1,), ValueError, 'cannot select an axis to squeeze out'),\n ((1, 2, 3), (None,), TypeError, 'cannot be interpreted as an integer'),\n ]))\n def testSqueezeShapeCheck(self, inshape, dimensions, error_type, err_msg):\n rng = jtu.rand_default(self.rng())\n x = rng(inshape, np.float32)\n with self.assertRaisesRegex(error_type, err_msg):\n lax.squeeze(x, dimensions=dimensions)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_dimensions={}\".format(\n jtu.format_shape_dtype_string(arg_shape, np.float32), dimensions),\n \"arg_shape\": arg_shape, \"dimensions\": dimensions}\n for arg_shape, dimensions in [\n [(1,), (0,)],\n [(1,), (-1,)],\n [(2, 1, 4), (1,)],\n [(2, 1, 3, 1), (1,)],\n [(2, 1, 3, 1), (1, 3)],\n [(2, 1, 3, 1), (3,)],\n ]))\n def testSqueeze(self, arg_shape, dimensions):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(arg_shape, np.float32)]\n op = lambda x: lax.squeeze(x, dimensions)\n numpy_op = lambda x: lax_reference.squeeze(x, dimensions)\n self._CompileAndCheck(op, args_maker)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n check_grads(op, args_maker(), 2, [\"fwd\", \"rev\"], eps=1.)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_outshape={}\".format(\n jtu.format_shape_dtype_string(arg_shape, dtype),\n jtu.format_shape_dtype_string(out_shape, dtype)),\n \"arg_shape\": arg_shape, \"out_shape\": out_shape, \"dtype\": dtype}\n for dtype in default_dtypes\n for arg_shape, out_shape in [\n [(3, 4), (12,)], [(2, 1, 4), (8,)], [(2, 2, 4), (2, 8)]\n ]))\n def testReshape(self, arg_shape, out_shape, dtype):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(arg_shape, dtype)]\n op = lambda x: lax.reshape(x, out_shape)\n self._CompileAndCheck(op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_outshape={}\".format(\n jtu.format_shape_dtype_string(arg_shape, dtype),\n jtu.format_shape_dtype_string(out_shape, dtype)),\n \"arg_shape\": arg_shape, \"out_shape\": out_shape, \"dtype\": dtype}\n for dtype in default_dtypes\n for arg_shape, out_shape in [\n [(3, 4), (12,)], [(2, 1, 4), (8,)], [(2, 2, 4), (2, 8)]\n ]))\n def testReshapeAgainstNumpy(self, arg_shape, out_shape, dtype):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(arg_shape, dtype)]\n op = lambda x: lax.reshape(x, out_shape)\n numpy_op = lambda x: lax_reference.reshape(x, out_shape)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n def testRoundRoundingMethods(self):\n x = np.array([-2.5, -1.5, -0.5, 0.5, 1.5, 2.5], dtype=np.float32)\n self.assertAllClose(lax.round(x, lax.RoundingMethod.AWAY_FROM_ZERO),\n np.array([-3, -2, -1, 1, 2, 3], dtype=np.float32))\n self.assertAllClose(lax.round(x, lax.RoundingMethod.TO_NEAREST_EVEN),\n np.array([-2, -2, 0, 0, 2, 2], dtype=np.float32))\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_pads={}\"\n .format(jtu.format_shape_dtype_string(shape, dtype), pads),\n \"shape\": shape, \"dtype\": dtype, \"pads\": pads}\n for dtype in default_dtypes\n for shape, pads in [\n ((0, 2), [(1, 2, 1), (0, 1, 0)]),\n ((2, 3), [(1, 2, 1), (0, 1, 0)]),\n ((2,), [(1, 2, 0)]),\n ((1, 2), [(1, 2, 0), (3, 4, 0)]),\n ((1, 2), [(0, 0, 0), (0, 0, 0)]),\n ((2,), [(1, 2, 3),]),\n ((3, 2), [(1, 2, 1), (3, 4, 2)]),\n ((2,), [(-1, 2, 0),]),\n ((4, 2), [(-1, -2, 0), (1, 2, 0)]),\n ((4, 2), [(-1, 2, 0), (1, 2, 2)]),\n ((5,), [(-1, -2, 2),]),\n ((4, 2), [(-1, -2, 1), (1, 2, 2)])\n ]))\n def testPad(self, shape, dtype, pads):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(shape, dtype)]\n fun = lambda operand: lax.pad(operand, np.array(0, dtype), pads)\n self._CompileAndCheck(fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_pads={}\"\n .format(jtu.format_shape_dtype_string(shape, dtype), pads),\n \"shape\": shape, \"dtype\": dtype, \"pads\": pads}\n for shape in [(2, 3)]\n for dtype in default_dtypes\n for pads in [\n [(0, 0, 0), (0, 0, 0)], # no padding\n [(1, 1, 0), (2, 2, 0)], # only positive edge padding\n [(1, 2, 1), (0, 1, 0)], # edge padding and interior padding\n [(0, 0, 0), (-1, -1, 0)], # negative padding\n [(0, 0, 0), (-2, -2, 4)], # add big dilation then remove from edges\n [(0, 0, 0), (-2, -3, 1)], # remove everything in one dimension\n ]))\n def testPadAgainstNumpy(self, shape, dtype, pads):\n rng = jtu.rand_small(self.rng())\n args_maker = lambda: [rng(shape, dtype)]\n op = lambda x: lax.pad(x, np.array(0, dtype), pads)\n numpy_op = lambda x: lax_reference.pad(x, np.array(0, dtype), pads)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n def testPadErrors(self):\n with self.assertRaisesRegex(ValueError, \"padding_config\"):\n lax.pad(np.zeros(2), 0., [(0, 1, 0), (0, 1, 0)])\n with self.assertRaisesRegex(ValueError, \"interior padding in padding_config must be nonnegative\"):\n lax.pad(np.zeros(2), 0., [(0, 1, -1)])\n with self.assertRaisesRegex(ValueError, \"Dimension size after padding is not at least 0\"):\n lax.pad(np.zeros(2), 0., [(-3, 0, 0)])\n with self.assertRaisesRegex(ValueError, \"Dimension size after padding is not at least 0\"):\n lax.pad(np.zeros(2), 0., [(-4, 0, 1)])\n\n def testReverse(self):\n rev = jax.jit(lambda operand: lax.rev(operand, dimensions))\n\n dimensions = []\n self.assertAllClose(np.array([0, 1, 2, 3]), rev(np.array([0, 1, 2, 3])),\n check_dtypes=False)\n\n dimensions = [0]\n self.assertAllClose(np.array([3, 2, 1]), rev(np.array([1, 2, 3])),\n check_dtypes=False)\n\n dimensions = [0, 1]\n self.assertAllClose(np.array([[6, 5, 4], [3, 2, 1]]),\n rev(np.array([[1, 2, 3], [4, 5, 6]])),\n check_dtypes=False)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_predshape={}_argshapes={}\".format(\n jtu.format_shape_dtype_string(pred_shape, np.bool_),\n jtu.format_shape_dtype_string(arg_shape, arg_dtype)),\n \"pred_shape\": pred_shape, \"arg_shape\": arg_shape, \"arg_dtype\": arg_dtype}\n for arg_shape in [(), (3,), (2, 3)]\n for pred_shape in ([(), arg_shape] if arg_shape else [()])\n for arg_dtype in default_dtypes))\n def testSelect(self, pred_shape, arg_shape, arg_dtype):\n rng = jtu.rand_default(self.rng())\n def args_maker():\n return [rng(pred_shape, np.bool_), rng(arg_shape, arg_dtype),\n rng(arg_shape, arg_dtype)]\n return self._CompileAndCheck(lax.select, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_predshape={}_argshapes={}\".format(\n jtu.format_shape_dtype_string(pred_shape, np.bool_),\n jtu.format_shape_dtype_string(arg_shape, arg_dtype)),\n \"pred_shape\": pred_shape, \"arg_shape\": arg_shape, \"arg_dtype\": arg_dtype}\n for arg_shape in [(), (3,), (2, 3)]\n for pred_shape in ([(), arg_shape] if arg_shape else [()])\n for arg_dtype in default_dtypes))\n def testSelectAgainstNumpy(self, pred_shape, arg_shape, arg_dtype):\n rng = jtu.rand_default(self.rng())\n def args_maker():\n return [rng(pred_shape, np.bool_), rng(arg_shape, arg_dtype),\n rng(arg_shape, arg_dtype)]\n return self._CheckAgainstNumpy(lax_reference.select, lax.select, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_shape={}_indices={}_limit_indices={}_strides={}\".format(\n jtu.format_shape_dtype_string(shape, dtype),\n indices, limit_indices, strides),\n \"shape\": shape, \"dtype\": dtype, \"starts\": indices,\n \"limits\": limit_indices, \"strides\": strides}\n for shape, indices, limit_indices, strides in [\n [(3,), (1,), (2,), None],\n [(7,), (4,), (7,), None],\n [(5,), (1,), (5,), (2,)],\n [(8,), (1,), (6,), (2,)],\n [(5, 3), (1, 1), (3, 2), None],\n [(5, 3), (1, 1), (3, 1), None],\n [(7, 5, 3), (4, 0, 1), (7, 1, 3), None],\n [(5, 3), (1, 1), (2, 1), (1, 1)],\n [(5, 3), (1, 1), (5, 3), (2, 1)],\n ]\n for dtype in default_dtypes))\n def testSlice(self, shape, dtype, starts, limits, strides):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(shape, dtype)]\n op = lambda x: lax.slice(x, starts, limits, strides)\n self._CompileAndCheck(op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_shape={}_indices={}_limit_indices={}_strides={}\".format(\n jtu.format_shape_dtype_string(shape, dtype),\n indices, limit_indices, strides),\n \"shape\": shape, \"dtype\": dtype, \"starts\": indices,\n \"limits\": limit_indices, \"strides\": strides}\n for shape, indices, limit_indices, strides in [\n [(3,), (1,), (2,), None],\n [(7,), (4,), (7,), None],\n [(5,), (1,), (5,), (2,)],\n [(8,), (1,), (6,), (2,)],\n [(5, 3), (1, 1), (3, 2), None],\n [(5, 3), (1, 1), (3, 1), None],\n [(7, 5, 3), (4, 0, 1), (7, 1, 3), None],\n [(5, 3), (1, 1), (2, 1), (1, 1)],\n [(5, 3), (1, 1), (5, 3), (2, 1)],\n ]\n for dtype in default_dtypes))\n def testSliceAgainstNumpy(self, shape, dtype, starts, limits, strides):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(shape, dtype)]\n op = lambda x: lax.slice(x, starts, limits, strides)\n numpy_op = lambda x: lax_reference.slice(x, starts, limits, strides)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_indices={}_size_indices={}\".format(\n jtu.format_shape_dtype_string(shape, dtype),\n indices, size_indices),\n \"shape\": shape, \"dtype\": dtype, \"indices\": indices,\n \"size_indices\": size_indices}\n for shape, indices, size_indices in [\n [(3,), np.array((1,)), (1,)],\n [(5, 3), (1, 1), (3, 1)],\n [(5, 3), np.array((1, 1)), (3, 1)],\n [(7, 5, 3), np.array((4, 1, 0)), (2, 0, 1)],\n ]\n for dtype in default_dtypes))\n def testDynamicSlice(self, shape, dtype, indices, size_indices):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(shape, dtype), np.array(indices)]\n op = lambda x, starts: lax.dynamic_slice(x, starts, size_indices)\n self._CompileAndCheck(op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_indices={}_size_indices={}\".format(\n jtu.format_shape_dtype_string(shape, dtype),\n indices, size_indices),\n \"shape\": shape, \"dtype\": dtype, \"indices\": indices,\n \"size_indices\": size_indices}\n for shape, indices, size_indices in [\n [(3,), (1,), (1,)],\n [(5, 3), (1, 1), (3, 1)],\n [(7, 5, 3), (4, 1, 0), (2, 0, 1)],\n ]\n for dtype in default_dtypes))\n def testDynamicSliceAgainstNumpy(self, shape, dtype, indices, size_indices):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(shape, dtype), np.array(indices)]\n op = lambda x, s: lax.dynamic_slice(x, s, size_indices)\n numpy_op = lambda x, s: lax_reference.dynamic_slice(x, s, size_indices)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n def testDynamicSliceInDim(self):\n # Regression test for mixed type problem in dynamic_slice_in_dim.\n rng = jtu.rand_default(self.rng())\n x = rng((6, 7), np.int32)\n np.testing.assert_equal(lax.dynamic_slice_in_dim(x, 2, 3), x[2:5])\n\n def testDynamicSliceArraySliceSizes(self):\n rng = jtu.rand_default(self.rng())\n x = rng((6, 7), np.int32)\n np.testing.assert_equal(lax.dynamic_slice(x, [2, 3], jnp.array([2, 2])),\n x[2:4, 3:5])\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_indices={}_update_shape={}\".format(\n jtu.format_shape_dtype_string(shape, dtype),\n indices, update_shape),\n \"shape\": shape, \"dtype\": dtype, \"indices\": indices,\n \"update_shape\": update_shape}\n for shape, indices, update_shape in [\n [(3,), (1,), (1,)],\n [(5, 3), (1, 1), (3, 1)],\n [(7, 5, 3), (4, 1, 0), (2, 0, 1)],\n ]\n for dtype in default_dtypes))\n def testDynamicUpdateSlice(self, shape, dtype, indices, update_shape):\n rng = jtu.rand_default(self.rng())\n\n def args_maker():\n return [rng(shape, dtype), rng(update_shape, dtype), np.array(indices)]\n\n self._CompileAndCheck(lax.dynamic_update_slice, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_indices={}_update_shape={}\".format(\n jtu.format_shape_dtype_string(shape, dtype),\n indices, update_shape),\n \"shape\": shape, \"dtype\": dtype, \"indices\": indices,\n \"update_shape\": update_shape}\n for shape, indices, update_shape in [\n [(3,), (1,), (1,)],\n [(5, 3), (1, 1), (3, 1)],\n [(7, 5, 3), (4, 1, 0), (2, 0, 1)],\n ]\n for dtype in default_dtypes))\n def testDynamicUpdateSliceAgainstNumpy(self, shape, dtype, indices,\n update_shape):\n rng = jtu.rand_default(self.rng())\n\n def args_maker():\n return [rng(shape, dtype), rng(update_shape, dtype), np.array(indices)]\n\n self._CheckAgainstNumpy(lax_reference.dynamic_update_slice,\n lax.dynamic_update_slice, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_perm={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), perm),\n \"shape\": shape, \"dtype\": dtype, \"perm\": perm}\n for shape, perm in [\n [(3, 4), (1, 0)],\n [(3, 4), (0, 1)],\n [(3, 4, 5), (2, 1, 0)],\n [(3, 4, 5), (1, 0, 2)],\n ]\n for dtype in default_dtypes))\n def testTranspose(self, shape, dtype, perm):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(shape, dtype)]\n op = lambda x: lax.transpose(x, perm)\n self._CompileAndCheck(op, args_maker)\n\n def testTransposeWithArrayPermutation(self):\n x = lax.transpose(np.ones((2, 3)), jnp.array([1, 0]))\n self.assertEqual((3, 2), x.shape)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_perm={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), perm),\n \"shape\": shape, \"dtype\": dtype, \"perm\": perm}\n for shape, perm in [\n [(3, 4), (1, 0)],\n [(3, 4), (0, 1)],\n [(3, 4, 5), (2, 1, 0)],\n [(3, 4, 5), (1, 0, 2)],\n ]\n for dtype in default_dtypes))\n def testTransposeAgainstNumpy(self, shape, dtype, perm):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(shape, dtype)]\n op = lambda x: lax.transpose(x, perm)\n numpy_op = lambda x: lax_reference.transpose(x, perm)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_op={}_inshape={}_reducedims={}_initval={}\"\n .format(op.__name__, jtu.format_shape_dtype_string(shape, dtype), dims,\n init_val),\n \"op\": op, \"init_val\": init_val, \"shape\": shape, \"dtype\": dtype, \"dims\": dims}\n for init_val, op, types in [\n (0, lax.add, default_dtypes),\n (1, lax.mul, default_dtypes),\n (0, lax.max, all_dtypes), # non-monoidal\n (-np.inf, lax.max, float_dtypes),\n (dtypes.iinfo(np.int32).min, lax.max, [np.int32]),\n (dtypes.iinfo(np.int64).min, lax.max, [np.int64]),\n (np.inf, lax.min, float_dtypes),\n (dtypes.iinfo(np.int32).max, lax.min, [np.int32]),\n (dtypes.iinfo(np.int64).max, lax.min, [np.int64]),\n (dtypes.iinfo(np.uint32).max, lax.min, [np.uint32]),\n (dtypes.iinfo(np.uint64).max, lax.min, [np.uint64]),\n ]\n for dtype in types\n for shape, dims in [\n [(3, 4, 5), (0,)], [(3, 4, 5), (1, 2)],\n [(3, 4, 5), (0, 2)], [(3, 4, 5), (0, 1, 2)]\n ]))\n def testReduce(self, op, init_val, shape, dtype, dims):\n rng_factory = (jtu.rand_default if dtypes.issubdtype(dtype, np.integer)\n else jtu.rand_small)\n rng = rng_factory(self.rng())\n init_val = np.asarray(init_val, dtype=dtype)\n fun = lambda operand, init_val: lax.reduce(operand, init_val, op, dims)\n args_maker = lambda: [rng(shape, dtype), init_val]\n self._CompileAndCheck(fun, args_maker)\n\n # we separately test the version that uses a concrete init_val because it\n # can hit different code paths\n fun = lambda operand: lax.reduce(operand, init_val, op, dims)\n args_maker = lambda: [rng(shape, dtype)]\n self._CompileAndCheck(fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_op={}.{}_arr_weak_type={}_init_weak_type={}\"\n .format(op_namespace.__name__, op, arr_weak_type, init_weak_type),\n \"op\": op, \"op_namespace\": op_namespace, \"arr_weak_type\": arr_weak_type, \"init_weak_type\": init_weak_type}\n for op in [\"add\", \"mul\"]\n for op_namespace in [lax, operator]\n for arr_weak_type in [True, False]\n for init_weak_type in [True, False]))\n def testReduceWeakType(self, op_namespace, op, arr_weak_type, init_weak_type):\n op = getattr(op_namespace, op)\n arr = lax._convert_element_type(np.arange(10), int, weak_type=arr_weak_type)\n init = lax._convert_element_type(1, int, weak_type=init_weak_type)\n fun = lambda arr, init: lax.reduce(arr, init, op, (0,))\n out = fun(arr, init)\n self.assertEqual(dtypes.is_weakly_typed(out), arr_weak_type and init_weak_type)\n out_jit = jax.jit(fun)(arr, init)\n self.assertEqual(dtypes.is_weakly_typed(out_jit), arr_weak_type and init_weak_type)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": (\"_op={}_shape={}_dims={}_strides={}_padding={}\"\n \"_basedilation={}_windowdilation={}\")\n .format(op.__name__, jtu.format_shape_dtype_string(shape, dtype),\n dims, strides, padding, base_dilation, window_dilation),\n \"op\": op, \"init_val\": init_val, \"dtype\": dtype, \"shape\": shape,\n \"dims\": dims, \"strides\": strides, \"padding\": padding,\n \"base_dilation\": base_dilation, \"window_dilation\": window_dilation}\n for init_val, op, dtypes in [\n (0, lax.add, [np.float32]),\n (-np.inf, lax.max, [np.float32]),\n (np.inf, lax.min, [np.float32]),\n ]\n for shape, dims, strides, padding, base_dilation, window_dilation in (\n itertools.chain(\n itertools.product(\n [(4, 6)],\n [(2, 1), (1, 2)],\n [(1, 1), (2, 1), (1, 2)],\n [\"VALID\", \"SAME\", [(0, 3), (1, 2)]],\n [(1, 1), (2, 3)],\n [(1, 1), (1, 2)]),\n itertools.product(\n [(3, 2, 4, 6)], [(1, 1, 2, 1), (2, 1, 2, 1)],\n [(1, 2, 2, 1), (1, 1, 1, 1)],\n [\"VALID\", \"SAME\", [(0, 1), (1, 0), (2, 3), (0, 2)]],\n [(1, 1, 1, 1), (2, 1, 3, 2)],\n [(1, 1, 1, 1), (1, 2, 2, 1)])))\n for dtype in dtypes))\n def testReduceWindow(self, op, init_val, dtype, shape, dims, strides, padding,\n base_dilation, window_dilation):\n rng = jtu.rand_small(self.rng())\n init_val = np.asarray(init_val, dtype=dtype)\n\n def fun(operand, init_val):\n return lax.reduce_window(operand, init_val, op, dims, strides, padding,\n base_dilation, window_dilation)\n\n def reference_fun(operand, init_val):\n return lax_reference.reduce_window(operand, init_val, op, dims, strides,\n padding, base_dilation)\n\n args_maker = lambda: [rng(shape, dtype), init_val]\n self._CompileAndCheck(fun, args_maker)\n if all(d == 1 for d in window_dilation):\n self._CheckAgainstNumpy(reference_fun, fun, args_maker)\n\n # we separately test the version that uses a concrete init_val because it\n # can hit different code paths\n def fun(operand):\n return lax.reduce_window(operand, init_val, op, dims, strides, padding,\n base_dilation, window_dilation)\n\n args_maker = lambda: [rng(shape, dtype)]\n self._CompileAndCheck(fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": (\"_shape={}_dims={}_strides={}_padding={}\"\n \"_basedilation={}_windowdilation={}\")\n .format(jtu.format_shape_dtype_string(shape, dtype),\n dims, strides, padding, base_dilation, window_dilation),\n \"dtype\": dtype, \"shape\": shape,\n \"dims\": dims, \"strides\": strides, \"padding\": padding,\n \"base_dilation\": base_dilation, \"window_dilation\": window_dilation}\n for dtype in [np.float32]\n for shape, dims, strides, padding, base_dilation, window_dilation in (\n itertools.chain(\n itertools.product(\n [(4, 6)],\n [(2, 1), (1, 2)],\n [(1, 1), (2, 1), (1, 2)],\n [\"VALID\", \"SAME\", [(0, 3), (1, 2)]],\n [(1, 1), (2, 3)],\n [(1, 1), (1, 2)]),\n itertools.product(\n [(3, 2, 4, 6)], [(1, 1, 2, 1), (2, 1, 2, 1)],\n [(1, 2, 2, 1), (1, 1, 1, 1)],\n [\"VALID\", \"SAME\", [(0, 1), (1, 0), (2, 3), (0, 2)]],\n [(1, 1, 1, 1), (2, 1, 3, 2)],\n [(1, 1, 1, 1), (1, 2, 2, 1)])))))\n # TODO(b/183233858): variadic reduce-window is not implemented on XLA:GPU\n @jtu.skip_on_devices(\"gpu\")\n def testReduceWindowVariadic(self, dtype, shape, dims, strides, padding,\n base_dilation, window_dilation):\n if (jtu.device_under_test() == \"tpu\" and\n any(d != 1 for d in window_dilation)):\n raise SkipTest(\"TPU support missing for arbitrary window dilation.\")\n rng = jtu.rand_small(self.rng())\n init_values = (np.asarray(0, dtype=dtype), np.array(-np.inf, dtype=dtype))\n\n def reducer(xs, ys):\n x1, x2 = xs\n y1, y2 = ys\n return (x1 + y1, lax.max(x2, y2))\n\n def fun(*operands):\n return lax.reduce_window(operands, init_values, reducer, dims, strides,\n padding, base_dilation, window_dilation)\n\n def reference_fun(*operands):\n return [\n lax_reference.reduce_window(operand, init_val, op, dims, strides,\n padding, base_dilation)\n for operand, init_val, op in zip(operands, init_values,\n [np.add, np.maximum])]\n\n args_maker = lambda: [rng(shape, dtype), rng(shape, dtype)]\n self._CompileAndCheck(fun, args_maker)\n if all(d == 1 for d in window_dilation):\n self._CheckAgainstNumpy(reference_fun, fun, args_maker)\n\n\n def testReduceWindowFailures(self):\n def empty_window_test():\n return lax.reduce_window(np.ones((1,)), 0., lax.add, padding='VALID',\n window_dimensions=(0,), window_strides=(1,))\n\n def zero_stride_test():\n return lax.reduce_window(np.ones((1,)), 0., lax.add, padding='VALID',\n window_dimensions=(1,), window_strides=(0,))\n\n for failure_fun in [empty_window_test, zero_stride_test]:\n with self.assertRaisesRegex(TypeError, \"must have every element be\"):\n failure_fun()\n\n with self.assertRaisesRegex(\n ValueError,\n \"reduce_window output must have the same tree structure as the \"\n \"operands.*\"):\n return lax.reduce_window(\n np.ones((1,)), 0., lambda x, y: [x + y],\n padding='VALID', window_dimensions=(1,), window_strides=(1,))\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": (f\"_shape={shape}_windowdimensions={window_dimensions}\"\n f\"_basedilation={base_dilation}_windowdilation=\"\n f\"{window_dilation}\"),\n \"shape\": shape, \"window_dimensions\": window_dimensions,\n \"base_dilation\": base_dilation, \"window_dilation\": window_dilation}\n for shape, window_dimensions, base_dilation, window_dilation in (\n itertools.chain(\n itertools.product(\n [(4, 6)],\n [(1, 1), (3, 4)],\n [(1, 1), (1, 2), (2, 13), (40, 60)],\n [(1, 1), (1, 2), (2, 13), (40, 60)]),\n itertools.product(\n [(3, 2, 4, 6)],\n [(1, 1, 1, 1), (2, 1, 2, 1)],\n [(1, 1, 1, 1), (1, 2, 2, 1), (30, 40, 3, 2)],\n [(1, 1, 1, 1), (1, 2, 2, 1), (30, 40, 3, 2)])))))\n def testReduceWindowShapeDilation(self, shape, window_dimensions,\n base_dilation, window_dilation):\n operand, padding, strides = np.ones(shape), 'SAME', (1,) * len(shape)\n result = lax.reduce_window(operand, 0., lax.add, padding=padding,\n window_strides=strides,\n window_dimensions=window_dimensions)\n # With a stride of 1 in each direction and a padding of 'SAME', the\n # shape of the input should be equal to the shape of the result according\n # to https://www.tensorflow.org/xla/operation_semantics#reducewindow.\n self.assertEqual(shape, result.shape)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_op={}_shape={}_axis={}_reverse={}\"\n .format(op.__name__, jtu.format_shape_dtype_string(shape, dtype), axis,\n reverse),\n \"op\": op, \"np_op\": np_op, \"shape\": shape, \"dtype\": dtype,\n \"axis\": axis, \"reverse\": reverse}\n for op, np_op, types in [\n (lax.cumsum, np.cumsum, default_dtypes),\n (lax.cumprod, np.cumprod, default_dtypes),\n (lax.cummax, np.maximum.accumulate, default_dtypes),\n (lax.cummin, np.minimum.accumulate, default_dtypes),\n ]\n for dtype in types\n for shape in [[10], [3, 4, 5]]\n for axis in range(len(shape))\n for reverse in [False, True]))\n def testCumulativeReduce(self, op, np_op, shape, dtype, axis, reverse):\n rng_factory = (jtu.rand_default if dtypes.issubdtype(dtype, np.integer)\n else jtu.rand_small)\n rng = rng_factory(self.rng())\n fun = partial(op, axis=axis, reverse=reverse)\n def np_fun(x):\n if reverse:\n return np.flip(np_op(np.flip(x, axis), axis=axis, dtype=dtype), axis)\n else:\n return np_op(x, axis=axis, dtype=dtype)\n args_maker = lambda: [rng(shape, dtype)]\n self._CompileAndCheck(fun, args_maker)\n self._CheckAgainstNumpy(np_fun, fun, args_maker)\n\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_out_dtype={}\".format(\n jtu.format_shape_dtype_string(shape, dtype),\n jtu.format_shape_dtype_string(shape, out_dtype)),\n \"shape\": shape, \"dtype\": dtype, \"out_dtype\": out_dtype}\n for shape in [(), (3,), (3, 4)]\n for dtype in float_dtypes\n for out_dtype in float_dtypes))\n def testReducePrecision(self, shape, dtype, out_dtype):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(shape, dtype)]\n info = dtypes.finfo(out_dtype)\n fun = lambda x: lax.reduce_precision(x, info.nexp, info.nmant)\n np_fun = lambda x: np.asarray(x).astype(out_dtype).astype(dtype)\n self._CheckAgainstNumpy(np_fun, fun, args_maker)\n self._CompileAndCheck(fun, args_maker)\n\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_axis={}_isstable={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), axis, is_stable),\n \"shape\": shape, \"dtype\": dtype, \"axis\": axis, \"is_stable\": is_stable}\n for dtype in all_dtypes\n for shape in [(5,), (5, 7)]\n for axis in [-1, len(shape) - 1]\n for is_stable in [False, True]))\n def testSort(self, shape, dtype, axis, is_stable):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(shape, dtype)]\n fun = lambda x: lax.sort(x, dimension=axis, is_stable=is_stable)\n self._CompileAndCheck(fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": f\"_dtype={dtype.__name__}\", \"dtype\": dtype}\n for dtype in float_dtypes))\n def testSortFloatSpecialValues(self, dtype):\n # Test confirms that\n # - NaNs are sorted to the end, regardless of representation\n # - sign bit of 0.0 is ignored\n x = jnp.array([-np.inf, 0.0, -0.0, np.inf, np.nan, -np.nan], dtype=dtype)\n index = lax.iota(dtypes.int_, x.size)\n argsort = lambda x: lax.sort_key_val(x, lax.iota(dtypes.int_, x.size), is_stable=True)[1]\n self.assertArraysEqual(argsort(x), index)\n self.assertArraysEqual(jax.jit(argsort)(x), index)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_axis={}_isstable={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), axis, is_stable),\n \"shape\": shape, \"dtype\": dtype, \"axis\": axis, \"is_stable\": is_stable}\n for dtype in all_dtypes\n for shape in [(5,), (5, 7)]\n for axis in [-1, len(shape) - 1]\n for is_stable in [False, True]))\n def testSortAgainstNumpy(self, shape, dtype, axis, is_stable):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(shape, dtype)]\n op = lambda x: lax.sort(x, dimension=axis, is_stable=is_stable)\n def numpy_op(x):\n if is_stable:\n return lax_reference.sort(x, axis, kind='stable')\n else:\n return lax_reference.sort(x, axis)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_keyshape={}_valshape={}_axis={}_isstable={}\".format(\n jtu.format_shape_dtype_string(shape, key_dtype),\n jtu.format_shape_dtype_string(shape, val_dtype),\n axis, is_stable),\n \"shape\": shape, \"key_dtype\": key_dtype, \"val_dtype\": val_dtype,\n \"axis\": axis, \"is_stable\": is_stable}\n for key_dtype in float_dtypes + complex_dtypes + int_dtypes + uint_dtypes\n for val_dtype in [np.float32, np.int32, np.uint32]\n for shape in [(3,), (5, 3)]\n for axis in [-1, len(shape) - 1]\n for is_stable in [False, True]))\n def testSortKeyVal(self, shape, key_dtype, val_dtype, axis, is_stable):\n if (np.issubdtype(key_dtype, np.complexfloating) and\n jtu.device_under_test() == \"cpu\"):\n raise SkipTest(\"Complex-valued sort not implemented\")\n rng = jtu.rand_default(self.rng())\n # This test relies on the property that wherever keys are tied, values are\n # too, since we don't guarantee the same ordering of values with equal keys.\n # To avoid that case, we generate unique keys (globally in the key array).\n def args_maker():\n flat_keys = np.arange(prod(shape), dtype=key_dtype)\n keys = self.rng().permutation(flat_keys).reshape(shape)\n values = rng(shape, val_dtype)\n return keys, values\n\n fun = lambda keys, values: lax.sort_key_val(keys, values, axis, is_stable)\n self._CompileAndCheck(fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_num_keys={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), num_keys),\n \"shape\": shape, \"dtype\": dtype, \"num_keys\": num_keys}\n for dtype in all_dtypes\n for shape in [(3, 5,), (4, 3)]\n for num_keys in range(1, shape[0] + 1)))\n def testSortNumKeys(self, shape, dtype, num_keys):\n rng = jtu.rand_default(self.rng())\n args_maker = lambda: [rng(shape, dtype)]\n lax_fun = lambda x: lax.sort(tuple(x), num_keys=num_keys)\n numpy_fun = lambda x: tuple(x[:, np.lexsort(x[:num_keys][::-1])])\n # self._CompileAndCheck(lax_fun, args_maker)\n self._CheckAgainstNumpy(numpy_fun, lax_fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_keyshape={}_valshape={}_axis={}\".format(\n jtu.format_shape_dtype_string(shape, key_dtype),\n jtu.format_shape_dtype_string(shape, val_dtype),\n axis),\n \"shape\": shape, \"key_dtype\": key_dtype, \"val_dtype\": val_dtype,\n \"axis\": axis}\n for key_dtype in float_dtypes + complex_dtypes + int_dtypes + uint_dtypes\n for val_dtype in [np.float32, np.int32, np.uint32]\n for shape in [(3,), (5, 3)]\n for axis in [-1, len(shape) - 1]))\n def testSortKeyValAgainstNumpy(self, shape, key_dtype, val_dtype, axis):\n if (np.issubdtype(key_dtype, np.complexfloating) and\n jtu.device_under_test() == \"cpu\"):\n raise SkipTest(\"Complex-valued sort not implemented\")\n rng = jtu.rand_default(self.rng())\n # This test relies on the property that wherever keys are tied, values are\n # too, since we don't guarantee the same ordering of values with equal keys.\n # To avoid that case, we generate unique keys (globally in the key array).\n def args_maker():\n flat_keys = np.arange(prod(shape), dtype=key_dtype)\n keys = self.rng().permutation(flat_keys).reshape(shape)\n values = rng(shape, val_dtype)\n return keys, values\n\n op = lambda ks, vs: lax.sort_key_val(ks, vs, axis)\n numpy_op = lambda ks, vs: lax_reference.sort_key_val(ks, vs, axis)\n self._CheckAgainstNumpy(numpy_op, op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_k={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), k),\n \"shape\": shape, \"dtype\": dtype, \"k\": k}\n for dtype in [np.float32, np.int32, np.uint32]\n for shape in [(3,), (5, 3)]\n for k in [1, 3]))\n def testTopK(self, shape, dtype, k):\n def args_maker():\n flat_values = np.arange(prod(shape), dtype=dtype)\n values = self.rng().permutation(flat_values).reshape(shape)\n return [values]\n def reference_top_k(x):\n bcast_idxs = np.broadcast_to(np.arange(shape[-1], dtype=np.int32), shape)\n sorted_vals, sorted_idxs = lax_reference.sort_key_val(x, bcast_idxs)\n return sorted_vals[..., :-k-1:-1], sorted_idxs[..., :-k-1:-1]\n op = lambda vs: lax.top_k(vs, k=k)\n self._CheckAgainstNumpy(op, reference_top_k, args_maker)\n self._CompileAndCheck(op, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_lhs_shape={}_rhs_shape={}\"\n .format(jtu.format_shape_dtype_string(lhs_shape, dtype),\n jtu.format_shape_dtype_string(rhs_shape, dtype)),\n \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype}\n for lhs_shape, rhs_shape in [((3, 2), (2, 4)),\n ((5, 3, 2), (5, 2, 4)),\n ((1, 2, 2, 3), (1, 2, 3, 1))]\n for dtype in float_dtypes))\n def testBatchMatMul(self, lhs_shape, rhs_shape, dtype):\n rng = jtu.rand_small(self.rng())\n arg_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n self._CompileAndCheck(lax.batch_matmul, arg_maker)\n\n def testCollapse(self):\n\n @jax.jit\n def collapse_first_two(x):\n return lax.collapse(x, 0, 2)\n\n self.assertEqual((6,), collapse_first_two(np.zeros((2, 3))).shape)\n self.assertEqual((6, 4), collapse_first_two(np.zeros((2, 3, 4))).shape)\n self.assertEqual((2, 3, 4),\n collapse_first_two(np.zeros((1, 2, 3, 4))).shape)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_idxs={}_axes={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), idxs, axes),\n \"shape\": shape, \"dtype\": dtype, \"idxs\": idxs, \"axes\": axes}\n for dtype in all_dtypes\n for shape, idxs, axes in [\n [(3, 4, 5), (np.array([0, 2, 1]),), (0,)],\n [(3, 4, 5), (np.array([-1, -2]),), (0,)],\n [(3, 4, 5), (np.array([0, 2]), np.array([1, 3])), (0, 1)],\n [(3, 4, 5), (np.array([0, 2]), np.array([1, 3])), (0, 2)],\n ]))\n def testIndexTake(self, shape, dtype, idxs, axes):\n rng = jtu.rand_default(self.rng())\n rand_idxs = lambda: tuple(rng(e.shape, e.dtype) for e in idxs)\n args_maker = lambda: [rng(shape, dtype), rand_idxs()]\n fun = lambda src, idxs: lax.index_take(src, idxs, axes)\n self._CompileAndCheck(fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_idxs={}_dnums={}_slice_sizes={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), idxs, dnums,\n slice_sizes),\n \"shape\": shape, \"dtype\": dtype, \"idxs\": idxs, \"dnums\": dnums,\n \"slice_sizes\": slice_sizes}\n for dtype in all_dtypes\n for shape, idxs, dnums, slice_sizes in [\n ((5,), np.array([[0], [2]]), lax.GatherDimensionNumbers(\n offset_dims=(), collapsed_slice_dims=(0,), start_index_map=(0,)),\n (1,)),\n ((10,), np.array([[0], [0], [0]]), lax.GatherDimensionNumbers(\n offset_dims=(1,), collapsed_slice_dims=(), start_index_map=(0,)),\n (2,)),\n ((10, 5,), np.array([[0], [2], [1]]), lax.GatherDimensionNumbers(\n offset_dims=(1,), collapsed_slice_dims=(0,), start_index_map=(0,)),\n (1, 3)),\n ((10, 5), np.array([[0, 2], [1, 0]]), lax.GatherDimensionNumbers(\n offset_dims=(1,), collapsed_slice_dims=(0,), start_index_map=(0, 1)),\n (1, 3)),\n ]))\n def testGather(self, shape, dtype, idxs, dnums, slice_sizes):\n rng = jtu.rand_default(self.rng())\n rng_idx = jtu.rand_int(self.rng(), high=max(shape))\n rand_idxs = lambda: rng_idx(idxs.shape, idxs.dtype)\n args_maker = lambda: [rng(shape, dtype), rand_idxs()]\n fun = partial(lax.gather, dimension_numbers=dnums, slice_sizes=slice_sizes)\n self._CompileAndCheck(fun, args_maker)\n\n # These tests are adapted from the corresponding tests in\n # tensorflow/compiler/xla/service/shape_inference_test.cc with slight\n # variations to account for the implicit setting of index_vector_dim in JAX.\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": f\"_{testcase_name}\", \"operand_shape\": operand_shape,\n \"indices_shape\": indices_shape,\n \"dimension_numbers\": lax.GatherDimensionNumbers(\n offset_dims=offset_dims,\n collapsed_slice_dims=collapsed_slice_dims,\n start_index_map=start_index_map),\n \"slice_sizes\": slice_sizes, \"msg\": msg}\n for (testcase_name, operand_shape, indices_shape, offset_dims,\n collapsed_slice_dims, start_index_map, slice_sizes, msg) in [\n (\"NonAscendingWindowIndices\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 1),\n (4, 5, 6, 8, 7), (), (0, 1, 2, 3, 4), (10, 9, 8, 7, 6),\n \"offset_dims in gather op must be sorted\"),\n (\"RepeatedWindowIndices\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 1),\n (4, 5, 6, 7, 7), (), (0, 1, 2, 3, 4), (10, 9, 8, 7, 6),\n \"offset_dims in gather op must not repeat\"),\n (\"WindowIndexOutOfBounds\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 1),\n (4, 5, 100, 101, 102), (), (0, 1, 2, 3, 4), (10, 9, 8, 7, 6),\n \"Offset dimension 2 in gather op is out of bounds\"),\n (\"WindowIndexBarelyOutOfBounds\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 1),\n (4, 5, 6, 7, 9), (), (0, 1, 2, 3, 4), (10, 9, 8, 7, 6),\n \"Offset dimension 4 in gather op is out of bounds\"),\n (\"MismatchingElidedWindowDims\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 5),\n (4, 5, 6, 7, 8), (4,), (0, 1, 2, 3, 4), (10, 9, 8, 7, 6),\n (\"All components of the offset index in a gather op must either be a \"\n \"offset dimension or explicitly collapsed\")),\n (\"OutOfBoundsWindowToInputMapping\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 5),\n (4, 5, 6, 7, 8), (0, 1, 2, 3, 19), (0, 1, 2, 3, 4), (10, 9, 8, 7, 6),\n \"Invalid collapsed_slice_dims set in gather op; valid range is\"),\n (\"RepeatedWindowToInputMapping\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 5),\n (4, 5, 6, 7, 8), (0, 1, 2, 3, 3), (0, 1, 2, 3, 4), (10, 9, 8, 7, 6),\n \"collapsed_slice_dims in gather op must not repeat\"),\n (\"MismatchingGatherToInputMapping\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 5),\n (4, 5, 6, 7, 8), (), (0, 1, 2, 3), (10, 9, 8, 7, 6),\n (\"Gather op has 4 elements in start_index_map and the bound of \"\n \"dimension index_vector_dim=4 of indices is 5. These two \"\n \"numbers must be equal.\")),\n (\"OutOfBoundsGatherToInputMapping\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 5),\n (4, 5, 6, 7, 8), (), (0, 1, 2, 3, 7), (10, 9, 8, 7, 6),\n \"Invalid start_index_map\"),\n (\"RepeatedGatherToInputMapping\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 5),\n (4, 5, 6, 7, 8), (), (0, 1, 2, 3, 3), (10, 9, 8, 7, 6),\n \"start_index_map in gather op must not repeat\"),\n (\"NonAscendingElidedWindowDims\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 5),\n (4, 5, 6, 7, 8), (2, 1), (0, 1, 2, 3, 4), (10, 9, 8, 7, 6),\n \"collapsed_slice_dims in gather op must be sorted\"),\n (\"WindowBoundsTooLarge\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 5),\n (4, 5, 6, 7), (2,), (0, 1, 2, 3, 4), (10, 9, 8, 100, 6),\n \"Slice size at index 3 in gather op is out of range\"),\n (\"MismatchingNumberOfWindowBounds\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 5),\n (4, 5, 6, 7), (), (0, 1, 2, 3, 4), (10, 9, 8, 7),\n \"Gather op must have one slice size for every input dimension\"),\n (\"WindowBoundsNot1ForElidedDim\", (10, 9, 8, 7, 6), (5, 4, 3, 2, 5),\n (4, 5, 6, 7), (1,), (0, 1, 2, 3, 4), (10, 9, 8, 7, 6),\n (\"Gather op can only collapse slice dims with bound 1, but bound \"\n \"is 9 for index 1 at position 0.\"))\n ]\n ))\n def testGatherShapeCheckingRule(self, operand_shape, indices_shape,\n dimension_numbers, slice_sizes, msg):\n operand = np.ones(operand_shape, dtype=np.int32)\n indices = np.ones(indices_shape, dtype=np.int32)\n\n with self.assertRaisesRegex(TypeError, msg):\n lax.gather(operand, indices, dimension_numbers, slice_sizes)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_idxs={}_update={}_dnums={}\".format(\n jtu.format_shape_dtype_string(arg_shape, dtype),\n idxs, update_shape, dnums),\n \"arg_shape\": arg_shape, \"dtype\": dtype, \"idxs\": idxs,\n \"update_shape\": update_shape, \"dnums\": dnums}\n for dtype in inexact_dtypes\n for arg_shape, idxs, update_shape, dnums in [\n ((5,), np.array([[0], [2]]), (2,), lax.ScatterDimensionNumbers(\n update_window_dims=(), inserted_window_dims=(0,),\n scatter_dims_to_operand_dims=(0,))),\n ((10,), np.array([[0], [0], [0]]), (3, 2), lax.ScatterDimensionNumbers(\n update_window_dims=(1,), inserted_window_dims=(),\n scatter_dims_to_operand_dims=(0,))),\n ((10, 5,), np.array([[0], [2], [1]]), (3, 3), lax.ScatterDimensionNumbers(\n update_window_dims=(1,), inserted_window_dims=(0,),\n scatter_dims_to_operand_dims=(0,))),\n ]))\n def testScatterAdd(self, arg_shape, dtype, idxs, update_shape, dnums):\n rng = jtu.rand_default(self.rng())\n rng_idx = jtu.rand_int(self.rng(), high=max(arg_shape))\n rand_idxs = lambda: rng_idx(idxs.shape, idxs.dtype)\n args_maker = lambda: [rng(arg_shape, dtype), rand_idxs(),\n rng(update_shape, dtype)]\n fun = partial(lax.scatter_add, dimension_numbers=dnums)\n self._CompileAndCheck(fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_idxs={}_update={}_dnums={}\".format(\n jtu.format_shape_dtype_string(arg_shape, dtype),\n idxs, update_shape, dnums),\n \"arg_shape\": arg_shape, \"dtype\": dtype, \"idxs\": idxs,\n \"update_shape\": update_shape, \"dnums\": dnums}\n for dtype in float_dtypes\n for arg_shape, idxs, update_shape, dnums in [\n ((5,), np.array([[0], [2]]), (2,), lax.ScatterDimensionNumbers(\n update_window_dims=(), inserted_window_dims=(0,),\n scatter_dims_to_operand_dims=(0,))),\n ((10,), np.array([[0], [0], [0]]), (3, 2), lax.ScatterDimensionNumbers(\n update_window_dims=(1,), inserted_window_dims=(),\n scatter_dims_to_operand_dims=(0,))),\n ((10, 5,), np.array([[0], [2], [1]]), (3, 3), lax.ScatterDimensionNumbers(\n update_window_dims=(1,), inserted_window_dims=(0,),\n scatter_dims_to_operand_dims=(0,))),\n ]))\n def testScatterMin(self, arg_shape, dtype, idxs, update_shape, dnums):\n rng = jtu.rand_default(self.rng())\n rng_idx = jtu.rand_int(self.rng(), high=max(arg_shape))\n rand_idxs = lambda: rng_idx(idxs.shape, idxs.dtype)\n args_maker = lambda: [rng(arg_shape, dtype), rand_idxs(),\n rng(update_shape, dtype)]\n fun = partial(lax.scatter_min, dimension_numbers=dnums)\n self._CompileAndCheck(fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_idxs={}_update={}_dnums={}\".format(\n jtu.format_shape_dtype_string(arg_shape, dtype),\n idxs, update_shape, dnums),\n \"arg_shape\": arg_shape, \"dtype\": dtype, \"idxs\": idxs,\n \"update_shape\": update_shape, \"dnums\": dnums}\n for dtype in float_dtypes\n for arg_shape, idxs, update_shape, dnums in [\n ((5,), np.array([[0], [2]]), (2,), lax.ScatterDimensionNumbers(\n update_window_dims=(), inserted_window_dims=(0,),\n scatter_dims_to_operand_dims=(0,))),\n ((10,), np.array([[0], [0], [0]]), (3, 2), lax.ScatterDimensionNumbers(\n update_window_dims=(1,), inserted_window_dims=(),\n scatter_dims_to_operand_dims=(0,))),\n ((10, 5,), np.array([[0], [2], [1]]), (3, 3), lax.ScatterDimensionNumbers(\n update_window_dims=(1,), inserted_window_dims=(0,),\n scatter_dims_to_operand_dims=(0,))),\n ]))\n def testScatterMax(self, arg_shape, dtype, idxs, update_shape, dnums):\n rng = jtu.rand_default(self.rng())\n rng_idx = jtu.rand_int(self.rng(), high=max(arg_shape))\n rand_idxs = lambda: rng_idx(idxs.shape, idxs.dtype)\n args_maker = lambda: [rng(arg_shape, dtype), rand_idxs(),\n rng(update_shape, dtype)]\n fun = partial(lax.scatter_max, dimension_numbers=dnums)\n self._CompileAndCheck(fun, args_maker)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_idxs={}_update={}_dnums={}\".format(\n jtu.format_shape_dtype_string(arg_shape, dtype),\n idxs, update_shape, dnums),\n \"arg_shape\": arg_shape, \"dtype\": dtype, \"idxs\": idxs,\n \"update_shape\": update_shape, \"dnums\": dnums}\n for dtype in float_dtypes\n for arg_shape, idxs, update_shape, dnums in [\n ((5,), np.array([[0], [2]]), (2,), lax.ScatterDimensionNumbers(\n update_window_dims=(), inserted_window_dims=(0,),\n scatter_dims_to_operand_dims=(0,))),\n ((10,), np.array([[0], [0], [0]]), (3, 2), lax.ScatterDimensionNumbers(\n update_window_dims=(1,), inserted_window_dims=(),\n scatter_dims_to_operand_dims=(0,))),\n ((10, 5,), np.array([[0], [2], [1]]), (3, 3), lax.ScatterDimensionNumbers(\n update_window_dims=(1,), inserted_window_dims=(0,),\n scatter_dims_to_operand_dims=(0,))),\n ]))\n def testScatter(self, arg_shape, dtype, idxs, update_shape, dnums):\n rng = jtu.rand_default(self.rng())\n rng_idx = jtu.rand_int(self.rng(), high=max(arg_shape))\n rand_idxs = lambda: rng_idx(idxs.shape, idxs.dtype)\n args_maker = lambda: [rng(arg_shape, dtype), rand_idxs(),\n rng(update_shape, dtype)]\n fun = partial(lax.scatter, dimension_numbers=dnums)\n self._CompileAndCheck(fun, args_maker)\n\n # These tests are adapted from the corresponding tests in\n # tensorflow/compiler/xla/service/shape_inference_test.cc with slight\n # variations to account for the implicit setting of index_vector_dim in JAX.\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": f\"_{testcase_name}\", \"operand_shape\": operand_shape,\n \"indices\": indices, \"update_shape\": update_shape,\n \"dimension_numbers\": lax.ScatterDimensionNumbers(\n update_window_dims=update_window_dims,\n inserted_window_dims=inserted_window_dims,\n scatter_dims_to_operand_dims=scatter_dims_to_operand_dims),\n \"msg\": msg}\n for (testcase_name, operand_shape, indices, update_shape,\n update_window_dims, inserted_window_dims,\n scatter_dims_to_operand_dims, msg) in [\n (\"ScatterWithUpdatesBiggerThanInput\", (64, 48), np.zeros((32, 1)),\n (65, 32), (0,), (1,), (1,), \"Bounds of the window dimensions\"),\n (\"ScatterWithUpdatesBiggerThanInputV2\", (64, 48),\n np.zeros((32, 1)), (32, 49), (1,), (0,), (1,),\n \"Bounds of the window dimensions\"),\n (\"ScatterWithUpdatesNotMatchingIndices\", (64, 48),\n np.zeros((32, 1)), (64, 31), (0,), (1,), (1,),\n \"Bounds of the scatter dimensions\"),\n (\"ScatterWithUpdatesNotMatchingIndicesV2\", (64, 48),\n np.zeros((32, 1)), (31, 48), (1,), (0,), (1,),\n \"Bounds of the scatter dimensions\"),\n (\"ScatterNdWithUpdatesBiggerThanInput\", (64, 48),\n np.zeros((10, 9, 8, 7, 1)), (10, 9, 8, 7, 65), (4,), (1,),\n (0,), \"Bounds of the window dimensions\"),\n (\"ScatterNdWithUpdatesNotMatchingIndices\", (64, 48),\n np.zeros((10, 9, 8, 7, 1)), (9, 9, 8, 7, 64), (4,), (1,), (0,),\n \"Bounds of the scatter dimensions\"),\n (\"InvalidUpdates\", (50, 49, 48, 47, 46),\n np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4, 1),\n (4, 5, 6), (1, 2), (0, 1, 2, 3, 4),\n \"Updates tensor must be of rank 7; got 8.\"),\n (\"NonAscendingUpdateWindowDims\", (6, 5, 4, 3, 2),\n np.zeros((5, 4, 3, 2, 1)), (10, 9, 8, 7, 6, 5, 4, 3, 2),\n (4, 5, 6, 8, 7), (), (0, 1, 2, 3, 4),\n \"update_window_dims in scatter op must be sorted\"),\n (\"RepeatedUpdateWindowDims\", (6, 5, 4, 3, 2),\n np.zeros((5, 4, 3, 2, 1)), (10, 9, 8, 7, 6, 5, 4, 3, 2),\n (4, 5, 6, 7, 7), (), (0, 1, 2, 3, 4),\n \"update_window_dims in scatter op must not repeat\"),\n (\"OutOfBoundsUpdateWindowDims\", (6, 5, 4, 3, 2),\n np.zeros((5, 4, 3, 2, 1)), (10, 9, 8, 7, 6, 5, 4, 3, 2),\n (4, 5, 6, 7, 9), (), (0, 1, 2, 3, 4),\n \"Invalid update_window_dims set in scatter op\"),\n (\"NonAscendingInsertedWindowDims\", (50, 49, 48, 47, 46),\n np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n (4, 5, 6), (2, 1), (0, 1, 2, 3, 4),\n \"inserted_window_dims in scatter op must be sorted\"),\n (\"RepeatedInsertedWindowDims\", (50, 49, 48, 47, 46),\n np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n (4, 5, 6), (1, 1), (0, 1, 2, 3, 4),\n \"inserted_window_dims in scatter op must not repeat\"),\n (\"OutOfBoundsInsertedWindowDims\", (50, 49, 48, 47, 46),\n np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n (4, 5, 6), (1, 5), (0, 1, 2, 3, 4),\n \"Invalid inserted_window_dims set in scatter op\"),\n (\"MismatchingScatterDimsToOperandDims\", (50, 49, 48, 47, 46),\n np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n (4, 5, 6), (1, 2), (0, 1, 2, 3),\n (\"Scatter op has 4 elements in scatter_dims_to_operand_dims and \"\n \"the bound of dimension index_vector_dim=4 of indices \"\n \"is 5. These two numbers must be equal\")),\n (\"OutOfBoundsScatterDimsToOperandDims\", (50, 49, 48, 47, 46),\n np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n (4, 5, 6), (1, 2), (0, 1, 2, 3, 10),\n \"Invalid scatter_dims_to_operand_dims mapping\"),\n (\"RepeatedValuesInScatterDimsToOperandDims\", (50, 49, 48, 47, 46),\n np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n (4, 5, 6), (1, 2), (0, 1, 2, 2, 3),\n \"scatter_dims_to_operand_dims in scatter op must not repeat\"),\n (\"InsufficientWindowDims\", (50, 49, 48, 47, 46),\n np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n (4, 5, 6), (1,), (0, 1, 2, 3),\n (\"Scatter op has window of size 4; doesn't match operand of \"\n \"rank 5.\"))\n ]\n ))\n def testScatterShapeCheckingRule(self, operand_shape, indices,\n update_shape, dimension_numbers, msg):\n\n def f(x, y):\n operand = lax.broadcast(x, operand_shape)\n updates = lax.broadcast(y, update_shape)\n return lax.scatter(operand, indices, updates, dimension_numbers)\n with self.assertRaisesRegex(TypeError, msg):\n jax.eval_shape(f, np.int32(1), np.int32(1))\n\n def testIssue831(self):\n # Tests the DeviceTuple constant handler\n def f(x):\n g = lambda *args: args[1]\n return jax.jit(lax.fori_loop, static_argnums=(2,))( 0, 10, g, x)\n\n jax.jit(f)(1.) # doesn't crash\n\n def testReshapeWithUnusualShapes(self):\n ans = lax.reshape(np.ones((3,), np.float32), (lax.add(1, 2), 1))\n self.assertAllClose(ans, np.ones((3, 1), np.float32))\n\n self.assertRaisesRegex(\n TypeError,\n \"Shapes must be 1D sequences of concrete values of integer type.*\",\n lambda: lax.reshape(np.ones(3,), (np.array([3, 1]),)))\n\n self.assertRaisesRegex(\n TypeError,\n \"Shapes must be 1D sequences of concrete values of integer type.*\",\n lambda: lax.reshape(np.ones(3,), (1.5, 2.0)))\n\n def testDynamicSliceTypeErrors(self):\n self.assertRaisesRegex(\n TypeError,\n \"index arguments to dynamic_slice must be integers of the same type\",\n lambda: lax.dynamic_slice(np.ones((3, 4), dtype=np.float32),\n (np.int32(1), np.int16(2)), (2, 2)))\n\n def testDynamicUpdateSliceTypeErrors(self):\n self.assertRaisesRegex(\n TypeError,\n \"index arguments to dynamic_update_slice must be integers of the same \"\n \"type\",\n lambda: lax.dynamic_update_slice(np.ones((3, 4), dtype=np.float32),\n np.zeros((2, 2), dtype=np.float32),\n (np.int32(1), np.int16(2))))\n\n def test_tie_in_error(self):\n raise SkipTest(\"test no longer needed after trivializing tie_in\")\n # with core.skipping_checks():\n # with self.assertRaisesRegex(\n # TypeError, \".* of type .*tuple.* is not a valid JAX type\"):\n # jax.make_jaxpr(lambda x: lax.tie_in((x, x), 1))(1.)\n\n def test_primitive_jaxtype_error(self):\n with jax.enable_checks(False):\n with self.assertRaisesRegex(\n TypeError, \"Argument .* of type .* is not a valid JAX type\"):\n lax.add(1, 'hi')\n\n def test_reduction_with_repeated_axes_error(self):\n with self.assertRaisesRegex(ValueError, \"duplicate value in 'axes' .*\"):\n lax.reduce(np.arange(3), 0, lax.add, (0, 0))\n\n def test_population_count_booleans_not_supported(self):\n # https://github.com/google/jax/issues/3886\n msg = \"population_count does not accept dtype bool\"\n with self.assertRaisesRegex(TypeError, msg):\n lax.population_count(True)\n\n def test_conv_general_dilated_different_input_ranks_error(self):\n # https://github.com/google/jax/issues/4316\n msg = (\"conv_general_dilated lhs and rhs must have the same number of \"\n \"dimensions\")\n dimension_numbers = lax.ConvDimensionNumbers(lhs_spec=(0, 1, 2),\n rhs_spec=(0, 1, 2),\n out_spec=(0, 1, 2))\n kwargs = { 'window_strides': (1,)\n , 'padding': ((0, 0),)\n , 'lhs_dilation': (1,)\n , 'rhs_dilation': (1,)\n , 'dimension_numbers': dimension_numbers\n , 'feature_group_count': 1\n , 'batch_group_count': 1\n , 'precision': None\n }\n lhs, rhs = np.ones((1, 1, 1)), np.ones((1, 1, 1, 1))\n with self.assertRaisesRegex(ValueError, msg):\n lax.conv_general_dilated(lhs, rhs, **kwargs)\n\n def test_window_strides_dimension_shape_rule(self):\n # https://github.com/google/jax/issues/5087\n msg = (\"conv_general_dilated window and window_strides must have \"\n \"the same number of dimensions\")\n lhs = jax.numpy.zeros((1, 1, 3, 3))\n rhs = np.zeros((1, 1, 1, 1))\n with self.assertRaisesRegex(ValueError, msg):\n jax.lax.conv(lhs, rhs, [1], 'SAME')\n\n def test_reduce_window_scalar_init_value_shape_rule(self):\n # https://github.com/google/jax/issues/4574\n args = { \"operand\": np.ones((4, 4), dtype=np.int32)\n , \"init_value\": np.zeros((1,), dtype=np.int32)\n , \"computation\": lax.max\n , \"window_dimensions\": (2, 2)\n , \"window_strides\": (2, 2)\n , \"padding\": \"VALID\"\n , \"base_dilation\": (1, 1)\n , \"window_dilation\": (1, 1)\n }\n\n msg = (r\"reduce_window expected init_values to be scalars but init_values \"\n r\"have shapes \\[\\(1,\\)\\].\")\n with self.assertRaisesRegex(TypeError, msg):\n lax.reduce_window(**args)\n\n def test_reduce_correctly_works_with_pytrees(self):\n operands = {'x': [np.ones(5), np.arange(5)]}\n init_values = {'x': [0., 0]}\n result = lax.reduce(operands, init_values,\n lambda x, y: tree_util.tree_multimap(lax.add, x, y),\n [0])\n self.assertDictEqual(result, {'x': [5., 10.]})\n\n def test_reduce_with_mismatched_pytrees_errors(self):\n operands = {'x': np.ones(5)}\n bad_init_values = {'y': 0.}\n\n with self.assertRaisesRegex(ValueError, 'Operands must have the same '\n 'tree structure as init_values'):\n lax.reduce(operands, bad_init_values,\n lambda x, y: dict(x=x['x'] + y['x']), [0])\n\n def test_reduce_with_nonscalar_inits_errors(self):\n operands = {'x': np.ones(5)}\n bad_init_values = {'x': np.ones(5)}\n\n with self.assertRaisesRegex(ValueError,\n 'reduce found non-scalar initial value'):\n lax.reduce(operands, bad_init_values,\n lambda x, y: dict(x=x['x'] + y['x']), [0])\n\n def test_select_jvp_complexity(self):\n jaxpr = jax.make_jaxpr(lambda x: jax.jvp(lambda x: lax.select(True, x, x),\n (x,), (1.,)))(1.)\n self.assertLen(jaxpr.jaxpr.eqns, 2)\n\n def testRngBitGenerator(self):\n # This test covers the original behavior of lax.rng_bit_generator, which\n # required x64=True, and only checks shapes and jit invariance.\n if not config.x64_enabled:\n raise SkipTest(\"RngBitGenerator requires 64bit key\")\n\n key = np.array((1, 2)).astype(np.uint64)\n def fn(k):\n return lax.rng_bit_generator(\n k, shape=(5, 7), algorithm=lax.RandomAlgorithm.RNG_THREE_FRY)\n\n out = fn(key)\n out_jit = jax.jit(fn)(key)\n self.assertEqual(out[0].shape, (2,))\n self.assertEqual(out[1].shape, (5, 7))\n self.assertArraysEqual(out[0], out_jit[0])\n self.assertArraysEqual(out[1], out_jit[1])\n\n @jtu.skip_on_devices(\"tpu\")\n def testRngBitGeneratorReturnedKey(self):\n # This test ensures that the key bit-packing/unpacking operations used in\n # the translation rule for rng_bit_generator, on older jaxlibs and at time\n # of writing on GPU, are inverses of one another.\n key = np.array([3, 1, 4, 2], dtype=np.dtype('uint32'))\n new_key, _ = lax.rng_bit_generator(key, (0,))\n self.assertAllClose(key, new_key)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_dtype={}_weak_type={}\".format(dtype.__name__, weak_type),\n \"dtype\": dtype, \"weak_type\": weak_type}\n for dtype in all_dtypes + python_scalar_types\n for weak_type in [True, False]))\n def test_const(self, dtype, weak_type):\n if dtype in set(python_scalar_types):\n val = dtype(0)\n else:\n val = lax._convert_element_type(0, dtype, weak_type=weak_type)\n\n const = lax._const(val, 0)\n self.assertEqual(dtypes.dtype(val, canonicalize=True),\n dtypes.dtype(const, canonicalize=True))\n\n\n def testIgammaSpecial(self):\n self.assertEqual(lax.igamma(1., np.inf), 1.)\n self.assertEqual(lax.igammac(1., np.inf), 0.)\n\n def testRegressionIssue5728(self):\n # The computation in this test gave garbage data on CPU due to an LLVM bug.\n @jax.jit\n def f(inputs):\n out_action_2 = lax.slice_in_dim(inputs, 0, 15, axis=-1)\n mask = lax.slice_in_dim(inputs, 7, 22, axis=-1)\n out_action_2 = lax.select(lax.eq(mask, np.float32(0)),\n lax.broadcast(np.float32(42), (1, 15)),\n out_action_2)\n return lax.pad(out_action_2, np.float32(42), [(0, 0, 0), (0, 15, 0)])\n self.assertArraysEqual(np.full((1, 30), np.float32(42)),\n f(np.zeros((1, 24), dtype=np.float32)))\n\n def testDynamicSliceU8Index(self):\n # Regression test for u8 index in dynamic-slice (#6122)\n # TODO(b/183216273): enable this test for CPU & GPU when possible.\n if jtu.device_under_test() == \"cpu\":\n raise unittest.SkipTest(\"DynamicSliceU8Index test is a known failure on CPU.\")\n if jtu.device_under_test() == \"gpu\":\n raise unittest.SkipTest(\"DynamicSliceU8Index test is a known failure on GPU.\")\n x = np.arange(200)\n np.testing.assert_equal(\n np.array(lax.dynamic_slice(x, np.uint8([128]), (1,))), [128])\n\n\nclass LazyConstantTest(jtu.JaxTestCase):\n def _Check(self, make_const, expected):\n # check casting to ndarray works\n asarray_result = np.asarray(make_const())\n\n # check passing as an argument works (should hit constant handler)\n zero = np.array(0, expected.dtype)\n argument_result = lax.add(zero, make_const())\n\n # check looping into a compiled computation works\n jit_result = jax.jit(lambda x: lax.add(x, make_const()))(zero)\n\n # ensure they're all the same\n self.assertAllClose(asarray_result, expected)\n self.assertAllClose(argument_result, expected)\n self.assertAllClose(jit_result, expected)\n\n # ensure repr doesn't crash\n repr(make_const())\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_fill={}\".format(\n jtu.format_shape_dtype_string(shape, dtype) if dtype else shape,\n fill_value),\n \"shape\": shape, \"dtype\": dtype, \"fill_value\": fill_value}\n for dtype in itertools.chain(default_dtypes, [None])\n for shape in [(), (3,), (2, 3), (2, 3, 4), (1001, 1001)]\n for fill_value in [0, 1, np.pi]))\n def testFilledConstant(self, shape, fill_value, dtype):\n make_const = lambda: lax.full(shape, fill_value, dtype)\n expected = np.full(shape, fill_value,\n dtype or dtypes.dtype(fill_value))\n self._Check(make_const, expected)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_dim={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), dimension),\n \"shape\": shape, \"dtype\": dtype, \"dimension\": dimension}\n for dtype in default_dtypes\n for shape in [(), (3,), (2, 3), (2, 3, 4),\n # TODO(mattjj): re-enable\n # (1001, 1001), (101, 101, 101),\n ]\n for dimension in range(len(shape))))\n def testIotaConstant(self, dtype, shape, dimension):\n make_const = lambda: lax.broadcasted_iota(dtype, shape, dimension)\n\n arr = np.arange(shape[dimension], dtype=dtypes.canonicalize_dtype(dtype))\n singleton_shape = [1] * len(shape)\n singleton_shape[dimension] = shape[dimension]\n expected = np.broadcast_to(arr.reshape(singleton_shape), shape)\n\n self._Check(make_const, expected)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_axes={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), axes),\n \"shape\": shape, \"dtype\": dtype, \"axes\": axes}\n for dtype in default_dtypes\n for shape, axes in [\n [(2, 3), (0, 1)],\n [(2, 3, 4), (0, 1)],\n [(2, 3, 4), (0, 2)],\n [(2, 3, 4), (1, 2)],\n [(2, 3, 4), (0, 1, 2)],\n [(2, 3, 4, 2), (0, 1, 2)],\n [(2, 3, 4, 2), (0, 2, 3)],\n [(1001, 1001), (0, 1)],\n ]))\n def testDeltaConstant(self, dtype, shape, axes):\n make_const = lambda: lax._delta(dtype, shape, axes)\n # don't check the asarray case, just assume it's right\n expected = np.asarray(make_const())\n self._Check(make_const, expected)\n\n def testBroadcastInDim(self):\n arr = lax.full((2, 1), 1.) + 1.\n arr_np = np.full((2, 1), 1.) + 1.\n expected = lax_reference.broadcast_in_dim(arr_np, (2, 1, 3), (0, 2))\n make_const = lambda: lax.broadcast_in_dim(arr, (2, 1, 3), (0, 2))\n self._Check(make_const, expected)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_input_type={}_dtype={}_value={}_jit={}\".format(\n input_type.__name__, dtype.__name__, value, jit),\n \"input_type\": input_type, \"dtype\": dtype, \"value\": value, \"jit\": jit}\n for input_type in [int, float, np.int32, np.float32, np.array]\n for dtype in [np.int32, np.float32]\n for jit in [True, False]\n for value in [0, 1]))\n def testConvertElementReturnType(self, input_type, dtype, value, jit):\n op = lambda x: lax.convert_element_type(x, dtype)\n if jit:\n op = jax.jit(op)\n result = op(input_type(value))\n assert isinstance(result, jnp.DeviceArray)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_dtype_in={}_dtype_out={}\".format(\n dtype_in.__name__, dtype_out.__name__),\n \"dtype_in\": dtype_in, \"dtype_out\": dtype_out}\n for dtype_in in all_dtypes for dtype_out in all_dtypes))\n @jtu.ignore_warning(category=np.ComplexWarning)\n def testConvertElementTypeAvoidsCopies(self, dtype_in, dtype_out):\n x = _device_put_raw(np.zeros(5, dtype_in))\n self.assertEqual(x.dtype, dtype_in)\n y = lax.convert_element_type(x, dtype_out)\n self.assertEqual(y.dtype, dtype_out)\n if np.dtype(dtype_in) == np.dtype(dtype_out):\n self.assertIs(x.device_buffer, y.device_buffer)\n else:\n self.assertFalse(x.device_buffer is y.device_buffer)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_fn={}_indexdtype={}\"\n .format(jax_fn.__name__, np.dtype(index_dtype).name),\n \"index_dtype\": index_dtype, \"jax_fn\": jax_fn}\n for index_dtype in jtu.dtypes.all_inexact + jtu.dtypes.boolean\n for jax_fn in [lax.argmin, lax.argmax]))\n def testArgMinMaxIndexDtypeError(self, jax_fn, index_dtype):\n with self.assertRaisesRegex(TypeError,\n \"index_dtype must be an integer type\"):\n jax_fn(np.ones((2, 2)), axis=0, index_dtype=index_dtype)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_fn={}\".format(jax_fn.__name__),\n \"jax_fn\": jax_fn}\n for jax_fn in [lax.argmin, lax.argmax]))\n def testArgMinMaxEmptyError(self, jax_fn):\n with self.assertRaisesRegex(ValueError,\n \"require non-empty reduced dimension\"):\n jax_fn(np.ones((0, 2)), axis=0, index_dtype=np.int32)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_fn={}\".format(jax_fn.__name__),\n \"jax_fn\": jax_fn}\n for jax_fn in [lax.argmin, lax.argmax]))\n def testArgMinMaxInvalidAxisError(self, jax_fn):\n with self.assertRaisesRegex(ValueError,\n \"Invalid axis -1 for operand\"):\n jax_fn(np.ones((2, 3)), axis=-1, index_dtype=np.int32)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_fn={}_weaktype={}\".format(jax_fn.__name__, weak_type),\n \"jax_fn\": jax_fn, \"weak_type\": weak_type}\n for jax_fn in [lax.argmin, lax.argmax]\n for weak_type in [True, False]))\n def testArgMinMaxWeakType(self, jax_fn, weak_type):\n op = lambda x: jax_fn(x, axis=0, index_dtype=np.int32)\n x_in = lax._convert_element_type(np.ones((2, 2)), weak_type=weak_type)\n self.assertEqual(dtypes.is_weakly_typed(x_in), weak_type)\n x_out = op(x_in)\n self.assertEqual(dtypes.is_weakly_typed(x_out), False)\n x_out_jit = jax.jit(op)(x_in)\n self.assertEqual(dtypes.is_weakly_typed(x_out_jit), False)\n\n def testArgMaxOfNanChoosesNaN(self):\n self.assertEqual(lax.argmax(np.array([0., np.nan]), axis=0,\n index_dtype=np.int32), 1)\n\n unary_op_types = {}\n for r in LAX_OPS:\n if r.nargs == 1:\n unary_op_types[r.op] = (unary_op_types.get(r.op, set()) |\n set(np.dtype(t) for t in r.dtypes))\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}\".format(op), \"op_name\": op, \"rec_dtypes\": dtypes}\n for op, dtypes in unary_op_types.items()))\n def testUnaryWeakTypes(self, op_name, rec_dtypes):\n \"\"\"Test that all lax unary ops propagate weak_type information appropriately.\"\"\"\n # Find a valid dtype for the function.\n for dtype in [np.float_, np.int_, np.complex_, np.bool_]:\n dtype = dtypes.canonicalize_dtype(dtype)\n if dtype in rec_dtypes:\n py_val = dtype.type(1).item()\n lax_val = lax.full((), py_val, dtype)\n break\n else:\n raise ValueError(f\"no available dtypes in {rec_dtypes}\")\n\n op = getattr(lax, op_name)\n py_op = op(py_val)\n lax_op = op(lax_val)\n\n self.assertAllClose(py_op, lax_op, check_dtypes=True)\n self.assertTrue(py_op.aval.weak_type)\n self.assertFalse(lax_op.aval.weak_type)\n\n def testCumsumLengthOne(self):\n # regression test for issue 4672\n x = lax.full((1,), 1)\n out = lax.cumsum(x)\n self.assertArraysEqual(out, x)\n\n def testLog1pNearOne(self):\n np.testing.assert_array_almost_equal_nulp(\n np.log1p(np.float32(1e-5)), lax.log1p(np.float32(1e-5)))\n np.testing.assert_array_almost_equal_nulp(\n np.log1p(np.float32(1e-5)), lax.log1p(np.complex64(1e-5)))\n\n\nclass LaxNamedShapeTest(jtu.JaxTestCase):\n\n def test_abstract_eval(self):\n aval1 = core.ShapedArray((2, 3), np.float32, False, {'i': 10})\n out = lax.sin_p.abstract_eval(aval1)\n self.assertEqual(out, aval1)\n\n aval1 = core.ShapedArray((2, 3), np.float32, False, {'i': 10})\n aval2 = core.ShapedArray((2, 3), np.float32, False, {'j': 5})\n expected = core.ShapedArray((2, 3), np.float32, False, {'i': 10, 'j': 5})\n out = lax.add_p.abstract_eval(aval1, aval2)\n self.assertEqual(out, expected)\n\n def test_abstract_eval_collective(self):\n with core.extend_axis_env('i', 10, None):\n aval1 = core.ShapedArray((2, 3), np.float32, False, {'i': 10, 'j': 5})\n expected = core.ShapedArray((2, 3), np.float32, False, {'j': 5})\n out, = lax.psum_p.abstract_eval(aval1, axes=('i',), axis_index_groups=None)\n self.assertEqual(out, expected)\n\nif __name__ == '__main__':\n absltest.main(testLoader=jtu.JaxTestLoader())\n"
] | [
[
"numpy.ones",
"numpy.complex64",
"numpy.take",
"numpy.dtype",
"numpy.issubdtype",
"numpy.ones_like",
"numpy.asarray",
"numpy.uint8",
"numpy.zeros",
"numpy.float32",
"numpy.arange",
"numpy.int32",
"numpy.lexsort",
"numpy.prod",
"numpy.pad",
"numpy.int16",
"numpy.swapaxes",
"numpy.flip",
"numpy.array",
"numpy.full"
]
] |
kellywzhang/OpenNMT-py | [
"2a38fb035fed0597f22694f4580303d1490cbb39"
] | [
"onmt/Optim.py"
] | [
"import torch.optim as optim\nfrom torch.nn.utils import clip_grad_norm\n\n\nclass Optim(object):\n \"\"\"\n Controller class for optimization. Mostly a thin\n wrapper for `optim`, but also useful for implementing\n rate scheduling beyond what is currently available.\n Also implements necessary methods for training RNNs such\n as grad manipulations.\n\n Args:\n method (:obj:`str`): one of [sgd, adagrad, adadelta, adam]\n lr (float): learning rate\n lr_decay (float, optional): learning rate decay multiplier\n start_decay_at (int, optional): epoch to start learning rate decay\n beta1, beta2 (float, optional): parameters for adam\n adagrad_accum (float, optional): initialization parameter for adagrad\n decay_method (str, option): custom decay options\n warmup_steps (int, option): parameter for `noam` decay\n model_size (int, option): parameter for `noam` decay\n \"\"\"\n # We use the default parameters for Adam that are suggested by\n # the original paper https://arxiv.org/pdf/1412.6980.pdf\n # These values are also used by other established implementations,\n # e.g. https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer\n # https://keras.io/optimizers/\n # Recently there are slightly different values used in the paper\n # \"Attention is all you need\"\n # https://arxiv.org/pdf/1706.03762.pdf, particularly the value beta2=0.98\n # was used there however, beta2=0.999 is still arguably the more\n # established value, so we use that here as well\n def __init__(self, method, lr, max_grad_norm,\n lr_decay=1, start_decay_at=None,\n beta1=0.9, beta2=0.999,\n adagrad_accum=0.0,\n decay_method=None,\n warmup_steps=4000,\n model_size=None,\n patience=0):\n self.last_ppl = None\n self.lr = lr\n self.original_lr = lr\n self.max_grad_norm = max_grad_norm\n self.method = method\n self.lr_decay = lr_decay\n self.start_decay_at = start_decay_at\n self.start_decay = False\n self._step = 0\n self.betas = [beta1, beta2]\n self.adagrad_accum = adagrad_accum\n self.decay_method = decay_method\n self.warmup_steps = warmup_steps\n self.model_size = model_size\n self.patience = patience\n self.patience_cnt = 0\n\n def set_parameters(self, params):\n self.params = [p for p in params if p.requires_grad]\n if self.method == 'sgd':\n self.optimizer = optim.SGD(self.params, lr=self.lr)\n elif self.method == 'adagrad':\n self.optimizer = optim.Adagrad(self.params, lr=self.lr)\n for group in self.optimizer.param_groups:\n for p in group['params']:\n self.optimizer.state[p]['sum'] = self.optimizer\\\n .state[p]['sum'].fill_(self.adagrad_accum)\n elif self.method == 'adadelta':\n self.optimizer = optim.Adadelta(self.params, lr=self.lr)\n elif self.method == 'adam':\n self.optimizer = optim.Adam(self.params, lr=self.lr,\n betas=self.betas, eps=1e-9)\n else:\n raise RuntimeError(\"Invalid optim method: \" + self.method)\n\n def _set_rate(self, lr):\n self.lr = lr\n self.optimizer.param_groups[0]['lr'] = self.lr\n\n def step(self):\n \"\"\"Update the model parameters based on current gradients.\n\n Optionally, will employ gradient modification or update learning\n rate.\n \"\"\"\n self._step += 1\n\n # Decay method used in tensor2tensor.\n if self.decay_method == \"noam\":\n self._set_rate(\n self.original_lr *\n (self.model_size ** (-0.5) *\n min(self._step ** (-0.5),\n self._step * self.warmup_steps**(-1.5))))\n\n if self.max_grad_norm:\n clip_grad_norm(self.params, self.max_grad_norm)\n self.optimizer.step()\n\n def update_learning_rate(self, ppl, epoch):\n \"\"\"\n Decay learning rate if val perf does not improve\n or we hit the start_decay_at limit.\n \"\"\"\n\n if self.start_decay_at is not None and epoch >= self.start_decay_at:\n self.start_decay = True\n # Change from original OpenNMT option\n if self.last_ppl is not None and ppl > self.last_ppl:\n self.patience_cnt += 1\n if self.patience_cnt > self.patience:\n self.start_decay = True\n else:\n self.start_decay = False\n self.patience_cnt = 0\n\n if self.start_decay:\n self.lr = self.lr * self.lr_decay\n print(\"Decaying learning rate to %g\" % self.lr)\n\n self.last_ppl = ppl\n self.optimizer.param_groups[0]['lr'] = self.lr\n"
] | [
[
"torch.optim.SGD",
"torch.optim.Adadelta",
"torch.nn.utils.clip_grad_norm",
"torch.optim.Adam",
"torch.optim.Adagrad"
]
] |
fierval/retina | [
"2bc50b3354e5e37f1cfd34f11fbe4b0a4178b7ac"
] | [
"DiabeticRetinopathy/Refactoring/kobra/tr_utils.py"
] | [
"import numpy as np\nfrom time import gmtime, strftime, localtime\nimport csv\nimport os\nfrom os import path\nimport shutil\nimport pandas as pd\nfrom pandas.io.parsers import csv\n\ndef prep_out_path(out_path):\n if path.exists(out_path):\n shutil.rmtree(out_path)\n os.makedirs(out_path)\n\ndef append_to_arr(arr, a, axis = 0):\n '''\n Append a to a numpy array arr. a - scalar, list or numpy array\n '''\n if isinstance(a, list) or isinstance(a, np.ndarray):\n a = np.array(a)\n\n if arr.shape[0] == 0:\n arr = a.reshape(1, a.shape[0])\n else:\n arr = np.append(arr, a.reshape(1, a.shape[0]), axis = axis)\n else:\n if arr.size == 0:\n arr = np.array([a]) # make sure it is a 1-dimensional array\n else:\n arr = np.append(arr, a)\n return arr\n\ndef time_now_str():\n return strftime(\"%d %b %Y %H:%M:%S\", localtime())\n\ndef merge_two_dicts(x, y):\n '''Given two dicts, merge them into a new dict.\n '''\n z = x.copy()\n z.update(y)\n return z\n\ndef vote(proba_list, weight_list):\n '''\n Given a list of probability arrays and a list of weights,\n Compute the final array by summiing probabilities and multiplying by their weights\n '''\n wts = np.array(weight_list)\n if wts[wts == 1].shape[0] == wts.shape[0]:\n proba = np.array([x for x in proba_list])\n return proba.mean(0)\n else:\n proba = np.array([x[0] * x[1] for x in zip(proba_list, weight_list)])\n return proba.sum(0)\n \ndef vote_reduce(arrs, weights):\n '''\n Given two arrays and a list of two weights, apply the voting rule as in vote(), unless\n a 0 or a 1 is encountered. In the former case pick the unweighted non-zero element, in the latter - the element\n with value of 1.\n '''\n def func (x, y):\n w2 = y[1]; y = y[0]\n for i, k in enumerate(np.nditer(y, ['c_index'])):\n if x[i] == 0 or y[i] == 1.0:\n x[i] = y[i]\n elif x[i] != 1 and y[i] != 0:\n x[i] = x[i] + y[i] * w2\n return x\n\n def init(x):\n return np.array([x * weights[0] if x != 1.0 else x for x in np.nditer(x, ['c_index'])])\n\n res = np.array([])\n probs = np.array(arrs)\n\n for i in range(0, probs.shape[1]):\n samples = probs[:, i, :].reshape(probs.shape[0], probs.shape[2])\n cur_proba = reduce(func, zip(samples[1:, :], np.array(weights)[1:]), init(samples[0]))\n res = append_to_arr(res, cur_proba) \n return res\n\ndef isEmpty(arr):\n return len(arr) == 0\n\ndef write_to_csv(task_labels, labels, probs, out_file):\n predict_columns = [\"Prediction{:1d}\".format(i) for i in range(1, 10) ]\n\n existing_rows = pd.read_csv(task_labels, header=0, quoting=csv.QUOTE_NONNUMERIC)\n file_names = pd.DataFrame(labels, columns= [\"Id\"])\n probas = pd.DataFrame(probs, columns = predict_columns)\n out = pd.concat([file_names, probas], axis=1)\n out = pd.concat([existing_rows, out])\n\n out.to_csv(out_file, index=False, quoting=csv.QUOTE_NONNUMERIC)"
] | [
[
"numpy.append",
"pandas.read_csv",
"pandas.DataFrame",
"numpy.nditer",
"pandas.concat",
"numpy.array"
]
] |
Chocomunk/caltech-ee148-spring2020-hw01 | [
"f4a5a1450560018c6098f706fca27138cedf55a0"
] | [
"strategies.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom skimage.exposure import equalize_adapthist\n\nfrom util import hsv2rgb, rgb2hsv, histogram_equalization, CLAHE, correlate, \\\n black_tophat\n\n\ndef threshold_strategy(I, r_b=85, r_t=145, g_b=0, g_t=0, b_b=75, b_t=130):\n img = black_tophat(I, 11)\n img = rgb2hsv(img)\n img = black_tophat(img, 11)\n return (r_b <= img[:,:,0]) & (img[:,:,0] <= r_t) & \\\n (g_b <= img[:,:,1]) & (img[:,:,1] <= g_t) & \\\n (b_b <= img[:,:,2]) & (img[:,:,2] <= b_t)\n\n\ndef correlate_strategy(I, filters):\n # Using scipy's equalize_adapthist is preferred for better balancing\n img = rgb2hsv(I)\n # img[:,:,2] = CLAHE(img[:,:,2], tile_size=(16,16))\n # img[:,:,2] = equalize_adapthist(img[:,:,2], clip_limit=0.03) * 255\n img[:,:,2] = histogram_equalization(img[:,:,2])\n img = hsv2rgb(img)\n\n # Find cossim against original image\n output = np.zeros(img.shape[:2], dtype=np.float32)\n for filt in filters:\n corr = correlate(img, filt, step=2)\n output = np.maximum(output, corr)\n return output, img"
] | [
[
"numpy.maximum",
"numpy.zeros"
]
] |
dzwallkilled/pytorch-cifar10 | [
"fee201da5a3b516a57104e0b6338e05008079b8b"
] | [
"models/VGG.py"
] | [
"import torch.nn as nn\n\n\ncfg = {\n 'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],\n 'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],\n}\n\n\nclass VGG(nn.Module):\n def __init__(self, vgg_name):\n super(VGG, self).__init__()\n self.features = self._make_layers(cfg[vgg_name])\n self.classifier = nn.Linear(512, 10)\n\n def forward(self, x):\n out = self.features(x)\n out = out.view(out.size(0), -1)\n out = self.classifier(out)\n return out\n\n def _make_layers(self, cfg):\n layers = []\n in_channels = 3\n for x in cfg:\n if x == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n else:\n layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1),\n nn.BatchNorm2d(x),\n nn.ReLU(inplace=True)]\n in_channels = x\n layers += [nn.AvgPool2d(kernel_size=1, stride=1)]\n return nn.Sequential(*layers)\n\n\ndef VGG11():\n return VGG('VGG11')\n\n\ndef VGG13():\n return VGG('VGG13')\n\n\ndef VGG16():\n return VGG('VGG16')\n\n\ndef VGG19():\n return VGG('VGG19')\n"
] | [
[
"torch.nn.MaxPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.Linear",
"torch.nn.Conv2d",
"torch.nn.Sequential",
"torch.nn.AvgPool2d",
"torch.nn.ReLU"
]
] |
asnt/moderngl | [
"b39cedd8cf216c34e43371b4aec822f6084f0f79"
] | [
"docs/the_guide/first.3.py"
] | [
"import moderngl\nimport numpy as np\n\nctx = moderngl.create_standalone_context()\n\nprog = ctx.program(\n vertex_shader='''\n #version 330\n\n in vec2 in_vert;\n in vec3 in_color;\n\n out vec3 v_color;\n\n void main() {\n v_color = in_color;\n gl_Position = vec4(in_vert, 0.0, 1.0);\n }\n ''',\n fragment_shader='''\n #version 330\n\n in vec3 v_color;\n\n out vec3 f_color;\n\n void main() {\n f_color = v_color;\n }\n ''',\n)\n\nx = np.linspace(-1.0, 1.0, 50)\ny = np.random.rand(50) - 0.5\nr = np.ones(50)\ng = np.zeros(50)\nb = np.zeros(50)\n\nvertices = np.dstack([x, y, r, g, b])\n\nvbo = ctx.buffer(vertices.astype('f4').tobytes())\nvao = ctx.simple_vertex_array(prog, vbo, 'in_vert', 'in_color')\n"
] | [
[
"numpy.ones",
"numpy.zeros",
"numpy.dstack",
"numpy.random.rand",
"numpy.linspace"
]
] |
CV-IP/interfacegan | [
"5a556b8e693f6e1888f769f653aaafaaccca5dc2"
] | [
"models/pggan_tf_official/dataset_tool.py"
] | [
"# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# This work is licensed under the Creative Commons Attribution-NonCommercial\n# 4.0 International License. To view a copy of this license, visit\n# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to\n# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n\nimport os\nimport sys\nimport glob\nimport argparse\nimport threading\nimport six.moves.queue as Queue\nimport traceback\nimport numpy as np\nimport tensorflow as tf\nimport PIL.Image\n\nimport tfutil\nimport dataset\n\n#----------------------------------------------------------------------------\n\ndef error(msg):\n print('Error: ' + msg)\n exit(1)\n\n#----------------------------------------------------------------------------\n\nclass TFRecordExporter:\n def __init__(self, tfrecord_dir, expected_images, print_progress=True, progress_interval=10):\n self.tfrecord_dir = tfrecord_dir\n self.tfr_prefix = os.path.join(self.tfrecord_dir, os.path.basename(self.tfrecord_dir))\n self.expected_images = expected_images\n self.cur_images = 0\n self.shape = None\n self.resolution_log2 = None\n self.tfr_writers = []\n self.print_progress = print_progress\n self.progress_interval = progress_interval\n if self.print_progress:\n print('Creating dataset \"%s\"' % tfrecord_dir)\n if not os.path.isdir(self.tfrecord_dir):\n os.makedirs(self.tfrecord_dir)\n assert(os.path.isdir(self.tfrecord_dir))\n \n def close(self):\n if self.print_progress:\n print('%-40s\\r' % 'Flushing data...', end='', flush=True)\n for tfr_writer in self.tfr_writers:\n tfr_writer.close()\n self.tfr_writers = []\n if self.print_progress:\n print('%-40s\\r' % '', end='', flush=True)\n print('Added %d images.' % self.cur_images)\n\n def choose_shuffled_order(self): # Note: Images and labels must be added in shuffled order.\n order = np.arange(self.expected_images)\n np.random.RandomState(123).shuffle(order)\n return order\n\n def add_image(self, img):\n if self.print_progress and self.cur_images % self.progress_interval == 0:\n print('%d / %d\\r' % (self.cur_images, self.expected_images), end='', flush=True)\n if self.shape is None:\n self.shape = img.shape\n self.resolution_log2 = int(np.log2(self.shape[1]))\n assert self.shape[0] in [1, 3]\n assert self.shape[1] == self.shape[2]\n assert self.shape[1] == 2**self.resolution_log2\n tfr_opt = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.NONE)\n for lod in range(self.resolution_log2 - 1):\n tfr_file = self.tfr_prefix + '-r%02d.tfrecords' % (self.resolution_log2 - lod)\n self.tfr_writers.append(tf.python_io.TFRecordWriter(tfr_file, tfr_opt))\n assert img.shape == self.shape\n for lod, tfr_writer in enumerate(self.tfr_writers):\n if lod:\n img = img.astype(np.float32)\n img = (img[:, 0::2, 0::2] + img[:, 0::2, 1::2] + img[:, 1::2, 0::2] + img[:, 1::2, 1::2]) * 0.25\n quant = np.rint(img).clip(0, 255).astype(np.uint8)\n ex = tf.train.Example(features=tf.train.Features(feature={\n 'shape': tf.train.Feature(int64_list=tf.train.Int64List(value=quant.shape)),\n 'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[quant.tostring()]))}))\n tfr_writer.write(ex.SerializeToString())\n self.cur_images += 1\n\n def add_labels(self, labels):\n if self.print_progress:\n print('%-40s\\r' % 'Saving labels...', end='', flush=True)\n assert labels.shape[0] == self.cur_images\n with open(self.tfr_prefix + '-rxx.labels', 'wb') as f:\n np.save(f, labels.astype(np.float32))\n \n def __enter__(self):\n return self\n \n def __exit__(self, *args):\n self.close()\n\n#----------------------------------------------------------------------------\n\nclass ExceptionInfo(object):\n def __init__(self):\n self.value = sys.exc_info()[1]\n self.traceback = traceback.format_exc()\n\n#----------------------------------------------------------------------------\n\nclass WorkerThread(threading.Thread):\n def __init__(self, task_queue):\n threading.Thread.__init__(self)\n self.task_queue = task_queue\n\n def run(self):\n while True:\n func, args, result_queue = self.task_queue.get()\n if func is None:\n break\n try:\n result = func(*args)\n except:\n result = ExceptionInfo()\n result_queue.put((result, args))\n\n#----------------------------------------------------------------------------\n\nclass ThreadPool(object):\n def __init__(self, num_threads):\n assert num_threads >= 1\n self.task_queue = Queue.Queue()\n self.result_queues = dict()\n self.num_threads = num_threads\n for idx in range(self.num_threads):\n thread = WorkerThread(self.task_queue)\n thread.daemon = True\n thread.start()\n\n def add_task(self, func, args=()):\n assert hasattr(func, '__call__') # must be a function\n if func not in self.result_queues:\n self.result_queues[func] = Queue.Queue()\n self.task_queue.put((func, args, self.result_queues[func]))\n\n def get_result(self, func): # returns (result, args)\n result, args = self.result_queues[func].get()\n if isinstance(result, ExceptionInfo):\n print('\\n\\nWorker thread caught an exception:\\n' + result.traceback)\n raise result.value\n return result, args\n\n def finish(self):\n for idx in range(self.num_threads):\n self.task_queue.put((None, (), None))\n\n def __enter__(self): # for 'with' statement\n return self\n\n def __exit__(self, *excinfo):\n self.finish()\n\n def process_items_concurrently(self, item_iterator, process_func=lambda x: x, pre_func=lambda x: x, post_func=lambda x: x, max_items_in_flight=None):\n if max_items_in_flight is None: max_items_in_flight = self.num_threads * 4\n assert max_items_in_flight >= 1\n results = []\n retire_idx = [0]\n\n def task_func(prepared, idx):\n return process_func(prepared)\n \n def retire_result():\n processed, (prepared, idx) = self.get_result(task_func)\n results[idx] = processed\n while retire_idx[0] < len(results) and results[retire_idx[0]] is not None:\n yield post_func(results[retire_idx[0]])\n results[retire_idx[0]] = None\n retire_idx[0] += 1\n \n for idx, item in enumerate(item_iterator):\n prepared = pre_func(item)\n results.append(None)\n self.add_task(func=task_func, args=(prepared, idx))\n while retire_idx[0] < idx - max_items_in_flight + 2:\n for res in retire_result(): yield res\n while retire_idx[0] < len(results):\n for res in retire_result(): yield res\n\n#----------------------------------------------------------------------------\n\ndef display(tfrecord_dir):\n print('Loading dataset \"%s\"' % tfrecord_dir)\n tfutil.init_tf({'gpu_options.allow_growth': True})\n dset = dataset.TFRecordDataset(tfrecord_dir, max_label_size='full', repeat=False, shuffle_mb=0)\n tfutil.init_uninited_vars()\n \n idx = 0\n while True:\n try:\n images, labels = dset.get_minibatch_np(1)\n except tf.errors.OutOfRangeError:\n break\n if idx == 0:\n print('Displaying images')\n import cv2 # pip install opencv-python\n cv2.namedWindow('dataset_tool')\n print('Press SPACE or ENTER to advance, ESC to exit')\n print('\\nidx = %-8d\\nlabel = %s' % (idx, labels[0].tolist()))\n cv2.imshow('dataset_tool', images[0].transpose(1, 2, 0)[:, :, ::-1]) # CHW => HWC, RGB => BGR\n idx += 1\n if cv2.waitKey() == 27:\n break\n print('\\nDisplayed %d images.' % idx)\n\n#----------------------------------------------------------------------------\n\ndef extract(tfrecord_dir, output_dir):\n print('Loading dataset \"%s\"' % tfrecord_dir)\n tfutil.init_tf({'gpu_options.allow_growth': True})\n dset = dataset.TFRecordDataset(tfrecord_dir, max_label_size=0, repeat=False, shuffle_mb=0)\n tfutil.init_uninited_vars()\n \n print('Extracting images to \"%s\"' % output_dir)\n if not os.path.isdir(output_dir):\n os.makedirs(output_dir)\n idx = 0\n while True:\n if idx % 10 == 0:\n print('%d\\r' % idx, end='', flush=True)\n try:\n images, labels = dset.get_minibatch_np(1)\n except tf.errors.OutOfRangeError:\n break\n if images.shape[1] == 1:\n img = PIL.Image.fromarray(images[0][0], 'L')\n else:\n img = PIL.Image.fromarray(images[0].transpose(1, 2, 0), 'RGB')\n img.save(os.path.join(output_dir, 'img%08d.png' % idx))\n idx += 1\n print('Extracted %d images.' % idx)\n\n#----------------------------------------------------------------------------\n\ndef compare(tfrecord_dir_a, tfrecord_dir_b, ignore_labels):\n max_label_size = 0 if ignore_labels else 'full'\n print('Loading dataset \"%s\"' % tfrecord_dir_a)\n tfutil.init_tf({'gpu_options.allow_growth': True})\n dset_a = dataset.TFRecordDataset(tfrecord_dir_a, max_label_size=max_label_size, repeat=False, shuffle_mb=0)\n print('Loading dataset \"%s\"' % tfrecord_dir_b)\n dset_b = dataset.TFRecordDataset(tfrecord_dir_b, max_label_size=max_label_size, repeat=False, shuffle_mb=0)\n tfutil.init_uninited_vars()\n \n print('Comparing datasets')\n idx = 0\n identical_images = 0\n identical_labels = 0\n while True:\n if idx % 100 == 0:\n print('%d\\r' % idx, end='', flush=True)\n try:\n images_a, labels_a = dset_a.get_minibatch_np(1)\n except tf.errors.OutOfRangeError:\n images_a, labels_a = None, None\n try:\n images_b, labels_b = dset_b.get_minibatch_np(1)\n except tf.errors.OutOfRangeError:\n images_b, labels_b = None, None\n if images_a is None or images_b is None:\n if images_a is not None or images_b is not None:\n print('Datasets contain different number of images')\n break\n if images_a.shape == images_b.shape and np.all(images_a == images_b):\n identical_images += 1\n else:\n print('Image %d is different' % idx)\n if labels_a.shape == labels_b.shape and np.all(labels_a == labels_b):\n identical_labels += 1\n else:\n print('Label %d is different' % idx)\n idx += 1\n print('Identical images: %d / %d' % (identical_images, idx))\n if not ignore_labels:\n print('Identical labels: %d / %d' % (identical_labels, idx))\n\n#----------------------------------------------------------------------------\n\ndef create_mnist(tfrecord_dir, mnist_dir):\n print('Loading MNIST from \"%s\"' % mnist_dir)\n import gzip\n with gzip.open(os.path.join(mnist_dir, 'train-images-idx3-ubyte.gz'), 'rb') as file:\n images = np.frombuffer(file.read(), np.uint8, offset=16)\n with gzip.open(os.path.join(mnist_dir, 'train-labels-idx1-ubyte.gz'), 'rb') as file:\n labels = np.frombuffer(file.read(), np.uint8, offset=8)\n images = images.reshape(-1, 1, 28, 28)\n images = np.pad(images, [(0,0), (0,0), (2,2), (2,2)], 'constant', constant_values=0)\n assert images.shape == (60000, 1, 32, 32) and images.dtype == np.uint8\n assert labels.shape == (60000,) and labels.dtype == np.uint8\n assert np.min(images) == 0 and np.max(images) == 255\n assert np.min(labels) == 0 and np.max(labels) == 9\n onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)\n onehot[np.arange(labels.size), labels] = 1.0\n \n with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:\n order = tfr.choose_shuffled_order()\n for idx in range(order.size):\n tfr.add_image(images[order[idx]])\n tfr.add_labels(onehot[order])\n\n#----------------------------------------------------------------------------\n\ndef create_mnistrgb(tfrecord_dir, mnist_dir, num_images=1000000, random_seed=123):\n print('Loading MNIST from \"%s\"' % mnist_dir)\n import gzip\n with gzip.open(os.path.join(mnist_dir, 'train-images-idx3-ubyte.gz'), 'rb') as file:\n images = np.frombuffer(file.read(), np.uint8, offset=16)\n images = images.reshape(-1, 28, 28)\n images = np.pad(images, [(0,0), (2,2), (2,2)], 'constant', constant_values=0)\n assert images.shape == (60000, 32, 32) and images.dtype == np.uint8\n assert np.min(images) == 0 and np.max(images) == 255\n \n with TFRecordExporter(tfrecord_dir, num_images) as tfr:\n rnd = np.random.RandomState(random_seed)\n for idx in range(num_images):\n tfr.add_image(images[rnd.randint(images.shape[0], size=3)])\n\n#----------------------------------------------------------------------------\n\ndef create_cifar10(tfrecord_dir, cifar10_dir):\n print('Loading CIFAR-10 from \"%s\"' % cifar10_dir)\n import pickle\n images = []\n labels = []\n for batch in range(1, 6):\n with open(os.path.join(cifar10_dir, 'data_batch_%d' % batch), 'rb') as file:\n data = pickle.load(file, encoding='latin1')\n images.append(data['data'].reshape(-1, 3, 32, 32))\n labels.append(data['labels'])\n images = np.concatenate(images)\n labels = np.concatenate(labels)\n assert images.shape == (50000, 3, 32, 32) and images.dtype == np.uint8\n assert labels.shape == (50000,) and labels.dtype == np.int32\n assert np.min(images) == 0 and np.max(images) == 255\n assert np.min(labels) == 0 and np.max(labels) == 9\n onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)\n onehot[np.arange(labels.size), labels] = 1.0\n\n with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:\n order = tfr.choose_shuffled_order()\n for idx in range(order.size):\n tfr.add_image(images[order[idx]])\n tfr.add_labels(onehot[order])\n\n#----------------------------------------------------------------------------\n\ndef create_cifar100(tfrecord_dir, cifar100_dir):\n print('Loading CIFAR-100 from \"%s\"' % cifar100_dir)\n import pickle\n with open(os.path.join(cifar100_dir, 'train'), 'rb') as file:\n data = pickle.load(file, encoding='latin1')\n images = data['data'].reshape(-1, 3, 32, 32)\n labels = np.array(data['fine_labels'])\n assert images.shape == (50000, 3, 32, 32) and images.dtype == np.uint8\n assert labels.shape == (50000,) and labels.dtype == np.int32\n assert np.min(images) == 0 and np.max(images) == 255\n assert np.min(labels) == 0 and np.max(labels) == 99\n onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)\n onehot[np.arange(labels.size), labels] = 1.0\n\n with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:\n order = tfr.choose_shuffled_order()\n for idx in range(order.size):\n tfr.add_image(images[order[idx]])\n tfr.add_labels(onehot[order])\n\n#----------------------------------------------------------------------------\n\ndef create_svhn(tfrecord_dir, svhn_dir):\n print('Loading SVHN from \"%s\"' % svhn_dir)\n import pickle\n images = []\n labels = []\n for batch in range(1, 4):\n with open(os.path.join(svhn_dir, 'train_%d.pkl' % batch), 'rb') as file:\n data = pickle.load(file, encoding='latin1')\n images.append(data[0])\n labels.append(data[1])\n images = np.concatenate(images)\n labels = np.concatenate(labels)\n assert images.shape == (73257, 3, 32, 32) and images.dtype == np.uint8\n assert labels.shape == (73257,) and labels.dtype == np.uint8\n assert np.min(images) == 0 and np.max(images) == 255\n assert np.min(labels) == 0 and np.max(labels) == 9\n onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)\n onehot[np.arange(labels.size), labels] = 1.0\n\n with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:\n order = tfr.choose_shuffled_order()\n for idx in range(order.size):\n tfr.add_image(images[order[idx]])\n tfr.add_labels(onehot[order])\n\n#----------------------------------------------------------------------------\n\ndef create_lsun(tfrecord_dir, lmdb_dir, resolution=256, max_images=None):\n print('Loading LSUN dataset from \"%s\"' % lmdb_dir)\n import lmdb # pip install lmdb\n import cv2 # pip install opencv-python\n import io\n with lmdb.open(lmdb_dir, readonly=True).begin(write=False) as txn:\n total_images = txn.stat()['entries']\n if max_images is None:\n max_images = total_images\n with TFRecordExporter(tfrecord_dir, max_images) as tfr:\n for idx, (key, value) in enumerate(txn.cursor()):\n try:\n try:\n img = cv2.imdecode(np.fromstring(value, dtype=np.uint8), 1)\n if img is None:\n raise IOError('cv2.imdecode failed')\n img = img[:, :, ::-1] # BGR => RGB\n except IOError:\n img = np.asarray(PIL.Image.open(io.BytesIO(value)))\n crop = np.min(img.shape[:2])\n img = img[(img.shape[0] - crop) // 2 : (img.shape[0] + crop) // 2, (img.shape[1] - crop) // 2 : (img.shape[1] + crop) // 2]\n img = PIL.Image.fromarray(img, 'RGB')\n img = img.resize((resolution, resolution), PIL.Image.ANTIALIAS)\n img = np.asarray(img)\n img = img.transpose(2, 0, 1) # HWC => CHW\n tfr.add_image(img)\n except:\n print(sys.exc_info()[1])\n if tfr.cur_images == max_images:\n break\n \n#----------------------------------------------------------------------------\n\ndef create_celeba(tfrecord_dir, celeba_dir, cx=89, cy=121):\n print('Loading CelebA from \"%s\"' % celeba_dir)\n glob_pattern = os.path.join(celeba_dir, 'img_align_celeba_png', '*.png')\n image_filenames = sorted(glob.glob(glob_pattern))\n expected_images = 202599\n if len(image_filenames) != expected_images:\n error('Expected to find %d images' % expected_images)\n \n with TFRecordExporter(tfrecord_dir, len(image_filenames)) as tfr:\n order = tfr.choose_shuffled_order()\n for idx in range(order.size):\n img = np.asarray(PIL.Image.open(image_filenames[order[idx]]))\n assert img.shape == (218, 178, 3)\n img = img[cy - 64 : cy + 64, cx - 64 : cx + 64]\n img = img.transpose(2, 0, 1) # HWC => CHW\n tfr.add_image(img)\n\n#----------------------------------------------------------------------------\n\ndef create_celebahq(tfrecord_dir, celeba_dir, delta_dir, num_threads=4, num_tasks=100):\n print('Loading CelebA from \"%s\"' % celeba_dir)\n expected_images = 202599\n if len(glob.glob(os.path.join(celeba_dir, 'img_celeba', '*.jpg'))) != expected_images:\n error('Expected to find %d images' % expected_images)\n with open(os.path.join(celeba_dir, 'Anno', 'list_landmarks_celeba.txt'), 'rt') as file:\n landmarks = [[float(value) for value in line.split()[1:]] for line in file.readlines()[2:]]\n landmarks = np.float32(landmarks).reshape(-1, 5, 2)\n \n print('Loading CelebA-HQ deltas from \"%s\"' % delta_dir)\n import scipy.ndimage\n import hashlib\n import bz2\n import zipfile\n import base64\n import cryptography.hazmat.primitives.hashes\n import cryptography.hazmat.backends\n import cryptography.hazmat.primitives.kdf.pbkdf2\n import cryptography.fernet\n expected_zips = 30\n if len(glob.glob(os.path.join(delta_dir, 'delta*.zip'))) != expected_zips:\n error('Expected to find %d zips' % expected_zips)\n with open(os.path.join(delta_dir, 'image_list.txt'), 'rt') as file:\n lines = [line.split() for line in file]\n fields = dict()\n for idx, field in enumerate(lines[0]):\n type = int if field.endswith('idx') else str\n fields[field] = [type(line[idx]) for line in lines[1:]]\n indices = np.array(fields['idx'])\n\n # Must use pillow version 3.1.1 for everything to work correctly.\n if getattr(PIL, 'PILLOW_VERSION', '') != '3.1.1':\n error('create_celebahq requires pillow version 3.1.1') # conda install pillow=3.1.1\n \n # Must use libjpeg version 8d for everything to work correctly.\n img = np.array(PIL.Image.open(os.path.join(celeba_dir, 'img_celeba', '000001.jpg')))\n md5 = hashlib.md5()\n md5.update(img.tobytes())\n if md5.hexdigest() != '9cad8178d6cb0196b36f7b34bc5eb6d3':\n error('create_celebahq requires libjpeg version 8d') # conda install jpeg=8d\n\n def rot90(v):\n return np.array([-v[1], v[0]])\n\n def process_func(idx):\n # Load original image.\n orig_idx = fields['orig_idx'][idx]\n orig_file = fields['orig_file'][idx]\n orig_path = os.path.join(celeba_dir, 'img_celeba', orig_file)\n img = PIL.Image.open(orig_path)\n\n # Choose oriented crop rectangle.\n lm = landmarks[orig_idx]\n eye_avg = (lm[0] + lm[1]) * 0.5 + 0.5\n mouth_avg = (lm[3] + lm[4]) * 0.5 + 0.5\n eye_to_eye = lm[1] - lm[0]\n eye_to_mouth = mouth_avg - eye_avg\n x = eye_to_eye - rot90(eye_to_mouth)\n x /= np.hypot(*x)\n x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)\n y = rot90(x)\n c = eye_avg + eye_to_mouth * 0.1\n quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])\n zoom = 1024 / (np.hypot(*x) * 2)\n\n # Shrink.\n shrink = int(np.floor(0.5 / zoom))\n if shrink > 1:\n size = (int(np.round(float(img.size[0]) / shrink)), int(np.round(float(img.size[1]) / shrink)))\n img = img.resize(size, PIL.Image.ANTIALIAS)\n quad /= shrink\n zoom *= shrink\n\n # Crop.\n border = max(int(np.round(1024 * 0.1 / zoom)), 3)\n crop = (int(np.floor(min(quad[:,0]))), int(np.floor(min(quad[:,1]))), int(np.ceil(max(quad[:,0]))), int(np.ceil(max(quad[:,1]))))\n crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]), min(crop[3] + border, img.size[1]))\n if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:\n img = img.crop(crop)\n quad -= crop[0:2]\n\n # Simulate super-resolution.\n superres = int(np.exp2(np.ceil(np.log2(zoom))))\n if superres > 1:\n img = img.resize((img.size[0] * superres, img.size[1] * superres), PIL.Image.ANTIALIAS)\n quad *= superres\n zoom /= superres\n\n # Pad.\n pad = (int(np.floor(min(quad[:,0]))), int(np.floor(min(quad[:,1]))), int(np.ceil(max(quad[:,0]))), int(np.ceil(max(quad[:,1]))))\n pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0), max(pad[3] - img.size[1] + border, 0))\n if max(pad) > border - 4:\n pad = np.maximum(pad, int(np.round(1024 * 0.3 / zoom)))\n img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')\n h, w, _ = img.shape\n y, x, _ = np.mgrid[:h, :w, :1]\n mask = 1.0 - np.minimum(np.minimum(np.float32(x) / pad[0], np.float32(y) / pad[1]), np.minimum(np.float32(w-1-x) / pad[2], np.float32(h-1-y) / pad[3]))\n blur = 1024 * 0.02 / zoom\n img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)\n img += (np.median(img, axis=(0,1)) - img) * np.clip(mask, 0.0, 1.0)\n img = PIL.Image.fromarray(np.uint8(np.clip(np.round(img), 0, 255)), 'RGB')\n quad += pad[0:2]\n \n # Transform.\n img = img.transform((4096, 4096), PIL.Image.QUAD, (quad + 0.5).flatten(), PIL.Image.BILINEAR)\n img = img.resize((1024, 1024), PIL.Image.ANTIALIAS)\n img = np.asarray(img).transpose(2, 0, 1)\n \n # Verify MD5.\n md5 = hashlib.md5()\n md5.update(img.tobytes())\n assert md5.hexdigest() == fields['proc_md5'][idx]\n \n # Load delta image and original JPG.\n with zipfile.ZipFile(os.path.join(delta_dir, 'deltas%05d.zip' % (idx - idx % 1000)), 'r') as zip:\n delta_bytes = zip.read('delta%05d.dat' % idx)\n with open(orig_path, 'rb') as file:\n orig_bytes = file.read()\n \n # Decrypt delta image, using original JPG data as decryption key.\n algorithm = cryptography.hazmat.primitives.hashes.SHA256()\n backend = cryptography.hazmat.backends.default_backend()\n salt = bytes(orig_file, 'ascii')\n kdf = cryptography.hazmat.primitives.kdf.pbkdf2.PBKDF2HMAC(algorithm=algorithm, length=32, salt=salt, iterations=100000, backend=backend)\n key = base64.urlsafe_b64encode(kdf.derive(orig_bytes))\n delta = np.frombuffer(bz2.decompress(cryptography.fernet.Fernet(key).decrypt(delta_bytes)), dtype=np.uint8).reshape(3, 1024, 1024)\n \n # Apply delta image.\n img = img + delta\n \n # Verify MD5.\n md5 = hashlib.md5()\n md5.update(img.tobytes())\n assert md5.hexdigest() == fields['final_md5'][idx]\n return img\n\n with TFRecordExporter(tfrecord_dir, indices.size) as tfr:\n order = tfr.choose_shuffled_order()\n with ThreadPool(num_threads) as pool:\n for img in pool.process_items_concurrently(indices[order].tolist(), process_func=process_func, max_items_in_flight=num_tasks):\n tfr.add_image(img)\n\n#----------------------------------------------------------------------------\n\ndef create_from_images(tfrecord_dir, image_dir, shuffle):\n print('Loading images from \"%s\"' % image_dir)\n image_filenames = sorted(glob.glob(os.path.join(image_dir, '*')))\n if len(image_filenames) == 0:\n error('No input images found')\n \n img = np.asarray(PIL.Image.open(image_filenames[0]))\n resolution = img.shape[0]\n channels = img.shape[2] if img.ndim == 3 else 1\n if img.shape[1] != resolution:\n error('Input images must have the same width and height')\n if resolution != 2 ** int(np.floor(np.log2(resolution))):\n error('Input image resolution must be a power-of-two')\n if channels not in [1, 3]:\n error('Input images must be stored as RGB or grayscale')\n \n with TFRecordExporter(tfrecord_dir, len(image_filenames)) as tfr:\n order = tfr.choose_shuffled_order() if shuffle else np.arange(len(image_filenames))\n for idx in range(order.size):\n img = np.asarray(PIL.Image.open(image_filenames[order[idx]]))\n if channels == 1:\n img = img[np.newaxis, :, :] # HW => CHW\n else:\n img = img.transpose(2, 0, 1) # HWC => CHW\n tfr.add_image(img)\n\n#----------------------------------------------------------------------------\n\ndef create_from_hdf5(tfrecord_dir, hdf5_filename, shuffle):\n print('Loading HDF5 archive from \"%s\"' % hdf5_filename)\n import h5py # conda install h5py\n with h5py.File(hdf5_filename, 'r') as hdf5_file:\n hdf5_data = max([value for key, value in hdf5_file.items() if key.startswith('data')], key=lambda lod: lod.shape[3])\n with TFRecordExporter(tfrecord_dir, hdf5_data.shape[0]) as tfr:\n order = tfr.choose_shuffled_order() if shuffle else np.arange(hdf5_data.shape[0])\n for idx in range(order.size):\n tfr.add_image(hdf5_data[order[idx]])\n npy_filename = os.path.splitext(hdf5_filename)[0] + '-labels.npy'\n if os.path.isfile(npy_filename):\n tfr.add_labels(np.load(npy_filename)[order])\n\n#----------------------------------------------------------------------------\n\ndef execute_cmdline(argv):\n prog = argv[0]\n parser = argparse.ArgumentParser(\n prog = prog,\n description = 'Tool for creating, extracting, and visualizing Progressive GAN datasets.',\n epilog = 'Type \"%s <command> -h\" for more information.' % prog)\n \n subparsers = parser.add_subparsers(dest='command')\n subparsers.required = True\n def add_command(cmd, desc, example=None):\n epilog = 'Example: %s %s' % (prog, example) if example is not None else None\n return subparsers.add_parser(cmd, description=desc, help=desc, epilog=epilog)\n\n p = add_command( 'display', 'Display images in dataset.',\n 'display datasets/mnist')\n p.add_argument( 'tfrecord_dir', help='Directory containing dataset')\n \n p = add_command( 'extract', 'Extract images from dataset.',\n 'extract datasets/mnist mnist-images')\n p.add_argument( 'tfrecord_dir', help='Directory containing dataset')\n p.add_argument( 'output_dir', help='Directory to extract the images into')\n\n p = add_command( 'compare', 'Compare two datasets.',\n 'compare datasets/mydataset datasets/mnist')\n p.add_argument( 'tfrecord_dir_a', help='Directory containing first dataset')\n p.add_argument( 'tfrecord_dir_b', help='Directory containing second dataset')\n p.add_argument( '--ignore_labels', help='Ignore labels (default: 0)', type=int, default=0)\n\n p = add_command( 'create_mnist', 'Create dataset for MNIST.',\n 'create_mnist datasets/mnist ~/downloads/mnist')\n p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')\n p.add_argument( 'mnist_dir', help='Directory containing MNIST')\n\n p = add_command( 'create_mnistrgb', 'Create dataset for MNIST-RGB.',\n 'create_mnistrgb datasets/mnistrgb ~/downloads/mnist')\n p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')\n p.add_argument( 'mnist_dir', help='Directory containing MNIST')\n p.add_argument( '--num_images', help='Number of composite images to create (default: 1000000)', type=int, default=1000000)\n p.add_argument( '--random_seed', help='Random seed (default: 123)', type=int, default=123)\n\n p = add_command( 'create_cifar10', 'Create dataset for CIFAR-10.',\n 'create_cifar10 datasets/cifar10 ~/downloads/cifar10')\n p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')\n p.add_argument( 'cifar10_dir', help='Directory containing CIFAR-10')\n\n p = add_command( 'create_cifar100', 'Create dataset for CIFAR-100.',\n 'create_cifar100 datasets/cifar100 ~/downloads/cifar100')\n p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')\n p.add_argument( 'cifar100_dir', help='Directory containing CIFAR-100')\n\n p = add_command( 'create_svhn', 'Create dataset for SVHN.',\n 'create_svhn datasets/svhn ~/downloads/svhn')\n p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')\n p.add_argument( 'svhn_dir', help='Directory containing SVHN')\n\n p = add_command( 'create_lsun', 'Create dataset for single LSUN category.',\n 'create_lsun datasets/lsun-car-100k ~/downloads/lsun/car_lmdb --resolution 256 --max_images 100000')\n p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')\n p.add_argument( 'lmdb_dir', help='Directory containing LMDB database')\n p.add_argument( '--resolution', help='Output resolution (default: 256)', type=int, default=256)\n p.add_argument( '--max_images', help='Maximum number of images (default: none)', type=int, default=None)\n\n p = add_command( 'create_celeba', 'Create dataset for CelebA.',\n 'create_celeba datasets/celeba ~/downloads/celeba')\n p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')\n p.add_argument( 'celeba_dir', help='Directory containing CelebA')\n p.add_argument( '--cx', help='Center X coordinate (default: 89)', type=int, default=89)\n p.add_argument( '--cy', help='Center Y coordinate (default: 121)', type=int, default=121)\n\n p = add_command( 'create_celebahq', 'Create dataset for CelebA-HQ.',\n 'create_celebahq datasets/celebahq ~/downloads/celeba ~/downloads/celeba-hq-deltas')\n p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')\n p.add_argument( 'celeba_dir', help='Directory containing CelebA')\n p.add_argument( 'delta_dir', help='Directory containing CelebA-HQ deltas')\n p.add_argument( '--num_threads', help='Number of concurrent threads (default: 4)', type=int, default=4)\n p.add_argument( '--num_tasks', help='Number of concurrent processing tasks (default: 100)', type=int, default=100)\n\n p = add_command( 'create_from_images', 'Create dataset from a directory full of images.',\n 'create_from_images datasets/mydataset myimagedir')\n p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')\n p.add_argument( 'image_dir', help='Directory containing the images')\n p.add_argument( '--shuffle', help='Randomize image order (default: 1)', type=int, default=1)\n\n p = add_command( 'create_from_hdf5', 'Create dataset from legacy HDF5 archive.',\n 'create_from_hdf5 datasets/celebahq ~/downloads/celeba-hq-1024x1024.h5')\n p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')\n p.add_argument( 'hdf5_filename', help='HDF5 archive containing the images')\n p.add_argument( '--shuffle', help='Randomize image order (default: 1)', type=int, default=1)\n\n args = parser.parse_args(argv[1:] if len(argv) > 1 else ['-h'])\n func = globals()[args.command]\n del args.command\n func(**vars(args))\n\n#----------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n execute_cmdline(sys.argv)\n\n#----------------------------------------------------------------------------\n"
] | [
[
"numpy.asarray",
"tensorflow.train.Int64List",
"numpy.random.RandomState",
"numpy.stack",
"tensorflow.python_io.TFRecordWriter",
"numpy.round",
"numpy.fromstring",
"numpy.load",
"numpy.hypot",
"tensorflow.python_io.TFRecordOptions",
"numpy.float32",
"numpy.median",
"numpy.arange",
"numpy.all",
"numpy.max",
"numpy.min",
"numpy.pad",
"numpy.rint",
"numpy.log2",
"numpy.floor",
"numpy.clip",
"numpy.array",
"numpy.concatenate"
]
] |
BAMresearch/ctsimu-toolbox | [
"2329fe0bba8a89061430649c043c70c58835a435"
] | [
"ctsimu/image.py"
] | [
"# -*- coding: UTF-8 -*-\r\n\"\"\"\r\nThis module provides classes for the virtual processing of images.\r\n\r\n* `Image` reads, stores, writes and handles image data.\r\n* `ImageFile` gathers information about an image file: file name, data type,\r\n byte order. It is used to instruct the `Image.read()` and `Image.save()`\r\n routines.\r\n* `ImageStack` represents a stack of images in the file system. It can be used\r\n in combination with a processing pipeline (see `ctsimu.processing`).\r\n* `ImageROI` defines a pixel region of interest in an image.\r\n\r\nImages\r\n------\r\nTo import a single image, you can specify its file name in the constructor\r\nand then use the `Image.read()` function to import it into the internal memory.\r\nIt will be stored in `Image.px` as a float64 NumPy array. When writing an\r\nimage using `Image.save()`, you have to specify the data type for the new file.\r\n\r\n from ctsimu.image import Image\r\n \r\n myImage = Image(\"example.tif\")\r\n myImage.read()\r\n \r\n # Mirror horizontally:\r\n myImage.flipHorizontal()\r\n \r\n myImage.save(\"example_mirrored.raw\", dataType=\"float32\")\r\n\r\n\r\nRAW File Handling\r\n-----------------\r\nTo read raw image data, its dimensions, data type, byte order and header size\r\nmust be specified:\r\n\r\n from ctsimu.image import Image\r\n\r\n myImage = Image(\"example_mirrored.raw\")\r\n myImage.read(width=501,\r\n height=501,\r\n dataType=\"float32\",\r\n byteOrder=\"little\",\r\n fileHeaderSize=0)\r\n\r\n # Export as big endian, uint16:\r\n myImage.save(\"example_converted.raw\",\r\n dataType=\"uint16\",\r\n byteOrder=\"big\")\r\n\r\n\"\"\"\r\n\r\nimport numpy\r\nimport os # File and path handling\r\nimport sys # To get native byte order ('little' or 'big' endian?)\r\nimport math\r\nimport copy\r\nfrom numpy.random import default_rng\r\n\r\n# Scipy:\r\n# 'ndimage' class for image processing\r\n# 'optimize' class for intensity fit\r\n# 'signal' class for drift analysis using FFT Convolution\r\nfrom scipy import ndimage, optimize, stats, signal, fft\r\n\r\nfrom .helpers import *\r\nfrom .primitives import * # Vectors and Polygons\r\nfrom .tiffy import tiff\r\n\r\n# pixelHalfDiagonal: longest distance a pixel center can have from a line\r\n# while still touching the line with a corner point:\r\npixelHalfDiagonal = 1.0/math.sqrt(2.0)\r\n\r\ndef isTIFF(filename: str) -> bool:\r\n \"\"\"Check if file name signifies a TIFF image.\"\"\"\r\n if filename is not None:\r\n if(filename.casefold().endswith('.tif') or filename.casefold().endswith('.tiff')):\r\n return True\r\n \r\n return False\r\n\r\ndef createImageStack(stack):\r\n \"\"\" Return an ImageStack object, if string is given. \"\"\"\r\n if isinstance(stack, ImageStack):\r\n return stack\r\n elif isinstance(stack, str):\r\n return ImageStack(stack)\r\n elif stack is None:\r\n return None\r\n else:\r\n raise Exception(\"Not a valid image file stack definition: {}\".format(stack))\r\n\r\nclass ImageFile:\r\n \"\"\"Fundamental image file properties used for input and output.\"\"\"\r\n\r\n def __init__(self, filename=None, dataType=None, byteOrder=None, flipByteOrder=False):\r\n self.filename = None\r\n self.dataType = None\r\n self.byteOrder = None # 'little' or 'big' endian\r\n self.flipByteOrder = False\r\n\r\n self.setFilename(filename)\r\n self.setDataType(dataType)\r\n self.setByteOrder(byteOrder)\r\n self.setFlipByteOrder(flipByteOrder)\r\n\r\n def setFilename(self, filename):\r\n self.filename = filename\r\n\r\n def getFilename(self) -> str:\r\n return self.filename\r\n\r\n def getFileBasename(self) -> str:\r\n return os.path.basename(self.filename)\r\n\r\n def getDataType(self) -> str:\r\n return self.dataType\r\n\r\n def getByteOrder(self) -> str:\r\n return self.byteOrder\r\n\r\n def doFlipByteOrder(self) -> bool:\r\n return self.flipByteOrder\r\n\r\n def setDataType(self, dataType: str):\r\n \"\"\" Set data type, either from numpy.dtype object or string. \"\"\"\r\n if isinstance(dataType, numpy.dtype):\r\n self.dataType = dataType\r\n elif dataType is None:\r\n self.dataType = None\r\n elif isinstance(dataType, str): # from string\r\n dt = numpy.dtype(dataType)\r\n self.setDataType(dt)\r\n else:\r\n raise Exception(\"{} is generally not a valid data type.\".format(dataType))\r\n\r\n def setByteOrder(self, byteOrder: str):\r\n \"\"\" Set endianness, do sanity check before. \"\"\"\r\n if byteOrder=='little' or byteOrder=='big' or byteOrder==None:\r\n self.byteOrder = byteOrder\r\n else:\r\n raise Exception(\"{} is not a valid byte order. Must be 'little' or 'big'.\".format(byteOrder))\r\n\r\n def setFlipByteOrder(self, flipByteOrder: bool):\r\n self.flipByteOrder = flipByteOrder\r\n\r\n def isInt(self) -> bool:\r\n \"\"\" True if data type is supported int data type. \"\"\"\r\n return numpy.issubdtype(self.dataType, numpy.integer)\r\n\r\n def isFloat(self) -> bool:\r\n \"\"\" True if data type is supported float data type. \"\"\"\r\n return numpy.issubdtype(self.dataType, numpy.floating)\r\n\r\nclass ImageROI:\r\n \"\"\" Defines a region of interest: upper left and lower right corner. \"\"\"\r\n\r\n def __init__(self, x0, y0, x1, y1):\r\n self.x0 = 0\r\n self.y0 = 0\r\n self.x1 = 0\r\n self.y1 = 0\r\n self.set(x0, y0, x1, y1)\r\n\r\n def __str__(self):\r\n return \"({x0}, {y0}) -- ({x1}, {y1})\".format(x0=self.x0, y0=self.y0, x1=self.x1, y1=self.y1)\r\n\r\n def set(self, x0, y0, x1, y1):\r\n if x1 < x0:\r\n x0, x1 = x1, x0\r\n\r\n if y1 < y0:\r\n y0, y1 = y1, y0\r\n\r\n self.x0 = int(x0)\r\n self.y0 = int(y0)\r\n self.x1 = int(x1)\r\n self.y1 = int(y1)\r\n\r\n def width(self):\r\n return self.x1 - self.x0\r\n\r\n def height(self):\r\n return self.y1 - self.y0\r\n\r\n def area(self):\r\n return self.width()*self.height()\r\n\r\n def grow(self, amount):\r\n amount = int(amount)\r\n self.set(self.x0-amount, self.y0-amount, self.x1+amount, self.y1+amount)\r\n\r\n\r\nclass Image:\r\n \"\"\" Stores pixel data, provides image processing routines. \"\"\"\r\n\r\n def __init__(self, inputFile=None, outputFile=None):\r\n self.inputFile = None # type ImageFile or string\r\n self.outputFile = None # type ImageFile or string\r\n self.px = 0 # 2D numpy array that contains the pixel values.\r\n self.height = 0 # Image height in px.\r\n self.width = 0 # Image width in px.\r\n self.index = 0 # Slice number in a 3D volume.\r\n\r\n self.rotation = None\r\n self.flipHorz = False\r\n self.flipVert = False\r\n\r\n self.n_accumulations = 0 # Counts number of accumulated pictures for averaging (mean)\r\n self.boundingBoxX0 = 0 # After cropping: bounding box offset relative to original image.\r\n self.boundingBoxY0 = 0\r\n self.resolution = 1 # After binning: new resolution relative to original image.\r\n\r\n self.setInputFile(inputFile)\r\n self.setOutputFile(outputFile)\r\n\r\n def __add__(self, other):\r\n if self.dimensionsMatch(other):\r\n result = copy.deepcopy(self)\r\n result.px += other.px\r\n return result\r\n else:\r\n raise Exception(\"Cannot add images of different dimensions.\")\r\n\r\n def __sub__(self, other):\r\n if self.dimensionsMatch(other):\r\n result = copy.deepcopy(self)\r\n result.px -= other.px\r\n return result\r\n else:\r\n raise Exception(\"Cannot subtract images of different dimensions.\")\r\n\r\n def __mul__(self, other):\r\n if self.dimensionsMatch(other):\r\n result = copy.deepcopy(self)\r\n result.px *= other.px\r\n return result\r\n else:\r\n raise Exception(\"Cannot multiply images of different dimensions.\")\r\n\r\n def __truediv__(self, other):\r\n if self.dimensionsMatch(other):\r\n result = copy.deepcopy(self)\r\n result.px[numpy.nonzero(other.px)] /= other.px[numpy.nonzero(other.px)]\r\n result.px = numpy.where(other.px==0, 0, result.px)\r\n return result\r\n else:\r\n raise Exception(\"Cannot divide images of different dimensions.\")\r\n\r\n def __floordiv__(self, other):\r\n if self.dimensionsMatch(other):\r\n result = copy.deepcopy(self)\r\n result.px[numpy.nonzero(other.px)] //= other.px[numpy.nonzero(other.px)]\r\n result = numpy.where(other.px==0, 0, result.px)\r\n return result\r\n else:\r\n raise Exception(\"Cannot divide images of different dimensions.\")\r\n\r\n def __del__(self):\r\n \"\"\" Delete pixel map upon object destruction. \"\"\"\r\n self.px =0\r\n\r\n def setInputFile(self, inputFile):\r\n \"\"\" Set input file properties from ImageFile object or string. \"\"\"\r\n if isinstance(inputFile, ImageFile) or (inputFile is None):\r\n self.inputFile = inputFile\r\n elif isinstance(inputFile, str): # string given\r\n self.inputFile = ImageFile(inputFile)\r\n else:\r\n raise Exception(\"{} is not a valid file identifier.\")\r\n\r\n def setOutputFile(self, outputFile):\r\n \"\"\" Set output file properties from ImageFile object or string. \"\"\"\r\n if isinstance(outputFile, ImageFile) or (outputFile is None):\r\n self.outputFile = outputFile\r\n elif isinstance(outputFile, str): # string given\r\n self.outputFile = ImageFile(outputFile)\r\n else:\r\n raise Exception(\"{} is not a valid file identifier.\")\r\n\r\n def setHeight(self, height):\r\n \"\"\" Set image height in px. \"\"\"\r\n self.height = height\r\n\r\n def setWidth(self, width):\r\n \"\"\" Set image width in px. \"\"\"\r\n self.width = width\r\n\r\n def setIndex(self, index):\r\n \"\"\" Set image index position in 3D stack (in px). \"\"\"\r\n self.index = index\r\n\r\n def shape(self, width, height, index=0, dataType=None, value=0):\r\n \"\"\" Re-format image to given dimensions and data type. \"\"\"\r\n self.setWidth(width)\r\n self.setHeight(height)\r\n self.setIndex(index)\r\n\r\n if dataType is None:\r\n dataType = self.getInternalDataType()\r\n\r\n self.erase(value=0, dataType=dataType)\r\n\r\n def shapeLike(self, otherImg, dataType=None):\r\n self.setWidth(otherImg.getWidth())\r\n self.setHeight(otherImg.getHeight())\r\n self.setIndex(otherImg.getIndex())\r\n\r\n if dataType is None:\r\n dataType = otherImg.getInternalDataType()\r\n\r\n self.erase(value=0, dataType=dataType)\r\n\r\n def erase(self, value=0, dataType=None):\r\n \"\"\" Set all pixels to 'value'. \"\"\"\r\n w = self.getWidth()\r\n h = self.getHeight()\r\n\r\n if dataType is None:\r\n dataType = self.getInternalDataType()\r\n\r\n self.px = 0\r\n self.px = numpy.full((h, w), fill_value=value, dtype=dataType)\r\n \r\n def getPixelMap(self):\r\n return self.px\r\n\r\n def setPixelMap(self, px):\r\n self.px = px\r\n\r\n def setPixel(self, x, y, value):\r\n self.px[y][x] = value\r\n\r\n def getPixel(self, x, y):\r\n return self.px[y][x]\r\n\r\n def isSet(self):\r\n \"\"\" Check if image has a valid width and height. \"\"\"\r\n if(self.getHeight() > 0):\r\n if(self.getWidth() > 0):\r\n return True\r\n\r\n return False\r\n\r\n def contains(self, x, y):\r\n \"\"\" Check if (x, y) is within image dimensions. \"\"\"\r\n if x >= 0:\r\n if y >= 0:\r\n if x < self.getWidth():\r\n if y < self.getHeight():\r\n return True\r\n\r\n return False\r\n\r\n def getWidth(self):\r\n return self.width\r\n\r\n def getHeight(self):\r\n return self.height\r\n\r\n def getNPixels(self):\r\n \"\"\" Calculate number of pixels in image. \"\"\"\r\n return (self.getWidth() * self.getHeight())\r\n\r\n def getIndex(self):\r\n return self.index\r\n\r\n def getBoundingBoxX0(self):\r\n return self.boundingBoxX0\r\n\r\n def getBoundingBoxY0(self):\r\n return self.boundingBoxY0\r\n\r\n def getResolution(self):\r\n return self.resolution\r\n\r\n def getFileByteOrder(self):\r\n return self.fileByteOrder\r\n\r\n def max(self, ROI=None):\r\n \"\"\" Return maximum intensity in image. \"\"\"\r\n\r\n # Take full image if no ROI is given\r\n if ROI==None:\r\n return numpy.amax(self.px)\r\n\r\n return numpy.amax(self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1])\r\n\r\n def min(self, ROI=None):\r\n \"\"\" Return minimum intensity in image. \"\"\"\r\n\r\n # Take full image if no ROI is given\r\n if ROI==None:\r\n return numpy.amin(self.px)\r\n\r\n return numpy.amin(self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1])\r\n\r\n def mean(self, ROI=None):\r\n \"\"\" Return arithmetic mean of the image grey values. \"\"\"\r\n \r\n # Take full image if no ROI is given\r\n if ROI==None:\r\n return numpy.mean(self.px)\r\n\r\n return numpy.mean(self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1])\r\n\r\n def stdDev(self, ROI=None):\r\n \"\"\" Return the standard deviation of the image grey values. \"\"\"\r\n\r\n # Take full image if no ROI is given\r\n if ROI==None:\r\n return numpy.std(self.px)\r\n\r\n return numpy.std(self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1])\r\n\r\n def centerOfMass(self):\r\n return ndimage.center_of_mass(self.px)\r\n\r\n def setRotation(self, rotation):\r\n self.rotation = rotation\r\n\r\n def getRotation(self):\r\n return self.rotation\r\n\r\n def rot90(self):\r\n if self.isSet():\r\n self.px = numpy.require(numpy.rot90(self.px, k=1), requirements=['C_CONTIGUOUS'])\r\n self.width, self.height = self.height, self.width\r\n\r\n def rot180(self):\r\n if self.isSet():\r\n self.px = numpy.require(numpy.rot90(self.px, k=2), requirements=['C_CONTIGUOUS'])\r\n\r\n def rot270(self):\r\n if self.isSet():\r\n self.px = numpy.require(numpy.rot90(self.px, k=-1), requirements=['C_CONTIGUOUS'])\r\n self.width, self.height = self.height, self.width\r\n\r\n def rotate(self, rotation):\r\n if rotation is None:\r\n rotation = self.rotation\r\n else:\r\n self.setRotation(rotation)\r\n\r\n if rotation == \"90\":\r\n self.rot90()\r\n elif rotation == \"180\":\r\n self.rot180()\r\n elif rotation == \"270\":\r\n self.rot270()\r\n\r\n def flipHorizontal(self):\r\n self.flipHorz = not self.flipHorz\r\n if self.isSet():\r\n self.px = numpy.require(numpy.fliplr(self.px), requirements=['C_CONTIGUOUS'])\r\n\r\n def flipVertical(self):\r\n self.flipVert = not self.flipVert\r\n if self.isSet():\r\n self.px = numpy.require(numpy.flipud(self.px), requirements=['C_CONTIGUOUS'])\r\n\r\n def setFlip(self, horz=False, vert=False):\r\n self.flipHorz = horz\r\n self.flipVert = vert\r\n\r\n def getHorizontalFlip(self):\r\n return self.flipHorz\r\n\r\n def getVerticalFlip(self):\r\n return self.flipVert\r\n\r\n def flip(self, horizontal=False, vertical=False):\r\n if horizontal:\r\n self.flipHorizontal()\r\n if vertical:\r\n self.flipVertical()\r\n\r\n def getInternalDataType(self):\r\n \"\"\" Data type used internally for all image data. \"\"\"\r\n return numpy.dtype('float64')\r\n\r\n def containsPixelValue(self, value):\r\n \"\"\" Check if image contains a certain grey value. \"\"\"\r\n return numpy.any(self.px == value)\r\n\r\n def dimensionsMatch(self, img):\r\n \"\"\" Check if image dimensions match with another image. \"\"\"\r\n if self.isSet() and img.isSet():\r\n if(self.getHeight() == img.getHeight()):\r\n if(self.getWidth() == img.getWidth()):\r\n return True\r\n\r\n raise Exception(\"Pixel dimensions do not match: {}x{} vs. {}x{}\".format(self.getWidth(), self.getHeight(), img.getWidth(), img.getHeight()))\r\n \r\n return False\r\n\r\n def read(self, filename=None, width=None, height=None, index=0, dataType=None, byteOrder=None, fileHeaderSize=0, imageHeaderSize=0):\r\n \"\"\" Read TIFF or RAW, decide by file name. \"\"\"\r\n if filename is None:\r\n filename = self.inputFile.getFilename()\r\n else:\r\n self.setInputFile(filename)\r\n\r\n # If no internal file name is specified, do nothing.\r\n if filename is None:\r\n return\r\n\r\n if isTIFF(self.inputFile.getFilename()):\r\n self.readTIFF(self.inputFile.doFlipByteOrder())\r\n else:\r\n self.readRAW(width=width, height=height, index=index, dataType=dataType, byteOrder=byteOrder, fileHeaderSize=fileHeaderSize, imageHeaderSize=imageHeaderSize)\r\n\r\n def readTIFF(self, flipByteOrder=False, obeyOrientation=True):\r\n \"\"\" Import TIFF file. \"\"\"\r\n if os.path.isfile(self.inputFile.getFilename()):\r\n basename = self.inputFile.getFileBasename()\r\n \r\n tiffimg = tiff()\r\n tiffimg.read(self.inputFile.getFilename())\r\n img = tiffimg.imageData(subfile=0, channel=0, obeyOrientation=obeyOrientation) # get a greyscale image from TIFF subfile 0\r\n width = tiffimg.getWidth(subfile=0)\r\n height = tiffimg.getHeight(subfile=0)\r\n\r\n self.inputFile.setDataType(img.dtype) \r\n\r\n if flipByteOrder:\r\n img.byteswap(inplace=True)\r\n\r\n # Convert to internal data type for either int or float:\r\n self.px = img.astype(self.getInternalDataType())\r\n\r\n # Check if array in memory has the dimensions stated in the TIFF file:\r\n if((height == len(self.px)) and (width == len(self.px[0]))):\r\n self.setHeight(height)\r\n self.setWidth(width)\r\n else:\r\n raise Exception(\"Width ({}px) and height ({}px) from the TIFF header do not match the data width ({}px) and height ({}px) that has been read.\".format(width, height, len(self.px[0]), len(self.px)))\r\n else:\r\n raise Exception(\"Can't find \" + self.inputFile.getFilename())\r\n\r\n def readRAW(self, width, height, index=0, dataType=None, byteOrder=None, fileHeaderSize=0, imageHeaderSize=0):\r\n \"\"\" Import RAW image file. \"\"\"\r\n if not isinstance(self.inputFile, ImageFile):\r\n raise Exception(\"No valid input file defined.\")\r\n\r\n if dataType is None:\r\n dataType = self.inputFile.getDataType()\r\n else:\r\n self.inputFile.setDataType(dataType)\r\n\r\n if byteOrder is None:\r\n byteOrder = self.inputFile.getByteOrder()\r\n if byteOrder is None:\r\n byteOrder = sys.byteorder\r\n\r\n self.inputFile.setByteOrder(byteOrder)\r\n\r\n if os.path.isfile(self.inputFile.getFilename()):\r\n self.shape(width, height, index, self.inputFile.getDataType())\r\n\r\n basename = self.inputFile.getFileBasename()\r\n #log(\"Reading RAW file {}...\".format(basename))\r\n\r\n byteOffset = fileHeaderSize + (index+1)*imageHeaderSize + index*(self.getNPixels() * self.inputFile.getDataType().itemsize)\r\n\r\n with open(self.inputFile.getFilename(), 'rb') as f:\r\n f.seek(byteOffset)\r\n self.px = numpy.fromfile(f, dtype=self.inputFile.getDataType(), count=self.getNPixels(), sep=\"\")\r\n\r\n if len(self.px) > 0:\r\n # Treat endianness. If the native byte order of the system is different\r\n # than the given file byte order, the bytes are swapped in memory\r\n # so that it matches the native byte order.\r\n nativeEndian = sys.byteorder\r\n if nativeEndian == 'little':\r\n if byteOrder == 'big':\r\n self.px.byteswap(inplace=True)\r\n elif nativeEndian == 'big':\r\n if byteOrder == 'little':\r\n self.px.byteswap(inplace=True)\r\n\r\n # Convert to internal data type:\r\n self.px = self.px.astype(self.getInternalDataType())\r\n\r\n # Reshape to 2D array:\r\n self.px = numpy.reshape(self.px, (height, width))\r\n else:\r\n raise Exception(\"Error reading RAW file {f}.\\nGot no data for index {idx}.\".format(f=self.inputFile.getFilename(), idx=index))\r\n\r\n else:\r\n raise Exception(\"Can't find \" + self.inputFile.getFilename())\r\n\r\n def getDataTypeClippingBoundaries(self, dataType):\r\n # Get clipping boundaries if grey values have to be\r\n # clipped to the interval supported by the int image type:\r\n clipMin = 0\r\n clipMax = 1\r\n if numpy.issubdtype(dataType, numpy.integer):\r\n intInfo = numpy.iinfo(dataType)\r\n clipMin = intInfo.min\r\n clipMax = intInfo.max\r\n elif numpy.issubdtype(dataType, numpy.floating):\r\n floatInfo = numpy.finfo(dataType)\r\n clipMin = floatInfo.min\r\n clipMax = floatInfo.max\r\n\r\n return clipMin, clipMax\r\n\r\n def touchFolder(self, filename):\r\n \"\"\" Check if folder exists. Otherwise, create. \"\"\"\r\n folder = os.path.dirname(filename)\r\n if folder == \"\" or folder is None:\r\n folder = \".\"\r\n if not os.path.exists(folder):\r\n os.makedirs(folder)\r\n\r\n def save(self, filename=None, dataType=None, byteOrder=None, appendChunk=False, clipValues=True):\r\n \"\"\" Save image as TIFF or RAW. \"\"\"\r\n if not isinstance(self.outputFile, ImageFile):\r\n self.outputFile = ImageFile()\r\n\r\n if (filename is None) or (filename == \"\"):\r\n filename = self.outputFile.getFilename()\r\n if (filename is None) or (filename == \"\"):\r\n raise Exception(\"No output file name specified.\")\r\n else:\r\n self.outputFile.setFilename(filename)\r\n\r\n if dataType is None:\r\n dataType = self.outputFile.getDataType()\r\n if dataType is None:\r\n if isinstance(self.inputFile, ImageFile):\r\n dataType = self.inputFile.getDataType()\r\n if(dataType != None):\r\n self.outputFile.setDataType(dataType)\r\n else:\r\n raise Exception(\"Please specify a data type for the output file: {filename}\".format(filename=filename))\r\n else:\r\n raise Exception(\"Please specify a data type for the output file: {filename}\".format(filename=filename))\r\n else:\r\n self.outputFile.setDataType(dataType)\r\n\r\n if byteOrder is None:\r\n byteOrder = self.outputFile.getByteOrder()\r\n if byteOrder is None:\r\n if isinstance(self.inputFile, ImageFile):\r\n byteOrder = self.inputFile.getByteOrder()\r\n self.outputFile.setByteOrder(byteOrder)\r\n\r\n if byteOrder is None:\r\n byteOrder = \"little\"\r\n\r\n self.outputFile.setByteOrder(byteOrder)\r\n\r\n if isTIFF(filename):\r\n self.saveTIFF(filename, dataType, clipValues)\r\n else:\r\n self.saveRAW(filename, dataType, byteOrder, appendChunk, clipValues, addInfo=False)\r\n\r\n def saveTIFF(self, filename=None, dataType=None, clipValues=True):\r\n if (filename != None) and (len(filename) > 0):\r\n fileBaseName = os.path.basename(filename)\r\n if (fileBaseName == \"\") or (fileBaseName is None):\r\n raise Exception(\"No output file name specified for the image to be saved.\")\r\n\r\n if dataType != None:\r\n if not isTIFF(filename):\r\n filename += \".tif\"\r\n\r\n self.touchFolder(filename)\r\n \r\n tiffdata = None\r\n if clipValues: # Clipping\r\n clipMin, clipMax = self.getDataTypeClippingBoundaries(dataType)\r\n tiffdata = numpy.clip(self.px, clipMin, clipMax).astype(dataType)\r\n else: # No clipping or float\r\n tiffdata = self.px.astype(dataType)\r\n\r\n tiffimg = tiff()\r\n tiffimg.set(tiffdata)\r\n tiffimg.save(filename=filename, endian='little')\r\n else:\r\n raise Exception(\"Please specify a data type for the output file: {filename}\".format(filename=filename))\r\n else:\r\n raise Exception(\"No output file name specified for the image to be saved.\")\r\n \r\n def saveRAW(self, filename=None, dataType=None, byteOrder=None, appendChunk=False, clipValues=True, addInfo=False):\r\n if (filename != None) and (len(filename) > 0):\r\n fileBaseName = os.path.basename(filename)\r\n if (fileBaseName == \"\") or (fileBaseName is None):\r\n raise Exception(\"No output file name specified for the image to be saved.\")\r\n\r\n if dataType != None:\r\n if byteOrder is None:\r\n byteOrder = \"little\"\r\n\r\n # Reshape to 1D array and convert to file data type (from internal 64bit data type)\r\n outBytes = numpy.reshape(self.px, int(self.width)*int(self.height))\r\n\r\n if clipValues: # Clipping\r\n clipMin, clipMax = self.getDataTypeClippingBoundaries(dataType)\r\n outBytes = numpy.clip(outBytes, clipMin, clipMax)\r\n\r\n outBytes = outBytes.astype(dataType)\r\n\r\n # Treat endianness. If the native byte order of the system is different\r\n # than the desired file byte order, the bytes are swapped in memory\r\n # before writing to disk.\r\n nativeEndian = sys.byteorder\r\n if nativeEndian == 'little':\r\n if byteOrder == 'big':\r\n outBytes.byteswap(inplace=True)\r\n elif nativeEndian == 'big':\r\n if byteOrder == 'little':\r\n outBytes.byteswap(inplace=True)\r\n\r\n if addInfo:\r\n shortEndian = \"LE\"\r\n if byteOrder == \"big\":\r\n shortEndian = \"BE\"\r\n\r\n infoString = \"_{width}x{height}_{dataType}_{endian}\".format(width=self.width, height=self.height, dataType=dataType, endian=shortEndian)\r\n\r\n basename, extension = os.path.splitext(filename)\r\n filename = basename + infoString + extension\r\n\r\n self.touchFolder(filename)\r\n if not appendChunk: # save as single raw file\r\n with open(filename, 'w+b') as file:\r\n file.write(outBytes)\r\n file.close()\r\n #outBytes.tofile(filename, sep=\"\")\r\n else: # append to the bytes of the chunk file\r\n with open(filename, 'a+b') as file:\r\n file.write(outBytes)\r\n file.close()\r\n else:\r\n raise Exception(\"Please specify a data type for the output file: {filename}\".format(filename=filename))\r\n else:\r\n raise Exception(\"No output file name specified for the image to be saved.\")\r\n\r\n def calcRelativeShift(self, referenceImage):\r\n if self.dimensionsMatch(referenceImage):\r\n # Convolution of this pixmap with the vertically and horizontally mirrored reference pixmap\r\n img1 = self.px - int(numpy.mean(self.px))\r\n img2 = referenceImage.getPixelMap() - numpy.mean(referenceImage.getPixelMap())\r\n\r\n convolution = signal.fftconvolve(img1, img2[::-1,::-1], mode='same')\r\n\r\n maximum = numpy.unravel_index(numpy.argmax(convolution), convolution.shape)\r\n\r\n return (maximum[1] - self.getWidth()/2, maximum[0] - self.getHeight()/2)\r\n else:\r\n raise Exception(\"Dimensions of image ({}, {}) and reference image ({}, {}) must match for convolution.\".format(self.getWidth(), self.getHeight(), referenceImage.getWidth(), referenceImage.getHeight()))\r\n\r\n def getShiftedPixmap(self, xShift, yShift):\r\n return ndimage.interpolation.shift(self.px, (int(xShift), int(yShift)), mode='nearest')\r\n\r\n def accumulate(self, addImg, compensateShift=False, roiX0=None, roiY0=None, roiX1=None, roiY1=None):\r\n if (compensateShift == True) and (self.n_accumulations > 0):\r\n shift = (0, 0)\r\n\r\n if (roiX0 is None) or (roiY0 is None) or (roiX1 is None) or (roiY1 is None):\r\n shift = self.calcRelativeShift(addImg)\r\n else:\r\n # Crop image to drift ROI,\r\n croppedRef = copy.deepcopy(self)\r\n croppedRef.crop(x0=roiX0, y0=roiY0, x1=roiX1, y1=roiY1)\r\n\r\n croppedImg = copy.deepcopy(addImg)\r\n croppedImg.crop(x0=roiX0, y0=roiY0, x1=roiX1, y1=roiY1)\r\n\r\n shift = croppedImg.calcRelativeShift(croppedRef)\r\n\r\n log(\"Shift: {}\".format(shift))\r\n shiftedPixMap = addImg.getShiftedPixmap(shift[1], shift[0])\r\n addImg.setPixelMap(shiftedPixMap)\r\n\r\n if self.n_accumulations == 0:\r\n self.setPixelMap(addImg.getPixelMap())\r\n else:\r\n if (self.dimensionsMatch(addImg)):\r\n self.px += addImg.getPixelMap()\r\n else:\r\n raise Exception(\"Current pixel dimensions ({currentX}x{currentY}) don't match dimensions of new file ({newX}x{newY}): {filename}\".format(currentX=self.getWidth(), currentY=self.getHeight(), newX=addImg.getWidth(), newY=addImg.getHeight(), filename=addImg.inputFile.getFilename()))\r\n\r\n self.n_accumulations += 1\r\n\r\n def resetAccumulations(self):\r\n self.n_accumulations = 0\r\n\r\n def averageAccumulations(self):\r\n if self.n_accumulations > 1:\r\n self.px = self.px / self.n_accumulations\r\n log(\"Accumulated and averaged {} images.\".format(self.n_accumulations))\r\n self.n_accumulations = 1\r\n\r\n def applyDark(self, dark):\r\n \"\"\" Apply dark image correction (offset). \"\"\"\r\n if self.dimensionsMatch(dark):\r\n self.px = self.px - dark.getPixelMap()\r\n else:\r\n raise Exception(\"The dimensions of the image do not match the dimensions of the dark image for offset correction.\")\r\n\r\n def applyFlatfield(self, ref, rescaleFactor=1):\r\n \"\"\" Apply flat field correction (free beam white image / gain correction). \"\"\"\r\n if self.dimensionsMatch(ref):\r\n if(not ref.containsPixelValue(0)): # avoid division by zero\r\n self.px = (self.px / ref.getPixelMap()) * float(rescaleFactor)\r\n else: # avoid division by zero\r\n self.px = (self.px / numpy.clip(ref.getPixelMap(), 0.1, None)) * float(rescaleFactor)\r\n else:\r\n raise Exception(\"The dimensions of the image do not match the dimensions of the flat image for flat field correction.\")\r\n\r\n def verticalProfile(self, xPos):\r\n if xPos < self.getWidth():\r\n return numpy.ravel(self.px[:,xPos])\r\n else:\r\n raise Exception(\"Requested position for vertical profile is out of bounds: x={} in an image that has {} rows.\".format(xPos, self.getWidth()))\r\n\r\n def verticalROIProfile(self, ROI):\r\n # Take full image if no ROI is given\r\n if ROI==None:\r\n ROI = ImageROI(0, 0, self.getWidth(), self.getHeight())\r\n\r\n slc = self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1]\r\n\r\n profile = slc.mean(axis=1)\r\n return numpy.ravel(profile)\r\n\r\n def horizontalProfile(self, yPos):\r\n if yPos < self.getHeight():\r\n return self.px[yPos]\r\n else:\r\n raise Exception(\"Requested position for horizontal profile is out of bounds: y={} in an image that has {} rows.\".format(yPos, self.getHeight()))\r\n\r\n def horizontalROIProfile(self, ROI):\r\n # Take full image if no ROI is given\r\n if ROI==None:\r\n ROI = ImageROI(0, 0, self.getWidth(), self.getHeight())\r\n\r\n slc = self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1]\r\n\r\n profile = slc.mean(axis=0)\r\n return profile\r\n\r\n def pixelsInShape(self, shape, seedPoint=None, mode='center', calculateWeights=False):\r\n \"\"\" Returns all pixels in the given shape (of class Polygon). \r\n\r\n mode:\r\n 'center' : a pixel's center must be within the shape to be accepted.\r\n 'full' : all corner points of a pixel must be within the shape to be accepted.\r\n 'partial' : only one corner point of a pixel must be within the shape to be accepted.\r\n\r\n calculateWeights:\r\n True : includes weights in returned pixel coordinate tuples,\r\n False : does not include weights in returned pixel coordinate tuples.\r\n \"\"\"\r\n\r\n if seedPoint != None:\r\n seedX = int(round(seedPoint.x))\r\n seedY = int(round(seedPoint.y))\r\n else:\r\n # Start at point p1 of shape:\r\n seedX = int(shape.points[0].x)\r\n seedY = int(shape.points[0].y)\r\n\r\n # Make a map of visited pixels. A visited pixel will get value 1:\r\n visited = numpy.zeros_like(a=self.px, dtype=numpy.dtype('uint8'))\r\n\r\n # Collect all points that belong to the shape in a list:\r\n contributions = []\r\n\r\n stack = [] # stack of pixels to visit\r\n stack.append((seedX, seedY))\r\n\r\n # Add seed's neighors to the stack as well:\r\n for offsetX in [-1, 0, 1]:\r\n for offsetY in [-1, 0, 1]:\r\n if not (offsetX==0 and offsetY==0):\r\n nx = seedX+offsetX\r\n ny = seedY+offsetY\r\n stack.append((nx, ny))\r\n\r\n while len(stack) > 0:\r\n pixel = stack.pop()\r\n x = pixel[0]\r\n y = pixel[1]\r\n\r\n if self.contains(x, y):\r\n if visited[y][x] == 0:\r\n visited[y][x] = 1\r\n\r\n # The pixel coordinate system is shifted by -0.5px against the shape coordinate system. Upper left pixel corner is its coordinate in the shape coordinate system. \r\n inside = False\r\n\r\n # Reserve names but set them up later only when they are needed.\r\n center = None\r\n upperLeft = None\r\n upperRight = None\r\n lowerLeft = None\r\n lowerRight = None\r\n\r\n center = Vector(x+0.5, y+0.5, 0)\r\n\r\n if mode == 'center':\r\n inside = shape.isInside2D(center)\r\n else:\r\n upperLeft = Vector(x, y, 0)\r\n upperRight = Vector(x+1, y, 0)\r\n lowerLeft = Vector(x, y+1, 0)\r\n lowerRight = Vector(x+1, y+1, 0)\r\n\r\n if mode == 'full':\r\n inside = shape.isInside2D(upperLeft) and shape.isInside2D(upperRight) and shape.isInside2D(lowerLeft) and shape.isInside2D(lowerRight)\r\n elif mode == 'partial':\r\n inside = True\r\n calculateWeights = True\r\n \r\n if inside:\r\n if calculateWeights:\r\n # Calculate pixel weight from the area of the clipped pixel:\r\n pixelPolygon = Polygon(upperLeft, upperRight, lowerRight, lowerLeft) # Clockwise order because pixel CS is y-flipped.\r\n\r\n clippedPixel = pixelPolygon.clip(shape)\r\n\r\n weight = clippedPixel.area()\r\n\r\n if weight > 0:\r\n contributions.append((x, y, weight))\r\n else:\r\n continue\r\n else:\r\n contributions.append((x, y, 0))\r\n\r\n # Now add neighbors to the stack:\r\n for offsetX in [-1, 0, 1]:\r\n for offsetY in [-1, 0, 1]:\r\n if not (offsetX==0 and offsetY==0):\r\n nx = x+offsetX\r\n ny = y+offsetY\r\n stack.append((nx, ny))\r\n\r\n return contributions\r\n\r\n @staticmethod\r\n def getPixelWeight(x, y, clipPolygon):\r\n # Calculate pixel weight from the area of the clipped pixel:\r\n upperLeft = Vector2D(x, y)\r\n upperRight = Vector2D(x+1, y)\r\n lowerLeft = Vector2D(x, y+1)\r\n lowerRight = Vector2D(x+1, y+1)\r\n pixelPolygon = Polygon(upperLeft, upperRight, lowerRight, lowerLeft) # Clockwise order because pixel CS is y-flipped.\r\n\r\n clippedPixel = pixelPolygon.clip(clipPolygon)\r\n weight = clippedPixel.area()\r\n\r\n return weight\r\n\r\n def meanGVinBin_polygonClipping(self, binCenter, sUnit, tUnit, sBoundary, tBoundary, binShape, weightFunction):\r\n \"\"\" Returns all pixels in the bin on the given vector s.\r\n\r\n binCenter: center of bin in world CS\r\n s: unit vector along profile axis\r\n t: unit vector along width axis\r\n \"\"\"\r\n\r\n roi_x0, roi_y0, roi_x1, roi_y1 = binShape.getBoundingBox()\r\n\r\n # Create a map with pixels' distances to the bin:\r\n # (measured parallel to s vector):\r\n roi_height = roi_y1 - roi_y0\r\n roi_width = roi_x1 - roi_x0\r\n\r\n roi_xaxis = numpy.linspace(start=roi_x0, stop=roi_x1, num=roi_width+1, endpoint=True, dtype=numpy.dtype('float64'))\r\n roi_yaxis = numpy.linspace(start=roi_y0, stop=roi_y1, num=roi_height+1, endpoint=True, dtype=numpy.dtype('float64'))\r\n\r\n roi_gridx, roi_gridy = numpy.meshgrid(roi_xaxis, roi_yaxis)\r\n\r\n # Shift by half a pixel, because they must represent\r\n # pixel centers in shape coordinate system. Also,\r\n # origin should be the bin center:\r\n roi_gridx = roi_gridx + 0.5 - binCenter.x\r\n roi_gridy = roi_gridy + 0.5 - binCenter.y\r\n\r\n # Transform coordinates into bin coordinate system (s and t axes):\r\n bin_grid_dist_s = numpy.abs(roi_gridx*sUnit.x + roi_gridy*sUnit.y)\r\n #bin_grid_dist_t = numpy.abs(roi_gridx*tUnit.x + roi_gridy*tUnit.y)\r\n\r\n # Set those that are too far from bin center in s and t direction to zero:\r\n bin_grid_dist_s = numpy.where(bin_grid_dist_s < sBoundary, bin_grid_dist_s, 0)\r\n #bin_grid_dist_t = numpy.where(bin_grid_dist_t < tBoundary, bin_grid_dist_t, 0)\r\n #bin_grid_dist_mul = bin_grid_dist_s * bin_grid_dist_t\r\n #pixel_indices = numpy.nonzero(bin_grid_dist_mul)\r\n pixel_indices = numpy.nonzero(bin_grid_dist_s)\r\n pixels_x = pixel_indices[1] + roi_x0\r\n pixels_y = pixel_indices[0] + roi_y0\r\n\r\n weights = weightFunction(pixels_x, pixels_y, binShape) # vectorized getPixelWeight()\r\n\r\n gvWeighted = self.px[pixels_y,pixels_x] * weights\r\n weightSum = numpy.sum(weights)\r\n meanGV = 0\r\n if weightSum > 0:\r\n meanGV = numpy.sum(gvWeighted) / weightSum\r\n\r\n return meanGV\r\n\r\n def meanGVinBin(self, binCenter, sUnit, tUnit, sBoundary, tBoundary, binShape, weightFunction):\r\n \"\"\" Returns all pixels in the bin on the given vector s.\r\n\r\n binCenter: center of bin in world CS\r\n s: unit vector along profile axis\r\n t: unit vector along width axis\r\n \"\"\"\r\n\r\n roi_x0, roi_y0, roi_x1, roi_y1 = binShape.getBoundingBox()\r\n\r\n # Create a map with pixels' distances to the bin:\r\n # (measured parallel to s vector):\r\n roi_height = roi_y1 - roi_y0\r\n roi_width = roi_x1 - roi_x0\r\n\r\n roi_xaxis = numpy.linspace(start=roi_x0, stop=roi_x1, num=roi_width+1, endpoint=True, dtype=numpy.dtype('float64'))\r\n roi_yaxis = numpy.linspace(start=roi_y0, stop=roi_y1, num=roi_height+1, endpoint=True, dtype=numpy.dtype('float64'))\r\n\r\n roi_gridx, roi_gridy = numpy.meshgrid(roi_xaxis, roi_yaxis)\r\n\r\n # Shift by half a pixel, because they must represent\r\n # pixel centers in shape coordinate system. Also,\r\n # origin should be the bin center:\r\n roi_gridx = roi_gridx + 0.5 - binCenter.x\r\n roi_gridy = roi_gridy + 0.5 - binCenter.y\r\n\r\n # Transform coordinates into bin coordinate system (s and t axes):\r\n bin_grid_dist_s = numpy.abs(roi_gridx*sUnit.x + roi_gridy*sUnit.y)\r\n #bin_grid_dist_t = numpy.abs(roi_gridx*tUnit.x + roi_gridy*tUnit.y)\r\n\r\n # Set those that are too far from bin center in s and t direction to zero:\r\n #bin_grid_dist_s = numpy.where(bin_grid_dist_s < sBoundary, bin_grid_dist_s, 0)\r\n #bin_grid_dist_t = numpy.where(bin_grid_dist_t < tBoundary, bin_grid_dist_t, 0)\r\n #bin_grid_dist_mul = bin_grid_dist_s * bin_grid_dist_t\r\n #pixel_indices = numpy.nonzero(bin_grid_dist_mul)\r\n\r\n pixel_indices = numpy.nonzero(bin_grid_dist_s < sBoundary)\r\n weights = bin_grid_dist_s[pixel_indices]\r\n pixels_x = pixel_indices[1] + roi_x0\r\n pixels_y = pixel_indices[0] + roi_y0\r\n\r\n weights = weightFunction(pixels_x, pixels_y, binShape) # vectorized getPixelWeight()\r\n\r\n gvWeighted = self.px[pixels_y,pixels_x] * weights\r\n weightSum = numpy.sum(weights)\r\n meanGV = 0\r\n if weightSum > 0:\r\n meanGV = numpy.sum(gvWeighted) / weightSum\r\n\r\n return meanGV\r\n\r\n \"\"\"\r\n def lineProfile_projectPixelsIntoProfileBins(self, x0, y0, x1, y1, width=1, resolution=1):\r\n # Vector pointing in direction of the requested line:\r\n s = Vector(x1-x0+1, y1-y0+1, 0) # +1 to fully include pixel (x1, y1)\r\n\r\n # Calculate vector t, perpendicular to s: t = s x z\r\n z = Vector(0, 0, 1) \r\n t = s.cross(z)\r\n t.makeUnitVector()\r\n t.scale(0.5*width)\r\n\r\n # Define a rectangle along the line and its width, separated into two triangles.\r\n origin = Vector(x0, y0, 0)\r\n A = origin - t\r\n B = origin + s - t\r\n C = origin + s + t\r\n D = origin + t\r\n\r\n rect = Polygon(A, B, C, D)\r\n\r\n print(\"s: {}\".format(s))\r\n print(\"t: {}\".format(t))\r\n\r\n print(rect)\r\n\r\n ceilLength = math.ceil(s.length())\r\n\r\n nSamples = int( ceilLength / resolution ) + 1 # +1 for endpoint\r\n\r\n # Set a seed point at the center of the rectangle:\r\n t.scale(0.5)\r\n s.scale(0.5)\r\n seed = A + t + s\r\n\r\n # Make a list of unique pixel coordinates within this rectangle:\r\n pixelsInRect = self.pixelsInShape(shape=rect, seedPoint=seed)\r\n\r\n # Create a histogram:\r\n sPositions, sStepSize = numpy.linspace(start=0, stop=ceilLength, num=nSamples, endpoint=True, retstep=True)\r\n sCounts = numpy.zeros_like(a=sPositions, dtype=numpy.dtype('float64')) # Number of contributions, for correct re-normalization, same datatype for efficiency during division later on...\r\n sSum = numpy.zeros_like(a=sPositions, dtype=numpy.dtype('float64')) # The sum of all grey value contributions\r\n\r\n # Make s a unit vector to correctly calculate projections using the dot product:\r\n s.makeUnitVector()\r\n\r\n # print(\"shape of positions: {}\".format(numpy.shape(sPositions)))\r\n\r\n print(\"{} pixels in rect.\".format(len(pixelsInRect)))\r\n\r\n offset = Vector(0.5, 0.5, 0)\r\n\r\n for pixel in pixelsInRect:\r\n # Project this pixel onto the s vector (pointing in direction of the line):\r\n\r\n # Move to line origin:\r\n p = pixel - origin + offset\r\n\r\n # Position on s axis:\r\n sPos = p.dot(s)\r\n\r\n # Find bin where this grey value should be counted:\r\n binPos = int(math.floor(sPos / sStepSize))\r\n\r\n #print(\"({x}, {y}): sPos: {spos}, binPos: {binpos}\".format(x=p.x, y=p.y, spos=sPos, binpos=binPos))\r\n\r\n sCounts[binPos] += 1\r\n sSum[binPos] += self.getPixel(int(pixel.x), int(pixel.y))\r\n\r\n # Replace zero counts by 1 to avoid div by zero:\r\n sCounts[sCounts==0] = 1\r\n\r\n sProfile = sSum / sCounts\r\n\r\n return sProfile, sPositions, sStepSize\r\n \"\"\"\r\n\r\n def lineProfile(self, x0, y0, x1, y1, width=1, resolution=1):\r\n \"\"\" Find line profile by adding weighted contributions of pixel grey values\r\n into bins of size (width x resolution).\r\n\r\n We always work in the 'shape coordinate system' with its origin\r\n at (0, 0) in the upper left corner.\r\n Center of pixel (0, 0) has shape CS coordinates (0.5, 0.5).\r\n\r\n x0, y0, x1 and y1 are shape coordinates.\r\n\r\n Returned 'sPositions' array contains bin center positions.\r\n \"\"\"\r\n\r\n # Vector pointing in direction of the requested line:\r\n s = Vector(x1-x0, y1-y0, 0)\r\n\r\n # Calculate vector t, perpendicular to s: t = s x z\r\n z = Vector(0, 0, 1) \r\n t = s.cross(z)\r\n t.makeUnitVector()\r\n\r\n # Convert to 2D vectors:\r\n s = Vector2D(s.x, s.y)\r\n t = Vector2D(t.x, t.y)\r\n\r\n tUnit = copy.deepcopy(t)\r\n\r\n t.scale(0.5*width) # t points from line origin half way in direction of width\r\n\r\n # Define a rectangle along the line and its width.\r\n origin = Vector2D(x0, y0)\r\n\r\n nSamples = math.ceil( s.length() / resolution ) #+ 1 # +1 for endpoint\r\n ceilLength = nSamples * resolution\r\n\r\n # Create a histogram:\r\n sPositions, sStepSize = numpy.linspace(start=0, stop=ceilLength, num=nSamples, endpoint=False, retstep=True)\r\n sProfile = numpy.zeros_like(a=sPositions, dtype=numpy.dtype('float64')) # Grey value profile\r\n\r\n # Create a unit vector in s direction:\r\n sUnit = copy.deepcopy(s)\r\n sUnit.makeUnitVector()\r\n\r\n # Half a unit vector:\r\n binUnitHalf = copy.deepcopy(sUnit)\r\n binUnitHalf.scale(0.5*resolution)\r\n\r\n # Make s the length of a bin step (i.e. resolution unit)\r\n s.makeUnitVector()\r\n s.scale(resolution)\r\n\r\n rectPos = Vector2D(0, 0)\r\n\r\n # A pixel center can be this far from the binPos (bin center)\r\n # in s and t direction to still be accepted:\r\n sBoundary = (resolution/2) + pixelHalfDiagonal\r\n tBoundary = (width/2) + pixelHalfDiagonal\r\n\r\n # Vectorize the pixel weight function:\r\n weightFunction = numpy.vectorize(self.getPixelWeight, otypes=[numpy.float64])\r\n\r\n i = 0\r\n for b in range(nSamples):\r\n print(\"\\rCalculating line profile... {:.1f}%\".format(100.0*i/nSamples), end=\"\")\r\n i += 1\r\n # Bin position on s axis:\r\n sPos = resolution*b\r\n\r\n # Construct a vector to the left point of the bin on the s axis:\r\n rectPos.setx(sUnit.x)\r\n rectPos.sety(sUnit.y)\r\n rectPos.scale(sPos)\r\n rectPos.add(origin)\r\n\r\n binPos = rectPos + binUnitHalf\r\n\r\n # Construct a rectangle that contains the area of this bin:\r\n A = rectPos - t\r\n B = rectPos + s - t\r\n C = rectPos + s + t\r\n D = rectPos + t\r\n\r\n binRect = Polygon(D, C, B, A) # Clockwise order because pixel CS is y-flipped.\r\n\r\n # Get all pixels and their relative areas in this bin:\r\n #pixelsInBin = self.pixelsInShape(shape=binRect, seedPoint=rectPos, mode='partial', calculateWeights=True)\r\n\r\n meanGV = self.meanGVinBin(binCenter=binPos, sUnit=sUnit, tUnit=tUnit, sBoundary=sBoundary, tBoundary=tBoundary, binShape=binRect, weightFunction=weightFunction)\r\n\r\n sProfile[b] = meanGV\r\n\r\n # Shift the sPositions by half a bin size so that they represent bin centers:\r\n sPositions += 0.5*resolution\r\n\r\n print(\"\\rCalculating line profile... 100% \")\r\n return sProfile, sPositions, sStepSize\r\n \r\n def clip(self, lower, upper):\r\n \"\"\" Clip grey values to given boundary interval. \"\"\"\r\n self.px = numpy.clip(self.px, lower, upper)\r\n\r\n def crop(self, x0, y0, x1, y1):\r\n \"\"\" Crop to given box (x0, y0)--(x1, y1). \"\"\"\r\n if x0 > x1:\r\n x0,x1 = x1,x0\r\n\r\n if y0 > y1:\r\n y0,y1 = y1,y0\r\n\r\n if y1 > self.getHeight() or x1 > self.getWidth():\r\n raise Exception(\"Trying to crop beyond image boundaries.\")\r\n\r\n self.boundingBoxX0 += x0\r\n self.boundingBoxY0 += y0\r\n\r\n self.px = self.px[int(y0):int(y1),int(x0):int(x1)] # Array has shape [y][x]\r\n self.width = int(x1 - x0)\r\n self.height = int(y1 - y0)\r\n\r\n def cropBorder(self, top=0, bottom=0, left=0, right=0):\r\n \"\"\" Crop away given border around image. \"\"\"\r\n x0 = int(left)\r\n y0 = int(top)\r\n x1 = self.getWidth() - int(right)\r\n y1 = self.getHeight() - int(bottom)\r\n\r\n self.crop(x0, y0, x1, y1)\r\n\r\n def cropROIaroundPoint(self, centerX, centerY, roiWidth, roiHeight):\r\n \"\"\" Crop a region of interest, centerd around given point. \"\"\"\r\n\r\n if roiWidth < 0:\r\n roiWidth = abs(roiWidth)\r\n if roiHeight < 0:\r\n roiHeight = abs(roiHeight)\r\n if roiWidth == 0 or roiHeight == 0:\r\n raise Exception(\"The region of interest should not be a square of size 0.\")\r\n\r\n x0 = int(math.floor(centerX - roiWidth/2))\r\n x1 = int(math.ceil(centerX + roiWidth/2))\r\n y0 = int(math.floor(centerY - roiHeight/2))\r\n y1 = int(math.ceil(centerY + roiHeight/2))\r\n\r\n if x1<0 or y1<0:\r\n raise Exception(\"Right or lower boundary for ROI (x1 or y1) cannot be below zero.\")\r\n\r\n if roiWidth>self.getWidth() or roiHeight>self.getHeight():\r\n raise Exception(\"Size of the ROI is bigger than the image size. ROI: \" + str(roiWidth) + \" x \" + str(roiHeight) + \". Image: \" + str(self.getWidth()) + \" x \" + str(self.getHeight())) \r\n if x0 < 0:\r\n x1 += abs(x0)\r\n x0 = 0\r\n\r\n if y0 < 0:\r\n y1 += abs(y0)\r\n y0 = 0\r\n\r\n if x1 >= self.getWidth():\r\n x1 = self.getWidth()\r\n x0 = x1 - roiWidth\r\n\r\n if y1 >= self.getHeight():\r\n y1 = self.getHeight()\r\n y0 = y1 - roiHeight\r\n\r\n # These should match roiWidth and roiHeight...\r\n roiDimX = x1 - x0\r\n roiDimY = y1 - y0\r\n\r\n self.crop(x0, y0, x1, y1)\r\n return x0, x1, y0, y1\r\n\r\n def bin(self, binSizeX, binSizeY, operation=\"mean\"):\r\n \"\"\" Decrease image size by merging pixels using specified operation.\r\n Valid operations: mean, max, min, sum. \"\"\"\r\n\r\n if binSizeX is None:\r\n binSizeX = 1\r\n\r\n if binSizeY is None:\r\n binSizeY = 1\r\n\r\n if (binSizeX > 1) or (binSizeY > 1):\r\n # Picture dimensions must be integer multiple of binning factor. If not, crop:\r\n overhangX = math.fmod(int(self.getWidth()), binSizeX)\r\n overhangY = math.fmod(int(self.getHeight()), binSizeY)\r\n if (overhangX > 0) or (overhangY > 0):\r\n #log(\"Cropping before binning because of nonzero overhang: (\" + str(overhangX) + \", \" + str(overhangY) + \")\")\r\n self.crop(0, 0, self.getWidth()-int(overhangX), self.getHeight()-int(overhangY))\r\n\r\n newWidth = self.width // binSizeX\r\n newHeight = self.height // binSizeY\r\n\r\n # Shift pixel values that need to be binned together into additional axes:\r\n binshape = (newHeight, binSizeY, newWidth, binSizeX)\r\n self.px = self.px.reshape(binshape)\r\n \r\n # Perform binning operation along binning axes (axis #3 and #1).\r\n # These axes will be collapsed to contain only the result\r\n # of the binning operation.\r\n if operation == \"mean\":\r\n self.px = self.px.mean(axis=(3, 1))\r\n elif operation == \"sum\":\r\n self.px = self.px.sum(axis=(3, 1))\r\n elif operation == \"max\":\r\n self.px = self.px.max(axis=(3, 1))\r\n elif operation == \"min\":\r\n self.px = self.px.min(axis=(3, 1))\r\n elif operation is None:\r\n raise Exception(\"No binning operation specified.\")\r\n else:\r\n raise Exception(\"Invalid binning operation: {}.\".format(operation))\r\n\r\n self.setWidth(newWidth)\r\n self.setHeight(newHeight)\r\n\r\n # Resolution assumes isotropic pixels...\r\n self.resolution *= binSizeX\r\n\r\n def addImage(self, other):\r\n \"\"\" Add pixel values from another image to this image. \"\"\"\r\n if self.dimensionsMatch(other):\r\n self.px = self.px + other.getPixelMap()\r\n\r\n def subtractImage(self, other):\r\n \"\"\" Subtract pixel values of another image from this image. \"\"\"\r\n if self.dimensionsMatch(other):\r\n self.px = self.px - other.getPixelMap()\r\n\r\n def multiplyImage(self, other):\r\n \"\"\" Multiply pixel values from another image to this image. \"\"\"\r\n if self.dimensionsMatch(other):\r\n self.px = self.px * other.getPixelMap()\r\n\r\n def divideImage(self, other):\r\n \"\"\" Multiply pixel values by another image. \"\"\"\r\n if self.dimensionsMatch(other):\r\n self.px = self.px / other.getPixelMap()\r\n\r\n def square(self):\r\n self.px *= self.px\r\n\r\n def sqrt(self):\r\n self.px = numpy.sqrt(self.px)\r\n\r\n def add(self, value):\r\n self.px += value\r\n\r\n def subtract(self, value):\r\n self.px -= value\r\n\r\n def multiply(self, value):\r\n self.px *= value\r\n\r\n def divide(self, value):\r\n \"\"\" Divide all pixels values by given scalar value. \"\"\"\r\n self.px = self.px / float(value)\r\n\r\n def invert(self, min=0, maximum=65535):\r\n self.px = maximum - self.px\r\n\r\n def renormalize(self, newMin=0, newMax=1, currentMin=None, currentMax=None, ROI=None):\r\n \"\"\"Renormalization of grey values from (currentMin, Max) to (newMin, Max) \"\"\"\r\n\r\n # Take full image if no ROI is given\r\n if ROI==None:\r\n ROI = ImageROI(0, 0, self.getWidth(), self.getHeight())\r\n\r\n slc = self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1]\r\n\r\n if currentMin is None:\r\n currentMin = slc.min()\r\n\r\n if currentMax is None:\r\n currentMax = slc.max()\r\n\r\n if(currentMax != currentMin):\r\n slc = (slc-currentMin)*(newMax-newMin)/(currentMax-currentMin)+newMin\r\n self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1] = slc\r\n else:\r\n slc = slc*0\r\n self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1] = slc\r\n #raise Exception(\"Division by zero upon renormalization: currentMax=currentMin={}\".format(currentMax))\r\n\r\n def map_lookup(self, gv, gv_from, gv_to):\r\n \"\"\" Return new grey value for given grey value 'gv'. Helper function for self.map().\"\"\"\r\n\r\n if gv in gv_from:\r\n # Given grey value is defined in 'from' list:\r\n return gv_to[numpy.where(gv_from==gv)]\r\n else:\r\n # Linear interpolation:\r\n a = 0 # left index of interpolation region\r\n if len(gv_from) > 2:\r\n for i in range(len(gv_from)-2):\r\n if gv_from[i+1] > gv:\r\n break\r\n\r\n a += 1\r\n\r\n b = a + 1 # right index of interpolation region\r\n\r\n xa = gv_from[a]\r\n xb = gv_from[b]\r\n ya = gv_to[a]\r\n yb = gv_to[b] \r\n\r\n # Slope of linear function:\r\n m = (yb-ya) / (xb-xa)\r\n\r\n # y axis intersection point (\"offset\"):\r\n n = yb - m*xb\r\n\r\n # newly assigned grey value:\r\n return (m*gv + n)\r\n\r\n\r\n def map(self, gv_from, gv_to, bins=1000):\r\n \"\"\" Applies a lookup table (LUT map) to convert image grey values\r\n according to given assignment tables (two numpy lists).\r\n\r\n gv_from: numpy array of given grey values (in current image)\r\n gv_to: numpy array of assigned grey values (for converted image)\r\n\r\n Linear interpolation will take place for gaps in lookup table.\r\n \"\"\"\r\n\r\n if len(gv_from) == len(gv_to):\r\n if len(gv_from) > 1:\r\n gvMin = self.min()\r\n gvMax = self.max()\r\n\r\n # Left position of each bin:\r\n positions, gvStepsize = numpy.linspace(start=gvMin, stop=gvMax, num=bins+1, endpoint=True, dtype=numpy.float64, retstep=True)\r\n\r\n # New grey value for each left position:\r\n mappingFunction = numpy.vectorize(pyfunc=self.map_lookup, excluded={1, 2})\r\n newGV = mappingFunction(positions, gv_from, gv_to)\r\n\r\n # Differences in newGV:\r\n deltaGV = numpy.diff(newGV, n=1)\r\n\r\n\r\n # Prepare parameters m (slope) and n (offset) for linear\r\n # interpolation functions of each bin:\r\n slopes = numpy.zeros(bins, dtype=numpy.float64)\r\n offsets = numpy.zeros(bins, dtype=numpy.float64)\r\n\r\n slopes = deltaGV / gvStepsize\r\n\r\n #print(\"newGV: {}\".format(numpy.shape(newGV)))\r\n #print(\"slopes: {}\".format(numpy.shape(slopes)))\r\n #print(\"positions: {}\".format(numpy.shape(positions)))\r\n\r\n offsets = newGV[1:] - slopes*positions[1:]\r\n\r\n inverse_stepsize = 1.0 / gvStepsize\r\n\r\n maxIndices = numpy.full(shape=numpy.shape(self.px), fill_value=bins-1, dtype=numpy.uint32)\r\n bin_indices = numpy.minimum(maxIndices, numpy.floor((self.px - gvMin) * inverse_stepsize).astype(numpy.uint32))\r\n\r\n m_px = slopes[bin_indices]\r\n n_px = offsets[bin_indices]\r\n\r\n self.px = m_px*self.px + n_px\r\n else:\r\n raise Exception(\"image.map(): At least two mappings are required in the grey value assignment lists.\")\r\n else:\r\n raise Exception(\"image.map(): gv_from must have same length as gv_to.\")\r\n\r\n def stats(self, ROI=None):\r\n \"\"\" Image or ROI statistics. Mean, Standard Deviation \"\"\"\r\n\r\n # Take full image if no ROI is given\r\n if ROI==None:\r\n ROI = ImageROI(0, 0, self.getWidth(), self.getHeight())\r\n\r\n slc = self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1]\r\n\r\n mean = numpy.mean(slc)\r\n sigma = numpy.std(slc)\r\n snr = 0\r\n if sigma > 0:\r\n snr = mean / sigma\r\n\r\n return {\"mean\": mean, \"stddev\": sigma, \"snr\": snr, \"width\": ROI.width(), \"height\": ROI.height(), \"area\": ROI.area()}\r\n\r\n def noise(self, sigma):\r\n \"\"\" Add noise to image.\r\n\r\n Gaussian noise:\r\n sigma: standard deviation (scalar or array that matches image size)\r\n \"\"\"\r\n\r\n rng = default_rng()\r\n self.px += rng.normal(loc=0, scale=sigma, size=numpy.shape(self.px))\r\n\r\n def smooth_gaussian(self, sigma):\r\n self.px = ndimage.gaussian_filter(input=self.px, sigma=sigma, order=0, )\r\n\r\n def applyMedian(self, kernelSize=1):\r\n if kernelSize > 1:\r\n self.px = ndimage.median_filter(self.px, int(kernelSize))\r\n\r\n def applyThreshold(self, threshold, lower=0, upper=65535):\r\n self.px = numpy.where(self.px > threshold, upper, lower).astype(self.getInternalDataType())\r\n\r\n def renormalizeToMeanAndStdDev(self, mean, stdDev, ROI=None):\r\n \"\"\" Renormalize grey values such that mean=30000, (mean-stdDev)=0, (mean+stdDev)=60000 \"\"\"\r\n\r\n # Take full image if no ROI is given\r\n if ROI==None:\r\n ROI = ImageROI(0, 0, self.getWidth(), self.getHeight())\r\n\r\n self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1] = ((self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1] - mean)/stdDev)*30000 + 30000\r\n\r\n def edges_sobel(self):\r\n # Sobel edge detection:\r\n edgesX = ndimage.sobel(self.px, axis=0, mode='nearest')\r\n edgesY = ndimage.sobel(self.px, axis=1, mode='nearest')\r\n return numpy.sqrt(edgesX**2 + edgesY**2)\r\n\r\n def edges_canny(self):\r\n # The 'feature' package from scikit-image,\r\n # only needed for Canny edge detection, when used instead of Sobel.\r\n from skimage.feature import canny # Canny edge detection\r\n\r\n # Canny edge detection. Needs 'scikit-image' package. from skimage import feature\r\n return canny(self.px)\r\n\r\n def filter_edges(self, mode='sobel'):\r\n if(mode == 'sobel'):\r\n self.px = self.edges_sobel()\r\n elif(mode == 'canny'):\r\n self.px = self.edges_canny()\r\n else:\r\n raise Exception(\"Valid edge detection modes: 'sobel'\")\r\n \r\n # Rescale:\r\n self.px = self.px.astype(self.getInternalDataType())\r\n #self.thresholding(0) # black=0, white=65535\r\n\r\n def cleanPatches(self, min_patch_area=None, max_patch_area=None, remove_border_patches=False, aspect_ratio_tolerance=None):\r\n iterationStructure = ndimage.generate_binary_structure(rank=2, connectivity=2) # apply to rank=2D array, only nearest neihbours (connectivity=1) or next nearest neighbours as well (connectivity=2)\r\n\r\n labelField, nPatches = ndimage.label(self.px, iterationStructure)\r\n nCleaned = 0\r\n nRemaining = 0\r\n patchGeometry = []\r\n\r\n if nPatches == 0:\r\n log(\"Found no structures\")\r\n else:\r\n self.erase()\r\n\r\n areaMin = 0\r\n if(min_patch_area != None):\r\n areaMin = min_patch_area\r\n \r\n areaMax = self.getWidth() * self.getHeight()\r\n if(max_patch_area != None):\r\n areaMax = max_patch_area\r\n\r\n areaMin = areaMin / (self.getResolution()**2)\r\n areaMax = areaMax / (self.getResolution()**2)\r\n\r\n for i in range(1, nPatches+1):\r\n patchCoordinates = numpy.nonzero(labelField==i)\r\n\r\n # Check patch size:\r\n nPatchPixels = len(patchCoordinates[0])\r\n if nPatchPixels < areaMin or nPatchPixels > areaMax: # Black out areas that are too small or too big for a circle\r\n nCleaned += 1\r\n continue\r\n \r\n coordinatesX = patchCoordinates[1]\r\n coordinatesY = patchCoordinates[0]\r\n\r\n left = numpy.amin(coordinatesX)\r\n right = numpy.amax(coordinatesX)\r\n top = numpy.amin(coordinatesY)\r\n bottom= numpy.amax(coordinatesY)\r\n\r\n if remove_border_patches: \r\n if((left==0) or (top==0) or (right==self.getWidth()-1) or (bottom==self.getHeight()-1)):\r\n nCleaned += 1\r\n continue\r\n\r\n # An ideal circle should have an aspect ratio of 1:\r\n if aspect_ratio_tolerance != None:\r\n aspectRatio = 0\r\n if(top != bottom):\r\n aspectRatio = abs(right-left) / abs(bottom-top)\r\n\r\n if abs(1-aspectRatio) > aspect_ratio_tolerance: # This is not a circle\r\n nCleaned += 1\r\n log(\"Aspect ratio {ar:.3f} doesn't meet aspect ratio tolerance |1-AR|={tolerance:.3f}\".format(ar=aspectRatio, tolerance=aspect_ratio_tolerance))\r\n continue\r\n\r\n # Add patch center as its coordinate:\r\n patchGeometry.append(((right+left)/2.0, (bottom+top)/2.0, right-left, bottom-top))\r\n\r\n self.px[patchCoordinates] = 1\r\n nRemaining += 1\r\n\r\n return nPatches, nCleaned, nRemaining, patchGeometry\r\n\r\n def fitCircle(self):\r\n # Linear least squares method by:\r\n # I. D. Coope,\r\n # Circle Fitting by Linear and Nonlinear Least Squares,\r\n # Journal of Optimization Theory and Applications, 1993, Volume 76, Issue 2, pp 381-388\r\n # https://doi.org/10.1007/BF00939613\r\n\r\n coordinates = numpy.nonzero(self.px)\r\n circlePixelsX = coordinates[1]\r\n circlePixelsY = coordinates[0]\r\n nPoints = len(circlePixelsX)\r\n circlePixels1 = numpy.ones(nPoints)\r\n\r\n # Create the matrix B for the system of linear equations:\r\n matrixB = numpy.array((circlePixelsX, circlePixelsY, circlePixels1))\r\n matrixB = matrixB.transpose()\r\n\r\n # linear equation to optimize:\r\n # matrix B * result = vector d\r\n d = []\r\n for i in range(nPoints):\r\n d.append(circlePixelsX[i]**2 + circlePixelsY[i]**2)\r\n\r\n vectorD = numpy.array(d)\r\n\r\n results, residuals, rank, s = numpy.linalg.lstsq(matrixB, vectorD, rcond=None)\r\n\r\n centerX = (results[0] / 2.0)\r\n centerY = (results[1] / 2.0)\r\n radius = math.sqrt(results[2] + centerX**2 + centerY**2)\r\n\r\n # Calculate deviation statistics:\r\n differenceSum = 0\r\n minDifference = 99999\r\n maxDifference = 0\r\n for i in range(nPoints):\r\n diff = abs(radius - math.sqrt((centerX - circlePixelsX[i])**2 + (centerY - circlePixelsY[i])**2))\r\n differenceSum += diff\r\n\r\n if minDifference > diff:\r\n minDifference = diff\r\n\r\n if maxDifference < diff:\r\n maxDifference = diff\r\n\r\n meanDifference = differenceSum / nPoints\r\n\r\n return centerX, centerY, radius, meanDifference, minDifference, maxDifference\r\n\r\n def intensityFunction2D(self, x, I0, mu, R, x0): # Lambert-Beer-Law for ball intensity, to fit.\r\n radicand = numpy.power(R,2) - numpy.power((x-x0),2)\r\n \r\n # Avoid root of negative numbers\r\n radicand[radicand < 0] = 0 \r\n\r\n # Huge radicands lead to exp()->0, therefore avoid huge exponentiation:\r\n radicand[radicand > (1400*1400)] = (1400*1400)\r\n\r\n result = I0*numpy.exp(-2.0*mu*numpy.sqrt(radicand))\r\n\r\n return result\r\n\r\n def intensityFunction3D(self, coord, I0, mu, R, x0, y0): # Lambert-Beer-Law for ball intensity, to fit.\r\n if len(coord) == 2:\r\n (x, y) = coord\r\n\r\n radicand = numpy.power(R,2) - numpy.power((x-x0),2) - numpy.power((y-y0),2)\r\n \r\n # Avoid root of negative numbers\r\n radicand[radicand < 0] = 0 \r\n\r\n # Huge radicands lead to exp()->0, therefore avoid huge exponentiation:\r\n radicand[radicand > (1400*1400)] = (1400*1400)\r\n\r\n result = I0 * numpy.exp(-2.0*mu*numpy.sqrt(radicand))\r\n \r\n return result\r\n else:\r\n raise Exception(\"3D Intensity fit function expects a tuple (x,y) for coordinates.\")\r\n\r\n def fitIntensityProfile(self, axis=\"x\", initI0=None, initMu=0.003, initR=250, initX0=None, avgLines=5):\r\n yData = 0\r\n xdata = 0\r\n if initI0 is None:\r\n initI0 = self.max() # Hoping that a median has been applied before.\r\n\r\n if axis == \"x\":\r\n if initX0 is None:\r\n initX0 = self.getWidth() / 2\r\n\r\n startLine = int((self.getHeight() / 2) - math.floor(avgLines/2))\r\n stopLine = int((self.getHeight() / 2) + math.floor(avgLines/2))\r\n\r\n # Accumulate intensity profile along 'avgLines' lines around the center line:\r\n yData = numpy.zeros(self.getWidth(), dtype=self.getInternalDataType())\r\n for l in range(startLine, stopLine+1):\r\n yData += self.px[l,:]\r\n\r\n xData = numpy.linspace(0, self.getWidth()-1, self.getWidth())\r\n\r\n elif axis == \"y\":\r\n if initX0 is None:\r\n initX0 = self.getHeight() / 2\r\n\r\n startLine = int((self.getWidth() / 2) - math.floor(avgLines/2))\r\n stopLine = int((self.getWidth() / 2) + math.floor(avgLines/2))\r\n\r\n # Accumulate intensity profile along 'avgLines' lines around the center line:\r\n yData = numpy.zeros(self.getHeight(), dtype=self.getInternalDataType())\r\n for l in range(startLine, stopLine+1):\r\n yData += self.px[:,l]\r\n\r\n xData = numpy.linspace(0, self.getHeight()-1, self.getHeight())\r\n\r\n else:\r\n raise Exception(\"projectionImage::fitIntensityProfile() needs profile direction to be 'x' or 'y'.\")\r\n\r\n yData = yData / int(avgLines) # average intensity profile\r\n firstGuess = (initI0, initMu, initR, initX0)\r\n\r\n try:\r\n optimalParameters, covariances = optimize.curve_fit(self.intensityFunction2D, xData, yData, p0=firstGuess)\r\n except Exception:\r\n optimalParameters = (None, None, None, None)\r\n\r\n\r\n fittedI0 = optimalParameters[0]\r\n fittedMu = optimalParameters[1]\r\n fittedR = optimalParameters[2]\r\n fittedX0 = optimalParameters[3]\r\n\r\n return fittedI0, fittedMu, fittedR, fittedX0\r\n\r\nclass ImageStack:\r\n \"\"\" Specify an image stack from a single file (RAW chunk) or\r\n a collection of single 2D RAW or TIFF files. \"\"\"\r\n\r\n def __init__(self, filePattern=None, width=None, height=None, dataType=None, byteOrder=None, rawFileHeaderSize=0, rawImageHeaderSize=0, slices=None, startNumber=0, flipByteOrder=False):\r\n self.files = ImageFile(filePattern, dataType, byteOrder, flipByteOrder)\r\n\r\n # Has this stack already been built?\r\n self.built = False\r\n\r\n self.width = width\r\n self.height = height\r\n self.nSlices = slices # number of slices in stack\r\n self.startNumber = startNumber\r\n\r\n # A RAW chunk can contain an overall file header, and\r\n # each image in the stack can contain an image header.\r\n self.rawFileHeaderSize = rawFileHeaderSize\r\n self.rawImageHeaderSize = rawImageHeaderSize\r\n\r\n self._isVolumeChunk = False # Is this a volume chunk or is a file list provided?\r\n\r\n self.fileList = []\r\n self.fileNumbers = [] # store original stack number in file name\r\n\r\n def addStack(self, other):\r\n if (self.width == other.width) and (self.height == other.height):\r\n self.nSlices += other.nSlices\r\n self.fileList.extend(other.fileList)\r\n self.fileNumbers.extend(other.fileNumbers)\r\n else:\r\n raise Exception(\"Error adding stack: image dimensions don't match.\")\r\n\r\n def isVolumeChunk(self):\r\n return self._isVolumeChunk\r\n\r\n def setVolumeChunk(self, isVolumeChunk):\r\n self._isVolumeChunk = isVolumeChunk\r\n\r\n def getFileByteOrder(self):\r\n return self.files.getByteOrder()\r\n\r\n def setFileByteOrder(self, byteOrder):\r\n self.files.setByteOrder(byteOrder)\r\n\r\n def getFileDataType(self):\r\n return self.files.getDataType()\r\n\r\n def setFileDataType(self, dataType):\r\n self.files.setDataType(dataType)\r\n\r\n def doFlipByteOrder(self):\r\n return self.files.doFlipByteOrder()\r\n\r\n def setFlipByteOrder(self, flipByteOrder):\r\n self.files.setFlipByteOrder(flipByteOrder)\r\n\r\n def fileStackInfo(self, filenameString):\r\n \"\"\" Split file pattern into lead & trail text, number of expected digits. \"\"\"\r\n if '%' in filenameString:\r\n # A % sign in the provided file pattern indicates an image stack: e.g. %04d\r\n percentagePosition = filenameString.find(\"%\")\r\n\r\n numberStart = percentagePosition + 1\r\n numberStop = filenameString.find(\"d\", percentagePosition)\r\n\r\n leadText = \"\"\r\n if(percentagePosition > 0):\r\n leadText = filenameString[:percentagePosition]\r\n\r\n trailText = \"\"\r\n if((numberStop+1) < len(filenameString)):\r\n trailText = filenameString[(numberStop+1):]\r\n\r\n if(numberStop > numberStart):\r\n numberString = filenameString[numberStart:numberStop]\r\n if(numberString.isdigit()):\r\n nDigitsExpected = int(numberString)\r\n return leadText, trailText, nDigitsExpected\r\n else:\r\n raise Exception(\"Image stack pattern is wrong. The wildcard for sequential digits in a filename must be %, followed by number of digits, followed by d, e.g. %04d\")\r\n else:\r\n raise Exception(\"Image stack pattern is wrong. The wildcard for sequential digits in a filename must be %, followed by number of digits, followed by d, e.g. %04d\")\r\n\r\n return filenameString, \"\", 0\r\n\r\n def buildStack(self):\r\n \"\"\" Build list of files that match given file name pattern. \"\"\"\r\n self.fileList = []\r\n self.fileNumbers = []\r\n\r\n # Treat projection files\r\n inFilePattern = self.files.getFilename()\r\n inputFolder = os.path.dirname(inFilePattern)\r\n projBasename = os.path.basename(inFilePattern)\r\n\r\n if inputFolder == \"\" or inputFolder is None:\r\n inputFolder = \".\"\r\n\r\n # Check if an image stack is provided:\r\n if('%' not in inFilePattern):\r\n self.fileList.append(inFilePattern)\r\n\r\n if(isTIFF(inFilePattern)): # treat as single TIFF projection \r\n self._isVolumeChunk = False\r\n testImage = Image(inFilePattern)\r\n testImage.read()\r\n self.width = testImage.getWidth()\r\n self.height = testImage.getHeight()\r\n self.nSlices = 1\r\n self.files.setDataType(testImage.inputFile.getDataType())\r\n else: # treat as raw chunk\r\n if (self.width != None) and (self.height != None):\r\n if (self.files.getDataType() != None):\r\n if os.path.isfile(inFilePattern):\r\n self._isVolumeChunk = True\r\n\r\n if (self.nSlices is None):\r\n # Determine number of slices.\r\n fileSizeInBytes = os.path.getsize(inFilePattern)\r\n dataSizeInBytes = fileSizeInBytes - self.rawFileHeaderSize\r\n bytesPerImage = self.rawImageHeaderSize + self.width * self.height * self.files.getDataType().itemsize\r\n\r\n if (dataSizeInBytes >= bytesPerImage):\r\n if (dataSizeInBytes % bytesPerImage) == 0:\r\n self.nSlices = int(dataSizeInBytes / bytesPerImage)\r\n log(\"{} slices found in raw chunk.\".format(self.nSlices))\r\n else:\r\n raise Exception(\"The raw chunk data size ({} bytes, without general file header) is not divisible by the calculated size of a single image ({} bytes, including image header). Therefore, the number of slices cannot be determined. {}\".format(dataSizeInBytes, bytesPerImage, inFilePattern))\r\n else:\r\n raise Exception(\"The raw chunk data size ({} bytes, without general file header) is smaller than the calculated size of a single image ({} bytes, including image header). {}\".format(dataSizeInBytes, bytesPerImage, inFilePattern))\r\n else:\r\n raise Exception(\"File not found: {}\".format(inFilePattern))\r\n else:\r\n raise Exception(\"Please provide the data type of the raw chunk.\")\r\n else:\r\n raise Exception(\"Please provide width and height (in pixels) of the raw chunk.\")\r\n else:\r\n # A % sign in the provided file pattern indicates an image stack: e.g. %04d\r\n leadText, trailText, nDigitsExpected = self.fileStackInfo(projBasename)\r\n\r\n # Get list of files in input folder:\r\n fileList = os.listdir(inputFolder)\r\n fileList.sort()\r\n\r\n nImported = 0\r\n\r\n for f in fileList:\r\n file = inputFolder + \"/\" + f\r\n if os.path.isfile(file):\r\n # Check if filename matches pattern:\r\n if(f.startswith(leadText) and f.endswith(trailText)):\r\n digitText = f[len(leadText):-len(trailText)]\r\n if digitText.isdigit(): # and len(digitText)==nDigitsExpected:\r\n # Pattern matches.\r\n n = int(digitText)\r\n if n >= self.startNumber:\r\n self.fileList.append(file)\r\n self.fileNumbers.append(n)\r\n\r\n nImported += 1\r\n if nImported == self.nSlices:\r\n break\r\n else:\r\n continue\r\n else:\r\n continue\r\n\r\n self.nSlices = len(self.fileList)\r\n\r\n if self.nSlices > 0:\r\n if isTIFF(self.fileList[0]):\r\n testImage = Image(self.fileList[0])\r\n testImage.read()\r\n self.width = testImage.getWidth()\r\n self.height = testImage.getHeight()\r\n self.files.setDataType(testImage.inputFile.getDataType())\r\n\r\n self.built = True\r\n \r\n\r\n def getFilename(self, index=None):\r\n if index != None:\r\n if self._isVolumeChunk:\r\n if len(self.fileList) > 0:\r\n return self.fileList[0]\r\n else:\r\n return None\r\n else:\r\n if len(self.fileList) > index:\r\n return self.fileList[index]\r\n else:\r\n return None\r\n else:\r\n return self.files.getFilename()\r\n\r\n def getFileBasename(self, index=None):\r\n if index != None:\r\n if self._isVolumeChunk:\r\n if len(self.fileList) > 0:\r\n return os.path.basename(self.fileList[0])\r\n else:\r\n return None\r\n else:\r\n if len(self.fileList) > index:\r\n return os.path.basename(self.fileList[index])\r\n else:\r\n return None\r\n else:\r\n return self.files.getFileBasename()\r\n\r\n def setFilename(self, filename):\r\n self.files.setFilename(filename)\r\n\r\n def getImage(self, index, outputFile=None):\r\n \"\"\" Read and return image at position 'index' within the stack. \"\"\"\r\n if index >= 0:\r\n if not self._isVolumeChunk: # read single image file from stack:\r\n if len(self.fileList) > index:\r\n filename = self.fileList[index]\r\n file = ImageFile(filename=filename, dataType=self.getFileDataType(), byteOrder=self.getFileByteOrder(), flipByteOrder=self.doFlipByteOrder())\r\n\r\n img = Image(file, outputFile)\r\n if isTIFF(filename):\r\n img.read()\r\n else:\r\n img.readRAW(self.width, self.height, 0, self.getFileDataType(), self.getFileByteOrder(), self.rawFileHeaderSize, self.rawImageHeaderSize)\r\n return img\r\n else:\r\n raise Exception(\"The requested slice nr. {} is out of bounds, because only {} image files were found.\".format(index, len(self.fileList)))\r\n else: # read slice from volume chunk, obeying start number\r\n if len(self.fileList) > 0:\r\n file = self.fileList[0]\r\n img = Image(file, outputFile)\r\n chunkIndex = index + self.startNumber\r\n if isTIFF(file):\r\n raise Exception(\"Cannot treat 3D TIFFs.\")\r\n else:\r\n img.readRAW(self.width, self.height, chunkIndex, self.getFileDataType(), self.getFileByteOrder(), self.rawFileHeaderSize, self.rawImageHeaderSize)\r\n return img\r\n else:\r\n raise Exception(\"No image file specified to be loaded.\")\r\n else:\r\n raise Exception(\"Negative slice numbers do not exists. {} requested.\".format(index))\r\n\r\n def getMeanImage(self, outputFile=None):\r\n \"\"\" Calculate the mean of all image files. \"\"\"\r\n if self.nSlices > 0:\r\n if self.nSlices > 1:\r\n sumImg = self.getImage(0, outputFile)\r\n for i in range(1, self.nSlices):\r\n print(\"\\rMean Image: summing up {i}/{n}\".format(i=(i+1), n=self.nSlices), end='')\r\n sumImg.addImage(self.getImage(i, outputFile))\r\n \r\n\r\n print(\"\")\r\n\r\n sumImg.divide(self.nSlices)\r\n return sumImg\r\n else:\r\n return self.getImage(0, outputFile)\r\n else:\r\n return None\r\n\r\n def getStdDevImage(self, meanImg=None, outputFile=None):\r\n \"\"\" Calculate the pixel-wise RMS of the image files. \"\"\"\r\n if self.nSlices > 0:\r\n if self.nSlices > 1:\r\n if meanImg is None:\r\n meanImg = self.getMeanImage(outputFile)\r\n\r\n sumImg = Image()\r\n sumImg.shapeLike(otherImg=meanImg)\r\n\r\n for i in range(0, self.nSlices):\r\n print(\"\\rRMSD Image: component {i}/{n}\".format(i=i+1, n=self.nSlices), end='')\r\n sqDiffImg = self.getImage(i, outputFile)\r\n sqDiffImg.subtractImage(meanImg)\r\n sqDiffImg.square()\r\n\r\n sumImg.addImage(sqDiffImg)\r\n\r\n sumImg.divide(self.nSlices)\r\n sumImg.sqrt()\r\n\r\n print(\"\")\r\n\r\n return sumImg\r\n else:\r\n return self.getImage(0, outputFile)\r\n else:\r\n return None"
] | [
[
"scipy.signal.fftconvolve",
"numpy.sum",
"numpy.ones",
"numpy.vectorize",
"scipy.optimize.curve_fit",
"numpy.diff",
"numpy.dtype",
"numpy.issubdtype",
"numpy.any",
"numpy.amax",
"numpy.meshgrid",
"numpy.fliplr",
"numpy.abs",
"numpy.reshape",
"numpy.where",
"numpy.linspace",
"numpy.nonzero",
"numpy.mean",
"scipy.ndimage.generate_binary_structure",
"scipy.ndimage.label",
"numpy.zeros",
"scipy.ndimage.center_of_mass",
"numpy.argmax",
"numpy.power",
"numpy.std",
"numpy.finfo",
"numpy.array",
"numpy.random.default_rng",
"numpy.flipud",
"scipy.ndimage.sobel",
"numpy.floor",
"numpy.ravel",
"numpy.amin",
"numpy.clip",
"scipy.ndimage.gaussian_filter",
"numpy.linalg.lstsq",
"numpy.iinfo",
"numpy.rot90",
"numpy.sqrt",
"numpy.shape",
"numpy.full"
]
] |
214929177/pyNastran | [
"73032d6ffd445ef085c124dde6b5e90a516a5b6a"
] | [
"pyNastran/op2/op2_interface/op2_scalar.py"
] | [
"#pylint: disable=R0913\n\"\"\"\nDefines the sub-OP2 class. This should never be called outisde of the OP2 class.\n\n - OP2_Scalar(debug=False, log=None, debug_file=None)\n\n **Methods**\n - set_subcases(subcases=None)\n - set_transient_times(times)\n - read_op2(op2_filename=None, combine=False)\n - set_additional_generalized_tables_to_read(tables)\n - set_additional_result_tables_to_read(tables)\n - set_additional_matrices_to_read(matrices)\n\n **Attributes**\n - total_effective_mass_matrix\n - effective_mass_matrix\n - rigid_body_mass_matrix\n - modal_effective_mass_fraction\n - modal_participation_factors\n - modal_effective_mass\n - modal_effective_weight\n - set_as_msc()\n - set_as_optistruct()\n\n **Private Methods**\n - _get_table_mapper()\n - _not_available(data, ndata)\n - _table_crasher(data, ndata)\n - _table_passer(data, ndata)\n - _validate_op2_filename(op2_filename)\n - _create_binary_debug()\n - _make_tables()\n - _read_tables(table_name)\n - _skip_table(table_name)\n - _read_table_name(rewind=False, stop_on_failure=True)\n - _update_generalized_tables(tables)\n - _read_cmodext()\n - _read_cmodext_helper(marker_orig, debug=False)\n - _read_geom_table()\n - _finish()\n\n\"\"\"\nimport os\nfrom struct import Struct, unpack\nfrom collections import defaultdict\nfrom typing import List, Tuple, Dict, Union, Any\n\nfrom numpy import array\nimport numpy as np\nfrom cpylog import get_logger\n\nfrom pyNastran import is_release, __version__\nfrom pyNastran.f06.errors import FatalError\nfrom pyNastran.op2.op2_interface.op2_reader import OP2Reader, mapfmt, reshape_bytes_block\nfrom pyNastran.bdf.cards.params import PARAM\n\n#============================\n\nfrom pyNastran.op2.op2_interface.msc_tables import MSC_RESULT_TABLES, MSC_MATRIX_TABLES, MSC_GEOM_TABLES\nfrom pyNastran.op2.op2_interface.nx_tables import NX_RESULT_TABLES, NX_MATRIX_TABLES, NX_GEOM_TABLES\n\nfrom pyNastran.op2.tables.lama_eigenvalues.lama import LAMA\nfrom pyNastran.op2.tables.oee_energy.onr import ONR\nfrom pyNastran.op2.tables.ogf_gridPointForces.ogpf import OGPF\n\nfrom pyNastran.op2.tables.oef_forces.oef import OEF\nfrom pyNastran.op2.tables.oes_stressStrain.oes import OES\n#from pyNastran.op2.tables.oes_stressStrain.oesm import OESM\nfrom pyNastran.op2.tables.ogs_grid_point_stresses.ogs import OGS\n\nfrom pyNastran.op2.tables.opg_appliedLoads.opg import OPG\nfrom pyNastran.op2.tables.oqg_constraintForces.oqg import OQG\nfrom pyNastran.op2.tables.oug.oug import OUG\nfrom pyNastran.op2.tables.ogpwg import OGPWG\nfrom pyNastran.op2.fortran_format import FortranFormat\n\nfrom pyNastran.utils import is_binary_file\n\"\"\"\nftp://161.24.15.247/Nastran2011/seminar/SEC04-DMAP_MODULES.pdf\n\nDatablock\tType\tDescription\nEFMFSMS\tMatrix\t6 x 1 Total Effective mass matrix\nEFMASSS\tMatrix\t6 x 6 Effective mass matrix\nRBMASS\tMatrix\t6 x 6 Rigid body mass matrix\nEFMFACS\tMatrix\t6 X N Modal effective mass fraction matrix\nMPFACS\tMatrix\t6 x N Modal participation factor matrix\nMEFMASS\tMatrix\t6 x N Modal effective mass matrix\nMEFWTS\tMatrix\t6 x N Modal effective weight matrix\nRAFGEN\tMatrix\tN x M Generalized force matrix\nRADEFMP\tMatrix\tN X U2 Effective inertia loads\nBHH\tMatrix\tN x N Viscous damping matrix\nK4HH\tMatrix\tN x N Structural damping matrix\nRADAMPZ\tMatrix\tN x N equivalent viscous damping ratios\nRADAMPG\tMatrix\tN X N equivalent structural damping ratio\n\nLAMA\tLAMA\tEigenvalue summary table\nOGPWG\tOGPWG\tMass properties output\nOQMG1\tOQMG\tModal MPC forces\nRANCONS\tORGY1\tConstraint mode element strain energy table\nRANEATC\tORGY1\tAttachment mode element strain energy table\nRAGCONS\tOGPFB\tConstraint mode grid point force table\nRAGEATC\tOGPFB\tAttachment mode grid point force table\nRAPCONS\tOES\tConstraint mode ply stress table\nRAPEATC\tOES\tAttachment mode ply stress table\nRASCONS\tOES\tConstraint mode element stress table\nRAECONS\tOES\tConstraint mode element strain table\nRASEATC\tOES\tAttachment mode element stress table\nRAEEATC\tOES\tAttachment mode element strain table\nOES1C\tOES\tModal Element Stress Table\nOES1X\tOES\tModal Element Stress Table\nOSTR1C\tOES\tModal Element Strain Table\nOSTR1X\tOSTR\tModal Element Strain Table\nRAQCONS\tOUG\tConstraint mode MPC force table\nRADCONS\tOUG\tConstraint mode displacement table\nRADEFFM\tOUG\tEffective inertia displacement table\nRAQEATC\tOUG\tAttachment mode MPC force table\nRADEATC\tOUG\tAttachment mode displacement table\nOUGV1\tOUG\tEigenvector Table\nRAFCONS\tOEF\tConstraint mode element force table\nRAFEATC\tOEF\tAttachment mode element force table\nOEF1X\tOEF\tModal Element Force Table\nOGPFB1\tOGPFB\tModal Grid Point Force Table\nONRGY1\tONRGY1\tModal Element Strain Energy Table\nONRGY2\tONRGY1\n\n#--------------------\n\nRADCONS - Displacement Constraint Mode\nRADDATC - Displacement Distributed Attachment Mode\nRADNATC - Displacement Nodal Attachment Mode\nRADEATC - Displacement Equivalent Inertia Attachment Mode\nRADEFFM - Displacement Effective Inertia Mode\n\nRAECONS - Strain Constraint Mode\nRAEDATC - Strain Distributed Attachment Mode\nRAENATC - Strain Nodal Attachment Mode\nRAEEATC - Strain Equivalent Inertia Attachment Mode\n\nRAFCONS - Element Force Constraint Mode\nRAFDATC - Element Force Distributed Attachment Mode\nRAFNATC - Element Force Nodal Attachment Mode\nRAFEATC - Element Force Equivalent Inertia Attachment Mode\n\nRALDATC - Load Vector Used to Compute the Distributed Attachment M\n\nRANCONS - Strain Energy Constraint Mode\nRANDATC - Strain Energy Distributed Attachment Mode\nRANNATC - Strain Energy Nodal Attachment Mode\nRANEATC - Strain Energy Equivalent Inertia Attachment Mode\n\nRAQCONS - Ply Strains Constraint Mode\nRAQDATC - Ply Strains Distributed Attachment Mode\nRAQNATC - Ply Strains Nodal Attachment Mode\nRAQEATC - Ply Strains Equivalent Inertia Attachment Mode\n\nRARCONS - Reaction Force Constraint Mode\nRARDATC - Reaction Force Distributed Attachment Mode\nRARNATC - Reaction Force Nodal Attachment Mode\nRAREATC - Reaction Force Equivalent Inertia Attachment Mode\n\nRASCONS - Stress Constraint Mode\nRASDATC - Stress Distributed Attachment Mode\nRASNATC - Stress Nodal Attachment Mode\nRASEATC - Stress Equivalent Inertia Attachment Mode\n\nRAPCONS - Ply Stresses Constraint Mode\nRAPDATC - Ply Stresses Distributed Attachment Mode\nRAPNATC - Ply Stresses Nodal Attachment Mode\nRAPEATC - Ply Stresses Equivalent Inertia Attachment Mode\n\nRAGCONS - Grid Point Forces Constraint Mode\nRAGDATC - Grid Point Forces Distributed Attachment Mode\nRAGNATC - Grid Point Forces Nodal Attachment Mode\nRAGEATC - Grid Point Forces Equivalent Inertia Attachment Mode\n\nRADEFMP - Displacement PHA^T * Effective Inertia Mode\n\nRADAMPZ - Viscous Damping Ratio Matrix\nRADAMPG - Structural Damping Ratio Matrix\n\nRAFGEN - Generalized Forces\nBHH - Modal Viscous Damping Matrix\nK4HH - Modal Structural Damping Matrix\n\"\"\"\nGEOM_TABLES = MSC_GEOM_TABLES + NX_GEOM_TABLES\n\nAUTODESK_MATRIX_TABLES = [\n #b'BELM',\n b'KELM',\n #b'MELM',\n] # type: List[bytes]\n# this will be split later\nTEST_MATRIX_TABLES = [b'ATB', b'BTA', b'MYDOF']\n\nRESULT_TABLES = NX_RESULT_TABLES + MSC_RESULT_TABLES\nMATRIX_TABLES = NX_MATRIX_TABLES + MSC_MATRIX_TABLES + AUTODESK_MATRIX_TABLES + TEST_MATRIX_TABLES + [b'MEFF']\n\n#GEOM_TABLES = MSC_GEOM_TABLES\n#RESULT_TABLES = MSC_RESULT_TABLES\n#MATRIX_TABLES = MSC_MATRIX_TABLES\n\n# TODO: these are weird...\n# RPOSTS1, MAXRATI, RESCOMP, PDRMSG\nINT_PARAMS_1 = {\n b'POST', b'OPPHIPA', b'OPPHIPB', b'GRDPNT', b'RPOSTS1', b'BAILOUT',\n b'COUPMASS', b'CURV', b'INREL', b'MAXRATI', b'OG',\n b'S1AM', b'S1M', b'DDRMM', b'MAXIT', b'PLTMSG', b'LGDISP', b'NLDISP',\n b'OUNIT2K', b'OUNIT2M', b'RESCOMP', b'PDRMSG', b'LMODES', b'USETPRT',\n b'NOCOMPS', b'OPTEXIT', b'RSOPT', b'GUSTAERO', b'MPTUNIT',\n b'USETSEL', b'NASPRT', b'DESPCH', b'DESPCH1', b'COMPARE', b'DBNBLKS', b'NEWSEQ', b'OLDSEQ',\n b'METHCMRS', b'NOFISR', b'KGGCPCH', b'ERROR', b'DBCDIAG', b'GPECT', b'LSTRN',\n b'DBDROPT', b'SEOP2CV', b'IRES', b'SNORMPRT', b'DBDRNL', b'VMOPT',\n b'OSWPPT', b'KDAMP', b'KDAMPFL', b'MATNL', b'MPCX', b'GEOMPLT', b'NOELOP',\n b'NOGPF', b'PROUT', b'SUPER', b'LGDIS', b'EST', b'SEP1XOVR',\n b'FRSEID', b'HRSEID', b'LRSEID', b'MODACC', b'XFLAG', b'TSTATIC',\n b'NASPDV', b'RMXCRT', b'RMXTRN', b'DBCLEAN', b'LANGLE', b'SEMAPPRT',\n b'FIXEDB', b'AMGOK', b'ASING', b'CNSTRT', b'CURVPLOT', b'CYCIO',\n b'CYCSEQ', b'DBDICT', b'DBINIT', b'DBSET1', b'DBSET2', b'DBSET3', b'DBSET4',\n b'DBSORT', b'DOPT', b'FACTOR', b'ALTSHAPE', b'MODTRK', b'IFTM', b'INRLM',\n b'KINDEX', b'KMIN', b'KMAX', b'LARGEDB', b'LOADINC', b'LOADING', b'LOOP',\n b'LOOPID', b'MODEL', b'MOREK', b'NEWDYN', b'NFECI', b'NINTPTS',\n b'NLAYERS', b'NOELOF', b'NOMSGSTR', b'NONCUP', b'NUMOUT', b'NUMOUT1', b'NUMOUT2',\n b'OPGTKG', b'OPPHIB', b'OUTOPT', b'PKRSP', b'RSPECTRA', b'RSPRINT',\n b'S1G', b'SCRSPEC', b'SEMAPOPT', b'SEQOUT', b'SESEF', b'SKPAMG', b'SKPAMP',\n b'SLOOPID', b'SOLID', b'SPCGEN', b'SRTELTYP', b'SRTOPT', b'START', b'SUBID',\n b'SUBSKP', b'TABID', b'TESTNEG', b'BDMNCON', b'FRUMIN',\n\n # not defined in qrg...\n b'NT', b'PNCHDB', b'DLOAD', b'NLOAD', b'NOAP', b'NOCMPFLD', b'NODATA',\n b'NODJE', b'NOMECH', b'NOSDR1', b'NOSHADE', b'NOSORT1', b'NOTRED',\n b'NSEGS', b'OLDELM', b'OPADOF', b'OUTPUT', b'P1', b'P2', b'P3', b'PCHRESP',\n b'PLOT', b'PLOTSUP', b'PRTPCH', b'RADLIN', b'RESDUAL', b'S1', b'SDATA',\n b'SEFINAL', b'SEMAP1', b'SKPLOAD', b'SKPMTRX', b'SOLID1', b'SSG3',\n b'PEDGEP', b'ACMSPROC', b'ACMSSEID', b'ACOUS', b'ACOUSTIC', b'ADJFLG',\n b'ADJLDF', b'AEDBCP', b'AESRNDM', b'ARCSIGNS', b'ATVUSE', b'BADMESH', b'BCHNG',\n b'BCTABLE', b'ROTCSV', b'ROTGPF', b'BEARDMP', b'BEARFORC', b'BOV', b'OP2FMT',\n\n # ???\n b'CHKSEC', b'CMSMETH', b'CNTNSUB', b'CNTSCL', b'CNTSTPS', b'CONCHG',\n b'DBDRPRJ', b'DBDRVER', b'DDAMRUN', b'DESCONX', b'DESEIG', b'DESFINAL',\n b'DESMAX', b'DESSOLAP', b'DIAGOPT',\n\n b'DOBUCKL', b'DOF123', b'DOMODES', b'DOSTATIC', b'DOTRIP', b'DRESP', b'DSGNOPTX',\n b'DSNOKD', b'DYNAMICX', b'EBULK', b'EIGNFREQ', b'ELOOPID',\n b'FDEPCB', b'FLUIDMP', b'FLUIDSE', b'FMODE', b'FREQDEP', b'FREQDEPS',\n b'GENEL', b'GEOMFLAG', b'GEOMU', b'GKCHNG', b'GLUSET', b'GMCONV', b'GNSTART',\n b'GOODVER', b'GOPH2', b'GRIDFMP', b'GRIDMP', b'HNNLK', b'ICTASET', b'IFPCHNG',\n b'INEP', b'INP2FMT', b'INP4FMT', b'INREL0', b'ITAPE', b'ITODENS', b'ITOITCNT',\n b'ITOMXITR', b'ITONDVAR', b'ITONGHBR', b'ITONOBJF', b'ITOOPITR', b'ITOPALG',\n b'ITOPALLR', b'ITOPCONV', b'ITOPDIAG', b'ITOPOPT', b'ITORMAS', b'ITOSIMP',\n b'ITOSIMP1', b'ITOSIMP2', b'IUNIT', b'K4CHNG', b'KCHNG', b'KREDX', b'LANGLES',\n b'LBEARING', b'LDSTI1', b'LMDYN', b'LMODESFL', b'LMSTAT', b'LNUMROT',\n b'LOADGENX', b'LOADREDX', b'LOADU', b'LODCHG', b'LROTOR', b'LTOPOPT',\n b'LUSET', b'LUSETD', b'LUSETS', b'LUSETX', b'MATGENX',\n b'MAXITER', b'MAXRPM', b'MAXSEIDX', b'MBDIFB', b'MBDIFO', b'MBDLMN',\n b'MCHNG', b'MDOF', b'MDTRKFLG', b'MELPG', b'MGRID', b'MLTIMSTR', b'MODESX',\n b'MODETRAK', b'MPIFRHD', b'MPNFLG', b'MREDX', b'MSCOP2', b'NACEXTRA',\n b'NCNOFFST', b'NDISOFP', b'NDVAR', b'NEWSET', b'NGELS', b'NJ', b'NK',\n b'NLBEAR', b'NLCBFOR', b'NMLOOP', b'NMSOL', b'NOA', b'NOASET', b'NOCOMP',\n b'NOFASET', b'NOFGSET', b'NOGENL', b'NOGEOM3', b'NOK4GG', b'NOK4JJ',\n b'NOKGGX', b'NOKJJX', b'NOLSET', b'NOMGG', b'NOMGGX', b'NOMJJX', b'NOQSET',\n b'NORADMAT', b'NORBM', b'NOSE', b'NOSIMP', b'NOSSET', b'NOUE', b'NOUP',\n b'NOYSET', b'NOZSET', b'NQSET', b'NR1OFFST', b'NR2OFFST', b'NR3OFFST',\n b'NROTORS', b'NSE', b'NSKIP0', b'NSOL', b'NSOLF', b'NUMPAN', b'NX',\n b'O2E', b'OADPMAX', b'OALTSHP', b'OBJIN', b'ODESMAX', b'ODSFLG', b'OMAXR',\n b'OP2SE', b'OP4FMT', b'OP4SE', b'OPGEOM', b'OPTIFCS',\n b'OPTII231', b'OPTII408', b'OPTII411', b'OPTII420', b'OPTIIDMP', b'OPTISNS',\n b'OTAPE', b'OUNIT1', b'OUNIT2', b'OUNIT2R', b'OUTFMP', b'OUTSMP', b'PANELMP',\n b'PBCONT', b'PCHNG', b'PITIME', b'PKLLR', b'POSTU', b'PRTMAT', b'PSLGDVX',\n b'PSLOAD', b'PSORT', b'PVALINIT', b'PVALLAST', b'PVALLIST', b'PYCHNG',\n b'REFOPT', b'RESLTOPT', b'RESPSENX', b'RGBEAMA', b'RGBEAME', b'RGLCRIT',\n b'RGSPRGK', b'RMXPANEL', b'ROTPRES', b'ROTPRT', b'RPDFRD', b'RVCHG', b'RVCHG1',\n b'RVCHG2', b'S1AG', b'SAVERSTL', b'SDSRFLAG', b'SEBULK',\n b'SEDMP231', b'SEDMP265', b'SEDMP408', b'SEDMP411', b'SEDMP445', b'SEDMPFLG',\n b'SELDPRS', b'SKIPSE', b'SNDSEIDX', b'SOLFINAL',\n b'SOLNLX', b'SOLNX', b'SOLVSUB', b'SPLINE', b'STOP0', b'STRUCTMP', b'SWEXIST',\n b'TORSIN', b'UACCEL', b'UNIQIDS', b'VOL', b'VOLS', b'VUELJUMP', b'VUENEXT',\n b'VUGJUMP', b'VUGNEXT', b'WGT', b'WGTS', b'WRTMAT',\n b'XSMALLQ',\n b'XNTIPS', b'XRESLTOP', b'XSEMEDIA', b'XSEUNIT', b'XTIPSCOL',\n b'XUPFAC', b'XYUNIT', b'XZCOLLCT', b'Z2XSING',\n b'ZUZRI1', b'ZUZRI2', b'ZUZRI3', b'ZUZRI4', b'ZUZRI5', b'ZUZRI6', b'ZUZRI7', b'ZUZRI8', b'ZUZRI9', b'ZUZRI10',\n b'ZUZRL1', b'ZUZRL2', b'ZUZRL3', b'ZUZRL4', b'ZUZRL5', b'ZUZRL6', b'ZUZRL7', b'ZUZRL8', b'ZUZRL9', b'ZUZRL10',\n b'ZUZRR1', b'ZUZRR2', b'ZUZRR3', b'ZUZRR4', b'ZUZRR5', b'ZUZRR6', b'ZUZRR7', b'ZUZRR8', b'ZUZRR9', b'ZUZRR10',\n\n # no\n #b'SEPS', b'SMALLQ', b'FEPS',\n}\nFLOAT_PARAMS_1 = {\n b'K6ROT', b'WTMASS', b'SNORM', b'PATVER', b'MAXRATIO', b'EPSHT',\n b'SIGMA', b'TABS', b'AUNITS', b'BOLTFACT', b'LMSCAL',\n 'DSZERO', b'G', b'GFL', b'LFREQ', b'HFREQ', b'ADPCON',\n b'W3', b'W4', b'W3FL', b'W4FL', b'PREFDB',\n b'EPZERO', b'DSZERO', b'TINY', b'TOLRSC',\n b'FRSPD', b'HRSPD', b'LRSPD', b'MTRFMAX', b'ROTCMRF', b'MTRRMAX',\n b'LAMLIM', b'BIGER', b'BIGER1', b'BIGER2', b'CLOSE',\n b'EPSBIG', b'EPSMALC', b'EPSMALU', b'HIRES', b'KDIAG', b'MACH', b'VREF',\n b'STIME', b'TESTSE', b'LFREQFL', b'Q', b'ADPCONS', b'AFNORM', b'AFZERO',\n b'GE', b'MASSDENS',\n\n # should this be FLOAT_PARAMS_1???\n b'EPPRT', b'HFREQFL',\n\n # not defined\n b'PRPA', b'PRPHIVZ', b'PRPJ', b'PRRULV', b'RMAX', b'ADJFRQ', b'ARF',\n b'ARS', # b'BSHDAMP',\n b'EPSRC',\n\n # floats - not verified\n b'THRSHOLD', b'SEPS', b'SMALLQ', b'FEPS',\n\n # or integer (not string)\n b'BSHDMP',\n b'BSHDMP4',\n b'CONFAC',\n b'CP',\n b'DBCPAE',\n b'DBCPATH',\n b'DFREQ', b'DFRSPCF', b'DSTSPCF', b'DTRSPCF',\n b'DUCTFMAX',\n b'EXTBEMI', b'EXTBEMO', b'EXTDONE', b'EXTDRUNT', b'EXTUNIT',\n b'FZERO', b'LMFACT', b'MPCZERO',\n b'RESVPGF', b'RESVRAT', b'SWPANGLE', b'UPFAC', b'UZROLD',\n}\nFLOAT_PARAMS_2 = {\n b'BETA', b'CB1', b'CB2', b'CK1', b'CK2', b'CK3', b'CK41', b'CK42',\n b'CM1', b'CM2',\n b'G1', b'G2', b'G3', b'G4', b'G5', b'G6', b'G7', b'G8', b'G9', b'G10',\n b'G11', b'G12', b'G13', b'G14', b'G15', b'G16', b'G17', b'G18', b'G19',\n b'ALPHA1', b'ALPHA2',\n b'CA1', b'CA2',\n b'CP1', b'CP2',\n\n\n # should this be FLOAT_PARAMS_1???\n #b'EPPRT',\n}\nINT_PARAMS_2 = {\n b'LOADFACS',\n b'ZUZRC1', b'ZUZRC2', b'ZUZRC3', b'ZUZRC4', b'ZUZRC5', b'ZUZRC6', b'ZUZRC7', b'ZUZRC8', b'ZUZRC9', b'ZUZRC10',\n}\nDOUBLE_PARAMS_1 = [] # b'Q'\nSTR_PARAMS_1 = {\n b'POSTEXT', b'PRTMAXIM', b'AUTOSPC', b'OGEOM', b'PRGPST',\n b'RESVEC', b'RESVINER', b'ALTRED', b'OGPS', b'OIBULK', b'OMACHPR',\n b'UNITSYS', b'F56', b'OUGCORD', b'OGEM', b'EXTSEOUT',\n b'CDIF', b'SUPAERO', b'RSCON', b'AUTOMPC', b'DBCCONV',\n b'AUTOSPRT', b'PBRPROP', b'OMID', b'HEATSTAT', b'SECOMB', b'ELEMITER',\n b'ELITASPC', b'DBCONV', b'SHLDAMP', b'COMPMATT', b'SPCSTR', b'ASCOUP',\n b'PRTRESLT', b'SRCOMPS', b'CHECKOUT', b'SEMAP', b'AESMETH', b'RESVALT',\n b'ROTSYNC', b'SYNCDAMP', b'PRGPOST', b'WMODAL', b'SDAMPUP',\n b'COLPHEXA', b'CHKOUT', b'CTYPE', b'DBNAME', b'VUHEXA', b'VUPENTA', b'VUTETRA',\n b'MESH', b'OPTION', b'PRINT', b'SENAME', b'MECHFIX', b'RMXTRAN', b'FLEXINV',\n b'ADSTAT', b'ACOUT', b'ACSYM', b'ACTYPE', b'ADBX', b'AUTOSEEL',\n b'RDSPARSE',\n b'SPARSEDR',\n b'BSHDAMP',\n b'CORROPT',\n b'DBACOUS',\n b'DBALLNOQ',\n b'DBALLX',\n b'DBAPI',\n b'DBAPP',\n b'DBCNT',\n b'DBCOVWRT',\n b'DBDNOPT',\n b'DBDNR', b'DBDNR1', b'DBDNX', b'DBEXT', b'DBGOA', b'DBMAP',\n b'DBOFP2X', b'DBOFPX', b'DBRCVX', b'DBSCRR', b'DBUPOPT', b'DBUPR',\n b'DBUPX', b'DBXSEDR', b'DBXSEDRR', b'DBZUZR', b'DSOR', b'DSOX',\n b'DVGRDN', b'DYNSPCF', b'EQVSCR', b'EXTDROUT',\n b'FLEXINCR', b'FTL', b'GDAMPF', b'GEOCENT', b'IFPSCR', b'IFPSOPT',\n b'IFPX', b'IFPXOPT', b'MASTER', b'MODEOUT',\n b'NXVER', b'OAPP', b'OCMP', b'OEE', b'OEEX', b'OEF', b'OEFX', b'OEPT',\n b'OES', b'OESE', b'OESX', b'OGPF', b'OMPT', b'OPG', b'OPTIM', b'OQG',\n b'OUG', b'OUMU', b'OUTSCR', b'PANAME', b'QSETREM', b'RESVSE', b'RESVSLI',\n b'RESVSO', b'RSATT', b'SAVEOFP', b'SAVERST', b'SCRATCH', b'SDRPOPT',\n b'SECOMB0', b'SELRNG', b'SERST', b'SOFTEXIT', b'SOLAPPI', b'SOLTYPI',\n b'TDB0', b'TDBX', b'UPDTBSH',\n b'USETSTR1', b'USETSTR2', b'USETSTR3', b'USETSTR4',\n b'VMOPTSET', b'VUBEAM', b'VUQUAD4', b'VUTRIA3', b'WRN', b'XAUTOSPT',\n b'XRESVECA', b'XRESVECO', b'XRESVIRA', b'XRESVIRO',\n b'ZUZRCL1', b'ZUZRCL2', b'ZUZRCL3', b'ZUZRCL4', b'ZUZRCL5', b'ZUZRCL6', b'ZUZRCL7', b'ZUZRCL8', b'ZUZRCL9', b'ZUZRCL10',\n b'ZUZRCH1', b'ZUZRCH2', b'ZUZRCH3', b'ZUZRCH4', b'ZUZRCH5', b'ZUZRCH6', b'ZUZRCH7', b'ZUZRCH8', b'ZUZRCH9', b'ZUZRCH10',\n b'APPI', b'APPF',\n\n # part of param, checkout\n b'PRTBGPDT', b'PRTCSTM', b'PRTEQXIN', b'PRTGPDT',\n b'PRTGPL', b'PRTGPTT', b'PRTMGG', b'PRTPG',\n\n # superelements\n b'EXTOUT', b'SESDAMP',\n\n # TODO: remove these as they're in the matrix test and are user\n # defined PARAMs; arguably all official examples should just work\n # TODO: add an option for custom PARAMs\n b'ADB', b'AEDB', b'MREDUC', b'OUTDRM', b'OUTFORM', b'REDMETH', b'DEBUG',\n b'AEDBX', b'AERO', b'AUTOSUP0', b'AXIOPT',\n}\n\nclass OP2_Scalar(LAMA, ONR, OGPF,\n OEF, OES, OGS, OPG, OQG, OUG, OGPWG, FortranFormat):\n \"\"\"Defines an interface for the Nastran OP2 file.\"\"\"\n @property\n def total_effective_mass_matrix(self):\n \"\"\"6x6 matrix\"\"\"\n return self.matrices['EFMFSMS']\n\n @property\n def effective_mass_matrix(self):\n \"\"\"6x6 matrix\"\"\"\n return self.matrices['EFMASSS']\n\n @property\n def rigid_body_mass_matrix(self):\n \"\"\"6x6 matrix\"\"\"\n return self.matrices['RBMASS']\n\n @property\n def modal_effective_mass_fraction(self):\n \"\"\"6xnmodes matrix\"\"\"\n return self.matrices['EFMFACS']#.dataframe\n\n @property\n def modal_participation_factors(self):\n \"\"\"6xnmodes matrix\"\"\"\n return self.matrices['MPFACS']#.dataframe\n\n @property\n def modal_effective_mass(self):\n \"\"\"6xnmodes matrix\"\"\"\n return self.matrices['MEFMASS']#.dataframe\n\n @property\n def modal_effective_weight(self):\n \"\"\"6xnmodes matrix\"\"\"\n return self.matrices['MEFWTS']#.dataframe\n\n @property\n def matrix_tables(self):\n return MATRIX_TABLES\n\n def set_as_nx(self):\n self.is_nx = True\n self.is_msc = False\n self.is_autodesk = False\n self.is_nasa95 = False\n self.is_optistruct = False\n self._nastran_format = 'nx'\n\n def set_as_msc(self):\n self.is_nx = False\n self.is_msc = True\n self.is_autodesk = False\n self.is_nasa95 = False\n self.is_optistruct = False\n self._nastran_format = 'msc'\n\n def set_as_autodesk(self):\n self.is_nx = False\n self.is_msc = False\n self.is_autodesk = True\n self.is_nasa95 = False\n self.is_optistruct = False\n self._nastran_format = 'autodesk'\n\n def set_as_nasa95(self):\n self.is_nx = False\n self.is_msc = False\n self.is_autodesk = False\n self.is_optistruct = False\n self.is_nasa95 = True\n self._nastran_format = 'nasa95'\n self._read_oes1_loads = self._read_oes1_loads_nasa95\n self._read_oef1_loads = self._read_oef1_loads_nasa95\n\n def set_as_optistruct(self):\n self.is_nx = False\n self.is_msc = False\n self.is_autodesk = False\n self.is_nasa95 = False\n self.is_optistruct = True\n self._nastran_format = 'optistruct'\n\n def __init__(self, debug=False, log=None, debug_file=None):\n \"\"\"\n Initializes the OP2_Scalar object\n\n Parameters\n ----------\n debug : bool; default=False\n enables the debug log and sets the debug in the logger\n log : Log()\n a logging object to write debug messages to\n (.. seealso:: import logging)\n debug_file : str; default=None (No debug)\n sets the filename that will be written to\n\n \"\"\"\n assert isinstance(debug, bool), 'debug=%r' % debug\n\n self.log = get_logger(log, 'debug' if debug else 'info')\n self._count = 0\n self.op2_filename = None\n self.bdf_filename = None\n self.f06_filename = None\n self.des_filename = None\n self.h5_filename = None\n self._encoding = 'utf8'\n\n #: should a MATPOOL \"symmetric\" matrix be stored as symmetric\n #: it takes double the RAM, but is easier to use\n self.apply_symmetry = True\n\n LAMA.__init__(self)\n ONR.__init__(self)\n OGPF.__init__(self)\n\n OEF.__init__(self)\n OES.__init__(self)\n #OESM.__init__(self)\n OGS.__init__(self)\n\n OPG.__init__(self)\n OQG.__init__(self)\n OUG.__init__(self)\n OGPWG.__init__(self)\n FortranFormat.__init__(self)\n\n self.is_vectorized = False\n self._close_op2 = True\n\n self.result_names = set()\n\n self.grid_point_weight = {}\n self.words = []\n self.debug = debug\n self._last_comment = None\n #self.debug = True\n #self.debug = False\n #debug_file = None\n if debug_file is None:\n self.debug_file = None\n else:\n assert isinstance(debug_file, str), debug_file\n self.debug_file = debug_file\n\n self.op2_reader = OP2Reader(self)\n\n def set_subcases(self, subcases=None):\n \"\"\"\n Allows you to read only the subcases in the list of isubcases\n\n Parameters\n ----------\n subcases : List[int, ...] / int; default=None->all subcases\n list of [subcase1_ID,subcase2_ID]\n\n \"\"\"\n #: stores the set of all subcases that are in the OP2\n #self.subcases = set()\n if subcases is None or subcases == []:\n #: stores if the user entered [] for isubcases\n self.is_all_subcases = True\n self.valid_subcases = []\n else:\n #: should all the subcases be read (default=True)\n self.is_all_subcases = False\n\n if isinstance(subcases, int):\n subcases = [subcases]\n\n #: the set of valid subcases -> set([1,2,3])\n self.valid_subcases = set(subcases)\n self.log.debug(\"set_subcases - subcases = %s\" % self.valid_subcases)\n\n def set_transient_times(self, times): # TODO this name sucks...\n \"\"\"\n Takes a dictionary of list of times in a transient case and\n gets the output closest to those times.\n\n Examples\n --------\n >>> times = {subcase_id_1: [time1, time2],\n subcase_id_2: [time3, time4]}\n\n .. warning:: I'm not sure this still works...\n\n \"\"\"\n expected_times = {}\n for (isubcase, etimes) in times.items():\n etimes = list(times)\n etimes.sort()\n expected_times[isubcase] = array(etimes)\n self.expected_times = expected_times\n\n def _get_table_mapper(self):\n \"\"\"gets the dictionary of function3 / function4\"\"\"\n\n # MSC table mapper\n table_mapper = {\n # per NX\n b'OESVM1' : [self._read_oes1_3, self._read_oes1_4], # isat_random\n b'OESVM1C' : [self._read_oes1_3, self._read_oes1_4], # isat_random\n b'OSTRVM1' : [self._read_oes1_3, self._read_ostr1_4], # isat_random\n b'OSTRVM1C' : [self._read_oes1_3, self._read_ostr1_4], # isat_random\n\n b'OSTRVM2' : [self._read_oes2_3, self._read_ostr2_4],\n\n b'OESVM2' : [self._read_oes2_3, self._read_oes2_4], # big random\n b'OES2C' : [self._read_oes2_3, self._read_oes2_4],\n b'OSTR2' : [self._read_oes2_3, self._read_ostr2_4], # TODO: disable\n b'OSTR2C' : [self._read_oes2_3, self._read_ostr2_4],\n #b'OES2C' : [self._table_passer, self._table_passer], # stress\n #b'OSTR2' : [self._table_passer, self._table_passer], # TODO: enable\n #b'OSTR2C' : [self._table_passer, self._table_passer],\n\n b'OTEMP1' : [self._read_otemp1_3, self._read_otemp1_4],\n # --------------------------------------------------------------------------\n # MSC TABLES\n # common tables\n\n # unorganized\n b'RADCONS': [self._read_oug1_3, self._read_oug_4], # Displacement Constraint Mode (OUG)\n b'RADEFFM': [self._read_oug1_3, self._read_oug_4], # Displacement Effective Inertia Mode (OUG)\n b'RADEATC': [self._read_oug1_3, self._read_oug_4], # Displacement Equivalent Inertia Attachment mode (OUG)\n\n # broken - isat_launch_100hz.op2 - wrong numwide\n # spc forces\n b'RAQCONS': [self._read_oqg1_3, self._read_oqg_4], # Constraint mode MPC force table (OQG)\n b'RAQEATC': [self._read_oqg1_3, self._read_oqg_4], # Attachment mode MPC force table (OQG)\n #b'RAQCONS': [self._table_passer, self._table_passer], # temporary\n #b'RAQEATC': [self._table_passer, self._table_passer], # temporary\n\n # element forces\n b'RAFCONS': [self._read_oef1_3, self._read_oef1_4], # Element Force Constraint Mode (OEF)\n b'RAFEATC': [self._read_oef1_3, self._read_oef1_4], # Element Force Equivalent Inertia Attachment mode (OEF)\n #b'RAFCONS': [self._table_passer, self._table_passer], # temporary\n #b'RAFEATC': [self._table_passer, self._table_passer], # temporary\n\n # grid point forces\n b'RAGCONS': [self._read_ogpf1_3, self._read_ogpf1_4], # Grid Point Forces Constraint Mode (OGPFB)\n b'RAGEATC': [self._read_ogpf1_3, self._read_ogpf1_4], # Grid Point Forces Equivalent Inertia Attachment mode (OEF)\n #b'RAGCONS': [self._table_passer, self._table_passer], # Grid Point Forces Constraint Mode (OGPFB)\n #b'RAGEATC': [self._table_passer, self._table_passer], # Grid Point Forces Equivalent Inertia Attachment mode (OEF)\n\n # stress\n b'RAPCONS': [self._read_oes1_3, self._read_oes1_4], # Constraint mode ply stress table (OES)\n b'RAPEATC': [self._read_oes1_3, self._read_oes1_4], # Attachment mode ply stress table (OES)\n #b'RAPCONS': [self._table_passer, self._table_passer], # Constraint mode ply stress table (OES)\n #b'RAPEATC': [self._table_passer, self._table_passer], # Attachment mode ply stress table (OES)\n\n # stress\n b'RASCONS': [self._read_oes1_3, self._read_oes1_4], # Stress Constraint Mode (OES)\n b'RASEATC': [self._read_oes1_3, self._read_oes1_4], # Stress Equivalent Inertia Attachment mode (OES)\n #b'RASCONS': [self._table_passer, self._table_passer], # temporary\n #b'RASEATC': [self._table_passer, self._table_passer], # temporary\n\n # strain\n b'RAEEATC': [self._read_oes1_3, self._read_ostr1_4], # Strain Equivalent Inertia Attachment mode (OES)\n b'RAECONS': [self._read_oes1_3, self._read_ostr1_4], # Strain Constraint Mode (OSTR)\n #b'RAEEATC': [self._table_passer, self._table_passer], # temporary\n #b'RAECONS': [self._table_passer, self._table_passer], # temporary\n\n # strain energy\n b'RANEATC' : [self._read_onr1_3, self._read_onr1_4], # Strain Energy Equivalent Inertia Attachment mode (ORGY1)\n b'RANCONS': [self._read_onr1_3, self._read_onr1_4], # Constraint mode element strain energy table (ORGY1)\n #b'RANEATC': [self._table_passer, self._table_passer], # Strain Energy Equivalent Inertia Attachment mode (ORGY1)\n #b'RANCONS': [self._table_passer, self._table_passer], # Constraint mode element strain energy table (ORGY1)\n\n\n #b'TOL': [self._table_passer, self._table_passer],\n\n b'MATPOOL': [self._table_passer, self._table_passer], # DMIG bulk data entries\n\n # this comment may refer to CSTM?\n #F:\\work\\pyNastran\\examples\\Dropbox\\pyNastran\\bdf\\cards\\test\\test_mass_01.op2\n #F:\\work\\pyNastran\\examples\\matpool\\gpsc1.op2\n b'AXIC': [self._table_passer, self._table_passer],\n\n b'RSOUGV1': [self._table_passer, self._table_passer],\n b'RESOES1': [self._table_passer, self._table_passer],\n b'RESEF1' : [self._table_passer, self._table_passer],\n b'DESCYC' : [self._table_passer, self._table_passer],\n #b'AEMONPT' : [self._read_aemonpt_3, self._read_aemonpt_4],\n #=======================\n # OEF\n # element forces\n #b'OEFITSTN' : [self._table_passer, self._table_passer], # works\n b'OEFITSTN' : [self._read_oef1_3, self._read_oef1_4],\n b'OEFIT' : [self._read_oef1_3, self._read_oef1_4], # failure indices\n b'OEF1X' : [self._read_oef1_3, self._read_oef1_4], # element forces at intermediate stations\n b'OEF1' : [self._read_oef1_3, self._read_oef1_4], # element forces or heat flux\n b'HOEF1' : [self._read_oef1_3, self._read_oef1_4], # element heat flux\n b'DOEF1' : [self._read_oef1_3, self._read_oef1_4], # scaled response spectra - forces\n\n # off force\n b'OEF2' : [self._read_oef2_3, self._read_oef2_4], # element forces or heat flux\n #=======================\n # OQG\n # spc forces\n # OQG1/OQGV1 - spc forces in the nodal frame\n # OQP1 - scaled response spectra - spc-forces\n b'OQG1' : [self._read_oqg1_3, self._read_oqg_4],\n b'OQG2' : [self._read_oqg2_3, self._read_oqg_4],\n\n b'OQGV1' : [self._read_oqg1_3, self._read_oqg_4],\n b'OQGV2' : [self._read_oqg2_3, self._read_oqg_4],\n\n b'OQP1' : [self._read_oqg1_3, self._read_oqg_4],\n b'OQP2' : [self._read_oqg2_3, self._read_oqg_4],\n\n # SPC/MPC tables depending on table_code\n # SPC - NX/MSC\n # MPC - MSC\n b'OQGATO1' : [self._read_oqg1_3, self._read_oqg_4],\n b'OQGCRM1' : [self._read_oqg1_3, self._read_oqg_4],\n b'OQGPSD1' : [self._read_oqg1_3, self._read_oqg_4],\n b'OQGRMS1' : [self._read_oqg1_3, self._read_oqg_4],\n b'OQGNO1' : [self._read_oqg1_3, self._read_oqg_4],\n\n b'OQGATO2' : [self._read_oqg2_3, self._read_oqg_4],\n b'OQGCRM2' : [self._read_oqg2_3, self._read_oqg_4],\n b'OQGPSD2' : [self._read_oqg2_3, self._read_oqg_4],\n b'OQGRMS2' : [self._table_passer, self._table_passer], # buggy on isat random\n b'OQGNO2' : [self._table_passer, self._table_passer], # buggy on isat random\n #b'OQGRMS2' : [self._read_oqg2_3, self._read_oqg_4], # buggy on isat random\n #b'OQGNO2' : [self._read_oqg2_3, self._read_oqg_4], # buggy on isat random\n\n b'PSDF' : [self._read_psdf_3, self._read_psdf_4], # MSC NASA/goesr\n\n #=======================\n # MPC Forces\n # these are NX tables\n\n # OQGM1 - mpc forces in the nodal frame\n b'OQMG1' : [self._read_oqg1_3, self._read_oqg_mpc_forces],\n b'OQMATO1' : [self._read_oqg1_3, self._read_oqg_mpc_ato],\n b'OQMCRM1' : [self._read_oqg1_3, self._read_oqg_mpc_crm],\n b'OQMPSD1' : [self._read_oqg1_3, self._read_oqg_mpc_psd],\n b'OQMRMS1' : [self._read_oqg1_3, self._read_oqg_mpc_rms],\n b'OQMNO1' : [self._read_oqg1_3, self._read_oqg_mpc_no],\n\n b'OQMG2' : [self._read_oqg2_3, self._read_oqg_mpc_forces], # big random\n b'OQMATO2' : [self._read_oqg2_3, self._read_oqg_mpc_ato],\n b'OQMCRM2' : [self._read_oqg2_3, self._read_oqg_mpc_crm],\n b'OQMPSD2' : [self._read_oqg2_3, self._read_oqg_mpc_psd],\n b'OQMRMS2' : [self._table_passer, self._table_passer], # buggy on isat random\n b'OQMNO2' : [self._table_passer, self._table_passer], # buggy on isat random\n #b'OQMRMS2' : [self._read_oqg2_3, self._read_oqg_mpc_rms], # buggy on isat random\n #b'OQMNO2' : [self._read_oqg2_3, self._read_oqg_mpc_no], # buggy on isat random\n\n #=======================\n # OPG\n # applied loads\n b'OPG1' : [self._read_opg1_3, self._read_opg1_4], # applied loads in the nodal frame\n b'OPGV1' : [self._read_opg1_3, self._read_opg1_4], # solution set applied loads?\n b'OPNL1' : [self._read_opg1_3, self._read_opg1_4], # nonlinear loads\n b'OCRPG' : [self._read_opg1_3, self._read_opg1_4], # post-buckling loads\n\n b'OPG2' : [self._read_opg2_3, self._read_opg1_4], # applied loads in the nodal frame\n b'OPNL2' : [self._read_opg2_3, self._read_opg1_4], # nonlinear loads\n\n b'OPGATO1' : [self._read_opg1_3, self._read_opg1_4],\n b'OPGCRM1' : [self._read_opg1_3, self._read_opg1_4],\n b'OPGPSD1' : [self._read_opg1_3, self._read_opg1_4],\n b'OPGRMS1' : [self._read_opg1_3, self._read_opg1_4],\n b'OPGNO1' : [self._read_opg1_3, self._read_opg1_4],\n\n b'OPGATO2' : [self._read_opg2_3, self._read_opg1_4],\n b'OPGCRM2' : [self._read_opg2_3, self._read_opg1_4],\n b'OPGPSD2' : [self._read_opg2_3, self._read_opg1_4],\n #b'OPGRMS2' : [self._table_passer, self._table_passer],\n #b'OPGNO2' : [self._table_passer, self._table_passer],\n b'OPGRMS2' : [self._read_opg2_3, self._read_opg1_4],\n b'OPGNO2' : [self._read_opg2_3, self._read_opg1_4],\n #=======================\n # OGPFB1\n # grid point forces\n b'OGPFB1' : [self._read_ogpf1_3, self._read_ogpf1_4], # grid point forces\n #b'OGPFB2' : [self._read_ogpf1_3, self._read_ogpf1_4], # grid point forces\n\n #=======================\n # ONR/OEE\n # strain energy density\n b'ONRGY' : [self._read_onr1_3, self._read_onr1_4],\n b'ONRGY1' : [self._read_onr1_3, self._read_onr1_4], # strain energy density\n b'ONRGY2': [self._read_onr2_3, self._read_onr1_4],\n #b'ONRGY2': [self._table_passer, self._table_passer],\n #===========================================================\n # OES\n # stress\n # OES1C - Table of composite element stresses or strains in SORT1 format\n # OESRT - Table of composite element ply strength ratio. Output by SDRCOMP\n b'OES1X1' : [self._read_oes1_3, self._read_oes1_4], # stress - nonlinear elements\n b'OES1' : [self._read_oes1_3, self._read_oes1_4], # stress - linear only\n b'OES1X' : [self._read_oes1_3, self._read_oes1_4], # element stresses at intermediate stations & nonlinear stresses\n b'OES1C' : [self._read_oes1_3, self._read_oes1_4], # stress - composite\n b'OESCP' : [self._read_oes1_3, self._read_oes1_4], # stress - nonlinear???\n b'OESRT' : [self._read_oes1_3, self._read_oes1_4], # ply strength ratio\n\n # strain\n b'OSTR1' : [self._read_oes1_3, self._read_ostr1_4], # strain - autodesk/9zk6b5uuo.op2\n b'OSTR1X' : [self._read_oes1_3, self._read_ostr1_4], # strain - isotropic\n b'OSTR1C' : [self._read_oes1_3, self._read_ostr1_4], # strain - composite\n b'OESTRCP' : [self._read_oes1_3, self._read_ostr1_4],\n\n b'OSTR1PL' : [self._table_passer, self._table_passer], # ????\n b'OSTR1THC' : [self._table_passer, self._table_passer], # ????\n b'OSTR1CR' : [self._table_passer, self._table_passer], # ????\n #b'OEFIIP'\n b'XCASECC' : [self._table_passer, self._table_passer], # ????\n\n # special nonlinear tables\n # OESNLBR - Slideline stresses\n # OESNLXD - Nonlinear transient stresses\n # OESNLXR - Nonlinear stress\n # Table of nonlinear element stresses in SORT1 format and appended for all subcases\n\n b'OESNLXR' : [self._read_oes1_3, self._read_oes1_4], # nonlinear stresses\n b'OESNLXD' : [self._read_oes1_3, self._read_oes1_4], # nonlinear transient stresses\n b'OESNLBR' : [self._read_oes1_3, self._read_oes1_4],\n b'OESNL1X' : [self._read_oes1_3, self._read_oes1_4],\n\n b'OESNL2' : [self._read_oes2_3, self._read_oes2_4],\n b'OESNLXR2' : [self._read_oes2_3, self._read_oes2_4],\n b'OESNLBR2' : [self._read_oes2_3, self._read_oes2_4],\n #b'OESNLXR2' : [self._table_passer, self._table_passer],\n #b'OESNLBR2' : [self._table_passer, self._table_passer],\n\n # off stress\n b'OES2' : [self._read_oes2_3, self._read_oes2_4], # stress - linear only - disabled; need better tests\n #b'OES2' : [self._table_passer, self._table_passer], # stress - linear only - disabled; need better tests\n\n b'OESPSD2C' : [self._read_oes2_3, self._read_oes2_4], # isat_random (nx)\n b'OSTPSD2C' : [self._read_oes2_3, self._read_ostr2_4], # isat_random (nx)\n #=======================\n\n # off strain\n b'OSTRATO1' : [self._read_oes1_3, self._read_ostr1_4],\n b'OSTRCRM1' : [self._read_oes1_3, self._read_ostr1_4],\n b'OSTRPSD1' : [self._read_oes1_3, self._read_ostr1_4],\n b'OSTRRMS1' : [self._read_oes1_3, self._read_ostr1_4], # isat_random\n b'OSTRNO1' : [self._read_oes1_3, self._read_ostr1_4], # isat_random\n\n b'OSTRATO2' : [self._read_oes2_3, self._read_ostr2_4],\n b'OSTRCRM2' : [self._read_oes2_3, self._read_ostr2_4],\n b'OSTRPSD2' : [self._read_oes2_3, self._read_ostr2_4],\n b'OSTRRMS2' : [self._table_passer, self._table_passer], # buggy on isat random\n b'OSTRNO2' : [self._table_passer, self._table_passer], # buggy on isat random\n #b'OSTRRMS2' : [self._read_oes2_3, self._read_ostr2_4], # buggy on isat random\n #b'OSTRNO2' : [self._read_oes2_3, self._read_ostr2_4], # buggy on isat random\n\n b'OSTRMS1C' : [self._read_oes1_3, self._read_ostr1_4], # isat_random\n b'OSTNO1C' : [self._read_oes1_3, self._read_ostr1_4], # isat_random\n\n #=======================\n # OUG\n # displacement/velocity/acceleration/eigenvector/temperature\n b'OUG1' : [self._read_oug1_3, self._read_oug_4], # displacements in nodal frame\n # OVG1?\n b'OAG1' : [self._read_oug1_3, self._read_oug_4], # accelerations in nodal frame\n\n b'OUG1F' : [self._read_oug1_3, self._read_oug_4], # acoustic displacements in ? frame\n\n b'OUGV1' : [self._read_oug1_3, self._read_oug_4], # displacements in nodal frame\n b'BOUGV1' : [self._read_oug1_3, self._read_oug_4], # OUG1 on the boundary???\n b'BOUGF1' : [self._read_oug1_3, self._read_oug_4], # OUG1 on the boundary???\n b'OUGV1PAT': [self._read_oug1_3, self._read_oug_4], # OUG1 + coord ID\n b'OUPV1' : [self._read_oug1_3, self._read_oug_4], # scaled response spectra - displacement\n b'TOUGV1' : [self._read_oug1_3, self._read_oug_4], # grid point temperature\n b'ROUGV1' : [self._read_oug1_3, self._read_oug_4], # relative OUG\n b'OPHSA' : [self._read_oug1_3, self._read_oug_4], # Displacement output table in SORT1\n b'OUXY1' : [self._read_oug1_3, self._read_oug_4], # Displacements in SORT1 format for h-set or d-set.\n b'OUGPC1' : [self._read_ougpc1_3, self._read_ougpc_4], # panel contributions\n b'OUGPC2' : [self._read_ougpc2_3, self._read_ougpc_4], # panel contributions\n b'OUGF1' : [self._read_oug1_3, self._read_oug_4], # Acoustic pressures at microphone points in SORT1 format\n b'OUGF2' : [self._read_oug2_3, self._read_oug_4], # Acoustic pressures at microphone points in SORT1 format\n\n b'OUGV2' : [self._read_oug2_3, self._read_oug_4], # displacements in nodal frame\n b'ROUGV2' : [self._read_oug2_3, self._read_oug_4], # relative OUG\n b'OUXY2' : [self._read_oug2_3, self._read_oug_4], # Displacements in SORT2 format for h-set or d-set.\n\n # modal contribution\n b'OUGMC1' : [self._read_oug1_3, self._read_ougmc_4],\n b'OQGMC1' : [self._read_oqg1_3, self._read_ougmc_4],\n b'OESMC1' : [self._read_oes1_3, self._read_oesmc_4],\n b'OSTRMC1' : [self._read_oes1_3, self._read_oesmc_4],\n\n #F:\\work\\pyNastran\\examples\\Dropbox\\move_tpl\\sbuckl2a.op2\n b'OCRUG' : [self._read_oug1_3, self._read_oug_4], # post-buckling displacement\n\n b'OPHIG' : [self._read_oug1_3, self._read_oug_4], # eigenvectors in basic coordinate system\n b'BOPHIG' : [self._read_oug1_3, self._read_oug_4], # eigenvectors in basic coordinate system\n b'BOPHIGF' : [self._read_oug1_3, self._read_oug_4], # Eigenvectors in the basic coordinate system for the fluid portion of the model.\n b'BOPHIGS' : [self._read_oug1_3, self._read_oug_4], # Eigenvectors in the basic coordinate system for the structural portion of the model.\n\n b'BOPG1' : [self._read_opg1_3, self._read_opg1_4], # applied loads in basic coordinate system\n\n b'OUGATO1' : [self._read_oug1_3, self._read_oug_ato],\n b'OUGCRM1' : [self._read_oug1_3, self._read_oug_crm],\n b'OUGPSD1' : [self._read_oug1_3, self._read_oug_psd],\n b'OUGRMS1' : [self._read_oug1_3, self._read_oug_rms],\n b'OUGNO1' : [self._read_oug1_3, self._read_oug_no],\n\n b'OUGATO2' : [self._read_oug2_3, self._read_oug_ato],\n b'OUGCRM2' : [self._read_oug2_3, self._read_oug_crm],\n b'OUGPSD2' : [self._read_oug2_3, self._read_oug_psd],\n b'OUGRMS2' : [self._table_passer, self._table_passer], # buggy on isat random\n b'OUGNO2' : [self._table_passer, self._table_passer], # buggy on isat random\n #b'OUGRMS2' : [self._read_oug2_3, self._read_oug_rms], # buggy on isat random\n #b'OUGNO2' : [self._read_oug2_3, self._read_oug_no], # buggy on isat random\n\n #=======================\n # extreme values of the respective table\n b'OUGV1MX' : [self._table_passer, self._table_passer],\n b'OEF1MX' : [self._table_passer, self._table_passer],\n b'OES1MX' : [self._table_passer, self._table_passer],\n\n #=======================\n # contact\n b'OQGCF1' : [self._read_oqg1_3, self._read_oqg_4], # Contact force at grid point.\n b'OQGCF2' : [self._read_oqg2_3, self._read_oqg_4], # Contact force at grid point.\n\n b'OSPDS1' : [self._nx_table_passer, self._table_passer], # Final separation distance.\n b'OSPDS2' : [self._nx_table_passer, self._table_passer],\n\n b'OSPDSI1' : [self._nx_table_passer, self._table_passer], # Initial separation distance.\n b'OSPDSI2' : [self._nx_table_passer, self._table_passer], # Output contact separation distance results.\n\n #b'OBC1' : [self._read_obc1_3, self._read_obc1_4],\n #b'OBC2' : [self._nx_table_passer, self._table_passer], # Contact pressures and tractions at grid points.\n\n #b'OSLIDE1'\n b'OPRPSD2' : [self._nx_table_passer, self._table_passer],\n b'OPRATO2' : [self._nx_table_passer, self._table_passer],\n b'OPRNO1' : [self._nx_table_passer, self._table_passer],\n b'OPRCRM2' : [self._nx_table_passer, self._table_passer],\n\n b'OCPSDFC' : [self._nx_table_passer, self._table_passer],\n b'OCCORFC' : [self._nx_table_passer, self._table_passer],\n\n # Glue normal and tangential tractions at grid point in basic coordinate system\n b'OBG1' : [self._nx_table_passer, self._table_passer],\n b'OBG2' : [self._nx_table_passer, self._table_passer],\n\n b'OQGGF1' : [self._read_oqg1_3, self._read_oqg_4], # Glue forces at grid point in basic coordinate system\n b'OQGGF2' : [self._read_oqg2_3, self._read_oqg_4],\n\n # Table of Euler Angles for transformation from material to basic coordinate system\n # in the undeformed configuration\n b'TRMBU' : [self._nx_table_passer, self._table_passer],\n b'TRMBD' : [self._nx_table_passer, self._table_passer],\n #=======================\n # OGPWG\n # grid point weight\n b'OGPWG' : [self._read_ogpwg_3, self._read_ogpwg_4], # grid point weight\n b'OGPWGM' : [self._read_ogpwg_3, self._read_ogpwg_4], # modal? grid point weight\n\n #=======================\n # OGS\n # grid point stresses\n b'OGS1' : [self._read_ogs1_3, self._read_ogs1_4], # grid point stresses\n #b'OGS2' : [self._read_ogs1_3, self._read_ogs1_4], # grid point stresses\n #=======================\n # eigenvalues\n b'BLAMA' : [self._read_buckling_eigenvalue_3, self._read_buckling_eigenvalue_4], # buckling eigenvalues\n b'CLAMA' : [self._read_complex_eigenvalue_3, self._read_complex_eigenvalue_4], # complex eigenvalues\n b'LAMA' : [self._read_real_eigenvalue_3, self._read_real_eigenvalue_4], # eigenvalues\n b'LAMAS' : [self._read_real_eigenvalue_3, self._read_real_eigenvalue_4], # eigenvalues-structure\n b'LAMAF' : [self._read_real_eigenvalue_3, self._read_real_eigenvalue_4], # eigenvalues-fluid\n\n # ===========================geom passers===========================\n # geometry\n b'GEOM1' : [self._table_passer, self._table_passer], # GEOM1-Geometry-related bulk data\n b'GEOM2' : [self._table_passer, self._table_passer], # GEOM2-element connectivity and SPOINT-related data\n b'GEOM3' : [self._table_passer, self._table_passer], # GEOM3-Static and thermal loads\n b'GEOM4' : [self._table_passer, self._table_passer], # GEOM4-constraints, DOF membership entries, MPC, and R-type element data\n\n # superelements\n b'GEOM1S' : [self._table_passer, self._table_passer], # GEOMx + superelement\n b'GEOM2S' : [self._table_passer, self._table_passer],\n b'GEOM3S' : [self._table_passer, self._table_passer],\n b'GEOM4S' : [self._table_passer, self._table_passer],\n\n b'GEOM1VU' : [self._table_passer, self._table_passer],\n b'GEOM2VU' : [self._table_passer, self._table_passer],\n b'BGPDTVU' : [self._table_passer, self._table_passer],\n\n b'GEOM1N' : [self._table_passer, self._table_passer],\n b'GEOM2N' : [self._table_passer, self._table_passer],\n b'GEOM3N' : [self._table_passer, self._table_passer],\n b'GEOM4N' : [self._table_passer, self._table_passer],\n\n b'GEOM1OLD' : [self._table_passer, self._table_passer],\n b'GEOM2OLD' : [self._table_passer, self._table_passer],\n b'GEOM3OLD' : [self._table_passer, self._table_passer],\n b'GEOM4OLD' : [self._table_passer, self._table_passer],\n\n b'EPT' : [self._table_passer, self._table_passer], # elements\n b'EPTS' : [self._table_passer, self._table_passer], # elements - superelements\n b'EPTOLD' : [self._table_passer, self._table_passer],\n\n b'MPT' : [self._table_passer, self._table_passer], # materials\n b'MPTS' : [self._table_passer, self._table_passer], # materials - superelements\n\n b'DYNAMIC' : [self._table_passer, self._table_passer],\n b'DYNAMICS' : [self._table_passer, self._table_passer],\n b'DIT' : [self._table_passer, self._table_passer],\n b'DITS' : [self._table_passer, self._table_passer],\n b'AXIC' : [self._table_passer, self._table_passer],\n # =========================end geom passers=========================\n\n # ===passers===\n #b'EQEXIN': [self._table_passer, self._table_passer],\n #b'EQEXINS': [self._table_passer, self._table_passer],\n\n b'GPDT' : [self._table_passer, self._table_passer], # grid points?\n b'BGPDT' : [self._table_passer, self._table_passer], # basic grid point defintion table\n b'BGPDTS' : [self._table_passer, self._table_passer],\n b'BGPDTOLD' : [self._table_passer, self._table_passer],\n\n b'PVT' : [self._read_pvto_3, self._read_pvto_4], # PVT - Parameter Variable Table\n b'PVTS' : [self._read_pvto_3, self._read_pvto_4], # ???\n b'PVT0' : [self._read_pvto_3, self._read_pvto_4], # user parameter value table\n b'TOLD' : [self._table_passer, self._table_passer],\n b'CASECC' : [self._table_passer, self._table_passer], # case control deck\n\n b'STDISP' : [self._table_passer, self._table_passer], # matrix?\n b'AEDISP' : [self._table_passer, self._table_passer], # matrix?\n #b'TOLB2' : [self._table_passer, self._table_passer], # matrix?\n\n # EDT - element deformation, aerodynamics, p-element, divergence analysis,\n # and iterative solver input (includes SET1 entries)\n b'EDT' : [self._table_passer, self._table_passer],\n b'EDTS' : [self._table_passer, self._table_passer],\n\n b'FOL' : [self._table_passer, self._table_passer],\n b'PERF' : [self._table_passer, self._table_passer],\n b'VIEWTB' : [self._table_passer, self._table_passer], # view elements\n\n # DSCMCOL - Correlation table for normalized design sensitivity coefficient matrix.\n # Output by DSTAP2.\n # DBCOPT - Design optimization history table for\n b'CONTACT' : [self._table_passer, self._table_passer],\n b'CONTACTS' : [self._table_passer, self._table_passer],\n b'OEKE1' : [self._table_passer, self._table_passer],\n #b'DSCMCOL' : [self._table_passer, self._table_passer],\n #b'DBCOPT' : [self._table_passer, self._table_passer],\n #b'FRL0': [self._table_passer, self._table_passer], # frequency response list\n\n #==================================\n # modal participation factors\n # OFMPF2M Table of fluid mode participation factors by normal mode.\n b'OFMPF2M' : [self._read_mpf_3, self._read_mpf_4],\n # OLMPF2M Load mode participation factors by normal mode.\n b'OLMPF2M' : [self._read_mpf_3, self._read_mpf_4],\n # OPMPF2M Panel mode participation factors by normal mode.\n b'OPMPF2M' : [self._read_mpf_3, self._read_mpf_4],\n # OPMPF2M Panel mode participation factors by normal mode.\n b'OSMPF2M' : [self._read_mpf_3, self._read_mpf_4],\n # OGMPF2M Grid mode participation factors by normal mode.\n b'OGPMPF2M' : [self._read_mpf_3, self._read_mpf_4],\n\n #OFMPF2E Table of fluid mode participation factors by excitation frequencies.\n #OSMPF2E Table of structure mode participation factors by excitation frequencies.\n #OPMPF2E Table of panel mode participation factors by excitation frequencies.\n #OLMPF2E Table of load mode participation factors by excitation frequencies.\n #OGMPF2E Table of grid mode participation factors by excitation frequencies.\n\n # velocity\n b'OVGATO1' : [self._read_oug1_3, self._read_oug_ato],\n b'OVGCRM1' : [self._read_oug1_3, self._read_oug_crm],\n b'OVGPSD1' : [self._read_oug1_3, self._read_oug_psd],\n b'OVGRMS1' : [self._read_oug1_3, self._read_oug_rms],\n b'OVGNO1' : [self._read_oug1_3, self._read_oug_no],\n\n b'OVGATO2' : [self._read_oug2_3, self._read_oug_ato],\n b'OVGCRM2' : [self._read_oug2_3, self._read_oug_crm],\n b'OVGPSD2' : [self._read_oug2_3, self._read_oug_psd],\n #b'OVGRMS2' : [self._table_passer, self._table_passer],\n #b'OVGNO2' : [self._table_passer, self._table_passer],\n b'OVGRMS2' : [self._read_oug2_3, self._read_oug_rms],\n b'OVGNO2' : [self._read_oug2_3, self._read_oug_no],\n\n #==================================\n #b'GPL': [self._table_passer, self._table_passer],\n #b'OMM2' : [self._table_passer, self._table_passer], # max/min table - kinda useless\n b'ERRORN' : [self._table_passer, self._table_passer], # p-element error summary table\n #==================================\n\n b'EDOM' : [self._table_passer, self._table_passer],\n b'OUG2T' : [self._table_passer, self._table_passer],\n\n # acceleration\n b'OAGATO1' : [self._read_oug1_3, self._read_oug_ato],\n b'OAGCRM1' : [self._read_oug1_3, self._read_oug_crm],\n b'OAGPSD1' : [self._read_oug1_3, self._read_oug_psd],\n b'OAGRMS1' : [self._read_oug1_3, self._read_oug_rms],\n b'OAGNO1' : [self._read_oug1_3, self._read_oug_no],\n\n b'OAGATO2' : [self._read_oug2_3, self._read_oug_ato],\n b'OAGCRM2' : [self._read_oug2_3, self._read_oug_crm],\n b'OAGPSD2' : [self._read_oug2_3, self._read_oug_psd],\n #b'OAGRMS2' : [self._table_passer, self._table_passer],\n #b'OAGNO2' : [self._table_passer, self._table_passer],\n b'OAGRMS2' : [self._read_oug2_3, self._read_oug_rms],\n b'OAGNO2' : [self._read_oug2_3, self._read_oug_no],\n\n # stress\n b'OESATO1' : [self._read_oes1_3, self._read_oes1_4],\n b'OESCRM1' : [self._read_oes1_3, self._read_oes1_4],\n b'OESPSD1' : [self._read_oes1_3, self._read_oes1_4],\n b'OESRMS1' : [self._read_oes1_3, self._read_oes1_4],\n b'OESNO1' : [self._read_oes1_3, self._read_oes1_4],\n\n # OESXRM1C : Composite element RMS stresses in SORT1 format for random analysis that includes von Mises stress output.\n b'OESXRMS1' : [self._read_oes1_3, self._read_oes1_4],\n b'OESXRM1C' : [self._read_oes1_3, self._read_oes1_4],\n b'OESXNO1' : [self._read_oes1_3, self._read_oes1_4],\n b'OESXNO1C' : [self._read_oes1_3, self._read_oes1_4],\n\n\n b'OESATO2' : [self._read_oes2_3, self._read_oes2_4],\n b'OESCRM2' : [self._read_oes2_3, self._read_oes2_4],\n b'OESPSD2' : [self._read_oes2_3, self._read_oes2_4],\n #b'OESRMS2' : [self._read_oes1_3, self._read_oes1_4], # buggy on isat random\n #b'OESNO2' : [self._read_oes1_3, self._read_oes1_4], # buggy on isat random\n b'OESRMS2' : [self._table_passer, self._table_passer], # buggy on isat random\n b'OESNO2' : [self._table_passer, self._table_passer], # buggy on isat random\n\n # force\n b'OEFATO1' : [self._read_oef1_3, self._read_oef1_4],\n b'OEFCRM1' : [self._read_oef1_3, self._read_oef1_4],\n b'OEFPSD1' : [self._read_oef1_3, self._read_oef1_4],\n b'OEFRMS1' : [self._read_oef1_3, self._read_oef1_4],\n b'OEFNO1' : [self._read_oef1_3, self._read_oef1_4],\n\n b'OEFATO2' : [self._read_oef2_3, self._read_oef2_4],\n b'OEFCRM2' : [self._read_oef2_3, self._read_oef2_4],\n b'OEFPSD2' : [self._read_oef2_3, self._read_oef2_4],\n #b'OEFRMS2' : [self._read_oef2_3, self._read_oef2_4], # buggy on isat random\n }\n if self.is_nx and 0:\n table_mapper2 = {\n #b'OUGRMS2' : [self._table_passer, self._table_passer], # buggy on isat random\n #b'OUGNO2' : [self._table_passer, self._table_passer], # buggy on isat random\n b'OUGRMS2' : [self._read_oug2_3, self._read_oug_rms], # buggy on isat random\n b'OUGNO2' : [self._read_oug2_3, self._read_oug_no], # buggy on isat random\n\n #b'OQMRMS2' : [self._table_passer, self._table_passer], # buggy on isat random\n #b'OQMNO2' : [self._table_passer, self._table_passer], # buggy on isat random\n b'OQMRMS2' : [self._read_oqg2_3, self._read_oqg_mpc_rms], # buggy on isat random\n b'OQMNO2' : [self._read_oqg2_3, self._read_oqg_mpc_no], # buggy on isat random\n\n #b'OSTRRMS2' : [self._table_passer, self._table_passer], # buggy on isat random\n #b'OSTRNO2' : [self._table_passer, self._table_passer], # buggy on isat random\n b'OSTRRMS2' : [self._read_oes2_3, self._read_ostr2_4], # buggy on isat random\n b'OSTRNO2' : [self._read_oes2_3, self._read_ostr2_4], # buggy on isat random\n\n b'OESRMS2' : [self._read_oes1_3, self._read_oes1_4], # buggy on isat random\n b'OESNO2' : [self._read_oes1_3, self._read_oes1_4], # buggy on isat random\n #b'OESRMS2' : [self._table_passer, self._table_passer], # buggy on isat random\n #b'OESNO2' : [self._table_passer, self._table_passer], # buggy on isat random\n\n b'OEFNO2' : [self._read_oef2_3, self._read_oef2_4],\n #b'OEFNO2' : [self._table_passer, self._table_passer], # buggy on isat_random_steve2.op2\n }\n for key, value in table_mapper2.items():\n table_mapper[key] = value\n #table_mapper.update(table_mapper2)\n return table_mapper\n\n def _read_mpf_3(self, data, ndata: int) -> int:\n \"\"\"reads table 3 (the header table)\n\n OFMPF2E Table of fluid mode participation factors by excitation frequencies.\n OFMPF2M Table of fluid mode participation factors by normal mode.\n OSMPF2E Table of structure mode participation factors by excitation frequencies.\n OSMPF2M Table of structure mode participation factors by normal mode.\n OPMPF2E Table of panel mode participation factors by excitation frequencies.\n OPMPF2M Table of panel mode participation factors by normal mode.\n OLMPF2E Table of load mode participation factors by excitation frequencies.\n OLMPF2M Table of load mode participation factors by normal mode.\n OGMPF2E Table of grid mode participation factors by excitation frequencies.\n OGMPF2M Table of grid mode participation factors by normal mode.\n \"\"\"\n #self._set_times_dtype()\n self.nonlinear_factor = np.nan\n self.is_table_1 = True\n self.is_table_2 = False\n unused_three = self.parse_approach_code(data)\n self.words = [\n 'approach_code', 'table_code', '???', 'isubcase',\n '???', '???', '???', 'random_code',\n 'format_code', 'num_wide', '???', '???',\n 'acoustic_flag', '???', '???', '???',\n '???', '???', '???', '???',\n '???', '???', 'thermal', '???',\n '???', 'Title', 'subtitle', 'label']\n\n ## random code\n self.random_code = self.add_data_parameter(data, 'random_code', b'i', 8, False)\n\n ## format code\n self.format_code = self.add_data_parameter(data, 'format_code', b'i', 9, False)\n\n ## number of words per entry in record\n self.num_wide = self.add_data_parameter(data, 'num_wide', b'i', 10, False)\n\n ## acoustic pressure flag\n self.acoustic_flag = self.add_data_parameter(data, 'acoustic_flag', b'i', 13, False)\n\n ## thermal flag; 1 for heat transfer, 0 otherwise\n self.thermal = self.add_data_parameter(data, 'thermal', b'i', 23, False)\n\n #if self.analysis_code == 1: # statics / displacement / heat flux\n ## load set number\n #self.lsdvmn = self.add_data_parameter(data, 'lsdvmn', b'i', 5, False)\n #self.data_names = self.apply_data_code_value('data_names', ['lsdvmn'])\n #self.setNullNonlinearFactor()\n #elif self.analysis_code == 2: # real eigenvalues\n ## mode number\n #self.mode = self.add_data_parameter(data, 'mode', b'i', 5)\n ## eigenvalue\n #self.eign = self.add_data_parameter(data, 'eign', b'f', 6, False)\n ## mode or cycle .. todo:: confused on the type - F1???\n #self.mode_cycle = self.add_data_parameter(data, 'mode_cycle', b'i', 7, False)\n #self.update_mode_cycle('mode_cycle')\n #self.data_names = self.apply_data_code_value('data_names', ['mode', 'eign', 'mode_cycle'])\n #elif self.analysis_code == 3: # differential stiffness\n #self.lsdvmn = self.get_values(data, b'i', 5) ## load set number\n #self.data_code['lsdvmn'] = self.lsdvmn\n #elif self.analysis_code == 4: # differential stiffness\n #self.lsdvmn = self.get_values(data, b'i', 5) ## load set number\n if self.analysis_code == 5: # frequency\n # frequency\n self.node_id = self.add_data_parameter(data, 'node_id', b'i', 5, fix_device_code=True)\n self.data_names = self.apply_data_code_value('data_names', ['node_id'])\n #self.freq = self.add_data_parameter(data, 'freq', b'f', 5)\n #self.data_names = self.apply_data_code_value('data_names', ['freq'])\n #elif self.analysis_code == 6: # transient\n ## time step\n #self.dt = self.add_data_parameter(data, 'dt', b'f', 5)\n #self.data_names = self.apply_data_code_value('data_names', ['dt'])\n #elif self.analysis_code == 7: # pre-buckling\n ## load set number\n #self.lsdvmn = self.add_data_parameter(data, 'lsdvmn', b'i', 5)\n #self.data_names = self.apply_data_code_value('data_names', ['lsdvmn'])\n #elif self.analysis_code == 8: # post-buckling\n ## load set number\n #self.lsdvmn = self.add_data_parameter(data, 'lsdvmn', b'i', 5)\n ## real eigenvalue\n #self.eigr = self.add_data_parameter(data, 'eigr', b'f', 6, False)\n #self.data_names = self.apply_data_code_value('data_names', ['lsdvmn', 'eigr'])\n #elif self.analysis_code == 9: # complex eigenvalues\n ## mode number\n #self.mode = self.add_data_parameter(data, 'mode', b'i', 5)\n ## real eigenvalue\n #self.eigr = self.add_data_parameter(data, 'eigr', b'f', 6, False)\n ## imaginary eigenvalue\n #self.eigi = self.add_data_parameter(data, 'eigi', b'f', 7, False)\n #self.data_names = self.apply_data_code_value('data_names', ['mode', 'eigr', 'eigi'])\n #elif self.analysis_code == 10: # nonlinear statics\n ## load step\n #self.lftsfq = self.add_data_parameter(data, 'lftsfq', b'f', 5)\n #self.data_names = self.apply_data_code_value('data_names', ['lftsfq'])\n #elif self.analysis_code == 11: # old geometric nonlinear statics\n ## load set number\n #self.lsdvmn = self.add_data_parameter(data, 'lsdvmn', b'i', 5)\n #self.data_names = self.apply_data_code_value('data_names', ['lsdvmn'])\n #elif self.analysis_code == 12: # contran ? (may appear as aCode=6) --> straight from DMAP...grrr...\n ## load set number\n #self.lsdvmn = self.add_data_parameter(data, 'lsdvmn', b'i', 5)\n #self.data_names = self.apply_data_code_value('data_names', ['lsdvmn'])\n else:\n msg = f'invalid analysis_code...analysis_code={self.analysis_code}\\ndata={self.data_code}'\n raise RuntimeError(msg)\n\n #print self.code_information()\n #\n self.fix_format_code()\n if self.num_wide == 8:\n self.format_code = 1\n self.data_code['format_code'] = 1\n else:\n #self.fix_format_code()\n if self.format_code == 1:\n self.format_code = 2\n self.data_code['format_code'] = 2\n assert self.format_code in [2, 3], self.code_information()\n\n self._parse_thermal_code()\n if self.is_debug_file:\n self.binary_debug.write(' approach_code = %r\\n' % self.approach_code)\n self.binary_debug.write(' tCode = %r\\n' % self.tCode)\n self.binary_debug.write(' isubcase = %r\\n' % self.isubcase)\n self._read_title(data)\n self._write_debug_bits()\n\n def _read_mpf_4(self, data, ndata):\n \"\"\"unused\"\"\"\n if self.read_mode == 1: # or self.table_name_str not in ['OFMPF2M']:\n return ndata\n #print(self.table_name_str, ndata, self.num_wide) # 176\n #self.show_ndata(100, types='ifs')\n\n structi = Struct('fiff')\n nelements = ndata // 16\n ndev = ndata % 16\n assert ndev == 0, ndev\n\n for i in range(nelements):\n datai = data[i*16 : (i+1)*16]\n freq, dunno_int, mag, phase = structi.unpack(datai)\n assert dunno_int == 2, str(self.node_id, freq, dunno_int, mag, phase)\n #print(self.node_id, freq, dunno_int, mag, phase)\n #print()\n if self.isubtable == -4:\n self.log.warning('%s results were read, but not saved' % self.table_name_str)\n return ndata\n\n def _read_pvto_3(self, data, ndata):\n \"\"\"unused\"\"\"\n raise RuntimeError(self.read_mode)\n\n def _read_pvto_4(self, data, ndata):\n \"\"\"reads PARAM cards\"\"\"\n if self.read_mode == 2:\n return ndata\n\n iloc = self.f.tell()\n try:\n ndata2 = self._read_pvto_4_helper(data, ndata)\n except NotImplementedError as e:\n self.log.error(str(e))\n #raise # only for testing\n if 'dev' in __version__ and self.IS_TESTING:\n raise # only for testing\n self.f.seek(iloc)\n ndata2 = ndata\n if 'NXVER' in self.params and not self.is_nx:\n self.set_as_nx()\n self.log.debug('found PARAM,NXVER -> setting as NX')\n return ndata2\n\n def _read_pvto_4_helper(self, data, ndata: int) -> int:\n \"\"\"reads PARAM cards\"\"\"\n xword = (4 * self.factor)\n nvalues = ndata // xword\n assert ndata % xword == 0, ndata\n\n if self.size == 4:\n structs8 = self.struct_8s\n #struct2s8 = Struct(b'4s8s')\n struct2i = self.struct_2i\n struct2f = Struct(b'ff')\n struct2d = Struct(b'dd')\n else:\n struct2i = self.struct_2q\n structs8 = self.struct_16s\n struct2f = Struct(b'dd')\n\n i = 0\n\n #print('---------------------------')\n #self.show_data(data, types='ifsqL')\n while i < nvalues:\n #print('-----------------------------------------------------------')\n #print('*i=%s nvalues=%s' % (i, nvalues))\n istart = i*xword\n #self.show_data(data[istart:istart+32], types='sqd')\n #self.show_data(data[istart:istart+64], types='sqd')\n if self.size == 4:\n word = data[istart:(i+2)*xword].rstrip()\n elif self.size == 8:\n bword = data[istart:(i+2)*xword]\n word = reshape_bytes_block(bword).rstrip()\n else:\n raise RuntimeError(self.size)\n\n #print('word=%r' % word)\n #word = s8.unpack(word)[0]#.decode(self._encoding)\n\n # the first two entries are typically trash, then we can get values\n if word in INT_PARAMS_1:\n slot = data[(i+2)*xword:(i+4)*xword]\n value = struct2i.unpack(slot)[1]\n i += 4\n elif word in FLOAT_PARAMS_1:\n slot = data[(i+2)*xword:(i+4)*xword]\n value = struct2f.unpack(slot)[1]\n i += 4\n elif word in FLOAT_PARAMS_2:\n slot = data[(i+3)*xword:(i+5)*xword]\n value = struct2f.unpack(slot)\n i += 5\n elif word in INT_PARAMS_2:\n slot = data[(i+3)*xword:(i+5)*xword]\n value = struct2i.unpack(slot)\n i += 5\n elif word in DOUBLE_PARAMS_1:\n slot = data[(i+1)*xword:(i+8)*xword]\n try:\n value = struct2d.unpack(slot)[1]\n except:\n print(word)\n raise\n i += 8\n #elif word in [b'VUHEXA']:\n #self.show_data(data[i*4:(i+5)*4], types='ifs', endian=None)\n #aaa\n elif word in STR_PARAMS_1:\n i += 3\n slot = data[i*xword:(i+2)*xword]\n bvalue = structs8.unpack(slot)[0]\n if self.size == 8:\n bvalue = reshape_bytes_block(bvalue)\n value = bvalue.decode('latin1').rstrip()\n i += 2\n else:\n if self.size == 4:\n self.show_data(data[i*xword+12:i*4+i*4+12], types='ifs')\n self.show_data(data[i*xword+8:(i+4)*4], types='ifs')\n else:\n self.show_data(data[i*xword+24:i*8+i*8+24], types='sdq')\n self.show_data(data[i*xword+16:(i+4)*8], types='sdq')\n #print(i*xword+24, i*8+i*8+24)\n #print(i*xword+16, (i+4)*8)\n self.log.error('%r' % word)\n raise NotImplementedError('%r is not a supported PARAM' % word)\n\n key = word.decode('latin1')\n param = PARAM(key, [value], comment='')\n self.params[key] = param\n #print(f'{key} = {value}')\n #print(param.rstrip())\n return nvalues\n\n def _not_available(self, data: bytes, ndata: int):\n \"\"\"testing function\"\"\"\n if ndata > 0:\n raise RuntimeError('this should never be called...'\n 'table_name=%r len(data)=%s' % (self.table_name, ndata))\n\n def _table_crasher(self, data, ndata):\n \"\"\"auto-table crasher\"\"\"\n if self.is_debug_file:\n self.binary_debug.write(' crashing table = %s\\n' % self.table_name)\n raise NotImplementedError(self.table_name)\n return ndata\n\n def _nx_table_passer(self, data, ndata: int):\n \"\"\"auto-table skipper\"\"\"\n self.to_nx()\n self._table_passer(data, ndata)\n\n def _table_passer(self, data, ndata: int):\n \"\"\"auto-table skipper\"\"\"\n if self.is_debug_file:\n self.binary_debug.write(' skipping table = %s\\n' % self.table_name)\n if self.table_name not in GEOM_TABLES and self.isubtable > -4:\n self.log.warning(' skipping table: %s' % self.table_name_str)\n if not is_release and self.isubtable > -4:\n if self.table_name in GEOM_TABLES and not self.make_geom:\n pass\n else:\n print('dont skip table %r' % self.table_name_str)\n raise RuntimeError('dont skip table %r' % self.table_name_str)\n return ndata\n\n def _validate_op2_filename(self, op2_filename):\n \"\"\"\n Pops a GUI if the op2_filename hasn't been set.\n\n Parameters\n ----------\n op2_filename : str\n the filename to check (None -> gui)\n\n Returns\n -------\n op2_filename : str\n a valid file string\n\n \"\"\"\n if op2_filename is None:\n from pyNastran.utils.gui_io import load_file_dialog\n wildcard_wx = \"Nastran OP2 (*.op2)|*.op2|\" \\\n \"All files (*.*)|*.*\"\n wildcard_qt = \"Nastran OP2 (*.op2);;All files (*)\"\n title = 'Please select a OP2 to load'\n op2_filename, unused_wildcard_level = load_file_dialog(\n title, wildcard_wx, wildcard_qt, dirname='')\n assert op2_filename is not None, op2_filename\n return op2_filename\n\n def _create_binary_debug(self):\n \"\"\"Instatiates the ``self.binary_debug`` variable/file\"\"\"\n if hasattr(self, 'binary_debug') and self.binary_debug is not None:\n self.binary_debug.close()\n del self.binary_debug\n\n self.is_debug_file, self.binary_debug = create_binary_debug(\n self.op2_filename, self.debug_file, self.log)\n\n def read_op2(self, op2_filename=None, combine=False, load_as_h5=False, h5_file=None, mode=None):\n \"\"\"\n Starts the OP2 file reading\n\n Parameters\n ----------\n op2_filename : str\n the op2 file\n combine : bool; default=True\n True : objects are isubcase based\n False : objects are (isubcase, subtitle) based;\n will be used for superelements regardless of the option\n load_as_h5 : default=None\n False : don't setup the h5_file\n True : loads the op2 as an h5 file to save memory\n stores the result.element/data attributes in h5 format\n h5_file : h5File; default=None\n None : ???\n h5File : ???\n\n +--------------+-----------------------+\n | op2_filename | Description |\n +--------------+-----------------------+\n | None | a dialog is popped up |\n +--------------+-----------------------+\n | string | the path is used |\n +--------------+-----------------------+\n \"\"\"\n fname = os.path.splitext(op2_filename)[0]\n self.op2_filename = op2_filename\n self.bdf_filename = fname + '.bdf'\n self.f06_filename = fname + '.f06'\n self.des_filename = fname + '.des'\n self.h5_filename = fname + '.h5'\n\n self.op2_reader.load_as_h5 = load_as_h5\n if load_as_h5:\n h5_file = None\n import h5py\n self.h5_file = h5py.File(self.h5_filename, 'w')\n self.op2_reader.h5_file = self.h5_file\n\n self._count = 0\n if self.read_mode == 1:\n #sr = list(self._results.saved)\n #sr.sort()\n #self.log.debug('_results.saved = %s' % str(sr))\n #self.log.info('_results.saved = %s' % str(sr))\n pass\n\n if self.read_mode != 2:\n op2_filename = self._validate_op2_filename(op2_filename)\n self.log.info('op2_filename = %r' % op2_filename)\n if not is_binary_file(op2_filename):\n if os.path.getsize(op2_filename) == 0:\n raise IOError('op2_filename=%r is empty.' % op2_filename)\n raise IOError('op2_filename=%r is not a binary OP2.' % op2_filename)\n\n self._create_binary_debug()\n self._setup_op2()\n _op2 = self.op2_reader.op2\n #is_nasa_nastran = False\n #if is_nasa_nastran:\n #self.show(104, types='ifs', endian=None)\n #self.show(52, types='ifs', endian=None)\n #aa\n #data = _op2.f.read(4)\n #_op2.n += 8\n #_op2.f.seek(_op2.n)\n #else:\n self.op2_reader.read_nastran_version(mode)\n data = _op2.f.read(4)\n _op2.f.seek(_op2.n)\n if len(data) == 0:\n raise FatalError('There was a Nastran FATAL Error. Check the F06.\\n'\n 'No tables exist...check for a license issue')\n\n #=================\n table_name = self.op2_reader._read_table_name(rewind=True, stop_on_failure=False)\n if table_name is None:\n raise FatalError('There was a Nastran FATAL Error. Check the F06.\\n'\n 'No tables exist...check for a license issue')\n\n self._make_tables()\n table_names = self._read_tables(table_name)\n\n self.close_op2(force=False)\n #self.remove_unpickable_data()\n return table_names\n\n def close_op2(self, force=True):\n \"\"\"closes the OP2 and debug file\"\"\"\n if self.is_debug_file:\n self.binary_debug.write('-' * 80 + '\\n')\n self.binary_debug.write('f.tell()=%s\\ndone...\\n' % self.f.tell())\n self.binary_debug.close()\n\n if self._close_op2 or force:\n if self.f is not None:\n # can happen if:\n # - is ascii file\n self.f.close()\n del self.binary_debug\n del self.f\n self._cleanup_data_members()\n self._cleanup_words()\n #self.op2_reader.h5_file.close()\n\n def _cleanup_words(self):\n \"\"\"\n Remove internal parameters that are not useful and just clutter\n the object attributes.\n \"\"\"\n words = [\n 'isubcase', 'int3', '_table4_count', 'nonlinear_factor',\n 'is_start_of_subtable', 'superelement_adaptivity_index',\n 'thermal_bits', 'is_vectorized', 'pval_step', #'_frequencies',\n '_analysis_code_fmt', 'isubtable', '_data_factor', 'sort_method',\n 'acoustic_flag', 'approach_code', 'format_code_original',\n 'element_name', 'sort_bits', 'code', 'n', 'use_vector', 'ask',\n 'stress_bits', 'expected_times', 'table_code', 'sort_code',\n 'is_all_subcases', 'num_wide', '_table_mapper', 'label',\n 'apply_symmetry',\n 'words', 'device_code', 'table_name', '_count', 'additional_matrices',\n # 350\n 'data_names', '_close_op2',\n 'op2_reader',\n # 74\n 'generalized_tables',\n # 124\n 'is_table_1', 'is_table_2', 'ntotal', 'element_mapper',\n 'is_debug_file', 'debug_file',\n '_results', 'skip_undefined_matrices',\n # 140\n #---------------------------------------------------------\n # dont remove...\n # make_geom, title, read_mode\n # result_names, op2_results\n\n ]\n for word in words:\n if hasattr(self, word):\n delattr(self, word)\n\n def _setup_op2(self):\n \"\"\"\n Does preliminary op2 tasks like:\n - open the file\n - set the endian\n - preallocate some struct objects\n\n \"\"\"\n #: file index\n self.n = 0\n self.table_name = None\n\n if not hasattr(self, 'f') or self.f is None:\n #: the OP2 file object\n self.f = open(self.op2_filename, 'rb')\n #: the endian in bytes\n self._endian = None\n #: the endian in unicode\n self._uendian = None\n flag_data = self.f.read(20)\n self.f.seek(0)\n\n #(8, 3, 0, 8, 24)\n little_data = unpack(b'<5i', flag_data)\n big_data = unpack(b'>5i', flag_data)\n if big_data[0] in [4, 8]:\n self._uendian = '>'\n self._endian = b'>'\n size = big_data[0]\n elif little_data[0] in [4, 8] or 1:\n self._uendian = '<'\n self._endian = b'<'\n size = little_data[0]\n #elif unpack(b'<ii', flag_data)[0] == 4:\n #self._endian = b'<'\n else:\n # Matrices from test show\n # (24, 10, 10, 6, 2) before the Matrix Name...\n print(little_data, big_data)\n self.show(30, types='ifs', endian='<')\n self.show(30, types='ifs', endian='>')\n self.show(12, types='ifs', endian='<')\n self.show(12, types='ifs', endian='>')\n #self.show_data(flag_data, types='iqlfsld', endian='<')\n #print('----------')\n #self.show_data(flag_data, types='iqlfsld', endian='>')\n raise FatalError('cannot determine endian')\n else:\n self.op2_reader._goto(self.n)\n\n if self.read_mode == 1:\n self._set_structs(size)\n\n def _make_tables(self):\n return\n #global RESULT_TABLES, NX_RESULT_TABLES, MSC_RESULT_TABLES\n #table_mapper = self._get_table_mapper()\n #RESULT_TABLES = table_mapper.keys()\n\n def _read_tables(self, table_name: bytes) -> List[bytes]:\n \"\"\"\n Reads all the geometry/result tables.\n The OP2 header is not read by this function.\n\n Parameters\n ----------\n table_name : bytes str\n the first table's name\n\n Returns\n -------\n table_names : List[bytes str]\n the table names that were read\n\n \"\"\"\n op2_reader = self.op2_reader\n table_names = []\n self.table_count = defaultdict(int)\n while table_name is not None:\n self.table_count[table_name] += 1\n table_names.append(table_name)\n\n if self.is_debug_file:\n self.binary_debug.write('-' * 80 + '\\n')\n self.binary_debug.write('table_name = %r\\n' % (table_name))\n\n if is_release:\n self.log.debug(' table_name=%r' % table_name)\n\n self.table_name = table_name\n #if 0:\n #op2_reader._skip_table(table_name)\n #else:\n #print(table_name, table_name in op2_reader.mapped_tables)\n if table_name in self.generalized_tables:\n t0 = self.f.tell()\n self.generalized_tables[table_name](self)\n assert self.f.tell() != t0, 'the position was unchanged...'\n elif table_name in op2_reader.mapped_tables:\n t0 = self.f.tell()\n op2_reader.mapped_tables[table_name]()\n assert self.f.tell() != t0, 'the position was unchanged...'\n elif table_name in GEOM_TABLES:\n op2_reader.read_geom_table() # DIT (agard)\n elif table_name in MATRIX_TABLES:\n op2_reader.read_matrix(table_name)\n elif table_name in RESULT_TABLES:\n op2_reader.read_results_table()\n elif self.skip_undefined_matrices:\n op2_reader.read_matrix(table_name)\n elif table_name.strip() in self.additional_matrices:\n op2_reader.read_matrix(table_name)\n else:\n #self.show(1000, types='ifsq')\n msg = (\n 'Invalid Table = %r\\n\\n'\n 'If you have matrices that you want to read, see:\\n'\n ' model.set_additional_matrices_to_read(matrices)'\n ' matrices = {\\n'\n \" b'BHH' : True,\\n\"\n \" b'KHH' : False,\\n\"\n ' } # you want to read some matrices, but not others\\n'\n \" matrices = [b'BHH', b'KHH'] # assumes True\\n\\n\"\n\n 'If you the table is a geom/result table, see:\\n'\n ' model.set_additional_result_tables_to_read(methods_dict)\\n'\n \" methods_dict = {\\n\"\n \" b'OUGV1' : [method3, method4],\\n\"\n \" b'GEOM4SX' : [method3, method4],\\n\"\n \" b'OES1X1' : False,\\n\"\n ' }\\n\\n'\n\n 'If you want to take control of the OP2 reader (mainly useful '\n 'for obscure tables), see:\\n'\n \" methods_dict = {\\n\"\n \" b'OUGV1' : [method],\\n\"\n ' }\\n'\n ' model.set_additional_generalized_tables_to_read(methods_dict)\\n' % (\n table_name)\n )\n raise NotImplementedError(msg)\n\n table_name = op2_reader._read_table_name(last_table_name=table_name,\n rewind=True, stop_on_failure=False)\n return table_names\n\n def set_additional_generalized_tables_to_read(self, tables):\n \"\"\"\n Adds methods to call a generalized table.\n Everything is left to the user.\n\n ::\n\n def read_some_table(self):\n # read the data from self.f\n pass\n\n # let's overwrite the existing OP2 table\n model2 = OP2Geom(debug=True)\n generalized_tables = {\n b'GEOM1S' : read_some_table,\n }\n\n model.set_additional_generalized_tables_to_read(generalized_tables)\n\n \"\"\"\n self._update_generalized_tables(tables)\n self.generalized_tables = tables\n\n def set_additional_result_tables_to_read(self, tables):\n \"\"\"\n Adds methods to read additional result tables.\n This is expected to really only be used for skipping\n unsupported tables or disabling enabled tables that are\n buggy (e.g., OUGV1).\n\n Parameters\n ----------\n tables : Dict[bytes] = varies\n a dictionary of key=name, value=list[method3, method4]/False,\n False : skips a table\n applies self._table_passer to method3 and method4\n method3 : function\n function to read table 3 results (e.g., metadata)\n method4 : function\n function to read table 4 results (e.g., the actual results)\n\n \"\"\"\n self._update_generalized_tables(tables)\n table_mapper = self._get_table_mapper()\n #is_added = False\n def func():\n \"\"\"overloaded version of _get_table_mapper\"\"\"\n #if is_added:\n #return table_mapper\n for _key, methods in tables.items():\n if methods is False:\n table_mapper[_key] = [self._table_passer, self._table_passer]\n else:\n assert len(methods) == 2, methods\n table_mapper[_key] = methods\n #is_added = True\n return table_mapper\n self._get_table_mapper = func\n\n def _update_generalized_tables(self, tables):\n \"\"\"\n helper function for:\n - set_additional_generalized_tables_to_read\n - set_additional_result_tables_to_read\n\n \"\"\"\n global NX_RESULT_TABLES\n global MSC_RESULT_TABLES\n global RESULT_TABLES\n failed_keys = []\n keys = list(tables.keys())\n for _key in keys:\n if not isinstance(_key, bytes):\n failed_keys.append(_key)\n if hasattr(self, 'is_nx') and self.is_nx:\n NX_RESULT_TABLES.append(_key)\n else:\n MSC_RESULT_TABLES.append(_key)\n if failed_keys:\n failed_keys_str = [str(_key) for _key in failed_keys]\n raise TypeError('[%s] must be bytes' % ', '. join(failed_keys_str))\n RESULT_TABLES = NX_RESULT_TABLES + MSC_RESULT_TABLES\n\n #RESULT_TABLES.sort()\n #assert 'OESXRMS1' in RESULT_TABLES, RESULT_TABLES\n\n def set_additional_matrices_to_read(self, matrices: Union[List[str], Dict[str, bool]]):\n \"\"\"\n Matrices (e.g., KHH) can be sparse or dense.\n\n Parameters\n ----------\n matrices : List[str]; Dict[str] = bool\n List[str]:\n simplified method to add matrices; value will be True\n Dict[str] = bool:\n a dictionary of key=name, value=True/False,\n where True/False indicates the matrix should be read\n\n .. note:: If you use an already defined table (e.g. KHH), it\n will be ignored. If the table you requested doesn't\n exist, there will be no effect.\n .. note:: Do not use this for result tables like OUGV1, which\n store results like displacement. Those are not matrices.\n Matrices are things like DMIGs.\n\n \"\"\"\n if isinstance(matrices, list):\n matrices2 = {}\n for matrix in matrices:\n assert isinstance(matrix, str), 'matrix=%r' % str(matrix)\n matrices2[matrix] = True\n matrices = matrices2\n\n self.additional_matrices = matrices\n self.additional_matrices = {}\n for matrix_name, matrix in matrices.items():\n if isinstance(matrix_name, bytes):\n self.additional_matrices[matrix_name] = matrix\n else:\n self.additional_matrices[matrix_name.encode('latin1')] = matrix\n\n def _finish(self):\n \"\"\"\n Clears out the data members contained within the self.words variable.\n This prevents mixups when working on the next table, but otherwise\n has no effect.\n\n \"\"\"\n for word in self.words:\n if word != '???' and hasattr(self, word):\n if word not in ['Title', 'reference_point']:\n delattr(self, word)\n self.obj = None\n if hasattr(self, 'subtable_name'):\n del self.subtable_name\n\n def _read_psdf_3(self, data, ndata):\n \"\"\"reads the PSDF table\"\"\"\n #(50, 2011, 4001, 0, 302130, 3\n # strip off the title\n unused_three = self.parse_approach_code(data)\n self.words = [\n 'approach_code', 'table_code', '???', 'isubcase',\n '???', '???', '???', 'random_code',\n 'format_code', 'num_wide', '???', '???',\n 'acoustic_flag', '???', '???', '???',\n '???', '???', '???', '???',\n '???', '???', 'thermal', '???',\n '???', 'Title', 'subtitle', 'label'\n ]\n\n ## random code\n self.random_code = self.add_data_parameter(data, 'random_code', b'i', 8, False)\n self._read_title(data)\n\n # simplifying to see the data better\n del self.data_code['title']\n del self.data_code['label']\n del self.data_code['subtitle']\n del self.data_code['subtitle_original']\n del self.data_code['superelement_adaptivity_index']\n #del self.data_code['pval_step']\n del self.data_code['table_name']\n\n del self.data_code['_encoding']\n del self.data_code['load_as_h5']\n del self.data_code['h5_file']\n del self.data_code['is_msc']\n #del self.data_code['is_nasa95']\n del self.data_code['pval_step']\n\n # wrong\n del self.data_code['isubcase']\n #del self.data_code['random_code']\n #del self.data_code['sort_bits']\n #del self.data_code['device_code']\n #del self.data_code['sort_code']\n #del self.data_code['sort_method']\n #print(self.data_code)\n\n #aaa\n #self._read_oug1_3(data, ndata)\n if self.read_mode == 1:\n return ndata\n # just stripping off title\n #self.show_data(data[:200], types='if')\n\n # stripping off zeros\n #self.show_data(data[:52], types='ifs')\n\n #self.show_data(data[:40], types='if')\n\n approach_code, tcode, int3, frame_id, int5, dof, float7, rms_value, float9, int10, stress_strain_flag = unpack(\n self._endian + b'6i 3f 2i', data[:44])\n self.stress_strain_flag = stress_strain_flag\n\n ints = np.frombuffer(data[:200], dtype=self.idtype)\n if ints[11:].max() > 0:\n self.log.warning(f'ints11 = {ints[11:].tolist()}')\n\n node = int5 // 10\n #dof = int5 % 10\n #from pyNastran.op2.op2_interface.op2_codes import TABLE_CODE_MAP\n #title = self.title\n #subtitle = self.subtitle\n #label = self.label\n #approach_code={iapproach_code} tcode={tcode} table_code={self.table_code}\n #print(f'analysis_code={self.analysis_code} '\n #print(f'title={title!r} subtitle={subtitle!r} label={label!r}')\n\n if (self.analysis_code, self.table_code, self.stress_strain_flag) == (5, 1, 0):\n word = 'displacements'\n elif (self.analysis_code, self.table_code, self.stress_strain_flag) == (5, 2, 0):\n word = 'load_vectors'\n elif (self.analysis_code, self.table_code, self.stress_strain_flag) == (5, 3, 0):\n word = 'spc_forces'\n elif (self.analysis_code, self.table_code, self.stress_strain_flag) == (5, 4, 0):\n word = 'force'\n\n elif (self.analysis_code, self.table_code, self.stress_strain_flag) == (5, 5, 0):\n word = 'stress'\n elif (self.analysis_code, self.table_code, self.stress_strain_flag) == (5, 5, 2):\n word = 'strain'\n\n elif (self.analysis_code, self.table_code, self.stress_strain_flag) == (5, 10, 0):\n word = 'velocities'\n elif (self.analysis_code, self.table_code, self.stress_strain_flag) == (5, 11, 0):\n word = 'accelerations'\n else: # pragma: no cover\n #print(f'table_code={self.table_code} table={TABLE_CODE_MAP[self.table_code]!r}')\n print(f'analysis_code={self.analysis_code} approach_code={approach_code} tcode={tcode} table_code={self.table_code} '\n f'int3={int3} frame_id={frame_id} node={node} dof={dof} '\n f'float7={float7} rms_value={rms_value:.5e} float9={float9:.4e} int10={int10} stress_strain_flag={stress_strain_flag}')\n raise NotImplementedError(f'analysis_code={self.analysis_code} '\n f'table_code={self.table_code} '\n f'stress_strain_flag={self.stress_strain_flag} is not supported')\n\n self.node = node\n self.dof = dof\n self.word = word\n return ndata\n #self.show_data(data, types='ifs', endian=None)\n #aaaa\n\n def _read_psdf_4(self, data, ndata):\n \"\"\"reads the PSDF table\"\"\"\n if self.read_mode == 1:\n return ndata\n #self.show_data(data[:100], types='ifs', endian=None)\n data2 = np.frombuffer(data, dtype=self.fdtype)\n ndata = len(data2)\n nfreqs = ndata // 2\n data2 = data2.reshape(nfreqs, 2)\n #last2 = data2[-2:, 1]\n #self.log.warning(f'skipping PSDF; nfreqs={nfreqs} [{last2[0]:.6e},{last2[1]:.6e}] '\n #f'ymin={data2[:,1].min():.6e} ymax={data2[:,1].max():.6e}') # {self.data_code}\n # self.show_data(), self._read_psdf_4\n key = (self.label, self.node, self.dof)\n slot = getattr(self.op2_results.psds, self.word)\n assert key not in slot, slot\n slot[key] = data2\n del self.node\n del self.dof\n del self.word\n\ndef main(): # pragma: no cover\n \"\"\"testing pickling\"\"\"\n from pickle import dump, load\n txt_filename = 'solid_shell_bar.txt'\n pickle_file = open(txt_filename, 'wb')\n op2_filename = 'solid_shell_bar.op2'\n op2 = OP2_Scalar()\n op2.read_op2(op2_filename)\n #print(op2.displacements[1])\n dump(op2, pickle_file)\n pickle_file.close()\n\n pickle_file = open(txt_filename, 'r')\n op2 = load(pickle_file)\n pickle_file.close()\n #print(op2.displacements[1])\n\n\n #import sys\n #op2_filename = sys.argv[1]\n\n #o = OP2_Scalar()\n #o.read_op2(op2_filename)\n #(model, ext) = os.path.splitext(op2_filename)\n #f06_outname = model + '.test_op2.f06'\n #o.write_f06(f06_outname)\n\ndef create_binary_debug(op2_filename: str, debug_file: str, log) -> Tuple[bool, Any]:\n \"\"\"helper method\"\"\"\n binary_debug = None\n\n if debug_file is not None:\n #: an ASCII version of the op2 (creates lots of output)\n log.debug('debug_file = %s' % debug_file)\n binary_debug = open(debug_file, 'w')\n binary_debug.write(op2_filename + '\\n')\n is_debug_file = True\n else:\n is_debug_file = False\n return is_debug_file, binary_debug\n\n\nif __name__ == '__main__': # pragma: no cover\n main()\n"
] | [
[
"numpy.array",
"numpy.frombuffer"
]
] |
bsipocz/glue | [
"7b7e4879b4c746b2419a0eca2a17c2d07a3fded3"
] | [
"glue/clients/__init__.py"
] | [
"from matplotlib import rcParams, rcdefaults\n#standardize mpl setup\nrcdefaults()\n\nfrom .histogram_client import HistogramClient\nfrom .image_client import ImageClient\nfrom .scatter_client import ScatterClient\n"
] | [
[
"matplotlib.rcdefaults"
]
] |
lxuechen/swissknife | [
"43dbd36f1e998ebe29c0b85fafd0de765dfb5de8"
] | [
"experiments/explainx/numerical.py"
] | [
"import math\nfrom typing import Union, Sequence\n\nimport torch\n\n\ndef logmeanexp(x: Union[Sequence[torch.Tensor], torch.Tensor], keepdim=False, dim=0):\n if isinstance(x, (tuple, list)):\n elem0 = x[0]\n if elem0.dim() == 0:\n x = torch.stack(x)\n elif elem0.dim() == 1:\n x = torch.cat(x, dim=0)\n else:\n raise ValueError\n return torch.logsumexp(x, dim=dim, keepdim=keepdim) - math.log(x.size(dim))\n"
] | [
[
"torch.logsumexp",
"torch.stack",
"torch.cat"
]
] |
ColinRioux/DeepPseudo | [
"f7b2ec1d5c60ae15b5cdb5dcc8de8b4d2f354340"
] | [
"src/EncoderLayer.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom src.EncoderBlockLayer import EncoderBlockLayer\nfrom src.PositionalEncodingLayer import PositionalEncodingLayer\n\nclass EncoderLayer(nn.Module):\n\n def __init__(self, vocab_size, max_len, d_model, n_heads, hidden_size, kernel_size, dropout, n_layers, scale, seq_thresh):\n super(EncoderLayer, self).__init__()\n self.vocab_size = vocab_size\n self.max_len = max_len\n self.d_model = d_model\n self.n_heads = n_heads\n self.hidden_size = hidden_size\n self.kernel_size = kernel_size\n self.dropout = nn.Dropout(p=dropout)\n self.n_layers = n_layers\n self.scale = scale\n self.token_embedding = nn.Embedding(vocab_size, d_model)\n self.position_encoding = PositionalEncodingLayer(d_model=d_model, max_len=max_len)\n self.encoder_block_layers = nn.ModuleList(\n [EncoderBlockLayer(d_model=d_model, n_heads=n_heads, hidden_size=hidden_size,\n dropout=dropout,seq_thresh=seq_thresh) for _ in range(n_layers)])\n self.fc_embedding_hidden = nn.Linear(d_model, hidden_size)\n self.fc_hidden_embedding = nn.Linear(hidden_size, d_model)\n self.conv1ds = nn.ModuleList([nn.Conv1d(hidden_size, hidden_size * 2, kernel_size=kernel_size,\n padding=(kernel_size - 1) // 2) for _ in range(n_layers)])\n\n def forward(self, src_sequences, src_mask):\n \"\"\"\n :param Tensor[batch_size, src_len] src_sequences\n :param Tensor[batch_size, src_len] src_mask\n :return Tensor[batch_size, src_len, d_model] outputs\n \"\"\"\n token_embedded = self.token_embedding(src_sequences) # [batch_size, src_len, d_model]\n position_encoded = self.position_encoding(src_sequences) # [batch_size, src_len, d_model]\n outputs = self.dropout(token_embedded) + position_encoded # [batch_size, src_len, d_model]\n\n embedded = outputs\n for layer in self.encoder_block_layers:\n outputs = layer(src_inputs=outputs, src_mask=src_mask) # [batch_size, src_len, d_model]\n\n conv_output = self.fc_embedding_hidden(embedded) # [batch_size, src_len, hidden_size]\n conv_output = conv_output.permute(0, 2, 1) # [batch_size, hidden_size, src_len]\n for conv1d in self.conv1ds:\n conv_output = self.dropout(conv_output)\n conved = conv1d(conv_output) # [batch_size, hidden_size * 2, src_len]\n conved = F.glu(conved, dim=1) # [batch_size, hidden_size, src_len]\n conv_output = (conved + conv_output) * self.scale # [batch_size, hidden_size, src_len] Residual connection\n conv_output = conv_output.permute(0, 2, 1) # [batch_size, src_len, hidden_size]\n conv_output = self.fc_hidden_embedding(conv_output) # [batch_size, src_len, d_model]\n\n outputs = outputs + conv_output\n return outputs"
] | [
[
"torch.nn.Linear",
"torch.nn.Embedding",
"torch.nn.Conv1d",
"torch.nn.functional.glu",
"torch.nn.Dropout"
]
] |
jmcabreira/Dynamic-risk-assessment-system | [
"9ad320b12eb8948345743e403a6a49268de72858"
] | [
"scoring.py"
] | [
"from flask import Flask, session, jsonify, request\nimport pandas as pd\nimport numpy as np\nimport pickle\nimport os\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nimport json\n\n#################Load config.json and get path variables\nwith open('config.json','r') as f:\n config = json.load(f) \n\ntest_data_path = os.path.join(config['test_data_path'], 'testdata.csv') \nmodel_path = os.path.join(config['output_model_path'], 'trainedmodel.pkl') \nscore_path = os.path.join(config['output_model_path'], 'latestscore.txt') \n\n#################Function for model scoring\ndef score_model(test_data_path):\n #this function should take a trained model, load test data, and calculate an F1 score for the model relative to the test data\n #it should write the result to the latestscore.txt file\n test_df = pd.read_csv(test_data_path)\n\n X_test = test_df.drop(['corporation', 'exited'], axis=1)\n y_test = test_df['exited']\n \n # Read model\n with open(model_path , 'rb') as file:\n model = pickle.load(file)\n \n # model scoring\n y_pred = model.predict(X_test)\n print(\"pred: \", (y_pred))\n print(\"teste: \",(y_test.values))\n f1_score = metrics.f1_score(y_test.values, y_pred)\n print(f'F1 Score: {f1_score}')\n\n print(f\"Savind F1 score in {score_path}\")\n with open(score_path, 'w') as file:\n file.write(str(f1_score))\n\n return f1_score\n\n\nif __name__ == '__main__':\n f1_score = score_model(test_data_path)\n\n"
] | [
[
"pandas.read_csv",
"sklearn.metrics.f1_score"
]
] |
Data-Science-in-Mechanical-Engineering/edge | [
"586eaba2f0957e75940f4f19fa774603f57eae89"
] | [
"edge/gym_wrappers/environment_wrapper.py"
] | [
"import gym.spaces as gspaces\n\nfrom edge.envs.environments import Environment\nfrom edge.space import StateActionSpace\nfrom . import BoxWrapper, DiscreteWrapper\n\n\nclass DummyDynamics:\n def __init__(self, stateaction_space):\n self.stateaction_space = stateaction_space\n\n @property\n def state_space(self):\n return self.stateaction_space.state_space\n\n @property\n def action_space(self):\n return self.stateaction_space.action_space\n\n def is_feasible_state(self, s):\n return True\n\n\ndef get_index_length(gym_box):\n return len(gym_box.low.reshape(-1))\n\n\nclass GymEnvironmentWrapper(Environment):\n def __init__(self, gym_env, shape=None, failure_critical=False,\n control_frequency=None, **kwargs):\n self.gym_env = gym_env\n if shape is None:\n obs_shape = None\n action_shape = None\n if isinstance(gym_env.action_space, gspaces.Box):\n if shape is not None:\n action_space_ndim = get_index_length(gym_env.action_space)\n action_shape = shape[-action_space_ndim:]\n action_space = BoxWrapper(\n gym_env.action_space, discretization_shape=action_shape,\n **kwargs\n )\n elif isinstance(gym_env.action_space, gspaces.Discrete):\n action_space = DiscreteWrapper(gym_env.action_space)\n else:\n raise TypeError(f'Gym environment action_space is of type {type(gym_env.action_space)}, but only Box '\n 'and Discrete are currently supported')\n\n if isinstance(gym_env.observation_space, gspaces.Box):\n if shape is not None:\n state_space_ndim = get_index_length(gym_env.observation_space)\n obs_shape = shape[:state_space_ndim]\n state_space = BoxWrapper(\n gym_env.observation_space,\n discretization_shape=obs_shape,\n **kwargs\n )\n elif isinstance(gym_env.observation_space, gspaces.Discrete):\n state_space = DiscreteWrapper(gym_env.observation_space)\n else:\n raise TypeError(f'Gym environment observation_space is of type {type(gym_env.observation_space)}, but only '\n 'Box and Discrete are currently supported')\n\n self.info = {}\n self._done = False\n self.failure_critical = failure_critical\n self.control_frequency = control_frequency\n\n dynamics = DummyDynamics(StateActionSpace(state_space, action_space))\n\n super(GymEnvironmentWrapper, self).__init__(\n dynamics=dynamics,\n reward=None,\n default_initial_state=gym_env.reset(),\n random_start=True\n )\n\n @property\n def in_failure_state(self):\n cost = self.info.get('cost')\n return cost is not None and cost != 0\n\n @property\n def done(self):\n return self._done\n\n @property\n def has_failed(self):\n # Same as in_failure_state, for compatibility with generic Environment\n return self.in_failure_state\n\n def reset(self, s=None):\n # Usually, Environments take s as a parameter, but this is not supported by safety_gym, so we\n # raise a meaningful error for the user\n if s is not None:\n raise ValueError('Selecting the initial state is not supported for Gym environments')\n reset_output = self.gym_env.reset()\n # Safety gym does not return anything with reset, whereas Gym returns\n # the state\n if reset_output is None:\n self.s = self.gym_env.obs()\n else:\n self.s = reset_output\n self._done = self.in_failure_state\n return self.s\n\n def step(self, action):\n gym_action = self.dynamics.action_space.to_gym(action)\n\n def do_one_gym_step():\n if not self.failure_critical or not self.has_failed:\n gym_new_state, reward, done, info = self.gym_env.step(\n gym_action\n )\n s = self.dynamics.state_space.from_gym(gym_new_state)\n # Gym does not put a hard constraint on the fact that the state\n # stays in the limit of the Box. Edge crashes if this happens,\n # so we project the resulting state in state-space\n s = self.dynamics.state_space.closest_in(s)\n else:\n reward = 0\n return s, reward, done, info\n\n step_done = False\n n_gym_steps = 0\n while not step_done:\n self.s, reward, self._done, _ = do_one_gym_step()\n n_gym_steps += 1\n step_done = (self.control_frequency is None) or \\\n (n_gym_steps >= self.control_frequency) or \\\n (self._done)\n\n return self.s, reward, self.has_failed\n\n def render(self):\n self.gym_env.render()\n\n def compute_dynamics_map(self):\n # General note: Q_map stores the index of the next state. This\n # approximates the dynamics by projecting the state we end up in, and\n # may lead to errors. A more precise implementation would keep the\n # exact value of the next state instead of its index. So far, this\n # method is only used for the computation of the viability sets, and\n # this requires the index of the next state: implementing the more\n # precise method is useless for this.\n # However, the following implementation may need to change if this\n # method is used for something else.\n\n import numpy as np\n unwrapped_gym_env = self.gym_env.unwrapped\n Q_map = np.zeros(self.stateaction_space.shape, dtype=tuple)\n for sa_index, stateaction in iter(self.stateaction_space):\n state, action = self.stateaction_space.get_tuple(stateaction)\n state = self.state_space.to_gym(state)\n action = self.action_space.to_gym(action)\n unwrapped_gym_env.state = state\n next_state, reward, failed = self.step(action)\n next_state = self.state_space.from_gym(next_state)\n # Gym does not ensure the stability of the stateaction space under\n # the dynamics, so we enforce it.\n # This may lead to edge effects.\n next_state = self.state_space.closest_in(next_state)\n next_state_index = self.state_space.get_index_of(\n next_state, around_ok=True\n )\n Q_map[sa_index] = next_state_index\n return Q_map"
] | [
[
"numpy.zeros"
]
] |
Kiwi-PUJ/DataLabelling | [
"1b89041dc371720be6254e1efb3ee8665ce69951"
] | [
"main.py"
] | [
"## @package Labelling_app\n# Labelling app software developed with Grabcut\n# \n# @version 1 \n#\n# Pontificia Universidad Javeriana\n# \n# Electronic Enginnering\n# \n# Developed by:\n# - Andrea Juliana Ruiz Gomez\n# Mail: <[email protected]>\n# GitHub: andrearuizg\n# - Pedro Eli Ruiz Zarate\n# Mail: <[email protected]>\n# GitHub: PedroRuizCode\n# \n# With support of:\n# - Francisco Carlos Calderon Bocanegra\n# Mail: <[email protected]>\n# GitHub: calderonf\n# - John Alberto Betancout Gonzalez\n# Mail: <[email protected]>\n# GitHub: JohnBetaCode\n\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import QIcon, QPalette, QColor, QPixmap, QImage\nfrom PyQt5.QtCore import Qt\nimport cv2\nimport numpy as np\nfrom time import time\nimport random\n\n\n## GUI class\nclass GUI(QMainWindow):\n\n ## The constructor\n #\n # Here you can configure the screen, buttons (rectangle, foreground,\n # iteration, open file, new label, original image, segmented image,\n # labelled image, previous, next, save, exit, reset), labels (video frame,\n # label, show image), spin box (video frames), list (labels), image panel,\n # checkbox (full screen, dark theme) and mouse events\n # @param self The object pointer.\n def __init__(self):\n super().__init__()\n app.setStyle('Fusion')\n\n screen = app.primaryScreen()\n rect = screen.size()\n width = rect.width()\n height = rect.height() - 30\n\n self.setGeometry(10, 10, width, height)\n self.setWindowTitle(\"Kiwi & PUJ - Labelling software\")\n self.setWindowIcon(QIcon(\"media/.icons/ICON.png\"))\n\n self.b_rec = QPushButton(self)\n self.b_rec.setText('&Rectangle')\n self.b_rec.move(((width // 2) - 210), 15)\n self.b_rec.setEnabled(False)\n self.b_rec.setShortcut('Ctrl+r')\n self.b_rec.clicked.connect(self.rectangle_)\n\n self.b_bg = QPushButton(self)\n self.b_bg.setText('&Background')\n self.b_bg.move(((width // 2) - 105), 15)\n self.b_bg.setEnabled(False)\n self.b_bg.setShortcut('Ctrl+b')\n self.b_bg.clicked.connect(self.background_)\n\n self.b_fg = QPushButton(self)\n self.b_fg.setText('&Foreground')\n self.b_fg.move(width // 2, 15)\n self.b_fg.setEnabled(False)\n self.b_fg.setShortcut('Ctrl+f')\n self.b_fg.clicked.connect(self.foreground_)\n\n self.b_it = QPushButton(self)\n self.b_it.setText('&Iteration')\n self.b_it.move(((width // 2) + 105), 15)\n self.b_it.setEnabled(False)\n self.b_it.setShortcut('Ctrl+i')\n self.b_it.clicked.connect(self.iteration_)\n\n f_open = QPushButton(self)\n f_open.setText('&Open file')\n f_open.setIcon(QIcon('media/.icons/file.png'))\n f_open.move(10, 15)\n f_open.setShortcut('Ctrl+o')\n f_open.clicked.connect(self.open_)\n\n t1 = QLabel(self)\n t1.setText(\"Video frames\")\n t1.move(10, height - 175)\n\n self.spin = QSpinBox(self)\n self.spin.move(10, height - 150)\n self.spin.setValue(30)\n self.spin.setRange(1, 999)\n self.spin.valueChanged.connect(self.sh_spin_val)\n\n t1 = QLabel(self)\n t1.setText(\"Labels\")\n t1.move(10, 90)\n\n self.b_new = QPushButton(self)\n self.b_new.setText('&New')\n self.b_new.setIcon(QIcon('media/.icons/new.png'))\n self.b_new.setEnabled(False)\n self.b_new.setShortcut('Ctrl+n')\n self.b_new.move(10, 120)\n self.b_new.clicked.connect(self.new_label)\n\n labels = open('/tmp/labels.txt', 'r').read()\n self.labels = list(labels.split(\"\\n\"))\n\n self.Label_n = QComboBox(self)\n for n in range(len(self.labels) - 1):\n self.Label_n.addItem(self.labels[n])\n self.Label_n.move(10, 150)\n self.Label_n.setEnabled(False)\n self.Label_n.activated[str].connect(self.sel_LN)\n\n t2 = QLabel(self)\n t2.setText(\"Show image\")\n t2.move(10, height // 2)\n\n self.b_or = QPushButton(self)\n self.b_or.setText('Original')\n self.b_or.move(10, (height // 2) + 30)\n self.b_or.setEnabled(False)\n self.b_or.clicked.connect(self.b_or_)\n\n self.b_seg = QPushButton(self)\n self.b_seg.setText('Segmented')\n self.b_seg.move(10, (height // 2) + 60)\n self.b_seg.setEnabled(False)\n self.b_seg.clicked.connect(self.b_seg_)\n\n self.b_lab = QPushButton(self)\n self.b_lab.setText('Labels')\n self.b_lab.move(10, (height // 2) + 90)\n self.b_lab.setEnabled(False)\n self.b_lab.clicked.connect(self.b_lab_)\n\n self.b_pre = QPushButton(self)\n self.b_pre.setText('Previous')\n self.b_pre.setIcon(QIcon('media/.icons/undo.png'))\n self.b_pre.move(10, height - 110)\n self.b_pre.setShortcut('Ctrl+Left')\n self.b_pre.setEnabled(False)\n self.b_pre.clicked.connect(self.b_pre_)\n\n self.b_nxt = QPushButton(self)\n self.b_nxt.setText('Next')\n self.b_nxt.setIcon(QIcon('media/.icons/redo.png'))\n self.b_nxt.move(10, height - 80)\n self.b_nxt.setShortcut('Ctrl+Right')\n self.b_nxt.setEnabled(False)\n self.b_nxt.clicked.connect(self.b_nxt_)\n\n self.b_sav = QPushButton(self)\n self.b_sav.setText('&SAVE')\n self.b_sav.setIcon(QIcon('media/.icons/save.png'))\n self.b_sav.move(10, height - 30)\n self.b_sav.setEnabled(False)\n self.b_sav.setShortcut('Ctrl+s')\n self.b_sav.clicked.connect(self.b_sav_)\n\n b_ext = QPushButton(self)\n b_ext.setText('EXIT')\n b_ext.setIcon(QIcon('media/.icons/exit.png'))\n b_ext.move(width - 110, height - 30)\n b_ext.clicked.connect(self.b_ext_)\n\n b_res = QPushButton(self)\n b_res.setText('RESET')\n b_res.move(width - 110, height - 80)\n b_res.clicked.connect(self.reset_)\n\n self.image_1 = QLabel(self)\n self.image_1.resize(640, 480)\n self.image_1.move((width // 2) - 320, (height // 2) - 200)\n\n self.dark = QCheckBox(self)\n self.dark.setText('Dark theme')\n self.dark.setChecked(True)\n self.dark.move((width - 110), 15)\n self.dark.toggled.connect(self.dark_)\n\n self.fs = QCheckBox(self)\n self.fs.setText('Full Screen')\n self.fs.setChecked(True)\n self.fs.move((width - 110), 35)\n self.fs.toggled.connect(self.fullScreen_)\n\n self.fullScreen_()\n self.show()\n self.reset_()\n self.dark_()\n\n self.image_1.mousePressEvent = self.mouse_down\n self.image_1.mouseMoveEvent = self.mouse_move\n self.image_1.mouseReleaseEvent = self.mouse_up\n\n ## Label selection function\n #\n # Select the label of the segmented image, and created the labelled image\n # file\n # @param self The object pointer.\n # @param text Label gave by the user\n def sel_LN(self, text):\n for n in range(len(self.labels) - 1):\n if text == self.labels[n]:\n self.contour_()\n self.colors = tuple(self.colors)\n cv2.drawContours(self.img_out, self.contours, -1, n + 1,\n thickness=cv2.FILLED)\n cv2.drawContours(self.img_label, self.contours, -1,\n self.colors[n], thickness=cv2.FILLED)\n\n ## Contour function\n #\n # Determine the contour of the segmented image\n # @param self The object pointer.\n def contour_(self):\n imgray = cv2.cvtColor(self.out, cv2.COLOR_BGR2GRAY)\n ret, thresh = cv2.threshold(imgray, 1, 255, 0)\n self.contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,\n cv2.CHAIN_APPROX_SIMPLE)\n\n ## New label button function\n #\n # Set enable flag true\n # @param self The object pointer.\n def new_label(self):\n self.Label_n.setEnabled(True)\n self.b_lab_()\n\n ## Original picture button\n #\n # Show original picture\n # @param self The object pointer.\n def b_or_(self):\n self.showImage_(self.img_in)\n\n ## Segmented picture button\n #\n # Show segmented picture\n # @param self The object pointer.\n def b_seg_(self):\n self.showImage_(self.out)\n\n ## Labelled picture button\n #\n # Show labelled picture\n # @param self The object pointer.\n def b_lab_(self):\n self.showImage_(self.img_label)\n\n ## Spin value function\n #\n # Update video frame variable\n # @param self The object pointer.\n def sh_spin_val(self):\n self.value_sp = self.spin.value()\n\n ## Previous image button function\n #\n # Disable buttons and show warnings\n # @param self The object pointer.\n def b_pre_(self):\n if self.flag_save == 0:\n self.b_sav.setEnabled(False)\n self.b_bg.setEnabled(False)\n self.b_fg.setEnabled(False)\n self.b_it.setEnabled(False)\n self.b_new.setEnabled(False)\n self.Label_n.setEnabled(False)\n self.b_or.setEnabled(False)\n self.b_seg.setEnabled(False)\n self.b_lab.setEnabled(False)\n if self.flag_save == 1:\n self.show_alert()\n if self.file_vid == 0:\n self.file_num -= 1\n self.load()\n else:\n if self.flag_vid == 1:\n self.flag_vid = 0\n self.file_num -= 2\n self.frame_act -= int(self.value_sp)\n self.load_vid()\n else:\n self.flag_save = 0\n self.show_alert()\n\n ## Next image button function\n #\n # Disable buttons and show warnings\n # @param self The object pointer.\n def b_nxt_(self):\n if self.flag_save == 0:\n self.b_sav.setEnabled(False)\n self.b_bg.setEnabled(False)\n self.b_fg.setEnabled(False)\n self.b_it.setEnabled(False)\n self.b_new.setEnabled(False)\n self.Label_n.setEnabled(False)\n self.b_or.setEnabled(False)\n self.b_seg.setEnabled(False)\n self.b_lab.setEnabled(False)\n if self.file_vid == 0:\n self.file_num += 1\n self.load()\n else:\n self.frame_act += int(self.value_sp)\n self.load_vid()\n else:\n self.flag_save = 0\n self.show_alert()\n\n ## Save button function\n #\n # Save files\n # - for pictures only save the labelled mask\n # - for videos save labelled mask and original frame\n # @param self The object pointer.\n def b_sav_(self):\n str = (self.filename[self.file_num].split(\".\")[0]).split(\"/\")[-1]\n if self.file_vid == 0:\n outfile = 'media/%s-mask.png' % (str)\n outfile1 = 'media/%s.png' % (str)\n else:\n outfile = 'media/%s-frame-%s-mask.png' % (str, self.frame_act)\n outfile1 = 'media/%s-frame-%s.png' % (str, self.frame_act)\n original = '%s' % self.filename[self.file_num].split(\"/\")[-1]\n mask = '%s' % outfile.split(\"/\")[-1]\n tf = '%s' % (time() - self.ti)\n self.d_time[self.frame_num, ...] = [original, mask, tf]\n cv2.imwrite(outfile, self.img_out)\n cv2.imwrite(outfile1, self.img_in)\n self.frame_num += 1\n self.flag_save = 0\n self.flag_file = 1\n\n ## Exit button function\n #\n # Save time stamps csv and close app\n # @param self The object pointer.\n def b_ext_(self):\n if self.flag_file == 1:\n np.savetxt(\"media/timestamps.csv\", self.d_time, delimiter=\", \", \n fmt='%s')\n self.close()\n QApplication.quit()\n\n ## Open button function\n #\n # Open file dialog window\n # @param self The object pointer.\n def open_(self):\n self.filename, _ = QFileDialog.getOpenFileNames(None, 'Buscar Imagen',\n '.', 'Image Files (*.png *.jpg *.jpeg *.bmp *.mp4)')\n self.file_num = 0\n self.frame_num = 1\n self.flag_save = 0\n self.flag_vid = 0\n self.file_vid = 0\n self.b_rec.setEnabled(True)\n self.b_pre.setEnabled(True)\n self.b_nxt.setEnabled(True)\n self.load()\n\n ## Load function\n #\n # Open file in open cv\n # @param self The object pointer.\n def load(self):\n self.flag_save = 0\n if self.file_num < len(self.filename):\n if (self.filename[self.file_num].split(\".\")[-1] in \n ['png', 'jpg', 'jpeg', 'bmp']):\n self.img_in = cv2.imread(self.filename[self.file_num], \n cv2.IMREAD_UNCHANGED)\n self.img_in = cv2.resize(self.img_in, (640, 480))\n self.img_copy = self.img_in.copy()\n self.img_out = np.zeros((480, 640), np.uint8)\n self.img_label = self.img_in.copy()\n self.showImage_(self.img_in)\n else:\n self.file_vid = 1\n self.vid = cv2.VideoCapture(self.filename[self.file_num])\n self.length = int(self.vid.get(cv2.CAP_PROP_FRAME_COUNT))\n self.frame_act = 1\n self.load_vid()\n else:\n self.b_ext_()\n if ((self.file_num == 0) and (self.file_vid == 0)):\n self.b_pre.setEnabled(False)\n else:\n self.b_pre.setEnabled(True)\n if ((self.file_num == (len(self.filename) - 1)) \n and (self.file_vid == 0)):\n self.b_nxt.setEnabled(False)\n else:\n self.b_nxt.setEnabled(True)\n\n ## Load video function\n #\n # Open video frames\n # @param self The object pointer.\n def load_vid(self):\n self.sh_spin_val()\n if self.vid.isOpened():\n if (self.frame_act <= self.length) and (self.frame_act > 0):\n self.vid.set(1, self.frame_act)\n ret, self.img_in = self.vid.read()\n self.img_in = cv2.resize(self.img_in, (640, 480))\n self.img_copy = self.img_in.copy()\n self.img_out = np.zeros((480, 640), np.uint8)\n self.img_label = self.img_in.copy()\n self.showImage_(self.img_in)\n else:\n self.flag_vid = 1\n self.vid.release()\n self.file_vid = 0\n self.file_num += 1\n self.load()\n\n ## Show image function\n #\n # Show picture in Pixmap\n # @param self The object pointer.\n # @param image Image to display.\n def showImage_(self, image):\n size = image.shape\n step = image.size / size[0]\n qformat = QImage.Format_Indexed8\n if len(size) == 3:\n if size[2] == 4:\n qformat = QImage.Format_RGBA8888\n else:\n qformat = QImage.Format_RGB888\n img = QImage(image, size[1], size[0], step, qformat)\n img = img.rgbSwapped()\n self.image_1.setPixmap(QPixmap.fromImage(img))\n self.resize(self.image_1.pixmap().size())\n\n ## Rectangle button function\n #\n # Enable flags to draw rectangle in picture\n # @param self The object pointer.\n def rectangle_(self):\n self.b_bg.setEnabled(True)\n self.b_fg.setEnabled(True)\n self.b_it.setEnabled(True)\n self.flag_rect = True\n self.flag_circle_fg = False\n self.flag_circle_bg = False\n self.ini_points = []\n self.ti = time()\n\n ## Background button function\n #\n # Enable flags to draw the background\n # @param self The object pointer.\n def background_(self):\n self.flag_rect = False\n self.flag_circle_fg = False\n self.flag_circle_bg = True\n\n ## Foreground button function\n #\n # Enable flags to draw the foreground\n # @param self The object pointer.\n def foreground_(self):\n self.flag_rect = False\n self.flag_circle_fg = True\n self.flag_circle_bg = False\n\n ## Iteration button function\n #\n # Iteration to make the segmented image\n # @param self The object pointer.\n def iteration_(self):\n self.b_sav.setEnabled(True)\n self.b_new.setEnabled(True)\n self.b_or.setEnabled(True)\n self.b_seg.setEnabled(True)\n self.b_lab.setEnabled(True)\n self.flag_save = 1\n self.flag_rect = False\n self.flag_circle_fg = False\n self.flag_circle_bg = False\n cv2.grabCut(self.img_in, self.mask, None, self.BGD_model,\n self.FGD_model, 1, cv2.GC_INIT_WITH_MASK)\n comp = (self.mask == 1) | (self.mask == 3)\n self.m_out = np.where(comp, 1, 0).astype('uint8')\n self.out = cv2.bitwise_and(self.img_in, self.img_in, mask=self.m_out)\n self.showImage_(self.out)\n\n ## Dark theme function\n #\n # Set dark or white theme\n # @param self The object pointer.\n def dark_(self):\n if self.dark.isChecked() is True:\n palette = QPalette()\n palette.setColor(QPalette.Window, QColor(53, 53, 53))\n palette.setColor(QPalette.WindowText, Qt.white)\n palette.setColor(QPalette.Base, QColor(25, 25, 25))\n palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))\n palette.setColor(QPalette.ToolTipBase, Qt.white)\n palette.setColor(QPalette.ToolTipText, Qt.white)\n palette.setColor(QPalette.Text, Qt.white)\n palette.setColor(QPalette.Button, QColor(53, 53, 53))\n palette.setColor(QPalette.ButtonText, Qt.white)\n palette.setColor(QPalette.BrightText, Qt.red)\n palette.setColor(QPalette.Link, QColor(42, 130, 218))\n palette.setColor(QPalette.Highlight, QColor(42, 130, 218))\n palette.setColor(QPalette.HighlightedText, Qt.black)\n palette.setColor(QPalette.Disabled, QPalette.Base, \n QColor(52, 52, 52))\n palette.setColor(QPalette.Disabled, QPalette.Text, \n QColor(57, 57, 57))\n palette.setColor(QPalette.Disabled, QPalette.Button, \n QColor(47, 47, 47))\n palette.setColor(QPalette.Disabled, QPalette.ButtonText, \n QColor(67, 67, 67))\n palette.setColor(QPalette.Disabled, QPalette.Window, \n QColor(49, 49, 49))\n palette.setColor(QPalette.Disabled, QPalette.WindowText, \n QColor(57, 57, 57))\n self.setPalette(palette)\n if self.dark.isChecked() is False:\n palette = QPalette()\n palette.setColor(QPalette.Window, QColor(239, 239, 239))\n palette.setColor(QPalette.WindowText, Qt.black)\n self.setPalette(palette)\n\n ## Show alert function\n #\n # Show alert when the labelled picture is not save\n # @param self The object pointer.\n def show_alert(self):\n warning = QMessageBox(self)\n warning.setIcon(QMessageBox.Warning)\n warning.setText(\"Remember to save the results\")\n warning.setWindowTitle(\"Warning\")\n warning.exec_()\n\n ## Maximized function\n #\n # Maximized window\n # @param self The object pointer.\n def maximized(self):\n self.showMaximized()\n\n ## Full-screen function\n #\n # Full-screen window\n # @param self The object pointer.\n def fullScreen_(self):\n if self.fs.isChecked() is True:\n self.showFullScreen()\n else:\n self.showMaximized()\n\n ## Mouse move function\n #\n # Make the rectangle or circles when user is pressing the mouse\n # @param self The object pointer.\n # @param event The mouse event.\n def mouse_move(self, event):\n x = event.pos().x()\n y = event.pos().y()\n if self.flag_rect is True:\n img_temp_m = self.img_in.copy()\n self.fin_points = [x, y]\n self.img_copy = cv2.rectangle(img_temp_m, tuple(self.ini_points), \n tuple(self.fin_points), (0, 0, 255), \n 5)\n if ((self.flag_circle_fg is True) and (self.start is True)):\n cv2.circle(self.img_copy, (x, y), 3, (255, 255, 255), -1)\n cv2.circle(self.mask, (x, y), 5, 1, -1)\n if ((self.flag_circle_bg is True) and (self.start is True)):\n cv2.circle(self.img_copy, (x, y), 3, (0, 0, 0), -1)\n cv2.circle(self.mask, (x, y), 5, 0, -1)\n self.showImage_(self.img_copy)\n\n ## Mouse down function\n #\n # Make the initial points of the rectangle or start circles\n # @param self The object pointer.\n # @param event The mouse event.\n def mouse_down(self, event):\n x = event.pos().x()\n y = event.pos().y()\n if self.flag_rect is True:\n self.ini_points = [x, y]\n if ((self.flag_rect is False) and ((self.flag_circle_fg is True) \n or (self.flag_circle_bg is True))):\n self.start = True\n\n ## Mouse up function\n #\n # Make the final points of the rectangle or finish circles\n # @param self The object pointer.\n # @param event The mouse event.\n def mouse_up(self, event):\n x = event.pos().x()\n y = event.pos().y()\n if self.flag_rect is True:\n img_temp = self.img_in.copy()\n self.fin_points = [x, y]\n self.img_copy = cv2.rectangle(img_temp, tuple(self.ini_points),\n tuple(self.fin_points), (0, 0, 255),\n 5)\n self.mask = np.zeros((480, 640), np.uint8)\n self.mask = cv2.rectangle(self.mask, tuple(self.ini_points), \n tuple(self.fin_points), 3, -1)\n self.flag_rect = False\n self.start = False\n self.showImage_(self.img_copy)\n\n ## Reset function\n #\n # Reset app\n # @param self The object pointer.\n def reset_(self):\n self.flag_file = 0\n self.d_time = np.zeros((10000, 3), dtype='U255')\n self.d_time[0, ...] = ['Img. Original', 'Img. Mask', 'Time (s)']\n self.BGD_model = np.zeros((1, 65), np.float64)\n self.FGD_model = np.zeros((1, 65), np.float64)\n self.ini_points, self.fin_points = [], []\n self.flag_rect = False\n self.flag_circle_fg = False\n self.flag_circle_bg = False\n self.start = False\n self.mask = np.zeros((640, 480), np.uint8)\n img = cv2.imread('media/.icons/INTRO.png', 1)\n img = cv2.resize(img, (640, 480))\n self.colors = np.random.randint(20, 255, (len(self.labels) - 1, 3))\n self.colors = []\n for n in range(len(self.labels) - 1):\n color = []\n for _ in range(3):\n color.append(random.randrange(0, 255))\n self.colors.append(tuple(color))\n self.showImage_(img)\n\n ## @var flag_file\n # It takes 0 value when the user hasn't chosen a file\n #\n # It takes 1 value when the user choose a file\n\n ## @var b_rec\n # Rectangle push button variable\n\n ## @var b_bg\n # Background push button variable\n\n ## @var b_fg\n # Foreground push button variable\n\n ## @var b_it\n # Iteration push button variable\n\n ## @var spin\n # Value of video frame variable at spin box\n\n ## @var b_new\n # New push button variable\n\n ## @var labels\n # List of labels that the user wrote on the labels.txt\n\n ## @var Label_n\n # List of labels\n\n ## @var b_or\n # Original image push button variable\n\n ## @var b_seg\n # Segmented image push button variable\n\n ## @var b_lab\n # Labelled image push button variable\n\n ## @var b_pre\n # Previous image push button variable\n\n ## @var b_nxt\n # Next image push button variable\n\n ## @var b_sav\n # Save image push button variable\n\n ## @var image_1\n # Image panel variable\n\n ## @var dark\n # Dark theme checkbox variable\n\n ## @var fs\n # Full screen checkbox variable\n\n ## @var colors\n # Variable of random colors generated when the application begins or \n # restart\n\n ## @var value_sp\n # Value at video frame spin box\n\n ## @var flag_save\n # It takes 0 value when the user hasn't saved a file\n #\n # It takes 1 value when the user save a file\n\n ## @var file_vid\n # It takes 0 value when the file is an image\n #\n # It takes 1 value when the file is a video\n\n ## @var flag_vid\n # Overflow when video frame is the first or the last\n\n ## @var d_time\n # List with the data of timestamps.csv\n\n ## @var file_num\n # Number of file that shows the image panel\n\n ## @var frame_num\n # Number of frame\n\n ## @var img_in\n # Input image or frame\n\n ## @var img_copy\n # Copy of input image or frame\n\n ## @var img_out\n # Output image\n\n ## @var img_label\n # Output labelled image\n\n ## @var vid\n # Video frame\n\n ## @var length\n # Length of video frames\n\n ## @var frame_act\n # Actual video frame\n\n ## @var flag_rect\n # It takes 0 value when the user hasn't pressed rectangle push button\n #\n # It takes 1 value when the user press rectangle push button\n\n ## @var flag_circle_fg\n # It takes 0 value when the user hasn't pressed foreground push button\n #\n # It takes 1 value when the user press foreground push button\n\n ## @var flag_circle_bg\n # It takes 0 value when the user hasn't pressed background push button\n #\n # It takes 1 value when the user press background push button\n\n ## @var ini_points\n # Initial coordinates of mouse at image panel after the rectangle push\n # button was pressed\n\n ## @var ti\n # Previous time. This variable is update after the rectangle push button\n # was pressed\n\n ## @var mask\n # Output mask of Grabcut algorithm. It can It takes 4 posible values:\n #\n # 0 - True background\n # 1 - True foreground\n # 2 - Possible background\n # 3 - Possible foreground\n\n ## @var m_out\n # Output mask. 0 and 2 values It takess 0 value; 1 and 3 values It takess 1 value.\n\n ## @var out\n # Out of segmented image\n\n ## @var fin_points\n # When the mouse is moving, it It takess the actual value of mouse coordinates\n # \n # When the mouse is up, it It takess the last value of mouse coordinates when\n # it was moving\n\n ## @var start\n # It takes 0 value when the user hasn't pressed background or foreground push\n # button. Can It takes 0 value when the user press background or foreground\n # push button and up the mouse in the image panel\n #\n # It takes 1 value when the user press background or foreground push button\n # and press the mouse in the image panel\n\n\n ## @var BGD_model\n # Variable exclusive of Grabcut algorithm\n\n ## @var FGD_model\n # Variable exclusive of Grabcut algorithm\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = GUI()\n sys.exit(app.exec_())\n"
] | [
[
"numpy.savetxt",
"numpy.where",
"numpy.zeros"
]
] |
zhaofang0627/HPBTT | [
"98cec9ff4ef95a01393718b024e9645e77fb70ee"
] | [
"data/background_pose.py"
] | [
"import os\n\nimport cv2\nimport numpy as np\nfrom absl import flags, app\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom .data_utils import RandomCrop\nfrom ..external.hmr.src.util import image as img_util\n\nimport tqdm\n\nbgData = './dataset/PRW-v16.04.20/frames'\nflags.DEFINE_string('PRW_img_path', bgData, 'Background Data Directory')\n\n\ndef pil_loader(path):\n # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n with open(path, 'rb') as f:\n with Image.open(f) as img:\n return img.convert('RGB')\n\n\nclass BackgroundDataset(Dataset):\n\n def __getitem__(self, index):\n texture_img_path = self.data[index]\n texture_img = np.array(pil_loader(texture_img_path)) # / 255.0\n if texture_img is None or texture_img.shape[0] <= 0 or texture_img.shape[1] <= 0:\n return self.__getitem__(np.random.randint(0, self.__len__()))\n texture_img = self.random_crop(texture_img)\n if np.random.rand(1) > 0.5:\n # Need copy bc torch collate doesnt like neg strides\n texture_img = texture_img[:, ::-1, :]\n\n texture_img, _ = img_util.scale_and_crop(texture_img, self.scale_cmr, self.center, self.img_size_cmr)\n\n # Finally transpose the image to 3xHxW\n texture_img = texture_img / 255.0\n texture_img = np.transpose(texture_img, (2, 0, 1))\n\n return {'bg_img': texture_img}\n\n def __len__(self):\n return len(self.data)\n\n def __init__(self, opts, data_path_list, img_size=(128, 64)):\n self.data_path_list = data_path_list\n self.img_size = img_size\n self.img_size_cmr = opts.img_size\n self.scale_cmr = (float(opts.img_size) / max(img_size))\n center = np.round(np.array(img_size) / 2).astype(int)\n # image center in (x,y)\n self.center = center[::-1]\n self.data = []\n self.generate_index()\n\n self.random_crop = RandomCrop(output_size=self.img_size)\n\n def generate_index(self):\n print('generating background index')\n for data_path in self.data_path_list:\n for root, dirs, files in os.walk(data_path):\n for name in tqdm.tqdm(files):\n if name.endswith('.jpg'):\n self.data.append(os.path.join(root, name))\n\n print('finish generating background index, found texture image: {}'.format(len(self.data)))\n\n\n#----------- Data Loader ----------#\n#----------------------------------#\ndef data_loader(opts, shuffle=True):\n background_dataset = BackgroundDataset(opts, [opts.PRW_img_path])\n return DataLoader(dataset=background_dataset, batch_size=opts.batch_size, shuffle=shuffle,\n num_workers=opts.n_data_workers, drop_last=True)\n"
] | [
[
"numpy.array",
"torch.utils.data.DataLoader",
"numpy.transpose",
"numpy.random.rand"
]
] |
adityaRakhecha/Image-Filters | [
"3d36008daf48ce16016e6152bcfb8dd422a095a0"
] | [
"sharpening.py"
] | [
"import cv2\nimport numpy as np\n\nclass sharpening:\n\n\tdef __init__(self):\n\t\tpass\n\t\n\tdef sharp(self,image):\n\t\t# Create sharpening kernel\n\t\tkernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])\n\n\t\t# applying the sharpening kernel to the input image & displaying it.\n\t\tsharpened = cv2.filter2D(image, -1, kernel)\n\n\t\t# Noise reduction\n\t\tsharpened = cv2.bilateralFilter(sharpened, 9, 75, 75) \n\t\treturn sharpened\n\n\n# Create an image object\nimage = cv2.imread(\"./car.jpg\")\n\ntmp_canvas = sharpening()\nres = tmp_canvas.sharp(image)\ncv2.imwrite('sharped.jpg', res)\ncv2.imshow('original',image)\ncv2.imshow('sharp',res)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n"
] | [
[
"numpy.array"
]
] |
yyyliu/latent-space-cartography | [
"c731029bfe540ac9ef703e832aac6774c01f075a"
] | [
"model/read.py"
] | [
"#!/usr/bin/env python\n\n'''\nReads an existing model and do something.\n'''\n\nfrom __future__ import print_function\nimport h5py\nfrom PIL import Image\nimport numpy as np\nimport os\n\nfrom keras import backend as K\n\nimport model\n\n# dataset config\nfrom config_emoji import *\n\nbatch_size = 100\n\n# path to the stored model\nbase = '/home/yliu0/data/{}/'.format(dset)\n\n# load training data\ndef load_data (fpath, original_img_size):\n f = h5py.File(fpath, 'r')\n dset = f[key_raw]\n\n x_train = dset[:train_split]\n x_test = dset[train_split:]\n\n x_train = x_train.astype('float32') / 255.\n x_train = x_train.reshape((x_train.shape[0],) + original_img_size)\n x_test = x_test.astype('float32') / 255.\n x_test = x_test.reshape((x_test.shape[0],) + original_img_size)\n\n return x_train, x_test\n\n# deserialize numpy array to image\ndef to_image (array):\n array = array.reshape(img_rows, img_cols, img_chns)\n array = 255 * (1.0 - array)\n return array.astype('uint8')\n\ndef visualize (x_test, encoder, generator, suffix=''):\n # encode and decode\n x_test_encoded = encoder.predict(x_test, batch_size=batch_size)\n x_test_decoded = generator.predict(x_test_encoded)\n\n m = 5\n original = np.zeros((img_rows * m, img_cols * m, img_chns), 'uint8')\n reconstructed = np.zeros((img_rows * m, img_cols * m, img_chns), 'uint8')\n\n def to_image (array):\n array = array.reshape(img_rows, img_cols, img_chns)\n array *= 255\n return array.astype('uint8')\n\n for i in range(m):\n for j in range(m):\n k = i * m + j\n orig = to_image(x_test[k])\n re = to_image(x_test_decoded[k])\n original[i * img_rows: (i + 1) * img_rows,\n j * img_cols: (j + 1) * img_cols] = orig\n reconstructed[i * img_rows: (i + 1) * img_rows,\n j * img_cols: (j + 1) * img_cols] = re\n\n img = Image.fromarray(original, img_mode)\n img.save('{}original.png'.format(imgbase))\n img = Image.fromarray(reconstructed, img_mode)\n img.save('{}reconstructed_{}.png'.format(imgbase, suffix))\n\n# run encoder through all points and save as a hdf5 file\n# indices should remain the same as raw data\ndef save_encoded (fn):\n # these will be numpy.ndarray with shape (length, latent_dim)\n x_test_encoded = encoder.predict(x_test, batch_size=batch_size)\n x_train_encoded = encoder.predict(x_train, batch_size=batch_size)\n encoded = np.concatenate((x_train_encoded, x_test_encoded), axis = 0)\n\n dim = encoded.shape[1]\n\n # remove previous result\n if os.path.exists(fn):\n os.remove(fn)\n \n f = h5py.File(fn, 'w')\n dset = f.create_dataset('latent', (1, dim), \n chunks=(1, dim),\n maxshape=(None, dim),\n dtype='float64')\n \n for i, val in enumerate(encoded):\n dset.resize((i + 1, dim))\n dset[i] = encoded[i]\n f.flush()\n \n f.close()\n\nif __name__ == '__main__':\n for latent_dim in dims:\n # input path\n rawpath = base + fn_raw\n resultbase = base + '{}_result/{}/'.format(dset, latent_dim)\n mpath = resultbase + '{}_model_dim={}.json'.format(dset, latent_dim)\n wpath = resultbase + '{}_model_dim={}.h5'.format(dset, latent_dim)\n\n # output path\n encode_path = base + 'latent{}.h5'.format(latent_dim)\n\n m = model.Vae(latent_dim = latent_dim, img_dim=(img_chns, img_rows, img_cols))\n vae, encoder, decoder = m.read(mpath, wpath)\n \n x_train, x_test = load_data(rawpath, m.original_img_size)\n # visualize(x_test, encoder, decoder)\n save_encoded(encode_path)\n"
] | [
[
"numpy.concatenate",
"numpy.zeros"
]
] |
tianchenji/Multimodal-SVAE | [
"c76b7f8984610e32819510a7a5295124b97460be"
] | [
"models/blocks/Decoder.py"
] | [
"import torch.nn as nn\n\nclass Decoder(nn.Module):\n\n def __init__(self, layer_sizes, latent_size):\n\n super().__init__()\n\n self.MLP = nn.Sequential()\n\n input_size = latent_size\n\n for i, (in_size, out_size) in enumerate(zip([input_size]+layer_sizes[:-1], layer_sizes)):\n self.MLP.add_module(\n name=\"L{:d}\".format(i), module=nn.Linear(in_size, out_size))\n if i+1 < len(layer_sizes):\n self.MLP.add_module(name=\"A{:d}\".format(i), module=nn.ReLU())\n else:\n self.MLP.add_module(name=\"sigmoid\", module=nn.Sigmoid())\n\n def forward(self, z):\n\n x = self.MLP(z)\n\n return x"
] | [
[
"torch.nn.ReLU",
"torch.nn.Sigmoid",
"torch.nn.Linear",
"torch.nn.Sequential"
]
] |
weapp/numpy | [
"33cc5c6530d48102730b85cdf2835aaf480013ad"
] | [
"numpy/typing/tests/data/reveal/dtype.py"
] | [
"import numpy as np\n\ndtype_obj: np.dtype[np.str_]\n\nreveal_type(np.dtype(np.float64)) # E: numpy.dtype[numpy.floating[numpy.typing._64Bit]]\nreveal_type(np.dtype(np.int64)) # E: numpy.dtype[numpy.signedinteger[numpy.typing._64Bit]]\n\n# String aliases\nreveal_type(np.dtype(\"float64\")) # E: numpy.dtype[numpy.floating[numpy.typing._64Bit]]\nreveal_type(np.dtype(\"float32\")) # E: numpy.dtype[numpy.floating[numpy.typing._32Bit]]\nreveal_type(np.dtype(\"int64\")) # E: numpy.dtype[numpy.signedinteger[numpy.typing._64Bit]]\nreveal_type(np.dtype(\"int32\")) # E: numpy.dtype[numpy.signedinteger[numpy.typing._32Bit]]\nreveal_type(np.dtype(\"bool\")) # E: numpy.dtype[numpy.bool_]\nreveal_type(np.dtype(\"bytes\")) # E: numpy.dtype[numpy.bytes_]\nreveal_type(np.dtype(\"str\")) # E: numpy.dtype[numpy.str_]\n\n# Python types\nreveal_type(np.dtype(complex)) # E: numpy.dtype[numpy.complexfloating[numpy.typing._\nreveal_type(np.dtype(float)) # E: numpy.dtype[numpy.floating[numpy.typing._\nreveal_type(np.dtype(int)) # E: numpy.dtype[numpy.signedinteger[numpy.typing._\nreveal_type(np.dtype(bool)) # E: numpy.dtype[numpy.bool_]\nreveal_type(np.dtype(str)) # E: numpy.dtype[numpy.str_]\nreveal_type(np.dtype(bytes)) # E: numpy.dtype[numpy.bytes_]\n\n# Special case for None\nreveal_type(np.dtype(None)) # E: numpy.dtype[numpy.floating[numpy.typing._\n\n# Dtypes of dtypes\nreveal_type(np.dtype(np.dtype(np.float64))) # E: numpy.dtype[numpy.floating[numpy.typing._64Bit]]\n\n# Parameterized dtypes\nreveal_type(np.dtype(\"S8\")) # E: numpy.dtype\n\n# Void\nreveal_type(np.dtype((\"U\", 10))) # E: numpy.dtype[numpy.void]\n\n# Methods and attributes\nreveal_type(dtype_obj.base) # E: numpy.dtype[numpy.str_]\nreveal_type(dtype_obj.subdtype) # E: Union[Tuple[numpy.dtype[numpy.str_], builtins.tuple[builtins.int]], None]\nreveal_type(dtype_obj.newbyteorder()) # E: numpy.dtype[numpy.str_]\nreveal_type(dtype_obj.type) # E: Type[numpy.str_]\n"
] | [
[
"numpy.dtype"
]
] |
irfanumar1994/pytorch-transformers | [
"f257b96a879e38922eaa377be383be69372e78f1"
] | [
"pytorch_transformers/modeling_bert.py"
] | [
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. 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\"\"\"PyTorch BERT model. \"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport json\nimport logging\nimport math\nimport os\nimport sys\nfrom io import open\n\nimport torch\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss, MSELoss\n\nfrom .modeling_utils import PreTrainedModel, prune_linear_layer\nfrom .configuration_bert import BertConfig\nfrom .file_utils import add_start_docstrings\n\nlogger = logging.getLogger(__name__)\n\nBERT_PRETRAINED_MODEL_ARCHIVE_MAP = {\n 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-pytorch_model.bin\",\n 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-pytorch_model.bin\",\n 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-pytorch_model.bin\",\n 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-pytorch_model.bin\",\n 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-pytorch_model.bin\",\n 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-pytorch_model.bin\",\n 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-pytorch_model.bin\",\n 'bert-base-german-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-cased-pytorch_model.bin\",\n 'bert-large-uncased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-pytorch_model.bin\",\n 'bert-large-cased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-pytorch_model.bin\",\n 'bert-large-uncased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-pytorch_model.bin\",\n 'bert-large-cased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-pytorch_model.bin\",\n 'bert-base-cased-finetuned-mrpc': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-pytorch_model.bin\",\n}\n\ndef load_tf_weights_in_bert(model, config, tf_checkpoint_path):\n \"\"\" Load tf checkpoints in a pytorch model.\n \"\"\"\n try:\n import re\n import numpy as np\n import tensorflow as tf\n except ImportError:\n logger.error(\"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see \"\n \"https://www.tensorflow.org/install/ for installation instructions.\")\n raise\n tf_path = os.path.abspath(tf_checkpoint_path)\n logger.info(\"Converting TensorFlow checkpoint from {}\".format(tf_path))\n # Load weights from TF model\n init_vars = tf.train.list_variables(tf_path)\n names = []\n arrays = []\n for name, shape in init_vars:\n logger.info(\"Loading TF weight {} with shape {}\".format(name, shape))\n array = tf.train.load_variable(tf_path, name)\n names.append(name)\n arrays.append(array)\n\n for name, array in zip(names, arrays):\n name = name.split('/')\n # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v\n # which are not required for using pretrained model\n if any(n in [\"adam_v\", \"adam_m\", \"global_step\"] for n in name):\n logger.info(\"Skipping {}\".format(\"/\".join(name)))\n continue\n pointer = model\n for m_name in name:\n if re.fullmatch(r'[A-Za-z]+_\\d+', m_name):\n l = re.split(r'_(\\d+)', m_name)\n else:\n l = [m_name]\n if l[0] == 'kernel' or l[0] == 'gamma':\n pointer = getattr(pointer, 'weight')\n elif l[0] == 'output_bias' or l[0] == 'beta':\n pointer = getattr(pointer, 'bias')\n elif l[0] == 'output_weights':\n pointer = getattr(pointer, 'weight')\n elif l[0] == 'squad':\n pointer = getattr(pointer, 'classifier')\n else:\n try:\n pointer = getattr(pointer, l[0])\n except AttributeError:\n logger.info(\"Skipping {}\".format(\"/\".join(name)))\n continue\n if len(l) >= 2:\n num = int(l[1])\n pointer = pointer[num]\n if m_name[-11:] == '_embeddings':\n pointer = getattr(pointer, 'weight')\n elif m_name == 'kernel':\n array = np.transpose(array)\n try:\n assert pointer.shape == array.shape\n except AssertionError as e:\n e.args += (pointer.shape, array.shape)\n raise\n logger.info(\"Initialize PyTorch weight {}\".format(name))\n pointer.data = torch.from_numpy(array)\n return model\n\n\ndef gelu(x):\n \"\"\"Implementation of the gelu activation function.\n For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):\n 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n Also see https://arxiv.org/abs/1606.08415\n \"\"\"\n return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))\n\n\ndef swish(x):\n return x * torch.sigmoid(x)\n\ndef get_weighted_loss(loss_fct, inputs, labels, weights):\n loss = 0.0\n for i in range(weights.shape[0]):\n loss += (weights[i] + 1.0) * loss_fct(inputs[i:i + 1], labels[i:i + 1])\n\n return loss / (sum(weights) + weights.shape[0])\n\nACT2FN = {\"gelu\": gelu, \"relu\": torch.nn.functional.relu, \"swish\": swish}\n\n\ntry:\n from apex.normalization.fused_layer_norm import FusedLayerNorm as BertLayerNorm\nexcept (ImportError, AttributeError) as e:\n logger.info(\"Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex .\")\n BertLayerNorm = torch.nn.LayerNorm\n\nclass BertEmbeddings(nn.Module):\n \"\"\"Construct the embeddings from word, position and token_type embeddings.\n \"\"\"\n def __init__(self, config):\n super(BertEmbeddings, self).__init__()\n self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=0)\n self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)\n self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)\n\n # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load\n # any TensorFlow checkpoint file\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, input_ids, token_type_ids=None, position_ids=None):\n seq_length = input_ids.size(1)\n if position_ids is None:\n position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)\n position_ids = position_ids.unsqueeze(0).expand_as(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n words_embeddings = self.word_embeddings(input_ids)\n position_embeddings = self.position_embeddings(position_ids)\n token_type_embeddings = self.token_type_embeddings(token_type_ids)\n\n embeddings = words_embeddings + position_embeddings + token_type_embeddings\n embeddings = self.LayerNorm(embeddings)\n embeddings = self.dropout(embeddings)\n return embeddings\n\n\nclass BertSelfAttention(nn.Module):\n def __init__(self, config):\n super(BertSelfAttention, self).__init__()\n if config.hidden_size % config.num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (config.hidden_size, config.num_attention_heads))\n self.output_attentions = config.output_attentions\n\n self.num_attention_heads = config.num_attention_heads\n self.attention_head_size = int(config.hidden_size / config.num_attention_heads)\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n\n self.query = nn.Linear(config.hidden_size, self.all_head_size)\n self.key = nn.Linear(config.hidden_size, self.all_head_size)\n self.value = nn.Linear(config.hidden_size, self.all_head_size)\n\n self.dropout = nn.Dropout(config.attention_probs_dropout_prob)\n\n def transpose_for_scores(self, x):\n new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)\n x = x.view(*new_x_shape)\n return x.permute(0, 2, 1, 3)\n\n def forward(self, hidden_states, attention_mask, head_mask=None):\n mixed_query_layer = self.query(hidden_states)\n mixed_key_layer = self.key(hidden_states)\n mixed_value_layer = self.value(hidden_states)\n\n query_layer = self.transpose_for_scores(mixed_query_layer)\n key_layer = self.transpose_for_scores(mixed_key_layer)\n value_layer = self.transpose_for_scores(mixed_value_layer)\n\n # Take the dot product between \"query\" and \"key\" to get the raw attention scores.\n attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))\n attention_scores = attention_scores / math.sqrt(self.attention_head_size)\n # Apply the attention mask is (precomputed for all layers in BertModel forward() function)\n attention_scores = attention_scores + attention_mask\n\n # Normalize the attention scores to probabilities.\n attention_probs = nn.Softmax(dim=-1)(attention_scores)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n attention_probs = self.dropout(attention_probs)\n\n # Mask heads if we want to\n if head_mask is not None:\n attention_probs = attention_probs * head_mask\n\n context_layer = torch.matmul(attention_probs, value_layer)\n\n context_layer = context_layer.permute(0, 2, 1, 3).contiguous()\n new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)\n context_layer = context_layer.view(*new_context_layer_shape)\n\n outputs = (context_layer, attention_probs) if self.output_attentions else (context_layer,)\n return outputs\n\n\nclass BertSelfOutput(nn.Module):\n def __init__(self, config):\n super(BertSelfOutput, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertAttention(nn.Module):\n def __init__(self, config):\n super(BertAttention, self).__init__()\n self.self = BertSelfAttention(config)\n self.output = BertSelfOutput(config)\n self.pruned_heads = set()\n\n def prune_heads(self, heads):\n if len(heads) == 0:\n return\n mask = torch.ones(self.self.num_attention_heads, self.self.attention_head_size)\n heads = set(heads) - self.pruned_heads # Convert to set and emove already pruned heads\n for head in heads:\n # Compute how many pruned heads are before the head and move the index accordingly\n head = head - sum(1 if h < head else 0 for h in self.pruned_heads)\n mask[head] = 0\n mask = mask.view(-1).contiguous().eq(1)\n index = torch.arange(len(mask))[mask].long()\n\n # Prune linear layers\n self.self.query = prune_linear_layer(self.self.query, index)\n self.self.key = prune_linear_layer(self.self.key, index)\n self.self.value = prune_linear_layer(self.self.value, index)\n self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)\n\n # Update hyper params and store pruned heads\n self.self.num_attention_heads = self.self.num_attention_heads - len(heads)\n self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads\n self.pruned_heads = self.pruned_heads.union(heads)\n\n def forward(self, input_tensor, attention_mask, head_mask=None):\n self_outputs = self.self(input_tensor, attention_mask, head_mask)\n attention_output = self.output(self_outputs[0], input_tensor)\n outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them\n return outputs\n\n\nclass BertIntermediate(nn.Module):\n def __init__(self, config):\n super(BertIntermediate, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.intermediate_size)\n if isinstance(config.hidden_act, str) or (sys.version_info[0] == 2 and isinstance(config.hidden_act, unicode)):\n self.intermediate_act_fn = ACT2FN[config.hidden_act]\n else:\n self.intermediate_act_fn = config.hidden_act\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n return hidden_states\n\n\nclass BertOutput(nn.Module):\n def __init__(self, config):\n super(BertOutput, self).__init__()\n self.dense = nn.Linear(config.intermediate_size, config.hidden_size)\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertLayer(nn.Module):\n def __init__(self, config):\n super(BertLayer, self).__init__()\n self.attention = BertAttention(config)\n self.intermediate = BertIntermediate(config)\n self.output = BertOutput(config)\n\n def forward(self, hidden_states, attention_mask, head_mask=None):\n attention_outputs = self.attention(hidden_states, attention_mask, head_mask)\n attention_output = attention_outputs[0]\n intermediate_output = self.intermediate(attention_output)\n layer_output = self.output(intermediate_output, attention_output)\n outputs = (layer_output,) + attention_outputs[1:] # add attentions if we output them\n return outputs\n\n\nclass BertEncoder(nn.Module):\n def __init__(self, config):\n super(BertEncoder, self).__init__()\n self.output_attentions = config.output_attentions\n self.output_hidden_states = config.output_hidden_states\n self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])\n\n def forward(self, hidden_states, attention_mask, head_mask=None):\n all_hidden_states = ()\n all_attentions = ()\n for i, layer_module in enumerate(self.layer):\n if self.output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n layer_outputs = layer_module(hidden_states, attention_mask, head_mask[i])\n hidden_states = layer_outputs[0]\n\n if self.output_attentions:\n all_attentions = all_attentions + (layer_outputs[1],)\n\n # Add last layer\n if self.output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n outputs = (hidden_states,)\n if self.output_hidden_states:\n outputs = outputs + (all_hidden_states,)\n if self.output_attentions:\n outputs = outputs + (all_attentions,)\n return outputs # last-layer hidden state, (all hidden states), (all attentions)\n\n\nclass BertPooler(nn.Module):\n def __init__(self, config):\n super(BertPooler, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.activation = nn.Tanh()\n\n def forward(self, hidden_states):\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token.\n first_token_tensor = hidden_states[:, 0]\n pooled_output = self.dense(first_token_tensor)\n pooled_output = self.activation(pooled_output)\n return pooled_output\n\n\nclass BertPredictionHeadTransform(nn.Module):\n def __init__(self, config):\n super(BertPredictionHeadTransform, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n if isinstance(config.hidden_act, str) or (sys.version_info[0] == 2 and isinstance(config.hidden_act, unicode)):\n self.transform_act_fn = ACT2FN[config.hidden_act]\n else:\n self.transform_act_fn = config.hidden_act\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.transform_act_fn(hidden_states)\n hidden_states = self.LayerNorm(hidden_states)\n return hidden_states\n\n\nclass BertLMPredictionHead(nn.Module):\n def __init__(self, config):\n super(BertLMPredictionHead, self).__init__()\n self.transform = BertPredictionHeadTransform(config)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(config.hidden_size,\n config.vocab_size,\n bias=False)\n\n self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states) + self.bias\n return hidden_states\n\n\nclass BertOnlyMLMHead(nn.Module):\n def __init__(self, config):\n super(BertOnlyMLMHead, self).__init__()\n self.predictions = BertLMPredictionHead(config)\n\n def forward(self, sequence_output):\n prediction_scores = self.predictions(sequence_output)\n return prediction_scores\n\n\nclass BertOnlyNSPHead(nn.Module):\n def __init__(self, config):\n super(BertOnlyNSPHead, self).__init__()\n self.seq_relationship = nn.Linear(config.hidden_size, 2)\n\n def forward(self, pooled_output):\n seq_relationship_score = self.seq_relationship(pooled_output)\n return seq_relationship_score\n\n\nclass BertPreTrainingHeads(nn.Module):\n def __init__(self, config):\n super(BertPreTrainingHeads, self).__init__()\n self.predictions = BertLMPredictionHead(config)\n self.seq_relationship = nn.Linear(config.hidden_size, 2)\n\n def forward(self, sequence_output, pooled_output):\n prediction_scores = self.predictions(sequence_output)\n seq_relationship_score = self.seq_relationship(pooled_output)\n return prediction_scores, seq_relationship_score\n\n\nclass BertPreTrainedModel(PreTrainedModel):\n \"\"\" An abstract class to handle weights initialization and\n a simple interface for dowloading and loading pretrained models.\n \"\"\"\n config_class = BertConfig\n pretrained_model_archive_map = BERT_PRETRAINED_MODEL_ARCHIVE_MAP\n load_tf_weights = load_tf_weights_in_bert\n base_model_prefix = \"bert\"\n\n def _init_weights(self, module):\n \"\"\" Initialize the weights \"\"\"\n if isinstance(module, (nn.Linear, nn.Embedding)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n elif isinstance(module, BertLayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n\nBERT_START_DOCSTRING = r\"\"\" The BERT model was proposed in\n `BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding`_\n by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova. It's a bidirectional transformer\n pre-trained using a combination of masked language modeling objective and next sentence prediction\n on a large corpus comprising the Toronto Book Corpus and Wikipedia.\n\n This model is a PyTorch `torch.nn.Module`_ sub-class. Use it as a regular PyTorch Module and\n refer to the PyTorch documentation for all matter related to general usage and behavior.\n\n .. _`BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding`:\n https://arxiv.org/abs/1810.04805\n\n .. _`torch.nn.Module`:\n https://pytorch.org/docs/stable/nn.html#module\n\n Parameters:\n config (:class:`~pytorch_transformers.BertConfig`): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the configuration.\n Check out the :meth:`~pytorch_transformers.PreTrainedModel.from_pretrained` method to load the model weights.\n\"\"\"\n\nBERT_INPUTS_DOCSTRING = r\"\"\"\n Inputs:\n **input_ids**: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Indices of input sequence tokens in the vocabulary.\n To match pre-training, BERT input sequence should be formatted with [CLS] and [SEP] tokens as follows:\n\n (a) For sequence pairs:\n\n ``tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]``\n\n ``token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1``\n\n (b) For single sequences:\n\n ``tokens: [CLS] the dog is hairy . [SEP]``\n\n ``token_type_ids: 0 0 0 0 0 0 0``\n\n Bert is a model with absolute position embeddings so it's usually advised to pad the inputs on\n the right rather than the left.\n\n Indices can be obtained using :class:`pytorch_transformers.BertTokenizer`.\n See :func:`pytorch_transformers.PreTrainedTokenizer.encode` and\n :func:`pytorch_transformers.PreTrainedTokenizer.convert_tokens_to_ids` for details.\n **attention_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, sequence_length)``:\n Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n **token_type_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Segment token indices to indicate first and second portions of the inputs.\n Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1``\n corresponds to a `sentence B` token\n (see `BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding`_ for more details).\n **position_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Indices of positions of each input sequence tokens in the position embeddings.\n Selected in the range ``[0, config.max_position_embeddings - 1]``.\n **head_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(num_heads,)`` or ``(num_layers, num_heads)``:\n Mask to nullify selected heads of the self-attention modules.\n Mask values selected in ``[0, 1]``:\n ``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**.\n\"\"\"\n\n@add_start_docstrings(\"The bare Bert Model transformer outputing raw hidden-states without any specific head on top.\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertModel(BertPreTrainedModel):\n r\"\"\"\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)``\n Sequence of hidden-states at the output of the last layer of the model.\n **pooler_output**: ``torch.FloatTensor`` of shape ``(batch_size, hidden_size)``\n Last layer hidden-state of the first token of the sequence (classification token)\n further processed by a Linear layer and a Tanh activation function. The Linear\n layer weights are trained from the next sentence prediction (classification)\n objective during Bert pretraining. This output is usually *not* a good summary\n of the semantic content of the input, you're often better with averaging or pooling\n the sequence of hidden-states for the whole input sequence.\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n model = BertModel.from_pretrained('bert-base-uncased')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n outputs = model(input_ids)\n last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple\n\n \"\"\"\n def __init__(self, config):\n super(BertModel, self).__init__(config)\n\n self.embeddings = BertEmbeddings(config)\n self.encoder = BertEncoder(config)\n self.pooler = BertPooler(config)\n\n self.init_weights()\n\n def _resize_token_embeddings(self, new_num_tokens):\n old_embeddings = self.embeddings.word_embeddings\n new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens)\n self.embeddings.word_embeddings = new_embeddings\n return self.embeddings.word_embeddings\n\n def _prune_heads(self, heads_to_prune):\n \"\"\" Prunes heads of the model.\n heads_to_prune: dict of {layer_num: list of heads to prune in this layer}\n See base class PreTrainedModel\n \"\"\"\n for layer, heads in heads_to_prune.items():\n self.encoder.layer[layer].attention.prune_heads(heads)\n\n def forward(self, input_ids, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None):\n if attention_mask is None:\n attention_mask = torch.ones_like(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, to_seq_length]\n # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]\n # this attention mask is more simple than the triangular masking of causal attention\n # used in OpenAI GPT, we just need to prepare the broadcast dimension here.\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n\n # Prepare head mask if needed\n # 1.0 in head_mask indicate we keep the head\n # attention_probs has shape bsz x n_heads x N x N\n # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]\n # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]\n if head_mask is not None:\n if head_mask.dim() == 1:\n head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)\n head_mask = head_mask.expand(self.config.num_hidden_layers, -1, -1, -1, -1)\n elif head_mask.dim() == 2:\n head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1) # We can specify head_mask for each layer\n head_mask = head_mask.to(dtype=next(self.parameters()).dtype) # switch to fload if need + fp16 compatibility\n else:\n head_mask = [None] * self.config.num_hidden_layers\n\n embedding_output = self.embeddings(input_ids, position_ids=position_ids, token_type_ids=token_type_ids)\n encoder_outputs = self.encoder(embedding_output,\n extended_attention_mask,\n head_mask=head_mask)\n sequence_output = encoder_outputs[0]\n pooled_output = self.pooler(sequence_output)\n\n outputs = (sequence_output, pooled_output,) + encoder_outputs[1:] # add hidden_states and attentions if they are here\n return outputs # sequence_output, pooled_output, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model with two heads on top as done during the pre-training:\n a `masked language modeling` head and a `next sentence prediction (classification)` head. \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForPreTraining(BertPreTrainedModel):\n r\"\"\"\n **masked_lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Labels for computing the masked language modeling loss.\n Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)\n Tokens with indices set to ``-1`` are ignored (masked), the loss is only computed for the tokens with labels\n in ``[0, ..., config.vocab_size]``\n **next_sentence_label**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see ``input_ids`` docstring)\n Indices should be in ``[0, 1]``.\n ``0`` indicates sequence B is a continuation of sequence A,\n ``1`` indicates sequence B is a random sequence.\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when both ``masked_lm_labels`` and ``next_sentence_label`` are provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Total loss as the sum of the masked language modeling loss and the next sequence prediction (classification) loss.\n **prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)``\n Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n **seq_relationship_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, 2)``\n Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n model = BertForPreTraining.from_pretrained('bert-base-uncased')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n outputs = model(input_ids)\n prediction_scores, seq_relationship_scores = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(BertForPreTraining, self).__init__(config)\n\n self.bert = BertModel(config)\n self.cls = BertPreTrainingHeads(config)\n\n self.init_weights()\n self.tie_weights()\n\n def tie_weights(self):\n \"\"\" Make sure we are sharing the input and output embeddings.\n Export to TorchScript can't handle parameter sharing so we are cloning them instead.\n \"\"\"\n self._tie_or_clone_weights(self.cls.predictions.decoder,\n self.bert.embeddings.word_embeddings)\n\n def forward(self, input_ids, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None,\n masked_lm_labels=None, next_sentence_label=None):\n\n outputs = self.bert(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask)\n\n sequence_output, pooled_output = outputs[:2]\n prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)\n\n outputs = (prediction_scores, seq_relationship_score,) + outputs[2:] # add hidden states and attention if they are here\n\n if masked_lm_labels is not None and next_sentence_label is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))\n next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))\n total_loss = masked_lm_loss + next_sentence_loss\n outputs = (total_loss,) + outputs\n\n return outputs # (loss), prediction_scores, seq_relationship_score, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model with a `language modeling` head on top. \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForMaskedLM(BertPreTrainedModel):\n r\"\"\"\n **masked_lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Labels for computing the masked language modeling loss.\n Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)\n Tokens with indices set to ``-1`` are ignored (masked), the loss is only computed for the tokens with labels\n in ``[0, ..., config.vocab_size]``\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Masked language modeling loss.\n **prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)``\n Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n model = BertForMaskedLM.from_pretrained('bert-base-uncased')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n outputs = model(input_ids, masked_lm_labels=input_ids)\n loss, prediction_scores = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(BertForMaskedLM, self).__init__(config)\n\n self.bert = BertModel(config)\n self.cls = BertOnlyMLMHead(config)\n\n self.init_weights()\n self.tie_weights()\n\n def tie_weights(self):\n \"\"\" Make sure we are sharing the input and output embeddings.\n Export to TorchScript can't handle parameter sharing so we are cloning them instead.\n \"\"\"\n self._tie_or_clone_weights(self.cls.predictions.decoder,\n self.bert.embeddings.word_embeddings)\n\n def forward(self, input_ids, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None,\n masked_lm_labels=None):\n\n outputs = self.bert(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask)\n\n sequence_output = outputs[0]\n prediction_scores = self.cls(sequence_output)\n\n outputs = (prediction_scores,) + outputs[2:] # Add hidden states and attention if they are here\n if masked_lm_labels is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))\n outputs = (masked_lm_loss,) + outputs\n\n return outputs # (masked_lm_loss), prediction_scores, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model with a `next sentence prediction (classification)` head on top. \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForNextSentencePrediction(BertPreTrainedModel):\n r\"\"\"\n **next_sentence_label**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see ``input_ids`` docstring)\n Indices should be in ``[0, 1]``.\n ``0`` indicates sequence B is a continuation of sequence A,\n ``1`` indicates sequence B is a random sequence.\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``next_sentence_label`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Next sequence prediction (classification) loss.\n **seq_relationship_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, 2)``\n Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n model = BertForNextSentencePrediction.from_pretrained('bert-base-uncased')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n outputs = model(input_ids)\n seq_relationship_scores = outputs[0]\n\n \"\"\"\n def __init__(self, config):\n super(BertForNextSentencePrediction, self).__init__(config)\n\n self.bert = BertModel(config)\n self.cls = BertOnlyNSPHead(config)\n\n self.init_weights()\n\n def forward(self, input_ids, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None,\n next_sentence_label=None):\n\n outputs = self.bert(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask)\n\n pooled_output = outputs[1]\n\n seq_relationship_score = self.cls(pooled_output)\n\n outputs = (seq_relationship_score,) + outputs[2:] # add hidden states and attention if they are here\n if next_sentence_label is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))\n outputs = (next_sentence_loss,) + outputs\n\n return outputs # (next_sentence_loss), seq_relationship_score, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForSequenceClassification(BertPreTrainedModel):\n r\"\"\"\n **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for computing the sequence classification/regression loss.\n Indices should be in ``[0, ..., config.num_labels - 1]``.\n If ``config.num_labels == 1`` a regression loss is computed (Mean-Square loss),\n If ``config.num_labels > 1`` a classification loss is computed (Cross-Entropy).\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Classification (or regression if config.num_labels==1) loss.\n **logits**: ``torch.FloatTensor`` of shape ``(batch_size, config.num_labels)``\n Classification (or regression if config.num_labels==1) scores (before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n model = BertForSequenceClassification.from_pretrained('bert-base-uncased')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n labels = torch.tensor([1]).unsqueeze(0) # Batch size 1\n outputs = model(input_ids, labels=labels)\n loss, logits = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(BertForSequenceClassification, self).__init__(config)\n self.num_labels = config.num_labels\n\n self.bert = BertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)\n\n self.init_weights()\n\n def forward(self, input_ids, attention_mask=None, token_type_ids=None,\n position_ids=None, head_mask=None, labels=None, weights=None):\n\n outputs = self.bert(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask)\n\n pooled_output = outputs[1]\n\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output)\n\n outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here\n\n if labels is not None:\n if self.num_labels == 1:\n # We are doing regression\n loss_fct = MSELoss()\n loss = loss_fct(logits.view(-1), labels.view(-1))\n else:\n loss_fct = CrossEntropyLoss()\n if weights is None:\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n else:\n loss = get_weighted_loss(loss_fct,\n logits.view(-1, self.num_labels),\n labels.view(-1), weights)\n outputs = (loss,) + outputs\n\n return outputs # (loss), logits, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model with a multiple choice classification head on top (a linear layer on top of\n the pooled output and a softmax) e.g. for RocStories/SWAG tasks. \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForMultipleChoice(BertPreTrainedModel):\n r\"\"\"\n **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for computing the multiple choice classification loss.\n Indices should be in ``[0, ..., num_choices]`` where `num_choices` is the size of the second dimension\n of the input tensors. (see `input_ids` above)\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Classification loss.\n **classification_scores**: ``torch.FloatTensor`` of shape ``(batch_size, num_choices)`` where `num_choices` is the size of the second dimension\n of the input tensors. (see `input_ids` above).\n Classification scores (before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n model = BertForMultipleChoice.from_pretrained('bert-base-uncased')\n choices = [\"Hello, my dog is cute\", \"Hello, my cat is amazing\"]\n input_ids = torch.tensor([tokenizer.encode(s) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices\n labels = torch.tensor(1).unsqueeze(0) # Batch size 1\n outputs = model(input_ids, labels=labels)\n loss, classification_scores = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(BertForMultipleChoice, self).__init__(config)\n\n self.bert = BertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, 1)\n\n self.init_weights()\n\n def forward(self, input_ids, attention_mask=None, token_type_ids=None,\n position_ids=None, head_mask=None, labels=None):\n num_choices = input_ids.shape[1]\n\n input_ids = input_ids.view(-1, input_ids.size(-1))\n attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None\n token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None\n position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None\n\n outputs = self.bert(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask)\n\n pooled_output = outputs[1]\n\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output)\n reshaped_logits = logits.view(-1, num_choices)\n\n outputs = (reshaped_logits,) + outputs[2:] # add hidden states and attention if they are here\n\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(reshaped_logits, labels)\n outputs = (loss,) + outputs\n\n return outputs # (loss), reshaped_logits, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model with a token classification head on top (a linear layer on top of\n the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForTokenClassification(BertPreTrainedModel):\n r\"\"\"\n **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Labels for computing the token classification loss.\n Indices should be in ``[0, ..., config.num_labels - 1]``.\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Classification loss.\n **scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.num_labels)``\n Classification scores (before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n model = BertForTokenClassification.from_pretrained('bert-base-uncased')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n labels = torch.tensor([1] * input_ids.size(1)).unsqueeze(0) # Batch size 1\n outputs = model(input_ids, labels=labels)\n loss, scores = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(BertForTokenClassification, self).__init__(config)\n self.num_labels = config.num_labels\n\n self.bert = BertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n\n self.init_weights()\n\n def forward(self, input_ids, attention_mask=None, token_type_ids=None,\n position_ids=None, head_mask=None, labels=None):\n\n outputs = self.bert(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask)\n\n sequence_output = outputs[0]\n\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n\n outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n # Only keep active parts of the loss\n if attention_mask is not None:\n active_loss = attention_mask.view(-1) == 1\n active_logits = logits.view(-1, self.num_labels)[active_loss]\n active_labels = labels.view(-1)[active_loss]\n loss = loss_fct(active_logits, active_labels)\n else:\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n outputs = (loss,) + outputs\n\n return outputs # (loss), scores, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of\n the hidden-states output to compute `span start logits` and `span end logits`). \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForQuestionAnswering(BertPreTrainedModel):\n r\"\"\"\n **start_positions**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`).\n Position outside of the sequence are not taken into account for computing the loss.\n **end_positions**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`).\n Position outside of the sequence are not taken into account for computing the loss.\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.\n **start_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length,)``\n Span-start scores (before SoftMax).\n **end_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length,)``\n Span-end scores (before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n model = BertForQuestionAnswering.from_pretrained('bert-base-uncased')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n start_positions = torch.tensor([1])\n end_positions = torch.tensor([3])\n outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)\n loss, start_scores, end_scores = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(BertForQuestionAnswering, self).__init__(config)\n self.num_labels = config.num_labels\n\n self.bert = BertModel(config)\n self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)\n\n self.init_weights()\n\n def forward(self, input_ids, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None,\n start_positions=None, end_positions=None):\n\n outputs = self.bert(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask)\n\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1)\n end_logits = end_logits.squeeze(-1)\n\n outputs = (start_logits, end_logits,) + outputs[2:]\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions.clamp_(0, ignored_index)\n end_positions.clamp_(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n outputs = (total_loss,) + outputs\n\n return outputs # (loss), start_logits, end_logits, (hidden_states), (attentions)\n"
] | [
[
"torch.ones_like",
"torch.ones",
"torch.nn.Linear",
"numpy.transpose",
"torch.nn.MSELoss",
"tensorflow.train.list_variables",
"torch.zeros_like",
"torch.nn.Softmax",
"torch.nn.Embedding",
"torch.nn.Tanh",
"torch.nn.CrossEntropyLoss",
"torch.from_numpy",
"torch.arange",
"torch.zeros",
"tensorflow.train.load_variable",
"torch.sigmoid",
"torch.nn.Dropout",
"torch.matmul"
]
] |
eladyaniv01/sc2-pathlib | [
"ae1737af0dd3d418016941dcb4ac30bcfb36726f"
] | [
"sc2pathlibp/path_finder.py"
] | [
"from .sc2pathlib import PathFind\n\n# from . import _sc2pathlib\n# import sc2pathlib\nimport numpy as np\nfrom typing import Union, List, Tuple\nfrom math import floor\n\n\ndef to_float2(original: Tuple[int, int]) -> Tuple[float, float]:\n return (original[0] + 0.5, original[1] + 0.5)\n\n\nclass PathFinder:\n def __init__(self, maze: Union[List[List[int]], np.array]):\n \"\"\" \n pathing values need to be integers to improve performance. \n Initialization should be done with array consisting values of 0 and 1.\n \"\"\"\n self._path_find = PathFind(maze)\n self.heuristic_accuracy = 1 # Octile distance\n\n def normalize_influence(self, value: int):\n \"\"\" \n Normalizes influence to integral value. \n Influence does not need to be calculated each frame, but this quickly resets\n influence values to specified value without changing available paths.\n \"\"\"\n self._path_find.normalize_influence(value)\n\n @property\n def width(self) -> int:\n \"\"\"\n :return: Width of the defined map\n \"\"\"\n return self._path_find.width\n\n @property\n def height(self) -> int:\n \"\"\"\n :return: Height of the defined map\n \"\"\"\n return self._path_find.height\n\n @property\n def map(self) -> List[List[int]]:\n \"\"\"\n :return: map as list of lists [x][y] in python readable format\n \"\"\"\n return self._path_find.map\n\n def reset(self):\n \"\"\"\n Reset the pathfind map data to it's original state\n \"\"\"\n self._path_find.reset()\n\n def set_map(self, data: List[List[int]]):\n self._path_find.map = data\n\n def create_block(self, center: Union[Tuple[float, float], List[Tuple[float, float]]], size: Tuple[int, int]):\n if isinstance(center, list):\n self._path_find.create_blocks(center, size)\n else:\n self._path_find.create_block(center, size)\n\n def remove_block(self, center: Union[Tuple[float, float], List[Tuple[float, float]]], size: Tuple[int, int]):\n if isinstance(center, list):\n self._path_find.remove_blocks(center, size)\n else:\n self._path_find.remove_block(center, size)\n\n def find_path(\n self, start: (float, float), end: (float, float), large: bool = False\n ) -> Tuple[List[Tuple[int, int]], float]:\n \"\"\"\n Finds a path ignoring influence.\n\n :param start: Start position in float tuple\n :param end: Start position in float tuple\n :param large: Unit is large and requires path to have width of 2 to pass\n :return: Tuple of points and total distance.\n \"\"\"\n start_int = (floor(start[0]), floor(start[1]))\n end_int = (floor(end[0]), floor(end[1]))\n if large:\n return self._path_find.find_path_large(start_int, end_int, self.heuristic_accuracy)\n return self._path_find.find_path(start_int, end_int, self.heuristic_accuracy)\n\n def find_path_influence(\n self, start: (float, float), end: (float, float), large: bool = False\n ) -> (List[Tuple[int, int]], float):\n \"\"\"\n Finds a path that takes influence into account\n\n :param start: Start position in float tuple\n :param end: Start position in float tuple\n :param large: Unit is large and requires path to have width of 2 to pass\n :return: Tuple of points and total distance including influence.\n \"\"\"\n start_int = (floor(start[0]), floor(start[1]))\n end_int = (floor(end[0]), floor(end[1]))\n if large:\n return self._path_find.find_path_influence_large(start_int, end_int, self.heuristic_accuracy)\n return self._path_find.find_path_influence(start_int, end_int, self.heuristic_accuracy)\n\n def safest_spot(self, destination_center: (float, float), walk_distance: float) -> (Tuple[int, int], float):\n destination_int = (floor(destination_center[0]), floor(destination_center[1]))\n return self._path_find.lowest_influence_walk(destination_int, walk_distance)\n\n def lowest_influence_in_grid(self, destination_center: (float, float), radius: int) -> (Tuple[int, int], float):\n destination_int = (floor(destination_center[0]), floor(destination_center[1]))\n return self._path_find.lowest_influence(destination_int, radius)\n\n def add_influence(self, points: List[Tuple[float, float]], value: float, distance: float, flat: bool = False):\n list = []\n for point in points:\n list.append((floor(point[0]), floor(point[1])))\n\n if flat:\n self._path_find.add_influence_flat(list, value, distance)\n else:\n self._path_find.add_influence(list, value, distance)\n\n def add_influence_walk(self, points: List[Tuple[float, float]], value: float, distance: float, flat: bool = False):\n list = []\n for point in points:\n list.append((floor(point[0]), floor(point[1])))\n\n if flat:\n self._path_find.add_walk_influence_flat(list, value, distance)\n else:\n self._path_find.add_walk_influence(list, value, distance)\n\n def find_low_inside_walk(\n self, start: (float, float), target: (float, float), distance: Union[int, float]\n ) -> (Tuple[float, float], float):\n \"\"\"\n Finds a compromise where low influence matches with close position to the start position.\n\n This is intended for finding optimal position for unit with more range to find optimal position to fight from\n :param start: This is the starting position of the unit with more range\n :param target: Target that the optimal position should be optimized for\n :param distance: This should represent the firing distance of the unit with more range\n :return: Tuple for position and influence distance to reach the destination\n \"\"\"\n # start_int = (floor(start[0]), floor(start[1]))\n # target_int = (floor(target[0]), floor(target[1]))\n return self._path_find.find_low_inside_walk(start, target, distance)\n\n def plot(self, path: List[Tuple[int, int]], image_name: str = \"map\", resize: int = 4):\n \"\"\"\n Uses cv2 to draw current pathing grid.\n \n requires opencv-python\n\n :param path: list of points to colorize\n :param image_name: name of the window to show the image in. Unique names update only when used multiple times.\n :param resize: multiplier for resizing the image\n :return: None\n \"\"\"\n import cv2\n\n image = np.array(self._path_find.map, dtype=np.uint8)\n for point in path:\n image[point] = 255\n image = np.rot90(image, 1)\n resized = cv2.resize(image, dsize=None, fx=resize, fy=resize)\n cv2.imshow(image_name, resized)\n cv2.waitKey(1)\n"
] | [
[
"numpy.array",
"numpy.rot90"
]
] |
videetparekh/model-zoo-models | [
"431d6e8f04c343a2e6dbc140e1b060cc5f0a089d"
] | [
"ssd_mobilenetv2/Evaluator.py"
] | [
"import sys\nfrom collections import Counter\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom eval_utils import *\n\n\nclass Evaluator:\n def GetPascalVOCMetrics(self,\n boundingboxes,\n IOUThreshold=0.5,\n method=MethodAveragePrecision.EveryPointInterpolation):\n \"\"\"Get the metrics used by the VOC Pascal 2012 challenge.\n Get\n Args:\n boundingboxes: Object of the class BoundingBoxes representing ground truth and detected\n bounding boxes;\n IOUThreshold: IOU threshold indicating which detections will be considered TP or FP\n (default value = 0.5);\n method (default = EveryPointInterpolation): It can be calculated as the implementation\n in the official PASCAL VOC toolkit (EveryPointInterpolation), or applying the 11-point\n interpolatio as described in the paper \"The PASCAL Visual Object Classes(VOC) Challenge\"\n or EveryPointInterpolation\" (ElevenPointInterpolation);\n Returns:\n A list of dictionaries. Each dictionary contains information and metrics of each class.\n The keys of each dictionary are:\n dict['class']: class representing the current dictionary;\n dict['precision']: array with the precision values;\n dict['recall']: array with the recall values;\n dict['AP']: average precision;\n dict['interpolated precision']: interpolated precision values;\n dict['interpolated recall']: interpolated recall values;\n dict['total positives']: total number of ground truth positives;\n dict['total TP']: total number of True Positive detections;\n dict['total FP']: total number of False Negative detections;\n \"\"\"\n ret = [] # list containing metrics (precision, recall, average precision) of each class\n # List with all ground truths (Ex: [imageName,class,confidence=1, (bb coordinates XYX2Y2)])\n groundTruths = []\n # List with all detections (Ex: [imageName,class,confidence,(bb coordinates XYX2Y2)])\n detections = []\n # Get all classes\n classes = []\n # Loop through all bounding boxes and separate them into GTs and detections\n for bb in boundingboxes.getBoundingBoxes():\n # [imageName, class, confidence, (bb coordinates XYX2Y2)]\n if bb.getBBType() == BBType.GroundTruth:\n groundTruths.append([\n bb.getImageName(),\n bb.getClassId(), 1,\n bb.getAbsoluteBoundingBox(BBFormat.XYX2Y2)\n ])\n else:\n detections.append([\n bb.getImageName(),\n bb.getClassId(),\n bb.getConfidence(),\n bb.getAbsoluteBoundingBox(BBFormat.XYX2Y2)\n ])\n # get class\n if bb.getClassId() not in classes:\n classes.append(bb.getClassId())\n classes = sorted(classes)\n # Precision x Recall is obtained individually by each class\n # Loop through by classes\n for c in classes:\n # Get only detection of class c\n dects = []\n [dects.append(d) for d in detections if d[1] == c]\n # Get only ground truths of class c\n gts = []\n [gts.append(g) for g in groundTruths if g[1] == c]\n npos = len(gts)\n # sort detections by decreasing confidence\n dects = sorted(dects, key=lambda conf: conf[2], reverse=True)\n TP = np.zeros(len(dects))\n FP = np.zeros(len(dects))\n # create dictionary with amount of gts for each image\n det = Counter([cc[0] for cc in gts])\n for key, val in det.items():\n det[key] = np.zeros(val)\n # print(\"Evaluating class: %s (%d detections)\" % (str(c), len(dects)))\n # Loop through detections\n for d in range(len(dects)):\n # print('dect %s => %s' % (dects[d][0], dects[d][3],))\n # Find ground truth image\n gt = [gt for gt in gts if gt[0] == dects[d][0]]\n iouMax = sys.float_info.min\n for j in range(len(gt)):\n # print('Ground truth gt => %s' % (gt[j][3],))\n iou = Evaluator.iou(dects[d][3], gt[j][3])\n if iou > iouMax:\n iouMax = iou\n jmax = j\n # Assign detection as true positive/don't care/false positive\n if iouMax >= IOUThreshold:\n if det[dects[d][0]][jmax] == 0:\n TP[d] = 1 # count as true positive\n # print(\"TP\")\n det[dects[d][0]][jmax] = 1 # flag as already 'seen'\n # - A detected \"cat\" is overlaped with a GT \"cat\" with IOU >= IOUThreshold.\n else:\n FP[d] = 1 # count as false positive\n # print(\"FP\")\n # compute precision, recall and average precision\n acc_FP = np.cumsum(FP)\n acc_TP = np.cumsum(TP)\n rec = acc_TP / npos\n prec = np.divide(acc_TP, (acc_FP + acc_TP))\n # Depending on the method, call the right implementation\n if method == MethodAveragePrecision.EveryPointInterpolation:\n [ap, mpre, mrec, ii] = Evaluator.CalculateAveragePrecision(rec, prec)\n else:\n [ap, mpre, mrec, _] = Evaluator.ElevenPointInterpolatedAP(rec, prec)\n # add class result in the dictionary to be returned\n r = {\n 'class': c,\n 'precision': prec,\n 'recall': rec,\n 'AP': ap,\n 'interpolated precision': mpre,\n 'interpolated recall': mrec,\n 'total positives': npos,\n 'total TP': np.sum(TP),\n 'total FP': np.sum(FP)\n }\n ret.append(r)\n return ret\n\n def PlotPrecisionRecallCurve(self,\n classId,\n boundingBoxes,\n IOUThreshold=0.5,\n method=MethodAveragePrecision.EveryPointInterpolation,\n showAP=False,\n showInterpolatedPrecision=False,\n savePath=None,\n showGraphic=True):\n \"\"\"PlotPrecisionRecallCurve\n Plot the Precision x Recall curve for a given class.\n Args:\n classId: The class that will be plot;\n boundingBoxes: Object of the class BoundingBoxes representing ground truth and detected\n bounding boxes;\n IOUThreshold (optional): IOU threshold indicating which detections will be considered\n TP or FP (default value = 0.5);\n method (default = EveryPointInterpolation): It can be calculated as the implementation\n in the official PASCAL VOC toolkit (EveryPointInterpolation), or applying the 11-point\n interpolatio as described in the paper \"The PASCAL Visual Object Classes(VOC) Challenge\"\n or EveryPointInterpolation\" (ElevenPointInterpolation).\n showAP (optional): if True, the average precision value will be shown in the title of\n the graph (default = False);\n showInterpolatedPrecision (optional): if True, it will show in the plot the interpolated\n precision (default = False);\n savePath (optional): if informed, the plot will be saved as an image in this path\n (ex: /home/mywork/ap.png) (default = None);\n showGraphic (optional): if True, the plot will be shown (default = True)\n Returns:\n A dictionary containing information and metric about the class. The keys of the\n dictionary are:\n dict['class']: class representing the current dictionary;\n dict['precision']: array with the precision values;\n dict['recall']: array with the recall values;\n dict['AP']: average precision;\n dict['interpolated precision']: interpolated precision values;\n dict['interpolated recall']: interpolated recall values;\n dict['total positives']: total number of ground truth positives;\n dict['total TP']: total number of True Positive detections;\n dict['total FP']: total number of False Negative detections;\n \"\"\"\n results = self.GetPascalVOCMetrics(boundingBoxes, IOUThreshold, method)\n result = None\n for res in results:\n if res['class'] == classId:\n result = res\n break\n if result is None:\n raise IOError('Error: Class %d could not be found.' % classId)\n\n precision = result['precision']\n recall = result['recall']\n average_precision = result['AP']\n mpre = result['interpolated precision']\n mrec = result['interpolated recall']\n npos = result['total positives']\n total_tp = result['total TP']\n total_fp = result['total FP']\n\n if showInterpolatedPrecision:\n if method == MethodAveragePrecision.EveryPointInterpolation:\n plt.plot(mrec, mpre, '--r', label='Interpolated precision (every point)')\n elif method == MethodAveragePrecision.ElevenPointInterpolation:\n # Uncomment the line below if you want to plot the area\n # plt.plot(mrec, mpre, 'or', label='11-point interpolated precision')\n # Remove duplicates, getting only the highest precision of each recall value\n nrec = []\n nprec = []\n for idx in range(len(mrec)):\n r = mrec[idx]\n if r not in nrec:\n idxEq = np.argwhere(mrec == r)\n nrec.append(r)\n nprec.append(max([mpre[int(id)] for id in idxEq]))\n plt.plot(nrec, nprec, 'or', label='11-point interpolated precision')\n plt.plot(recall, precision, label='Precision')\n plt.xlabel('recall')\n plt.ylabel('precision')\n if showAP:\n ap_str = \"{0:.2f}%\".format(average_precision * 100)\n plt.title('Precision x Recall curve \\nClass: %s, AP: %s' % (str(classId), ap_str))\n # plt.title('Precision x Recall curve \\nClass: %s, AP: %.4f' % (str(classId),\n # average_precision))\n else:\n plt.title('Precision x Recall curve \\nClass: %d' % classId)\n plt.legend(shadow=True)\n plt.grid()\n ############################################################\n # Uncomment the following block to create plot with points #\n ############################################################\n # plt.plot(recall, precision, 'bo')\n # labels = ['R', 'Y', 'J', 'A', 'U', 'C', 'M', 'F', 'D', 'B', 'H', 'P', 'E', 'X', 'N', 'T',\n # 'K', 'Q', 'V', 'I', 'L', 'S', 'G', 'O']\n # dicPosition = {}\n # dicPosition['left_zero'] = (-30,0)\n # dicPosition['left_zero_slight'] = (-30,-10)\n # dicPosition['right_zero'] = (30,0)\n # dicPosition['left_up'] = (-30,20)\n # dicPosition['left_down'] = (-30,-25)\n # dicPosition['right_up'] = (20,20)\n # dicPosition['right_down'] = (20,-20)\n # dicPosition['up_zero'] = (0,30)\n # dicPosition['up_right'] = (0,30)\n # dicPosition['left_zero_long'] = (-60,-2)\n # dicPosition['down_zero'] = (-2,-30)\n # vecPositions = [\n # dicPosition['left_down'],\n # dicPosition['left_zero'],\n # dicPosition['right_zero'],\n # dicPosition['right_zero'], #'R', 'Y', 'J', 'A',\n # dicPosition['left_up'],\n # dicPosition['left_up'],\n # dicPosition['right_up'],\n # dicPosition['left_up'], # 'U', 'C', 'M', 'F',\n # dicPosition['left_zero'],\n # dicPosition['right_up'],\n # dicPosition['right_down'],\n # dicPosition['down_zero'], #'D', 'B', 'H', 'P'\n # dicPosition['left_up'],\n # dicPosition['up_zero'],\n # dicPosition['right_up'],\n # dicPosition['left_up'], # 'E', 'X', 'N', 'T',\n # dicPosition['left_zero'],\n # dicPosition['right_zero'],\n # dicPosition['left_zero_long'],\n # dicPosition['left_zero_slight'], # 'K', 'Q', 'V', 'I',\n # dicPosition['right_down'],\n # dicPosition['left_down'],\n # dicPosition['right_up'],\n # dicPosition['down_zero']\n # ] # 'L', 'S', 'G', 'O'\n # for idx in range(len(labels)):\n # box = dict(boxstyle='round,pad=.5',facecolor='yellow',alpha=0.5)\n # plt.annotate(labels[idx],\n # xy=(recall[idx],precision[idx]), xycoords='data',\n # xytext=vecPositions[idx], textcoords='offset points',\n # arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3\"),\n # bbox=box)\n if savePath is not None:\n plt.savefig(savePath)\n if showGraphic is True:\n plt.show()\n # plt.waitforbuttonpress()\n ret = {}\n ret['class'] = classId\n ret['precision'] = precision\n ret['recall'] = recall\n ret['AP'] = average_precision\n ret['interpolated precision'] = mpre\n ret['interpolated recall'] = mrec\n ret['total positives'] = npos\n ret['total TP'] = total_tp\n ret['total FP'] = total_fp\n return ret\n\n @staticmethod\n def CalculateAveragePrecision(rec, prec):\n mrec = []\n mrec.append(0)\n [mrec.append(e) for e in rec]\n mrec.append(1)\n mpre = []\n mpre.append(0)\n [mpre.append(e) for e in prec]\n mpre.append(0)\n for i in range(len(mpre) - 1, 0, -1):\n mpre[i - 1] = max(mpre[i - 1], mpre[i])\n ii = []\n for i in range(len(mrec) - 1):\n if mrec[1:][i] != mrec[0:-1][i]:\n ii.append(i + 1)\n ap = 0\n for i in ii:\n ap = ap + np.sum((mrec[i] - mrec[i - 1]) * mpre[i])\n # return [ap, mpre[1:len(mpre)-1], mrec[1:len(mpre)-1], ii]\n return [ap, mpre[0:len(mpre) - 1], mrec[0:len(mpre) - 1], ii]\n\n @staticmethod\n # 11-point interpolated average precision\n def ElevenPointInterpolatedAP(rec, prec):\n # def CalculateAveragePrecision2(rec, prec):\n mrec = []\n # mrec.append(0)\n [mrec.append(e) for e in rec]\n # mrec.append(1)\n mpre = []\n # mpre.append(0)\n [mpre.append(e) for e in prec]\n # mpre.append(0)\n recallValues = np.linspace(0, 1, 11)\n recallValues = list(recallValues[::-1])\n rhoInterp = []\n recallValid = []\n # For each recallValues (0, 0.1, 0.2, ... , 1)\n for r in recallValues:\n # Obtain all recall values higher or equal than r\n argGreaterRecalls = np.argwhere(mrec[:-1] >= r)\n pmax = 0\n # If there are recalls above r\n if argGreaterRecalls.size != 0:\n pmax = max(mpre[argGreaterRecalls.min():])\n recallValid.append(r)\n rhoInterp.append(pmax)\n # By definition AP = sum(max(precision whose recall is above r))/11\n ap = sum(rhoInterp) / 11\n # Generating values for the plot\n rvals = []\n rvals.append(recallValid[0])\n [rvals.append(e) for e in recallValid]\n rvals.append(0)\n pvals = []\n pvals.append(0)\n [pvals.append(e) for e in rhoInterp]\n pvals.append(0)\n # rhoInterp = rhoInterp[::-1]\n cc = []\n for i in range(len(rvals)):\n p = (rvals[i], pvals[i - 1])\n if p not in cc:\n cc.append(p)\n p = (rvals[i], pvals[i])\n if p not in cc:\n cc.append(p)\n recallValues = [i[0] for i in cc]\n rhoInterp = [i[1] for i in cc]\n return [ap, rhoInterp, recallValues, None]\n\n # For each detections, calculate IOU with reference\n @staticmethod\n def _getAllIOUs(reference, detections):\n ret = []\n bbReference = reference.getAbsoluteBoundingBox(BBFormat.XYX2Y2)\n # img = np.zeros((200,200,3), np.uint8)\n for d in detections:\n bb = d.getAbsoluteBoundingBox(BBFormat.XYX2Y2)\n iou = Evaluator.iou(bbReference, bb)\n # Show blank image with the bounding boxes\n # img = add_bb_into_image(img, d, color=(255,0,0), thickness=2, label=None)\n # img = add_bb_into_image(img, reference, color=(0,255,0), thickness=2, label=None)\n ret.append((iou, reference, d)) # iou, reference, detection\n # cv2.imshow(\"comparing\",img)\n # cv2.waitKey(0)\n # cv2.destroyWindow(\"comparing\")\n return sorted(ret, key=lambda i: i[0], reverse=True) # sort by iou (from highest to lowest)\n\n @staticmethod\n def iou(boxA, boxB):\n # if boxes dont intersect\n if Evaluator._boxesIntersect(boxA, boxB) is False:\n return 0\n interArea = Evaluator._getIntersectionArea(boxA, boxB)\n union = Evaluator._getUnionAreas(boxA, boxB, interArea=interArea)\n # intersection over union\n iou = interArea / union\n assert iou >= 0\n return iou\n\n # boxA = (Ax1,Ay1,Ax2,Ay2)\n # boxB = (Bx1,By1,Bx2,By2)\n @staticmethod\n def _boxesIntersect(boxA, boxB):\n if boxA[0] > boxB[2]:\n return False # boxA is right of boxB\n if boxB[0] > boxA[2]:\n return False # boxA is left of boxB\n if boxA[3] < boxB[1]:\n return False # boxA is above boxB\n if boxA[1] > boxB[3]:\n return False # boxA is below boxB\n return True\n\n @staticmethod\n def _getIntersectionArea(boxA, boxB):\n xA = max(boxA[0], boxB[0])\n yA = max(boxA[1], boxB[1])\n xB = min(boxA[2], boxB[2])\n yB = min(boxA[3], boxB[3])\n # intersection area\n return (xB - xA + 1) * (yB - yA + 1)\n\n @staticmethod\n def _getUnionAreas(boxA, boxB, interArea=None):\n area_A = Evaluator._getArea(boxA)\n area_B = Evaluator._getArea(boxB)\n if interArea is None:\n interArea = Evaluator._getIntersectionArea(boxA, boxB)\n return float(area_A + area_B - interArea)\n\n @staticmethod\n def _getArea(box):\n return (box[2] - box[0] + 1) * (box[3] - box[1] + 1)\n"
] | [
[
"numpy.sum",
"matplotlib.pyplot.legend",
"numpy.cumsum",
"numpy.divide",
"numpy.argwhere",
"numpy.zeros",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.plot",
"numpy.linspace",
"matplotlib.pyplot.xlabel"
]
] |
carsault/chord_sequence_prediction | [
"6eb539a963ca6350bcf0c88b8d8756775ad7c488"
] | [
"utilities/modelsGen.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 9 18:00:12 2019\n\n@author: carsault\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom utilities import utils\nfrom utilities.utils import *\n#%%\nclass ModelFamily(nn.Module):\n def __init__(self):\n super(ModelFamily, self).__init__()\n self.models = nn.ModuleDict()\n self.decim = []\n\n def addModel(self, model, decim):\n self.models[decim] = model\n self.decim.append(decim)\n \n def forward(self, x, args, bornInf, bornSup):\n out = []\n i = 0\n for d in self.decim:\n if d != str(1) :\n data = x[:,bornInf[int(d)]:bornSup[int(d)],:].to(args.device)\n out.append(self.models[d].encoder(data))\n i += 1\n out = torch.cat(out, 1)\n data = x[:,bornInf[1]:bornSup[1],:].to(args.device)\n #print(data)\n y = self.models[\"1\"](data,out)\n return y\n \n def train_epoch(self, training_generator, enc_optimizer, dec_optimizer, criterion, bornInf, bornSup, tf_mappingR, args):\n train_total_loss = 0\n for local_batch, local_labels, local_key, local_beat in training_generator:\n if args.alphaRep == \"alphaRep\":\n local_batch = nn.functional.one_hot(local_batch.long(),self.encoder.n_categories) \n local_labels = nn.functional.one_hot(local_labels.long(),self.encoder.n_categories)\n if len(args.decimList) == 1:\n local_batch = local_batch[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous()\n local_labels = local_labels[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous() \n local_batch, local_labels = local_batch.to(args.device,non_blocking=True), local_labels.to(args.device,non_blocking=True)\n \n self.train() \n self.zero_grad()\n if args.alphaRep == \"alphaRep\":\n output = self(local_batch.float(), args, bornInf, bornSup)\n else:\n output = self(local_batch, args, bornInf, bornSup)\n #print(output.size())\n if args.decimList[0] != 1:\n loss = criterion(output, local_labels)\n else:\n output = output.transpose(1,2)\n topv, topi = local_labels.topk(1)\n topi = topi[:,:,0]\n #loss = criterion(output, local_labels)\n loss = criterion(output, topi)\n output = output.transpose(1,2)\n #print(topi.size())\n #loss = criterion(output, local_labels)\n #loss = criterion(output, topi)\n loss.backward()\n \n enc_optimizer.step()\n dec_optimizer.step()\n train_total_loss += loss\n return train_total_loss \n \nclass MlpTensorFamily(nn.Module):\n def __init__(self):\n super(MlpTensorFamily, self).__init__()\n self.encoderTensor = nn.ModuleDict()\n self.decim = []\n \n def addEncoder(self, enc):\n self.encoder = enc\n \n def addDecoder(self, dec):\n self.decoder = dec\n\n def addEncoderTensor(self, model, decim):\n self.encoderTensor[str(decim)] = model\n self.decim.append(decim)\n \n def forward(self, x, u, args):\n out = []\n out.append(self.encoder(x))\n for d in range(args.lenSeq-1):\n data = u[d]\n out.append(self.encoderTensor[str(d)](data))\n out = torch.cat(out, 1)\n y = self.decoder(out)\n return y\n \n def train_epoch(self, training_generator, optimizer, criterion, bornInf, bornSup, tf_mappingR, args):\n train_total_loss = 0\n for local_batch, local_labels, local_key, local_beat in training_generator:\n if args.alphaRep == \"alphaRep\":\n local_batch = nn.functional.one_hot(local_batch.long(),self.encoder.n_categories) \n local_labels = nn.functional.one_hot(local_labels.long(),self.encoder.n_categories)\n if len(args.decimList) == 1:\n local_batch = local_batch[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous()\n local_labels = local_labels[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous() \n local_batch, local_labels = local_batch.to(args.device,non_blocking=True), local_labels.to(args.device,non_blocking=True)\n \n self.train() \n self.zero_grad()\n if args.alphaRep == \"alphaRep\":\n output = self(local_batch.float())\n else:\n output = self(local_batch)\n #print(output.size())\n if args.decimList[0] != 1:\n loss = criterion(output, local_labels)\n else:\n output = output.transpose(1,2)\n topv, topi = local_labels.topk(1)\n topi = topi[:,:,0]\n #loss = criterion(output, local_labels)\n loss = criterion(output, topi)\n output = output.transpose(1,2)\n #print(topi.size())\n #loss = criterion(output, local_labels)\n #loss = criterion(output, topi)\n loss.backward()\n \n optimizer.step()\n train_total_loss += loss\n return train_total_loss \n \nclass ModelFamilySum(nn.Module):\n def __init__(self):\n super(ModelFamilySum, self).__init__()\n self.models = nn.ModuleDict()\n self.decim = []\n\n def addModel(self, model, decim):\n self.models[decim] = model\n self.decim.append(decim)\n \n def forward(self, x, args):\n out = []\n i = 0\n for d in self.decim:\n if d != str(1) :\n data = x[i].to(args.device)\n data = self.models[d](data)\n data = data.repeat(1,int(d),1)\n data = data.div(int(d))\n out.append(data)\n i += 1\n data = x[0].to(args.device)\n out.append(self.models[\"1\"](data))\n out = torch.stack(out)\n y = torch.sum(out, dim = 0)\n return y\n\n def train_epoch(self, training_generator, optimizer, criterion, bornInf, bornSup, tf_mappingR, args):\n train_total_loss = 0\n for local_batch, local_labels, local_key, local_beat in training_generator:\n if args.alphaRep == \"alphaRep\":\n local_batch = nn.functional.one_hot(local_batch.long(),self.encoder.n_categories) \n local_labels = nn.functional.one_hot(local_labels.long(),self.encoder.n_categories)\n if len(args.decimList) == 1:\n local_batch = local_batch[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous()\n local_labels = local_labels[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous() \n local_batch, local_labels = local_batch.to(args.device,non_blocking=True), local_labels.to(args.device,non_blocking=True)\n \n self.train() \n self.zero_grad()\n if args.alphaRep == \"alphaRep\":\n output = self(local_batch.float())\n else:\n output = self(local_batch)\n #print(output.size())\n if args.decimList[0] != 1:\n loss = criterion(output, local_labels)\n else:\n output = output.transpose(1,2)\n topv, topi = local_labels.topk(1)\n topi = topi[:,:,0]\n #loss = criterion(output, local_labels)\n loss = criterion(output, topi)\n output = output.transpose(1,2)\n #print(topi.size())\n #loss = criterion(output, local_labels)\n #loss = criterion(output, topi)\n loss.backward()\n \n optimizer.step()\n train_total_loss += loss\n return train_total_loss \n \n \nclass InOutModel(nn.Module):\n def __init__(self, encoder, decoder):\n super(InOutModel, self).__init__()\n self.encoder = encoder\n self.decoder = decoder\n \n def forward(self, x):\n y = self.encoder(x)\n y = self.decoder(y)\n return y\n \n def train_epoch(self, training_generator, optimizer, criterion, bornInf, bornSup, tf_mappingR, args):\n train_total_loss = 0\n for local_batch, local_labels, local_key, local_beat in training_generator:\n if args.alphaRep == \"alphaRep\":\n local_batch = nn.functional.one_hot(local_batch.long(),self.encoder.n_categories)\n local_labels = nn.functional.one_hot(local_labels.long(),self.encoder.n_categories)\n if len(args.decimList) == 1:\n local_batch = local_batch[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous()\n local_labels = local_labels[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous() \n local_batch, local_labels = local_batch.to(args.device,non_blocking=True), local_labels.to(args.device,non_blocking=True)\n \n self.train() \n self.zero_grad()\n if args.alphaRep == \"alphaRep\":\n output = self(local_batch.float())\n else:\n output = self(local_batch)\n #print(output.size())\n if args.decimList[0] != 1:\n loss = criterion(output, local_labels)\n else:\n output = output.transpose(1,2)\n topv, topi = local_labels.topk(1)\n topi = topi[:,:,0]\n #loss = criterion(output, local_labels)\n loss = criterion(output, topi)\n output = output.transpose(1,2)\n #print(topi.size())\n #loss = criterion(output, local_labels)\n #loss = criterion(output, topi)\n loss.backward()\n \n optimizer.step()\n train_total_loss += loss\n return train_total_loss\n \n \nclass InOutModelDouble(nn.Module):\n def __init__(self, encoder, encoderTensor, decoder):\n super(InOutModelDouble, self).__init__()\n self.encoder = encoder\n self.encoderTensor = encoderTensor\n self.decoder = decoder\n \n def forward(self, x, u):\n out = []\n y1 = self.encoder(x)\n out.append(y1)\n y2 = self.encoderTensor(u)\n out.append(y2)\n out = torch.cat(out, 1)\n y = self.decoder(out)\n return y\n \n def train_epoch(self, training_generator, optimizer, criterion, bornInf, bornSup, tf_mappingR, args):\n train_total_loss = 0\n for local_batch, local_labels, local_key, local_beat in training_generator:\n if len(args.decimList) == 1:\n local_batch = local_batch[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous()\n local_labels = local_labels[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous() \n local_batch, local_labels = local_batch.to(args.device,non_blocking=True), local_labels.to(args.device,non_blocking=True)\n \n self.train() \n self.zero_grad()\n tensorSim = computeTensor(local_batch, tf_mappingR.float())\n output = self(local_batch, tensorSim)\n loss = criterion(output, local_labels)\n loss.backward()\n \n optimizer.step()\n train_total_loss += loss\n return train_total_loss\n\nclass InOutModelDoubleKey(nn.Module):\n def __init__(self, encoder, encoderKey, decoder):\n super(InOutModelDoubleKey, self).__init__()\n self.encoder = encoder\n self.encoderKey = encoderKey\n self.decoder = decoder\n \n def forward(self, x, u):\n out = []\n y1 = self.encoder(x)\n out.append(y1)\n y2 = self.encoderKey(u)\n out.append(y2)\n out = torch.cat(out, 1)\n y = self.decoder(out)\n return y\n \n def train_epoch(self, training_generator, optimizer, criterion, bornInf, bornSup, tf_mappingR, args):\n train_total_loss = 0\n for local_batch, local_labels, local_key, local_beat in training_generator:\n if len(args.decimList) == 1:\n local_batch = local_batch[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous()\n local_labels = local_labels[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous() \n local_batch, local_labels = local_batch.to(args.device,non_blocking=True), local_labels.to(args.device,non_blocking=True)\n local_beat = local_beat.to(args.device,non_blocking=True)\n local_key = local_key.to(args.device,non_blocking=True)\n self.train() \n self.zero_grad()\n #tensorSim = computeTensor(local_batch, tf_mappingR.float())\n local_key = keyToOneHot(local_key)\n output = self(local_batch, local_key)\n #print(output.size())\n output = output.transpose(1,2)\n topv, topi = local_labels.topk(1)\n topi = topi[:,:,0]\n #print(topi.size())\n #loss = criterion(output, local_labels)\n loss = criterion(output, topi)\n loss.backward()\n \n optimizer.step()\n train_total_loss += loss\n return train_total_loss\n\nclass InOutModelDoubleBeat(nn.Module):\n def __init__(self, encoder, encoderBeat, decoder):\n super(InOutModelDoubleBeat, self).__init__()\n self.encoder = encoder\n self.encoderBeat = encoderBeat\n self.decoder = decoder\n \n def forward(self, x, u):\n out = []\n y1 = self.encoder(x)\n out.append(y1)\n y2 = self.encoderBeat(u)\n out.append(y2)\n out = torch.cat(out, 1)\n y = self.decoder(out)\n return y\n \n def train_epoch(self, training_generator, optimizer, criterion, bornInf, bornSup, tf_mappingR, args):\n train_total_loss = 0\n for local_batch, local_labels, local_key, local_beat in training_generator:\n if len(args.decimList) == 1:\n local_batch = local_batch[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous()\n local_labels = local_labels[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous() \n local_batch, local_labels = local_batch.to(args.device,non_blocking=True), local_labels.to(args.device,non_blocking=True)\n local_beat = local_beat.to(args.device,non_blocking=True)\n local_key = local_key.to(args.device,non_blocking=True) \n self.train() \n self.zero_grad()\n #tensorSim = computeTensor(local_batch, tf_mappingR.float())\n local_beat = beatToOneHot(local_beat)\n output = self(local_batch, local_beat)\n #print(output.size())\n output = output.transpose(1,2)\n topv, topi = local_labels.topk(1)\n topi = topi[:,:,0]\n #print(topi.size())\n #loss = criterion(output, local_labels)\n loss = criterion(output, topi)\n loss.backward()\n \n optimizer.step()\n train_total_loss += loss\n return train_total_loss\n \nclass InOutModelTripleKeyBeat(nn.Module):\n def __init__(self, encoder, encoderBeat, encoderKey, decoder):\n super(InOutModelTripleKeyBeat, self).__init__()\n self.encoder = encoder\n self.encoderKey = encoderKey\n self.encoderBeat = encoderBeat\n self.decoder = decoder\n \n def forward(self, x, u, v):\n out = []\n y1 = self.encoder(x)\n out.append(y1)\n y2 = self.encoderKey(u)\n out.append(y2)\n y3 = self.encoderBeat(v)\n out.append(y3)\n out = torch.cat(out, 1)\n y = self.decoder(out)\n return y\n \n def train_epoch(self, training_generator, optimizer, criterion, bornInf, bornSup, tf_mappingR, args):\n train_total_loss = 0\n for local_batch, local_labels, local_key, local_beat in training_generator:\n if len(args.decimList) == 1:\n local_batch = local_batch[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous()\n local_labels = local_labels[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous() \n local_batch, local_labels = local_batch.to(args.device,non_blocking=True), local_labels.to(args.device,non_blocking=True)\n local_beat = local_beat.to(args.device,non_blocking=True)\n local_key = local_key.to(args.device,non_blocking=True) \n self.train() \n self.zero_grad()\n #tensorSim = computeTensor(local_batch, tf_mappingR.float())\n local_key = keyToOneHot(local_key)\n local_beat = beatToOneHot(local_beat)\n output = self(local_batch, local_key, local_beat)\n #print(output.size())\n output = output.transpose(1,2)\n topv, topi = local_labels.topk(1)\n topi = topi[:,:,0]\n #print(topi.size())\n #loss = criterion(output, local_labels)\n loss = criterion(output, topi)\n loss.backward()\n \n optimizer.step()\n train_total_loss += loss\n return train_total_loss\n\n\nclass InOutModelTripleRawData(nn.Module):\n def __init__(self, encTensor1,encTensor2, decoder, args):\n super(InOutModelTripleRawData, self).__init__()\n self.encoderTensor1 = encTensor1\n self.encoderTensor2 = encTensor2\n self.decoder = decoder\n self.args = args\n \n def forward(self, x):\n out = []\n u = x.view(-1, int(self.args.lenSeq * self.args.n_categories))\n out.append(u)\n y2 = self.encoderTensor1(x)\n out.append(y2)\n y3 = self.encoderTensor2(x)\n out.append(y3)\n out = torch.cat(out, 1)\n y = self.decoder(out)\n y2 = nn.Softmax(dim=1)(y2)\n y3 = nn.Softmax(dim=1)(y3)\n return y, y2, y3\n #return y\n \n def train_epoch(self, training_generator, optimizerRecEnc, optimizerRecDec, optimizerKey, optimizerBeat, criterion, criterionKey, criterionBeat, bornInf, bornSup, tensorSim, args):\n train_total_loss = 0\n train_keytotal_loss = 0\n train_beattotal_loss = 0\n for local_batch, local_labels, local_key, local_beat in training_generator:\n if len(args.decimList) == 1:\n local_batch = local_batch[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous()\n local_labels = local_labels[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous() \n local_batch, local_labels = local_batch.to(args.device,non_blocking=True), local_labels.to(args.device,non_blocking=True)\n local_beat = local_beat.to(args.device,non_blocking=True)\n local_key = local_key.to(args.device,non_blocking=True)\n self.train()\n \n if args.key == True:\n output, beat, key = self(local_batch)\n self.zero_grad()\n local_key = keyToOneHot(local_key)\n local_key = local_key[:,0,:]\n losskey = criterionKey(key, local_key)\n losskey.backward()\n train_keytotal_loss += losskey\n optimizerKey.step()\n \n if args.beat == True:\n output, beat, key = self(local_batch)\n self.zero_grad()\n local_beat = beatToOneHot(local_beat)\n local_beat = local_beat[:,0,:]\n lossbeat = criterionBeat(beat, local_beat)\n lossbeat.backward()\n train_beattotal_loss += lossbeat \n optimizerBeat.step()\n \n if args.rec == True:\n output, beat, key = self(local_batch)\n self.zero_grad()\n loss = criterion(output, local_labels)\n loss.backward()\n train_total_loss += loss\n #optimizerRecEnc.step()\n optimizerRecDec.step()\n \n return train_total_loss, train_keytotal_loss, train_beattotal_loss\n \nclass InOutModelTriple(nn.Module):\n def __init__(self, encoder, encTensor1,encTensor2, decoder):\n super(InOutModelTriple, self).__init__()\n self.encoder = encoder\n self.encoderTensor1 = encTensor1\n self.encoderTensor2 = encTensor2\n self.decoder = decoder\n \n def forward(self, x):\n out = []\n y1 = self.encoder(x)\n out.append(y1)\n y2 = self.encoderTensor1(x)\n out.append(y2)\n y3 = self.encoderTensor2(x)\n out.append(y3)\n out = torch.cat(out, 1)\n y = self.decoder(out)\n y2 = nn.Softmax(dim=1)(y2)\n y3 = nn.Softmax(dim=1)(y3)\n return y, y2, y3\n #return y\n \n def train_epoch(self, training_generator, optimizerRecEnc, optimizerRecDec, optimizerKey, optimizerBeat, criterion, criterionKey, criterionBeat, bornInf, bornSup, tensorSim, args):\n train_total_loss = 0\n train_keytotal_loss = 0\n train_beattotal_loss = 0\n for local_batch, local_labels, local_key, local_beat in training_generator:\n if args.alphaRep == \"alphaRep\":\n local_batch = nn.functional.one_hot(local_batch.long(),args.n_categories) \n local_labels = nn.functional.one_hot(local_labels.long(),args.n_categories)\n if len(args.decimList) == 1:\n local_batch = local_batch[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous()\n local_labels = local_labels[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous() \n local_batch, local_labels = local_batch.to(args.device,non_blocking=True), local_labels.to(args.device,non_blocking=True)\n local_beat = local_beat.to(args.device,non_blocking=True)\n local_key = local_key.to(args.device,non_blocking=True)\n self.train()\n \n if args.key == True:\n #output, beat, key = self(local_batch)\n if args.alphaRep == \"alphaRep\":\n output, beat, key = self(local_batch.float())\n else:\n output, beat, key = self(local_batch)\n self.zero_grad()\n #local_key = keyToOneHot(local_key)\n #local_key = local_key[:,0,:]\n #print(key.size())\n #print(local_key.size())\n losskey = criterionKey(key, local_key[:,0].long())\n losskey.backward()\n train_keytotal_loss += losskey\n optimizerKey.step()\n \n if args.beat == True:\n #output, beat, key = self(local_batch)\n if args.alphaRep == \"alphaRep\":\n output, beat, key = self(local_batch.float())\n else:\n output, beat, key = self(local_batch)\n self.zero_grad()\n #local_beat = beatToOneHot(local_beat)\n #local_beat = local_beat[:,0,:]\n lossbeat = criterionBeat(beat, local_beat[:,0].long())\n lossbeat.backward()\n train_beattotal_loss += lossbeat \n optimizerBeat.step()\n \n if args.rec == True:\n #output, beat, key = self(local_batch)\n if args.alphaRep == \"alphaRep\":\n output, beat, key = self(local_batch.float())\n else:\n output, beat, key = self(local_batch)\n self.zero_grad()\n output = output.transpose(1,2)\n topv, topi = local_labels.topk(1)\n topi = topi[:,:,0]\n #loss = criterion(output, local_labels)\n loss = criterion(output, topi)\n #output = output.transpose(1,2)\n #loss = criterion(output, local_labels)\n loss.backward()\n train_total_loss += loss\n optimizerRecEnc.step()\n optimizerRecDec.step()\n \n return train_total_loss, train_keytotal_loss, train_beattotal_loss\n \nclass InOutModelTripleMatrix(nn.Module):\n def __init__(self, encoder, encTensor1,encTensor2, decoder):\n super(InOutModelTripleMatrix, self).__init__()\n self.encoder = encoder\n self.encoderTensor1 = encTensor1\n self.encoderTensor2 = encTensor2\n self.decoder = decoder\n \n def forward(self, x, m):\n out = []\n y1 = self.encoder(x, m)\n out.append(y1)\n y2 = self.encoderTensor1(x, m)\n out.append(y2)\n y3 = self.encoderTensor2(x, m)\n out.append(y3)\n out = torch.cat(out, 1)\n y = self.decoder(out)\n y2 = nn.Softmax(dim=1)(y2)\n y3 = nn.Softmax(dim=1)(y3)\n return y, y2, y3\n #return y\n \n def train_epoch(self, training_generator, optimizerRecEnc, optimizerRecDec, optimizerKey, optimizerBeat, criterion, criterionKey, criterionBeat, bornInf, bornSup, tf_mappingR, args):\n train_total_loss = 0\n train_keytotal_loss = 0\n train_beattotal_loss = 0\n for local_batch, local_labels, local_key, local_beat in training_generator:\n if len(args.decimList) == 1:\n local_batch = local_batch[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous()\n local_labels = local_labels[:,bornInf[args.decimList[0]]:bornSup[args.decimList[0]],:].contiguous() \n local_batch, local_labels = local_batch.to(args.device,non_blocking=True), local_labels.to(args.device,non_blocking=True) \n local_beat = local_beat.to(args.device,non_blocking=True)\n local_key = local_key.to(args.device,non_blocking=True)\n self.train()\n tensorSim = computeTensor(local_batch, tf_mappingR.float())\n \n if args.key == True:\n output, beat, key = self(local_batch, tensorSim)\n self.zero_grad()\n local_key = keyToOneHot(local_key)\n local_key = local_key[:,0,:]\n losskey = criterionKey(key, local_key)\n losskey.backward()\n train_keytotal_loss += losskey\n optimizerKey.step()\n \n if args.beat == True:\n output, beat, key = self(local_batch, tensorSim)\n self.zero_grad()\n local_beat = beatToOneHot(local_beat)\n local_beat = local_beat[:,0,:]\n lossbeat = criterionBeat(beat, local_beat)\n lossbeat.backward()\n train_beattotal_loss += lossbeat \n optimizerBeat.step()\n \n if args.rec == True:\n output, beat, key = self(local_batch, tensorSim)\n self.zero_grad()\n loss = criterion(output, local_labels)\n loss.backward()\n train_total_loss += loss\n optimizerRecEnc.step()\n optimizerRecDec.step()\n \n return train_total_loss, train_keytotal_loss, train_beattotal_loss\n \n \n \nclass InOutModelTripleMatrixBis(nn.Module):\n def __init__(self, encoder, encTensor1,encTensor2, decoder):\n super(InOutModelTripleMatrixBis, self).__init__()\n self.encoder = encoder\n self.encoderTensor1 = encTensor1\n self.encoderTensor2 = encTensor2\n self.decoder = decoder\n \n def forward(self, x, m):\n out = []\n y1 = self.encoder(x, m)\n out.append(y1)\n y2 = self.encoderTensor1(x)\n out.append(y2)\n y3 = self.encoderTensor2(x)\n out.append(y3)\n out = torch.cat(out, 1)\n y = self.decoder(out)\n y2 = nn.Softmax(dim=1)(y2)\n y3 = nn.Softmax(dim=1)(y3)\n return y, y2, y3\n #return y\n \nclass InOutModelTripleOLD1402(nn.Module):\n def __init__(self, encoder, encTensor1,encTensor2, decoder):\n super(InOutModelTripleOLD1402, self).__init__()\n self.encoder = encoder\n self.encoderTensor1 = encTensor1\n self.encoderTensor2 = encTensor2\n self.decoder = decoder\n \n def forward(self, x, u,v):\n out = []\n y1 = self.encoder(x)\n out.append(y1)\n y2 = self.encoderTensor1(u)\n out.append(y2)\n y3 = self.encoderTensor2(v)\n out.append(y3)\n out = torch.cat(out, 1)\n y = self.decoder(out)\n return y, y2, y3\n #return y\n \nclass FinalModel(nn.Module):\n def __init__(self, encoder, decoder):\n super(FinalModel, self).__init__()\n self.encoder = encoder\n self.decoder = decoder\n \n def forward(self, x, out):\n y = self.encoder(x)\n y = self.decoder(y, out)\n return y\n \nclass EncoderMLP(nn.Module):\n def __init__(self, lenSeq, n_categories, n_hidden, n_latent, decimRatio,n_layer = 1, dropRatio = 0.5):\n super(EncoderMLP, self).__init__()\n self.fc1 = nn.Linear(int(lenSeq * n_categories / decimRatio), n_hidden)\n self.bn1 = nn.BatchNorm1d(n_hidden)\n self.fc2 = nn.ModuleList()\n self.bn2 = nn.ModuleList()\n for i in range(n_layer):\n self.fc2.append(nn.Linear(n_hidden, n_hidden))\n self.bn2.append(nn.BatchNorm1d(n_hidden))\n self.fc3 = nn.Linear(n_hidden, n_latent)\n self.drop_layer = nn.Dropout(p=dropRatio)\n self.n_categories = n_categories\n self.decimRatio = decimRatio\n self.lenSeq = lenSeq\n self.n_layer = n_layer\n def forward(self, x):\n x = x.view(-1, int(self.lenSeq * self.n_categories/ self.decimRatio))\n x = F.relu(self.bn1(self.fc1(x)))\n for i in range(self.n_layer):\n x = self.drop_layer(x)\n x = F.relu(self.bn2[i](self.fc2[i](x)))\n x = self.fc3(x)\n return x\n \n \nclass NetConv(nn.Module):\n def __init__(self):\n super(NetConv, self).__init__()\n self.conv1 = nn.Conv2d(1, 10, kernel_size=4,padding=True)\n self.conv2 = nn.Conv2d(10, 20, kernel_size=3,padding=True)\n self.conv2_drop = nn.Dropout2d()\n self.fc1 = nn.Linear(20, 50)\n self.fc2 = nn.Linear(50, 5)\n\n def forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x.view(-1,1,8,8)), 2))\n x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))\n x = x.view(-1, 20)\n x = F.relu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n #return F.log_softmax(x)\n return x\n\nclass GaussianNoise(nn.Module):\n \"\"\"Gaussian noise regularizer.\n\n Args:\n sigma (float, optional): relative standard deviation used to generate the\n noise. Relative means that it will be multiplied by the magnitude of\n the value your are adding the noise to. This means that sigma can be\n the same regardless of the scale of the vector.\n is_relative_detach (bool, optional): whether to detach the variable before\n computing the scale of the noise. If `False` then the scale of the noise\n won't be seen as a constant but something to optimize: this will bias the\n network to generate vectors with smaller values.\n \"\"\"\n\n def __init__(self, args, sigma=0.1, is_relative_detach=True):\n super().__init__()\n self.sigma = sigma\n self.is_relative_detach = is_relative_detach\n self.noise = torch.tensor(0.0).to(args.device)\n\n def forward(self, x):\n if self.training and self.sigma != 0:\n scale = self.sigma * x.detach() if self.is_relative_detach else self.sigma * x\n sampled_noise = self.noise.repeat(*x.size()).normal_() * scale\n x = x + sampled_noise\n return x \n\n# Convolutional neural network (two convolutional layers) \nclass ConvNet(nn.Module):\n def __init__(self, args, num_classes=25, drop_outRate = 0.6):\n super(ConvNet, self).__init__()\n self.layer1 = nn.Sequential(\n nn.BatchNorm2d(1),\n GaussianNoise(args, 0.3),\n nn.Conv2d(1, 64, kernel_size=(3,25), stride=1, padding=0),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Dropout(drop_outRate),\n #nn.MaxPool2d(kernel_size=(3,1), stride=1),\n nn.Conv2d(64, 32, kernel_size=(6,1), stride=1, padding=0),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.Dropout(drop_outRate),\n nn.Conv2d(32, 200, kernel_size=(1,1), stride=1, padding=0),\n nn.BatchNorm2d(200),\n nn.ReLU(),\n nn.Dropout(drop_outRate))\n self.layer5 = nn.Sequential(nn.Linear(200,200), nn.Linear(200,50))\n \n def forward(self, x):\n out = self.layer1(x) \n out = out.view(out.size(0), -1)\n out = self.layer5(out)\n return out\n\nclass dilatConv(nn.Module):\n def __init__(self, lenSeq, lenPred, n_categories, latent):\n super(dilatConv, self).__init__()\n self.conv1 = nn.Conv2d(1, 250, 2, 1, dilation = (2,1))\n self.conv2 = nn.Conv2d(250, 25, 2, 1, dilation = (4,1))\n self.fc1 = nn.Linear(1150, 500)\n self.fc2 = nn.Linear(500, latent)\n self.lenPred = lenPred\n self.lenSeq = lenSeq\n self.n_categories = n_categories\n self.latent = latent\n\n def forward(self, x):\n x = x.view(-1, 1, self.lenSeq, self.n_categories)\n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = x.view(-1, 1150)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n\n return x\n \n def name(self):\n return \"dilatConv\"\n \nclass dilatConvBatch(nn.Module):\n def __init__(self, lenSeq, lenPred, n_categories, latent, drop_outRate = 0.6):\n super(dilatConvBatch, self).__init__()\n self.batch0 = nn.BatchNorm2d(1)\n self.conv1 = nn.Conv2d(1, 250, 2, 1, dilation = (2,1))\n self.batch1 = nn.BatchNorm2d(250)\n self.do1 = nn.Dropout(drop_outRate)\n self.conv2 = nn.Conv2d(250, 25, 2, 1, dilation = (4,1))\n self.batch2 = nn.BatchNorm2d(25)\n self.do2 = nn.Dropout(drop_outRate)\n self.fc1 = nn.Linear(1150, 500)\n self.fc2 = nn.Linear(500, latent)\n self.lenPred = lenPred\n self.lenSeq = lenSeq\n self.n_categories = n_categories\n self.latent = latent\n\n def forward(self, x):\n x = self.batch0(x.view(-1, 1, self.lenSeq, self.n_categories))\n x = self.do1(F.relu(self.batch1(self.conv1(x))))\n x = self.do2(F.relu(self.batch2(self.conv2(x))))\n x = x.view(-1, 1150)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n\n return x\n \nclass dilatConvBatchV2(nn.Module):\n def __init__(self, lenSeq, lenPred, n_categories, latent, drop_outRate = 0.6):\n super(dilatConvBatchV2, self).__init__()\n self.batch0 = nn.BatchNorm2d(1)\n self.conv1 = nn.Conv2d(1, 50, (2,25), 1, dilation = (2,1))\n self.batch1 = nn.BatchNorm2d(50)\n self.do1 = nn.Dropout(drop_outRate)\n self.conv2 = nn.Conv2d(50, 30, (2,1) , 1, dilation = (4,1))\n self.batch2 = nn.BatchNorm2d(30)\n self.do2 = nn.Dropout(drop_outRate)\n #self.conv3 = nn.Conv2d(30, 10, 2, 1, dilation = (8,1))\n #self.batch3 = nn.BatchNorm2d(10)\n #self.do3 = nn.Dropout(drop_outRate)\n self.fc1 = nn.Linear(60, 100)\n self.fc2 = nn.Linear(100, latent)\n self.lenPred = lenPred\n self.lenSeq = lenSeq\n self.n_categories = n_categories\n self.latent = latent\n\n def forward(self, x):\n x = self.batch0(x.view(-1, 1, self.lenSeq, self.n_categories))\n x = self.do1(F.relu(self.batch1(self.conv1(x))))\n x = self.do2(F.relu(self.batch2(self.conv2(x))))\n #x = self.do3(F.relu(self.batch3(self.conv3(x))))\n x = x.view(-1, 60)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n\n return x\n \n def name(self):\n return \"dilatConv\"\n \nclass DecoderMLP(nn.Module):\n def __init__(self, lenPred, n_categories, n_hidden, n_latent, decimRatio, n_layer = 1, dropRatio = 0.5):\n super(DecoderMLP, self).__init__()\n self.fc1 = nn.Linear(n_latent , n_hidden)\n self.bn1 = nn.BatchNorm1d(n_hidden)\n self.fc2 = nn.ModuleList()\n self.bn2 = nn.ModuleList()\n for i in range(n_layer):\n self.fc2.append(nn.Linear(n_hidden, n_hidden))\n self.bn2.append(nn.BatchNorm1d(n_hidden))\n self.fc3 = nn.Linear(n_hidden, int(lenPred * n_categories / decimRatio))\n self.drop_layer = nn.Dropout(p=dropRatio)\n self.n_categories = n_categories\n self.decimRatio = decimRatio\n self.lenPred = lenPred\n self.n_layer = n_layer\n def forward(self, x):\n x = F.relu(self.bn1(self.fc1(x)))\n for i in range(self.n_layer):\n x = self.drop_layer(x)\n x = F.relu(self.bn2[i](self.fc2[i](x)))\n x = self.fc3(x)\n x = x.view(-1, int(self.lenPred / self.decimRatio), self.n_categories)\n #if self.decimRatio == 1 :\n # x = nn.Softmax(dim=2)(x)\n if self.decimRatio != 1 :\n x = F.relu(x)\n return x\n \nclass DecoderMLPKey(nn.Module):\n def __init__(self, lenPred, n_categories, n_hidden, n_latent, decimRatio, n_layer = 1, dropRatio = 0.5):\n super(DecoderMLPKey, self).__init__()\n self.fc1 = nn.Linear(n_latent , n_hidden)\n self.bn1 = nn.BatchNorm1d(n_hidden)\n self.fc2 = nn.ModuleList()\n self.bn2 = nn.ModuleList()\n for i in range(n_layer):\n self.fc2.append(nn.Linear(n_hidden, n_hidden))\n self.bn2.append(nn.BatchNorm1d(n_hidden))\n self.fc3 = nn.Linear(n_hidden, int(lenPred * n_categories / decimRatio))\n self.drop_layer = nn.Dropout(p=dropRatio)\n self.n_categories = n_categories\n self.decimRatio = decimRatio\n self.lenPred = lenPred\n self.n_layer = n_layer\n def forward(self, x):\n x = F.relu(self.bn1(self.fc1(x)))\n for i in range(self.n_layer):\n x = self.drop_layer(x)\n x = F.relu(self.bn2[i](self.fc2[i](x)))\n x = self.fc3(x)\n x = x.view(-1, self.n_categories)\n #if self.decimRatio == 1 :\n # x = nn.Softmax(dim=1)(x)\n #else:\n # x = F.relu(x)\n #x = F.sigmoid(x)\n return x \n \nclass DecoderFinal(nn.Module):\n def __init__(self, lenSeq, lenPred, n_categories, n_hidden, n_latent, n_layer = 1, dropRatio = 0.5):\n super(DecoderFinal, self).__init__()\n self.fc1 = nn.Linear(n_latent , n_hidden)\n self.bn1 = nn.BatchNorm1d(n_hidden)\n self.fc2 = nn.ModuleList()\n self.bn2 = nn.ModuleList()\n for i in range(n_layer):\n self.fc2.append(nn.Linear(n_hidden, n_hidden))\n self.bn2.append(nn.BatchNorm1d(n_hidden))\n self.fc3 = nn.Linear(n_hidden, lenPred * n_categories)\n self.drop_layer = nn.Dropout(p=dropRatio)\n self.n_categories = n_categories\n self.lenPred = lenPred\n self.n_layer = n_layer\n def forward(self, x, out):\n x = torch.cat((x,out), 1) \n x = F.relu(self.bn1(self.fc1(x)))\n for i in range(self.n_layer):\n x = self.drop_layer(x)\n x = F.relu(self.bn2[i](self.fc2[i](x)))\n x = self.fc3(x)\n x = x.view(-1, self.lenPred, self.n_categories)\n #x = nn.Softmax(dim=2)(x)\n return x\n\n#%%\n#%%\nclass VAEModelFamily(nn.Module):\n def __init__(self):\n super(VAEModelFamily, self).__init__()\n self.models = nn.ModuleDict()\n self.decim = []\n\n def addModel(self, model, decim):\n self.models[decim] = model\n self.decim.append(decim) \n \n def reparametrize(self, mu, logvar):\n std = torch.exp(0.5*logvar)\n eps = torch.randn_like(std)\n return mu + eps*std \n def forward(self, x, args):\n out = []\n i = 0\n for d in self.decim:\n if d != str(1) :\n data = x[i].to(args.device)\n out1, out2 = self.models[d].encoder(data)\n out.append(self.reparametrize(out1,out2))\n i += 1\n out = torch.cat(out, 1)\n data = x[0].to(args.device)\n #print(data)\n y = self.models[\"1\"](data,out)\n return y\n \nclass VAEInOutModel(nn.Module):\n def __init__(self, encoder, decoder):\n super(VAEInOutModel, self).__init__()\n self.encoder = encoder\n self.decoder = decoder\n \n def forward(self, x):\n y1, y2 = self.encoder(x)\n y = self.decoder(y1, y2)\n return y\n \nclass VAEFinalModel(nn.Module):\n def __init__(self, encoder, decoder):\n super(VAEFinalModel, self).__init__()\n self.encoder = encoder\n self.decoder = decoder\n \n def forward(self, x, out):\n y1, y2 = self.encoder(x)\n y = self.decoder(y1, y2, out)\n return y\n \nclass VAEEncoderMLP(nn.Module):\n def __init__(self, lenSeq, n_categories, n_hidden, n_latent, decimRatio, n_layer = 1, dropRatio = 0.5):\n super(VAEEncoderMLP, self).__init__()\n self.fc1 = nn.Linear(int(lenSeq * n_categories / decimRatio), n_hidden)\n self.fc2 = nn.ModuleList()\n for i in range(n_layer):\n self.fc2.append(nn.Linear(n_hidden, n_hidden))\n self.fc31 = nn.Linear(n_hidden, n_latent)\n self.fc32 = nn.Linear(n_hidden, n_latent)\n self.drop_layer = nn.Dropout(p=dropRatio)\n self.n_categories = n_categories\n self.decimRatio = decimRatio\n self.lenSeq = lenSeq\n self.n_layer = n_layer\n def forward(self, x):\n x = x.view(-1, int(self.lenSeq * self.n_categories/ self.decimRatio))\n x = F.relu(self.fc1(x))\n for i in range(self.n_layer):\n x = self.drop_layer(x)\n x = F.relu(self.fc2[i](x))\n x1 = self.fc31(x)\n x2 = self.fc32(x)\n return x1, x2\n \nclass VAEDecoderMLP(nn.Module):\n def __init__(self, lenPred, n_categories, n_hidden, n_latent, decimRatio, n_layer = 1, dropRatio = 0.5):\n super(VAEDecoderMLP, self).__init__()\n self.fc1 = nn.Linear(n_latent , n_hidden)\n self.fc2 = nn.ModuleList()\n for i in range(n_layer):\n self.fc2.append(nn.Linear(n_hidden, n_hidden))\n self.fc3 = nn.Linear(n_hidden, int(lenPred * n_categories / decimRatio))\n self.drop_layer = nn.Dropout(p=dropRatio)\n self.n_categories = n_categories\n self.decimRatio = decimRatio\n self.lenPred = lenPred\n self.n_layer = n_layer\n def reparametrize(self, mu, logvar):\n std = torch.exp(0.5*logvar)\n eps = torch.randn_like(std)\n return mu + eps*std \n def forward(self, x1, x2):\n z = self.reparametrize(x1, x2)\n x = F.relu(self.fc1(z))\n for i in range(self.n_layer):\n x = self.drop_layer(x)\n x = F.relu(self.fc2[i](x))\n x = self.fc3(x)\n x = x.view(-1, int(self.lenPred / self.decimRatio), self.n_categories)\n if self.decimRatio == 1 :\n x = nn.Softmax(dim=2)(x)\n return x, x1, x2\n \nclass VAEDecoderFinal(nn.Module):\n def __init__(self, lenSeq, lenPred, n_categories, n_hidden, n_latent, n_layer = 1, dropRatio = 0.5):\n super(VAEDecoderFinal, self).__init__()\n self.fc1 = nn.Linear(n_latent , n_hidden)\n self.fc2 = nn.ModuleList()\n for i in range(n_layer):\n self.fc2.append(nn.Linear(n_hidden, n_hidden))\n self.fc3 = nn.Linear(n_hidden, lenPred * n_categories)\n self.drop_layer = nn.Dropout(p=dropRatio)\n self.n_categories = n_categories\n self.lenPred = lenPred\n self.n_layer = n_layer\n def reparametrize(self, mu, logvar):\n std = torch.exp(0.5*logvar)\n eps = torch.randn_like(std)\n return mu + eps*std\n def forward(self, x1, x2, out):\n x = self.reparametrize(x1, x2)\n x = torch.cat([x,out], 1) \n x = F.relu(self.fc1(x))\n for i in range(self.n_layer):\n x = self.drop_layer(x)\n x = F.relu(self.fc2[i](x))\n x = self.fc3(x)\n x = x.view(-1, self.lenPred, self.n_categories)\n x = nn.Softmax(dim=2)(x)\n return x, x1, x2\n#%%\nclass MLPNet(nn.Module):\n def __init__(self, lenSeq, lenPred, n_categories):\n super(MLPNet, self).__init__()\n self.fc1 = nn.Linear(lenSeq * n_categories, 1000)\n self.fc2 = nn.Linear(1000, 1000)\n self.fc3 = nn.Linear(1000, lenPred * n_categories)\n self.lenPred = lenPred\n self.n_categories = n_categories\n def forward(self, x):\n x = x.view(-1, 16*25)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n x = x.view(-1, self.lenPred, self.n_categories)\n x = nn.Softmax(dim=2)(x)\n return x\n \n#%%\nclass LeNet(nn.Module):\n def __init__(self, lenSeq, lenPred, n_categories):\n super(LeNet, self).__init__()\n self.conv1 = nn.Conv2d(1, 20, 5, 1)\n self.conv2 = nn.Conv2d(20, 50, 5, 1)\n self.fc1 = nn.Linear(8*17*50, 500)\n self.fc2 = nn.Linear(500, lenPred * n_categories)\n self.lenPred = lenPred\n self.lenSeq = lenSeq\n self.n_categories = n_categories\n\n def forward(self, x):\n x = x.view(-1, 1, self.lenSeq, self.n_categories)\n x = F.relu(self.conv1(x))\n #x = F.max_pool2d(x, 2, 2)\n x = F.relu(self.conv2(x))\n #x = F.max_pool2d(x, 2, 2)\n x = x.view(-1, 8*17*50)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n x = x.view(-1, self.lenPred, self.n_categories)\n x = nn.Softmax(dim=2)(x)\n return x\n \n def name(self):\n return \"LeNet\"\n \n#%%\n\n#%%\nn_inputs = 25\nn_hidden = 128\nbatch_size = 500\nlenSeq = 16\nn_categories=25\nclass MockupModel(nn.Module):\n\n def __init__(self):\n super().__init__()\n self.model = nn.ModuleDict({\n 'lstm': nn.LSTM(\n input_size=n_inputs, # 45, see the data definition\n hidden_size=n_hidden, # Can vary\n num_layers = 3,\n dropout = 0.6, #0.6\n batch_first = True\n ),\n 'linear': nn.Linear(\n in_features=n_hidden,\n out_features=n_categories)\n })\n \n def forward(self, x):\n\n # From [batches, seqs, seq len, features]\n # to [seq len, batch data, features]\n # Data is fed to the LSTM\n out, _ = self.model['lstm'](x)\n #print(f'lstm output={out.size()}')\n\n # From [seq len, batch, num_directions * hidden_size]\n # to [batches, seqs, seq_len,prediction]\n out = out.view(batch_size, lenSeq, -1)\n #print(f'transformed output={out.size()}')\n\n # Data is fed to the Linear layer\n out = self.model['linear'](out)\n #print(f'linear output={out.size()}')\n\n # The prediction utilizing the whole sequence is the last one\n #y_pred = nn.Softmax()(y_pred)\n y_pred = out[:, -1]\n y_pred = nn.Softmax()(y_pred)\n \n #print(f'y_pred={y_pred.size()}')\n\n return y_pred\n#%% \nclass MockupModelMask(nn.Module):\n\n def __init__(self):\n super().__init__()\n self.model = nn.ModuleDict({\n 'lstm': nn.LSTM(\n input_size=n_inputs, # 45, see the data definition\n hidden_size=n_hidden, # Can vary\n num_layers = 3,\n dropout = 0.6, #0.6\n batch_first = True\n ),\n 'linear': nn.Linear(\n in_features=n_hidden,\n out_features=n_categories)\n })\n \n def forward(self, x, nbZero, mask = False):\n\n # From [batches, seqs, seq len, features]\n # to [seq len, batch data, features]\n if mask == True:\n for i in range(x.size()[0]):\n for j in range(nbZero):\n x[i][randint(0,15)] = torch.zeros(n_inputs)\n # Data is fed to the LSTM\n out, _ = self.model['lstm'](x)\n #print(f'lstm output={out.size()}')\n\n # From [seq len, batch, num_directions * hidden_size]\n # to [batches, seqs, seq_len,prediction]\n out = out.view(batch_size, lenSeq, -1)\n #print(f'transformed output={out.size()}')\n\n # Data is fed to the Linear layer\n out = self.model['linear'](out)\n #print(f'linear output={out.size()}')\n\n # The prediction utilizing the whole sequence is the last one\n #y_pred = nn.Softmax()(y_pred)\n y_pred = out[:, -1]\n y_pred = nn.Softmax()(y_pred)\n \n #print(f'y_pred={y_pred.size()}')\n#%%\nclass ResBlock(nn.Module):\n def __init__(self, dim, dim_res=32):\n super().__init__()\n self.block = nn.Sequential(\n nn.ReLU(True),\n nn.Conv2d(dim, dim_res, 3, 1, 1),\n nn.BatchNorm2d(dim_res),\n nn.ReLU(True),\n nn.Conv2d(dim_res, dim, 1),\n nn.BatchNorm2d(dim),\n nn.ReLU(True)\n )\n\n def forward(self, x):\n return x + self.block(x)\n \nclass View1(nn.Module):\n def __init__(self):\n super(View1, self).__init__()\n \n def forward(self, x):\n return x.view(-1,16*24)\n \nclass View2(nn.Module):\n def __init__(self):\n super(View2, self).__init__()\n \n def forward(self, x):\n return x.view(-1,1,16,25) #make it with lenPred\n#%%\n# Construct encoders and decoders for different types\ndef construct_enc_dec(input_dim, dim, embed_dim = 64):\n encoder, decoder = None, None\n # Image data\n encoder = nn.Sequential(\n nn.Conv2d(input_dim, int(dim / 2), 4, 2, 1),\n #nn.BatchNorm2d(dim),\n nn.ReLU(True),\n nn.Conv2d(int(dim / 2), dim, 4, 2, 1),\n #nn.BatchNorm2d(dim),\n nn.ReLU(True),\n nn.Conv2d(dim, dim, 3, 1, 1),\n ResBlock(dim),\n ResBlock(dim),\n nn.Conv2d(dim, embed_dim, 1)\n )\n decoder = nn.Sequential(\n nn.ConvTranspose2d(embed_dim, dim, 3, 1, 1),\n ResBlock(dim),\n ResBlock(dim),\n nn.ConvTranspose2d(dim, int(dim / 2), 4, 2, 1),\n #nn.BatchNorm2d(dim),\n nn.ReLU(True),\n nn.ConvTranspose2d(int(dim / 2), input_dim, 4, 2, 1),\n View1(),\n nn.Linear(16*24,16*25), #make it with lenPred\n View2()\n #nn.Tanh()\n )\n return encoder, decoder\n\n#%% Seq 2 Seq from https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html -> see also attention is page\nclass EncoderRNN(nn.Module):\n def __init__(self, input_size, hidden_size, device):\n super(EncoderRNN, self).__init__()\n self.hidden_size = hidden_size\n\n self.embedding = nn.Embedding(input_size, hidden_size)\n self.gru = nn.GRU(hidden_size, hidden_size)\n \n self.device = device\n \n def forward(self, input, hidden):\n embedded = self.embedding(input).view(1, 1, -1)\n output = embedded\n output, hidden = self.gru(output, hidden)\n return output, hidden\n\n def initHidden(self):\n return torch.zeros(1, 1, self.hidden_size, device=self.device)\n \nclass DecoderRNN(nn.Module):\n def __init__(self, hidden_size, output_size, device):\n super(DecoderRNN, self).__init__()\n self.hidden_size = hidden_size\n\n self.embedding = nn.Embedding(output_size, hidden_size)\n self.gru = nn.GRU(hidden_size, hidden_size)\n self.out = nn.Linear(hidden_size, output_size)\n self.softmax = nn.LogSoftmax(dim=1)\n \n self.device = device\n\n def forward(self, input, hidden):\n output = self.embedding(input).view(1, 1, -1)\n output = F.relu(output)\n output, hidden = self.gru(output, hidden)\n output = self.softmax(self.out(output[0]))\n return output, hidden\n\n def initHidden(self):\n return torch.zeros(1, 1, self.hidden_size, device=self.device)\n \n\n \n"
] | [
[
"torch.stack",
"torch.nn.GRU",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.cat",
"torch.nn.Dropout",
"torch.nn.ConvTranspose2d",
"torch.nn.BatchNorm2d",
"torch.nn.functional.dropout",
"torch.nn.BatchNorm1d",
"torch.nn.Softmax",
"torch.nn.LSTM",
"torch.tensor",
"torch.nn.LogSoftmax",
"torch.sum",
"torch.nn.Linear",
"torch.nn.Dropout2d",
"torch.randn_like",
"torch.nn.Embedding",
"torch.exp",
"torch.nn.functional.relu",
"torch.zeros",
"torch.nn.ModuleDict",
"torch.nn.ReLU"
]
] |
kuo1220/verbose-barnacle | [
"7e8927e7af0c51ac20a63bd4eab6ff83df1a39ae"
] | [
"tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch_test.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\"\"\"Tests for GBDT train function.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom google.protobuf import text_format\nfrom tensorflow.contrib import layers\nfrom tensorflow.contrib.boosted_trees.proto import learner_pb2\nfrom tensorflow.contrib.boosted_trees.proto import tree_config_pb2\nfrom tensorflow.contrib.boosted_trees.python.ops import model_ops\nfrom tensorflow.contrib.boosted_trees.python.training.functions import gbdt_batch\nfrom tensorflow.contrib.boosted_trees.python.utils import losses\nfrom tensorflow.contrib.layers.python.layers import feature_column as feature_column_lib\nfrom tensorflow.contrib.learn.python.learn.estimators import model_fn\nfrom tensorflow.python.feature_column import feature_column_lib as core_feature_column\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import resources\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import googletest\n\n\ndef _squared_loss(label, unused_weights, predictions):\n \"\"\"Unweighted loss implementation.\"\"\"\n loss = math_ops.reduce_sum(\n math_ops.square(predictions - label), 1, keepdims=True)\n return loss\n\n\ndef _append_to_leaf(leaf, c_id, w):\n \"\"\"Helper method for building tree leaves.\n\n Appends weight contributions for the given class index to a leaf node.\n\n Args:\n leaf: leaf node to append to.\n c_id: class Id for the weight update.\n w: weight contribution value.\n \"\"\"\n leaf.sparse_vector.index.append(c_id)\n leaf.sparse_vector.value.append(w)\n\n\ndef _set_float_split(split, feat_col, thresh, l_id, r_id):\n \"\"\"Helper method for building tree float splits.\n\n Sets split feature column, threshold and children.\n\n Args:\n split: split node to update.\n feat_col: feature column for the split.\n thresh: threshold to split on forming rule x <= thresh.\n l_id: left child Id.\n r_id: right child Id.\n \"\"\"\n split.feature_column = feat_col\n split.threshold = thresh\n split.left_id = l_id\n split.right_id = r_id\n\n\nclass GbdtTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n super(GbdtTest, self).setUp()\n\n def testExtractFeatures(self):\n \"\"\"Tests feature extraction.\"\"\"\n with self.test_session():\n features = {}\n features[\"dense_float\"] = array_ops.zeros([2, 1], dtypes.float32)\n features[\"sparse_float\"] = sparse_tensor.SparseTensor(\n array_ops.zeros([2, 2], dtypes.int64),\n array_ops.zeros([2], dtypes.float32),\n array_ops.zeros([2], dtypes.int64))\n features[\"sparse_int\"] = sparse_tensor.SparseTensor(\n array_ops.zeros([2, 2], dtypes.int64),\n array_ops.zeros([2], dtypes.int64), array_ops.zeros([2],\n dtypes.int64))\n (fc_names, dense_floats, sparse_float_indices, sparse_float_values,\n sparse_float_shapes, sparse_int_indices, sparse_int_values,\n sparse_int_shapes) = (\n gbdt_batch.extract_features(features, None, use_core_columns=False))\n self.assertEqual(len(fc_names), 3)\n self.assertAllEqual(fc_names,\n [\"dense_float\", \"sparse_float\", \"sparse_int\"])\n self.assertEqual(len(dense_floats), 1)\n self.assertEqual(len(sparse_float_indices), 1)\n self.assertEqual(len(sparse_float_values), 1)\n self.assertEqual(len(sparse_float_shapes), 1)\n self.assertEqual(len(sparse_int_indices), 1)\n self.assertEqual(len(sparse_int_values), 1)\n self.assertEqual(len(sparse_int_shapes), 1)\n self.assertAllEqual(dense_floats[0].eval(),\n features[\"dense_float\"].eval())\n self.assertAllEqual(sparse_float_indices[0].eval(),\n features[\"sparse_float\"].indices.eval())\n self.assertAllEqual(sparse_float_values[0].eval(),\n features[\"sparse_float\"].values.eval())\n self.assertAllEqual(sparse_float_shapes[0].eval(),\n features[\"sparse_float\"].dense_shape.eval())\n self.assertAllEqual(sparse_int_indices[0].eval(),\n features[\"sparse_int\"].indices.eval())\n self.assertAllEqual(sparse_int_values[0].eval(),\n features[\"sparse_int\"].values.eval())\n self.assertAllEqual(sparse_int_shapes[0].eval(),\n features[\"sparse_int\"].dense_shape.eval())\n\n def testExtractFeaturesWithTransformation(self):\n \"\"\"Tests feature extraction.\"\"\"\n with self.test_session():\n features = {}\n features[\"dense_float\"] = array_ops.zeros([2, 1], dtypes.float32)\n features[\"sparse_float\"] = sparse_tensor.SparseTensor(\n array_ops.zeros([2, 2], dtypes.int64),\n array_ops.zeros([2], dtypes.float32),\n array_ops.zeros([2], dtypes.int64))\n features[\"sparse_categorical\"] = sparse_tensor.SparseTensor(\n array_ops.zeros([2, 2], dtypes.int64),\n array_ops.zeros([2], dtypes.string), array_ops.zeros([2],\n dtypes.int64))\n feature_columns = set()\n feature_columns.add(layers.real_valued_column(\"dense_float\"))\n feature_columns.add(\n layers.feature_column._real_valued_var_len_column(\n \"sparse_float\", is_sparse=True))\n feature_columns.add(\n feature_column_lib.sparse_column_with_hash_bucket(\n \"sparse_categorical\", hash_bucket_size=1000000))\n (fc_names, dense_floats, sparse_float_indices, sparse_float_values,\n sparse_float_shapes, sparse_int_indices, sparse_int_values,\n sparse_int_shapes) = (\n gbdt_batch.extract_features(\n features, feature_columns, use_core_columns=False))\n self.assertEqual(len(fc_names), 3)\n self.assertAllEqual(fc_names,\n [\"dense_float\", \"sparse_float\", \"sparse_categorical\"])\n self.assertEqual(len(dense_floats), 1)\n self.assertEqual(len(sparse_float_indices), 1)\n self.assertEqual(len(sparse_float_values), 1)\n self.assertEqual(len(sparse_float_shapes), 1)\n self.assertEqual(len(sparse_int_indices), 1)\n self.assertEqual(len(sparse_int_values), 1)\n self.assertEqual(len(sparse_int_shapes), 1)\n self.assertAllEqual(dense_floats[0].eval(),\n features[\"dense_float\"].eval())\n self.assertAllEqual(sparse_float_indices[0].eval(),\n features[\"sparse_float\"].indices.eval())\n self.assertAllEqual(sparse_float_values[0].eval(),\n features[\"sparse_float\"].values.eval())\n self.assertAllEqual(sparse_float_shapes[0].eval(),\n features[\"sparse_float\"].dense_shape.eval())\n self.assertAllEqual(sparse_int_indices[0].eval(),\n features[\"sparse_categorical\"].indices.eval())\n self.assertAllEqual(sparse_int_values[0].eval(), [397263, 397263])\n self.assertAllEqual(sparse_int_shapes[0].eval(),\n features[\"sparse_categorical\"].dense_shape.eval())\n\n def testExtractFeaturesFromCoreFeatureColumns(self):\n \"\"\"Tests feature extraction when using core columns.\"\"\"\n with self.test_session():\n features = {}\n # Sparse float column does not exist in core, so only dense numeric and\n # categorical.\n features[\"dense_float\"] = array_ops.zeros([2, 1], dtypes.float32)\n features[\"sparse_categorical\"] = sparse_tensor.SparseTensor(\n array_ops.zeros([2, 2], dtypes.int64),\n array_ops.zeros([2], dtypes.string), array_ops.zeros([2],\n dtypes.int64))\n\n feature_columns = set()\n feature_columns.add(core_feature_column.numeric_column(\"dense_float\"))\n feature_columns.add(\n core_feature_column.categorical_column_with_hash_bucket(\n \"sparse_categorical\", hash_bucket_size=1000000))\n (fc_names, dense_floats, _, _, _, sparse_int_indices, sparse_int_values,\n sparse_int_shapes) = (\n gbdt_batch.extract_features(\n features, feature_columns, use_core_columns=True))\n self.assertEqual(len(fc_names), 2)\n self.assertAllEqual(fc_names, [\"dense_float\", \"sparse_categorical\"])\n self.assertEqual(len(dense_floats), 1)\n self.assertEqual(len(sparse_int_indices), 1)\n self.assertEqual(len(sparse_int_values), 1)\n self.assertEqual(len(sparse_int_shapes), 1)\n self.assertAllEqual(dense_floats[0].eval(),\n features[\"dense_float\"].eval())\n self.assertAllEqual(sparse_int_indices[0].eval(),\n features[\"sparse_categorical\"].indices.eval())\n self.assertAllEqual(sparse_int_values[0].eval(), [397263, 397263])\n self.assertAllEqual(sparse_int_shapes[0].eval(),\n features[\"sparse_categorical\"].dense_shape.eval())\n\n def testTrainFnChiefNoBiasCentering(self):\n \"\"\"Tests the train function running on chief without bias centering.\"\"\"\n with self.test_session() as sess:\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.regularization.l1 = 0\n learner_config.regularization.l2 = 0\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.min_node_weight = 0\n features = {}\n features[\"dense_float\"] = array_ops.ones([4, 1], dtypes.float32)\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=True,\n num_ps_replicas=0,\n center_bias=False,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0], [1.0], [0.0], [2.0]], dtype=dtypes.float32)\n partition_ids = array_ops.zeros([4], dtypes.int32)\n ensemble_stamp = variables.Variable(\n initial_value=0,\n name=\"ensemble_stamp\",\n trainable=False,\n dtype=dtypes.int64)\n\n predictions_dict = {\n \"predictions\": predictions,\n \"predictions_no_dropout\": predictions,\n \"partition_ids\": partition_ids,\n \"ensemble_stamp\": ensemble_stamp,\n \"num_trees\": 12,\n }\n\n labels = array_ops.ones([4, 1], dtypes.float32)\n weights = array_ops.ones([4, 1], dtypes.float32)\n # Create train op.\n train_op = gbdt_model.train(\n loss=math_ops.reduce_mean(\n _squared_loss(labels, weights, predictions)),\n predictions_dict=predictions_dict,\n labels=labels)\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # On first run, expect no splits to be chosen because the quantile\n # buckets will not be ready.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 0)\n self.assertEquals(len(output.tree_weights), 0)\n self.assertEquals(stamp_token.eval(), 1)\n\n # Update the stamp to be able to run a second time.\n sess.run([ensemble_stamp.assign_add(1)])\n\n # On second run, expect a trivial split to be chosen to basically\n # predict the average.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 1)\n self.assertAllClose(output.tree_weights, [0.1])\n self.assertEquals(stamp_token.eval(), 2)\n expected_tree = \"\"\"\n nodes {\n dense_float_binary_split {\n threshold: 1.0\n left_id: 1\n right_id: 2\n }\n node_metadata {\n gain: 0\n }\n }\n nodes {\n leaf {\n vector {\n value: 0.25\n }\n }\n }\n nodes {\n leaf {\n vector {\n value: 0.0\n }\n }\n }\"\"\"\n self.assertProtoEquals(expected_tree, output.trees[0])\n\n def testTrainFnChiefSparseAndDense(self):\n \"\"\"Tests the train function with sparse and dense features.\"\"\"\n with self.test_session() as sess:\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.regularization.l1 = 0\n learner_config.regularization.l2 = 0\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.min_node_weight = 0\n features = {}\n features[\"dense_float\"] = array_ops.ones([4, 1], dtypes.float32)\n features[\"sparse_float\"] = sparse_tensor.SparseTensor(\n array_ops.zeros([2, 2], dtypes.int64),\n array_ops.zeros([2], dtypes.float32),\n array_ops.constant([4, 1], dtypes.int64))\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=True,\n num_ps_replicas=0,\n center_bias=False,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0], [1.0], [0.0], [2.0]], dtype=dtypes.float32)\n partition_ids = array_ops.zeros([4], dtypes.int32)\n ensemble_stamp = variables.Variable(\n initial_value=0,\n name=\"ensemble_stamp\",\n trainable=False,\n dtype=dtypes.int64)\n\n predictions_dict = {\n \"predictions\": predictions,\n \"predictions_no_dropout\": predictions,\n \"partition_ids\": partition_ids,\n \"ensemble_stamp\": ensemble_stamp,\n \"num_trees\": 12,\n }\n\n labels = array_ops.ones([4, 1], dtypes.float32)\n weights = array_ops.ones([4, 1], dtypes.float32)\n # Create train op.\n train_op = gbdt_model.train(\n loss=math_ops.reduce_mean(\n _squared_loss(labels, weights, predictions)),\n predictions_dict=predictions_dict,\n labels=labels)\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # On first run, expect no splits to be chosen because the quantile\n # buckets will not be ready.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 0)\n self.assertEquals(len(output.tree_weights), 0)\n self.assertEquals(stamp_token.eval(), 1)\n\n # Update the stamp to be able to run a second time.\n sess.run([ensemble_stamp.assign_add(1)])\n\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 1)\n self.assertAllClose(output.tree_weights, [0.1])\n self.assertEquals(stamp_token.eval(), 2)\n expected_tree = \"\"\"\n nodes {\n sparse_float_binary_split_default_right {\n split{\n left_id: 1\n right_id: 2\n }\n }\n node_metadata {\n gain: 1.125\n }\n }\n nodes {\n leaf {\n vector {\n value: 1.0\n }\n }\n }\n nodes {\n leaf {\n vector {\n value: -0.5\n }\n }\n }\"\"\"\n self.assertProtoEquals(expected_tree, output.trees[0])\n\n def testTrainFnChiefScalingNumberOfExamples(self):\n \"\"\"Tests the train function running on chief without bias centering.\"\"\"\n with self.test_session() as sess:\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.regularization.l1 = 0\n learner_config.regularization.l2 = 0\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.min_node_weight = 0\n num_examples_fn = (\n lambda layer: math_ops.pow(math_ops.cast(2, dtypes.int64), layer) * 1)\n features = {}\n features[\"dense_float\"] = array_ops.ones([4, 1], dtypes.float32)\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=True,\n num_ps_replicas=0,\n center_bias=False,\n ensemble_handle=ensemble_handle,\n examples_per_layer=num_examples_fn,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0], [1.0], [0.0], [2.0]], dtype=dtypes.float32)\n partition_ids = array_ops.zeros([4], dtypes.int32)\n ensemble_stamp = variables.Variable(\n initial_value=0,\n name=\"ensemble_stamp\",\n trainable=False,\n dtype=dtypes.int64)\n\n predictions_dict = {\n \"predictions\": predictions,\n \"predictions_no_dropout\": predictions,\n \"partition_ids\": partition_ids,\n \"ensemble_stamp\": ensemble_stamp,\n \"num_trees\": 12,\n }\n\n labels = array_ops.ones([4, 1], dtypes.float32)\n weights = array_ops.ones([4, 1], dtypes.float32)\n # Create train op.\n train_op = gbdt_model.train(\n loss=math_ops.reduce_mean(\n _squared_loss(labels, weights, predictions)),\n predictions_dict=predictions_dict,\n labels=labels)\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # On first run, expect no splits to be chosen because the quantile\n # buckets will not be ready.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 0)\n self.assertEquals(len(output.tree_weights), 0)\n self.assertEquals(stamp_token.eval(), 1)\n\n # Update the stamp to be able to run a second time.\n sess.run([ensemble_stamp.assign_add(1)])\n\n # On second run, expect a trivial split to be chosen to basically\n # predict the average.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 1)\n self.assertAllClose(output.tree_weights, [0.1])\n self.assertEquals(stamp_token.eval(), 2)\n expected_tree = \"\"\"\n nodes {\n dense_float_binary_split {\n threshold: 1.0\n left_id: 1\n right_id: 2\n }\n node_metadata {\n gain: 0\n }\n }\n nodes {\n leaf {\n vector {\n value: 0.25\n }\n }\n }\n nodes {\n leaf {\n vector {\n value: 0.0\n }\n }\n }\"\"\"\n self.assertProtoEquals(expected_tree, output.trees[0])\n\n def testTrainFnChiefWithBiasCentering(self):\n \"\"\"Tests the train function running on chief with bias centering.\"\"\"\n with self.test_session():\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.regularization.l1 = 0\n learner_config.regularization.l2 = 0\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.min_node_weight = 0\n features = {}\n features[\"dense_float\"] = array_ops.ones([4, 1], dtypes.float32)\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=True,\n num_ps_replicas=0,\n center_bias=True,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0], [1.0], [0.0], [2.0]], dtype=dtypes.float32)\n partition_ids = array_ops.zeros([4], dtypes.int32)\n ensemble_stamp = variables.Variable(\n initial_value=0,\n name=\"ensemble_stamp\",\n trainable=False,\n dtype=dtypes.int64)\n\n predictions_dict = {\n \"predictions\": predictions,\n \"predictions_no_dropout\": predictions,\n \"partition_ids\": partition_ids,\n \"ensemble_stamp\": ensemble_stamp,\n \"num_trees\": 12,\n }\n\n labels = array_ops.ones([4, 1], dtypes.float32)\n weights = array_ops.ones([4, 1], dtypes.float32)\n # Create train op.\n train_op = gbdt_model.train(\n loss=math_ops.reduce_mean(\n _squared_loss(labels, weights, predictions)),\n predictions_dict=predictions_dict,\n labels=labels)\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # On first run, expect bias to be centered.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n expected_tree = \"\"\"\n nodes {\n leaf {\n vector {\n value: 0.25\n }\n }\n }\"\"\"\n self.assertEquals(len(output.trees), 1)\n self.assertAllEqual(output.tree_weights, [1.0])\n self.assertProtoEquals(expected_tree, output.trees[0])\n self.assertEquals(stamp_token.eval(), 1)\n\n def testTrainFnNonChiefNoBiasCentering(self):\n \"\"\"Tests the train function running on worker without bias centering.\"\"\"\n with self.test_session():\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.regularization.l1 = 0\n learner_config.regularization.l2 = 0\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.min_node_weight = 0\n features = {}\n features[\"dense_float\"] = array_ops.ones([4, 1], dtypes.float32)\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=False,\n num_ps_replicas=0,\n center_bias=False,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0], [1.0], [0.0], [2.0]], dtype=dtypes.float32)\n partition_ids = array_ops.zeros([4], dtypes.int32)\n ensemble_stamp = variables.Variable(\n initial_value=0,\n name=\"ensemble_stamp\",\n trainable=False,\n dtype=dtypes.int64)\n\n predictions_dict = {\n \"predictions\": predictions,\n \"predictions_no_dropout\": predictions,\n \"partition_ids\": partition_ids,\n \"ensemble_stamp\": ensemble_stamp\n }\n\n labels = array_ops.ones([4, 1], dtypes.float32)\n weights = array_ops.ones([4, 1], dtypes.float32)\n # Create train op.\n train_op = gbdt_model.train(\n loss=math_ops.reduce_mean(\n _squared_loss(labels, weights, predictions)),\n predictions_dict=predictions_dict,\n labels=labels)\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # Regardless of how many times the train op is run, a non-chief worker\n # can only accumulate stats so the tree ensemble never changes.\n for _ in range(5):\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 0)\n self.assertEquals(len(output.tree_weights), 0)\n self.assertEquals(stamp_token.eval(), 0)\n\n def testTrainFnNonChiefWithCentering(self):\n \"\"\"Tests the train function running on worker with bias centering.\"\"\"\n with self.test_session():\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.regularization.l1 = 0\n learner_config.regularization.l2 = 0\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.min_node_weight = 0\n features = {}\n features[\"dense_float\"] = array_ops.ones([4, 1], dtypes.float32)\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=False,\n num_ps_replicas=0,\n center_bias=True,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0], [1.0], [0.0], [2.0]], dtype=dtypes.float32)\n partition_ids = array_ops.zeros([4], dtypes.int32)\n ensemble_stamp = variables.Variable(\n initial_value=0,\n name=\"ensemble_stamp\",\n trainable=False,\n dtype=dtypes.int64)\n\n predictions_dict = {\n \"predictions\": predictions,\n \"predictions_no_dropout\": predictions,\n \"partition_ids\": partition_ids,\n \"ensemble_stamp\": ensemble_stamp\n }\n\n labels = array_ops.ones([4, 1], dtypes.float32)\n weights = array_ops.ones([4, 1], dtypes.float32)\n # Create train op.\n train_op = gbdt_model.train(\n loss=math_ops.reduce_mean(\n _squared_loss(labels, weights, predictions)),\n predictions_dict=predictions_dict,\n labels=labels)\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # Regardless of how many times the train op is run, a non-chief worker\n # can only accumulate stats so the tree ensemble never changes.\n for _ in range(5):\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 0)\n self.assertEquals(len(output.tree_weights), 0)\n self.assertEquals(stamp_token.eval(), 0)\n\n def testPredictFn(self):\n \"\"\"Tests the predict function.\"\"\"\n with self.test_session() as sess:\n # Create ensemble with one bias node.\n ensemble_config = tree_config_pb2.DecisionTreeEnsembleConfig()\n text_format.Merge(\n \"\"\"\n trees {\n nodes {\n leaf {\n vector {\n value: 0.25\n }\n }\n }\n }\n tree_weights: 1.0\n tree_metadata {\n num_tree_weight_updates: 1\n num_layers_grown: 1\n is_finalized: true\n }\"\"\", ensemble_config)\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=3,\n tree_ensemble_config=ensemble_config.SerializeToString(),\n name=\"tree_ensemble\")\n resources.initialize_resources(resources.shared_resources()).run()\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.regularization.l1 = 0\n learner_config.regularization.l2 = 0\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.min_node_weight = 0\n features = {}\n features[\"dense_float\"] = array_ops.ones([4, 1], dtypes.float32)\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=False,\n num_ps_replicas=0,\n center_bias=True,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n # Create predict op.\n mode = model_fn.ModeKeys.EVAL\n predictions_dict = sess.run(gbdt_model.predict(mode))\n self.assertEquals(predictions_dict[\"ensemble_stamp\"], 3)\n self.assertAllClose(predictions_dict[\"predictions\"],\n [[0.25], [0.25], [0.25], [0.25]])\n self.assertAllClose(predictions_dict[\"partition_ids\"], [0, 0, 0, 0])\n\n def testPredictFnWithLeafIndexAdvancedLeft(self):\n \"\"\"Tests the predict function with output leaf ids.\"\"\"\n with self.test_session() as sess:\n # Create ensemble with one bias node.\n ensemble_config = tree_config_pb2.DecisionTreeEnsembleConfig()\n text_format.Merge(\n \"\"\"\n trees {\n nodes {\n dense_float_binary_split {\n threshold: 1.0\n left_id: 1\n right_id: 2\n }\n node_metadata {\n gain: 0\n }\n }\n nodes {\n leaf {\n vector {\n value: 0.25\n }\n }\n }\n nodes {\n leaf {\n vector {\n value: 0.15\n }\n }\n }\n }\n trees {\n nodes {\n dense_float_binary_split {\n threshold: 0.99\n left_id: 1\n right_id: 2\n }\n node_metadata {\n gain: 00\n }\n }\n nodes {\n leaf {\n vector {\n value: 0.25\n }\n }\n }\n nodes {\n leaf {\n vector {\n value: 0.23\n }\n }\n }\n }\n tree_weights: 1.0\n tree_weights: 1.0\n tree_metadata {\n num_tree_weight_updates: 1\n num_layers_grown: 1\n is_finalized: true\n }\n tree_metadata {\n num_tree_weight_updates: 1\n num_layers_grown: 1\n is_finalized: true\n }\"\"\", ensemble_config)\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=3,\n tree_ensemble_config=ensemble_config.SerializeToString(),\n name=\"tree_ensemble\")\n resources.initialize_resources(resources.shared_resources()).run()\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.regularization.l1 = 0\n learner_config.regularization.l2 = 0\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.min_node_weight = 0\n features = {}\n features[\"dense_float\"] = array_ops.constant(\n [[0.0], [1.0], [1.1], [2.0]], dtype=dtypes.float32)\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=False,\n num_ps_replicas=0,\n center_bias=True,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features,\n output_leaf_index=True)\n\n # Create predict op.\n mode = model_fn.ModeKeys.INFER\n predictions_dict = sess.run(gbdt_model.predict(mode))\n self.assertEquals(predictions_dict[\"ensemble_stamp\"], 3)\n # here are how the numbers in expected results are calculated,\n # 0.5 = 0.25 + 0.25\n # 0.48 = 0.25 + 0.23\n # 0.38 = 0.15 + 0.23\n # 0.38 = 0.15 + 0.23\n self.assertAllClose(predictions_dict[\"predictions\"],\n [[0.5], [0.48], [0.38], [0.38]])\n self.assertAllClose(predictions_dict[\"partition_ids\"], [0, 0, 0, 0])\n self.assertAllClose(predictions_dict[\"leaf_index\"],\n [[1, 1], [1, 2], [2, 2], [2, 2]])\n\n def testTrainFnMulticlassFullHessian(self):\n \"\"\"Tests the GBDT train for multiclass full hessian.\"\"\"\n with self.test_session() as sess:\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 1\n # Use full hessian multiclass strategy.\n learner_config.multi_class_strategy = (\n learner_pb2.LearnerConfig.FULL_HESSIAN)\n learner_config.num_classes = 5\n learner_config.regularization.l1 = 0\n # To make matrix inversible.\n learner_config.regularization.l2 = 1e-5\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.min_node_weight = 0\n features = {}\n batch_size = 3\n features[\"dense_float\"] = array_ops.constant(\n [0.3, 1.5, 1.1], dtype=dtypes.float32)\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=True,\n num_ps_replicas=0,\n center_bias=False,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=5,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0, -1.0, 0.5, 1.2, 3.1], [1.0, 0.0, 0.8, 0.3, 1.0],\n [0.0, 0.0, 0.0, 0.0, 1.2]],\n dtype=dtypes.float32)\n\n labels = array_ops.constant([[2], [2], [3]], dtype=dtypes.float32)\n weights = array_ops.ones([batch_size, 1], dtypes.float32)\n\n partition_ids = array_ops.zeros([batch_size], dtypes.int32)\n ensemble_stamp = variables.Variable(\n initial_value=0,\n name=\"ensemble_stamp\",\n trainable=False,\n dtype=dtypes.int64)\n\n predictions_dict = {\n \"predictions\": predictions,\n \"predictions_no_dropout\": predictions,\n \"partition_ids\": partition_ids,\n \"ensemble_stamp\": ensemble_stamp,\n \"num_trees\": 0,\n }\n\n # Create train op.\n train_op = gbdt_model.train(\n loss=math_ops.reduce_mean(\n losses.per_example_maxent_loss(\n labels,\n weights,\n predictions,\n num_classes=learner_config.num_classes)[0]),\n predictions_dict=predictions_dict,\n labels=labels)\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # On first run, expect no splits to be chosen because the quantile\n # buckets will not be ready.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 0)\n self.assertEquals(len(output.tree_weights), 0)\n self.assertEquals(stamp_token.eval(), 1)\n\n # Update the stamp to be able to run a second time.\n sess.run([ensemble_stamp.assign_add(1)])\n # On second run, expect a trivial split to be chosen to basically\n # predict the average.\n train_op.run()\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output.ParseFromString(serialized.eval())\n self.assertEqual(len(output.trees), 1)\n # We got 3 nodes: one parent and 2 leafs.\n self.assertEqual(len(output.trees[0].nodes), 3)\n self.assertAllClose(output.tree_weights, [1])\n self.assertEquals(stamp_token.eval(), 2)\n\n # Leafs should have a dense vector of size 5.\n expected_leaf_1 = [-3.4480, -3.4429, 13.8490, -3.45, -3.4508]\n expected_leaf_2 = [-1.2547, -1.3145, 1.52, 2.3875, -1.3264]\n self.assertArrayNear(expected_leaf_1,\n output.trees[0].nodes[1].leaf.vector.value, 1e-3)\n self.assertArrayNear(expected_leaf_2,\n output.trees[0].nodes[2].leaf.vector.value, 1e-3)\n\n def testTrainFnMulticlassDiagonalHessian(self):\n \"\"\"Tests the GBDT train for multiclass diagonal hessian.\"\"\"\n with self.test_session() as sess:\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 1\n # Use full hessian multiclass strategy.\n learner_config.multi_class_strategy = (\n learner_pb2.LearnerConfig.DIAGONAL_HESSIAN)\n learner_config.num_classes = 5\n learner_config.regularization.l1 = 0\n # To make matrix inversible.\n learner_config.regularization.l2 = 1e-5\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.min_node_weight = 0\n batch_size = 3\n features = {}\n features[\"dense_float\"] = array_ops.constant(\n [0.3, 1.5, 1.1], dtype=dtypes.float32)\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=True,\n num_ps_replicas=0,\n center_bias=False,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=5,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0, -1.0, 0.5, 1.2, 3.1], [1.0, 0.0, 0.8, 0.3, 1.0],\n [0.0, 0.0, 0.0, 0.0, 1.2]],\n dtype=dtypes.float32)\n\n labels = array_ops.constant([[2], [2], [3]], dtype=dtypes.float32)\n weights = array_ops.ones([batch_size, 1], dtypes.float32)\n\n partition_ids = array_ops.zeros([batch_size], dtypes.int32)\n ensemble_stamp = variables.Variable(\n initial_value=0,\n name=\"ensemble_stamp\",\n trainable=False,\n dtype=dtypes.int64)\n\n predictions_dict = {\n \"predictions\": predictions,\n \"predictions_no_dropout\": predictions,\n \"partition_ids\": partition_ids,\n \"ensemble_stamp\": ensemble_stamp,\n \"num_trees\": 0,\n }\n\n # Create train op.\n train_op = gbdt_model.train(\n loss=math_ops.reduce_mean(\n losses.per_example_maxent_loss(\n labels,\n weights,\n predictions,\n num_classes=learner_config.num_classes)[0]),\n predictions_dict=predictions_dict,\n labels=labels)\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # On first run, expect no splits to be chosen because the quantile\n # buckets will not be ready.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEqual(len(output.trees), 0)\n self.assertEqual(len(output.tree_weights), 0)\n self.assertEqual(stamp_token.eval(), 1)\n\n # Update the stamp to be able to run a second time.\n sess.run([ensemble_stamp.assign_add(1)])\n # On second run, expect a trivial split to be chosen to basically\n # predict the average.\n train_op.run()\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output.ParseFromString(serialized.eval())\n self.assertEqual(len(output.trees), 1)\n # We got 3 nodes: one parent and 2 leafs.\n self.assertEqual(len(output.trees[0].nodes), 3)\n self.assertAllClose(output.tree_weights, [1])\n self.assertEqual(stamp_token.eval(), 2)\n\n # Leafs should have a dense vector of size 5.\n expected_leaf_1 = [-1.0354, -1.0107, 17.2976, -1.1313, -4.5023]\n expected_leaf_2 = [-1.2924, -1.1376, 2.2042, 3.1052, -1.6269]\n self.assertArrayNear(expected_leaf_1,\n output.trees[0].nodes[1].leaf.vector.value, 1e-3)\n self.assertArrayNear(expected_leaf_2,\n output.trees[0].nodes[2].leaf.vector.value, 1e-3)\n\n def testTrainFnMulticlassTreePerClass(self):\n \"\"\"Tests the GBDT train for multiclass tree per class strategy.\"\"\"\n with self.test_session() as sess:\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 1\n # Use full hessian multiclass strategy.\n learner_config.multi_class_strategy = (\n learner_pb2.LearnerConfig.TREE_PER_CLASS)\n learner_config.num_classes = 5\n learner_config.regularization.l1 = 0\n # To make matrix inversible.\n learner_config.regularization.l2 = 1e-5\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.min_node_weight = 0\n features = {\n \"dense_float\":\n array_ops.constant([[1.0], [1.5], [2.0]], dtypes.float32),\n }\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=True,\n num_ps_replicas=0,\n center_bias=False,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=5,\n features=features)\n\n batch_size = 3\n predictions = array_ops.constant(\n [[0.0, -1.0, 0.5, 1.2, 3.1], [1.0, 0.0, 0.8, 0.3, 1.0],\n [0.0, 0.0, 0.0, 2.0, 1.2]],\n dtype=dtypes.float32)\n\n labels = array_ops.constant([[2], [2], [3]], dtype=dtypes.float32)\n weights = array_ops.ones([batch_size, 1], dtypes.float32)\n\n partition_ids = array_ops.zeros([batch_size], dtypes.int32)\n ensemble_stamp = variables.Variable(\n initial_value=0,\n name=\"ensemble_stamp\",\n trainable=False,\n dtype=dtypes.int64)\n\n predictions_dict = {\n \"predictions\": predictions,\n \"predictions_no_dropout\": predictions,\n \"partition_ids\": partition_ids,\n \"ensemble_stamp\": ensemble_stamp,\n # This should result in a tree built for a class 2.\n \"num_trees\": 13,\n }\n\n # Create train op.\n train_op = gbdt_model.train(\n loss=math_ops.reduce_mean(\n losses.per_example_maxent_loss(\n labels,\n weights,\n predictions,\n num_classes=learner_config.num_classes)[0]),\n predictions_dict=predictions_dict,\n labels=labels)\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # On first run, expect no splits to be chosen because the quantile\n # buckets will not be ready.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEqual(len(output.trees), 0)\n self.assertEqual(len(output.tree_weights), 0)\n self.assertEqual(stamp_token.eval(), 1)\n\n # Update the stamp to be able to run a second time.\n sess.run([ensemble_stamp.assign_add(1)])\n # On second run, expect a trivial split to be chosen to basically\n # predict the average.\n train_op.run()\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output.ParseFromString(serialized.eval())\n self.assertEqual(len(output.trees), 1)\n self.assertAllClose(output.tree_weights, [1])\n self.assertEqual(stamp_token.eval(), 2)\n\n # One node for a split, two children nodes.\n self.assertEqual(3, len(output.trees[0].nodes))\n\n # Leafs will have a sparse vector for class 3.\n self.assertEqual(1,\n len(output.trees[0].nodes[1].leaf.sparse_vector.index))\n self.assertEqual(3, output.trees[0].nodes[1].leaf.sparse_vector.index[0])\n self.assertAlmostEqual(\n -1.13134455681, output.trees[0].nodes[1].leaf.sparse_vector.value[0])\n\n self.assertEqual(1,\n len(output.trees[0].nodes[2].leaf.sparse_vector.index))\n self.assertEqual(3, output.trees[0].nodes[2].leaf.sparse_vector.index[0])\n self.assertAllClose(\n 0.893284678459,\n output.trees[0].nodes[2].leaf.sparse_vector.value[0],\n atol=1e-4,\n rtol=1e-4)\n\n def testTrainFnChiefFeatureSelectionReachedLimitNoGoodSplit(self):\n \"\"\"Tests the train function running on chief with feature selection.\"\"\"\n with self.test_session() as sess:\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.regularization.l1 = 0\n learner_config.regularization.l2 = 0\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.max_number_of_unique_feature_columns = 1\n learner_config.constraints.min_node_weight = 0\n features = {}\n features[\"dense_float_0\"] = array_ops.ones([4, 1], dtypes.float32)\n # Feature 1 is predictive but it won't be used because we have reached the\n # limit of num_used_handlers >= max_number_of_unique_feature_columns\n features[\"dense_float_1\"] = array_ops.constant([0, 0, 1, 1],\n dtypes.float32)\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=True,\n num_ps_replicas=0,\n center_bias=False,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0], [1.0], [0.0], [2.0]], dtype=dtypes.float32)\n partition_ids = array_ops.zeros([4], dtypes.int32)\n ensemble_stamp = variables.Variable(\n initial_value=0,\n name=\"ensemble_stamp\",\n trainable=False,\n dtype=dtypes.int64)\n\n predictions_dict = {\n \"predictions\":\n predictions,\n \"predictions_no_dropout\":\n predictions,\n \"partition_ids\":\n partition_ids,\n \"ensemble_stamp\":\n ensemble_stamp,\n \"num_trees\":\n 12,\n \"num_used_handlers\":\n array_ops.constant(1, dtype=dtypes.int64),\n \"used_handlers_mask\":\n array_ops.constant([True, False], dtype=dtypes.bool),\n }\n\n labels = array_ops.constant([0, 0, 1, 1], dtypes.float32)\n weights = array_ops.ones([4, 1], dtypes.float32)\n # Create train op.\n train_op = gbdt_model.train(\n loss=math_ops.reduce_mean(\n _squared_loss(labels, weights, predictions)),\n predictions_dict=predictions_dict,\n labels=labels)\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # On first run, expect no splits to be chosen because the quantile\n # buckets will not be ready.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 0)\n self.assertEquals(len(output.tree_weights), 0)\n self.assertEquals(stamp_token.eval(), 1)\n\n # Update the stamp to be able to run a second time.\n sess.run([ensemble_stamp.assign_add(1)])\n\n # On second run, expect a trivial split to be chosen to basically\n # predict the average.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 1)\n self.assertAllClose(output.tree_weights, [0.1])\n self.assertEquals(stamp_token.eval(), 2)\n expected_tree = \"\"\"\n nodes {\n dense_float_binary_split {\n feature_column: 0\n threshold: 1.0\n left_id: 1\n right_id: 2\n }\n node_metadata {\n gain: 0\n }\n }\n nodes {\n leaf {\n vector {\n value: -0.25\n }\n }\n }\n nodes {\n leaf {\n vector {\n value: 0.0\n }\n }\n }\"\"\"\n self.assertProtoEquals(expected_tree, output.trees[0])\n\n def testTrainFnChiefFeatureSelectionWithGoodSplits(self):\n \"\"\"Tests the train function running on chief with feature selection.\"\"\"\n with self.test_session() as sess:\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.regularization.l1 = 0\n learner_config.regularization.l2 = 0\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.max_number_of_unique_feature_columns = 1\n learner_config.constraints.min_node_weight = 0\n features = {}\n features[\"dense_float_0\"] = array_ops.ones([4, 1], dtypes.float32)\n # Feature 1 is predictive and is in our selected features so it will be\n # used even when we're at the limit.\n features[\"dense_float_1\"] = array_ops.constant([0, 0, 1, 1],\n dtypes.float32)\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=True,\n num_ps_replicas=0,\n center_bias=False,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0], [1.0], [0.0], [2.0]], dtype=dtypes.float32)\n partition_ids = array_ops.zeros([4], dtypes.int32)\n ensemble_stamp = variables.Variable(\n initial_value=0,\n name=\"ensemble_stamp\",\n trainable=False,\n dtype=dtypes.int64)\n\n predictions_dict = {\n \"predictions\":\n predictions,\n \"predictions_no_dropout\":\n predictions,\n \"partition_ids\":\n partition_ids,\n \"ensemble_stamp\":\n ensemble_stamp,\n \"num_trees\":\n 12,\n \"num_used_handlers\":\n array_ops.constant(1, dtype=dtypes.int64),\n \"used_handlers_mask\":\n array_ops.constant([False, True], dtype=dtypes.bool),\n }\n\n labels = array_ops.constant([0, 0, 1, 1], dtypes.float32)\n weights = array_ops.ones([4, 1], dtypes.float32)\n # Create train op.\n train_op = gbdt_model.train(\n loss=math_ops.reduce_mean(\n _squared_loss(labels, weights, predictions)),\n predictions_dict=predictions_dict,\n labels=labels)\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # On first run, expect no splits to be chosen because the quantile\n # buckets will not be ready.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 0)\n self.assertEquals(len(output.tree_weights), 0)\n self.assertEquals(stamp_token.eval(), 1)\n\n # Update the stamp to be able to run a second time.\n sess.run([ensemble_stamp.assign_add(1)])\n\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n\n self.assertEquals(len(output.trees), 1)\n self.assertAllClose(output.tree_weights, [0.1])\n self.assertEquals(stamp_token.eval(), 2)\n expected_tree = \"\"\"\n nodes {\n dense_float_binary_split {\n feature_column: 1\n left_id: 1\n right_id: 2\n }\n node_metadata {\n gain: 0.5\n }\n }\n nodes {\n leaf {\n vector {\n value: 0.0\n }\n }\n }\n nodes {\n leaf {\n vector {\n value: -0.5\n }\n }\n }\"\"\"\n self.assertProtoEquals(expected_tree, output.trees[0])\n\n def testTrainFnChiefFeatureSelectionReachedLimitIncrementAttemptedLayer(self):\n \"\"\"Tests the train function running on chief with feature selection.\"\"\"\n with self.test_session() as sess:\n tree_ensemble_config = tree_config_pb2.DecisionTreeEnsembleConfig()\n tree = tree_ensemble_config.trees.add()\n\n _set_float_split(\n tree.nodes.add().sparse_float_binary_split_default_right.split, 2,\n 4.0, 1, 2)\n _append_to_leaf(tree.nodes.add().leaf, 0, 0.5)\n _append_to_leaf(tree.nodes.add().leaf, 1, 1.2)\n tree_ensemble_config.tree_weights.append(1.0)\n metadata = tree_ensemble_config.tree_metadata.add()\n metadata.is_finalized = False\n metadata.num_layers_grown = 1\n tree_ensemble_config = tree_ensemble_config.SerializeToString()\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0,\n tree_ensemble_config=tree_ensemble_config,\n name=\"tree_ensemble\")\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.regularization.l1 = 0\n learner_config.regularization.l2 = 0\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.max_number_of_unique_feature_columns = 1\n learner_config.constraints.min_node_weight = 0\n features = {}\n # Both features will be disabled since the feature selection limit is\n # already reached.\n features[\"dense_float_0\"] = array_ops.ones([4, 1], dtypes.float32)\n features[\"dense_float_1\"] = array_ops.constant([0, 0, 1, 1],\n dtypes.float32)\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=True,\n num_ps_replicas=0,\n center_bias=False,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0], [1.0], [0.0], [2.0]], dtype=dtypes.float32)\n partition_ids = array_ops.zeros([4], dtypes.int32)\n ensemble_stamp = variables.Variable(\n initial_value=0,\n name=\"ensemble_stamp\",\n trainable=False,\n dtype=dtypes.int64)\n\n predictions_dict = {\n \"predictions\":\n predictions,\n \"predictions_no_dropout\":\n predictions,\n \"partition_ids\":\n partition_ids,\n \"ensemble_stamp\":\n ensemble_stamp,\n \"num_trees\":\n 12,\n # We have somehow reached our limit 1. Both of the handlers will be\n # disabled.\n \"num_used_handlers\":\n array_ops.constant(1, dtype=dtypes.int64),\n \"used_handlers_mask\":\n array_ops.constant([False, False], dtype=dtypes.bool),\n }\n\n labels = array_ops.constant([0, 0, 1, 1], dtypes.float32)\n weights = array_ops.ones([4, 1], dtypes.float32)\n # Create train op.\n train_op = gbdt_model.train(\n loss=math_ops.reduce_mean(\n _squared_loss(labels, weights, predictions)),\n predictions_dict=predictions_dict,\n labels=labels)\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # On first run, expect no splits to be chosen because the quantile\n # buckets will not be ready.\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 1)\n self.assertEquals(output.growing_metadata.num_layers_attempted, 1)\n self.assertEquals(stamp_token.eval(), 1)\n\n # Update the stamp to be able to run a second time.\n sess.run([ensemble_stamp.assign_add(1)])\n\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n # Make sure the trees are not modified, but the num_layers_attempted is\n # incremented so that eventually the training stops.\n self.assertEquals(len(output.trees), 1)\n self.assertEquals(len(output.trees[0].nodes), 3)\n\n self.assertEquals(output.growing_metadata.num_layers_attempted, 2)\n\n def testResetModelBeforeAndAfterSplit(self):\n \"\"\"Tests whether resetting works.\"\"\"\n with self.test_session():\n # First build a small tree and train it to verify training works.\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.constraints.max_tree_depth = 1\n features = {}\n features[\"dense_float\"] = array_ops.ones([4, 1], dtypes.float32)\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=True,\n num_ps_replicas=0,\n center_bias=False,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0], [1.0], [0.0], [2.0]], dtype=dtypes.float32)\n partition_ids = array_ops.zeros([4], dtypes.int32)\n ensemble_stamp = model_ops.tree_ensemble_stamp_token(ensemble_handle)\n\n predictions_dict = {\n \"predictions\": predictions,\n \"predictions_no_dropout\": predictions,\n \"partition_ids\": partition_ids,\n \"ensemble_stamp\": ensemble_stamp,\n \"num_trees\": 12,\n \"max_tree_depth\": 4,\n }\n\n labels = array_ops.ones([4, 1], dtypes.float32)\n weights = array_ops.ones([4, 1], dtypes.float32)\n loss = math_ops.reduce_mean(_squared_loss(labels, weights, predictions))\n\n # Create train op.\n update_op, reset_op, training_state = gbdt_model.update_stats(\n loss, predictions_dict)\n with ops.control_dependencies(update_op):\n train_op = gbdt_model.increment_step_counter_and_maybe_update_ensemble(\n predictions_dict, training_state)\n\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n original_stamp = ensemble_stamp.eval()\n expected_tree = \"\"\"\n nodes {\n dense_float_binary_split {\n threshold: 1.0\n left_id: 1\n right_id: 2\n }\n node_metadata {\n gain: 0\n }\n }\n nodes {\n leaf {\n vector {\n value: 0.25\n }\n }\n }\n nodes {\n leaf {\n vector {\n value: 0.0\n }\n }\n }\"\"\"\n\n def _train_once_and_check(expect_split):\n stamp = ensemble_stamp.eval()\n train_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(stamp_token.eval(), stamp + 1)\n if expect_split:\n # State of the ensemble after a split occurs.\n self.assertEquals(len(output.trees), 1)\n self.assertProtoEquals(expected_tree, output.trees[0])\n else:\n # State of the ensemble after a single accumulation but before any\n # splitting occurs\n self.assertEquals(len(output.trees), 0)\n self.assertProtoEquals(\"\"\"\n growing_metadata {\n num_trees_attempted: 1\n num_layers_attempted: 1\n }\"\"\", output)\n\n def _run_reset():\n stamp_before_reset = ensemble_stamp.eval()\n reset_op.run()\n stamp_after_reset = ensemble_stamp.eval()\n self.assertNotEquals(stamp_after_reset, stamp_before_reset)\n\n _, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertProtoEquals(\"\", output)\n\n return stamp_after_reset\n\n # Exit after one train_op, so no new layer are created but the handlers\n # contain enough information to split on the next call to train.\n _train_once_and_check(expect_split=False)\n self.assertEquals(ensemble_stamp.eval(), original_stamp + 1)\n\n # Reset the handlers so it still requires two training calls to split.\n stamp_after_reset = _run_reset()\n\n _train_once_and_check(expect_split=False)\n _train_once_and_check(expect_split=True)\n self.assertEquals(ensemble_stamp.eval(), stamp_after_reset + 2)\n\n # This time, test that the reset_op works right after splitting.\n stamp_after_reset = _run_reset()\n\n # Test that after resetting, the tree can be trained as normal.\n _train_once_and_check(expect_split=False)\n _train_once_and_check(expect_split=True)\n self.assertEquals(ensemble_stamp.eval(), stamp_after_reset + 2)\n\n def testResetModelNonChief(self):\n \"\"\"Tests the reset function on a non-chief worker.\"\"\"\n with self.test_session():\n # Create ensemble with one bias node.\n ensemble_config = tree_config_pb2.DecisionTreeEnsembleConfig()\n text_format.Merge(\n \"\"\"\n trees {\n nodes {\n leaf {\n vector {\n value: 0.25\n }\n }\n }\n }\n tree_weights: 1.0\n tree_metadata {\n num_tree_weight_updates: 1\n num_layers_grown: 1\n is_finalized: false\n }\"\"\", ensemble_config)\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0,\n tree_ensemble_config=ensemble_config.SerializeToString(),\n name=\"tree_ensemble\")\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.constraints.max_tree_depth = 1\n features = {}\n features[\"dense_float\"] = array_ops.ones([4, 1], dtypes.float32)\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=False,\n num_ps_replicas=0,\n center_bias=False,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0], [1.0], [0.0], [2.0]], dtype=dtypes.float32)\n partition_ids = array_ops.zeros([4], dtypes.int32)\n ensemble_stamp = model_ops.tree_ensemble_stamp_token(ensemble_handle)\n\n predictions_dict = {\n \"predictions\": predictions,\n \"predictions_no_dropout\": predictions,\n \"partition_ids\": partition_ids,\n \"ensemble_stamp\": ensemble_stamp\n }\n\n labels = array_ops.ones([4, 1], dtypes.float32)\n weights = array_ops.ones([4, 1], dtypes.float32)\n loss = math_ops.reduce_mean(_squared_loss(labels, weights, predictions))\n\n # Create reset op.\n _, reset_op, _ = gbdt_model.update_stats(\n loss, predictions_dict)\n\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # Reset op doesn't do anything because this is a non-chief worker.\n reset_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 1)\n self.assertEquals(len(output.tree_weights), 1)\n self.assertEquals(stamp_token.eval(), 0)\n\n def testResetModelWithCenterBias(self):\n \"\"\"Tests the reset function running on chief with bias centering.\"\"\"\n with self.test_session():\n ensemble_handle = model_ops.tree_ensemble_variable(\n stamp_token=0, tree_ensemble_config=\"\", name=\"tree_ensemble\")\n learner_config = learner_pb2.LearnerConfig()\n learner_config.learning_rate_tuner.fixed.learning_rate = 0.1\n learner_config.num_classes = 2\n learner_config.regularization.l1 = 0\n learner_config.regularization.l2 = 0\n learner_config.constraints.max_tree_depth = 1\n learner_config.constraints.min_node_weight = 0\n features = {}\n features[\"dense_float\"] = array_ops.ones([4, 1], dtypes.float32)\n\n gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(\n is_chief=True,\n num_ps_replicas=0,\n center_bias=True,\n ensemble_handle=ensemble_handle,\n examples_per_layer=1,\n learner_config=learner_config,\n logits_dimension=1,\n features=features)\n\n predictions = array_ops.constant(\n [[0.0], [1.0], [0.0], [2.0]], dtype=dtypes.float32)\n partition_ids = array_ops.zeros([4], dtypes.int32)\n ensemble_stamp = model_ops.tree_ensemble_stamp_token(ensemble_handle)\n\n predictions_dict = {\n \"predictions\": predictions,\n \"predictions_no_dropout\": predictions,\n \"partition_ids\": partition_ids,\n \"ensemble_stamp\": ensemble_stamp,\n \"num_trees\": 12,\n }\n\n labels = array_ops.ones([4, 1], dtypes.float32)\n weights = array_ops.ones([4, 1], dtypes.float32)\n loss = math_ops.reduce_mean(_squared_loss(labels, weights, predictions))\n\n # Create train op.\n update_op, reset_op, training_state = gbdt_model.update_stats(\n loss, predictions_dict)\n with ops.control_dependencies(update_op):\n train_op = gbdt_model.increment_step_counter_and_maybe_update_ensemble(\n predictions_dict, training_state)\n\n variables.global_variables_initializer().run()\n resources.initialize_resources(resources.shared_resources()).run()\n\n # On first run, expect bias to be centered.\n def train_and_check():\n train_op.run()\n _, serialized = model_ops.tree_ensemble_serialize(ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n expected_tree = \"\"\"\n nodes {\n leaf {\n vector {\n value: 0.25\n }\n }\n }\"\"\"\n self.assertEquals(len(output.trees), 1)\n self.assertAllEqual(output.tree_weights, [1.0])\n self.assertProtoEquals(expected_tree, output.trees[0])\n\n train_and_check()\n self.assertEquals(ensemble_stamp.eval(), 1)\n\n reset_op.run()\n stamp_token, serialized = model_ops.tree_ensemble_serialize(\n ensemble_handle)\n output = tree_config_pb2.DecisionTreeEnsembleConfig()\n output.ParseFromString(serialized.eval())\n self.assertEquals(len(output.trees), 0)\n self.assertEquals(len(output.tree_weights), 0)\n self.assertEquals(stamp_token.eval(), 2)\n\n train_and_check()\n self.assertEquals(ensemble_stamp.eval(), 3)\n\n\nif __name__ == \"__main__\":\n googletest.main()\n"
] | [
[
"tensorflow.contrib.boosted_trees.proto.learner_pb2.LearnerConfig",
"tensorflow.python.feature_column.feature_column_lib.categorical_column_with_hash_bucket",
"tensorflow.contrib.boosted_trees.python.ops.model_ops.tree_ensemble_stamp_token",
"tensorflow.contrib.layers.real_valued_column",
"tensorflow.python.ops.resources.shared_resources",
"tensorflow.contrib.boosted_trees.python.ops.model_ops.tree_ensemble_variable",
"tensorflow.contrib.boosted_trees.python.training.functions.gbdt_batch.extract_features",
"tensorflow.contrib.boosted_trees.python.utils.losses.per_example_maxent_loss",
"tensorflow.contrib.boosted_trees.python.ops.model_ops.tree_ensemble_serialize",
"tensorflow.contrib.boosted_trees.proto.tree_config_pb2.DecisionTreeEnsembleConfig",
"tensorflow.python.feature_column.feature_column_lib.numeric_column",
"tensorflow.python.ops.math_ops.square",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.ops.variables.global_variables_initializer",
"tensorflow.python.framework.ops.control_dependencies",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.ops.array_ops.constant",
"tensorflow.python.ops.variables.Variable",
"tensorflow.contrib.layers.python.layers.feature_column.sparse_column_with_hash_bucket",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.contrib.boosted_trees.python.training.functions.gbdt_batch.GradientBoostedDecisionTreeModel",
"tensorflow.python.platform.googletest.main",
"tensorflow.contrib.layers.feature_column._real_valued_var_len_column"
]
] |
kevin1kevin1k/bokeh | [
"9f34b5b710e2748ec803c12918ec1706098a3477"
] | [
"examples/plotting/file/custom_datetime_axis.py"
] | [
"import pandas as pd\n\nfrom bokeh.io import show, output_file\nfrom bokeh.plotting import figure\nfrom bokeh.sampledata.stocks import MSFT\n\ndf = pd.DataFrame(MSFT)[:51]\ninc = df.close > df.open\ndec = df.open > df.close\n\np = figure(plot_width=1000, title=\"MSFT Candlestick with Custom X-Axis\")\n\n# map dataframe indices to date strings and use as label overrides\np.xaxis.major_label_overrides = {\n i: date.strftime('%b %d') for i, date in enumerate(pd.to_datetime(df[\"date\"]))\n}\np.xaxis.bounds = (0, df.index[-1])\np.x_range.range_padding = 0.05\n\np.segment(df.index, df.high, df.index, df.low, color=\"black\")\np.vbar(df.index[inc], 0.5, df.open[inc], df.close[inc], fill_color=\"#D5E1DD\", line_color=\"black\")\np.vbar(df.index[dec], 0.5, df.open[dec], df.close[dec], fill_color=\"#F2583E\", line_color=\"black\")\n\noutput_file(\"custom_datetime_axis.html\", title=\"custom_datetime_axis.py example\")\n\nshow(p)\n"
] | [
[
"pandas.to_datetime",
"pandas.DataFrame"
]
] |
korolm/kaggle-mlcourse | [
"94df0346cfcf9412cd150e1b3ca5239cbe6c9521"
] | [
"assignment2/alice/features/sites.py"
] | [
"from scipy.sparse import csr_matrix\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport numpy as np\nimport pickle\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport re\n\nfrom joblib import Memory\n\ncachedir = 'cache/'\nmemory = Memory(cachedir, verbose=0)\n\npath_to_site_dict = 'data/site_dic.pkl'\n\n\ndef load_site_dict():\n with open(path_to_site_dict, 'rb') as f:\n site2id = pickle.load(f)\n id2site = {v: k for (k, v) in site2id.items()}\n # we treat site with id 0 as \"unknown\"\n id2site[0] = 'unknown'\n return id2site\n\n\nsites = ['site%s' % i for i in range(1, 11)]\nid2site = load_site_dict()\n\n\ndef transform_to_txt_format(train_df, test_df):\n train_file = 'tmp/train_sessions_text.txt'\n test_file = 'tmp/test_sessions_text.txt'\n sites = ['site%s' % i for i in range(1, 11)]\n train_df[sites].fillna(0).astype('int').to_csv(train_file,\n sep=' ',\n index=None, header=None)\n test_df[sites].fillna(0).astype('int').to_csv(test_file,\n sep=' ',\n index=None, header=None)\n return train_file, test_file\n\n\[email protected]\ndef f_sites(train_df, test_df, ngram_range=(1, 3)):\n train_file, test_file = transform_to_txt_format(train_df, test_df)\n cv = CountVectorizer(ngram_range=ngram_range, max_features=50000)\n with open(train_file) as inp_train_file:\n X_train = cv.fit_transform(inp_train_file)\n with open(test_file) as inp_test_file:\n X_test = cv.transform(inp_test_file)\n return X_train, X_test#, cv.get_feature_names()\n\n\[email protected]\ndef f_tfidf_sites(train_df, test_df, ngram_range=(1, 5), sub=False, max_features=50000):\n def join_row(row):\n return ' '.join([id2site[i] for i in row])\n\n train_sessions = train_df[sites].fillna(0).astype('int').apply(join_row, axis=1)\n test_sessions = test_df[sites].fillna(0).astype('int').apply(join_row, axis=1)\n\n vectorizer = TfidfVectorizer(ngram_range=ngram_range,\n max_features=max_features,\n tokenizer=lambda s: s.split())\n X_train = vectorizer.fit_transform(train_sessions)\n X_test = vectorizer.transform(test_sessions)\n return X_train, X_test#, vectorizer.get_feature_names()\n\n\[email protected]\ndef time_sites(train_df, test_df, ngram_range=(1, 5), max_features=50000):\n time_diff = ['time_diff_%s' % i for i in range(1, 11)]\n\n def est_session_length(s):\n if s <= 5:\n return 'small'\n if 6 <= s <= 30:\n return 'medium'\n if 31 <= s <= 90:\n return 'large'\n if 91 <= s:\n return 'extra-large'\n\n def join_row_with_time(row):\n # str_sites = []\n # for i in range(1, 11):\n # site_id = row['site%s' % i]\n # if np.isnan(site_id):\n # site_str = 'no_site'\n # else:\n # site_str = str(id2site[row['site%s' % i]])\n # diff_str = str(row['time_diff_%s' % i])\n # str_sites.append(site_str + '_' + diff_str)\n return ' '.join(['no_site' + '_' + str(row['time_diff_%s' % i])\n if np.isnan(row['site%s' % i])\n else str(id2site[row['site%s' % i]]) + '_' + str(row['time_diff_%s' % i])\n for i in range(1, 11)])\n\n for t in range(1, 10):\n train_df['time_diff_' + str(t)] = (\n (train_df['time' + str(t + 1)] - train_df['time' + str(t)]) / np.timedelta64(1, 's')).apply(\n est_session_length)\n test_df['time_diff_' + str(t)] = (\n (test_df['time' + str(t + 1)] - test_df['time' + str(t)]) / np.timedelta64(1, 's')).apply(\n est_session_length)\n\n train_df['time_diff_10'] = None\n test_df['time_diff_10'] = None\n\n train_df[sites].fillna(0).astype('int')\n test_df[sites].fillna(0).astype('int')\n train_sessions = train_df[sites + time_diff].apply(join_row_with_time, axis=1)\n\n test_sessions = test_df[sites + time_diff].apply(join_row_with_time, axis=1)\n\n vectorizer = TfidfVectorizer(ngram_range=ngram_range,\n max_features=max_features,\n tokenizer=lambda s: s.split())\n X_train = vectorizer.fit_transform(train_sessions)\n X_test = vectorizer.transform(test_sessions)\n return X_train, X_test#, vectorizer.get_feature_names()\n\n\ndef count_not_zeros(x):\n unique = set(x)\n if 0 in unique:\n unique.discard(0)\n return len(unique)\n\n\nunique_sites = lambda df: np.array([count_not_zeros(x) for x in df[sites].values]).reshape(-1, 1)\n\n\ndef f_unique(traim_df, test_df):\n return unique_sites(traim_df), unique_sites(test_df), ['unique']\n\ndef extract_unique(df):\n data = df[sites].fillna(0).astype('int')\n return csr_matrix([[sum(1 for s in np.unique(row.values) if s != 0)] for _, row in data.iterrows()])\n"
] | [
[
"numpy.timedelta64",
"numpy.unique",
"sklearn.feature_extraction.text.CountVectorizer",
"numpy.isnan"
]
] |
jalexvig/imitating_optimizer | [
"c0a62869ae678a62df9d13d1007efa0e531c6c3c"
] | [
"src/models/mnist.py"
] | [
"import os\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torchvision import datasets, transforms\n\nfrom src.models.base import BaseModel\n\n\nclass MNIST(BaseModel):\n\n def _setup(self):\n\n self.conv1 = nn.Conv2d(1, 10, kernel_size=5)\n self.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n self.conv2_drop = nn.Dropout2d()\n self.fc1 = nn.Linear(320, 50)\n self.fc2 = nn.Linear(50, 10)\n\n def forward(self, x):\n\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))\n x = x.view(-1, 320)\n x = F.relu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n\n return x\n\n def get_criterion(self):\n\n return nn.CrossEntropyLoss()\n\n def get_data_gen(self, batch_size, train=True):\n\n dpath_data = os.path.join(\n os.path.dirname(__file__),\n '..',\n '..',\n 'data'\n )\n\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST(dpath_data, train=train, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=batch_size, shuffle=True)\n\n return iter(train_loader)\n"
] | [
[
"torch.nn.Linear",
"torch.nn.Dropout2d",
"torch.nn.functional.dropout",
"torch.nn.CrossEntropyLoss",
"torch.nn.Conv2d"
]
] |
anzhao920/MicrosoftProject15_Invictus | [
"15f44eebb09561acbbe7b6730dfadf141e4c166d"
] | [
"COMP0016_2020_21_Team12-datasetsExperimentsAna/pwa/FADapp/pythonScripts/venv/Lib/site-packages/numpy/core/tests/test_dtype.py"
] | [
"import sys\r\nimport operator\r\nimport pytest\r\nimport ctypes\r\nimport gc\r\n\r\nimport numpy as np\r\nfrom numpy.core._rational_tests import rational\r\nfrom numpy.core._multiarray_tests import create_custom_field_dtype\r\nfrom numpy.testing import (\r\n assert_, assert_equal, assert_array_equal, assert_raises, HAS_REFCOUNT)\r\nfrom numpy.compat import pickle\r\nfrom itertools import permutations\r\n\r\ndef assert_dtype_equal(a, b):\r\n assert_equal(a, b)\r\n assert_equal(hash(a), hash(b),\r\n \"two equivalent types do not hash to the same value !\")\r\n\r\ndef assert_dtype_not_equal(a, b):\r\n assert_(a != b)\r\n assert_(hash(a) != hash(b),\r\n \"two different types hash to the same value !\")\r\n\r\nclass TestBuiltin:\r\n @pytest.mark.parametrize('t', [int, float, complex, np.int32, str, object,\r\n np.compat.unicode])\r\n def test_run(self, t):\r\n \"\"\"Only test hash runs at all.\"\"\"\r\n dt = np.dtype(t)\r\n hash(dt)\r\n\r\n @pytest.mark.parametrize('t', [int, float])\r\n def test_dtype(self, t):\r\n # Make sure equivalent byte order char hash the same (e.g. < and = on\r\n # little endian)\r\n dt = np.dtype(t)\r\n dt2 = dt.newbyteorder(\"<\")\r\n dt3 = dt.newbyteorder(\">\")\r\n if dt == dt2:\r\n assert_(dt.byteorder != dt2.byteorder, \"bogus test\")\r\n assert_dtype_equal(dt, dt2)\r\n else:\r\n assert_(dt.byteorder != dt3.byteorder, \"bogus test\")\r\n assert_dtype_equal(dt, dt3)\r\n\r\n def test_equivalent_dtype_hashing(self):\r\n # Make sure equivalent dtypes with different type num hash equal\r\n uintp = np.dtype(np.uintp)\r\n if uintp.itemsize == 4:\r\n left = uintp\r\n right = np.dtype(np.uint32)\r\n else:\r\n left = uintp\r\n right = np.dtype(np.ulonglong)\r\n assert_(left == right)\r\n assert_(hash(left) == hash(right))\r\n\r\n def test_invalid_types(self):\r\n # Make sure invalid type strings raise an error\r\n\r\n assert_raises(TypeError, np.dtype, 'O3')\r\n assert_raises(TypeError, np.dtype, 'O5')\r\n assert_raises(TypeError, np.dtype, 'O7')\r\n assert_raises(TypeError, np.dtype, 'b3')\r\n assert_raises(TypeError, np.dtype, 'h4')\r\n assert_raises(TypeError, np.dtype, 'I5')\r\n assert_raises(TypeError, np.dtype, 'e3')\r\n assert_raises(TypeError, np.dtype, 'f5')\r\n\r\n if np.dtype('g').itemsize == 8 or np.dtype('g').itemsize == 16:\r\n assert_raises(TypeError, np.dtype, 'g12')\r\n elif np.dtype('g').itemsize == 12:\r\n assert_raises(TypeError, np.dtype, 'g16')\r\n\r\n if np.dtype('l').itemsize == 8:\r\n assert_raises(TypeError, np.dtype, 'l4')\r\n assert_raises(TypeError, np.dtype, 'L4')\r\n else:\r\n assert_raises(TypeError, np.dtype, 'l8')\r\n assert_raises(TypeError, np.dtype, 'L8')\r\n\r\n if np.dtype('q').itemsize == 8:\r\n assert_raises(TypeError, np.dtype, 'q4')\r\n assert_raises(TypeError, np.dtype, 'Q4')\r\n else:\r\n assert_raises(TypeError, np.dtype, 'q8')\r\n assert_raises(TypeError, np.dtype, 'Q8')\r\n\r\n @pytest.mark.parametrize(\"dtype\",\r\n ['Bool', 'Complex32', 'Complex64', 'Float16', 'Float32', 'Float64',\r\n 'Int8', 'Int16', 'Int32', 'Int64', 'Object0', 'Timedelta64',\r\n 'UInt8', 'UInt16', 'UInt32', 'UInt64', 'Void0',\r\n \"Float128\", \"Complex128\"])\r\n def test_numeric_style_types_are_invalid(self, dtype):\r\n with assert_raises(TypeError):\r\n np.dtype(dtype)\r\n\r\n @pytest.mark.parametrize(\r\n 'value',\r\n ['m8', 'M8', 'datetime64', 'timedelta64',\r\n 'i4, (2,3)f8, f4', 'a3, 3u8, (3,4)a10',\r\n '>f', '<f', '=f', '|f',\r\n ])\r\n def test_dtype_bytes_str_equivalence(self, value):\r\n bytes_value = value.encode('ascii')\r\n from_bytes = np.dtype(bytes_value)\r\n from_str = np.dtype(value)\r\n assert_dtype_equal(from_bytes, from_str)\r\n\r\n def test_dtype_from_bytes(self):\r\n # Empty bytes object\r\n assert_raises(TypeError, np.dtype, b'')\r\n # Byte order indicator, but no type\r\n assert_raises(TypeError, np.dtype, b'|')\r\n\r\n # Single character with ordinal < NPY_NTYPES returns\r\n # type by index into _builtin_descrs\r\n assert_dtype_equal(np.dtype(bytes([0])), np.dtype('bool'))\r\n assert_dtype_equal(np.dtype(bytes([17])), np.dtype(object))\r\n\r\n # Single character where value is a valid type code\r\n assert_dtype_equal(np.dtype(b'f'), np.dtype('float32'))\r\n\r\n # Bytes with non-ascii values raise errors\r\n assert_raises(TypeError, np.dtype, b'\\xff')\r\n assert_raises(TypeError, np.dtype, b's\\xff')\r\n\r\n def test_bad_param(self):\r\n # Can't give a size that's too small\r\n assert_raises(ValueError, np.dtype,\r\n {'names':['f0', 'f1'],\r\n 'formats':['i4', 'i1'],\r\n 'offsets':[0, 4],\r\n 'itemsize':4})\r\n # If alignment is enabled, the alignment (4) must divide the itemsize\r\n assert_raises(ValueError, np.dtype,\r\n {'names':['f0', 'f1'],\r\n 'formats':['i4', 'i1'],\r\n 'offsets':[0, 4],\r\n 'itemsize':9}, align=True)\r\n # If alignment is enabled, the individual fields must be aligned\r\n assert_raises(ValueError, np.dtype,\r\n {'names':['f0', 'f1'],\r\n 'formats':['i1', 'f4'],\r\n 'offsets':[0, 2]}, align=True)\r\n\r\n def test_field_order_equality(self):\r\n x = np.dtype({'names': ['A', 'B'],\r\n 'formats': ['i4', 'f4'],\r\n 'offsets': [0, 4]})\r\n y = np.dtype({'names': ['B', 'A'],\r\n 'formats': ['f4', 'i4'],\r\n 'offsets': [4, 0]})\r\n assert_equal(x == y, False)\r\n # But it is currently an equivalent cast:\r\n assert np.can_cast(x, y, casting=\"equiv\")\r\n\r\n\r\nclass TestRecord:\r\n def test_equivalent_record(self):\r\n \"\"\"Test whether equivalent record dtypes hash the same.\"\"\"\r\n a = np.dtype([('yo', int)])\r\n b = np.dtype([('yo', int)])\r\n assert_dtype_equal(a, b)\r\n\r\n def test_different_names(self):\r\n # In theory, they may hash the same (collision) ?\r\n a = np.dtype([('yo', int)])\r\n b = np.dtype([('ye', int)])\r\n assert_dtype_not_equal(a, b)\r\n\r\n def test_different_titles(self):\r\n # In theory, they may hash the same (collision) ?\r\n a = np.dtype({'names': ['r', 'b'],\r\n 'formats': ['u1', 'u1'],\r\n 'titles': ['Red pixel', 'Blue pixel']})\r\n b = np.dtype({'names': ['r', 'b'],\r\n 'formats': ['u1', 'u1'],\r\n 'titles': ['RRed pixel', 'Blue pixel']})\r\n assert_dtype_not_equal(a, b)\r\n\r\n @pytest.mark.skipif(not HAS_REFCOUNT, reason=\"Python lacks refcounts\")\r\n def test_refcount_dictionary_setting(self):\r\n names = [\"name1\"]\r\n formats = [\"f8\"]\r\n titles = [\"t1\"]\r\n offsets = [0]\r\n d = dict(names=names, formats=formats, titles=titles, offsets=offsets)\r\n refcounts = {k: sys.getrefcount(i) for k, i in d.items()}\r\n np.dtype(d)\r\n refcounts_new = {k: sys.getrefcount(i) for k, i in d.items()}\r\n assert refcounts == refcounts_new\r\n\r\n def test_mutate(self):\r\n # Mutating a dtype should reset the cached hash value\r\n a = np.dtype([('yo', int)])\r\n b = np.dtype([('yo', int)])\r\n c = np.dtype([('ye', int)])\r\n assert_dtype_equal(a, b)\r\n assert_dtype_not_equal(a, c)\r\n a.names = ['ye']\r\n assert_dtype_equal(a, c)\r\n assert_dtype_not_equal(a, b)\r\n state = b.__reduce__()[2]\r\n a.__setstate__(state)\r\n assert_dtype_equal(a, b)\r\n assert_dtype_not_equal(a, c)\r\n\r\n def test_not_lists(self):\r\n \"\"\"Test if an appropriate exception is raised when passing bad values to\r\n the dtype constructor.\r\n \"\"\"\r\n assert_raises(TypeError, np.dtype,\r\n dict(names={'A', 'B'}, formats=['f8', 'i4']))\r\n assert_raises(TypeError, np.dtype,\r\n dict(names=['A', 'B'], formats={'f8', 'i4'}))\r\n\r\n def test_aligned_size(self):\r\n # Check that structured dtypes get padded to an aligned size\r\n dt = np.dtype('i4, i1', align=True)\r\n assert_equal(dt.itemsize, 8)\r\n dt = np.dtype([('f0', 'i4'), ('f1', 'i1')], align=True)\r\n assert_equal(dt.itemsize, 8)\r\n dt = np.dtype({'names':['f0', 'f1'],\r\n 'formats':['i4', 'u1'],\r\n 'offsets':[0, 4]}, align=True)\r\n assert_equal(dt.itemsize, 8)\r\n dt = np.dtype({'f0': ('i4', 0), 'f1':('u1', 4)}, align=True)\r\n assert_equal(dt.itemsize, 8)\r\n # Nesting should preserve that alignment\r\n dt1 = np.dtype([('f0', 'i4'),\r\n ('f1', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')]),\r\n ('f2', 'i1')], align=True)\r\n assert_equal(dt1.itemsize, 20)\r\n dt2 = np.dtype({'names':['f0', 'f1', 'f2'],\r\n 'formats':['i4',\r\n [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')],\r\n 'i1'],\r\n 'offsets':[0, 4, 16]}, align=True)\r\n assert_equal(dt2.itemsize, 20)\r\n dt3 = np.dtype({'f0': ('i4', 0),\r\n 'f1': ([('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 4),\r\n 'f2': ('i1', 16)}, align=True)\r\n assert_equal(dt3.itemsize, 20)\r\n assert_equal(dt1, dt2)\r\n assert_equal(dt2, dt3)\r\n # Nesting should preserve packing\r\n dt1 = np.dtype([('f0', 'i4'),\r\n ('f1', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')]),\r\n ('f2', 'i1')], align=False)\r\n assert_equal(dt1.itemsize, 11)\r\n dt2 = np.dtype({'names':['f0', 'f1', 'f2'],\r\n 'formats':['i4',\r\n [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')],\r\n 'i1'],\r\n 'offsets':[0, 4, 10]}, align=False)\r\n assert_equal(dt2.itemsize, 11)\r\n dt3 = np.dtype({'f0': ('i4', 0),\r\n 'f1': ([('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 4),\r\n 'f2': ('i1', 10)}, align=False)\r\n assert_equal(dt3.itemsize, 11)\r\n assert_equal(dt1, dt2)\r\n assert_equal(dt2, dt3)\r\n # Array of subtype should preserve alignment\r\n dt1 = np.dtype([('a', '|i1'),\r\n ('b', [('f0', '<i2'),\r\n ('f1', '<f4')], 2)], align=True)\r\n assert_equal(dt1.descr, [('a', '|i1'), ('', '|V3'),\r\n ('b', [('f0', '<i2'), ('', '|V2'),\r\n ('f1', '<f4')], (2,))])\r\n\r\n def test_union_struct(self):\r\n # Should be able to create union dtypes\r\n dt = np.dtype({'names':['f0', 'f1', 'f2'], 'formats':['<u4', '<u2', '<u2'],\r\n 'offsets':[0, 0, 2]}, align=True)\r\n assert_equal(dt.itemsize, 4)\r\n a = np.array([3], dtype='<u4').view(dt)\r\n a['f1'] = 10\r\n a['f2'] = 36\r\n assert_equal(a['f0'], 10 + 36*256*256)\r\n # Should be able to specify fields out of order\r\n dt = np.dtype({'names':['f0', 'f1', 'f2'], 'formats':['<u4', '<u2', '<u2'],\r\n 'offsets':[4, 0, 2]}, align=True)\r\n assert_equal(dt.itemsize, 8)\r\n # field name should not matter: assignment is by position\r\n dt2 = np.dtype({'names':['f2', 'f0', 'f1'],\r\n 'formats':['<u4', '<u2', '<u2'],\r\n 'offsets':[4, 0, 2]}, align=True)\r\n vals = [(0, 1, 2), (3, -1, 4)]\r\n vals2 = [(0, 1, 2), (3, -1, 4)]\r\n a = np.array(vals, dt)\r\n b = np.array(vals2, dt2)\r\n assert_equal(a.astype(dt2), b)\r\n assert_equal(b.astype(dt), a)\r\n assert_equal(a.view(dt2), b)\r\n assert_equal(b.view(dt), a)\r\n # Should not be able to overlap objects with other types\r\n assert_raises(TypeError, np.dtype,\r\n {'names':['f0', 'f1'],\r\n 'formats':['O', 'i1'],\r\n 'offsets':[0, 2]})\r\n assert_raises(TypeError, np.dtype,\r\n {'names':['f0', 'f1'],\r\n 'formats':['i4', 'O'],\r\n 'offsets':[0, 3]})\r\n assert_raises(TypeError, np.dtype,\r\n {'names':['f0', 'f1'],\r\n 'formats':[[('a', 'O')], 'i1'],\r\n 'offsets':[0, 2]})\r\n assert_raises(TypeError, np.dtype,\r\n {'names':['f0', 'f1'],\r\n 'formats':['i4', [('a', 'O')]],\r\n 'offsets':[0, 3]})\r\n # Out of order should still be ok, however\r\n dt = np.dtype({'names':['f0', 'f1'],\r\n 'formats':['i1', 'O'],\r\n 'offsets':[np.dtype('intp').itemsize, 0]})\r\n\r\n @pytest.mark.parametrize([\"obj\", \"dtype\", \"expected\"],\r\n [([], (\"(2)f4,\"), np.empty((0, 2), dtype=\"f4\")),\r\n (3, \"(3)f4,\", [3, 3, 3]),\r\n (np.float64(2), \"(2)f4,\", [2, 2]),\r\n ([((0, 1), (1, 2)), ((2,),)], '(2,2)f4', None),\r\n ([\"1\", \"2\"], \"(2)i,\", None)])\r\n def test_subarray_list(self, obj, dtype, expected):\r\n dtype = np.dtype(dtype)\r\n res = np.array(obj, dtype=dtype)\r\n\r\n if expected is None:\r\n # iterate the 1-d list to fill the array\r\n expected = np.empty(len(obj), dtype=dtype)\r\n for i in range(len(expected)):\r\n expected[i] = obj[i]\r\n\r\n assert_array_equal(res, expected)\r\n\r\n def test_comma_datetime(self):\r\n dt = np.dtype('M8[D],datetime64[Y],i8')\r\n assert_equal(dt, np.dtype([('f0', 'M8[D]'),\r\n ('f1', 'datetime64[Y]'),\r\n ('f2', 'i8')]))\r\n\r\n def test_from_dictproxy(self):\r\n # Tests for PR #5920\r\n dt = np.dtype({'names': ['a', 'b'], 'formats': ['i4', 'f4']})\r\n assert_dtype_equal(dt, np.dtype(dt.fields))\r\n dt2 = np.dtype((np.void, dt.fields))\r\n assert_equal(dt2.fields, dt.fields)\r\n\r\n def test_from_dict_with_zero_width_field(self):\r\n # Regression test for #6430 / #2196\r\n dt = np.dtype([('val1', np.float32, (0,)), ('val2', int)])\r\n dt2 = np.dtype({'names': ['val1', 'val2'],\r\n 'formats': [(np.float32, (0,)), int]})\r\n\r\n assert_dtype_equal(dt, dt2)\r\n assert_equal(dt.fields['val1'][0].itemsize, 0)\r\n assert_equal(dt.itemsize, dt.fields['val2'][0].itemsize)\r\n\r\n def test_bool_commastring(self):\r\n d = np.dtype('?,?,?') # raises?\r\n assert_equal(len(d.names), 3)\r\n for n in d.names:\r\n assert_equal(d.fields[n][0], np.dtype('?'))\r\n\r\n def test_nonint_offsets(self):\r\n # gh-8059\r\n def make_dtype(off):\r\n return np.dtype({'names': ['A'], 'formats': ['i4'],\r\n 'offsets': [off]})\r\n\r\n assert_raises(TypeError, make_dtype, 'ASD')\r\n assert_raises(OverflowError, make_dtype, 2**70)\r\n assert_raises(TypeError, make_dtype, 2.3)\r\n assert_raises(ValueError, make_dtype, -10)\r\n\r\n # no errors here:\r\n dt = make_dtype(np.uint32(0))\r\n np.zeros(1, dtype=dt)[0].item()\r\n\r\n def test_fields_by_index(self):\r\n dt = np.dtype([('a', np.int8), ('b', np.float32, 3)])\r\n assert_dtype_equal(dt[0], np.dtype(np.int8))\r\n assert_dtype_equal(dt[1], np.dtype((np.float32, 3)))\r\n assert_dtype_equal(dt[-1], dt[1])\r\n assert_dtype_equal(dt[-2], dt[0])\r\n assert_raises(IndexError, lambda: dt[-3])\r\n\r\n assert_raises(TypeError, operator.getitem, dt, 3.0)\r\n\r\n assert_equal(dt[1], dt[np.int8(1)])\r\n\r\n @pytest.mark.parametrize('align_flag',[False, True])\r\n def test_multifield_index(self, align_flag):\r\n # indexing with a list produces subfields\r\n # the align flag should be preserved\r\n dt = np.dtype([\r\n (('title', 'col1'), '<U20'), ('A', '<f8'), ('B', '<f8')\r\n ], align=align_flag)\r\n\r\n dt_sub = dt[['B', 'col1']]\r\n assert_equal(\r\n dt_sub,\r\n np.dtype({\r\n 'names': ['B', 'col1'],\r\n 'formats': ['<f8', '<U20'],\r\n 'offsets': [88, 0],\r\n 'titles': [None, 'title'],\r\n 'itemsize': 96\r\n })\r\n )\r\n assert_equal(dt_sub.isalignedstruct, align_flag)\r\n\r\n dt_sub = dt[['B']]\r\n assert_equal(\r\n dt_sub,\r\n np.dtype({\r\n 'names': ['B'],\r\n 'formats': ['<f8'],\r\n 'offsets': [88],\r\n 'itemsize': 96\r\n })\r\n )\r\n assert_equal(dt_sub.isalignedstruct, align_flag)\r\n\r\n dt_sub = dt[[]]\r\n assert_equal(\r\n dt_sub,\r\n np.dtype({\r\n 'names': [],\r\n 'formats': [],\r\n 'offsets': [],\r\n 'itemsize': 96\r\n })\r\n )\r\n assert_equal(dt_sub.isalignedstruct, align_flag)\r\n\r\n assert_raises(TypeError, operator.getitem, dt, ())\r\n assert_raises(TypeError, operator.getitem, dt, [1, 2, 3])\r\n assert_raises(TypeError, operator.getitem, dt, ['col1', 2])\r\n assert_raises(KeyError, operator.getitem, dt, ['fake'])\r\n assert_raises(KeyError, operator.getitem, dt, ['title'])\r\n assert_raises(ValueError, operator.getitem, dt, ['col1', 'col1'])\r\n\r\n def test_partial_dict(self):\r\n # 'names' is missing\r\n assert_raises(ValueError, np.dtype,\r\n {'formats': ['i4', 'i4'], 'f0': ('i4', 0), 'f1':('i4', 4)})\r\n\r\n def test_fieldless_views(self):\r\n a = np.zeros(2, dtype={'names':[], 'formats':[], 'offsets':[],\r\n 'itemsize':8})\r\n assert_raises(ValueError, a.view, np.dtype([]))\r\n\r\n d = np.dtype((np.dtype([]), 10))\r\n assert_equal(d.shape, (10,))\r\n assert_equal(d.itemsize, 0)\r\n assert_equal(d.base, np.dtype([]))\r\n\r\n arr = np.fromiter((() for i in range(10)), [])\r\n assert_equal(arr.dtype, np.dtype([]))\r\n assert_raises(ValueError, np.frombuffer, b'', dtype=[])\r\n assert_equal(np.frombuffer(b'', dtype=[], count=2),\r\n np.empty(2, dtype=[]))\r\n\r\n assert_raises(ValueError, np.dtype, ([], 'f8'))\r\n assert_raises(ValueError, np.zeros(1, dtype='i4').view, [])\r\n\r\n assert_equal(np.zeros(2, dtype=[]) == np.zeros(2, dtype=[]),\r\n np.ones(2, dtype=bool))\r\n\r\n assert_equal(np.zeros((1, 2), dtype=[]) == a,\r\n np.ones((1, 2), dtype=bool))\r\n\r\n\r\nclass TestSubarray:\r\n def test_single_subarray(self):\r\n a = np.dtype((int, (2)))\r\n b = np.dtype((int, (2,)))\r\n assert_dtype_equal(a, b)\r\n\r\n assert_equal(type(a.subdtype[1]), tuple)\r\n assert_equal(type(b.subdtype[1]), tuple)\r\n\r\n def test_equivalent_record(self):\r\n \"\"\"Test whether equivalent subarray dtypes hash the same.\"\"\"\r\n a = np.dtype((int, (2, 3)))\r\n b = np.dtype((int, (2, 3)))\r\n assert_dtype_equal(a, b)\r\n\r\n def test_nonequivalent_record(self):\r\n \"\"\"Test whether different subarray dtypes hash differently.\"\"\"\r\n a = np.dtype((int, (2, 3)))\r\n b = np.dtype((int, (3, 2)))\r\n assert_dtype_not_equal(a, b)\r\n\r\n a = np.dtype((int, (2, 3)))\r\n b = np.dtype((int, (2, 2)))\r\n assert_dtype_not_equal(a, b)\r\n\r\n a = np.dtype((int, (1, 2, 3)))\r\n b = np.dtype((int, (1, 2)))\r\n assert_dtype_not_equal(a, b)\r\n\r\n def test_shape_equal(self):\r\n \"\"\"Test some data types that are equal\"\"\"\r\n assert_dtype_equal(np.dtype('f8'), np.dtype(('f8', tuple())))\r\n # FutureWarning during deprecation period; after it is passed this\r\n # should instead check that \"(1)f8\" == \"1f8\" == (\"f8\", 1).\r\n with pytest.warns(FutureWarning):\r\n assert_dtype_equal(np.dtype('f8'), np.dtype(('f8', 1)))\r\n assert_dtype_equal(np.dtype((int, 2)), np.dtype((int, (2,))))\r\n assert_dtype_equal(np.dtype(('<f4', (3, 2))), np.dtype(('<f4', (3, 2))))\r\n d = ([('a', 'f4', (1, 2)), ('b', 'f8', (3, 1))], (3, 2))\r\n assert_dtype_equal(np.dtype(d), np.dtype(d))\r\n\r\n def test_shape_simple(self):\r\n \"\"\"Test some simple cases that shouldn't be equal\"\"\"\r\n assert_dtype_not_equal(np.dtype('f8'), np.dtype(('f8', (1,))))\r\n assert_dtype_not_equal(np.dtype(('f8', (1,))), np.dtype(('f8', (1, 1))))\r\n assert_dtype_not_equal(np.dtype(('f4', (3, 2))), np.dtype(('f4', (2, 3))))\r\n\r\n def test_shape_monster(self):\r\n \"\"\"Test some more complicated cases that shouldn't be equal\"\"\"\r\n assert_dtype_not_equal(\r\n np.dtype(([('a', 'f4', (2, 1)), ('b', 'f8', (1, 3))], (2, 2))),\r\n np.dtype(([('a', 'f4', (1, 2)), ('b', 'f8', (1, 3))], (2, 2))))\r\n assert_dtype_not_equal(\r\n np.dtype(([('a', 'f4', (2, 1)), ('b', 'f8', (1, 3))], (2, 2))),\r\n np.dtype(([('a', 'f4', (2, 1)), ('b', 'i8', (1, 3))], (2, 2))))\r\n assert_dtype_not_equal(\r\n np.dtype(([('a', 'f4', (2, 1)), ('b', 'f8', (1, 3))], (2, 2))),\r\n np.dtype(([('e', 'f8', (1, 3)), ('d', 'f4', (2, 1))], (2, 2))))\r\n assert_dtype_not_equal(\r\n np.dtype(([('a', [('a', 'i4', 6)], (2, 1)), ('b', 'f8', (1, 3))], (2, 2))),\r\n np.dtype(([('a', [('a', 'u4', 6)], (2, 1)), ('b', 'f8', (1, 3))], (2, 2))))\r\n\r\n def test_shape_sequence(self):\r\n # Any sequence of integers should work as shape, but the result\r\n # should be a tuple (immutable) of base type integers.\r\n a = np.array([1, 2, 3], dtype=np.int16)\r\n l = [1, 2, 3]\r\n # Array gets converted\r\n dt = np.dtype([('a', 'f4', a)])\r\n assert_(isinstance(dt['a'].shape, tuple))\r\n assert_(isinstance(dt['a'].shape[0], int))\r\n # List gets converted\r\n dt = np.dtype([('a', 'f4', l)])\r\n assert_(isinstance(dt['a'].shape, tuple))\r\n #\r\n\r\n class IntLike:\r\n def __index__(self):\r\n return 3\r\n\r\n def __int__(self):\r\n # (a PyNumber_Check fails without __int__)\r\n return 3\r\n\r\n dt = np.dtype([('a', 'f4', IntLike())])\r\n assert_(isinstance(dt['a'].shape, tuple))\r\n assert_(isinstance(dt['a'].shape[0], int))\r\n dt = np.dtype([('a', 'f4', (IntLike(),))])\r\n assert_(isinstance(dt['a'].shape, tuple))\r\n assert_(isinstance(dt['a'].shape[0], int))\r\n\r\n def test_shape_matches_ndim(self):\r\n dt = np.dtype([('a', 'f4', ())])\r\n assert_equal(dt['a'].shape, ())\r\n assert_equal(dt['a'].ndim, 0)\r\n\r\n dt = np.dtype([('a', 'f4')])\r\n assert_equal(dt['a'].shape, ())\r\n assert_equal(dt['a'].ndim, 0)\r\n\r\n dt = np.dtype([('a', 'f4', 4)])\r\n assert_equal(dt['a'].shape, (4,))\r\n assert_equal(dt['a'].ndim, 1)\r\n\r\n dt = np.dtype([('a', 'f4', (1, 2, 3))])\r\n assert_equal(dt['a'].shape, (1, 2, 3))\r\n assert_equal(dt['a'].ndim, 3)\r\n\r\n def test_shape_invalid(self):\r\n # Check that the shape is valid.\r\n max_int = np.iinfo(np.intc).max\r\n max_intp = np.iinfo(np.intp).max\r\n # Too large values (the datatype is part of this)\r\n assert_raises(ValueError, np.dtype, [('a', 'f4', max_int // 4 + 1)])\r\n assert_raises(ValueError, np.dtype, [('a', 'f4', max_int + 1)])\r\n assert_raises(ValueError, np.dtype, [('a', 'f4', (max_int, 2))])\r\n # Takes a different code path (fails earlier:\r\n assert_raises(ValueError, np.dtype, [('a', 'f4', max_intp + 1)])\r\n # Negative values\r\n assert_raises(ValueError, np.dtype, [('a', 'f4', -1)])\r\n assert_raises(ValueError, np.dtype, [('a', 'f4', (-1, -1))])\r\n\r\n def test_alignment(self):\r\n #Check that subarrays are aligned\r\n t1 = np.dtype('(1,)i4', align=True)\r\n t2 = np.dtype('2i4', align=True)\r\n assert_equal(t1.alignment, t2.alignment)\r\n\r\n\r\ndef iter_struct_object_dtypes():\r\n \"\"\"\r\n Iterates over a few complex dtypes and object pattern which\r\n fill the array with a given object (defaults to a singleton).\r\n\r\n Yields\r\n ------\r\n dtype : dtype\r\n pattern : tuple\r\n Structured tuple for use with `np.array`.\r\n count : int\r\n Number of objects stored in the dtype.\r\n singleton : object\r\n A singleton object. The returned pattern is constructed so that\r\n all objects inside the datatype are set to the singleton.\r\n \"\"\"\r\n obj = object()\r\n\r\n dt = np.dtype([('b', 'O', (2, 3))])\r\n p = ([[obj] * 3] * 2,)\r\n yield pytest.param(dt, p, 6, obj, id=\"<subarray>\")\r\n\r\n dt = np.dtype([('a', 'i4'), ('b', 'O', (2, 3))])\r\n p = (0, [[obj] * 3] * 2)\r\n yield pytest.param(dt, p, 6, obj, id=\"<subarray in field>\")\r\n\r\n dt = np.dtype([('a', 'i4'),\r\n ('b', [('ba', 'O'), ('bb', 'i1')], (2, 3))])\r\n p = (0, [[(obj, 0)] * 3] * 2)\r\n yield pytest.param(dt, p, 6, obj, id=\"<structured subarray 1>\")\r\n\r\n dt = np.dtype([('a', 'i4'),\r\n ('b', [('ba', 'O'), ('bb', 'O')], (2, 3))])\r\n p = (0, [[(obj, obj)] * 3] * 2)\r\n yield pytest.param(dt, p, 12, obj, id=\"<structured subarray 2>\")\r\n\r\n\r\[email protected](not HAS_REFCOUNT, reason=\"Python lacks refcounts\")\r\nclass TestStructuredObjectRefcounting:\r\n \"\"\"These tests cover various uses of complicated structured types which\r\n include objects and thus require reference counting.\r\n \"\"\"\r\n @pytest.mark.parametrize(['dt', 'pat', 'count', 'singleton'],\r\n iter_struct_object_dtypes())\r\n @pytest.mark.parametrize([\"creation_func\", \"creation_obj\"], [\r\n pytest.param(np.empty, None,\r\n # None is probably used for too many things\r\n marks=pytest.mark.skip(\"unreliable due to python's behaviour\")),\r\n (np.ones, 1),\r\n (np.zeros, 0)])\r\n def test_structured_object_create_delete(self, dt, pat, count, singleton,\r\n creation_func, creation_obj):\r\n \"\"\"Structured object reference counting in creation and deletion\"\"\"\r\n # The test assumes that 0, 1, and None are singletons.\r\n gc.collect()\r\n before = sys.getrefcount(creation_obj)\r\n arr = creation_func(3, dt)\r\n\r\n now = sys.getrefcount(creation_obj)\r\n assert now - before == count * 3\r\n del arr\r\n now = sys.getrefcount(creation_obj)\r\n assert now == before\r\n\r\n @pytest.mark.parametrize(['dt', 'pat', 'count', 'singleton'],\r\n iter_struct_object_dtypes())\r\n def test_structured_object_item_setting(self, dt, pat, count, singleton):\r\n \"\"\"Structured object reference counting for simple item setting\"\"\"\r\n one = 1\r\n\r\n gc.collect()\r\n before = sys.getrefcount(singleton)\r\n arr = np.array([pat] * 3, dt)\r\n assert sys.getrefcount(singleton) - before == count * 3\r\n # Fill with `1` and check that it was replaced correctly:\r\n before2 = sys.getrefcount(one)\r\n arr[...] = one\r\n after2 = sys.getrefcount(one)\r\n assert after2 - before2 == count * 3\r\n del arr\r\n gc.collect()\r\n assert sys.getrefcount(one) == before2\r\n assert sys.getrefcount(singleton) == before\r\n\r\n @pytest.mark.parametrize(['dt', 'pat', 'count', 'singleton'],\r\n iter_struct_object_dtypes())\r\n @pytest.mark.parametrize(\r\n ['shape', 'index', 'items_changed'],\r\n [((3,), ([0, 2],), 2),\r\n ((3, 2), ([0, 2], slice(None)), 4),\r\n ((3, 2), ([0, 2], [1]), 2),\r\n ((3,), ([True, False, True]), 2)])\r\n def test_structured_object_indexing(self, shape, index, items_changed,\r\n dt, pat, count, singleton):\r\n \"\"\"Structured object reference counting for advanced indexing.\"\"\"\r\n zero = 0\r\n one = 1\r\n\r\n arr = np.zeros(shape, dt)\r\n\r\n gc.collect()\r\n before_zero = sys.getrefcount(zero)\r\n before_one = sys.getrefcount(one)\r\n # Test item getting:\r\n part = arr[index]\r\n after_zero = sys.getrefcount(zero)\r\n assert after_zero - before_zero == count * items_changed\r\n del part\r\n # Test item setting:\r\n arr[index] = one\r\n gc.collect()\r\n after_zero = sys.getrefcount(zero)\r\n after_one = sys.getrefcount(one)\r\n assert before_zero - after_zero == count * items_changed\r\n assert after_one - before_one == count * items_changed\r\n\r\n @pytest.mark.parametrize(['dt', 'pat', 'count', 'singleton'],\r\n iter_struct_object_dtypes())\r\n def test_structured_object_take_and_repeat(self, dt, pat, count, singleton):\r\n \"\"\"Structured object reference counting for specialized functions.\r\n The older functions such as take and repeat use different code paths\r\n then item setting (when writing this).\r\n \"\"\"\r\n indices = [0, 1]\r\n\r\n arr = np.array([pat] * 3, dt)\r\n gc.collect()\r\n before = sys.getrefcount(singleton)\r\n res = arr.take(indices)\r\n after = sys.getrefcount(singleton)\r\n assert after - before == count * 2\r\n new = res.repeat(10)\r\n gc.collect()\r\n after_repeat = sys.getrefcount(singleton)\r\n assert after_repeat - after == count * 2 * 10\r\n\r\n\r\nclass TestStructuredDtypeSparseFields:\r\n \"\"\"Tests subarray fields which contain sparse dtypes so that\r\n not all memory is used by the dtype work. Such dtype's should\r\n leave the underlying memory unchanged.\r\n \"\"\"\r\n dtype = np.dtype([('a', {'names':['aa', 'ab'], 'formats':['f', 'f'],\r\n 'offsets':[0, 4]}, (2, 3))])\r\n sparse_dtype = np.dtype([('a', {'names':['ab'], 'formats':['f'],\r\n 'offsets':[4]}, (2, 3))])\r\n\r\n @pytest.mark.xfail(reason=\"inaccessible data is changed see gh-12686.\")\r\n @pytest.mark.valgrind_error(reason=\"reads from uninitialized buffers.\")\r\n def test_sparse_field_assignment(self):\r\n arr = np.zeros(3, self.dtype)\r\n sparse_arr = arr.view(self.sparse_dtype)\r\n\r\n sparse_arr[...] = np.finfo(np.float32).max\r\n # dtype is reduced when accessing the field, so shape is (3, 2, 3):\r\n assert_array_equal(arr[\"a\"][\"aa\"], np.zeros((3, 2, 3)))\r\n\r\n def test_sparse_field_assignment_fancy(self):\r\n # Fancy assignment goes to the copyswap function for complex types:\r\n arr = np.zeros(3, self.dtype)\r\n sparse_arr = arr.view(self.sparse_dtype)\r\n\r\n sparse_arr[[0, 1, 2]] = np.finfo(np.float32).max\r\n # dtype is reduced when accessing the field, so shape is (3, 2, 3):\r\n assert_array_equal(arr[\"a\"][\"aa\"], np.zeros((3, 2, 3)))\r\n\r\n\r\nclass TestMonsterType:\r\n \"\"\"Test deeply nested subtypes.\"\"\"\r\n\r\n def test1(self):\r\n simple1 = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'],\r\n 'titles': ['Red pixel', 'Blue pixel']})\r\n a = np.dtype([('yo', int), ('ye', simple1),\r\n ('yi', np.dtype((int, (3, 2))))])\r\n b = np.dtype([('yo', int), ('ye', simple1),\r\n ('yi', np.dtype((int, (3, 2))))])\r\n assert_dtype_equal(a, b)\r\n\r\n c = np.dtype([('yo', int), ('ye', simple1),\r\n ('yi', np.dtype((a, (3, 2))))])\r\n d = np.dtype([('yo', int), ('ye', simple1),\r\n ('yi', np.dtype((a, (3, 2))))])\r\n assert_dtype_equal(c, d)\r\n\r\n def test_list_recursion(self):\r\n l = list()\r\n l.append(('f', l))\r\n with pytest.raises(RecursionError):\r\n np.dtype(l)\r\n\r\n def test_tuple_recursion(self):\r\n d = np.int32\r\n for i in range(100000):\r\n d = (d, (1,))\r\n with pytest.raises(RecursionError):\r\n np.dtype(d)\r\n\r\n def test_dict_recursion(self):\r\n d = dict(names=['self'], formats=[None], offsets=[0])\r\n d['formats'][0] = d\r\n with pytest.raises(RecursionError):\r\n np.dtype(d)\r\n\r\n\r\nclass TestMetadata:\r\n def test_no_metadata(self):\r\n d = np.dtype(int)\r\n assert_(d.metadata is None)\r\n\r\n def test_metadata_takes_dict(self):\r\n d = np.dtype(int, metadata={'datum': 1})\r\n assert_(d.metadata == {'datum': 1})\r\n\r\n def test_metadata_rejects_nondict(self):\r\n assert_raises(TypeError, np.dtype, int, metadata='datum')\r\n assert_raises(TypeError, np.dtype, int, metadata=1)\r\n assert_raises(TypeError, np.dtype, int, metadata=None)\r\n\r\n def test_nested_metadata(self):\r\n d = np.dtype([('a', np.dtype(int, metadata={'datum': 1}))])\r\n assert_(d['a'].metadata == {'datum': 1})\r\n\r\n def test_base_metadata_copied(self):\r\n d = np.dtype((np.void, np.dtype('i4,i4', metadata={'datum': 1})))\r\n assert_(d.metadata == {'datum': 1})\r\n\r\nclass TestString:\r\n def test_complex_dtype_str(self):\r\n dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)),\r\n ('rtile', '>f4', (64, 36))], (3,)),\r\n ('bottom', [('bleft', ('>f4', (8, 64)), (1,)),\r\n ('bright', '>f4', (8, 36))])])\r\n assert_equal(str(dt),\r\n \"[('top', [('tiles', ('>f4', (64, 64)), (1,)), \"\r\n \"('rtile', '>f4', (64, 36))], (3,)), \"\r\n \"('bottom', [('bleft', ('>f4', (8, 64)), (1,)), \"\r\n \"('bright', '>f4', (8, 36))])]\")\r\n\r\n # If the sticky aligned flag is set to True, it makes the\r\n # str() function use a dict representation with an 'aligned' flag\r\n dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)),\r\n ('rtile', '>f4', (64, 36))],\r\n (3,)),\r\n ('bottom', [('bleft', ('>f4', (8, 64)), (1,)),\r\n ('bright', '>f4', (8, 36))])],\r\n align=True)\r\n assert_equal(str(dt),\r\n \"{'names':['top','bottom'], \"\r\n \"'formats':[([('tiles', ('>f4', (64, 64)), (1,)), \"\r\n \"('rtile', '>f4', (64, 36))], (3,)),\"\r\n \"[('bleft', ('>f4', (8, 64)), (1,)), \"\r\n \"('bright', '>f4', (8, 36))]], \"\r\n \"'offsets':[0,76800], \"\r\n \"'itemsize':80000, \"\r\n \"'aligned':True}\")\r\n assert_equal(np.dtype(eval(str(dt))), dt)\r\n\r\n dt = np.dtype({'names': ['r', 'g', 'b'], 'formats': ['u1', 'u1', 'u1'],\r\n 'offsets': [0, 1, 2],\r\n 'titles': ['Red pixel', 'Green pixel', 'Blue pixel']})\r\n assert_equal(str(dt),\r\n \"[(('Red pixel', 'r'), 'u1'), \"\r\n \"(('Green pixel', 'g'), 'u1'), \"\r\n \"(('Blue pixel', 'b'), 'u1')]\")\r\n\r\n dt = np.dtype({'names': ['rgba', 'r', 'g', 'b'],\r\n 'formats': ['<u4', 'u1', 'u1', 'u1'],\r\n 'offsets': [0, 0, 1, 2],\r\n 'titles': ['Color', 'Red pixel',\r\n 'Green pixel', 'Blue pixel']})\r\n assert_equal(str(dt),\r\n \"{'names':['rgba','r','g','b'],\"\r\n \" 'formats':['<u4','u1','u1','u1'],\"\r\n \" 'offsets':[0,0,1,2],\"\r\n \" 'titles':['Color','Red pixel',\"\r\n \"'Green pixel','Blue pixel'],\"\r\n \" 'itemsize':4}\")\r\n\r\n dt = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'],\r\n 'offsets': [0, 2],\r\n 'titles': ['Red pixel', 'Blue pixel']})\r\n assert_equal(str(dt),\r\n \"{'names':['r','b'],\"\r\n \" 'formats':['u1','u1'],\"\r\n \" 'offsets':[0,2],\"\r\n \" 'titles':['Red pixel','Blue pixel'],\"\r\n \" 'itemsize':3}\")\r\n\r\n dt = np.dtype([('a', '<m8[D]'), ('b', '<M8[us]')])\r\n assert_equal(str(dt),\r\n \"[('a', '<m8[D]'), ('b', '<M8[us]')]\")\r\n\r\n def test_repr_structured(self):\r\n dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)),\r\n ('rtile', '>f4', (64, 36))], (3,)),\r\n ('bottom', [('bleft', ('>f4', (8, 64)), (1,)),\r\n ('bright', '>f4', (8, 36))])])\r\n assert_equal(repr(dt),\r\n \"dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)), \"\r\n \"('rtile', '>f4', (64, 36))], (3,)), \"\r\n \"('bottom', [('bleft', ('>f4', (8, 64)), (1,)), \"\r\n \"('bright', '>f4', (8, 36))])])\")\r\n\r\n dt = np.dtype({'names': ['r', 'g', 'b'], 'formats': ['u1', 'u1', 'u1'],\r\n 'offsets': [0, 1, 2],\r\n 'titles': ['Red pixel', 'Green pixel', 'Blue pixel']},\r\n align=True)\r\n assert_equal(repr(dt),\r\n \"dtype([(('Red pixel', 'r'), 'u1'), \"\r\n \"(('Green pixel', 'g'), 'u1'), \"\r\n \"(('Blue pixel', 'b'), 'u1')], align=True)\")\r\n\r\n def test_repr_structured_not_packed(self):\r\n dt = np.dtype({'names': ['rgba', 'r', 'g', 'b'],\r\n 'formats': ['<u4', 'u1', 'u1', 'u1'],\r\n 'offsets': [0, 0, 1, 2],\r\n 'titles': ['Color', 'Red pixel',\r\n 'Green pixel', 'Blue pixel']}, align=True)\r\n assert_equal(repr(dt),\r\n \"dtype({'names':['rgba','r','g','b'],\"\r\n \" 'formats':['<u4','u1','u1','u1'],\"\r\n \" 'offsets':[0,0,1,2],\"\r\n \" 'titles':['Color','Red pixel',\"\r\n \"'Green pixel','Blue pixel'],\"\r\n \" 'itemsize':4}, align=True)\")\r\n\r\n dt = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'],\r\n 'offsets': [0, 2],\r\n 'titles': ['Red pixel', 'Blue pixel'],\r\n 'itemsize': 4})\r\n assert_equal(repr(dt),\r\n \"dtype({'names':['r','b'], \"\r\n \"'formats':['u1','u1'], \"\r\n \"'offsets':[0,2], \"\r\n \"'titles':['Red pixel','Blue pixel'], \"\r\n \"'itemsize':4})\")\r\n\r\n def test_repr_structured_datetime(self):\r\n dt = np.dtype([('a', '<M8[D]'), ('b', '<m8[us]')])\r\n assert_equal(repr(dt),\r\n \"dtype([('a', '<M8[D]'), ('b', '<m8[us]')])\")\r\n\r\n def test_repr_str_subarray(self):\r\n dt = np.dtype(('<i2', (1,)))\r\n assert_equal(repr(dt), \"dtype(('<i2', (1,)))\")\r\n assert_equal(str(dt), \"('<i2', (1,))\")\r\n\r\n def test_base_dtype_with_object_type(self):\r\n # Issue gh-2798, should not error.\r\n np.array(['a'], dtype=\"O\").astype((\"O\", [(\"name\", \"O\")]))\r\n\r\n def test_empty_string_to_object(self):\r\n # Pull request #4722\r\n np.array([\"\", \"\"]).astype(object)\r\n\r\n def test_void_subclass_unsized(self):\r\n dt = np.dtype(np.record)\r\n assert_equal(repr(dt), \"dtype('V')\")\r\n assert_equal(str(dt), '|V0')\r\n assert_equal(dt.name, 'record')\r\n\r\n def test_void_subclass_sized(self):\r\n dt = np.dtype((np.record, 2))\r\n assert_equal(repr(dt), \"dtype('V2')\")\r\n assert_equal(str(dt), '|V2')\r\n assert_equal(dt.name, 'record16')\r\n\r\n def test_void_subclass_fields(self):\r\n dt = np.dtype((np.record, [('a', '<u2')]))\r\n assert_equal(repr(dt), \"dtype((numpy.record, [('a', '<u2')]))\")\r\n assert_equal(str(dt), \"(numpy.record, [('a', '<u2')])\")\r\n assert_equal(dt.name, 'record16')\r\n\r\n\r\nclass TestDtypeAttributeDeletion:\r\n\r\n def test_dtype_non_writable_attributes_deletion(self):\r\n dt = np.dtype(np.double)\r\n attr = [\"subdtype\", \"descr\", \"str\", \"name\", \"base\", \"shape\",\r\n \"isbuiltin\", \"isnative\", \"isalignedstruct\", \"fields\",\r\n \"metadata\", \"hasobject\"]\r\n\r\n for s in attr:\r\n assert_raises(AttributeError, delattr, dt, s)\r\n\r\n def test_dtype_writable_attributes_deletion(self):\r\n dt = np.dtype(np.double)\r\n attr = [\"names\"]\r\n for s in attr:\r\n assert_raises(AttributeError, delattr, dt, s)\r\n\r\n\r\nclass TestDtypeAttributes:\r\n def test_descr_has_trailing_void(self):\r\n # see gh-6359\r\n dtype = np.dtype({\r\n 'names': ['A', 'B'],\r\n 'formats': ['f4', 'f4'],\r\n 'offsets': [0, 8],\r\n 'itemsize': 16})\r\n new_dtype = np.dtype(dtype.descr)\r\n assert_equal(new_dtype.itemsize, 16)\r\n\r\n def test_name_dtype_subclass(self):\r\n # Ticket #4357\r\n class user_def_subcls(np.void):\r\n pass\r\n assert_equal(np.dtype(user_def_subcls).name, 'user_def_subcls')\r\n\r\n\r\nclass TestPickling:\r\n\r\n def check_pickling(self, dtype):\r\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\r\n pickled = pickle.loads(pickle.dumps(dtype, proto))\r\n assert_equal(pickled, dtype)\r\n assert_equal(pickled.descr, dtype.descr)\r\n if dtype.metadata is not None:\r\n assert_equal(pickled.metadata, dtype.metadata)\r\n # Check the reconstructed dtype is functional\r\n x = np.zeros(3, dtype=dtype)\r\n y = np.zeros(3, dtype=pickled)\r\n assert_equal(x, y)\r\n assert_equal(x[0], y[0])\r\n\r\n @pytest.mark.parametrize('t', [int, float, complex, np.int32, str, object,\r\n np.compat.unicode, bool])\r\n def test_builtin(self, t):\r\n self.check_pickling(np.dtype(t))\r\n\r\n def test_structured(self):\r\n dt = np.dtype(([('a', '>f4', (2, 1)), ('b', '<f8', (1, 3))], (2, 2)))\r\n self.check_pickling(dt)\r\n\r\n def test_structured_aligned(self):\r\n dt = np.dtype('i4, i1', align=True)\r\n self.check_pickling(dt)\r\n\r\n def test_structured_unaligned(self):\r\n dt = np.dtype('i4, i1', align=False)\r\n self.check_pickling(dt)\r\n\r\n def test_structured_padded(self):\r\n dt = np.dtype({\r\n 'names': ['A', 'B'],\r\n 'formats': ['f4', 'f4'],\r\n 'offsets': [0, 8],\r\n 'itemsize': 16})\r\n self.check_pickling(dt)\r\n\r\n def test_structured_titles(self):\r\n dt = np.dtype({'names': ['r', 'b'],\r\n 'formats': ['u1', 'u1'],\r\n 'titles': ['Red pixel', 'Blue pixel']})\r\n self.check_pickling(dt)\r\n\r\n @pytest.mark.parametrize('base', ['m8', 'M8'])\r\n @pytest.mark.parametrize('unit', ['', 'Y', 'M', 'W', 'D', 'h', 'm', 's',\r\n 'ms', 'us', 'ns', 'ps', 'fs', 'as'])\r\n def test_datetime(self, base, unit):\r\n dt = np.dtype('%s[%s]' % (base, unit) if unit else base)\r\n self.check_pickling(dt)\r\n if unit:\r\n dt = np.dtype('%s[7%s]' % (base, unit))\r\n self.check_pickling(dt)\r\n\r\n def test_metadata(self):\r\n dt = np.dtype(int, metadata={'datum': 1})\r\n self.check_pickling(dt)\r\n\r\n\r\ndef test_rational_dtype():\r\n # test for bug gh-5719\r\n a = np.array([1111], dtype=rational).astype\r\n assert_raises(OverflowError, a, 'int8')\r\n\r\n # test that dtype detection finds user-defined types\r\n x = rational(1)\r\n assert_equal(np.array([x,x]).dtype, np.dtype(rational))\r\n\r\n\r\ndef test_dtypes_are_true():\r\n # test for gh-6294\r\n assert bool(np.dtype('f8'))\r\n assert bool(np.dtype('i8'))\r\n assert bool(np.dtype([('a', 'i8'), ('b', 'f4')]))\r\n\r\n\r\ndef test_invalid_dtype_string():\r\n # test for gh-10440\r\n assert_raises(TypeError, np.dtype, 'f8,i8,[f8,i8]')\r\n assert_raises(TypeError, np.dtype, u'Fl\\xfcgel')\r\n\r\n\r\ndef test_keyword_argument():\r\n # test for https://github.com/numpy/numpy/pull/16574#issuecomment-642660971\r\n assert np.dtype(dtype=np.float64) == np.dtype(np.float64)\r\n\r\n\r\nclass TestFromDTypeAttribute:\r\n def test_simple(self):\r\n class dt:\r\n dtype = \"f8\"\r\n\r\n assert np.dtype(dt) == np.float64\r\n assert np.dtype(dt()) == np.float64\r\n\r\n def test_recursion(self):\r\n class dt:\r\n pass\r\n\r\n dt.dtype = dt\r\n with pytest.raises(RecursionError):\r\n np.dtype(dt)\r\n\r\n dt_instance = dt()\r\n dt_instance.dtype = dt\r\n with pytest.raises(RecursionError):\r\n np.dtype(dt_instance)\r\n\r\n def test_void_subtype(self):\r\n class dt(np.void):\r\n # This code path is fully untested before, so it is unclear\r\n # what this should be useful for. Note that if np.void is used\r\n # numpy will think we are deallocating a base type [1.17, 2019-02].\r\n dtype = np.dtype(\"f,f\")\r\n pass\r\n\r\n np.dtype(dt)\r\n np.dtype(dt(1))\r\n\r\n def test_void_subtype_recursion(self):\r\n class dt(np.void):\r\n pass\r\n\r\n dt.dtype = dt\r\n\r\n with pytest.raises(RecursionError):\r\n np.dtype(dt)\r\n\r\n with pytest.raises(RecursionError):\r\n np.dtype(dt(1))\r\n\r\n\r\nclass TestDTypeClasses:\r\n @pytest.mark.parametrize(\"dtype\", list(np.typecodes['All']) + [rational])\r\n def test_basic_dtypes_subclass_properties(self, dtype):\r\n # Note: Except for the isinstance and type checks, these attributes\r\n # are considered currently private and may change.\r\n dtype = np.dtype(dtype)\r\n assert isinstance(dtype, np.dtype)\r\n assert type(dtype) is not np.dtype\r\n assert type(dtype).__name__ == f\"dtype[{dtype.type.__name__}]\"\r\n assert type(dtype).__module__ == \"numpy\"\r\n assert not type(dtype)._abstract\r\n\r\n # the flexible dtypes and datetime/timedelta have additional parameters\r\n # which are more than just storage information, these would need to be\r\n # given when creating a dtype:\r\n parametric = (np.void, np.str_, np.bytes_, np.datetime64, np.timedelta64)\r\n if dtype.type not in parametric:\r\n assert not type(dtype)._parametric\r\n assert type(dtype)() is dtype\r\n else:\r\n assert type(dtype)._parametric\r\n with assert_raises(TypeError):\r\n type(dtype)()\r\n\r\n def test_dtype_superclass(self):\r\n assert type(np.dtype) is not type\r\n assert isinstance(np.dtype, type)\r\n\r\n assert type(np.dtype).__name__ == \"_DTypeMeta\"\r\n assert type(np.dtype).__module__ == \"numpy\"\r\n assert np.dtype._abstract\r\n\r\n\r\nclass TestFromCTypes:\r\n\r\n @staticmethod\r\n def check(ctype, dtype):\r\n dtype = np.dtype(dtype)\r\n assert_equal(np.dtype(ctype), dtype)\r\n assert_equal(np.dtype(ctype()), dtype)\r\n\r\n def test_array(self):\r\n c8 = ctypes.c_uint8\r\n self.check( 3 * c8, (np.uint8, (3,)))\r\n self.check( 1 * c8, (np.uint8, (1,)))\r\n self.check( 0 * c8, (np.uint8, (0,)))\r\n self.check(1 * (3 * c8), ((np.uint8, (3,)), (1,)))\r\n self.check(3 * (1 * c8), ((np.uint8, (1,)), (3,)))\r\n\r\n def test_padded_structure(self):\r\n class PaddedStruct(ctypes.Structure):\r\n _fields_ = [\r\n ('a', ctypes.c_uint8),\r\n ('b', ctypes.c_uint16)\r\n ]\r\n expected = np.dtype([\r\n ('a', np.uint8),\r\n ('b', np.uint16)\r\n ], align=True)\r\n self.check(PaddedStruct, expected)\r\n\r\n def test_bit_fields(self):\r\n class BitfieldStruct(ctypes.Structure):\r\n _fields_ = [\r\n ('a', ctypes.c_uint8, 7),\r\n ('b', ctypes.c_uint8, 1)\r\n ]\r\n assert_raises(TypeError, np.dtype, BitfieldStruct)\r\n assert_raises(TypeError, np.dtype, BitfieldStruct())\r\n\r\n def test_pointer(self):\r\n p_uint8 = ctypes.POINTER(ctypes.c_uint8)\r\n assert_raises(TypeError, np.dtype, p_uint8)\r\n\r\n def test_void_pointer(self):\r\n self.check(ctypes.c_void_p, np.uintp)\r\n\r\n def test_union(self):\r\n class Union(ctypes.Union):\r\n _fields_ = [\r\n ('a', ctypes.c_uint8),\r\n ('b', ctypes.c_uint16),\r\n ]\r\n expected = np.dtype(dict(\r\n names=['a', 'b'],\r\n formats=[np.uint8, np.uint16],\r\n offsets=[0, 0],\r\n itemsize=2\r\n ))\r\n self.check(Union, expected)\r\n\r\n def test_union_with_struct_packed(self):\r\n class Struct(ctypes.Structure):\r\n _pack_ = 1\r\n _fields_ = [\r\n ('one', ctypes.c_uint8),\r\n ('two', ctypes.c_uint32)\r\n ]\r\n\r\n class Union(ctypes.Union):\r\n _fields_ = [\r\n ('a', ctypes.c_uint8),\r\n ('b', ctypes.c_uint16),\r\n ('c', ctypes.c_uint32),\r\n ('d', Struct),\r\n ]\r\n expected = np.dtype(dict(\r\n names=['a', 'b', 'c', 'd'],\r\n formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]],\r\n offsets=[0, 0, 0, 0],\r\n itemsize=ctypes.sizeof(Union)\r\n ))\r\n self.check(Union, expected)\r\n\r\n def test_union_packed(self):\r\n class Struct(ctypes.Structure):\r\n _fields_ = [\r\n ('one', ctypes.c_uint8),\r\n ('two', ctypes.c_uint32)\r\n ]\r\n _pack_ = 1\r\n class Union(ctypes.Union):\r\n _pack_ = 1\r\n _fields_ = [\r\n ('a', ctypes.c_uint8),\r\n ('b', ctypes.c_uint16),\r\n ('c', ctypes.c_uint32),\r\n ('d', Struct),\r\n ]\r\n expected = np.dtype(dict(\r\n names=['a', 'b', 'c', 'd'],\r\n formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]],\r\n offsets=[0, 0, 0, 0],\r\n itemsize=ctypes.sizeof(Union)\r\n ))\r\n self.check(Union, expected)\r\n\r\n def test_packed_structure(self):\r\n class PackedStructure(ctypes.Structure):\r\n _pack_ = 1\r\n _fields_ = [\r\n ('a', ctypes.c_uint8),\r\n ('b', ctypes.c_uint16)\r\n ]\r\n expected = np.dtype([\r\n ('a', np.uint8),\r\n ('b', np.uint16)\r\n ])\r\n self.check(PackedStructure, expected)\r\n\r\n def test_large_packed_structure(self):\r\n class PackedStructure(ctypes.Structure):\r\n _pack_ = 2\r\n _fields_ = [\r\n ('a', ctypes.c_uint8),\r\n ('b', ctypes.c_uint16),\r\n ('c', ctypes.c_uint8),\r\n ('d', ctypes.c_uint16),\r\n ('e', ctypes.c_uint32),\r\n ('f', ctypes.c_uint32),\r\n ('g', ctypes.c_uint8)\r\n ]\r\n expected = np.dtype(dict(\r\n formats=[np.uint8, np.uint16, np.uint8, np.uint16, np.uint32, np.uint32, np.uint8 ],\r\n offsets=[0, 2, 4, 6, 8, 12, 16],\r\n names=['a', 'b', 'c', 'd', 'e', 'f', 'g'],\r\n itemsize=18))\r\n self.check(PackedStructure, expected)\r\n\r\n def test_big_endian_structure_packed(self):\r\n class BigEndStruct(ctypes.BigEndianStructure):\r\n _fields_ = [\r\n ('one', ctypes.c_uint8),\r\n ('two', ctypes.c_uint32)\r\n ]\r\n _pack_ = 1\r\n expected = np.dtype([('one', 'u1'), ('two', '>u4')])\r\n self.check(BigEndStruct, expected)\r\n\r\n def test_little_endian_structure_packed(self):\r\n class LittleEndStruct(ctypes.LittleEndianStructure):\r\n _fields_ = [\r\n ('one', ctypes.c_uint8),\r\n ('two', ctypes.c_uint32)\r\n ]\r\n _pack_ = 1\r\n expected = np.dtype([('one', 'u1'), ('two', '<u4')])\r\n self.check(LittleEndStruct, expected)\r\n\r\n def test_little_endian_structure(self):\r\n class PaddedStruct(ctypes.LittleEndianStructure):\r\n _fields_ = [\r\n ('a', ctypes.c_uint8),\r\n ('b', ctypes.c_uint16)\r\n ]\r\n expected = np.dtype([\r\n ('a', '<B'),\r\n ('b', '<H')\r\n ], align=True)\r\n self.check(PaddedStruct, expected)\r\n\r\n def test_big_endian_structure(self):\r\n class PaddedStruct(ctypes.BigEndianStructure):\r\n _fields_ = [\r\n ('a', ctypes.c_uint8),\r\n ('b', ctypes.c_uint16)\r\n ]\r\n expected = np.dtype([\r\n ('a', '>B'),\r\n ('b', '>H')\r\n ], align=True)\r\n self.check(PaddedStruct, expected)\r\n\r\n def test_simple_endian_types(self):\r\n self.check(ctypes.c_uint16.__ctype_le__, np.dtype('<u2'))\r\n self.check(ctypes.c_uint16.__ctype_be__, np.dtype('>u2'))\r\n self.check(ctypes.c_uint8.__ctype_le__, np.dtype('u1'))\r\n self.check(ctypes.c_uint8.__ctype_be__, np.dtype('u1'))\r\n\r\n all_types = set(np.typecodes['All'])\r\n all_pairs = permutations(all_types, 2)\r\n\r\n @pytest.mark.parametrize(\"pair\", all_pairs)\r\n def test_pairs(self, pair):\r\n \"\"\"\r\n Check that np.dtype('x,y') matches [np.dtype('x'), np.dtype('y')]\r\n Example: np.dtype('d,I') -> dtype([('f0', '<f8'), ('f1', '<u4')])\r\n \"\"\"\r\n # gh-5645: check that np.dtype('i,L') can be used\r\n pair_type = np.dtype('{},{}'.format(*pair))\r\n expected = np.dtype([('f0', pair[0]), ('f1', pair[1])])\r\n assert_equal(pair_type, expected)\r\n\r\n\r\nclass TestUserDType:\r\n @pytest.mark.leaks_references(reason=\"dynamically creates custom dtype.\")\r\n def test_custom_structured_dtype(self):\r\n class mytype:\r\n pass\r\n\r\n blueprint = np.dtype([(\"field\", object)])\r\n dt = create_custom_field_dtype(blueprint, mytype, 0)\r\n assert dt.type == mytype\r\n # We cannot (currently) *create* this dtype with `np.dtype` because\r\n # mytype does not inherit from `np.generic`. This seems like an\r\n # unnecessary restriction, but one that has been around forever:\r\n assert np.dtype(mytype) == np.dtype(\"O\")\r\n\r\n def test_custom_structured_dtype_errors(self):\r\n class mytype:\r\n pass\r\n\r\n blueprint = np.dtype([(\"field\", object)])\r\n\r\n with pytest.raises(ValueError):\r\n # Tests what happens if fields are unset during creation\r\n # which is currently rejected due to the containing object\r\n # (see PyArray_RegisterDataType).\r\n create_custom_field_dtype(blueprint, mytype, 1)\r\n\r\n with pytest.raises(RuntimeError):\r\n # Tests that a dtype must have its type field set up to np.dtype\r\n # or in this case a builtin instance.\r\n create_custom_field_dtype(blueprint, mytype, 2)\r\n"
] | [
[
"numpy.ones",
"numpy.testing.assert_equal",
"numpy.dtype",
"numpy.float64",
"numpy.testing.assert_array_equal",
"numpy.uint32",
"numpy.core._rational_tests.rational",
"numpy.can_cast",
"numpy.int8",
"numpy.zeros",
"numpy.compat.pickle.dumps",
"numpy.finfo",
"numpy.core._multiarray_tests.create_custom_field_dtype",
"numpy.testing.assert_raises",
"numpy.empty",
"numpy.iinfo",
"numpy.testing.assert_",
"numpy.array",
"numpy.frombuffer"
]
] |
kudo1026/packnet-sfm | [
"b7c6230e1a093b1f096a9577616d40ada5e376e6"
] | [
"packnet_sfm/networks/layers/resnet/ds_decoder.py"
] | [
"# Copyright 2020 Toyota Research Institute. All rights reserved.\n\n# Adapted from monodepth2\n# https://github.com/nianticlabs/monodepth2/blob/master/networks/depth_decoder.py\n\nfrom __future__ import absolute_import, division, print_function\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom collections import OrderedDict\nfrom .layers import ConvBlock, Conv3x3, upsample\n\n\nclass DSDecoder(nn.Module):\n def __init__(self, num_ch_enc, scales=[0], num_output_channels=3, use_skips=True):\n super(DSDecoder, self).__init__()\n\n self.num_output_channels = num_output_channels\n self.use_skips = use_skips\n self.upsample_mode = 'nearest'\n self.scales = scales\n\n self.num_ch_enc = num_ch_enc\n self.num_ch_dec = np.array([16, 32, 64, 128, 256])\n\n # camera intrinsic parameter as a vector\n # i = torch.tensor([183.85 / 1000, 191.47 / 1000, 186.73 / 1000, 132.81 / 1000, (-0.221 + 1) / 2, 0.576])\n # i = torch.tensor([208.10/1000, 216.78/1000, 186.24/1000, 132.82/1000, (-0.172 + 1)/2, 0.592])\n # i = torch.tensor([181.4/1000, 188.9/1000, 186.4/1000, 132.6/1000, (-0.230+1)/2, 0.571]) # euroc gt\n # i = i * 0.9\n # i = i * 1.10\n # sigmoid_inv_i = torch.log(i / (1 - i))\n # self.intrinsic_vector = nn.Parameter(sigmoid_inv_i)\n # self.intrinsic_vector = nn.Parameter(torch.zeros(6))\n self.intrinsic_vector = nn.Parameter(-torch.ones(6))\n\n self.tanh = nn.Tanh()\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, input_features):\n self.output = {}\n\n # get forcal length and offsets\n x = input_features[-1]\n B = x.shape[0]\n \n fx, fy, cx, cy = self.sigmoid(self.intrinsic_vector[0:4]) * 1000\n xi = self.sigmoid(self.intrinsic_vector[4]) * 2 - 1\n alpha = self.sigmoid(self.intrinsic_vector[5]) * 1\n\n I = torch.zeros(6)\n I[0] = fx\n I[1] = fy\n I[2] = cx\n I[3] = cy\n I[4] = xi\n I[5] = alpha\n\n self.output = I.unsqueeze(0).repeat(B,1)\n\n return self.output\n"
] | [
[
"torch.ones",
"torch.zeros",
"torch.nn.Tanh",
"numpy.array",
"torch.nn.Sigmoid"
]
] |
lcl1026504480/mfpython | [
"c1b1689a42488129299e31152764c535eb8e66e0"
] | [
"evolution/6.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 9 21:25:15 2020\n\n@author: lenovouser\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nN_MOVES = 150\nDNA_SIZE = N_MOVES*2 # 40 x moves, 40 y moves\nDIRECTION_BOUND = [0, 1]\nCROSS_RATE = 0.8\nMUTATE_RATE = 0.0001\nPOP_SIZE = 100\nN_GENERATIONS = 200\nGOAL_POINT = [10, 5]\nSTART_POINT = [0, 5]\nOBSTACLE_LINE = np.array([[5, 2], [5, 8]])\n\n\nclass GA(object):\n def __init__(self, DNA_size, DNA_bound, cross_rate, mutation_rate, pop_size, ):\n self.DNA_size = DNA_size\n DNA_bound[1] += 1\n self.DNA_bound = DNA_bound\n self.cross_rate = cross_rate\n self.mutate_rate = mutation_rate\n self.pop_size = pop_size\n\n self.pop = np.random.randint(*DNA_bound, size=(pop_size, DNA_size))\n\n def DNA2product(self, DNA, n_moves, start_point): # convert to readable string\n pop = (DNA - 0.5) \n pop[:, 0], pop[:, n_moves] = start_point[0], start_point[1]\n lines_x = np.cumsum(pop[:, :n_moves], axis=1)\n lines_y = np.cumsum(pop[:, n_moves:], axis=1)\n return lines_x, lines_y\n\n def get_fitness(self, lines_x, lines_y, goal_point, obstacle_line):\n dist2goal = np.sqrt((goal_point[0] - lines_x[:, -1]) ** 2 + (goal_point[1] - lines_y[:, -1]) ** 2)\n fitness=np.exp(-10*dist2goal)\n points = (lines_x > obstacle_line[0, 0] - 0.5) & (lines_x < obstacle_line[1, 0] + 0.5)\n y_values = np.where(points, lines_y, np.zeros_like(lines_y) - 100)\n bad_lines = ((y_values > obstacle_line[0, 1]) & (y_values < obstacle_line[1, 1])).max(axis=1)\n fitness[bad_lines] = 1e-6\n return fitness\n\n def select(self, fitness):\n idx = np.random.choice(np.arange(self.pop_size), size=self.pop_size, replace=True, p=fitness/fitness.sum())\n return self.pop[idx]\n\n def crossover(self, parent, pop):\n if np.random.rand() < self.cross_rate:\n i_ = np.random.randint(0, self.pop_size, size=1) # select another individual from pop\n cross_points = np.random.randint(0, 2, self.DNA_size).astype(np.bool) # choose crossover points\n parent[cross_points] = pop[i_, cross_points] # mating and produce one child\n return parent\n\n def mutate(self, child):\n for point in range(self.DNA_size):\n if np.random.rand() < self.mutate_rate:\n child[point] = np.random.randint(*self.DNA_bound)\n return child\n\n def evolve(self, fitness):\n pop = self.select(fitness)\n pop_copy = pop.copy()\n for parent in pop: # for every parent\n child = self.crossover(parent, pop_copy)\n child = self.mutate(child)\n parent[:] = child\n self.pop = pop\n\n\nclass Line(object):\n def __init__(self, n_moves, goal_point, start_point, obstacle_line):\n self.n_moves = n_moves\n self.goal_point = goal_point\n self.start_point = start_point\n self.obstacle_line = obstacle_line\n\n plt.ion()\n\n def plotting(self, lines_x, lines_y):\n plt.cla()\n plt.scatter(*self.goal_point, s=200, c='r')\n plt.scatter(*self.start_point, s=100, c='b')\n plt.plot(self.obstacle_line[:, 0], self.obstacle_line[:, 1], lw=3, c='k')\n plt.plot(lines_x.T, lines_y.T, c='k')\n plt.scatter(lines_x[:,-1],lines_y[:,-1],100,\"y\")\n plt.xlim((-5, 15))\n plt.ylim((-5, 15))\n plt.pause(0.01)\n\n\nga = GA(DNA_size=DNA_SIZE, DNA_bound=DIRECTION_BOUND,\n cross_rate=CROSS_RATE, mutation_rate=MUTATE_RATE, pop_size=POP_SIZE)\n\nenv = Line(N_MOVES, GOAL_POINT, START_POINT, OBSTACLE_LINE)\n\nfor generation in range(N_GENERATIONS):\n lx, ly = ga.DNA2product(ga.pop, N_MOVES, START_POINT)\n fitness = ga.get_fitness(lx, ly, GOAL_POINT, OBSTACLE_LINE)\n ga.evolve(fitness)\n print('Gen:', generation, '| best fit:', fitness.max())\n env.plotting(lx, ly)\n\nplt.ioff()\nplt.show()\n"
] | [
[
"numpy.sqrt",
"numpy.zeros_like",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.pause",
"numpy.cumsum",
"matplotlib.pyplot.cla",
"matplotlib.pyplot.ioff",
"numpy.exp",
"matplotlib.pyplot.xlim",
"numpy.arange",
"matplotlib.pyplot.show",
"numpy.random.rand",
"matplotlib.pyplot.ylim",
"numpy.array",
"matplotlib.pyplot.ion",
"numpy.random.randint",
"matplotlib.pyplot.scatter"
]
] |
BroadDong/Caffe_2 | [
"c1a636983dc84a960d6abe150c996234d6f6278c"
] | [
"caffe2/python/rnn_cell.py"
] | [
"# Copyright (c) 2016-present, Facebook, Inc.\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## @package rnn_cell\n# Module caffe2.python.rnn_cell\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport functools\nimport itertools\nimport logging\nimport numpy as np\nimport random\nimport six\nfrom future.utils import viewkeys\n\nfrom caffe2.proto import caffe2_pb2\nfrom caffe2.python.attention import (\n AttentionType,\n apply_regular_attention,\n apply_recurrent_attention,\n apply_dot_attention,\n apply_soft_coverage_attention,\n)\nfrom caffe2.python import core, recurrent, workspace, brew, scope\nfrom caffe2.python.modeling.parameter_sharing import ParameterSharing\nfrom caffe2.python.modeling.parameter_info import ParameterTags\nfrom caffe2.python.modeling.initializers import Initializer\nfrom caffe2.python.model_helper import ModelHelper\n\n\nclass RNNCell(object):\n '''\n Base class for writing recurrent / stateful operations.\n\n One needs to implement 3 methods: _apply, prepare_input and get_state_names.\n As a result base class will provice apply_over_sequence method, which\n allows you to apply recurrent operations over a sequence of any length.\n '''\n def __init__(self, name, forward_only=False, initializer=None):\n self.name = name\n self.recompute_blobs = []\n self.forward_only = forward_only\n self._initializer = initializer\n\n @property\n def initializer(self):\n return self._initializer\n\n @initializer.setter\n def initializer(self, value):\n self._initializer = value\n\n def scope(self, name):\n return self.name + '/' + name if self.name is not None else name\n\n def apply_over_sequence(\n self,\n model,\n inputs,\n seq_lengths,\n initial_states=None,\n outputs_with_grads=None,\n ):\n if initial_states is None:\n with scope.NameScope(self.name):\n if self.initializer is None:\n raise Exception(\"Either initial states\"\n \"or initializer have to be set\")\n initial_states = self.initializer.create_states(model)\n\n preprocessed_inputs = self.prepare_input(model, inputs)\n step_model = ModelHelper(name=self.name, param_model=model)\n input_t, timestep = step_model.net.AddScopedExternalInputs(\n 'input_t',\n 'timestep',\n )\n states_prev = step_model.net.AddScopedExternalInputs(*[\n s + '_prev' for s in self.get_state_names()\n ])\n states = self._apply(\n model=step_model,\n input_t=input_t,\n seq_lengths=seq_lengths,\n states=states_prev,\n timestep=timestep,\n )\n\n if outputs_with_grads is None:\n outputs_with_grads = [self.get_output_state_index() * 2]\n\n # states_for_all_steps consists of combination of\n # states gather for all steps and final states. It looks like this:\n # (state_1_all, state_1_final, state_2_all, state_2_final, ...)\n states_for_all_steps = recurrent.recurrent_net(\n net=model.net,\n cell_net=step_model.net,\n inputs=[(input_t, preprocessed_inputs)],\n initial_cell_inputs=list(zip(states_prev, initial_states)),\n links=dict(zip(states_prev, states)),\n timestep=timestep,\n scope=self.name,\n forward_only=self.forward_only,\n outputs_with_grads=outputs_with_grads,\n recompute_blobs_on_backward=self.recompute_blobs,\n )\n\n output = self._prepare_output_sequence(\n model,\n states_for_all_steps,\n )\n return output, states_for_all_steps\n\n def apply(self, model, input_t, seq_lengths, states, timestep):\n input_t = self.prepare_input(model, input_t)\n states = self._apply(\n model, input_t, seq_lengths, states, timestep)\n output = self._prepare_output(model, states)\n return output, states\n\n def _apply(\n self,\n model,\n input_t,\n seq_lengths,\n states,\n timestep,\n extra_inputs,\n ):\n '''\n A single step of a recurrent network.\n\n model: ModelHelper object new operators would be added to\n\n input_t: single input with shape (1, batch_size, input_dim)\n\n seq_lengths: blob containing sequence lengths which would be passed to\n LSTMUnit operator\n\n states: previous recurrent states\n\n timestep: current recurrent iteration. Could be used together with\n seq_lengths in order to determine, if some shorter sequences\n in the batch have already ended.\n\n extra_inputs: list of tuples (input, dim). specifies additional input\n which is not subject to prepare_input(). (useful when a cell is a\n component of a larger recurrent structure, e.g., attention)\n '''\n raise NotImplementedError('Abstract method')\n\n def prepare_input(self, model, input_blob):\n '''\n If some operations in _apply method depend only on the input,\n not on recurrent states, they could be computed in advance.\n\n model: ModelHelper object new operators would be added to\n\n input_blob: either the whole input sequence with shape\n (sequence_length, batch_size, input_dim) or a single input with shape\n (1, batch_size, input_dim).\n '''\n return input_blob\n\n def get_output_state_index(self):\n '''\n Return index into state list of the \"primary\" step-wise output.\n '''\n return 0\n\n def get_state_names(self):\n '''\n Return the names of the recurrent states.\n It's required by apply_over_sequence method in order to allocate\n recurrent states for all steps with meaningful names.\n '''\n raise NotImplementedError('Abstract method')\n\n def get_output_dim(self):\n '''\n Specifies the dimension (number of units) of stepwise output.\n '''\n raise NotImplementedError('Abstract method')\n\n def _prepare_output(self, model, states):\n '''\n Allows arbitrary post-processing of primary output.\n '''\n return states[self.get_output_state_index()]\n\n def _prepare_output_sequence(self, model, state_outputs):\n '''\n Allows arbitrary post-processing of primary sequence output.\n\n (Note that state_outputs alternates between full-sequence and final\n output for each state, thus the index multiplier 2.)\n '''\n output_sequence_index = 2 * self.get_output_state_index()\n return state_outputs[output_sequence_index]\n\n\nclass LSTMInitializer(object):\n def __init__(self, hidden_size):\n self.hidden_size = hidden_size\n\n def create_states(self, model):\n return [\n model.create_param(\n param_name='initial_hidden_state',\n initializer=Initializer(operator_name='ConstantFill',\n value=0.0),\n shape=[self.hidden_size],\n ),\n model.create_param(\n param_name='initial_cell_state',\n initializer=Initializer(operator_name='ConstantFill',\n value=0.0),\n shape=[self.hidden_size],\n )\n ]\n\n\nclass LSTMCell(RNNCell):\n\n def __init__(\n self,\n input_size,\n hidden_size,\n forget_bias,\n memory_optimization,\n drop_states=False,\n initializer=None,\n **kwargs\n ):\n super(LSTMCell, self).__init__(initializer=initializer, **kwargs)\n self.initializer = initializer or LSTMInitializer(\n hidden_size=hidden_size)\n\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.forget_bias = float(forget_bias)\n self.memory_optimization = memory_optimization\n self.drop_states = drop_states\n\n def _apply(\n self,\n model,\n input_t,\n seq_lengths,\n states,\n timestep,\n extra_inputs=None,\n ):\n hidden_t_prev, cell_t_prev = states\n\n fc_input = hidden_t_prev\n fc_input_dim = self.hidden_size\n\n if extra_inputs is not None:\n extra_input_blobs, extra_input_sizes = zip(*extra_inputs)\n fc_input = brew.concat(\n model,\n [hidden_t_prev] + list(extra_input_blobs),\n self.scope('gates_concatenated_input_t'),\n axis=2,\n )\n fc_input_dim += sum(extra_input_sizes)\n\n gates_t = brew.fc(\n model,\n fc_input,\n self.scope('gates_t'),\n dim_in=fc_input_dim,\n dim_out=4 * self.hidden_size,\n axis=2,\n )\n brew.sum(model, [gates_t, input_t], gates_t)\n\n hidden_t, cell_t = model.net.LSTMUnit(\n [\n hidden_t_prev,\n cell_t_prev,\n gates_t,\n seq_lengths,\n timestep,\n ],\n list(self.get_state_names()),\n forget_bias=self.forget_bias,\n drop_states=self.drop_states,\n )\n model.net.AddExternalOutputs(hidden_t, cell_t)\n if self.memory_optimization:\n self.recompute_blobs = [gates_t]\n return hidden_t, cell_t\n\n def get_input_params(self):\n return {\n 'weights': self.scope('i2h') + '_w',\n 'biases': self.scope('i2h') + '_b',\n }\n\n def get_recurrent_params(self):\n return {\n 'weights': self.scope('gates_t') + '_w',\n 'biases': self.scope('gates_t') + '_b',\n }\n\n def prepare_input(self, model, input_blob):\n return brew.fc(\n model,\n input_blob,\n self.scope('i2h'),\n dim_in=self.input_size,\n dim_out=4 * self.hidden_size,\n axis=2,\n )\n\n def get_state_names(self):\n return (self.scope('hidden_t'), self.scope('cell_t'))\n\n def get_output_dim(self):\n return self.hidden_size\n\n\nclass MILSTMCell(LSTMCell):\n\n def _apply(\n self,\n model,\n input_t,\n seq_lengths,\n states,\n timestep,\n extra_inputs=None,\n ):\n hidden_t_prev, cell_t_prev = states\n\n fc_input = hidden_t_prev\n fc_input_dim = self.hidden_size\n\n if extra_inputs is not None:\n extra_input_blobs, extra_input_sizes = zip(*extra_inputs)\n fc_input = brew.concat(\n model,\n [hidden_t_prev] + list(extra_input_blobs),\n self.scope('gates_concatenated_input_t'),\n axis=2,\n )\n fc_input_dim += sum(extra_input_sizes)\n\n prev_t = brew.fc(\n model,\n fc_input,\n self.scope('prev_t'),\n dim_in=fc_input_dim,\n dim_out=4 * self.hidden_size,\n axis=2,\n )\n\n # defining initializers for MI parameters\n alpha = model.create_param(\n self.scope('alpha'),\n shape=[4 * self.hidden_size],\n initializer=Initializer('ConstantFill', value=1.0),\n )\n beta_h = model.create_param(\n self.scope('beta1'),\n shape=[4 * self.hidden_size],\n initializer=Initializer('ConstantFill', value=1.0),\n )\n beta_i = model.create_param(\n self.scope('beta2'),\n shape=[4 * self.hidden_size],\n initializer=Initializer('ConstantFill', value=1.0),\n )\n b = model.create_param(\n self.scope('b'),\n shape=[4 * self.hidden_size],\n initializer=Initializer('ConstantFill', value=0.0),\n )\n\n # alpha * input_t + beta_h\n # Shape: [1, batch_size, 4 * hidden_size]\n alpha_by_input_t_plus_beta_h = model.net.ElementwiseLinear(\n [input_t, alpha, beta_h],\n self.scope('alpha_by_input_t_plus_beta_h'),\n axis=2,\n )\n # (alpha * input_t + beta_h) * prev_t =\n # alpha * input_t * prev_t + beta_h * prev_t\n # Shape: [1, batch_size, 4 * hidden_size]\n alpha_by_input_t_plus_beta_h_by_prev_t = model.net.Mul(\n [alpha_by_input_t_plus_beta_h, prev_t],\n self.scope('alpha_by_input_t_plus_beta_h_by_prev_t')\n )\n # beta_i * input_t + b\n # Shape: [1, batch_size, 4 * hidden_size]\n beta_i_by_input_t_plus_b = model.net.ElementwiseLinear(\n [input_t, beta_i, b],\n self.scope('beta_i_by_input_t_plus_b'),\n axis=2,\n )\n # alpha * input_t * prev_t + beta_h * prev_t + beta_i * input_t + b\n # Shape: [1, batch_size, 4 * hidden_size]\n gates_t = brew.sum(\n model,\n [alpha_by_input_t_plus_beta_h_by_prev_t, beta_i_by_input_t_plus_b],\n self.scope('gates_t')\n )\n hidden_t, cell_t = model.net.LSTMUnit(\n [hidden_t_prev, cell_t_prev, gates_t, seq_lengths, timestep],\n [self.scope('hidden_t_intermediate'), self.scope('cell_t')],\n forget_bias=self.forget_bias,\n drop_states=self.drop_states,\n )\n model.net.AddExternalOutputs(\n cell_t,\n hidden_t,\n )\n if self.memory_optimization:\n self.recompute_blobs = [gates_t]\n return hidden_t, cell_t\n\n\nclass DropoutCell(RNNCell):\n '''\n Wraps arbitrary RNNCell, applying dropout to its output (but not to the\n recurrent connection for the corresponding state).\n '''\n\n def __init__(self, internal_cell, dropout_ratio=None, **kwargs):\n self.internal_cell = internal_cell\n self.dropout_ratio = dropout_ratio\n assert 'is_test' in kwargs, \"Argument 'is_test' is required\"\n self.is_test = kwargs.pop('is_test')\n super(DropoutCell, self).__init__(**kwargs)\n\n self.prepare_input = internal_cell.prepare_input\n self.get_output_state_index = internal_cell.get_output_state_index\n self.get_state_names = internal_cell.get_state_names\n self.get_output_dim = internal_cell.get_output_dim\n\n self.mask = 0\n\n def _apply(\n self,\n model,\n input_t,\n seq_lengths,\n states,\n timestep,\n extra_inputs=None,\n ):\n return self.internal_cell._apply(\n model,\n input_t,\n seq_lengths,\n states,\n timestep,\n extra_inputs,\n )\n\n def _prepare_output(self, model, states):\n output = self.internal_cell._prepare_output(\n model,\n states,\n )\n if self.dropout_ratio is not None:\n output = self._apply_dropout(model, output)\n return output\n\n def _prepare_output_sequence(self, model, state_outputs):\n output = self.internal_cell._prepare_output_sequence(\n model,\n state_outputs,\n )\n if self.dropout_ratio is not None:\n output = self._apply_dropout(model, output)\n return output\n\n def _apply_dropout(self, model, output):\n if self.dropout_ratio and not self.forward_only:\n with core.NameScope(self.name or ''):\n output = brew.dropout(\n model,\n output,\n str(output) + '_with_dropout_mask{}'.format(self.mask),\n ratio=float(self.dropout_ratio),\n is_test=self.is_test,\n )\n self.mask += 1\n return output\n\n\nclass MultiRNNCellInitializer(object):\n def __init__(self, cells):\n self.cells = cells\n\n def create_states(self, model):\n states = []\n for cell in self.cells:\n with core.NameScope(cell.name):\n states.extend(cell.initializer.create_states(model))\n return states\n\nclass MultiRNNCell(RNNCell):\n '''\n Multilayer RNN via the composition of RNNCell instance.\n\n It is the resposibility of calling code to ensure the compatibility\n of the successive layers in terms of input/output dimensiality, etc.,\n and to ensure that their blobs do not have name conflicts, typically by\n creating the cells with names that specify layer number.\n\n Assumes first state (recurrent output) for each layer should be the input\n to the next layer.\n '''\n\n def __init__(self, cells, residual_output_layers=None, **kwargs):\n '''\n cells: list of RNNCell instances, from input to output side.\n\n name: string designating network component (for scoping)\n\n residual_output_layers: list of indices of layers whose input will\n be added elementwise to their output elementwise. (It is the\n responsibility of the client code to ensure shape compatibility.)\n Note that layer 0 (zero) cannot have residual output because of the\n timing of prepare_input().\n\n forward_only: used to construct inference-only network.\n '''\n super(MultiRNNCell, self).__init__(**kwargs)\n self.cells = cells\n\n if residual_output_layers is None:\n self.residual_output_layers = []\n else:\n self.residual_output_layers = residual_output_layers\n\n output_index_per_layer = []\n base_index = 0\n for cell in self.cells:\n output_index_per_layer.append(\n base_index + cell.get_output_state_index(),\n )\n base_index += len(cell.get_state_names())\n\n self.output_connected_layers = []\n self.output_indices = []\n for i in range(len(self.cells) - 1):\n if (i + 1) in self.residual_output_layers:\n self.output_connected_layers.append(i)\n self.output_indices.append(output_index_per_layer[i])\n else:\n self.output_connected_layers = []\n self.output_indices = []\n self.output_connected_layers.append(len(self.cells) - 1)\n self.output_indices.append(output_index_per_layer[-1])\n\n self.state_names = []\n for cell in self.cells:\n self.state_names.extend(cell.get_state_names())\n\n if len(self.state_names) != len(set(self.state_names)):\n duplicates = {\n state_name for state_name in self.state_names\n if self.state_names.count(state_name) > 1\n }\n raise RuntimeError(\n 'Duplicate state names in MultiRNNCell: {}'.format(\n list(duplicates),\n ),\n )\n\n self.initializer = MultiRNNCellInitializer(cells)\n\n def prepare_input(self, model, input_blob):\n return self.cells[0].prepare_input(model, input_blob)\n\n def _apply(\n self,\n model,\n input_t,\n seq_lengths,\n states,\n timestep,\n extra_inputs=None,\n ):\n\n states_per_layer = [len(cell.get_state_names()) for cell in self.cells]\n assert len(states) == sum(states_per_layer)\n\n next_states = []\n states_index = 0\n\n layer_input = input_t\n for i, layer_cell in enumerate(self.cells):\n num_states = states_per_layer[i]\n layer_states = states[states_index:(states_index + num_states)]\n states_index += num_states\n\n if i > 0:\n prepared_input = layer_cell.prepare_input(model, layer_input)\n else:\n prepared_input = layer_input\n\n layer_next_states = layer_cell._apply(\n model,\n prepared_input,\n seq_lengths,\n layer_states,\n timestep,\n extra_inputs=(None if i > 0 else extra_inputs),\n )\n # Since we're using here non-public method _apply, instead of apply,\n # we have to manually extract output from states\n if i != len(self.cells) - 1:\n layer_output = layer_cell._prepare_output(\n model,\n layer_next_states,\n )\n if i > 0 and i in self.residual_output_layers:\n layer_input = brew.sum(\n model,\n [layer_output, layer_input],\n self.scope('residual_output_{}'.format(i)),\n )\n else:\n layer_input = layer_output\n\n next_states.extend(layer_next_states)\n return next_states\n\n def get_state_names(self):\n return self.state_names\n\n def get_output_state_index(self):\n index = 0\n for cell in self.cells[:-1]:\n index += len(cell.get_state_names())\n index += self.cells[-1].get_output_state_index()\n return index\n\n def _prepare_output(self, model, states):\n connected_outputs = []\n state_index = 0\n for i, cell in enumerate(self.cells):\n num_states = len(cell.get_state_names())\n if i in self.output_connected_layers:\n layer_states = states[state_index:state_index + num_states]\n layer_output = cell._prepare_output(\n model,\n layer_states\n )\n connected_outputs.append(layer_output)\n state_index += num_states\n if len(connected_outputs) > 1:\n output = brew.sum(\n model,\n connected_outputs,\n self.scope('residual_output'),\n )\n else:\n output = connected_outputs[0]\n return output\n\n def _prepare_output_sequence(self, model, states):\n connected_outputs = []\n state_index = 0\n for i, cell in enumerate(self.cells):\n num_states = 2 * len(cell.get_state_names())\n if i in self.output_connected_layers:\n layer_states = states[state_index:state_index + num_states]\n layer_output = cell._prepare_output_sequence(\n model,\n layer_states\n )\n connected_outputs.append(layer_output)\n state_index += num_states\n if len(connected_outputs) > 1:\n output = brew.sum(\n model,\n connected_outputs,\n self.scope('residual_output_sequence'),\n )\n else:\n output = connected_outputs[0]\n return output\n\n\nclass AttentionCell(RNNCell):\n\n def __init__(\n self,\n encoder_output_dim,\n encoder_outputs,\n encoder_lengths,\n decoder_cell,\n decoder_state_dim,\n attention_type,\n weighted_encoder_outputs,\n attention_memory_optimization,\n **kwargs\n ):\n super(AttentionCell, self).__init__(**kwargs)\n self.encoder_output_dim = encoder_output_dim\n self.encoder_outputs = encoder_outputs\n self.encoder_lengths = encoder_lengths\n self.decoder_cell = decoder_cell\n self.decoder_state_dim = decoder_state_dim\n self.weighted_encoder_outputs = weighted_encoder_outputs\n self.encoder_outputs_transposed = None\n assert attention_type in [\n AttentionType.Regular,\n AttentionType.Recurrent,\n AttentionType.Dot,\n AttentionType.SoftCoverage,\n ]\n self.attention_type = attention_type\n self.attention_memory_optimization = attention_memory_optimization\n\n def _apply(\n self,\n model,\n input_t,\n seq_lengths,\n states,\n timestep,\n extra_inputs=None,\n ):\n if self.attention_type == AttentionType.SoftCoverage:\n decoder_prev_states = states[:-2]\n attention_weighted_encoder_context_t_prev = states[-2]\n coverage_t_prev = states[-1]\n else:\n decoder_prev_states = states[:-1]\n attention_weighted_encoder_context_t_prev = states[-1]\n\n assert extra_inputs is None\n\n decoder_states = self.decoder_cell._apply(\n model,\n input_t,\n seq_lengths,\n decoder_prev_states,\n timestep,\n extra_inputs=[(\n attention_weighted_encoder_context_t_prev,\n self.encoder_output_dim,\n )],\n )\n\n self.hidden_t_intermediate = self.decoder_cell._prepare_output(\n model,\n decoder_states,\n )\n\n if self.attention_type == AttentionType.Recurrent:\n (\n attention_weighted_encoder_context_t,\n self.attention_weights_3d,\n attention_blobs,\n ) = apply_recurrent_attention(\n model=model,\n encoder_output_dim=self.encoder_output_dim,\n encoder_outputs_transposed=self.encoder_outputs_transposed,\n weighted_encoder_outputs=self.weighted_encoder_outputs,\n decoder_hidden_state_t=self.hidden_t_intermediate,\n decoder_hidden_state_dim=self.decoder_state_dim,\n scope=self.name,\n attention_weighted_encoder_context_t_prev=(\n attention_weighted_encoder_context_t_prev\n ),\n encoder_lengths=self.encoder_lengths,\n )\n elif self.attention_type == AttentionType.Regular:\n (\n attention_weighted_encoder_context_t,\n self.attention_weights_3d,\n attention_blobs,\n ) = apply_regular_attention(\n model=model,\n encoder_output_dim=self.encoder_output_dim,\n encoder_outputs_transposed=self.encoder_outputs_transposed,\n weighted_encoder_outputs=self.weighted_encoder_outputs,\n decoder_hidden_state_t=self.hidden_t_intermediate,\n decoder_hidden_state_dim=self.decoder_state_dim,\n scope=self.name,\n encoder_lengths=self.encoder_lengths,\n )\n elif self.attention_type == AttentionType.Dot:\n (\n attention_weighted_encoder_context_t,\n self.attention_weights_3d,\n attention_blobs,\n ) = apply_dot_attention(\n model=model,\n encoder_output_dim=self.encoder_output_dim,\n encoder_outputs_transposed=self.encoder_outputs_transposed,\n decoder_hidden_state_t=self.hidden_t_intermediate,\n decoder_hidden_state_dim=self.decoder_state_dim,\n scope=self.name,\n encoder_lengths=self.encoder_lengths,\n )\n elif self.attention_type == AttentionType.SoftCoverage:\n (\n attention_weighted_encoder_context_t,\n self.attention_weights_3d,\n attention_blobs,\n coverage_t,\n ) = apply_soft_coverage_attention(\n model=model,\n encoder_output_dim=self.encoder_output_dim,\n encoder_outputs_transposed=self.encoder_outputs_transposed,\n weighted_encoder_outputs=self.weighted_encoder_outputs,\n decoder_hidden_state_t=self.hidden_t_intermediate,\n decoder_hidden_state_dim=self.decoder_state_dim,\n scope=self.name,\n encoder_lengths=self.encoder_lengths,\n coverage_t_prev=coverage_t_prev,\n coverage_weights=self.coverage_weights,\n )\n else:\n raise Exception('Attention type {} not implemented'.format(\n self.attention_type\n ))\n\n if self.attention_memory_optimization:\n self.recompute_blobs.extend(attention_blobs)\n\n output = list(decoder_states) + [attention_weighted_encoder_context_t]\n if self.attention_type == AttentionType.SoftCoverage:\n output.append(coverage_t)\n\n output[self.decoder_cell.get_output_state_index()] = model.Copy(\n output[self.decoder_cell.get_output_state_index()],\n self.scope('hidden_t_external'),\n )\n model.net.AddExternalOutputs(*output)\n\n return output\n\n def get_attention_weights(self):\n # [batch_size, encoder_length, 1]\n return self.attention_weights_3d\n\n def prepare_input(self, model, input_blob):\n if self.encoder_outputs_transposed is None:\n self.encoder_outputs_transposed = brew.transpose(\n model,\n self.encoder_outputs,\n self.scope('encoder_outputs_transposed'),\n axes=[1, 2, 0],\n )\n if (\n self.weighted_encoder_outputs is None and\n self.attention_type != AttentionType.Dot\n ):\n self.weighted_encoder_outputs = brew.fc(\n model,\n self.encoder_outputs,\n self.scope('weighted_encoder_outputs'),\n dim_in=self.encoder_output_dim,\n dim_out=self.encoder_output_dim,\n axis=2,\n )\n\n return self.decoder_cell.prepare_input(model, input_blob)\n\n def build_initial_coverage(self, model):\n \"\"\"\n initial_coverage is always zeros of shape [encoder_length],\n which shape must be determined programmatically dureing network\n computation.\n\n This method also sets self.coverage_weights, a separate transform\n of encoder_outputs which is used to determine coverage contribution\n tp attention.\n \"\"\"\n assert self.attention_type == AttentionType.SoftCoverage\n\n # [encoder_length, batch_size, encoder_output_dim]\n self.coverage_weights = brew.fc(\n model,\n self.encoder_outputs,\n self.scope('coverage_weights'),\n dim_in=self.encoder_output_dim,\n dim_out=self.encoder_output_dim,\n axis=2,\n )\n\n encoder_length = model.net.Slice(\n model.net.Shape(self.encoder_outputs),\n starts=[0],\n ends=[1],\n )\n if (\n scope.CurrentDeviceScope() is not None and\n scope.CurrentDeviceScope().device_type == caffe2_pb2.CUDA\n ):\n encoder_length = model.net.CopyGPUToCPU(\n encoder_length,\n 'encoder_length_cpu',\n )\n # total attention weight applied across decoding steps_per_checkpoint\n # shape: [encoder_length]\n initial_coverage = model.net.ConstantFill(\n encoder_length,\n self.scope('initial_coverage'),\n value=0.0,\n input_as_shape=1,\n )\n return initial_coverage\n\n def get_state_names(self):\n state_names = list(self.decoder_cell.get_state_names())\n state_names[self.get_output_state_index()] = self.scope(\n 'hidden_t_external',\n )\n state_names.append(self.scope('attention_weighted_encoder_context_t'))\n if self.attention_type == AttentionType.SoftCoverage:\n state_names.append(self.scope('coverage_t'))\n return state_names\n\n def get_output_dim(self):\n return self.decoder_state_dim + self.encoder_output_dim\n\n def get_output_state_index(self):\n return self.decoder_cell.get_output_state_index()\n\n def _prepare_output(self, model, states):\n if self.attention_type == AttentionType.SoftCoverage:\n attention_context = states[-2]\n else:\n attention_context = states[-1]\n\n with core.NameScope(self.name or ''):\n output = brew.concat(\n model,\n [self.hidden_t_intermediate, attention_context],\n 'states_and_context_combination',\n axis=2,\n )\n\n return output\n\n def _prepare_output_sequence(self, model, state_outputs):\n if self.attention_type == AttentionType.SoftCoverage:\n decoder_state_outputs = state_outputs[:-4]\n else:\n decoder_state_outputs = state_outputs[:-2]\n\n decoder_output = self.decoder_cell._prepare_output_sequence(\n model,\n decoder_state_outputs,\n )\n\n if self.attention_type == AttentionType.SoftCoverage:\n attention_context_index = 2 * (len(self.get_state_names()) - 2)\n else:\n attention_context_index = 2 * (len(self.get_state_names()) - 1)\n\n with core.NameScope(self.name or ''):\n output = brew.concat(\n model,\n [\n decoder_output,\n state_outputs[attention_context_index],\n ],\n 'states_and_context_combination',\n axis=2,\n )\n return output\n\n\nclass LSTMWithAttentionCell(AttentionCell):\n\n def __init__(\n self,\n encoder_output_dim,\n encoder_outputs,\n encoder_lengths,\n decoder_input_dim,\n decoder_state_dim,\n name,\n attention_type,\n weighted_encoder_outputs,\n forget_bias,\n lstm_memory_optimization,\n attention_memory_optimization,\n forward_only=False,\n ):\n decoder_cell = LSTMCell(\n input_size=decoder_input_dim,\n hidden_size=decoder_state_dim,\n forget_bias=forget_bias,\n memory_optimization=lstm_memory_optimization,\n name='{}/decoder'.format(name),\n forward_only=False,\n drop_states=False,\n )\n super(LSTMWithAttentionCell, self).__init__(\n encoder_output_dim=encoder_output_dim,\n encoder_outputs=encoder_outputs,\n encoder_lengths=encoder_lengths,\n decoder_cell=decoder_cell,\n decoder_state_dim=decoder_state_dim,\n name=name,\n attention_type=attention_type,\n weighted_encoder_outputs=weighted_encoder_outputs,\n attention_memory_optimization=attention_memory_optimization,\n forward_only=forward_only,\n )\n\n\nclass MILSTMWithAttentionCell(AttentionCell):\n\n def __init__(\n self,\n encoder_output_dim,\n encoder_outputs,\n decoder_input_dim,\n decoder_state_dim,\n name,\n attention_type,\n weighted_encoder_outputs,\n forget_bias,\n lstm_memory_optimization,\n attention_memory_optimization,\n forward_only=False,\n ):\n decoder_cell = MILSTMCell(\n input_size=decoder_input_dim,\n hidden_size=decoder_state_dim,\n forget_bias=forget_bias,\n memory_optimization=lstm_memory_optimization,\n name='{}/decoder'.format(name),\n forward_only=False,\n drop_states=False,\n )\n super(MILSTMWithAttentionCell, self).__init__(\n encoder_output_dim=encoder_output_dim,\n encoder_outputs=encoder_outputs,\n decoder_cell=decoder_cell,\n decoder_state_dim=decoder_state_dim,\n name=name,\n attention_type=attention_type,\n weighted_encoder_outputs=weighted_encoder_outputs,\n attention_memory_optimization=attention_memory_optimization,\n forward_only=forward_only,\n )\n\n\ndef _LSTM(\n cell_class,\n model,\n input_blob,\n seq_lengths,\n initial_states,\n dim_in,\n dim_out,\n scope,\n outputs_with_grads=(0,),\n return_params=False,\n memory_optimization=False,\n forget_bias=0.0,\n forward_only=False,\n drop_states=False,\n return_last_layer_only=True,\n static_rnn_unroll_size=None,\n):\n '''\n Adds a standard LSTM recurrent network operator to a model.\n\n cell_class: LSTMCell or compatible subclass\n\n model: ModelHelper object new operators would be added to\n\n input_blob: the input sequence in a format T x N x D\n where T is sequence size, N - batch size and D - input dimension\n\n seq_lengths: blob containing sequence lengths which would be passed to\n LSTMUnit operator\n\n initial_states: a list of (2 * num_layers) blobs representing the initial\n hidden and cell states of each layer. If this argument is None,\n these states will be added to the model as network parameters.\n\n dim_in: input dimension\n\n dim_out: number of units per LSTM layer\n (use int for single-layer LSTM, list of ints for multi-layer)\n\n outputs_with_grads : position indices of output blobs for LAST LAYER which\n will receive external error gradient during backpropagation.\n These outputs are: (h_all, h_last, c_all, c_last)\n\n return_params: if True, will return a dictionary of parameters of the LSTM\n\n memory_optimization: if enabled, the LSTM step is recomputed on backward\n step so that we don't need to store forward activations for each\n timestep. Saves memory with cost of computation.\n\n forget_bias: forget gate bias (default 0.0)\n\n forward_only: whether to create a backward pass\n\n drop_states: drop invalid states, passed through to LSTMUnit operator\n\n return_last_layer_only: only return outputs from final layer\n (so that length of results does depend on number of layers)\n\n static_rnn_unroll_size: if not None, we will use static RNN which is\n unrolled into Caffe2 graph. The size of the unroll is the value of\n this parameter.\n '''\n if type(dim_out) is not list and type(dim_out) is not tuple:\n dim_out = [dim_out]\n num_layers = len(dim_out)\n\n cells = []\n for i in range(num_layers):\n name = scope + \"/layer_{}\".format(i) if num_layers > 1 else scope\n cell = cell_class(\n input_size=(dim_in if i == 0 else dim_out[i - 1]),\n hidden_size=dim_out[i],\n forget_bias=forget_bias,\n memory_optimization=memory_optimization,\n name=name,\n forward_only=forward_only,\n drop_states=drop_states,\n )\n cells.append(cell)\n\n cell = MultiRNNCell(\n cells,\n name=scope,\n forward_only=forward_only,\n ) if num_layers > 1 else cells[0]\n\n cell = (\n cell if static_rnn_unroll_size is None\n else UnrolledCell(cell, static_rnn_unroll_size))\n\n # outputs_with_grads argument indexes into final layer\n outputs_with_grads = [4 * (num_layers - 1) + i for i in outputs_with_grads]\n _, result = cell.apply_over_sequence(\n model=model,\n inputs=input_blob,\n seq_lengths=seq_lengths,\n initial_states=initial_states,\n outputs_with_grads=outputs_with_grads,\n )\n\n if return_last_layer_only:\n result = result[4 * (num_layers - 1):]\n if return_params:\n result = list(result) + [{\n 'input': cell.get_input_params(),\n 'recurrent': cell.get_recurrent_params(),\n }]\n return tuple(result)\n\n\nLSTM = functools.partial(_LSTM, LSTMCell)\nMILSTM = functools.partial(_LSTM, MILSTMCell)\n\n\nclass UnrolledCell(RNNCell):\n def __init__(self, cell, T):\n self.T = T\n self.cell = cell\n\n def apply_over_sequence(\n self,\n model,\n inputs,\n seq_lengths,\n initial_states,\n outputs_with_grads=None,\n ):\n inputs = self.cell.prepare_input(model, inputs)\n\n # Now they are blob references - outputs of splitting the input sequence\n split_inputs = model.net.Split(\n inputs,\n [str(inputs) + \"_timestep_{}\".format(i)\n for i in range(self.T)],\n axis=0)\n if self.T == 1:\n split_inputs = [split_inputs]\n\n states = initial_states\n all_states = []\n for t in range(0, self.T):\n scope_name = \"timestep_{}\".format(t)\n # Parameters of all timesteps are shared\n with ParameterSharing({scope_name: ''}),\\\n scope.NameScope(scope_name):\n timestep = model.param_init_net.ConstantFill(\n [], \"timestep\", value=t, shape=[1],\n dtype=core.DataType.INT32,\n device_option=core.DeviceOption(caffe2_pb2.CPU))\n states = self.cell._apply(\n model=model,\n input_t=split_inputs[t],\n seq_lengths=seq_lengths,\n states=states,\n timestep=timestep,\n )\n all_states.append(states)\n\n all_states = zip(*all_states)\n all_states = [\n model.net.Concat(\n list(full_output),\n [\n str(full_output[0])[len(\"timestep_0/\"):] + \"_concat\",\n str(full_output[0])[len(\"timestep_0/\"):] + \"_concat_info\"\n\n ],\n axis=0)[0]\n for full_output in all_states\n ]\n outputs = tuple(\n six.next(it) for it in\n itertools.cycle([iter(all_states), iter(states)])\n )\n outputs_without_grad = set(range(len(outputs))) - set(\n outputs_with_grads)\n for i in outputs_without_grad:\n model.net.ZeroGradient(outputs[i], [])\n logging.debug(\"Added 0 gradients for blobs:\",\n [outputs[i] for i in outputs_without_grad])\n\n final_output = self.cell._prepare_output_sequence(model, outputs)\n\n return final_output, outputs\n\n\ndef GetLSTMParamNames():\n weight_params = [\"input_gate_w\", \"forget_gate_w\", \"output_gate_w\", \"cell_w\"]\n bias_params = [\"input_gate_b\", \"forget_gate_b\", \"output_gate_b\", \"cell_b\"]\n return {'weights': weight_params, 'biases': bias_params}\n\n\ndef InitFromLSTMParams(lstm_pblobs, param_values):\n '''\n Set the parameters of LSTM based on predefined values\n '''\n weight_params = GetLSTMParamNames()['weights']\n bias_params = GetLSTMParamNames()['biases']\n for input_type in viewkeys(param_values):\n weight_values = [\n param_values[input_type][w].flatten()\n for w in weight_params\n ]\n wmat = np.array([])\n for w in weight_values:\n wmat = np.append(wmat, w)\n bias_values = [\n param_values[input_type][b].flatten()\n for b in bias_params\n ]\n bm = np.array([])\n for b in bias_values:\n bm = np.append(bm, b)\n\n weights_blob = lstm_pblobs[input_type]['weights']\n bias_blob = lstm_pblobs[input_type]['biases']\n cur_weight = workspace.FetchBlob(weights_blob)\n cur_biases = workspace.FetchBlob(bias_blob)\n\n workspace.FeedBlob(\n weights_blob,\n wmat.reshape(cur_weight.shape).astype(np.float32))\n workspace.FeedBlob(\n bias_blob,\n bm.reshape(cur_biases.shape).astype(np.float32))\n\n\ndef cudnn_LSTM(model, input_blob, initial_states, dim_in, dim_out,\n scope, recurrent_params=None, input_params=None,\n num_layers=1, return_params=False):\n '''\n CuDNN version of LSTM for GPUs.\n input_blob Blob containing the input. Will need to be available\n when param_init_net is run, because the sequence lengths\n and batch sizes will be inferred from the size of this\n blob.\n initial_states tuple of (hidden_init, cell_init) blobs\n dim_in input dimensions\n dim_out output/hidden dimension\n scope namescope to apply\n recurrent_params dict of blobs containing values for recurrent\n gate weights, biases (if None, use random init values)\n See GetLSTMParamNames() for format.\n input_params dict of blobs containing values for input\n gate weights, biases (if None, use random init values)\n See GetLSTMParamNames() for format.\n num_layers number of LSTM layers\n return_params if True, returns (param_extract_net, param_mapping)\n where param_extract_net is a net that when run, will\n populate the blobs specified in param_mapping with the\n current gate weights and biases (input/recurrent).\n Useful for assigning the values back to non-cuDNN\n LSTM.\n '''\n with core.NameScope(scope):\n weight_params = GetLSTMParamNames()['weights']\n bias_params = GetLSTMParamNames()['biases']\n\n input_weight_size = dim_out * dim_in\n upper_layer_input_weight_size = dim_out * dim_out\n recurrent_weight_size = dim_out * dim_out\n input_bias_size = dim_out\n recurrent_bias_size = dim_out\n\n def init(layer, pname, input_type):\n input_weight_size_for_layer = input_weight_size if layer == 0 else \\\n upper_layer_input_weight_size\n if pname in weight_params:\n sz = input_weight_size_for_layer if input_type == 'input' \\\n else recurrent_weight_size\n elif pname in bias_params:\n sz = input_bias_size if input_type == 'input' \\\n else recurrent_bias_size\n else:\n assert False, \"unknown parameter type {}\".format(pname)\n return model.param_init_net.UniformFill(\n [],\n \"lstm_init_{}_{}_{}\".format(input_type, pname, layer),\n shape=[sz])\n\n # Multiply by 4 since we have 4 gates per LSTM unit\n first_layer_sz = input_weight_size + recurrent_weight_size + \\\n input_bias_size + recurrent_bias_size\n upper_layer_sz = upper_layer_input_weight_size + \\\n recurrent_weight_size + input_bias_size + \\\n recurrent_bias_size\n total_sz = 4 * (first_layer_sz + (num_layers - 1) * upper_layer_sz)\n\n weights = model.create_param(\n 'lstm_weight',\n shape=[total_sz],\n initializer=Initializer('UniformFill'),\n tags=ParameterTags.WEIGHT,\n )\n\n lstm_args = {\n 'hidden_size': dim_out,\n 'rnn_mode': 'lstm',\n 'bidirectional': 0, # TODO\n 'dropout': 1.0, # TODO\n 'input_mode': 'linear', # TODO\n 'num_layers': num_layers,\n 'engine': 'CUDNN'\n }\n\n param_extract_net = core.Net(\"lstm_param_extractor\")\n param_extract_net.AddExternalInputs([input_blob, weights])\n param_extract_mapping = {}\n\n # Populate the weights-blob from blobs containing parameters for\n # the individual components of the LSTM, such as forget/input gate\n # weights and bises. Also, create a special param_extract_net that\n # can be used to grab those individual params from the black-box\n # weights blob. These results can be then fed to InitFromLSTMParams()\n for input_type in ['input', 'recurrent']:\n param_extract_mapping[input_type] = {}\n p = recurrent_params if input_type == 'recurrent' else input_params\n if p is None:\n p = {}\n for pname in weight_params + bias_params:\n for j in range(0, num_layers):\n values = p[pname] if pname in p else init(j, pname, input_type)\n model.param_init_net.RecurrentParamSet(\n [input_blob, weights, values],\n weights,\n layer=j,\n input_type=input_type,\n param_type=pname,\n **lstm_args\n )\n if pname not in param_extract_mapping[input_type]:\n param_extract_mapping[input_type][pname] = {}\n b = param_extract_net.RecurrentParamGet(\n [input_blob, weights],\n [\"lstm_{}_{}_{}\".format(input_type, pname, j)],\n layer=j,\n input_type=input_type,\n param_type=pname,\n **lstm_args\n )\n param_extract_mapping[input_type][pname][j] = b\n\n (hidden_input_blob, cell_input_blob) = initial_states\n output, hidden_output, cell_output, rnn_scratch, dropout_states = \\\n model.net.Recurrent(\n [input_blob, hidden_input_blob, cell_input_blob, weights],\n [\"lstm_output\", \"lstm_hidden_output\", \"lstm_cell_output\",\n \"lstm_rnn_scratch\", \"lstm_dropout_states\"],\n seed=random.randint(0, 100000), # TODO: dropout seed\n **lstm_args\n )\n model.net.AddExternalOutputs(\n hidden_output, cell_output, rnn_scratch, dropout_states)\n\n if return_params:\n param_extract = param_extract_net, param_extract_mapping\n return output, hidden_output, cell_output, param_extract\n else:\n return output, hidden_output, cell_output\n\n\ndef LSTMWithAttention(\n model,\n decoder_inputs,\n decoder_input_lengths,\n initial_decoder_hidden_state,\n initial_decoder_cell_state,\n initial_attention_weighted_encoder_context,\n encoder_output_dim,\n encoder_outputs,\n encoder_lengths,\n decoder_input_dim,\n decoder_state_dim,\n scope,\n attention_type=AttentionType.Regular,\n outputs_with_grads=(0, 4),\n weighted_encoder_outputs=None,\n lstm_memory_optimization=False,\n attention_memory_optimization=False,\n forget_bias=0.0,\n forward_only=False,\n):\n '''\n Adds a LSTM with attention mechanism to a model.\n\n The implementation is based on https://arxiv.org/abs/1409.0473, with\n a small difference in the order\n how we compute new attention context and new hidden state, similarly to\n https://arxiv.org/abs/1508.04025.\n\n The model uses encoder-decoder naming conventions,\n where the decoder is the sequence the op is iterating over,\n while computing the attention context over the encoder.\n\n model: ModelHelper object new operators would be added to\n\n decoder_inputs: the input sequence in a format T x N x D\n where T is sequence size, N - batch size and D - input dimension\n\n decoder_input_lengths: blob containing sequence lengths\n which would be passed to LSTMUnit operator\n\n initial_decoder_hidden_state: initial hidden state of LSTM\n\n initial_decoder_cell_state: initial cell state of LSTM\n\n initial_attention_weighted_encoder_context: initial attention context\n\n encoder_output_dim: dimension of encoder outputs\n\n encoder_outputs: the sequence, on which we compute the attention context\n at every iteration\n\n encoder_lengths: a tensor with lengths of each encoder sequence in batch\n (may be None, meaning all encoder sequences are of same length)\n\n decoder_input_dim: input dimension (last dimension on decoder_inputs)\n\n decoder_state_dim: size of hidden states of LSTM\n\n attention_type: One of: AttentionType.Regular, AttentionType.Recurrent.\n Determines which type of attention mechanism to use.\n\n outputs_with_grads : position indices of output blobs which will receive\n external error gradient during backpropagation\n\n weighted_encoder_outputs: encoder outputs to be used to compute attention\n weights. In the basic case it's just linear transformation of\n encoder outputs (that the default, when weighted_encoder_outputs is None).\n However, it can be something more complicated - like a separate\n encoder network (for example, in case of convolutional encoder)\n\n lstm_memory_optimization: recompute LSTM activations on backward pass, so\n we don't need to store their values in forward passes\n\n attention_memory_optimization: recompute attention for backward pass\n\n forward_only: whether to create only forward pass\n '''\n cell = LSTMWithAttentionCell(\n encoder_output_dim=encoder_output_dim,\n encoder_outputs=encoder_outputs,\n encoder_lengths=encoder_lengths,\n decoder_input_dim=decoder_input_dim,\n decoder_state_dim=decoder_state_dim,\n name=scope,\n attention_type=attention_type,\n weighted_encoder_outputs=weighted_encoder_outputs,\n forget_bias=forget_bias,\n lstm_memory_optimization=lstm_memory_optimization,\n attention_memory_optimization=attention_memory_optimization,\n forward_only=forward_only,\n )\n initial_states = [\n initial_decoder_hidden_state,\n initial_decoder_cell_state,\n initial_attention_weighted_encoder_context,\n ]\n if attention_type == AttentionType.SoftCoverage:\n initial_states.append(cell.build_initial_coverage(model))\n _, result = cell.apply_over_sequence(\n model=model,\n inputs=decoder_inputs,\n seq_lengths=decoder_input_lengths,\n initial_states=initial_states,\n outputs_with_grads=outputs_with_grads,\n )\n return result\n\n\ndef _layered_LSTM(\n model, input_blob, seq_lengths, initial_states,\n dim_in, dim_out, scope, outputs_with_grads=(0,), return_params=False,\n memory_optimization=False, forget_bias=0.0, forward_only=False,\n drop_states=False, create_lstm=None):\n params = locals() # leave it as a first line to grab all params\n params.pop('create_lstm')\n if not isinstance(dim_out, list):\n return create_lstm(**params)\n elif len(dim_out) == 1:\n params['dim_out'] = dim_out[0]\n return create_lstm(**params)\n\n assert len(dim_out) != 0, \"dim_out list can't be empty\"\n assert return_params is False, \"return_params not supported for layering\"\n for i, output_dim in enumerate(dim_out):\n params.update({\n 'dim_out': output_dim\n })\n output, last_output, all_states, last_state = create_lstm(**params)\n params.update({\n 'input_blob': output,\n 'dim_in': output_dim,\n 'initial_states': (last_output, last_state),\n 'scope': scope + '_layer_{}'.format(i + 1)\n })\n return output, last_output, all_states, last_state\n\n\nlayered_LSTM = functools.partial(_layered_LSTM, create_lstm=LSTM)\n"
] | [
[
"numpy.array",
"numpy.append"
]
] |
Holmes-Alan/See360 | [
"24853246c126f883544bd618d622033f7a82c214"
] | [
"test_demo.py"
] | [
"from __future__ import print_function\r\nimport argparse\r\nfrom math import log10\r\n\r\nimport os\r\nimport torch\r\nimport torch.nn as nn\r\nfrom PIL import Image, ImageEnhance\r\nimport torch.backends.cudnn as cudnn\r\nimport torch.nn.functional as F\r\nfrom torch.utils.data import DataLoader\r\nfrom modules import *\r\nimport torchvision.transforms as transforms\r\nimport socket\r\nimport numpy as np\r\nfrom datasets import get_theta\r\nfrom util import PSNR, SSIM, rgb2ycbcr\r\nfrom os.path import join\r\nimport time\r\nimport json\r\nimport lpips\r\n\r\n\r\n# Training settings\r\nparser = argparse.ArgumentParser(description='PyTorch See360 model')\r\nparser.add_argument('--batchSize', type=int, default=64, help='training batch size')\r\nparser.add_argument('--gpu_mode', type=bool, default=True)\r\nparser.add_argument('--threads', type=int, default=6, help='number of threads for data loader to use')\r\nparser.add_argument('--seed', type=int, default=123, help='random seed to use. Default=123')\r\nparser.add_argument('--gpus', default=2, type=int, help='number of gpu')\r\nparser.add_argument('--data_dir', type=str, default='./data/real_world')\r\nparser.add_argument('--test_set', type=str, default='British') # British, Louvre, Manhattan, Parliament\r\nparser.add_argument('--save_dir', default='result/', help='Location to save checkpoint models')\r\nparser.add_argument('--log_folder', default='record/', help='Location to save checkpoint models')\r\n\r\n\r\nopt = parser.parse_args()\r\ngpus_list = range(opt.gpus)\r\nhostname = str(socket.gethostname())\r\ncudnn.benchmark = True\r\nprint(opt)\r\n\r\n\r\ntransform = transforms.Compose([\r\n transforms.ToTensor(), # range [0, 255] -> [0.0,1.0]\r\n # transforms.Lambda(lambda x: x.mul(255))\r\n # transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))\r\n]\r\n)\r\n\r\n\r\ncuda = opt.gpu_mode\r\nif cuda and not torch.cuda.is_available():\r\n raise Exception(\"No GPU found, please run without --cuda\")\r\n\r\ntorch.manual_seed(opt.seed)\r\nif cuda:\r\n torch.cuda.manual_seed(opt.seed)\r\n\r\nprint('===> Loading datasets')\r\n\r\n\r\nfile_path = join(opt.data_dir, opt.test_set)\r\nsave_path = join(opt.save_dir, opt.test_set)\r\n\r\n\r\nprint('===> Building model ')\r\n\r\nmodel = generator_final_v2(input_dim=3, dim=64)\r\n\r\n\r\nmodel = torch.nn.DataParallel(model)\r\n\r\nloss_fn_alex = lpips.LPIPS(net='alex') # best forward scores\r\n\r\nif cuda:\r\n model = model.cuda(gpus_list[0])\r\n loss_fn_alex = loss_fn_alex.cuda(gpus_list[0])\r\n\r\nmodel.eval()\r\nloss_fn_alex.eval()\r\n\r\ndef eval(angle_left, angle_right, angle_target):\r\n\r\n model_name = 'models/' + opt.test_set + '/GAN_final.pth'\r\n\r\n if os.path.exists(model_name):\r\n model.load_state_dict(torch.load(model_name, map_location=lambda storage, loc: storage))\r\n # print('===> read model as: ', model_name)\r\n\r\n theta = int(12 / np.abs(angle_right - angle_left) * (angle_target - angle_left))\r\n code = F.one_hot(torch.tensor(theta), num_classes=12).float()\r\n\r\n if angle_right == 360:\r\n angle_right = 0\r\n img1 = Image.open(file_path + '/' + 'img1_crop.png').convert('RGB')\r\n img2 = Image.open(file_path + '/' + 'img2_crop.png').convert('RGB')\r\n\r\n img1 = transform(img1).unsqueeze(0)\r\n img2 = transform(img2).unsqueeze(0)\r\n\r\n img1 = img1.cuda(gpus_list[0])\r\n img2 = img2.cuda(gpus_list[0])\r\n\r\n with torch.no_grad():\r\n img1 = 2.0 * (img1 - 0.5)\r\n img2 = 2.0 * (img2 - 0.5)\r\n\r\n code = code.view(img1.shape[0], 12).cuda()\r\n\r\n output = model(img1, img2, code)\r\n\r\n output = output * 0.5 + 0.5\r\n\r\n output = output.data[0].cpu().permute(1, 2, 0)\r\n\r\n output = output * 255\r\n output = output.clamp(0, 255)\r\n\r\n out_name = save_path + '/' + str(angle_target) + '.png'\r\n Image.fromarray(np.uint8(output)).save(out_name)\r\n\r\n\r\n\r\n##########\r\n## Done ##\r\n##########\r\n\r\n##Eval Start!!!!\r\neval(angle_left=0, angle_right=60, angle_target=30)\r\n\r\n\r\n\r\n\r\n"
] | [
[
"torch.load",
"torch.cuda.manual_seed",
"torch.manual_seed",
"torch.no_grad",
"numpy.abs",
"torch.tensor",
"torch.cuda.is_available",
"torch.nn.DataParallel",
"numpy.uint8"
]
] |
jminsk-cc/xarray | [
"48c680f8e631b0786989356e8360968bef551195"
] | [
"xarray/tests/test_combine.py"
] | [
"from collections import OrderedDict\nfrom datetime import datetime\nfrom itertools import product\n\nimport numpy as np\nimport pytest\n\nfrom xarray import (\n DataArray,\n Dataset,\n auto_combine,\n combine_by_coords,\n combine_nested,\n concat,\n)\nfrom xarray.core import dtypes\nfrom xarray.core.combine import (\n _check_shape_tile_ids,\n _combine_all_along_first_dim,\n _combine_nd,\n _infer_concat_order_from_coords,\n _infer_concat_order_from_positions,\n _new_tile_id,\n)\n\nfrom . import assert_equal, assert_identical, raises_regex\nfrom .test_dataset import create_test_data\n\n\ndef assert_combined_tile_ids_equal(dict1, dict2):\n assert len(dict1) == len(dict2)\n for k, v in dict1.items():\n assert k in dict2.keys()\n assert_equal(dict1[k], dict2[k])\n\n\nclass TestTileIDsFromNestedList:\n def test_1d(self):\n ds = create_test_data\n input = [ds(0), ds(1)]\n\n expected = {(0,): ds(0), (1,): ds(1)}\n actual = _infer_concat_order_from_positions(input)\n assert_combined_tile_ids_equal(expected, actual)\n\n def test_2d(self):\n ds = create_test_data\n input = [[ds(0), ds(1)], [ds(2), ds(3)], [ds(4), ds(5)]]\n\n expected = {\n (0, 0): ds(0),\n (0, 1): ds(1),\n (1, 0): ds(2),\n (1, 1): ds(3),\n (2, 0): ds(4),\n (2, 1): ds(5),\n }\n actual = _infer_concat_order_from_positions(input)\n assert_combined_tile_ids_equal(expected, actual)\n\n def test_3d(self):\n ds = create_test_data\n input = [\n [[ds(0), ds(1)], [ds(2), ds(3)], [ds(4), ds(5)]],\n [[ds(6), ds(7)], [ds(8), ds(9)], [ds(10), ds(11)]],\n ]\n\n expected = {\n (0, 0, 0): ds(0),\n (0, 0, 1): ds(1),\n (0, 1, 0): ds(2),\n (0, 1, 1): ds(3),\n (0, 2, 0): ds(4),\n (0, 2, 1): ds(5),\n (1, 0, 0): ds(6),\n (1, 0, 1): ds(7),\n (1, 1, 0): ds(8),\n (1, 1, 1): ds(9),\n (1, 2, 0): ds(10),\n (1, 2, 1): ds(11),\n }\n actual = _infer_concat_order_from_positions(input)\n assert_combined_tile_ids_equal(expected, actual)\n\n def test_single_dataset(self):\n ds = create_test_data(0)\n input = [ds]\n\n expected = {(0,): ds}\n actual = _infer_concat_order_from_positions(input)\n assert_combined_tile_ids_equal(expected, actual)\n\n def test_redundant_nesting(self):\n ds = create_test_data\n input = [[ds(0)], [ds(1)]]\n\n expected = {(0, 0): ds(0), (1, 0): ds(1)}\n actual = _infer_concat_order_from_positions(input)\n assert_combined_tile_ids_equal(expected, actual)\n\n def test_ignore_empty_list(self):\n ds = create_test_data(0)\n input = [ds, []]\n expected = {(0,): ds}\n actual = _infer_concat_order_from_positions(input)\n assert_combined_tile_ids_equal(expected, actual)\n\n def test_uneven_depth_input(self):\n # Auto_combine won't work on ragged input\n # but this is just to increase test coverage\n ds = create_test_data\n input = [ds(0), [ds(1), ds(2)]]\n\n expected = {(0,): ds(0), (1, 0): ds(1), (1, 1): ds(2)}\n actual = _infer_concat_order_from_positions(input)\n assert_combined_tile_ids_equal(expected, actual)\n\n def test_uneven_length_input(self):\n # Auto_combine won't work on ragged input\n # but this is just to increase test coverage\n ds = create_test_data\n input = [[ds(0)], [ds(1), ds(2)]]\n\n expected = {(0, 0): ds(0), (1, 0): ds(1), (1, 1): ds(2)}\n actual = _infer_concat_order_from_positions(input)\n assert_combined_tile_ids_equal(expected, actual)\n\n def test_infer_from_datasets(self):\n ds = create_test_data\n input = [ds(0), ds(1)]\n\n expected = {(0,): ds(0), (1,): ds(1)}\n actual = _infer_concat_order_from_positions(input)\n assert_combined_tile_ids_equal(expected, actual)\n\n\nclass TestTileIDsFromCoords:\n def test_1d(self):\n ds0 = Dataset({\"x\": [0, 1]})\n ds1 = Dataset({\"x\": [2, 3]})\n\n expected = {(0,): ds0, (1,): ds1}\n actual, concat_dims = _infer_concat_order_from_coords([ds1, ds0])\n assert_combined_tile_ids_equal(expected, actual)\n assert concat_dims == [\"x\"]\n\n def test_2d(self):\n ds0 = Dataset({\"x\": [0, 1], \"y\": [10, 20, 30]})\n ds1 = Dataset({\"x\": [2, 3], \"y\": [10, 20, 30]})\n ds2 = Dataset({\"x\": [0, 1], \"y\": [40, 50, 60]})\n ds3 = Dataset({\"x\": [2, 3], \"y\": [40, 50, 60]})\n ds4 = Dataset({\"x\": [0, 1], \"y\": [70, 80, 90]})\n ds5 = Dataset({\"x\": [2, 3], \"y\": [70, 80, 90]})\n\n expected = {\n (0, 0): ds0,\n (1, 0): ds1,\n (0, 1): ds2,\n (1, 1): ds3,\n (0, 2): ds4,\n (1, 2): ds5,\n }\n actual, concat_dims = _infer_concat_order_from_coords(\n [ds1, ds0, ds3, ds5, ds2, ds4]\n )\n assert_combined_tile_ids_equal(expected, actual)\n assert concat_dims == [\"x\", \"y\"]\n\n def test_no_dimension_coords(self):\n ds0 = Dataset({\"foo\": (\"x\", [0, 1])})\n ds1 = Dataset({\"foo\": (\"x\", [2, 3])})\n with raises_regex(ValueError, \"Could not find any dimension\"):\n _infer_concat_order_from_coords([ds1, ds0])\n\n def test_coord_not_monotonic(self):\n ds0 = Dataset({\"x\": [0, 1]})\n ds1 = Dataset({\"x\": [3, 2]})\n with raises_regex(\n ValueError,\n \"Coordinate variable x is neither \" \"monotonically increasing nor\",\n ):\n _infer_concat_order_from_coords([ds1, ds0])\n\n def test_coord_monotonically_decreasing(self):\n ds0 = Dataset({\"x\": [3, 2]})\n ds1 = Dataset({\"x\": [1, 0]})\n\n expected = {(0,): ds0, (1,): ds1}\n actual, concat_dims = _infer_concat_order_from_coords([ds1, ds0])\n assert_combined_tile_ids_equal(expected, actual)\n assert concat_dims == [\"x\"]\n\n def test_no_concatenation_needed(self):\n ds = Dataset({\"foo\": (\"x\", [0, 1])})\n expected = {(): ds}\n actual, concat_dims = _infer_concat_order_from_coords([ds])\n assert_combined_tile_ids_equal(expected, actual)\n assert concat_dims == []\n\n def test_2d_plus_bystander_dim(self):\n ds0 = Dataset({\"x\": [0, 1], \"y\": [10, 20, 30], \"t\": [0.1, 0.2]})\n ds1 = Dataset({\"x\": [2, 3], \"y\": [10, 20, 30], \"t\": [0.1, 0.2]})\n ds2 = Dataset({\"x\": [0, 1], \"y\": [40, 50, 60], \"t\": [0.1, 0.2]})\n ds3 = Dataset({\"x\": [2, 3], \"y\": [40, 50, 60], \"t\": [0.1, 0.2]})\n\n expected = {(0, 0): ds0, (1, 0): ds1, (0, 1): ds2, (1, 1): ds3}\n actual, concat_dims = _infer_concat_order_from_coords([ds1, ds0, ds3, ds2])\n assert_combined_tile_ids_equal(expected, actual)\n assert concat_dims == [\"x\", \"y\"]\n\n def test_string_coords(self):\n ds0 = Dataset({\"person\": [\"Alice\", \"Bob\"]})\n ds1 = Dataset({\"person\": [\"Caroline\", \"Daniel\"]})\n\n expected = {(0,): ds0, (1,): ds1}\n actual, concat_dims = _infer_concat_order_from_coords([ds1, ds0])\n assert_combined_tile_ids_equal(expected, actual)\n assert concat_dims == [\"person\"]\n\n # Decided against natural sorting of string coords GH #2616\n def test_lexicographic_sort_string_coords(self):\n ds0 = Dataset({\"simulation\": [\"run8\", \"run9\"]})\n ds1 = Dataset({\"simulation\": [\"run10\", \"run11\"]})\n\n expected = {(0,): ds1, (1,): ds0}\n actual, concat_dims = _infer_concat_order_from_coords([ds1, ds0])\n assert_combined_tile_ids_equal(expected, actual)\n assert concat_dims == [\"simulation\"]\n\n def test_datetime_coords(self):\n ds0 = Dataset({\"time\": [datetime(2000, 3, 6), datetime(2001, 3, 7)]})\n ds1 = Dataset({\"time\": [datetime(1999, 1, 1), datetime(1999, 2, 4)]})\n\n expected = {(0,): ds1, (1,): ds0}\n actual, concat_dims = _infer_concat_order_from_coords([ds0, ds1])\n assert_combined_tile_ids_equal(expected, actual)\n assert concat_dims == [\"time\"]\n\n\[email protected](scope=\"module\")\ndef create_combined_ids():\n return _create_combined_ids\n\n\ndef _create_combined_ids(shape):\n tile_ids = _create_tile_ids(shape)\n nums = range(len(tile_ids))\n return {tile_id: create_test_data(num) for tile_id, num in zip(tile_ids, nums)}\n\n\ndef _create_tile_ids(shape):\n tile_ids = product(*(range(i) for i in shape))\n return list(tile_ids)\n\n\nclass TestNewTileIDs:\n @pytest.mark.parametrize(\n \"old_id, new_id\",\n [((3, 0, 1), (0, 1)), ((0, 0), (0,)), ((1,), ()), ((0,), ()), ((1, 0), (0,))],\n )\n def test_new_tile_id(self, old_id, new_id):\n ds = create_test_data\n assert _new_tile_id((old_id, ds)) == new_id\n\n def test_get_new_tile_ids(self, create_combined_ids):\n shape = (1, 2, 3)\n combined_ids = create_combined_ids(shape)\n\n expected_tile_ids = sorted(combined_ids.keys())\n actual_tile_ids = _create_tile_ids(shape)\n assert expected_tile_ids == actual_tile_ids\n\n\nclass TestCombineND:\n @pytest.mark.parametrize(\"concat_dim\", [\"dim1\", \"new_dim\"])\n def test_concat_once(self, create_combined_ids, concat_dim):\n shape = (2,)\n combined_ids = create_combined_ids(shape)\n ds = create_test_data\n result = _combine_all_along_first_dim(\n combined_ids,\n dim=concat_dim,\n data_vars=\"all\",\n coords=\"different\",\n compat=\"no_conflicts\",\n )\n\n expected_ds = concat([ds(0), ds(1)], dim=concat_dim)\n assert_combined_tile_ids_equal(result, {(): expected_ds})\n\n def test_concat_only_first_dim(self, create_combined_ids):\n shape = (2, 3)\n combined_ids = create_combined_ids(shape)\n result = _combine_all_along_first_dim(\n combined_ids,\n dim=\"dim1\",\n data_vars=\"all\",\n coords=\"different\",\n compat=\"no_conflicts\",\n )\n\n ds = create_test_data\n partway1 = concat([ds(0), ds(3)], dim=\"dim1\")\n partway2 = concat([ds(1), ds(4)], dim=\"dim1\")\n partway3 = concat([ds(2), ds(5)], dim=\"dim1\")\n expected_datasets = [partway1, partway2, partway3]\n expected = {(i,): ds for i, ds in enumerate(expected_datasets)}\n\n assert_combined_tile_ids_equal(result, expected)\n\n @pytest.mark.parametrize(\"concat_dim\", [\"dim1\", \"new_dim\"])\n def test_concat_twice(self, create_combined_ids, concat_dim):\n shape = (2, 3)\n combined_ids = create_combined_ids(shape)\n result = _combine_nd(combined_ids, concat_dims=[\"dim1\", concat_dim])\n\n ds = create_test_data\n partway1 = concat([ds(0), ds(3)], dim=\"dim1\")\n partway2 = concat([ds(1), ds(4)], dim=\"dim1\")\n partway3 = concat([ds(2), ds(5)], dim=\"dim1\")\n expected = concat([partway1, partway2, partway3], dim=concat_dim)\n\n assert_equal(result, expected)\n\n\nclass TestCheckShapeTileIDs:\n def test_check_depths(self):\n ds = create_test_data(0)\n combined_tile_ids = {(0,): ds, (0, 1): ds}\n with raises_regex(ValueError, \"sub-lists do not have \" \"consistent depths\"):\n _check_shape_tile_ids(combined_tile_ids)\n\n def test_check_lengths(self):\n ds = create_test_data(0)\n combined_tile_ids = {(0, 0): ds, (0, 1): ds, (0, 2): ds, (1, 0): ds, (1, 1): ds}\n with raises_regex(ValueError, \"sub-lists do not have \" \"consistent lengths\"):\n _check_shape_tile_ids(combined_tile_ids)\n\n\nclass TestNestedCombine:\n def test_nested_concat(self):\n objs = [Dataset({\"x\": [0]}), Dataset({\"x\": [1]})]\n expected = Dataset({\"x\": [0, 1]})\n actual = combine_nested(objs, concat_dim=\"x\")\n assert_identical(expected, actual)\n actual = combine_nested(objs, concat_dim=[\"x\"])\n assert_identical(expected, actual)\n\n actual = combine_nested([actual], concat_dim=None)\n assert_identical(expected, actual)\n\n actual = combine_nested([actual], concat_dim=\"x\")\n assert_identical(expected, actual)\n\n objs = [Dataset({\"x\": [0, 1]}), Dataset({\"x\": [2]})]\n actual = combine_nested(objs, concat_dim=\"x\")\n expected = Dataset({\"x\": [0, 1, 2]})\n assert_identical(expected, actual)\n\n # ensure combine_nested handles non-sorted variables\n objs = [\n Dataset(OrderedDict([(\"x\", (\"a\", [0])), (\"y\", (\"a\", [0]))])),\n Dataset(OrderedDict([(\"y\", (\"a\", [1])), (\"x\", (\"a\", [1]))])),\n ]\n actual = combine_nested(objs, concat_dim=\"a\")\n expected = Dataset({\"x\": (\"a\", [0, 1]), \"y\": (\"a\", [0, 1])})\n assert_identical(expected, actual)\n\n objs = [Dataset({\"x\": [0], \"y\": [0]}), Dataset({\"x\": [0]})]\n with pytest.raises(KeyError):\n combine_nested(objs, concat_dim=\"x\")\n\n @pytest.mark.parametrize(\n \"join, expected\",\n [\n (\"outer\", Dataset({\"x\": [0, 1], \"y\": [0, 1]})),\n (\"inner\", Dataset({\"x\": [0, 1], \"y\": []})),\n (\"left\", Dataset({\"x\": [0, 1], \"y\": [0]})),\n (\"right\", Dataset({\"x\": [0, 1], \"y\": [1]})),\n ],\n )\n def test_combine_nested_join(self, join, expected):\n objs = [Dataset({\"x\": [0], \"y\": [0]}), Dataset({\"x\": [1], \"y\": [1]})]\n actual = combine_nested(objs, concat_dim=\"x\", join=join)\n assert_identical(expected, actual)\n\n def test_combine_nested_join_exact(self):\n objs = [Dataset({\"x\": [0], \"y\": [0]}), Dataset({\"x\": [1], \"y\": [1]})]\n with raises_regex(ValueError, \"indexes along dimension\"):\n combine_nested(objs, concat_dim=\"x\", join=\"exact\")\n\n def test_empty_input(self):\n assert_identical(Dataset(), combine_nested([], concat_dim=\"x\"))\n\n # Fails because of concat's weird treatment of dimension coords, see #2975\n @pytest.mark.xfail\n def test_nested_concat_too_many_dims_at_once(self):\n objs = [Dataset({\"x\": [0], \"y\": [1]}), Dataset({\"y\": [0], \"x\": [1]})]\n with pytest.raises(ValueError, match=\"not equal across datasets\"):\n combine_nested(objs, concat_dim=\"x\", coords=\"minimal\")\n\n def test_nested_concat_along_new_dim(self):\n objs = [\n Dataset({\"a\": (\"x\", [10]), \"x\": [0]}),\n Dataset({\"a\": (\"x\", [20]), \"x\": [0]}),\n ]\n expected = Dataset({\"a\": ((\"t\", \"x\"), [[10], [20]]), \"x\": [0]})\n actual = combine_nested(objs, concat_dim=\"t\")\n assert_identical(expected, actual)\n\n # Same but with a DataArray as new dim, see GH #1988 and #2647\n dim = DataArray([100, 150], name=\"baz\", dims=\"baz\")\n expected = Dataset(\n {\"a\": ((\"baz\", \"x\"), [[10], [20]]), \"x\": [0], \"baz\": [100, 150]}\n )\n actual = combine_nested(objs, concat_dim=dim)\n assert_identical(expected, actual)\n\n def test_nested_merge(self):\n data = Dataset({\"x\": 0})\n actual = combine_nested([data, data, data], concat_dim=None)\n assert_identical(data, actual)\n\n ds1 = Dataset({\"a\": (\"x\", [1, 2]), \"x\": [0, 1]})\n ds2 = Dataset({\"a\": (\"x\", [2, 3]), \"x\": [1, 2]})\n expected = Dataset({\"a\": (\"x\", [1, 2, 3]), \"x\": [0, 1, 2]})\n actual = combine_nested([ds1, ds2], concat_dim=None)\n assert_identical(expected, actual)\n actual = combine_nested([ds1, ds2], concat_dim=[None])\n assert_identical(expected, actual)\n\n tmp1 = Dataset({\"x\": 0})\n tmp2 = Dataset({\"x\": np.nan})\n actual = combine_nested([tmp1, tmp2], concat_dim=None)\n assert_identical(tmp1, actual)\n actual = combine_nested([tmp1, tmp2], concat_dim=[None])\n assert_identical(tmp1, actual)\n\n # Single object, with a concat_dim explicitly provided\n # Test the issue reported in GH #1988\n objs = [Dataset({\"x\": 0, \"y\": 1})]\n dim = DataArray([100], name=\"baz\", dims=\"baz\")\n actual = combine_nested(objs, concat_dim=[dim])\n expected = Dataset({\"x\": (\"baz\", [0]), \"y\": (\"baz\", [1])}, {\"baz\": [100]})\n assert_identical(expected, actual)\n\n # Just making sure that auto_combine is doing what is\n # expected for non-scalar values, too.\n objs = [Dataset({\"x\": (\"z\", [0, 1]), \"y\": (\"z\", [1, 2])})]\n dim = DataArray([100], name=\"baz\", dims=\"baz\")\n actual = combine_nested(objs, concat_dim=[dim])\n expected = Dataset(\n {\"x\": ((\"baz\", \"z\"), [[0, 1]]), \"y\": ((\"baz\", \"z\"), [[1, 2]])},\n {\"baz\": [100]},\n )\n assert_identical(expected, actual)\n\n def test_concat_multiple_dims(self):\n objs = [\n [Dataset({\"a\": ((\"x\", \"y\"), [[0]])}), Dataset({\"a\": ((\"x\", \"y\"), [[1]])})],\n [Dataset({\"a\": ((\"x\", \"y\"), [[2]])}), Dataset({\"a\": ((\"x\", \"y\"), [[3]])})],\n ]\n actual = combine_nested(objs, concat_dim=[\"x\", \"y\"])\n expected = Dataset({\"a\": ((\"x\", \"y\"), [[0, 1], [2, 3]])})\n assert_identical(expected, actual)\n\n def test_concat_name_symmetry(self):\n \"\"\"Inspired by the discussion on GH issue #2777\"\"\"\n\n da1 = DataArray(name=\"a\", data=[[0]], dims=[\"x\", \"y\"])\n da2 = DataArray(name=\"b\", data=[[1]], dims=[\"x\", \"y\"])\n da3 = DataArray(name=\"a\", data=[[2]], dims=[\"x\", \"y\"])\n da4 = DataArray(name=\"b\", data=[[3]], dims=[\"x\", \"y\"])\n\n x_first = combine_nested([[da1, da2], [da3, da4]], concat_dim=[\"x\", \"y\"])\n y_first = combine_nested([[da1, da3], [da2, da4]], concat_dim=[\"y\", \"x\"])\n\n assert_identical(x_first, y_first)\n\n def test_concat_one_dim_merge_another(self):\n data = create_test_data()\n data1 = data.copy(deep=True)\n data2 = data.copy(deep=True)\n\n objs = [\n [data1.var1.isel(dim2=slice(4)), data2.var1.isel(dim2=slice(4, 9))],\n [data1.var2.isel(dim2=slice(4)), data2.var2.isel(dim2=slice(4, 9))],\n ]\n\n expected = data[[\"var1\", \"var2\"]]\n actual = combine_nested(objs, concat_dim=[None, \"dim2\"])\n assert expected.identical(actual)\n\n def test_auto_combine_2d(self):\n ds = create_test_data\n\n partway1 = concat([ds(0), ds(3)], dim=\"dim1\")\n partway2 = concat([ds(1), ds(4)], dim=\"dim1\")\n partway3 = concat([ds(2), ds(5)], dim=\"dim1\")\n expected = concat([partway1, partway2, partway3], dim=\"dim2\")\n\n datasets = [[ds(0), ds(1), ds(2)], [ds(3), ds(4), ds(5)]]\n result = combine_nested(datasets, concat_dim=[\"dim1\", \"dim2\"])\n assert_equal(result, expected)\n\n def test_combine_nested_missing_data_new_dim(self):\n # Your data includes \"time\" and \"station\" dimensions, and each year's\n # data has a different set of stations.\n datasets = [\n Dataset({\"a\": (\"x\", [2, 3]), \"x\": [1, 2]}),\n Dataset({\"a\": (\"x\", [1, 2]), \"x\": [0, 1]}),\n ]\n expected = Dataset(\n {\"a\": ((\"t\", \"x\"), [[np.nan, 2, 3], [1, 2, np.nan]])}, {\"x\": [0, 1, 2]}\n )\n actual = combine_nested(datasets, concat_dim=\"t\")\n assert_identical(expected, actual)\n\n def test_invalid_hypercube_input(self):\n ds = create_test_data\n\n datasets = [[ds(0), ds(1), ds(2)], [ds(3), ds(4)]]\n with raises_regex(ValueError, \"sub-lists do not have \" \"consistent lengths\"):\n combine_nested(datasets, concat_dim=[\"dim1\", \"dim2\"])\n\n datasets = [[ds(0), ds(1)], [[ds(3), ds(4)]]]\n with raises_regex(ValueError, \"sub-lists do not have \" \"consistent depths\"):\n combine_nested(datasets, concat_dim=[\"dim1\", \"dim2\"])\n\n datasets = [[ds(0), ds(1)], [ds(3), ds(4)]]\n with raises_regex(ValueError, \"concat_dims has length\"):\n combine_nested(datasets, concat_dim=[\"dim1\"])\n\n def test_merge_one_dim_concat_another(self):\n objs = [\n [Dataset({\"foo\": (\"x\", [0, 1])}), Dataset({\"bar\": (\"x\", [10, 20])})],\n [Dataset({\"foo\": (\"x\", [2, 3])}), Dataset({\"bar\": (\"x\", [30, 40])})],\n ]\n expected = Dataset({\"foo\": (\"x\", [0, 1, 2, 3]), \"bar\": (\"x\", [10, 20, 30, 40])})\n\n actual = combine_nested(objs, concat_dim=[\"x\", None], compat=\"equals\")\n assert_identical(expected, actual)\n\n # Proving it works symmetrically\n objs = [\n [Dataset({\"foo\": (\"x\", [0, 1])}), Dataset({\"foo\": (\"x\", [2, 3])})],\n [Dataset({\"bar\": (\"x\", [10, 20])}), Dataset({\"bar\": (\"x\", [30, 40])})],\n ]\n actual = combine_nested(objs, concat_dim=[None, \"x\"], compat=\"equals\")\n assert_identical(expected, actual)\n\n def test_combine_concat_over_redundant_nesting(self):\n objs = [[Dataset({\"x\": [0]}), Dataset({\"x\": [1]})]]\n actual = combine_nested(objs, concat_dim=[None, \"x\"])\n expected = Dataset({\"x\": [0, 1]})\n assert_identical(expected, actual)\n\n objs = [[Dataset({\"x\": [0]})], [Dataset({\"x\": [1]})]]\n actual = combine_nested(objs, concat_dim=[\"x\", None])\n expected = Dataset({\"x\": [0, 1]})\n assert_identical(expected, actual)\n\n objs = [[Dataset({\"x\": [0]})]]\n actual = combine_nested(objs, concat_dim=[None, None])\n expected = Dataset({\"x\": [0]})\n assert_identical(expected, actual)\n\n def test_combine_nested_but_need_auto_combine(self):\n objs = [Dataset({\"x\": [0, 1]}), Dataset({\"x\": [2], \"wall\": [0]})]\n with raises_regex(ValueError, \"cannot be combined\"):\n combine_nested(objs, concat_dim=\"x\")\n\n @pytest.mark.parametrize(\"fill_value\", [dtypes.NA, 2, 2.0])\n def test_combine_nested_fill_value(self, fill_value):\n datasets = [\n Dataset({\"a\": (\"x\", [2, 3]), \"x\": [1, 2]}),\n Dataset({\"a\": (\"x\", [1, 2]), \"x\": [0, 1]}),\n ]\n if fill_value == dtypes.NA:\n # if we supply the default, we expect the missing value for a\n # float array\n fill_value = np.nan\n expected = Dataset(\n {\"a\": ((\"t\", \"x\"), [[fill_value, 2, 3], [1, 2, fill_value]])},\n {\"x\": [0, 1, 2]},\n )\n actual = combine_nested(datasets, concat_dim=\"t\", fill_value=fill_value)\n assert_identical(expected, actual)\n\n\nclass TestCombineAuto:\n def test_combine_by_coords(self):\n objs = [Dataset({\"x\": [0]}), Dataset({\"x\": [1]})]\n actual = combine_by_coords(objs)\n expected = Dataset({\"x\": [0, 1]})\n assert_identical(expected, actual)\n\n actual = combine_by_coords([actual])\n assert_identical(expected, actual)\n\n objs = [Dataset({\"x\": [0, 1]}), Dataset({\"x\": [2]})]\n actual = combine_by_coords(objs)\n expected = Dataset({\"x\": [0, 1, 2]})\n assert_identical(expected, actual)\n\n # ensure auto_combine handles non-sorted variables\n objs = [\n Dataset({\"x\": (\"a\", [0]), \"y\": (\"a\", [0]), \"a\": [0]}),\n Dataset({\"x\": (\"a\", [1]), \"y\": (\"a\", [1]), \"a\": [1]}),\n ]\n actual = combine_by_coords(objs)\n expected = Dataset({\"x\": (\"a\", [0, 1]), \"y\": (\"a\", [0, 1]), \"a\": [0, 1]})\n assert_identical(expected, actual)\n\n objs = [Dataset({\"x\": [0], \"y\": [0]}), Dataset({\"y\": [1], \"x\": [1]})]\n actual = combine_by_coords(objs)\n expected = Dataset({\"x\": [0, 1], \"y\": [0, 1]})\n assert_equal(actual, expected)\n\n objs = [Dataset({\"x\": 0}), Dataset({\"x\": 1})]\n with raises_regex(ValueError, \"Could not find any dimension \" \"coordinates\"):\n combine_by_coords(objs)\n\n objs = [Dataset({\"x\": [0], \"y\": [0]}), Dataset({\"x\": [0]})]\n with raises_regex(ValueError, \"Every dimension needs a coordinate\"):\n combine_by_coords(objs)\n\n def test_empty_input(self):\n assert_identical(Dataset(), combine_by_coords([]))\n\n @pytest.mark.parametrize(\n \"join, expected\",\n [\n (\"outer\", Dataset({\"x\": [0, 1], \"y\": [0, 1]})),\n (\"inner\", Dataset({\"x\": [0, 1], \"y\": []})),\n (\"left\", Dataset({\"x\": [0, 1], \"y\": [0]})),\n (\"right\", Dataset({\"x\": [0, 1], \"y\": [1]})),\n ],\n )\n def test_combine_coords_join(self, join, expected):\n objs = [Dataset({\"x\": [0], \"y\": [0]}), Dataset({\"x\": [1], \"y\": [1]})]\n actual = combine_nested(objs, concat_dim=\"x\", join=join)\n assert_identical(expected, actual)\n\n def test_combine_coords_join_exact(self):\n objs = [Dataset({\"x\": [0], \"y\": [0]}), Dataset({\"x\": [1], \"y\": [1]})]\n with raises_regex(ValueError, \"indexes along dimension\"):\n combine_nested(objs, concat_dim=\"x\", join=\"exact\")\n\n def test_infer_order_from_coords(self):\n data = create_test_data()\n objs = [data.isel(dim2=slice(4, 9)), data.isel(dim2=slice(4))]\n actual = combine_by_coords(objs)\n expected = data\n assert expected.broadcast_equals(actual)\n\n def test_combine_leaving_bystander_dimensions(self):\n # Check non-monotonic bystander dimension coord doesn't raise\n # ValueError on combine (https://github.com/pydata/xarray/issues/3150)\n ycoord = [\"a\", \"c\", \"b\"]\n\n data = np.random.rand(7, 3)\n\n ds1 = Dataset(\n data_vars=dict(data=([\"x\", \"y\"], data[:3, :])),\n coords=dict(x=[1, 2, 3], y=ycoord),\n )\n\n ds2 = Dataset(\n data_vars=dict(data=([\"x\", \"y\"], data[3:, :])),\n coords=dict(x=[4, 5, 6, 7], y=ycoord),\n )\n\n expected = Dataset(\n data_vars=dict(data=([\"x\", \"y\"], data)),\n coords=dict(x=[1, 2, 3, 4, 5, 6, 7], y=ycoord),\n )\n\n actual = combine_by_coords((ds1, ds2))\n assert_identical(expected, actual)\n\n def test_combine_by_coords_previously_failed(self):\n # In the above scenario, one file is missing, containing the data for\n # one year's data for one variable.\n datasets = [\n Dataset({\"a\": (\"x\", [0]), \"x\": [0]}),\n Dataset({\"b\": (\"x\", [0]), \"x\": [0]}),\n Dataset({\"a\": (\"x\", [1]), \"x\": [1]}),\n ]\n expected = Dataset({\"a\": (\"x\", [0, 1]), \"b\": (\"x\", [0, np.nan])}, {\"x\": [0, 1]})\n actual = combine_by_coords(datasets)\n assert_identical(expected, actual)\n\n def test_combine_by_coords_still_fails(self):\n # concat can't handle new variables (yet):\n # https://github.com/pydata/xarray/issues/508\n datasets = [Dataset({\"x\": 0}, {\"y\": 0}), Dataset({\"x\": 1}, {\"y\": 1, \"z\": 1})]\n with pytest.raises(ValueError):\n combine_by_coords(datasets, \"y\")\n\n def test_combine_by_coords_no_concat(self):\n objs = [Dataset({\"x\": 0}), Dataset({\"y\": 1})]\n actual = combine_by_coords(objs)\n expected = Dataset({\"x\": 0, \"y\": 1})\n assert_identical(expected, actual)\n\n objs = [Dataset({\"x\": 0, \"y\": 1}), Dataset({\"y\": np.nan, \"z\": 2})]\n actual = combine_by_coords(objs)\n expected = Dataset({\"x\": 0, \"y\": 1, \"z\": 2})\n assert_identical(expected, actual)\n\n def test_check_for_impossible_ordering(self):\n ds0 = Dataset({\"x\": [0, 1, 5]})\n ds1 = Dataset({\"x\": [2, 3]})\n with raises_regex(\n ValueError, \"does not have monotonic global indexes\" \" along dimension x\"\n ):\n combine_by_coords([ds1, ds0])\n\n\[email protected](\n \"ignore:In xarray version 0.13 `auto_combine` \" \"will be deprecated\"\n)\[email protected](\"ignore:Also `open_mfdataset` will no longer\")\[email protected](\"ignore:The datasets supplied\")\nclass TestAutoCombineOldAPI:\n \"\"\"\n Set of tests which check that old 1-dimensional auto_combine behaviour is\n still satisfied. #2616\n \"\"\"\n\n def test_auto_combine(self):\n objs = [Dataset({\"x\": [0]}), Dataset({\"x\": [1]})]\n actual = auto_combine(objs)\n expected = Dataset({\"x\": [0, 1]})\n assert_identical(expected, actual)\n\n actual = auto_combine([actual])\n assert_identical(expected, actual)\n\n objs = [Dataset({\"x\": [0, 1]}), Dataset({\"x\": [2]})]\n actual = auto_combine(objs)\n expected = Dataset({\"x\": [0, 1, 2]})\n assert_identical(expected, actual)\n\n # ensure auto_combine handles non-sorted variables\n objs = [\n Dataset(OrderedDict([(\"x\", (\"a\", [0])), (\"y\", (\"a\", [0]))])),\n Dataset(OrderedDict([(\"y\", (\"a\", [1])), (\"x\", (\"a\", [1]))])),\n ]\n actual = auto_combine(objs)\n expected = Dataset({\"x\": (\"a\", [0, 1]), \"y\": (\"a\", [0, 1])})\n assert_identical(expected, actual)\n\n objs = [Dataset({\"x\": [0], \"y\": [0]}), Dataset({\"y\": [1], \"x\": [1]})]\n with raises_regex(ValueError, \"too many .* dimensions\"):\n auto_combine(objs)\n\n objs = [Dataset({\"x\": 0}), Dataset({\"x\": 1})]\n with raises_regex(ValueError, \"cannot infer dimension\"):\n auto_combine(objs)\n\n objs = [Dataset({\"x\": [0], \"y\": [0]}), Dataset({\"x\": [0]})]\n with pytest.raises(KeyError):\n auto_combine(objs)\n\n def test_auto_combine_previously_failed(self):\n # In the above scenario, one file is missing, containing the data for\n # one year's data for one variable.\n datasets = [\n Dataset({\"a\": (\"x\", [0]), \"x\": [0]}),\n Dataset({\"b\": (\"x\", [0]), \"x\": [0]}),\n Dataset({\"a\": (\"x\", [1]), \"x\": [1]}),\n ]\n expected = Dataset({\"a\": (\"x\", [0, 1]), \"b\": (\"x\", [0, np.nan])}, {\"x\": [0, 1]})\n actual = auto_combine(datasets)\n assert_identical(expected, actual)\n\n # Your data includes \"time\" and \"station\" dimensions, and each year's\n # data has a different set of stations.\n datasets = [\n Dataset({\"a\": (\"x\", [2, 3]), \"x\": [1, 2]}),\n Dataset({\"a\": (\"x\", [1, 2]), \"x\": [0, 1]}),\n ]\n expected = Dataset(\n {\"a\": ((\"t\", \"x\"), [[np.nan, 2, 3], [1, 2, np.nan]])}, {\"x\": [0, 1, 2]}\n )\n actual = auto_combine(datasets, concat_dim=\"t\")\n assert_identical(expected, actual)\n\n def test_auto_combine_still_fails(self):\n # concat can't handle new variables (yet):\n # https://github.com/pydata/xarray/issues/508\n datasets = [Dataset({\"x\": 0}, {\"y\": 0}), Dataset({\"x\": 1}, {\"y\": 1, \"z\": 1})]\n with pytest.raises(ValueError):\n auto_combine(datasets, \"y\")\n\n def test_auto_combine_no_concat(self):\n objs = [Dataset({\"x\": 0}), Dataset({\"y\": 1})]\n actual = auto_combine(objs)\n expected = Dataset({\"x\": 0, \"y\": 1})\n assert_identical(expected, actual)\n\n objs = [Dataset({\"x\": 0, \"y\": 1}), Dataset({\"y\": np.nan, \"z\": 2})]\n actual = auto_combine(objs)\n expected = Dataset({\"x\": 0, \"y\": 1, \"z\": 2})\n assert_identical(expected, actual)\n\n data = Dataset({\"x\": 0})\n actual = auto_combine([data, data, data], concat_dim=None)\n assert_identical(data, actual)\n\n # Single object, with a concat_dim explicitly provided\n # Test the issue reported in GH #1988\n objs = [Dataset({\"x\": 0, \"y\": 1})]\n dim = DataArray([100], name=\"baz\", dims=\"baz\")\n actual = auto_combine(objs, concat_dim=dim)\n expected = Dataset({\"x\": (\"baz\", [0]), \"y\": (\"baz\", [1])}, {\"baz\": [100]})\n assert_identical(expected, actual)\n\n # Just making sure that auto_combine is doing what is\n # expected for non-scalar values, too.\n objs = [Dataset({\"x\": (\"z\", [0, 1]), \"y\": (\"z\", [1, 2])})]\n dim = DataArray([100], name=\"baz\", dims=\"baz\")\n actual = auto_combine(objs, concat_dim=dim)\n expected = Dataset(\n {\"x\": ((\"baz\", \"z\"), [[0, 1]]), \"y\": ((\"baz\", \"z\"), [[1, 2]])},\n {\"baz\": [100]},\n )\n assert_identical(expected, actual)\n\n def test_auto_combine_order_by_appearance_not_coords(self):\n objs = [\n Dataset({\"foo\": (\"x\", [0])}, coords={\"x\": (\"x\", [1])}),\n Dataset({\"foo\": (\"x\", [1])}, coords={\"x\": (\"x\", [0])}),\n ]\n actual = auto_combine(objs)\n expected = Dataset({\"foo\": (\"x\", [0, 1])}, coords={\"x\": (\"x\", [1, 0])})\n assert_identical(expected, actual)\n\n @pytest.mark.parametrize(\"fill_value\", [dtypes.NA, 2, 2.0])\n def test_auto_combine_fill_value(self, fill_value):\n datasets = [\n Dataset({\"a\": (\"x\", [2, 3]), \"x\": [1, 2]}),\n Dataset({\"a\": (\"x\", [1, 2]), \"x\": [0, 1]}),\n ]\n if fill_value == dtypes.NA:\n # if we supply the default, we expect the missing value for a\n # float array\n fill_value = np.nan\n expected = Dataset(\n {\"a\": ((\"t\", \"x\"), [[fill_value, 2, 3], [1, 2, fill_value]])},\n {\"x\": [0, 1, 2]},\n )\n actual = auto_combine(datasets, concat_dim=\"t\", fill_value=fill_value)\n assert_identical(expected, actual)\n\n\nclass TestAutoCombineDeprecation:\n \"\"\"\n Set of tests to check that FutureWarnings are correctly raised until the\n deprecation cycle is complete. #2616\n \"\"\"\n\n def test_auto_combine_with_concat_dim(self):\n objs = [Dataset({\"x\": [0]}), Dataset({\"x\": [1]})]\n with pytest.warns(FutureWarning, match=\"`concat_dim`\"):\n auto_combine(objs, concat_dim=\"x\")\n\n def test_auto_combine_with_merge_and_concat(self):\n objs = [Dataset({\"x\": [0]}), Dataset({\"x\": [1]}), Dataset({\"z\": ((), 99)})]\n with pytest.warns(FutureWarning, match=\"require both concatenation\"):\n auto_combine(objs)\n\n def test_auto_combine_with_coords(self):\n objs = [\n Dataset({\"foo\": (\"x\", [0])}, coords={\"x\": (\"x\", [0])}),\n Dataset({\"foo\": (\"x\", [1])}, coords={\"x\": (\"x\", [1])}),\n ]\n with pytest.warns(FutureWarning, match=\"supplied have global\"):\n auto_combine(objs)\n\n def test_auto_combine_without_coords(self):\n objs = [Dataset({\"foo\": (\"x\", [0])}), Dataset({\"foo\": (\"x\", [1])})]\n with pytest.warns(FutureWarning, match=\"supplied do not have global\"):\n auto_combine(objs)\n"
] | [
[
"numpy.random.rand"
]
] |
miltondp/clustermatch-gene-expr | [
"664bcf9032f53e22165ce7aa586dbf11365a5827"
] | [
"nbs/others/05_clustermatch_profiling/10_cm_optimized/py/02-cdist_parts_v01.py"
] | [
"# ---\n# jupyter:\n# jupytext:\n# cell_metadata_filter: all,-execution,-papermill,-trusted\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.11.5\n# kernelspec:\n# display_name: Python 3 (ipykernel)\n# language: python\n# name: python3\n# ---\n\n# %% [markdown] tags=[]\n# # Description\n\n# %% [markdown]\n# UPDATE:\n#\n# list changes here\n\n# %% [markdown]\n# \n\n# %% [markdown] tags=[]\n# # Remove pycache dir\n\n# %%\n# !echo ${CODE_DIR}\n\n# %%\n# !find ${CODE_DIR} -regex '^.*\\(__pycache__\\)$' -print\n\n# %%\n# !find ${CODE_DIR} -regex '^.*\\(__pycache__\\)$' -exec rm -rf {} \\;\n\n# %%\n# !find ${CODE_DIR} -regex '^.*\\(__pycache__\\)$' -print\n\n# %% [markdown] tags=[]\n# # Modules\n\n# %% tags=[]\nimport numpy as np\n\nfrom clustermatch.coef import _cm\n\n# %% [markdown] tags=[]\n# # Settings\n\n# %%\nN_REPS = 10\n\n# %% tags=[]\nnp.random.seed(0)\n\n# %% [markdown] tags=[]\n# # Setup\n\n# %%\n# let numba compile all the code before profiling\n_cm.py_func(np.random.rand(10), np.random.rand(10))\n\n# %% [markdown] tags=[]\n# # Run with `n_samples` small\n\n# %%\nN_SAMPLES = 100\n\n# %%\nx = np.random.rand(N_SAMPLES)\ny = np.random.rand(N_SAMPLES)\n\n\n# %% tags=[]\ndef func():\n for i in range(N_REPS):\n # py_func accesses the original python function, not the numba-optimized one\n # this is needed to be able to profile the function\n _cm.py_func(x, y)\n\n\n# %% tags=[]\n# %%timeit -n1 -r1 func()\nfunc()\n\n# %% tags=[]\n# %%prun -s cumulative -l 20 -T 02-n_samples_small.txt\nfunc()\n\n# %% [markdown] tags=[]\n# **No improvement** for this case.\n\n# %% [markdown] tags=[]\n# # Run with `n_samples` large\n\n# %%\nN_SAMPLES = 100000\n\n# %%\nx = np.random.rand(N_SAMPLES)\ny = np.random.rand(N_SAMPLES)\n\n\n# %% tags=[]\ndef func():\n for i in range(N_REPS):\n # py_func accesses the original python function, not the numba-optimized one\n # this is needed to be able to profile the function\n _cm.py_func(x, y)\n\n\n# %% tags=[]\n# %%timeit -n1 -r1 func()\nfunc()\n\n# %% tags=[]\n# %%prun -s cumulative -l 20 -T 02-n_samples_large.txt\nfunc()\n\n# %% [markdown] tags=[]\n# **Important improvement** for this case. `cdist_parts` takes now 0.370 percall instead of 0.824 (from reference).\n#\n# **However**, compared with `v00` (0.370 per call), this one is slightly worse.\n\n# %%\n"
] | [
[
"numpy.random.seed",
"numpy.random.rand"
]
] |
bjwheltor/improver | [
"21b21106f2a7376ee32cd01f47ea81bb770f56a9"
] | [
"improver/ensemble_copula_coupling/ensemble_copula_coupling.py"
] | [
"# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# (C) British Crown Copyright 2017-2021 Met Office.\n# 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# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * 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# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software 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\"\"\"\nThis module defines the plugins required for Ensemble Copula Coupling.\n\n\"\"\"\nimport warnings\nfrom typing import List, Optional, Tuple\n\nimport iris\nimport numpy as np\nfrom iris.cube import Cube\nfrom iris.exceptions import CoordinateNotFoundError, InvalidCubeError\nfrom numpy import ndarray\nfrom scipy import stats\n\nimport improver.ensemble_copula_coupling._scipy_continuous_distns as scipy_cont_distns\nfrom improver import BasePlugin\nfrom improver.calibration.utilities import convert_cube_data_to_2d\nfrom improver.ensemble_copula_coupling.utilities import (\n choose_set_of_percentiles,\n concatenate_2d_array_with_2d_array_endpoints,\n create_cube_with_percentiles,\n get_bounds_of_distribution,\n insert_lower_and_upper_endpoint_to_1d_array,\n interpolate_multiple_rows_same_x,\n interpolate_multiple_rows_same_y,\n restore_non_percentile_dimensions,\n)\nfrom improver.metadata.probabilistic import (\n find_percentile_coordinate,\n find_threshold_coordinate,\n format_cell_methods_for_diagnostic,\n get_diagnostic_cube_name_from_probability_name,\n get_threshold_coord_name_from_probability_name,\n probability_is_above_or_below,\n)\nfrom improver.utilities.cube_checker import (\n check_cube_coordinates,\n check_for_x_and_y_axes,\n)\nfrom improver.utilities.cube_manipulation import (\n MergeCubes,\n enforce_coordinate_ordering,\n get_dim_coord_names,\n)\nfrom improver.utilities.indexing_operations import choose\n\n\nclass RebadgePercentilesAsRealizations(BasePlugin):\n \"\"\"\n Class to rebadge percentiles as ensemble realizations.\n This will allow the quantisation to percentiles to be completed, without\n a subsequent EnsembleReordering step to restore spatial correlations,\n if required.\n \"\"\"\n\n @staticmethod\n def process(\n cube: Cube, ensemble_realization_numbers: Optional[ndarray] = None\n ) -> Cube:\n \"\"\"\n Rebadge percentiles as ensemble realizations. The ensemble\n realization numbering will depend upon the number of percentiles in\n the input cube i.e. 0, 1, 2, 3, ..., n-1, if there are n percentiles.\n\n Args:\n cube:\n Cube containing a percentile coordinate, which will be\n rebadged as ensemble realization.\n ensemble_realization_numbers:\n An array containing the ensemble numbers required in the output\n realization coordinate. Default is None, meaning the\n realization coordinate will be numbered 0, 1, 2 ... n-1 for n\n percentiles on the input cube.\n\n Returns:\n Processed cube\n\n Raises:\n InvalidCubeError:\n If the realization coordinate already exists on the cube.\n \"\"\"\n percentile_coord_name = find_percentile_coordinate(cube).name()\n\n if ensemble_realization_numbers is None:\n ensemble_realization_numbers = np.arange(\n len(cube.coord(percentile_coord_name).points), dtype=np.int32\n )\n\n cube.coord(percentile_coord_name).points = ensemble_realization_numbers\n\n # we can't rebadge if the realization coordinate already exists:\n try:\n realization_coord = cube.coord(\"realization\")\n except CoordinateNotFoundError:\n realization_coord = None\n\n if realization_coord:\n raise InvalidCubeError(\n \"Cannot rebadge percentile coordinate to realization \"\n \"coordinate because a realization coordinate already exists.\"\n )\n\n cube.coord(percentile_coord_name).rename(\"realization\")\n cube.coord(\"realization\").units = \"1\"\n cube.coord(\"realization\").points = cube.coord(\"realization\").points.astype(\n np.int32\n )\n\n return cube\n\n\nclass ResamplePercentiles(BasePlugin):\n \"\"\"\n Class for resampling percentiles from an existing set of percentiles.\n In combination with the Ensemble Reordering plugin, this is a variant of\n Ensemble Copula Coupling.\n\n This class includes the ability to linearly interpolate from an\n input set of percentiles to a different output set of percentiles.\n\n \"\"\"\n\n def __init__(self, ecc_bounds_warning: bool = False) -> None:\n \"\"\"\n Initialise the class.\n\n Args:\n ecc_bounds_warning:\n If true and ECC bounds are exceeded by the percentile values,\n a warning will be generated rather than an exception.\n Default value is FALSE.\n \"\"\"\n self.ecc_bounds_warning = ecc_bounds_warning\n\n def _add_bounds_to_percentiles_and_forecast_at_percentiles(\n self,\n percentiles: ndarray,\n forecast_at_percentiles: ndarray,\n bounds_pairing: Tuple[int, int],\n ) -> Tuple[ndarray, ndarray]:\n \"\"\"\n Padding of the lower and upper bounds of the percentiles for a\n given phenomenon, and padding of forecast values using the\n constant lower and upper bounds.\n\n Args:\n percentiles:\n Array of percentiles from a Cumulative Distribution Function.\n forecast_at_percentiles:\n Array containing the underlying forecast values at each\n percentile.\n bounds_pairing:\n Lower and upper bound to be used as the ends of the\n cumulative distribution function.\n\n Returns:\n - Percentiles\n - Forecast at percentiles with endpoints\n\n Raises:\n ValueError: If the percentile points are outside the ECC bounds\n and self.ecc_bounds_warning is False.\n ValueError: If the percentiles are not in ascending order.\n\n Warns:\n Warning: If the percentile points are outside the ECC bounds\n and self.ecc_bounds_warning is True.\n \"\"\"\n lower_bound, upper_bound = bounds_pairing\n percentiles = insert_lower_and_upper_endpoint_to_1d_array(percentiles, 0, 100)\n forecast = concatenate_2d_array_with_2d_array_endpoints(\n forecast_at_percentiles, lower_bound, upper_bound\n )\n\n if np.any(np.diff(forecast) < 0):\n out_of_bounds_vals = forecast[np.where(np.diff(forecast) < 0)]\n msg = (\n \"Forecast values exist that fall outside the expected extrema \"\n \"values that are defined as bounds in \"\n \"ensemble_copula_coupling/constants.py. \"\n \"Applying the extrema values as end points to the distribution \"\n \"would result in non-monotonically increasing values. \"\n \"The defined extremes are {}, whilst the following forecast \"\n \"values exist outside this range: {}.\".format(\n bounds_pairing, out_of_bounds_vals\n )\n )\n\n if self.ecc_bounds_warning:\n warn_msg = msg + (\n \" The percentile values that have \"\n \"exceeded the existing bounds will be used \"\n \"as new bounds.\"\n )\n warnings.warn(warn_msg)\n if upper_bound < forecast.max():\n upper_bound = forecast.max()\n if lower_bound > forecast.min():\n lower_bound = forecast.min()\n forecast = concatenate_2d_array_with_2d_array_endpoints(\n forecast_at_percentiles, lower_bound, upper_bound\n )\n else:\n raise ValueError(msg)\n if np.any(np.diff(percentiles) < 0):\n msg = (\n \"The percentiles must be in ascending order.\"\n \"The input percentiles were {}\".format(percentiles)\n )\n raise ValueError(msg)\n return percentiles, forecast\n\n def _interpolate_percentiles(\n self,\n forecast_at_percentiles: Cube,\n desired_percentiles: ndarray,\n bounds_pairing: Tuple[int, int],\n percentile_coord_name: str,\n ) -> Cube:\n \"\"\"\n Interpolation of forecast for a set of percentiles from an initial\n set of percentiles to a new set of percentiles. This is constructed\n by linearly interpolating between the original set of percentiles\n to a new set of percentiles.\n\n Args:\n forecast_at_percentiles:\n Cube containing a percentile coordinate.\n desired_percentiles:\n Array of the desired percentiles.\n bounds_pairing:\n Lower and upper bound to be used as the ends of the\n cumulative distribution function.\n percentile_coord_name:\n Name of required percentile coordinate.\n\n Returns:\n Cube containing values for the required diagnostic e.g.\n air_temperature at the required percentiles.\n \"\"\"\n original_percentiles = forecast_at_percentiles.coord(\n percentile_coord_name\n ).points\n\n original_mask = None\n if np.ma.is_masked(forecast_at_percentiles.data):\n original_mask = forecast_at_percentiles.data.mask[0]\n\n # Ensure that the percentile dimension is first, so that the\n # conversion to a 2d array produces data in the desired order.\n enforce_coordinate_ordering(forecast_at_percentiles, percentile_coord_name)\n forecast_at_reshaped_percentiles = convert_cube_data_to_2d(\n forecast_at_percentiles, coord=percentile_coord_name\n )\n\n (\n original_percentiles,\n forecast_at_reshaped_percentiles,\n ) = self._add_bounds_to_percentiles_and_forecast_at_percentiles(\n original_percentiles, forecast_at_reshaped_percentiles, bounds_pairing\n )\n\n forecast_at_interpolated_percentiles = interpolate_multiple_rows_same_x(\n np.array(desired_percentiles, dtype=np.float64),\n original_percentiles.astype(np.float64),\n forecast_at_reshaped_percentiles.astype(np.float64),\n )\n forecast_at_interpolated_percentiles = np.transpose(\n forecast_at_interpolated_percentiles\n )\n\n # Reshape forecast_at_percentiles, so the percentiles dimension is\n # first, and any other dimension coordinates follow.\n forecast_at_percentiles_data = restore_non_percentile_dimensions(\n forecast_at_interpolated_percentiles,\n next(forecast_at_percentiles.slices_over(percentile_coord_name)),\n len(desired_percentiles),\n )\n\n template_cube = next(forecast_at_percentiles.slices_over(percentile_coord_name))\n template_cube.remove_coord(percentile_coord_name)\n percentile_cube = create_cube_with_percentiles(\n desired_percentiles, template_cube, forecast_at_percentiles_data,\n )\n if original_mask is not None:\n original_mask = np.broadcast_to(original_mask, percentile_cube.shape)\n percentile_cube.data = np.ma.MaskedArray(\n percentile_cube.data, mask=original_mask\n )\n return percentile_cube\n\n def process(\n self,\n forecast_at_percentiles: Cube,\n no_of_percentiles: Optional[int] = None,\n sampling: Optional[str] = \"quantile\",\n percentiles: Optional[List] = None,\n ) -> Cube:\n \"\"\"\n 1. Creates a list of percentiles, if not provided.\n 2. Accesses the lower and upper bound pair of the forecast values,\n in order to specify lower and upper bounds for the percentiles.\n 3. Interpolate the percentile coordinate into an alternative\n set of percentiles using linear interpolation.\n\n Args:\n forecast_at_percentiles:\n Cube expected to contain a percentile coordinate.\n no_of_percentiles:\n Number of percentiles\n If None, the number of percentiles within the input\n forecast_at_percentiles cube is used as the\n number of percentiles.\n sampling:\n Type of sampling of the distribution to produce a set of\n percentiles e.g. quantile or random.\n\n Accepted options for sampling are:\n\n * Quantile: A regular set of equally-spaced percentiles aimed\n at dividing a Cumulative Distribution Function into\n blocks of equal probability.\n * Random: A random set of ordered percentiles.\n percentiles:\n List of the desired output percentiles.\n\n Returns:\n Cube with forecast values at the desired set of percentiles.\n The percentile coordinate is always the zeroth dimension.\n\n Raises:\n ValueError: The percentiles supplied must be between 0 and 100.\n \"\"\"\n percentile_coord = find_percentile_coordinate(forecast_at_percentiles)\n\n if percentiles:\n if any(p < 0 or p > 100 for p in percentiles):\n msg = (\n \"The percentiles supplied must be between 0 and 100. \"\n f\"Percentiles supplied: {percentiles}\"\n )\n raise ValueError(msg)\n else:\n if no_of_percentiles is None:\n no_of_percentiles = len(\n forecast_at_percentiles.coord(percentile_coord).points\n )\n percentiles = choose_set_of_percentiles(\n no_of_percentiles, sampling=sampling\n )\n\n cube_units = forecast_at_percentiles.units\n bounds_pairing = get_bounds_of_distribution(\n forecast_at_percentiles.name(), cube_units\n )\n\n forecast_at_percentiles = self._interpolate_percentiles(\n forecast_at_percentiles,\n percentiles,\n bounds_pairing,\n percentile_coord.name(),\n )\n return forecast_at_percentiles\n\n\nclass ConvertProbabilitiesToPercentiles(BasePlugin):\n \"\"\"\n Class for generating percentiles from probabilities.\n In combination with the Ensemble Reordering plugin, this is a variant\n Ensemble Copula Coupling.\n\n This class includes the ability to interpolate between probabilities\n specified using multiple thresholds in order to generate the percentiles,\n see Figure 1 from Flowerdew, 2014.\n\n Scientific Reference:\n Flowerdew, J., 2014.\n Calibrated ensemble reliability whilst preserving spatial structure.\n Tellus Series A, Dynamic Meteorology and Oceanography, 66, 22662.\n\n \"\"\"\n\n def __init__(self, ecc_bounds_warning: bool = False) -> None:\n \"\"\"\n Initialise the class.\n\n Args:\n ecc_bounds_warning:\n If true and ECC bounds are exceeded by the percentile values,\n a warning will be generated rather than an exception.\n Default value is FALSE.\n \"\"\"\n self.ecc_bounds_warning = ecc_bounds_warning\n\n def _add_bounds_to_thresholds_and_probabilities(\n self,\n threshold_points: ndarray,\n probabilities_for_cdf: ndarray,\n bounds_pairing: Tuple[int, int],\n ) -> Tuple[ndarray, ndarray]:\n \"\"\"\n Padding of the lower and upper bounds of the distribution for a\n given phenomenon for the threshold_points, and padding of\n probabilities of 0 and 1 to the forecast probabilities.\n\n Args:\n threshold_points:\n Array of threshold values used to calculate the probabilities.\n probabilities_for_cdf:\n Array containing the probabilities used for constructing an\n cumulative distribution function i.e. probabilities\n below threshold.\n bounds_pairing:\n Lower and upper bound to be used as the ends of the\n cumulative distribution function.\n\n Returns:\n - Array of threshold values padded with the lower and upper\n bound of the distribution.\n - Array containing the probabilities padded with 0 and 1 at\n each end.\n\n Raises:\n ValueError: If the thresholds exceed the ECC bounds for\n the diagnostic and self.ecc_bounds_warning is False.\n\n Warns:\n Warning: If the thresholds exceed the ECC bounds for\n the diagnostic and self.ecc_bounds_warning is True.\n \"\"\"\n lower_bound, upper_bound = bounds_pairing\n threshold_points_with_endpoints = insert_lower_and_upper_endpoint_to_1d_array(\n threshold_points, lower_bound, upper_bound\n )\n probabilities_for_cdf = concatenate_2d_array_with_2d_array_endpoints(\n probabilities_for_cdf, 0, 1\n )\n\n if np.any(np.diff(threshold_points_with_endpoints) < 0):\n msg = (\n \"The calculated threshold values {} are not in ascending \"\n \"order as required for the cumulative distribution \"\n \"function (CDF). This is due to the threshold values \"\n \"exceeding the range given by the ECC bounds {}.\".format(\n threshold_points_with_endpoints, bounds_pairing\n )\n )\n # If ecc_bounds_warning has been set, generate a warning message\n # rather than raising an exception so that subsequent processing\n # can continue. Then apply the new bounds as necessary to\n # ensure the threshold values and endpoints are in ascending\n # order and avoid problems further along the processing chain.\n if self.ecc_bounds_warning:\n warn_msg = msg + (\n \" The threshold points that have \"\n \"exceeded the existing bounds will be used \"\n \"as new bounds.\"\n )\n warnings.warn(warn_msg)\n if upper_bound < max(threshold_points_with_endpoints):\n upper_bound = max(threshold_points_with_endpoints)\n if lower_bound > min(threshold_points_with_endpoints):\n lower_bound = min(threshold_points_with_endpoints)\n threshold_points_with_endpoints = insert_lower_and_upper_endpoint_to_1d_array(\n threshold_points, lower_bound, upper_bound\n )\n else:\n raise ValueError(msg)\n return threshold_points_with_endpoints, probabilities_for_cdf\n\n def _probabilities_to_percentiles(\n self,\n forecast_probabilities: Cube,\n percentiles: ndarray,\n bounds_pairing: Tuple[int, int],\n ) -> Cube:\n \"\"\"\n Conversion of probabilities to percentiles through the construction\n of an cumulative distribution function. This is effectively\n constructed by linear interpolation from the probabilities associated\n with each threshold to a set of percentiles.\n\n Args:\n forecast_probabilities:\n Cube with a threshold coordinate.\n percentiles:\n Array of percentiles, at which the corresponding values will be\n calculated.\n bounds_pairing:\n Lower and upper bound to be used as the ends of the\n cumulative distribution function.\n\n Returns:\n Cube containing values for the required diagnostic e.g.\n air_temperature at the required percentiles.\n\n Raises:\n NotImplementedError: If the threshold coordinate has an\n spp__relative_to_threshold attribute that is not either\n \"above\" or \"below\".\n\n Warns:\n Warning: If the probability values are not ascending, so the\n resulting cdf is not monotonically increasing.\n \"\"\"\n threshold_coord = find_threshold_coordinate(forecast_probabilities)\n threshold_unit = threshold_coord.units\n threshold_points = threshold_coord.points\n\n original_mask = None\n if np.ma.is_masked(forecast_probabilities.data):\n original_mask = forecast_probabilities.data.mask[0]\n\n # Ensure that the percentile dimension is first, so that the\n # conversion to a 2d array produces data in the desired order.\n enforce_coordinate_ordering(forecast_probabilities, threshold_coord.name())\n prob_slices = convert_cube_data_to_2d(\n forecast_probabilities, coord=threshold_coord.name()\n )\n\n # The requirement below for a monotonically changing probability\n # across thresholds can be thwarted by precision errors of order 1E-10,\n # as such, here we round to a precision of 9 decimal places.\n prob_slices = np.around(prob_slices, 9)\n\n # Invert probabilities for data thresholded above thresholds.\n relation = probability_is_above_or_below(forecast_probabilities)\n if relation == \"above\":\n probabilities_for_cdf = 1 - prob_slices\n elif relation == \"below\":\n probabilities_for_cdf = prob_slices\n else:\n msg = (\n \"Probabilities to percentiles only implemented for \"\n \"thresholds above or below a given value.\"\n \"The relation to threshold is given as {}\".format(relation)\n )\n raise NotImplementedError(msg)\n\n (\n threshold_points,\n probabilities_for_cdf,\n ) = self._add_bounds_to_thresholds_and_probabilities(\n threshold_points, probabilities_for_cdf, bounds_pairing\n )\n\n if np.any(np.diff(probabilities_for_cdf) < 0):\n msg = (\n \"The probability values used to construct the \"\n \"Cumulative Distribution Function (CDF) \"\n \"must be ascending i.e. in order to yield \"\n \"a monotonically increasing CDF.\"\n \"The probabilities are {}\".format(probabilities_for_cdf)\n )\n warnings.warn(msg)\n\n # Convert percentiles into fractions.\n percentiles_as_fractions = np.array(\n [x / 100.0 for x in percentiles], dtype=np.float32\n )\n\n forecast_at_percentiles = interpolate_multiple_rows_same_y(\n percentiles_as_fractions.astype(np.float64),\n probabilities_for_cdf.astype(np.float64),\n threshold_points.astype(np.float64),\n )\n forecast_at_percentiles = forecast_at_percentiles.transpose()\n\n # Reshape forecast_at_percentiles, so the percentiles dimension is\n # first, and any other dimension coordinates follow.\n forecast_at_percentiles = restore_non_percentile_dimensions(\n forecast_at_percentiles,\n next(forecast_probabilities.slices_over(threshold_coord)),\n len(percentiles),\n )\n\n template_cube = next(forecast_probabilities.slices_over(threshold_coord.name()))\n template_cube.rename(\n get_diagnostic_cube_name_from_probability_name(template_cube.name())\n )\n template_cube.remove_coord(threshold_coord.name())\n\n percentile_cube = create_cube_with_percentiles(\n percentiles,\n template_cube,\n forecast_at_percentiles,\n cube_unit=threshold_unit,\n )\n\n if original_mask is not None:\n original_mask = np.broadcast_to(original_mask, percentile_cube.shape)\n percentile_cube.data = np.ma.MaskedArray(\n percentile_cube.data, mask=original_mask\n )\n return percentile_cube\n\n def process(\n self,\n forecast_probabilities: Cube,\n no_of_percentiles: Optional[int] = None,\n percentiles: Optional[List[float]] = None,\n sampling: str = \"quantile\",\n ) -> Cube:\n \"\"\"\n 1. Concatenates cubes with a threshold coordinate.\n 2. Creates a list of percentiles.\n 3. Accesses the lower and upper bound pair to find the ends of the\n cumulative distribution function.\n 4. Convert the threshold coordinate into\n values at a set of percentiles using linear interpolation,\n see Figure 1 from Flowerdew, 2014.\n\n Args:\n forecast_probabilities:\n Cube containing a threshold coordinate.\n no_of_percentiles:\n Number of percentiles. If None and percentiles is not set,\n the number of thresholds within the input\n forecast_probabilities cube is used as the number of\n percentiles. This argument is mutually exclusive with\n percentiles.\n percentiles:\n The desired percentile values in the interval [0, 100].\n This argument is mutually exclusive with no_of_percentiles.\n sampling:\n Type of sampling of the distribution to produce a set of\n percentiles e.g. quantile or random.\n\n Accepted options for sampling are:\n\n * Quantile: A regular set of equally-spaced percentiles aimed\n at dividing a Cumulative Distribution Function into\n blocks of equal probability.\n * Random: A random set of ordered percentiles.\n\n Returns:\n Cube with forecast values at the desired set of percentiles.\n The threshold coordinate is always the zeroth dimension.\n\n Raises:\n ValueError: If both no_of_percentiles and percentiles are provided\n \"\"\"\n if no_of_percentiles is not None and percentiles is not None:\n raise ValueError(\n \"Cannot specify both no_of_percentiles and percentiles to \"\n \"{}\".format(self.__class__.__name__)\n )\n\n threshold_coord = find_threshold_coordinate(forecast_probabilities)\n phenom_name = get_threshold_coord_name_from_probability_name(\n forecast_probabilities.name()\n )\n\n if no_of_percentiles is None:\n no_of_percentiles = len(\n forecast_probabilities.coord(threshold_coord.name()).points\n )\n\n if percentiles is None:\n percentiles = choose_set_of_percentiles(\n no_of_percentiles, sampling=sampling\n )\n elif not isinstance(percentiles, (tuple, list)):\n percentiles = [percentiles]\n percentiles = np.array(percentiles, dtype=np.float32)\n\n cube_units = forecast_probabilities.coord(threshold_coord.name()).units\n bounds_pairing = get_bounds_of_distribution(phenom_name, cube_units)\n\n # If a cube still has multiple realizations, slice over these to reduce\n # the memory requirements into manageable chunks.\n try:\n slices_over_realization = forecast_probabilities.slices_over(\"realization\")\n except CoordinateNotFoundError:\n slices_over_realization = [forecast_probabilities]\n\n cubelist = iris.cube.CubeList([])\n for cube_realization in slices_over_realization:\n cubelist.append(\n self._probabilities_to_percentiles(\n cube_realization, percentiles, bounds_pairing\n )\n )\n forecast_at_percentiles = cubelist.merge_cube()\n\n # Update cell methods on final cube\n if forecast_at_percentiles.cell_methods:\n format_cell_methods_for_diagnostic(forecast_at_percentiles)\n\n return forecast_at_percentiles\n\n\nclass ConvertLocationAndScaleParameters:\n \"\"\"\n Base Class to support the plugins that compute percentiles and\n probabilities from the location and scale parameters.\n \"\"\"\n\n def __init__(\n self, distribution: str = \"norm\", shape_parameters: Optional[ndarray] = None,\n ) -> None:\n \"\"\"\n Initialise the class.\n\n In order to construct percentiles or probabilities from the location\n or scale parameter, the distribution for the resulting output needs\n to be selected. For use with the outputs from EMOS, where it has been\n assumed that the outputs from minimising the CRPS follow a particular\n distribution, then the same distribution should be selected, as used\n for the CRPS minimisation. The conversion to percentiles and\n probabilities from the location and scale parameter relies upon\n functionality within scipy.stats.\n\n Args:\n distribution:\n Name of a distribution supported by scipy.stats.\n shape_parameters:\n For use with distributions in scipy.stats (e.g. truncnorm) that\n require the specification of shape parameters to be able to\n define the shape of the distribution. For the truncated normal\n distribution, the shape parameters should be appropriate for\n the distribution constructed from the location and scale\n parameters provided.\n Please note that for use with\n :meth:`~improver.calibration.\\\nensemble_calibration.ContinuousRankedProbabilityScoreMinimisers.\\\ncalculate_truncated_normal_crps`,\n the shape parameters for a truncated normal distribution with\n a lower bound of zero should be [0, np.inf].\n\n \"\"\"\n if distribution == \"truncnorm\":\n # Use scipy v1.3.3 truncnorm\n self.distribution = scipy_cont_distns.truncnorm\n else:\n try:\n self.distribution = getattr(stats, distribution)\n except AttributeError as err:\n msg = (\n \"The distribution requested {} is not a valid distribution \"\n \"in scipy.stats. {}\".format(distribution, err)\n )\n raise AttributeError(msg)\n\n if shape_parameters is None:\n if self.distribution.name == \"truncnorm\":\n raise ValueError(\n \"For the truncated normal distribution, \"\n \"shape parameters must be specified.\"\n )\n shape_parameters = []\n self.shape_parameters = shape_parameters\n\n def __repr__(self) -> str:\n \"\"\"Represent the configured plugin instance as a string.\"\"\"\n result = (\n \"<ConvertLocationAndScaleParameters: distribution: {}; \"\n \"shape_parameters: {}>\"\n )\n return result.format(self.distribution.name, self.shape_parameters)\n\n def _rescale_shape_parameters(\n self, location_parameter: ndarray, scale_parameter: ndarray\n ) -> None:\n \"\"\"\n Rescale the shape parameters for the desired location and scale\n parameters for the truncated normal distribution. The shape parameters\n for any other distribution will remain unchanged.\n\n For the truncated normal distribution, if the shape parameters are not\n rescaled, then :data:`scipy.stats.truncnorm` will assume that the shape\n parameters are appropriate for a standard normal distribution. As the\n aim is to construct a distribution using specific values for the\n location and scale parameters, the assumption of a standard normal\n distribution is not appropriate. Therefore the shape parameters are\n rescaled using the equations:\n\n .. math::\n a\\\\_rescaled = (a - location\\\\_parameter)/scale\\\\_parameter\n\n b\\\\_rescaled = (b - location\\\\_parameter)/scale\\\\_parameter\n\n Please see :data:`scipy.stats.truncnorm` for some further information.\n\n Args:\n location_parameter:\n Location parameter to be used to scale the shape parameters.\n scale_parameter:\n Scale parameter to be used to scale the shape parameters.\n \"\"\"\n if self.distribution.name == \"truncnorm\":\n rescaled_values = []\n for value in self.shape_parameters:\n rescaled_values.append((value - location_parameter) / scale_parameter)\n self.shape_parameters = rescaled_values\n\n\nclass ConvertLocationAndScaleParametersToPercentiles(\n BasePlugin, ConvertLocationAndScaleParameters\n):\n \"\"\"\n Plugin focusing on generating percentiles from location and scale\n parameters. In combination with the EnsembleReordering plugin, this is\n Ensemble Copula Coupling.\n \"\"\"\n\n def __repr__(self) -> str:\n \"\"\"Represent the configured plugin instance as a string.\"\"\"\n result = (\n \"<ConvertLocationAndScaleParametersToPercentiles: \"\n \"distribution: {}; shape_parameters: {}>\"\n )\n return result.format(self.distribution.name, self.shape_parameters)\n\n def _location_and_scale_parameters_to_percentiles(\n self,\n location_parameter: Cube,\n scale_parameter: Cube,\n template_cube: Cube,\n percentiles: List[float],\n ) -> Cube:\n \"\"\"\n Function returning percentiles based on the supplied location and\n scale parameters.\n\n Args:\n location_parameter:\n Location parameter of calibrated distribution.\n scale_parameter:\n Scale parameter of the calibrated distribution.\n template_cube:\n Template cube containing either a percentile or realization\n coordinate. All coordinates apart from the percentile or\n realization coordinate will be copied from the template cube.\n Metadata will also be copied from this cube.\n percentiles:\n Percentiles at which to calculate the value of the phenomenon\n at.\n\n Returns:\n Cube containing the values for the phenomenon at each of the\n percentiles requested.\n\n Raises:\n ValueError: If any of the resulting percentile values are\n nans and these nans are not caused by a scale parameter of\n zero.\n \"\"\"\n # Remove any mask that may be applied to location and scale parameters\n # and replace with ones\n location_data = np.ma.filled(location_parameter.data, 1).flatten()\n scale_data = np.ma.filled(scale_parameter.data, 1).flatten()\n\n # Convert percentiles into fractions.\n percentiles_as_fractions = np.array(\n [x / 100.0 for x in percentiles], dtype=np.float32\n )\n\n result = np.zeros(\n (len(percentiles_as_fractions), location_data.shape[0]), dtype=np.float32\n )\n\n self._rescale_shape_parameters(location_data, scale_data)\n\n percentile_method = self.distribution(\n *self.shape_parameters, loc=location_data, scale=scale_data\n )\n\n # Loop over percentiles, and use the distribution as the\n # \"percentile_method\" with the location and scale parameter to\n # calculate the values at each percentile.\n for index, percentile in enumerate(percentiles_as_fractions):\n percentile_list = np.repeat(percentile, len(location_data))\n result[index, :] = percentile_method.ppf(percentile_list)\n # If percent point function (PPF) returns NaNs, fill in\n # mean instead of NaN values. NaN will only be generated if the\n # scale parameter (standard deviation) is zero. Therefore, if the\n # scale parameter (standard deviation) is zero, the mean value is\n # used for all gridpoints with a NaN.\n if np.any(scale_data == 0):\n nan_index = np.argwhere(np.isnan(result[index, :]))\n result[index, nan_index] = location_data[nan_index]\n if np.any(np.isnan(result)):\n msg = (\n \"NaNs are present within the result for the {} \"\n \"percentile. Unable to calculate the percent point \"\n \"function.\"\n )\n raise ValueError(msg)\n\n # Reshape forecast_at_percentiles, so the percentiles dimension is\n # first, and any other dimension coordinates follow.\n result = result.reshape((len(percentiles),) + location_parameter.data.shape)\n\n for prob_coord_name in [\"realization\", \"percentile\"]:\n if template_cube.coords(prob_coord_name, dim_coords=True):\n prob_coord = template_cube.coord(prob_coord_name)\n template_slice = next(template_cube.slices_over(prob_coord))\n template_slice.remove_coord(prob_coord)\n elif template_cube.coords(prob_coord_name, dim_coords=False):\n template_slice = template_cube\n\n percentile_cube = create_cube_with_percentiles(\n percentiles, template_slice, result\n )\n # Define a mask to be reapplied later\n mask = np.logical_or(\n np.ma.getmaskarray(location_parameter.data),\n np.ma.getmaskarray(scale_parameter.data),\n )\n # Make the mask defined above fit the data size and then apply to the\n # percentile cube.\n mask_array = np.stack([mask] * len(percentiles))\n percentile_cube.data = np.ma.masked_where(mask_array, percentile_cube.data)\n # Remove cell methods associated with finding the ensemble mean\n percentile_cube.cell_methods = {}\n return percentile_cube\n\n def process(\n self,\n location_parameter: Cube,\n scale_parameter: Cube,\n template_cube: Cube,\n no_of_percentiles: Optional[int] = None,\n percentiles: Optional[List[float]] = None,\n ) -> Cube:\n \"\"\"\n Generate ensemble percentiles from the location and scale parameters.\n\n Args:\n location_parameter:\n Cube containing the location parameters.\n scale_parameter:\n Cube containing the scale parameters.\n template_cube:\n Template cube containing either a percentile or realization\n coordinate. All coordinates apart from the percentile or\n realization coordinate will be copied from the template cube.\n Metadata will also be copied from this cube.\n no_of_percentiles:\n Integer defining the number of percentiles that will be\n calculated from the location and scale parameters.\n percentiles:\n List of percentiles that will be generated from the location\n and scale parameters provided.\n\n Returns:\n Cube for calibrated percentiles.\n The percentile coordinate is always the zeroth dimension.\n\n Raises:\n ValueError: Ensure that it is not possible to supply\n \"no_of_percentiles\" and \"percentiles\" simultaneously\n as keyword arguments.\n \"\"\"\n if no_of_percentiles and percentiles:\n msg = (\n \"Please specify either the number of percentiles or \"\n \"provide a list of percentiles. The number of percentiles \"\n \"provided was {} and the list of percentiles \"\n \"provided was {}\".format(no_of_percentiles, percentiles)\n )\n raise ValueError(msg)\n\n if no_of_percentiles:\n percentiles = choose_set_of_percentiles(no_of_percentiles)\n calibrated_forecast_percentiles = self._location_and_scale_parameters_to_percentiles(\n location_parameter, scale_parameter, template_cube, percentiles\n )\n\n return calibrated_forecast_percentiles\n\n\nclass ConvertLocationAndScaleParametersToProbabilities(\n BasePlugin, ConvertLocationAndScaleParameters\n):\n \"\"\"\n Plugin to generate probabilities relative to given thresholds from the\n location and scale parameters of a distribution.\n \"\"\"\n\n def __repr__(self) -> str:\n \"\"\"Represent the configured plugin instance as a string.\"\"\"\n result = (\n \"<ConvertLocationAndScaleParametersToProbabilities: \"\n \"distribution: {}; shape_parameters: {}>\"\n )\n return result.format(self.distribution.name, self.shape_parameters)\n\n def _check_template_cube(self, cube: Cube) -> None:\n \"\"\"\n The template cube is expected to contain a leading threshold dimension\n followed by spatial (y/x) dimensions for a gridded cube. For a spot\n template cube, the spatial dimensions are not expected to be dimension\n coordinates. If the cube contains the expected dimensions,\n a threshold leading order is enforced.\n\n Args:\n cube:\n A cube whose dimensions are checked to ensure they match what\n is expected.\n\n Raises:\n ValueError: If cube is not of the expected dimensions.\n \"\"\"\n require_dim_coords = False if cube.coords(\"wmo_id\") else True\n check_for_x_and_y_axes(cube, require_dim_coords=require_dim_coords)\n dim_coords = get_dim_coord_names(cube)\n msg = (\n \"{} expects a cube with only a leading threshold dimension, \"\n \"followed by spatial (y/x) dimensions. \"\n \"Got dimensions: {}\".format(self.__class__.__name__, dim_coords)\n )\n\n try:\n threshold_coord = find_threshold_coordinate(cube)\n except CoordinateNotFoundError:\n raise ValueError(msg)\n\n if len(dim_coords) < 4:\n enforce_coordinate_ordering(cube, threshold_coord.name())\n return\n\n raise ValueError(msg)\n\n @staticmethod\n def _check_unit_compatibility(\n location_parameter: Cube, scale_parameter: Cube, probability_cube_template: Cube\n ) -> None:\n \"\"\"\n The location parameter, scale parameters, and threshold values come\n from three different cubes. This is a sanity check to ensure the units\n are as expected, converting units of the location parameter and\n scale parameter if possible.\n\n Args:\n location_parameter:\n Cube of location parameter values.\n scale_parameter:\n Cube of scale parameter values.\n probability_cube_template:\n Cube containing threshold values.\n\n Raises:\n ValueError: If units of input cubes are not compatible.\n \"\"\"\n threshold_units = find_threshold_coordinate(probability_cube_template).units\n\n try:\n location_parameter.convert_units(threshold_units)\n scale_parameter.convert_units(threshold_units)\n except ValueError as err:\n msg = (\n \"Error: {} This is likely because the location parameter, \"\n \"scale parameter and template cube threshold units are \"\n \"not equivalent/compatible.\".format(err)\n )\n raise ValueError(msg)\n\n def _location_and_scale_parameters_to_probabilities(\n self,\n location_parameter: Cube,\n scale_parameter: Cube,\n probability_cube_template: Cube,\n ) -> Cube:\n \"\"\"\n Function returning probabilities relative to provided thresholds based\n on the supplied location and scale parameters.\n\n Args:\n location_parameter:\n Predictor for the calibrated forecast location parameter.\n scale_parameter:\n Scale parameter for the calibrated forecast.\n probability_cube_template:\n A probability cube that has a threshold coordinate, where the\n probabilities are defined as above or below the threshold by\n the spp__relative_to_threshold attribute. This cube matches\n the desired output cube format.\n\n Returns:\n Cube containing the data expressed as probabilities relative to\n the provided thresholds in the way described by\n spp__relative_to_threshold.\n \"\"\"\n # Define a mask to be reapplied later\n loc_mask = np.ma.getmaskarray(location_parameter.data)\n scale_mask = np.ma.getmaskarray(scale_parameter.data)\n mask = np.logical_or(loc_mask, scale_mask)\n # Remove any mask that may be applied to location and scale parameters\n # and replace with ones\n location_parameter.data = np.ma.filled(location_parameter.data, 1)\n scale_parameter.data = np.ma.filled(scale_parameter.data, 1)\n thresholds = find_threshold_coordinate(probability_cube_template).points\n relative_to_threshold = probability_is_above_or_below(probability_cube_template)\n\n self._rescale_shape_parameters(\n location_parameter.data.flatten(), scale_parameter.data.flatten()\n )\n\n # Loop over thresholds, and use the specified distribution with the\n # location and scale parameter to calculate the probabilities relative\n # to each threshold.\n probabilities = np.empty_like(probability_cube_template.data)\n\n distribution = self.distribution(\n *self.shape_parameters,\n loc=location_parameter.data.flatten(),\n scale=scale_parameter.data.flatten(),\n )\n\n probability_method = distribution.cdf\n if relative_to_threshold == \"above\":\n probability_method = distribution.sf\n\n for index, threshold in enumerate(thresholds):\n probabilities[index, ...] = np.reshape(\n probability_method(threshold), probabilities.shape[1:]\n )\n\n probability_cube = probability_cube_template.copy(data=probabilities)\n # Make the mask defined above fit the data size and then apply to the\n # probability cube.\n mask_array = np.array([mask] * len(probabilities))\n probability_cube.data = np.ma.masked_where(mask_array, probability_cube.data)\n return probability_cube\n\n def process(\n self,\n location_parameter: Cube,\n scale_parameter: Cube,\n probability_cube_template: Cube,\n ) -> Cube:\n \"\"\"\n Generate probabilities from the location and scale parameters of the\n distribution.\n\n Args:\n location_parameter:\n Cube containing the location parameters.\n scale_parameter:\n Cube containing the scale parameters.\n probability_cube_template:\n A probability cube that has a threshold coordinate, where the\n probabilities are defined as above or below the threshold by\n the spp__relative_to_threshold attribute. This cube matches\n the desired output cube format.\n\n Returns:\n A cube of diagnostic data expressed as probabilities relative\n to the thresholds found in the probability_cube_template.\n \"\"\"\n self._check_template_cube(probability_cube_template)\n self._check_unit_compatibility(\n location_parameter, scale_parameter, probability_cube_template\n )\n\n probability_cube = self._location_and_scale_parameters_to_probabilities(\n location_parameter, scale_parameter, probability_cube_template\n )\n\n return probability_cube\n\n\nclass EnsembleReordering(BasePlugin):\n \"\"\"\n Plugin for applying the reordering step of Ensemble Copula Coupling,\n in order to generate ensemble realizations with multivariate structure\n from percentiles. The percentiles are assumed to be in ascending order.\n\n Reference:\n Schefzik, R., Thorarinsdottir, T.L. & Gneiting, T., 2013.\n Uncertainty Quantification in Complex Simulation Models Using Ensemble\n Copula Coupling.\n Statistical Science, 28(4), pp.616-640.\n\n \"\"\"\n\n @staticmethod\n def _recycle_raw_ensemble_realizations(\n post_processed_forecast_percentiles: Cube,\n raw_forecast_realizations: Cube,\n percentile_coord_name: str,\n ) -> Cube:\n \"\"\"\n Function to determine whether there is a mismatch between the number\n of percentiles and the number of raw forecast realizations. If more\n percentiles are requested than ensemble realizations, then the ensemble\n realizations are recycled. This assumes that the identity of the\n ensemble realizations within the raw ensemble forecast is random, such\n that the raw ensemble realizations are exchangeable. If fewer\n percentiles are requested than ensemble realizations, then only the\n first n ensemble realizations are used.\n\n Args:\n post_processed_forecast_percentiles :\n Cube for post-processed percentiles.\n The percentiles are assumed\n to be in ascending order.\n raw_forecast_realizations:\n Cube containing the raw (not post-processed) forecasts.\n percentile_coord_name:\n Name of required percentile coordinate.\n\n Returns:\n Cube for the raw ensemble forecast, where the raw ensemble\n realizations have either been recycled or constrained,\n depending upon the number of percentiles present\n in the post-processed forecast cube.\n \"\"\"\n plen = len(\n post_processed_forecast_percentiles.coord(percentile_coord_name).points\n )\n mlen = len(raw_forecast_realizations.coord(\"realization\").points)\n if plen == mlen:\n pass\n else:\n raw_forecast_realizations_extended = iris.cube.CubeList()\n realization_list = []\n mpoints = raw_forecast_realizations.coord(\"realization\").points\n # Loop over the number of percentiles and finding the\n # corresponding ensemble realization number. The ensemble\n # realization numbers are recycled e.g. 1, 2, 3, 1, 2, 3, etc.\n for index in range(plen):\n realization_list.append(mpoints[index % len(mpoints)])\n\n # Assume that the ensemble realizations are ascending linearly.\n new_realization_numbers = realization_list[0] + list(range(plen))\n\n # Extract the realizations required in the realization_list from\n # the raw_forecast_realizations. Edit the realization number as\n # appropriate and append to a cubelist containing rebadged\n # raw ensemble realizations.\n for realization, index in zip(realization_list, new_realization_numbers):\n constr = iris.Constraint(realization=realization)\n raw_forecast_realization = raw_forecast_realizations.extract(constr)\n raw_forecast_realization.coord(\"realization\").points = index\n raw_forecast_realizations_extended.append(raw_forecast_realization)\n raw_forecast_realizations = MergeCubes()(\n raw_forecast_realizations_extended, slice_over_realization=True\n )\n return raw_forecast_realizations\n\n @staticmethod\n def rank_ecc(\n post_processed_forecast_percentiles: Cube,\n raw_forecast_realizations: Cube,\n random_ordering: bool = False,\n random_seed: Optional[int] = None,\n ) -> Cube:\n \"\"\"\n Function to apply Ensemble Copula Coupling. This ranks the\n post-processed forecast realizations based on a ranking determined from\n the raw forecast realizations.\n\n Args:\n post_processed_forecast_percentiles:\n Cube for post-processed percentiles. The percentiles are\n assumed to be in ascending order.\n raw_forecast_realizations:\n Cube containing the raw (not post-processed) forecasts.\n The probabilistic dimension is assumed to be the zeroth\n dimension.\n random_ordering:\n If random_ordering is True, the post-processed forecasts are\n reordered randomly, rather than using the ordering of the\n raw ensemble.\n random_seed:\n If random_seed is an integer, the integer value is used for\n the random seed.\n If random_seed is None, no random seed is set, so the random\n values generated are not reproducible.\n\n Returns:\n Cube for post-processed realizations where at a particular grid\n point, the ranking of the values within the ensemble matches\n the ranking from the raw ensemble.\n \"\"\"\n results = iris.cube.CubeList([])\n for rawfc, calfc in zip(\n raw_forecast_realizations.slices_over(\"time\"),\n post_processed_forecast_percentiles.slices_over(\"time\"),\n ):\n if random_seed is not None:\n random_seed = int(random_seed)\n random_seed = np.random.RandomState(random_seed)\n random_data = random_seed.rand(*rawfc.data.shape)\n if random_ordering:\n # Returns the indices that would sort the array.\n # As these indices are from a random dataset, only an argsort\n # is used.\n ranking = np.argsort(random_data, axis=0)\n else:\n # Lexsort returns the indices sorted firstly by the\n # primary key, the raw forecast data (unless random_ordering\n # is enabled), and secondly by the secondary key, an array of\n # random data, in order to split tied values randomly.\n sorting_index = np.lexsort((random_data, rawfc.data), axis=0)\n # Returns the indices that would sort the array.\n ranking = np.argsort(sorting_index, axis=0)\n # Index the post-processed forecast data using the ranking array.\n # The following uses a custom choose function that reproduces the\n # required elements of the np.choose method without the limitation\n # of having < 32 arrays or a leading dimension < 32 in the\n # input data array. This function allows indexing of a 3d array\n # using a 3d array.\n mask = np.ma.getmask(calfc.data)\n calfc.data = choose(ranking, calfc.data)\n if mask is not np.ma.nomask:\n calfc.data = np.ma.MaskedArray(calfc.data, mask, dtype=np.float32)\n results.append(calfc)\n # Ensure we haven't lost any dimensional coordinates with only one\n # value in.\n results = results.merge_cube()\n results = check_cube_coordinates(post_processed_forecast_percentiles, results)\n return results\n\n @staticmethod\n def _check_input_cube_masks(post_processed_forecast, raw_forecast):\n \"\"\"\n Checks that if the raw_forecast is masked the post_processed_forecast\n is also masked. The code supports the post_processed_forecast being\n masked even if the raw_forecast isn't masked, but not vice versa.\n\n If both post_processed_forecast and raw_forecast are masked checks\n that both input cubes have the same mask applied to each\n x-y slice.\n\n Args:\n post_processed_forecast:\n The cube containing the post-processed\n forecast realizations.\n raw_forecast:\n The cube containing the raw (not post-processed)\n forecast.\n\n Raises:\n ValueError:\n If only the raw_forecast is masked\n ValueError:\n If the post_processed_forecast does not have same mask on all\n x-y slices\n ValueError:\n If the raw_forecast x-y slices do not all have the same mask\n as the post_processed_forecast.\n \"\"\"\n if np.ma.is_masked(post_processed_forecast.data) and np.ma.is_masked(\n raw_forecast.data\n ):\n for aslice in post_processed_forecast.data.mask[1:, ...]:\n if np.any(aslice != post_processed_forecast.data.mask[0]):\n\n message = (\n \"The post_processed_forecast does not have same\"\n \" mask on all x-y slices\"\n )\n raise (ValueError(message))\n for aslice in raw_forecast.data.mask[0:, ...]:\n if np.any(aslice != post_processed_forecast.data.mask[0]):\n message = (\n \"The raw_forecast x-y slices do not all have the\"\n \" same mask as the post_processed_forecast.\"\n )\n raise (ValueError(message))\n if np.ma.is_masked(raw_forecast.data) and not np.ma.is_masked(\n post_processed_forecast.data\n ):\n message = (\n \"The raw_forecast provided has a mask, but the \"\n \"post_processed_forecast isn't masked. The \"\n \"post_processed_forecast and the raw_forecast should \"\n \"have the same mask applied to them.\"\n )\n raise (ValueError(message))\n\n def process(\n self,\n post_processed_forecast: Cube,\n raw_forecast: Cube,\n random_ordering: bool = False,\n random_seed: Optional[int] = None,\n ) -> Cube:\n \"\"\"\n Reorder post-processed forecast using the ordering of the\n raw ensemble.\n\n Args:\n post_processed_forecast:\n The cube containing the post-processed\n forecast realizations.\n raw_forecast:\n The cube containing the raw (not post-processed)\n forecast.\n random_ordering:\n If random_ordering is True, the post-processed forecasts are\n reordered randomly, rather than using the ordering of the\n raw ensemble.\n random_seed:\n If random_seed is an integer, the integer value is used for\n the random seed.\n If random_seed is None, no random seed is set, so the random\n values generated are not reproducible.\n\n Returns:\n Cube containing the new ensemble realizations where all points\n within the dataset have been reordered in comparison to the\n input percentiles. This cube contains the same ensemble\n realization numbers as the raw forecast.\n \"\"\"\n percentile_coord_name = find_percentile_coordinate(\n post_processed_forecast\n ).name()\n\n enforce_coordinate_ordering(post_processed_forecast, percentile_coord_name)\n enforce_coordinate_ordering(raw_forecast, \"realization\")\n\n self._check_input_cube_masks(post_processed_forecast, raw_forecast)\n\n raw_forecast = self._recycle_raw_ensemble_realizations(\n post_processed_forecast, raw_forecast, percentile_coord_name\n )\n post_processed_forecast_realizations = self.rank_ecc(\n post_processed_forecast,\n raw_forecast,\n random_ordering=random_ordering,\n random_seed=random_seed,\n )\n plugin = RebadgePercentilesAsRealizations()\n post_processed_forecast_realizations = plugin(\n post_processed_forecast_realizations,\n ensemble_realization_numbers=raw_forecast.coord(\"realization\").points,\n )\n\n enforce_coordinate_ordering(post_processed_forecast_realizations, \"realization\")\n return post_processed_forecast_realizations\n"
] | [
[
"numpy.logical_or",
"numpy.ma.is_masked",
"numpy.transpose",
"numpy.ma.masked_where",
"numpy.diff",
"numpy.ma.getmask",
"numpy.any",
"numpy.argsort",
"numpy.ma.filled",
"numpy.empty_like",
"numpy.random.RandomState",
"numpy.lexsort",
"numpy.ma.MaskedArray",
"numpy.broadcast_to",
"numpy.array",
"numpy.around",
"numpy.ma.getmaskarray",
"numpy.isnan"
]
] |
dossett/incubator-airflow | [
"60583a3c6d1c4b5bbecaad6cd195301107530de9"
] | [
"airflow/www/views.py"
] | [
"# -*- coding: utf-8 -*-\n#\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.\n#\n\nimport ast\nimport codecs\nimport copy\nimport datetime as dt\nimport itertools\nimport json\nimport logging\nimport math\nimport os\nimport traceback\nfrom collections import defaultdict\nfrom datetime import timedelta\nfrom functools import wraps\nfrom textwrap import dedent\n\nimport bleach\nimport markdown\nimport nvd3\nimport pendulum\nimport pkg_resources\nimport sqlalchemy as sqla\nfrom flask import (\n abort, jsonify, redirect, url_for, request, Markup, Response,\n current_app, render_template, make_response)\nfrom flask import flash\nfrom flask._compat import PY2\nfrom flask_admin import BaseView, expose, AdminIndexView\nfrom flask_admin.actions import action\nfrom flask_admin.babel import lazy_gettext\nfrom flask_admin.contrib.sqla import ModelView\nfrom flask_admin.form.fields import DateTimeField\nfrom flask_admin.tools import iterdecode\nfrom jinja2 import escape\nfrom jinja2.sandbox import ImmutableSandboxedEnvironment\nfrom past.builtins import basestring, unicode\nfrom pygments import highlight, lexers\nfrom pygments.formatters import HtmlFormatter\nfrom sqlalchemy import or_, desc, and_, union_all\nfrom wtforms import (\n Form, SelectField, TextAreaField, PasswordField,\n StringField, validators)\n\nimport airflow\nfrom airflow import configuration as conf\nfrom airflow import models\nfrom airflow import settings\nfrom airflow.api.common.experimental.mark_tasks import (set_dag_run_state_to_running,\n set_dag_run_state_to_success,\n set_dag_run_state_to_failed)\nfrom airflow.exceptions import AirflowException\nfrom airflow.models import BaseOperator\nfrom airflow.models import XCom, DagRun\nfrom airflow.operators.subdag_operator import SubDagOperator\nfrom airflow.ti_deps.dep_context import DepContext, QUEUE_DEPS, SCHEDULER_DEPS\nfrom airflow.utils import timezone\nfrom airflow.utils.dates import infer_time_unit, scale_time_units, parse_execution_date\nfrom airflow.utils.db import create_session, provide_session\nfrom airflow.utils.helpers import alchemy_to_dict\nfrom airflow.utils.json import json_ser\nfrom airflow.utils.net import get_hostname\nfrom airflow.utils.state import State\nfrom airflow.utils.timezone import datetime\nfrom airflow.www import utils as wwwutils\nfrom airflow.www.forms import (DateTimeForm, DateTimeWithNumRunsForm,\n DateTimeWithNumRunsWithDagRunsForm)\nfrom airflow.www.validators import GreaterEqualThan\n\nQUERY_LIMIT = 100000\nCHART_LIMIT = 200000\n\nUTF8_READER = codecs.getreader('utf-8')\n\ndagbag = models.DagBag(settings.DAGS_FOLDER)\n\nlogin_required = airflow.login.login_required\ncurrent_user = airflow.login.current_user\nlogout_user = airflow.login.logout_user\n\nFILTER_BY_OWNER = False\n\nPAGE_SIZE = conf.getint('webserver', 'page_size')\n\nif conf.getboolean('webserver', 'FILTER_BY_OWNER'):\n # filter_by_owner if authentication is enabled and filter_by_owner is true\n FILTER_BY_OWNER = not current_app.config['LOGIN_DISABLED']\n\n\ndef dag_link(v, c, m, p):\n if m.dag_id is None:\n return Markup()\n\n dag_id = bleach.clean(m.dag_id)\n url = url_for(\n 'airflow.graph',\n dag_id=dag_id,\n execution_date=m.execution_date)\n return Markup(\n '<a href=\"{}\">{}</a>'.format(url, dag_id))\n\n\ndef log_url_formatter(v, c, m, p):\n return Markup(\n '<a href=\"{m.log_url}\">'\n ' <span class=\"glyphicon glyphicon-book\" aria-hidden=\"true\">'\n '</span></a>').format(**locals())\n\n\ndef dag_run_link(v, c, m, p):\n dag_id = bleach.clean(m.dag_id)\n url = url_for(\n 'airflow.graph',\n dag_id=m.dag_id,\n run_id=m.run_id,\n execution_date=m.execution_date)\n return Markup('<a href=\"{url}\">{m.run_id}</a>'.format(**locals()))\n\n\ndef task_instance_link(v, c, m, p):\n dag_id = bleach.clean(m.dag_id)\n task_id = bleach.clean(m.task_id)\n url = url_for(\n 'airflow.task',\n dag_id=dag_id,\n task_id=task_id,\n execution_date=m.execution_date.isoformat())\n url_root = url_for(\n 'airflow.graph',\n dag_id=dag_id,\n root=task_id,\n execution_date=m.execution_date.isoformat())\n return Markup(\n \"\"\"\n <span style=\"white-space: nowrap;\">\n <a href=\"{url}\">{task_id}</a>\n <a href=\"{url_root}\" title=\"Filter on this task and upstream\">\n <span class=\"glyphicon glyphicon-filter\" style=\"margin-left: 0px;\"\n aria-hidden=\"true\"></span>\n </a>\n </span>\n \"\"\".format(**locals()))\n\n\ndef state_token(state):\n color = State.color(state)\n return Markup(\n '<span class=\"label\" style=\"background-color:{color};\">'\n '{state}</span>'.format(**locals()))\n\n\ndef parse_datetime_f(value):\n if not isinstance(value, dt.datetime):\n return value\n\n return timezone.make_aware(value)\n\n\ndef state_f(v, c, m, p):\n return state_token(m.state)\n\n\ndef duration_f(v, c, m, p):\n if m.end_date and m.duration:\n return timedelta(seconds=m.duration)\n\n\ndef datetime_f(v, c, m, p):\n attr = getattr(m, p)\n dttm = attr.isoformat() if attr else ''\n if timezone.utcnow().isoformat()[:4] == dttm[:4]:\n dttm = dttm[5:]\n return Markup(\"<nobr>{}</nobr>\".format(dttm))\n\n\ndef nobr_f(v, c, m, p):\n return Markup(\"<nobr>{}</nobr>\".format(getattr(m, p)))\n\n\ndef label_link(v, c, m, p):\n try:\n default_params = ast.literal_eval(m.default_params)\n except Exception:\n default_params = {}\n url = url_for(\n 'airflow.chart', chart_id=m.id, iteration_no=m.iteration_no,\n **default_params)\n return Markup(\"<a href='{url}'>{m.label}</a>\".format(**locals()))\n\n\ndef pool_link(v, c, m, p):\n url = '/admin/taskinstance/?flt1_pool_equals=' + m.pool\n return Markup(\"<a href='{url}'>{m.pool}</a>\".format(**locals()))\n\n\ndef pygment_html_render(s, lexer=lexers.TextLexer):\n return highlight(\n s,\n lexer(),\n HtmlFormatter(linenos=True),\n )\n\n\ndef render(obj, lexer):\n out = \"\"\n if isinstance(obj, basestring):\n out += pygment_html_render(obj, lexer)\n elif isinstance(obj, (tuple, list)):\n for i, s in enumerate(obj):\n out += \"<div>List item #{}</div>\".format(i)\n out += \"<div>\" + pygment_html_render(s, lexer) + \"</div>\"\n elif isinstance(obj, dict):\n for k, v in obj.items():\n out += '<div>Dict item \"{}\"</div>'.format(k)\n out += \"<div>\" + pygment_html_render(v, lexer) + \"</div>\"\n return out\n\n\ndef wrapped_markdown(s):\n return '<div class=\"rich_doc\">' + markdown.markdown(s) + \"</div>\"\n\n\nattr_renderer = {\n 'bash_command': lambda x: render(x, lexers.BashLexer),\n 'hql': lambda x: render(x, lexers.SqlLexer),\n 'sql': lambda x: render(x, lexers.SqlLexer),\n 'doc': lambda x: render(x, lexers.TextLexer),\n 'doc_json': lambda x: render(x, lexers.JsonLexer),\n 'doc_rst': lambda x: render(x, lexers.RstLexer),\n 'doc_yaml': lambda x: render(x, lexers.YamlLexer),\n 'doc_md': wrapped_markdown,\n 'python_callable': lambda x: render(\n wwwutils.get_python_source(x),\n lexers.PythonLexer,\n ),\n}\n\n\ndef data_profiling_required(f):\n \"\"\"Decorator for views requiring data profiling access\"\"\"\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if (\n current_app.config['LOGIN_DISABLED'] or\n (not current_user.is_anonymous and current_user.data_profiling())\n ):\n return f(*args, **kwargs)\n else:\n flash(\"This page requires data profiling privileges\", \"error\")\n return redirect(url_for('admin.index'))\n\n return decorated_function\n\n\ndef fused_slots(v, c, m, p):\n url = (\n '/admin/taskinstance/' +\n '?flt1_pool_equals=' + m.pool +\n '&flt2_state_equals=running')\n return Markup(\"<a href='{0}'>{1}</a>\".format(url, m.used_slots()))\n\n\ndef fqueued_slots(v, c, m, p):\n url = (\n '/admin/taskinstance/' +\n '?flt1_pool_equals=' + m.pool +\n '&flt2_state_equals=queued&sort=10&desc=1')\n return Markup(\"<a href='{0}'>{1}</a>\".format(url, m.queued_slots()))\n\n\ndef recurse_tasks(tasks, task_ids, dag_ids, task_id_to_dag):\n if isinstance(tasks, list):\n for task in tasks:\n recurse_tasks(task, task_ids, dag_ids, task_id_to_dag)\n return\n if isinstance(tasks, SubDagOperator):\n subtasks = tasks.subdag.tasks\n dag_ids.append(tasks.subdag.dag_id)\n for subtask in subtasks:\n if subtask.task_id not in task_ids:\n task_ids.append(subtask.task_id)\n task_id_to_dag[subtask.task_id] = tasks.subdag\n recurse_tasks(subtasks, task_ids, dag_ids, task_id_to_dag)\n if isinstance(tasks, BaseOperator):\n task_id_to_dag[tasks.task_id] = tasks.dag\n\n\ndef get_chart_height(dag):\n \"\"\"\n TODO(aoen): See [AIRFLOW-1263] We use the number of tasks in the DAG as a heuristic to\n approximate the size of generated chart (otherwise the charts are tiny and unreadable\n when DAGs have a large number of tasks). Ideally nvd3 should allow for dynamic-height\n charts, that is charts that take up space based on the size of the components within.\n \"\"\"\n return 600 + len(dag.tasks) * 10\n\n\ndef get_date_time_num_runs_dag_runs_form_data(request, session, dag):\n dttm = request.args.get('execution_date')\n if dttm:\n dttm = pendulum.parse(dttm)\n else:\n dttm = dag.latest_execution_date or timezone.utcnow()\n\n base_date = request.args.get('base_date')\n if base_date:\n base_date = timezone.parse(base_date)\n else:\n # The DateTimeField widget truncates milliseconds and would loose\n # the first dag run. Round to next second.\n base_date = (dttm + timedelta(seconds=1)).replace(microsecond=0)\n\n default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')\n num_runs = request.args.get('num_runs')\n num_runs = int(num_runs) if num_runs else default_dag_run\n\n DR = models.DagRun\n drs = (\n session.query(DR)\n .filter(\n DR.dag_id == dag.dag_id,\n DR.execution_date <= base_date)\n .order_by(desc(DR.execution_date))\n .limit(num_runs)\n .all()\n )\n dr_choices = []\n dr_state = None\n for dr in drs:\n dr_choices.append((dr.execution_date.isoformat(), dr.run_id))\n if dttm == dr.execution_date:\n dr_state = dr.state\n\n # Happens if base_date was changed and the selected dag run is not in result\n if not dr_state and drs:\n dr = drs[0]\n dttm = dr.execution_date\n dr_state = dr.state\n\n return {\n 'dttm': dttm,\n 'base_date': base_date,\n 'num_runs': num_runs,\n 'execution_date': dttm.isoformat(),\n 'dr_choices': dr_choices,\n 'dr_state': dr_state,\n }\n\n\nclass Airflow(BaseView):\n def is_visible(self):\n return False\n\n @expose('/')\n @login_required\n def index(self):\n return self.render('airflow/dags.html')\n\n @expose('/chart_data')\n @data_profiling_required\n @wwwutils.gzipped\n # @cache.cached(timeout=3600, key_prefix=wwwutils.make_cache_key)\n def chart_data(self):\n from airflow import macros\n import pandas as pd\n if conf.getboolean('core', 'secure_mode'):\n abort(404)\n\n with create_session() as session:\n chart_id = request.args.get('chart_id')\n csv = request.args.get('csv') == \"true\"\n chart = session.query(models.Chart).filter_by(id=chart_id).first()\n db = session.query(\n models.Connection).filter_by(conn_id=chart.conn_id).first()\n\n payload = {\n \"state\": \"ERROR\",\n \"error\": \"\"\n }\n\n # Processing templated fields\n try:\n args = ast.literal_eval(chart.default_params)\n if not isinstance(args, dict):\n raise AirflowException('Not a dict')\n except Exception:\n args = {}\n payload['error'] += (\n \"Default params is not valid, string has to evaluate as \"\n \"a Python dictionary. \")\n\n request_dict = {k: request.args.get(k) for k in request.args}\n args.update(request_dict)\n args['macros'] = macros\n sandbox = ImmutableSandboxedEnvironment()\n sql = sandbox.from_string(chart.sql).render(**args)\n label = sandbox.from_string(chart.label).render(**args)\n payload['sql_html'] = Markup(highlight(\n sql,\n lexers.SqlLexer(), # Lexer call\n HtmlFormatter(noclasses=True))\n )\n payload['label'] = label\n\n pd.set_option('display.max_colwidth', 100)\n hook = db.get_hook()\n try:\n df = hook.get_pandas_df(\n wwwutils.limit_sql(sql, CHART_LIMIT, conn_type=db.conn_type))\n df = df.fillna(0)\n except Exception as e:\n payload['error'] += \"SQL execution failed. Details: \" + str(e)\n\n if csv:\n return Response(\n response=df.to_csv(index=False),\n status=200,\n mimetype=\"application/text\")\n\n if not payload['error'] and len(df) == CHART_LIMIT:\n payload['warning'] = (\n \"Data has been truncated to {0}\"\n \" rows. Expect incomplete results.\").format(CHART_LIMIT)\n\n if not payload['error'] and len(df) == 0:\n payload['error'] += \"Empty result set. \"\n elif (\n not payload['error'] and\n chart.sql_layout == 'series' and\n chart.chart_type != \"datatable\" and\n len(df.columns) < 3):\n payload['error'] += \"SQL needs to return at least 3 columns. \"\n elif (\n not payload['error'] and\n chart.sql_layout == 'columns' and\n len(df.columns) < 2):\n payload['error'] += \"SQL needs to return at least 2 columns. \"\n elif not payload['error']:\n import numpy as np\n chart_type = chart.chart_type\n\n data = None\n if chart.show_datatable or chart_type == \"datatable\":\n data = df.to_dict(orient=\"split\")\n data['columns'] = [{'title': c} for c in data['columns']]\n payload['data'] = data\n\n # Trying to convert time to something Highcharts likes\n x_col = 1 if chart.sql_layout == 'series' else 0\n if chart.x_is_date:\n try:\n # From string to datetime\n df[df.columns[x_col]] = pd.to_datetime(\n df[df.columns[x_col]])\n df[df.columns[x_col]] = df[df.columns[x_col]].apply(\n lambda x: int(x.strftime(\"%s\")) * 1000)\n except Exception as e:\n payload['error'] = \"Time conversion failed\"\n\n if chart_type == 'datatable':\n payload['state'] = 'SUCCESS'\n return wwwutils.json_response(payload)\n else:\n if chart.sql_layout == 'series':\n # User provides columns (series, x, y)\n df[df.columns[2]] = df[df.columns[2]].astype(np.float)\n df = df.pivot_table(\n index=df.columns[1],\n columns=df.columns[0],\n values=df.columns[2], aggfunc=np.sum)\n else:\n # User provides columns (x, y, metric1, metric2, ...)\n df.index = df[df.columns[0]]\n df = df.sort(df.columns[0])\n del df[df.columns[0]]\n for col in df.columns:\n df[col] = df[col].astype(np.float)\n\n df = df.fillna(0)\n NVd3ChartClass = chart_mapping.get(chart.chart_type)\n NVd3ChartClass = getattr(nvd3, NVd3ChartClass)\n nvd3_chart = NVd3ChartClass(x_is_date=chart.x_is_date)\n\n for col in df.columns:\n nvd3_chart.add_serie(name=col, y=df[col].tolist(), x=df[col].index.tolist())\n try:\n nvd3_chart.buildcontent()\n payload['chart_type'] = nvd3_chart.__class__.__name__\n payload['htmlcontent'] = nvd3_chart.htmlcontent\n except Exception as e:\n payload['error'] = str(e)\n\n payload['state'] = 'SUCCESS'\n payload['request_dict'] = request_dict\n return wwwutils.json_response(payload)\n\n @expose('/chart')\n @data_profiling_required\n def chart(self):\n if conf.getboolean('core', 'secure_mode'):\n abort(404)\n\n with create_session() as session:\n chart_id = request.args.get('chart_id')\n embed = request.args.get('embed')\n chart = session.query(models.Chart).filter_by(id=chart_id).first()\n\n NVd3ChartClass = chart_mapping.get(chart.chart_type)\n if not NVd3ChartClass:\n flash(\n \"Not supported anymore as the license was incompatible, \"\n \"sorry\",\n \"danger\")\n redirect('/admin/chart/')\n\n sql = \"\"\n if chart.show_sql:\n sql = Markup(highlight(\n chart.sql,\n lexers.SqlLexer(), # Lexer call\n HtmlFormatter(noclasses=True))\n )\n return self.render(\n 'airflow/nvd3.html',\n chart=chart,\n title=\"Airflow - Chart\",\n sql=sql,\n label=chart.label,\n embed=embed)\n\n @expose('/dag_stats')\n @login_required\n @provide_session\n def dag_stats(self, session=None):\n ds = models.DagStat\n\n ds.update(\n dag_ids=[dag.dag_id for dag in dagbag.dags.values() if not dag.is_subdag]\n )\n\n qry = (\n session.query(ds.dag_id, ds.state, ds.count)\n )\n\n data = {}\n for dag_id, state, count in qry:\n if dag_id not in data:\n data[dag_id] = {}\n data[dag_id][state] = count\n\n payload = {}\n for dag in dagbag.dags.values():\n payload[dag.safe_dag_id] = []\n for state in State.dag_states:\n try:\n count = data[dag.dag_id][state]\n except Exception:\n count = 0\n d = {\n 'state': state,\n 'count': count,\n 'dag_id': dag.dag_id,\n 'color': State.color(state)\n }\n payload[dag.safe_dag_id].append(d)\n return wwwutils.json_response(payload)\n\n @expose('/task_stats')\n @login_required\n @provide_session\n def task_stats(self, session=None):\n TI = models.TaskInstance\n DagRun = models.DagRun\n Dag = models.DagModel\n\n LastDagRun = (\n session.query(DagRun.dag_id, sqla.func.max(DagRun.execution_date).label('execution_date'))\n .join(Dag, Dag.dag_id == DagRun.dag_id)\n .filter(DagRun.state != State.RUNNING)\n .filter(Dag.is_active == True) # noqa: E712\n .filter(Dag.is_subdag == False) # noqa: E712\n .group_by(DagRun.dag_id)\n .subquery('last_dag_run')\n )\n RunningDagRun = (\n session.query(DagRun.dag_id, DagRun.execution_date)\n .join(Dag, Dag.dag_id == DagRun.dag_id)\n .filter(DagRun.state == State.RUNNING)\n .filter(Dag.is_active == True) # noqa: E712\n .filter(Dag.is_subdag == False) # noqa: E712\n .subquery('running_dag_run')\n )\n\n # Select all task_instances from active dag_runs.\n # If no dag_run is active, return task instances from most recent dag_run.\n LastTI = (\n session.query(TI.dag_id.label('dag_id'), TI.state.label('state'))\n .join(LastDagRun, and_(\n LastDagRun.c.dag_id == TI.dag_id,\n LastDagRun.c.execution_date == TI.execution_date))\n )\n RunningTI = (\n session.query(TI.dag_id.label('dag_id'), TI.state.label('state'))\n .join(RunningDagRun, and_(\n RunningDagRun.c.dag_id == TI.dag_id,\n RunningDagRun.c.execution_date == TI.execution_date))\n )\n\n UnionTI = union_all(LastTI, RunningTI).alias('union_ti')\n qry = (\n session.query(UnionTI.c.dag_id, UnionTI.c.state, sqla.func.count())\n .group_by(UnionTI.c.dag_id, UnionTI.c.state)\n )\n\n data = {}\n for dag_id, state, count in qry:\n if dag_id not in data:\n data[dag_id] = {}\n data[dag_id][state] = count\n session.commit()\n\n payload = {}\n for dag in dagbag.dags.values():\n payload[dag.safe_dag_id] = []\n for state in State.task_states:\n try:\n count = data[dag.dag_id][state]\n except Exception:\n count = 0\n d = {\n 'state': state,\n 'count': count,\n 'dag_id': dag.dag_id,\n 'color': State.color(state)\n }\n payload[dag.safe_dag_id].append(d)\n return wwwutils.json_response(payload)\n\n @expose('/code')\n @login_required\n def code(self):\n dag_id = request.args.get('dag_id')\n dag = dagbag.get_dag(dag_id)\n title = dag_id\n try:\n with wwwutils.open_maybe_zipped(dag.fileloc, 'r') as f:\n code = f.read()\n html_code = highlight(\n code, lexers.PythonLexer(), HtmlFormatter(linenos=True))\n except IOError as e:\n html_code = str(e)\n\n return self.render(\n 'airflow/dag_code.html', html_code=html_code, dag=dag, title=title,\n root=request.args.get('root'),\n demo_mode=conf.getboolean('webserver', 'demo_mode'))\n\n @expose('/dag_details')\n @login_required\n @provide_session\n def dag_details(self, session=None):\n dag_id = request.args.get('dag_id')\n dag = dagbag.get_dag(dag_id)\n title = \"DAG details\"\n\n TI = models.TaskInstance\n states = session\\\n .query(TI.state, sqla.func.count(TI.dag_id))\\\n .filter(TI.dag_id == dag_id)\\\n .group_by(TI.state)\\\n .all()\n\n return self.render(\n 'airflow/dag_details.html',\n dag=dag, title=title, states=states, State=State)\n\n @current_app.errorhandler(404)\n def circles(self):\n return render_template(\n 'airflow/circles.html', hostname=get_hostname()), 404\n\n @current_app.errorhandler(500)\n def show_traceback(self):\n from airflow.utils import asciiart as ascii_\n return render_template(\n 'airflow/traceback.html',\n hostname=get_hostname(),\n nukular=ascii_.nukular,\n info=traceback.format_exc()), 500\n\n @expose('/noaccess')\n def noaccess(self):\n return self.render('airflow/noaccess.html')\n\n @expose('/pickle_info')\n @login_required\n def pickle_info(self):\n d = {}\n dag_id = request.args.get('dag_id')\n dags = [dagbag.dags.get(dag_id)] if dag_id else dagbag.dags.values()\n for dag in dags:\n if not dag.is_subdag:\n d[dag.dag_id] = dag.pickle_info()\n return wwwutils.json_response(d)\n\n @expose('/login', methods=['GET', 'POST'])\n def login(self):\n return airflow.login.login(self, request)\n\n @expose('/logout')\n def logout(self):\n logout_user()\n flash('You have been logged out.')\n return redirect(url_for('admin.index'))\n\n @expose('/rendered')\n @login_required\n @wwwutils.action_logging\n def rendered(self):\n dag_id = request.args.get('dag_id')\n task_id = request.args.get('task_id')\n execution_date = request.args.get('execution_date')\n dttm = pendulum.parse(execution_date)\n form = DateTimeForm(data={'execution_date': dttm})\n dag = dagbag.get_dag(dag_id)\n task = copy.copy(dag.get_task(task_id))\n ti = models.TaskInstance(task=task, execution_date=dttm)\n try:\n ti.render_templates()\n except Exception as e:\n flash(\"Error rendering template: \" + str(e), \"error\")\n title = \"Rendered Template\"\n html_dict = {}\n for template_field in task.__class__.template_fields:\n content = getattr(task, template_field)\n if template_field in attr_renderer:\n html_dict[template_field] = attr_renderer[template_field](content)\n else:\n html_dict[template_field] = (\n \"<pre><code>\" + str(content) + \"</pre></code>\")\n\n return self.render(\n 'airflow/ti_code.html',\n html_dict=html_dict,\n dag=dag,\n task_id=task_id,\n execution_date=execution_date,\n form=form,\n title=title, )\n\n @expose('/get_logs_with_metadata')\n @login_required\n @wwwutils.action_logging\n @provide_session\n def get_logs_with_metadata(self, session=None):\n dag_id = request.args.get('dag_id')\n task_id = request.args.get('task_id')\n execution_date = request.args.get('execution_date')\n dttm = pendulum.parse(execution_date)\n try_number = int(request.args.get('try_number'))\n metadata = request.args.get('metadata')\n metadata = json.loads(metadata)\n\n # metadata may be null\n if not metadata:\n metadata = {}\n\n # Convert string datetime into actual datetime\n try:\n execution_date = timezone.parse(execution_date)\n except ValueError:\n error_message = (\n 'Given execution date, {}, could not be identified '\n 'as a date. Example date format: 2015-11-16T14:34:15+00:00'.format(\n execution_date))\n response = jsonify({'error': error_message})\n response.status_code = 400\n\n return response\n\n logger = logging.getLogger('airflow.task')\n task_log_reader = conf.get('core', 'task_log_reader')\n handler = next((handler for handler in logger.handlers\n if handler.name == task_log_reader), None)\n\n ti = session.query(models.TaskInstance).filter(\n models.TaskInstance.dag_id == dag_id,\n models.TaskInstance.task_id == task_id,\n models.TaskInstance.execution_date == dttm).first()\n try:\n if ti is None:\n logs = [\"*** Task instance did not exist in the DB\\n\"]\n metadata['end_of_log'] = True\n else:\n dag = dagbag.get_dag(dag_id)\n ti.task = dag.get_task(ti.task_id)\n logs, metadatas = handler.read(ti, try_number, metadata=metadata)\n metadata = metadatas[0]\n for i, log in enumerate(logs):\n if PY2 and not isinstance(log, unicode):\n logs[i] = log.decode('utf-8')\n message = logs[0]\n return jsonify(message=message, metadata=metadata)\n except AttributeError as e:\n error_message = [\"Task log handler {} does not support read logs.\\n{}\\n\"\n .format(task_log_reader, str(e))]\n metadata['end_of_log'] = True\n return jsonify(message=error_message, error=True, metadata=metadata)\n\n @expose('/log')\n @login_required\n @wwwutils.action_logging\n @provide_session\n def log(self, session=None):\n dag_id = request.args.get('dag_id')\n task_id = request.args.get('task_id')\n execution_date = request.args.get('execution_date')\n dttm = pendulum.parse(execution_date)\n form = DateTimeForm(data={'execution_date': dttm})\n dag = dagbag.get_dag(dag_id)\n\n ti = session.query(models.TaskInstance).filter(\n models.TaskInstance.dag_id == dag_id,\n models.TaskInstance.task_id == task_id,\n models.TaskInstance.execution_date == dttm).first()\n\n logs = [''] * (ti.next_try_number - 1 if ti is not None else 0)\n return self.render(\n 'airflow/ti_log.html',\n logs=logs, dag=dag, title=\"Log by attempts\",\n dag_id=dag.dag_id, task_id=task_id,\n execution_date=execution_date, form=form)\n\n @expose('/task')\n @login_required\n @wwwutils.action_logging\n def task(self):\n TI = models.TaskInstance\n\n dag_id = request.args.get('dag_id')\n task_id = request.args.get('task_id')\n # Carrying execution_date through, even though it's irrelevant for\n # this context\n execution_date = request.args.get('execution_date')\n dttm = pendulum.parse(execution_date)\n form = DateTimeForm(data={'execution_date': dttm})\n dag = dagbag.get_dag(dag_id)\n\n if not dag or task_id not in dag.task_ids:\n flash(\n \"Task [{}.{}] doesn't seem to exist\"\n \" at the moment\".format(dag_id, task_id),\n \"error\")\n return redirect('/admin/')\n task = copy.copy(dag.get_task(task_id))\n task.resolve_template_files()\n ti = TI(task=task, execution_date=dttm)\n ti.refresh_from_db()\n\n ti_attrs = []\n for attr_name in dir(ti):\n if not attr_name.startswith('_'):\n attr = getattr(ti, attr_name)\n if type(attr) != type(self.task): # noqa: E721\n ti_attrs.append((attr_name, str(attr)))\n\n task_attrs = []\n for attr_name in dir(task):\n if not attr_name.startswith('_'):\n attr = getattr(task, attr_name)\n if type(attr) != type(self.task) and \\\n attr_name not in attr_renderer: # noqa: E721\n task_attrs.append((attr_name, str(attr)))\n\n # Color coding the special attributes that are code\n special_attrs_rendered = {}\n for attr_name in attr_renderer:\n if hasattr(task, attr_name):\n source = getattr(task, attr_name)\n special_attrs_rendered[attr_name] = attr_renderer[attr_name](source)\n\n no_failed_deps_result = [(\n \"Unknown\",\n dedent(\"\"\"\\\n All dependencies are met but the task instance is not running.\n In most cases this just means that the task will probably\n be scheduled soon unless:<br/>\n - The scheduler is down or under heavy load<br/>\n - The following configuration values may be limiting the number\n of queueable processes:\n <code>parallelism</code>,\n <code>dag_concurrency</code>,\n <code>max_active_dag_runs_per_dag</code>,\n <code>non_pooled_task_slot_count</code><br/>\n {}\n <br/>\n If this task instance does not start soon please contact your Airflow \"\"\"\n \"\"\"administrator for assistance.\"\"\"\n .format(\n \"- This task instance already ran and had its state changed \"\n \"manually (e.g. cleared in the UI)<br/>\"\n if ti.state == State.NONE else \"\")))]\n\n # Use the scheduler's context to figure out which dependencies are not met\n dep_context = DepContext(SCHEDULER_DEPS)\n failed_dep_reasons = [(dep.dep_name, dep.reason) for dep in\n ti.get_failed_dep_statuses(\n dep_context=dep_context)]\n\n title = \"Task Instance Details\"\n return self.render(\n 'airflow/task.html',\n task_attrs=task_attrs,\n ti_attrs=ti_attrs,\n failed_dep_reasons=failed_dep_reasons or no_failed_deps_result,\n task_id=task_id,\n execution_date=execution_date,\n special_attrs_rendered=special_attrs_rendered,\n form=form,\n dag=dag, title=title)\n\n @expose('/xcom')\n @login_required\n @wwwutils.action_logging\n @provide_session\n def xcom(self, session=None):\n dag_id = request.args.get('dag_id')\n task_id = request.args.get('task_id')\n # Carrying execution_date through, even though it's irrelevant for\n # this context\n execution_date = request.args.get('execution_date')\n dttm = pendulum.parse(execution_date)\n form = DateTimeForm(data={'execution_date': dttm})\n dag = dagbag.get_dag(dag_id)\n if not dag or task_id not in dag.task_ids:\n flash(\n \"Task [{}.{}] doesn't seem to exist\"\n \" at the moment\".format(dag_id, task_id),\n \"error\")\n return redirect('/admin/')\n\n xcomlist = session.query(XCom).filter(\n XCom.dag_id == dag_id, XCom.task_id == task_id,\n XCom.execution_date == dttm).all()\n\n attributes = []\n for xcom in xcomlist:\n if not xcom.key.startswith('_'):\n attributes.append((xcom.key, xcom.value))\n\n title = \"XCom\"\n return self.render(\n 'airflow/xcom.html',\n attributes=attributes,\n task_id=task_id,\n execution_date=execution_date,\n form=form,\n dag=dag, title=title)\n\n @expose('/run')\n @login_required\n @wwwutils.action_logging\n @wwwutils.notify_owner\n def run(self):\n dag_id = request.args.get('dag_id')\n task_id = request.args.get('task_id')\n origin = request.args.get('origin')\n dag = dagbag.get_dag(dag_id)\n task = dag.get_task(task_id)\n\n execution_date = request.args.get('execution_date')\n execution_date = pendulum.parse(execution_date)\n ignore_all_deps = request.args.get('ignore_all_deps') == \"true\"\n ignore_task_deps = request.args.get('ignore_task_deps') == \"true\"\n ignore_ti_state = request.args.get('ignore_ti_state') == \"true\"\n\n from airflow.executors import GetDefaultExecutor\n executor = GetDefaultExecutor()\n valid_celery_config = False\n valid_kubernetes_config = False\n\n try:\n from airflow.executors.celery_executor import CeleryExecutor\n valid_celery_config = isinstance(executor, CeleryExecutor)\n except ImportError:\n pass\n\n try:\n from airflow.contrib.executors.kubernetes_executor import KubernetesExecutor\n valid_kubernetes_config = isinstance(executor, KubernetesExecutor)\n except ImportError:\n pass\n\n if not valid_celery_config and not valid_kubernetes_config:\n flash(\"Only works with the Celery or Kubernetes executors, sorry\", \"error\")\n return redirect(origin)\n\n ti = models.TaskInstance(task=task, execution_date=execution_date)\n ti.refresh_from_db()\n\n # Make sure the task instance can be queued\n dep_context = DepContext(\n deps=QUEUE_DEPS,\n ignore_all_deps=ignore_all_deps,\n ignore_task_deps=ignore_task_deps,\n ignore_ti_state=ignore_ti_state)\n failed_deps = list(ti.get_failed_dep_statuses(dep_context=dep_context))\n if failed_deps:\n failed_deps_str = \", \".join(\n [\"{}: {}\".format(dep.dep_name, dep.reason) for dep in failed_deps])\n flash(\"Could not queue task instance for execution, dependencies not met: \"\n \"{}\".format(failed_deps_str),\n \"error\")\n return redirect(origin)\n\n executor.start()\n executor.queue_task_instance(\n ti,\n ignore_all_deps=ignore_all_deps,\n ignore_task_deps=ignore_task_deps,\n ignore_ti_state=ignore_ti_state)\n executor.heartbeat()\n flash(\n \"Sent {} to the message queue, \"\n \"it should start any moment now.\".format(ti))\n return redirect(origin)\n\n @expose('/delete')\n @login_required\n @wwwutils.action_logging\n @wwwutils.notify_owner\n def delete(self):\n from airflow.api.common.experimental import delete_dag\n from airflow.exceptions import DagNotFound, DagFileExists\n\n dag_id = request.args.get('dag_id')\n origin = request.args.get('origin') or \"/admin/\"\n\n try:\n delete_dag.delete_dag(dag_id)\n except DagNotFound:\n flash(\"DAG with id {} not found. Cannot delete\".format(dag_id))\n return redirect(request.referrer)\n except DagFileExists:\n flash(\"Dag id {} is still in DagBag. \"\n \"Remove the DAG file first.\".format(dag_id))\n return redirect(request.referrer)\n\n flash(\"Deleting DAG with id {}. May take a couple minutes to fully\"\n \" disappear.\".format(dag_id))\n # Upon successful delete return to origin\n return redirect(origin)\n\n @expose('/trigger')\n @login_required\n @wwwutils.action_logging\n @wwwutils.notify_owner\n def trigger(self):\n dag_id = request.args.get('dag_id')\n origin = request.args.get('origin') or \"/admin/\"\n dag = dagbag.get_dag(dag_id)\n\n if not dag:\n flash(\"Cannot find dag {}\".format(dag_id))\n return redirect(origin)\n\n execution_date = timezone.utcnow()\n run_id = \"manual__{0}\".format(execution_date.isoformat())\n\n dr = DagRun.find(dag_id=dag_id, run_id=run_id)\n if dr:\n flash(\"This run_id {} already exists\".format(run_id))\n return redirect(origin)\n\n run_conf = {}\n\n dag.create_dagrun(\n run_id=run_id,\n execution_date=execution_date,\n state=State.RUNNING,\n conf=run_conf,\n external_trigger=True\n )\n\n flash(\n \"Triggered {}, \"\n \"it should start any moment now.\".format(dag_id))\n return redirect(origin)\n\n def _clear_dag_tis(self, dag, start_date, end_date, origin,\n recursive=False, confirmed=False):\n if confirmed:\n count = dag.clear(\n start_date=start_date,\n end_date=end_date,\n include_subdags=recursive,\n include_parentdag=recursive,\n )\n\n flash(\"{0} task instances have been cleared\".format(count))\n return redirect(origin)\n\n tis = dag.clear(\n start_date=start_date,\n end_date=end_date,\n include_subdags=recursive,\n dry_run=True,\n include_parentdag=recursive,\n )\n if not tis:\n flash(\"No task instances to clear\", 'error')\n response = redirect(origin)\n else:\n details = \"\\n\".join([str(t) for t in tis])\n\n response = self.render(\n 'airflow/confirm.html',\n message=(\"Here's the list of task instances you are about \"\n \"to clear:\"),\n details=details)\n\n return response\n\n @expose('/clear')\n @login_required\n @wwwutils.action_logging\n @wwwutils.notify_owner\n def clear(self):\n dag_id = request.args.get('dag_id')\n task_id = request.args.get('task_id')\n origin = request.args.get('origin')\n dag = dagbag.get_dag(dag_id)\n\n execution_date = request.args.get('execution_date')\n execution_date = pendulum.parse(execution_date)\n confirmed = request.args.get('confirmed') == \"true\"\n upstream = request.args.get('upstream') == \"true\"\n downstream = request.args.get('downstream') == \"true\"\n future = request.args.get('future') == \"true\"\n past = request.args.get('past') == \"true\"\n recursive = request.args.get('recursive') == \"true\"\n\n dag = dag.sub_dag(\n task_regex=r\"^{0}$\".format(task_id),\n include_downstream=downstream,\n include_upstream=upstream)\n\n end_date = execution_date if not future else None\n start_date = execution_date if not past else None\n\n return self._clear_dag_tis(dag, start_date, end_date, origin,\n recursive=recursive, confirmed=confirmed)\n\n @expose('/dagrun_clear')\n @login_required\n @wwwutils.action_logging\n @wwwutils.notify_owner\n def dagrun_clear(self):\n dag_id = request.args.get('dag_id')\n origin = request.args.get('origin')\n execution_date = request.args.get('execution_date')\n confirmed = request.args.get('confirmed') == \"true\"\n\n dag = dagbag.get_dag(dag_id)\n execution_date = pendulum.parse(execution_date)\n start_date = execution_date\n end_date = execution_date\n\n return self._clear_dag_tis(dag, start_date, end_date, origin,\n recursive=True, confirmed=confirmed)\n\n @expose('/blocked')\n @login_required\n @provide_session\n def blocked(self, session=None):\n DR = models.DagRun\n dags = session\\\n .query(DR.dag_id, sqla.func.count(DR.id))\\\n .filter(DR.state == State.RUNNING)\\\n .group_by(DR.dag_id)\\\n .all()\n\n payload = []\n for dag_id, active_dag_runs in dags:\n max_active_runs = 0\n if dag_id in dagbag.dags:\n max_active_runs = dagbag.dags[dag_id].max_active_runs\n payload.append({\n 'dag_id': dag_id,\n 'active_dag_run': active_dag_runs,\n 'max_active_runs': max_active_runs,\n })\n return wwwutils.json_response(payload)\n\n def _mark_dagrun_state_as_failed(self, dag_id, execution_date, confirmed, origin):\n if not execution_date:\n flash('Invalid execution date', 'error')\n return redirect(origin)\n\n execution_date = pendulum.parse(execution_date)\n dag = dagbag.get_dag(dag_id)\n\n if not dag:\n flash('Cannot find DAG: {}'.format(dag_id), 'error')\n return redirect(origin)\n\n new_dag_state = set_dag_run_state_to_failed(dag, execution_date, commit=confirmed)\n\n if confirmed:\n flash('Marked failed on {} task instances'.format(len(new_dag_state)))\n return redirect(origin)\n\n else:\n details = '\\n'.join([str(t) for t in new_dag_state])\n\n response = self.render('airflow/confirm.html',\n message=(\"Here's the list of task instances you are \"\n \"about to mark as failed\"),\n details=details)\n\n return response\n\n def _mark_dagrun_state_as_success(self, dag_id, execution_date, confirmed, origin):\n if not execution_date:\n flash('Invalid execution date', 'error')\n return redirect(origin)\n\n execution_date = pendulum.parse(execution_date)\n dag = dagbag.get_dag(dag_id)\n\n if not dag:\n flash('Cannot find DAG: {}'.format(dag_id), 'error')\n return redirect(origin)\n\n new_dag_state = set_dag_run_state_to_success(dag, execution_date,\n commit=confirmed)\n\n if confirmed:\n flash('Marked success on {} task instances'.format(len(new_dag_state)))\n return redirect(origin)\n\n else:\n details = '\\n'.join([str(t) for t in new_dag_state])\n\n response = self.render('airflow/confirm.html',\n message=(\"Here's the list of task instances you are \"\n \"about to mark as success\"),\n details=details)\n\n return response\n\n @expose('/dagrun_failed')\n @login_required\n @wwwutils.action_logging\n @wwwutils.notify_owner\n def dagrun_failed(self):\n dag_id = request.args.get('dag_id')\n execution_date = request.args.get('execution_date')\n confirmed = request.args.get('confirmed') == 'true'\n origin = request.args.get('origin')\n return self._mark_dagrun_state_as_failed(dag_id, execution_date,\n confirmed, origin)\n\n @expose('/dagrun_success')\n @login_required\n @wwwutils.action_logging\n @wwwutils.notify_owner\n def dagrun_success(self):\n dag_id = request.args.get('dag_id')\n execution_date = request.args.get('execution_date')\n confirmed = request.args.get('confirmed') == 'true'\n origin = request.args.get('origin')\n return self._mark_dagrun_state_as_success(dag_id, execution_date,\n confirmed, origin)\n\n def _mark_task_instance_state(self, dag_id, task_id, origin, execution_date,\n confirmed, upstream, downstream,\n future, past, state):\n dag = dagbag.get_dag(dag_id)\n task = dag.get_task(task_id)\n task.dag = dag\n\n execution_date = pendulum.parse(execution_date)\n\n if not dag:\n flash(\"Cannot find DAG: {}\".format(dag_id))\n return redirect(origin)\n\n if not task:\n flash(\"Cannot find task {} in DAG {}\".format(task_id, dag.dag_id))\n return redirect(origin)\n\n from airflow.api.common.experimental.mark_tasks import set_state\n\n if confirmed:\n altered = set_state(task=task, execution_date=execution_date,\n upstream=upstream, downstream=downstream,\n future=future, past=past, state=state,\n commit=True)\n\n flash(\"Marked {} on {} task instances\".format(state, len(altered)))\n return redirect(origin)\n\n to_be_altered = set_state(task=task, execution_date=execution_date,\n upstream=upstream, downstream=downstream,\n future=future, past=past, state=state,\n commit=False)\n\n details = \"\\n\".join([str(t) for t in to_be_altered])\n\n response = self.render(\"airflow/confirm.html\",\n message=(\"Here's the list of task instances you are \"\n \"about to mark as {}:\".format(state)),\n details=details)\n\n return response\n\n @expose('/failed')\n @login_required\n @wwwutils.action_logging\n @wwwutils.notify_owner\n def failed(self):\n dag_id = request.args.get('dag_id')\n task_id = request.args.get('task_id')\n origin = request.args.get('origin')\n execution_date = request.args.get('execution_date')\n\n confirmed = request.args.get('confirmed') == \"true\"\n upstream = request.args.get('upstream') == \"true\"\n downstream = request.args.get('downstream') == \"true\"\n future = request.args.get('future') == \"true\"\n past = request.args.get('past') == \"true\"\n\n return self._mark_task_instance_state(dag_id, task_id, origin, execution_date,\n confirmed, upstream, downstream,\n future, past, State.FAILED)\n\n @expose('/success')\n @login_required\n @wwwutils.action_logging\n @wwwutils.notify_owner\n def success(self):\n dag_id = request.args.get('dag_id')\n task_id = request.args.get('task_id')\n origin = request.args.get('origin')\n execution_date = request.args.get('execution_date')\n\n confirmed = request.args.get('confirmed') == \"true\"\n upstream = request.args.get('upstream') == \"true\"\n downstream = request.args.get('downstream') == \"true\"\n future = request.args.get('future') == \"true\"\n past = request.args.get('past') == \"true\"\n\n return self._mark_task_instance_state(dag_id, task_id, origin, execution_date,\n confirmed, upstream, downstream,\n future, past, State.SUCCESS)\n\n @expose('/tree')\n @login_required\n @wwwutils.gzipped\n @wwwutils.action_logging\n @provide_session\n def tree(self, session=None):\n default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')\n dag_id = request.args.get('dag_id')\n blur = conf.getboolean('webserver', 'demo_mode')\n dag = dagbag.get_dag(dag_id)\n if dag_id not in dagbag.dags:\n flash('DAG \"{0}\" seems to be missing.'.format(dag_id), \"error\")\n return redirect('/admin/')\n\n root = request.args.get('root')\n if root:\n dag = dag.sub_dag(\n task_regex=root,\n include_downstream=False,\n include_upstream=True)\n\n base_date = request.args.get('base_date')\n num_runs = request.args.get('num_runs')\n num_runs = int(num_runs) if num_runs else default_dag_run\n\n if base_date:\n base_date = timezone.parse(base_date)\n else:\n base_date = dag.latest_execution_date or timezone.utcnow()\n\n DR = models.DagRun\n dag_runs = (\n session.query(DR)\n .filter(\n DR.dag_id == dag.dag_id,\n DR.execution_date <= base_date)\n .order_by(DR.execution_date.desc())\n .limit(num_runs)\n .all()\n )\n dag_runs = {\n dr.execution_date: alchemy_to_dict(dr) for dr in dag_runs}\n\n dates = sorted(list(dag_runs.keys()))\n max_date = max(dates) if dates else None\n min_date = min(dates) if dates else None\n\n tis = dag.get_task_instances(\n session, start_date=min_date, end_date=base_date)\n task_instances = {}\n for ti in tis:\n tid = alchemy_to_dict(ti)\n dr = dag_runs.get(ti.execution_date)\n tid['external_trigger'] = dr['external_trigger'] if dr else False\n task_instances[(ti.task_id, ti.execution_date)] = tid\n\n expanded = []\n # The default recursion traces every path so that tree view has full\n # expand/collapse functionality. After 5,000 nodes we stop and fall\n # back on a quick DFS search for performance. See PR #320.\n node_count = [0]\n node_limit = 5000 / max(1, len(dag.roots))\n\n def recurse_nodes(task, visited):\n visited.add(task)\n node_count[0] += 1\n\n children = [\n recurse_nodes(t, visited) for t in task.upstream_list\n if node_count[0] < node_limit or t not in visited]\n\n # D3 tree uses children vs _children to define what is\n # expanded or not. The following block makes it such that\n # repeated nodes are collapsed by default.\n children_key = 'children'\n if task.task_id not in expanded:\n expanded.append(task.task_id)\n elif children:\n children_key = \"_children\"\n\n def set_duration(tid):\n if isinstance(tid, dict) and tid.get(\"state\") == State.RUNNING \\\n and tid[\"start_date\"] is not None:\n d = timezone.utcnow() - pendulum.parse(tid[\"start_date\"])\n tid[\"duration\"] = d.total_seconds()\n return tid\n\n return {\n 'name': task.task_id,\n 'instances': [\n set_duration(task_instances.get((task.task_id, d))) or {\n 'execution_date': d.isoformat(),\n 'task_id': task.task_id\n }\n for d in dates],\n children_key: children,\n 'num_dep': len(task.upstream_list),\n 'operator': task.task_type,\n 'retries': task.retries,\n 'owner': task.owner,\n 'start_date': task.start_date,\n 'end_date': task.end_date,\n 'depends_on_past': task.depends_on_past,\n 'ui_color': task.ui_color,\n }\n\n data = {\n 'name': '[DAG]',\n 'children': [recurse_nodes(t, set()) for t in dag.roots],\n 'instances': [dag_runs.get(d) or {'execution_date': d.isoformat()} for d in dates],\n }\n\n # minimize whitespace as this can be huge for bigger dags\n data = json.dumps(data, default=json_ser, separators=(',', ':'))\n session.commit()\n\n form = DateTimeWithNumRunsForm(data={'base_date': max_date,\n 'num_runs': num_runs})\n return self.render(\n 'airflow/tree.html',\n operators=sorted(\n list(set([op.__class__ for op in dag.tasks])),\n key=lambda x: x.__name__\n ),\n root=root,\n form=form,\n dag=dag, data=data, blur=blur, num_runs=num_runs)\n\n @expose('/graph')\n @login_required\n @wwwutils.gzipped\n @wwwutils.action_logging\n @provide_session\n def graph(self, session=None):\n dag_id = request.args.get('dag_id')\n blur = conf.getboolean('webserver', 'demo_mode')\n dag = dagbag.get_dag(dag_id)\n if dag_id not in dagbag.dags:\n flash('DAG \"{0}\" seems to be missing.'.format(dag_id), \"error\")\n return redirect('/admin/')\n\n root = request.args.get('root')\n if root:\n dag = dag.sub_dag(\n task_regex=root,\n include_upstream=True,\n include_downstream=False)\n\n arrange = request.args.get('arrange', dag.orientation)\n\n nodes = []\n edges = []\n for task in dag.tasks:\n nodes.append({\n 'id': task.task_id,\n 'value': {\n 'label': task.task_id,\n 'labelStyle': \"fill:{0};\".format(task.ui_fgcolor),\n 'style': \"fill:{0};\".format(task.ui_color),\n }\n })\n\n def get_upstream(task):\n for t in task.upstream_list:\n edge = {\n 'u': t.task_id,\n 'v': task.task_id,\n }\n if edge not in edges:\n edges.append(edge)\n get_upstream(t)\n\n for t in dag.roots:\n get_upstream(t)\n\n dt_nr_dr_data = get_date_time_num_runs_dag_runs_form_data(request, session, dag)\n dt_nr_dr_data['arrange'] = arrange\n dttm = dt_nr_dr_data['dttm']\n\n class GraphForm(DateTimeWithNumRunsWithDagRunsForm):\n arrange = SelectField(\"Layout\", choices=(\n ('LR', \"Left->Right\"),\n ('RL', \"Right->Left\"),\n ('TB', \"Top->Bottom\"),\n ('BT', \"Bottom->Top\"),\n ))\n\n form = GraphForm(data=dt_nr_dr_data)\n form.execution_date.choices = dt_nr_dr_data['dr_choices']\n\n task_instances = {\n ti.task_id: alchemy_to_dict(ti)\n for ti in dag.get_task_instances(session, dttm, dttm)}\n tasks = {\n t.task_id: {\n 'dag_id': t.dag_id,\n 'task_type': t.task_type,\n }\n for t in dag.tasks}\n if not tasks:\n flash(\"No tasks found\", \"error\")\n session.commit()\n doc_md = markdown.markdown(dag.doc_md) if hasattr(dag, 'doc_md') and dag.doc_md else ''\n\n return self.render(\n 'airflow/graph.html',\n dag=dag,\n form=form,\n width=request.args.get('width', \"100%\"),\n height=request.args.get('height', \"800\"),\n execution_date=dttm.isoformat(),\n state_token=state_token(dt_nr_dr_data['dr_state']),\n doc_md=doc_md,\n arrange=arrange,\n operators=sorted(\n list(set([op.__class__ for op in dag.tasks])),\n key=lambda x: x.__name__\n ),\n blur=blur,\n root=root or '',\n task_instances=json.dumps(task_instances, indent=2),\n tasks=json.dumps(tasks, indent=2),\n nodes=json.dumps(nodes, indent=2),\n edges=json.dumps(edges, indent=2), )\n\n @expose('/duration')\n @login_required\n @wwwutils.action_logging\n @provide_session\n def duration(self, session=None):\n default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')\n dag_id = request.args.get('dag_id')\n dag = dagbag.get_dag(dag_id)\n base_date = request.args.get('base_date')\n num_runs = request.args.get('num_runs')\n num_runs = int(num_runs) if num_runs else default_dag_run\n\n if dag is None:\n flash('DAG \"{0}\" seems to be missing.'.format(dag_id), \"error\")\n return redirect('/admin/')\n\n if base_date:\n base_date = pendulum.parse(base_date)\n else:\n base_date = dag.latest_execution_date or timezone.utcnow()\n\n dates = dag.date_range(base_date, num=-abs(num_runs))\n min_date = dates[0] if dates else datetime(2000, 1, 1)\n\n root = request.args.get('root')\n if root:\n dag = dag.sub_dag(\n task_regex=root,\n include_upstream=True,\n include_downstream=False)\n\n chart_height = get_chart_height(dag)\n chart = nvd3.lineChart(\n name=\"lineChart\", x_is_date=True, height=chart_height, width=\"1200\")\n cum_chart = nvd3.lineChart(\n name=\"cumLineChart\", x_is_date=True, height=chart_height, width=\"1200\")\n\n y = defaultdict(list)\n x = defaultdict(list)\n cum_y = defaultdict(list)\n\n tis = dag.get_task_instances(\n session, start_date=min_date, end_date=base_date)\n TF = models.TaskFail\n ti_fails = (\n session\n .query(TF)\n .filter(\n TF.dag_id == dag.dag_id,\n TF.execution_date >= min_date,\n TF.execution_date <= base_date,\n TF.task_id.in_([t.task_id for t in dag.tasks]))\n .all()\n )\n\n fails_totals = defaultdict(int)\n for tf in ti_fails:\n dict_key = (tf.dag_id, tf.task_id, tf.execution_date)\n fails_totals[dict_key] += tf.duration\n\n for ti in tis:\n if ti.duration:\n dttm = wwwutils.epoch(ti.execution_date)\n x[ti.task_id].append(dttm)\n y[ti.task_id].append(float(ti.duration))\n fails_dict_key = (ti.dag_id, ti.task_id, ti.execution_date)\n fails_total = fails_totals[fails_dict_key]\n cum_y[ti.task_id].append(float(ti.duration + fails_total))\n\n # determine the most relevant time unit for the set of task instance\n # durations for the DAG\n y_unit = infer_time_unit([d for t in y.values() for d in t])\n cum_y_unit = infer_time_unit([d for t in cum_y.values() for d in t])\n # update the y Axis on both charts to have the correct time units\n chart.create_y_axis('yAxis', format='.02f', custom_format=False,\n label='Duration ({})'.format(y_unit))\n chart.axislist['yAxis']['axisLabelDistance'] = '40'\n cum_chart.create_y_axis('yAxis', format='.02f', custom_format=False,\n label='Duration ({})'.format(cum_y_unit))\n cum_chart.axislist['yAxis']['axisLabelDistance'] = '40'\n for task in dag.tasks:\n if x[task.task_id]:\n chart.add_serie(name=task.task_id, x=x[task.task_id],\n y=scale_time_units(y[task.task_id], y_unit))\n cum_chart.add_serie(name=task.task_id, x=x[task.task_id],\n y=scale_time_units(cum_y[task.task_id],\n cum_y_unit))\n\n dates = sorted(list({ti.execution_date for ti in tis}))\n max_date = max([ti.execution_date for ti in tis]) if dates else None\n\n session.commit()\n\n form = DateTimeWithNumRunsForm(data={'base_date': max_date,\n 'num_runs': num_runs})\n chart.buildcontent()\n cum_chart.buildcontent()\n s_index = cum_chart.htmlcontent.rfind('});')\n cum_chart.htmlcontent = (cum_chart.htmlcontent[:s_index] +\n \"$(function() {$( document ).trigger('chartload') })\" +\n cum_chart.htmlcontent[s_index:])\n\n return self.render(\n 'airflow/duration_chart.html',\n dag=dag,\n demo_mode=conf.getboolean('webserver', 'demo_mode'),\n root=root,\n form=form,\n chart=chart.htmlcontent,\n cum_chart=cum_chart.htmlcontent\n )\n\n @expose('/tries')\n @login_required\n @wwwutils.action_logging\n @provide_session\n def tries(self, session=None):\n default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')\n dag_id = request.args.get('dag_id')\n dag = dagbag.get_dag(dag_id)\n base_date = request.args.get('base_date')\n num_runs = request.args.get('num_runs')\n num_runs = int(num_runs) if num_runs else default_dag_run\n\n if base_date:\n base_date = pendulum.parse(base_date)\n else:\n base_date = dag.latest_execution_date or timezone.utcnow()\n\n dates = dag.date_range(base_date, num=-abs(num_runs))\n min_date = dates[0] if dates else datetime(2000, 1, 1)\n\n root = request.args.get('root')\n if root:\n dag = dag.sub_dag(\n task_regex=root,\n include_upstream=True,\n include_downstream=False)\n\n chart_height = get_chart_height(dag)\n chart = nvd3.lineChart(\n name=\"lineChart\", x_is_date=True, y_axis_format='d', height=chart_height,\n width=\"1200\")\n\n for task in dag.tasks:\n y = []\n x = []\n for ti in task.get_task_instances(session, start_date=min_date,\n end_date=base_date):\n dttm = wwwutils.epoch(ti.execution_date)\n x.append(dttm)\n y.append(ti.try_number)\n if x:\n chart.add_serie(name=task.task_id, x=x, y=y)\n\n tis = dag.get_task_instances(\n session, start_date=min_date, end_date=base_date)\n tries = sorted(list({ti.try_number for ti in tis}))\n max_date = max([ti.execution_date for ti in tis]) if tries else None\n\n session.commit()\n\n form = DateTimeWithNumRunsForm(data={'base_date': max_date,\n 'num_runs': num_runs})\n\n chart.buildcontent()\n\n return self.render(\n 'airflow/chart.html',\n dag=dag,\n demo_mode=conf.getboolean('webserver', 'demo_mode'),\n root=root,\n form=form,\n chart=chart.htmlcontent\n )\n\n @expose('/landing_times')\n @login_required\n @wwwutils.action_logging\n @provide_session\n def landing_times(self, session=None):\n default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')\n dag_id = request.args.get('dag_id')\n dag = dagbag.get_dag(dag_id)\n base_date = request.args.get('base_date')\n num_runs = request.args.get('num_runs')\n num_runs = int(num_runs) if num_runs else default_dag_run\n\n if base_date:\n base_date = pendulum.parse(base_date)\n else:\n base_date = dag.latest_execution_date or timezone.utcnow()\n\n dates = dag.date_range(base_date, num=-abs(num_runs))\n min_date = dates[0] if dates else datetime(2000, 1, 1)\n\n root = request.args.get('root')\n if root:\n dag = dag.sub_dag(\n task_regex=root,\n include_upstream=True,\n include_downstream=False)\n\n chart_height = get_chart_height(dag)\n chart = nvd3.lineChart(\n name=\"lineChart\", x_is_date=True, height=chart_height, width=\"1200\")\n y = {}\n x = {}\n for task in dag.tasks:\n y[task.task_id] = []\n x[task.task_id] = []\n for ti in task.get_task_instances(session, start_date=min_date,\n end_date=base_date):\n if ti.end_date:\n ts = ti.execution_date\n following_schedule = dag.following_schedule(ts)\n if dag.schedule_interval and following_schedule:\n ts = following_schedule\n\n dttm = wwwutils.epoch(ti.execution_date)\n secs = (ti.end_date - ts).total_seconds()\n x[ti.task_id].append(dttm)\n y[ti.task_id].append(secs)\n\n # determine the most relevant time unit for the set of landing times\n # for the DAG\n y_unit = infer_time_unit([d for t in y.values() for d in t])\n # update the y Axis to have the correct time units\n chart.create_y_axis('yAxis', format='.02f', custom_format=False,\n label='Landing Time ({})'.format(y_unit))\n chart.axislist['yAxis']['axisLabelDistance'] = '40'\n for task in dag.tasks:\n if x[task.task_id]:\n chart.add_serie(name=task.task_id, x=x[task.task_id],\n y=scale_time_units(y[task.task_id], y_unit))\n\n tis = dag.get_task_instances(\n session, start_date=min_date, end_date=base_date)\n dates = sorted(list({ti.execution_date for ti in tis}))\n max_date = max([ti.execution_date for ti in tis]) if dates else None\n\n form = DateTimeWithNumRunsForm(data={'base_date': max_date,\n 'num_runs': num_runs})\n chart.buildcontent()\n return self.render(\n 'airflow/chart.html',\n dag=dag,\n chart=chart.htmlcontent,\n height=str(chart_height + 100) + \"px\",\n demo_mode=conf.getboolean('webserver', 'demo_mode'),\n root=root,\n form=form,\n )\n\n @expose('/paused', methods=['POST'])\n @login_required\n @wwwutils.action_logging\n @provide_session\n def paused(self, session=None):\n DagModel = models.DagModel\n dag_id = request.args.get('dag_id')\n orm_dag = session.query(\n DagModel).filter(DagModel.dag_id == dag_id).first()\n if request.args.get('is_paused') == 'false':\n orm_dag.is_paused = True\n else:\n orm_dag.is_paused = False\n session.merge(orm_dag)\n session.commit()\n\n dagbag.get_dag(dag_id)\n return \"OK\"\n\n @expose('/refresh')\n @login_required\n @wwwutils.action_logging\n @provide_session\n def refresh(self, session=None):\n DagModel = models.DagModel\n dag_id = request.args.get('dag_id')\n orm_dag = session.query(\n DagModel).filter(DagModel.dag_id == dag_id).first()\n\n if orm_dag:\n orm_dag.last_expired = timezone.utcnow()\n session.merge(orm_dag)\n session.commit()\n\n dagbag.get_dag(dag_id)\n flash(\"DAG [{}] is now fresh as a daisy\".format(dag_id))\n return redirect(request.referrer)\n\n @expose('/refresh_all')\n @login_required\n @wwwutils.action_logging\n def refresh_all(self):\n dagbag.collect_dags(only_if_updated=False)\n flash(\"All DAGs are now up to date\")\n return redirect('/')\n\n @expose('/gantt')\n @login_required\n @wwwutils.action_logging\n @provide_session\n def gantt(self, session=None):\n dag_id = request.args.get('dag_id')\n dag = dagbag.get_dag(dag_id)\n demo_mode = conf.getboolean('webserver', 'demo_mode')\n\n root = request.args.get('root')\n if root:\n dag = dag.sub_dag(\n task_regex=root,\n include_upstream=True,\n include_downstream=False)\n\n dt_nr_dr_data = get_date_time_num_runs_dag_runs_form_data(request, session, dag)\n dttm = dt_nr_dr_data['dttm']\n\n form = DateTimeWithNumRunsWithDagRunsForm(data=dt_nr_dr_data)\n form.execution_date.choices = dt_nr_dr_data['dr_choices']\n\n tis = [\n ti for ti in dag.get_task_instances(session, dttm, dttm)\n if ti.start_date]\n tis = sorted(tis, key=lambda ti: ti.start_date)\n TF = models.TaskFail\n ti_fails = list(itertools.chain(*[(\n session\n .query(TF)\n .filter(TF.dag_id == ti.dag_id,\n TF.task_id == ti.task_id,\n TF.execution_date == ti.execution_date)\n .all()\n ) for ti in tis]))\n TR = models.TaskReschedule\n ti_reschedules = list(itertools.chain(*[(\n session\n .query(TR)\n .filter(TR.dag_id == ti.dag_id,\n TR.task_id == ti.task_id,\n TR.execution_date == ti.execution_date)\n .all()\n ) for ti in tis]))\n # determine bars to show in the gantt chart\n # all reschedules of one attempt are combinded into one bar\n gantt_bar_items = []\n for task_id, items in itertools.groupby(\n sorted(tis + ti_fails + ti_reschedules, key=lambda ti: ti.task_id),\n key=lambda ti: ti.task_id):\n start_date = None\n for i in sorted(items, key=lambda ti: ti.start_date):\n start_date = start_date or i.start_date\n end_date = i.end_date or timezone.utcnow()\n if type(i) == models.TaskInstance:\n gantt_bar_items.append((task_id, start_date, end_date, i.state))\n start_date = None\n elif type(i) == TF and (len(gantt_bar_items) == 0 or\n end_date != gantt_bar_items[-1][2]):\n gantt_bar_items.append((task_id, start_date, end_date, State.FAILED))\n start_date = None\n\n tasks = []\n for gantt_bar_item in gantt_bar_items:\n task_id = gantt_bar_item[0]\n start_date = gantt_bar_item[1]\n end_date = gantt_bar_item[2]\n state = gantt_bar_item[3]\n tasks.append({\n 'startDate': wwwutils.epoch(start_date),\n 'endDate': wwwutils.epoch(end_date),\n 'isoStart': start_date.isoformat()[:-4],\n 'isoEnd': end_date.isoformat()[:-4],\n 'taskName': task_id,\n 'duration': \"{}\".format(end_date - start_date)[:-4],\n 'status': state,\n 'executionDate': dttm.isoformat(),\n })\n states = {task['status']: task['status'] for task in tasks}\n data = {\n 'taskNames': [ti.task_id for ti in tis],\n 'tasks': tasks,\n 'taskStatus': states,\n 'height': len(tis) * 25 + 25,\n }\n\n session.commit()\n\n return self.render(\n 'airflow/gantt.html',\n dag=dag,\n execution_date=dttm.isoformat(),\n form=form,\n data=json.dumps(data, indent=2),\n base_date='',\n demo_mode=demo_mode,\n root=root,\n )\n\n @expose('/object/task_instances')\n @login_required\n @wwwutils.action_logging\n @provide_session\n def task_instances(self, session=None):\n dag_id = request.args.get('dag_id')\n dag = dagbag.get_dag(dag_id)\n\n dttm = request.args.get('execution_date')\n if dttm:\n dttm = pendulum.parse(dttm)\n else:\n return \"Error: Invalid execution_date\"\n\n task_instances = {\n ti.task_id: alchemy_to_dict(ti)\n for ti in dag.get_task_instances(session, dttm, dttm)}\n\n return json.dumps(task_instances)\n\n @expose('/variables/<form>', methods=[\"GET\", \"POST\"])\n @login_required\n @wwwutils.action_logging\n def variables(self, form):\n try:\n if request.method == 'POST':\n data = request.json\n if data:\n with create_session() as session:\n var = models.Variable(key=form, val=json.dumps(data))\n session.add(var)\n session.commit()\n return \"\"\n else:\n return self.render(\n 'airflow/variables/{}.html'.format(form)\n )\n except Exception:\n # prevent XSS\n form = escape(form)\n return (\"Error: form airflow/variables/{}.html \"\n \"not found.\").format(form), 404\n\n @expose('/varimport', methods=[\"GET\", \"POST\"])\n @login_required\n @wwwutils.action_logging\n def varimport(self):\n try:\n d = json.load(UTF8_READER(request.files['file']))\n except Exception as e:\n flash(\"Missing file or syntax error: {}.\".format(e))\n else:\n suc_count = fail_count = 0\n for k, v in d.items():\n try:\n models.Variable.set(k, v, serialize_json=isinstance(v, dict))\n except Exception as e:\n logging.info('Variable import failed: {}'.format(repr(e)))\n fail_count += 1\n else:\n suc_count += 1\n flash(\"{} variable(s) successfully updated.\".format(suc_count), 'info')\n if fail_count:\n flash(\n \"{} variables(s) failed to be updated.\".format(fail_count), 'error')\n\n return redirect('/admin/variable')\n\n\nclass HomeView(AdminIndexView):\n @expose(\"/\")\n @login_required\n @provide_session\n def index(self, session=None):\n DM = models.DagModel\n\n # restrict the dags shown if filter_by_owner and current user is not superuser\n do_filter = FILTER_BY_OWNER and (not current_user.is_superuser())\n owner_mode = conf.get('webserver', 'OWNER_MODE').strip().lower()\n\n hide_paused_dags_by_default = conf.getboolean('webserver',\n 'hide_paused_dags_by_default')\n show_paused_arg = request.args.get('showPaused', 'None')\n\n def get_int_arg(value, default=0):\n try:\n return int(value)\n except ValueError:\n return default\n\n arg_current_page = request.args.get('page', '0')\n arg_search_query = request.args.get('search', None)\n\n dags_per_page = PAGE_SIZE\n current_page = get_int_arg(arg_current_page, default=0)\n\n if show_paused_arg.strip().lower() == 'false':\n hide_paused = True\n elif show_paused_arg.strip().lower() == 'true':\n hide_paused = False\n else:\n hide_paused = hide_paused_dags_by_default\n\n # read orm_dags from the db\n sql_query = session.query(DM)\n\n if do_filter and owner_mode == 'ldapgroup':\n sql_query = sql_query.filter(\n ~DM.is_subdag,\n DM.is_active,\n DM.owners.in_(current_user.ldap_groups)\n )\n elif do_filter and owner_mode == 'user':\n sql_query = sql_query.filter(\n ~DM.is_subdag, DM.is_active,\n DM.owners == current_user.user.username\n )\n else:\n sql_query = sql_query.filter(\n ~DM.is_subdag, DM.is_active\n )\n\n # optionally filter out \"paused\" dags\n if hide_paused:\n sql_query = sql_query.filter(~DM.is_paused)\n\n orm_dags = {dag.dag_id: dag for dag\n in sql_query\n .all()}\n\n import_errors = session.query(models.ImportError).all()\n for ie in import_errors:\n flash(\n \"Broken DAG: [{ie.filename}] {ie.stacktrace}\".format(ie=ie),\n \"error\")\n\n # get a list of all non-subdag dags visible to everyone\n # optionally filter out \"paused\" dags\n if hide_paused:\n unfiltered_webserver_dags = [dag for dag in dagbag.dags.values() if\n not dag.parent_dag and not dag.is_paused]\n\n else:\n unfiltered_webserver_dags = [dag for dag in dagbag.dags.values() if\n not dag.parent_dag]\n\n # optionally filter to get only dags that the user should see\n if do_filter and owner_mode == 'ldapgroup':\n # only show dags owned by someone in @current_user.ldap_groups\n webserver_dags = {\n dag.dag_id: dag\n for dag in unfiltered_webserver_dags\n if dag.owner in current_user.ldap_groups\n }\n elif do_filter and owner_mode == 'user':\n # only show dags owned by @current_user.user.username\n webserver_dags = {\n dag.dag_id: dag\n for dag in unfiltered_webserver_dags\n if dag.owner == current_user.user.username\n }\n else:\n webserver_dags = {\n dag.dag_id: dag\n for dag in unfiltered_webserver_dags\n }\n\n if arg_search_query:\n lower_search_query = arg_search_query.lower()\n # filter by dag_id\n webserver_dags_filtered = {\n dag_id: dag\n for dag_id, dag in webserver_dags.items()\n if (lower_search_query in dag_id.lower() or\n lower_search_query in dag.owner.lower())\n }\n\n all_dag_ids = (set([dag.dag_id for dag in orm_dags.values()\n if lower_search_query in dag.dag_id.lower() or\n lower_search_query in dag.owners.lower()]) |\n set(webserver_dags_filtered.keys()))\n\n sorted_dag_ids = sorted(all_dag_ids)\n else:\n webserver_dags_filtered = webserver_dags\n sorted_dag_ids = sorted(set(orm_dags.keys()) | set(webserver_dags.keys()))\n\n start = current_page * dags_per_page\n end = start + dags_per_page\n\n num_of_all_dags = len(sorted_dag_ids)\n page_dag_ids = sorted_dag_ids[start:end]\n num_of_pages = int(math.ceil(num_of_all_dags / float(dags_per_page)))\n\n auto_complete_data = set()\n for dag in webserver_dags_filtered.values():\n auto_complete_data.add(dag.dag_id)\n auto_complete_data.add(dag.owner)\n for dag in orm_dags.values():\n auto_complete_data.add(dag.dag_id)\n auto_complete_data.add(dag.owners)\n\n return self.render(\n 'airflow/dags.html',\n webserver_dags=webserver_dags_filtered,\n orm_dags=orm_dags,\n hide_paused=hide_paused,\n current_page=current_page,\n search_query=arg_search_query if arg_search_query else '',\n page_size=dags_per_page,\n num_of_pages=num_of_pages,\n num_dag_from=start + 1,\n num_dag_to=min(end, num_of_all_dags),\n num_of_all_dags=num_of_all_dags,\n paging=wwwutils.generate_pages(current_page, num_of_pages,\n search=arg_search_query,\n showPaused=not hide_paused),\n dag_ids_in_page=page_dag_ids,\n auto_complete_data=auto_complete_data)\n\n\nclass QueryView(wwwutils.DataProfilingMixin, BaseView):\n @expose('/', methods=['POST', 'GET'])\n @wwwutils.gzipped\n @provide_session\n def query(self, session=None):\n dbs = session.query(models.Connection).order_by(\n models.Connection.conn_id).all()\n session.expunge_all()\n db_choices = list(\n ((db.conn_id, db.conn_id) for db in dbs if db.get_hook()))\n conn_id_str = request.form.get('conn_id')\n csv = request.form.get('csv') == \"true\"\n sql = request.form.get('sql')\n\n class QueryForm(Form):\n conn_id = SelectField(\"Layout\", choices=db_choices)\n sql = TextAreaField(\"SQL\", widget=wwwutils.AceEditorWidget())\n\n data = {\n 'conn_id': conn_id_str,\n 'sql': sql,\n }\n results = None\n has_data = False\n error = False\n if conn_id_str:\n db = [db for db in dbs if db.conn_id == conn_id_str][0]\n hook = db.get_hook()\n try:\n df = hook.get_pandas_df(wwwutils.limit_sql(sql, QUERY_LIMIT, conn_type=db.conn_type))\n # df = hook.get_pandas_df(sql)\n has_data = len(df) > 0\n df = df.fillna('')\n results = df.to_html(\n classes=[\n 'table', 'table-bordered', 'table-striped', 'no-wrap'],\n index=False,\n na_rep='',\n ) if has_data else ''\n except Exception as e:\n flash(str(e), 'error')\n error = True\n\n if has_data and len(df) == QUERY_LIMIT:\n flash(\n \"Query output truncated at \" + str(QUERY_LIMIT) +\n \" rows\", 'info')\n\n if not has_data and error:\n flash('No data', 'error')\n\n if csv:\n return Response(\n response=df.to_csv(index=False),\n status=200,\n mimetype=\"application/text\")\n\n form = QueryForm(request.form, data=data)\n session.commit()\n return self.render(\n 'airflow/query.html', form=form,\n title=\"Ad Hoc Query\",\n results=results or '',\n has_data=has_data)\n\n\nclass AirflowModelView(ModelView):\n list_template = 'airflow/model_list.html'\n edit_template = 'airflow/model_edit.html'\n create_template = 'airflow/model_create.html'\n column_display_actions = True\n page_size = PAGE_SIZE\n\n\nclass ModelViewOnly(wwwutils.LoginMixin, AirflowModelView):\n \"\"\"\n Modifying the base ModelView class for non edit, browse only operations\n \"\"\"\n named_filter_urls = True\n can_create = False\n can_edit = False\n can_delete = False\n column_display_pk = True\n\n\nclass PoolModelView(wwwutils.SuperUserMixin, AirflowModelView):\n column_list = ('pool', 'slots', 'used_slots', 'queued_slots')\n column_formatters = dict(\n pool=pool_link, used_slots=fused_slots, queued_slots=fqueued_slots)\n named_filter_urls = True\n form_args = {\n 'pool': {\n 'validators': [\n validators.DataRequired(),\n ]\n }\n }\n\n\nclass SlaMissModelView(wwwutils.SuperUserMixin, ModelViewOnly):\n verbose_name_plural = \"SLA misses\"\n verbose_name = \"SLA miss\"\n column_list = (\n 'dag_id', 'task_id', 'execution_date', 'email_sent', 'timestamp')\n column_formatters = dict(\n task_id=task_instance_link,\n execution_date=datetime_f,\n timestamp=datetime_f,\n dag_id=dag_link)\n named_filter_urls = True\n column_searchable_list = ('dag_id', 'task_id',)\n column_filters = (\n 'dag_id', 'task_id', 'email_sent', 'timestamp', 'execution_date')\n filter_converter = wwwutils.UtcFilterConverter()\n form_widget_args = {\n 'email_sent': {'disabled': True},\n 'timestamp': {'disabled': True},\n }\n\n\n@provide_session\ndef _connection_ids(session=None):\n return [(c.conn_id, c.conn_id) for c in (\n session\n .query(models.Connection.conn_id)\n .group_by(models.Connection.conn_id))]\n\n\nclass ChartModelView(wwwutils.DataProfilingMixin, AirflowModelView):\n verbose_name = \"chart\"\n verbose_name_plural = \"charts\"\n form_columns = (\n 'label',\n 'owner',\n 'conn_id',\n 'chart_type',\n 'show_datatable',\n 'x_is_date',\n 'y_log_scale',\n 'show_sql',\n 'height',\n 'sql_layout',\n 'sql',\n 'default_params',\n )\n column_list = (\n 'label',\n 'conn_id',\n 'chart_type',\n 'owner',\n 'last_modified',\n )\n column_sortable_list = (\n 'label',\n 'conn_id',\n 'chart_type',\n ('owner', 'owner.username'),\n 'last_modified',\n )\n column_formatters = dict(label=label_link, last_modified=datetime_f)\n column_default_sort = ('last_modified', True)\n create_template = 'airflow/chart/create.html'\n edit_template = 'airflow/chart/edit.html'\n column_filters = ('label', 'owner.username', 'conn_id')\n column_searchable_list = ('owner.username', 'label', 'sql')\n column_descriptions = {\n 'label': \"Can include {{ templated_fields }} and {{ macros }}\",\n 'chart_type': \"The type of chart to be displayed\",\n 'sql': \"Can include {{ templated_fields }} and {{ macros }}.\",\n 'height': \"Height of the chart, in pixels.\",\n 'conn_id': \"Source database to run the query against\",\n 'x_is_date': (\n \"Whether the X axis should be casted as a date field. Expect most \"\n \"intelligible date formats to get casted properly.\"\n ),\n 'owner': (\n \"The chart's owner, mostly used for reference and filtering in \"\n \"the list view.\"\n ),\n 'show_datatable':\n \"Whether to display an interactive data table under the chart.\",\n 'default_params': (\n 'A dictionary of {\"key\": \"values\",} that define what the '\n 'templated fields (parameters) values should be by default. '\n 'To be valid, it needs to \"eval\" as a Python dict. '\n 'The key values will show up in the url\\'s querystring '\n 'and can be altered there.'\n ),\n 'show_sql': \"Whether to display the SQL statement as a collapsible \"\n \"section in the chart page.\",\n 'y_log_scale': \"Whether to use a log scale for the Y axis.\",\n 'sql_layout': (\n \"Defines the layout of the SQL that the application should \"\n \"expect. Depending on the tables you are sourcing from, it may \"\n \"make more sense to pivot / unpivot the metrics.\"\n ),\n }\n column_labels = {\n 'sql': \"SQL\",\n 'height': \"Chart Height\",\n 'sql_layout': \"SQL Layout\",\n 'show_sql': \"Display the SQL Statement\",\n 'default_params': \"Default Parameters\",\n }\n form_choices = {\n 'chart_type': [\n ('line', 'Line Chart'),\n ('spline', 'Spline Chart'),\n ('bar', 'Bar Chart'),\n ('column', 'Column Chart'),\n ('area', 'Overlapping Area Chart'),\n ('stacked_area', 'Stacked Area Chart'),\n ('percent_area', 'Percent Area Chart'),\n ('datatable', 'No chart, data table only'),\n ],\n 'sql_layout': [\n ('series', 'SELECT series, x, y FROM ...'),\n ('columns', 'SELECT x, y (series 1), y (series 2), ... FROM ...'),\n ],\n 'conn_id': _connection_ids()\n }\n\n def on_model_change(self, form, model, is_created=True):\n if model.iteration_no is None:\n model.iteration_no = 0\n else:\n model.iteration_no += 1\n if not model.user_id and current_user and hasattr(current_user, 'id'):\n model.user_id = current_user.id\n model.last_modified = timezone.utcnow()\n\n\nchart_mapping = (\n ('line', 'lineChart'),\n ('spline', 'lineChart'),\n ('bar', 'multiBarChart'),\n ('column', 'multiBarChart'),\n ('area', 'stackedAreaChart'),\n ('stacked_area', 'stackedAreaChart'),\n ('percent_area', 'stackedAreaChart'),\n ('datatable', 'datatable'),\n)\nchart_mapping = dict(chart_mapping)\n\n\nclass KnownEventView(wwwutils.DataProfilingMixin, AirflowModelView):\n verbose_name = \"known event\"\n verbose_name_plural = \"known events\"\n form_columns = (\n 'label',\n 'event_type',\n 'start_date',\n 'end_date',\n 'reported_by',\n 'description',\n )\n form_args = {\n 'label': {\n 'validators': [\n validators.DataRequired(),\n ],\n },\n 'event_type': {\n 'validators': [\n validators.DataRequired(),\n ],\n },\n 'start_date': {\n 'validators': [\n validators.DataRequired(),\n ],\n 'filters': [\n parse_datetime_f,\n ],\n },\n 'end_date': {\n 'validators': [\n validators.DataRequired(),\n GreaterEqualThan(fieldname='start_date'),\n ],\n 'filters': [\n parse_datetime_f,\n ]\n },\n 'reported_by': {\n 'validators': [\n validators.DataRequired(),\n ],\n }\n }\n column_list = (\n 'label',\n 'event_type',\n 'start_date',\n 'end_date',\n 'reported_by',\n )\n column_default_sort = (\"start_date\", True)\n column_sortable_list = (\n 'label',\n # todo: yes this has a spelling error\n ('event_type', 'event_type.know_event_type'),\n 'start_date',\n 'end_date',\n ('reported_by', 'reported_by.username'),\n )\n filter_converter = wwwutils.UtcFilterConverter()\n form_overrides = dict(start_date=DateTimeField, end_date=DateTimeField)\n\n\nclass KnownEventTypeView(wwwutils.DataProfilingMixin, AirflowModelView):\n pass\n\n\n# NOTE: For debugging / troubleshooting\n# mv = KnowEventTypeView(\n# models.KnownEventType,\n# Session, name=\"Known Event Types\", category=\"Manage\")\n# admin.add_view(mv)\n# class DagPickleView(SuperUserMixin, ModelView):\n# pass\n# mv = DagPickleView(\n# models.DagPickle,\n# Session, name=\"Pickles\", category=\"Manage\")\n# admin.add_view(mv)\n\n\nclass VariableView(wwwutils.DataProfilingMixin, AirflowModelView):\n verbose_name = \"Variable\"\n verbose_name_plural = \"Variables\"\n list_template = 'airflow/variable_list.html'\n\n def hidden_field_formatter(view, context, model, name):\n if wwwutils.should_hide_value_for_key(model.key):\n return Markup('*' * 8)\n val = getattr(model, name)\n if val:\n return val\n else:\n return Markup('<span class=\"label label-danger\">Invalid</span>')\n\n form_columns = (\n 'key',\n 'val',\n )\n column_list = ('key', 'val', 'is_encrypted',)\n column_filters = ('key', 'val')\n column_searchable_list = ('key', 'val', 'is_encrypted',)\n column_default_sort = ('key', False)\n form_widget_args = {\n 'is_encrypted': {'disabled': True},\n 'val': {\n 'rows': 20,\n }\n }\n form_args = {\n 'key': {\n 'validators': {\n validators.DataRequired(),\n },\n },\n }\n column_sortable_list = (\n 'key',\n 'val',\n 'is_encrypted',\n )\n column_formatters = {\n 'val': hidden_field_formatter,\n }\n\n # Default flask-admin export functionality doesn't handle serialized json\n @action('varexport', 'Export', None)\n @provide_session\n def action_varexport(self, ids, session=None):\n V = models.Variable\n qry = session.query(V).filter(V.id.in_(ids)).all()\n\n var_dict = {}\n d = json.JSONDecoder()\n for var in qry:\n val = None\n try:\n val = d.decode(var.val)\n except Exception:\n val = var.val\n var_dict[var.key] = val\n\n response = make_response(json.dumps(var_dict, sort_keys=True, indent=4))\n response.headers[\"Content-Disposition\"] = \"attachment; filename=variables.json\"\n return response\n\n def on_form_prefill(self, form, id):\n if wwwutils.should_hide_value_for_key(form.key.data):\n form.val.data = '*' * 8\n\n\nclass XComView(wwwutils.SuperUserMixin, AirflowModelView):\n verbose_name = \"XCom\"\n verbose_name_plural = \"XComs\"\n\n form_columns = (\n 'key',\n 'value',\n 'execution_date',\n 'task_id',\n 'dag_id',\n )\n\n form_extra_fields = {\n 'value': StringField('Value'),\n }\n\n form_args = {\n 'execution_date': {\n 'filters': [\n parse_datetime_f,\n ]\n }\n }\n\n column_filters = ('key', 'timestamp', 'execution_date', 'task_id', 'dag_id')\n column_searchable_list = ('key', 'timestamp', 'execution_date', 'task_id', 'dag_id')\n filter_converter = wwwutils.UtcFilterConverter()\n form_overrides = dict(execution_date=DateTimeField)\n\n\nclass JobModelView(ModelViewOnly):\n verbose_name_plural = \"jobs\"\n verbose_name = \"job\"\n column_display_actions = False\n column_default_sort = ('start_date', True)\n column_filters = (\n 'job_type', 'dag_id', 'state',\n 'unixname', 'hostname', 'start_date', 'end_date', 'latest_heartbeat')\n column_formatters = dict(\n start_date=datetime_f,\n end_date=datetime_f,\n hostname=nobr_f,\n state=state_f,\n latest_heartbeat=datetime_f)\n filter_converter = wwwutils.UtcFilterConverter()\n\n\nclass DagRunModelView(ModelViewOnly):\n verbose_name_plural = \"DAG Runs\"\n can_edit = True\n can_create = True\n column_editable_list = ('state',)\n verbose_name = \"dag run\"\n column_default_sort = ('execution_date', True)\n form_choices = {\n 'state': [\n ('success', 'success'),\n ('running', 'running'),\n ('failed', 'failed'),\n ],\n }\n form_args = dict(\n dag_id=dict(validators=[validators.DataRequired()])\n )\n column_list = (\n 'state', 'dag_id', 'execution_date', 'run_id', 'external_trigger')\n column_filters = column_list\n filter_converter = wwwutils.UtcFilterConverter()\n column_searchable_list = ('dag_id', 'state', 'run_id')\n column_formatters = dict(\n execution_date=datetime_f,\n state=state_f,\n start_date=datetime_f,\n dag_id=dag_link,\n run_id=dag_run_link\n )\n\n @action('new_delete', \"Delete\", \"Are you sure you want to delete selected records?\")\n @provide_session\n def action_new_delete(self, ids, session=None):\n deleted = set(session.query(models.DagRun)\n .filter(models.DagRun.id.in_(ids))\n .all())\n session.query(models.DagRun) \\\n .filter(models.DagRun.id.in_(ids)) \\\n .delete(synchronize_session='fetch')\n session.commit()\n dirty_ids = []\n for row in deleted:\n dirty_ids.append(row.dag_id)\n models.DagStat.update(dirty_ids, dirty_only=False, session=session)\n\n @action('set_running', \"Set state to 'running'\", None)\n @provide_session\n def action_set_running(self, ids, session=None):\n try:\n DR = models.DagRun\n count = 0\n dirty_ids = []\n for dr in session.query(DR).filter(DR.id.in_(ids)).all():\n dirty_ids.append(dr.dag_id)\n count += 1\n dr.state = State.RUNNING\n dr.start_date = timezone.utcnow()\n models.DagStat.update(dirty_ids, session=session)\n flash(\n \"{count} dag runs were set to running\".format(**locals()))\n except Exception as ex:\n if not self.handle_view_exception(ex):\n raise Exception(\"Ooops\")\n flash('Failed to set state', 'error')\n\n @action('set_failed', \"Set state to 'failed'\",\n \"All running task instances would also be marked as failed, are you sure?\")\n @provide_session\n def action_set_failed(self, ids, session=None):\n try:\n DR = models.DagRun\n count = 0\n dirty_ids = []\n altered_tis = []\n for dr in session.query(DR).filter(DR.id.in_(ids)).all():\n dirty_ids.append(dr.dag_id)\n count += 1\n altered_tis += \\\n set_dag_run_state_to_failed(dagbag.get_dag(dr.dag_id),\n dr.execution_date,\n commit=True,\n session=session)\n models.DagStat.update(dirty_ids, session=session)\n altered_ti_count = len(altered_tis)\n flash(\n \"{count} dag runs and {altered_ti_count} task instances \"\n \"were set to failed\".format(**locals()))\n except Exception as ex:\n if not self.handle_view_exception(ex):\n raise Exception(\"Ooops\")\n flash('Failed to set state', 'error')\n\n @action('set_success', \"Set state to 'success'\",\n \"All task instances would also be marked as success, are you sure?\")\n @provide_session\n def action_set_success(self, ids, session=None):\n try:\n DR = models.DagRun\n count = 0\n dirty_ids = []\n altered_tis = []\n for dr in session.query(DR).filter(DR.id.in_(ids)).all():\n dirty_ids.append(dr.dag_id)\n count += 1\n altered_tis += \\\n set_dag_run_state_to_success(dagbag.get_dag(dr.dag_id),\n dr.execution_date,\n commit=True,\n session=session)\n models.DagStat.update(dirty_ids, session=session)\n altered_ti_count = len(altered_tis)\n flash(\n \"{count} dag runs and {altered_ti_count} task instances \"\n \"were set to success\".format(**locals()))\n except Exception as ex:\n if not self.handle_view_exception(ex):\n raise Exception(\"Ooops\")\n flash('Failed to set state', 'error')\n\n # Called after editing DagRun model in the UI.\n @provide_session\n def after_model_change(self, form, dagrun, is_created, session=None):\n altered_tis = []\n if dagrun.state == State.SUCCESS:\n altered_tis = set_dag_run_state_to_success(\n dagbag.get_dag(dagrun.dag_id),\n dagrun.execution_date,\n commit=True,\n session=session)\n elif dagrun.state == State.FAILED:\n altered_tis = set_dag_run_state_to_failed(\n dagbag.get_dag(dagrun.dag_id),\n dagrun.execution_date,\n commit=True,\n session=session)\n elif dagrun.state == State.RUNNING:\n altered_tis = set_dag_run_state_to_running(\n dagbag.get_dag(dagrun.dag_id),\n dagrun.execution_date,\n commit=True,\n session=session)\n\n altered_ti_count = len(altered_tis)\n models.DagStat.update([dagrun.dag_id], session=session)\n flash(\n \"1 dag run and {altered_ti_count} task instances \"\n \"were set to '{dagrun.state}'\".format(**locals()))\n\n\nclass LogModelView(ModelViewOnly):\n verbose_name_plural = \"logs\"\n verbose_name = \"log\"\n column_display_actions = False\n column_default_sort = ('dttm', True)\n column_filters = ('dag_id', 'task_id', 'execution_date', 'extra')\n filter_converter = wwwutils.UtcFilterConverter()\n column_formatters = dict(\n dttm=datetime_f, execution_date=datetime_f, dag_id=dag_link)\n\n\nclass TaskInstanceModelView(ModelViewOnly):\n verbose_name_plural = \"task instances\"\n verbose_name = \"task instance\"\n column_filters = (\n 'state', 'dag_id', 'task_id', 'execution_date', 'hostname',\n 'queue', 'pool', 'operator', 'start_date', 'end_date')\n filter_converter = wwwutils.UtcFilterConverter()\n named_filter_urls = True\n column_formatters = dict(\n log_url=log_url_formatter,\n task_id=task_instance_link,\n hostname=nobr_f,\n state=state_f,\n execution_date=datetime_f,\n start_date=datetime_f,\n end_date=datetime_f,\n queued_dttm=datetime_f,\n dag_id=dag_link,\n run_id=dag_run_link,\n duration=duration_f)\n column_searchable_list = ('dag_id', 'task_id', 'state')\n column_default_sort = ('job_id', True)\n form_choices = {\n 'state': [\n ('success', 'success'),\n ('running', 'running'),\n ('failed', 'failed'),\n ],\n }\n column_list = (\n 'state', 'dag_id', 'task_id', 'execution_date', 'operator',\n 'start_date', 'end_date', 'duration', 'job_id', 'hostname',\n 'unixname', 'priority_weight', 'queue', 'queued_dttm', 'try_number',\n 'pool', 'log_url')\n page_size = PAGE_SIZE\n\n @action('set_running', \"Set state to 'running'\", None)\n def action_set_running(self, ids):\n self.set_task_instance_state(ids, State.RUNNING)\n\n @action('set_failed', \"Set state to 'failed'\", None)\n def action_set_failed(self, ids):\n self.set_task_instance_state(ids, State.FAILED)\n\n @action('set_success', \"Set state to 'success'\", None)\n def action_set_success(self, ids):\n self.set_task_instance_state(ids, State.SUCCESS)\n\n @action('set_retry', \"Set state to 'up_for_retry'\", None)\n def action_set_retry(self, ids):\n self.set_task_instance_state(ids, State.UP_FOR_RETRY)\n\n @provide_session\n @action('clear',\n lazy_gettext('Clear'),\n lazy_gettext(\n 'Are you sure you want to clear the state of the selected task instance(s)'\n ' and set their dagruns to the running state?'))\n def action_clear(self, ids, session=None):\n try:\n TI = models.TaskInstance\n\n dag_to_task_details = {}\n dag_to_tis = {}\n\n # Collect dags upfront as dagbag.get_dag() will reset the session\n for id_str in ids:\n task_id, dag_id, execution_date = iterdecode(id_str)\n dag = dagbag.get_dag(dag_id)\n task_details = dag_to_task_details.setdefault(dag, [])\n task_details.append((task_id, execution_date))\n\n for dag, task_details in dag_to_task_details.items():\n for task_id, execution_date in task_details:\n execution_date = parse_execution_date(execution_date)\n\n ti = session.query(TI).filter(TI.task_id == task_id,\n TI.dag_id == dag.dag_id,\n TI.execution_date == execution_date).one()\n\n tis = dag_to_tis.setdefault(dag, [])\n tis.append(ti)\n\n for dag, tis in dag_to_tis.items():\n models.clear_task_instances(tis, session, dag=dag)\n\n session.commit()\n\n flash(\"{0} task instances have been cleared\".format(len(ids)))\n\n except Exception as ex:\n if not self.handle_view_exception(ex):\n raise Exception(\"Ooops\")\n flash('Failed to clear task instances', 'error')\n\n @provide_session\n def set_task_instance_state(self, ids, target_state, session=None):\n try:\n TI = models.TaskInstance\n count = len(ids)\n for id in ids:\n task_id, dag_id, execution_date = iterdecode(id)\n execution_date = parse_execution_date(execution_date)\n\n ti = session.query(TI).filter(TI.task_id == task_id,\n TI.dag_id == dag_id,\n TI.execution_date == execution_date).one()\n ti.state = target_state\n session.commit()\n flash(\n \"{count} task instances were set to '{target_state}'\".format(**locals()))\n except Exception as ex:\n if not self.handle_view_exception(ex):\n raise Exception(\"Ooops\")\n flash('Failed to set state', 'error')\n\n def get_one(self, id):\n \"\"\"\n As a workaround for AIRFLOW-252, this method overrides Flask-Admin's ModelView.get_one().\n\n TODO: this method should be removed once the below bug is fixed on Flask-Admin side.\n https://github.com/flask-admin/flask-admin/issues/1226\n \"\"\"\n task_id, dag_id, execution_date = iterdecode(id)\n execution_date = pendulum.parse(execution_date)\n return self.session.query(self.model).get((task_id, dag_id, execution_date))\n\n\nclass ConnectionModelView(wwwutils.SuperUserMixin, AirflowModelView):\n create_template = 'airflow/conn_create.html'\n edit_template = 'airflow/conn_edit.html'\n list_template = 'airflow/conn_list.html'\n form_columns = (\n 'conn_id',\n 'conn_type',\n 'host',\n 'schema',\n 'login',\n 'password',\n 'port',\n 'extra',\n 'extra__jdbc__drv_path',\n 'extra__jdbc__drv_clsname',\n 'extra__google_cloud_platform__project',\n 'extra__google_cloud_platform__key_path',\n 'extra__google_cloud_platform__keyfile_dict',\n 'extra__google_cloud_platform__scope',\n )\n verbose_name = \"Connection\"\n verbose_name_plural = \"Connections\"\n column_default_sort = ('conn_id', False)\n column_list = ('conn_id', 'conn_type', 'host', 'port', 'is_encrypted', 'is_extra_encrypted',)\n form_overrides = dict(_password=PasswordField, _extra=TextAreaField)\n form_widget_args = {\n 'is_extra_encrypted': {'disabled': True},\n 'is_encrypted': {'disabled': True},\n }\n # Used to customized the form, the forms elements get rendered\n # and results are stored in the extra field as json. All of these\n # need to be prefixed with extra__ and then the conn_type ___ as in\n # extra__{conn_type}__name. You can also hide form elements and rename\n # others from the connection_form.js file\n form_extra_fields = {\n 'extra__jdbc__drv_path': StringField('Driver Path'),\n 'extra__jdbc__drv_clsname': StringField('Driver Class'),\n 'extra__google_cloud_platform__project': StringField('Project Id'),\n 'extra__google_cloud_platform__key_path': StringField('Keyfile Path'),\n 'extra__google_cloud_platform__keyfile_dict': PasswordField('Keyfile JSON'),\n 'extra__google_cloud_platform__scope': StringField('Scopes (comma separated)'),\n }\n form_choices = {\n 'conn_type': models.Connection._types\n }\n\n def on_model_change(self, form, model, is_created):\n formdata = form.data\n if formdata['conn_type'] in ['jdbc', 'google_cloud_platform']:\n extra = {\n key: formdata[key]\n for key in self.form_extra_fields.keys() if key in formdata}\n model.extra = json.dumps(extra)\n\n @classmethod\n def alert_fernet_key(cls):\n fk = None\n try:\n fk = conf.get('core', 'fernet_key')\n except Exception:\n pass\n return fk is None\n\n @classmethod\n def is_secure(cls):\n \"\"\"\n Used to display a message in the Connection list view making it clear\n that the passwords and `extra` field can't be encrypted.\n \"\"\"\n is_secure = False\n try:\n import cryptography # noqa F401\n conf.get('core', 'fernet_key')\n is_secure = True\n except Exception:\n pass\n return is_secure\n\n def on_form_prefill(self, form, id):\n try:\n d = json.loads(form.data.get('extra', '{}'))\n except Exception:\n d = {}\n\n for field in list(self.form_extra_fields.keys()):\n value = d.get(field, '')\n if value:\n field = getattr(form, field)\n field.data = value\n\n\nclass UserModelView(wwwutils.SuperUserMixin, AirflowModelView):\n verbose_name = \"User\"\n verbose_name_plural = \"Users\"\n column_default_sort = 'username'\n\n\nclass VersionView(wwwutils.SuperUserMixin, BaseView):\n @expose('/')\n def version(self):\n # Look at the version from setup.py\n try:\n airflow_version = pkg_resources.require(\"apache-airflow\")[0].version\n except Exception as e:\n airflow_version = None\n logging.error(e)\n\n # Get the Git repo and git hash\n git_version = None\n try:\n with open(os.path.join(*[settings.AIRFLOW_HOME, 'airflow', 'git_version'])) as f:\n git_version = f.readline()\n except Exception as e:\n logging.error(e)\n\n # Render information\n title = \"Version Info\"\n return self.render('airflow/version.html',\n title=title,\n airflow_version=airflow_version,\n git_version=git_version)\n\n\nclass ConfigurationView(wwwutils.SuperUserMixin, BaseView):\n @expose('/')\n def conf(self):\n raw = request.args.get('raw') == \"true\"\n title = \"Airflow Configuration\"\n subtitle = conf.AIRFLOW_CONFIG\n if conf.getboolean(\"webserver\", \"expose_config\"):\n with open(conf.AIRFLOW_CONFIG, 'r') as f:\n config = f.read()\n table = [(section, key, value, source)\n for section, parameters in conf.as_dict(True, True).items()\n for key, (value, source) in parameters.items()]\n\n else:\n config = (\n \"# Your Airflow administrator chose not to expose the \"\n \"configuration, most likely for security reasons.\")\n table = None\n if raw:\n return Response(\n response=config,\n status=200,\n mimetype=\"application/text\")\n else:\n code_html = Markup(highlight(\n config,\n lexers.IniLexer(), # Lexer call\n HtmlFormatter(noclasses=True))\n )\n return self.render(\n 'airflow/config.html',\n pre_subtitle=settings.HEADER + \" v\" + airflow.__version__,\n code_html=code_html, title=title, subtitle=subtitle,\n table=table)\n\n\nclass DagModelView(wwwutils.SuperUserMixin, ModelView):\n column_list = ('dag_id', 'owners')\n column_editable_list = ('is_paused',)\n form_excluded_columns = ('is_subdag', 'is_active')\n column_searchable_list = ('dag_id',)\n column_filters = (\n 'dag_id', 'owners', 'is_paused', 'is_active', 'is_subdag',\n 'last_scheduler_run', 'last_expired')\n filter_converter = wwwutils.UtcFilterConverter()\n form_widget_args = {\n 'last_scheduler_run': {'disabled': True},\n 'fileloc': {'disabled': True},\n 'is_paused': {'disabled': True},\n 'last_pickled': {'disabled': True},\n 'pickle_id': {'disabled': True},\n 'last_loaded': {'disabled': True},\n 'last_expired': {'disabled': True},\n 'pickle_size': {'disabled': True},\n 'scheduler_lock': {'disabled': True},\n 'owners': {'disabled': True},\n }\n column_formatters = dict(\n dag_id=dag_link,\n )\n can_delete = False\n can_create = False\n page_size = PAGE_SIZE\n list_template = 'airflow/list_dags.html'\n named_filter_urls = True\n\n def get_query(self):\n \"\"\"\n Default filters for model\n \"\"\"\n return super(DagModelView, self)\\\n .get_query()\\\n .filter(or_(models.DagModel.is_active, models.DagModel.is_paused))\\\n .filter(~models.DagModel.is_subdag)\n\n def get_count_query(self):\n \"\"\"\n Default filters for model\n \"\"\"\n return super(DagModelView, self)\\\n .get_count_query()\\\n .filter(models.DagModel.is_active)\\\n .filter(~models.DagModel.is_subdag)\n"
] | [
[
"pandas.to_datetime",
"pandas.set_option"
]
] |
gkaramanolakis/ISWD | [
"41452f447284491cf8ade8e09f3bc4e314ec64f7"
] | [
"iswd/cotrain_experiments.py"
] | [
"#!/usr/bin/env python\nimport os\nfrom os.path import expanduser\nhome = expanduser(\"~\")\nimport sys\nimport h5py\nimport argparse\nfrom datetime import datetime\nfrom time import time\n\nimport numpy as np\nfrom numpy.random import permutation, seed\nfrom scipy.cluster.vq import kmeans\nimport glob\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.init import xavier_uniform\nfrom torch.nn.utils import clip_grad_norm\n\nfrom tensorboardX import SummaryWriter\n\nfrom sklearn.externals import joblib\nfrom copy import deepcopy\n\n\nfrom DataHandler import DataHandler\n\nsys.path.append(os.path.join(home, \"code/research_code/Spring_2018/TextModules/\"))\nfrom Evaluator import Evaluator\nfrom Logger import get_logger\nfrom model_library import AspectCLF, StudentBoWCLF, SeedCLF, smooth_cross_entropy\n\nall_semeval_domains = ['english_restaurants', 'spanish_restaurants', 'french_restaurants', 'russian_restaurants',\n 'dutch_restaurants', 'turkish_restaurants']\nall_domains = ['bags_and_cases', 'keyboards', 'boots', 'bluetooth', 'tv', 'vacuums']\n\nclass Trainer:\n def __init__(self, args):\n self.args = args\n self.comment = '_{}'.format(args.domain)\n if self.args.loss in ['SmoothCrossEntropy', \"KL\"]:\n self.args.one_hot = True\n else:\n self.args.one_hot = False\n self.datahandler = DataHandler(self.args)\n self.writer = SummaryWriter(log_dir=self.args.logdir)\n loggerfile = os.path.join(self.args.logdir, 'log.log')\n self.logger = get_logger(logfile=loggerfile)\n self.check_gpu()\n joblib.dump(self.args, os.path.join(self.args.logdir, 'args.pkl'))\n\n self.evaluator = Evaluator(args) \n if args.no_seed_weights:\n self.logger.info('NOT using seed weights...')\n seed_weights = None\n else:\n self.logger.info('USING seed weights...')\n seed_weights = self.datahandler.seed_w\n\n if args.no_pretrained_emb:\n self.logger.info('NOT using pretrained word embeddings...')\n pretrained_emb = None\n else:\n pretrained_emb = self.datahandler.w_emb\n\n if self.datahandler.num_aspects != self.args.num_aspects:\n self.logger.info(\"Automatically changing num_aspects from {} to {}\".format(self.args.num_aspects, self.datahandler.num_aspects))\n self.args.num_aspects = self.datahandler.num_aspects\n\n if args.model_type == 'embedding_based':\n self.logger.info('Model: Embeddings based Classifier')\n # prev model is loaded just to gather previous predictions and regularize the new model to\n # provide similar predictions.\n if args.memory_reg > 0:\n self.prev_model = AspectCLF(vocab_size=self.datahandler.vocab_size, pretrained_emb=pretrained_emb, emb_size=self.datahandler.emb_size,\n seed_encodings=None, seed_weights=seed_weights, num_aspects=self.args.num_aspects,\n num_seeds=args.num_seeds, fix_a_emb=False, fix_w_emb=args.fix_w_emb, attention=args.attention,\n deep_clf=args.deep_aspect_clf, enable_gpu=args.enable_gpu, cuda_device=args.cuda_device,\n emb_dropout=args.emb_dropout, batch_norm= args.batch_norm, use_bert=args.use_bert,\n bert_model=args.bert_model)\n self.model = AspectCLF(vocab_size=self.datahandler.vocab_size, pretrained_emb=pretrained_emb, emb_size=self.datahandler.emb_size,\n seed_encodings=None, seed_weights=seed_weights, num_aspects=self.args.num_aspects,\n num_seeds=args.num_seeds, fix_a_emb=False, fix_w_emb=args.fix_w_emb, attention=args.attention,\n deep_clf=args.deep_aspect_clf, enable_gpu=args.enable_gpu, cuda_device=args.cuda_device,\n emb_dropout=args.emb_dropout, batch_norm= args.batch_norm, use_bert=args.use_bert,\n bert_model=args.bert_model)\n elif args.model_type == 'bow_based':\n self.logger.info('Model: BoW Classifier')\n self.model = StudentBoWCLF(self.datahandler.id2word, self.datahandler.aspects_ids)\n else:\n raise(BaseException('unknown model type: {}'.format(args.model_type)))\n self.model = self.cuda(self.model)\n\n self.teacher = SeedCLF(self.datahandler.id2word, self.datahandler.aspects_ids, seed_weights,\n verbose=0, general_ind=self.datahandler.general_ind,\n hard_pred=args.hard_teacher_pred)\n\n self.optimizer = self.get_optimizer(args)\n if args.scheduler_gamma > 0:\n ms=args.bootstrap_epoch\n self.scheduler = torch.optim.lr_scheduler.MultiStepLR(self.optimizer, milestones=[ms, ms+1, ms+2, ms+3], gamma=args.scheduler_gamma)\n self.loss_fn = self.get_loss_fn(args)\n self.logger.info('Saving log at {}'.format(loggerfile))\n self.logger.debug('enable_gpu={}'.format(args.enable_gpu))\n self.epoch = -1\n self.results = []\n self.metric = self.args.target_metric\n self.best_score = -1.0\n self.best_test_score = -1.0\n self.epoch_results = {}\n if args.memory_reg > 0:\n self.memory_loss = self.get_memory_loss_fn(args)\n self.prev_model = self.cuda(self.prev_model)\n\n self.student_proba_train = None\n self.student_proba_dev = None\n self.student_proba_test = None\n self.labels_dev = None\n self.labels_test = None\n self.teacher_proba_train = None\n self.teacher_pred_dev = None\n self.teacher_pred_test = None\n self.disagreement = -1\n\n def check_gpu(self):\n if self.args.enable_gpu:\n torch.cuda.manual_seed(self.args.seed)\n if self.args.enable_gpu and not torch.cuda.is_available():\n raise(BaseException('CUDA is not supported in this machine. Please rerun by setting enable_gpu=False'))\n if torch.cuda.device_count() > 1:\n self.logger.info(\"Tip: You could use {} GPUs in this machine!\".format(torch.cuda.device_count()))\n\n def get_optimizer(self, args):\n if args.optimizer == 'Adam':\n optimizer = torch.optim.Adam(self.model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n elif args.optimizer == 'Adadelta':\n optimizer = torch.optim.Adadelta(self.model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n elif args.optimizer == 'SGD':\n optimizer = torch.optim.SGD(self.model.parameters(), lr=args.lr, weight_decay=args.weight_decay, momentum=args.momentum)\n else:\n raise(NotImplementedError('unknown optimizer: {}'.format(args.optimizer)))\n return optimizer\n\n def get_loss_fn(self, args):\n if args.loss == 'CrossEntropy':\n loss_fn = nn.CrossEntropyLoss()\n elif args.loss == 'NLL':\n loss_fn = nn.NLLLoss()\n elif args.loss == 'SmoothCrossEntropy':\n loss_fn = smooth_cross_entropy\n elif args.loss == 'KL':\n loss_fn = nn.KLDivLoss()\n else:\n raise(NotImplementedError('unknown loss function: {}'.format(args.loss)))\n return loss_fn\n\n\n def get_memory_loss_fn(self, args):\n if args.memory_loss == 'CrossEntropy':\n loss_fn = nn.CrossEntropyLoss()\n elif args.memory_loss == 'NLL':\n loss_fn = nn.NLLLoss()\n elif args.memory_loss == 'SmoothCrossEntropy':\n loss_fn = smooth_cross_entropy\n elif args.memory_loss == 'KL':\n loss_fn = nn.KLDivLoss()\n else:\n raise(NotImplementedError('unknown loss function: {}'.format(args.loss)))\n return loss_fn\n\n def cuda(self, x):\n if self.args.enable_gpu:\n return x.cuda(self.args.cuda_device)\n else:\n return x\n\n def train(self):\n self.model.train()\n if self.args.memory_reg > 0:\n self.prev_model.eval()\n all_losses = []\n all_memory_losses = []\n all_preds = self.cuda(torch.Tensor())\n all_labels = []\n self.teacher_scores_train = []\n self.teacher_seed_word_pred_train = []\n\n if args.scheduler_gamma > 0:\n self.scheduler.step()\n self.logger.info(\"Optimizing with lr={}\".format(self.optimizer.state_dict()['param_groups'][0]['lr']))\n\n if self.teacher.conf_mat is None:\n self.logger.info(\"TEACHER does NOT use confusion matrices\")\n else:\n self.logger.info(\"TEACHER uses confusion matrices\")\n for batch in self.datahandler.get_train_batches():\n self.optimizer.zero_grad()\n i = batch['ind']\n if (args.deep_aspect_clf in ['CNN', 'charCNN']) and i > batch['total'] - 20: #or\n # ignore really big segments when clf is CNN to avoid OOM error. \n break\n\n pred = self.model(batch)\n\n # I use different ids for the teacher, because if SWD=1, then the seed words are dropped from batch['ids']. \n teacher_scores, teacher_seed_word_pred = map(list, zip(*[self.teacher.predict_verbose(seg) for seg in batch['teacher_ids'].tolist()]))\n\n if self.args.loss not in [\"SmoothCrossEntropy\", \"KL\"]:\n label = np.argmax(teacher_scores, axis=1)\n all_labels.extend(list(label))\n label = self.cuda(Variable(torch.LongTensor(label)))\n else:\n # Convert the ground-truth aspect scores into probabilities summing to 1.\n label = teacher_scores\n all_labels.extend([np.argmax(l) for l in label])\n label = self.cuda(Variable(torch.Tensor(label)))\n label = F.softmax(label, dim=1)\n loss = self.loss_fn(pred, label)\n all_losses.append(loss.data.cpu().numpy())\n\n if args.memory_reg == 0.0:\n loss.backward()\n else:\n # Regularize the model to avoid forgetting the previous weights / predictions.\n prev_pred = F.softmax(self.prev_model(batch), dim=1)\n memory_loss = self.memory_loss(pred, prev_pred)\n all_memory_losses.append(memory_loss.data.cpu().numpy())\n total_loss = (1 - args.memory_reg) * loss + args.memory_reg * memory_loss\n loss += memory_loss\n total_loss.backward()\n\n self.optimizer.step()\n\n all_preds = torch.cat((all_preds, pred.data), dim=0)\n self.teacher_scores_train.extend(teacher_scores)\n self.teacher_seed_word_pred_train.extend(teacher_seed_word_pred)\n\n if (self.args.report_every != -1) and (i % self.args.report_every == 0) and (i > 0):\n avg_loss = np.mean(all_losses[-self.args.report_every:])\n avg_memory_loss = np.mean(all_memory_losses[-self.args.report_every:])\n if args.memory_reg == 0:\n self.logger.debug('[{}][{}:{}/{}]\\tLoss: {:f}'.format(self.args.domain, self.epoch, i, batch['total'], avg_loss))\n else:\n self.logger.debug('[{}][{}:{}/{}]\\tLoss: {:.5f}\\tMemory Loss: {:.5f}'.format(self.args.domain, self.epoch, i, batch['total'], avg_loss, avg_memory_loss))\n\n all_proba = all_preds.cpu().numpy()\n self.student_proba_train = all_proba\n max_prob, all_preds = all_preds.max(dim=1)\n all_preds = all_preds.cpu().numpy()\n avg_loss = np.mean(all_losses)\n res = self.evaluator.evaluate_group(all_preds, all_labels, all_proba, gt_classes=range(self.args.num_aspects),verbose=False)\n res['loss'] = avg_loss\n self.epoch_results['train'] = res\n self.writer.add_histogram('train_loss{}'.format(self.comment), np.array(all_losses), self.epoch, bins=100)\n\n # save disagreement\n s_pred_hard = np.argmax(self.student_proba_train, axis=1)\n t_pred_hard = np.argmax(self.teacher_scores_train, axis=1)\n self.disagreement = ((s_pred_hard != t_pred_hard).sum()) / float(s_pred_hard.shape[0])\n self.epoch_results['hard_disagreement'] = self.disagreement\n\n\n def update_teacher(self):\n # Use Maximum Likelihood Estimation to update the seed word confusion matrices.\n assert self.student_proba_train is not None, \"Student proba is None.\"\n assert self.teacher_scores_train is not None, \"Teacher scores is None.\"\n\n\n s_pred_hard = np.argmax(self.student_proba_train, axis=1)\n s_pred_soft = F.softmax(torch.Tensor(self.student_proba_train), dim=1).numpy()\n t_pred_hard = np.argmax(self.teacher_scores_train, axis=1)\n seed_word_occurences = np.array(self.teacher_seed_word_pred_train)\n teacher_answers = seed_word_occurences.sum(axis=1) > 0\n self.disagreement = ((s_pred_hard[teacher_answers] != t_pred_hard[teacher_answers]).sum()) / float(teacher_answers.sum())\n self.epoch_results['train_disagreement'] = self.disagreement\n\n K = self.args.num_aspects\n N = s_pred_hard.shape[0]\n\n # Initialize a zero confusion matrix for each seed word.\n conf_mat = {wid: np.zeros(K) for wid in self.teacher.seed_list}\n\n # Maximum Likelihood Estimation for the class priors\n self.q = np.array([np.sum(s_pred_hard == i) for i in range(K)]) / float(N)\n self.logger.info('Estimated class priors: {}'.format(\",\".join([\"{:.2f}\".format(x) for x in self.q])))\n\n # Maximum Likelihood Estimation for each confusion matrix\n for wid_i, wid in enumerate(self.teacher.seed_list):\n # keep the segments where this seed word has been activated\n relevant_ind = (seed_word_occurences[:, wid_i] > 0)\n pred_aspect = self.teacher.seed_dict[wid][0]\n\n if args.teacher_type == 'v1':\n # Precision-based updates\n if args.soft_updates == False:\n conf_mat[wid] = np.array([np.sum(s_pred_hard[relevant_ind]==i) / float(np.sum(relevant_ind)) for i in range(K)])\n else:\n conf_mat[wid] = np.array([s_pred_soft[relevant_ind][:, i].sum() for i in range(K)])\n conf_mat[wid] = conf_mat[wid] / float(conf_mat[wid].sum())\n elif args.teacher_type == 'v2':\n # Dawid-Skene model where each seed word is applied when it occurs in the segment\n # We allow positive mass to other aspects.\n conf_mat[wid][:] = self.args.pos_mass / float(K - 1)\n conf_mat[wid][pred_aspect] = 1 - self.args.pos_mass\n\n student_sum = s_pred_soft[relevant_ind].sum(axis=0) # adding student probabilities for all classes for all relevant samples\n conf_mat[wid] *= student_sum\n conf_mat[wid] /= conf_mat[wid].sum()\n else:\n raise(BaseException('{} not implemented'.format(args.teacher_type))) \n\n # GRADIENT EM\n prev_param = np.zeros(K)\n prev_param[pred_aspect] = 1\n conf_mat[wid] = self.args.teacher_memory * prev_param + (1 - self.args.teacher_memory) * conf_mat[wid] # (self.conf_mat[wid] + prev_param) / 2.0\n\n self.logger.info(\"Teacher answers on the {}% ({}/{}) of the training set\".format(100 * teacher_answers.sum() / teacher_answers.shape[0], teacher_answers.sum(), teacher_answers.shape[0]))\n self.logger.info(\"Student-Teacher disagreement: {}/{} ({:.2f}%)\".format((s_pred_hard[teacher_answers] != t_pred_hard[teacher_answers]).sum(), teacher_answers.sum(),100*self.disagreement))\n self.logger.info(\"Avg of seed word occurences in training set: {:.2f}\".format(np.average(seed_word_occurences.sum(axis=0))))\n\n self.conf_mat = conf_mat\n joblib.dump(self.conf_mat, self.args.logdir + 'conf_mat_{}.pkl'.format(self.epoch))\n joblib.dump(self.q, self.args.logdir + 'prior_{}.pkl'.format(self.epoch))\n\n return\n\n def validate(self):\n self.model.eval()\n all_losses = []\n all_preds = self.cuda(torch.Tensor())\n all_labels = []\n for batch in self.datahandler.get_eval_batches():\n i = batch['ind']\n pred = self.model(batch)\n label = batch['label']\n # import pdb; pdb.set_trace()\n if self.args.loss not in [\"SmoothCrossEntropy\", \"KL\"]:\n all_labels.extend(list(label))\n label = self.cuda(Variable(torch.LongTensor(label)))\n else:\n # Convert the ground-truth label into a one-hot label and treat is as a prob distribution\n all_labels.extend(list(label))\n one_hot = np.zeros((len(label), self.args.num_aspects))\n one_hot[np.arange(len(label)), label] = 1\n label = self.cuda(Variable(torch.Tensor(one_hot)))\n loss = self.loss_fn(pred, label)\n all_losses.append(loss.data.cpu().numpy())\n\n all_preds = torch.cat((all_preds, pred.data), dim=0)\n\n all_proba = all_preds.cpu().numpy()\n max_prob, all_preds = all_preds.max(dim=1)\n all_preds = all_preds.cpu().numpy()\n\n avg_loss = np.mean(all_losses)\n res = self.evaluator.evaluate_group(all_preds, all_labels, all_proba, gt_classes=range(self.args.num_aspects), verbose=False)\n res['loss'] = avg_loss\n if res[self.metric] >= self.best_score:\n # Save the best validation model\n self.best_score = res[self.metric]\n torch.save(self.model.state_dict(), os.path.join(self.args.logdir, 'best_valid_model.pt'))\n self.epoch_results['valid'] = res\n self.writer.add_histogram('valid_loss{}'.format(self.comment), np.array(all_losses), self.epoch, bins=100)\n self.flattened_valid_result_dict = self.evaluator.flattened_result_dict\n\n\n def validate_test(self):\n # Giannis: also validate on the test set\n self.model.eval()\n all_losses = []\n all_preds = self.cuda(torch.Tensor())\n all_labels = []\n for batch in self.datahandler.get_test_batches():\n i = batch['ind']\n pred = self.model(batch)\n label = batch['label']\n # import pdb; pdb.set_trace()\n if self.args.loss not in [\"SmoothCrossEntropy\", \"KL\"]:\n all_labels.extend(list(label))\n label = self.cuda(Variable(torch.LongTensor(label)))\n else:\n # Convert the ground-truth label into a one-hot label and treat is as a prob distribution\n all_labels.extend(list(label))\n one_hot = np.zeros((len(label), self.args.num_aspects))\n one_hot[np.arange(len(label)), label] = 1\n label = self.cuda(Variable(torch.Tensor(one_hot)))\n loss = self.loss_fn(pred, label)\n all_losses.append(loss.data.cpu().numpy())\n\n all_preds = torch.cat((all_preds, pred.data), dim=0)\n\n all_proba = all_preds.cpu().numpy()\n max_prob, all_preds = all_preds.max(dim=1)\n all_preds = all_preds.cpu().numpy()\n\n avg_loss = np.mean(all_losses)\n res = self.evaluator.evaluate_group(all_preds, all_labels, all_proba, gt_classes=range(self.args.num_aspects), verbose=False)\n res['loss'] = avg_loss\n if res[self.metric] >= self.best_test_score:\n # Save the best test model\n self.best_test_score = res[self.metric]\n torch.save(self.model.state_dict(), os.path.join(self.args.logdir, 'best_test_model.pt'))\n self.epoch_results['test'] = res\n self.writer.add_histogram('test_loss{}'.format(self.comment), np.array(all_losses), self.epoch, bins=100)\n self.flattened_test_result_dict = self.evaluator.flattened_result_dict\n\n\n def test(self, savename='results.pkl'):\n self.model.eval()\n all_preds = self.cuda(torch.Tensor())\n all_labels = []\n teacher_scores_test = []\n\n for batch in self.datahandler.get_test_batches():\n i = batch['ind']\n pred = self.model(batch)\n teacher_scores, teacher_seed_word_pred = map(list, zip(*[self.teacher.predict_verbose(seg) for seg in batch['ids'].tolist()]))\n label = batch['label']\n\n all_preds = torch.cat((all_preds, pred.data), dim=0)\n teacher_scores_test.extend(teacher_scores)\n all_labels.extend(list(label))\n\n all_proba = all_preds.cpu().numpy()\n max_prob, all_preds = all_preds.max(dim=1)\n all_preds = all_preds.cpu().numpy()\n\n res = self.evaluator.evaluate_group(all_preds, all_labels, all_proba, gt_classes=range(self.args.num_aspects),verbose=False)\n self.epoch_results['test'] = res\n\n\n teacher_scores_test = np.array(teacher_scores_test)\n teacher_preds = np.argmax(teacher_scores_test, axis=1)\n teacher_res = self.evaluator.evaluate_group(teacher_preds, all_labels, teacher_scores_test, gt_classes=range(self.args.num_aspects), verbose=False)\n self.epoch_results['teacher_test'] = teacher_res\n\n self.logger.info('Test {}:\\t STUDENT={:.3}\\t TEACHER={:.3}'.format(self.metric, res[self.metric], teacher_res[self.metric]))\n self.logger.info('Train disagreement: {}%'.format(100*self.disagreement))\n self.logger.info('STUDENT confusion Matrix:\\n{}'.format(res['conf_mat']))\n self.logger.info('TEACHER confusion Matrix:\\n{}'.format(teacher_res['conf_mat']))\n\n\n joblib.dump(res, os.path.join(self.args.logdir, savename))\n\n\n def start_epoch(self):\n # Do necessary staff at the beginning of each epoch\n self.epoch_results = {}\n return\n\n def end_epoch(self):\n # Do necessary staff at the end of each epoch\n self.writer.add_scalars('loss{}'.format(self.comment), {\n 'train_loss': self.epoch_results['train']['loss'],\n 'valid_loss': self.epoch_results['valid']['loss']}, self.epoch)\n score = self.epoch_results['valid'][self.metric]\n test_score = self.epoch_results['test'][self.metric]\n self.logger.info('{}: {:.3}'.format(self.metric, score))\n self.logger.info('{} (test): {:.3}'.format(self.metric, test_score))\n self.writer.add_scalars(self.metric, {self.args.domain: score}, self.epoch)\n self.writer.add_scalars('test_' + self.metric, {self.args.domain: score}, self.epoch)\n\n res_flattened = self.flattened_test_result_dict\n res_flattened['avg_prec'] = np.average(self.epoch_results['valid']['prec'])\n res_flattened['avg_rec'] = np.average(self.epoch_results['valid']['rec'])\n important_list = ['acc', 'avg_prec', 'avg_rec', 'macro_average_f1', 'micro_average_f1']\n self.writer.add_scalars('average_test_results{}'.format(self.comment), {x: res_flattened[x] for x in important_list}, self.epoch)\n self.writer.add_scalars('test_results{}'.format(self.comment), {x:res_flattened[x] for x in res_flattened if not 'conf' in x}, self.epoch)\n self.writer.add_scalars('test_conf_matrix{}'.format(self.comment), {x: res_flattened[x] for x in res_flattened if 'conf' in x}, self.epoch)\n\n self.results.append(self.epoch_results)\n joblib.dump(self.results, os.path.join(self.args.logdir, 'epoch_results.pkl')) # saving intermediate results\n return\n\n def close(self):\n self.writer.close()\n torch.save(self.model.state_dict(), os.path.join(self.args.logdir, 'last_model.pt'))\n joblib.dump(self.results, os.path.join(self.args.logdir, 'results.pkl'))\n self.logger.info(\"Process ended in {:.3f} s\".format(self.total_time))\n self.logger.info(\"Results stored at {}\".format(self.args.logdir))\n\n\n def process(self):\n self.total_time = 0\n self.test()\n\n for epoch in range(self.args.num_epochs):\n if epoch == 0:\n # Do not regularize the model in the first epochs until we start bootstrapping.\n mem_reg = self.args.memory_reg\n self.args.memory_reg = 0\n\n # Use CrossEntropyLoss with hard targets for the first epochs.\n target_loss_fn = self.args.loss\n elif epoch == self.args.bootstrap_epoch + 1:\n # When we're done with the burnout epochs, we restore the right cotraining parameters. \n if mem_reg > 0:\n self.logger.info(\"Adding prev_model regularization with mem_reg={}\".format(mem_reg))\n self.args.memory_reg = mem_reg\n self.prev_model.load_state_dict(deepcopy(self.model.state_dict()))\n self.logger.info(\"Switching to loss={}\".format(target_loss_fn))\n self.args.loss = target_loss_fn\n self.loss_fn = self.get_loss_fn(self.args)\n t0 = time()\n self.epoch = epoch\n self.start_epoch()\n\n self.train()\n\n if epoch >= self.args.bootstrap_epoch:\n self.update_teacher()\n if not args.fix_teacher:\n self.teacher.conf_mat = self.conf_mat\n self.teacher.prior = self.q\n\n self.validate()\n self.validate_test()\n epoch_time = time() - t0\n self.total_time += epoch_time\n self.logger.info(\"Epoch {} Done in {} s.\".format(self.epoch, epoch_time))\n self.epoch_results['time'] = epoch_time\n self.test()\n self.end_epoch()\n\n self.test()\n self.close()\n\n\ndef run_cotrain(args, domain):\n print(\"Running {}\".format(domain))\n args.domain = domain\n\n # Define output paths\n args.logdir += '/' + domain + '/'\n if not os.path.exists(args.logdir):\n os.mkdir(args.logdir)\n args.pretrained_model += '/' + domain + '/'\n args.student_folder = args.logdir + \\\n 'student' + \\\n '_{}'.format(args.loss) + \\\n '_lr{}'.format(args.lr) + \\\n '_memloss{}'.format(args.memory_loss) + \\\n '_memreg{}'.format(args.memory_reg)\n\n args.teacher_folder = args.logdir + \\\n 'teacher' + \\\n \"_{}\".format(args.teacher_type) + \\\n \"_memory{}\".format(args.teacher_memory)\n\n if not os.path.exists(args.student_folder):\n os.mkdir(args.student_folder)\n if not os.path.exists(args.teacher_folder):\n os.mkdir(args.teacher_folder)\n\n\n trainer = Trainer(args)\n trainer.process()\n return\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('domain', help=\"Domain name (without extension)\", type=str, default='pairs')\n\n # Trainer Specific\n parser.add_argument('--logdir', help=\"log directory for tensorboard\", type=str, default='../experiments/')\n parser.add_argument('--debug', help=\"Enable debug mode\", action='store_true')\n parser.add_argument('--num_epochs', help=\"Number of epochs (default: 25)\", type=int, default=5)\n parser.add_argument('--loss', help=\"Loss Function (CrossEntropy / NLL)\", type=str, default='CrossEntropy')\n parser.add_argument('--optimizer', help=\"Optimizer (Adam / Adadelta)\", type=str, default='Adam')\n parser.add_argument('--lr', help=\"Learning rate (default: 0.0001)\", type=float, default=0.00005)\n parser.add_argument('--weight_decay', help=\"Weight Decay\", type=float, default=0.0)\n parser.add_argument('--momentum', help=\"Momentum (used for optimizer=SGD)\", type=float, default=0.9)\n parser.add_argument('--report_every', help=\"Report every x number of batches\", type=int, default=50)\n parser.add_argument('--cuda_device', help=\"CUDA Device ID\", type=int, default=0)\n parser.add_argument('--batch_size', help=\"Batch Size\", type=int, default=1024)\n parser.add_argument('--target_metric', help=\"Target Metric to report\", type=str, default='micro_average_f1')\n parser.add_argument('--version', help=\"Run # (0..4)\", type=int, default=0)\n parser.add_argument('--memory_loss', help=\"Loss Function for the memory regularization term\", type=str, default='SmoothCrossEntropy')\n parser.add_argument('--memory_reg', help=\"Memory regularization (not forget the previous model)\", type=float, default=0.0)\n parser.add_argument('--teacher_memory', help=\"Teacher memory (not forget the initial teacher model)\", type=float, default=0.0)\n parser.add_argument('--scheduler_gamma', help=\"Scheduler's multiplier of lr in each epoch\", type=float, default=0.1)\n parser.add_argument('--bootstrap_epoch', help=\"Epoch at which we start the teacher updates\", type=int, default=0)\n parser.add_argument('--disable_gpu', help=\"Disable GPU\", action='store_true')\n\n # Domain Specific\n parser.add_argument('--test_data', help=\"hdf5 file of test segments\", type=str, default='')\n parser.add_argument('--min_len', help=\"Minimum number of non-stop-words in segment (default: 2)\", type=int, default=2)\n parser.add_argument('--num_aspects', help=\"Number of aspects (default: 9)\", type=int, default=9)\n parser.add_argument('--aspect_seeds', help='file that contains aspect seed words (overrides number of aspects)', type=str, default='')\n parser.add_argument('-q', '--quiet', help=\"No information to stdout\", action='store_true')\n parser.add_argument('--num_seeds', help=\"Number of seed words to use (default: 30)\", type=int, default=30)\n parser.add_argument('--no_seed_weights', help=\"Forcing the *unweighted* avg of seed word embeddings\", action='store_true')\n parser.add_argument('--batch_norm', help=\"Batch normalization on segment encodings\", action='store_true')\n parser.add_argument('--emb_dropout', help=\"Dropout at the segment embedding layer\", type=float, default=0.0)\n parser.add_argument('--swd', help=\"Seed Word Dropout (default=0.0 i.e., never drop the seed word)\", type=float, default=0.0)\n parser.add_argument('--no_pretrained_emb', help=\"Do NOT use pre-trained word embeddings\", action='store_true')\n parser.add_argument('--use_bert', help=\"Use BERT (base uncased) for segment embedding\", action='store_true')\n parser.add_argument('--bert_model', help=\"Type of BERT model: base/large\", type=str, default='base')\n parser.add_argument('--simple_aspects', help=\"Use fine/coarse grained aspects (-1: original A#B label, 0: first part, 1: second part of A#B label\", type=int, default=-1)\n\n\n # Model Specific\n parser.add_argument('--pretrained_model', help=\"Pre-trained model\", type=str, default='')\n parser.add_argument('--attention', help=\"Use word attention\", action='store_true')\n parser.add_argument('--fix_w_emb', help=\"Fix word embeddings\", action='store_true')\n parser.add_argument('--fix_a_emb', help=\"Fix aspect embeddings\", action='store_true')\n parser.add_argument('--model_type', help=\"Model type (embedding_based vs bow_based)\", type=str, default='embedding_based')\n parser.add_argument('--deep_aspect_clf', help=\"Use a deep CLF on top of word embeddings\", type=str, default='NO')\n parser.add_argument('--teacher_type', help=\"Teacher Type (v1..3)\", type=str, default='v1')\n parser.add_argument('--pos_mass', help=\"Probability mass to cut from the given aspect and distribute to the remaining aspects\", type=float, default=0.2)\n parser.add_argument('--soft_updates', help=\"Soft (instead of hard) teacher (precision-based) updates (only for v1)\", action='store_true')\n parser.add_argument('--hard_teacher_pred', help=\"Hard aspect predictions per seed word (only the most probable aspect)\", action='store_true')\n parser.add_argument('--fix_teacher', help=\"Fix teacher throughout training (instead of updating)\", action='store_true')\n\n args = parser.parse_args()\n args.enable_gpu = not args.disable_gpu\n\n seeds = [20, 7, 1993, 42, 127]\n args.seed = seeds[args.version]\n torch.cuda.manual_seed(args.seed)\n seed(args.seed)\n args.num_epochs += args.bootstrap_epoch\n\n if args.logdir == '../experiments/':\n args.logdir += datetime.now().strftime('%b%d_%H-%M-%S') + '_'\n\n if args.debug:\n args.logdir = './debug'\n if os.path.exists(args.logdir):\n os.system('rm -rf {}'.format(args.logdir))\n else:\n args.logdir = args.logdir + \\\n \"COTRAINING\" + \\\n \"_att{}\".format(args.attention) + \\\n \"_fixw{}\".format(args.fix_w_emb) + \\\n \"_fixa{}\".format(args.fix_a_emb) + \\\n \"_{}\".format(args.loss) + \\\n \"_lr{}\".format(args.lr) + \\\n \"_dropout{}\".format(args.emb_dropout) + \\\n '_memloss{}'.format(args.memory_loss) + \\\n '_memreg{}'.format(args.memory_reg) + \\\n \"_teacher{}\".format(args.teacher_type) + \\\n \"_tmem{}\".format(args.teacher_memory) + \\\n '_schedgamma{}'.format(args.scheduler_gamma) + \\\n \"_bepoch{}\".format(args.bootstrap_epoch)\n\n if not os.path.exists(args.logdir):\n os.mkdir(args.logdir)\n original_logdir = args.logdir\n args.logdir += '/v{}'.format(args.version)\n if not os.path.exists(args.logdir):\n os.mkdir(args.logdir)\n args.pretrained_model += '/v{}'.format(args.version)\n\n\n print('\\t\\tEXPERIMENT with domain={}\\nargs: {}\\nlogdir: {}'.format(args.domain, args, args.logdir))\n run_cotrain(args, args.domain)\n"
] | [
[
"torch.nn.NLLLoss",
"numpy.sum",
"torch.Tensor",
"numpy.zeros",
"torch.cuda.manual_seed",
"torch.nn.functional.softmax",
"numpy.random.seed",
"numpy.argmax",
"torch.cuda.device_count",
"torch.nn.CrossEntropyLoss",
"torch.nn.KLDivLoss",
"torch.cuda.is_available",
"torch.optim.lr_scheduler.MultiStepLR",
"numpy.array",
"torch.LongTensor",
"numpy.average",
"torch.cat",
"numpy.mean"
]
] |
1Stohk1/tami | [
"e0aa902bb767631dd2435ed0eac05209b9bd64ed"
] | [
"models_code/nedo.py"
] | [
"from tensorflow.keras import layers\nfrom tensorflow.keras import models\nfrom tensorflow.keras.metrics import Precision, Recall, AUC\n\n\nclass NEDO:\n\n def __init__(self, num_classes, img_size, channels, name=\"nedo\"):\n self.name = name\n self.num_classes = num_classes\n self.input_width_height = img_size\n self.channels = channels\n self.input_type = 'images'\n\n def build(self):\n model = models.Sequential()\n model.add(layers.Conv2D(64, (3, 3), activation='relu', input_shape=(self.input_width_height,\n self.input_width_height,\n self.channels)))\n model.add(layers.MaxPooling2D((2, 2)))\n model.add(layers.Conv2D(96, (3, 3), activation='relu'))\n model.add(layers.MaxPooling2D((2, 2)))\n model.add(layers.Conv2D(128, (3, 3), activation='relu'))\n model.add(layers.MaxPooling2D((2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dropout(0.45))\n model.add(layers.Dense(1024, activation='relu'))\n model.add(layers.Dropout(0.35))\n model.add(layers.Dense(512, activation='relu'))\n model.add(layers.Dense(self.num_classes, activation='softmax'))\n\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['acc', Precision(name=\"prec\"), Recall(name=\"rec\"), AUC(name='auc')])\n\n return model\n\n def build_tuning(self, hp):\n\n model = models.Sequential()\n model.add(layers.Conv2D(hp.Int('filters_1', 16, 128, step=16), (3, 3), activation='relu',\n input_shape=(self.input_width_height, self.input_width_height, self.channels)))\n model.add(layers.MaxPooling2D((2, 2)))\n for i in range(hp.Int('conv_blocks', 2, 5, default=3)):\n model.add(layers.Conv2D(hp.Int('filters_' + str(i), 32, 256, step=32), (3, 3), activation='relu'))\n model.add(layers.MaxPooling2D((2, 2)))\n #if hp.Choice('pooling_' + str(i), ['avg', 'max']) == 'max':\n # x = tf.keras.layers.MaxPool2D()(x)\n #else:\n # x = tf.keras.layers.AvgPool2D()(x)\n model.add(layers.Flatten())\n model.add(layers.Dropout(hp.Float('dropout', 0, 0.7, step=0.1, default=0.5)))\n model.add(layers.Dense(hp.Int('hidden_size', 512, 1024, step=128, default=512), activation='relu'))\n model.add(layers.Dropout(hp.Float('dropout', 0, 0.7, step=0.1, default=0.5)))\n model.add(layers.Dense(hp.Int('hidden_size', 128, 512, step=128, default=512), activation='relu'))\n model.add(layers.Dense(self.num_classes, activation='softmax'))\n # activation=hp.Choice('act_1', ['relu', 'tanh'])\n\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['acc', Precision(name=\"prec\"), Recall(name=\"rec\"), AUC(name='auc')])\n\n return model\n"
] | [
[
"tensorflow.keras.metrics.Recall",
"tensorflow.keras.models.Sequential",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.metrics.Precision",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.metrics.AUC"
]
] |
ArgonneCPAC/bnlhack19 | [
"d399b2e200ec7dbd733c754b06c4bd368eb00e67"
] | [
"scripts/demo_cupy_rawkernel.py"
] | [
"import os, sys\n\nimport cupy as cp\nimport numpy as np\nfrom numba import cuda\n\nfrom chopperhack19.mock_obs.tests import random_weighted_points\nfrom chopperhack19.mock_obs.tests.generate_test_data import (\n DEFAULT_RBINS_SQUARED)\nfrom chopperhack19.mock_obs import chaining_mesh as cm\nfrom chopperhack19.mock_obs.double_chop_kernel import double_chop_pairs_cuda\n\n########################################################################\n# This demo shows how to compile a CUDA .cu file, load a particular CUDA\n# kernel, launch it with CuPy arrays. Also shows how to make CuPy and \n# Numba work together\n########################################################################\n\n\nfilepath = os.path.abspath(os.path.join(__file__, \"../../chopperhack19/mock_obs/double_chop_kernel.cu\"))\nwith open(filepath) as f:\n source_code = f.read()\n\n# compile and load CUDA kernel using CuPy\n# before CuPy v7.0.0b3:\n# in this case, compilation happens at the first invocation of the kernel, \n# not the declaration time\ndouble_chop_kernel = cp.RawKernel(source_code, 'double_chop_pairs_pure_cuda')\n\n## starting CuPy v7.0.0b3:\n## RawModule is suitable for importing a large CUDA codebase\n## the compilation happens when initializing the RawModule instance\n#mod = cp.RawModule(source_code)\n#double_chop_kernel = mod.get_function('double_chop_pairs_pure_cuda')\n\n# parameters\nblocks = 512\nthreads = 512\nnpoints = 200013\nnmesh1 = 4\nnmesh2 = 16\n\nLbox = 1000.\n\n# array init\n# CuPy functionalities should be used to avoid unnecessary computation\n# and transfer, which I didn't do here as it's midnight...\nresult = np.zeros_like(DEFAULT_RBINS_SQUARED)[:-1].astype(cp.float32)\n\nn1 = npoints\nn2 = npoints\nx1, y1, z1, w1 = random_weighted_points(n1, Lbox, 0)\nx2, y2, z2, w2 = random_weighted_points(n2, Lbox, 1)\n\nnx1 = nmesh1\nny1 = nmesh1\nnz1 = nmesh1\nnx2 = nmesh2\nny2 = nmesh2\nnz2 = nmesh2\nrmax_x = np.sqrt(DEFAULT_RBINS_SQUARED[-1])\nrmax_y = rmax_x\nrmax_z = rmax_y\nxperiod = Lbox\nyperiod = Lbox\nzperiod = Lbox\n(x1out, y1out, z1out, w1out, cell1out,\n x2out, y2out, z2out, w2out, indx2) = (\n cm.get_double_chopped_data(\n x1, y1, z1, w1, x2, y2, z2, w2, nx1, ny1, nz1, nx2, ny2, nz2,\n rmax_x, rmax_y, rmax_z, xperiod, yperiod, zperiod))\n\nd_x1 = cp.asarray(x1out, dtype=cp.float32)\nd_y1 = cp.asarray(y1out, dtype=cp.float32)\nd_z1 = cp.asarray(z1out, dtype=cp.float32)\nd_w1 = cp.asarray(w1out, dtype=cp.float32)\nd_cell1out = cp.asarray(cell1out, dtype=cp.int32)\n\nd_x2 = cp.asarray(x2out, dtype=cp.float32)\nd_y2 = cp.asarray(y2out, dtype=cp.float32)\nd_z2 = cp.asarray(z2out, dtype=cp.float32)\nd_w2 = cp.asarray(w2out, dtype=cp.float32)\nd_indx2 = cp.asarray(indx2, dtype=cp.int32)\n\nd_rbins_squared = cp.asarray(DEFAULT_RBINS_SQUARED, dtype=cp.float32)\nd_result = cp.asarray(result, dtype=cp.float32)\n\n# for GPU timing using CuPy\nstart = cp.cuda.Event()\nend = cp.cuda.Event()\ntiming_cp = 0\n\n# running the kernel using CuPy's functionality\nfor i in range(4):\n d_result[...] = 0.\n if i > 0: # warm-up not needed if using RawModule\n start.record()\n double_chop_kernel((blocks,), (threads,),\n (d_x1, d_y1, d_z1, d_w1, d_cell1out,\n d_x2, d_y2, d_z2, d_w2, d_indx2,\n d_rbins_squared, d_result,\n cp.int32(d_x1.shape[0]), cp.int32(d_rbins_squared.shape[0]))\n )\n if i > 0: # warm-up not needed if using RawModule\n end.record()\n end.synchronize()\n timing_cp += cp.cuda.get_elapsed_time(start, end)\n#cp.cuda.Stream.null.synchronize()\nprint('launching CUDA kernel from CuPy took', timing_cp/3, 'ms in average')\nd_result_cp = d_result.copy()\n\n# for GPU timing using Numba\nstart = cuda.event()\nend = cuda.event()\ntiming_nb = 0\n\n# running the Numba jit kernel\n# this works because CuPy arrays have the __cuda_array_interface__ attribute,\n# which is accepted by Numba kernels, so you don't have to create the arrays\n# again using Numba's API\nfor i in range(4):\n d_result[...] = 0.\n if i > 0:\n start.record()\n double_chop_pairs_cuda[blocks, threads](d_x1, d_y1, d_z1, d_w1, d_cell1out,\n d_x2, d_y2, d_z2, d_w2, d_indx2,\n d_rbins_squared, d_result)\n if i > 0:\n end.record()\n end.synchronize()\n timing_nb += cuda.event_elapsed_time(start, end)\nprint('launching Numba jit kernel took', timing_nb/3, 'ms in average')\nd_result_nb = d_result.copy()\n\n# check that the CUDA kernel agrees with the Numba kernel\nassert cp.allclose(d_result_cp, d_result_nb, rtol=5E-4)\n"
] | [
[
"numpy.sqrt",
"numpy.zeros_like"
]
] |
fdlm/ignite | [
"a22a0f5e909ac70d2a1f76a60b6e84b2134f196c"
] | [
"tests/ignite/contrib/engines/test_common.py"
] | [
"import os\n\nimport torch\nimport torch.nn as nn\n\nfrom ignite.engine import Events, Engine\nfrom ignite.contrib.engines.common import (\n setup_common_training_handlers,\n save_best_model_by_val_score,\n add_early_stopping_by_val_score,\n setup_tb_logging,\n setup_visdom_logging,\n)\n\nfrom ignite.handlers import TerminateOnNan\nimport ignite.contrib.handlers.tensorboard_logger as tb_logger_module\nimport ignite.contrib.handlers.visdom_logger as visdom_logger_module\n\nimport pytest\nfrom unittest.mock import MagicMock\n\n\nclass DummyModel(nn.Module):\n def __init__(self):\n super(DummyModel, self).__init__()\n self.net = nn.Linear(1, 1)\n\n def forward(self, x):\n return self.net(x)\n\n\[email protected]\ndef visdom_server():\n\n import time\n import subprocess\n\n from visdom.server import download_scripts\n\n download_scripts()\n\n hostname = \"localhost\"\n port = 8099\n p = subprocess.Popen(\"visdom --hostname {} -port {}\".format(hostname, port), shell=True)\n time.sleep(5)\n yield (hostname, port)\n p.terminate()\n\n\ndef _test_setup_common_training_handlers(dirname, device, rank=0, local_rank=0, distributed=False):\n\n lr = 0.01\n step_size = 100\n gamma = 0.5\n\n model = DummyModel().to(device)\n if distributed:\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank,], output_device=local_rank)\n optimizer = torch.optim.SGD(model.parameters(), lr=lr)\n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=step_size, gamma=gamma)\n\n def update_fn(engine, batch):\n optimizer.zero_grad()\n x = torch.tensor([batch], requires_grad=True, device=device)\n y_pred = model(x)\n loss = y_pred.mean()\n loss.backward()\n optimizer.step()\n return loss\n\n train_sampler = MagicMock()\n train_sampler.set_epoch = MagicMock()\n\n trainer = Engine(update_fn)\n setup_common_training_handlers(\n trainer,\n train_sampler=train_sampler,\n to_save={\"model\": model, \"optimizer\": optimizer},\n save_every_iters=75,\n output_path=dirname,\n lr_scheduler=lr_scheduler,\n with_gpu_stats=False,\n output_names=[\"batch_loss\",],\n with_pbars=True,\n with_pbar_on_iters=True,\n log_every_iters=50,\n device=device,\n )\n\n num_iters = 100\n num_epochs = 10\n data = [i * 0.1 for i in range(num_iters)]\n trainer.run(data, max_epochs=num_epochs)\n\n # check handlers\n handlers = trainer._event_handlers[Events.ITERATION_COMPLETED]\n for cls in [\n TerminateOnNan,\n ]:\n assert any([isinstance(h[0], cls) for h in handlers]), \"{}\".format(handlers)\n assert \"batch_loss\" in trainer.state.metrics\n\n # Check saved checkpoint\n if rank == 0:\n checkpoints = list(os.listdir(dirname))\n assert len(checkpoints) == 1\n for v in [\n \"training_checkpoint\",\n ]:\n assert any([v in c for c in checkpoints])\n\n # Check LR scheduling\n assert optimizer.param_groups[0][\"lr\"] <= lr * gamma ** (num_iters * num_epochs / step_size), \"{} vs {}\".format(\n optimizer.param_groups[0][\"lr\"], lr * gamma ** (num_iters * num_epochs / step_size)\n )\n\n\ndef test_asserts_setup_common_training_handlers():\n trainer = Engine(lambda e, b: None)\n\n with pytest.raises(\n ValueError, match=r\"If to_save argument is provided then output_path argument should be \" r\"also defined\"\n ):\n setup_common_training_handlers(trainer, to_save={})\n\n with pytest.warns(\n UserWarning, match=r\"Argument train_sampler distributed sampler used to call \" r\"`set_epoch` method on epoch\"\n ):\n train_sampler = MagicMock()\n setup_common_training_handlers(trainer, train_sampler=train_sampler, with_gpu_stats=False)\n\n\ndef test_setup_common_training_handlers(dirname, capsys):\n\n _test_setup_common_training_handlers(dirname, device=\"cpu\")\n\n # Check epoch-wise pbar\n captured = capsys.readouterr()\n out = captured.err.split(\"\\r\")\n out = list(map(lambda x: x.strip(), out))\n out = list(filter(None, out))\n assert \"Epoch:\" in out[-1], \"{}\".format(out[-1])\n\n\ndef test_save_best_model_by_val_score(dirname, capsys):\n\n trainer = Engine(lambda e, b: None)\n evaluator = Engine(lambda e, b: None)\n model = DummyModel()\n\n acc_scores = [0.1, 0.2, 0.3, 0.4, 0.3, 0.5, 0.6, 0.61, 0.7, 0.5]\n\n @trainer.on(Events.EPOCH_COMPLETED)\n def validate(engine):\n evaluator.run(\n [0,]\n )\n\n @evaluator.on(Events.EPOCH_COMPLETED)\n def set_eval_metric(engine):\n engine.state.metrics = {\"acc\": acc_scores[trainer.state.epoch - 1]}\n\n save_best_model_by_val_score(dirname, evaluator, model, metric_name=\"acc\", n_saved=2, trainer=trainer)\n\n data = [\n 0,\n ]\n trainer.run(data, max_epochs=len(acc_scores))\n\n assert set(os.listdir(dirname)) == set([\"best_model_8_val_acc=0.6100.pth\", \"best_model_9_val_acc=0.7000.pth\"])\n\n\ndef test_add_early_stopping_by_val_score():\n trainer = Engine(lambda e, b: None)\n evaluator = Engine(lambda e, b: None)\n\n acc_scores = [0.1, 0.2, 0.3, 0.4, 0.3, 0.3, 0.2, 0.1, 0.1, 0.0]\n\n @trainer.on(Events.EPOCH_COMPLETED)\n def validate(engine):\n evaluator.run(\n [0,]\n )\n\n @evaluator.on(Events.EPOCH_COMPLETED)\n def set_eval_metric(engine):\n engine.state.metrics = {\"acc\": acc_scores[trainer.state.epoch - 1]}\n\n add_early_stopping_by_val_score(patience=3, evaluator=evaluator, trainer=trainer, metric_name=\"acc\")\n\n data = [\n 0,\n ]\n state = trainer.run(data, max_epochs=len(acc_scores))\n\n assert state.epoch == 7\n\n\ndef test_setup_tb_logging(dirname):\n def _test(with_eval, with_optim):\n trainer = Engine(lambda e, b: b)\n evaluators = None\n optimizers = None\n\n if with_eval:\n evaluator = Engine(lambda e, b: None)\n acc_scores = [0.1, 0.2, 0.3, 0.4, 0.3, 0.3, 0.2, 0.1, 0.1, 0.0]\n\n @trainer.on(Events.EPOCH_COMPLETED)\n def validate(engine):\n evaluator.run(\n [0,]\n )\n\n @evaluator.on(Events.EPOCH_COMPLETED)\n def set_eval_metric(engine):\n engine.state.metrics = {\"acc\": acc_scores[trainer.state.epoch - 1]}\n\n evaluators = {\"validation\": evaluator}\n\n if with_optim:\n t = torch.tensor([0,])\n optimizers = {\"optimizer\": torch.optim.SGD([t,], lr=0.01)}\n\n setup_tb_logging(dirname, trainer, optimizers=optimizers, evaluators=evaluators, log_every_iters=1)\n\n handlers = trainer._event_handlers[Events.ITERATION_COMPLETED]\n for cls in [\n tb_logger_module.OutputHandler,\n ]:\n assert any([isinstance(h[0], cls) for h in handlers]), \"{}\".format(handlers)\n\n if with_optim:\n handlers = trainer._event_handlers[Events.ITERATION_STARTED]\n for cls in [\n tb_logger_module.OptimizerParamsHandler,\n ]:\n assert any([isinstance(h[0], cls) for h in handlers]), \"{}\".format(handlers)\n\n if with_eval:\n handlers = evaluator._event_handlers[Events.COMPLETED]\n for cls in [\n tb_logger_module.OutputHandler,\n ]:\n assert any([isinstance(h[0], cls) for h in handlers]), \"{}\".format(handlers)\n\n data = [0, 1, 2]\n trainer.run(data, max_epochs=10)\n\n tb_files = list(os.listdir(dirname))\n assert len(tb_files) == 1\n for v in [\n \"events\",\n ]:\n assert any([v in c for c in tb_files]), \"{}\".format(tb_files)\n\n _test(with_eval=False, with_optim=False)\n _test(with_eval=True, with_optim=True)\n\n\ndef test_setup_visdom_logging(visdom_server):\n def _test(with_eval, with_optim):\n trainer = Engine(lambda e, b: b)\n evaluators = None\n optimizers = None\n\n if with_eval:\n evaluator = Engine(lambda e, b: None)\n acc_scores = [0.1, 0.2, 0.3, 0.4, 0.3, 0.3, 0.2, 0.1, 0.1, 0.0]\n\n @trainer.on(Events.EPOCH_COMPLETED)\n def validate(engine):\n evaluator.run(\n [0,]\n )\n\n @evaluator.on(Events.EPOCH_COMPLETED)\n def set_eval_metric(engine):\n engine.state.metrics = {\"acc\": acc_scores[trainer.state.epoch - 1]}\n\n evaluators = {\"validation\": evaluator}\n\n if with_optim:\n t = torch.tensor([0,])\n optimizers = {\"optimizer\": torch.optim.SGD([t,], lr=0.01)}\n\n # import os\n # os.environ[\"VISDOM_SERVER_URL\"] = visdom_server[0]\n # os.environ[\"VISDOM_PORT\"] = str(visdom_server[1])\n\n vis_logger = setup_visdom_logging(\n trainer,\n optimizers=optimizers,\n evaluators=evaluators,\n log_every_iters=1,\n server=visdom_server[0],\n port=str(visdom_server[1]),\n )\n\n handlers = trainer._event_handlers[Events.ITERATION_COMPLETED]\n for cls in [\n visdom_logger_module.OutputHandler,\n ]:\n assert any([isinstance(h[0], cls) for h in handlers]), \"{}\".format(handlers)\n\n if with_optim:\n handlers = trainer._event_handlers[Events.ITERATION_STARTED]\n for cls in [\n visdom_logger_module.OptimizerParamsHandler,\n ]:\n assert any([isinstance(h[0], cls) for h in handlers]), \"{}\".format(handlers)\n\n if with_eval:\n handlers = evaluator._event_handlers[Events.COMPLETED]\n for cls in [\n visdom_logger_module.OutputHandler,\n ]:\n assert any([isinstance(h[0], cls) for h in handlers]), \"{}\".format(handlers)\n\n data = [0, 1, 2]\n trainer.run(data, max_epochs=10)\n return vis_logger\n\n vis_logger_optim = _test(with_eval=False, with_optim=False)\n vis_logger_all = _test(with_eval=True, with_optim=True)\n\n vis_logger_optim.close()\n vis_logger_all.close()\n\n\[email protected]\[email protected](torch.cuda.device_count() < 1, reason=\"Skip if no GPU\")\ndef test_distrib_gpu(dirname, distributed_context_single_node_nccl):\n local_rank = distributed_context_single_node_nccl[\"local_rank\"]\n device = \"cuda:{}\".format(local_rank)\n _test_setup_common_training_handlers(dirname, device, rank=local_rank, local_rank=local_rank, distributed=True)\n test_add_early_stopping_by_val_score()\n\n\[email protected]\ndef test_distrib_cpu(dirname, distributed_context_single_node_gloo):\n device = \"cpu\"\n local_rank = distributed_context_single_node_gloo[\"local_rank\"]\n _test_setup_common_training_handlers(dirname, device, rank=local_rank)\n test_add_early_stopping_by_val_score()\n\n\[email protected]_distributed\[email protected](\"MULTINODE_DISTRIB\" not in os.environ, reason=\"Skip if not multi-node distributed\")\ndef test_multinode_distrib_cpu(dirname, distributed_context_multi_node_gloo):\n device = \"cpu\"\n rank = distributed_context_multi_node_gloo[\"rank\"]\n _test_setup_common_training_handlers(dirname, device, rank=rank)\n test_add_early_stopping_by_val_score()\n\n\[email protected]_distributed\[email protected](\"GPU_MULTINODE_DISTRIB\" not in os.environ, reason=\"Skip if not multi-node distributed\")\ndef test_multinode_distrib_gpu(dirname, distributed_context_multi_node_nccl):\n local_rank = distributed_context_multi_node_nccl[\"local_rank\"]\n rank = distributed_context_multi_node_nccl[\"rank\"]\n device = \"cuda:{}\".format(local_rank)\n _test_setup_common_training_handlers(dirname, device, rank=rank, local_rank=local_rank, distributed=True)\n test_add_early_stopping_by_val_score()\n"
] | [
[
"torch.nn.Linear",
"torch.optim.SGD",
"torch.tensor",
"torch.cuda.device_count",
"torch.nn.parallel.DistributedDataParallel",
"torch.optim.lr_scheduler.StepLR"
]
] |
stjordanis/catalyst-1 | [
"84bc7576c981278f389279d87dda85dd66a758b6"
] | [
"catalyst/contrib/datasets/mnist.py"
] | [
"from typing import Any, Callable, Dict, List, Optional\nimport os\n\nimport torch\nfrom torch.utils.data import Dataset\n\nfrom catalyst.contrib.datasets.functional import (\n download_and_extract_archive,\n read_sn3_pascalvincent_tensor,\n)\nfrom catalyst.data.dataset.metric_learning import MetricLearningTrainDataset, QueryGalleryDataset\n\n\ndef _read_label_file(path):\n with open(path, \"rb\") as f:\n x = read_sn3_pascalvincent_tensor(f, strict=False)\n assert x.dtype == torch.uint8\n assert x.ndimension() == 1\n return x.long()\n\n\ndef _read_image_file(path):\n with open(path, \"rb\") as f:\n x = read_sn3_pascalvincent_tensor(f, strict=False)\n assert x.dtype == torch.uint8\n assert x.ndimension() == 3\n return x\n\n\nclass MNIST(Dataset):\n \"\"\"`MNIST <http://yann.lecun.com/exdb/mnist/>`_ Dataset.\"\"\"\n\n _repr_indent = 4\n\n # CVDF mirror of http://yann.lecun.com/exdb/mnist/\n resources = [\n (\n \"https://storage.googleapis.com/cvdf-datasets/mnist/train-images-idx3-ubyte.gz\",\n \"f68b3c2dcbeaaa9fbdd348bbdeb94873\",\n ),\n (\n \"https://storage.googleapis.com/cvdf-datasets/mnist/train-labels-idx1-ubyte.gz\",\n \"d53e105ee54ea40749a09fcbcd1e9432\",\n ),\n (\n \"https://storage.googleapis.com/cvdf-datasets/mnist/t10k-images-idx3-ubyte.gz\",\n \"9fb629c4189551a2d022fa330f9573f3\",\n ),\n (\n \"https://storage.googleapis.com/cvdf-datasets/mnist/t10k-labels-idx1-ubyte.gz\",\n \"ec29112dd5afa0611ce80d1b7f02629c\",\n ),\n ]\n\n training_file = \"training.pt\"\n test_file = \"test.pt\"\n classes = [\n \"0 - zero\",\n \"1 - one\",\n \"2 - two\",\n \"3 - three\",\n \"4 - four\",\n \"5 - five\",\n \"6 - six\",\n \"7 - seven\",\n \"8 - eight\",\n \"9 - nine\",\n ]\n\n def __init__(self, root, train=True, transform=None, target_transform=None, download=False):\n \"\"\"\n Args:\n root: Root directory of dataset where\n ``MNIST/processed/training.pt``\n and ``MNIST/processed/test.pt`` exist.\n train (bool, optional): If True, creates dataset from\n ``training.pt``, otherwise from ``test.pt``.\n download (bool, optional): If true, downloads the dataset from\n the internet and puts it in root directory. If dataset\n is already downloaded, it is not downloaded again.\n transform (callable, optional): A function/transform that\n takes in an image and returns a transformed version.\n target_transform (callable, optional): A function/transform\n that takes in the target and transforms it.\n \"\"\"\n if isinstance(root, torch._six.string_classes):\n root = os.path.expanduser(root)\n self.root = root\n self.train = train # training set or test set\n self.transform = transform\n self.target_transform = target_transform\n\n if download:\n self.download()\n\n if not self._check_exists():\n raise RuntimeError(\"Dataset not found. You can use download=True to download it\")\n\n if self.train:\n data_file = self.training_file\n else:\n data_file = self.test_file\n self.data, self.targets = torch.load(os.path.join(self.processed_folder, data_file))\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index: Index\n\n Returns:\n tuple: (image, target) where target is index of the target class.\n \"\"\"\n img, target = self.data[index].numpy(), int(self.targets[index])\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n\n def __len__(self):\n \"\"\"@TODO: Docs. Contribution is welcome.\"\"\"\n return len(self.data)\n\n def __repr__(self):\n \"\"\"@TODO: Docs. Contribution is welcome.\"\"\"\n head = \"Dataset \" + self.__class__.__name__\n body = [\"Number of datapoints: {}\".format(self.__len__())]\n if self.root is not None:\n body.append(\"Root location: {}\".format(self.root))\n body += self.extra_repr().splitlines()\n if hasattr(self, \"transforms\") and self.transforms is not None:\n body += [repr(self.transforms)]\n lines = [head] + [\" \" * self._repr_indent + line for line in body]\n return \"\\n\".join(lines)\n\n @property\n def raw_folder(self):\n \"\"\"@TODO: Docs. Contribution is welcome.\"\"\"\n return os.path.join(self.root, self.__class__.__name__, \"raw\")\n\n @property\n def processed_folder(self):\n \"\"\"@TODO: Docs. Contribution is welcome.\"\"\"\n return os.path.join(self.root, self.__class__.__name__, \"processed\")\n\n @property\n def class_to_idx(self):\n \"\"\"@TODO: Docs. Contribution is welcome.\"\"\"\n return {_class: i for i, _class in enumerate(self.classes)}\n\n def _check_exists(self):\n return os.path.exists(\n os.path.join(self.processed_folder, self.training_file)\n ) and os.path.exists(os.path.join(self.processed_folder, self.test_file))\n\n def download(self):\n \"\"\"Download the MNIST data if it doesn't exist in processed_folder.\"\"\"\n if self._check_exists():\n return\n\n os.makedirs(self.raw_folder, exist_ok=True)\n os.makedirs(self.processed_folder, exist_ok=True)\n\n # download files\n for url, md5 in self.resources:\n filename = url.rpartition(\"/\")[2]\n download_and_extract_archive(\n url, download_root=self.raw_folder, filename=filename, md5=md5\n )\n\n # process and save as torch files\n print(\"Processing...\")\n\n training_set = (\n _read_image_file(os.path.join(self.raw_folder, \"train-images-idx3-ubyte\")),\n _read_label_file(os.path.join(self.raw_folder, \"train-labels-idx1-ubyte\")),\n )\n test_set = (\n _read_image_file(os.path.join(self.raw_folder, \"t10k-images-idx3-ubyte\")),\n _read_label_file(os.path.join(self.raw_folder, \"t10k-labels-idx1-ubyte\")),\n )\n with open(os.path.join(self.processed_folder, self.training_file), \"wb\") as f:\n torch.save(training_set, f)\n with open(os.path.join(self.processed_folder, self.test_file), \"wb\") as f:\n torch.save(test_set, f)\n\n print(\"Done!\")\n\n def extra_repr(self):\n \"\"\"@TODO: Docs. Contribution is welcome.\"\"\"\n return \"Split: {}\".format(\"Train\" if self.train is True else \"Test\")\n\n\nclass MnistMLDataset(MetricLearningTrainDataset, MNIST):\n \"\"\"\n Simple wrapper for MNIST dataset for metric learning train stage.\n This dataset can be used only for training. For test stage\n use MnistQGDataset.\n\n For this dataset we use only training part of the MNIST and only\n those images that are labeled as 0, 1, 2, 3, 4.\n \"\"\"\n\n _split = 5\n classes = [\n \"0 - zero\",\n \"1 - one\",\n \"2 - two\",\n \"3 - three\",\n \"4 - four\",\n ]\n\n def __init__(self, **kwargs):\n \"\"\"\n Raises:\n ValueError: if train argument is False (MnistMLDataset\n should be used only for training)\n \"\"\"\n if \"train\" in kwargs:\n if kwargs[\"train\"] is False:\n raise ValueError(\"MnistMLDataset can be used only for training stage.\")\n else:\n kwargs[\"train\"] = True\n super(MnistMLDataset, self).__init__(**kwargs)\n self._filter()\n\n def get_labels(self) -> List[int]:\n \"\"\"\n Returns:\n labels of digits\n \"\"\"\n return self.targets.tolist()\n\n def _filter(self) -> None:\n \"\"\"Filter MNIST dataset: select images of 0, 1, 2, 3, 4 classes.\"\"\"\n mask = self.targets < self._split\n self.data = self.data[mask]\n self.targets = self.targets[mask]\n\n\nclass MnistQGDataset(QueryGalleryDataset):\n \"\"\"\n MNIST for metric learning with query and gallery split.\n MnistQGDataset should be used for test stage.\n\n For this dataset we used only test part of the MNIST and only\n those images that are labeled as 5, 6, 7, 8, 9.\n \"\"\"\n\n _split = 5\n classes = [\n \"5 - five\",\n \"6 - six\",\n \"7 - seven\",\n \"8 - eight\",\n \"9 - nine\",\n ]\n\n def __init__(\n self, root: str, transform: Optional[Callable] = None, gallery_fraq: Optional[float] = 0.2\n ) -> None:\n \"\"\"\n Args:\n root: root directory for storing dataset\n transform: transform\n gallery_fraq: gallery size\n \"\"\"\n self._mnist = MNIST(root, train=False, download=True, transform=transform)\n self._filter()\n\n self._gallery_size = int(gallery_fraq * len(self._mnist))\n self._query_size = len(self._mnist) - self._gallery_size\n\n self._is_query = torch.zeros(len(self._mnist)).type(torch.bool)\n self._is_query[: self._query_size] = True\n\n def _filter(self) -> None:\n \"\"\"Filter MNIST dataset: select images of 5, 6, 7, 8, 9 classes.\"\"\"\n mask = self._mnist.targets >= self._split\n self._mnist.data = self._mnist.data[mask]\n self._mnist.targets = self._mnist.targets[mask]\n\n def __getitem__(self, idx: int) -> Dict[str, Any]:\n \"\"\"\n Get item method for dataset\n\n\n Args:\n idx: index of the object\n\n Returns:\n Dict with features, targets and is_query flag\n \"\"\"\n image, label = self._mnist[idx]\n return {\n \"features\": image,\n \"targets\": label,\n \"is_query\": self._is_query[idx],\n }\n\n def __len__(self) -> int:\n \"\"\"Length\"\"\"\n return len(self._mnist)\n\n def __repr__(self) -> None:\n \"\"\"Print info about the dataset\"\"\"\n return self._mnist.__repr__()\n\n @property\n def gallery_size(self) -> int:\n \"\"\"Query Gallery dataset should have gallery_size property\"\"\"\n return self._gallery_size\n\n @property\n def query_size(self) -> int:\n \"\"\"Query Gallery dataset should have query_size property\"\"\"\n return self._query_size\n\n @property\n def data(self) -> torch.Tensor:\n \"\"\"Images from MNIST\"\"\"\n return self._mnist.data\n\n @property\n def targets(self) -> torch.Tensor:\n \"\"\"Labels of digits\"\"\"\n return self._mnist.targets\n\n\n__all__ = [\"MNIST\", \"MnistMLDataset\", \"MnistQGDataset\"]\n"
] | [
[
"torch.save"
]
] |
BalderOdinson/Deep-Learning-Lab | [
"70786ff1be40fc829d64a644585c1d5683c76538"
] | [
"deep-learning-lab-01/tf_logreg.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 28 22:39:01 2019\n\n@author: Oshikuru\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport data\n\nclass TFLogreg:\n def __init__(self, D, C, param_delta=0.5, param_lambda=1e-3):\n \"\"\"Arguments:\n - D: dimensions of each datapoint \n - C: number of classes\n - param_delta: training step\n \"\"\"\n # definicija podataka i parametara:\n self.X = tf.placeholder(tf.float32, [None, D])\n self.Y_ = tf.placeholder(tf.float32, [None, C])\n self.W = tf.Variable(tf.random_normal([D, C], stddev=0.35), tf.float32)\n self.b = tf.Variable(tf.zeros([C]), tf.float32)\n self.param_lambda = tf.constant(param_lambda, tf.float32)\n\n # formulacija modela: izračunati self.probs\n # koristiti: tf.matmul, tf.nn.softmax\n self.probs = tf.nn.softmax(tf.matmul(self.X, self.W) + self.b)\n \n # formulacija gubitka: self.loss\n reg_loss = 0.5*self.param_lambda*tf.reduce_sum(self.W*self.W)\n self.loss = tf.reduce_mean(-tf.reduce_sum(self.Y_ * tf.log(self.probs), reduction_indices=1)) + reg_loss\n\n # formulacija operacije učenja: self.train_step\n self.train_step = tf.train.GradientDescentOptimizer(param_delta).minimize(self.loss)\n\n # instanciranje izvedbenog konteksta: self.session\n self.session = tf.Session()\n\n def train(self, X, Yoh_, param_niter):\n \"\"\"Arguments:\n - X: actual datapoints [NxD]\n - Yoh_: one-hot encoded labels [NxC]\n - param_niter: number of iterations\n \"\"\"\n # incijalizacija parametara\n # koristiti: tf.initializers.global_variables \n self.session.run(tf.initializers.global_variables())\n \n # optimizacijska petlja\n # koristiti: tf.Session.run\n for i in range(param_niter):\n loss,_ = self.session.run([self.loss, self.train_step], \n feed_dict={self.X: X, self.Y_: Yoh_})\n if i % 10 == 0:\n print(\"iteration {}: loss {}\".format(i, loss))\n\n def eval(self, X):\n \"\"\"Arguments:\n - X: actual datapoints [NxD]\n Returns: predicted class probabilites [NxC]\n \"\"\"\n return self.session.run(self.probs, \n feed_dict={self.X: X})\n \ndef calc_class(X):\n y = tflr.eval(X)\n return np.argmax(y, axis=1) * np.max(y, axis=1)\n \nif __name__ == \"__main__\":\n # inicijaliziraj generatore slučajnih brojeva\n np.random.seed(100)\n tf.set_random_seed(100)\n\n # instanciraj podatke X i labele Yoh_\n X,Y_ = data.sample_gmm_2d(6, 2, 10)\n Yoh_ = data.class_to_onehot(Y_)\n\n # izgradi graf:\n tflr = TFLogreg(X.shape[1], Yoh_.shape[1], 0.06,1)\n\n # nauči parametre:\n tflr.train(X, Yoh_, 1000)\n\n # dohvati vjerojatnosti na skupu za učenje\n probs = tflr.eval(X)\n Y = np.argmax(probs, axis=1)\n\n # ispiši performansu (preciznost i odziv po razredima)\n accuracy, recall, precision = data.eval_perf_multi(Y, Y_)\n AP = data.eval_AP(Y_)\n print (accuracy, recall, precision, AP)\n\n # iscrtaj rezultate, decizijsku plohu\n rect=(np.min(X, axis=0), np.max(X, axis=0))\n data.graph_surface(calc_class, rect, offset=0.5)\n data.graph_data(X, Y_, Y, special=[])\n plt.show()"
] | [
[
"tensorflow.placeholder",
"tensorflow.zeros",
"tensorflow.initializers.global_variables",
"numpy.random.seed",
"numpy.argmax",
"tensorflow.matmul",
"matplotlib.pyplot.show",
"tensorflow.set_random_seed",
"numpy.max",
"tensorflow.Session",
"numpy.min",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.log",
"tensorflow.constant",
"tensorflow.random_normal",
"tensorflow.reduce_sum"
]
] |
gdsa-upc/K-LERA | [
"3f4b5fb1a6c4b3df4fde05eb55fbf3dc3815cce4"
] | [
"Scripts21-12-17/get_params.py"
] | [
"import os,sys\nimport pandas as pd\nimport numpy as np\n\ndef get_params():\n\n '''\n Define dictionary with parameters\n '''\n params = {} \n\n params['src'] = '/home/dani/Escritorio/K-LERA-master/Semana4_ok'\n \n # Source data\n params['root'] = '/home/dani/Escritorio/K-LERA-master/Semana4_ok'\n params['database'] = 'TB2016'\n\n # To generate\n \n # 'root_save' directory goes under 'root':\n params['root_save'] = 'save'\n \n # All the following go under 'root_save':\n params['image_lists'] = 'image_lists'\n params['feats_dir'] = 'features'\n params['rankings_dir'] = 'rankings'\n params['classification_dir'] = 'classification'\n params['codebooks_dir'] = 'codebooks'\n params['classifiers_dir'] = 'classifiers'\n params['kaggle_dir'] = 'kaggle'\n \n\n # Parameters\n params['split'] = 'val'\n params['descriptor_size'] = 1024 # Number of clusters\n params['descriptor_type'] = 'SIFT'\n params['keypoint_type'] = 'SIFT'\n params['max_size'] = 500 # Widht size\n params['distance_type'] = 'euclidean'\n params['save_for_kaggle'] = True\n \n # Classification\n params['classifier'] = 'SVM'\n params['svm_tune'] =[{'kernel': ['rbf'], 'gamma': [1e-1, 1e-2, 1e-3, 1e-4, 1e-5],\n 'C': [0.1, 1, 10, 100, 1000]},\n {'kernel': ['linear'], 'C': [0.1, 1, 10, 100, 1000]}] # Parameters to tune the SVM\n \n params['num_neighbors'] = 3 # For KNN\n params['manual_balance'] = False\n \n # Normalization of local descriptors\n params['whiten'] = False\n params['normalize_feats'] = False\n params['scale'] = False\n \n \n # We read the training annotations to know the set of possible labels\n data = pd.read_csv(os.path.join(params['root'],params['database'],'train','annotation.txt'), sep='\\t', header = 0)\n \n # Store them in the parameters dictionary for later use\n params['possible_labels'] = np.unique(data['ClassID'])\n\n create_dirs(params)\n\n return params\n\n\ndef make_dir(dir):\n '''\n Creates a directory if it does not exist\n dir: absolute path to directory to create\n '''\n if not os.path.isdir(dir):\n os.makedirs(dir)\n\ndef create_dirs(params):\n\n '''\n Create directories specified in params\n '''\n save_dir = os.path.join(params['root'], params['root_save'])\n\n make_dir(save_dir)\n make_dir(os.path.join(save_dir,params['image_lists']))\n make_dir(os.path.join(save_dir,params['feats_dir']))\n make_dir(os.path.join(save_dir,params['rankings_dir']))\n make_dir(os.path.join(save_dir,params['classification_dir']))\n make_dir(os.path.join(save_dir,params['codebooks_dir']))\n make_dir(os.path.join(save_dir,params['classifiers_dir']))\n make_dir(os.path.join(save_dir,params['kaggle_dir']))\n \n make_dir(os.path.join(save_dir,params['rankings_dir'],params['descriptor_type']))\n make_dir(os.path.join(save_dir,params['rankings_dir'],params['descriptor_type'],params['split']))\n make_dir(os.path.join(save_dir,params['classification_dir'],params['descriptor_type']))\n\nif __name__ == \"__main__\":\n\n\tparams = get_params()"
] | [
[
"numpy.unique"
]
] |
betaros/traffic_sign | [
"6f5ef4afb7093c929cc2e94c7f72daebbd149b7e"
] | [
"src/traffic_sign.py"
] | [
"#!/usr/bin/env python\n\nimport numpy as np\n\nimport cv2\n\nimport roslib\nroslib.load_manifest('traffic_sign')\nimport rospy\n\nfrom sensor_msgs.msg import CompressedImage\nfrom std_msgs.msg import String\n\nclass image_feature:\n def __init__(self):\n self.counter = 1;\n self.raspi_subscriber = rospy.Subscriber(\"/raspicam_node/image/compressed\", CompressedImage, self.callback)\n rospy.loginfo(\"Subscribed to /raspicam_node/image/compressed\")\n\n self.detection_publisher = rospy.Publisher(\"/traffic_sign/detected\", String, queue_size=10)\n rospy.loginfo(\"Publishing /traffic_sign/detected\")\n\n self.image_publisher = rospy.Publisher(\"/traffic_sign/image/compressed\", CompressedImage, queue_size=10)\n rospy.loginfo(\"Publishing /traffic_sign/image/compressed\")\n\n def callback(self, ros_data):\n # rospy.loginfo(type(ros_data))\n \"\"\"\n Shows live images with marked detections\n \"\"\"\n if self.counter%10 != 0:\n self.counter = self.counter + 1\n else:\n self.counter = 1\n\n np_arr = np.fromstring(ros_data.data, np.uint8)\n # img = cv2.imdecode(np_arr, cv2.CV_LOAD_IMAGE_COLOR)\n img = cv2.imdecode(np_arr, cv2.IMREAD_UNCHANGED) # OpenCV >= 3.0:\n center = (205, 154)\n\n #if not img is None:\n # rospy.logwarn(\"No image received\")\n # return\n\n # img = cv2.resize(img, (960, 540))\n M = cv2.getRotationMatrix2D(center, 180, 1.0)\n img = cv2.warpAffine(img, M, (410, 308))\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n biggest_value = 0\n found_msg = \"nothing\"\n\n #face_cascade = cv2.CascadeClassifier('/home/user/catkin_ws/src/traffic_sign/cascades/haarcascade_frontalface_default.xml')\n #faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n #for (x, y, w, h) in faces:\n # cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n # if biggest_value < x*y:\n # found_msg = \"face\"\n # biggest_value = x * y\n # y = y - 5\n # self.write_text_on_image(img, \"Faces\", x, y)\n\n # No parking\n no_parking_cascade = cv2.CascadeClassifier(\n '/home/user/catkin_ws/src/traffic_sign/cascades/cascade_no_parking.xml')\n no_parking = no_parking_cascade.detectMultiScale(gray, 1.3, 5)\n for (x, y, w, h) in no_parking:\n cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 128), 2)\n if biggest_value < x * y:\n found_msg = \"no_parking\"\n biggest_value = x * y\n y = y - 5\n self.write_text_on_image(img, \"no parking\", x, y)\n\n # Entry forbidden\n entry_forbidden_cascade = cv2.CascadeClassifier(\n '/home/user/catkin_ws/src/traffic_sign/cascades/cascade_entry_forbidden.xml')\n entry_forbidden = entry_forbidden_cascade.detectMultiScale(gray, 1.3, 5)\n for (x, y, w, h) in entry_forbidden:\n cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)\n if biggest_value < x * y:\n found_msg = \"entry_forbidden\"\n biggest_value = x * y\n y = y - 5\n self.write_text_on_image(img, \"entry forbidden\", x, y)\n\n # Bus stop\n bus_stop_cascade = cv2.CascadeClassifier(\n '/home/user/catkin_ws/src/traffic_sign/cascades/cascade_bus_stop.xml')\n bus_stop = bus_stop_cascade.detectMultiScale(gray, 1.3, 5)\n for (x, y, w, h) in bus_stop:\n cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)\n if biggest_value < x * y:\n found_msg = \"bus_stop\"\n biggest_value = x * y\n y = y - 5\n self.write_text_on_image(img, \"bus stop\", x, y)\n\n form_triangle_cascade = cv2.CascadeClassifier(\n '/home/user/catkin_ws/src/traffic_sign/cascades/red_triangle/cascade.xml')\n form_triangle = form_triangle_cascade.detectMultiScale(gray, 1.3, 5)\n for (x, y, w, h) in form_triangle:\n # pedestrians\n pedestrians_cascade = cv2.CascadeClassifier(\n '/home/user/catkin_ws/src/traffic_sign/cascades/pedestrians/cascade.xml')\n pedestrians = pedestrians_cascade.detectMultiScale(gray, 1.3, 5)\n for (xa, ya, wa, ha) in pedestrians:\n cv2.rectangle(img, (x, y), (x + w, y + h), (255, 128, 0), 2)\n if biggest_value < x * y:\n found_msg = \"pedestrians\"\n biggest_value = x * y\n y = y - 5\n self.write_text_on_image(img, \"pedestrians\", x, y)\n\n # turn right\n turn_right_cascade = cv2.CascadeClassifier(\n '/home/user/catkin_ws/src/traffic_sign/cascades/turn_right/cascade.xml')\n turn_right = turn_right_cascade.detectMultiScale(gray, 1.3, 5)\n for (xa, ya, wa, ha) in turn_right:\n cv2.rectangle(img, (x, y), (x + w, y + h), (128, 255, 0), 2)\n if biggest_value < x * y:\n found_msg = \"turn_right\"\n biggest_value = x * y\n y = y - 5\n self.write_text_on_image(img, \"turn right\", x, y)\n\n # turn left\n turn_left_cascade = cv2.CascadeClassifier(\n '/home/user/catkin_ws/src/traffic_sign/cascades/turn_left/cascade.xml')\n turn_left = turn_left_cascade.detectMultiScale(gray, 1.3, 5)\n for (xa, ya, wa, ha) in turn_left:\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 128, 0), 2)\n if biggest_value < x * y:\n found_msg = \"turn_left\"\n biggest_value = x * y\n y = y - 5\n self.write_text_on_image(img, \"turn left\", x, y)\n\n # warning\n warning_cascade = cv2.CascadeClassifier(\n '/home/user/catkin_ws/src/traffic_sign/cascades/warning/cascade.xml')\n warning = warning_cascade.detectMultiScale(gray, 1.3, 5)\n for (xa, ya, wa, ha) in warning:\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 128, 128), 2)\n if biggest_value < x * y:\n found_msg = \"warning\"\n biggest_value = x * y\n y = y - 5\n self.write_text_on_image(img, \"warning\", x, y)\n\n # crossing\n crossing_cascade = cv2.CascadeClassifier(\n '/home/user/catkin_ws/src/traffic_sign/cascades/cross/cascade.xml')\n crossing = crossing_cascade.detectMultiScale(gray, 1.3, 5)\n for (xa, ya, wa, ha) in crossing:\n cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)\n if biggest_value < x * y:\n found_msg = \"entry_crossing\"\n biggest_value = x * y\n y = y - 5\n self.write_text_on_image(img, \"crossing\", x, y)\n\n # slippery\n slippery_cascade = cv2.CascadeClassifier(\n '/home/user/catkin_ws/src/traffic_sign/cascades/slippery/cascade.xml')\n slippery = slippery_cascade.detectMultiScale(gray, 1.3, 5)\n for (xa, ya, wa, ha) in slippery:\n cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)\n if biggest_value < x * y:\n found_msg = \"entry_slippery\"\n biggest_value = x * y\n y = y - 5\n self.write_text_on_image(img, \"slippery\", x, y)\n\n # main road\n main_road_cascade = cv2.CascadeClassifier(\n '/home/user/catkin_ws/src/traffic_sign/cascades/cascade_main_road.xml')\n main_road = main_road_cascade.detectMultiScale(gray, 1.3, 5)\n for (x, y, w, h) in main_road:\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 255), 2)\n if biggest_value < x * y:\n found_msg = \"main_road\"\n biggest_value = x * y\n y = y - 5\n self.write_text_on_image(img, \"main road\", x, y)\n\n # road closed\n road_closed_cascade = cv2.CascadeClassifier('/home/user/catkin_ws/src/traffic_sign/cascades/cascade_road_closed.xml')\n road_closed = road_closed_cascade.detectMultiScale(gray, 1.3, 5)\n for (x, y, w, h) in road_closed:\n cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)\n if biggest_value < x * y:\n found_msg = \"entry_road_closed\"\n biggest_value = x * y\n y = y - 5\n self.write_text_on_image(img, \"road closed\", x, y)\n\n rospy.loginfo(found_msg)\n \n #### Create CompressedIamge ####\n msg = CompressedImage()\n msg.header.stamp = rospy.Time.now()\n msg.format = \"jpeg\"\n msg.data = np.array(cv2.imencode('.jpg', img)[1]).tostring()\n\n # Publish new image\n self.image_publisher.publish(msg)\n self.detection_publisher.publish(found_msg)\n #random_number = str(random.randint(1,101))\n #self.detection_publisher.publish(random_number)\n\n def write_text_on_image(self, img, message, x, y):\n \"\"\"\n Writes text above the recognized field\n\n :param img:\n :param message:\n :return:\n \"\"\"\n\n bottom_left_corner_of_text=(x,y)\n font = cv2.FONT_HERSHEY_SIMPLEX\n font_scale = 1\n font_color = (0, 255, 0)\n line_type = 2\n\n cv2.putText(img, message,\n bottom_left_corner_of_text,\n font,\n font_scale,\n font_color,\n line_type)\n\nif __name__ == '__main__':\n image = image_feature()\n rospy.init_node('traffic_sign', log_level=rospy.DEBUG)\n try:\n rospy.spin()\n except KeyboardInterrupt:\n rospy.loginfo(\"Shutting down traffic sign node\")\n cv2.destroyAllWindows()\n"
] | [
[
"numpy.fromstring"
]
] |
yongpi-scu/TPRNet | [
"bc97169ebe4d123a64da6b0fdc787ecb89c7372f"
] | [
"utils/metrics.py"
] | [
"import numpy as np\r\ndef get_confusion_matrix(output,target):\r\n confusion_matrix = np.zeros((output[0].shape[0],output[0].shape[0]))\r\n for i in range(len(output)):\r\n true_idx = target[i]\r\n pred_idx = np.argmax(output[i])\r\n confusion_matrix[true_idx][pred_idx] += 1.0\r\n return confusion_matrix\r\n\r\ndef get_confusion_matrix_logits(output,target):\r\n confusion_matrix = np.zeros((2,2))\r\n for i in range(len(output)):\r\n true_idx = target[i]\r\n pred_idx = 1 if output[i]>0.5 else 0\r\n confusion_matrix[true_idx][pred_idx] += 1.0\r\n return confusion_matrix\r\n"
] | [
[
"numpy.argmax",
"numpy.zeros"
]
] |
ninastijepovic/MasterThesis | [
"2579f1e74c0ce404f350a6d441e273b6aef4eadc"
] | [
"train_unet.py"
] | [
"# import the necessary packages\nimport os\nimport argparse\nimport random\nimport pandas as pd\nimport numpy as np\nimport pickle\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom matplotlib import image, pyplot as plt\nfrom random import sample,randint\nmatplotlib.use(\"Agg\")\n\nfrom preprocessor import preprocessor\nfrom tqdm import tqdm_notebook, tnrange\nfrom itertools import chain\nfrom sklearn.metrics import roc_curve, auc \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import multilabel_confusion_matrix\nfrom unet import get_unet \n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.python.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom tensorflow.python.keras.models import Model\nfrom tensorflow.python.keras import layers\nfrom tensorflow.python.keras.models import Sequential\nfrom tensorflow.python.keras.optimizers import Adam, SGD, RMSprop\nfrom tensorflow.python.keras.layers import Input, Activation, Reshape, Dropout, Flatten, Conv2D, MaxPooling2D, Dense, BatchNormalization, GlobalAveragePooling2D\nimport wandb\nfrom wandb.keras import WandbCallback\n\n# initialize the number of epochs to train for, initial learning rate,\n# batch size, and image dimensions\n\n# set parameters\ndefaults=dict(\n learn_rate = 0.001,\n batch_size = 256,\n epochs = 100,\n )\nwandb.init(project=\"master_thesis\", config=defaults, name=\"unet_mask4_100samples\")\nconfig = wandb.config\n\n#load data\nf = open(\"/var/scratch/nsc400/hera_data/HERA_masks29-07-2020.pkl\",\"rb\")\ndataset = pickle.load(f,encoding='latin1')\ndata = dataset[0]\nlabels = dataset[2]\nmask1 = dataset[4]\nmask2 = dataset[5]\nmask3 = dataset[6]\nmask4 = dataset[7]\n\n\nd_height = data.shape[1]\nd_width = data.shape[2]\n\n# partition the data into training and testing splits using 80% of\n# the data for training and the remaining 20% for testing\n\ntrainX, testX, trainY, testY = train_test_split(data,\n mask4, train_size=0.004, random_state=42)\n\n# initialize the model using a sigmoid activation as the final layer\n\nprint(\"[INFO] compiling model...\")\ninput_data = Input((d_height, d_width, 1), name='data')\nmodel = get_unet(input_data, n_filters=16, dropout=0.05, batchnorm=True)\n\n# initialize the optimizer\nopt = Adam(lr=config.learn_rate,decay = config.learn_rate/config.epochs)\n#decay = config.learn_rate/config.epochs\n#opt = SGD(lr=config.learn_rate)\n#opt = RMSprop(lr=config.learn_rate)\n\nmodel.compile(loss=\"binary_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])\n\n#print(\"[INFO] summary of model...\")\n#print(model.summary())\n\ncallbacks = [\n WandbCallback(),\n EarlyStopping(patience=50, verbose=1, monitor='val_loss'),\n ReduceLROnPlateau(factor=0.1, patience=30, verbose=1),\n ModelCheckpoint('model-unet-mask1-100.h5', verbose=1, save_best_only=True,save_weights_only=False)\n]\n\n# train the network\nprint(\"[INFO] training network...\")\nH = model.fit(trainX, trainY, batch_size=config.batch_size,\n validation_data=(testX, testY), epochs=config.epochs, verbose=1, callbacks=callbacks)\n\n# log the number of total parameters\nconfig.total_params = model.count_params()\nprint(\"Total params: \", config.total_params)\n\n# save the model to disk\nprint(\"[INFO] serializing network...\")\nmodel.save(\"model_unet_mask4_100\")\n\n#save model\nwandb.save('model_unet_rfi_impulse.h5')\n\n# Predict on train, val and test\npreds_train = model.predict(trainX, verbose=1)\npreds_val = model.predict(testX, verbose=1)\n\npreds_train_t = (preds_train > 0.5).astype(np.uint8)\npreds_val_t = (preds_val > 0.5).astype(np.uint8)\n\n#cf = ClassificationReport(ix)\n#cf_mean = cf.generate(trainY, preds_train_t)\n#print(\"Classification report mean : {}\".format(cf_mean))\n#classification report\n#print(classification_report(testY, preds_val))\n\nprint('Classification report:\\n', classification_report(testY.flatten(), preds_val_t.flatten()))\n\ndef plot_io(model,data,mask):\n\n mask = mask \n output = model.predict(data)\n binaryp = (output >0.04).astype(np.uint8)\n print(model.evaluate(data, mask, verbose=1))\n it = 1\n if isinstance(data,list):\n it = 2\n shape = output[0].shape[0]\n else:\n shape = output.shape[0]\n\n for i in range(it):\n fig,axs = plt.subplots(3,2,figsize=(10,10))\n\n if isinstance(data,list):\n inp = data[i]\n msk = mask[i]\n outp = output[i]\n bp = binaryp[i]\n else:\n inp = data\n msk = mask\n outp = output\n bp = binaryp\n\n for j in range(2):\n r = randint(0,shape-1)\n has_mask = msk[r,...,0].max() > 0\n\n axs[0,j].imshow(inp[r,...,0]);\n #if has_mask:\n #axs[0,j].contour(msk[r,...,0].squeeze(), levels=[0.1])\n axs[0,j].set_title(f' {labels[r]}',fontsize=10)\n\n axs[1,j].imshow(msk[r,...,0].squeeze(), vmin=0, vmax=1);\n axs[1,j].title.set_text('Mask {}'.format(r))\n\n #axs[2,j].imshow(outp[r,...,0]);\n #if has_mask:\n #axs[2,j].contour(msk[r,...,0].squeeze(),levels=[0.1])\n #axs[2,j].title.set_text('Mask Predicted{}'.format(r))\n\n axs[2,j].imshow(bp[r,...,0].squeeze(), vmin=0, vmax=1);\n if has_mask:\n axs[2,j].contour(msk[r,...,0].squeeze(),levels=[0.09])\n axs[2,j].title.set_text('Mask Binary Predicted{}'.format(r))\n\n\n return plt\n\n\nwandb.log({'Analysis':plot_io(model,testX,testY)})\n\n\nrealm=testY.ravel()\npredicted=preds_val.ravel()\nfpr, tpr, _ = roc_curve(realm, predicted)\nroc_auc = auc(fpr,tpr)\n\nfig, ax = plt.subplots(1,1)\nax.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)\nax.plot([0, 1], [0, 1], 'k--')\nax.set_xlim([0.0, 1.0])\nax.set_ylim([0.0, 1.05])\nax.set_xlabel('False Positive Rate')\nax.set_ylabel('True Positive Rate')\nax.legend(loc=\"lower right\")\nplt.grid()\nplt.savefig('rocunet_mask4_100.png')\nwandb.Image(plt)\nwandb.log({\"ROC\": plt})\n"
] | [
[
"sklearn.metrics.roc_curve",
"matplotlib.pyplot.grid",
"sklearn.metrics.auc",
"matplotlib.pyplot.savefig",
"tensorflow.python.keras.callbacks.ReduceLROnPlateau",
"tensorflow.python.keras.callbacks.ModelCheckpoint",
"matplotlib.pyplot.subplots",
"tensorflow.python.keras.optimizers.Adam",
"tensorflow.python.keras.callbacks.EarlyStopping",
"tensorflow.python.keras.layers.Input",
"matplotlib.use",
"sklearn.model_selection.train_test_split"
]
] |
philippgualdi/PyQMRI | [
"5de3a7da5feb2d01b746acd47d1dba91a8a1417e"
] | [
"test/unittests/test_symmetrized_gradient_double.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 12 11:26:41 2019\n\n@author: omaier\n\"\"\"\n\nimport pyqmri\ntry:\n import unittest2 as unittest\nexcept ImportError:\n import unittest\nfrom pyqmri._helper_fun import CLProgram as Program\nfrom pkg_resources import resource_filename\nimport pyopencl.array as clarray\nimport numpy as np\n\n\nDTYPE = np.complex128\nDTYPE_real = np.float64\nATOL=1e-14\nRTOL=1e-12\n\nclass tmpArgs():\n pass\n\n\ndef setupPar(par):\n par[\"NScan\"] = 10\n par[\"NC\"] = 15\n par[\"NSlice\"] = 10\n par[\"dimX\"] = 128\n par[\"dimY\"] = 128\n par[\"Nproj\"] = 21\n par[\"N\"] = 256\n par[\"unknowns_TGV\"] = 2\n par[\"unknowns_H1\"] = 0\n par[\"unknowns\"] = 2\n par[\"dz\"] = 1\n par[\"weights\"] = np.array([1, 0.1])\n\n\nclass SymmetrizedGradientTest(unittest.TestCase):\n def setUp(self):\n parser = tmpArgs()\n parser.streamed = False\n parser.devices = -1\n parser.use_GPU = True\n\n par = {}\n pyqmri.pyqmri._setupOCL(parser, par)\n setupPar(par)\n if DTYPE == np.complex128:\n file = open(\n resource_filename(\n 'pyqmri', 'kernels/OpenCL_Kernels_double.c'))\n else:\n file = open(\n resource_filename(\n 'pyqmri', 'kernels/OpenCL_Kernels.c'))\n prg = Program(\n par[\"ctx\"][0],\n file.read())\n file.close()\n\n self.weights = par[\"weights\"]\n\n self.symgrad = pyqmri.operator.OperatorFiniteSymGradient(\n par, prg,\n DTYPE=DTYPE,\n DTYPE_real=DTYPE_real)\n\n self.symgradin = np.random.randn(par[\"unknowns\"], par[\"NSlice\"],\n par[\"dimY\"], par[\"dimX\"], 4) +\\\n 1j * np.random.randn(par[\"unknowns\"], par[\"NSlice\"],\n par[\"dimY\"], par[\"dimX\"], 4)\n self.symdivin = np.random.randn(par[\"unknowns\"], par[\"NSlice\"],\n par[\"dimY\"], par[\"dimX\"], 8) +\\\n 1j * np.random.randn(par[\"unknowns\"], par[\"NSlice\"],\n par[\"dimY\"], par[\"dimX\"], 8)\n self.symgradin = self.symgradin.astype(DTYPE)\n self.symdivin = self.symdivin.astype(DTYPE)\n self.dz = par[\"dz\"]\n self.queue = par[\"queue\"][0]\n\n def test_sym_grad_outofplace(self):\n gradx = np.zeros_like(self.symgradin)\n grady = np.zeros_like(self.symgradin)\n gradz = np.zeros_like(self.symgradin)\n\n gradx[..., 1:, :] = -np.flip(\n np.diff(\n np.flip(self.symgradin, axis=-2), axis=-2), axis=-2)\n grady[..., 1:, :, :] = -np.flip(\n np.diff(\n np.flip(self.symgradin, axis=-3), axis=-3), axis=-3)\n gradz[:, 1:, ...] = -np.flip(\n np.diff(\n np.flip(self.symgradin, axis=-4), axis=-4), axis=-4)\n\n symgrad = np.stack((gradx[..., 0],\n grady[..., 1],\n gradz[..., 2]*self.dz,\n 1/2 * (gradx[..., 1] + grady[..., 0]),\n 1/2 * (gradx[..., 2] + gradz[..., 0]*self.dz),\n 1/2 * (grady[..., 2] + gradz[..., 1]*self.dz)),\n axis=-1)\n symgrad *= self.weights[:, None, None, None, None]\n\n inp = clarray.to_device(self.queue, self.symgradin)\n outp = self.symgrad.fwdoop(inp)\n outp = outp.get()\n\n np.testing.assert_allclose(outp[..., :6], symgrad, rtol=RTOL, atol=ATOL)\n\n def test_sym_grad_inplace(self):\n gradx = np.zeros_like(self.symgradin)\n grady = np.zeros_like(self.symgradin)\n gradz = np.zeros_like(self.symgradin)\n\n gradx[..., 1:, :] = -np.flip(\n np.diff(\n np.flip(self.symgradin, axis=-2), axis=-2), axis=-2)\n grady[..., 1:, :, :] = -np.flip(\n np.diff(\n np.flip(self.symgradin, axis=-3), axis=-3), axis=-3)\n gradz[:, 1:, ...] = -np.flip(\n np.diff(\n np.flip(self.symgradin, axis=-4), axis=-4), axis=-4)\n\n symgrad = np.stack((gradx[..., 0],\n grady[..., 1],\n gradz[..., 2]*self.dz,\n 1/2 * (gradx[..., 1] + grady[..., 0]),\n 1/2 * (gradx[..., 2] + gradz[..., 0]*self.dz),\n 1/2 * (grady[..., 2] + gradz[..., 1]*self.dz)),\n axis=-1)\n symgrad *= self.weights[:, None, None, None, None]\n inp = clarray.to_device(self.queue, self.symgradin)\n outp = clarray.to_device(self.queue, self.symdivin)\n outp.add_event(self.symgrad.fwd(outp, inp))\n outp = outp.get()\n\n np.testing.assert_allclose(outp[..., :6], symgrad, rtol=RTOL, atol=ATOL)\n\n def test_adj_outofplace(self):\n inpgrad = clarray.to_device(self.queue, self.symgradin)\n inpdiv = clarray.to_device(self.queue, self.symdivin)\n\n outgrad = self.symgrad.fwdoop(inpgrad)\n outdiv = self.symgrad.adjoop(inpdiv)\n\n outgrad = outgrad.get()\n outdiv = outdiv.get()\n a1 = np.vdot(outgrad[..., :3].flatten(),\n self.symdivin[..., :3].flatten())/self.symgradin.size*4\n a2 = 2*np.vdot(outgrad[..., 3:6].flatten(),\n self.symdivin[..., 3:6].flatten())/self.symgradin.size*4\n a = a1+a2\n b = np.vdot(self.symgradin[..., :3].flatten(),\n -outdiv[..., :3].flatten())/self.symgradin.size*4\n\n print(\"Adjointness: %.2e +1j %.2e\" % ((a - b).real, (a - b).imag))\n\n np.testing.assert_allclose(a, b, rtol=RTOL, atol=ATOL)\n\n def test_adj_inplace(self):\n inpgrad = clarray.to_device(self.queue, self.symgradin)\n inpdiv = clarray.to_device(self.queue, self.symdivin)\n\n outgrad = clarray.zeros_like(inpdiv)\n outdiv = clarray.zeros_like(inpgrad)\n\n outgrad.add_event(self.symgrad.fwd(outgrad, inpgrad))\n outdiv.add_event(self.symgrad.adj(outdiv, inpdiv))\n\n outgrad = outgrad.get()\n outdiv = outdiv.get()\n\n a1 = np.vdot(outgrad[..., :3].flatten(),\n self.symdivin[..., :3].flatten())/self.symgradin.size*4\n a2 = 2*np.vdot(outgrad[..., 3:6].flatten(),\n self.symdivin[..., 3:6].flatten())/self.symgradin.size*4\n a = a1+a2\n b = np.vdot(self.symgradin[..., :3].flatten(),\n -outdiv[..., :3].flatten())/self.symgradin.size*4\n\n print(\"Adjointness: %.2e +1j %.2e\" % ((a - b).real, (a - b).imag))\n\n np.testing.assert_allclose(a, b, rtol=RTOL, atol=ATOL)\n\n\nclass SymmetrizedGradientStreamedTest(unittest.TestCase):\n def setUp(self):\n parser = tmpArgs()\n parser.streamed = True\n parser.devices = -1\n parser.use_GPU = True\n\n par = {}\n pyqmri.pyqmri._setupOCL(parser, par)\n setupPar(par)\n if DTYPE == np.complex128:\n file = resource_filename(\n 'pyqmri', 'kernels/OpenCL_Kernels_double_streamed.c')\n else:\n file = resource_filename(\n 'pyqmri', 'kernels/OpenCL_Kernels_streamed.c')\n\n prg = []\n for j in range(len(par[\"ctx\"])):\n with open(file) as myfile:\n prg.append(Program(\n par[\"ctx\"][j],\n myfile.read()))\n\n par[\"par_slices\"] = 1\n\n self.weights = par[\"weights\"]\n\n self.symgrad = pyqmri.operator.OperatorFiniteSymGradientStreamed(\n par, prg,\n DTYPE=DTYPE,\n DTYPE_real=DTYPE_real)\n\n self.symgradin = np.random.randn(par[\"NSlice\"], par[\"unknowns\"],\n par[\"dimY\"], par[\"dimX\"], 4) +\\\n 1j * np.random.randn(par[\"NSlice\"], par[\"unknowns\"],\n par[\"dimY\"], par[\"dimX\"], 4)\n self.symdivin = np.random.randn(par[\"NSlice\"], par[\"unknowns\"],\n par[\"dimY\"], par[\"dimX\"], 8) +\\\n 1j * np.random.randn(par[\"NSlice\"], par[\"unknowns\"],\n par[\"dimY\"], par[\"dimX\"], 8)\n self.symgradin = self.symgradin.astype(DTYPE)\n self.symdivin = self.symdivin.astype(DTYPE)\n self.dz = par[\"dz\"]\n\n def test_grad_outofplace(self):\n gradx = np.zeros_like(self.symgradin)\n grady = np.zeros_like(self.symgradin)\n gradz = np.zeros_like(self.symgradin)\n\n gradx[..., 1:, :] = -np.flip(\n np.diff(\n np.flip(self.symgradin, axis=-2), axis=-2), axis=-2)\n grady[..., 1:, :, :] = -np.flip(\n np.diff(\n np.flip(self.symgradin, axis=-3), axis=-3), axis=-3)\n gradz[1:, ...] = -np.flip(\n np.diff(\n np.flip(self.symgradin, axis=0), axis=0), axis=0)\n\n symgrad = np.stack((gradx[..., 0],\n grady[..., 1],\n gradz[..., 2]*self.dz,\n 1/2 * (gradx[..., 1] + grady[..., 0]),\n 1/2 * (gradx[..., 2] + gradz[..., 0]*self.dz),\n 1/2 * (grady[..., 2] + gradz[..., 1]*self.dz)),\n axis=-1)\n symgrad *= self.weights[None, :, None, None, None]\n outp = self.symgrad.fwdoop([[self.symgradin]])\n\n np.testing.assert_allclose(outp[..., :6], symgrad, rtol=RTOL, atol=ATOL)\n\n def test_grad_inplace(self):\n gradx = np.zeros_like(self.symgradin)\n grady = np.zeros_like(self.symgradin)\n gradz = np.zeros_like(self.symgradin)\n\n gradx[..., 1:, :] = -np.flip(\n np.diff(\n np.flip(self.symgradin, axis=-2), axis=-2), axis=-2)\n grady[..., 1:, :, :] = -np.flip(\n np.diff(\n np.flip(self.symgradin, axis=-3), axis=-3), axis=-3)\n gradz[1:, ...] = -np.flip(\n np.diff(\n np.flip(self.symgradin, axis=0), axis=0), axis=0)\n\n symgrad = np.stack((gradx[..., 0],\n grady[..., 1],\n gradz[..., 2]*self.dz,\n 1/2 * (gradx[..., 1] + grady[..., 0]),\n 1/2 * (gradx[..., 2] + gradz[..., 0]*self.dz),\n 1/2 * (grady[..., 2] + gradz[..., 1]*self.dz)),\n axis=-1)\n symgrad *= self.weights[None, :, None, None, None]\n outp = np.zeros_like(self.symdivin)\n\n self.symgrad.fwd([outp], [[self.symgradin]])\n\n np.testing.assert_allclose(outp[..., :6], symgrad, rtol=RTOL, atol=ATOL)\n\n def test_adj_outofplace(self):\n\n outgrad = self.symgrad.fwdoop([[self.symgradin]])\n outdiv = self.symgrad.adjoop([[self.symdivin]])\n\n a1 = np.vdot(outgrad[..., :3].flatten(),\n self.symdivin[..., :3].flatten())/self.symgradin.size*4\n a2 = 2*np.vdot(outgrad[..., 3:6].flatten(),\n self.symdivin[..., 3:6].flatten())/self.symgradin.size*4\n a = a1+a2\n b = np.vdot(self.symgradin[..., :3].flatten(),\n -outdiv[..., :3].flatten())/self.symgradin.size*4\n\n print(\"Adjointness: %.2e +1j %.2e\" % ((a - b).real, (a - b).imag))\n\n np.testing.assert_allclose(a, b, rtol=RTOL, atol=ATOL)\n\n def test_adj_inplace(self):\n\n outgrad = np.zeros_like(self.symdivin)\n outdiv = np.zeros_like(self.symgradin)\n\n self.symgrad.fwd([outgrad], [[self.symgradin]])\n self.symgrad.adj([outdiv], [[self.symdivin]])\n\n a1 = np.vdot(outgrad[..., :3].flatten(),\n self.symdivin[..., :3].flatten())/self.symgradin.size*4\n a2 = 2*np.vdot(outgrad[..., 3:6].flatten(),\n self.symdivin[..., 3:6].flatten())/self.symgradin.size*4\n a = a1+a2\n b = np.vdot(self.symgradin[..., :3].flatten(),\n -outdiv[..., :3].flatten())/self.symgradin.size*4\n\n print(\"Adjointness: %.2e +1j %.2e\" % ((a - b).real, (a - b).imag))\n\n np.testing.assert_allclose(a, b, rtol=RTOL, atol=ATOL)\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] | [
[
"numpy.zeros_like",
"numpy.stack",
"numpy.random.randn",
"numpy.flip",
"numpy.testing.assert_allclose",
"numpy.array"
]
] |
g-mitu/timeseries | [
"3b2daf33f9af022d1aae7c4a9caf69b8abd58348"
] | [
"WritingNovel/show_matplotlib.py"
] | [
"import matplotlib.pyplot as plt\r\nimport numpy as np # 导入包\r\n\r\nt1 = np.arange(0.0, 4.0, 0.1)\r\nt2 = np.arange(0.0, 4.0, 0.05) # 准备一些数据\r\n\r\nfig = plt.figure() # 准备好这张纸,并把句柄传给fig\r\nax1 = fig.add_subplot(211) # 使用句柄fig添加一个子图\r\nline1, = plt.plot(t1, np.sin(2 * np.pi * t1), '--*') # 绘图,将句柄返给line1\r\nplt.title('sine function demo')\r\nplt.xlabel('time(s)')\r\nplt.ylabel('votage(mV)')\r\nplt.xlim([0.0, 5.0])\r\nplt.ylim([-1.2, 1.2])\r\nplt.grid('on')\r\n\r\nplt.setp(line1, lw=2, c='g') # 通过setp函数,设置句柄为line1的线的属性,c是color的简写\r\nline1.set_antialiased(False) # 通过line1句柄的set_*属性设置line1的属性\r\nplt.text(4, 0, '$\\mu=100,\\\\sigma=15$') # 添加text,注意,它能接受LaTeX哟!\r\n\r\nax2 = fig.add_subplot(212)\r\nplt.plot(t2, np.exp(-t2), ':r')\r\n\r\nplt.plot(t2, np.cos(2 * np.pi * t2), '--b')\r\n\r\nplt.xlabel('time')\r\nplt.ylabel('amplitude')\r\nplt.show()\r\n\r\n## sample 2\r\n\"\"\"\r\n==================\r\nggplot style sheet\r\n==================\r\n\r\nThis example demonstrates the \"ggplot\" style, which adjusts the style to\r\nemulate ggplot_ (a popular plotting package for R_).\r\n\r\nThese settings were shamelessly stolen from [1]_ (with permission).\r\n\r\n.. [1] http://www.huyng.com/posts/sane-color-scheme-for-matplotlib/\r\n\r\n.. _ggplot: http://ggplot2.org/\r\n.. _R: https://www.r-project.org/\r\n\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nplt.style.use('ggplot')\r\n\r\nfig, axes = plt.subplots(ncols=2, nrows=2)\r\nax1, ax2, ax3, ax4 = axes.ravel()\r\n\r\n# scatter plot (Note: `plt.scatter` doesn't use default colors)\r\nx, y = np.random.normal(size=(2, 200))\r\nax1.plot(x, y, 'o')\r\n\r\n# sinusoidal lines with colors from default color cycle\r\nL = 2*np.pi\r\nx = np.linspace(0, L)\r\nncolors = len(plt.rcParams['axes.prop_cycle'])\r\nshift = np.linspace(0, L, ncolors, endpoint=False)\r\nfor s in shift:\r\n ax2.plot(x, np.sin(x + s), '-')\r\nax2.margins(0)\r\n\r\n# bar graphs\r\nx = np.arange(5)\r\ny1, y2 = np.random.randint(1, 25, size=(2, 5))\r\nwidth = 0.25\r\nax3.bar(x, y1, width)\r\nax3.bar(x + width, y2, width,\r\n color=list(plt.rcParams['axes.prop_cycle'])[2]['color'])\r\nax3.set_xticks(x + width)\r\nax3.set_xticklabels(['a', 'b', 'c', 'd', 'e'])\r\n\r\n# circles with colors from default color cycle\r\nfor i, color in enumerate(plt.rcParams['axes.prop_cycle']):\r\n xy = np.random.normal(size=2)\r\n ax4.add_patch(plt.Circle(xy, radius=0.3, color=color['color']))\r\nax4.axis('equal')\r\nax4.margins(0)\r\n\r\nplt.show()"
] | [
[
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.figure",
"numpy.cos",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.title",
"matplotlib.pyplot.text",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.arange",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.Circle",
"matplotlib.pyplot.grid",
"numpy.exp",
"matplotlib.pyplot.setp",
"matplotlib.pyplot.show",
"numpy.random.normal",
"numpy.sin",
"numpy.random.randint",
"matplotlib.pyplot.xlabel"
]
] |
muntashir/movie-review-sentiment-classifier | [
"f850f4902186b4ac6bc62126fa333d8e9975a759"
] | [
"data.py"
] | [
"import os\r\nimport random\r\nimport json\r\nimport torch\r\nimport numpy as np\r\n\r\nVOCAB_SIZE = 89528\r\nMAX_LENGTH = 150\r\n\r\nclass Dataset:\r\n\r\n def __init__(self, data_dir):\r\n test_percent = 0.1\r\n validation_percent = 0.1\r\n\r\n # Index for minibatches\r\n self.data_index = {'train': 0, 'validation': 0, 'test': 0}\r\n self.epoch_count = 0\r\n\r\n dataset_filepath = os.path.join(data_dir, 'dataset.json')\r\n if os.path.isfile(dataset_filepath):\r\n print('Loading data split from cache')\r\n\r\n with open(dataset_filepath) as dataset_file:\r\n self.dataset = json.load(dataset_file)\r\n else:\r\n print('Generating data split')\r\n data_and_labels = []\r\n\r\n for folder, _, filenames in os.walk(data_dir):\r\n for filename in filenames:\r\n if data_dir == folder:\r\n continue\r\n\r\n label = folder.split(os.sep)[-1]\r\n full_path = os.path.join(folder, filename)\r\n data_and_label = {}\r\n data_and_label['path'] = full_path\r\n data_and_label['label'] = label\r\n data_and_labels.append(data_and_label)\r\n\r\n random.shuffle(data_and_labels)\r\n\r\n test_slice = int(len(data_and_labels) * test_percent)\r\n validation_slice = -int(len(data_and_labels) * validation_percent)\r\n\r\n self.dataset = {}\r\n self.dataset['test'] = data_and_labels[:test_slice]\r\n self.dataset['train'] = data_and_labels[test_slice:validation_slice]\r\n self.dataset['validation'] = data_and_labels[validation_slice:]\r\n\r\n with open(dataset_filepath, 'w') as dataset_file:\r\n json.dump(self.dataset, dataset_file)\r\n\r\n vocab_filepath = os.path.join(data_dir, 'imdb.vocab')\r\n if not os.path.isfile(vocab_filepath):\r\n print('vocab.txt file missing in dataset/')\r\n else:\r\n with open(vocab_filepath, 'r') as vocab_file:\r\n self.word_to_index = [line.rstrip('\\n') for line in vocab_file]\r\n\r\n def __load_text_as_vectors(self, batch):\r\n batch_size = len(batch)\r\n vectors_and_labels = []\r\n time_steps = 0\r\n\r\n for data in batch:\r\n vectors_and_label = {}\r\n label = np.zeros(2)\r\n if (data['label'] == 'pos'):\r\n label[0] = 1\r\n elif (data['label'] == 'neg'):\r\n label[1] = 1\r\n vectors_and_label['label'] = label\r\n vectors_and_label['vectors'] = []\r\n\r\n filepath = data['path']\r\n with open(filepath, 'r') as f:\r\n words = f.read() \\\r\n .replace('<br />', ' ') \\\r\n .replace('(', '') \\\r\n .replace(')', '') \\\r\n .replace('--', '') \\\r\n .replace('.', ' ') \\\r\n .replace('\"', ' ') \\\r\n .replace('\\'', ' ') \\\r\n .replace('!', '') \\\r\n .replace('?', '') \\\r\n .replace('_', '') \\\r\n .replace('/', '') \\\r\n .replace(',', '') \\\r\n .replace(':', '') \\\r\n .replace(';', '') \\\r\n .replace('*', '') \\\r\n .replace('`', '') \\\r\n .replace('&', '') \\\r\n .replace('\\\\', '') \\\r\n .split(' ')\r\n words = list(filter(None, words))\r\n words = list(filter(lambda x: x != '-', words))\r\n\r\n for word in words:\r\n word = word.lower()\r\n try:\r\n index = self.word_to_index.index(word)\r\n except ValueError:\r\n if __name__ == '__main__':\r\n print('Unknown word: ' + word)\r\n index = self.word_to_index.index('UNKNOWN_WORD_TOKEN')\r\n word_vector = np.zeros(VOCAB_SIZE)\r\n word_vector[index] = 1\r\n vectors_and_label['vectors'].append(word_vector)\r\n\r\n time_steps = np.max([len(vectors_and_label['vectors']), time_steps])\r\n vectors_and_labels.append(vectors_and_label)\r\n\r\n batch_matrix = torch.zeros(batch_size, int(np.min([time_steps, MAX_LENGTH])), VOCAB_SIZE)\r\n label_matrix = torch.zeros(batch_size, 2).type(torch.LongTensor)\r\n\r\n for batch_number, vectors_and_label in enumerate(vectors_and_labels):\r\n vectors = vectors_and_label['vectors']\r\n # Pad vectors to max length in batch and limit to MAX_LENGTH\r\n vectors += [np.zeros(VOCAB_SIZE)] * (time_steps - len(vectors))\r\n if time_steps > MAX_LENGTH:\r\n vectors = vectors[:MAX_LENGTH]\r\n\r\n label = vectors_and_label['label']\r\n label_matrix[batch_number, :] = torch.from_numpy(label).type(torch.LongTensor)\r\n\r\n for time_step, vector in enumerate(vectors):\r\n batch_matrix[batch_number, time_step, :] = torch.from_numpy(vector)\r\n\r\n return batch_matrix, label_matrix\r\n\r\n def get_next_minibatch(self, dataset_split, batch_size):\r\n epoch_end = False\r\n\r\n if self.data_index[dataset_split] == 0:\r\n random.shuffle(self.dataset[dataset_split])\r\n if dataset_split == 'train':\r\n self.epoch_count += 1\r\n print('\\nEpoch %i' % self.epoch_count)\r\n\r\n start_pos = self.data_index[dataset_split]\r\n end_pos = start_pos + batch_size\r\n\r\n if end_pos >= len(self.dataset[dataset_split]):\r\n end_pos = len(self.dataset[dataset_split])\r\n self.data_index[dataset_split] = 0\r\n epoch_end = True\r\n else:\r\n self.data_index[dataset_split] += batch_size\r\n\r\n minibatch = self.dataset[dataset_split][start_pos:end_pos]\r\n return self.__load_text_as_vectors(minibatch), epoch_end\r\n\r\n\r\ndef test():\r\n dataset = Dataset('dataset')\r\n assert(len(dataset.word_to_index) == VOCAB_SIZE)\r\n\r\n minibatch = dataset.get_next_minibatch('train', 3)\r\n assert(minibatch[0][0].size()[0] == 3)\r\n assert(minibatch[0][0].size()[2] == VOCAB_SIZE)\r\n assert(minibatch[0][1].size()[0] == 3)\r\n assert(minibatch[0][1].size()[1] == 2)\r\n\r\nif __name__ == '__main__':\r\n test()\r\n"
] | [
[
"torch.zeros",
"torch.from_numpy",
"numpy.min",
"numpy.zeros"
]
] |
rmothukuru/probability | [
"24352279e5e255e054bfe9c7bdc7080ecb280fba"
] | [
"tensorflow_probability/python/bijectors/reciprocal.py"
] | [
"# Copyright 2018 The TensorFlow Probability 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\"\"\"A `Bijector` that computes `b(x) = 1. / x`.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.bijectors import bijector\nfrom tensorflow_probability.python.internal import assert_util\nfrom tensorflow_probability.python.internal import auto_composite_tensor\nfrom tensorflow_probability.python.internal import dtype_util\n\n__all__ = ['Reciprocal']\n\n\n@auto_composite_tensor.auto_composite_tensor(omit_kwargs=('name',))\nclass Reciprocal(bijector.AutoCompositeTensorBijector):\n \"\"\"A `Bijector` that computes the reciprocal `b(x) = 1. / x` entrywise.\n\n This bijector accepts any non-zero values for both `forward` and `inverse`.\n\n #### Examples\n\n ```python\n bijector.Reciprocal().forward(x=[[1., 2.], [4., 5.]])\n # Result: [[1., .5], [.25, .2]], i.e., 1 / x\n\n bijector.Reciprocal().forward(x=[[0., 2.], [4., 5.]])\n # Result: AssertionError, doesn't accept zero.\n\n bijector.Square().inverse(y=[[1., 2.], [4., 5.]])\n # Result: [[1., .5], [.25, .2]], i.e. 1 / x\n\n ```\n \"\"\"\n\n _type_spec_id = 366918664\n\n def __init__(self, validate_args=False, name='reciprocal'):\n \"\"\"Instantiates the `Reciprocal`.\n\n Args:\n validate_args: Python `bool` indicating whether arguments should be\n checked for correctness.\n name: Python `str` name given to ops managed by this object.\n \"\"\"\n parameters = dict(locals())\n with tf.name_scope(name) as name:\n super(Reciprocal, self).__init__(\n forward_min_event_ndims=0,\n validate_args=validate_args,\n parameters=parameters,\n name=name)\n\n @classmethod\n def _is_increasing(cls):\n return False\n\n @classmethod\n def _parameter_properties(cls, dtype):\n return dict()\n\n def _forward(self, x):\n with tf.control_dependencies(self._assertions(x)):\n return 1. / x\n\n _inverse = _forward\n\n def _forward_log_det_jacobian(self, x):\n with tf.control_dependencies(self._assertions(x)):\n return -2. * tf.math.log(tf.math.abs(x))\n\n _inverse_log_det_jacobian = _forward_log_det_jacobian\n\n def _assertions(self, t):\n if not self.validate_args:\n return []\n return [assert_util.assert_none_equal(\n t, dtype_util.as_numpy_dtype(t.dtype)(0.),\n message='All elements must be non-zero.')]\n"
] | [
[
"tensorflow.compat.v2.name_scope",
"tensorflow.compat.v2.math.abs"
]
] |
SchetininVitaliy/AeroPy | [
"65a4c68fafcbd0bd04ee70ffa9d4a98302a45c6b"
] | [
"aeropy/filehandling/vtk.py"
] | [
"import numpy as np\n\ndef generate_surface(data, filename='panair') :\n '''\n Function to generate vtk files from a panair input mesh \n INPUT :\n - data is a list of networks which are 3D arrays with the dimensions being \n columns, rows, and coordinates)\n - 'filename' is a string to use in filenames. \n For example 'panair' will result in files called 'panair_network_1', etc.\n \n OUTPUT : \n The function will produce one or several files, one for each network, \n in the folder it's run from.\n '''\n from evtk.hl import gridToVTK\n # TODO: Currently not working when meshes seeds are not the same\n def _write_network(points_array, multiple_networks = False):\n n_columns = int(points_array.shape[0])\n n_rows = int(points_array.shape[1])\n \n X = np.zeros((n_rows, n_columns, 1))\n Y = np.zeros((n_rows, n_columns, 1))\n Z = np.zeros((n_rows, n_columns, 1))\n \n for i in range(n_columns) :\n for j in range(n_rows) :\n X[j, i, 0] = points_array[i, j, 0]\n Y[j, i, 0] = points_array[i, j, 1]\n Z[j, i, 0] = points_array[i, j, 2]\n\n if multiple_networks:\n gridToVTK(filename+'_network'+str(n+1), X, Y, Z)\n else:\n gridToVTK(filename+'_network', X, Y, Z)\n \n if type(data) == dict:\n networks = len(data.keys())\n else:\n networks = len(data)\n\n if type(data) != dict:\n try:\n #check to see if list of networks or just a single one\n check = data[0][0][0][0]\n for n in range(networks) :\n points_array = data[n]\n _write_network(points_array, multiple_networks = True)\n except:\n _write_network(data, multiple_networks = False)\n else:\n for n in range(networks) :\n points_array = data[list(data.keys())[n]]\n _write_network(points_array, multiple_networks = True)\n\ndef generate_points(data, filename):\n #TODO: Still cannot visualize points well\n from evtk.hl import pointsToVTK\n x,y,z = data.T\n # Sometimes np.arrays could have manipulated to no longer\n # be c-continuous os we have to impose it\n x = np.ascontiguousarray(x)\n y = np.ascontiguousarray(y)\n z = np.ascontiguousarray(z)\n pointsToVTK(filename, x, y, z)"
] | [
[
"numpy.ascontiguousarray",
"numpy.zeros"
]
] |
zamanashiq3/code-DNN | [
"c6133740fa272f9cac005b9ee754642b5bb20975"
] | [
"time_dis_cnn.py"
] | [
"\"\"\"\nMultiple stacked lstm implemeation on the lip movement data.\n\nAkm Ashiquzzaman\[email protected]\nFall 2016\n\n\"\"\"\nfrom __future__ import print_function\nimport numpy as np\nnp.random.seed(1337)\n#random seed fixing for reproducibility\n\n#data load & preprocessing \nX_train = np.load('../data/videopart43.npy').astype('float32')\nY_train = np.load('../data/audiopart43.npy').astype('float32')\n\n#normalizing data\nX_train = X_train/255\nY_train = Y_train/32767\n\nX_train = X_train.reshape((826,13,1,53,53)).astype('float32')\nY_train = Y_train.reshape((826,13*4702)).astype('float32')\n\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Activation,Dropout,TimeDistributed,LSTM,Bidirectional\nfrom keras.layers import Convolution2D,Flatten,MaxPooling2D\nimport time\n\nprint(\"Building Model.....\")\nmodel_time = time.time()\n\nmodel = Sequential()\n\nmodel.add(TimeDistributed(Convolution2D(64, 3, 3,border_mode='valid'),batch_input_shape=(14,13,1,53,53),input_shape=(13,1,53,53)))\nmodel.add(Activation('tanh'))\nmodel.add(Dropout(0.25))\n\nmodel.add(TimeDistributed(Convolution2D(32, 2, 2, border_mode='valid')))\nmodel.add(Activation('tanh'))\n\n\nmodel.add(TimeDistributed(Flatten()))\n\nmodel.add(Bidirectional(LSTM(256,return_sequences=True,stateful=True)))\nmodel.add(Dropout(0.20))\nmodel.add(Bidirectional(LSTM(128,return_sequences=True,stateful=True)))\nmodel.add(Dropout(0.20))\nmodel.add((LSTM(64,stateful=True)))\nmodel.add(Dropout(0.20))\n\nmodel.add((Dense(512)))\nmodel.add(Activation('tanh'))\nmodel.add(Dropout(0.5))\n\nmodel.add((Dense(13*4702)))\nmodel.add(Activation('tanh'))\n\nmodel.compile(loss='mse', optimizer='rmsprop', metrics=['accuracy'])\n\n#checkpoint import\nfrom keras.callbacks import ModelCheckpoint\nfrom os.path import isfile, join\n#weight file name\nweight_file = '../weights/time-dis-cnn_weight.h5'\n\n#loading previous weight file for resuming training \nif isfile(weight_file):\n\tmodel.load_weights(weight_file)\n\n#weight-checkmark\ncheckpoint = ModelCheckpoint(weight_file, monitor='acc', verbose=1, save_best_only=True, mode='max')\n\ncallbacks_list = [checkpoint]\n\nprint(\"model compile time: \"+str(time.time()-model_time)+'s')\n\n# fit the model\nmodel.fit(X_train,Y_train, nb_epoch=1, batch_size=14,callbacks=callbacks_list)\n\npred = model.predict(X_train,batch_size=14,verbose=1)\n\npred = pred*32767\npred = pred.reshape(826*13,4702)\nprint('pred shape',pred.shape)\nprint('pred dtype',pred.dtype)\nnp.save('../predictions/pred-time-cnn.npy',pred)\n"
] | [
[
"numpy.load",
"numpy.save",
"numpy.random.seed"
]
] |
skat00sh/Handcrafted-DP | [
"d1f8bc004adc240d5c424a10bdcc30fc266c8218"
] | [
"log.py"
] | [
"import numpy as np\nimport os\nimport shutil\nimport sys\nfrom torch.utils.tensorboard import SummaryWriter\nimport torch\n\n\ndef model_input(data, device):\n datum = data.data[0:1]\n if isinstance(datum, np.ndarray):\n return torch.from_numpy(datum).float().to(device)\n else:\n return datum.float().to(device)\n\n\ndef get_script():\n py_script = os.path.basename(sys.argv[0])\n return os.path.splitext(py_script)[0]\n\n\ndef get_specified_params(hparams):\n keys = [k.split(\"=\")[0][2:] for k in sys.argv[1:]]\n specified = {k: hparams[k] for k in keys}\n return specified\n\n\ndef make_hparam_str(hparams, exclude):\n return \",\".join([f\"{key}_{value}\"\n for key, value in sorted(hparams.items())\n if key not in exclude])\n\n\nclass Logger(object):\n def __init__(self, logdir):\n\n if logdir is None:\n self.writer = None\n else:\n if os.path.exists(logdir) and os.path.isdir(logdir):\n shutil.rmtree(logdir)\n\n self.writer = SummaryWriter(log_dir=logdir)\n\n def log_model(self, model, input_to_model):\n if self.writer is None:\n return\n self.writer.add_graph(model, input_to_model)\n\n def log_epoch(self, epoch, train_loss, train_acc, test_loss, test_acc, epsilon=None):\n if self.writer is None:\n return\n self.writer.add_scalar(\"Loss/train\", train_loss, epoch)\n self.writer.add_scalar(\"Loss/test\", test_loss, epoch)\n self.writer.add_scalar(\"Accuracy/train\", train_acc, epoch)\n self.writer.add_scalar(\"Accuracy/test\", test_acc, epoch)\n\n if epsilon is not None:\n self.writer.add_scalar(\"Acc@Eps/train\", train_acc, 100*epsilon)\n self.writer.add_scalar(\"Acc@Eps/test\", test_acc, 100*epsilon)\n\n def log_scalar(self, tag, scalar_value, global_step):\n if self.writer is None or scalar_value is None:\n return\n self.writer.add_scalar(tag, scalar_value, global_step)\n"
] | [
[
"torch.utils.tensorboard.SummaryWriter",
"torch.from_numpy"
]
] |
njcuk9999/jwst-mtl | [
"81d3e7ec6adc5dae180cd9d3bff8e4a2a7292596"
] | [
"SOSS/dms/soss_engine.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# TODO remove use of args and kwargs as much as possible for clearer code.\n\n# General imports.\nimport numpy as np\nfrom scipy.sparse import issparse, csr_matrix, diags\nfrom scipy.sparse.linalg import spsolve\nfrom scipy.interpolate import interp1d, Akima1DInterpolator\nfrom scipy.optimize import minimize_scalar\n\n# Local imports.\nfrom SOSS.dms import engine_utils\n\n# Plotting.\nimport matplotlib.pyplot as plt\n\n\nclass _BaseOverlap: # TODO Merge with TrpzOverlap?\n \"\"\"\n Base class for overlaping extraction of the form:\n (B_T * B) * f = (data/sig)_T * B\n where B is a matrix and f is an array.\n The matrix multiplication B * f is the 2d model of the detector.\n We want to solve for the array f.\n The elements of f are labelled by 'k'.\n The pixels are labeled by 'i'.\n Every pixel 'i' is covered by a set of 'k' for each order\n of diffraction.\n The classes inheriting from this class should specify the\n methods get_w which computes the 'k' associated to each pixel 'i'.\n These depends of the type of interpolation used.\n \"\"\"\n def __init__(self, wave_map, aperture, throughput, kernels, # TODO rename aperture\n orders=None, global_mask=None,\n wave_grid=None, wave_bounds=None, n_os=2,\n threshold=1e-5, c_kwargs=None,\n verbose=False):\n \"\"\"\n Parameters\n ----------\n wave_map : (N_ord, N, M) list or array of 2-D arrays\n A list or array of the central wavelength position for each\n order on the detector.\n It has to have the same (N, M) as `data`.\n aperture : (N_ord, N, M) list or array of 2-D arrays\n A list or array of the spatial profile for each order\n on the detector. It has to have the same (N, M) as `data`.\n throughput : (N_ord [, N_k]) list of array or callable\n A list of functions or array of the throughput at each order.\n If callable, the functions depend on the wavelength.\n If array, projected on `wave_grid`.\n kernels : array, callable or sparse matrix\n Convolution kernel to be applied on the spectrum (f_k) for each orders.\n Can be array of the shape (N_ker, N_k_c).\n Can be a callable with the form f(x, x0) where x0 is\n the position of the center of the kernel. In this case, it must\n return a 1D array (len(x)), so a kernel value\n for each pairs of (x, x0). If array or callable,\n it will be passed to `convolution.get_c_matrix` function\n and the `c_kwargs` can be passed to this function.\n If sparse, the shape has to be (N_k_c, N_k) and it will\n be used directly. N_ker is the length of the effective kernel\n and N_k_c is the length of the spectrum (f_k) convolved.\n global_mask : (N, M) array_like boolean, optional\n Boolean Mask of the detector pixels to mask for every extraction.\n orders: list, optional:\n List of orders considered. Default is orders = [1, 2]\n wave_grid : (N_k) array_like, optional\n The grid on which f(lambda) will be projected.\n Default is a grid from `utils.get_soss_grid`.\n `n_os` will be passed to this function.\n wave_bounds : list or array-like (N_ord, 2), optional\n Boundary wavelengths covered by each orders.\n Default is the wavelength covered by `wave_map`.\n n_os : int, optional\n if `wave_grid`is None, it will be used to generate\n a grid. Default is 2.\n threshold : float, optional:\n The pixels where the estimated spatial profile is less than\n this value will be masked. Default is 1e-5.\n c_kwargs : list of N_ord dictionnaries or dictionnary, optional\n Inputs keywords arguments to pass to\n `convolution.get_c_matrix` function for each orders.\n If dictionnary, the same c_kwargs will be used for each orders.\n verbose : bool, optional\n Print steps. Default is False.\n \"\"\"\n\n # If no orders specified extract on orders 1 and 2.\n if orders is None:\n orders = [1, 2]\n\n ###########################\n # Save basic parameters\n ###########################\n\n # Spectral orders and number of orders.\n self.data_shape = wave_map[0].shape\n self.orders = orders\n self.n_orders = len(orders)\n self.threshold = threshold\n self.verbose = verbose\n\n # Raise error if the number of orders is not consistent.\n if self.n_orders != len(wave_map):\n msg = (\"The number of orders specified {} and the number of \"\n \"wavelength maps provided {} do not match.\")\n raise ValueError(msg.format(self.n_orders, len(wave_map)))\n\n # Detector image.\n self.data = np.full(self.data_shape, fill_value=np.nan)\n\n # Error map of each pixels.\n self.error = np.ones(self.data_shape)\n\n # Set all reference file quantities to None.\n self.wave_map = None\n self.aperture = None\n self.throughput = None\n self.kernels = None\n\n # Set the wavelength map and aperture for each order.\n self.update_wave_map(wave_map)\n self.update_aperture(aperture)\n\n # Generate a wavelength grid if none was provided. TODO Requires self.aperture self.wave_map\n if wave_grid is None:\n\n if self.n_orders == 2: # TODO should this be mandatory input.\n wave_grid = engine_utils.get_soss_grid(wave_map, aperture, n_os=n_os) # TODO check difference between get_soss_grid and grid_from_map\n else:\n wave_grid, _ = self.grid_from_map()\n\n # Set the wavelength grid and its size.\n self.wave_grid = wave_grid.copy()\n self.n_wavepoints = len(wave_grid)\n\n # Set the throughput for each order.\n self.update_throughput(throughput) # TODO requires self.wave_grid\n\n ###################################\n # Build detector mask\n ###################################\n\n # Assign a first estimate of i_bounds to be able to compute mask.\n self.i_bounds = [[0, len(wave_grid)] for _ in range(self.n_orders)] # TODO double check how the i_bounds and mask interact.\n\n # First estimate of a global mask and masks for each orders\n self.mask, self.mask_ord = self._get_masks(global_mask)\n\n # Correct i_bounds if it was not specified\n self.i_bounds = self._get_i_bnds(wave_bounds)\n\n # Re-build global mask and masks for each orders\n self.mask, self.mask_ord = self._get_masks(global_mask)\n\n # Save mask here as the general mask,\n # since `mask` attribute can be changed.\n self.general_mask = self.mask.copy()\n\n ####################################\n # Build convolution matrix\n ####################################\n self.update_kernels(kernels, c_kwargs) # TODO requires self.wave_grid self.i_bounds\n\n #############################\n # Compute integration weights\n #############################\n # The weights depend on the integration method used solve\n # the integral of the flux over a pixel and are encoded\n # in the class method `get_w()`.\n self.weights, self.weights_k_idx = self.compute_weights() # TODO put shapes in commments, name of indices.\n\n #########################\n # Save remaining inputs\n #########################\n\n # Set masked values to zero. TODO may not be necessary.\n self.data[self.mask] = 0\n\n # Init the pixel mapping (b_n) matrices. Matrices that transforms the 1D spectrum to a the image pixels.\n self.pixel_mapping = [None for _ in range(self.n_orders)]\n self.i_grid = None\n self.tikho = None\n self.tikho_mat = None\n self.w_t_wave_c = None\n\n return\n\n def verbose_print(self, *args, **kwargs):\n \"\"\"Print if verbose is True. Same as `print` function.\"\"\"\n\n if self.verbose:\n print(*args, **kwargs)\n\n return\n\n def get_attributes(self, *args, i_order=None):\n \"\"\"Return list of attributes\n\n Parameters\n ----------\n args: str\n All attributes to return.\n i_order: None or int, optionoal\n Index of order to extract. If specified, it will\n be applied to all attributes in args, so it cannot\n be mixed with non-order dependent attributes).\n \"\"\"\n\n if i_order is None:\n out = [getattr(self, arg) for arg in args]\n else:\n out = [getattr(self, arg)[i_order] for arg in args]\n\n if len(out) == 1:\n out = out[0]\n\n return out\n\n def update_wave_map(self, wave_map):\n\n self.wave_map = [wave_n.copy() for wave_n in wave_map] # TODO make dict with order number as key.\n\n return\n\n def update_aperture(self, aperture):\n \"\"\"Update the aperture maps.\"\"\"\n\n # Update the aperture profile.\n self.aperture = [aperture_n.copy() for aperture_n in aperture] # TODO make dict with order number as key.\n\n return\n\n def update_throughput(self, throughput):\n \"\"\"Update the throughput values.\"\"\"\n\n # Update the throughput values.\n throughput_new = [] # TODO make dict with order number as key.\n for throughput_n in throughput: # Loop over orders.\n\n if callable(throughput_n):\n\n # Througput was given as a callable function.\n throughput_new.append(throughput_n(self.wave_grid))\n\n elif throughput_n.shape == self.wave_grid.shape:\n\n # Throughput was given as an array.\n throughput_new.append(throughput_n)\n\n else:\n msg = 'Throughputs must be given as callable or arrays matching the extraction grid.'\n raise ValueError(msg)\n\n # Set the attribute to the new values.\n self.throughput = throughput_new\n\n return\n\n def update_kernels(self, kernels, c_kwargs):\n\n # Verify the c_kwargs. TODO Be explict here?\n if c_kwargs is None:\n c_kwargs = [{} for _ in range(self.n_orders)]\n\n elif isinstance(c_kwargs, dict):\n c_kwargs = [c_kwargs for _ in range(self.n_orders)]\n\n # Define convolution sparse matrix. TODO make dict with order number as key.\n kernels_new = []\n for i_order, kernel_n in enumerate(kernels):\n\n if not issparse(kernel_n):\n kernel_n = engine_utils.get_c_matrix(kernel_n, self.wave_grid,\n i_bounds=self.i_bounds[i_order],\n **c_kwargs[i_order])\n\n kernels_new.append(kernel_n)\n\n self.kernels = kernels_new\n\n return\n\n def get_mask_wave(self, i_order):\n \"\"\"Mask according to wavelength grid \"\"\"\n\n wave = self.wave_map[i_order]\n imin, imax = self.i_bounds[i_order]\n wave_min = self.wave_grid[imin]\n wave_max = self.wave_grid[imax - 1] # TODO change so -1 not needed?\n\n mask = (wave <= wave_min) | (wave >= wave_max)\n\n return mask\n\n def _get_masks(self, global_mask):\n \"\"\"\n Compute a general mask on the detector and for each orders.\n Depends on the spatial profile, the wavelength grid\n and the user defined mask (optional). These are all specified\n when initiating the object.\n \"\"\"\n\n # Get needed attributes\n threshold, n_orders = self.get_attributes('threshold', 'n_orders')\n throughput, aperture, wave_map = self.get_attributes('throughput', 'aperture', 'wave_map')\n\n # Mask according to the spatial profile.\n mask_aperture = np.array([aperture_n < threshold for aperture_n in aperture])\n\n # Mask pixels not covered by the wavelength grid.\n mask_wave = np.array([self.get_mask_wave(i_order) for i_order in range(n_orders)])\n\n # Apply user defined mask.\n if global_mask is None:\n mask_ord = np.any([mask_aperture, mask_wave], axis=0)\n else:\n mask = [global_mask for _ in range(n_orders)] # For each orders\n mask_ord = np.any([mask_aperture, mask_wave, mask], axis=0)\n\n # Find pixels that are masked in each order.\n general_mask = np.all(mask_ord, axis=0)\n\n # Mask pixels if mask_aperture not masked but mask_wave is.\n # This means that an order is contaminated by another\n # order, but the wavelength range does not cover this part\n # of the spectrum. Thus, it cannot be treated correctly.\n general_mask |= (np.any(mask_wave, axis=0)\n & np.all(~mask_aperture, axis=0))\n\n # Apply this new general mask to each orders.\n mask_ord = (mask_wave | general_mask[None, :, :])\n\n return general_mask, mask_ord\n\n def update_mask(self, mask):\n \"\"\"\n Update `mask` attribute by completing the\n `general_mask` attribute with the input `mask`.\n Everytime the mask is changed, the integration weights\n need to be recomputed since the pixels change.\n \"\"\"\n\n # Get general mask\n general_mask = self.general_mask\n\n # Complete with the input mask\n new_mask = (general_mask | mask)\n\n # Update attribute\n self.mask = new_mask\n\n # Correct i_bounds if it was not specified\n # self.update_i_bnds()\n\n # Re-compute weights\n self.weights, self.weights_k_idx = self.compute_weights()\n\n return\n\n def _get_i_bnds(self, wave_bounds=None):\n \"\"\"\n Define wavelength boundaries for each orders using the order's mask.\n \"\"\"\n\n wave_grid = self.wave_grid\n i_bounds = self.i_bounds\n\n # Check if wave_bounds given\n if wave_bounds is None:\n wave_bounds = []\n for i in range(self.n_orders):\n wave = self.wave_map[i][~self.mask_ord[i]]\n wave_bounds.append([wave.min(), wave.max()])\n\n # What we need is the boundary position\n # on the wavelength grid.\n i_bnds_new = []\n for bounds, i_bnds in zip(wave_bounds, i_bounds):\n\n a = np.min(np.where(wave_grid >= bounds[0])[0])\n b = np.max(np.where(wave_grid <= bounds[1])[0]) + 1\n\n # Take the most restrictive bound\n a = np.maximum(a, i_bnds[0])\n b = np.minimum(b, i_bnds[1])\n\n # Keep value\n i_bnds_new.append([a, b])\n\n return i_bnds_new\n\n def update_i_bnds(self):\n \"\"\"Update the grid limits for the extraction.\n Needs to be done after modification of the mask\n \"\"\"\n\n # Get old and new boundaries.\n i_bnds_old = self.i_bounds\n i_bnds_new = self._get_i_bnds()\n\n for i_order in range(self.n_orders):\n\n # Take most restrictive lower bound.\n low_bnds = [i_bnds_new[i_order][0], i_bnds_old[i_order][0]]\n i_bnds_new[i_order][0] = np.max(low_bnds)\n\n # Take most restrictive upper bound.\n up_bnds = [i_bnds_new[i_order][1], i_bnds_old[i_order][1]]\n i_bnds_new[i_order][1] = np.min(up_bnds)\n\n # Update attribute.\n self.i_bounds = i_bnds_new\n\n return\n\n def wave_grid_c(self, i_order):\n \"\"\"\n Return wave_grid for the convolved flux at a given order.\n \"\"\"\n\n index = slice(*self.i_bounds[i_order])\n\n return self.wave_grid[index]\n\n def get_w(self, i_order):\n \"\"\"Dummy method to be able to init this class\"\"\"\n\n return np.array([]), np.array([])\n\n def compute_weights(self):\n \"\"\"\n Compute integration weights\n\n The weights depend on the integration method used solve\n the integral of the flux over a pixel and are encoded\n in the class method `get_w()`.\n\n Returns the lists of weights and corresponding grid indices\n \"\"\"\n\n # Init lists\n weights, weights_k_idx = [], []\n for i_order in range(self.n_orders): # For each orders\n\n weights_n, k_idx_n = self.get_w(i_order) # Compute weigths\n\n # Convert to sparse matrix\n # First get the dimension of the convolved grid\n n_kc = np.diff(self.i_bounds[i_order]).astype(int)[0]\n\n # Then convert to sparse\n weights_n = engine_utils.sparse_k(weights_n, k_idx_n, n_kc)\n weights.append(weights_n), weights_k_idx.append(k_idx_n)\n\n return weights, weights_k_idx\n\n def _set_w_t_wave_c(self, i_order, product): # TODO better name? prod_mat tmp_mat, intermediate_mat?\n \"\"\"\n Save the matrix product of the weighs (w), the throughput (t),\n the wavelength (lam) and the convolution matrix for faster computation.\n \"\"\"\n\n if self.w_t_wave_c is None:\n self.w_t_wave_c = [[] for _ in range(self.n_orders)] # TODO make dict with order number as key.\n\n # Assign value\n self.w_t_wave_c[i_order] = product.copy()\n\n return\n\n def grid_from_map(self, i_order=0):\n \"\"\"\n Return the wavelength grid and the columns associated\n to a given order index (i_order)\n \"\"\"\n\n attrs = ['wave_map', 'aperture']\n wave_map, aperture = self.get_attributes(*attrs, i_order=i_order)\n\n wave_grid, icol = engine_utils._grid_from_map(wave_map, aperture, out_col=True)\n\n return wave_grid, icol\n\n def get_adapt_grid(self, spectrum=None, n_max=3, **kwargs):\n \"\"\"\n Return an irregular grid needed to reach a\n given precision when integrating over each pixels.\n\n Parameters (all optional)\n ----------\n spectrum (f_k): 1D array-like\n Input flux in the integral to be optimized.\n f_k is the projection of the flux on self.wave_grid\n n_max: int (n_max > 0)\n Maximum number of nodes in each intervals of self.wave_grid.\n Needs to be greater then zero.\n\n kwargs (arguments passed to the function get_n_nodes)\n ------\n tol, rtol : float, optional\n The desired absolute and relative tolerances. Defaults are 1.48e-4.\n divmax : int, optional\n Maximum order of extrapolation. Default is 10.\n\n Returns\n -------\n os_grid : 1D array\n Oversampled grid which minimizes the integration error based on\n Romberg's method\n See Also\n --------\n utils.get_n_nodes\n scipy.integrate.quadrature.romberg\n References\n ----------\n [1] 'Romberg's method' https://en.wikipedia.org/wiki/Romberg%27s_method\n\n \"\"\"\n # Generate the spectrum (f_k) if not given.\n if spectrum is None:\n spectrum = self.extract()\n\n # Init output oversampled grid\n os_grid = []\n\n # Iterate starting with the last order\n for i_order in range(self.n_orders - 1, -1, -1): # TODO easier way of inverse loop?\n\n # Grid covered by this order\n grid_ord = self.wave_grid_c(i_order)\n\n # Estimate the flux at this order\n convolved_spectrum = self.kernels[i_order].dot(spectrum)\n # Interpolate with a cubic spline\n fct = interp1d(grid_ord, convolved_spectrum, kind='cubic')\n\n # Find number of nodes to reach the precision\n n_oversample, _ = engine_utils.get_n_nodes(grid_ord, fct, **kwargs)\n\n # Make sure n_oversample is not greater than\n # user's define `n_max`\n n_oversample = np.clip(n_oversample, 0, n_max)\n\n # Generate oversampled grid\n grid_ord = engine_utils.oversample_grid(grid_ord, n_os=n_oversample)\n\n # Keep only wavelength that are not already\n # covered by os_grid.\n if os_grid:\n # Under or above os_grid\n index = (grid_ord < np.min(os_grid))\n index |= (grid_ord > np.max(os_grid))\n else:\n index = slice(None)\n\n # Keep these values\n os_grid.append(grid_ord[index])\n\n # Convert os_grid to 1D array\n os_grid = np.concatenate(os_grid)\n\n # Return sorted and unique.\n wave_grid = np.unique(os_grid)\n\n return wave_grid\n\n def estimate_noise(self, i_order=0, data=None, error=None, mask=None):\n \"\"\"\n Relative noise estimate over columns.\n\n Parameters\n ----------\n i_order: int, optional\n index of diffraction order. Default is 0\n data: 2d array, optional\n map of the detector image\n Default is `self.data`.\n error: 2d array, optional\n map of the estimate of the detector noise.\n Default is `self.sig`\n mask: 2d array, optional\n Bool map of the masked pixels for order `i_order`.\n Default is `self.mask_ord[i_order]`\n\n Returns\n ------\n wave_grid, noise\n \"\"\"\n\n # Use object attributes if not given\n if data is None:\n data = self.data\n\n if error is None:\n error = self.error\n\n if mask is None:\n mask = self.mask_ord[i_order]\n\n # Compute noise estimate only on the trace (mask the rest)\n noise = np.ma.array(error, mask=mask)\n\n # RMS over columns\n noise = np.sqrt((noise**2).sum(axis=0))\n\n # Relative\n noise /= np.ma.array(data, mask=mask).sum(axis=0)\n\n # Convert to array with nans\n noise = noise.filled(fill_value=np.nan)\n\n # Get associated wavelengths\n wave_grid, i_col = self.grid_from_map(i_order)\n\n # Return sorted according to wavelenghts\n return wave_grid, noise[i_col]\n\n def get_pixel_mapping(self, i_order, same=False, error=True, quick=False):\n \"\"\"\n Compute the matrix `b_n = (P/sig).w.T.lambda.c_n` ,\n where `P` is the spatial profile matrix (diag),\n `w` is the integrations weights matrix,\n `T` is the throughput matrix (diag),\n `lambda` is the convolved wavelength grid matrix (diag),\n `c_n` is the convolution kernel.\n The model of the detector at order n (`model_n`)\n is given by the system:\n model_n = b_n.c_n.f ,\n where f is the incoming flux projected on the wavelenght grid.\n This methods updates the `b_n_list` attribute.\n Parameters\n ----------\n i_order: integer\n Label of the order (depending on the initiation of the object).\n same: bool, optional\n Do not recompute, b_n. Take the last b_n computed.\n Useful to speed up code. Default is False.\n error: bool or (N, M) array_like, optional\n If 2-d array, `sig` is the new error estimation map.\n It is the same shape as `sig` initiation input. If bool,\n wheter to apply sigma or not. The method will return\n b_n/sigma if True or array_like and b_n if False. If True,\n the default object attribute `sig` will be use.\n quick: bool, optional\n If True, only perform one matrix multiplication\n instead of the whole system: (P/sig).(w.T.lambda.c_n)\n\n Returns\n ------\n sparse matrix of b_n coefficients\n \"\"\"\n\n # Force to compute if b_n never computed.\n if self.pixel_mapping[i_order] is None:\n same = False\n\n # Take the last b_n computed if nothing changes\n if same:\n pixel_mapping = self.pixel_mapping[i_order]\n\n else:\n pixel_mapping = self._get_pixel_mapping(i_order, error=error, quick=quick)\n\n # Save new pixel mapping matrix.\n self.pixel_mapping[i_order] = pixel_mapping\n\n return pixel_mapping\n\n def _get_pixel_mapping(self, i_order, error=True, quick=False): # TODO merge with get_pixel_mapping?\n \"\"\"\n Compute the matrix `b_n = (P/sig).w.T.lambda.c_n` ,\n where `P` is the spatial profile matrix (diag),\n `w` is the integrations weights matrix,\n `T` is the throughput matrix (diag),\n `lambda` is the convolved wavelength grid matrix (diag),\n `c_n` is the convolution kernel.\n The model of the detector at order n (`model_n`)\n is given by the system:\n model_n = b_n.c_n.f ,\n where f is the incoming flux projected on the wavelenght grid.\n Parameters\n ----------\n i_order : integer\n Label of the order (depending on the initiation of the object).\n error: bool or (N, M) array_like, optional\n If 2-d array, `sig` is the new error estimation map.\n It is the same shape as `sig` initiation input. If bool,\n wheter to apply sigma or not. The method will return\n b_n/sigma if True or array_like and b_n if False. If True,\n the default object attribute `sig` will be use.\n quick: bool, optional\n If True, only perform one matrix multiplication\n instead of the whole system: (P/sig).(w.T.lambda.c_n)\n\n Returns\n ------\n sparse matrix of b_n coefficients\n \"\"\"\n\n # Special treatment for error map\n # Can be bool or array.\n if error is False:\n # Sigma will have no effect\n error = np.ones(self.data_shape)\n else:\n if error is not True:\n # Sigma must be an array so\n # update object attribute\n self.error = error.copy()\n\n # Take sigma from object\n error = self.error\n\n # Get needed attributes ...\n attrs = ['wave_grid', 'mask']\n wave_grid, mask = self.get_attributes(*attrs)\n\n # ... order dependent attributes\n attrs = ['aperture', 'throughput', 'kernels', 'weights', 'i_bounds']\n aperture_n, throughput_n, kernel_n, weights_n, i_bnds = self.get_attributes(*attrs, i_order=i_order)\n\n # Keep only valid pixels (P and sig are still 2-D)\n # And apply direcly 1/sig here (quicker)\n aperture_n = aperture_n[~mask] / error[~mask]\n\n # Compute b_n\n # Quick mode if only `p_n` or `sig` has changed\n if quick:\n # Get pre-computed (right) part of the equation\n right = self.w_t_wave_c[i_order]\n\n # Apply new p_n\n pixel_mapping = diags(aperture_n).dot(right)\n\n else:\n # First (T * lam) for the convolve axis (n_k_c)\n product = (throughput_n * wave_grid)[slice(*i_bnds)]\n\n # then convolution\n product = diags(product).dot(kernel_n)\n\n # then weights\n product = weights_n.dot(product)\n\n # Save this product for quick mode\n self._set_w_t_wave_c(i_order, product)\n\n # Then spatial profile\n pixel_mapping = diags(aperture_n).dot(product)\n\n return pixel_mapping\n\n def get_i_grid(self, d):\n \"\"\" Return the index of the grid that are well defined, so d != 0 \"\"\"\n\n if self.i_grid is None: # TODO Shouldn't this update even if the attribute is already set?\n self.i_grid = np.nonzero(d)[0]\n\n return self.i_grid\n\n def build_sys(self, data=None, error=True, mask=None, aperture=None, throughput=None):\n \"\"\"\n Build linear system arising from the logL maximisation.\n TIPS: To be quicker, only specify the psf (`p_list`) in kwargs.\n There will be only one matrix multiplication:\n (P/sig).(w.T.lambda.c_n).\n Parameters\n ----------\n data : (N, M) array_like, optional\n A 2-D array of real values representing the detector image.\n Default is the object attribute `data`.\n error: bool or (N, M) array_like, optional\n Estimate of the error on each pixel.\n If 2-d array, `sig` is the new error estimation map.\n It is the same shape as `sig` initiation input. If bool,\n wheter to apply sigma or not. The method will return\n b_n/sigma if True or array_like and b_n if False. If True,\n the default object attribute `sig` will be use.\n mask : (N, M) array_like boolean, optional\n Additionnal mask for a given exposure. Will be added\n to the object general mask.\n aperture : (N_ord, N, M) list or array of 2-D arrays, optional\n A list or array of the spatial profile for each order\n on the detector. It has to have the same (N, M) as `data`.\n Default is the object attribute `p_list`\n throughput : (N_ord [, N_k]) list or array of functions, optional\n A list or array of the throughput at each order.\n The functions depend on the wavelength\n Default is the object attribute `t_list`\n\n Returns\n ------\n A and b from Ax = b beeing the system to solve.\n \"\"\"\n\n # Check if inputs are suited for quick mode;\n # Quick mode if `t_list` is not specified.\n quick = (throughput is None)\n\n # and if mask doesn't change\n quick &= (mask is None)\n quick &= (self.w_t_wave_c is not None) # Pre-computed\n if quick:\n self.verbose_print('Quick mode is on!')\n\n # Use data from object as default\n if data is None:\n data = self.data\n else:\n # Update data\n self.data = data\n\n # Update mask if given\n if mask is not None:\n self.update_mask(mask)\n\n # Take (updated) mask from object\n mask = self.mask\n\n # Get some dimensions infos\n n_wavepoints, n_orders = self.n_wavepoints, self.n_orders\n\n # Update aperture maps and throughput values.\n if aperture is not None:\n self.update_aperture(aperture)\n\n if throughput is not None:\n self.update_throughput(throughput)\n\n # Calculations\n\n # Build matrix B\n # Initiate with empty matrix\n n_i = (~mask).sum() # n good pixels\n b_matrix = csr_matrix((n_i, n_wavepoints))\n\n # Sum over orders\n for i_order in range(n_orders):\n\n # Get sparse pixel mapping matrix.\n b_matrix += self.get_pixel_mapping(i_order, error=error, quick=quick)\n\n # Build system\n # Fisrt get `sig` which have been update`\n # when calling `get_b_n`\n error = self.error\n\n # Take only valid pixels and apply `error` on data\n data = data[~mask]/error[~mask]\n\n # (B_T * B) * f = (data/sig)_T * B\n # (matrix ) * f = result\n matrix = b_matrix.T.dot(b_matrix)\n result = csr_matrix(data.T).dot(b_matrix)\n\n return matrix, result.toarray().squeeze()\n\n def set_tikho_matrix(self, t_mat=None, t_mat_func=None,\n fargs=None, fkwargs=None):\n \"\"\"\n Set the tikhonov matrix attribute.\n The matrix can be directly specified as an input, or\n it can be built using `t_mat_func`\n\n Parameters\n ----------\n t_mat: matrix-like, optional\n TIkhonov regularisation matrix. scipy.sparse matrix\n are recommended.\n t_mat_func: callable, optional\n Function use to generate `t_mat`is not specified.\n Will take `fargs` and `fkwargs`as imput.\n fargs: tuple, optional\n Arguments passed to `t_mat_func`\n fkwargs: dict, optional\n Keywords arguments passed to `t_mat_func`\n \"\"\"\n\n # Generate the matrix with the function\n if t_mat is None:\n\n # Default function if not specified\n if t_mat_func is None:\n\n # Use the nyquist sampled gaussian kernel\n t_mat_func = engine_utils.get_nyquist_matrix\n\n # Default args\n if fargs is None:\n fargs = (self.wave_grid, )\n if fkwargs is None:\n fkwargs = {\"integrate\": True}\n\n # Call function\n t_mat = t_mat_func(*fargs, **fkwargs)\n\n # Set attribute\n self.tikho_mat = t_mat\n\n return\n\n def get_tikho_matrix(self, **kwargs):\n \"\"\"\n Return the tikhonov matrix.\n Generate it with `set_tikho_matrix` method\n if not define yet. If so, all arguments are passed\n to `set_tikho_matrix`. The result is saved as an attribute.\n \"\"\"\n\n if self.tikho_mat is None:\n self.set_tikho_matrix(**kwargs)\n\n return self.tikho_mat\n\n def get_tikho_tests(self, factors, tikho=None, estimate=None,\n tikho_kwargs=None, **kwargs):\n \"\"\"\n Test different factors for Tikhonov regularisation.\n\n Parameters\n ----------\n factors: 1D list or array-like\n Factors to be tested.\n tikho: Tikhonov object, optional\n Tikhonov regularisation object (see regularisation.Tikhonov).\n If not given, an object will be initiated using the linear system\n from `build_sys` method and kwargs will be passed.\n estimate: 1D array-like, optional\n Estimate of the flux projected on the wavelength grid.\n tikho_kwargs:\n passed to init Tikhonov object. Possible options\n are `t_mat`, `grid` and `verbose`\n data : (N, M) array_like, optional\n A 2-D array of real values representing the detector image.\n Default is the object attribute `data`.\n error : (N, M) array_like, optional\n Estimate of the error on each pixel`\n Same shape as `data`.\n Default is the object attribute `sig`.\n aperture : (N_ord, N, M) list or array of 2-D arrays, optional\n A list or array of the spatial profile for each order\n on the detector. It has to have the same (N, M) as `data`.\n Default is the object attribute `p_list`\n throughput : (N_ord [, N_k]) list or array of functions, optional\n A list or array of the throughput at each order.\n The functions depend on the wavelength\n Default is the object attribute `t_list`\n\n Returns\n ------\n dictonary of the tests results\n \"\"\"\n\n # Build the system to solve\n matrix, result = self.build_sys(**kwargs)\n\n # Get valid grid index\n i_grid = self.get_i_grid(result)\n\n if tikho is None:\n t_mat = self.get_tikho_matrix()\n default_kwargs = {'grid': self.wave_grid,\n 'index': i_grid,\n 't_mat': t_mat}\n if tikho_kwargs is None:\n tikho_kwargs = {}\n tikho_kwargs = {**default_kwargs, **tikho_kwargs}\n tikho = engine_utils.Tikhonov(matrix, result, **tikho_kwargs)\n self.tikho = tikho\n\n # Test all factors\n tests = tikho.test_factors(factors, estimate)\n\n # Generate logl using solutions for each factors\n logl_list = []\n\n # Compute b_n only the first iteration. Then\n # use the same value to rebuild the detector.\n same = False\n for sln in tests['solution']:\n\n # Init the spectrum (f_k) with nan, so it has the adequate shape\n spectrum = np.ones(result.shape[-1]) * np.nan\n spectrum[i_grid] = sln # Assign valid values\n logl_list.append(self.compute_likelihood(spectrum, same=same)) # log_l\n same = True\n\n # Save in tikho's tests\n tikho.test['-logl'] = -1 * np.array(logl_list)\n\n # Save also grid\n tikho.test[\"grid\"] = self.wave_grid[i_grid]\n tikho.test[\"i_grid\"] = i_grid\n\n return tikho.test\n\n def best_tikho_factor(self, tests=None, interpolate=True,\n interp_index=None, i_plot=False):\n \"\"\"Compute the best scale factor for Tikhonov regularisation.\n It is determine by taking the factor giving the highest logL on\n the detector.\n\n Parameters\n ----------\n tests: dictionnary, optional\n Results of tikhonov extraction tests\n for different factors.\n Must have the keys \"factors\" and \"-logl\".\n If not specified, the tests from self.tikho.tests\n are used.\n interpolate: bool, optional\n If True, use akima spline interpolation\n to find a finer minimum. Default is true.\n interp_index: 2 element list, optional\n Index around the minimum value on the tested factors.\n Will be used for the interpolation.\n For example, if i_min is the position of\n the minimum logL value and [i1, i2] = interp_index,\n then the interpolation will be perform between\n i_min + i1 and i_min + i2 - 1\n i_plot: bool, optional\n Plot the result of the minimization\n\n Returns\n -------\n Best scale factor (float)\n \"\"\"\n\n if interp_index is None:\n interp_index = [-2, 4]\n\n # Use pre-run tests if not specified\n if tests is None:\n tests = self.tikho.tests\n\n # Get relevant quantities from tests\n factors = tests[\"factors\"]\n logl = tests[\"-logl\"]\n\n # Get position of the minimum value\n i_min = np.argmin(logl)\n\n # Interpolate to get a finer value\n if interpolate:\n\n # Only around the best value\n i_range = [i_min + d_i for d_i in interp_index]\n\n # Make sure it's still a valid index\n i_range[0] = np.max([i_range[0], 0])\n i_range[-1] = np.min([i_range[-1], len(logl) - 1])\n\n # Which index to use\n index = np.arange(*i_range, 1)\n\n # Akima spline in log space\n x_val, y_val = np.log10(factors[index]), np.log10(logl[index])\n i_sort = np.argsort(x_val)\n x_val, y_val = x_val[i_sort], y_val[i_sort]\n fct = Akima1DInterpolator(x_val, y_val)\n\n # Find min\n bounds = (x_val.min(), x_val.max())\n opt_args = {\"bounds\": bounds,\n \"method\": \"bounded\"}\n min_fac = minimize_scalar(fct, **opt_args).x\n\n # Plot the fit if required\n if i_plot:\n\n # Original grid\n plt.plot(np.log10(factors), np.log10(logl), \":\")\n\n # Fit sub-grid\n plt.plot(x_val, y_val, \".\")\n\n # Show akima spline\n x_new = np.linspace(*bounds, 100)\n plt.plot(x_new, fct(x_new))\n\n # Show minimum found\n plt.plot(min_fac, fct(min_fac), \"x\")\n\n # Labels\n plt.xlabel(r\"$\\log_{10}$(factor)\")\n plt.ylabel(r\"$\\log_{10}( - \\log L)$\")\n plt.tight_layout()\n\n # Return to linear scale\n min_fac = 10.**min_fac\n\n # Simply return the minimum value if no interpolation required\n else:\n min_fac = factors[i_min]\n\n # Return scale factor minimizing the logL\n return min_fac\n\n def rebuild(self, spectrum=None, i_orders=None, same=False):\n \"\"\"Build current model image of the detector.\n\n :param spectrum: flux as a function of wavelength if callable\n or array of flux values corresponding to self.wave_grid.\n :param i_orders: Indices of orders to model. Default is\n all available orders.\n :param same: If True, do not recompute the pixel_mapping matrix (b_n)\n and instead use the most recent pixel_mapping to speed up the computation.\n Default is False.\n\n :type spectrum: callable or array-like\n :type i_orders: List[int]\n :type same: bool\n\n :returns: model - the modelled detector image.\n :rtype: array[float]\n \"\"\"\n\n # If no spectrum given compute it.\n if spectrum is None:\n spectrum = self.extract()\n\n # If flux is callable, evaluate on the wavelength grid.\n if callable(spectrum):\n spectrum = spectrum(self.wave_grid)\n\n # Iterate over all orders by default.\n if i_orders is None:\n i_orders = range(self.n_orders)\n\n # Get required class attribute.\n mask = self.mask\n\n # Evaluate the detector model.\n model = np.zeros(self.data_shape)\n for i_order in i_orders:\n\n # Compute the pixel mapping matrix (b_n) for the current order.\n pixel_mapping = self.get_pixel_mapping(i_order, error=False, same=same)\n\n # Evaluate the model of the current order.\n model[~mask] += pixel_mapping.dot(spectrum)\n\n # Set masked values to NaN.\n model[mask] = np.nan\n\n return model\n\n def compute_likelihood(self, spectrum=None, same=False):\n \"\"\"Return the log likelihood asssociated with a particular spectrum.\n\n :param spectrum: flux as a function of wavelength if callable\n or array of flux values corresponding to self.wave_grid.\n If not given it will be computed by calling self.extract().\n :param same: If True, do not recompute the pixel_mapping matrix (b_n)\n and instead use the most recent pixel_mapping to speed up the computation.\n Default is False.\n\n :type spectrum: array-like\n :type same: bool\n\n :return: logl - The log-likelihood of the spectrum.\n :rtype: array[float]\n\n \"\"\"\n\n # If no spectrum given compute it.\n if spectrum is None:\n spectrum = self.extract()\n\n # Evaluate the model image for the spectrum.\n model = self.rebuild(spectrum, same=same)\n\n # Get data and error attributes.\n data = self.data\n error = self.error\n\n # Compute the log-likelihood for the spectrum.\n logl = -np.nansum((model - data)**2/error**2)\n\n return logl\n\n @staticmethod\n def _solve(matrix, result, index=slice(None)):\n \"\"\"\n Simply pass `matrix` and `result`\n to `scipy.spsolve` and apply index.\n \"\"\"\n\n return spsolve(matrix[index, :][:, index], result[index])\n\n @staticmethod\n def _solve_tikho(matrix, result, index=slice(None), **kwargs):\n \"\"\"Solve system using Tikhonov regularisation\"\"\"\n\n # Note that the indexing is applied inside the function\n return engine_utils.tikho_solve(matrix, result, index=index, **kwargs)\n\n def extract(self, tikhonov=False, tikho_kwargs=None, # TODO merge with __call__.\n factor=None, **kwargs):\n \"\"\"\n Extract underlying flux on the detector.\n All parameters are passed to `build_sys` method.\n TIPS: To be quicker, only specify the psf (`p_list`) in kwargs.\n There will be only one matrix multiplication:\n (P/sig).(w.T.lambda.c_n).\n\n Parameters\n ----------\n tikhonov : bool, optional\n Wheter to use tikhonov extraction\n (see regularisation.tikho_solve function).\n Default is False.\n tikho_kwargs : dictionnary or None, optional\n Arguments passed to `tikho_solve`.\n factor : the tikhonov factor to use of tikhonov is True\n data : (N, M) array_like, optional\n A 2-D array of real values representing the detector image.\n Default is the object attribute `data`.\n error : (N, M) array_like, optional\n Estimate of the error on each pixel`\n Same shape as `data`.\n Default is the object attribute `sig`.\n mask : (N, M) array_like boolean, optional\n Additionnal mask for a given exposure. Will be added\n to the object general mask.\n aperture : (N_ord, N, M) list or array of 2-D arrays, optional\n A list or array of the spatial profile for each order\n on the detector. It has to have the same (N, M) as `data`.\n Default is the object attribute `p_list`\n throughput : (N_ord [, N_k]) list or array of functions, optional\n A list or array of the throughput at each order.\n The functions depend on the wavelength\n Default is the object attribute `t_list`\n\n Returns\n -----\n spectrum (f_k): solution of the linear system\n \"\"\"\n\n # Build the system to solve\n matrix, result = self.build_sys(**kwargs)\n\n # Get index of `wave_grid` convered by the pixel.\n # `wave_grid` may cover more then the pixels.\n i_grid = self.get_i_grid(result)\n\n # Init spectrum with NaNs.\n spectrum = np.ones(result.shape[-1]) * np.nan\n\n # Solve with the specified solver.\n # Only solve for valid range `i_grid` (on the detector).\n # It will be a singular matrix otherwise.\n if tikhonov:\n\n if factor is None:\n raise ValueError(\"Please specify tikhonov `factor`.\")\n\n t_mat = self.get_tikho_matrix()\n default_kwargs = {'grid': self.wave_grid,\n 'index': i_grid,\n 't_mat': t_mat,\n 'factor': factor}\n\n if tikho_kwargs is None:\n tikho_kwargs = {}\n\n tikho_kwargs = {**default_kwargs, **tikho_kwargs}\n spectrum[i_grid] = self._solve_tikho(matrix, result, **tikho_kwargs)\n\n else:\n spectrum[i_grid] = self._solve(matrix, result, index=i_grid)\n\n return spectrum\n\n def __call__(self, **kwargs):\n \"\"\"\n Extract underlying flux on the detector by calling\n the `extract` method.\n All parameters are passed to `build_sys` method.\n TIPS: To be quicker, only specify the psf (`p_list`) in kwargs.\n There will be only one matrix multiplication:\n (P/sig).(w.T.lambda.c_n).\n Parameters\n ----------\n tikhonov : bool, optional\n Wheter to use tikhonov extraction\n (see regularisation.tikho_solve function).\n Default is False.\n tikho_kwargs : dictionnary or None, optional\n Arguments passed to `tikho_solve`.\n data : (N, M) array_like, optional\n A 2-D array of real values representing the detector image.\n Default is the object attribute `data`.\n error : (N, M) array_like, optional\n Estimate of the error on each pixel`\n Same shape as `data`.\n Default is the object attribute `sig`.\n mask : (N, M) array_like boolean, optional\n Additionnal mask for a given exposure. Will be added\n to the object general mask.\n throughput : (N_ord [, N_k]) list or array of functions, optional\n A list or array of the throughput at each order.\n The functions depend on the wavelength\n Default is the object attribute `t_list`\n aperture : (N_ord, N, M) list or array of 2-D arrays, optional\n A list or array of the spatial profile for each order\n on the detector. It has to have the same (N, M) as `data`.\n Default is the object attribute `p_list`\n\n Returns\n -----\n spectrum (f_k): solution of the linear system\n \"\"\"\n\n return self.extract(**kwargs)\n\n def bin_to_pixel(self, i_order=0, grid_pix=None, grid_f_k=None, convolved_spectrum=None,\n spectrum=None, bounds_error=False, throughput=None, **kwargs):\n \"\"\"\n Integrate the convolved_spectrum (f_k_c) over a pixel grid using the trapezoidal rule.\n The concoled spectrum (f_k_c) is interpolated using scipy.interpolate.interp1d and the\n kwargs and bounds_error are passed to interp1d.\n i_order: int, optional\n index of the order to be integrated, default is 0, so\n the first order specified.\n grid_pix: tuple of two 1d-arrays or 1d-array\n If a tuple of 2 arrays is given, assume it is the lower and upper\n integration ranges. If 1d-array, assume it is the center\n of the pixels. If not given, the wavelength map and the psf map\n of `i_order` will be used to compute a pixel grid.\n grid_f_k: 1d array, optional\n grid on which the convolved flux is projected.\n Default is the wavelength grid for `i_order`.\n convolved_spectrum (f_k_c): 1d array, optional\n Convolved flux to be integrated. If not given, `spectrum`\n will be used (and convolved to `i_order` resolution)\n spectrum (f_k): 1d array, optional\n non-convolved flux (result of the `extract` method).\n Not used if `convolved_spectrum` is specified.\n bounds_error and kwargs:\n passed to interp1d function to interpolate the convolved_spectrum.\n throughput: callable, optional\n Spectral throughput for a given order (ì_ord).\n Default is given by the list of throughput saved as\n the attribute `t_list`.\n \"\"\"\n # Take the value from the order if not given...\n\n # ... for the flux grid ...\n if grid_f_k is None:\n grid_f_k = self.wave_grid_c(i_order)\n\n # ... for the convolved flux ...\n if convolved_spectrum is None:\n # Use the spectrum (f_k) if the convolved_spectrum (f_k_c) not given.\n if spectrum is None:\n raise ValueError(\"`spectrum` or `convolved_spectrum` must be specified.\")\n else:\n # Convolve the spectrum (f_k).\n convolved_spectrum = self.kernels[i_order].dot(spectrum)\n\n # ... and for the pixel bins\n if grid_pix is None:\n pix_center, _ = self.grid_from_map(i_order)\n\n # Get pixels borders (plus and minus)\n pix_p, pix_m = engine_utils.get_wave_p_or_m(pix_center)\n\n else: # Else, unpack grid_pix\n\n # Could be a scalar or a 2-elements object)\n if len(grid_pix) == 2:\n\n # 2-elements object, so we have the borders\n pix_m, pix_p = grid_pix\n\n # Need to compute pixel center\n d_pix = (pix_p - pix_m)\n pix_center = grid_pix[0] + d_pix\n else:\n\n # 1-element object, so we have the pix centers\n pix_center = grid_pix\n\n # Need to compute the borders\n pix_p, pix_m = engine_utils.get_wave_p_or_m(pix_center)\n\n # Set the throughput to object attribute\n # if not given\n if throughput is None:\n\n # Need to interpolate\n x, y = self.wave_grid, self.throughput[i_order]\n throughput = interp1d(x, y)\n\n # Apply throughput on flux\n convolved_spectrum = convolved_spectrum * throughput(grid_f_k)\n\n # Interpolate\n kwargs['bounds_error'] = bounds_error\n fct_f_k = interp1d(grid_f_k, convolved_spectrum, **kwargs)\n\n # Intergrate over each bins\n bin_val = []\n for x1, x2 in zip(pix_m, pix_p):\n\n # Grid points that fall inside the pixel range\n i_grid = (x1 < grid_f_k) & (grid_f_k < x2)\n x_grid = grid_f_k[i_grid]\n\n # Add boundaries values to the integration grid\n x_grid = np.concatenate([[x1], x_grid, [x2]])\n\n # Integrate\n integrand = fct_f_k(x_grid) * x_grid\n bin_val.append(np.trapz(integrand, x_grid))\n\n # Convert to array and return with the pixel centers.\n return pix_center, np.array(bin_val)\n\n @staticmethod\n def _check_plot_inputs(fig, ax):\n \"\"\"Method to manage inputs for plots methods.\"\"\"\n\n # Use ax or fig if given. Else, init the figure\n if (fig is None) and (ax is None):\n fig, ax = plt.subplots(1, 1, sharex=True)\n elif ax is None:\n ax = fig.subplots(1, 1, sharex=True)\n\n return fig, ax\n\n def plot_tikho_factors(self):\n \"\"\"Plot results of tikhonov tests.\n\n Returns\n ------\n figure and axes (for plot)\n \"\"\"\n\n # Use tikhonov extraction from object\n tikho = self.tikho\n\n # Init figure\n fig, ax = plt.subplots(2, 1, sharex=True, figsize=(8, 6))\n\n # logl plot\n tikho.error_plot(ax=ax[0], test_key='-logl')\n\n # Error plot\n tikho.error_plot(ax=ax[1])\n\n # Labels\n ax[0].set_ylabel(r'$\\log{L}$ on detector')\n\n # Other details\n fig.tight_layout()\n\n return fig, ax\n\n def plot_sln(self, spectrum, fig=None, ax=None, i_order=0,\n ylabel='Flux', xlabel=r'Wavelength [$\\mu$m]', **kwargs):\n \"\"\"Plot extracted spectrum\n\n Parameters\n ----------\n spectrum (f_k): array-like\n Flux projected on the wavelength grid\n fig: matplotlib figure, optional\n Figure to use for plot\n If not given and ax is None, new figure is initiated\n ax: matplotlib axis, optional\n axis to use for plot. If not given, a new axis is initiated.\n i_order: int, optional\n index of the order to plot.\n Default is 0 (so the first order given).\n ylabel: str, optional\n Label of y axis\n xlabel: str, optional\n Label of x axis\n kwargs:\n other kwargs to be passed to plt.plot\n\n Returns\n ------\n fig, ax\n \"\"\"\n\n # Manage method's inputs\n fig, ax = self._check_plot_inputs(fig, ax)\n\n # Set values to plot\n x = self.wave_grid_c(i_order)\n y = self.kernels[i_order].dot(spectrum)\n\n # Plot\n ax.plot(x, y, **kwargs)\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n\n return fig, ax\n\n def plot_err(self, spectrum, f_th_ord, fig=None, ax=None,\n i_order=0, error='relative', ylabel='Error',\n xlabel=r'Wavelength [$\\mu$m]', **kwargs):\n \"\"\"Plot error on extracted spectrum\n\n Parameters\n ----------\n spectrum (f_k): array-like\n Flux projected on the wavelength grid\n f_th_ord: array-like\n Injected flux projected on the wavelength grid\n and convolved at `i_order` resolution\n fig: matplotlib figure, optional\n Figure to use for plot\n If not given and ax is None, new figure is initiated\n ax: matplotlib axis, optional\n axis to use for plot. If not given, a new axis is initiated.\n i_order: int, optional\n index of the order to plot. Default is 0 (so the first order given)\n error: str, optional\n Which type of error to plot.\n Possibilities: 'relative', 'absolute', 'to_noise'\n Default is 'relative'. To noise is the error relative\n to the expected Poisson noise error\n ylabel: str, optional\n Label of y axis\n xlabel: str, optional\n Label of x axis\n kwargs:\n other kwargs to be passed to plt.plot\n\n Returns\n ------\n fig, ax\n \"\"\"\n\n # Manage method's inputs\n fig, ax = self._check_plot_inputs(fig, ax)\n\n # Set values to plot\n x = self.wave_grid_c(i_order)\n convolved_spectrum = self.kernels[i_order].dot(spectrum)\n\n if error == 'relative':\n y = (convolved_spectrum - f_th_ord) / f_th_ord\n elif error == 'absolute':\n y = convolved_spectrum - f_th_ord\n elif error == 'to_noise':\n y = (convolved_spectrum - f_th_ord) / np.sqrt(f_th_ord)\n else:\n raise ValueError('`error` argument is not valid.')\n\n # Add info to ylabel\n ylabel += ' ({})'.format(error)\n\n # Plot\n ax.plot(x, y, **kwargs)\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n\n return fig, ax\n\n\nclass ExtractionEngine(_BaseOverlap): # TODO Merge with _BaseOverlap?\n \"\"\"\n Version of overlaping extraction with oversampled trapezoidal integration\n overlaping extraction solve the equation of the form:\n (B_T * B) * f = (data/sig)_T * B\n where B is a matrix and f is an array.\n The matrix multiplication B * f is the 2d model of the detector.\n We want to solve for the array f.\n The elements of f are labelled by 'k'.\n The pixels are labeled by 'i'.\n Every pixel 'i' is covered by a set of 'k' for each order\n of diffraction.\n \"\"\"\n\n def __init__(self, wave_map, aperture, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n aperture : (N_ord, N, M) list or array of 2-D arrays\n A list or array of the spatial profile for each order\n on the detector. It has to have the same (N, M) as `data`.\n wave_map : (N_ord, N, M) list or array of 2-D arrays\n A list or array of the central wavelength position for each\n order on the detector.\n It has to have the same (N, M) as `data`.\n throughput : (N_ord [, N_k]) list of array or callable\n A list of functions or array of the throughput at each order.\n If callable, the functions depend on the wavelength.\n If array, projected on `wave_grid`.\n kernels : array, callable or sparse matrix\n Convolution kernel to be applied on spectrum (f_k) for each orders.\n Can be array of the shape (N_ker, N_k_c).\n Can be a callable with the form f(x, x0) where x0 is\n the position of the center of the kernel. In this case, it must\n return a 1D array (len(x)), so a kernel value\n for each pairs of (x, x0). If array or callable,\n it will be passed to `convolution.get_c_matrix` function\n and the `c_kwargs` can be passed to this function.\n If sparse, the shape has to be (N_k_c, N_k) and it will\n be used directly. N_ker is the length of the effective kernel\n and N_k_c is the length of the spectrum (f_k) convolved.\n data : (N, M) array_like, optional\n A 2-D array of real values representing the detector image.\n error : (N, M) array_like, optional\n Estimate of the error on each pixel. Default is one everywhere.\n mask : (N, M) array_like boolean, optional\n Boolean Mask of the bad pixels on the detector.\n orders: list, optional:\n List of orders considered. Default is orders = [1, 2]\n wave_grid : (N_k) array_like, optional\n The grid on which f(lambda) will be projected.\n Default still has to be improved.\n wave_bounds : list or array-like (N_ord, 2), optional\n Boundary wavelengths covered by each orders.\n Default is the wavelength covered by `wave_map`.\n tresh : float, optional:\n The pixels where the estimated spatial profile is less than\n this value will be masked. Default is 1e-5.\n c_kwargs : list of N_ord dictionnaries or dictionnary, optional\n Inputs keywords arguments to pass to\n `convolution.get_c_matrix` function for each orders.\n If dictionnary, the same c_kwargs will be used for each orders.\n verbose : bool, optional\n Print steps. Default is False.\n \"\"\"\n\n # Get wavelength at the boundary of each pixel\n # TODO Could also be an input??\n wave_p, wave_m = [], []\n for wave in wave_map: # For each order\n lp, lm = engine_utils.get_wave_p_or_m(wave) # Lambda plus or minus\n wave_p.append(lp), wave_m.append(lm)\n\n self.wave_p, self.wave_m = wave_p, wave_m # Save values\n\n # Init upper class\n super().__init__(wave_map, aperture, *args, **kwargs)\n\n def _get_lo_hi(self, grid, i_order):\n \"\"\"\n Find the lowest (lo) and highest (hi) index\n of wave_grid for each pixels and orders.\n\n Returns:\n -------\n 1d array of the lowest and 1d array of the highest index.\n the length is the number of non-masked pixels\n \"\"\"\n\n self.verbose_print('Compute low high')\n\n # Get needed attributes\n mask = self.mask\n\n # ... order dependent attributes\n attrs = ['wave_p', 'wave_m', 'mask_ord']\n wave_p, wave_m, mask_ord = self.get_attributes(*attrs, i_order=i_order)\n\n # Compute only for valid pixels\n wave_p = wave_p[~mask]\n wave_m = wave_m[~mask]\n\n # Find lower (lo) index in the pixel\n lo = np.searchsorted(grid, wave_m, side='right')\n\n # Find higher (hi) index in the pixel\n hi = np.searchsorted(grid, wave_p) - 1\n\n # Set invalid pixels for this order to lo=-1 and hi=-2\n ma = mask_ord[~mask]\n lo[ma], hi[ma] = -1, -2\n\n self.verbose_print('Done')\n\n return lo, hi\n\n def get_mask_wave(self, i_order):\n \"\"\" Mask according to wavelength grid \"\"\"\n\n attrs = ['wave_p', 'wave_m', 'i_bounds']\n wave_p, wave_m, i_bnds = self.get_attributes(*attrs, i_order=i_order)\n wave_min = self.wave_grid[i_bnds[0]]\n wave_max = self.wave_grid[i_bnds[1]-1]\n\n mask = (wave_m < wave_min) | (wave_p > wave_max)\n\n return mask\n\n def get_w(self, i_order):\n \"\"\"\n Compute integration weights for each grid points and each pixels.\n Depends on the order `n`.\n\n Returns\n ------\n w_n: 2d array\n weights at this specific order `n`. The shape is given by:\n (number of pixels, max number of wavelenghts covered by a pixel)\n k_n: 2d array\n index of the wavelength grid corresponding to the weights.\n Same shape as w_n\n \"\"\"\n\n self.verbose_print('Compute weigths and k')\n\n # Get needed attributes\n wave_grid, mask = self.get_attributes('wave_grid', 'mask')\n\n # ... order dependent attributes\n attrs = ['wave_p', 'wave_m', 'mask_ord', 'i_bounds']\n wave_p, wave_m, mask_ord, i_bnds = self.get_attributes(*attrs, i_order=i_order)\n\n # Use the convolved grid (depends on the order)\n wave_grid = wave_grid[i_bnds[0]:i_bnds[1]]\n\n # Compute the wavelength coverage of the grid\n d_grid = np.diff(wave_grid)\n\n # Get lo hi\n lo, hi = self._get_lo_hi(wave_grid, i_order) # Get indexes\n\n # Compute only valid pixels\n wave_p, wave_m = wave_p[~mask], wave_m[~mask]\n ma = mask_ord[~mask]\n\n # Number of used pixels\n n_i = len(lo)\n i = np.arange(n_i)\n\n self.verbose_print('Compute k')\n\n # Define fisrt and last index of wave_grid\n # for each pixel\n k_first, k_last = -1*np.ones(n_i), -1*np.ones(n_i)\n\n # If lowest value close enough to the exact grid value,\n # NOTE: Could be approximately equal to the exact grid\n # value. It would look like that.\n # >>> lo_dgrid = lo\n # >>> lo_dgrid[lo_dgrid==len(d_grid)] = len(d_grid) - 1\n # >>> cond = (grid[lo]-wave_m)/d_grid[lo_dgrid] <= 1.0e-8\n # But let's stick with the exactly equal\n cond = (wave_grid[lo] == wave_m)\n\n # special case (no need for lo_i - 1)\n k_first[cond & ~ma] = lo[cond & ~ma]\n wave_m[cond & ~ma] = wave_grid[lo[cond & ~ma]]\n\n # else, need lo_i - 1\n k_first[~cond & ~ma] = lo[~cond & ~ma] - 1\n\n # Same situation for highest value. If we follow the note\n # above (~=), the code could look like\n # >>> cond = (wave_p-grid[hi])/d_grid[hi-1] <= 1.0e-8\n # But let's stick with the exactly equal\n cond = (wave_p == wave_grid[hi])\n\n # special case (no need for hi_i - 1)\n k_last[cond & ~ma] = hi[cond & ~ma]\n wave_p[cond & ~ma] = wave_grid[hi[cond & ~ma]]\n\n # else, need hi_i + 1\n k_last[~cond & ~ma] = hi[~cond & ~ma] + 1\n\n # Generate array of all k_i. Set to -1 if not valid\n k_n, bad = engine_utils.arange_2d(k_first, k_last + 1, dtype=int)\n k_n[bad] = -1\n\n # Number of valid k per pixel\n n_k = np.sum(~bad, axis=-1)\n\n # Compute array of all w_i. Set to np.nan if not valid\n # Initialize\n w_n = np.zeros(k_n.shape, dtype=float)\n ####################\n ####################\n # 4 different cases\n ####################\n ####################\n\n self.verbose_print('compute w')\n\n # Valid for every cases\n w_n[:, 0] = wave_grid[k_n[:, 1]] - wave_m\n w_n[i, n_k-1] = wave_p - wave_grid[k_n[i, n_k-2]]\n\n ##################\n # Case 1, n_k == 2\n ##################\n case = (n_k == 2) & ~ma\n if case.any():\n\n self.verbose_print('n_k = 2')\n\n # if k_i[0] != lo_i\n cond = case & (k_n[:, 0] != lo)\n w_n[cond, 1] += wave_m[cond] - wave_grid[k_n[cond, 0]]\n\n # if k_i[-1] != hi_i\n cond = case & (k_n[:, 1] != hi)\n w_n[cond, 0] += wave_grid[k_n[cond, 1]] - wave_p[cond]\n\n # Finally\n part1 = (wave_p[case] - wave_m[case])\n part2 = d_grid[k_n[case, 0]]\n w_n[case, :] *= (part1 / part2)[:, None]\n\n ##################\n # Case 2, n_k >= 3\n ##################\n case = (n_k >= 3) & ~ma\n if case.any():\n\n self.verbose_print('n_k = 3')\n n_ki = n_k[case]\n w_n[case, 1] = wave_grid[k_n[case, 1]] - wave_m[case]\n w_n[case, n_ki-2] += wave_p[case] - wave_grid[k_n[case, n_ki-2]]\n\n # if k_i[0] != lo_i\n cond = case & (k_n[:, 0] != lo)\n nume1 = wave_grid[k_n[cond, 1]] - wave_m[cond]\n nume2 = wave_m[cond] - wave_grid[k_n[cond, 0]]\n deno = d_grid[k_n[cond, 0]]\n w_n[cond, 0] *= (nume1 / deno)\n w_n[cond, 1] += (nume1 * nume2 / deno)\n\n # if k_i[-1] != hi_i\n cond = case & (k_n[i, n_k-1] != hi)\n n_ki = n_k[cond]\n nume1 = wave_p[cond] - wave_grid[k_n[cond, n_ki-2]]\n nume2 = wave_grid[k_n[cond, n_ki-1]] - wave_p[cond]\n deno = d_grid[k_n[cond, n_ki-2]]\n w_n[cond, n_ki-1] *= (nume1 / deno)\n w_n[cond, n_ki-2] += (nume1 * nume2 / deno)\n\n ##################\n # Case 3, n_k >= 4\n ##################\n case = (n_k >= 4) & ~ma\n if case.any():\n self.verbose_print('n_k = 4')\n n_ki = n_k[case]\n w_n[case, 1] += wave_grid[k_n[case, 2]] - wave_grid[k_n[case, 1]]\n w_n[case, n_ki-2] += (wave_grid[k_n[case, n_ki-2]]\n - wave_grid[k_n[case, n_ki-3]])\n\n ##################\n # Case 4, n_k > 4\n ##################\n case = (n_k > 4) & ~ma\n if case.any():\n self.verbose_print('n_k > 4')\n i_k = np.indices(k_n.shape)[-1]\n cond = case[:, None] & (2 <= i_k) & (i_k < n_k[:, None]-2)\n ind1, ind2 = np.where(cond)\n w_n[ind1, ind2] = (d_grid[k_n[ind1, ind2]-1]\n + d_grid[k_n[ind1, ind2]])\n\n # Finally, divide w_n by 2\n w_n /= 2.\n\n # Make sure invalid values are masked\n w_n[k_n < 0] = np.nan\n\n self.verbose_print('Done')\n\n return w_n, k_n\n"
] | [
[
"numpy.ones",
"numpy.sum",
"scipy.interpolate.interp1d",
"numpy.diff",
"matplotlib.pyplot.tight_layout",
"numpy.any",
"numpy.argsort",
"numpy.nansum",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.plot",
"numpy.trapz",
"numpy.argmin",
"numpy.log10",
"numpy.where",
"numpy.nonzero",
"numpy.unique",
"numpy.linspace",
"numpy.minimum",
"numpy.sqrt",
"numpy.zeros",
"scipy.sparse.linalg.spsolve",
"numpy.searchsorted",
"matplotlib.pyplot.subplots",
"scipy.sparse.diags",
"numpy.arange",
"numpy.all",
"numpy.max",
"numpy.min",
"numpy.indices",
"numpy.maximum",
"scipy.interpolate.Akima1DInterpolator",
"scipy.optimize.minimize_scalar",
"scipy.sparse.issparse",
"scipy.sparse.csr_matrix",
"numpy.ma.array",
"numpy.clip",
"numpy.array",
"numpy.concatenate",
"numpy.full",
"matplotlib.pyplot.xlabel"
]
] |
nevinkjohn/luminol | [
"42e4ab969b774ff98f902d064cb041556017f635"
] | [
"src/luminol/algorithms/anomaly_detector_algorithms/exp_avg_detector.py"
] | [
"# coding=utf-8\n\"\"\"\n© 2015 LinkedIn Corp. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\"\"\"\nimport numpy\n\nfrom luminol import utils\nfrom luminol.algorithms.anomaly_detector_algorithms import AnomalyDetectorAlgorithm\nfrom luminol.modules.time_series import TimeSeries\nfrom luminol.constants import (DEFAULT_EMA_SMOOTHING_FACTOR,\n DEFAULT_EMA_WINDOW_SIZE_PCT)\n\n\nclass ExpAvgDetector(AnomalyDetectorAlgorithm):\n\n \"\"\"\n Exponential Moving Average.\n This method uses a data point's deviation from the exponential moving average of a lagging window\n to determine its anomaly score.\n \"\"\"\n def __init__(self, time_series, baseline_time_series=None, smoothing_factor=0, use_lag_window=False, lag_window_size=None):\n \"\"\"\n Initializer\n :param TimeSeries time_series: a TimeSeries object.\n :param TimeSeries baseline_time_series: baseline TimeSeries.\n :param float smoothing_factor: smoothing factor for computing exponential moving average.\n :param int lag_window_size: lagging window size.\n \"\"\"\n super(ExpAvgDetector, self).__init__(self.__class__.__name__, time_series, baseline_time_series)\n self.use_lag_window = use_lag_window\n self.smoothing_factor = smoothing_factor if smoothing_factor > 0 else DEFAULT_EMA_SMOOTHING_FACTOR\n self.lag_window_size = lag_window_size if lag_window_size else int(self.time_series_length * DEFAULT_EMA_WINDOW_SIZE_PCT)\n self.time_series_items = self.time_series.items()\n\n def _compute_anom_score(self, lag_window_points, point):\n \"\"\"\n Compute anomaly score for a single data point.\n Anomaly score for a single data point(t,v) equals: abs(v - ema(lagging window)).\n :param list lag_window_points: values in the lagging window.\n :param float point: data point value.\n :return float: the anomaly score.\n \"\"\"\n ema = utils.compute_ema(self.smoothing_factor, lag_window_points)[-1]\n return abs(point - ema)\n\n def _compute_anom_data_using_window(self):\n \"\"\"\n Compute anomaly scores using a lagging window.\n \"\"\"\n anom_scores = {}\n values = self.time_series.values\n stdev = numpy.std(values)\n for i, (timestamp, value) in enumerate(self.time_series_items):\n if i < self.lag_window_size:\n anom_score = self._compute_anom_score(values[:i + 1], value)\n else:\n anom_score = self._compute_anom_score(values[i - self.lag_window_size: i + 1], value)\n if stdev:\n anom_scores[timestamp] = anom_score / stdev\n else:\n anom_scores[timestamp] = anom_score\n self.anom_scores = TimeSeries(self._denoise_scores(anom_scores))\n\n def _compute_anom_data_decay_all(self):\n \"\"\"\n Compute anomaly scores using a lagging window covering all the data points before.\n \"\"\"\n anom_scores = {}\n values = self.time_series.values\n ema = utils.compute_ema(self.smoothing_factor, values)\n stdev = numpy.std(values)\n for i, (timestamp, value) in enumerate(self.time_series_items):\n anom_score = abs((value - ema[i]) / stdev) if stdev else value - ema[i]\n anom_scores[timestamp] = anom_score\n self.anom_scores = TimeSeries(self._denoise_scores(anom_scores))\n\n def _set_scores(self):\n \"\"\"\n Compute anomaly scores for the time series.\n Currently uses a lagging window covering all the data points before.\n \"\"\"\n if self.use_lag_window:\n self._compute_anom_data_using_window()\n self._compute_anom_data_decay_all()\n"
] | [
[
"numpy.std"
]
] |
akilasadhish/Remote-sensing-scene-classification | [
"18c27648553f0db8c67c7df58b851aa27a4b4942"
] | [
"classification.py"
] | [
"import pandas as pd \r\nimport seaborn as sn\r\nimport numpy as np \r\nimport os\r\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix\r\nfrom matplotlib import pyplot as plt\r\n#csv_name:using predict.py and the csv file will be generated.\r\n#labels:A list. The list includes all the category names of the dataset being tested.\r\n#csv_name2:using train.py and the csv file will be gernerated.\r\ndef acc_score(csv_name):\r\n r_c = pd.read_csv('./result_show/' + csv_name)\r\n true_labels = r_c['true_labels']\r\n pred_labels = r_c['pred_labels']\r\n acc = accuracy_score(true_labels, pred_labels)\r\n return acc\r\n\r\ndef report(csv_name, labels):\r\n r_c = pd.read_csv('./result_show/' + csv_name)\r\n true_labels = r_c['true_labels']\r\n pred_labels = r_c['pred_labels']\r\n r = classification_report(true_labels, pred_labels, digits=4, target_names=labels)\r\n return r\r\n\r\ndef matrix(csv_name, labels):\r\n r_c = pd.read_csv('./result_show/' + csv_name)\r\n true_labels = r_c['true_labels']\r\n pred_labels = r_c['pred_labels']\r\n mat = confusion_matrix(true_labels, pred_labels)\r\n mat_2 = np.ndarray((len(labels), len(labels)))\r\n names = []\r\n for n in range(1, len(labels)+1):\r\n name = str(n) + '#'\r\n names.append(name)\r\n\r\n for i in range(len(labels)):\r\n for k in range(len(labels)):\r\n mat_2[i][k] = mat[i][k] / np.sum(mat[i])\r\n\r\n mat_2 = np.round(mat_2, decimals=2)\r\n sn.heatmap(mat_2, annot=True, fmt='.2f', cmap='gray_r', xticklabels=names, yticklabels=labels,\r\n mask=mat_2<0.001, annot_kws={'size':8})\r\n plt.yticks(rotation=360)\r\n plt.show()\r\n\r\ndef plt_acc(csv_name2):\r\n r_c = pd.read_csv(csv_name2)\r\n acc = r_c['acc']\r\n val_acc = r_c['val_acc']\r\n epochs = range(1, len(acc) + 1)\r\n plt.plot(epochs, acc, 'blue', label='train_acc', marker='', linestyle='-')\r\n plt.plot(epochs, val_acc, 'red', label='test_acc', marker='.', linestyle='-')\r\n plt.title('Train and Test Accuracy')\r\n plt.legend()\r\n plt.grid()\r\n plt.show()\r\n\r\ndef plt_loss(csv_name2):\r\n r_c = pd.read_csv(csv_name2)\r\n loss = r_c['loss']\r\n val_loss = r_c['val_loss']\r\n epochs = range(1, len(loss) + 1)\r\n plt.plot(epochs, loss, 'blue', label='train_loss', marker='', linestyle='-')\r\n plt.plot(epochs, val_loss, 'red', label='test_loss', marker='.', linestyle='-')\r\n plt.title('Train and Test Loss')\r\n plt.legend()\r\n plt.grid()\r\n plt.show()\r\n\r\n\r\n"
] | [
[
"numpy.sum",
"matplotlib.pyplot.legend",
"sklearn.metrics.classification_report",
"pandas.read_csv",
"matplotlib.pyplot.grid",
"sklearn.metrics.confusion_matrix",
"sklearn.metrics.accuracy_score",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"numpy.round",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.yticks"
]
] |
tianjuchen/pyro | [
"d5b0545c4f992d435692080db6969314a2c32f05"
] | [
"tests/distributions/test_zero_inflated.py"
] | [
"# Copyright (c) 2017-2019 Uber Technologies, Inc.\n# SPDX-License-Identifier: Apache-2.0\n\nimport math\n\nimport pytest\nimport torch\n\nfrom pyro.distributions import (\n Delta,\n NegativeBinomial,\n Normal,\n Poisson,\n ZeroInflatedDistribution,\n ZeroInflatedNegativeBinomial,\n ZeroInflatedPoisson,\n)\nfrom pyro.distributions.util import broadcast_shape\nfrom tests.common import assert_close\n\n\[email protected](\"gate_shape\", [(), (2,), (3, 1), (3, 2)])\[email protected](\"base_shape\", [(), (2,), (3, 1), (3, 2)])\ndef test_zid_shape(gate_shape, base_shape):\n gate = torch.rand(gate_shape)\n base_dist = Normal(torch.randn(base_shape), torch.randn(base_shape).exp())\n\n d = ZeroInflatedDistribution(base_dist, gate=gate)\n assert d.batch_shape == broadcast_shape(gate_shape, base_shape)\n assert d.support == base_dist.support\n\n d2 = d.expand([4, 3, 2])\n assert d2.batch_shape == (4, 3, 2)\n\n\[email protected](\"rate\", [0.1, 0.5, 0.9, 1.0, 1.1, 2.0, 10.0])\ndef test_zip_0_gate(rate):\n # if gate is 0 ZIP is Poisson\n zip1 = ZeroInflatedPoisson(torch.tensor(rate), gate=torch.zeros(1))\n zip2 = ZeroInflatedPoisson(torch.tensor(rate), gate_logits=torch.tensor(-99.9))\n pois = Poisson(torch.tensor(rate))\n s = pois.sample((20,))\n zip1_prob = zip1.log_prob(s)\n zip2_prob = zip2.log_prob(s)\n pois_prob = pois.log_prob(s)\n assert_close(zip1_prob, pois_prob)\n assert_close(zip2_prob, pois_prob)\n\n\[email protected](\"rate\", [0.1, 0.5, 0.9, 1.0, 1.1, 2.0, 10.0])\ndef test_zip_1_gate(rate):\n # if gate is 1 ZIP is Delta(0)\n zip1 = ZeroInflatedPoisson(torch.tensor(rate), gate=torch.ones(1))\n zip2 = ZeroInflatedPoisson(torch.tensor(rate), gate_logits=torch.tensor(math.inf))\n delta = Delta(torch.zeros(1))\n s = torch.tensor([0.0, 1.0])\n zip1_prob = zip1.log_prob(s)\n zip2_prob = zip2.log_prob(s)\n delta_prob = delta.log_prob(s)\n assert_close(zip1_prob, delta_prob)\n assert_close(zip2_prob, delta_prob)\n\n\[email protected](\"gate\", [0.0, 0.25, 0.5, 0.75, 1.0])\[email protected](\"rate\", [0.1, 0.5, 0.9, 1.0, 1.1, 2.0, 10.0])\ndef test_zip_mean_variance(gate, rate):\n num_samples = 1000000\n zip_ = ZeroInflatedPoisson(torch.tensor(rate), gate=torch.tensor(gate))\n s = zip_.sample((num_samples,))\n expected_mean = zip_.mean\n estimated_mean = s.mean()\n expected_std = zip_.stddev\n estimated_std = s.std()\n assert_close(expected_mean, estimated_mean, atol=1e-02)\n assert_close(expected_std, estimated_std, atol=1e-02)\n\n\[email protected](\"total_count\", [0.1, 0.5, 0.9, 1.0, 1.1, 2.0, 10.0])\[email protected](\"probs\", [0.1, 0.5, 0.9])\ndef test_zinb_0_gate(total_count, probs):\n # if gate is 0 ZINB is NegativeBinomial\n zinb1 = ZeroInflatedNegativeBinomial(\n total_count=torch.tensor(total_count),\n gate=torch.zeros(1),\n probs=torch.tensor(probs),\n )\n zinb2 = ZeroInflatedNegativeBinomial(\n total_count=torch.tensor(total_count),\n gate_logits=torch.tensor(-99.9),\n probs=torch.tensor(probs),\n )\n neg_bin = NegativeBinomial(torch.tensor(total_count), probs=torch.tensor(probs))\n s = neg_bin.sample((20,))\n zinb1_prob = zinb1.log_prob(s)\n zinb2_prob = zinb2.log_prob(s)\n neg_bin_prob = neg_bin.log_prob(s)\n assert_close(zinb1_prob, neg_bin_prob)\n assert_close(zinb2_prob, neg_bin_prob)\n\n\[email protected](\"total_count\", [0.1, 0.5, 0.9, 1.0, 1.1, 2.0, 10.0])\[email protected](\"probs\", [0.1, 0.5, 0.9])\ndef test_zinb_1_gate(total_count, probs):\n # if gate is 1 ZINB is Delta(0)\n zinb1 = ZeroInflatedNegativeBinomial(\n total_count=torch.tensor(total_count),\n gate=torch.ones(1),\n probs=torch.tensor(probs),\n )\n zinb2 = ZeroInflatedNegativeBinomial(\n total_count=torch.tensor(total_count),\n gate_logits=torch.tensor(math.inf),\n probs=torch.tensor(probs),\n )\n delta = Delta(torch.zeros(1))\n s = torch.tensor([0.0, 1.0])\n zinb1_prob = zinb1.log_prob(s)\n zinb2_prob = zinb2.log_prob(s)\n delta_prob = delta.log_prob(s)\n assert_close(zinb1_prob, delta_prob)\n assert_close(zinb2_prob, delta_prob)\n\n\[email protected](\"gate\", [0.0, 0.25, 0.5, 0.75, 1.0])\[email protected](\"total_count\", [0.1, 0.5, 0.9, 1.0, 1.1, 2.0, 10.0])\[email protected](\"logits\", [-0.5, 0.5, -0.9, 1.9])\ndef test_zinb_mean_variance(gate, total_count, logits):\n num_samples = 1000000\n zinb_ = ZeroInflatedNegativeBinomial(\n total_count=torch.tensor(total_count),\n gate=torch.tensor(gate),\n logits=torch.tensor(logits),\n )\n s = zinb_.sample((num_samples,))\n expected_mean = zinb_.mean\n estimated_mean = s.mean()\n expected_std = zinb_.stddev\n estimated_std = s.std()\n assert_close(expected_mean, estimated_mean, atol=1e-01)\n assert_close(expected_std, estimated_std, atol=1e-1)\n"
] | [
[
"torch.ones",
"torch.randn",
"torch.rand",
"torch.tensor",
"torch.zeros"
]
] |
makram93/executors | [
"9e88b56650ee154e811b8ecfaf883861475c082f"
] | [
"tests/integration/psql_dump_reload/test_dump_psql.py"
] | [
"import os\nimport time\nfrom collections import OrderedDict\nfrom pathlib import Path\nfrom typing import Dict\n\nimport numpy as np\nimport pytest\nfrom jina import Flow, Document, Executor, DocumentArray, requests\nfrom jina.logging.profile import TimeContext\nfrom jina_commons.indexers.dump import (\n import_vectors,\n import_metas,\n)\n\n\[email protected]()\ndef docker_compose(request):\n os.system(\n f\"docker-compose -f {request.param} --project-directory . up --build -d --remove-orphans\"\n )\n time.sleep(5)\n yield\n os.system(\n f\"docker-compose -f {request.param} --project-directory . down --remove-orphans\"\n )\n\n\n# noinspection PyUnresolvedReferences\nfrom jinahub.indexers.storage.PostgreSQLStorage.postgreshandler import (\n doc_without_embedding,\n)\n\n# required in order to be found by Flow creation\n# noinspection PyUnresolvedReferences\nfrom jinahub.indexers.searcher.compound.NumpyPostgresSearcher import (\n NumpyPostgresSearcher,\n)\nfrom jinahub.indexers.storage.PostgreSQLStorage import PostgreSQLStorage\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\ncompose_yml = os.path.join(cur_dir, 'docker-compose.yml')\nstorage_flow_yml = os.path.join(cur_dir, 'flow_storage.yml')\nquery_flow_yml = os.path.join(cur_dir, 'flow_query.yml')\n\n\nclass Pass(Executor):\n @requests(on='/search')\n def pass_me(self, **kwargs):\n pass\n\n\nclass MatchMerger(Executor):\n @requests(on='/search')\n def merge(self, docs_matrix, parameters: Dict, **kwargs):\n if docs_matrix:\n results = OrderedDict()\n for docs in docs_matrix:\n for doc in docs:\n if doc.id in results:\n results[doc.id].matches.extend(doc.matches)\n else:\n results[doc.id] = doc\n\n top_k = parameters.get('top_k')\n if top_k:\n top_k = int(top_k)\n\n for doc in results.values():\n try:\n doc.matches = sorted(\n doc.matches,\n key=lambda m: m.scores['cosine'].value,\n reverse=True,\n )[:top_k]\n except TypeError as e:\n print(f'##### {e}')\n\n docs = DocumentArray(list(results.values()))\n return docs\n\n\ndef get_documents(nr=10, index_start=0, emb_size=7):\n for i in range(index_start, nr + index_start):\n with Document() as d:\n d.id = f'aa{i}' # to test it supports non-int ids\n d.text = f'hello world {i}'\n d.embedding = np.random.random(emb_size)\n d.tags['field'] = f'tag data {i}'\n yield d\n\n\ndef assert_dump_data(dump_path, docs, shards, pea_id):\n docs = sorted(\n docs, key=lambda doc: doc.id\n ) # necessary since the ordering is done as str in PSQL\n size_shard = len(docs) // shards\n size_shard_modulus = len(docs) % shards\n ids_dump, vectors_dump = import_vectors(\n dump_path,\n str(pea_id),\n )\n if pea_id == shards - 1:\n docs_expected = docs[\n (pea_id) * size_shard : (pea_id + 1) * size_shard + size_shard_modulus\n ]\n else:\n docs_expected = docs[(pea_id) * size_shard : (pea_id + 1) * size_shard]\n print(f'### pea {pea_id} has {len(docs_expected)} docs')\n\n # TODO these might fail if we implement any ordering of elements on dumping / reloading\n ids_dump = list(ids_dump)\n vectors_dump = list(vectors_dump)\n np.testing.assert_equal(set(ids_dump), set([d.id for d in docs_expected]))\n np.testing.assert_allclose(vectors_dump, [d.embedding for d in docs_expected])\n\n _, metas_dump = import_metas(\n dump_path,\n str(pea_id),\n )\n metas_dump = list(metas_dump)\n np.testing.assert_equal(\n metas_dump,\n [doc_without_embedding(d) for d in docs_expected],\n )\n\n\ndef path_size(dump_path):\n dir_size = (\n sum(f.stat().st_size for f in Path(dump_path).glob('**/*') if f.is_file()) / 1e6\n )\n return dir_size\n\n\n# replicas w 1 shard doesn't work\n# @pytest.mark.parametrize('shards', [1, 3, 7])\[email protected]('shards', [3, 7])\[email protected]('nr_docs', [100])\[email protected]('emb_size', [10])\[email protected]('docker_compose', [compose_yml], indirect=['docker_compose'])\ndef test_dump_reload(tmpdir, nr_docs, emb_size, shards, docker_compose):\n # for psql to start\n time.sleep(2)\n top_k = 5\n docs = DocumentArray(\n list(get_documents(nr=nr_docs, index_start=0, emb_size=emb_size))\n )\n # make sure to delete any overlapping docs\n PostgreSQLStorage().delete(docs, {})\n assert len(docs) == nr_docs\n\n dump_path = os.path.join(str(tmpdir), 'dump_dir')\n os.environ['STORAGE_WORKSPACE'] = os.path.join(str(tmpdir), 'index_ws')\n os.environ['SHARDS'] = str(shards)\n if shards > 1:\n os.environ['USES_AFTER'] = 'MatchMerger'\n else:\n os.environ['USES_AFTER'] = 'Pass'\n\n with Flow.load_config(storage_flow_yml) as flow_storage:\n with Flow.load_config(query_flow_yml) as flow_query:\n with TimeContext(f'### indexing {len(docs)} docs'):\n flow_storage.post(on='/index', inputs=docs)\n\n results = flow_query.post(on='/search', inputs=docs, return_results=True)\n assert len(results[0].docs[0].matches) == 0\n\n with TimeContext(f'### dumping {len(docs)} docs'):\n flow_storage.post(\n on='/dump',\n target_peapod='indexer_storage',\n parameters={\n 'dump_path': dump_path,\n 'shards': shards,\n 'timeout': -1,\n },\n )\n\n dir_size = path_size(dump_path)\n assert dir_size > 0\n print(f'### dump path size: {dir_size} MBs')\n\n flow_query.rolling_update(pod_name='indexer_query', dump_path=dump_path)\n results = flow_query.post(\n on='/search',\n inputs=docs,\n parameters={'top_k': top_k},\n return_results=True,\n )\n assert len(results[0].docs[0].matches) == top_k\n assert results[0].docs[0].matches[0].scores['cosine'].value == 1.0\n\n idx = PostgreSQLStorage()\n assert idx.size == nr_docs\n\n # assert data dumped is correct\n for pea_id in range(shards):\n assert_dump_data(dump_path, docs, shards, pea_id)\n\n\ndef _in_docker():\n \"\"\" Returns: True if running in a Docker container, else False \"\"\"\n with open('/proc/1/cgroup', 'rt') as ifh:\n if 'docker' in ifh.read():\n print('in docker, skipping benchmark')\n return True\n return False\n\n\n# benchmark only\[email protected](\n _in_docker() or ('GITHUB_WORKFLOW' in os.environ),\n reason='skip the benchmark test on github workflow or docker',\n)\[email protected]('docker_compose', [compose_yml], indirect=['docker_compose'])\ndef test_benchmark(tmpdir, docker_compose):\n nr_docs = 1000\n return test_dump_reload(\n tmpdir, nr_docs=nr_docs, emb_size=128, shards=3, docker_compose=compose_yml\n )\n"
] | [
[
"numpy.random.random",
"numpy.testing.assert_allclose"
]
] |
FrederichRiver/neutrino | [
"e91db53486e56ddeb83ae9714311d606b33fb165"
] | [
"applications/alkaid/alkaid/phoenix.py"
] | [
"#!/usr/bin/python3\n# from strategy_base import strategyBase\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, Dataset\n\ninput_size = 4\nhidden_size = 4 * input_size\nnum_layers = 1\nseq_len = 10\nbatch_size = 20\n\n\nclass strategyBase(object):\n def __init__(self):\n pass\n\n def _get_data(self):\n pass\n\n def _settle(self):\n pass\n\n\nclass Phoenix(nn.Module):\n \"\"\"\n input (batch, seq_len, feature_size)\n output (batch, 1)\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(Phoenix, self).__init__()\n self.lstm = nn.LSTM(input_size,\n hidden_size,\n num_layers)\n # nn.init.xavier_uniform_(self.lstm.weight)\n self.linear = nn.Linear(hidden_size, 1)\n\n def forward(self, x):\n x, _ = self.lstm(x)\n print(x.size())\n b, s, h = x.shape\n x = x.reshape(batch_size * seq_len, hidden_size)\n x = self.linear(x)\n print(x.size())\n return x\n\n def train(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=0.001)\n loss_func = nn.CrossEntropyLoss()\n for epoch in range(10):\n pass\n\n\nclass stockData(torch.utils.data.Dataset):\n def __init__(self):\n from polaris.mysql8 import mysqlBase, mysqlHeader\n from dev_global.env import GLOBAL_HEADER\n import torch.tensor\n import pandas\n import numpy as np\n stock_code = 'SH600000'\n self.mysql = mysqlBase(GLOBAL_HEADER)\n result = self.mysql.select_values(stock_code, 'open_price,close_price,highest_price,lowest_price')\n predict = pandas.DataFrame()\n predict['predict'] = result[1].shift(-1)\n # print(result.head(10))\n self.input = []\n self.label = []\n # print(result.shape[0])\n block = 10\n for i in range(int(result.shape[0]/block)):\n x = result[i*block: (i+1)*block]\n y = predict['predict'][(i+1)*block-1]\n self.input.append(torch.tensor(np.array(x), dtype=torch.float32))\n self.label.append(torch.tensor(np.array(y), dtype=torch.float32))\n # print(result.head(15))\n # print(self.input[0])\n # print(self.label[0])\n\n def __len__(self):\n return len(self.input)\n\n def __getitem__(self, index):\n return self.input[index], self.label[index]\n\n\nh = torch.randn(num_layers, batch_size, hidden_size)\nc = torch.randn(num_layers, batch_size, hidden_size)\ninput = torch.randn(seq_len, batch_size, input_size)\n# print(input)\nnet = Phoenix()\n# output, _ = net.lstm(input, (h, c))\n# out2 = net.forward(input)\n\ndt = stockData()\ninp = DataLoader(dt, batch_size=batch_size, drop_last=True)\n\nfor step, (x, y) in enumerate(inp):\n # print(step)\n # print(x.size())\n # print(x)\n # print(input.size())\n # print(input)\n print(y)\n print(net.forward(x))\n pass\n"
] | [
[
"torch.utils.data.DataLoader",
"torch.nn.LSTM",
"torch.nn.Linear",
"torch.randn",
"pandas.DataFrame",
"torch.nn.CrossEntropyLoss",
"numpy.array"
]
] |
DSPLab-IC6/ikfs_anomaly_detector | [
"e0a36e185be6e9dcd75451c956a2aaf6a6fec677"
] | [
"ikfs_anomaly_detector/intellectual/tests.py"
] | [
"import unittest\n\nimport numpy as np\n\nfrom ikfs_anomaly_detector.intellectual.autoencoder import LSTMAutoencoder\nfrom ikfs_anomaly_detector.intellectual.predictor import LSTMPredictor\nfrom ikfs_anomaly_detector.intellectual.utils import (\n z_normalization,\n calculate_mean,\n find_anomaly_points,\n calculate_covariance_matrix,\n mahalanobis_distance,\n squared_error,\n ewma,\n)\n\n\nclass TestAutoencoder(unittest.TestCase):\n\n def test_init(self) -> None:\n LSTMAutoencoder(signals_count=5)\n\n\nclass TestPredictor(unittest.TestCase):\n\n def test_init(self) -> None:\n LSTMPredictor()\n\n\nclass TestUtils(unittest.TestCase):\n\n def test_z_normalization(self) -> None:\n arr = np.array([1, 2, 3, 30, 30, 3, 2, 1])\n self.assertListEqual(\n list(z_normalization(arr)), [\n -0.6587095756740946,\n -0.5763708787148328,\n -0.49403218175557095,\n 1.7291126361444984,\n 1.7291126361444984,\n -0.49403218175557095,\n -0.5763708787148328,\n -0.6587095756740946,\n ])\n\n def test_calculate_mean(self) -> None:\n arr = np.array([1, 2, 5, 10])\n self.assertAlmostEqual(calculate_mean(arr), arr.mean(axis=0))\n\n def test_calculate_covariance_matrix(self) -> None:\n arr = np.array([[1., 1.5], [2., 2.], [3., 1.], [1., 5.]])\n mean, matrix = calculate_covariance_matrix(arr)\n\n self.assertAlmostEqual(mean, 2.0625)\n self.assertListEqual([list(v) for v in matrix], [[0.78515625, -0.87890625],\n [-0.87890625, 2.51953125]])\n\n def test_mahalanobis_distance(self) -> None:\n arr = np.array([[1., 1.5], [2., 2.], [3., 1.], [1., 5.]])\n mean, matrix = calculate_covariance_matrix(arr)\n\n self.assertAlmostEqual(mahalanobis_distance(arr[0], mean, matrix), 3.43629, places=5)\n\n def test_squared_error(self) -> None:\n a = np.array([1, 2, 3])\n b = np.array([4, 5, 6])\n\n self.assertListEqual(list(squared_error(a, b)), [3.0, 3.0, 3.0])\n\n def test_ewma(self) -> None:\n arr = np.array(range(10))\n self.assertListEqual(list(ewma(arr, window=4)), [0.0, 0.5, 1.0, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5])\n\n def test_find_anomaly_points(self) -> None:\n arr = np.array([1, 10, 20, 30, 10, 20, 2, 2, 1, 10])\n self.assertListEqual(find_anomaly_points(arr, threshold=5, offset=2), [1, 3, 5, 9])\n"
] | [
[
"numpy.array"
]
] |
yoshihikosuzuki/pbcore | [
"956c45dea8868b5cf7d9b8e9ce98ac8fe8a60150"
] | [
"pbcore/io/align/BamIO.py"
] | [
"# Author: David Alexander\n\n\n\n\n__all__ = [ \"BamReader\", \"IndexedBamReader\" ]\n\ntry:\n from pysam.calignmentfile import AlignmentFile # pylint: disable=no-name-in-module, import-error, fixme, line-too-long\nexcept ImportError:\n from pysam.libcalignmentfile import AlignmentFile # pylint: disable=no-name-in-module, import-error, fixme, line-too-long\nfrom pbcore.io import FastaTable\nfrom pbcore.chemistry import decodeTriple, ChemistryLookupError\n\nimport numpy as np\nfrom itertools import groupby\nfrom functools import wraps\nfrom os.path import abspath, expanduser, exists\n\nfrom ..base import ReaderBase\nfrom .PacBioBamIndex import PacBioBamIndex\nfrom .BamAlignment import *\nfrom ._BamSupport import *\nfrom ._AlignmentMixin import AlignmentReaderMixin, IndexedAlignmentReaderMixin\n\n\ndef requiresBai(method):\n @wraps(method)\n def f(bamReader, *args, **kwargs):\n if not bamReader.peer.has_index():\n raise UnavailableFeature(\"this feature requires an standard BAM index file (bam.bai)\")\n else:\n return method(bamReader, *args, **kwargs)\n return f\n\n\nclass _BamReaderBase(ReaderBase):\n \"\"\"\n The BamReader class provides a high-level interface to PacBio BAM\n files. If a PacBio BAM index (bam.pbi file) is present and the\n user instantiates the BamReader using the reference FASTA as the\n second argument, the BamReader will provide an interface\n compatible with CmpH5Reader.\n \"\"\"\n def _loadReferenceInfo(self):\n refRecords = self.peer.header[\"SQ\"]\n refNames = [r[\"SN\"] for r in refRecords]\n refLengths = [r[\"LN\"] for r in refRecords]\n refMD5s = [r[\"M5\"] for r in refRecords]\n refIds = list(map(self.peer.get_tid, refNames))\n nRefs = len(refRecords)\n\n if nRefs > 0:\n self._referenceInfoTable = np.rec.fromrecords(list(zip(\n refIds,\n refIds,\n refNames,\n refNames,\n refLengths,\n refMD5s,\n np.zeros(nRefs, dtype=np.uint32),\n np.zeros(nRefs, dtype=np.uint32))),\n dtype=[('ID', '<i8'), ('RefInfoID', '<i8'),\n ('Name', 'O'), ('FullName', 'O'),\n ('Length', '<i8'), ('MD5', 'O'),\n ('StartRow', '<u4'), ('EndRow', '<u4')])\n self._referenceDict = {}\n self._referenceDict.update(list(zip(refIds, self._referenceInfoTable)))\n self._referenceDict.update(list(zip(refNames, self._referenceInfoTable)))\n else:\n self._referenceInfoTable = None\n self._referenceDict = None\n\n def _loadReadGroupInfo(self):\n rgs = self.peer.header[\"RG\"]\n readGroupTable_ = []\n\n # RGID -> (\"abstract feature name\" -> actual feature name)\n self._baseFeatureNameMappings = {}\n self._pulseFeatureNameMappings = {}\n\n for rg in rgs:\n rgID = rgAsInt(rg[\"ID\"])\n rgName = rg[\"PU\"]\n ds = dict([pair.split(\"=\") for pair in rg[\"DS\"].split(\";\") if pair != \"\"])\n # spec: we only consider first two components of basecaller version\n # in \"chem\" lookup\n rgReadType = ds[\"READTYPE\"]\n rgChem = \"unknown\"\n rgFrameRate = 0.0\n if rgReadType != \"TRANSCRIPT\":\n rgFrameRate = ds[\"FRAMERATEHZ\"]\n basecallerVersion = \".\".join(ds[\"BASECALLERVERSION\"].split(\".\")[0:2])\n triple = ds[\"BINDINGKIT\"], ds[\"SEQUENCINGKIT\"], basecallerVersion\n rgChem = decodeTriple(*triple)\n\n # Look for the features manifest entries within the DS tag,\n # and build an \"indirection layer\", i.e. to get from\n # \"Ipd\" to \"Ipd:Frames\"\n # (This is a bit messy. Can we separate the manifest from\n # the rest of the DS content?)\n baseFeatureNameMapping = { key.split(\":\")[0] : key\n for key in list(ds.keys())\n if key in BASE_FEATURE_TAGS }\n pulseFeatureNameMapping = { key.split(\":\")[0] : key\n for key in list(ds.keys())\n if key in PULSE_FEATURE_TAGS }\n self._baseFeatureNameMappings[rgID] = baseFeatureNameMapping\n self._pulseFeatureNameMappings[rgID] = pulseFeatureNameMapping\n\n readGroupTable_.append((rgID, rgName, rgReadType, rgChem, rgFrameRate,\n frozenset(iter(baseFeatureNameMapping.keys()))))\n\n self._readGroupTable = np.rec.fromrecords(\n readGroupTable_,\n dtype=[(\"ID\" , np.int32),\n (\"MovieName\" , \"O\"),\n (\"ReadType\" , \"O\"),\n (\"SequencingChemistry\", \"O\"),\n (\"FrameRate\", float),\n (\"BaseFeatures\", \"O\")])\n assert len(set(self._readGroupTable.ID)) == len(self._readGroupTable), \\\n \"First 8 chars of read group IDs must be unique!\"\n\n self._readGroupDict = { rg.ID : rg\n for rg in self._readGroupTable }\n\n # The base/pulse features \"available\" to clients of this file are the intersection\n # of features available from each read group.\n self._baseFeaturesAvailable = set.intersection(\n *[set(mapping.keys()) for mapping in list(self._baseFeatureNameMappings.values())])\n self._pulseFeaturesAvailable = set.intersection(\n *[set(mapping.keys()) for mapping in list(self._pulseFeatureNameMappings.values())])\n\n def _loadProgramInfo(self):\n pgRecords = [ (pg[\"ID\"], pg.get(\"VN\", None), pg.get(\"CL\", None))\n for pg in self.peer.header.get(\"PG\", []) ]\n\n if len(pgRecords) > 0:\n self._programTable = np.rec.fromrecords(\n pgRecords,\n dtype=[(\"ID\" , \"O\"),\n (\"Version\", \"O\"),\n (\"CommandLine\", \"O\")])\n else:\n self._programTable = None\n\n def _loadReferenceFasta(self, referenceFastaFname):\n ft = FastaTable(referenceFastaFname)\n # Verify that this FASTA is in agreement with the BAM's\n # reference table---BAM should be a subset.\n fastaIdsAndLens = set((c.id, len(c)) for c in ft)\n bamIdsAndLens = set((c.Name, c.Length) for c in self.referenceInfoTable)\n if not bamIdsAndLens.issubset(fastaIdsAndLens):\n raise ReferenceMismatch(\"FASTA file must contain superset of reference contigs in BAM\")\n self.referenceFasta = ft\n\n def _checkFileCompatibility(self):\n # Verify that this is a \"pacbio\" BAM file of version at least\n # 3.0.1\n badVersionException = IncompatibleFile(\n \"This BAM file is incompatible with this API \" +\n \"(only PacBio BAM files version >= 3.0.1 are supported)\")\n checkedVersion = self.version\n if \"b\" in checkedVersion:\n raise badVersionException\n else:\n major, minor, patch = checkedVersion.split('.')\n if not (major, minor, patch) >= (3, 0, 1):\n raise badVersionException\n\n def __init__(self, fname, referenceFastaFname=None):\n self.filename = fname = abspath(expanduser(fname))\n self.peer = AlignmentFile(fname, \"rb\", check_sq=False)\n self._checkFileCompatibility()\n\n self._loadReferenceInfo()\n self._loadReadGroupInfo()\n self._loadProgramInfo()\n\n self.referenceFasta = None\n if referenceFastaFname is not None:\n if self.isUnmapped:\n raise ValueError(\"Unmapped BAM file--reference FASTA should not be given as argument to BamReader\")\n self._loadReferenceFasta(referenceFastaFname)\n\n @property\n def isIndexLoaded(self):\n return self.index is not None # pylint: disable=no-member\n\n @property\n def isReferenceLoaded(self):\n return self.referenceFasta is not None\n\n @property\n def isUnmapped(self):\n return not(self.isMapped)\n\n @property\n def isMapped(self):\n return len(self.peer.header[\"SQ\"]) > 0\n\n @property\n def alignmentIndex(self):\n raise UnavailableFeature(\"BAM has no alignment index\")\n\n @property\n def movieNames(self):\n return set([mi.MovieName for mi in self.readGroupTable])\n\n @property\n def readGroupTable(self):\n return self._readGroupTable\n\n def readGroupInfo(self, readGroupId):\n return self._readGroupDict[readGroupId]\n\n @property\n def sequencingChemistry(self):\n \"\"\"\n List of the sequencing chemistries by movie. Order is\n unspecified.\n \"\"\"\n return list(self.readGroupTable.SequencingChemistry)\n\n @property\n def referenceInfoTable(self):\n return self._referenceInfoTable\n\n #TODO: standard? how about subread instead? why capitalize ccs?\n # can we standardize this? is cDNA an additional possibility\n @property\n def readType(self):\n \"\"\"\n Either \"standard\", \"CCS\", \"mixed\", or \"unknown\", to represent the\n type of PacBio reads aligned in this BAM file.\n \"\"\"\n readTypes = self.readGroupTable.ReadType\n if all(readTypes == \"SUBREAD\"):\n return \"standard\"\n elif all(readTypes == \"CCS\"):\n return \"CCS\"\n elif all(readTypes == \"TRANSCRIPT\"):\n return \"TRANSCRIPT\"\n elif all((readTypes == \"CCS\") | (readTypes == \"SUBREAD\")):\n return \"mixed\"\n else:\n return \"unknown\"\n\n @property\n def version(self):\n return self.peer.header[\"HD\"][\"pb\"]\n\n def versionAtLeast(self, minimalVersion):\n raise Unimplemented()\n\n def softwareVersion(self, programName):\n raise Unimplemented()\n\n @property\n def isSorted(self):\n return self.peer.header[\"HD\"][\"SO\"] == \"coordinate\"\n\n @property\n def isBarcoded(self):\n raise Unimplemented()\n\n @property\n def isEmpty(self):\n return (len(self) == 0)\n\n def referenceInfo(self, key):\n return self._referenceDict[key]\n\n def atOffset(self, offset):\n self.peer.seek(offset)\n return BamAlignment(self, next(self.peer))\n\n def hasBaseFeature(self, featureName):\n return featureName in self._baseFeaturesAvailable\n\n def baseFeaturesAvailable(self):\n return self._baseFeaturesAvailable\n\n def hasPulseFeature(self, featureName):\n return featureName in self._pulseFeaturesAvailable\n\n def pulseFeaturesAvailable(self):\n return self._pulseFeaturesAvailable\n\n def hasPulseFeatures(self):\n \"\"\"\n Is this BAM file a product of running analysis with the\n PacBio-internal analysis mode enabled?\n \"\"\"\n return self.hasPulseFeature(\"PulseCall\")\n\n @property\n def barcode(self):\n raise Unimplemented()\n\n @property\n def barcodeName(self):\n raise Unimplemented()\n\n @property\n def barcodes(self):\n raise Unimplemented()\n\n @requiresBai\n def __len__(self):\n return self.peer.mapped + self.peer.unmapped\n\n def close(self):\n if hasattr(self, \"file\") and self.file is not None:\n self.file.close()\n self.file = None\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.close()\n\n\nclass BamReader(_BamReaderBase, AlignmentReaderMixin):\n \"\"\"\n Reader for a BAM with a bam.bai (SAMtools) index, but not a\n bam.pbi (PacBio) index. Supports basic BAM operations.\n \"\"\"\n def __init__(self, fname, referenceFastaFname=None):\n super(BamReader, self).__init__(fname, referenceFastaFname)\n\n @property\n def index(self):\n return None\n\n def __iter__(self):\n self.peer.reset()\n for a in self.peer:\n yield BamAlignment(self, a)\n\n def readsInRange(self, winId, winStart, winEnd, justIndices=False):\n # PYSAM BUG: fetch doesn't work if arg 1 is tid and not rname\n if not isinstance(winId, str):\n winId = self.peer.get_reference_name(winId)\n if justIndices == True:\n raise UnavailableFeature(\"BAM is not random-access\")\n else:\n return ( BamAlignment(self, it)\n for it in self.peer.fetch(winId, winStart, winEnd, multiple_iterators=False) )\n\n def __getitem__(self, rowNumbers):\n raise UnavailableFeature(\"Use IndexedBamReader to get row-number based slicing.\")\n\n\n\nclass IndexedBamReader(_BamReaderBase, IndexedAlignmentReaderMixin):\n \"\"\"\n A `IndexedBamReader` is a BAM reader class that uses the\n ``bam.pbi`` (PacBio BAM index) file to enable random access by\n \"row number\" and to provide access to precomputed semantic\n information about the BAM records\n \"\"\"\n def __init__(self, fname, referenceFastaFname=None, sharedIndex=None):\n super(IndexedBamReader, self).__init__(fname, referenceFastaFname)\n if sharedIndex is None:\n self.pbi = None\n pbiFname = self.filename + \".pbi\"\n if exists(pbiFname):\n self.pbi = PacBioBamIndex(pbiFname)\n else:\n raise IOError(\"IndexedBamReader requires bam.pbi index file \"+\n \"to read {f}\".format(f=fname))\n else:\n self.pbi = sharedIndex\n\n @property\n def index(self):\n return self.pbi\n\n def atRowNumber(self, rn):\n offset = self.pbi.virtualFileOffset[rn]\n self.peer.seek(offset)\n return BamAlignment(self, next(self.peer), rn)\n\n def readsInRange(self, winId, winStart, winEnd, justIndices=False):\n if isinstance(winId, str):\n winId = self.referenceInfo(winId).ID\n ix = self.pbi.rangeQuery(winId, winStart, winEnd)\n if justIndices:\n return ix\n else:\n return self[ix]\n\n def __iter__(self):\n self.peer.reset()\n for (rowNumber, peerRecord) in enumerate(self.peer):\n yield BamAlignment(self, peerRecord, rowNumber)\n\n def __len__(self):\n return len(self.pbi)\n\n def __getitem__(self, rowNumbers):\n if (isinstance(rowNumbers, int) or\n issubclass(type(rowNumbers), np.integer)):\n return self.atRowNumber(rowNumbers)\n elif isinstance(rowNumbers, slice):\n return ( self.atRowNumber(r)\n for r in range(*rowNumbers.indices(len(self))))\n elif isinstance(rowNumbers, list) or isinstance(rowNumbers, np.ndarray):\n if len(rowNumbers) == 0:\n return []\n else:\n entryType = type(rowNumbers[0])\n if entryType == int or issubclass(entryType, np.integer):\n return ( self.atRowNumber(r) for r in rowNumbers )\n elif entryType == bool or issubclass(entryType, np.bool_):\n return ( self.atRowNumber(r) for r in np.flatnonzero(rowNumbers) )\n raise TypeError(\"Invalid type for IndexedBamReader slicing\")\n\n def __getattr__(self, key):\n if key in self.pbi.columnNames:\n return getattr(self.pbi, key)\n else:\n raise AttributeError(\"no such column in pbi index\")\n\n def __dir__(self):\n basicDir = dir(self.__class__)\n return basicDir + self.pbi.columnNames\n\n @property\n def identity(self):\n \"\"\"\n Fractional alignment sequence identities as numpy array.\n \"\"\"\n if len(self.pbi) == 0:\n return np.array([])\n if not \"nMM\" in self.pbi.columnNames:\n raise AttributeError(\"Identities require mapped BAM.\")\n return 1 - ((self.pbi.nMM + self.pbi.nIns + self.pbi.nDel) /\n (self.pbi.aEnd.astype(float) - self.pbi.aStart.astype(float)))\n"
] | [
[
"numpy.array",
"numpy.flatnonzero",
"numpy.rec.fromrecords",
"numpy.zeros"
]
] |
jschuhmac/qiskit-nature | [
"b8b1181d951cf8fa76fe0db9e5ea192dad5fb186"
] | [
"test/problems/second_quantization/lattice/models/test_fermi_hubbard_model.py"
] | [
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Test FermiHubbardModel.\"\"\"\nfrom test import QiskitNatureTestCase\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nfrom retworkx import PyGraph, is_isomorphic\n\nfrom qiskit_nature.problems.second_quantization.lattice import FermiHubbardModel, Lattice\n\n\nclass TestFermiHubbardModel(QiskitNatureTestCase):\n \"\"\"TestFermiHubbardModel\"\"\"\n\n def test_init(self):\n \"\"\"Test init.\"\"\"\n graph = PyGraph(multigraph=False)\n graph.add_nodes_from(range(3))\n weighted_edge_list = [\n (0, 1, 1.0 + 1.0j),\n (0, 2, -1.0),\n (1, 1, 2.0),\n ]\n graph.add_edges_from(weighted_edge_list)\n lattice = Lattice(graph)\n fhm = FermiHubbardModel(lattice, onsite_interaction=10.0)\n\n with self.subTest(\"Check the graph.\"):\n self.assertTrue(\n is_isomorphic(fhm.lattice.graph, lattice.graph, edge_matcher=lambda x, y: x == y)\n )\n\n with self.subTest(\"Check the hopping matrix\"):\n hopping_matrix = fhm.hopping_matrix()\n target_matrix = np.array(\n [[0.0, 1.0 + 1.0j, -1.0], [1.0 - 1.0j, 2.0, 0.0], [-1.0, 0.0, 0.0]]\n )\n assert_array_equal(hopping_matrix, target_matrix)\n\n with self.subTest(\"Check the second q op representation.\"):\n hopping = [\n (\"+_0 -_2\", 1.0 + 1.0j),\n (\"-_0 +_2\", -(1.0 - 1.0j)),\n (\"+_0 -_4\", -1.0),\n (\"-_0 +_4\", 1.0),\n (\"+_1 -_3\", 1.0 + 1.0j),\n (\"-_1 +_3\", -(1.0 - 1.0j)),\n (\"+_1 -_5\", -1.0),\n (\"-_1 +_5\", 1.0),\n (\"+_2 -_2\", 2.0),\n (\"+_3 -_3\", 2.0),\n ]\n\n interaction = [\n (\"+_0 -_0 +_1 -_1\", 10.0),\n (\"+_2 -_2 +_3 -_3\", 10.0),\n (\"+_4 -_4 +_5 -_5\", 10.0),\n ]\n\n ham = hopping + interaction\n\n self.assertSetEqual(set(ham), set(fhm.second_q_ops(display_format=\"sparse\").to_list()))\n\n def test_uniform_parameters(self):\n \"\"\"Test uniform_parameters.\"\"\"\n graph = PyGraph(multigraph=False)\n graph.add_nodes_from(range(3))\n weighted_edge_list = [\n (0, 1, 1.0 + 1.0j),\n (0, 2, -1.0),\n (1, 1, 2.0),\n ]\n graph.add_edges_from(weighted_edge_list)\n lattice = Lattice(graph)\n uniform_fhm = FermiHubbardModel.uniform_parameters(\n lattice,\n uniform_interaction=1.0 + 1.0j,\n uniform_onsite_potential=0.0,\n onsite_interaction=10.0,\n )\n with self.subTest(\"Check the graph.\"):\n target_graph = PyGraph(multigraph=False)\n target_graph.add_nodes_from(range(3))\n target_weight = [\n (0, 1, 1.0 + 1.0j),\n (0, 2, 1.0 + 1.0j),\n (0, 0, 0.0),\n (1, 1, 0.0),\n (2, 2, 0.0),\n ]\n target_graph.add_edges_from(target_weight)\n self.assertTrue(\n is_isomorphic(\n uniform_fhm.lattice.graph, target_graph, edge_matcher=lambda x, y: x == y\n )\n )\n with self.subTest(\"Check the hopping matrix.\"):\n hopping_matrix = uniform_fhm.hopping_matrix()\n target_matrix = np.array(\n [[0.0, 1.0 + 1.0j, 1.0 + 1.0j], [1.0 - 1.0j, 0.0, 0.0], [1.0 - 1.0j, 0.0, 0.0]]\n )\n assert_array_equal(hopping_matrix, target_matrix)\n\n with self.subTest(\"Check the second q op representation.\"):\n hopping = [\n (\"+_0 -_2\", 1.0 + 1.0j),\n (\"-_0 +_2\", -(1.0 - 1.0j)),\n (\"+_0 -_4\", 1.0 + 1.0j),\n (\"-_0 +_4\", -(1.0 - 1.0j)),\n (\"+_1 -_3\", 1.0 + 1.0j),\n (\"-_1 +_3\", -(1.0 - 1.0j)),\n (\"+_1 -_5\", 1.0 + 1.0j),\n (\"-_1 +_5\", -(1.0 - 1.0j)),\n (\"+_0 -_0\", 0.0),\n (\"+_1 -_1\", 0.0),\n (\"+_2 -_2\", 0.0),\n (\"+_3 -_3\", 0.0),\n (\"+_4 -_4\", 0.0),\n (\"+_5 -_5\", 0.0),\n ]\n\n interaction = [\n (\"+_0 -_0 +_1 -_1\", 10.0),\n (\"+_2 -_2 +_3 -_3\", 10.0),\n (\"+_4 -_4 +_5 -_5\", 10.0),\n ]\n\n ham = hopping + interaction\n\n self.assertSetEqual(\n set(ham), set(uniform_fhm.second_q_ops(display_format=\"sparse\").to_list())\n )\n\n def test_from_parameters(self):\n \"\"\"Test from_parameters.\"\"\"\n hopping_matrix = np.array(\n [[1.0, 1.0 + 1.0j, 2.0 + 2.0j], [1.0 - 1.0j, 0.0, 0.0], [2.0 - 2.0j, 0.0, 1.0]]\n )\n\n onsite_interaction = 10.0\n fhm = FermiHubbardModel.from_parameters(hopping_matrix, onsite_interaction)\n with self.subTest(\"Check the graph.\"):\n target_graph = PyGraph(multigraph=False)\n target_graph.add_nodes_from(range(3))\n target_weight = [(0, 0, 1.0), (0, 1, 1.0 + 1.0j), (0, 2, 2.0 + 2.0j), (2, 2, 1.0)]\n target_graph.add_edges_from(target_weight)\n self.assertTrue(\n is_isomorphic(fhm.lattice.graph, target_graph, edge_matcher=lambda x, y: x == y)\n )\n\n with self.subTest(\"Check the hopping matrix.\"):\n assert_array_equal(fhm.hopping_matrix(), hopping_matrix)\n\n with self.subTest(\"Check the second q op representation.\"):\n hopping = [\n (\"+_0 -_2\", 1.0 + 1.0j),\n (\"-_0 +_2\", -(1.0 - 1.0j)),\n (\"+_0 -_4\", 2.0 + 2.0j),\n (\"-_0 +_4\", -(2.0 - 2.0j)),\n (\"+_1 -_3\", 1.0 + 1.0j),\n (\"-_1 +_3\", -(1.0 - 1.0j)),\n (\"+_1 -_5\", 2.0 + 2.0j),\n (\"-_1 +_5\", -(2.0 - 2.0j)),\n (\"+_0 -_0\", 1.0),\n (\"+_1 -_1\", 1.0),\n (\"+_4 -_4\", 1.0),\n (\"+_5 -_5\", 1.0),\n ]\n\n interaction = [\n (\"+_0 -_0 +_1 -_1\", onsite_interaction),\n (\"+_2 -_2 +_3 -_3\", onsite_interaction),\n (\"+_4 -_4 +_5 -_5\", onsite_interaction),\n ]\n\n ham = hopping + interaction\n\n self.assertSetEqual(set(ham), set(fhm.second_q_ops(display_format=\"sparse\").to_list()))\n"
] | [
[
"numpy.array",
"numpy.testing.assert_array_equal"
]
] |
walterddr/nestedtensor | [
"2818db1d83dbd475aa54aee3ab84749a4c13e911"
] | [
"nestedtensor/nested/fuser.py"
] | [
"import torch.fx as fx\nfrom typing import Type, Dict, Any, Tuple, Iterable\nimport torch\nimport copy\nfrom torch.fx import symbolic_trace\nimport time\n\ndef _parent_name(target : str) -> Tuple[str, str]:\n \"\"\"\n Splits a qualname into parent path and last atom.\n For example, `foo.bar.baz` -> (`foo.bar`, `baz`)\n \"\"\"\n *parent, name = target.rsplit('.', 1)\n return parent[0] if parent else '', name\n\n# Works for length 2 patterns with 2 modules\ndef matches_module_pattern(pattern: Iterable[Type], node: fx.Node, modules: Dict[str, Any]):\n if len(node.args) == 0:\n return False\n nodes: Tuple[Any, fx.Node] = (node.args[0], node)\n for expected_type, current_node in zip(pattern, nodes):\n if not isinstance(current_node, fx.Node):\n return False\n if current_node.op != 'call_module':\n return False\n if not isinstance(current_node.target, str):\n return False\n if current_node.target not in modules:\n return False\n if type(modules[current_node.target]) is not expected_type:\n return False\n return True\n\n\ndef replace_node_module(node: fx.Node, modules: Dict[str, Any], new_module: torch.nn.Module):\n assert(isinstance(node.target, str))\n parent_name, name = _parent_name(node.target)\n setattr(modules[parent_name], name, new_module)\n\ndef computeUpdatedConvWeightAndBias(\n bn_rv,\n bn_eps,\n bn_w,\n bn_b,\n bn_rm,\n conv_w,\n conv_b=None):\n orig_dtype = bn_rv.dtype\n bn_var_rsqrt = (bn_w / torch.sqrt(bn_rv.to(torch.double) + bn_eps))\n new_w = (conv_w * (bn_var_rsqrt).reshape(-1, 1, 1, 1)).to(orig_dtype)\n if conv_b is None:\n return new_w\n new_b = (conv_b - bn_rm) * bn_var_rsqrt * bn_w + bn_b\n return new_w, new_b\n\ndef fuse_conv_bn_eval(conv, bn):\n assert(not (conv.training or bn.training)), \"Fusion only for eval!\"\n fused_conv = copy.deepcopy(conv)\n fused_conv.bias = None\n\n fused_conv.weight = \\\n torch.nn.Parameter(computeUpdatedConvWeightAndBias(bn.running_var, bn.eps, bn.weight, bn.bias, bn.running_mean, fused_conv.weight))\n\n return fused_conv\n\ndef fuse_conv_bn(model: torch.nn.Module, inplace=False) -> torch.nn.Module:\n \"\"\"\n Fuses convolution/BN layers for inference purposes. Will deepcopy your\n model by default, but can modify the model inplace as well.\n \"\"\"\n patterns = [(torch.nn.Conv2d, torch.nn.BatchNorm2d)]\n if not inplace:\n model = copy.deepcopy(model)\n fx_model = fx.symbolic_trace(model)\n modules = dict(fx_model.named_modules())\n new_graph = copy.deepcopy(fx_model.graph)\n\n for pattern in patterns:\n for node in new_graph.nodes:\n if matches_module_pattern(pattern, node, modules):\n if len(node.args[0].users) > 1: # Output of conv is used by other nodes\n continue\n conv = modules[node.args[0].target]\n bn = modules[node.target]\n fused_conv = fuse_conv_bn_eval(conv, bn)\n replace_node_module(node.args[0], modules, fused_conv)\n node.replace_all_uses_with(node.args[0])\n new_graph.erase_node(node)\n return fx.GraphModule(fx_model, new_graph)\n"
] | [
[
"torch.fx.GraphModule",
"torch.fx.symbolic_trace"
]
] |
QiXi9409/Simultaneous_ECG_Heartbeat | [
"8984084d570a0e45bf3508a1a23d562ba147ca84"
] | [
"rcn_tool_b.py"
] | [
"from rcn_tool_a import rcn_tool_a\r\nimport torch\r\nfrom config import cfg\r\nclass rcn_tool_b(rcn_tool_a):\r\n def roi_pooling_cuda(self, features, proposal, label=None, stride=cfg.feature_stride, pool=None, batch=False):\r\n if batch == True:\r\n batch_output = []\r\n batch_label = []\r\n if label != None:\r\n batch_label.extend([j for i in label for j in i])\r\n batch_label = torch.stack(batch_label)\r\n outputs = pool(features, proposal)\r\n batch_output = outputs\r\n class_num = [0] * 6\r\n # if label != None:\r\n # for i in batch_label:\r\n # if i != -1:\r\n # class_num[i.item()] += 1\r\n # average = int(sum(class_num) / 6)\r\n # class_num = [average / (i + 1) for i in class_num]\r\n return batch_output, batch_label, class_num\r\n else:\r\n if len(features.size()) == 3:\r\n batch_size, num_channels, data_width = features.size()\r\n batch_output = []\r\n batch_label = []\r\n for index in range(batch_size):\r\n data = features[index]\r\n this_proposal = proposal[index]\r\n # num_proposal = this_proposal.size()[0]\r\n outputs = pool(data, this_proposal)\r\n # if torch.isnan(outputs).sum()>=1:\r\n # print('nan produce')\r\n # if torch.isinf(outputs).sum()>=1:\r\n # print('inf procude')\r\n batch_output.append(outputs)\r\n if label != None:\r\n batch_label.extend([i for i in label[index]])\r\n if label != None:\r\n batch_label = torch.stack(batch_label)\r\n # batch_output = [torch.stack(i) for i in batch_output]\r\n\r\n class_num = [0] * 5\r\n # if label != None:\r\n # for i in batch_label:\r\n # if i != -1:\r\n # class_num[i.item()] += 1\r\n # average = int(sum(class_num) / 5)\r\n # class_num = [average / (i + 1) for i in class_num]\r\n # class_num[0] /= 30\r\n return batch_output, batch_label, class_num\r\n else:\r\n batch_output = []\r\n batch_label = []\r\n # num_channels, data_width = features.size()\r\n data = features\r\n this_proposal = proposal\r\n num_proposal = this_proposal.size()[0]\r\n # width_limit_right = torch.Tensor([data_width - 1] * num_proposal).cuda()\r\n # width_limit_left = torch.zeros(num_proposal).cuda()\r\n # start = torch.floor(this_proposal * (1 / stride))[:,\r\n # 0]\r\n # end = torch.ceil(this_proposal * (1 / stride))[:, 1] #\r\n # wstart = torch.min(width_limit_right, torch.max(width_limit_left, start)).type(\r\n # torch.long)\r\n # wend = torch.min(width_limit_right, torch.max(width_limit_left, end)).type(\r\n # torch.long)\r\n # tmp = self.get_average(data, wstart, wend, stride)\r\n outputs = pool(data, this_proposal)\r\n # outputs = tmp\r\n batch_output.extend([outputs[i, :] for i in range(num_proposal)])\r\n if label != None:\r\n batch_label.extend(label)\r\n batch_output = torch.stack(batch_output, 0)\r\n return batch_output"
] | [
[
"torch.stack"
]
] |
pquochuy/SeqSleepNet | [
"ae0b4bd72aec456d0ef6fe15589ef17cdb9468e3"
] | [
"tensorflow_net/E2E-ARNN/train_arnn_sleep.py"
] | [
"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0,-1\"\nimport numpy as np\nimport tensorflow as tf\n\n#from tensorflow.python.client import device_lib\n#print(device_lib.list_local_devices())\n\nimport shutil, sys\nfrom datetime import datetime\nimport h5py\n\nfrom arnn_sleep import ARNN_Sleep\nfrom arnn_sleep_config import Config\n\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import cohen_kappa_score\n\nfrom datagenerator_from_list_v2 import DataGenerator\n\n#from scipy.io import loadmat\n\n\n# Parameters\n# ==================================================\n\n# Misc Parameters\ntf.app.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\ntf.app.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\n\n# My Parameters\ntf.app.flags.DEFINE_string(\"eeg_train_data\", \"../train_data.mat\", \"Point to directory of input data\")\ntf.app.flags.DEFINE_string(\"eeg_eval_data\", \"../data/eval_data_1.mat\", \"Point to directory of input data\")\ntf.app.flags.DEFINE_string(\"eeg_test_data\", \"../test_data.mat\", \"Point to directory of input data\")\ntf.app.flags.DEFINE_string(\"eog_train_data\", \"../train_data.mat\", \"Point to directory of input data\")\ntf.app.flags.DEFINE_string(\"eog_eval_data\", \"../data/eval_data_1.mat\", \"Point to directory of input data\")\ntf.app.flags.DEFINE_string(\"eog_test_data\", \"../test_data.mat\", \"Point to directory of input data\")\ntf.app.flags.DEFINE_string(\"emg_train_data\", \"../train_data.mat\", \"Point to directory of input data\")\ntf.app.flags.DEFINE_string(\"emg_eval_data\", \"../data/eval_data_1.mat\", \"Point to directory of input data\")\ntf.app.flags.DEFINE_string(\"emg_test_data\", \"../test_data.mat\", \"Point to directory of input data\")\ntf.app.flags.DEFINE_string(\"out_dir\", \"./output/\", \"Point to output directory\")\ntf.app.flags.DEFINE_string(\"checkpoint_dir\", \"./checkpoint/\", \"Point to checkpoint directory\")\n\ntf.app.flags.DEFINE_float(\"dropout_keep_prob_rnn\", 0.75, \"Dropout keep probability (default: 0.75)\")\n\ntf.app.flags.DEFINE_integer(\"seq_len\", 32, \"Sequence length (default: 32)\")\n\ntf.app.flags.DEFINE_integer(\"nfilter\", 20, \"Sequence length (default: 20)\")\n\ntf.app.flags.DEFINE_integer(\"nhidden1\", 64, \"Sequence length (default: 20)\")\ntf.app.flags.DEFINE_integer(\"attention_size1\", 32, \"Sequence length (default: 20)\")\n\nFLAGS = tf.app.flags.FLAGS\nprint(\"\\nParameters:\")\nfor attr, value in sorted(FLAGS.__flags.items()): # python3\n print(\"{}={}\".format(attr.upper(), value))\nprint(\"\")\n\n# Data Preparatopn\n# ==================================================\n\n# path where some output are stored\nout_path = os.path.abspath(os.path.join(os.path.curdir,FLAGS.out_dir))\n# path where checkpoint models are stored\ncheckpoint_path = os.path.abspath(os.path.join(out_path,FLAGS.checkpoint_dir))\nif not os.path.isdir(os.path.abspath(out_path)): os.makedirs(os.path.abspath(out_path))\nif not os.path.isdir(os.path.abspath(checkpoint_path)): os.makedirs(os.path.abspath(checkpoint_path))\n\nconfig = Config()\nconfig.dropout_keep_prob_rnn = FLAGS.dropout_keep_prob_rnn\nconfig.epoch_seq_len = FLAGS.seq_len\nconfig.epoch_step = FLAGS.seq_len\nconfig.nfilter = FLAGS.nfilter\nconfig.nhidden1 = FLAGS.nhidden1\nconfig.attention_size1 = FLAGS.attention_size1\n\neeg_active = ((FLAGS.eeg_train_data != \"\") and (FLAGS.eeg_test_data != \"\"))\neog_active = ((FLAGS.eog_train_data != \"\") and (FLAGS.eog_test_data != \"\"))\nemg_active = ((FLAGS.emg_train_data != \"\") and (FLAGS.emg_test_data != \"\"))\n\nif (eeg_active):\n print(\"eeg active\")\n # Initalize the data generator seperately for the training, validation, and test sets\n eeg_train_gen = DataGenerator(os.path.abspath(FLAGS.eeg_train_data), data_shape=[config.frame_seq_len, config.ndim], shuffle = False)\n eeg_test_gen = DataGenerator(os.path.abspath(FLAGS.eeg_test_data), data_shape=[config.frame_seq_len, config.ndim], shuffle = False)\n eeg_eval_gen = DataGenerator(os.path.abspath(FLAGS.eeg_eval_data), data_shape=[config.frame_seq_len, config.ndim], shuffle = False)\n\n # data normalization here\n X = eeg_train_gen.X\n X = np.reshape(X,(eeg_train_gen.data_size*eeg_train_gen.data_shape[0], eeg_train_gen.data_shape[1]))\n meanX = X.mean(axis=0)\n stdX = X.std(axis=0)\n X = (X - meanX) / stdX\n eeg_train_gen.X = np.reshape(X, (eeg_train_gen.data_size, eeg_train_gen.data_shape[0], eeg_train_gen.data_shape[1]))\n\n X = eeg_eval_gen.X\n X = np.reshape(X,(eeg_eval_gen.data_size*eeg_eval_gen.data_shape[0], eeg_eval_gen.data_shape[1]))\n X = (X - meanX) / stdX\n eeg_eval_gen.X = np.reshape(X, (eeg_eval_gen.data_size, eeg_eval_gen.data_shape[0], eeg_eval_gen.data_shape[1]))\n\n X = eeg_test_gen.X\n X = np.reshape(X,(eeg_test_gen.data_size*eeg_test_gen.data_shape[0], eeg_test_gen.data_shape[1]))\n X = (X - meanX) / stdX\n eeg_test_gen.X = np.reshape(X, (eeg_test_gen.data_size, eeg_test_gen.data_shape[0], eeg_test_gen.data_shape[1]))\n\nif (eog_active):\n print(\"eog active\")\n # Initalize the data generator seperately for the training, validation, and test sets\n eog_train_gen = DataGenerator(os.path.abspath(FLAGS.eog_train_data), data_shape=[config.frame_seq_len, config.ndim], shuffle = False)\n eog_test_gen = DataGenerator(os.path.abspath(FLAGS.eog_test_data), data_shape=[config.frame_seq_len, config.ndim], shuffle = False)\n eog_eval_gen = DataGenerator(os.path.abspath(FLAGS.eog_eval_data), data_shape=[config.frame_seq_len, config.ndim], shuffle = False)\n\n # data normalization here\n X = eog_train_gen.X\n X = np.reshape(X,(eog_train_gen.data_size*eog_train_gen.data_shape[0], eog_train_gen.data_shape[1]))\n meanX = X.mean(axis=0)\n stdX = X.std(axis=0)\n X = (X - meanX) / stdX\n eog_train_gen.X = np.reshape(X, (eog_train_gen.data_size, eog_train_gen.data_shape[0], eog_train_gen.data_shape[1]))\n\n X = eog_eval_gen.X\n X = np.reshape(X,(eog_eval_gen.data_size*eog_eval_gen.data_shape[0], eog_eval_gen.data_shape[1]))\n X = (X - meanX) / stdX\n eog_eval_gen.X = np.reshape(X, (eog_eval_gen.data_size, eog_eval_gen.data_shape[0], eog_eval_gen.data_shape[1]))\n\n X = eog_test_gen.X\n X = np.reshape(X,(eog_test_gen.data_size*eog_test_gen.data_shape[0], eog_test_gen.data_shape[1]))\n X = (X - meanX) / stdX\n eog_test_gen.X = np.reshape(X, (eog_test_gen.data_size, eog_test_gen.data_shape[0], eog_test_gen.data_shape[1]))\n\nif (emg_active):\n print(\"emg active\")\n # Initalize the data generator seperately for the training, validation, and test sets\n emg_train_gen = DataGenerator(os.path.abspath(FLAGS.emg_train_data), data_shape=[config.frame_seq_len, config.ndim], shuffle = False)\n emg_test_gen = DataGenerator(os.path.abspath(FLAGS.emg_test_data), data_shape=[config.frame_seq_len, config.ndim], shuffle = False)\n emg_eval_gen = DataGenerator(os.path.abspath(FLAGS.emg_eval_data), data_shape=[config.frame_seq_len, config.ndim], shuffle = False)\n\n # data normalization here\n X = emg_train_gen.X\n X = np.reshape(X,(emg_train_gen.data_size*emg_train_gen.data_shape[0], emg_train_gen.data_shape[1]))\n meanX = X.mean(axis=0)\n stdX = X.std(axis=0)\n X = (X - meanX) / stdX\n emg_train_gen.X = np.reshape(X, (emg_train_gen.data_size, emg_train_gen.data_shape[0], emg_train_gen.data_shape[1]))\n\n X = emg_eval_gen.X\n X = np.reshape(X,(emg_eval_gen.data_size*emg_eval_gen.data_shape[0], emg_eval_gen.data_shape[1]))\n X = (X - meanX) / stdX\n emg_eval_gen.X = np.reshape(X, (emg_eval_gen.data_size, emg_eval_gen.data_shape[0], emg_eval_gen.data_shape[1]))\n\n X = emg_test_gen.X\n X = np.reshape(X,(emg_test_gen.data_size*emg_test_gen.data_shape[0], emg_test_gen.data_shape[1]))\n X = (X - meanX) / stdX\n emg_test_gen.X = np.reshape(X, (emg_test_gen.data_size, emg_test_gen.data_shape[0], emg_test_gen.data_shape[1]))\n\n# eeg always active\ntrain_generator = eeg_train_gen\ntest_generator = eeg_test_gen\neval_generator = eeg_eval_gen\n\nif (not(eog_active) and not(emg_active)):\n train_generator.X = np.expand_dims(train_generator.X, axis=-1) # expand channel dimension\n train_generator.data_shape = train_generator.X.shape[1:]\n test_generator.X = np.expand_dims(test_generator.X, axis=-1) # expand channel dimension\n test_generator.data_shape = test_generator.X.shape[1:]\n eval_generator.X = np.expand_dims(eval_generator.X, axis=-1) # expand channel dimension\n eval_generator.data_shape = eval_generator.X.shape[1:]\n nchannel = 1\n print(train_generator.X.shape)\n\nif (eog_active and not(emg_active)):\n print(train_generator.X.shape)\n print(eog_train_gen.X.shape)\n train_generator.X = np.stack((train_generator.X, eog_train_gen.X), axis=-1) # merge and make new dimension\n train_generator.data_shape = train_generator.X.shape[1:]\n test_generator.X = np.stack((test_generator.X, eog_test_gen.X), axis=-1) # merge and make new dimension\n test_generator.data_shape = test_generator.X.shape[1:]\n eval_generator.X = np.stack((eval_generator.X, eog_eval_gen.X), axis=-1) # merge and make new dimension\n eval_generator.data_shape = eval_generator.X.shape[1:]\n nchannel = 2\n print(train_generator.X.shape)\n\nif (eog_active and emg_active):\n print(train_generator.X.shape)\n print(eog_train_gen.X.shape)\n print(emg_train_gen.X.shape)\n train_generator.X = np.stack((train_generator.X, eog_train_gen.X, emg_train_gen.X), axis=-1) # merge and make new dimension\n train_generator.data_shape = train_generator.X.shape[1:]\n test_generator.X = np.stack((test_generator.X, eog_test_gen.X, emg_test_gen.X), axis=-1) # merge and make new dimension\n test_generator.data_shape = test_generator.X.shape[1:]\n eval_generator.X = np.stack((eval_generator.X, eog_eval_gen.X, emg_eval_gen.X), axis=-1) # merge and make new dimension\n eval_generator.data_shape = eval_generator.X.shape[1:]\n nchannel = 3\n print(train_generator.X.shape)\n\nconfig.nchannel = nchannel\n\ndel eeg_train_gen\ndel eeg_test_gen\ndel eeg_eval_gen\nif (eog_active):\n del eog_train_gen\n del eog_test_gen\n del eog_eval_gen\nif (emg_active):\n del emg_train_gen\n del emg_test_gen\n del emg_eval_gen\n\n# shuffle training data here\ntrain_generator.shuffle_data()\n\ntrain_batches_per_epoch = np.floor(len(train_generator.data_index) / config.batch_size).astype(np.uint32)\neval_batches_per_epoch = np.floor(len(eval_generator.data_index) / config.batch_size).astype(np.uint32)\ntest_batches_per_epoch = np.floor(len(test_generator.data_index) / config.batch_size).astype(np.uint32)\n\nprint(\"Train/Eval/Test set: {:d}/{:d}/{:d}\".format(train_generator.data_size, eval_generator.data_size, test_generator.data_size))\n\nprint(\"Train/Eval/Test batches per epoch: {:d}/{:d}/{:d}\".format(train_batches_per_epoch, eval_batches_per_epoch, test_batches_per_epoch))\n\n# variable to keep track of best fscore\nbest_fscore = 0.0\nbest_acc = 0.0\nbest_kappa = 0.0\nmin_loss = float(\"inf\")\n# Training\n# ==================================================\n\nwith tf.Graph().as_default():\n session_conf = tf.ConfigProto(\n allow_soft_placement=FLAGS.allow_soft_placement,\n log_device_placement=FLAGS.log_device_placement)\n session_conf.gpu_options.allow_growth = True\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n arnn = ARNN_Sleep(config=config)\n\n # Define Training procedure\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n optimizer = tf.train.AdamOptimizer(config.learning_rate)\n grads_and_vars = optimizer.compute_gradients(arnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)\n\n out_dir = os.path.abspath(os.path.join(os.path.curdir,FLAGS.out_dir))\n print(\"Writing to {}\\n\".format(out_dir))\n\n saver = tf.train.Saver(tf.all_variables(), max_to_keep=1)\n\n # initialize all variables\n print(\"Model initialized\")\n sess.run(tf.initialize_all_variables())\n\n def train_step(x_batch, y_batch):\n \"\"\"\n A single training step\n \"\"\"\n frame_seq_len = np.ones(len(x_batch),dtype=int) * config.frame_seq_len\n feed_dict = {\n arnn.input_x: x_batch,\n arnn.input_y: y_batch,\n arnn.dropout_keep_prob_rnn: config.dropout_keep_prob_rnn,\n arnn.frame_seq_len: frame_seq_len\n }\n _, step, output_loss, total_loss, accuracy = sess.run(\n [train_op, global_step, arnn.output_loss, arnn.loss, arnn.accuracy],\n feed_dict)\n return step, output_loss, total_loss, accuracy\n\n def dev_step(x_batch, y_batch):\n frame_seq_len = np.ones(len(x_batch),dtype=int) * config.frame_seq_len\n feed_dict = {\n arnn.input_x: x_batch,\n arnn.input_y: y_batch,\n arnn.dropout_keep_prob_rnn: 1.0,\n arnn.frame_seq_len: frame_seq_len\n }\n output_loss, total_loss, yhat = sess.run(\n [arnn.output_loss, arnn.loss, arnn.prediction], feed_dict)\n return output_loss, total_loss, yhat\n\n def evaluate(gen, log_filename):\n # Validate the model on the entire evaluation test set after each epoch\n output_loss =0\n total_loss = 0\n yhat = np.zeros([len(gen.data_index)])\n num_batch_per_epoch = np.floor(len(gen.data_index) / (config.batch_size)).astype(np.uint32)\n test_step = 1\n while test_step < num_batch_per_epoch:\n x_batch, y_batch, label_batch_ = gen.next_batch(config.batch_size)\n output_loss_, total_loss_, yhat_ = dev_step(x_batch, y_batch)\n output_loss += output_loss_\n total_loss += total_loss_\n\n yhat[(test_step-1)*config.batch_size : test_step*config.batch_size] = yhat_\n test_step += 1\n if(gen.pointer < len(gen.data_index)):\n actual_len, x_batch, y_batch, label_batch_ = gen.rest_batch(config.batch_size)\n output_loss_, total_loss_, yhat_ = dev_step(x_batch, y_batch)\n\n yhat[(test_step-1)*config.batch_size : len(gen.data_index)] = yhat_\n output_loss += output_loss_\n total_loss += total_loss_\n yhat = yhat + 1\n acc = accuracy_score(gen.label, yhat)\n with open(os.path.join(out_dir, log_filename), \"a\") as text_file:\n text_file.write(\"{:g} {:g} {:g}\\n\".format(output_loss, total_loss, acc))\n return acc, yhat, output_loss, total_loss\n\n # Loop over number of epochs\n for epoch in range(config.training_epoch):\n print(\"{} Epoch number: {}\".format(datetime.now(), epoch + 1))\n step = 1\n while step < train_batches_per_epoch:\n # Get a batch\n x_batch, y_batch, label_batch = train_generator.next_batch(config.batch_size)\n train_step_, train_output_loss_, train_total_loss_, train_acc_ = train_step(x_batch, y_batch)\n time_str = datetime.now().isoformat()\n\n print(\"{}: step {}, output_loss {}, total_loss {} acc {}\".format(time_str, train_step_, train_output_loss_, train_total_loss_, train_acc_))\n step += 1\n\n current_step = tf.train.global_step(sess, global_step)\n if current_step % config.evaluate_every == 0:\n # Validate the model on the entire evaluation test set after each epoch\n print(\"{} Start validation\".format(datetime.now()))\n eval_acc, eval_yhat, eval_output_loss, eval_total_loss = evaluate(gen=eval_generator, log_filename=\"eval_result_log.txt\")\n test_acc, test_yhat, test_output_loss, test_total_loss = evaluate(gen=test_generator, log_filename=\"test_result_log.txt\")\n\n if(eval_acc >= best_acc):\n best_acc = eval_acc\n checkpoint_name = os.path.join(checkpoint_path, 'model_step' + str(current_step) +'.ckpt')\n save_path = saver.save(sess, checkpoint_name)\n\n print(\"Best model updated\")\n source_file = checkpoint_name\n dest_file = os.path.join(checkpoint_path, 'best_model_acc')\n shutil.copy(source_file + '.data-00000-of-00001', dest_file + '.data-00000-of-00001')\n shutil.copy(source_file + '.index', dest_file + '.index')\n shutil.copy(source_file + '.meta', dest_file + '.meta')\n\n\n test_generator.reset_pointer()\n eval_generator.reset_pointer()\n train_generator.reset_pointer()\n"
] | [
[
"tensorflow.initialize_all_variables",
"tensorflow.train.global_step",
"tensorflow.app.flags.DEFINE_string",
"tensorflow.all_variables",
"numpy.reshape",
"tensorflow.train.AdamOptimizer",
"tensorflow.Graph",
"sklearn.metrics.accuracy_score",
"numpy.expand_dims",
"tensorflow.Variable",
"tensorflow.app.flags.DEFINE_float",
"tensorflow.Session",
"numpy.stack",
"tensorflow.app.flags.DEFINE_boolean",
"tensorflow.ConfigProto",
"tensorflow.app.flags.DEFINE_integer"
]
] |
AdityaSavara/Frhodo | [
"90ad23b8f238bd2b4dd9b94eea757fa658e92499"
] | [
"src/mech_fcns.py"
] | [
"# This file is part of Frhodo. Copyright © 2020, UChicago Argonne, LLC\n# and licensed under BSD-3-Clause. See License.txt in the top-level \n# directory for license and copyright information.\n\nimport os, io, stat, contextlib, pathlib, time\nimport cantera as ct\nfrom cantera import interrupts, cti2yaml#, ck2yaml, ctml2yaml\nimport numpy as np\nimport integrate, shock_fcns, ck2yaml\nfrom timeit import default_timer as timer\n\n# list of all possible variables\nall_var = {'Laboratory Time': {'SIM_name': 't_lab', 'sub_type': None},\n 'Shockwave Time': {'SIM_name': 't_shock', 'sub_type': None}, \n 'Gas Velocity': {'SIM_name': 'vel', 'sub_type': None}, \n 'Temperature': {'SIM_name': 'T', 'sub_type': None}, \n 'Pressure': {'SIM_name': 'P', 'sub_type': None}, \n 'Enthalpy': {'SIM_name': 'h', 'sub_type': ['total', 'species']},\n 'Entropy': {'SIM_name': 's', 'sub_type': ['total', 'species']}, \n 'Density': {'SIM_name': 'rho', 'sub_type': None}, \n 'Density Gradient': {'SIM_name': 'drhodz', 'sub_type': ['total', 'rxn']},\n '% Density Gradient': {'SIM_name': 'perc_drhodz', 'sub_type': ['rxn']},\n 'Mole Fraction': {'SIM_name': 'X', 'sub_type': ['species']}, \n 'Mass Fraction': {'SIM_name': 'Y', 'sub_type': ['species']}, \n 'Concentration': {'SIM_name': 'conc', 'sub_type': ['species']}, \n 'Net Production Rate': {'SIM_name': 'wdot', 'sub_type': ['species']},\n 'Creation Rate': {'SIM_name': 'wdotfor', 'sub_type': ['species']}, \n 'Destruction Rate': {'SIM_name': 'wdotrev', 'sub_type': ['species']},\n 'Heat Release Rate': {'SIM_name': 'HRR', 'sub_type': ['total', 'rxn']},\n 'Delta Enthalpy (Heat of Reaction)':{'SIM_name': 'delta_h', 'sub_type': ['rxn']},\n 'Delta Entropy': {'SIM_name': 'delta_s', 'sub_type': ['rxn']}, \n 'Equilibrium Constant': {'SIM_name': 'eq_con', 'sub_type': ['rxn']}, \n 'Forward Rate Constant': {'SIM_name': 'rate_con', 'sub_type': ['rxn']}, \n 'Reverse Rate Constant': {'SIM_name': 'rate_con_rev', 'sub_type': ['rxn']}, \n 'Net Rate of Progress': {'SIM_name': 'net_ROP', 'sub_type': ['rxn']}, \n 'Forward Rate of Progress': {'SIM_name': 'for_ROP', 'sub_type': ['rxn']}, \n 'Reverse Rate of Progress': {'SIM_name': 'rev_ROP', 'sub_type': ['rxn']}}\n\nrev_all_var = {all_var[key]['SIM_name']: \n {'name': key, 'sub_type': all_var[key]['sub_type']} for key in all_var.keys()}\n\n# translation dictionary between SIM name and ct.SolutionArray name\nSIM_Dict = {'t_lab': 't', 't_shock': 't_shock', 'z': 'z', 'A': 'A', 'vel': 'vel', 'T': 'T', 'P': 'P', \n 'h_tot': 'enthalpy_mole', 'h': 'partial_molar_enthalpies', \n 's_tot': 'entropy_mole', 's': 'partial_molar_entropies',\n 'rho': 'density', 'drhodz_tot': 'drhodz_tot', 'drhodz': 'drhodz', 'perc_drhodz': 'perc_drhodz',\n 'Y': 'Y', 'X': 'X', 'conc': 'concentrations', 'wdot': 'net_production_rates', \n 'wdotfor': 'creation_rates', 'wdotrev': 'destruction_rates', \n 'HRR_tot': 'heat_release_rate', 'HRR': 'heat_production_rates',\n 'delta_h': 'delta_enthalpy', 'delta_s': 'delta_entropy', \n 'eq_con': 'equilibrium_constants', 'rate_con': 'forward_rate_constants', \n 'rate_con_rev': 'reverse_rate_constants', 'net_ROP': 'net_rates_of_progress',\n 'for_ROP': 'forward_rates_of_progress', 'rev_ROP': 'reverse_rates_of_progress'}\n\nclass SIM_Property:\n def __init__(self, name, parent=None):\n self.name = name\n self.parent = parent\n self.conversion = None # this needs to be assigned per property\n self.value = {'SI': np.array([]), 'CGS': np.array([])}\n self.ndim = self.value['SI'].ndim\n\n def clear(self):\n self.value = {'SI': np.array([]), 'CGS': np.array([])}\n self.ndim = self.value['SI'].ndim\n\n def __call__(self, idx=None, units='CGS'): # units must be 'CGS' or 'SI'\n # assumes Sim data comes in as SI and is converted to CGS\n # values to be calculated post-simulation\n if len(self.value['SI']) == 0 or np.isnan(self.value['SI']).all():\n parent = self.parent\n if self.name == 'drhodz_tot':\n self.value['SI'] = shock_fcns.drhodz(parent.states)\n elif self.name == 'drhodz':\n self.value['SI'] = shock_fcns.drhodz_per_rxn(parent.states)\n elif self.name == 'perc_drhodz':\n self.value['SI'] = parent.drhodz(units='SI').T*100/parent.drhodz_tot(units='SI')[:,None]\n else:\n self.value['SI'] = getattr(parent.states, SIM_Dict[self.name])\n\n if self.value['SI'].ndim > 1: # Transpose if matrix\n self.value['SI'] = self.value['SI'].T\n\n self.ndim = self.value['SI'].ndim\n\n # currently converts entire list of properties rather than by index\n if units == 'CGS' and len(self.value['CGS']) == 0:\n if self.conversion is None:\n self.value['CGS'] = self.value['SI']\n else:\n self.value['CGS'] = self.conversion(self.value['SI'])\n\n return self.value[units]\n\n\nclass Simulation_Result:\n def __init__(self, num=None, states=None, reactor_vars=[]):\n self.states = states\n self.all_var = all_var\n self.rev_all_var = rev_all_var\n self.reactor_var = {}\n for var in reactor_vars:\n if var in self.rev_all_var:\n self.reactor_var[self.rev_all_var[var]['name']] = var\n\n if num is None: # if no simulation stop here\n self.reactor_var = {}\n return\n\n self.conv = {'conc': 1E-3, 'wdot': 1E-3, 'P': 760/101325, 'vel': 1E2, \n 'rho': 1E-3, 'drhodz_tot': 1E-5, 'drhodz': 1E-5, \n 'delta_h': 1E-3/4184, 'h_tot': 1E-3/4184, 'h': 1E-3/4184, # to kcal\n 'delta_s': 1/4184, 's_tot': 1/4184, 's': 1/4184, \n 'eq_con': 1E3**np.array(num['reac'] - num['prod'])[:,None],\n 'rate_con': np.power(1E3,num['reac']-1)[:,None],\n 'rate_con_rev': np.power(1E3,num['prod']-1)[:,None],\n 'net_ROP': 1E-3/3.8, # Don't understand 3.8 value\n 'for_ROP': 1E-3/3.8, # Don't understand 3.8 value\n 'rev_ROP': 1E-3/3.8} # Don't understand 3.8 value\n\n for name in reactor_vars:\n property = SIM_Property(name, parent=self)\n if name in self.conv:\n property.conversion = lambda x, s=self.conv[name]: x*s\n setattr(self, name, property)\n\n def set_independent_var(self, ind_var, units='CGS'):\n self.independent_var = getattr(self, ind_var)(units=units)\n\n def set_observable(self, observable, units='CGS'):\n k = observable['sub']\n if observable['main'] == 'Temperature':\n self.observable = self.T(units=units)\n elif observable['main'] == 'Pressure':\n self.observable = self.P(units=units)\n elif observable['main'] == 'Density Gradient':\n self.observable = self.drhodz_tot(units=units)\n elif observable['main'] == 'Heat Release Rate':\n self.observable = self.HRR_tot(units=units)\n elif observable['main'] == 'Mole Fraction':\n self.observable = self.X(units=units)\n elif observable['main'] == 'Mass Fraction':\n self.observable = self.Y(units=units)\n elif observable['main'] == 'Concentration':\n self.observable = self.conc(units=units)\n\n if self.observable.ndim > 1: # reduce observable down to only plotted information\n self.observable = self.observable[k]\n\n def finalize(self, success, ind_var, observable, units='CGS'): \n self.set_independent_var(ind_var, units)\n self.set_observable(observable, units)\n \n self.success = success\n \n\nclass Chemical_Mechanism:\n def __init__(self):\n self.isLoaded = False\n self.reactor = Reactor(self)\n\n def load_mechanism(self, path, silent=False):\n def loader(self, path):\n # path is assumed to be the path dictionary\n surfaces = []\n if path['mech'].suffix in ['.yaml', '.yml']: # check if it's a yaml cantera file\n mech_path = str(path['mech'])\n else: # if not convert into yaml cantera file\n mech_path = str(path['Cantera_Mech'])\n \n if path['mech'].suffix == '.cti':\n cti2yaml.convert(path['mech'], path['Cantera_Mech'])\n elif path['mech'].suffix in ['.ctml', '.xml']:\n raise Exception('not implemented')\n #ctml2yaml.convert(path['mech'], path['Cantera_Mech'])\n else: # if not a cantera file, assume chemkin\n surfaces = self.chemkin2cantera(path)\n \n print('Validating mechanism...', end='') \n try: # This test taken from ck2cti\n self.yaml_txt = path['Cantera_Mech'].read_text() # Storing full text could be bad if large\n self.gas = ct.Solution(yaml=self.yaml_txt)\n for surfname in surfaces:\n phase = ct.Interface(outName, surfname, [self.gas])\n print('PASSED.')\n except RuntimeError as e:\n print('FAILED.')\n print(e)\n \n output = {'success': False, 'message': []}\n # Intialize and report any problems to log, not to console window\n stdout = io.StringIO()\n stderr = io.StringIO()\n with contextlib.redirect_stderr(stderr):\n with contextlib.redirect_stdout(stdout):\n try:\n loader(self, path)\n output['success'] = True\n except Exception as e:\n output['message'].append('Error in loading mech\\n{:s}'.format(str(e)))\n except:\n pass\n # output['message'].append('Error when loading mech:\\n')\n \n ct_out = stdout.getvalue()\n ct_err = stderr.getvalue().replace('INFO:root:', 'Warning: ')\n \n if 'FAILED' in ct_out:\n output['success'] = False\n self.isLoaded = False\n elif 'PASSED' in ct_out:\n output['success'] = True\n self.isLoaded = True\n \n for log_str in [ct_out, ct_err]:\n if log_str != '' and not silent:\n if (path['Cantera_Mech'], pathlib.WindowsPath): # reformat string to remove \\\\ making it unable to be copy paste\n cantera_path = str(path['Cantera_Mech']).replace('\\\\', '\\\\\\\\')\n log_str = log_str.replace(cantera_path, str(path['Cantera_Mech']))\n output['message'].append(log_str)\n output['message'].append('\\n')\n \n if self.isLoaded:\n self.set_rate_expression_coeffs() # set copy of coeffs\n self.set_thermo_expression_coeffs() # set copy of thermo coeffs\n \n return output\n \n def chemkin2cantera(self, path):\n if path['thermo'] is not None:\n surfaces = ck2yaml.convert_mech(path['mech'], thermo_file=path['thermo'], transport_file=None, surface_file=None,\n phase_name='gas', out_name=path['Cantera_Mech'], quiet=False, permissive=True)\n else:\n surfaces = ck2yaml.convert_mech(path['mech'], thermo_file=None, transport_file=None, surface_file=None,\n phase_name='gas', out_name=path['Cantera_Mech'], quiet=False, permissive=True)\n \n return surfaces\n \n def set_mechanism(self, mech_txt):\n self.gas = ct.Solution(yaml=mech_txt)\n \n self.set_rate_expression_coeffs() # set copy of coeffs\n self.set_thermo_expression_coeffs() # set copy of thermo coeffs\n \n def gas(self): return self.gas \n \n def set_rate_expression_coeffs(self):\n coeffs = []\n coeffs_bnds = []\n rate_bnds = []\n for rxnNum, rxn in enumerate(self.gas.reactions()):\n if hasattr(rxn, 'rate'):\n attrs = [p for p in dir(rxn.rate) if not p.startswith('_')] # attributes not including __ \n coeffs.append({attr: getattr(rxn.rate, attr) for attr in attrs})\n coeffs_bnds.append({attr: {'resetVal': getattr(rxn.rate, attr), \n 'value': np.nan, 'type': 'F'} for attr in attrs})\n for coef_name in coeffs_bnds[-1].keys():\n coeffs_bnds[-1][coef_name]['limits'] = Uncertainty('coef', rxnNum, \n coef_name=coef_name, coeffs_bnds=coeffs_bnds)\n \n rate_bnds.append({'value': np.nan, 'limits': None, 'type': 'F', 'opt': False})\n rate_bnds[-1]['limits'] = Uncertainty('rate', rxnNum, rate_bnds=rate_bnds)\n else:\n coeffs.append({})\n coeffs_bnds.append({})\n rate_bnds.append({})\n\n self.coeffs = coeffs\n self.coeffs_bnds = coeffs_bnds\n self.rate_bnds = rate_bnds\n \n def set_thermo_expression_coeffs(self): # TODO Doesn't work with NASA 9\n self.thermo_coeffs = []\n for i in range(self.gas.n_species):\n S = self.gas.species(i)\n thermo_dict = {'name': S.name}\n thermo_dict['h_scaler'] = 1\n thermo_dict['s_scaler'] = 1\n try:\n thermo_dict['type'] = type(S.thermo)\n thermo_dict['coeffs'] = np.array(S.thermo.coeffs)\n except:\n thermo_dict['type'] = 'unknown'\n thermo_dict['coeffs'] = []\n \n self.thermo_coeffs.append(thermo_dict) \n \n def modify_reactions(self, coeffs, rxnNums=[]): # Only works for Arrhenius equations currently\n if not rxnNums: # if rxnNums does not exist, modify all\n rxnNums = range(len(coeffs))\n else:\n if isinstance(rxnNums, (float, int)): # if single reaction given, run that one\n rxnNums = [rxnNums]\n \n for rxnNum in rxnNums:\n rxn = self.gas.reaction(rxnNum)\n rxnChanged = False\n if type(rxn) is ct.ElementaryReaction or type(rxn) is ct.ThreeBodyReaction:\n for coefName in ['activation_energy', 'pre_exponential_factor', 'temperature_exponent']:\n if coeffs[rxnNum][coefName] != eval(f'rxn.rate.{coefName}'):\n rxnChanged = True\n \n if rxnChanged: # Update reaction rate\n A = coeffs[rxnNum]['pre_exponential_factor']\n b = coeffs[rxnNum]['temperature_exponent']\n Ea = coeffs[rxnNum]['activation_energy']\n rxn.rate = ct.Arrhenius(A, b, Ea)\n # elif type(rxn) is ct.PlogReaction:\n # print(dir(rxn))\n # print(rxn.rates[rxn_num])\n # elif type(rxn) is ct.ChebyshevReaction: \n # print(dir(rxn))\n # print(rxn.rates[rxn_num])\n else:\n continue\n \n if rxnChanged:\n self.gas.modify_reaction(rxnNum, rxn)\n\n time.sleep(5E-3) # Not sure if this is necessary, but it reduces strange behavior in incident shock reactor\n \n def modify_thermo(self, multipliers): # Only works for NasaPoly2 (NASA 7) currently\n for i in range(np.shape(self.gas.species_names)[0]):\n S_initial = self.gas.species(i)\n S = self.gas.species(i)\n if type(S.thermo) is ct.NasaPoly2:\n # Get current values \n T_low = S_initial.thermo.min_temp\n T_high = S_initial.thermo.max_temp\n P_ref = S_initial.thermo.reference_pressure\n coeffs = S_initial.thermo.coeffs\n \n # Update thermo properties\n coeffs[1:] *= multipliers[i]\n S.thermo = ct.NasaPoly2(T_low, T_high, P_ref, coeffs)\n # elif type(S.thermo) is ct.ShomatePoly2: continue\n # elif type(S.thermo) is ct.NasaPoly1: continue\n # elif type(S.thermo) is ct.Nasa9PolyMultiTempRegion: continue\n # elif type(S.thermo) is ct.Nasa9Poly1: continue\n # elif type(S.thermo) is ct.ShomatePoly: continue\n else:\n print(\"{:.s}'s thermo is type: {:s}\".format(self.gas.species_names[i], type(S.thermo)))\n continue\n\n self.gas.modify_species(i, S)\n \n def set_TPX(self, T, P, X=[]):\n output = {'success': False, 'message': []}\n if T <= 0 or np.isnan(T):\n output['message'].append('Error: Temperature is invalid')\n return output\n if P <= 0 or np.isnan(P):\n output['message'].append('Error: Pressure is invalid')\n return output\n if len(X) > 0:\n for species in X:\n if species not in self.gas.species_names:\n output['message'].append('Species: {:s} is not in the mechanism'.format(species))\n return output\n \n self.gas.TPX = T, P, X\n else:\n self.gas.TP = T, P\n \n output['success'] = True\n return output\n\n def run(self, reactor_choice, t_end, T_reac, P_reac, mix, **kwargs):\n return self.reactor.run(reactor_choice, t_end, T_reac, P_reac, mix, **kwargs)\n\n\nclass Uncertainty: # alternate name: why I hate pickle part 10\n def __init__(self, unc_type, rxnNum, **kwargs):\n # self.gas = gas\n self.unc_type = unc_type\n self.rxnNum = rxnNum\n self.unc_dict = kwargs\n \n def unc_fcn(self, x, uncVal, uncType): # uncertainty function\n if np.isnan(uncVal):\n return [np.nan, np.nan]\n elif uncType == 'F':\n return np.sort([x/uncVal, x*uncVal])\n elif uncType == '%':\n return np.sort([x/(1+uncVal), x*(1+uncVal)])\n elif uncType == '±':\n return np.sort([x-uncVal, x+uncVal])\n elif uncType == '+':\n return np.sort([x, x+uncVal])\n elif uncType == '-':\n return np.sort([x-uncVal, x])\n\n def __call__(self, x=None):\n if self.unc_type == 'rate':\n #if x is None: # defaults to giving current rate bounds\n # x = self.gas.forward_rate_constants[self.rxnNum]\n rate_bnds = self.unc_dict['rate_bnds']\n unc_value = rate_bnds[self.rxnNum]['value']\n unc_type = rate_bnds[self.rxnNum]['type']\n return self.unc_fcn(x, unc_value, unc_type)\n else:\n coeffs_bnds = self.unc_dict['coeffs_bnds']\n coefName = self.unc_dict['coef_name']\n coef_dict = coeffs_bnds[self.rxnNum][coefName]\n coef_val = coef_dict['resetVal']\n unc_value = coef_dict['value']\n unc_type = coef_dict['type']\n return self.unc_fcn(coef_val, unc_value, unc_type)\n \n\nclass Reactor:\n def __init__(self, mech):\n self.mech = mech\n self.ODE_success = False\n\n def run(self, reactor_choice, t_end, T_reac, P_reac, mix, **kwargs):\n def list2ct_mixture(mix): # list in the form of [[species, mol_frac], [species, mol_frac],...]\n return ', '.join(\"{!s}:{!r}\".format(species, mol_frac) for (species, mol_frac) in mix)\n \n details = {'success': False, 'message': []}\n \n if isinstance(mix, list):\n mix = list2ct_mixture(mix)\n \n mech_out = self.mech.set_TPX(T_reac, P_reac, mix)\n if not mech_out['success']:\n details['success'] = False\n details['message'] = mech_out['message']\n return None, mech_out\n \n #start = timer()\n if reactor_choice == 'Incident Shock Reactor':\n SIM, details = self.incident_shock_reactor(self.mech.gas, details, t_end, **kwargs)\n elif '0d Reactor' in reactor_choice:\n if reactor_choice == '0d Reactor - Constant Volume':\n reactor = ct.IdealGasReactor(self.mech.gas)\n elif reactor_choice == '0d Reactor - Constant Pressure':\n reactor = ct.IdealGasConstPressureReactor(self.mech.gas)\n \n SIM, details = self.zero_d_ideal_gas_reactor(self.mech.gas, reactor, details, t_end, **kwargs)\n \n #print('{:0.1f} us'.format((timer() - start)*1E3))\n return SIM, details\n \n def checkRxnRates(self, gas):\n limit = [1E9, 1E15, 1E21] # reaction limit [first order, second order, third order]\n checkRxn = []\n for rxnIdx in range(gas.n_reactions):\n coef_sum = int(sum(gas.reaction(rxnIdx).reactants.values()))\n if type(gas.reactions()[rxnIdx]) is ct.ThreeBodyReaction:\n coef_sum += 1\n if coef_sum > 0 and coef_sum-1 <= len(limit): # check that the limit is specified\n rate = [gas.forward_rate_constants[rxnIdx], gas.reverse_rate_constants[rxnIdx]]\n if (np.array(rate) > limit[coef_sum-1]).any(): # if forward or reverse rate exceeds limit\n checkRxn.append(rxnIdx+1)\n \n return checkRxn\n\n def incident_shock_reactor(self, gas, details, t_end, **kwargs):\n if 'u_reac' not in kwargs or 'rho1' not in kwargs:\n details['success'] = False\n details['message'] = 'velocity and rho1 not specified\\n'\n return None, details\n \n # set default values\n var = {'sim_int_f': 1, 'observable': {'main': 'Density Gradient', 'sub': 0},\n 'A1': 0.2, 'As': 0.2, 'L': 0.1, 't_lab_save': None, \n 'ODE_solver': 'BDF', 'rtol': 1E-4, 'atol': 1E-7} \n var.update(kwargs)\n \n y0 = np.hstack((0.0, var['A1'], gas.density, var['u_reac'], gas.T, 0.0, gas.Y)) # Initial condition\n ode = shock_fcns.ReactorOde(gas, t_end, var['rho1'], var['L'], var['As'], var['A1'], False)\n\n sol = integrate.solve_ivp(ode, [0, t_end], y0, method=var['ODE_solver'],\n dense_output=True, rtol=var['rtol'], atol=var['atol'])\n \n if sol.success:\n self.ODE_success = True # this is passed to SIM to inform saving output function\n details['success'] = True\n else:\n self.ODE_success = False # this is passed to SIM to inform saving output function\n details['success'] = False\n \n # Generate log output\n explanation = '\\nCheck for: Fast rates or bad thermo data'\n checkRxns = self.checkRxnRates(gas)\n if len(checkRxns) > 0:\n explanation += '\\nSuggested Reactions: ' + ', '.join([str(x) for x in checkRxns])\n details['message'] = '\\nODE Error: {:s}\\n{:s}\\n'.format(sol.message, explanation)\n \n if var['sim_int_f'] > np.shape(sol.t)[0]: # in case of integration failure\n var['sim_int_f'] = np.shape(sol.t)[0]\n \n if var['sim_int_f'] == 1:\n t_sim = sol.t\n else: # perform interpolation if integrator sample factor > 1\n j = 0\n t_sim = np.zeros(var['sim_int_f']*(np.shape(sol.t)[0] - 1) + 1) # preallocate array\n for i in range(np.shape(sol.t)[0]-1):\n t_interp = np.interp(np.linspace(i, i+1, var['sim_int_f']+1), [i, i+1], sol.t[i:i+2])\n t_sim[j:j+len(t_interp)] = t_interp\n j += len(t_interp) - 1\n \n ind_var = 't_lab' # INDEPENDENT VARIABLE CURRENTLY HARDCODED FOR t_lab\n if var['t_lab_save'] is None: # if t_save is not being sent, only plotting variables are needed\n t_all = t_sim\n else:\n t_all = np.sort(np.unique(np.concatenate((t_sim, var['t_lab_save'])))) # combine t_all and t_save, sort, only unique values\n \n states = ct.SolutionArray(gas, extra=['t', 't_shock', 'z', 'A', 'vel', 'drhodz_tot', 'drhodz', 'perc_drhodz'])\n for i, t in enumerate(t_all): # calculate from solution\n y = sol.sol(t) \n z, A, rho, v, T, t_shock = y[0:6]\n Y = y[6:]\n\n states.append(TDY=(T, rho, Y), t=t, t_shock=t_shock, z=z, A=A, vel=v, drhodz_tot=np.nan, drhodz=np.nan, perc_drhodz=np.nan)\n \n reactor_vars = ['t_lab', 't_shock', 'z', 'A', 'vel', 'T', 'P', 'h_tot', 'h', \n 's_tot', 's', 'rho', 'drhodz_tot', 'drhodz', 'perc_drhodz',\n 'Y', 'X', 'conc', 'wdot', 'wdotfor', 'wdotrev', \n 'HRR_tot', 'HRR', 'delta_h', 'delta_s', \n 'eq_con', 'rate_con', 'rate_con_rev', 'net_ROP', 'for_ROP', 'rev_ROP']\n\n num = {'reac': np.sum(gas.reactant_stoich_coeffs(), axis=0),\n 'prod': np.sum(gas.product_stoich_coeffs(), axis=0),\n 'rxns': gas.n_reactions}\n \n SIM = Simulation_Result(num, states, reactor_vars)\n SIM.finalize(self.ODE_success, ind_var, var['observable'], units='CGS')\n \n return SIM, details\n \n def zero_d_ideal_gas_reactor(self, gas, reactor, details, t_end, **kwargs):\n # set default values\n var = {'sim_int_f': 1, 'observable': {'main': 'Concentration', 'sub': 0},\n 't_lab_save': None, 'rtol': 1E-4, 'atol': 1E-7}\n \n var.update(kwargs)\n \n # Modify reactor if necessary for frozen composition and isothermal\n reactor.energy_enabled = var['solve_energy']\n reactor.chemistry_enabled = not var['frozen_comp']\n \n # Create Sim\n sim = ct.ReactorNet([reactor])\n sim.atol = var['atol']\n sim.rtol = var['rtol']\n \n # set up times and observables\n ind_var = 't_lab' # INDEPENDENT VARIABLE CURRENTLY HARDCODED FOR t_lab\n if var['t_lab_save'] is None:\n t_all = [t_end]\n else:\n t_all = np.sort(np.unique(np.concatenate(([t_end], var['t_lab_save'])))) # combine t_end and t_save, sort, only unique values\n \n states = ct.SolutionArray(gas, extra=['t'])\n states.append(reactor.thermo.state, t = 0.0)\n for t in t_all:\n while sim.time < t: # integrator step until time > target time\n sim.step()\n if sim.time > t: # force interpolation to target time\n sim.advance(t)\n states.append(reactor.thermo.state, t=sim.time)\n \n self.ODE_success = True # TODO: NEED REAL ERROR CHECKING OF REACTOR SUCCESS\n details['success'] = True\n \n reactor_vars = ['t_lab', 'T', 'P', 'h_tot', 'h', 's_tot', 's', 'rho', \n 'Y', 'X', 'conc', 'wdot', 'wdotfor', 'wdotrev', 'HRR_tot', 'HRR',\n 'delta_h', 'delta_s', 'eq_con', 'rate_con', 'rate_con_rev', \n 'net_ROP', 'for_ROP', 'rev_ROP']\n\n num = {'reac': np.sum(gas.reactant_stoich_coeffs(), axis=0),\n 'prod': np.sum(gas.product_stoich_coeffs(), axis=0),\n 'rxns': gas.n_reactions}\n \n SIM = Simulation_Result(num, states, reactor_vars)\n SIM.finalize(self.ODE_success, ind_var, var['observable'], units='CGS')\n\n return SIM, details"
] | [
[
"numpy.sort",
"numpy.hstack",
"numpy.power",
"numpy.shape",
"numpy.isnan",
"numpy.array",
"numpy.concatenate",
"numpy.linspace"
]
] |
Jos33y/student-performance-knn | [
"4e965434f52dd6a1380904aa257df1edfaebb3c4"
] | [
"venv/Lib/site-packages/sklearn/tree/tests/test_reingold_tilford.py"
] | [
"import numpy as np\r\nimport pytest\r\nfrom sklearn.tree._reingold_tilford import buchheim, Tree\r\n\r\nsimple_tree = Tree(\"\", 0,\r\n Tree(\"\", 1),\r\n Tree(\"\", 2))\r\n\r\nbigger_tree = Tree(\"\", 0,\r\n Tree(\"\", 1,\r\n Tree(\"\", 3),\r\n Tree(\"\", 4,\r\n Tree(\"\", 7),\r\n Tree(\"\", 8)\r\n ),\r\n ),\r\n Tree(\"\", 2,\r\n Tree(\"\", 5),\r\n Tree(\"\", 6)\r\n )\r\n )\r\n\r\n\r\[email protected](\"tree, n_nodes\", [(simple_tree, 3), (bigger_tree, 9)])\r\ndef test_buchheim(tree, n_nodes):\r\n def walk_tree(draw_tree):\r\n res = [(draw_tree.x, draw_tree.y)]\r\n for child in draw_tree.children:\r\n # parents higher than children:\r\n assert child.y == draw_tree.y + 1\r\n res.extend(walk_tree(child))\r\n if len(draw_tree.children):\r\n # these trees are always binary\r\n # parents are centered above children\r\n assert draw_tree.x == (draw_tree.children[0].x\r\n + draw_tree.children[1].x) / 2\r\n return res\r\n\r\n layout = buchheim(tree)\r\n coordinates = walk_tree(layout)\r\n assert len(coordinates) == n_nodes\r\n # test that x values are unique per depth / level\r\n # we could also do it quicker using defaultdicts..\r\n depth = 0\r\n while True:\r\n x_at_this_depth = [coordinates[0] for node in coordinates\r\n if coordinates[1] == depth]\r\n if not x_at_this_depth:\r\n # reached all leafs\r\n break\r\n assert len(np.unique(x_at_this_depth)) == len(x_at_this_depth)\r\n depth += 1\r\n"
] | [
[
"sklearn.tree._reingold_tilford.Tree",
"sklearn.tree._reingold_tilford.buchheim",
"numpy.unique"
]
] |
samueljamesbell/scikit-optimize | [
"c53998816481d150ccc745ffd07d022fdb1fd25d"
] | [
"examples/utils.py"
] | [
"# Module to import functions from in examples for multiprocessing backend\nimport numpy as np\n\n\ndef obj_fun(x, noise_level=0.1):\n return np.sin(5 * x[0]) * (1 - np.tanh(x[0] ** 2)) +\\\n np.random.randn() * noise_level\n"
] | [
[
"numpy.sin",
"numpy.random.randn",
"numpy.tanh"
]
] |
smiledinisa/SimpleCVReproduction | [
"c6ac180887472a920d86b6eb15f933294b65dcec"
] | [
"RL/actor_critic.py"
] | [
"import argparse\nimport gym\nimport numpy as np\nfrom itertools import count\nfrom collections import namedtuple\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.distributions import Categorical\n\n# Cart Pole\n\nparser = argparse.ArgumentParser(description='PyTorch actor-critic example')\nparser.add_argument('--gamma', type=float, default=0.99, metavar='G',\n help='discount factor (default: 0.99)')\nparser.add_argument('--seed', type=int, default=543, metavar='N',\n help='random seed (default: 543)')\nparser.add_argument('--render', action='store_true',\n help='render the environment')\nparser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='interval between training status logs (default: 10)')\nargs = parser.parse_args()\n\n\nenv = gym.make('CartPole-v0')\nenv.seed(args.seed)\ntorch.manual_seed(args.seed)\n\n\nSavedAction = namedtuple('SavedAction', ['log_prob', 'value'])\n\n\nclass Policy(nn.Module):\n \"\"\"\n implements both actor and critic in one model\n \"\"\"\n def __init__(self):\n super(Policy, self).__init__()\n self.affine1 = nn.Linear(4, 128)\n\n # actor's layer\n self.action_head = nn.Linear(128, 2)\n\n # critic's layer\n self.value_head = nn.Linear(128, 1)\n\n # action & reward buffer\n self.saved_actions = []\n self.rewards = []\n\n def forward(self, x):\n \"\"\"\n forward of both actor and critic\n \"\"\"\n x = F.relu(self.affine1(x))\n\n # actor: choses action to take from state s_t \n # by returning probability of each action\n action_prob = F.softmax(self.action_head(x), dim=-1)\n\n # critic: evaluates being in the state s_t\n state_values = self.value_head(x)\n\n # return values for both actor and critic as a tuple of 2 values:\n # 1. a list with the probability of each action over the action space\n # 2. the value from state s_t \n return action_prob, state_values\n\n\nmodel = Policy()\noptimizer = optim.Adam(model.parameters(), lr=3e-2)\neps = np.finfo(np.float32).eps.item()\n\n\ndef select_action(state):\n state = torch.from_numpy(state).float()\n probs, state_value = model(state)\n\n # create a categorical distribution over the list of probabilities of actions\n m = Categorical(probs)\n\n # and sample an action using the distribution\n action = m.sample()\n\n # save to action buffer\n model.saved_actions.append(SavedAction(m.log_prob(action), state_value))\n\n # the action to take (left or right)\n return action.item()\n\n\ndef finish_episode():\n \"\"\"\n Training code. Calculates actor and critic loss and performs backprop.\n \"\"\"\n R = 0\n saved_actions = model.saved_actions\n policy_losses = [] # list to save actor (policy) loss\n value_losses = [] # list to save critic (value) loss\n returns = [] # list to save the true values\n\n # calculate the true value using rewards returned from the environment\n for r in model.rewards[::-1]:\n # calculate the discounted value\n R = r + args.gamma * R\n returns.insert(0, R)\n\n returns = torch.tensor(returns)\n returns = (returns - returns.mean()) / (returns.std() + eps)\n\n for (log_prob, value), R in zip(saved_actions, returns):\n advantage = R - value.item()\n\n # calculate actor (policy) loss \n policy_losses.append(-log_prob * advantage)\n\n # calculate critic (value) loss using L1 smooth loss\n value_losses.append(F.smooth_l1_loss(value, torch.tensor([R])))\n\n # reset gradients\n optimizer.zero_grad()\n\n # sum up all the values of policy_losses and value_losses\n loss = torch.stack(policy_losses).sum() + torch.stack(value_losses).sum()\n\n # perform backprop\n loss.backward()\n optimizer.step()\n\n # reset rewards and action buffer\n del model.rewards[:]\n del model.saved_actions[:]\n\n\ndef main():\n running_reward = 10\n\n # run inifinitely many episodes\n for i_episode in count(1):\n\n # reset environment and episode reward\n state = env.reset()\n ep_reward = 0\n\n # for each episode, only run 9999 steps so that we don't \n # infinite loop while learning\n for t in range(1, 20000):\n\n # select action from policy\n action = select_action(state)\n\n # take the action\n state, reward, done, _ = env.step(action)\n\n if args.render:\n env.render()\n\n model.rewards.append(reward)\n ep_reward += reward\n if done:\n break\n\n # update cumulative reward\n running_reward = 0.05 * ep_reward + (1 - 0.05) * running_reward\n\n # perform backprop\n finish_episode()\n\n # log results\n if i_episode % args.log_interval == 0:\n print('Episode {}\\tLast reward: {:.2f}\\tAverage reward: {:.2f}'.format(\n i_episode, ep_reward, running_reward))\n\n # check if we have \"solved\" the cart pole problem\n if running_reward > env.spec.reward_threshold:\n print(\"Solved! Running reward is now {} and \"\n \"the last episode runs to {} time steps!\".format(running_reward, t))\n break\n\n\nif __name__ == '__main__':\n main()"
] | [
[
"torch.stack",
"torch.nn.Linear",
"torch.distributions.Categorical",
"torch.manual_seed",
"torch.tensor",
"torch.from_numpy",
"numpy.finfo"
]
] |
mjchi7/CS234 | [
"c476714aafcd880c4d7707799d9556dfb2de24a6"
] | [
"assignment2/core/deep_q_learning.py"
] | [
"import os\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport time\r\n\r\nfrom q_learning import QN\r\n\r\n\r\nclass DQN(QN):\r\n \"\"\"\r\n Abstract class for Deep Q Learning\r\n \"\"\"\r\n def add_placeholders_op(self):\r\n raise NotImplementedError\r\n\r\n\r\n def get_q_values_op(self, scope, reuse=False):\r\n \"\"\"\r\n set Q values, of shape = (batch_size, num_actions)\r\n \"\"\"\r\n raise NotImplementedError\r\n\r\n\r\n def add_update_target_op(self, q_scope, target_q_scope):\r\n \"\"\"\r\n Update_target_op will be called periodically \r\n to copy Q network to target Q network\r\n \r\n Args:\r\n q_scope: name of the scope of variables for q\r\n target_q_scope: name of the scope of variables for the target\r\n network\r\n \"\"\"\r\n raise NotImplementedError\r\n\r\n\r\n def add_loss_op(self, q, target_q):\r\n \"\"\"\r\n Set (Q_target - Q)^2\r\n \"\"\"\r\n raise NotImplementedError\r\n\r\n\r\n def add_optimizer_op(self, scope):\r\n \"\"\"\r\n Set training op wrt to loss for variable in scope\r\n \"\"\"\r\n raise NotImplementedError\r\n\r\n\r\n def process_state(self, state):\r\n \"\"\"\r\n Processing of state\r\n\r\n State placeholders are tf.uint8 for fast transfer to GPU\r\n Need to cast it to float32 for the rest of the tf graph.\r\n\r\n Args:\r\n state: node of tf graph of shape = (batch_size, height, width, nchannels)\r\n of type tf.uint8.\r\n if , values are between 0 and 255 -> 0 and 1\r\n \"\"\"\r\n state = tf.cast(state, tf.float32)\r\n state /= self.config.high\r\n\r\n return state\r\n\r\n\r\n def build(self):\r\n \"\"\"\r\n Build model by adding all necessary variables\r\n \"\"\"\r\n # add placeholders\r\n self.add_placeholders_op()\r\n\r\n # compute Q values of state\r\n s = self.process_state(self.s)\r\n self.q = self.get_q_values_op(s, scope=\"q\", reuse=False)\r\n\r\n # compute Q values of next state\r\n sp = self.process_state(self.sp)\r\n self.target_q = self.get_q_values_op(sp, scope=\"target_q\", reuse=False)\r\n\r\n # add update operator for target network\r\n self.add_update_target_op(\"q\", \"target_q\")\r\n\r\n # add square loss\r\n self.add_loss_op(self.q, self.target_q)\r\n\r\n # add optmizer for the main networks\r\n self.add_optimizer_op(\"q\")\r\n\r\n\r\n def initialize(self):\r\n \"\"\"\r\n Assumes the graph has been constructed\r\n Creates a tf Session and run initializer of variables\r\n \"\"\"\r\n # create tf session\r\n self.sess = tf.Session()\r\n\r\n # tensorboard stuff\r\n self.add_summary()\r\n\r\n # initiliaze all variables\r\n init = tf.global_variables_initializer()\r\n self.sess.run(init)\r\n\r\n # synchronise q and target_q networks\r\n self.sess.run(self.update_target_op)\r\n\r\n # for saving networks weights\r\n self.saver = tf.train.Saver()\r\n\r\n \r\n def add_summary(self):\r\n \"\"\"\r\n Tensorboard stuff\r\n \"\"\"\r\n # extra placeholders to log stuff from python\r\n self.avg_reward_placeholder = tf.placeholder(tf.float32, shape=(), name=\"avg_reward\")\r\n self.max_reward_placeholder = tf.placeholder(tf.float32, shape=(), name=\"max_reward\")\r\n self.std_reward_placeholder = tf.placeholder(tf.float32, shape=(), name=\"std_reward\")\r\n\r\n self.avg_q_placeholder = tf.placeholder(tf.float32, shape=(), name=\"avg_q\")\r\n self.max_q_placeholder = tf.placeholder(tf.float32, shape=(), name=\"max_q\")\r\n self.std_q_placeholder = tf.placeholder(tf.float32, shape=(), name=\"std_q\")\r\n\r\n self.eval_reward_placeholder = tf.placeholder(tf.float32, shape=(), name=\"eval_reward\")\r\n\r\n # add placeholders from the graph\r\n tf.summary.scalar(\"loss\", self.loss)\r\n tf.summary.scalar(\"grads norm\", self.grad_norm)\r\n\r\n # extra summaries from python -> placeholders\r\n tf.summary.scalar(\"Avg Reward\", self.avg_reward_placeholder)\r\n tf.summary.scalar(\"Max Reward\", self.max_reward_placeholder)\r\n tf.summary.scalar(\"Std Reward\", self.std_reward_placeholder)\r\n\r\n tf.summary.scalar(\"Avg Q\", self.avg_q_placeholder)\r\n tf.summary.scalar(\"Max Q\", self.max_q_placeholder)\r\n tf.summary.scalar(\"Std Q\", self.std_q_placeholder)\r\n\r\n tf.summary.scalar(\"Eval Reward\", self.eval_reward_placeholder)\r\n \r\n # logging\r\n self.merged = tf.summary.merge_all()\r\n self.file_writer = tf.summary.FileWriter(self.config.output_path, \r\n self.sess.graph)\r\n\r\n\r\n\r\n def save(self):\r\n \"\"\"\r\n Saves session\r\n \"\"\"\r\n if not os.path.exists(self.config.model_output):\r\n os.makedirs(self.config.model_output)\r\n\r\n self.saver.save(self.sess, self.config.model_output)\r\n\r\n\r\n def get_best_action(self, state):\r\n \"\"\"\r\n Return best action\r\n\r\n Args:\r\n state: 4 consecutive observations from gym\r\n Returns:\r\n action: (int)\r\n action_values: (np array) q values for all actions\r\n \"\"\"\r\n action_values = self.sess.run(self.q, feed_dict={self.s: [state]})[0]\r\n return np.argmax(action_values), action_values\r\n\r\n\r\n def update_step(self, t, replay_buffer, lr):\r\n \"\"\"\r\n Performs an update of parameters by sampling from replay_buffer\r\n\r\n Args:\r\n t: number of iteration (episode and move)\r\n replay_buffer: ReplayBuffer instance .sample() gives batches\r\n lr: (float) learning rate\r\n Returns:\r\n loss: (Q - Q_target)^2\r\n \"\"\"\r\n\r\n s_batch, a_batch, r_batch, sp_batch, done_mask_batch = replay_buffer.sample(\r\n self.config.batch_size)\r\n\r\n\r\n fd = {\r\n # inputs\r\n self.s: s_batch,\r\n self.a: a_batch,\r\n self.r: r_batch,\r\n self.sp: sp_batch, \r\n self.done_mask: done_mask_batch,\r\n self.lr: lr, \r\n # extra info\r\n self.avg_reward_placeholder: self.avg_reward, \r\n self.max_reward_placeholder: self.max_reward, \r\n self.std_reward_placeholder: self.std_reward, \r\n self.avg_q_placeholder: self.avg_q, \r\n self.max_q_placeholder: self.max_q, \r\n self.std_q_placeholder: self.std_q, \r\n self.eval_reward_placeholder: self.eval_reward, \r\n }\r\n\r\n loss_eval, grad_norm_eval, summary, _ = self.sess.run([self.loss, self.grad_norm, \r\n self.merged, self.train_op], feed_dict=fd)\r\n\r\n\r\n # tensorboard stuff\r\n self.file_writer.add_summary(summary, t)\r\n \r\n return loss_eval, grad_norm_eval\r\n\r\n\r\n def update_target_params(self):\r\n \"\"\"\r\n Update parametes of Q' with parameters of Q\r\n \"\"\"\r\n self.sess.run(self.update_target_op)\r\n\r\n"
] | [
[
"tensorflow.summary.scalar",
"tensorflow.placeholder",
"tensorflow.summary.merge_all",
"tensorflow.global_variables_initializer",
"numpy.argmax",
"tensorflow.cast",
"tensorflow.train.Saver",
"tensorflow.Session",
"tensorflow.summary.FileWriter"
]
] |
shkarupa-alex/segme | [
"d5bc0043f9e709c8ccaf8949d662bc6fd6144006"
] | [
"segme/model/f3_net/model.py"
] | [
"import tensorflow as tf\nfrom keras import models, layers\nfrom keras.utils.generic_utils import register_keras_serializable\nfrom keras.utils.tf_utils import shape_type_conversion\nfrom .decoder import Decoder\nfrom ...backbone import Backbone\nfrom ...common import ConvBnRelu, HeadActivation, HeadProjection, resize_by_sample\n\n\n@register_keras_serializable(package='SegMe>F3Net')\nclass F3Net(layers.Layer):\n def __init__(self, classes, bone_arch, bone_init, bone_train, filters, **kwargs):\n super().__init__(**kwargs)\n self.input_spec = layers.InputSpec(ndim=4, dtype='uint8')\n self.classes = classes\n self.bone_arch = bone_arch\n self.bone_init = bone_init\n self.bone_train = bone_train\n self.filters = filters\n\n @shape_type_conversion\n def build(self, input_shape):\n self.bone = Backbone(self.bone_arch, self.bone_init, self.bone_train, scales=[4, 8, 16, 32])\n\n self.squeeze2 = ConvBnRelu(self.filters, 1, kernel_initializer='he_normal')\n self.squeeze3 = ConvBnRelu(self.filters, 1, kernel_initializer='he_normal')\n self.squeeze4 = ConvBnRelu(self.filters, 1, kernel_initializer='he_normal')\n self.squeeze5 = ConvBnRelu(self.filters, 1, kernel_initializer='he_normal')\n\n self.decoder1 = Decoder(False, self.filters)\n self.decoder2 = Decoder(True, self.filters)\n\n self.proj_p1 = HeadProjection(self.classes, kernel_size=3, kernel_initializer='he_normal')\n self.proj_p2 = HeadProjection(self.classes, kernel_size=3, kernel_initializer='he_normal')\n self.proj_o2 = HeadProjection(self.classes, kernel_size=3, kernel_initializer='he_normal')\n self.proj_o3 = HeadProjection(self.classes, kernel_size=3, kernel_initializer='he_normal')\n self.proj_o4 = HeadProjection(self.classes, kernel_size=3, kernel_initializer='he_normal')\n self.proj_o5 = HeadProjection(self.classes, kernel_size=3, kernel_initializer='he_normal')\n\n self.act = HeadActivation(self.classes)\n\n super().build(input_shape)\n\n def call(self, inputs, **kwargs):\n out2h, out3h, out4h, out5v = self.bone(inputs)\n\n out2h = self.squeeze2(out2h)\n out3h = self.squeeze3(out3h)\n out4h = self.squeeze4(out4h)\n out5v = self.squeeze5(out5v)\n\n out2h, out3h, out4h, out5v, pred1 = self.decoder1([out2h, out3h, out4h, out5v])\n out2h, out3h, out4h, out5v, pred2 = self.decoder2([out2h, out3h, out4h, out5v, pred1])\n\n pred1 = self.proj_p1(pred1)\n pred2 = self.proj_p2(pred2)\n out2h = self.proj_o2(out2h)\n out3h = self.proj_o3(out3h)\n out4h = self.proj_o4(out4h)\n out5v = self.proj_o5(out5v)\n\n outputs = [pred2, pred1, out2h, out3h, out4h, out5v]\n outputs = [resize_by_sample([out, inputs]) for out in outputs]\n outputs = [self.act(out) for out in outputs]\n\n return outputs\n\n @shape_type_conversion\n def compute_output_shape(self, input_shape):\n output_shape = input_shape[:-1] + (self.classes,)\n\n return [output_shape] * 6\n\n def compute_output_signature(self, input_signature):\n outptut_signature = super().compute_output_signature(input_signature)\n\n return [tf.TensorSpec(dtype='float32', shape=os.shape) for os in outptut_signature]\n\n def get_config(self):\n config = super().get_config()\n config.update({\n 'classes': self.classes,\n 'bone_arch': self.bone_arch,\n 'bone_init': self.bone_init,\n 'bone_train': self.bone_train,\n 'filters': self.filters\n })\n\n return config\n\n\ndef build_f3_net(classes, bone_arch='resnet_50', bone_init='imagenet', bone_train=False, filters=64):\n inputs = layers.Input(name='image', shape=[None, None, 3], dtype='uint8')\n outputs = F3Net(\n classes, bone_arch=bone_arch, bone_init=bone_init, bone_train=bone_train, filters=filters)(inputs)\n model = models.Model(inputs=inputs, outputs=outputs, name='f3_net')\n\n return model\n"
] | [
[
"tensorflow.TensorSpec"
]
] |
syakoo/galois-field | [
"e642adfa7da55f6cd95cadceb0116cdea379c181"
] | [
"galois_field/core/gcd.py"
] | [
"from typing import Tuple\n\nimport numpy as np\n\nfrom . import modulus, inverse\n\n\ndef gcd_poly(poly1: np.poly1d, poly2: np.poly1d, p: int) -> np.poly1d:\n \"\"\"Seek the gcd of two polynomials over Fp.\n\n Args:\n poly1 (np.poly1d): A polynomial.\n poly2 (np.poly1d): A polynomial.\n p (int): A prime number.\n\n Returns:\n np.poly1d: gcd(poly1, poly2) over Fp.\n \"\"\"\n def poly2monic(poly: np.poly1d)\\\n -> Tuple[np.poly1d, Tuple[np.poly1d, np.poly1d]]:\n highest_degree_coeff = poly.coeffs[0]\n if highest_degree_coeff == 1:\n return poly, (np.poly1d([1]), np.poly1d([1]))\n\n inv_hdc = inverse.inverse_el(highest_degree_coeff, p)\n coeffs = poly.coeffs * inv_hdc\n return np.poly1d(modulus.modulus_coeffs(coeffs, p)),\\\n (np.poly1d([highest_degree_coeff]), np.poly1d([inv_hdc]))\n\n if len(poly1.coeffs) < len(poly2.coeffs):\n poly1, poly2 = poly2, poly1\n\n poly2_monic, hdc = poly2monic(poly2)\n _, r = np.polydiv(poly1 * hdc[1], poly2_monic)\n r = np.poly1d(modulus.modulus_coeffs(r.coeffs, p)) * hdc[0]\n r = modulus.modulus_poly_over_fp(r, p)\n\n if r.coeffs[0] == 0:\n return poly2\n\n return gcd_poly(poly2, r, p)\n"
] | [
[
"numpy.poly1d",
"numpy.polydiv"
]
] |
sghislandi/GSSI_Numerical_Methods_2020-2021 | [
"171853ff2d99560565783bdd2e0f3a9e0c4c5ca5"
] | [
"pyplots/simpson_integration/error_plotter.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport os.path\n\n#Reading the output\nflag = 0\nif os.path.exists('../../build/output/simpson_integration/simpson_approximation_errors_v1.txt'):\n flag = 1\n N, deviation = np.loadtxt('../../build/output/simpson_integration/simpson_approximation_errors_v1.txt', skiprows = 1, unpack = True)\nelif os.path.exists('output/simpson_integration/simpson_approximation_errors_v1.txt'):\n flag = 2\n N, deviation = np.loadtxt('output/simpson_integration/simpson_approximation_errors_v1.txt', skiprows = 1, unpack = True)\nelif os.path.exists('../../build/output/simpson_integration/simpson_approximation_errors.txt'):\n flag = 3\n N, deviation = np.loadtxt('../../build/output/simpson_integration/simpson_approximation_errors.txt', skiprows = 1, unpack = True)\nelif os.path.exists('output/simpson_integration/simpson_approximation_errors.txt'):\n flag = 4\n N, deviation = np.loadtxt('output/simpson_integration/simpson_approximation_errors.txt', skiprows = 1, unpack = True)\nelse:\n print(\"No output file found\")\n exit()\n\n#Fixed quantities\na = 0\nb = 2\nthird_derivative_a = 0\nthird_derivative_b = 48\n\n#Error computed as I_simpson - I_exact\nlog_deviation = np.log10(abs(deviation))\n\n#Error from theory\nlog_theoretical_error = np.log10(1/90*(third_derivative_b-third_derivative_a)*((b-a)/(2**N))**4)\n\n#Error computed trhough the difference between I(N) and I(2N)\nlog_approximated_error= [None] * (deviation.size-1)\nfor i in range(0,deviation.size-1):\n log_approximated_error[i] = np.log10(1/15*(abs(deviation[i+1]-deviation[i])))\n\n#Definition of useful quantities\nN = 2**N\nlogN = np.log10(N)\n\n#Plots\nfig = plt.figure(figsize=(4.5*np.sqrt(2),4.5))\nplt.plot(logN,log_deviation,'o',markersize=5, label = r'$\\left| \\widetilde{I} - I \\right|$')\nplt.plot(logN,log_theoretical_error,'o', markersize=5, color = 'red', label = 'Theoretical Error')\nplt.plot(logN[1:],log_approximated_error,'o', markersize=5, label = 'Numerical error' )\nplt.title(\"Error analysis for Simpson integration method\", fontsize = 14)\nplt.xlabel('Log(N)' , fontsize = 12)\nplt.ylabel('Log(value)', fontsize = 12)\nplt.legend( fontsize = 12)\n\nfit_deviation = np.polyfit(logN[0:10], log_deviation[0:10], 1)\nfit_theoretical_error = np.polyfit(logN[0:10], log_theoretical_error[0:10], 1)\nfit_approximated_error = np.polyfit(logN[0:10], log_approximated_error[0:10], 1)\n\nprint('**********************')\nprint('PYTHON SCRIPT RESULTS:')\nprint(f'Deviation slope = {fit_deviation[0]}')\nprint(f'Theoretical slope = {fit_theoretical_error[0]}')\nprint(f'Approximated slope = {fit_approximated_error[0]}')\nprint('**********************')\n\nif(flag == 1 or flag == 3):\n plt.savefig('simpson_approximation_errors.pdf')\nelse:\n plt.savefig('../pyplots/simpson_integration/simpson_approximation_errors.pdf')\n\nprint(\"\\nOutput saved in pyplots/simpson_approximation_errors.pdf\")\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.title",
"numpy.log10",
"matplotlib.pyplot.ylabel",
"numpy.polyfit",
"numpy.sqrt",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"numpy.loadtxt"
]
] |
woonzh/semantics | [
"8689acb5af7be689318486aea10da812aa383bb4"
] | [
"modeling.py"
] | [
"# coding=utf-8\r\n# Copyright 2018 The Google AI Language Team Authors.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"The main BERT model and related functions.\"\"\"\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport collections\r\nimport copy\r\nimport json\r\nimport math\r\nimport re\r\nimport six\r\nimport tensorflow as tf\r\n\r\n\r\nclass BertConfig(object):\r\n \"\"\"Configuration for `BertModel`.\"\"\"\r\n\r\n def __init__(self,\r\n vocab_size,\r\n hidden_size=768,\r\n num_hidden_layers=12,\r\n num_attention_heads=12,\r\n intermediate_size=3072,\r\n hidden_act=\"gelu\",\r\n hidden_dropout_prob=0.1,\r\n attention_probs_dropout_prob=0.1,\r\n max_position_embeddings=512,\r\n type_vocab_size=16,\r\n initializer_range=0.02):\r\n \"\"\"Constructs BertConfig.\r\n\r\n Args:\r\n vocab_size: Vocabulary size of `inputs_ids` in `BertModel`.\r\n hidden_size: Size of the encoder layers and the pooler layer.\r\n num_hidden_layers: Number of hidden layers in the Transformer encoder.\r\n num_attention_heads: Number of attention heads for each attention layer in\r\n the Transformer encoder.\r\n intermediate_size: The size of the \"intermediate\" (i.e., feed-forward)\r\n layer in the Transformer encoder.\r\n hidden_act: The non-linear activation function (function or string) in the\r\n encoder and pooler.\r\n hidden_dropout_prob: The dropout probability for all fully connected\r\n layers in the embeddings, encoder, and pooler.\r\n attention_probs_dropout_prob: The dropout ratio for the attention\r\n probabilities.\r\n max_position_embeddings: The maximum sequence length that this model might\r\n ever be used with. Typically set this to something large just in case\r\n (e.g., 512 or 1024 or 2048).\r\n type_vocab_size: The vocabulary size of the `token_type_ids` passed into\r\n `BertModel`.\r\n initializer_range: The stdev of the truncated_normal_initializer for\r\n initializing all weight matrices.\r\n \"\"\"\r\n self.vocab_size = vocab_size\r\n self.hidden_size = hidden_size\r\n self.num_hidden_layers = num_hidden_layers\r\n self.num_attention_heads = num_attention_heads\r\n self.hidden_act = hidden_act\r\n self.intermediate_size = intermediate_size\r\n self.hidden_dropout_prob = hidden_dropout_prob\r\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\r\n self.max_position_embeddings = max_position_embeddings\r\n self.type_vocab_size = type_vocab_size\r\n self.initializer_range = initializer_range\r\n\r\n @classmethod\r\n def from_dict(cls, json_object):\r\n \"\"\"Constructs a `BertConfig` from a Python dictionary of parameters.\"\"\"\r\n config = BertConfig(vocab_size=None)\r\n for (key, value) in six.iteritems(json_object):\r\n config.__dict__[key] = value\r\n return config\r\n\r\n @classmethod\r\n def from_json_file(cls, json_file):\r\n \"\"\"Constructs a `BertConfig` from a json file of parameters.\"\"\"\r\n with tf.gfile.GFile(json_file, \"r\") as reader:\r\n text = reader.read()\r\n return cls.from_dict(json.loads(text))\r\n\r\n def to_dict(self):\r\n \"\"\"Serializes this instance to a Python dictionary.\"\"\"\r\n output = copy.deepcopy(self.__dict__)\r\n return output\r\n\r\n def to_json_string(self):\r\n \"\"\"Serializes this instance to a JSON string.\"\"\"\r\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\r\n\r\n\r\nclass BertModel(object):\r\n \"\"\"BERT model (\"Bidirectional Encoder Representations from Transformers\").\r\n\r\n Example usage:\r\n\r\n ```python\r\n # Already been converted into WordPiece token ids\r\n input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])\r\n input_mask = tf.constant([[1, 1, 1], [1, 1, 0]])\r\n token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]])\r\n\r\n config = modeling.BertConfig(vocab_size=32000, hidden_size=512,\r\n num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)\r\n\r\n model = modeling.BertModel(config=config, is_training=True,\r\n input_ids=input_ids, input_mask=input_mask, token_type_ids=token_type_ids)\r\n\r\n label_embeddings = tf.get_variable(...)\r\n pooled_output = model.get_pooled_output()\r\n logits = tf.matmul(pooled_output, label_embeddings)\r\n ...\r\n ```\r\n \"\"\"\r\n\r\n def __init__(self,\r\n config,\r\n is_training,\r\n input_ids,\r\n input_mask=None,\r\n token_type_ids=None,\r\n use_one_hot_embeddings=True,\r\n scope=None):\r\n \"\"\"Constructor for BertModel.\r\n\r\n Args:\r\n config: `BertConfig` instance.\r\n is_training: bool. true for training model, false for eval model. Controls\r\n whether dropout will be applied.\r\n input_ids: int32 Tensor of shape [batch_size, seq_length].\r\n input_mask: (optional) int32 Tensor of shape [batch_size, seq_length].\r\n token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].\r\n use_one_hot_embeddings: (optional) bool. Whether to use one-hot word\r\n embeddings or tf.embedding_lookup() for the word embeddings. On the TPU,\r\n it is much faster if this is True, on the CPU or GPU, it is faster if\r\n this is False.\r\n scope: (optional) variable scope. Defaults to \"bert\".\r\n\r\n Raises:\r\n ValueError: The config is invalid or one of the input tensor shapes\r\n is invalid.\r\n \"\"\"\r\n config = copy.deepcopy(config)\r\n if not is_training:\r\n config.hidden_dropout_prob = 0.0\r\n config.attention_probs_dropout_prob = 0.0\r\n\r\n input_shape = get_shape_list(input_ids, expected_rank=2)\r\n batch_size = input_shape[0]\r\n seq_length = input_shape[1]\r\n\r\n if input_mask is None:\r\n input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32)\r\n\r\n if token_type_ids is None:\r\n token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32)\r\n\r\n with tf.variable_scope(scope, default_name=\"bert\"):\r\n with tf.variable_scope(\"embeddings\"):\r\n # Perform embedding lookup on the word ids.\r\n (self.embedding_output, self.embedding_table) = embedding_lookup(\r\n input_ids=input_ids,\r\n vocab_size=config.vocab_size,\r\n embedding_size=config.hidden_size,\r\n initializer_range=config.initializer_range,\r\n word_embedding_name=\"word_embeddings\",\r\n use_one_hot_embeddings=use_one_hot_embeddings)\r\n\r\n # Add positional embeddings and token type embeddings, then layer\r\n # normalize and perform dropout.\r\n self.embedding_output = embedding_postprocessor(\r\n input_tensor=self.embedding_output,\r\n use_token_type=True,\r\n token_type_ids=token_type_ids,\r\n token_type_vocab_size=config.type_vocab_size,\r\n token_type_embedding_name=\"token_type_embeddings\",\r\n use_position_embeddings=True,\r\n position_embedding_name=\"position_embeddings\",\r\n initializer_range=config.initializer_range,\r\n max_position_embeddings=config.max_position_embeddings,\r\n dropout_prob=config.hidden_dropout_prob)\r\n\r\n with tf.variable_scope(\"encoder\"):\r\n # This converts a 2D mask of shape [batch_size, seq_length] to a 3D\r\n # mask of shape [batch_size, seq_length, seq_length] which is used\r\n # for the attention scores.\r\n attention_mask = create_attention_mask_from_input_mask(\r\n input_ids, input_mask)\r\n\r\n # Run the stacked transformer.\r\n # `sequence_output` shape = [batch_size, seq_length, hidden_size].\r\n self.all_encoder_layers = transformer_model(\r\n input_tensor=self.embedding_output,\r\n attention_mask=attention_mask,\r\n hidden_size=config.hidden_size,\r\n num_hidden_layers=config.num_hidden_layers,\r\n num_attention_heads=config.num_attention_heads,\r\n intermediate_size=config.intermediate_size,\r\n intermediate_act_fn=get_activation(config.hidden_act),\r\n hidden_dropout_prob=config.hidden_dropout_prob,\r\n attention_probs_dropout_prob=config.attention_probs_dropout_prob,\r\n initializer_range=config.initializer_range,\r\n do_return_all_layers=True)\r\n\r\n self.sequence_output = self.all_encoder_layers[-1]\r\n # The \"pooler\" converts the encoded sequence tensor of shape\r\n # [batch_size, seq_length, hidden_size] to a tensor of shape\r\n # [batch_size, hidden_size]. This is necessary for segment-level\r\n # (or segment-pair-level) classification tasks where we need a fixed\r\n # dimensional representation of the segment.\r\n with tf.variable_scope(\"pooler\"):\r\n # We \"pool\" the model by simply taking the hidden state corresponding\r\n # to the first token. We assume that this has been pre-trained\r\n first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)\r\n self.pooled_output = tf.layers.dense(\r\n first_token_tensor,\r\n config.hidden_size,\r\n activation=tf.tanh,\r\n kernel_initializer=create_initializer(config.initializer_range))\r\n\r\n def get_pooled_output(self):\r\n return self.pooled_output\r\n\r\n def get_sequence_output(self):\r\n \"\"\"Gets final hidden layer of encoder.\r\n\r\n Returns:\r\n float Tensor of shape [batch_size, seq_length, hidden_size] corresponding\r\n to the final hidden of the transformer encoder.\r\n \"\"\"\r\n return self.sequence_output\r\n\r\n def get_all_encoder_layers(self):\r\n return self.all_encoder_layers\r\n\r\n def get_embedding_output(self):\r\n \"\"\"Gets output of the embedding lookup (i.e., input to the transformer).\r\n\r\n Returns:\r\n float Tensor of shape [batch_size, seq_length, hidden_size] corresponding\r\n to the output of the embedding layer, after summing the word\r\n embeddings with the positional embeddings and the token type embeddings,\r\n then performing layer normalization. This is the input to the transformer.\r\n \"\"\"\r\n return self.embedding_output\r\n\r\n def get_embedding_table(self):\r\n return self.embedding_table\r\n\r\n\r\ndef gelu(input_tensor):\r\n \"\"\"Gaussian Error Linear Unit.\r\n\r\n This is a smoother version of the RELU.\r\n Original paper: https://arxiv.org/abs/1606.08415\r\n\r\n Args:\r\n input_tensor: float Tensor to perform activation.\r\n\r\n Returns:\r\n `input_tensor` with the GELU activation applied.\r\n \"\"\"\r\n cdf = 0.5 * (1.0 + tf.erf(input_tensor / tf.sqrt(2.0)))\r\n return input_tensor * cdf\r\n\r\n\r\ndef get_activation(activation_string):\r\n \"\"\"Maps a string to a Python function, e.g., \"relu\" => `tf.nn.relu`.\r\n\r\n Args:\r\n activation_string: String name of the activation function.\r\n\r\n Returns:\r\n A Python function corresponding to the activation function. If\r\n `activation_string` is None, empty, or \"linear\", this will return None.\r\n If `activation_string` is not a string, it will return `activation_string`.\r\n\r\n Raises:\r\n ValueError: The `activation_string` does not correspond to a known\r\n activation.\r\n \"\"\"\r\n\r\n # We assume that anything that\"s not a string is already an activation\r\n # function, so we just return it.\r\n if not isinstance(activation_string, six.string_types):\r\n return activation_string\r\n\r\n if not activation_string:\r\n return None\r\n\r\n act = activation_string.lower()\r\n if act == \"linear\":\r\n return None\r\n elif act == \"relu\":\r\n return tf.nn.relu\r\n elif act == \"gelu\":\r\n return gelu\r\n elif act == \"tanh\":\r\n return tf.tanh\r\n else:\r\n raise ValueError(\"Unsupported activation: %s\" % act)\r\n\r\n\r\ndef get_assignment_map_from_checkpoint(tvars, init_checkpoint):\r\n \"\"\"Compute the union of the current variables and checkpoint variables.\"\"\"\r\n assignment_map = {}\r\n initialized_variable_names = {}\r\n\r\n name_to_variable = collections.OrderedDict()\r\n for var in tvars:\r\n name = var.name\r\n m = re.match(\"^(.*):\\\\d+$\", name)\r\n if m is not None:\r\n name = m.group(1)\r\n name_to_variable[name] = var\r\n\r\n init_vars = tf.train.list_variables(init_checkpoint)\r\n\r\n assignment_map = collections.OrderedDict()\r\n for x in init_vars:\r\n (name, var) = (x[0], x[1])\r\n if name not in name_to_variable:\r\n continue\r\n assignment_map[name] = name\r\n initialized_variable_names[name] = 1\r\n initialized_variable_names[name + \":0\"] = 1\r\n\r\n return (assignment_map, initialized_variable_names)\r\n\r\n\r\ndef dropout(input_tensor, dropout_prob):\r\n \"\"\"Perform dropout.\r\n\r\n Args:\r\n input_tensor: float Tensor.\r\n dropout_prob: Python float. The probability of dropping out a value (NOT of\r\n *keeping* a dimension as in `tf.nn.dropout`).\r\n\r\n Returns:\r\n A version of `input_tensor` with dropout applied.\r\n \"\"\"\r\n if dropout_prob is None or dropout_prob == 0.0:\r\n return input_tensor\r\n\r\n output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob)\r\n return output\r\n\r\n\r\ndef layer_norm(input_tensor, name=None):\r\n \"\"\"Run layer normalization on the last dimension of the tensor.\"\"\"\r\n return tf.contrib.layers.layer_norm(\r\n inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)\r\n\r\n\r\ndef layer_norm_and_dropout(input_tensor, dropout_prob, name=None):\r\n \"\"\"Runs layer normalization followed by dropout.\"\"\"\r\n output_tensor = layer_norm(input_tensor, name)\r\n output_tensor = dropout(output_tensor, dropout_prob)\r\n return output_tensor\r\n\r\n\r\ndef create_initializer(initializer_range=0.02):\r\n \"\"\"Creates a `truncated_normal_initializer` with the given range.\"\"\"\r\n return tf.truncated_normal_initializer(stddev=initializer_range)\r\n\r\n\r\ndef embedding_lookup(input_ids,\r\n vocab_size,\r\n embedding_size=128,\r\n initializer_range=0.02,\r\n word_embedding_name=\"word_embeddings\",\r\n use_one_hot_embeddings=False):\r\n \"\"\"Looks up words embeddings for id tensor.\r\n\r\n Args:\r\n input_ids: int32 Tensor of shape [batch_size, seq_length] containing word\r\n ids.\r\n vocab_size: int. Size of the embedding vocabulary.\r\n embedding_size: int. Width of the word embeddings.\r\n initializer_range: float. Embedding initialization range.\r\n word_embedding_name: string. Name of the embedding table.\r\n use_one_hot_embeddings: bool. If True, use one-hot method for word\r\n embeddings. If False, use `tf.nn.embedding_lookup()`. One hot is better\r\n for TPUs.\r\n\r\n Returns:\r\n float Tensor of shape [batch_size, seq_length, embedding_size].\r\n \"\"\"\r\n # This function assumes that the input is of shape [batch_size, seq_length,\r\n # num_inputs].\r\n #\r\n # If the input is a 2D tensor of shape [batch_size, seq_length], we\r\n # reshape to [batch_size, seq_length, 1].\r\n if input_ids.shape.ndims == 2:\r\n input_ids = tf.expand_dims(input_ids, axis=[-1])\r\n\r\n embedding_table = tf.get_variable(\r\n name=word_embedding_name,\r\n shape=[vocab_size, embedding_size],\r\n initializer=create_initializer(initializer_range))\r\n\r\n if use_one_hot_embeddings:\r\n flat_input_ids = tf.reshape(input_ids, [-1])\r\n one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size)\r\n output = tf.matmul(one_hot_input_ids, embedding_table)\r\n else:\r\n output = tf.nn.embedding_lookup(embedding_table, input_ids)\r\n\r\n input_shape = get_shape_list(input_ids)\r\n\r\n output = tf.reshape(output,\r\n input_shape[0:-1] + [input_shape[-1] * embedding_size])\r\n return (output, embedding_table)\r\n\r\n\r\ndef embedding_postprocessor(input_tensor,\r\n use_token_type=False,\r\n token_type_ids=None,\r\n token_type_vocab_size=16,\r\n token_type_embedding_name=\"token_type_embeddings\",\r\n use_position_embeddings=True,\r\n position_embedding_name=\"position_embeddings\",\r\n initializer_range=0.02,\r\n max_position_embeddings=512,\r\n dropout_prob=0.1):\r\n \"\"\"Performs various post-processing on a word embedding tensor.\r\n\r\n Args:\r\n input_tensor: float Tensor of shape [batch_size, seq_length,\r\n embedding_size].\r\n use_token_type: bool. Whether to add embeddings for `token_type_ids`.\r\n token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].\r\n Must be specified if `use_token_type` is True.\r\n token_type_vocab_size: int. The vocabulary size of `token_type_ids`.\r\n token_type_embedding_name: string. The name of the embedding table variable\r\n for token type ids.\r\n use_position_embeddings: bool. Whether to add position embeddings for the\r\n position of each token in the sequence.\r\n position_embedding_name: string. The name of the embedding table variable\r\n for positional embeddings.\r\n initializer_range: float. Range of the weight initialization.\r\n max_position_embeddings: int. Maximum sequence length that might ever be\r\n used with this model. This can be longer than the sequence length of\r\n input_tensor, but cannot be shorter.\r\n dropout_prob: float. Dropout probability applied to the final output tensor.\r\n\r\n Returns:\r\n float tensor with same shape as `input_tensor`.\r\n\r\n Raises:\r\n ValueError: One of the tensor shapes or input values is invalid.\r\n \"\"\"\r\n input_shape = get_shape_list(input_tensor, expected_rank=3)\r\n batch_size = input_shape[0]\r\n seq_length = input_shape[1]\r\n width = input_shape[2]\r\n\r\n output = input_tensor\r\n\r\n if use_token_type:\r\n if token_type_ids is None:\r\n raise ValueError(\"`token_type_ids` must be specified if\"\r\n \"`use_token_type` is True.\")\r\n token_type_table = tf.get_variable(\r\n name=token_type_embedding_name,\r\n shape=[token_type_vocab_size, width],\r\n initializer=create_initializer(initializer_range))\r\n # This vocab will be small so we always do one-hot here, since it is always\r\n # faster for a small vocabulary.\r\n flat_token_type_ids = tf.reshape(token_type_ids, [-1])\r\n one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size)\r\n token_type_embeddings = tf.matmul(one_hot_ids, token_type_table)\r\n token_type_embeddings = tf.reshape(token_type_embeddings,\r\n [batch_size, seq_length, width])\r\n output += token_type_embeddings\r\n\r\n if use_position_embeddings:\r\n assert_op = tf.assert_less_equal(seq_length, max_position_embeddings)\r\n with tf.control_dependencies([assert_op]):\r\n full_position_embeddings = tf.get_variable(\r\n name=position_embedding_name,\r\n shape=[max_position_embeddings, width],\r\n initializer=create_initializer(initializer_range))\r\n # Since the position embedding table is a learned variable, we create it\r\n # using a (long) sequence length `max_position_embeddings`. The actual\r\n # sequence length might be shorter than this, for faster training of\r\n # tasks that do not have long sequences.\r\n #\r\n # So `full_position_embeddings` is effectively an embedding table\r\n # for position [0, 1, 2, ..., max_position_embeddings-1], and the current\r\n # sequence has positions [0, 1, 2, ... seq_length-1], so we can just\r\n # perform a slice.\r\n position_embeddings = tf.slice(full_position_embeddings, [0, 0],\r\n [seq_length, -1])\r\n num_dims = len(output.shape.as_list())\r\n\r\n # Only the last two dimensions are relevant (`seq_length` and `width`), so\r\n # we broadcast among the first dimensions, which is typically just\r\n # the batch size.\r\n position_broadcast_shape = []\r\n for _ in range(num_dims - 2):\r\n position_broadcast_shape.append(1)\r\n position_broadcast_shape.extend([seq_length, width])\r\n position_embeddings = tf.reshape(position_embeddings,\r\n position_broadcast_shape)\r\n output += position_embeddings\r\n\r\n output = layer_norm_and_dropout(output, dropout_prob)\r\n return output\r\n\r\n\r\ndef create_attention_mask_from_input_mask(from_tensor, to_mask):\r\n \"\"\"Create 3D attention mask from a 2D tensor mask.\r\n\r\n Args:\r\n from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].\r\n to_mask: int32 Tensor of shape [batch_size, to_seq_length].\r\n\r\n Returns:\r\n float Tensor of shape [batch_size, from_seq_length, to_seq_length].\r\n \"\"\"\r\n from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])\r\n batch_size = from_shape[0]\r\n from_seq_length = from_shape[1]\r\n\r\n to_shape = get_shape_list(to_mask, expected_rank=2)\r\n to_seq_length = to_shape[1]\r\n\r\n to_mask = tf.cast(\r\n tf.reshape(to_mask, [batch_size, 1, to_seq_length]), tf.float32)\r\n\r\n # We don't assume that `from_tensor` is a mask (although it could be). We\r\n # don't actually care if we attend *from* padding tokens (only *to* padding)\r\n # tokens so we create a tensor of all ones.\r\n #\r\n # `broadcast_ones` = [batch_size, from_seq_length, 1]\r\n broadcast_ones = tf.ones(\r\n shape=[batch_size, from_seq_length, 1], dtype=tf.float32)\r\n\r\n # Here we broadcast along two dimensions to create the mask.\r\n mask = broadcast_ones * to_mask\r\n\r\n return mask\r\n\r\n\r\ndef attention_layer(from_tensor,\r\n to_tensor,\r\n attention_mask=None,\r\n num_attention_heads=1,\r\n size_per_head=512,\r\n query_act=None,\r\n key_act=None,\r\n value_act=None,\r\n attention_probs_dropout_prob=0.0,\r\n initializer_range=0.02,\r\n do_return_2d_tensor=False,\r\n batch_size=None,\r\n from_seq_length=None,\r\n to_seq_length=None):\r\n \"\"\"Performs multi-headed attention from `from_tensor` to `to_tensor`.\r\n\r\n This is an implementation of multi-headed attention based on \"Attention\r\n is all you Need\". If `from_tensor` and `to_tensor` are the same, then\r\n this is self-attention. Each timestep in `from_tensor` attends to the\r\n corresponding sequence in `to_tensor`, and returns a fixed-with vector.\r\n\r\n This function first projects `from_tensor` into a \"query\" tensor and\r\n `to_tensor` into \"key\" and \"value\" tensors. These are (effectively) a list\r\n of tensors of length `num_attention_heads`, where each tensor is of shape\r\n [batch_size, seq_length, size_per_head].\r\n\r\n Then, the query and key tensors are dot-producted and scaled. These are\r\n softmaxed to obtain attention probabilities. The value tensors are then\r\n interpolated by these probabilities, then concatenated back to a single\r\n tensor and returned.\r\n\r\n In practice, the multi-headed attention are done with transposes and\r\n reshapes rather than actual separate tensors.\r\n\r\n Args:\r\n from_tensor: float Tensor of shape [batch_size, from_seq_length,\r\n from_width].\r\n to_tensor: float Tensor of shape [batch_size, to_seq_length, to_width].\r\n attention_mask: (optional) int32 Tensor of shape [batch_size,\r\n from_seq_length, to_seq_length]. The values should be 1 or 0. The\r\n attention scores will effectively be set to -infinity for any positions in\r\n the mask that are 0, and will be unchanged for positions that are 1.\r\n num_attention_heads: int. Number of attention heads.\r\n size_per_head: int. Size of each attention head.\r\n query_act: (optional) Activation function for the query transform.\r\n key_act: (optional) Activation function for the key transform.\r\n value_act: (optional) Activation function for the value transform.\r\n attention_probs_dropout_prob: (optional) float. Dropout probability of the\r\n attention probabilities.\r\n initializer_range: float. Range of the weight initializer.\r\n do_return_2d_tensor: bool. If True, the output will be of shape [batch_size\r\n * from_seq_length, num_attention_heads * size_per_head]. If False, the\r\n output will be of shape [batch_size, from_seq_length, num_attention_heads\r\n * size_per_head].\r\n batch_size: (Optional) int. If the input is 2D, this might be the batch size\r\n of the 3D version of the `from_tensor` and `to_tensor`.\r\n from_seq_length: (Optional) If the input is 2D, this might be the seq length\r\n of the 3D version of the `from_tensor`.\r\n to_seq_length: (Optional) If the input is 2D, this might be the seq length\r\n of the 3D version of the `to_tensor`.\r\n\r\n Returns:\r\n float Tensor of shape [batch_size, from_seq_length,\r\n num_attention_heads * size_per_head]. (If `do_return_2d_tensor` is\r\n true, this will be of shape [batch_size * from_seq_length,\r\n num_attention_heads * size_per_head]).\r\n\r\n Raises:\r\n ValueError: Any of the arguments or tensor shapes are invalid.\r\n \"\"\"\r\n\r\n def transpose_for_scores(input_tensor, batch_size, num_attention_heads,\r\n seq_length, width):\r\n output_tensor = tf.reshape(\r\n input_tensor, [batch_size, seq_length, num_attention_heads, width])\r\n\r\n output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])\r\n return output_tensor\r\n\r\n from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])\r\n to_shape = get_shape_list(to_tensor, expected_rank=[2, 3])\r\n\r\n if len(from_shape) != len(to_shape):\r\n raise ValueError(\r\n \"The rank of `from_tensor` must match the rank of `to_tensor`.\")\r\n\r\n if len(from_shape) == 3:\r\n batch_size = from_shape[0]\r\n from_seq_length = from_shape[1]\r\n to_seq_length = to_shape[1]\r\n elif len(from_shape) == 2:\r\n if (batch_size is None or from_seq_length is None or to_seq_length is None):\r\n raise ValueError(\r\n \"When passing in rank 2 tensors to attention_layer, the values \"\r\n \"for `batch_size`, `from_seq_length`, and `to_seq_length` \"\r\n \"must all be specified.\")\r\n\r\n # Scalar dimensions referenced here:\r\n # B = batch size (number of sequences)\r\n # F = `from_tensor` sequence length\r\n # T = `to_tensor` sequence length\r\n # N = `num_attention_heads`\r\n # H = `size_per_head`\r\n\r\n from_tensor_2d = reshape_to_matrix(from_tensor)\r\n to_tensor_2d = reshape_to_matrix(to_tensor)\r\n\r\n # `query_layer` = [B*F, N*H]\r\n query_layer = tf.layers.dense(\r\n from_tensor_2d,\r\n num_attention_heads * size_per_head,\r\n activation=query_act,\r\n name=\"query\",\r\n kernel_initializer=create_initializer(initializer_range))\r\n\r\n # `key_layer` = [B*T, N*H]\r\n key_layer = tf.layers.dense(\r\n to_tensor_2d,\r\n num_attention_heads * size_per_head,\r\n activation=key_act,\r\n name=\"key\",\r\n kernel_initializer=create_initializer(initializer_range))\r\n\r\n # `value_layer` = [B*T, N*H]\r\n value_layer = tf.layers.dense(\r\n to_tensor_2d,\r\n num_attention_heads * size_per_head,\r\n activation=value_act,\r\n name=\"value\",\r\n kernel_initializer=create_initializer(initializer_range))\r\n\r\n # `query_layer` = [B, N, F, H]\r\n query_layer = transpose_for_scores(query_layer, batch_size,\r\n num_attention_heads, from_seq_length,\r\n size_per_head)\r\n\r\n # `key_layer` = [B, N, T, H]\r\n key_layer = transpose_for_scores(key_layer, batch_size, num_attention_heads,\r\n to_seq_length, size_per_head)\r\n\r\n # Take the dot product between \"query\" and \"key\" to get the raw\r\n # attention scores.\r\n # `attention_scores` = [B, N, F, T]\r\n attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)\r\n attention_scores = tf.multiply(attention_scores,\r\n 1.0 / math.sqrt(float(size_per_head)))\r\n\r\n if attention_mask is not None:\r\n # `attention_mask` = [B, 1, F, T]\r\n attention_mask = tf.expand_dims(attention_mask, axis=[1])\r\n\r\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\r\n # masked positions, this operation will create a tensor which is 0.0 for\r\n # positions we want to attend and -10000.0 for masked positions.\r\n adder = (1.0 - tf.cast(attention_mask, tf.float32)) * -10000.0\r\n\r\n # Since we are adding it to the raw scores before the softmax, this is\r\n # effectively the same as removing these entirely.\r\n attention_scores += adder\r\n\r\n # Normalize the attention scores to probabilities.\r\n # `attention_probs` = [B, N, F, T]\r\n attention_probs = tf.nn.softmax(attention_scores)\r\n\r\n # This is actually dropping out entire tokens to attend to, which might\r\n # seem a bit unusual, but is taken from the original Transformer paper.\r\n attention_probs = dropout(attention_probs, attention_probs_dropout_prob)\r\n\r\n # `value_layer` = [B, T, N, H]\r\n value_layer = tf.reshape(\r\n value_layer,\r\n [batch_size, to_seq_length, num_attention_heads, size_per_head])\r\n\r\n # `value_layer` = [B, N, T, H]\r\n value_layer = tf.transpose(value_layer, [0, 2, 1, 3])\r\n\r\n # `context_layer` = [B, N, F, H]\r\n context_layer = tf.matmul(attention_probs, value_layer)\r\n\r\n # `context_layer` = [B, F, N, H]\r\n context_layer = tf.transpose(context_layer, [0, 2, 1, 3])\r\n\r\n if do_return_2d_tensor:\r\n # `context_layer` = [B*F, N*H]\r\n context_layer = tf.reshape(\r\n context_layer,\r\n [batch_size * from_seq_length, num_attention_heads * size_per_head])\r\n else:\r\n # `context_layer` = [B, F, N*H]\r\n context_layer = tf.reshape(\r\n context_layer,\r\n [batch_size, from_seq_length, num_attention_heads * size_per_head])\r\n\r\n return context_layer\r\n\r\n\r\ndef transformer_model(input_tensor,\r\n attention_mask=None,\r\n hidden_size=768,\r\n num_hidden_layers=12,\r\n num_attention_heads=12,\r\n intermediate_size=3072,\r\n intermediate_act_fn=gelu,\r\n hidden_dropout_prob=0.1,\r\n attention_probs_dropout_prob=0.1,\r\n initializer_range=0.02,\r\n do_return_all_layers=False):\r\n \"\"\"Multi-headed, multi-layer Transformer from \"Attention is All You Need\".\r\n\r\n This is almost an exact implementation of the original Transformer encoder.\r\n\r\n See the original paper:\r\n https://arxiv.org/abs/1706.03762\r\n\r\n Also see:\r\n https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.py\r\n\r\n Args:\r\n input_tensor: float Tensor of shape [batch_size, seq_length, hidden_size].\r\n attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length,\r\n seq_length], with 1 for positions that can be attended to and 0 in\r\n positions that should not be.\r\n hidden_size: int. Hidden size of the Transformer.\r\n num_hidden_layers: int. Number of layers (blocks) in the Transformer.\r\n num_attention_heads: int. Number of attention heads in the Transformer.\r\n intermediate_size: int. The size of the \"intermediate\" (a.k.a., feed\r\n forward) layer.\r\n intermediate_act_fn: function. The non-linear activation function to apply\r\n to the output of the intermediate/feed-forward layer.\r\n hidden_dropout_prob: float. Dropout probability for the hidden layers.\r\n attention_probs_dropout_prob: float. Dropout probability of the attention\r\n probabilities.\r\n initializer_range: float. Range of the initializer (stddev of truncated\r\n normal).\r\n do_return_all_layers: Whether to also return all layers or just the final\r\n layer.\r\n\r\n Returns:\r\n float Tensor of shape [batch_size, seq_length, hidden_size], the final\r\n hidden layer of the Transformer.\r\n\r\n Raises:\r\n ValueError: A Tensor shape or parameter is invalid.\r\n \"\"\"\r\n if hidden_size % num_attention_heads != 0:\r\n raise ValueError(\r\n \"The hidden size (%d) is not a multiple of the number of attention \"\r\n \"heads (%d)\" % (hidden_size, num_attention_heads))\r\n\r\n attention_head_size = int(hidden_size / num_attention_heads)\r\n input_shape = get_shape_list(input_tensor, expected_rank=3)\r\n batch_size = input_shape[0]\r\n seq_length = input_shape[1]\r\n input_width = input_shape[2]\r\n\r\n # The Transformer performs sum residuals on all layers so the input needs\r\n # to be the same as the hidden size.\r\n if input_width != hidden_size:\r\n raise ValueError(\"The width of the input tensor (%d) != hidden size (%d)\" %\r\n (input_width, hidden_size))\r\n\r\n # We keep the representation as a 2D tensor to avoid re-shaping it back and\r\n # forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on\r\n # the GPU/CPU but may not be free on the TPU, so we want to minimize them to\r\n # help the optimizer.\r\n prev_output = reshape_to_matrix(input_tensor)\r\n\r\n all_layer_outputs = []\r\n for layer_idx in range(num_hidden_layers):\r\n with tf.variable_scope(\"layer_%d\" % layer_idx):\r\n layer_input = prev_output\r\n\r\n with tf.variable_scope(\"attention\"):\r\n attention_heads = []\r\n with tf.variable_scope(\"self\"):\r\n attention_head = attention_layer(\r\n from_tensor=layer_input,\r\n to_tensor=layer_input,\r\n attention_mask=attention_mask,\r\n num_attention_heads=num_attention_heads,\r\n size_per_head=attention_head_size,\r\n attention_probs_dropout_prob=attention_probs_dropout_prob,\r\n initializer_range=initializer_range,\r\n do_return_2d_tensor=True,\r\n batch_size=batch_size,\r\n from_seq_length=seq_length,\r\n to_seq_length=seq_length)\r\n attention_heads.append(attention_head)\r\n\r\n attention_output = None\r\n if len(attention_heads) == 1:\r\n attention_output = attention_heads[0]\r\n else:\r\n # In the case where we have other sequences, we just concatenate\r\n # them to the self-attention head before the projection.\r\n attention_output = tf.concat(attention_heads, axis=-1)\r\n\r\n # Run a linear projection of `hidden_size` then add a residual\r\n # with `layer_input`.\r\n with tf.variable_scope(\"output\"):\r\n attention_output = tf.layers.dense(\r\n attention_output,\r\n hidden_size,\r\n kernel_initializer=create_initializer(initializer_range))\r\n attention_output = dropout(attention_output, hidden_dropout_prob)\r\n attention_output = layer_norm(attention_output + layer_input)\r\n\r\n # The activation is only applied to the \"intermediate\" hidden layer.\r\n with tf.variable_scope(\"intermediate\"):\r\n intermediate_output = tf.layers.dense(\r\n attention_output,\r\n intermediate_size,\r\n activation=intermediate_act_fn,\r\n kernel_initializer=create_initializer(initializer_range))\r\n\r\n # Down-project back to `hidden_size` then add the residual.\r\n with tf.variable_scope(\"output\"):\r\n layer_output = tf.layers.dense(\r\n intermediate_output,\r\n hidden_size,\r\n kernel_initializer=create_initializer(initializer_range))\r\n layer_output = dropout(layer_output, hidden_dropout_prob)\r\n layer_output = layer_norm(layer_output + attention_output)\r\n prev_output = layer_output\r\n all_layer_outputs.append(layer_output)\r\n\r\n if do_return_all_layers:\r\n final_outputs = []\r\n for layer_output in all_layer_outputs:\r\n final_output = reshape_from_matrix(layer_output, input_shape)\r\n final_outputs.append(final_output)\r\n return final_outputs\r\n else:\r\n final_output = reshape_from_matrix(prev_output, input_shape)\r\n return final_output\r\n\r\n\r\ndef get_shape_list(tensor, expected_rank=None, name=None):\r\n \"\"\"Returns a list of the shape of tensor, preferring static dimensions.\r\n\r\n Args:\r\n tensor: A tf.Tensor object to find the shape of.\r\n expected_rank: (optional) int. The expected rank of `tensor`. If this is\r\n specified and the `tensor` has a different rank, and exception will be\r\n thrown.\r\n name: Optional name of the tensor for the error message.\r\n\r\n Returns:\r\n A list of dimensions of the shape of tensor. All static dimensions will\r\n be returned as python integers, and dynamic dimensions will be returned\r\n as tf.Tensor scalars.\r\n \"\"\"\r\n if name is None:\r\n name = tensor.name\r\n\r\n if expected_rank is not None:\r\n assert_rank(tensor, expected_rank, name)\r\n\r\n shape = tensor.shape.as_list()\r\n\r\n non_static_indexes = []\r\n for (index, dim) in enumerate(shape):\r\n if dim is None:\r\n non_static_indexes.append(index)\r\n\r\n if not non_static_indexes:\r\n return shape\r\n\r\n dyn_shape = tf.shape(tensor)\r\n for index in non_static_indexes:\r\n shape[index] = dyn_shape[index]\r\n return shape\r\n\r\n\r\ndef reshape_to_matrix(input_tensor):\r\n \"\"\"Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix).\"\"\"\r\n ndims = input_tensor.shape.ndims\r\n if ndims < 2:\r\n raise ValueError(\"Input tensor must have at least rank 2. Shape = %s\" %\r\n (input_tensor.shape))\r\n if ndims == 2:\r\n return input_tensor\r\n\r\n width = input_tensor.shape[-1]\r\n output_tensor = tf.reshape(input_tensor, [-1, width])\r\n return output_tensor\r\n\r\n\r\ndef reshape_from_matrix(output_tensor, orig_shape_list):\r\n \"\"\"Reshapes a rank 2 tensor back to its original rank >= 2 tensor.\"\"\"\r\n if len(orig_shape_list) == 2:\r\n return output_tensor\r\n\r\n output_shape = get_shape_list(output_tensor)\r\n\r\n orig_dims = orig_shape_list[0:-1]\r\n width = output_shape[-1]\r\n\r\n return tf.reshape(output_tensor, orig_dims + [width])\r\n\r\n\r\ndef assert_rank(tensor, expected_rank, name=None):\r\n \"\"\"Raises an exception if the tensor rank is not of the expected rank.\r\n\r\n Args:\r\n tensor: A tf.Tensor to check the rank of.\r\n expected_rank: Python integer or list of integers, expected rank.\r\n name: Optional name of the tensor for the error message.\r\n\r\n Raises:\r\n ValueError: If the expected shape doesn't match the actual shape.\r\n \"\"\"\r\n if name is None:\r\n name = tensor.name\r\n\r\n expected_rank_dict = {}\r\n if isinstance(expected_rank, six.integer_types):\r\n expected_rank_dict[expected_rank] = True\r\n else:\r\n for x in expected_rank:\r\n expected_rank_dict[x] = True\r\n\r\n actual_rank = tensor.shape.ndims\r\n if actual_rank not in expected_rank_dict:\r\n scope_name = tf.get_variable_scope().name\r\n raise ValueError(\r\n \"For the tensor `%s` in scope `%s`, the actual rank \"\r\n \"`%d` (shape = %s) is not equal to the expected rank `%s`\" %\r\n (name, scope_name, actual_rank, str(tensor.shape), str(expected_rank)))\r\n"
] | [
[
"tensorflow.reshape",
"tensorflow.ones",
"tensorflow.variable_scope",
"tensorflow.matmul",
"tensorflow.squeeze",
"tensorflow.one_hot",
"tensorflow.slice",
"tensorflow.get_variable_scope",
"tensorflow.concat",
"tensorflow.nn.softmax",
"tensorflow.contrib.layers.layer_norm",
"tensorflow.nn.dropout",
"tensorflow.truncated_normal_initializer",
"tensorflow.gfile.GFile",
"tensorflow.transpose",
"tensorflow.shape",
"tensorflow.train.list_variables",
"tensorflow.expand_dims",
"tensorflow.cast",
"tensorflow.control_dependencies",
"tensorflow.nn.embedding_lookup",
"tensorflow.zeros",
"tensorflow.sqrt",
"tensorflow.assert_less_equal"
]
] |
GinoBacallao/openai-python | [
"88bbe08947bceb10845b335d7f4cfb5ff406d948"
] | [
"examples/embeddings/utils.py"
] | [
"import openai\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tenacity import retry, wait_random_exponential, stop_after_attempt\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import average_precision_score\n\n\n@retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6))\ndef get_embedding(text, engine=\"davinci-similarity\"):\n\n # replace newlines, which can negatively affect performance.\n text = text.replace(\"\\n\", \" \")\n\n return openai.Engine(id=engine).embeddings(input = [text])['data'][0]['embedding']\n\n\ndef cosine_similarity(a, b):\n return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))\n\n\ndef plot_multiclass_precision_recall(\n y_score, y_true_untransformed, class_list, classifier_name\n):\n \"\"\"\n Precision-Recall plotting for a multiclass problem. It plots average precision-recall, per class precision recall and reference f1 contours.\n\n Code slightly modified, but heavily based on https://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html\n \"\"\"\n n_classes = len(class_list)\n y_true = pd.concat(\n [(y_true_untransformed == class_list[i]) for i in range(n_classes)], axis=1\n ).values\n\n # For each class\n precision = dict()\n recall = dict()\n average_precision = dict()\n for i in range(n_classes):\n precision[i], recall[i], _ = precision_recall_curve(y_true[:, i], y_score[:, i])\n average_precision[i] = average_precision_score(y_true[:, i], y_score[:, i])\n\n # A \"micro-average\": quantifying score on all classes jointly\n precision[\"micro\"], recall[\"micro\"], _ = precision_recall_curve(\n y_true.ravel(), y_score.ravel()\n )\n average_precision[\"micro\"] = average_precision_score(\n y_true, y_score, average=\"micro\"\n )\n print(\n str(classifier_name)\n + \" - Average precision score over all classes: {0:0.2f}\".format(\n average_precision[\"micro\"]\n )\n )\n\n # setup plot details\n plt.figure(figsize=(9, 10))\n f_scores = np.linspace(0.2, 0.8, num=4)\n lines = []\n labels = []\n for f_score in f_scores:\n x = np.linspace(0.01, 1)\n y = f_score * x / (2 * x - f_score)\n (l,) = plt.plot(x[y >= 0], y[y >= 0], color=\"gray\", alpha=0.2)\n plt.annotate(\"f1={0:0.1f}\".format(f_score), xy=(0.9, y[45] + 0.02))\n\n lines.append(l)\n labels.append(\"iso-f1 curves\")\n (l,) = plt.plot(recall[\"micro\"], precision[\"micro\"], color=\"gold\", lw=2)\n lines.append(l)\n labels.append(\n \"average Precision-recall (auprc = {0:0.2f})\"\n \"\".format(average_precision[\"micro\"])\n )\n\n for i in range(n_classes):\n (l,) = plt.plot(recall[i], precision[i], lw=2)\n lines.append(l)\n labels.append(\n \"Precision-recall for class `{0}` (auprc = {1:0.2f})\"\n \"\".format(class_list[i], average_precision[i])\n )\n\n fig = plt.gcf()\n fig.subplots_adjust(bottom=0.25)\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel(\"Recall\")\n plt.ylabel(\"Precision\")\n plt.title(f\"{classifier_name}: Precision-Recall curve for each class\")\n plt.legend(lines, labels)"
] | [
[
"matplotlib.pyplot.legend",
"numpy.linalg.norm",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.gcf",
"sklearn.metrics.precision_recall_curve",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"numpy.dot",
"sklearn.metrics.average_precision_score",
"numpy.linspace",
"matplotlib.pyplot.xlabel"
]
] |
elsa-burren/easy-neuralnetwork | [
"249149397016c104dd963c17a580f3fe45397191"
] | [
"myNN.py"
] | [
"# myNN.py\n# tested with Python3.7\n# author: Elsa Burren\n\nimport numpy as np\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\nclass MyNode:\n def __init__(self, w):\n self.w = w\n def update(self, dw):\n self.w += dw\n def output(self, x):\n return sigmoid(np.dot(x, self.w))\n\nclass MyHiddenLayer:\n def __init__(self, W, b):\n self.b = b\n self.W = W\n self.nbNodes = self.W.shape[0]\n def update(self, dW):\n self.W += dW \n def output(self, x): \n y = np.zeros(self.nbNodes) \n for i in range(0, self.nbNodes): \n y[i] = sigmoid(np.inner(self.W[i,], x) + self.b)\n return y\n\nclass MyOutputLayer: \n def __init__(self, w): \n self.w = w \n def update(self, dw):\n self.w += dw \n def output(self, x): \n return np.inner(self.w, x)\n \ndef example_3nodes_1feature(): \n import matplotlib.pyplot as plt\n w_hidden = np.array([1.0, -1.5, .5]) \n w_output = np.array([1, 1, -1])\n hidden_layer = MyHiddenLayer(w_hidden, 5) \n output_layer =MyOutputLayer(w_output) \n x = np.linspace(-10, 10, 20)\n y = np.zeros(len(x))\n for i, dx in enumerate(x):\n y[i] = output_layer.output(hidden_layer.output(dx))\n print([y[i]])\n plt.plot(x, y)\n plt.show()\n\ndef example_sigmoid():\n import matplotlib.pyplot as plt\n x = np.linspace(-2, 2, 20)\n y = sigmoid(2*x)\n plt.plot(x,y)\n plt.show()\n\ndef not_available():\n print(\"This example does not exist!\")\n \nif __name__ == \"__main__\":\n\n def select_example(x):\n return {\n \"a\" : \"example_3nodes_1feature\",\n \"b\" : \"example_sigmoid\"\n }.get(x, \"not_available\")\n \n print(\"\\nSo far, two examples are implemented\")\n print(\"\\nExample a: plots the output of a network with one hidden layer, 3 nodes and 1 feature. The purpose is to illustrate what a graph of such a function can look like.\")\n print(\"\\nExample b: a plot of a sigmoid function\")\n print(\"(see the script for the code of these examples)\")\n example_input = input(\"\\nSelect the example (enter a or b) :\")\n example_funct = select_example(example_input)\n locals()[example_funct]()\n\n"
] | [
[
"numpy.zeros",
"numpy.dot",
"numpy.exp",
"matplotlib.pyplot.show",
"numpy.array",
"matplotlib.pyplot.plot",
"numpy.inner",
"numpy.linspace"
]
] |
teshima058/3d_pose_baseline_openpose | [
"a5103a6db6df3cb34590bf68ddb179d4e543ffb2"
] | [
"src/poseVisualizer.py"
] | [
"import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# pose.shape : ({joint_num}, 3)\n# index_list : np.arange({joint_num})\ndef visualizePose(pose, mode=None, fig_scale=1, index_list=None,):\n fig = plt.figure()\n ax = fig.add_subplot(111 , projection='3d')\n for i,p in enumerate(pose):\n if mode == 'upper':\n upper_joints = [0, 1, 3, 4, 5, 9, 10, 11]\n if not i in upper_joints:\n continue\n ax.scatter(p[0], p[1], zs=p[2], zdir='z', s=20, marker='o', cmap=plt.cm.jet) \n elif index_list is not None:\n ax.scatter(p[0], p[1], zs=p[2], zdir='z', s=50, marker='${}$'.format(index_list[i]), cmap=plt.cm.jet) \n else:\n ax.scatter(p[0], p[1], zs=p[2], zdir='z', s=20, marker='o', cmap=plt.cm.jet) \n\n if mode == 'h36':\n borne_list = [[0,1], [0,4], [1,2], [2,3], [4,5], [5,6], [0,7], [7,8], [8,9], [9,10], [8,11], [11,12], [12,13], [8,14], [14,15], [15,16]]\n for b in borne_list:\n ax.plot([pose[b[0]][0], pose[b[1]][0]], [pose[b[0]][1], pose[b[1]][1]], [pose[b[0]][2], pose[b[1]][2]], lw=2)\n elif mode == 'cmu':\n borne_list = [[0,1], [0,2], [0,3], [3,4], [4,5], [2,6], [6,7], [7,8], [0,9], [9,10], [10,11], [2,12], [12,13], [13,14], [1,15], [15,16], [1,17], [17,18]]\n for b in borne_list:\n ax.plot([pose[b[0]][0], pose[b[1]][0]], [pose[b[0]][1], pose[b[1]][1]], [pose[b[0]][2], pose[b[1]][2]], lw=2)\n elif mode == 'upper':\n borne_list = [[0, 1], [0, 3], [3, 4], [4, 5], [0, 9], [9, 10], [10, 11]]\n for b in borne_list:\n ax.plot([pose[b[0]][0], pose[b[1]][0]], [pose[b[0]][1], pose[b[1]][1]], [pose[b[0]][2], pose[b[1]][2]], lw=2)\n\n # ax.set_xlim(-3 * fig_scale, 3 * fig_scale)\n # ax.set_ylim(-4 * fig_scale, 8 * fig_scale)\n # ax.set_zlim(-3 * fig_scale, 3 * fig_scale)\n ax.set_xlabel(\"X-axis\")\n ax.set_ylabel(\"Y-axis\")\n ax.set_zlabel(\"Z-axis\")\n plt.show()\n\n\n# Example\n# --------------------------\n# visualize outputs\n# --------------------------\n# ~~~\n# outputs = model(inputs)\n# \n# idx = 0\n# pose = outputs[idx].reshape(-1, 3)\n# pose = pose.cpu().detach().numpy()\n# index_frame = np.arange(len(pose))\n# visualizePose(pose, index_frame)\n\n\n\n# --------------------------\n# visualize inputs\n# --------------------------\n# idx = 0\n# pose = []\n# for i in range(len(inputs[idx])):\n# pose.append(inputs[idx][i].cpu().detach().numpy())\n# if i % 2 == 1:\n# pose.append(0)\n# pose = np.array(pose)\n# pose = np.reshape(pose, [-1, 3])\n# index_frame = np.arange(len(pose))\n# visualizePose(pose, index_frame)"
] | [
[
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show"
]
] |
megcrow/kinetic-schemes | [
"d1f5c5cc95481554e2d68a69b3b8663f9501df3d"
] | [
"functions/blasi.py"
] | [
"\"\"\"\nFunctions for Blasi 1993 and Blasi Branca 2001 kinetic reaction schemes for\nbiomass pyrolysis. See comments in each function for more details.\n\nReferences:\nBlasi, 1993. Combustion Science and Technology, 90, pp 315–340.\nBlasi, Branca, 2001. Ind. Eng. Chem. Res., 40, pp 5547-5556.\n\"\"\"\n\nimport numpy as np\n\ndef blasi(wood, gas, tar, char, T, dt, s=1):\n \"\"\"\n Primary and secondary kinetic reactions from Table 1 in Blasi 1993 paper.\n Note that primary reaction parameters in table are not cited correctly from\n the Thurner and Mann 1981 paper, this function uses the correct parameters.\n\n Parameters\n ----------\n wood = wood concentration, kg/m^3\n gas = gas concentation, kg/m^3\n tar = tar concentation, kg/m^3\n char = char concentation, kg/m^3\n T = temperature, K\n dt = time step, s\n s = 1 primary reactions only, 2 primary and secondary reactions\n\n Returns\n -------\n nwood = new wood concentration, kg/m^3\n ngas = new gas concentration, kg/m^3\n ntar = new tar concentration, kg/m^3\n nchar = new char concentration, kg/m^3\n \"\"\"\n # A = pre-factor (1/s) and E = activation energy (kJ/mol)\n A1 = 1.4345e4; E1 = 88.6 # wood -> gas\n A2 = 4.125e6; E2 = 112.7 # wood -> tar\n A3 = 7.3766e5; E3 = 106.5 # wood -> char\n A4 = 4.28e6; E4 = 108 # tar -> gas\n A5 = 1.0e6; E5 = 108 # tar -> char\n R = 0.008314 # universal gas constant, kJ/mol*K\n\n # reaction rate constant for each reaction, 1/s\n K1 = A1 * np.exp(-E1 / (R * T)) # wood -> gas\n K2 = A2 * np.exp(-E2 / (R * T)) # wood -> tar\n K3 = A3 * np.exp(-E3 / (R * T)) # wood -> char\n K4 = A4 * np.exp(-E4 / (R * T)) # tar -> gas\n K5 = A5 * np.exp(-E5 / (R * T)) # tar -> char\n\n if s == 1:\n # primary reactions only\n rw = -(K1+K2+K3)*wood # wood rate\n rg = K1*wood # gas rate\n rt = K2*wood # tar rate\n rc = K3*wood # char rate\n nwood = wood + rw*dt # update wood concentration\n ngas = gas + rg*dt # update gas concentration\n ntar = tar + rt*dt # update tar concentration\n nchar = char + rc*dt # update char concentration\n elif s == 2:\n # primary and secondary reactions\n rw = -(K1+K2+K3)*wood # wood rate\n rg = K1*wood + K4*tar # gas rate\n rt = K2*wood - (K4+K5)*tar # tar rate\n rc = K3*wood + K5*tar # char rate\n nwood = wood + rw*dt # update wood concentration\n ngas = gas + rg*dt # update gas concentration\n ntar = tar + rt*dt # update tar concentration\n nchar = char + rc*dt # update char concentration\n\n # return new wood, gas, tar, char mass concentrations, kg/m^3\n return nwood, ngas, ntar, nchar\n\n\ndef blasibranca(pw, pg, pt, pc, T, dt):\n \"\"\"\n Primary kinetic reactions from Table 1 in Blasi and Branca 2001 paper.\n\n Parameters\n ----------\n pw = wood concentration, kg/m^3\n pg = gas concentation, kg/m^3\n pt = tar concentation, kg/m^3\n pc = char concentation, kg/m^3\n T = temperature, K\n dt = time step, s\n\n Returns\n -------\n nw = new wood concentration, kg/m^3\n ng = new gas concentration, kg/m^3\n nt = new tar concentration, kg/m^3\n nc = new char concentration, kg/m^3\n \"\"\"\n # A = pre-factor (1/s) and E = activation energy (kJ/mol)\n A1 = 4.38e9; E1 = 152.7 # wood -> gas\n A2 = 1.08e10; E2 = 148 # wood -> tar\n A3 = 3.27e6; E3 = 111.7 # wood -> char\n R = 0.008314 # universal gas constant, kJ/mol*K\n\n # reaction rate constant for each reaction, 1/s\n K1 = A1 * np.exp(-E1 / (R * T)) # wood -> gas\n K2 = A2 * np.exp(-E2 / (R * T)) # wood -> tar\n K3 = A3 * np.exp(-E3 / (R * T)) # wood -> char\n\n # primary reactions only\n rw = -(K1+K2+K3)*pw # wood rate\n rg = K1*pw # gas rate\n rt = K2*pw # tar rate\n rc = K3*pw # char rate\n nw = pw + rw*dt # update wood concentration\n ng = pg + rg*dt # update gas concentration\n nt = pt + rt*dt # update tar concentration\n nc = pc + rc*dt # update char concentration\n\n # return new wood, gas, tar, char as mass concentrations, kg/m^3\n return nw, ng, nt, nc\n"
] | [
[
"numpy.exp"
]
] |
sethusaim/Automatic-Number-Plate-Recognition | [
"8b26008f8511e52600b150157901079e0fd0ebfe"
] | [
"base2designs/utils/vrd_evaluation.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\"\"\"Evaluator class for Visual Relations Detection.\n\nVRDDetectionEvaluator is a class which manages ground truth information of a\nvisual relations detection (vrd) dataset, and computes frequently used detection\nmetrics such as Precision, Recall, Recall@k, of the provided vrd detection\nresults.\nIt supports the following operations:\n1) Adding ground truth information of images sequentially.\n2) Adding detection results of images sequentially.\n3) Evaluating detection metrics on already inserted detection results.\n\nNote1: groundtruth should be inserted before evaluation.\nNote2: This module operates on numpy boxes and box lists.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom abc import abstractmethod\nimport collections\nimport logging\nimport numpy as np\nimport six\nfrom six.moves import range\n\nfrom object_detection.core import standard_fields\nfrom object_detection.utils import metrics\nfrom object_detection.utils import object_detection_evaluation\nfrom object_detection.utils import per_image_vrd_evaluation\n\n# Below standard input numpy datatypes are defined:\n# box_data_type - datatype of the groundtruth visual relations box annotations;\n# this datatype consists of two named boxes: subject bounding box and object\n# bounding box. Each box is of the format [y_min, x_min, y_max, x_max], each\n# coordinate being of type float32.\n# label_data_type - corresponding datatype of the visual relations label\n# annotaions; it consists of three numerical class labels: subject class label,\n# object class label and relation class label, each class label being of type\n# int32.\nvrd_box_data_type = np.dtype([(\"subject\", \"f4\", (4,)), (\"object\", \"f4\", (4,))])\nsingle_box_data_type = np.dtype([(\"box\", \"f4\", (4,))])\nlabel_data_type = np.dtype([(\"subject\", \"i4\"), (\"object\", \"i4\"), (\"relation\", \"i4\")])\n\n\nclass VRDDetectionEvaluator(object_detection_evaluation.DetectionEvaluator):\n \"\"\"A class to evaluate VRD detections.\n\n This class serves as a base class for VRD evaluation in two settings:\n - phrase detection\n - relation detection.\n \"\"\"\n\n def __init__(self, matching_iou_threshold=0.5, metric_prefix=None):\n \"\"\"Constructor.\n\n Args:\n matching_iou_threshold: IOU threshold to use for matching groundtruth\n boxes to detection boxes.\n metric_prefix: (optional) string prefix for metric name; if None, no\n prefix is used.\n\n \"\"\"\n super(VRDDetectionEvaluator, self).__init__([])\n self._matching_iou_threshold = matching_iou_threshold\n self._evaluation = _VRDDetectionEvaluation(\n matching_iou_threshold=self._matching_iou_threshold\n )\n self._image_ids = set([])\n self._metric_prefix = (metric_prefix + \"_\") if metric_prefix else \"\"\n self._evaluatable_labels = {}\n self._negative_labels = {}\n\n @abstractmethod\n def _process_groundtruth_boxes(self, groundtruth_box_tuples):\n \"\"\"Pre-processes boxes before adding them to the VRDDetectionEvaluation.\n\n Phrase detection and Relation detection subclasses re-implement this method\n depending on the task.\n\n Args:\n groundtruth_box_tuples: A numpy array of structures with the shape\n [M, 1], each structure containing the same number of named bounding\n boxes. Each box is of the format [y_min, x_min, y_max, x_max] (see\n datatype vrd_box_data_type, single_box_data_type above).\n \"\"\"\n raise NotImplementedError(\n \"_process_groundtruth_boxes method should be implemented in subclasses\"\n \"of VRDDetectionEvaluator.\"\n )\n\n @abstractmethod\n def _process_detection_boxes(self, detections_box_tuples):\n \"\"\"Pre-processes boxes before adding them to the VRDDetectionEvaluation.\n\n Phrase detection and Relation detection subclasses re-implement this method\n depending on the task.\n\n Args:\n detections_box_tuples: A numpy array of structures with the shape\n [M, 1], each structure containing the same number of named bounding\n boxes. Each box is of the format [y_min, x_min, y_max, x_max] (see\n datatype vrd_box_data_type, single_box_data_type above).\n \"\"\"\n raise NotImplementedError(\n \"_process_detection_boxes method should be implemented in subclasses\"\n \"of VRDDetectionEvaluator.\"\n )\n\n def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n standard_fields.InputDataFields.groundtruth_boxes: A numpy array\n of structures with the shape [M, 1], representing M tuples, each tuple\n containing the same number of named bounding boxes.\n Each box is of the format [y_min, x_min, y_max, x_max] (see\n datatype vrd_box_data_type, single_box_data_type above).\n standard_fields.InputDataFields.groundtruth_classes: A numpy array of\n structures shape [M, 1], representing the class labels of the\n corresponding bounding boxes and possibly additional classes (see\n datatype label_data_type above).\n standard_fields.InputDataFields.groundtruth_image_classes: numpy array\n of shape [K] containing verified labels.\n Raises:\n ValueError: On adding groundtruth for an image more than once.\n \"\"\"\n if image_id in self._image_ids:\n raise ValueError(\"Image with id {} already added.\".format(image_id))\n\n groundtruth_class_tuples = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_classes\n ]\n groundtruth_box_tuples = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_boxes\n ]\n\n self._evaluation.add_single_ground_truth_image_info(\n image_key=image_id,\n groundtruth_box_tuples=self._process_groundtruth_boxes(\n groundtruth_box_tuples\n ),\n groundtruth_class_tuples=groundtruth_class_tuples,\n )\n self._image_ids.update([image_id])\n all_classes = []\n for field in groundtruth_box_tuples.dtype.fields:\n all_classes.append(groundtruth_class_tuples[field])\n groudtruth_positive_classes = np.unique(np.concatenate(all_classes))\n verified_labels = groundtruth_dict.get(\n standard_fields.InputDataFields.groundtruth_image_classes,\n np.array([], dtype=int),\n )\n self._evaluatable_labels[image_id] = np.unique(\n np.concatenate((verified_labels, groudtruth_positive_classes))\n )\n\n self._negative_labels[image_id] = np.setdiff1d(\n verified_labels, groudtruth_positive_classes\n )\n\n def add_single_detected_image_info(self, image_id, detections_dict):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary containing -\n standard_fields.DetectionResultFields.detection_boxes: A numpy array of\n structures with shape [N, 1], representing N tuples, each tuple\n containing the same number of named bounding boxes.\n Each box is of the format [y_min, x_min, y_max, x_max] (as an example\n see datatype vrd_box_data_type, single_box_data_type above).\n standard_fields.DetectionResultFields.detection_scores: float32 numpy\n array of shape [N] containing detection scores for the boxes.\n standard_fields.DetectionResultFields.detection_classes: A numpy array\n of structures shape [N, 1], representing the class labels of the\n corresponding bounding boxes and possibly additional classes (see\n datatype label_data_type above).\n \"\"\"\n if image_id not in self._image_ids:\n logging.warning(\"No groundtruth for the image with id %s.\", image_id)\n # Since for the correct work of evaluator it is assumed that groundtruth\n # is inserted first we make sure to break the code if is it not the case.\n self._image_ids.update([image_id])\n self._negative_labels[image_id] = np.array([])\n self._evaluatable_labels[image_id] = np.array([])\n\n num_detections = detections_dict[\n standard_fields.DetectionResultFields.detection_boxes\n ].shape[0]\n detection_class_tuples = detections_dict[\n standard_fields.DetectionResultFields.detection_classes\n ]\n detection_box_tuples = detections_dict[\n standard_fields.DetectionResultFields.detection_boxes\n ]\n negative_selector = np.zeros(num_detections, dtype=bool)\n selector = np.ones(num_detections, dtype=bool)\n # Only check boxable labels\n for field in detection_box_tuples.dtype.fields:\n # Verify if one of the labels is negative (this is sure FP)\n negative_selector |= np.isin(\n detection_class_tuples[field], self._negative_labels[image_id]\n )\n # Verify if all labels are verified\n selector &= np.isin(\n detection_class_tuples[field], self._evaluatable_labels[image_id]\n )\n selector |= negative_selector\n self._evaluation.add_single_detected_image_info(\n image_key=image_id,\n detected_box_tuples=self._process_detection_boxes(\n detection_box_tuples[selector]\n ),\n detected_scores=detections_dict[\n standard_fields.DetectionResultFields.detection_scores\n ][selector],\n detected_class_tuples=detection_class_tuples[selector],\n )\n\n def evaluate(self, relationships=None):\n \"\"\"Compute evaluation result.\n\n Args:\n relationships: A dictionary of numerical label-text label mapping; if\n specified, returns per-relationship AP.\n\n Returns:\n A dictionary of metrics with the following fields -\n\n summary_metrics:\n 'weightedAP@<matching_iou_threshold>IOU' : weighted average precision\n at the specified IOU threshold.\n 'AP@<matching_iou_threshold>IOU/<relationship>' : AP per relationship.\n 'mAP@<matching_iou_threshold>IOU': mean average precision at the\n specified IOU threshold.\n 'Recall@50@<matching_iou_threshold>IOU': recall@50 at the specified IOU\n threshold.\n 'Recall@100@<matching_iou_threshold>IOU': recall@100 at the specified\n IOU threshold.\n if relationships is specified, returns <relationship> in AP metrics as\n readable names, otherwise the names correspond to class numbers.\n \"\"\"\n (\n weighted_average_precision,\n mean_average_precision,\n average_precisions,\n _,\n _,\n recall_50,\n recall_100,\n _,\n _,\n ) = self._evaluation.evaluate()\n\n vrd_metrics = {\n (\n self._metric_prefix\n + \"weightedAP@{}IOU\".format(self._matching_iou_threshold)\n ): weighted_average_precision,\n self._metric_prefix\n + \"mAP@{}IOU\".format(self._matching_iou_threshold): mean_average_precision,\n self._metric_prefix\n + \"Recall@50@{}IOU\".format(self._matching_iou_threshold): recall_50,\n self._metric_prefix\n + \"Recall@100@{}IOU\".format(self._matching_iou_threshold): recall_100,\n }\n if relationships:\n for key, average_precision in six.iteritems(average_precisions):\n vrd_metrics[\n self._metric_prefix\n + \"AP@{}IOU/{}\".format(\n self._matching_iou_threshold, relationships[key]\n )\n ] = average_precision\n else:\n for key, average_precision in six.iteritems(average_precisions):\n vrd_metrics[\n self._metric_prefix\n + \"AP@{}IOU/{}\".format(self._matching_iou_threshold, key)\n ] = average_precision\n\n return vrd_metrics\n\n def clear(self):\n \"\"\"Clears the state to prepare for a fresh evaluation.\"\"\"\n self._evaluation = _VRDDetectionEvaluation(\n matching_iou_threshold=self._matching_iou_threshold\n )\n self._image_ids.clear()\n self._negative_labels.clear()\n self._evaluatable_labels.clear()\n\n\nclass VRDRelationDetectionEvaluator(VRDDetectionEvaluator):\n \"\"\"A class to evaluate VRD detections in relations setting.\n\n Expected groundtruth box datatype is vrd_box_data_type, expected groudtruth\n labels datatype is label_data_type.\n Expected detection box datatype is vrd_box_data_type, expected detection\n labels\n datatype is label_data_type.\n \"\"\"\n\n def __init__(self, matching_iou_threshold=0.5):\n super(VRDRelationDetectionEvaluator, self).__init__(\n matching_iou_threshold=matching_iou_threshold,\n metric_prefix=\"VRDMetric_Relationships\",\n )\n\n def _process_groundtruth_boxes(self, groundtruth_box_tuples):\n \"\"\"Pre-processes boxes before adding them to the VRDDetectionEvaluation.\n\n Args:\n groundtruth_box_tuples: A numpy array of structures with the shape\n [M, 1], each structure containing the same number of named bounding\n boxes. Each box is of the format [y_min, x_min, y_max, x_max].\n\n Returns:\n Unchanged input.\n \"\"\"\n\n return groundtruth_box_tuples\n\n def _process_detection_boxes(self, detections_box_tuples):\n \"\"\"Pre-processes boxes before adding them to the VRDDetectionEvaluation.\n\n Phrase detection and Relation detection subclasses re-implement this method\n depending on the task.\n\n Args:\n detections_box_tuples: A numpy array of structures with the shape\n [M, 1], each structure containing the same number of named bounding\n boxes. Each box is of the format [y_min, x_min, y_max, x_max] (see\n datatype vrd_box_data_type, single_box_data_type above).\n Returns:\n Unchanged input.\n \"\"\"\n return detections_box_tuples\n\n\nclass VRDPhraseDetectionEvaluator(VRDDetectionEvaluator):\n \"\"\"A class to evaluate VRD detections in phrase setting.\n\n Expected groundtruth box datatype is vrd_box_data_type, expected groudtruth\n labels datatype is label_data_type.\n Expected detection box datatype is single_box_data_type, expected detection\n labels datatype is label_data_type.\n \"\"\"\n\n def __init__(self, matching_iou_threshold=0.5):\n super(VRDPhraseDetectionEvaluator, self).__init__(\n matching_iou_threshold=matching_iou_threshold,\n metric_prefix=\"VRDMetric_Phrases\",\n )\n\n def _process_groundtruth_boxes(self, groundtruth_box_tuples):\n \"\"\"Pre-processes boxes before adding them to the VRDDetectionEvaluation.\n\n In case of phrase evaluation task, evaluation expects exactly one bounding\n box containing all objects in the phrase. This bounding box is computed\n as an enclosing box of all groundtruth boxes of a phrase.\n\n Args:\n groundtruth_box_tuples: A numpy array of structures with the shape\n [M, 1], each structure containing the same number of named bounding\n boxes. Each box is of the format [y_min, x_min, y_max, x_max]. See\n vrd_box_data_type for an example of structure.\n\n Returns:\n result: A numpy array of structures with the shape [M, 1], each\n structure containing exactly one named bounding box. i-th output\n structure corresponds to the result of processing i-th input structure,\n where the named bounding box is computed as an enclosing bounding box\n of all bounding boxes of the i-th input structure.\n \"\"\"\n first_box_key = next(six.iterkeys(groundtruth_box_tuples.dtype.fields))\n miny = groundtruth_box_tuples[first_box_key][:, 0]\n minx = groundtruth_box_tuples[first_box_key][:, 1]\n maxy = groundtruth_box_tuples[first_box_key][:, 2]\n maxx = groundtruth_box_tuples[first_box_key][:, 3]\n for fields in groundtruth_box_tuples.dtype.fields:\n miny = np.minimum(groundtruth_box_tuples[fields][:, 0], miny)\n minx = np.minimum(groundtruth_box_tuples[fields][:, 1], minx)\n maxy = np.maximum(groundtruth_box_tuples[fields][:, 2], maxy)\n maxx = np.maximum(groundtruth_box_tuples[fields][:, 3], maxx)\n data_result = []\n for i in range(groundtruth_box_tuples.shape[0]):\n data_result.append(([miny[i], minx[i], maxy[i], maxx[i]],))\n result = np.array(data_result, dtype=[(\"box\", \"f4\", (4,))])\n return result\n\n def _process_detection_boxes(self, detections_box_tuples):\n \"\"\"Pre-processes boxes before adding them to the VRDDetectionEvaluation.\n\n In case of phrase evaluation task, evaluation expects exactly one bounding\n box containing all objects in the phrase. This bounding box is computed\n as an enclosing box of all groundtruth boxes of a phrase.\n\n Args:\n detections_box_tuples: A numpy array of structures with the shape\n [M, 1], each structure containing the same number of named bounding\n boxes. Each box is of the format [y_min, x_min, y_max, x_max]. See\n vrd_box_data_type for an example of this structure.\n\n Returns:\n result: A numpy array of structures with the shape [M, 1], each\n structure containing exactly one named bounding box. i-th output\n structure corresponds to the result of processing i-th input structure,\n where the named bounding box is computed as an enclosing bounding box\n of all bounding boxes of the i-th input structure.\n \"\"\"\n first_box_key = next(six.iterkeys(detections_box_tuples.dtype.fields))\n miny = detections_box_tuples[first_box_key][:, 0]\n minx = detections_box_tuples[first_box_key][:, 1]\n maxy = detections_box_tuples[first_box_key][:, 2]\n maxx = detections_box_tuples[first_box_key][:, 3]\n for fields in detections_box_tuples.dtype.fields:\n miny = np.minimum(detections_box_tuples[fields][:, 0], miny)\n minx = np.minimum(detections_box_tuples[fields][:, 1], minx)\n maxy = np.maximum(detections_box_tuples[fields][:, 2], maxy)\n maxx = np.maximum(detections_box_tuples[fields][:, 3], maxx)\n data_result = []\n for i in range(detections_box_tuples.shape[0]):\n data_result.append(([miny[i], minx[i], maxy[i], maxx[i]],))\n result = np.array(data_result, dtype=[(\"box\", \"f4\", (4,))])\n return result\n\n\nVRDDetectionEvalMetrics = collections.namedtuple(\n \"VRDDetectionEvalMetrics\",\n [\n \"weighted_average_precision\",\n \"mean_average_precision\",\n \"average_precisions\",\n \"precisions\",\n \"recalls\",\n \"recall_50\",\n \"recall_100\",\n \"median_rank_50\",\n \"median_rank_100\",\n ],\n)\n\n\nclass _VRDDetectionEvaluation(object):\n \"\"\"Performs metric computation for the VRD task. This class is internal.\n \"\"\"\n\n def __init__(self, matching_iou_threshold=0.5):\n \"\"\"Constructor.\n\n Args:\n matching_iou_threshold: IOU threshold to use for matching groundtruth\n boxes to detection boxes.\n \"\"\"\n self._per_image_eval = per_image_vrd_evaluation.PerImageVRDEvaluation(\n matching_iou_threshold=matching_iou_threshold\n )\n\n self._groundtruth_box_tuples = {}\n self._groundtruth_class_tuples = {}\n self._num_gt_instances = 0\n self._num_gt_imgs = 0\n self._num_gt_instances_per_relationship = {}\n\n self.clear_detections()\n\n def clear_detections(self):\n \"\"\"Clears detections.\"\"\"\n self._detection_keys = set()\n self._scores = []\n self._relation_field_values = []\n self._tp_fp_labels = []\n self._average_precisions = {}\n self._precisions = []\n self._recalls = []\n\n def add_single_ground_truth_image_info(\n self, image_key, groundtruth_box_tuples, groundtruth_class_tuples\n ):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n Args:\n image_key: A unique string/integer identifier for the image.\n groundtruth_box_tuples: A numpy array of structures with the shape\n [M, 1], representing M tuples, each tuple containing the same number\n of named bounding boxes.\n Each box is of the format [y_min, x_min, y_max, x_max].\n groundtruth_class_tuples: A numpy array of structures shape [M, 1],\n representing the class labels of the corresponding bounding boxes and\n possibly additional classes.\n \"\"\"\n if image_key in self._groundtruth_box_tuples:\n logging.warning(\n \"image %s has already been added to the ground truth database.\",\n image_key,\n )\n return\n\n self._groundtruth_box_tuples[image_key] = groundtruth_box_tuples\n self._groundtruth_class_tuples[image_key] = groundtruth_class_tuples\n\n self._update_groundtruth_statistics(groundtruth_class_tuples)\n\n def add_single_detected_image_info(\n self, image_key, detected_box_tuples, detected_scores, detected_class_tuples\n ):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n Args:\n image_key: A unique string/integer identifier for the image.\n detected_box_tuples: A numpy array of structures with shape [N, 1],\n representing N tuples, each tuple containing the same number of named\n bounding boxes.\n Each box is of the format [y_min, x_min, y_max, x_max].\n detected_scores: A float numpy array of shape [N, 1], representing\n the confidence scores of the detected N object instances.\n detected_class_tuples: A numpy array of structures shape [N, 1],\n representing the class labels of the corresponding bounding boxes and\n possibly additional classes.\n \"\"\"\n self._detection_keys.add(image_key)\n if image_key in self._groundtruth_box_tuples:\n groundtruth_box_tuples = self._groundtruth_box_tuples[image_key]\n groundtruth_class_tuples = self._groundtruth_class_tuples[image_key]\n else:\n groundtruth_box_tuples = np.empty(\n shape=[0, 4], dtype=detected_box_tuples.dtype\n )\n groundtruth_class_tuples = np.array([], dtype=detected_class_tuples.dtype)\n\n scores, tp_fp_labels, mapping = self._per_image_eval.compute_detection_tp_fp(\n detected_box_tuples=detected_box_tuples,\n detected_scores=detected_scores,\n detected_class_tuples=detected_class_tuples,\n groundtruth_box_tuples=groundtruth_box_tuples,\n groundtruth_class_tuples=groundtruth_class_tuples,\n )\n\n self._scores += [scores]\n self._tp_fp_labels += [tp_fp_labels]\n self._relation_field_values += [detected_class_tuples[mapping][\"relation\"]]\n\n def _update_groundtruth_statistics(self, groundtruth_class_tuples):\n \"\"\"Updates grouth truth statistics.\n\n Args:\n groundtruth_class_tuples: A numpy array of structures shape [M, 1],\n representing the class labels of the corresponding bounding boxes and\n possibly additional classes.\n \"\"\"\n self._num_gt_instances += groundtruth_class_tuples.shape[0]\n self._num_gt_imgs += 1\n for relation_field_value in np.unique(groundtruth_class_tuples[\"relation\"]):\n if relation_field_value not in self._num_gt_instances_per_relationship:\n self._num_gt_instances_per_relationship[relation_field_value] = 0\n self._num_gt_instances_per_relationship[relation_field_value] += np.sum(\n groundtruth_class_tuples[\"relation\"] == relation_field_value\n )\n\n def evaluate(self):\n \"\"\"Computes evaluation result.\n\n Returns:\n A named tuple with the following fields -\n average_precision: a float number corresponding to average precision.\n precisions: an array of precisions.\n recalls: an array of recalls.\n recall@50: recall computed on 50 top-scoring samples.\n recall@100: recall computed on 100 top-scoring samples.\n median_rank@50: median rank computed on 50 top-scoring samples.\n median_rank@100: median rank computed on 100 top-scoring samples.\n \"\"\"\n if self._num_gt_instances == 0:\n logging.warning(\"No ground truth instances\")\n\n if not self._scores:\n scores = np.array([], dtype=float)\n tp_fp_labels = np.array([], dtype=bool)\n else:\n scores = np.concatenate(self._scores)\n tp_fp_labels = np.concatenate(self._tp_fp_labels)\n relation_field_values = np.concatenate(self._relation_field_values)\n\n for relation_field_value, _ in six.iteritems(\n self._num_gt_instances_per_relationship\n ):\n precisions, recalls = metrics.compute_precision_recall(\n scores[relation_field_values == relation_field_value],\n tp_fp_labels[relation_field_values == relation_field_value],\n self._num_gt_instances_per_relationship[relation_field_value],\n )\n self._average_precisions[\n relation_field_value\n ] = metrics.compute_average_precision(precisions, recalls)\n\n self._mean_average_precision = np.mean(list(self._average_precisions.values()))\n\n self._precisions, self._recalls = metrics.compute_precision_recall(\n scores, tp_fp_labels, self._num_gt_instances\n )\n self._weighted_average_precision = metrics.compute_average_precision(\n self._precisions, self._recalls\n )\n\n self._recall_50 = metrics.compute_recall_at_k(\n self._tp_fp_labels, self._num_gt_instances, 50\n )\n self._median_rank_50 = metrics.compute_median_rank_at_k(self._tp_fp_labels, 50)\n self._recall_100 = metrics.compute_recall_at_k(\n self._tp_fp_labels, self._num_gt_instances, 100\n )\n self._median_rank_100 = metrics.compute_median_rank_at_k(\n self._tp_fp_labels, 100\n )\n\n return VRDDetectionEvalMetrics(\n self._weighted_average_precision,\n self._mean_average_precision,\n self._average_precisions,\n self._precisions,\n self._recalls,\n self._recall_50,\n self._recall_100,\n self._median_rank_50,\n self._median_rank_100,\n )\n"
] | [
[
"numpy.ones",
"numpy.sum",
"numpy.empty",
"numpy.zeros",
"numpy.maximum",
"numpy.dtype",
"numpy.setdiff1d",
"numpy.isin",
"numpy.array",
"numpy.concatenate",
"numpy.unique",
"numpy.minimum"
]
] |
nuannuanhcc/ps_reppoint | [
"abf9a82f53e5812936d0eed46f417c4500ffe151"
] | [
"mmdetection/mmdet/models/anchor_heads/anchor_head.py"
] | [
"from __future__ import division\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom mmcv.cnn import normal_init\n\nfrom mmdet.core import (AnchorGenerator, anchor_target, delta2bbox, force_fp32,\n multi_apply, multiclass_nms)\nfrom ..builder import build_loss\nfrom ..registry import HEADS\n\n\[email protected]_module\nclass AnchorHead(nn.Module):\n \"\"\"Anchor-based head (RPN, RetinaNet, SSD, etc.).\n\n Args:\n in_channels (int): Number of channels in the input feature map.\n feat_channels (int): Number of channels of the feature map.\n anchor_scales (Iterable): Anchor scales.\n anchor_ratios (Iterable): Anchor aspect ratios.\n anchor_strides (Iterable): Anchor strides.\n anchor_base_sizes (Iterable): Anchor base sizes.\n target_means (Iterable): Mean values of regression targets.\n target_stds (Iterable): Std values of regression targets.\n loss_cls (dict): Config of classification loss.\n loss_bbox (dict): Config of localization loss.\n \"\"\" # noqa: W605\n\n def __init__(self,\n num_classes,\n in_channels,\n feat_channels=256,\n anchor_scales=[8, 16, 32],\n anchor_ratios=[0.5, 1.0, 2.0],\n anchor_strides=[4, 8, 16, 32, 64],\n anchor_base_sizes=None,\n target_means=(.0, .0, .0, .0),\n target_stds=(1.0, 1.0, 1.0, 1.0),\n loss_cls=dict(\n type='CrossEntropyLoss',\n use_sigmoid=True,\n loss_weight=1.0),\n loss_bbox=dict(\n type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)):\n super(AnchorHead, self).__init__()\n self.in_channels = in_channels\n self.num_classes = num_classes\n self.feat_channels = feat_channels\n self.anchor_scales = anchor_scales\n self.anchor_ratios = anchor_ratios\n self.anchor_strides = anchor_strides\n self.anchor_base_sizes = list(\n anchor_strides) if anchor_base_sizes is None else anchor_base_sizes\n self.target_means = target_means\n self.target_stds = target_stds\n\n self.use_sigmoid_cls = loss_cls.get('use_sigmoid', False)\n self.sampling = loss_cls['type'] not in ['FocalLoss', 'GHMC']\n if self.use_sigmoid_cls:\n self.cls_out_channels = num_classes - 1\n else:\n self.cls_out_channels = num_classes\n self.loss_cls = build_loss(loss_cls)\n self.loss_bbox = build_loss(loss_bbox)\n self.fp16_enabled = False\n\n self.anchor_generators = []\n for anchor_base in self.anchor_base_sizes:\n self.anchor_generators.append(\n AnchorGenerator(anchor_base, anchor_scales, anchor_ratios))\n\n self.num_anchors = len(self.anchor_ratios) * len(self.anchor_scales)\n self._init_layers()\n\n def _init_layers(self):\n self.conv_cls = nn.Conv2d(self.feat_channels,\n self.num_anchors * self.cls_out_channels, 1)\n self.conv_reg = nn.Conv2d(self.feat_channels, self.num_anchors * 4, 1)\n\n def init_weights(self):\n normal_init(self.conv_cls, std=0.01)\n normal_init(self.conv_reg, std=0.01)\n\n def forward_single(self, x):\n cls_score = self.conv_cls(x)\n bbox_pred = self.conv_reg(x)\n return cls_score, bbox_pred\n\n def forward(self, feats):\n return multi_apply(self.forward_single, feats)\n\n def get_anchors(self, featmap_sizes, img_metas):\n \"\"\"Get anchors according to feature map sizes.\n\n Args:\n featmap_sizes (list[tuple]): Multi-level feature map sizes.\n img_metas (list[dict]): Image meta info.\n\n Returns:\n tuple: anchors of each image, valid flags of each image\n \"\"\"\n num_imgs = len(img_metas)\n num_levels = len(featmap_sizes)\n\n # since feature map sizes of all images are the same, we only compute\n # anchors for one time\n multi_level_anchors = []\n for i in range(num_levels):\n anchors = self.anchor_generators[i].grid_anchors(\n featmap_sizes[i], self.anchor_strides[i])\n multi_level_anchors.append(anchors)\n anchor_list = [multi_level_anchors for _ in range(num_imgs)]\n\n # for each image, we compute valid flags of multi level anchors\n valid_flag_list = []\n for img_id, img_meta in enumerate(img_metas):\n multi_level_flags = []\n for i in range(num_levels):\n anchor_stride = self.anchor_strides[i]\n feat_h, feat_w = featmap_sizes[i]\n h, w, _ = img_meta['pad_shape']\n valid_feat_h = min(int(np.ceil(h / anchor_stride)), feat_h)\n valid_feat_w = min(int(np.ceil(w / anchor_stride)), feat_w)\n flags = self.anchor_generators[i].valid_flags(\n (feat_h, feat_w), (valid_feat_h, valid_feat_w))\n multi_level_flags.append(flags)\n valid_flag_list.append(multi_level_flags)\n\n return anchor_list, valid_flag_list\n\n def loss_single(self, cls_score, bbox_pred, labels, label_weights,\n bbox_targets, bbox_weights, num_total_samples, cfg):\n # classification loss\n if labels.dim() == 3:\n all_labels = labels.clone()\n labels = all_labels[:, :, 0]\n labels = labels.reshape(-1)\n label_weights = label_weights.reshape(-1)\n cls_score = cls_score.permute(0, 2, 3,\n 1).reshape(-1, self.cls_out_channels)\n loss_cls = self.loss_cls(\n cls_score, labels, label_weights, avg_factor=num_total_samples)\n # regression loss\n bbox_targets = bbox_targets.reshape(-1, 4)\n bbox_weights = bbox_weights.reshape(-1, 4)\n bbox_pred = bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4)\n loss_bbox = self.loss_bbox(\n bbox_pred,\n bbox_targets,\n bbox_weights,\n avg_factor=num_total_samples)\n return loss_cls, loss_bbox\n\n @force_fp32(apply_to=('cls_scores', 'bbox_preds'))\n def loss(self,\n cls_scores,\n bbox_preds,\n gt_bboxes,\n gt_labels,\n img_metas,\n cfg,\n gt_bboxes_ignore=None):\n featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]\n assert len(featmap_sizes) == len(self.anchor_generators)\n\n anchor_list, valid_flag_list = self.get_anchors(\n featmap_sizes, img_metas)\n label_channels = self.cls_out_channels if self.use_sigmoid_cls else 1\n cls_reg_targets = anchor_target(\n anchor_list,\n valid_flag_list,\n gt_bboxes,\n img_metas,\n self.target_means,\n self.target_stds,\n cfg,\n gt_bboxes_ignore_list=gt_bboxes_ignore,\n gt_labels_list=gt_labels,\n label_channels=label_channels,\n sampling=self.sampling)\n if cls_reg_targets is None:\n return None\n (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list,\n num_total_pos, num_total_neg) = cls_reg_targets\n num_total_samples = (\n num_total_pos + num_total_neg if self.sampling else num_total_pos)\n losses_cls, losses_bbox = multi_apply(\n self.loss_single,\n cls_scores,\n bbox_preds,\n labels_list,\n label_weights_list,\n bbox_targets_list,\n bbox_weights_list,\n num_total_samples=num_total_samples,\n cfg=cfg)\n return dict(loss_cls=losses_cls, loss_bbox=losses_bbox)\n\n @force_fp32(apply_to=('cls_scores', 'bbox_preds'))\n def get_bboxes(self, cls_scores, bbox_preds, img_metas, cfg,\n rescale=False):\n assert len(cls_scores) == len(bbox_preds)\n num_levels = len(cls_scores)\n\n mlvl_anchors = [\n self.anchor_generators[i].grid_anchors(cls_scores[i].size()[-2:],\n self.anchor_strides[i])\n for i in range(num_levels)\n ]\n result_list = []\n for img_id in range(len(img_metas)):\n cls_score_list = [\n cls_scores[i][img_id].detach() for i in range(num_levels)\n ]\n bbox_pred_list = [\n bbox_preds[i][img_id].detach() for i in range(num_levels)\n ]\n img_shape = img_metas[img_id]['img_shape']\n scale_factor = img_metas[img_id]['scale_factor']\n proposals = self.get_bboxes_single(cls_score_list, bbox_pred_list,\n mlvl_anchors, img_shape,\n scale_factor, cfg, rescale)\n result_list.append(proposals)\n return result_list\n\n def get_bboxes_single(self,\n cls_scores,\n bbox_preds,\n mlvl_anchors,\n img_shape,\n scale_factor,\n cfg,\n rescale=False):\n assert len(cls_scores) == len(bbox_preds) == len(mlvl_anchors)\n mlvl_bboxes = []\n mlvl_scores = []\n for cls_score, bbox_pred, anchors in zip(cls_scores, bbox_preds,\n mlvl_anchors):\n assert cls_score.size()[-2:] == bbox_pred.size()[-2:]\n cls_score = cls_score.permute(1, 2,\n 0).reshape(-1, self.cls_out_channels)\n if self.use_sigmoid_cls:\n scores = cls_score.sigmoid()\n else:\n scores = cls_score.softmax(-1)\n bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, 4)\n nms_pre = cfg.get('nms_pre', -1)\n if nms_pre > 0 and scores.shape[0] > nms_pre:\n if self.use_sigmoid_cls:\n max_scores, _ = scores.max(dim=1)\n else:\n max_scores, _ = scores[:, 1:].max(dim=1)\n _, topk_inds = max_scores.topk(nms_pre)\n anchors = anchors[topk_inds, :]\n bbox_pred = bbox_pred[topk_inds, :]\n scores = scores[topk_inds, :]\n bboxes = delta2bbox(anchors, bbox_pred, self.target_means,\n self.target_stds, img_shape)\n mlvl_bboxes.append(bboxes)\n mlvl_scores.append(scores)\n mlvl_bboxes = torch.cat(mlvl_bboxes)\n if rescale:\n mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor)\n mlvl_scores = torch.cat(mlvl_scores)\n if self.use_sigmoid_cls:\n padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1)\n mlvl_scores = torch.cat([padding, mlvl_scores], dim=1)\n det_bboxes, det_labels = multiclass_nms(mlvl_bboxes, mlvl_scores,\n cfg.score_thr, cfg.nms,\n cfg.max_per_img)\n return det_bboxes, det_labels\n"
] | [
[
"numpy.ceil",
"torch.nn.Conv2d",
"torch.cat"
]
] |
gongzhitaao/adversarial-classifier | [
"ded40b5b319fe13e8eb40147113e9fced53433ed"
] | [
"src/figure_1.py"
] | [
"import os\n# supress tensorflow logging other than errors\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom keras import backend as K\nfrom keras.datasets import mnist\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Convolution2D, MaxPooling2D\nfrom keras.utils import np_utils\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nfrom attacks.fgsm import fgsm\n\n\nimg_rows = 28\nimg_cols = 28\nimg_chas = 1\ninput_shape = (img_rows, img_cols, img_chas)\nnb_classes = 10\n\n\nprint('\\nLoading mnist')\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n\nX_train = X_train.astype('float32') / 255.\nX_test = X_test.astype('float32') / 255.\n\nX_train = X_train.reshape(-1, img_rows, img_cols, img_chas)\nX_test = X_test.reshape(-1, img_rows, img_cols, img_chas)\n\n# one hot encoding\ny_train = np_utils.to_categorical(y_train, nb_classes)\nz0 = y_test.copy()\ny_test = np_utils.to_categorical(y_test, nb_classes)\n\n\nsess = tf.InteractiveSession()\nK.set_session(sess)\n\n\nif False:\n print('\\nLoading model')\n model = load_model('model/figure_1.h5')\nelse:\n print('\\nBuilding model')\n model = Sequential([\n Convolution2D(32, 3, 3, input_shape=input_shape),\n Activation('relu'),\n Convolution2D(32, 3, 3),\n Activation('relu'),\n MaxPooling2D(pool_size=(2, 2)),\n Dropout(0.25),\n Flatten(),\n Dense(128),\n Activation('relu'),\n Dropout(0.5),\n Dense(10),\n Activation('softmax')])\n\n model.compile(optimizer='adam', loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n print('\\nTraining model')\n model.fit(X_train, y_train, nb_epoch=10)\n\n print('\\nSaving model')\n os.makedirs('model', exist_ok=True)\n model.save('model/figure_1.h5')\n\n\nx = tf.placeholder(tf.float32, (None, img_rows, img_cols, img_chas))\nx_adv = fgsm(model, x, nb_epoch=9, eps=0.02)\n\n\nprint('\\nTest against clean data')\nscore = model.evaluate(X_test, y_test)\nprint('\\nloss: {0:.4f} acc: {1:.4f}'.format(score[0], score[1]))\n\n\nif False:\n print('\\nLoading adversarial data')\n X_adv = np.load('data/figure_1.npy')\nelse:\n print('\\nGenerating adversarial data')\n nb_sample = X_test.shape[0]\n batch_size = 128\n nb_batch = int(np.ceil(nb_sample/batch_size))\n X_adv = np.empty(X_test.shape)\n for batch in range(nb_batch):\n print('batch {0}/{1}'.format(batch+1, nb_batch), end='\\r')\n start = batch * batch_size\n end = min(nb_sample, start+batch_size)\n tmp = sess.run(x_adv, feed_dict={x: X_test[start:end],\n K.learning_phase(): 0})\n X_adv[start:end] = tmp\n\n os.makedirs('data', exist_ok=True)\n np.save('data/figure_1.npy', X_adv)\n\n\nprint('\\nTest against adversarial data')\nscore = model.evaluate(X_adv, y_test)\nprint('\\nloss: {0:.4f} acc: {1:.4f}'.format(score[0], score[1]))\n\n\nprint('\\nMake predictions')\ny1 = model.predict(X_test)\nz1 = np.argmax(y1, axis=1)\ny2 = model.predict(X_adv)\nz2 = np.argmax(y2, axis=1)\n\nprint('\\nSelecting figures')\nX_tmp = np.empty((2, 10, 28, 28))\ny_proba = np.empty((2, 10, 10))\nfor i in range(10):\n print('Target {0}'.format(i))\n ind, = np.where(np.all([z0==i, z1==i, z2!=i], axis=0))\n cur = np.random.choice(ind)\n X_tmp[0][i] = np.squeeze(X_test[cur])\n X_tmp[1][i] = np.squeeze(X_adv[cur])\n y_proba[0][i] = y1[cur]\n y_proba[1][i] = y2[cur]\n\n\nprint('\\nPlotting results')\nfig = plt.figure(figsize=(10, 3))\ngs = gridspec.GridSpec(2, 10, wspace=0.1, hspace=0.1)\n\nlabel = np.argmax(y_proba, axis=2)\nproba = np.max(y_proba, axis=2)\nfor i in range(10):\n for j in range(2):\n ax = fig.add_subplot(gs[j, i])\n ax.imshow(X_tmp[j][i], cmap='gray', interpolation='none')\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_xlabel('{0} ({1:.2f})'.format(label[j][i],\n proba[j][i]),\n fontsize=12)\n\nprint('\\nSaving figure')\ngs.tight_layout(fig)\nos.makedirs('img', exist_ok=True)\nplt.savefig('img/figure_1.pdf')\n"
] | [
[
"numpy.load",
"tensorflow.placeholder",
"numpy.save",
"numpy.empty",
"numpy.squeeze",
"numpy.ceil",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.savefig",
"numpy.random.choice",
"numpy.argmax",
"tensorflow.InteractiveSession",
"numpy.max",
"numpy.all",
"matplotlib.use",
"matplotlib.gridspec.GridSpec"
]
] |
dreadbird06/tso_vace_wpe | [
"3e9d9d9b0ebe3d3e360e678af5960ff23d57eae2"
] | [
"run.py"
] | [
"\"\"\"\nExample codes for speech dereverberation based on the WPE variants.\n\nauthor: Joon-Young Yang (E-mail: [email protected])\n\"\"\"\nimport os\n# os.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_id\n\nimport numpy as np\nimport soundfile as sf\n\nimport torch\ntorch.set_printoptions(precision=10)\n\nfrom torch_custom.torch_utils import load_checkpoint, to_arr\nfrom torch_custom.iterative_wpe import IterativeWPE\nfrom torch_custom.neural_wpe import NeuralWPE\n\nfrom bldnn_4M62 import LstmDnnNet as LPSEstimator\nfrom gcunet4c_4M4390 import VACENet\nfrom vace_wpe import VACEWPE\n\n\n## ----------------------------------------------------- ##\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\nprint('device = {}'.format(device))\n# device = \"cpu\"\n\nstft_opts_torch = dict(\n n_fft=1024, hop_length=256, win_length=1024, win_type='hanning', \n symmetric=True)\nfft_bins = stft_opts_torch['n_fft']//2 + 1\n\n# mfcc_opts_torch = dict(\n# fs=16000, nfft=1024, lowfreq=20., maxfreq=7600., \n# nlinfilt=0, nlogfilt=40, nceps=40, \n# lifter_type='sinusoidal', lift=-22.0) # only useful during fine-tuning\n\ndelay, taps1, taps2 = 3, 30, 15\n## ----------------------------------------------------- ##\n\n\ndef apply_drc(audio, drc_ratio=0.25, n_pop=100, dtype='float32'):\n normalized = (max(audio.max(), abs(audio.min())) <= 1.0)\n normalizer = 1.0 if normalized else float(2**15)\n ## compute MMD\n audio_sorted = np.sort(audio.squeeze(), axis=-1) # either (N,) or (D, N)\n audio_mmd = audio_sorted[..., -1:-n_pop-1:-1].mean(dtype=dtype) \\\n - audio_sorted[..., :n_pop].mean(dtype=dtype)\n drange_gain = 2 * (normalizer/audio_mmd) * drc_ratio\n return (audio * drange_gain).astype(dtype), drange_gain.astype(dtype)\n\n\ndef run_vace_wpe(wpath, prefix, pretrain_opt='late', simp_opt='b'):\n assert pretrain_opt == 'late' # VACENet should be pretrained to estimate late reverberation components\n assert simp_opt == 'b' # Simplified VACE-WPE architecture is used\n print(f'Running \"{prefix}-VACE-WPE\"...')\n\n ## Saved checkpoint file\n prefix = prefix.lower()\n if prefix == 'drv': # Drv-VACE-WPE\n ckpt_file = 'models/20210615-183131/ckpt-ep60'\n elif prefix == 'dns': # Dns-VACE-WPE\n ckpt_file = 'models/20210615-221501/ckpt-ep60'\n elif prefix == 'dr-tsoc': # DR-TSO_\\mathcal{C}-VACE-WPE\n ckpt_file = 'models/20210617-095331/ckpt-ep30'\n elif prefix == 'tsoc': # TSO_\\mathcal{C}-VACE-WPE\n ckpt_file = 'models/20210617-103601/ckpt-ep30'\n elif prefix == 'tson': # TSO_\\mathcal{N}-VACE-WPE\n ckpt_file = 'models/20210617-125831/ckpt-ep30'\n\n ## ------------------------------------------------- ##\n\n ## VACENet\n fake_scale = 2.0\n vacenet = VACENet(\n input_dim=fft_bins, stft_opts=stft_opts_torch, \n input_norm='globalmvn', # loaded from the saved checkpoint\n scope='vace_unet', fake_scale=fake_scale)\n vacenet = vacenet.to(device)\n vacenet.eval()\n # print('VACENet size = {:.2f}M'.format(vacenet.size))\n # vacenet.check_trainable_parameters()\n\n ## LPSNet\n lpsnet = LPSEstimator(\n input_dim=fft_bins, \n stft_opts=stft_opts_torch, \n input_norm='globalmvn', # loaded from the saved checkpoint\n scope='ldnn_lpseir_ns')\n lpsnet = lpsnet.to(device)\n lpsnet.eval()\n # lpsnet.freeze() # should be frozen when fine-tuning the VACENet\n # print('LPSNet size = {:.2f}M'.format(lpsnet.size))\n # lpsnet.check_trainable_parameters()\n\n ## VACE-WPE\n dnn_vwpe = VACEWPE(\n stft_opts=stft_opts_torch, \n lpsnet=lpsnet, vacenet=vacenet)#, \n # mfcc_opts=mfcc_opts_torch) # only useful when fine-tuning the VACENet\n dnn_vwpe, *_ = load_checkpoint(dnn_vwpe, checkpoint=ckpt_file, strict=False)\n dnn_vwpe.to(device)\n dnn_vwpe.eval()\n # print('VACE-WPE size = {:.2f}M'.format(dnn_vwpe.size))\n # dnn_vwpe.check_trainable_parameters()\n\n ## ------------------------------------------------- ##\n\n ## Load audio and apply DRC\n aud, fs = sf.read(wpath) # (t,), 16000\n aud, drc_gain = apply_drc(aud) # (t,), ()\n\n ## Perform dereverberation\n aud = torch.from_numpy(aud)[None] # (batch, samples)\n with torch.no_grad():\n ## The input audio is in shape (batch, samples) (always assume #channels == 1)\n enh = dnn_vwpe.dereverb(\n aud.to(device), delay=delay, taps=taps2) # (t,)\n ## Save\n output_wav_path = f'data/{prefix}-vace_wpe_taps{taps2}.wav'\n sf.write(output_wav_path, data=enh, samplerate=fs)\n\n\ndef run_neural_wpe(wpath, chs='single', dtype=torch.float64):\n print(f'Running \"Neural-WPE-{chs}\"...')\n\n ckpt_file = np.random.choice([\n 'models/20210615-183131/ckpt-ep60', # Drv-VACE-WPE\n 'models/20210615-221501/ckpt-ep60', # Dns-VACE-WPE\n 'models/20210617-095331/ckpt-ep30', # TSON-VACE-WPE\n 'models/20210617-103601/ckpt-ep30', # TSOC-VACE-WPE\n 'models/20210617-125831/ckpt-ep30', # DR-TSOC-VACE-WPE\n ]) # the VACE-WPE variants share the same LPSNet model for PSD estimation\n\n ## ------------------------------------------------- ##\n\n ## LPSNet\n lpsnet = LPSEstimator(\n input_dim=fft_bins, \n stft_opts=stft_opts_torch, \n input_norm='globalmvn', # loaded from the saved checkpoint\n scope='ldnn_lpseir_ns')\n lpsnet = lpsnet.to(device)\n # lpsnet.freeze() # should be frozen when fine-tuning the VACENet\n lpsnet.eval()\n # print('LPSNet size = {:.2f}M'.format(lpsnet.size))\n # lpsnet.check_trainable_parameters()\n\n ## Neural WPE\n dnn_wpe = NeuralWPE(\n stft_opts=stft_opts_torch, \n lpsnet=lpsnet)\n dnn_wpe, *_ = load_checkpoint(dnn_wpe, checkpoint=ckpt_file, strict=False)\n dnn_wpe.to(device)\n dnn_wpe.eval()\n # print('Neural WPE size = {:.2f}M'.format(dnn_wpe.size))\n # dnn_wpe.check_trainable_parameters()\n\n ## ------------------------------------------------- ##\n\n ## Load audio and apply DRC\n aud, fs = sf.read(wpath) # (t,), 16000\n aud, drc_gain = apply_drc(aud) # (t,), ()\n\n if chs == 'single':\n aud = aud[None] # (channels=1, samples)\n taps = taps1\n if chs == 'dual':\n aud2, fs2 = sf.read(sample_wav2, dtype='float32')\n aud2 = aud2 * drc_gain\n aud = np.stack((aud, aud2), axis=0) # (channels=2, samples)\n taps = taps2\n\n ## Perform dereverberation\n aud = torch.from_numpy(aud)[None] # (batch, channels, samples)\n with torch.no_grad():\n ## The input audio must be in shape (batch, channels, samples)\n enh = dnn_wpe(\n aud.to(device), delay=delay, taps=taps, dtype=dtype) # (t,)\n enh = to_arr(enh).squeeze() # convert to numpy array and squeeze\n ## Save\n if chs == 'dual':\n enh = enh[0] # only save the first channel\n # print(enh.sum())\n output_wav_path = f'data/nwpe_{chs}_taps{taps}.wav'\n sf.write(output_wav_path, data=enh, samplerate=fs)\n\n\ndef run_iterative_wpe(wpath, chs='single', n_iter=1, dtype=torch.float64):\n print(f'Running \"Iterative-WPE-{chs}\"...')\n\n ## IterativeWPE WPE\n iter_wpe = IterativeWPE(\n stft_opts=stft_opts_torch)\n\n ## Load audio and apply DRC\n aud, fs = sf.read(wpath) # (t,), 16000\n aud, drc_gain = apply_drc(aud) # (t,), ()\n\n if chs == 'single':\n aud = aud[None] # (channels=1, samples)\n taps = taps1\n if chs == 'dual':\n aud2, fs2 = sf.read(sample_wav2, dtype='float32')\n aud2 = aud2 * drc_gain\n aud = np.stack((aud, aud2), axis=0) # (channels=2, samples)\n taps = taps2\n\n ## Perform dereverberation\n aud = torch.from_numpy(aud)[None] # (batch, channels, samples)\n with torch.no_grad():\n ## The input audio must be in shape (batch, channels, samples)\n enh = iter_wpe(\n aud.to(device), delay=delay, taps=taps, dtype=dtype) # (t,)\n enh = to_arr(enh).squeeze() # convert to numpy array and squeeze\n ## Save\n if chs == 'dual':\n enh = enh[0] # only save the first channel\n output_wav_path = f'data/iwpe_{chs}_taps{taps}_iter{n_iter}.wav'\n sf.write(output_wav_path, data=enh, samplerate=fs)\n\n\n\nif __name__==\"__main__\":\n dtype = torch.float64\n\n sample_wav = 'data/AMI_WSJ20-Array1-1_T10c0201.wav'\n # sample_wav2 = 'data/AMI_WSJ20-Array1-2_T10c0201.wav'\n\n sample_wav = 'data/VOiCES_2019_Challenge_SID_eval_1327.wav' # babble noise\n # sample_wav = 'data/VOiCES_2019_Challenge_SID_eval_8058.wav' # ambient noise\n # sample_wav = 'data/VOiCES_2019_Challenge_SID_eval_11391.wav' # music + vocal\n\n\n\n ## Save DRC-applied raw signal\n aud, fs = sf.read(sample_wav) # (t,), 16000\n aud, drc_gain = apply_drc(aud) # (t,), ()\n sample_wav_drc = 'data/raw_signal.wav'\n sf.write(sample_wav_drc, data=aud, samplerate=fs)\n\n # ## Iterative WPE\n # run_iterative_wpe('single', n_iter=1, dtype=dtype)\n # ### run_iterative_wpe('dual', n_iter=1, dtype=dtype)\n\n ## Neural WPE\n run_neural_wpe(sample_wav, 'single', dtype=dtype)\n ### run_neural_wpe('dual', dtype=dtype)\n\n ## VACE-WPE\n run_vace_wpe(sample_wav, prefix='drv')\n run_vace_wpe(sample_wav, prefix='dns')\n run_vace_wpe(sample_wav, prefix='tson')\n run_vace_wpe(sample_wav, prefix='tsoc')\n run_vace_wpe(sample_wav, prefix='dr-tsoc')\n"
] | [
[
"torch.set_printoptions",
"torch.no_grad",
"numpy.random.choice",
"torch.from_numpy",
"torch.cuda.is_available",
"numpy.stack",
"torch.device"
]
] |
faridsaud/ML-Snippets | [
"4e846e7dde63480c34f51329f261aef73040b0d6"
] | [
"UnsupervisedLearning/HerarchicalClustering/Hierarchical Clustering Lab.py"
] | [
"#!/usr/bin/env python\n# coding: utf-8\n\n# # Hierarchical Clustering Lab\n# In this notebook, we will be using sklearn to conduct hierarchical clustering on the [Iris dataset](https://archive.ics.uci.edu/ml/datasets/iris) which contains 4 dimensions/attributes and 150 samples. Each sample is labeled as one of the three type of Iris flowers.\n# \n# In this exercise, we'll ignore the labeling and cluster based on the attributes, then we'll compare the results of different hierarchical clustering techniques with the original labels to see which one does a better job in this scenario. We'll then proceed to visualize the resulting cluster hierarchies.\n# \n# ## 1. Importing the Iris dataset\n# \n\n# In[1]:\n\n\nfrom sklearn import datasets\n\niris = datasets.load_iris()\n\n\n# A look at the first 10 samples in the dataset\n\n# In[2]:\n\n\niris.data[:10]\n\n\n# ```iris.target``` contains the labels that indicate which type of Iris flower each sample is\n\n# In[3]:\n\n\niris.target\n\n\n# ## 2. Clustering\n# Let's now use sklearn's ```AgglomerativeClustering``` to conduct the heirarchical clustering\n\n# In[4]:\n\n\nfrom sklearn.cluster import AgglomerativeClustering\n\n# Hierarchical clustering\n# Ward is the default linkage algorithm, so we'll start with that\nward = AgglomerativeClustering(n_clusters=3)\nward_pred = ward.fit_predict(iris.data)\n\n\n# Let's also try complete and average linkages\n# \n# **Exercise**:\n# * Conduct hierarchical clustering with complete linkage, store the predicted labels in the variable ```complete_pred```\n# * Conduct hierarchical clustering with average linkage, store the predicted labels in the variable ```avg_pred```\n\n# In[5]:\n\n\n# Hierarchical clustering using complete linkage\n# TODO: Create an instance of AgglomerativeClustering with the appropriate parameters\ncomplete = AgglomerativeClustering(n_clusters=3, linkage=\"complete\")\n# Fit & predict\n# TODO: Make AgglomerativeClustering fit the dataset and predict the cluster labels\ncomplete_pred = complete.fit_predict(iris.data)\n\n# Hierarchical clustering using average linkage\n# TODO: Create an instance of AgglomerativeClustering with the appropriate parameters\navg = AgglomerativeClustering(n_clusters=3, linkage=\"average\")\n# Fit & predict\n# TODO: Make AgglomerativeClustering fit the dataset and predict the cluster labels\navg_pred = avg.fit_predict(iris.data)\n\n\n# To determine which clustering result better matches the original labels of the samples, we can use ```adjusted_rand_score``` which is an *external cluster validation index* which results in a score between -1 and 1, where 1 means two clusterings are identical of how they grouped the samples in a dataset (regardless of what label is assigned to each cluster).\n# \n# Cluster validation indices are discussed later in the course.\n\n# In[6]:\n\n\nfrom sklearn.metrics import adjusted_rand_score\n\nward_ar_score = adjusted_rand_score(iris.target, ward_pred)\n\n\n# **Exercise**:\n# * Calculate the Adjusted Rand score of the clusters resulting from complete linkage and average linkage\n\n# In[7]:\n\n\n# TODO: Calculated the adjusted Rand score for the complete linkage clustering labels\ncomplete_ar_score = adjusted_rand_score(iris.target, complete_pred)\n\n# TODO: Calculated the adjusted Rand score for the average linkage clustering labels\navg_ar_score = adjusted_rand_score(iris.target, avg_pred)\n\n\n# Which algorithm results in the higher Adjusted Rand Score?\n\n# In[8]:\n\n\nprint( \"Scores: \\nWard:\", ward_ar_score,\"\\nComplete: \", complete_ar_score, \"\\nAverage: \", avg_ar_score)\n\n\n# ## 3. The Effect of Normalization on Clustering\n# \n# Can we improve on this clustering result?\n# \n# Let's take another look at the dataset\n\n# In[9]:\n\n\niris.data[:15]\n\n\n# Looking at this, we can see that the forth column has smaller values than the rest of the columns, and so its variance counts for less in the clustering process (since clustering is based on distance). Let us [normalize](https://en.wikipedia.org/wiki/Feature_scaling) the dataset so that each dimension lies between 0 and 1, so they have equal weight in the clustering process.\n# \n# This is done by subtracting the minimum from each column then dividing the difference by the range.\n# \n# sklearn provides us with a useful utility called ```preprocessing.normalize()``` that can do that for us\n\n# In[9]:\n\n\nfrom sklearn import preprocessing\n\nnormalized_X = preprocessing.normalize(iris.data)\nnormalized_X[:10]\n\n\n# Now all the columns are in the range between 0 and 1. Would clustering the dataset after this transformation lead to a better clustering? (one that better matches the original labels of the samples)\n\n# In[10]:\n\n\nward = AgglomerativeClustering(n_clusters=3)\nward_pred = ward.fit_predict(normalized_X)\n\ncomplete = AgglomerativeClustering(n_clusters=3, linkage=\"complete\")\ncomplete_pred = complete.fit_predict(normalized_X)\n\navg = AgglomerativeClustering(n_clusters=3, linkage=\"average\")\navg_pred = avg.fit_predict(normalized_X)\n\n\nward_ar_score = adjusted_rand_score(iris.target, ward_pred)\ncomplete_ar_score = adjusted_rand_score(iris.target, complete_pred)\navg_ar_score = adjusted_rand_score(iris.target, avg_pred)\n\nprint( \"Scores: \\nWard:\", ward_ar_score,\"\\nComplete: \", complete_ar_score, \"\\nAverage: \", avg_ar_score)\n\n\n# ## 4. Dendrogram visualization with scipy\n# \n# Let's visualize the highest scoring clustering result. \n# \n# To do that, we'll need to use Scipy's [```linkage```](https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html) function to perform the clusteirng again so we can obtain the linkage matrix it will later use to visualize the hierarchy\n\n# In[11]:\n\n\n# Import scipy's linkage function to conduct the clustering\nfrom scipy.cluster.hierarchy import linkage\n\n# Specify the linkage type. Scipy accepts 'ward', 'complete', 'average', as well as other values\n# Pick the one that resulted in the highest Adjusted Rand Score\nlinkage_type = 'ward'\n\nlinkage_matrix = linkage(normalized_X, linkage_type)\n\n\n# Plot using scipy's [dendrogram](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.cluster.hierarchy.dendrogram.html) function\n\n# In[13]:\n\n\nfrom scipy.cluster.hierarchy import dendrogram\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(22,18))\n\n# plot using 'dendrogram()'\ndendrogram(linkage_matrix)\n\nplt.show()\n\n\n# ## 5. Visualization with Seaborn's ```clustermap``` \n# \n# The [seaborn](http://seaborn.pydata.org/index.html) plotting library for python can plot a [clustermap](http://seaborn.pydata.org/generated/seaborn.clustermap.html), which is a detailed dendrogram which also visualizes the dataset in more detail. It conducts the clustering as well, so we only need to pass it the dataset and the linkage type we want, and it will use scipy internally to conduct the clustering\n\n# In[ ]:\n\n\nimport seaborn as sns\n\nsns.clustermap(normalized_X, figsize=(12,18), method=linkage_type, cmap='viridis')\n\n# Expand figsize to a value like (18, 50) if you want the sample labels to be readable\n# Draw back is that you'll need more scrolling to observe the dendrogram\n\nplt.show()\n\n\n# Looking at the colors of the dimensions can you observe how they differ between the three type of flowers? You should at least be able to notice how one is vastly different from the two others (in the top third of the image).\n\n# In[ ]:\n\n\n\n\n"
] | [
[
"scipy.cluster.hierarchy.dendrogram",
"sklearn.metrics.adjusted_rand_score",
"matplotlib.pyplot.figure",
"scipy.cluster.hierarchy.linkage",
"matplotlib.pyplot.show",
"sklearn.preprocessing.normalize",
"sklearn.cluster.AgglomerativeClustering",
"sklearn.datasets.load_iris"
]
] |
aassumpcao/tseresearch | [
"8c46a81fddee1f2a18b35a28a32dfe0a1f294750"
] | [
"scripts/10_tse_sentence_classification.py"
] | [
"### electoral crime and performance paper\n# judicial decisions script\n# this script uses the trained models to predict sentence categories. i\n# use the textual info in the sentences to determine the (class)\n# allegations against individual candidates running for office.\n# author: andre assumpcao\n# by [email protected]\n\n# import statements\nfrom sklearn.svm import LinearSVC\nfrom sklearn.externals import joblib\nimport pickle, csv\nimport pandas as pd\nimport scipy.sparse as sparse\n\n# define function to load the data\ndef load_tse():\n kwargs = {'index_col': False, 'encoding': 'utf-8'}\n df = pd.read_csv('data/tsePredictions.csv', **kwargs)\n df['classID'] = df['class'].factorize()[0]\n df = df.sort_values('classID').reset_index(drop = True)\n return df\n\n# define function to save candidateIDs\ndef save_candidateID(df):\n split = len(df[df['classID'] == -1])\n return (\n df.loc[split:, 'candidateID'].reset_index(drop = True),\n df.loc[:(split-1), 'candidateID'].reset_index(drop = True)\n )\n\n# define function to split validation and classification samples\ndef split_labels_tse(df):\n split = len(df[df['classID'] == -1])\n return (\n df.loc[split:, 'classID'].reset_index(drop = True),\n df.loc[:(split-1), 'classID'].reset_index(drop = True)\n )\n\n# define function to load features into python\ndef load_features():\n features_cv = sparse.load_npz('data/features_tfidf_cv.npz').toarray()\n features_pr = sparse.load_npz('data/features_tfidf_pr.npz').toarray()\n return features_cv, features_pr\n\n# define main program block\ndef main():\n\n # load dataset and split labels for validation and classification\n tse = load_tse()\n\n # load features for validation and classification\n labels_cv, labels_pr = split_labels_tse(tse)\n\n # save candidateIDs\n id_cv, id_pr = save_candidateID(tse)\n\n # load features for validation and classification\n features_cv, features_pr = load_features()\n\n # load linear SVC model\n model = joblib.load('data/LinearSVC.pkl')\n\n # predict classes\n y_pred = model.predict(features_pr)\n\n # check dimensions of all prediction files\n len(labels_pr) == len(id_pr) == len(features_pr) == len(y_pred)\n\n # create new datasets with observed and predicted classes\n tseObserved = pd.DataFrame({'class': labels_cv, 'candidateID': id_cv})\n tsePredicted = pd.DataFrame({'class': y_pred, 'candidateID': id_pr})\n\n # create new dataset with the class probability from dnn model\n tseClasses = pd.concat([tseObserved, tsePredicted], ignore_index = True)\n\n # save to file\n kwargs = {'index': False, 'quoting': csv.QUOTE_ALL}\n tseClasses.to_csv('data/tseClasses.csv', **kwargs)\n\n# define main program block\nif __name__ == '__main__':\n main()\n"
] | [
[
"pandas.read_csv",
"pandas.DataFrame",
"scipy.sparse.load_npz",
"sklearn.externals.joblib.load",
"pandas.concat"
]
] |
tylertownsend/bingo | [
"0aeebe03df71a632f833c56ceb9c697dddbe78fc"
] | [
"tests/Base/test_continuous_local_optimization.py"
] | [
"# Ignoring some linting rules in tests\n# pylint: disable=redefined-outer-name\n# pylint: disable=missing-docstring\nimport pytest\nimport numpy as np\n\nfrom bingo.Base.FitnessFunction import FitnessFunction, VectorBasedFunction\nfrom bingo.Base.ContinuousLocalOptimization import ContinuousLocalOptimization\nfrom bingo.Base.MultipleFloats import MultipleFloatChromosome\n\nNUM_VALS = 10\nNUM_OPT = 3\n\n\nclass MultipleFloatValueFitnessFunction(FitnessFunction):\n def __call__(self, individual):\n print(individual)\n return np.linalg.norm(individual.values)\n\n\nclass FloatVectorFitnessFunction(VectorBasedFunction):\n def _evaluate_fitness_vector(self, individual):\n vals = individual.values\n return [x - 0 for x in vals]\n\n\[email protected]\ndef opt_individual():\n vals = [1. for _ in range(NUM_VALS)]\n return MultipleFloatChromosome(vals, [1, 3, 4])\n\n\[email protected]\ndef reg_individual():\n vals = [1. for _ in range(NUM_VALS)]\n return MultipleFloatChromosome(vals)\n\n\[email protected](\"algorithm\", [\n 'Nelder-Mead',\n 'Powell',\n 'CG',\n 'BFGS',\n # 'Newton-CG',\n 'L-BFGS-B',\n # 'TNC',\n # 'COBYLA',\n 'SLSQP'\n # 'trust-constr'\n # 'dogleg',\n # 'trust-ncg',\n # 'trust-exact',\n # 'trust-krylov'\n])\ndef test_optimize_params(opt_individual, reg_individual, algorithm):\n fitness_function = MultipleFloatValueFitnessFunction()\n local_opt_fitness_function = ContinuousLocalOptimization(\n fitness_function, algorithm)\n opt_indv_fitness = local_opt_fitness_function(opt_individual)\n reg_indv_fitness = local_opt_fitness_function(reg_individual)\n assert opt_indv_fitness == pytest.approx(np.sqrt(NUM_VALS - NUM_OPT))\n assert reg_indv_fitness == pytest.approx(np.sqrt(NUM_VALS))\n\n\[email protected](\"algorithm\", [\n # 'hybr',\n 'lm'\n # 'broyden1',\n # 'broyden2',\n # 'anderson',\n # 'linearmixing',\n # 'diagbroyden',\n # 'excitingmixing',\n # 'krylov',\n # 'df-sane'\n])\ndef test_optimize_fitness_vector(opt_individual, reg_individual, algorithm):\n reg_list = [1. for _ in range(NUM_VALS)]\n opt_list = [1. for _ in range(NUM_VALS)]\n opt_list[:3] = [0., 0., 0.]\n fitness_function = FloatVectorFitnessFunction()\n local_opt_fitness_function = ContinuousLocalOptimization(\n fitness_function, algorithm)\n opt_indv_fitness = local_opt_fitness_function(opt_individual)\n reg_indv_fitness = local_opt_fitness_function(reg_individual)\n assert opt_indv_fitness == pytest.approx(np.mean(opt_list))\n assert reg_indv_fitness == pytest.approx(np.mean(reg_list))\n\n\ndef test_valid_fitness_function():\n fitness_function = MultipleFloatValueFitnessFunction()\n with pytest.raises(TypeError):\n ContinuousLocalOptimization(fitness_function, algorithm='lm')\n\n\ndef test_not_valid_algorithm():\n fitness_function = MultipleFloatValueFitnessFunction()\n with pytest.raises(KeyError):\n ContinuousLocalOptimization(fitness_function,\n algorithm='Dwayne - The Rock - Johnson')\n\n\ndef test_get_eval_count_pass_through():\n fitness_function = MultipleFloatValueFitnessFunction()\n fitness_function.eval_count = 123\n local_opt_fitness_function = \\\n ContinuousLocalOptimization(fitness_function, \"Powell\")\n assert local_opt_fitness_function.eval_count == 123\n\n\ndef test_set_eval_count_pass_through():\n fitness_function = MultipleFloatValueFitnessFunction()\n local_opt_fitness_function = \\\n ContinuousLocalOptimization(fitness_function, \"Powell\")\n local_opt_fitness_function.eval_count = 123\n assert fitness_function.eval_count == 123\n\n\ndef test_get_training_data_pass_through():\n fitness_function = MultipleFloatValueFitnessFunction()\n fitness_function.training_data = 123\n local_opt_fitness_function = \\\n ContinuousLocalOptimization(fitness_function, \"Powell\")\n assert local_opt_fitness_function.training_data == 123\n\n\ndef test_set_training_data_pass_through():\n fitness_function = MultipleFloatValueFitnessFunction()\n local_opt_fitness_function = \\\n ContinuousLocalOptimization(fitness_function, \"Powell\")\n local_opt_fitness_function.training_data = 123\n assert fitness_function.training_data == 123\n"
] | [
[
"numpy.sqrt",
"numpy.linalg.norm",
"numpy.mean"
]
] |
ruizca/astromatch | [
"14fa56768149d0d292b939248560210c17d6d3b1"
] | [
"astromatch/priors.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nastromatch module for calculation of magnitude priors.\n\n@author: A.Ruiz\n\"\"\"\nimport os\nimport warnings\n\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.table import Table\nfrom astropy.utils.exceptions import AstropyUserWarning\nfrom scipy.interpolate import interp1d\nfrom scipy.ndimage import convolve\n\n\nfrom .catalogues import Catalogue\n\n\nclass Prior(object):\n \"\"\"\n Class for probability priors.\n \"\"\"\n\n def __init__(\n self,\n pcat=None,\n scat=None,\n rndcat=True,\n radius=5*u.arcsec,\n magmin='auto',\n magmax='auto',\n magbinsize='auto',\n match_mags=None,\n prior_dict=None\n ):\n \"\"\"\n Estimates the prior probability distribution for a source in the\n primary catalogue `pcat` having a counterpart in the secondary\n catalogue `scat` with magnitude m.\n\n The a priori probability is determined as follows. First, we estimate\n the magnitude distribution of the spurious matches and it is scaled\n to the area within which we search for counterparts. This is then\n subtracted from the magnitude distribution of all counterparts in the\n secondary catalogue to determine the magnitude distribution of the\n true associations.\n\n Parameters\n ----------\n pcat, scat : ``Catalogue``\n rndcat : `boolean`, optional\n We implemented two methods for estimating the magnitude distribution\n of spurious matches: If 'rndcat' is ``False``, it removes all sources\n in the secondary catalogue within one arcmin of the positions of the\n primary sources. The magnitude distribution of the remaining sources,\n divided by the remaining catalogue area, corresponds to the\n probability distribution of a spurious match per magnitude and per\n square degree.\n If 'rndcat' is ``True``, it generates a catalogue of random\n positions away from the primary sources and searchs for all available\n counterparts in the secondary catalogue. The magnitude distribution\n of these sources corresponds to the probability distribution of a\n spurious match.\n radius : Astropy ``Quantity``, optional\n Distance limit used for searching counterparts in the secondary\n catalogue in angular units. Default to 5 arcsec.\n magmin : `float` or 'auto', optional\n Lower magnitude limit when estimating magnitude distributions.\n Default to 'auto'.\n magmax : `float` or 'auto', optional\n Upper magnitude limit when estimating magnitude distributions.\n Default to 'auto'.\n magbinsize : `float` or 'auto', optional\n Magnitude bin width when estimating magnitude distributions.\n Default to 'auto'.\n \"\"\"\n if prior_dict is None:\n self._from_catalogues(pcat, scat, match_mags, rndcat,\n radius, magmin, magmax, magbinsize)\n else:\n self.prior_dict = prior_dict\n self.rndcat = None\n\n def _from_catalogues(self, pcat, scat, match_mags, rndcat,\n radius, magmin, magmax, magbinsize):\n if None in [pcat, scat]:\n raise ValueError('Two Catalogues must be passed!')\n\n if rndcat is True:\n self.rndcat = pcat.randomise()\n\n elif isinstance(rndcat, Catalogue):\n self.rndcat = rndcat\n\n else:\n message = 'Using mask method for the prior calculation.'\n warnings.warn(message, AstropyUserWarning)\n self.rndcat = None\n\n if match_mags is None:\n match_mags = self._get_match_mags(pcat, scat, radius)\n\n self.prior_dict = self._calc_prior_dict(\n pcat, scat, radius, match_mags, magmin, magmax, magbinsize\n )\n\n @property\n def magnames(self):\n return list(self.prior_dict.keys())\n\n @classmethod\n def from_nway_hists(cls, cat, renorm_factors, path='.'):\n \"\"\"\n Create a ``Prior`` object using nway histogram files.\n \"\"\"\n prior_dict = {}\n for mag in cat.mags.colnames:\n filename = '{}_{}_fit.txt'.format(cat.name, mag)\n filename = os.path.join(path, filename)\n prior_dict[mag] = cls._from_nway_maghist(filename, renorm_factors[mag])\n\n return cls(prior_dict=prior_dict)\n\n @classmethod\n def from_table(cls, priors_table, magnames):\n \"\"\"\n Create a ``Prior`` object using an Astropy Table.\n\n Parameters\n ----------\n priors_table : `str` or ``Table``\n Astropy table with the prior values or, alternatively,\n a file path containing a table in a format readable by Astropy.\n Note: If the table does not include priors for \"field\" sources,\n they are set to zero.\n magnames : `list`\n Magnitude names.\n \"\"\"\n if not isinstance(priors_table, Table):\n priors_table = Table.read(priors_table)\n\n # TODO: how to do this when magbinsize is 'auto'\n bins = cls._midvals_to_bins(priors_table['MAG'])\n\n prior_dict = {}\n for mag in magnames:\n maghist = {}\n maghist['bins'] = bins\n maghist['target'] = priors_table['PRIOR_' + mag].data\n\n try:\n maghist['field'] = priors_table['PRIOR_BKG_' + mag].data\n except KeyError:\n maghist['field'] = np.zeros_like(bins)\n\n message = 'Field prior for {} set to zero.'.format(mag)\n warnings.warn(message, AstropyUserWarning)\n\n prior_dict[mag] = maghist\n\n return cls(prior_dict=prior_dict)\n\n def to_nway_hists(self, output_path=None):\n \"\"\"\n Returns a dictionary with the prior histograms in\n a format compatible with nway. If `output_path` is not ``None``,\n a text file is created with a formatting compatible with nway.\n \"\"\"\n nhists = []\n for magcol in self.magnames:\n if output_path is not None:\n filename = '{}_{}_fit.txt'.format(self.scat.name, magcol)\n filename = os.path.join(output_path, filename)\n else:\n filename = None\n\n maghist = self._to_nway_maghist(self.prior_dict[magcol], filename)\n nhists.append(maghist)\n\n return nhists\n\n def interp(self, mags, magcol):\n \"\"\"\n Return the prior at magnitude values `mags` for magnitude `magcol`.\n\n Parameters\n ----------\n \"\"\"\n if magcol not in self.prior_dict:\n raise ValueError('Unknown magcol: {}'.format(magcol))\n\n bins = self.bins_midvals(magcol)\n prior = self.prior_dict[magcol]\n\n itp = interp1d(\n bins, prior['target'], kind='nearest', fill_value=0, bounds_error=False\n )\n pvals = itp(mags)\n\n return pvals\n\n def qcap(self, magcol):\n \"\"\"\n Overall identification ratio for magnitude `magcol`\n between the two catalogues used to build the prior.\n \"\"\"\n if magcol not in self.prior_dict:\n raise ValueError('Unknown magcol: {}'.format(magcol))\n\n prior = self.prior_dict[magcol]\n\n # Whatch out prior is dN/dm,\n # i.e. I have divided by dm so it is probability density and\n # Sum(dN/dm*dm)=Q ie the overall identification ratio (not 1)\n return np.sum(prior['target'] * np.diff(prior['bins']))\n\n def bins_midvals(self, magcol):\n if magcol not in self.prior_dict:\n raise ValueError('Unknown magcol: {}'.format(magcol))\n\n edges = self.prior_dict[magcol]['bins']\n\n return (edges[1:] + edges[:-1])/2\n\n def to_table(self, include_bkg_priors=False):\n \"\"\"\n Dump prior data into an Astropy Table.\n \"\"\"\n # TODO: how to build this table when magbinsize is 'auto'\n priors_table = Table()\n priors_table['MAG'] = self.bins_midvals(self.magnames[0])\n for mag in self.magnames:\n priors_table['PRIOR_' + mag] = self.prior_dict[mag]['target']\n\n if include_bkg_priors:\n priors_table['PRIOR_BKG_' + mag] = self.prior_dict[mag]['field']\n\n return priors_table\n\n def plot(self, magname, filename=None):\n \"\"\"\n Plot priors for magnitude `magname`.\n\n Parameters\n \"\"\"\n import matplotlib.pyplot as plt\n\n mbins = self.bins_midvals(magname)\n prior = self.prior_dict[magname]\n\n plt.plot(mbins, prior['target'])\n plt.plot(mbins, prior['field'])\n plt.title(magname)\n\n if filename is None:\n plt.show()\n else:\n plt.savefig(filename)\n plt.close()\n\n\n def _get_match_mags(self, pcat, scat, radius):\n _, idx_near, _, _ = scat.coords.search_around_sky(pcat.coords, radius)\n\n return scat.mags[idx_near]\n\n def _calc_prior_dict(\n self,\n pcat,\n scat,\n radius,\n match_mags,\n magmin,\n magmax,\n magbinsize,\n mask_radius=1*u.arcmin\n ):\n if self.rndcat is None:\n field_cat = self._field_sources(pcat, scat, mask_radius)\n else:\n field_cat = self._random_sources(scat, radius)\n\n renorm_factor = len(pcat) * np.pi*radius**2 / field_cat.area # area_match / area field\n\n prior_dict = {}\n for magcol in match_mags.colnames:\n target_mags = match_mags[magcol]\n field_mags = field_cat.mags[magcol]\n prior_dict[magcol] = self._mag_hist(\n len(pcat), target_mags, field_mags, renorm_factor, magmin, magmax, magbinsize\n )\n return prior_dict\n\n def _field_sources(self, pcat, scat, mask_radius):\n # Find sources within the mask_radius\n pcoords = pcat.coords\n scoords = scat.coords\n _, idx_near, _, _ = scoords.search_around_sky(pcoords, mask_radius)\n\n # Select all sources but those within the mask_radius\n idx_all = range(len(scat))\n idx_far = list(set(idx_all) - set(idx_near))\n field_cat = scat[idx_far]\n\n # Area covered by the new catalogue\n field_cat.area = scat.area - len(pcat)*np.pi*mask_radius**2\n field_cat.moc = None\n\n return field_cat\n\n def _random_sources(self, scat, radius):\n assert self.rndcat is not None\n\n # Select sources from the secondary catalogue within radius of random sources\n pcoords = self.rndcat.coords\n scoords = scat.coords\n _, sidx, _, _ = scoords.search_around_sky(pcoords, radius)\n rnd_scat = scat[sidx]\n\n # Area covered by the new catalogue\n rnd_scat.area = len(self.rndcat)*np.pi*radius**2\n rnd_scat.moc = None\n\n return rnd_scat\n\n def _mag_hist(\n self,\n pcat_nsources,\n target_mags,\n field_mags,\n renorm_factor,\n magmin,\n magmax,\n magbinsize\n ):\n if magmin == 'auto':\n magmin = np.nanmin(target_mags)\n\n if magmax == 'auto':\n magmax = np.nanmax(target_mags)\n\n bins, magrange = _define_magbins(magmin, magmax, magbinsize)\n target_counts, bins = np.histogram(target_mags, range=magrange, bins=bins)\n field_counts, _ = np.histogram(field_mags, range=magrange, bins=bins)\n magbinsize = np.diff(bins)\n\n target_prior = target_counts - field_counts * renorm_factor\n target_prior[target_prior < 0] = 0.0\n # TODO: calculate general values for the convolution parameters\n # (magbinsize dependent)\n target_prior = convolve(target_prior, [0.25, 0.5, 0.25])\n # target_prior = convolve(target_prior, [magbinsize[0]/2., magbinsize[0], magbinsize[0]/2.])\n\n # renormalise here to 0.999 in case\n # prior sums to a value above unit\n # Not unit because then zeros in Reliability\n # estimation, i.e. (1-QCAP) term\n# test = target_prior.sum() / len(self.pcat)\n# if test > 1:\n# target_prior = 0.999 * target_prior / test\n\n maghist = {\n 'bins': bins,\n 'target': target_prior / pcat_nsources / magbinsize,\n 'field': 1.0*field_counts / len(field_mags) / magbinsize,\n }\n\n return maghist\n\n @staticmethod\n def _to_nway_maghist(maghist, filename=None):\n nrows = maghist['target'].size\n\n hist_data = np.zeros((nrows, 4))\n hist_data[:, 0] = maghist['bins'][:-1]\n hist_data[:, 1] = maghist['bins'][1:]\n hist_data[:, 2] = (\n maghist['target'] / np.sum(maghist['target'] * np.diff(maghist['bins']))\n )\n hist_data[:, 3] = maghist['field']\n\n if filename is not None:\n header = '{}\\nlo hi selected others'.format(filename)\n np.savetxt(filename, hist_data, fmt='%10.5f', header=header)\n\n return [row for row in hist_data.T]\n\n @staticmethod\n def _from_nway_maghist(filename, renorm_factor):\n hist_data = Table.read(filename, format='ascii')\n\n maghist = {\n 'bins': np.concatenate((hist_data['lo'], [hist_data['hi'][-1]])),\n 'target': renorm_factor * hist_data['selected'].data,\n 'field': hist_data['others'].data,\n }\n\n return maghist\n\n # @staticmethod\n # def _midvals_to_bins(midvals):\n # dbins = np.diff(midvals) / 2\n # bins_lo = set(midvals[:-1] - dbins)\n # bins_hi = set(midvals[1:] + dbins)\n # bins = np.array(list(bins_lo.union(bins_hi)))\n # bins.sort()\n\n # return bins\n\n @staticmethod\n def _midvals_to_bins(midvals):\n dbins = np.diff(midvals) / 2\n bins = np.zeros_like(midvals)\n bins[1:] = midvals[1:] + dbins\n bins[0] = midvals[0] - dbins[0]\n\n return bins\n\n\nclass BKGpdf(object):\n\n def __init__(self, cat, magmin='auto', magmax='auto', magbinsize='auto'):\n \"\"\"\n Magnitude probability distribution of sources in ``Catalogue`` 'cat'.\n\n Parameters\n ----------\n cat : ``Catalogue``\n ``Catalogue`` object.\n magmin : `float` or 'auto', optional\n Lower magnitude limit when estimating magnitude distributions.\n Default to 'auto'.\n magmax : `float` or 'auto', optional\n Upper magnitude limit when estimating magnitude distributions.\n Default to 'auto'.\n magbinsize : `float` or 'auto', optional\n Magnitude bin width when estimating magnitude distributions.\n Default to 'auto'.\n\n Return\n ------\n bkg : Astropy ``Table``\n Table with the background probability distribution for each\n available magnitude in the secondary catalogue.\n \"\"\"\n if cat.mags is None:\n raise ValueError('No magnitudes defined in the catalogue!')\n\n #self.magnames = self._set_magnames(cat)\n self.pdf_dict = self._calc_pdf(cat, magmin, magmax, magbinsize)\n\n @property\n def magnames(self):\n return list(self.pdf_dict.keys())\n\n def bins_midvals(self, magcol):\n edges = self.pdf_dict[magcol]['bins']\n\n return (edges[1:] + edges[:-1])/2\n\n def interp(self, mags, magcol):\n assert magcol in self.pdf_dict\n\n bins = self.bins_midvals(magcol)\n pdf = self.pdf_dict[magcol]['pdf']\n itp = interp1d(\n bins, pdf, kind='nearest', fill_value=np.inf, bounds_error=False\n )\n # We use inf as fill_value because these results are mostly used\n # as divisor (e.g. LR method), this way we avoid dividing by zero.\n\n return itp(mags)\n\n def to_table(self):\n # TODO: how to build this table when magbinsize is 'auto'\n pdf_table = Table()\n pdf_table['MAG'] = self.bins_midvals(self.magnames[0])\n for mag in self.magnames:\n pdf_table['BKG_' + mag] = self.pdf_dict[mag]['pdf']\n\n return pdf_table\n\n def _set_magnames(self, cat):\n return cat.mags.colnames\n\n def _calc_pdf(self, cat, magmin, magmax, magbinsize):\n mags = cat.mags\n area = cat.area.to(u.arcsec**2)\n\n pdf_dict = {}\n for magcol in mags.colnames:\n pdf_dict[magcol] = self._mag_hist(\n mags[magcol], area, magmin, magmax, magbinsize\n )\n\n return pdf_dict\n\n def _mag_hist(self, mags, area, magmin, magmax, magbinsize):\n\n if magmin == 'auto':\n magmin = np.nanmin(mags)\n\n if magmax == 'auto':\n magmax = np.nanmax(mags)\n\n bins, magrange = _define_magbins(magmin, magmax, magbinsize)\n counts, bins = np.histogram(mags, range=magrange, bins=bins)\n magbinsize = np.diff(bins)\n\n maghist = {}\n maghist['bins'] = bins\n maghist['pdf'] = counts / magbinsize / area ## in arcsec**2!!!\n\n return maghist\n\n\ndef _define_magbins(magmin, magmax, magbinsize):\n if magbinsize == 'auto':\n bins = 'auto'\n else:\n nbins = 1 + int((magmax - magmin)/magbinsize)\n bins = np.linspace(magmin, magmax, num=nbins)\n\n limits = (magmin, magmax)\n\n return bins, limits"
] | [
[
"numpy.zeros_like",
"scipy.interpolate.interp1d",
"numpy.nanmax",
"numpy.zeros",
"numpy.diff",
"numpy.histogram",
"matplotlib.pyplot.savefig",
"numpy.savetxt",
"scipy.ndimage.convolve",
"numpy.nanmin",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.close",
"matplotlib.pyplot.plot",
"numpy.concatenate",
"numpy.linspace"
]
] |
predictive-analytics-lab/pgmpy | [
"6c2a31641adc72793acd130d007190fdb1632271"
] | [
"pgmpy/factors/discrete/JointProbabilityDistribution.py"
] | [
"import itertools\nfrom operator import mul\n\nimport numpy as np\n\nfrom pgmpy.factors.discrete import DiscreteFactor\nfrom pgmpy.independencies import Independencies\nfrom pgmpy.extern.six.moves import range, zip\nfrom pgmpy.extern import six\n\n\nclass JointProbabilityDistribution(DiscreteFactor):\n \"\"\"\n Base class for Joint Probability Distribution\n\n Public Methods\n --------------\n conditional_distribution(values)\n create_bayesian_model()\n get_independencies()\n pmap()\n marginal_distribution(variables)\n minimal_imap()\n is_imap(model)\n \"\"\"\n\n def __init__(self, variables, cardinality, values):\n \"\"\"\n Initialize a Joint Probability Distribution class.\n\n Defined above, we have the following mapping from variable\n assignments to the index of the row vector in the value field:\n\n +-----+-----+-----+-------------------------+\n | x1 | x2 | x3 | P(x1, x2, x2) |\n +-----+-----+-----+-------------------------+\n | x1_0| x2_0| x3_0| P(x1_0, x2_0, x3_0) |\n +-----+-----+-----+-------------------------+\n | x1_1| x2_0| x3_0| P(x1_1, x2_0, x3_0) |\n +-----+-----+-----+-------------------------+\n | x1_0| x2_1| x3_0| P(x1_0, x2_1, x3_0) |\n +-----+-----+-----+-------------------------+\n | x1_1| x2_1| x3_0| P(x1_1, x2_1, x3_0) |\n +-----+-----+-----+-------------------------+\n | x1_0| x2_0| x3_1| P(x1_0, x2_0, x3_1) |\n +-----+-----+-----+-------------------------+\n | x1_1| x2_0| x3_1| P(x1_1, x2_0, x3_1) |\n +-----+-----+-----+-------------------------+\n | x1_0| x2_1| x3_1| P(x1_0, x2_1, x3_1) |\n +-----+-----+-----+-------------------------+\n | x1_1| x2_1| x3_1| P(x1_1, x2_1, x3_1) |\n +-----+-----+-----+-------------------------+\n\n Parameters\n ----------\n variables: list\n List of scope of Joint Probability Distribution.\n cardinality: list, array_like\n List of cardinality of each variable\n value: list, array_like\n List or array of values of factor.\n A Joint Probability Distribution's values are stored in a row\n vector in the value using an ordering such that the left-most\n variables as defined in the variable field cycle through their\n values the fastest.\n\n Examples\n --------\n >>> import numpy as np\n >>> from pgmpy.factors.discrete import JointProbabilityDistribution\n >>> prob = JointProbabilityDistribution(['x1', 'x2', 'x3'], [2, 2, 2], np.ones(8)/8)\n >>> print(prob)\n x1 x2 x3 P(x1,x2,x3)\n ---- ---- ---- -------------\n x1_0 x2_0 x3_0 0.1250\n x1_0 x2_0 x3_1 0.1250\n x1_0 x2_1 x3_0 0.1250\n x1_0 x2_1 x3_1 0.1250\n x1_1 x2_0 x3_0 0.1250\n x1_1 x2_0 x3_1 0.1250\n x1_1 x2_1 x3_0 0.1250\n x1_1 x2_1 x3_1 0.1250\n \"\"\"\n if np.isclose(np.sum(values), 1):\n super(JointProbabilityDistribution, self).__init__(variables, cardinality, values)\n else:\n raise ValueError(\"The probability values doesn't sum to 1.\")\n\n def __repr__(self):\n var_card = \", \".join(\n [\n \"{var}:{card}\".format(var=var, card=card)\n for var, card in zip(self.variables, self.cardinality)\n ]\n )\n return \"<Joint Distribution representing P({var_card}) at {address}>\".format(\n address=hex(id(self)), var_card=var_card\n )\n\n def __str__(self):\n if six.PY2:\n return self._str(phi_or_p=\"P\", tablefmt=\"pqsl\")\n else:\n return self._str(phi_or_p=\"P\")\n\n def marginal_distribution(self, variables, inplace=True):\n \"\"\"\n Returns the marginal distribution over variables.\n\n Parameters\n ----------\n variables: string, list, tuple, set, dict\n Variable or list of variables over which marginal distribution needs\n to be calculated\n inplace: Boolean (default True)\n If False return a new instance of JointProbabilityDistribution\n\n Examples\n --------\n >>> import numpy as np\n >>> from pgmpy.factors.discrete import JointProbabilityDistribution\n >>> values = np.random.rand(12)\n >>> prob = JointProbabilityDistribution(['x1', 'x2', 'x3'], [2, 3, 2], values/np.sum(values))\n >>> prob.marginal_distribution(['x1', 'x2'])\n >>> print(prob)\n x1 x2 P(x1,x2)\n ---- ---- ----------\n x1_0 x2_0 0.1502\n x1_0 x2_1 0.1626\n x1_0 x2_2 0.1197\n x1_1 x2_0 0.2339\n x1_1 x2_1 0.1996\n x1_1 x2_2 0.1340\n \"\"\"\n return self.marginalize(\n list(\n set(list(self.variables))\n - set(variables if isinstance(variables, (list, set, dict, tuple)) else [variables])\n ),\n inplace=inplace,\n )\n\n def check_independence(self, event1, event2, event3=None, condition_random_variable=False):\n \"\"\"\n Check if the Joint Probability Distribution satisfies the given independence condition.\n\n Parameters\n ----------\n event1: list\n random variable whose independence is to be checked.\n event2: list\n random variable from which event1 is independent.\n values: 2D array or list like or 1D array or list like\n A 2D list of tuples of the form (variable_name, variable_state).\n A 1D list or array-like to condition over randome variables (condition_random_variable must be True)\n The values on which to condition the Joint Probability Distribution.\n condition_random_variable: Boolean (Default false)\n If true and event3 is not None than will check independence condition over random variable.\n\n For random variables say X, Y, Z to check if X is independent of Y given Z.\n event1 should be either X or Y.\n event2 should be either Y or X.\n event3 should Z.\n\n Examples\n --------\n >>> from pgmpy.factors.discrete import JointProbabilityDistribution as JPD\n >>> prob = JPD(['I','D','G'],[2,2,3],\n [0.126,0.168,0.126,0.009,0.045,0.126,0.252,0.0224,0.0056,0.06,0.036,0.024])\n >>> prob.check_independence(['I'], ['D'])\n True\n >>> prob.check_independence(['I'], ['D'], [('G', 1)]) # Conditioning over G_1\n False\n >>> # Conditioning over random variable G\n >>> prob.check_independence(['I'], ['D'], ('G',), condition_random_variable=True)\n False\n \"\"\"\n JPD = self.copy()\n if isinstance(event1, six.string_types):\n raise TypeError(\"Event 1 should be a list or array-like structure\")\n\n if isinstance(event2, six.string_types):\n raise TypeError(\"Event 2 should be a list or array-like structure\")\n\n if event3:\n if isinstance(event3, six.string_types):\n raise TypeError(\"Event 3 cannot of type string\")\n\n elif condition_random_variable:\n if not all(isinstance(var, six.string_types) for var in event3):\n raise TypeError(\"Event3 should be a 1d list of strings\")\n event3 = list(event3)\n # Using the definition of conditional independence\n # If P(X,Y|Z) = P(X|Z)*P(Y|Z)\n # This can be expanded to P(X,Y,Z)*P(Z) == P(X,Z)*P(Y,Z)\n phi_z = JPD.marginal_distribution(event3, inplace=False).to_factor()\n for variable_pair in itertools.product(event1, event2):\n phi_xyz = JPD.marginal_distribution(\n event3 + list(variable_pair), inplace=False\n ).to_factor()\n phi_xz = JPD.marginal_distribution(\n event3 + [variable_pair[0]], inplace=False\n ).to_factor()\n phi_yz = JPD.marginal_distribution(\n event3 + [variable_pair[1]], inplace=False\n ).to_factor()\n if phi_xyz * phi_z != phi_xz * phi_yz:\n return False\n return True\n else:\n JPD.conditional_distribution(event3)\n\n for variable_pair in itertools.product(event1, event2):\n if JPD.marginal_distribution(variable_pair, inplace=False) != JPD.marginal_distribution(\n variable_pair[0], inplace=False\n ) * JPD.marginal_distribution(variable_pair[1], inplace=False):\n return False\n return True\n\n def get_independencies(self, condition=None):\n \"\"\"\n Returns the independent variables in the joint probability distribution.\n Returns marginally independent variables if condition=None.\n Returns conditionally independent variables if condition!=None\n\n Parameter\n ---------\n condition: array_like\n Random Variable on which to condition the Joint Probability Distribution.\n\n Examples\n --------\n >>> import numpy as np\n >>> from pgmpy.factors.discrete import JointProbabilityDistribution\n >>> prob = JointProbabilityDistribution(['x1', 'x2', 'x3'], [2, 3, 2], np.ones(12)/12)\n >>> prob.get_independencies()\n (x1 _|_ x2)\n (x1 _|_ x3)\n (x2 _|_ x3)\n \"\"\"\n JPD = self.copy()\n if condition:\n JPD.conditional_distribution(condition)\n independencies = Independencies()\n for variable_pair in itertools.combinations(list(JPD.variables), 2):\n if JPD.marginal_distribution(variable_pair, inplace=False) == JPD.marginal_distribution(\n variable_pair[0], inplace=False\n ) * JPD.marginal_distribution(variable_pair[1], inplace=False):\n independencies.add_assertions(variable_pair)\n return independencies\n\n def conditional_distribution(self, values, inplace=True):\n \"\"\"\n Returns Conditional Probability Distribution after setting values to 1.\n\n Parameters\n ----------\n values: list or array_like\n A list of tuples of the form (variable_name, variable_state).\n The values on which to condition the Joint Probability Distribution.\n inplace: Boolean (default True)\n If False returns a new instance of JointProbabilityDistribution\n\n Examples\n --------\n >>> import numpy as np\n >>> from pgmpy.factors.discrete import JointProbabilityDistribution\n >>> prob = JointProbabilityDistribution(['x1', 'x2', 'x3'], [2, 2, 2], np.ones(8)/8)\n >>> prob.conditional_distribution([('x1', 1)])\n >>> print(prob)\n x2 x3 P(x2,x3)\n ---- ---- ----------\n x2_0 x3_0 0.2500\n x2_0 x3_1 0.2500\n x2_1 x3_0 0.2500\n x2_1 x3_1 0.2500\n \"\"\"\n JPD = self if inplace else self.copy()\n JPD.reduce(values)\n JPD.normalize()\n if not inplace:\n return JPD\n\n def copy(self):\n \"\"\"\n Returns A copy of JointProbabilityDistribution object\n\n Examples\n ---------\n >>> import numpy as np\n >>> from pgmpy.factors.discrete import JointProbabilityDistribution\n >>> prob = JointProbabilityDistribution(['x1', 'x2', 'x3'], [2, 3, 2], np.ones(12)/12)\n >>> prob_copy = prob.copy()\n >>> prob_copy.values == prob.values\n True\n >>> prob_copy.variables == prob.variables\n True\n >>> prob_copy.variables[1] = 'y'\n >>> prob_copy.variables == prob.variables\n False\n \"\"\"\n return JointProbabilityDistribution(self.scope(), self.cardinality, self.values)\n\n def minimal_imap(self, order):\n \"\"\"\n Returns a Bayesian Model which is minimal IMap of the Joint Probability Distribution\n considering the order of the variables.\n\n Parameters\n ----------\n order: array-like\n The order of the random variables.\n\n Examples\n --------\n >>> import numpy as np\n >>> from pgmpy.factors.discrete import JointProbabilityDistribution\n >>> prob = JointProbabilityDistribution(['x1', 'x2', 'x3'], [2, 3, 2], np.ones(12)/12)\n >>> bayesian_model = prob.minimal_imap(order=['x2', 'x1', 'x3'])\n >>> bayesian_model\n <pgmpy.models.models.models at 0x7fd7440a9320>\n >>> bayesian_model.edges()\n [('x1', 'x3'), ('x2', 'x3')]\n \"\"\"\n from pgmpy.models import BayesianModel\n\n def get_subsets(u):\n for r in range(len(u) + 1):\n for i in itertools.combinations(u, r):\n yield i\n\n G = BayesianModel()\n for variable_index in range(len(order)):\n u = order[:variable_index]\n for subset in get_subsets(u):\n if len(subset) < len(u) and self.check_independence(\n [order[variable_index]], set(u) - set(subset), subset, True\n ):\n G.add_edges_from([(variable, order[variable_index]) for variable in subset])\n return G\n\n def is_imap(self, model):\n \"\"\"\n Checks whether the given BayesianModel is Imap of JointProbabilityDistribution\n\n Parameters\n -----------\n model : An instance of BayesianModel Class, for which you want to\n check the Imap\n\n Returns\n --------\n boolean : True if given bayesian model is Imap for Joint Probability Distribution\n False otherwise\n Examples\n --------\n >>> from pgmpy.models import BayesianModel\n >>> from pgmpy.factors.discrete import TabularCPD\n >>> from pgmpy.factors.discrete import JointProbabilityDistribution\n >>> bm = BayesianModel([('diff', 'grade'), ('intel', 'grade')])\n >>> diff_cpd = TabularCPD('diff', 2, [[0.2], [0.8]])\n >>> intel_cpd = TabularCPD('intel', 3, [[0.5], [0.3], [0.2]])\n >>> grade_cpd = TabularCPD('grade', 3,\n ... [[0.1,0.1,0.1,0.1,0.1,0.1],\n ... [0.1,0.1,0.1,0.1,0.1,0.1],\n ... [0.8,0.8,0.8,0.8,0.8,0.8]],\n ... evidence=['diff', 'intel'],\n ... evidence_card=[2, 3])\n >>> bm.add_cpds(diff_cpd, intel_cpd, grade_cpd)\n >>> val = [0.01, 0.01, 0.08, 0.006, 0.006, 0.048, 0.004, 0.004, 0.032,\n 0.04, 0.04, 0.32, 0.024, 0.024, 0.192, 0.016, 0.016, 0.128]\n >>> JPD = JointProbabilityDistribution(['diff', 'intel', 'grade'], [2, 3, 3], val)\n >>> JPD.is_imap(bm)\n True\n \"\"\"\n from pgmpy.models import BayesianModel\n\n if not isinstance(model, BayesianModel):\n raise TypeError(\"model must be an instance of BayesianModel\")\n factors = [cpd.to_factor() for cpd in model.get_cpds()]\n factor_prod = six.moves.reduce(mul, factors)\n JPD_fact = DiscreteFactor(self.variables, self.cardinality, self.values)\n if JPD_fact == factor_prod:\n return True\n else:\n return False\n\n def to_factor(self):\n \"\"\"\n Returns JointProbabilityDistribution as a DiscreteFactor object\n\n Examples\n --------\n >>> import numpy as np\n >>> from pgmpy.factors.discrete import JointProbabilityDistribution\n >>> prob = JointProbabilityDistribution(['x1', 'x2', 'x3'], [2, 3, 2], np.ones(12)/12)\n >>> phi = prob.to_factor()\n >>> type(phi)\n pgmpy.factors.DiscreteFactor.DiscreteFactor\n \"\"\"\n return DiscreteFactor(self.variables, self.cardinality, self.values)\n\n def pmap(self):\n pass\n"
] | [
[
"numpy.sum"
]
] |
Deci-AI/super-gradients | [
"bfed440ecaf485af183570bf965eb5b74cb9f832"
] | [
"src/super_gradients/training/losses/r_squared_loss.py"
] | [
"from __future__ import print_function, absolute_import\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn.modules.loss import _Loss\n\nfrom super_gradients.training.utils import convert_to_tensor\n\n\nclass RSquaredLoss(_Loss):\n\n def forward(self, output, target):\n # FIXME - THIS NEEDS TO BE CHANGED SUCH THAT THIS CLASS INHERETS FROM _Loss (TAKE A LOOK AT YoLoV3DetectionLoss)\n \"\"\"Computes the R-squared for the output and target values\n :param output: Tensor / Numpy / List\n The prediction\n :param target: Tensor / Numpy / List\n The corresponding lables\n \"\"\"\n # Convert to tensor\n output = convert_to_tensor(output)\n target = convert_to_tensor(target)\n\n criterion_mse = nn.MSELoss()\n return 1 - criterion_mse(output, target).item() / torch.var(target).item()\n"
] | [
[
"torch.var",
"torch.nn.MSELoss"
]
] |
lucyundead/athena--fork | [
"04a4027299145f61bdc08528548e0b1b398ba0a6"
] | [
"tst/regression/scripts/tests/pgen/hdf5_reader_serial.py"
] | [
"# Serial test script for initializing problem with preexisting array\n\n# Standard modules\nimport sys\n\n# Other modules\nimport logging\nimport numpy as np\nimport h5py\n\n# Athena modules\nimport scripts.utils.athena as athena\nsys.path.insert(0, '../../vis/python')\nimport athena_read # noqa\nathena_read.check_nan_flag = True\nlogger = logging.getLogger('athena' + __name__[7:]) # set logger name based on module\n\n# Parameters\nfilename_input = 'initial_data.hdf5'\nfilename_output = 'from_array.cons.00000.athdf'\ndataset_cons = 'cons'\ndataset_b1 = 'b1'\ndataset_b2 = 'b2'\ndataset_b3 = 'b3'\nnb1 = 4\nnx1 = 4\nnx2 = 6\nnx3 = 4\ngamma = 5.0/3.0\n\n\n# Prepare Athena++\ndef prepare(**kwargs):\n logger.debug('Running test ' + __name__)\n\n # Configure and compile code\n athena.configure('b',\n 'hdf5', 'h5double',\n prob='from_array',\n **kwargs)\n athena.make()\n\n # Calculate initial field values\n b1 = np.empty((nx3, nx2, nb1 * nx1 + 1))\n b1[...] = np.arange(nx2)[None, :, None] - np.arange(nx3)[:, None, None]\n b1_input = np.empty((nb1, nx3, nx2, nx1 + 1))\n b2_input = np.zeros((nb1, nx3, nx2 + 1, nx1))\n b3_input = np.zeros((nb1, nx3 + 1, nx2, nx1))\n for n in range(nb1):\n b1_input[n, ...] = b1[:, :, n*nx1:(n+1)*nx1+1]\n # (second-order accurate assumption)\n b1v = 0.5 * (b1_input[:, :, :, :-1] + b1_input[:, :, :, 1:])\n\n # Calculate initial conserved values\n num_cells = nb1 * nx1 * nx2 * nx3\n density = np.reshape(np.arange(1, num_cells+1), (1, nb1, nx3, nx2, nx1))\n momentum = np.zeros((3, nb1, nx3, nx2, nx1))\n energy = np.ones((1, nb1, nx3, nx2, nx1)) / (gamma - 1.0) + 0.5 * b1v[None, ...] ** 2\n cons_input = np.vstack((density, momentum, energy))\n\n # Write file to be loaded\n with h5py.File('bin/{0}'.format(filename_input), 'w') as f:\n f.create_dataset(dataset_cons, data=cons_input)\n f.create_dataset(dataset_b1, data=b1_input)\n f.create_dataset(dataset_b2, data=b2_input)\n f.create_dataset(dataset_b3, data=b3_input)\n\n\n# Run Athena++\ndef run(**kwargs):\n arguments = ['time/tlim=0',\n 'time/ncycle_out=0',\n 'mesh/nx1={0}'.format(nb1 * nx1),\n 'mesh/nx2={0}'.format(nx2),\n 'mesh/nx3={0}'.format(nx3),\n 'meshblock/nx1={0}'.format(nx1),\n 'meshblock/nx2={0}'.format(nx2),\n 'meshblock/nx3={0}'.format(nx3),\n 'problem/input_filename={0}'.format(filename_input)]\n athena.run('mhd/athinput.from_array', arguments)\n\n\n# Analyze outputs\ndef analyze():\n analyze_status = True\n # Read input data\n with h5py.File('bin/{0}'.format(filename_input), 'r') as f:\n cons_input = f[dataset_cons][:]\n b1_input = f[dataset_b1][:]\n b2_input = f[dataset_b2][:]\n b3_input = f[dataset_b3][:]\n\n # Calculate cell-centered field inputs from face-centered values\n # (second-order accurate assumption)\n b1v = 0.5 * (b1_input[:, :, :, :-1] + b1_input[:, :, :, 1:])\n b2v = 0.5 * (b2_input[:, :, :-1, :] + b2_input[:, :, 1:, :])\n b3v = 0.5 * (b3_input[:, :-1, :, :] + b3_input[:, 1:, :, :])\n\n # Read output data\n with h5py.File('bin/{0}'.format(filename_output), 'r') as f:\n num_vars = f.attrs['NumVariables']\n dataset_names = f.attrs['DatasetNames'].astype('U')\n output_vars = f.attrs['VariableNames'].astype('U')\n cons_output = f['cons'][:]\n field_output = f['B'][:]\n\n # Order conserved output data to match inputs\n index_cons = np.where(dataset_names == 'cons')[0][0]\n num_vars_cons = num_vars[index_cons]\n num_vars_pre_cons = np.sum(num_vars[:index_cons])\n output_vars_cons = output_vars[num_vars_pre_cons:num_vars_pre_cons+num_vars_cons]\n dens = cons_output[np.where(output_vars_cons == 'dens')[0], ...]\n mom1 = cons_output[np.where(output_vars_cons == 'mom1')[0], ...]\n mom2 = cons_output[np.where(output_vars_cons == 'mom2')[0], ...]\n mom3 = cons_output[np.where(output_vars_cons == 'mom3')[0], ...]\n etot = cons_output[np.where(output_vars_cons == 'Etot')[0], ...]\n cons_output = np.vstack((dens, mom1, mom2, mom3, etot))\n\n # Order field output data to match inputs\n index_field = np.where(dataset_names == 'B')[0][0]\n num_vars_field = num_vars[index_field]\n num_vars_pre_field = np.sum(num_vars[:index_field])\n output_vars_field = output_vars[num_vars_pre_field:num_vars_pre_field+num_vars_field]\n b1_output = field_output[np.where(output_vars_field == 'Bcc1')[0][0], ...]\n b2_output = field_output[np.where(output_vars_field == 'Bcc2')[0][0], ...]\n b3_output = field_output[np.where(output_vars_field == 'Bcc3')[0][0], ...]\n\n # Check that outputs match inputs\n if not np.all(cons_output == cons_input):\n analyze_status = False\n if not np.all(b1_output == b1v):\n analyze_status = False\n if not np.all(b2_output == b2v):\n analyze_status = False\n if not np.all(b3_output == b3v):\n analyze_status = False\n return analyze_status\n"
] | [
[
"numpy.vstack",
"numpy.sum",
"numpy.ones",
"numpy.empty",
"numpy.zeros",
"numpy.arange",
"numpy.all",
"numpy.where"
]
] |
cbfinn/ray | [
"18f9fe0e2b85d04f22e3e04907bbfacadca4bc2d"
] | [
"examples/a3c/runner.py"
] | [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import namedtuple\nimport numpy as np\nimport tensorflow as tf\nimport six.moves.queue as queue\nimport scipy.signal\nimport threading\n\n\ndef discount(x, gamma):\n return scipy.signal.lfilter([1], [1, -gamma], x[::-1], axis=0)[::-1]\n\n\ndef process_rollout(rollout, gamma, lambda_=1.0):\n \"\"\"Given a rollout, compute its returns and the advantage.\"\"\"\n batch_si = np.asarray(rollout.states)\n batch_a = np.asarray(rollout.actions)\n rewards = np.asarray(rollout.rewards)\n vpred_t = np.asarray(rollout.values + [rollout.r])\n\n rewards_plus_v = np.asarray(rollout.rewards + [rollout.r])\n batch_r = discount(rewards_plus_v, gamma)[:-1]\n delta_t = rewards + gamma * vpred_t[1:] - vpred_t[:-1]\n # This formula for the advantage comes \"Generalized Advantage Estimation\":\n # https://arxiv.org/abs/1506.02438\n batch_adv = discount(delta_t, gamma * lambda_)\n\n features = rollout.features[0]\n return Batch(batch_si, batch_a, batch_adv, batch_r, rollout.terminal,\n features)\n\n\nBatch = namedtuple(\"Batch\", [\"si\", \"a\", \"adv\", \"r\", \"terminal\", \"features\"])\n\n\nclass PartialRollout(object):\n \"\"\"A piece of a complete rollout.\n\n We run our agent, and process its experience once it has processed enough\n steps.\n \"\"\"\n def __init__(self):\n self.states = []\n self.actions = []\n self.rewards = []\n self.values = []\n self.r = 0.0\n self.terminal = False\n self.features = []\n\n def add(self, state, action, reward, value, terminal, features):\n self.states += [state]\n self.actions += [action]\n self.rewards += [reward]\n self.values += [value]\n self.terminal = terminal\n self.features += [features]\n\n def extend(self, other):\n assert not self.terminal\n self.states.extend(other.states)\n self.actions.extend(other.actions)\n self.rewards.extend(other.rewards)\n self.values.extend(other.values)\n self.r = other.r\n self.terminal = other.terminal\n self.features.extend(other.features)\n\n\nclass RunnerThread(threading.Thread):\n \"\"\"This thread interacts with the environment and tells it what to do.\"\"\"\n def __init__(self, env, policy, num_local_steps, visualise=False):\n threading.Thread.__init__(self)\n self.queue = queue.Queue(5)\n self.num_local_steps = num_local_steps\n self.env = env\n self.last_features = None\n self.policy = policy\n self.daemon = True\n self.sess = None\n self.summary_writer = None\n self.visualise = visualise\n\n def start_runner(self, sess, summary_writer):\n self.sess = sess\n self.summary_writer = summary_writer\n self.start()\n\n def run(self):\n with self.sess.as_default():\n self._run()\n\n def _run(self):\n rollout_provider = env_runner(self.env, self.policy, self.num_local_steps,\n self.summary_writer, self.visualise)\n while True:\n # The timeout variable exists because apparently, if one worker dies, the\n # other workers won't die with it, unless the timeout is set to some\n # large number. This is an empirical observation.\n self.queue.put(next(rollout_provider), timeout=600.0)\n\n\ndef env_runner(env, policy, num_local_steps, summary_writer, render):\n \"\"\"This impleents the logic of the thread runner.\n\n It continually runs the policy, and as long as the rollout exceeds a certain\n length, the thread runner appends the policy to the queue.\n \"\"\"\n last_state = env.reset()\n last_features = policy.get_initial_features()\n length = 0\n rewards = 0\n rollout_number = 0\n\n while True:\n terminal_end = False\n rollout = PartialRollout()\n\n for _ in range(num_local_steps):\n fetched = policy.act(last_state, *last_features)\n action, value_, features = fetched[0], fetched[1], fetched[2:]\n # Argmax to convert from one-hot.\n state, reward, terminal, info = env.step(action.argmax())\n if render:\n env.render()\n\n # Collect the experience.\n rollout.add(last_state, action, reward, value_, terminal, last_features)\n length += 1\n rewards += reward\n\n last_state = state\n last_features = features\n\n if info:\n summary = tf.Summary()\n for k, v in info.items():\n summary.value.add(tag=k, simple_value=float(v))\n summary_writer.add_summary(summary, rollout_number)\n summary_writer.flush()\n\n timestep_limit = env.spec.tags.get(\"wrapper_config.TimeLimit\"\n \".max_episode_steps\")\n if terminal or length >= timestep_limit:\n terminal_end = True\n if length >= timestep_limit or not env.metadata.get(\"semantics\"\n \".autoreset\"):\n last_state = env.reset()\n last_features = policy.get_initial_features()\n rollout_number += 1\n length = 0\n rewards = 0\n break\n\n if not terminal_end:\n rollout.r = policy.value(last_state, *last_features)\n\n # Once we have enough experience, yield it, and have the ThreadRunner\n # place it on a queue.\n yield rollout\n"
] | [
[
"numpy.asarray",
"tensorflow.Summary"
]
] |
perathambkk/ml-techniques | [
"5d6fd122322342c0b47dc65d09c4425fd73f2ea9"
] | [
"text/naivebayes.py"
] | [
"\"\"\"\nAuthor: Peratham Wiriyathammabhum\n\n\n\"\"\"\nimport numpy as np \nimport pandas as pd \nimport scipy as sp\nimport matplotlib.pyplot as plt \nimport scipy.sparse.linalg as linalg\n\ndef naivebayes(X):\n\t\"\"\"\n\tPerform spectral clustering on an input row matrix X.\n\tmode \\in {'affinity','neighborhood','gaussian'}\n\tSee: http://www.math.ucsd.edu/~fan/research/revised.html\n\t\thttp://www.math.ucsd.edu/~fan/research/cbms.pdf\n\t\"\"\"\n\tni, nd = X.shape\n\tL = laplacian_graph(X, mode='affinity', knn=knn, eta=eta, sigma=sigma)\n\n\tvals, vecs = linalg.eigs(L, k=k, which='SR')\n\t# ind = np.argsort(vals, axis=0)\n\t# vals = vals[ind]\n\t# vecs = vecs[:, ind]\n\n\tmu = kmeans(vecs, k=k, thres=10**-5, max_iters=max_iters)\n\t\n\tdist = ((vecs[:,None,:] - mu[None,:,:])**2).sum(axis=2)\n\tcidx = np.argmin(dist, axis=1)\n\treturn mu, cidx\n\ndef tfidf():\n\n\treturn\n\ndef main(opts):\n\tk = opts['k']\n\n\t# load data\n\tcategories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']\n\tfrom sklearn.datasets import fetch_20newsgroups\n\tfrom sklearn.feature_extraction.text import CountVectorizer\n\tcount_vect = CountVectorizer()\n\tX_train_counts = count_vect.fit_transform(twenty_train.data)\n\n\t# tf-idf\n\n\t# clustering\n\t_, cidx = spectral_clustering(X, mode=mode, k=k, knn=knn, eta=eta, sigma=sigma, max_iters=max_iters)\n\n\t# plot\n\t\n\treturn\n\nif __name__ == '__main__':\n\timport argparse\n\n\tparser = argparse.ArgumentParser(description='run naivebayes.')\n\tparser.add_argument('--k', dest='k',\n\t\t\t\t\t help='number of clusters',\n\t\t\t\t\t default=2, type=int)\n\targs = parser.parse_args()\n\topts = vars(args)\n\n\tmain(opts)\n"
] | [
[
"numpy.argmin",
"scipy.sparse.linalg.eigs",
"sklearn.feature_extraction.text.CountVectorizer"
]
] |
Crypto-TII/syndrome_decoding_estimator | [
"c7d9aaeed83708dbf5db3c45a007c0010a1225c8"
] | [
"sd_estimator/estimator.py"
] | [
"from .theoretical_estimates import *\nfrom math import inf, ceil, log2, comb\nfrom prettytable import PrettyTable\nfrom progress.bar import Bar\nfrom scipy.special import binom as binom_sp\nfrom scipy.optimize import fsolve\nfrom warnings import filterwarnings\n\nfilterwarnings(\"ignore\", category=RuntimeWarning)\n\n\ndef binom(n, k):\n return comb(int(n), int(k))\n\n\ndef __truncate(x, precision):\n \"\"\"\n Truncates a float\n\n INPUT:\n\n - ``x`` -- value to be truncated\n - ``precision`` -- number of decimal places to after which the ``x`` is truncated\n\n \"\"\"\n\n return float(int(x * 10 ** precision) / 10 ** precision)\n\n\ndef __concat_pretty_tables(t1, t2):\n v = t1.split(\"\\n\")\n v2 = t2.split(\"\\n\")\n vnew = \"\"\n for i in range(len(v)):\n vnew += v[i] + v2[i][1:] + \"\\n\"\n return vnew[:-1]\n\n\ndef __round_or_truncate_to_given_precision(T, M, truncate, precision):\n if truncate:\n T, M = __truncate(T, precision), __truncate(M, precision)\n else:\n T, M = round(T, precision), round(M, precision)\n return '{:.{p}f}'.format(T, p=precision), '{:.{p}f}'.format(M, p=precision)\n\n\ndef __memory_access_cost(mem, memory_access):\n if memory_access == 0:\n return 0\n elif memory_access == 1:\n return log2(mem)\n elif memory_access == 2:\n return mem / 2\n elif memory_access == 3:\n return mem / 3\n elif callable(memory_access):\n return memory_access(mem)\n return 0\n\n\ndef _gaussian_elimination_complexity(n, k, r):\n \"\"\"\n Complexity estimate of Gaussian elimination routine\n\n INPUT:\n\n - ``n`` -- Row additons are perfomed on ``n`` coordinates\n - ``k`` -- Matrix consists of ``n-k`` rows\n - ``r`` -- Blocksize of method of the four russian for inversion, default is zero\n\n [Bar07]_ Bard, G.V.: Algorithms for solving linear and polynomial systems of equations over finite fields\n with applications to cryptanalysis. Ph.D. thesis (2007)\n\n [BLP08] Bernstein, D.J., Lange, T., Peters, C.: Attacking and defending the mceliece cryptosystem.\n In: International Workshop on Post-Quantum Cryptography. pp. 31–46. Springer (2008)\n\n EXAMPLES::\n\n >>> from .estimator import _gaussian_elimination_complexity\n >>> _gaussian_elimination_complexity(n=100,k=20,r=1) # doctest: +SKIP\n\n \"\"\"\n\n if r != 0:\n return (r ** 2 + 2 ** r + (n - k - r)) * int(((n + r - 1) / r))\n\n return (n - k) ** 2\n\n\ndef _optimize_m4ri(n, k, mem=inf):\n \"\"\"\n Find optimal blocksize for Gaussian elimination via M4RI\n\n INPUT:\n\n - ``n`` -- Row additons are perfomed on ``n`` coordinates\n - ``k`` -- Matrix consists of ``n-k`` rows\n\n \"\"\"\n\n (r, v) = (0, inf)\n for i in range(n - k):\n tmp = log2(_gaussian_elimination_complexity(n, k, i))\n if v > tmp and r < mem:\n r = i\n v = tmp\n return r\n\n\ndef _mem_matrix(n, k, r):\n \"\"\"\n Memory usage of parity check matrix in vector space elements\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``r`` -- block size of M4RI procedure\n\n EXAMPLES::\n\n >>> from .estimator import _mem_matrix\n >>> _mem_matrix(n=100,k=20,r=0) # doctest: +SKIP\n\n \"\"\"\n return n - k + 2 ** r\n\n\ndef _list_merge_complexity(L, l, hmap):\n \"\"\"\n Complexity estimate of merging two lists exact\n\n INPUT:\n\n - ``L`` -- size of lists to be merged\n - ``l`` -- amount of bits used for matching\n - ``hmap`` -- indicates if hashmap is being used (Default 0: no hashmap)\n\n EXAMPLES::\n\n >>> from .estimator import _list_merge_complexity\n >>> _list_merge_complexity(L=2**16,l=16,hmap=1) # doctest: +SKIP\n\n \"\"\"\n\n if L == 1:\n return 1\n if not hmap:\n return max(1, 2 * int(log2(L)) * L + L ** 2 // 2 ** l)\n else:\n return 2 * L + L ** 2 // 2 ** l\n\n\ndef _indyk_motwani_complexity(L, l, w, hmap):\n \"\"\"\n Complexity of Indyk-Motwani nearest neighbor search\n\n INPUT:\n\n - ``L`` -- size of lists to be matched\n - ``l`` -- amount of bits used for matching\n - ``w`` -- target weight\n - ``hmap`` -- indicates if hashmap is being used (Default 0: no hashmap)\n\n EXAMPLES::\n\n >>> from .estimator import _indyk_motwani_complexity\n >>> _indyk_motwani_complexity(L=2**16,l=16,w=2,hmap=1) # doctest: +SKIP\n\n \"\"\"\n\n if w == 0:\n return _list_merge_complexity(L, l, hmap)\n lam = max(0, int(min(ceil(log2(L)), l - 2 * w)))\n return binom(l, lam) // binom(l - w, lam) * _list_merge_complexity(L, lam, hmap)\n\n\ndef _mitm_nn_complexity(L, l, w, hmap):\n \"\"\"\n Complexity of Indyk-Motwani nearest neighbor search\n\n INPUT:\n\n - ``L`` -- size of lists to be matched\n - ``l`` -- amount of bits used for matching\n - ``w`` -- target weight\n - ``hmap`` -- indicates if hashmap is being used (Default 0: no hashmap)\n\n EXAMPLES::\n\n >>> from .estimator import _indyk_motwani_complexity\n >>> _indyk_motwani_complexity(L=2**16,l=16,w=2,hmap=1) # doctest: +SKIP\n\n \"\"\"\n if w == 0:\n return _list_merge_complexity(L, l, hmap)\n L1 = L * binom(l / 2, w / 2)\n return _list_merge_complexity(L1, l, hmap)\n\n\ndef prange_complexity(n, k, w, mem=inf, memory_access=0):\n \"\"\"\n Complexity estimate of Prange's ISD algorithm\n\n [Pra62] Prange, E.: The use of information sets in decoding cyclic codes. IRE Transactions\n on Information Theory 8(5), 5–9 (1962)\n\n expected weight distribution::\n\n +--------------------------------+-------------------------------+\n | <----------+ n - k +---------> | <----------+ k +------------> |\n | w | 0 |\n +--------------------------------+-------------------------------+\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2(bits)), default unlimited\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import prange_complexity\n >>> prange_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n\n solutions = max(0, log2(binom(n, w)) - (n - k))\n\n r = _optimize_m4ri(n, k, mem)\n Tp = max(log2(binom(n, w)) - log2(binom(n - k, w)) - solutions, 0)\n Tg = log2(_gaussian_elimination_complexity(n, k, r))\n time = Tp + Tg\n memory = log2(_mem_matrix(n, k, r))\n\n time += __memory_access_cost(memory, memory_access)\n\n params = [r]\n\n par = {\"r\": params[0]}\n res = {\"time\": time, \"memory\": memory, \"parameters\": par}\n return res\n\n\ndef stern_complexity(n, k, w, mem=inf, hmap=1, memory_access=0):\n \"\"\"\n Complexity estimate of Stern's ISD algorithm\n\n [Ste88] Stern, J.: A method for finding codewords of small weight. In: International\n Colloquium on Coding Theory and Applications. pp. 106–113. Springer (1988)\n\n [BLP08] Bernstein, D.J., Lange, T., Peters, C.: Attacking and defending the mceliece cryptosystem.\n In: International Workshop on Post-Quantum Cryptography. pp. 31–46. Springer (2008)\n\n expected weight distribution::\n\n +-------------------------+---------+-------------+-------------+\n | <----+ n - k - l +----> |<-- l -->|<--+ k/2 +-->|<--+ k/2 +-->|\n | w - 2p | 0 | p | p |\n +-------------------------+---------+-------------+-------------+\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2), default unlimited\n - ``hmap`` -- indicates if hashmap is being used (default: true)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import stern_complexity\n >>> stern_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n\n solutions = max(0, log2(binom(n, w)) - (n - k))\n\n r = _optimize_m4ri(n, k, mem)\n time = inf\n memory = 0\n params = [-1 for i in range(2)]\n i_val = [20]\n i_val_inc = [10]\n k1 = k // 2\n while True:\n stop = True\n for p in range(min(k1, w // 2, i_val[0])):\n L1 = binom(k1, p)\n l_val = int(log2(L1))\n if log2(L1) > time:\n continue\n for l in range(max(l_val - i_val_inc[0], 0), l_val + i_val_inc[0]):\n\n tmp_mem = log2(2 * L1 + _mem_matrix(n, k, r))\n if tmp_mem > mem:\n continue\n\n Tp = max(0,\n log2(binom(n, w)) - log2(binom(n - k, w - 2 * p)) - log2(binom(k1, p) ** 2) - solutions)\n\n # We use Indyk-Motwani (IM) taking into account the possibility of multiple existing solutions\n # with correct weight distribution, decreasing the amount of necessary projections\n # remaining_sol denotes the number of expected solutions per permutation\n # l_part_iterations is the expected number of projections need by IM to find one of those solutions\n\n remaining_sol = (binom(n - k, w - 2 * p) * binom(k1, p) ** 2 * binom(n, w) // 2 ** (n - k)) // binom(n,\n w)\n l_part_iterations = binom(n - k, w - 2 * p) // binom(n - k - l, w - 2 * p)\n\n if remaining_sol > 0:\n l_part_iterations //= max(1, remaining_sol)\n l_part_iterations = max(1, l_part_iterations)\n\n Tg = _gaussian_elimination_complexity(n, k, r)\n tmp = Tp + log2(Tg + _list_merge_complexity(L1, l, hmap) * l_part_iterations)\n\n tmp += __memory_access_cost(tmp_mem, memory_access)\n\n time = min(time, tmp)\n\n if tmp == time:\n memory = tmp_mem\n params = [p, l]\n\n for i in range(len(i_val)):\n if params[i] == i_val[i] - 1:\n stop = False\n i_val[i] += i_val_inc[i]\n\n if stop:\n break\n\n par = {\"l\": params[1], \"p\": params[0]}\n res = {\"time\": time, \"memory\": memory, \"parameters\": par}\n return res\n\n\ndef dumer_complexity(n, k, w, mem=inf, hmap=1, memory_access=0):\n \"\"\"\n Complexity estimate of Dumer's ISD algorithm\n\n [Dum91] Dumer, I.: On minimum distance decoding of linear codes. In: Proc. 5th Joint\n Soviet-Swedish Int. Workshop Inform. Theory. pp. 50–52 (1991)\n\n expected weight distribution::\n\n +--------------------------+------------------+-------------------+\n | <-----+ n - k - l +----->|<-- (k + l)/2 +-->|<--+ (k + l)/2 +-->|\n | w - 2p | p | p |\n +--------------------------+------------------+-------------------+\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2), default unlimited\n - ``hmap`` -- indicates if hashmap is being used (default: true)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import dumer_complexity\n >>> dumer_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n\n \"\"\"\n solutions = max(0, log2(binom(n, w)) - (n - k))\n time = inf\n memory = 0\n r = _optimize_m4ri(n, k, mem)\n\n i_val = [10, 40]\n i_val_inc = [10, 10]\n params = [-1 for _ in range(2)]\n while True:\n stop = True\n for p in range(min(w // 2, i_val[0])):\n for l in range(min(n - k - (w - p), i_val[1])):\n k1 = (k + l) // 2\n L1 = binom(k1, p)\n if log2(L1) > time:\n continue\n\n tmp_mem = log2(2 * L1 + _mem_matrix(n, k, r))\n if tmp_mem > mem:\n continue\n\n Tp = max(log2(binom(n, w)) - log2(binom(n - k - l, w - 2 * p)) - log2(binom(k1, p) ** 2) - solutions, 0)\n Tg = _gaussian_elimination_complexity(n, k, r)\n tmp = Tp + log2(Tg + _list_merge_complexity(L1, l, hmap))\n\n tmp += __memory_access_cost(tmp_mem, memory_access)\n\n time = min(time, tmp)\n if tmp == time:\n memory = tmp_mem\n params = [p, l]\n\n for i in range(len(i_val)):\n if params[i] == i_val[i] - 1:\n stop = False\n i_val[i] += i_val_inc[i]\n\n if stop:\n break\n\n par = {\"l\": params[1], \"p\": params[0]}\n res = {\"time\": time, \"memory\": memory, \"parameters\": par}\n return res\n\n\ndef ball_collision_decoding_complexity(n, k, w, mem=inf, hmap=1, memory_access=0):\n \"\"\"\n Complexity estimate of the ball collision decodding algorithm\n\n [BLP11] Bernstein, D.J., Lange, T., Peters, C.: Smaller decoding exponents: ball-collision decoding.\n In: Annual Cryptology Conference. pp. 743–760. Springer (2011)\n\n expected weight distribution::\n\n +------------------+---------+---------+-------------+-------------+\n | <-+ n - k - l +->|<- l/2 ->|<- l/2 ->|<--+ k/2 +-->|<--+ k/2 +-->|\n | w - 2p - 2pl | pl | pl | p | p |\n +------------------+---------+---------+-------------+-------------+\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2), default unlimited\n - ``hmap`` -- indicates if hashmap is being used (default: true)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import ball_collision_decoding_complexity\n >>> ball_collision_decoding_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n solutions = max(0, log2(binom(n, w)) - (n - k))\n time = inf\n memory = 0\n r = _optimize_m4ri(n, k, mem)\n\n i_val = [10, 80, 4]\n i_val_inc = [10, 10, 10]\n params = [-1 for _ in range(3)]\n k1 = k // 2\n while True:\n stop = True\n for p in range(min(w // 2, i_val[0])):\n for l in range(min(n - k - (w - 2 * p), i_val[1])):\n for pl in range(min(i_val[2], (w - 2 * p) // 2, l // 2 + 1)):\n L1 = binom(k1, p)\n L1 *= max(1, binom(l // 2, pl))\n if log2(L1) > time:\n continue\n\n tmp_mem = log2(2 * L1 + _mem_matrix(n, k, r))\n if tmp_mem > mem:\n continue\n\n Tp = max(\n log2(binom(n, w)) - log2(binom(n - k - l, w - 2 * p - 2 * pl)) - 2 * log2(\n binom(k1, p)) - 2 * log2(\n binom(l // 2, pl)) - solutions, 0)\n Tg = _gaussian_elimination_complexity(n, k, r)\n tmp = Tp + log2(Tg + _list_merge_complexity(L1, l, hmap))\n\n tmp += __memory_access_cost(tmp_mem, memory_access)\n\n time = min(time, tmp)\n if tmp == time:\n memory = tmp_mem\n params = [p, pl, l]\n\n for i in range(len(i_val)):\n if params[i] == i_val[i] - 1:\n stop = False\n i_val[i] += i_val_inc[i]\n\n if stop:\n break\n\n par = {\"l\": params[2], \"p\": params[0], \"pl\": params[1]}\n res = {\"time\": time, \"memory\": memory, \"parameters\": par}\n return res\n\n\ndef bjmm_complexity(n, k, w, mem=inf, hmap=1, only_depth_two=0, memory_access=0):\n \"\"\"\n Complexity estimate of BJMM algorithm\n\n [MMT11] May, A., Meurer, A., Thomae, E.: Decoding random linear codes in 2^(0.054n). In: International Conference\n on the Theory and Application of Cryptology and Information Security. pp. 107–124. Springer (2011)\n\n [BJMM12] Becker, A., Joux, A., May, A., Meurer, A.: Decoding random binary linear codes in 2^(n/20): How 1+ 1= 0\n improves information set decoding. In: Annual international conference on the theory and applications of\n cryptographic techniques. pp. 520–536. Springer (2012)\n\n expected weight distribution::\n\n +--------------------------+-------------------+-------------------+\n | <-----+ n - k - l +----->|<--+ (k + l)/2 +-->|<--+ (k + l)/2 +-->|\n | w - 2p | p | p |\n +--------------------------+-------------------+-------------------+\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2), default unlimited\n - ``hmap`` -- indicates if hashmap is being used (default: true)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import bjmm_complexity\n >>> bjmm_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n d2 = bjmm_depth_2_complexity(n, k, w, mem, hmap, memory_access)\n d3 = bjmm_depth_3_complexity(n, k, w, mem, hmap, memory_access)\n return d2 if d2[\"time\"] < d3[\"time\"] or only_depth_two else d3\n\n\ndef bjmm_depth_2_complexity(n, k, w, mem=inf, hmap=1, memory_access=0, mmt=0):\n \"\"\"\n Complexity estimate of BJMM algorithm in depth 2\n\n [MMT11] May, A., Meurer, A., Thomae, E.: Decoding random linear codes in 2^(0.054n). In: International Conference\n on the Theory and Application of Cryptology and Information Security. pp. 107–124. Springer (2011)\n\n [BJMM12] Becker, A., Joux, A., May, A., Meurer, A.: Decoding random binary linear codes in 2^(n/20): How 1+ 1= 0\n improves information set decoding. In: Annual international conference on the theory and applications of\n cryptographic techniques. pp. 520–536. Springer (2012)\n\n expected weight distribution::\n\n +--------------------------+-------------------+-------------------+\n | <-----+ n - k - l +----->|<--+ (k + l)/2 +-->|<--+ (k + l)/2 +-->|\n | w - 2p | p | p |\n +--------------------------+-------------------+-------------------+\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2), default unlimited\n - ``hmap`` -- indicates if hashmap is being used (default: true)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n - ``mmt`` -- restrict optimization to use of MMT algorithm (precisely enforce p1=p/2)\n\n EXAMPLES::\n\n >>> from .estimator import bjmm_depth_2_complexity\n >>> bjmm_depth_2_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n solutions = max(0, log2(binom(n, w)) - (n - k))\n time = inf\n memory = 0\n r = _optimize_m4ri(n, k, mem)\n\n i_val = [35, 500, 35]\n i_val_inc = [10, 10, 10]\n params = [-1 for _ in range(3)]\n while True:\n stop = True\n for p in range(max(params[0] - i_val_inc[0] // 2, 0), min(w // 2, i_val[0]), 2):\n for l in range(max(params[1] - i_val_inc[1] // 2, 0), min(n - k - (w - 2 * p), min(i_val[1], n - k))):\n for p1 in range(max(params[2] - i_val_inc[2] // 2, (p + 1) // 2), min(w, i_val[2])):\n if mmt and p1 != p // 2:\n continue\n k1 = (k + l) // 2\n L1 = binom(k1, p1)\n if log2(L1) > time:\n continue\n\n if k1 - p < p1 - p / 2:\n continue\n reps = (binom(p, p / 2) * binom(k1 - p, p1 - p / 2)) ** 2\n\n l1 = int(ceil(log2(reps)))\n\n if l1 > l:\n continue\n\n L12 = max(1, L1 ** 2 // 2 ** l1)\n\n tmp_mem = log2((2 * L1 + L12) + _mem_matrix(n, k, r))\n if tmp_mem > mem:\n continue\n\n Tp = max(log2(binom(n, w)) - log2(binom(n - k - l, w - 2 * p)) - 2 * log2(\n binom((k + l) // 2, p)) - solutions, 0)\n Tg = _gaussian_elimination_complexity(n, k, r)\n T_tree = 2 * _list_merge_complexity(L1, l1, hmap) + _list_merge_complexity(L12,\n l - l1,\n hmap)\n T_rep = int(ceil(2 ** (l1 - log2(reps))))\n\n tmp = Tp + log2(Tg + T_rep * T_tree)\n tmp += __memory_access_cost(tmp_mem, memory_access)\n\n time = min(tmp, time)\n if tmp == time:\n memory = tmp_mem\n params = [p, l, p1]\n\n for i in range(len(i_val)):\n if params[i] == i_val[i] - 1:\n stop = False\n i_val[i] += i_val_inc[i]\n\n if stop:\n break\n\n par = {\"l\": params[1], \"p\": params[0], \"p1\": params[2], \"depth\": 2}\n res = {\"time\": time, \"memory\": memory, \"parameters\": par}\n return res\n\n\ndef bjmm_depth_3_complexity(n, k, w, mem=inf, hmap=1, memory_access=0):\n \"\"\"\n Complexity estimate of BJMM algorithm in depth 3\n\n [MMT11] May, A., Meurer, A., Thomae, E.: Decoding random linear codes in 2^(0.054n). In: International Conference\n on the Theory and Application of Cryptology and Information Security. pp. 107–124. Springer (2011)\n\n [BJMM12] Becker, A., Joux, A., May, A., Meurer, A.: Decoding random binary linear codes in 2^(n/20): How 1+ 1= 0\n improves information set decoding. In: Annual international conference on the theory and applications of\n cryptographic techniques. pp. 520–536. Springer (2012)\n\n expected weight distribution::\n\n +--------------------------+-------------------+-------------------+\n | <-----+ n - k - l +----->|<--+ (k + l)/2 +-->|<--+ (k + l)/2 +-->|\n | w - 2p | p | p |\n +--------------------------+-------------------+-------------------+\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2), default unlimited\n - ``hmap`` -- indicates if hashmap is being used (default: true)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import bjmm_depth_3_complexity\n >>> bjmm_depth_3_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n solutions = max(0, log2(binom(n, w)) - (n - k))\n time = inf\n memory = 0\n r = _optimize_m4ri(n, k, mem)\n\n params = [-1 for _ in range(4)]\n i_val = [25, 400, 20, 10]\n i_val_inc = [10, 10, 10, 10]\n while True:\n stop = True\n for p in range(max(params[0] - i_val_inc[0] // 2 + (params[0] - i_val_inc[0] // 2) % 2, 0),\n min(w // 2, i_val[0]), 2):\n for l in range(max(params[1] - i_val_inc[1] // 2, 0), min(n - k - (w - 2 * p), min(n - k, i_val[1]))):\n k1 = (k + l) // 2\n for p2 in range(max(params[2] - i_val_inc[2] // 2, p // 2 + ((p // 2) % 2)), i_val[2], 2):\n for p1 in range(max(params[3] - i_val_inc[3] // 2, (p2 + 1) // 2), i_val[3]):\n L1 = binom(k1, p1)\n\n if log2(L1) > time:\n continue\n\n reps1 = (binom(p2, p2 / 2) * binom(k1 - p2, p1 - p2 / 2)) ** 2\n l1 = int((log2(reps1))) if reps1 != 1 else 0\n\n L12 = max(1, L1 ** 2 // 2 ** l1)\n reps2 = (binom(p, p / 2) * binom(k1 - p, p2 - p / 2)) ** 2\n l2 = int(ceil(log2(reps2))) if reps2 != 1 else 0\n\n L1234 = max(1, L12 ** 2 // 2 ** (l2 - l1))\n tmp_mem = log2((2 * L1 + L12 + L1234) + _mem_matrix(n, k, r))\n if tmp_mem > mem:\n continue\n\n Tp = max(log2(binom(n, w)) - log2(binom(n - k - l, w - 2 * p)) - 2 * log2(\n binom((k + l) // 2, p)) - solutions, 0)\n Tg = _gaussian_elimination_complexity(n, k, r)\n T_tree = 4 * _list_merge_complexity(L1, l1, hmap) + 2 * _list_merge_complexity(L12,\n l2 - l1,\n hmap) + _list_merge_complexity(\n L1234,\n l - l2,\n hmap)\n T_rep = int(ceil(2 ** (3 * max(0, l1 - log2(reps1)) + max(0, l2 - log2(reps2)))))\n\n tmp = Tp + log2(Tg + T_rep * T_tree)\n tmp += __memory_access_cost(tmp_mem, memory_access)\n\n if tmp < time:\n time = tmp\n memory = tmp_mem\n params = [p, l, p2, p1]\n\n for i in range(len(i_val)):\n if params[i] >= i_val[i] - i_val_inc[i] / 2:\n stop = False\n i_val[i] += i_val_inc[i]\n\n if stop:\n break\n\n par = {\"l\": params[1], \"p\": params[0], \"p1\": params[3], \"p2\": params[2], \"depth\": 3}\n res = {\"time\": time, \"memory\": memory, \"parameters\": par}\n return res\n\n\ndef bjmm_depth_2_partially_disjoint_weight_complexity(n, k, w, mem=inf, hmap=1, memory_access=0):\n \"\"\"\n Complexity estimate of BJMM algorithm in depth 2 using partially disjoint weight, applying explicit MitM-NN search on second level\n\n [MMT11] May, A., Meurer, A., Thomae, E.: Decoding random linear codes in 2^(0.054n). In: International Conference\n on the Theory and Application of Cryptology and Information Security. pp. 107–124. Springer (2011)\n\n [BJMM12] Becker, A., Joux, A., May, A., Meurer, A.: Decoding random binary linear codes in 2^(n/20): How 1+ 1= 0\n improves information set decoding. In: Annual international conference on the theory and applications of\n cryptographic techniques. pp. 520–536. Springer (2012)\n\n [EssBel21] Esser, A. and Bellini, E.: Syndrome Decoding Estimator. In: IACR Cryptol. ePrint Arch. 2021 (2021), 1243\n\n expected weight distribution::\n\n +--------------------------+--------------------+--------------------+--------+--------+\n | <-+ n - k - l1 - 2 l2 +->|<-+ (k + l1) / 2 +->|<-+ (k + l1) / 2 +->| l2 | l2 |\n | w - 2 p - 2 w2 | p | p | w2 | w2 |\n +--------------------------+--------------------+--------------------+--------+--------+\n\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2), default unlimited\n - ``hmap`` -- indicates if hashmap is being used (default: true)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import bjmm_depth_2_partially_disjoint_weight_complexity\n >>> bjmm_depth_2_partially_disjoint_weight_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n solutions = max(0, log2(binom(n, w)) - (n - k))\n time = inf\n memory = 0\n r = _optimize_m4ri(n, k, mem)\n\n i_val = [30, 25, 5]\n i_val_inc = [10, 10, 10, 10, 10]\n params = [-1 for _ in range(5)]\n while True:\n stop = True\n for p in range(max(params[0] - i_val_inc[0] // 2, 0), min(w // 2, i_val[0]), 2):\n for p1 in range(max(params[1] - i_val_inc[1] // 2, (p + 1) // 2), min(w, i_val[1])):\n for w2 in range(max(params[2] - i_val_inc[2] // 2, 0), min(w - p1, i_val[2])):\n\n #############################################################################################\n ######choose start value for l1 close to the logarithm of the number of representations######\n #############################################################################################\n try:\n f = lambda x: log2((binom(p, p // 2) * binom_sp((k + x) / 2 - p, p1 - p // 2))) * 2 - x\n l1_val = int(fsolve(f, 0)[0])\n except:\n continue\n if f(l1_val) < 0 or f(l1_val) > 1:\n continue\n #############################################################################################\n\n for l1 in range(max(0, l1_val - i_val_inc[3] // 2), l1_val + i_val_inc[3] // 2):\n k1 = (k + l1) // 2\n reps = (binom(p, p // 2) * binom(k1 - p, p1 - p // 2)) ** 2\n\n L1 = binom(k1, p1)\n if log2(L1) > time:\n continue\n\n L12 = L1 ** 2 // 2 ** l1\n L12 = max(L12, 1)\n tmp_mem = log2((2 * L1 + L12) + _mem_matrix(n, k, r))\n if tmp_mem > mem:\n continue\n\n #################################################################################\n #######choose start value for l2 such that resultlist size is close to L12#######\n #################################################################################\n try:\n f = lambda x: log2(int(L12)) + int(2) * log2(binom_sp(x, int(w2))) - int(2) * x\n l2_val = int(fsolve(f, 0)[0])\n except:\n continue\n if f(l2_val) < 0 or f(l2_val) > 1:\n continue\n ################################################################################\n l2_min = w2\n l2_max = (n - k - l1 - (w - 2 * p - 2 * w2)) // 2\n l2_range = [l2_val - i_val_inc[4] // 2, l2_val + i_val_inc[4] // 2]\n for l2 in range(max(l2_min, l2_range[0]), min(l2_max, l2_range[1])):\n Tp = max(\n log2(binom(n, w)) - log2(binom(n - k - l1 - 2 * l2, w - 2 * p - 2 * w2)) - 2 * log2(\n binom(k1, p)) - 2 * log2(binom(l2, w2)) - solutions, 0)\n Tg = _gaussian_elimination_complexity(n, k, r)\n\n T_tree = 2 * _list_merge_complexity(L1, l1, hmap) + _mitm_nn_complexity(L12, 2 * l2, 2 * w2,\n hmap)\n T_rep = int(ceil(2 ** max(l1 - log2(reps), 0)))\n\n tmp = Tp + log2(Tg + T_rep * T_tree)\n tmp += __memory_access_cost(tmp_mem, memory_access)\n\n time = min(tmp, time)\n\n if tmp == time:\n memory = tmp_mem\n params = [p, p1, w2, l2, l1]\n\n for i in range(len(i_val)):\n if params[i] >= i_val[i] - i_val_inc[i] / 2:\n i_val[i] += i_val_inc[i]\n stop = False\n if stop:\n break\n break\n\n par = {\"l1\": params[4], \"p\": params[0], \"p1\": params[1], \"depth\": 2, \"l2\": params[3], \"w2\": params[2]}\n res = {\"time\": time, \"memory\": memory, \"parameters\": par}\n return res\n\n\ndef bjmm_depth_2_disjoint_weight_complexity(n, k, w, mem=inf, hmap=1, p_range=[0, 25], memory_access=0):\n \"\"\"\n Complexity estimate of May-Ozerov algorithm in depth 2 using Indyk-Motwani for NN search\n\n\n [MMT11] May, A., Meurer, A., Thomae, E.: Decoding random linear codes in 2^(0.054n). In: International Conference\n on the Theory and Application of Cryptology and Information Security. pp. 107–124. Springer (2011)\n\n [BJMM12] Becker, A., Joux, A., May, A., Meurer, A.: Decoding random binary linear codes in 2^(n/20): How 1+ 1= 0\n improves information set decoding. In: Annual international conference on the theory and applications of\n cryptographic techniques. pp. 520–536. Springer (2012)\n\n [EssBel21] Esser, A. and Bellini, E.: Syndrome Decoding Estimator. In: IACR Cryptol. ePrint Arch. 2021 (2021), 1243\n \n expected weight distribution::\n\n +---------------------------+-------------+------------+----------+----------+----------+----------+\n |<-+ n - k - 2 l1 - 2 l2 +->|<-+ k / 2 +->|<-+ k / 2 ->|<-+ l1 +->|<-+ l1 +->|<-+ l2 +->|<-+ l2 +->|\n | w - 2 p - 2 w1 - 2 w2 | p | p | w1 | w1 | w2 | w2 |\n +---------------------------+-------------+------------+----------+----------+----------+----------+\n\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2), default unlimited\n - ``hmap`` -- indicates if hashmap is being used (default: true)\n - ``p_range`` -- interval in which the parameter p is searched (default: [0, 25], helps speeding up computation)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import bjmm_depth_2_disjoint_weight_complexity\n >>> bjmm_depth_2_disjoint_weight_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n\n solutions = max(0, log2(binom(n, w)) - (n - k))\n time = inf\n memory = 0\n r = _optimize_m4ri(n, k)\n i_val = [p_range[1], 20, 10, 10, 5]\n i_val_inc = [10, 10, 10, 10, 10, 10, 10]\n params = [-1 for _ in range(7)]\n while True:\n stop = True\n for p in range(max(p_range[0], params[0] - i_val_inc[0] // 2, 0), min(w // 2, i_val[0]), 2):\n for p1 in range(max(params[1] - i_val_inc[1] // 2, (p + 1) // 2), min(w, i_val[1])):\n s = max(params[2] - i_val_inc[2] // 2, 0)\n for w1 in range(s - (s % 2), min(w // 2 - p, i_val[2]), 2):\n for w11 in range(max(params[3] - i_val_inc[3] // 2, (w1 + 1) // 2), min(w, i_val[3])):\n for w2 in range(max(params[4] - i_val_inc[4] // 2, 0), min(w // 2 - p - w1, i_val[4])):\n ##################################################################################\n ######choose start value for l1 such that representations cancel out exactly######\n ##################################################################################\n try:\n f = lambda x: 2 * log2((binom(p, p // 2) * binom(k // 2 - p, p1 - p // 2)) * (\n binom_sp(x, w1 // 2) * binom_sp(x - w1, w11 - w1 // 2)) + 1) - 2 * x\n l1_val = int(\n fsolve(f, 2 * log2((binom(p, p // 2) * binom(k // 2 - p, p1 - p // 2))))[0])\n except:\n continue\n if f(l1_val) < 0 or f(l1_val) > 10:\n continue\n #################################################################################\n\n for l1 in range(max(l1_val - i_val_inc[5], w1, w11), l1_val + i_val_inc[5]):\n k1 = k // 2\n reps = (binom(p, p // 2) * binom(k1 - p, p1 - p // 2)) ** 2 * (\n binom(w1, w1 // 2) * binom(l1 - w1, w11 - w1 // 2)) ** 2\n reps = max(reps, 1)\n L1 = binom(k1, p1)\n if log2(L1) > time:\n continue\n\n L12 = L1 ** 2 * binom(l1, w11) ** 2 // 2 ** (2 * l1)\n L12 = max(L12, 1)\n tmp_mem = log2((2 * L1 + L12) + _mem_matrix(n, k, r))\n if tmp_mem > mem:\n continue\n\n #################################################################################\n #######choose start value for l2 such that resultlist size is equal to L12#######\n #################################################################################\n try:\n f = lambda x: log2(L12) + 2 * log2(binom_sp(x, w2) + 1) - 2 * x\n l2_val = int(fsolve(f, 50)[0])\n except:\n continue\n if f(l2_val) < 0 or f(l2_val) > 10:\n continue\n ################################################################################\n l2_max = (n - k - 2 * l1 - (w - 2 * p - 2 * w1 - 2 * w2)) // 2\n l2_min = w2\n l2_range = [l2_val - i_val_inc[6] // 2, l2_val + i_val_inc[6] // 2]\n for l2 in range(max(l2_min, l2_range[0]), min(l2_max, l2_range[1])):\n Tp = max(\n log2(binom(n, w)) - log2(\n binom(n - k - 2 * l1 - 2 * l2, w - 2 * p - 2 * w1 - 2 * w2)) - 2 * log2(\n binom(k1, p)) - 2 * log2(binom(l1, w1)) - 2 * log2(\n binom(l2, w2)) - solutions, 0)\n Tg = _gaussian_elimination_complexity(n, k, r)\n\n T_tree = 2 * _mitm_nn_complexity(L1, 2 * l1, 2 * w11, hmap) + _mitm_nn_complexity(\n L12, 2 * l2, 2 * w2, hmap)\n T_rep = int(ceil(2 ** max(2 * l1 - log2(reps), 0)))\n\n tmp = Tp + log2(Tg + T_rep * T_tree)\n tmp += __memory_access_cost(tmp_mem, memory_access)\n\n time = min(tmp, time)\n\n if tmp == time:\n memory = tmp_mem\n params = [p, p1, w1, w11, w2, l2, l1 + l2]\n\n for i in range(len(i_val)):\n if params[i] >= i_val[i] - i_val_inc[i] / 2:\n i_val[i] += i_val_inc[i]\n stop = False\n if stop:\n break\n break\n par = {\"l\": params[6], \"p\": params[0], \"p1\": params[1], \"w1\": params[2], \"w11\": params[3], \"l2\": params[5],\n \"w2\": params[4], \"depth\": 2}\n res = {\"time\": time, \"memory\": memory, \"parameters\": par}\n return res\n\n\ndef both_may_depth_2_complexity(n, k, w, mem=inf, hmap=1, memory_access=0):\n \"\"\"\n Complexity estimate of Both-May algorithm in depth 2 using Indyk-Motwani and MitM for NN search\n\n [BotMay18] Both, L., May, A.: Decoding linear codes with high error rate and its impact for LPN security. In:\n International Conference on Post-Quantum Cryptography. pp. 25--46. Springer (2018)\n\n expected weight distribution::\n\n +-------------------+---------+-------------------+-------------------+\n | <--+ n - k - l+-->|<-+ l +->|<----+ k / 2 +---->|<----+ k / 2 +---->|\n | w - w2 - 2p | w2 | p | p |\n +-------------------+---------+-------------------+-------------------+\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2), default unlimited\n - ``hmap`` -- indicates if hashmap is being used (default: true)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import both_may_depth_2_complexity\n >>> both_may_depth_2_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n\n solutions = max(0, log2(binom(n, w)) - (n - k))\n time = inf\n memory = 0\n r = _optimize_m4ri(n, k, mem)\n\n i_val = [20, 160, 5, 4, 15]\n i_val_inc = [10, 10, 10, 6, 6]\n params = [-1 for _ in range(5)]\n while True:\n stop = True\n for p in range(max(params[0] - i_val_inc[0] // 2, 0), min(w // 2, i_val[0]), 2):\n for l in range(max(params[1] - i_val_inc[1] // 2, 0), min(n - k - (w - 2 * p), i_val[1])):\n for w1 in range(max(params[2] - i_val_inc[2] // 2, 0), min(w, l + 1, i_val[2])):\n for w2 in range(max(params[3] - i_val_inc[3] // 2, 0), min(w - 2 * p, l + 1, i_val[3], 2 * w1), 2):\n for p1 in range(max(params[4] - i_val_inc[4] // 2, (p + 1) // 2), min(w, i_val[4])):\n k1 = (k) // 2\n reps = (binom(p, p / 2) * binom(k1 - p, p1 - p / 2)) ** 2 * binom(w2, w2 / 2) * binom(\n l - w2,\n w1 - w2 / 2)\n reps = 1 if reps == 0 else reps\n L1 = binom(k1, p1)\n\n if log2(L1) > time:\n continue\n\n L12 = max(1, L1 ** 2 * binom(l, w1) // 2 ** l)\n\n tmp_mem = log2((2 * L1 + L12) + _mem_matrix(n, k, r))\n if tmp_mem > mem:\n continue\n Tp = max(log2(binom(n, w)) - log2(binom(n - k - l, w - w2 - 2 * p)) - 2 * log2(\n binom(k1, p)) - log2(binom(l, w2)) - solutions, 0)\n Tg = _gaussian_elimination_complexity(n, k, r)\n\n first_level_nn = _indyk_motwani_complexity(L1, l, w1, hmap)\n second_level_nn = _indyk_motwani_complexity(L12, n - k - l, w - 2 * p - w2, hmap)\n T_tree = 2 * first_level_nn + second_level_nn\n T_rep = int(ceil(2 ** max(0, l - log2(reps))))\n\n tmp = Tp + log2(Tg + T_rep * T_tree)\n tmp += __memory_access_cost(tmp_mem, memory_access)\n\n time = min(tmp, time)\n\n if tmp == time:\n memory = tmp_mem\n params = [p, l, w1, w2, p1, log2(L1), log2(L12)]\n\n for i in range(len(i_val)):\n if params[i] >= i_val[i] - i_val_inc[i] / 2:\n i_val[i] += i_val_inc[i]\n stop = False\n if stop:\n break\n\n par = {\"l\": params[1], \"p\": params[0], \"p1\": params[4], \"w1\": params[2], \"w2\": params[3], \"depth\": 2}\n res = {\"time\": time, \"memory\": memory, \"parameters\": par}\n return res\n\n\ndef may_ozerov_complexity(n, k, w, mem=inf, hmap=1, only_depth_two=0, memory_access=0):\n \"\"\"\n Complexity estimate of May-Ozerov algorithm using Indyk-Motwani for NN search\n\n [MayOze15] May, A. and Ozerov, I.: On computing nearest neighbors with applications to decoding of binary linear codes.\n In: Annual International Conference on the Theory and Applications of Cryptographic Techniques. pp. 203--228. Springer (2015)\n\n expected weight distribution::\n\n +-------------------------+---------------------+---------------------+\n | <-----+ n - k - l+----->|<--+ (k + l) / 2 +-->|<--+ (k + l) / 2 +-->|\n | w - 2p | p | p |\n +-------------------------+---------------------+---------------------+\n\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2), default unlimited\n - ``hmap`` -- indicates if hashmap is being used (default: true)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import may_ozerov_complexity\n >>> may_ozerov_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n d2 = may_ozerov_depth_2_complexity(n, k, w, mem, hmap, memory_access)\n d3 = may_ozerov_depth_3_complexity(n, k, w, mem, hmap, memory_access)\n return d2 if d2[\"time\"] < d3[\"time\"] or only_depth_two else d3\n\n\ndef may_ozerov_depth_2_complexity(n, k, w, mem=inf, hmap=1, memory_access=0):\n \"\"\"\n Complexity estimate of May-Ozerov algorithm in depth 2 using Indyk-Motwani for NN search\n\n [MayOze15] May, A. and Ozerov, I.: On computing nearest neighbors with applications to decoding of binary linear codes.\n In: Annual International Conference on the Theory and Applications of Cryptographic Techniques. pp. 203--228. Springer (2015)\n\n expected weight distribution::\n\n +-------------------------+---------------------+---------------------+\n | <-----+ n - k - l+----->|<--+ (k + l) / 2 +-->|<--+ (k + l) / 2 +-->|\n | w - 2p | p | p |\n +-------------------------+---------------------+---------------------+\n\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2), default unlimited\n - ``hmap`` -- indicates if hashmap is being used (default: true)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import may_ozerov_depth_2_complexity\n >>> may_ozerov_depth_2_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n solutions = max(0, log2(binom(n, w)) - (n - k))\n time = inf\n memory = 0\n r = _optimize_m4ri(n, k, mem)\n\n i_val = [30, 300, 25]\n i_val_inc = [10, 10, 10]\n params = [-1 for _ in range(3)]\n while True:\n stop = True\n for p in range(max(params[0] - i_val_inc[0] // 2, 0), min(w // 2, i_val[0]), 2):\n for l in range(max(params[1] - i_val_inc[1] // 2, 0), min(n - k - (w - 2 * p), i_val[1])):\n for p1 in range(max(params[2] - i_val_inc[2] // 2, (p + 1) // 2), min(w, i_val[2])):\n k1 = (k + l) // 2\n reps = (binom(p, p // 2) * binom(k1 - p, p1 - p // 2)) ** 2\n\n L1 = binom(k1, p1)\n if log2(L1) > time:\n continue\n\n L12 = L1 ** 2 // 2 ** l\n L12 = max(L12, 1)\n tmp_mem = log2((2 * L1 + L12) + _mem_matrix(n, k, r))\n if tmp_mem > mem:\n continue\n\n Tp = max(\n log2(binom(n, w)) - log2(binom(n - k - l, w - 2 * p)) - 2 * log2(binom(k1, p)) - solutions, 0)\n Tg = _gaussian_elimination_complexity(n, k, r)\n\n T_tree = 2 * _list_merge_complexity(L1, l, hmap) + _indyk_motwani_complexity(L12,\n n - k - l,\n w - 2 * p,\n hmap)\n T_rep = int(ceil(2 ** max(l - log2(reps), 0)))\n\n tmp = Tp + log2(Tg + T_rep * T_tree)\n tmp += __memory_access_cost(tmp_mem, memory_access)\n\n time = min(tmp, time)\n\n if tmp == time:\n memory = tmp_mem\n params = [p, l, p1]\n\n for i in range(len(i_val)):\n if params[i] >= i_val[i] - i_val_inc[i] / 2:\n i_val[i] += i_val_inc[i]\n stop = False\n if stop:\n break\n break\n\n par = {\"l\": params[1], \"p\": params[0], \"p1\": params[2], \"depth\": 2}\n res = {\"time\": time, \"memory\": memory, \"parameters\": par}\n return res\n\n\ndef may_ozerov_depth_3_complexity(n, k, w, mem=inf, hmap=1, memory_access=0):\n \"\"\"\n Complexity estimate of May-Ozerov algorithm in depth 3 using Indyk-Motwani for NN search\n\n [MayOze15] May, A. and Ozerov, I.: On computing nearest neighbors with applications to decoding of binary linear codes.\n In: Annual International Conference on the Theory and Applications of Cryptographic Techniques. pp. 203--228. Springer (2015)\n\n expected weight distribution::\n\n +-------------------------+---------------------+---------------------+\n | <-----+ n - k - l+----->|<--+ (k + l) / 2 +-->|<--+ (k + l) / 2 +-->|\n | w - 2p | p | p |\n +-------------------------+---------------------+---------------------+\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``mem`` -- upper bound on the available memory (as log2), default unlimited\n - ``hmap`` -- indicates if hashmap is being used (default: true)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import may_ozerov_depth_3_complexity\n >>> may_ozerov_depth_3_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n solutions = max(0, log2(binom(n, w)) - (n - k))\n time = inf\n memory = 0\n r = _optimize_m4ri(n, k, mem)\n\n i_val = [20, 200, 20, 10]\n i_val_inc = [10, 10, 10, 10]\n params = [-1 for _ in range(4)]\n while True:\n stop = True\n for p in range(max(params[0] - i_val_inc[0] // 2, 0), min(w // 2, i_val[0]), 2):\n for l in range(max(params[1] - i_val_inc[1] // 2, 0), min(n - k - (w - 2 * p), i_val[1])):\n k1 = (k + l) // 2\n for p2 in range(max(params[2] - i_val_inc[2] // 2, p // 2 + ((p // 2) % 2)), p + i_val[2], 2):\n for p1 in range(max(params[3] - i_val_inc[3] // 2, (p2 + 1) // 2),\n min(p2 + i_val[3], k1 - p2 // 2)):\n L1 = binom(k1, p1)\n if log2(L1) > time:\n continue\n\n reps1 = (binom(p2, p2 // 2) * binom(k1 - p2, p1 - p2 // 2)) ** 2\n l1 = int(ceil(log2(reps1)))\n\n if l1 > l:\n continue\n L12 = max(1, L1 ** 2 // 2 ** l1)\n reps2 = (binom(p, p // 2) * binom(k1 - p, p2 - p // 2)) ** 2\n\n L1234 = max(1, L12 ** 2 // 2 ** (l - l1))\n tmp_mem = log2((2 * L1 + L12 + L1234) + _mem_matrix(n, k, r))\n if tmp_mem > mem:\n continue\n\n Tp = max(\n log2(binom(n, w)) - log2(binom(n - k - l, w - 2 * p)) - 2 * log2(binom(k1, p)) - solutions,\n 0)\n Tg = _gaussian_elimination_complexity(n, k, r)\n T_tree = 4 * _list_merge_complexity(L1, l1, hmap) + 2 * _list_merge_complexity(L12,\n l - l1,\n hmap) + _indyk_motwani_complexity(\n L1234,\n n - k - l,\n w - 2 * p,\n hmap)\n T_rep = int(ceil(2 ** (max(l - log2(reps2), 0) + 3 * max(l1 - log2(reps1), 0))))\n tmp = Tp + log2(Tg + T_rep * T_tree)\n tmp += __memory_access_cost(tmp_mem, memory_access)\n\n if tmp < time:\n time = tmp\n memory = tmp_mem\n params = [p, l, p2, p1]\n for i in range(len(i_val)):\n if params[i] >= i_val[i] - i_val_inc[i] / 2:\n i_val[i] += i_val_inc[i]\n stop = False\n if stop:\n break\n break\n par = {\"l\": params[1], \"p\": params[0], \"p1\": params[3], \"p2\": params[2], \"depth\": 3}\n res = {\"time\": time, \"memory\": memory, \"parameters\": par}\n\n return res\n\n\ndef quantum_prange_complexity(n, k, w, maxdepth=96, matrix_mult_constant=2.5):\n \"\"\"\n Optimistic complexity estimate of quantum version of Prange's algorithm\n\n [Pra62] Prange, E.: The use of information sets in decoding cyclic codes. IRE Transactions\n on Information Theory 8(5), 5–9 (1962)\n\n [Ber10] Bernstein, D.J.: Grover vs. McEliece. In: International Workshop on Post-QuantumCryptography.\n pp. 73–80. Springer (2010)\n\n expected weight distribution::\n\n +--------------------------------+-------------------------------+\n | <----------+ n - k +---------> | <----------+ k +------------> |\n | w | 0 |\n +--------------------------------+-------------------------------+\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``maxdepth`` -- maximum allowed depth of the quantum circuit (default: 96)\n - ``matrix_mult_constant`` -- used matrix multiplication constant (default: 2.5)\n\n\n EXAMPLES::\n\n >>> from .estimator import quantum_prange_complexity\n >>> quantum_prange_complexity(n=100,k=50,w=10) # doctest: +SKIP\n\n \"\"\"\n\n Tg = matrix_mult_constant * log2(n - k)\n if Tg > maxdepth:\n return 0\n\n full_circuit = Tg + (log2(binom(n, w)) - log2(binom(n - k, w))) / 2\n if full_circuit < maxdepth:\n return full_circuit\n\n time = log2(binom(n, w)) - log2(binom(n - k, w)) + 2 * Tg - maxdepth\n return time\n\n\ndef sd_estimate_display(n, k, w, memory_limit=inf, bit_complexities=1, hmap=1, skip=[\"BJMM-dw\"], precision=1,\n truncate=0,\n all_parameters=0, theoretical_estimates=0, use_mo=1, workfactor_accuracy=1, limit_depth=0,\n quantum_estimates=1,\n maxdepth=96, matrix_mult_constant=2.5, memory_access=0):\n \"\"\"\n Output estimates of complexity to solve the syndrome decoding problem\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``memory_limit`` -- upper bound on the available memory (in log2) (default: unlimited)\n - ``bit_complexities`` -- state security level in number of bitoperations, otherwise field operations (default: true)\n - ``hmap`` -- indicates if hashmap is used for sorting lists (default: true)\n - ``skip`` -- list of algorithms not to consider (default: [\"BJMM-dw\"] (this variant will take a long time to optimize))\n - ``precision`` -- amount of decimal places displayed for complexity estimates (default: 1)\n - ``truncate`` -- decimal places exceeding ``precision`` are truncated, otherwise rounded (default: false)\n - ``all_parameters`` -- print values of all hyperparameters (default: false)\n - ``theoretical_estimates`` -- compute theoretical workfactors for all algorithms (default: false)\n - ``use_mo`` -- use may-ozerov nearest neighbor search in theoretical workfactor computation (default: true)\n - ``workfactor_accuracy`` -- the higher the more accurate the workfactor computation, can slow down computations significantly, recommended range 0-2 (needs to be larger than 0) (default: 1)\n - ``limit_depth`` -- restricts BJMM and May-Ozerov algorithms to depth two only (default: false)\n - ``quantum_estimates`` -- compute quantum estimates of all algorithms (default: true)\n - ``maxdepth`` -- maximum allowed depth of the quantum circuit (default: 96)\n - ``matrix_mult_constant`` -- used matrix multiplication constant (default: 2.5)\n - ``memory_access`` -- specifies the memory access cost model (default: 0, choices: 0 - constant, 1 - logarithmic, 2 - square-root, 3 - cube-root or deploy custom function which takes as input the logarithm of the total memory usage)\n\n EXAMPLES::\n\n >>> from .estimator import *\n >>> sd_estimate_display(n=600,k=400,w=22)\n =========================================================================\n Complexity estimation to solve the (600,400,22) syndrome decoding problem\n =========================================================================\n The following table states bit complexity estimates of the corresponding algorithms including an approximation of the polynomial factors inherent to the algorithm.\n The quantum estimate gives a very optimistic estimation of the cost for a quantum aided attack with a circuit of limitted depth (should be understood as a lowerbound).\n +----------------+---------------+---------+\n | | estimate | quantum |\n +----------------+------+--------+---------+\n | algorithm | time | memory | time |\n +----------------+------+--------+---------+\n | Prange | 60.1 | 17.3 | 37.1 |\n | Stern | 47.0 | 24.5 | -- |\n | Dumer | 47.6 | 24.6 | -- |\n | Ball Collision | 47.7 | 24.5 | -- |\n | BJMM (MMT) | 47.6 | 22.7 | -- |\n | BJMM-pdw | 47.7 | 21.7 | -- |\n | May-Ozerov | 46.5 | 22.6 | -- |\n | Both-May | 47.1 | 22.6 | -- |\n +----------------+------+--------+---------+\n\n\n >>> from .estimator import *\n >>> sd_estimate_display(n=1000,k=500,w=100,all_parameters=1,theoretical_estimates=1,precision=2) # long time\n ===========================================================================\n Complexity estimation to solve the (1000,500,100) syndrome decoding problem\n ===========================================================================\n The following table states bit complexity estimates of the corresponding algorithms including an approximation of the polynomial factors inherent to the algorithm.\n The approximation is based on the theoretical workfactor of the respective algorithms, disregarding all polynomial factors and using further approximations that introduce additional polynomial inaccurcies.\n The quantum estimate gives a very optimistic estimation of the cost for a quantum aided attack with a circuit of limitted depth (should be understood as a lowerbound).\n +----------------+-----------------+-----------------+---------+--------------------------------------------------------------------+\n | | estimate | approximation | quantum | parameters |\n +----------------+--------+--------+--------+--------+---------+--------------------------------------------------------------------+\n | algorithm | time | memory | time | memory | time | classical |\n +----------------+--------+--------+--------+--------+---------+--------------------------------------------------------------------+\n | Prange | 134.46 | 19.26 | 108.03 | 0.00 | 76.39 | r : 7 |\n | Stern | 117.04 | 38.21 | 104.02 | 31.39 | -- | l : 27 | p : 4 |\n | Dumer | 116.82 | 38.53 | 103.76 | 33.68 | -- | l : 28 | p : 4 |\n | Ball Collision | 117.04 | 38.21 | 103.76 | 32.67 | -- | l : 27 | p : 4 | pl : 0 |\n | BJMM (MMT) | 112.39 | 73.15 | 90.17 | 67.76 | -- | l : 120 | p : 16 | p1 : 10 | depth : 2 |\n | BJMM-pdw | 113.92 | 52.74 | -- | -- | -- | l1 : 35 | p : 10 | p1 : 6 | depth : 2 | l2 : 21 | w2 : 0 |\n | May-Ozerov | 111.56 | 70.44 | 89.51 | 51.39 | -- | l : 69 | p : 14 | p1 : 10 | depth : 2 |\n | Both-May | 113.68 | 68.58 | 87.60 | 64.13 | -- | l : 75 | p : 14 | p1 : 10 | w1 : 2 | w2 : 2 | depth : 2 |\n +----------------+--------+--------+--------+--------+---------+--------------------------------------------------------------------+\n\n\n TESTS::\n\n >>> from .estimator import *\n >>> sd_estimate_display(24646,12323,142,all_parameters=True) # long time\n ==============================================================================\n Complexity estimation to solve the (24646,12323,142) syndrome decoding problem\n ==============================================================================\n The following table states bit complexity estimates of the corresponding algorithms including an approximation of the polynomial factors inherent to the algorithm.\n The quantum estimate gives a very optimistic estimation of the cost for a quantum aided attack with a circuit of limitted depth (should be understood as a lowerbound).\n +----------------+----------------+---------+--------------------------------------------------------------------+\n | | estimate | quantum | parameters |\n +----------------+-------+--------+---------+--------------------------------------------------------------------+\n | algorithm | time | memory | time | classical |\n +----------------+-------+--------+---------+--------------------------------------------------------------------+\n | Prange | 182.1 | 28.4 | 114.5 | r : 11 |\n | Stern | 160.6 | 39.8 | -- | l : 33 | p : 2 |\n | Dumer | 161.1 | 39.8 | -- | l : 28 | p : 2 |\n | Ball Collision | 161.1 | 39.8 | -- | l : 28 | p : 2 | pl : 0 |\n | BJMM (MMT) | 160.9 | 54.2 | -- | l : 74 | p : 4 | p1 : 3 | depth : 2 |\n | BJMM-pdw | 160.9 | 55.0 | -- | l1 : 30 | p : 4 | p1 : 3 | depth : 2 | l2 : 22 | w2 : 0 |\n | May-Ozerov | 160.4 | 55.0 | -- | l : 30 | p : 4 | p1 : 3 | depth : 2 |\n | Both-May | 161.1 | 37.8 | -- | l : 4 | p : 2 | p1 : 1 | w1 : 1 | w2 : 0 | depth : 2 |\n +----------------+-------+--------+---------+--------------------------------------------------------------------+\n\n\n >>> from .estimator import *\n >>> sd_estimate_display(300,200,20,all_parameters=True, skip=[])\n =========================================================================\n Complexity estimation to solve the (300,200,20) syndrome decoding problem\n =========================================================================\n The following table states bit complexity estimates of the corresponding algorithms including an approximation of the polynomial factors inherent to the algorithm.\n The quantum estimate gives a very optimistic estimation of the cost for a quantum aided attack with a circuit of limitted depth (should be understood as a lowerbound).\n +----------------+---------------+---------+-------------------------------------------------------------------------------------------+\n | | estimate | quantum | parameters |\n +----------------+------+--------+---------+-------------------------------------------------------------------------------------------+\n | algorithm | time | memory | time | classical |\n +----------------+------+--------+---------+-------------------------------------------------------------------------------------------+\n | Prange | 52.5 | 15.3 | 33.5 | r : 5 |\n | Stern | 40.7 | 21.5 | -- | l : 13 | p : 2 |\n | Dumer | 41.1 | 26.9 | -- | l : 18 | p : 3 |\n | Ball Collision | 41.3 | 21.5 | -- | l : 12 | p : 2 | pl : 0 |\n | BJMM (MMT) | 41.1 | 27.5 | -- | l : 25 | p : 4 | p1 : 2 | depth : 2 |\n | BJMM-pdw | 41.3 | 18.9 | -- | l1 : 3 | p : 2 | p1 : 1 | depth : 2 | l2 : 4 | w2 : 0 |\n | BJMM-dw | 41.3 | 19.7 | -- | l : 6 | p : 2 | p1 : 1 | w1 : 0 | w11 : 1 | l2 : 5 | w2 : 0 | depth : 2 |\n | May-Ozerov | 40.1 | 19.7 | -- | l : 2 | p : 2 | p1 : 1 | depth : 2 |\n | Both-May | 40.4 | 19.7 | -- | l : 2 | p : 2 | p1 : 1 | w1 : 2 | w2 : 0 | depth : 2 |\n +----------------+------+--------+---------+-------------------------------------------------------------------------------------------+\n\n\n\n \"\"\"\n\n complexities = _sd_estimate(n, k, w, theoretical_estimates, memory_limit, bit_complexities, hmap, skip, use_mo,\n workfactor_accuracy, limit_depth, quantum_estimates, maxdepth, matrix_mult_constant,\n memory_access)\n\n headline = \"Complexity estimation to solve the ({},{},{}) syndrome decoding problem\".format(n, k, w)\n print(\"=\" * len(headline))\n print(headline)\n print(\"=\" * len(headline))\n if bit_complexities:\n print(\n \"The following table states bit complexity estimates of the corresponding algorithms including an approximation of the polynomial factors inherent to the algorithm.\")\n else:\n print(\n \"The following table states complexity estimates of the corresponding algorithms including an approximation of the polynomial factors inherent to the algorithm.\")\n print(\"The time complexity estimate is measured in the number of additions in (F_2)^n.\")\n print(\"The memory complexity estimate is given in the number of vector space elements that need to be stored.\")\n\n if theoretical_estimates:\n print(\n \"The approximation is based on the theoretical workfactor of the respective algorithms, disregarding all polynomial factors and using further approximations that introduce additional polynomial inaccurcies.\")\n if quantum_estimates:\n print(\n \"The quantum estimate gives a very optimistic estimation of the cost for a quantum aided attack with a circuit of limitted depth (should be understood as a lowerbound).\")\n tables = []\n table_fields = ['algorithm']\n\n tbl_names = PrettyTable(table_fields)\n tbl_names.padding_width = 1\n tbl_names.title = ' '\n\n for i in complexities.keys():\n tbl_names.add_row([i])\n tbl_names.align[\"algorithm\"] = \"l\"\n tables.append(tbl_names)\n\n table_fields = ['time', 'memory']\n tbl_estimates = PrettyTable(table_fields)\n tbl_estimates.padding_width = 1\n tbl_estimates.title = 'estimate'\n tbl_estimates.align[\"time\"] = \"r\"\n tbl_estimates.align[\"memory\"] = \"r\"\n for i in complexities.keys():\n if complexities[i][\"time\"] != inf:\n T, M = __round_or_truncate_to_given_precision(complexities[i][\"time\"], complexities[i][\"memory\"], truncate,\n precision)\n else:\n T, M = \"--\", \"--\"\n tbl_estimates.add_row([T, M])\n\n tables.append(tbl_estimates)\n\n if theoretical_estimates:\n table_fields = ['time', 'memory']\n tbl_approx = PrettyTable(table_fields)\n tbl_approx.padding_width = 1\n tbl_approx.title = 'approximation'\n tbl_approx.align[\"time\"] = \"r\"\n tbl_approx.align[\"memory\"] = \"r\"\n\n for i in complexities.keys():\n if complexities[i][\"Workfactor time\"] != 0:\n T, M = __round_or_truncate_to_given_precision(complexities[i][\"Workfactor time\"] * n,\n complexities[i][\"Workfactor memory\"] * n, truncate,\n precision)\n else:\n T, M = \"--\", \"--\"\n tbl_approx.add_row([T, M])\n\n tables.append(tbl_approx)\n\n if quantum_estimates:\n table_fields = [' time']\n tbl_quantum = PrettyTable(table_fields)\n tbl_quantum.padding_width = 1\n tbl_quantum.title = \"quantum\"\n tbl_quantum.align[\"time\"] = \"r\"\n for i in complexities.keys():\n if \"quantum time\" in complexities[i].keys() and complexities[i][\"quantum time\"] != 0:\n T, M = __round_or_truncate_to_given_precision(complexities[i][\"quantum time\"], 0, truncate, precision)\n else:\n T = \"--\"\n tbl_quantum.add_row([T])\n tables.append(tbl_quantum)\n\n if all_parameters:\n table_fields = ['classical']\n tbl_params = PrettyTable(table_fields)\n tbl_params.padding_width = 1\n tbl_params.title = \"parameters\"\n tbl_params.align['classical'] = \"l\"\n\n for i in complexities.keys():\n row = \"\"\n for j in complexities[i][\"parameters\"].keys():\n row += \"{:<{align}}\".format(j, align=max(2, len(j))) + \" : \" + '{:3d}'.format(\n complexities[i][\"parameters\"][j]) + \" | \"\n tbl_params.add_row([row[:-3]])\n\n tables.append(tbl_params)\n\n tbl_join = __concat_pretty_tables(str(tables[0]), str(tables[1]))\n for i in range(2, len(tables)):\n tbl_join = __concat_pretty_tables(tbl_join, str(tables[i]))\n\n print(tbl_join)\n\n\ndef _add_theoretical_estimates(complexities, n, k, w, memory_limit, skip, use_mo, workfactor_accuracy):\n rate = k / n\n omega = w / n\n\n grid_std_accuracy = {\"prange\": [20, 150], \"stern\": [20, 150], \"dumer\": [20, 150], \"ball_collision\": [15, 150],\n \"bjmm\": [10, 250], \"may-ozerov\": [5, 1000], \"both-may\": [5, 1000]}\n\n if workfactor_accuracy != 1:\n for i in grid_std_accuracy.keys():\n for j in range(2):\n grid_std_accuracy[i][j] = int(ceil(grid_std_accuracy[i][j] * workfactor_accuracy))\n\n for i in complexities.keys():\n complexities[i][\"Workfactor time\"] = 0\n complexities[i][\"Workfactor memory\"] = 0\n\n nr_algorithms = 7 - len(skip)\n nr_algorithms += 1 if \"BJMM-dw\" in skip else 0\n nr_algorithms += 1 if \"BJMM-p-dw\" in skip or \"BJMM-pdw\" in skip else 0\n bar = Bar('Computing theoretical workfactors\\t', max=nr_algorithms)\n\n if \"prange\" not in skip:\n T, M = prange_workfactor(rate, omega, grid_std_accuracy[\"prange\"][0], grid_std_accuracy[\"prange\"][1],\n memory_limit)\n complexities[\"Prange\"][\"Workfactor time\"] = T\n complexities[\"Prange\"][\"Workfactor memory\"] = M\n bar.next()\n if \"stern\" not in skip:\n T, M = stern_workfactor(rate, omega, grid_std_accuracy[\"stern\"][0], grid_std_accuracy[\"stern\"][1], memory_limit)\n complexities[\"Stern\"][\"Workfactor time\"] = T\n complexities[\"Stern\"][\"Workfactor memory\"] = M\n bar.next()\n if \"dumer\" not in skip:\n T, M = dumer_workfactor(rate, omega, grid_std_accuracy[\"dumer\"][0], grid_std_accuracy[\"dumer\"][1], memory_limit)\n complexities[\"Dumer\"][\"Workfactor time\"] = T\n complexities[\"Dumer\"][\"Workfactor memory\"] = M\n bar.next()\n if \"ball_collision\" not in skip:\n T, M = ball_collision_workfactor(rate, omega, grid_std_accuracy[\"ball_collision\"][0],\n grid_std_accuracy[\"ball_collision\"][1], memory_limit)\n complexities[\"Ball Collision\"][\"Workfactor time\"] = T\n complexities[\"Ball Collision\"][\"Workfactor memory\"] = M\n bar.next()\n if \"BJMM\" not in skip and \"MMT\" not in skip:\n T, M = bjmm_workfactor(rate, omega, grid_std_accuracy[\"bjmm\"][0], grid_std_accuracy[\"bjmm\"][1], memory_limit)\n complexities[\"BJMM (MMT)\"][\"Workfactor time\"] = T\n complexities[\"BJMM (MMT)\"][\"Workfactor memory\"] = M\n bar.next()\n if \"MO\" not in skip and \"May-Ozerov\" not in skip:\n T, M = may_ozerov_workfactor(rate, omega, grid_std_accuracy[\"may-ozerov\"][0],\n grid_std_accuracy[\"may-ozerov\"][1], memory_limit, use_mo)\n complexities[\"May-Ozerov\"][\"Workfactor time\"] = T\n complexities[\"May-Ozerov\"][\"Workfactor memory\"] = M\n bar.next()\n if \"BM\" not in skip and \"Both-May\" not in skip:\n T, M = both_may_workfactor(rate, omega, grid_std_accuracy[\"both-may\"][0], grid_std_accuracy[\"both-may\"][1],\n memory_limit, use_mo)\n complexities[\"Both-May\"][\"Workfactor time\"] = T\n complexities[\"Both-May\"][\"Workfactor memory\"] = M\n bar.next()\n\n bar.finish()\n\n\ndef _sd_estimate(n, k, w, theoretical_estimates, memory_limit, bit_complexities, hmap, skip, use_mo,\n workfactor_accuracy, limit_depth, quantum_estimates, maxdepth, matrix_mult_constant, memory_access):\n \"\"\"\n Estimate complexity to solve syndrome decoding problem\n\n INPUT:\n\n - ``n`` -- length of the code\n - ``k`` -- dimension of the code\n - ``w`` -- Hamming weight of error vector\n - ``memory_limit`` -- upper bound on the available memory (as log2(bits))\n - ``hmap`` -- indicates if hashmap should be used for sorting lists\n - ``skip`` -- list of algorithms not to consider\n - ``use_mo`` -- use may-ozerov nearest neighbor search in theoretical workfactor computation\n - ``workfactor_accuracy`` -- the higher the more accurate the workfactor computation, can slow down computations significantly, recommended range 0-2 (needs to be larger than 0)\n\n \"\"\"\n\n complexities = {}\n if bit_complexities:\n memory_limit -= log2(n)\n\n nr_algorithms = 9 - len(skip)\n bar = Bar('Computing estimates\\t\\t\\t', max=nr_algorithms)\n\n if \"prange\" not in skip:\n complexities[\"Prange\"] = prange_complexity(n, k, w, mem=memory_limit, memory_access=memory_access)\n if quantum_estimates:\n complexities[\"Prange\"][\"quantum time\"] = quantum_prange_complexity(n, k, w, maxdepth=maxdepth,\n matrix_mult_constant=matrix_mult_constant)\n bar.next()\n\n if \"stern\" not in skip:\n complexities[\"Stern\"] = stern_complexity(n, k, w, mem=memory_limit, hmap=hmap, memory_access=memory_access)\n bar.next()\n if \"dumer\" not in skip:\n complexities[\"Dumer\"] = dumer_complexity(n, k, w, mem=memory_limit, hmap=hmap, memory_access=memory_access)\n bar.next()\n if \"ball_collision\" not in skip:\n complexities[\"Ball Collision\"] = ball_collision_decoding_complexity(n, k, w, mem=memory_limit, hmap=hmap,\n memory_access=memory_access)\n bar.next()\n if \"BJMM\" not in skip and \"MMT\" not in skip:\n complexities[\"BJMM (MMT)\"] = bjmm_complexity(n, k, w, mem=memory_limit, hmap=hmap, only_depth_two=limit_depth,\n memory_access=memory_access)\n bar.next()\n if \"BJMM-pdw\" not in skip and \"BJMM-p-dw\" not in skip:\n complexities[\"BJMM-pdw\"] = bjmm_depth_2_partially_disjoint_weight_complexity(n, k, w, mem=memory_limit,\n hmap=hmap,\n memory_access=memory_access)\n bar.next()\n if \"BJMM-dw\" not in skip:\n complexities[\"BJMM-dw\"] = bjmm_depth_2_disjoint_weight_complexity(n, k, w, mem=memory_limit, hmap=hmap,\n memory_access=memory_access)\n bar.next()\n if \"MO\" not in skip and \"May-Ozerov\" not in skip:\n complexities[\"May-Ozerov\"] = may_ozerov_complexity(n, k, w, mem=memory_limit, hmap=hmap,\n only_depth_two=limit_depth, memory_access=memory_access)\n bar.next()\n if \"BM\" not in skip and \"Both-May\" not in skip:\n complexities[\"Both-May\"] = both_may_depth_2_complexity(n, k, w, mem=memory_limit, hmap=hmap,\n memory_access=memory_access)\n bar.next()\n\n bar.finish()\n if theoretical_estimates:\n _add_theoretical_estimates(complexities, n, k, w, memory_limit, skip, use_mo, workfactor_accuracy)\n\n if bit_complexities:\n field_op = log2(n)\n for i in complexities.keys():\n complexities[i][\"time\"] += field_op\n complexities[i][\"memory\"] += field_op\n\n return complexities\n"
] | [
[
"scipy.special.binom",
"scipy.optimize.fsolve"
]
] |
Siddhant085/tensorflow | [
"6f6161a0110d99b2655efc9d933b753dadadbc38"
] | [
"tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.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\"\"\"Tests for GBDT estimator.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport tempfile\nfrom tensorflow.contrib.boosted_trees.estimator_batch import estimator\nfrom tensorflow.contrib.boosted_trees.proto import learner_pb2\nfrom tensorflow.contrib.layers.python.layers import feature_column as contrib_feature_column\nfrom tensorflow.contrib.learn.python.learn.estimators import run_config\nfrom tensorflow.python.estimator.canned import head as head_lib\nfrom tensorflow.python.feature_column import feature_column_lib as core_feature_column\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops.losses import losses\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import googletest\n\n\ndef _train_input_fn():\n features = {\"x\": constant_op.constant([[2.], [1.], [1.]])}\n label = constant_op.constant([[1], [0], [0]], dtype=dtypes.int32)\n return features, label\n\n\ndef _ranking_train_input_fn():\n features = {\n \"a.f1\": constant_op.constant([[3.], [0.3], [1.]]),\n \"a.f2\": constant_op.constant([[0.1], [3.], [1.]]),\n \"b.f1\": constant_op.constant([[13.], [0.4], [5.]]),\n \"b.f2\": constant_op.constant([[1.], [3.], [0.01]]),\n }\n label = constant_op.constant([[0], [0], [1]], dtype=dtypes.int32)\n return features, label\n\n\ndef _eval_input_fn():\n features = {\"x\": constant_op.constant([[1.], [2.], [2.]])}\n label = constant_op.constant([[0], [1], [1]], dtype=dtypes.int32)\n return features, label\n\n\ndef _infer_ranking_train_input_fn():\n features = {\n \"f1\": constant_op.constant([[3.], [2], [1.]]),\n \"f2\": constant_op.constant([[0.1], [3.], [1.]])\n }\n return features, None\n\n\nclass BoostedTreeEstimatorTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n self._export_dir_base = tempfile.mkdtemp() + \"export/\"\n gfile.MkDir(self._export_dir_base)\n\n def testFitAndEvaluateDontThrowException(self):\n learner_config = learner_pb2.LearnerConfig()\n learner_config.num_classes = 2\n learner_config.constraints.max_tree_depth = 1\n model_dir = tempfile.mkdtemp()\n config = run_config.RunConfig()\n\n classifier = estimator.GradientBoostedDecisionTreeClassifier(\n learner_config=learner_config,\n num_trees=1,\n examples_per_layer=3,\n model_dir=model_dir,\n config=config,\n feature_columns=[contrib_feature_column.real_valued_column(\"x\")])\n\n classifier.fit(input_fn=_train_input_fn, steps=15)\n classifier.evaluate(input_fn=_eval_input_fn, steps=1)\n classifier.export(self._export_dir_base)\n\n def testThatLeafIndexIsInPredictions(self):\n learner_config = learner_pb2.LearnerConfig()\n learner_config.num_classes = 2\n learner_config.constraints.max_tree_depth = 1\n model_dir = tempfile.mkdtemp()\n config = run_config.RunConfig()\n\n classifier = estimator.GradientBoostedDecisionTreeClassifier(\n learner_config=learner_config,\n num_trees=1,\n examples_per_layer=3,\n model_dir=model_dir,\n config=config,\n feature_columns=[contrib_feature_column.real_valued_column(\"x\")],\n output_leaf_index=True)\n\n classifier.fit(input_fn=_train_input_fn, steps=15)\n result_iter = classifier.predict(input_fn=_eval_input_fn)\n for prediction_dict in result_iter:\n self.assertTrue(\"leaf_index\" in prediction_dict)\n self.assertTrue(\"logits\" in prediction_dict)\n\n def testFitAndEvaluateDontThrowExceptionWithCoreForEstimator(self):\n learner_config = learner_pb2.LearnerConfig()\n learner_config.num_classes = 2\n learner_config.constraints.max_tree_depth = 1\n model_dir = tempfile.mkdtemp()\n config = run_config.RunConfig()\n\n # Use core head\n head_fn = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss(\n loss_reduction=losses.Reduction.SUM_OVER_BATCH_SIZE)\n\n model = estimator.GradientBoostedDecisionTreeEstimator(\n head=head_fn,\n learner_config=learner_config,\n num_trees=1,\n examples_per_layer=3,\n model_dir=model_dir,\n config=config,\n feature_columns=[core_feature_column.numeric_column(\"x\")],\n use_core_libs=True)\n\n model.fit(input_fn=_train_input_fn, steps=15)\n model.evaluate(input_fn=_eval_input_fn, steps=1)\n model.export(self._export_dir_base)\n\n def testFitAndEvaluateDontThrowExceptionWithCoreForClassifier(self):\n learner_config = learner_pb2.LearnerConfig()\n learner_config.num_classes = 2\n learner_config.constraints.max_tree_depth = 1\n model_dir = tempfile.mkdtemp()\n config = run_config.RunConfig()\n\n classifier = estimator.GradientBoostedDecisionTreeClassifier(\n learner_config=learner_config,\n num_trees=1,\n examples_per_layer=3,\n model_dir=model_dir,\n config=config,\n feature_columns=[core_feature_column.numeric_column(\"x\")],\n use_core_libs=True)\n\n classifier.fit(input_fn=_train_input_fn, steps=15)\n classifier.evaluate(input_fn=_eval_input_fn, steps=1)\n classifier.export(self._export_dir_base)\n\n def testFitAndEvaluateDontThrowExceptionWithCoreForRegressor(self):\n learner_config = learner_pb2.LearnerConfig()\n learner_config.num_classes = 2\n learner_config.constraints.max_tree_depth = 1\n model_dir = tempfile.mkdtemp()\n config = run_config.RunConfig()\n\n regressor = estimator.GradientBoostedDecisionTreeRegressor(\n learner_config=learner_config,\n num_trees=1,\n examples_per_layer=3,\n model_dir=model_dir,\n config=config,\n feature_columns=[core_feature_column.numeric_column(\"x\")],\n use_core_libs=True)\n\n regressor.fit(input_fn=_train_input_fn, steps=15)\n regressor.evaluate(input_fn=_eval_input_fn, steps=1)\n regressor.export(self._export_dir_base)\n\n def testRankingDontThrowExceptionForForEstimator(self):\n learner_config = learner_pb2.LearnerConfig()\n learner_config.num_classes = 2\n learner_config.constraints.max_tree_depth = 1\n model_dir = tempfile.mkdtemp()\n config = run_config.RunConfig()\n\n head_fn = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss(\n loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)\n\n model = estimator.GradientBoostedDecisionTreeRanker(\n head=head_fn,\n learner_config=learner_config,\n num_trees=1,\n examples_per_layer=3,\n model_dir=model_dir,\n config=config,\n use_core_libs=True,\n feature_columns=[\n core_feature_column.numeric_column(\"f1\"),\n core_feature_column.numeric_column(\"f2\")\n ],\n ranking_model_pair_keys=(\"a\", \"b\"))\n\n model.fit(input_fn=_ranking_train_input_fn, steps=1000)\n model.evaluate(input_fn=_ranking_train_input_fn, steps=1)\n model.predict(input_fn=_infer_ranking_train_input_fn)\n\n\nclass CoreGradientBoostedDecisionTreeEstimator(test_util.TensorFlowTestCase):\n\n def testTrainEvaluateInferDoesNotThrowError(self):\n head_fn = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss(\n loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)\n\n learner_config = learner_pb2.LearnerConfig()\n learner_config.num_classes = 2\n learner_config.constraints.max_tree_depth = 1\n model_dir = tempfile.mkdtemp()\n config = run_config.RunConfig()\n\n est = estimator.CoreGradientBoostedDecisionTreeEstimator(\n head=head_fn,\n learner_config=learner_config,\n num_trees=1,\n examples_per_layer=3,\n model_dir=model_dir,\n config=config,\n feature_columns=[core_feature_column.numeric_column(\"x\")])\n\n # Train for a few steps.\n est.train(input_fn=_train_input_fn, steps=1000)\n est.evaluate(input_fn=_eval_input_fn, steps=1)\n est.predict(input_fn=_eval_input_fn)\n\n\nif __name__ == \"__main__\":\n googletest.main()\n"
] | [
[
"tensorflow.python.feature_column.feature_column_lib.numeric_column",
"tensorflow.contrib.layers.python.layers.feature_column.real_valued_column",
"tensorflow.python.platform.googletest.main",
"tensorflow.python.estimator.canned.head._binary_logistic_head_with_sigmoid_cross_entropy_loss",
"tensorflow.contrib.boosted_trees.proto.learner_pb2.LearnerConfig",
"tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig",
"tensorflow.python.platform.gfile.MkDir",
"tensorflow.python.framework.constant_op.constant"
]
] |
aliabdelkader/FusionTransformer | [
"4175e13a3633a6c6b8b2aa44beb94a89acf7307f"
] | [
"FusionTransformer/common/utils/torch_util.py"
] | [
"import random\nimport numpy as np\nimport torch\n\n\ndef set_random_seed(seed):\n if seed < 0:\n return\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\ndef worker_init_fn(worker_id):\n \"\"\"The function is designed for pytorch multi-process dataloader.\n Note that we use the pytorch random generator to generate a base_seed.\n Please try to be consistent.\n\n References:\n https://pytorch.org/docs/stable/notes/faq.html#dataloader-workers-random-seed\n\n \"\"\"\n base_seed = torch.IntTensor(1).random_().item()\n # print(worker_id, base_seed)\n np.random.seed(base_seed + worker_id)\n\ndef dist_worker_init_fn(worker_id):\n\n worker_seed = torch.initial_seed() % 2**32\n np.random.seed(worker_seed)\n random.seed(worker_seed)"
] | [
[
"torch.cuda.manual_seed_all",
"torch.cuda.manual_seed",
"torch.manual_seed",
"torch.initial_seed",
"numpy.random.seed",
"torch.IntTensor"
]
] |
beiyan1911/conditional_aia_generation | [
"0ace640d6e8dae41b63f26809a494b88cc3718e2"
] | [
"models/base_model.py"
] | [
"import os\nfrom abc import ABC, abstractmethod\nfrom collections import OrderedDict\nimport torch.optim as optim\nimport torch\nfrom models import net_utils\n\n\nclass BaseModel(ABC):\n\n def __init__(self, config):\n self.config = config\n self.isTrain = config.isTrain\n self.device = config.device\n torch.backends.cudnn.benchmark = True\n self.loss_names = []\n self.model_names = []\n self.visual_names = []\n self.optimizers = []\n self.loss_stack = OrderedDict()\n self.metric = 0 # used for learning rate policy 'plateau'\n\n # 设置输入数据\n @abstractmethod\n def set_input(self, input):\n pass\n\n @abstractmethod\n def forward(self):\n pass\n\n @abstractmethod\n def optimize_parameters(self):\n pass\n\n def setup(self, opt):\n \"\"\"\n create schedulers\n \"\"\"\n if self.isTrain:\n self.schedulers = [optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.epoch_num, eta_min=1e-6) for\n optimizer in self.optimizers]\n\n if opt.resume:\n for per_scheduler in self.schedulers:\n per_scheduler.step(opt.resume_count)\n print('re-adjust learning rate')\n\n @abstractmethod\n def test(self):\n pass\n\n def get_lr(self):\n lr = self.optimizers[0].param_groups[0]['lr']\n return lr\n\n def update_learning_rate(self, epoch):\n \"\"\"Update learning rates for all the models; called at the end of every epoch\"\"\"\n for scheduler in self.schedulers:\n scheduler.step()\n # lr = self.optimizers[0].param_groups[0]['lr']\n # print('learning rate = %.7f' % lr)\n\n # 返回输出结果\n def get_current_np_outputs(self):\n pass\n\n # 返回 loss names\n def get_loss_names(self):\n return self.loss_names\n\n # 返回最近的loss值\n def get_current_losses(self):\n loss_dict = OrderedDict()\n for name in self.loss_names:\n if isinstance(name, str):\n loss_dict[name] = float(getattr(self, 'loss_' + name))\n return loss_dict\n\n # **************************** save、load、print models *****************************#\n\n def save_networks(self, epoch):\n \"\"\"Save all the models to the disk.\n\n Parameters:\n epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)\n \"\"\"\n for name in self.model_names:\n if isinstance(name, str):\n save_filename = 'epoch_%d_net_%s.pth' % (epoch, name)\n save_path = os.path.join(self.config.checkpoints_dir, save_filename)\n net = getattr(self, 'net' + name)\n\n torch.save(net.state_dict(), save_path)\n print('save epoch %d models to file !' % epoch)\n\n def load_networks(self, epoch):\n \"\"\"Load all the models from the disk.\n\n Parameters:\n epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)\n \"\"\"\n for name in self.model_names:\n if isinstance(name, str):\n load_filename = 'epoch_%d_net_%s.pth' % (epoch, name)\n load_path = os.path.join(self.config.checkpoints_dir, load_filename)\n if not os.path.exists(load_path):\n continue\n net = getattr(self, 'net' + name)\n print('loading the models from %s' % load_path)\n state_dict = torch.load(load_path, map_location=str(self.device))\n if hasattr(state_dict, '_metadata'):\n del state_dict._metadata\n\n net.load_state_dict(state_dict)\n\n def print_networks(self):\n \"\"\"Print the total number of parameters in the network and (if verbose) network architecture\n\n Parameters:\n verbose (bool) -- if verbose: print the network architecture\n \"\"\"\n print('---------- Networks initialized -------------')\n for name in self.model_names:\n if isinstance(name, str):\n net = getattr(self, 'net' + name)\n num_params = 0\n for param in net.parameters():\n num_params += param.numel()\n print(net)\n print('[Network %s] Total number of parameters : %.3f M' % (name, num_params / 1e6))\n print('-----------------------------------------------')\n\n def train(self):\n \"\"\"Make models eval mode during test time\"\"\"\n for name in self.model_names:\n if isinstance(name, str):\n net = getattr(self, 'net' + name)\n net.train()\n\n def eval(self):\n \"\"\"Make models eval mode during test time\"\"\"\n for name in self.model_names:\n if isinstance(name, str):\n net = getattr(self, 'net' + name)\n net.eval()\n\n def set_requires_grad(self, nets, requires_grad=False):\n \"\"\"Set requies_grad=Fasle for all the models to avoid unnecessary computations\n Parameters:\n nets (network list) -- a list of models\n requires_grad (bool) -- whether the models require gradients or not\n \"\"\"\n if not isinstance(nets, list):\n nets = [nets]\n for net in nets:\n if net is not None:\n for param in net.parameters():\n param.requires_grad = requires_grad\n"
] | [
[
"torch.optim.lr_scheduler.CosineAnnealingLR"
]
] |
andrejromanov/dd-trace-py | [
"661011e891d4699006614b1a238096d7140cc55c"
] | [
"tests/tracer/test_span.py"
] | [
"# -*- coding: utf-8 -*-\nimport time\nfrom unittest.case import SkipTest\n\nimport mock\nimport pytest\n\nfrom ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY\nfrom ddtrace.constants import ENV_KEY\nfrom ddtrace.constants import SERVICE_VERSION_KEY\nfrom ddtrace.constants import SPAN_MEASURED_KEY\nfrom ddtrace.constants import VERSION_KEY\nfrom ddtrace.ext import SpanTypes\nfrom ddtrace.ext import errors\nfrom ddtrace.span import Span\nfrom tests import TracerTestCase\nfrom tests import assert_is_measured\nfrom tests import assert_is_not_measured\n\n\nclass SpanTestCase(TracerTestCase):\n def test_ids(self):\n s = Span(tracer=None, name=\"span.test\")\n assert s.trace_id\n assert s.span_id\n assert not s.parent_id\n\n s2 = Span(tracer=None, name=\"t\", trace_id=1, span_id=2, parent_id=1)\n assert s2.trace_id == 1\n assert s2.span_id == 2\n assert s2.parent_id == 1\n\n def test_tags(self):\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(\"a\", \"a\")\n s.set_tag(\"b\", 1)\n s.set_tag(\"c\", \"1\")\n d = s.to_dict()\n assert d[\"meta\"] == dict(a=\"a\", c=\"1\")\n assert d[\"metrics\"] == dict(b=1)\n\n def test_numeric_tags(self):\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(\"negative\", -1)\n s.set_tag(\"zero\", 0)\n s.set_tag(\"positive\", 1)\n s.set_tag(\"large_int\", 2 ** 53)\n s.set_tag(\"really_large_int\", (2 ** 53) + 1)\n s.set_tag(\"large_negative_int\", -(2 ** 53))\n s.set_tag(\"really_large_negative_int\", -((2 ** 53) + 1))\n s.set_tag(\"float\", 12.3456789)\n s.set_tag(\"negative_float\", -12.3456789)\n s.set_tag(\"large_float\", 2.0 ** 53)\n s.set_tag(\"really_large_float\", (2.0 ** 53) + 1)\n\n d = s.to_dict()\n assert d[\"meta\"] == dict(\n really_large_int=str(((2 ** 53) + 1)),\n really_large_negative_int=str(-((2 ** 53) + 1)),\n )\n assert d[\"metrics\"] == {\n \"negative\": -1,\n \"zero\": 0,\n \"positive\": 1,\n \"large_int\": 2 ** 53,\n \"large_negative_int\": -(2 ** 53),\n \"float\": 12.3456789,\n \"negative_float\": -12.3456789,\n \"large_float\": 2.0 ** 53,\n \"really_large_float\": (2.0 ** 53) + 1,\n }\n\n def test_set_tag_bool(self):\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(\"true\", True)\n s.set_tag(\"false\", False)\n\n d = s.to_dict()\n assert d[\"meta\"] == dict(true=\"True\", false=\"False\")\n assert \"metrics\" not in d\n\n def test_set_tag_metric(self):\n s = Span(tracer=None, name=\"test.span\")\n\n s.set_tag(\"test\", \"value\")\n assert s.meta == dict(test=\"value\")\n assert s.metrics == dict()\n\n s.set_tag(\"test\", 1)\n assert s.meta == dict()\n assert s.metrics == dict(test=1)\n\n def test_set_valid_metrics(self):\n s = Span(tracer=None, name=\"test.span\")\n s.set_metric(\"a\", 0)\n s.set_metric(\"b\", -12)\n s.set_metric(\"c\", 12.134)\n s.set_metric(\"d\", 1231543543265475686787869123)\n s.set_metric(\"e\", \"12.34\")\n d = s.to_dict()\n expected = {\n \"a\": 0,\n \"b\": -12,\n \"c\": 12.134,\n \"d\": 1231543543265475686787869123,\n \"e\": 12.34,\n }\n assert d[\"metrics\"] == expected\n\n def test_set_invalid_metric(self):\n s = Span(tracer=None, name=\"test.span\")\n\n invalid_metrics = [None, {}, [], s, \"quarante-douze\", float(\"nan\"), float(\"inf\"), 1j]\n\n for i, m in enumerate(invalid_metrics):\n k = str(i)\n s.set_metric(k, m)\n assert s.get_metric(k) is None\n\n def test_set_numpy_metric(self):\n try:\n import numpy as np\n except ImportError:\n raise SkipTest(\"numpy not installed\")\n s = Span(tracer=None, name=\"test.span\")\n s.set_metric(\"a\", np.int64(1))\n assert s.get_metric(\"a\") == 1\n assert type(s.get_metric(\"a\")) == float\n\n def test_tags_not_string(self):\n # ensure we can cast as strings\n class Foo(object):\n def __repr__(self):\n 1 / 0\n\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(\"a\", Foo())\n\n def test_finish(self):\n # ensure span.finish() marks the end time of the span\n s = Span(None, \"test.span\")\n sleep = 0.05\n time.sleep(sleep)\n s.finish()\n assert s.duration >= sleep, \"%s < %s\" % (s.duration, sleep)\n\n def test_finish_no_tracer(self):\n # ensure finish works with no tracer without raising exceptions\n s = Span(tracer=None, name=\"test.span\")\n s.finish()\n\n def test_finish_called_multiple_times(self):\n # we should only record a span the first time finish is called on it\n s = Span(self.tracer, \"bar\")\n s.finish()\n s.finish()\n\n def test_finish_set_span_duration(self):\n # If set the duration on a span, the span should be recorded with this\n # duration\n s = Span(tracer=None, name=\"test.span\")\n s.duration = 1337.0\n s.finish()\n assert s.duration == 1337.0\n\n def test_setter_casts_duration_ns_as_int(self):\n s = Span(tracer=None, name=\"test.span\")\n s.duration = 3.2\n s.finish()\n assert s.duration == 3.2\n assert s.duration_ns == 3200000000\n assert isinstance(s.duration_ns, int)\n\n def test_get_span_returns_none_by_default(self):\n s = Span(tracer=None, name=\"test.span\")\n assert s.duration is None\n\n def test_traceback_with_error(self):\n s = Span(None, \"test.span\")\n try:\n 1 / 0\n except ZeroDivisionError:\n s.set_traceback()\n else:\n assert 0, \"should have failed\"\n\n assert s.error\n assert \"by zero\" in s.get_tag(errors.ERROR_MSG)\n assert \"ZeroDivisionError\" in s.get_tag(errors.ERROR_TYPE)\n\n def test_traceback_without_error(self):\n s = Span(None, \"test.span\")\n s.set_traceback()\n assert not s.error\n assert not s.get_tag(errors.ERROR_MSG)\n assert not s.get_tag(errors.ERROR_TYPE)\n assert \"in test_traceback_without_error\" in s.get_tag(errors.ERROR_STACK)\n\n def test_ctx_mgr(self):\n s = Span(self.tracer, \"bar\")\n assert not s.duration\n assert not s.error\n\n e = Exception(\"boo\")\n try:\n with s:\n time.sleep(0.01)\n raise e\n except Exception as out:\n assert out == e\n assert s.duration > 0, s.duration\n assert s.error\n assert s.get_tag(errors.ERROR_MSG) == \"boo\"\n assert \"Exception\" in s.get_tag(errors.ERROR_TYPE)\n assert s.get_tag(errors.ERROR_STACK)\n\n else:\n assert 0, \"should have failed\"\n\n def test_span_type(self):\n s = Span(tracer=None, name=\"test.span\", service=\"s\", resource=\"r\", span_type=SpanTypes.WEB)\n s.set_tag(\"a\", \"1\")\n s.set_meta(\"b\", \"2\")\n s.finish()\n\n d = s.to_dict()\n assert d\n assert d[\"span_id\"] == s.span_id\n assert d[\"trace_id\"] == s.trace_id\n assert d[\"parent_id\"] == s.parent_id\n assert d[\"meta\"] == {\"a\": \"1\", \"b\": \"2\"}\n assert d[\"type\"] == \"web\"\n assert d[\"error\"] == 0\n assert type(d[\"error\"]) == int\n\n def test_span_to_dict(self):\n s = Span(tracer=None, name=\"test.span\", service=\"s\", resource=\"r\")\n s.span_type = \"foo\"\n s.set_tag(\"a\", \"1\")\n s.set_meta(\"b\", \"2\")\n s.finish()\n\n d = s.to_dict()\n assert d\n assert d[\"span_id\"] == s.span_id\n assert d[\"trace_id\"] == s.trace_id\n assert d[\"parent_id\"] == s.parent_id\n assert d[\"meta\"] == {\"a\": \"1\", \"b\": \"2\"}\n assert d[\"type\"] == \"foo\"\n assert d[\"error\"] == 0\n assert type(d[\"error\"]) == int\n\n def test_span_to_dict_sub(self):\n parent = Span(tracer=None, name=\"test.span\", service=\"s\", resource=\"r\")\n s = Span(tracer=None, name=\"test.span\", service=\"s\", resource=\"r\")\n s._parent = parent\n s.span_type = \"foo\"\n s.set_tag(\"a\", \"1\")\n s.set_meta(\"b\", \"2\")\n s.finish()\n\n d = s.to_dict()\n assert d\n assert d[\"span_id\"] == s.span_id\n assert d[\"trace_id\"] == s.trace_id\n assert d[\"parent_id\"] == s.parent_id\n assert d[\"meta\"] == {\"a\": \"1\", \"b\": \"2\"}\n assert d[\"type\"] == \"foo\"\n assert d[\"error\"] == 0\n assert type(d[\"error\"]) == int\n\n def test_span_boolean_err(self):\n s = Span(tracer=None, name=\"foo.bar\", service=\"s\", resource=\"r\")\n s.error = True\n s.finish()\n\n d = s.to_dict()\n assert d\n assert d[\"error\"] == 1\n assert type(d[\"error\"]) == int\n\n @mock.patch(\"ddtrace.span.log\")\n def test_numeric_tags_none(self, span_log):\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, None)\n d = s.to_dict()\n assert d\n assert \"metrics\" not in d\n\n # Ensure we log a debug message\n span_log.debug.assert_called_once_with(\n \"ignoring not number metric %s:%s\",\n ANALYTICS_SAMPLE_RATE_KEY,\n None,\n )\n\n def test_numeric_tags_true(self):\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, True)\n d = s.to_dict()\n assert d\n expected = {ANALYTICS_SAMPLE_RATE_KEY: 1.0}\n assert d[\"metrics\"] == expected\n\n def test_numeric_tags_value(self):\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, 0.5)\n d = s.to_dict()\n assert d\n expected = {ANALYTICS_SAMPLE_RATE_KEY: 0.5}\n assert d[\"metrics\"] == expected\n\n def test_numeric_tags_bad_value(self):\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, \"Hello\")\n d = s.to_dict()\n assert d\n assert \"metrics\" not in d\n\n def test_set_tag_none(self):\n s = Span(tracer=None, name=\"root.span\", service=\"s\", resource=\"r\")\n assert s.meta == dict()\n\n s.set_tag(\"custom.key\", \"100\")\n\n assert s.meta == {\"custom.key\": \"100\"}\n\n s.set_tag(\"custom.key\", None)\n\n assert s.meta == {\"custom.key\": \"None\"}\n\n def test_duration_zero(self):\n s = Span(tracer=None, name=\"foo.bar\", service=\"s\", resource=\"r\", start=123)\n s.finish(finish_time=123)\n assert s.duration_ns == 0\n assert s.duration == 0\n\n def test_start_int(self):\n s = Span(tracer=None, name=\"foo.bar\", service=\"s\", resource=\"r\", start=123)\n assert s.start == 123\n assert s.start_ns == 123000000000\n\n s = Span(tracer=None, name=\"foo.bar\", service=\"s\", resource=\"r\", start=123.123)\n assert s.start == 123.123\n assert s.start_ns == 123123000000\n\n s = Span(tracer=None, name=\"foo.bar\", service=\"s\", resource=\"r\", start=123.123)\n s.start = 234567890.0\n assert s.start == 234567890\n assert s.start_ns == 234567890000000000\n\n def test_duration_int(self):\n s = Span(tracer=None, name=\"foo.bar\", service=\"s\", resource=\"r\")\n s.finish()\n assert isinstance(s.duration_ns, int)\n assert isinstance(s.duration, float)\n\n s = Span(tracer=None, name=\"foo.bar\", service=\"s\", resource=\"r\", start=123)\n s.finish(finish_time=123.2)\n assert s.duration_ns == 200000000\n assert s.duration == 0.2\n\n s = Span(tracer=None, name=\"foo.bar\", service=\"s\", resource=\"r\", start=123.1)\n s.finish(finish_time=123.2)\n assert s.duration_ns == 100000000\n assert s.duration == 0.1\n\n s = Span(tracer=None, name=\"foo.bar\", service=\"s\", resource=\"r\", start=122)\n s.finish(finish_time=123)\n assert s.duration_ns == 1000000000\n assert s.duration == 1\n\n def test_set_tag_version(self):\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(VERSION_KEY, \"1.2.3\")\n assert s.get_tag(VERSION_KEY) == \"1.2.3\"\n assert s.get_tag(SERVICE_VERSION_KEY) is None\n\n s.set_tag(SERVICE_VERSION_KEY, \"service.version\")\n assert s.get_tag(VERSION_KEY) == \"service.version\"\n assert s.get_tag(SERVICE_VERSION_KEY) == \"service.version\"\n\n def test_set_tag_env(self):\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(ENV_KEY, \"prod\")\n assert s.get_tag(ENV_KEY) == \"prod\"\n\n\[email protected](\n \"value,assertion\",\n [\n (None, assert_is_measured),\n (1, assert_is_measured),\n (1.0, assert_is_measured),\n (-1, assert_is_measured),\n (True, assert_is_measured),\n (\"true\", assert_is_measured),\n # DEV: Ends up being measured because we do `bool(\"false\")` which is `True`\n (\"false\", assert_is_measured),\n (0, assert_is_not_measured),\n (0.0, assert_is_not_measured),\n (False, assert_is_not_measured),\n ],\n)\ndef test_set_tag_measured(value, assertion):\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(SPAN_MEASURED_KEY, value)\n assertion(s)\n\n\ndef test_set_tag_measured_not_set():\n # Span is not measured by default\n s = Span(tracer=None, name=\"test.span\")\n assert_is_not_measured(s)\n\n\ndef test_set_tag_measured_no_value():\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(SPAN_MEASURED_KEY)\n assert_is_measured(s)\n\n\ndef test_set_tag_measured_change_value():\n s = Span(tracer=None, name=\"test.span\")\n s.set_tag(SPAN_MEASURED_KEY, True)\n assert_is_measured(s)\n\n s.set_tag(SPAN_MEASURED_KEY, False)\n assert_is_not_measured(s)\n\n s.set_tag(SPAN_MEASURED_KEY)\n assert_is_measured(s)\n\n\[email protected](\"ddtrace.span.log\")\ndef test_span_key(span_log):\n # Span tag keys must be strings\n s = Span(tracer=None, name=\"test.span\")\n\n s.set_tag(123, True)\n span_log.warning.assert_called_once_with(\"Ignoring tag pair %s:%s. Key must be a string.\", 123, True)\n assert s.get_tag(123) is None\n assert s.get_tag(\"123\") is None\n\n span_log.reset_mock()\n\n s.set_tag(None, \"val\")\n span_log.warning.assert_called_once_with(\"Ignoring tag pair %s:%s. Key must be a string.\", None, \"val\")\n assert s.get_tag(123.32) is None\n\n\ndef test_span_finished():\n span = Span(None, None)\n assert span.finished is False\n assert span.duration_ns is None\n\n span.finished = True\n assert span.finished is True\n assert span.duration_ns is not None\n duration = span.duration_ns\n\n span.finished = True\n assert span.finished is True\n assert span.duration_ns == duration\n\n span.finished = False\n assert span.finished is False\n\n span.finished = True\n assert span.finished is True\n assert span.duration_ns != duration\n\n\ndef test_span_unicode_set_tag():\n span = Span(None, None)\n span.set_tag(\"key\", u\"😌\")\n span.set_tag(\"😐\", u\"😌\")\n span._set_str_tag(\"key\", u\"😌\")\n span._set_str_tag(u\"😐\", u\"😌\")\n\n\ndef test_span_ignored_exceptions():\n s = Span(None, None)\n s._ignore_exception(ValueError)\n\n with pytest.raises(ValueError):\n with s:\n raise ValueError()\n\n assert s.error == 0\n assert s.get_tag(errors.ERROR_MSG) is None\n assert s.get_tag(errors.ERROR_TYPE) is None\n assert s.get_tag(errors.ERROR_STACK) is None\n\n s = Span(None, None)\n s._ignore_exception(ValueError)\n\n with pytest.raises(ValueError):\n with s:\n raise ValueError()\n\n with pytest.raises(RuntimeError):\n with s:\n raise RuntimeError()\n\n assert s.error == 1\n assert s.get_tag(errors.ERROR_MSG) is not None\n assert \"RuntimeError\" in s.get_tag(errors.ERROR_TYPE)\n assert s.get_tag(errors.ERROR_STACK) is not None\n\n\ndef test_span_ignored_exception_multi():\n s = Span(None, None)\n s._ignore_exception(ValueError)\n s._ignore_exception(RuntimeError)\n\n with pytest.raises(ValueError):\n with s:\n raise ValueError()\n\n with pytest.raises(RuntimeError):\n with s:\n raise RuntimeError()\n\n assert s.error == 0\n assert s.get_tag(errors.ERROR_MSG) is None\n assert s.get_tag(errors.ERROR_TYPE) is None\n assert s.get_tag(errors.ERROR_STACK) is None\n\n\ndef test_span_ignored_exception_subclass():\n s = Span(None, None)\n s._ignore_exception(Exception)\n\n with pytest.raises(ValueError):\n with s:\n raise ValueError()\n\n with pytest.raises(RuntimeError):\n with s:\n raise RuntimeError()\n\n assert s.error == 0\n assert s.get_tag(errors.ERROR_MSG) is None\n assert s.get_tag(errors.ERROR_TYPE) is None\n assert s.get_tag(errors.ERROR_STACK) is None\n"
] | [
[
"numpy.int64"
]
] |
marwahaha/dit | [
"feaa7dfa87b4f6067039be4ac05c7e645fdcec3c"
] | [
"dit/profiles/base_profile.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThe base information profile.\n\"\"\"\n\nfrom abc import ABCMeta, abstractmethod\n\nfrom six import with_metaclass\n\nimport numpy as np\n\n\nprofile_docstring = \"\"\"\n{name}\n\nStatic Attributes\n-----------------\nxlabel : str\n The label for the x-axis when plotting.\nylabel : str\n The label for the y-axis when plotting.\n{static_attributes}\n\nAttributes\n----------\ndist : Distribution\nprofile : dict\nwidths : [float]\n{attributes}\n\nMethods\n-------\ndraw\n Plot the profile\n{methods}\n\nPrivate Methods\n---------------\n_compute\n Compute the profile\n\"\"\"\n\n\nclass BaseProfile(with_metaclass(ABCMeta, object)):\n \"\"\"\n BaseProfile\n\n Static Attributes\n -----------------\n xlabel : str\n The label for the x-axis when plotting.\n ylabel : str\n The label for the y-axis when plotting.\n\n Attributes\n ----------\n dist : Distribution\n profile : dict\n widths : [float]\n\n Methods\n -------\n draw\n Plot the profile.\n\n Abstract Methods\n ----------------\n _compute\n Compute the profile.\n \"\"\"\n\n xlabel = 'scale'\n ylabel = 'information [bits]'\n align = 'center'\n\n def __init__(self, dist):\n \"\"\"\n Initialize the profile.\n\n Parameters\n ----------\n dist : Distribution\n The distribution to compute the profile for.\n \"\"\"\n super(BaseProfile, self).__init__()\n self.dist = dist.copy(base='linear')\n self._compute()\n\n @abstractmethod\n def _compute(self):\n \"\"\"\n Abstract method to compute the profile.\n \"\"\"\n pass\n\n def draw(self, ax=None): # pragma: no cover\n \"\"\"\n Draw the profile using matplotlib.\n\n Parameters\n ----------\n ax : axis\n The axis to draw the profile on. If None, a new axis is created.\n\n Returns\n -------\n ax : axis\n The axis with profile.\n \"\"\"\n if ax is None:\n import matplotlib.pyplot as plt\n ax = plt.figure().gca()\n\n # pylint: disable=no-member\n left, height = zip(*sorted(self.profile.items()))\n ax.bar(left, height, width=self.widths, align=self.align)\n\n ax.set_xticks(sorted(self.profile.keys()))\n\n ax.set_xlabel(self.xlabel)\n ax.set_ylabel(self.ylabel)\n\n low, high = ax.get_ylim()\n if np.isclose(low, 0, atol=1e-5):\n low = -0.1\n if np.isclose(high, 0, atol=1e-5):\n high = 0.1\n ax.set_ylim((low, high))\n\n return ax\n"
] | [
[
"matplotlib.pyplot.figure",
"numpy.isclose"
]
] |
lgasyou/spark-scheduler-configuration-optimizer | [
"05c0ea9411db642c7c7e675a6949ffcc6814947a"
] | [
"optimizer/environment/yarn/statebuilder.py"
] | [
"from typing import Tuple\n\nimport requests\nimport torch\nfrom requests.exceptions import ConnectionError\n\nfrom optimizer.hyperparameters import STATE_SHAPE\nfrom optimizer.environment.yarn.yarnmodel import *\nfrom optimizer.environment.spark.sparkapplicationtimedelaypredictor import SparkApplicationTimeDelayPredictor\nfrom optimizer.environment.spark.sparkapplicationbuilder import SparkApplicationBuilder\nfrom optimizer.environment.spark.completedsparkapplicationanalyzer import CompletedSparkApplicationAnalyzer\nfrom optimizer.environment.stateinvalidexception import StateInvalidException\nfrom optimizer.util import jsonutil\n\n\nclass StateBuilder(object):\n\n def __init__(self, rm_api_url: str, spark_history_server_api_url: str, scheduler_strategy):\n self.RM_API_URL = rm_api_url\n self.SPARK_HISTORY_SERVER_API_URL = spark_history_server_api_url\n self.scheduler_strategy = scheduler_strategy\n self.application_time_delay_predictor = SparkApplicationTimeDelayPredictor(spark_history_server_api_url)\n self._tmp_add_models()\n\n # TODO: Replace this with train set.\n def _tmp_add_models(self):\n builder = SparkApplicationBuilder(self.SPARK_HISTORY_SERVER_API_URL)\n analyzer = CompletedSparkApplicationAnalyzer()\n predictor = self.application_time_delay_predictor\n\n app = builder.build('application_1562834622700_0051')\n svm_model = analyzer.analyze(app)\n predictor.add_algorithm('linear', svm_model)\n\n # ALS\n app = builder.build('application_1562834622700_0039')\n als_model = analyzer.analyze(app)\n predictor.add_algorithm('als', als_model)\n\n # KMeans\n app = builder.build('application_1562834622700_0018')\n svm_model = analyzer.analyze(app)\n predictor.add_algorithm('kmeans', svm_model)\n\n # SVM\n app = builder.build('application_1562834622700_0014')\n svm_model = analyzer.analyze(app)\n predictor.add_algorithm('svm', svm_model)\n\n # Bayes\n app = builder.build('application_1562834622700_0043')\n svm_model = analyzer.analyze(app)\n predictor.add_algorithm('bayes', svm_model)\n\n # FPGrowth\n app = builder.build('application_1562834622700_0054')\n svm_model = analyzer.analyze(app)\n predictor.add_algorithm('fpgrowth', svm_model)\n\n # LDA\n app = builder.build('application_1562834622700_0058')\n svm_model = analyzer.analyze(app)\n predictor.add_algorithm('lda', svm_model)\n\n def build(self):\n try:\n waiting_apps, running_apps = self.parse_and_build_applications()\n resources = self.parse_and_build_resources()\n constraints = self.parse_and_build_constraints()\n return State(waiting_apps, running_apps, resources, constraints)\n except (ConnectionError, TypeError, requests.exceptions.HTTPError):\n raise StateInvalidException\n\n @staticmethod\n def build_tensor(raw: State):\n height, width = STATE_SHAPE\n tensor = torch.zeros(height, width)\n\n # Line 0-74: waiting apps and their resource requests\n for i, wa in enumerate(raw.waiting_apps[:75]):\n line = [wa.elapsed_time, wa.priority, wa.converted_location]\n for rr in wa.request_resources[:64]:\n line.extend([rr.priority, rr.memory, rr.cpu])\n line.extend([0.0] * (width - len(line)))\n tensor[i] = torch.Tensor(line)\n\n # Line 75-149: running apps and their resource requests\n for i, ra in enumerate(raw.running_apps[:75]):\n row = i + 75\n line = [ra.elapsed_time, ra.priority, ra.converted_location,\n ra.progress, ra.queue_usage_percentage, ra.predicted_time_delay]\n for rr in ra.request_resources[:65]:\n line.extend([rr.priority, rr.memory, rr.cpu])\n line.extend([0.0] * (width - len(line)))\n tensor[row] = torch.Tensor(line)\n\n # Line 150-198: resources of cluster\n row, idx = 150, 0\n for r in raw.resources[:4900]:\n tensor[row][idx] = r.mem\n idx += 1\n tensor[row][idx] = r.vcore_num\n idx += 1\n if idx == width:\n row += 1\n idx = 0\n\n # Line 199: queue constraints\n row, queue_constraints = 199, []\n for c in raw.constraints[:50]:\n queue_constraints.extend([c.converted_name, c.capacity, c.max_capacity, c.used_capacity])\n queue_constraints.extend([0.0] * (width - len(queue_constraints)))\n tensor[row] = torch.Tensor(queue_constraints)\n\n return tensor\n\n def parse_and_build_applications(self) -> Tuple[List[WaitingApplication], List[RunningApplication]]:\n waiting_apps = self.parse_and_build_waiting_apps()\n running_apps = self.parse_and_build_running_apps()\n return waiting_apps, running_apps\n\n def parse_and_build_waiting_apps(self) -> List[WaitingApplication]:\n url = self.RM_API_URL + 'ws/v1/cluster/apps?states=NEW,NEW_SAVING,SUBMITTED,ACCEPTED'\n app_json = jsonutil.get_json(url)\n return self.build_waiting_apps_from_json(app_json)\n\n def parse_and_build_running_apps(self) -> List[RunningApplication]:\n url = self.RM_API_URL + 'ws/v1/cluster/apps?states=RUNNING'\n app_json = jsonutil.get_json(url)\n return self.build_running_apps_from_json(app_json)\n\n def parse_and_build_resources(self) -> List[Resource]:\n url = self.RM_API_URL + 'ws/v1/cluster/nodes'\n conf = jsonutil.get_json(url)\n nodes = conf['nodes']['node']\n resources = []\n for n in nodes:\n memory = (int(n['usedMemoryMB']) + int(n['availMemoryMB'])) / 1024\n vcores = int(n['usedVirtualCores']) + int(n['availableVirtualCores'])\n resources.append(Resource(vcores, int(memory)))\n return resources\n\n def parse_and_build_constraints(self) -> List[QueueConstraint]:\n return self.scheduler_strategy.get_queue_constraints()\n\n def build_running_apps_from_json(self, j: dict) -> List[RunningApplication]:\n if j['apps'] is None:\n return []\n\n apps_json, apps = j['apps']['app'], []\n for j in apps_json:\n application_id = j['id']\n name = j['name']\n elapsed_time = j['elapsedTime']\n priority = j['priority']\n progress = j['progress']\n queue_usage_percentage = j['queueUsagePercentage']\n location = j['queue']\n predicted_time_delay = self.application_time_delay_predictor.predict(application_id, name)\n request_resources = self.build_request_resources_from_json(j)\n apps.append(RunningApplication(application_id, elapsed_time, priority, location, progress,\n queue_usage_percentage, predicted_time_delay, request_resources))\n\n return apps\n\n def build_waiting_apps_from_json(self, j: dict) -> List[WaitingApplication]:\n if j['apps'] is None:\n return []\n\n apps_json = j['apps']['app']\n apps = []\n for j in apps_json:\n elapsed_time = j['elapsedTime']\n priority = j['priority']\n location = j['queue']\n request_resources = self.build_request_resources_from_json(j)\n apps.append(WaitingApplication(elapsed_time, priority, location, request_resources))\n\n return apps\n\n @staticmethod\n def build_request_resources_from_json(j: dict) -> List[ApplicationRequestResource]:\n ret = []\n\n if 'resourceRequests' not in j:\n return ret\n\n resource_requests = j['resourceRequests']\n for req in resource_requests:\n priority = req['priority']\n capability = req['capability']\n memory = capability['memory']\n cpu = capability['vCores']\n ret.append(ApplicationRequestResource(priority, memory, cpu))\n\n return ret\n"
] | [
[
"torch.zeros",
"torch.Tensor"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.