repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
yangyuchi/ACER
[ "573e00f9515c97c2f9828a39753cfc6f5fc4a511" ]
[ "test.py" ]
[ "# -*- coding: utf-8 -*-\nimport time\nfrom datetime import datetime\nimport gym\nimport tensorflow as tf\n\n\ndef test(args, counter, test_net, global_net, sess):\n tf.set_random_seed(args.seed)\n env = gym.make(args.env)\n env.seed(args.seed)\n\n can_test = True # Test flag\n t_start = 1 # Test step counter to check against global counter\n rewards, steps = [], [] # Rewards and steps for plotting\n l = str(len(str(args.max_training_steps))) # Max num. of digits for logging steps\n done = True # Start new episode\n\n # stores step, reward, avg_steps and time\n results_dict = {'t': [], 'reward': [], 'avg_steps': [], 'time': []}\n\n while counter.value() <= args.max_training_steps:\n if can_test:\n t_start = counter.value() # Reset counter\n\n # Evaluate over several episodes and average results\n avg_rewards, avg_episode_lengths = [], []\n for _ in range(args.evaluation_episodes):\n while True:\n # Reset or pass on hidden state\n if done:\n # Sync with shared model every episode\n sess.run([tf.assign(t_p, g_p) for t_p, g_p in zip(test_net.a_params, global_net.a_params)])\n # Reset environment and done flag\n state = env.reset()\n done, episode_length = False, 0\n reward_sum = 0\n\n # Optionally render validation states\n if args.render:\n env.render()\n\n # Choose action greedily\n action = test_net.choose_action(state)\n\n # Step\n state, reward, done, _ = env.step(action)\n reward_sum += reward\n done = done or episode_length >= args.max_episode_length # Stop episodes at a max length\n episode_length += 1 # Increase episode counter\n\n # Log and reset statistics at the end of every episode\n if done:\n avg_rewards.append(reward_sum)\n avg_episode_lengths.append(episode_length)\n break\n\n print(('[{}] Step: {:<' + l + '} Avg. Reward: {:<8} Avg. Episode Length: {:<8}').format(\n datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S,%f')[:-3],\n t_start,\n sum(avg_rewards) / args.evaluation_episodes,\n sum(avg_episode_lengths) / args.evaluation_episodes))\n\n # storing data in the dictionary.\n results_dict['t'].append(t_start)\n results_dict['reward'].append(sum(avg_rewards) / args.evaluation_episodes)\n results_dict['avg_steps'].append(sum(avg_episode_lengths) / args.evaluation_episodes)\n results_dict['time'].append(str(datetime.now()))\n\n rewards.append(avg_rewards) # Keep all evaluations\n steps.append(t_start)\n can_test = False # Finish testing\n else:\n if counter.value() - t_start >= args.evaluation_interval:\n can_test = True\n\n time.sleep(0.001) # Check if available to test every millisecond\n\n env.close()\n" ]
[ [ "tensorflow.set_random_seed", "tensorflow.assign" ] ]
kingaza/keras-gp
[ "0b62224d2fd727143c70385a0a5b40bdc09c5bd8" ]
[ "kgp/backend/engines.py" ]
[ "\"\"\"\nComputational engines used by GP backends.\n\"\"\"\nimport numpy as np\n\n\nclass Engine(object):\n \"\"\"The base class for computational engines.\n \"\"\"\n def addpath(self, path):\n self._eng.addpath(path)\n\n def eval(self, expr, verbose):\n \"\"\"Evaluate an expression.\n \"\"\"\n raise NotImplementedError\n\n def push(self, name, var):\n \"\"\"Push a variable into the engine session under the given name.\n \"\"\"\n raise NotImplementedError\n\n def pull(self, name):\n \"\"\"Pull a variable from the engine session.\n \"\"\"\n raise NotImplementedError\n\n\nclass MATLABEngine(Engine):\n def __init__(self):\n import matlab.engine\n from matlab import double as matdouble\n\n from StringIO import StringIO\n\n self._matarray = matdouble\n self._eng = matlab.engine.start_matlab()\n self._devnull = StringIO()\n\n def push(self, name, var):\n # Convert np.ndarrays into matlab.doubles and push into the workspace\n if type(var) is np.ndarray:\n self._eng.workspace[name] = self._matarray(var.tolist())\n elif type(var) is dict:\n var_copy = var.copy()\n for k, v in var_copy.iteritems():\n if type(v) is np.ndarray:\n var_copy[k] = self._matarray(v.tolist())\n self._eng.workspace[name] = var_copy\n elif type(var) in {list, int, float}:\n self._eng.workspace[name] = var\n else:\n raise ValueError(\"Unknown type (%s) variable being pushed \"\n \"into the MATLAB session.\" % type(var))\n\n def pull(self, name):\n var = self._eng.workspace[name]\n if type(var) is self._matarray:\n var = np.asarray(var)\n elif type(var) is dict:\n for k, v in var.iteritems():\n if type(v) is self._matarray:\n var[k] = np.asarray(v)\n return var\n\n def eval(self, expr, verbose=0):\n assert type(expr) is str\n stdout = None if verbose else self._devnull\n self._eng.eval(expr, nargout=0, stdout=stdout)\n\n\nclass OctaveEngine(Engine):\n def __init__(self, jit_enable=True):\n from oct2py import Oct2Py\n from oct2py import Struct\n\n self._struct = Struct\n self._eng = Oct2Py()\n if jit_enable:\n self._eng.eval('jit_enable(1)', verbose=0)\n self._eng.eval('pkg load statistics', verbose=0)\n\n def push(self, name, var):\n if type(var) is np.ndarray and var.dtype == 'float32':\n # Octave does not support `sparse matrix * dense matrix` operations\n # for float32 type, hence we cast `var` to float64 before pushing\n # into the Octave session\n var = var.astype('float64')\n self._eng.push(name, var)\n\n def pull(self, name):\n var = self._eng.pull(name)\n if type(var) is self._struct:\n var = dict(var)\n return var\n\n def eval(self, expr, verbose=0):\n assert type(expr) is str\n self._eng.eval(expr, verbose=verbose)\n\n" ]
[ [ "numpy.asarray" ] ]
cfpryor/uncertainty-baselines
[ "07c7abe0a196a6d8b4d3f489deb87caafa7b0e9e" ]
[ "baselines/diabetic_retinopathy_detection/jax_finetune_sngp.py" ]
[ "# coding=utf-8\n# Copyright 2022 The Uncertainty Baselines 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\"\"\"Finetune SNGP.\"\"\"\nimport functools\nimport itertools\nimport multiprocessing\nimport os\nimport time\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nfrom clu import metric_writers\nfrom clu import parameter_overview\nfrom clu import periodic_actions\nfrom clu import preprocess_spec\nimport flax\nimport jax\nimport jax.numpy as jnp\nimport ml_collections.config_flags\nimport numpy as np\nimport tensorflow as tf\n\ntf.config.experimental.set_visible_devices([], 'GPU')\ntf.config.experimental.set_visible_devices([], 'TPU_SYSTEM')\ntf.config.experimental.set_visible_devices([], 'TPU')\n\nlogging.info(tf.config.experimental.get_visible_devices())\n\n# pylint: disable=g-import-not-at-top,line-too-long\nimport uncertainty_baselines as ub\nimport checkpoint_utils # local file import from baselines.diabetic_retinopathy_detection\nimport input_utils # local file import from baselines.diabetic_retinopathy_detection\nimport preprocess_utils # local file import from baselines.diabetic_retinopathy_detection\nimport train_utils # local file import from baselines.diabetic_retinopathy_detection\nfrom utils import results_storage_utils\nfrom utils import vit_utils\nimport wandb\n# pylint: enable=g-import-not-at-top,line-too-long\n\nlogging.info(tf.config.experimental.get_visible_devices())\n\n# TODO(nband): lock config after separating total and warmup steps arguments.\nml_collections.config_flags.DEFINE_config_file(\n 'config', None, 'Training configuration.', lock_config=False)\n# Set up extraneous flags for use in Googler job launching.\nflags.DEFINE_string('output_dir', default=None, help='Work unit directory.')\nflags.DEFINE_integer(\n 'num_cores', default=None, help='Unused. How many devices being used.')\nflags.DEFINE_boolean(\n 'use_gpu', default=None, help='Unused. Whether or not running on GPU.')\nflags.DEFINE_string('tpu', None,\n 'Unused. Name of the TPU. Only used if use_gpu is False.')\nFLAGS = flags.FLAGS\n\n\ndef main(argv):\n del argv # unused arg\n\n config = FLAGS.config\n\n # Unpack total and warmup steps\n # TODO(nband): revert this to separate arguments.\n total_steps = config.total_and_warmup_steps[0]\n warmup_steps = config.total_and_warmup_steps[1]\n del config.total_and_warmup_steps\n config.total_steps = total_steps\n config.lr.warmup_steps = warmup_steps\n\n # Wandb and Checkpointing Setup\n output_dir = FLAGS.output_dir\n wandb_run, output_dir = vit_utils.maybe_setup_wandb(config)\n tf.io.gfile.makedirs(output_dir)\n logging.info('Saving checkpoints at %s', output_dir)\n\n # Dataset Split Flags\n dist_shift = config.distribution_shift\n print(f'Distribution Shift: {dist_shift}.')\n dataset_names, split_names = vit_utils.get_dataset_and_split_names(dist_shift)\n\n # LR / Optimization Flags\n batch_size = config.batch_size\n grad_clip_norm = config.grad_clip_norm\n weight_decay = config.weight_decay\n print('Standard wandb hyperparameters:')\n print({\n 'batch_size': batch_size,\n 'grad_clip_norm': grad_clip_norm,\n 'weight_decay': weight_decay,\n 'total_steps': config.total_steps,\n 'lr': config.lr\n })\n print('SNGP Params:', config.gp_layer)\n\n # Reweighting loss for class imbalance\n # class_reweight_mode = config.class_reweight_mode\n # if class_reweight_mode == 'constant':\n # class_weights = utils.get_diabetic_retinopathy_class_balance_weights()\n # else:\n # class_weights = None\n\n # Shows the number of available devices.\n # In a CPU/GPU runtime this will be a single device.\n # In a TPU runtime this will be 8 cores.\n print('Number of Jax local devices:', jax.local_devices())\n\n # TODO(nband): fix sigmoid loss issues.\n assert config.get('loss', None) == 'softmax_xent'\n\n seed = config.seed\n rng = jax.random.PRNGKey(seed)\n tf.random.set_seed(seed)\n\n if config.get('data_dir'):\n logging.info('data_dir=%s', config.data_dir)\n logging.info('Output dir: %s', output_dir)\n\n save_checkpoint_path = None\n if config.get('checkpoint_steps'):\n tf.io.gfile.makedirs(output_dir)\n save_checkpoint_path = os.path.join(output_dir, 'checkpoint.npz')\n\n # Create an asynchronous multi-metric writer.\n writer = metric_writers.create_default_writer(\n output_dir, just_logging=jax.process_index() > 0)\n\n # The pool is used to perform misc operations such as logging in async way.\n pool = multiprocessing.pool.ThreadPool()\n\n def write_note(note):\n if jax.process_index() == 0:\n logging.info('NOTE: %s', note)\n\n write_note('Initializing...')\n\n # Verify settings to make sure no checkpoints are accidentally missed.\n if config.get('keep_checkpoint_steps'):\n assert config.get('checkpoint_steps'), 'Specify `checkpoint_steps`.'\n assert config.keep_checkpoint_steps % config.checkpoint_steps == 0, (\n f'`keep_checkpoint_steps` ({config.checkpoint_steps}) should be'\n f'divisible by `checkpoint_steps ({config.checkpoint_steps}).`')\n\n batch_size_eval = config.get('batch_size_eval', batch_size)\n if (batch_size % jax.device_count() != 0 or\n batch_size_eval % jax.device_count() != 0):\n raise ValueError(f'Batch sizes ({batch_size} and {batch_size_eval}) must '\n f'be divisible by device number ({jax.device_count()})')\n\n local_batch_size = batch_size // jax.process_count()\n local_batch_size_eval = batch_size_eval // jax.process_count()\n logging.info(\n 'Global batch size %d on %d hosts results in %d local batch size. '\n 'With %d dev per host (%d dev total), that is a %d per-device batch size.',\n batch_size,\n jax.process_count(), local_batch_size, jax.local_device_count(),\n jax.device_count(), local_batch_size // jax.local_device_count())\n\n write_note('Initializing preprocessing function...')\n # Same preprocessing function for training and evaluation\n preproc_fn = preprocess_spec.parse(\n spec=config.pp_train, available_ops=preprocess_utils.all_ops())\n\n write_note('Initializing train dataset...')\n rng, train_ds_rng = jax.random.split(rng)\n train_ds_rng = jax.random.fold_in(train_ds_rng, jax.process_index())\n train_base_dataset = ub.datasets.get(\n dataset_names['in_domain_dataset'],\n split=split_names['train_split'],\n data_dir=config.get('data_dir'))\n train_dataset_builder = train_base_dataset._dataset_builder # pylint: disable=protected-access\n train_ds = input_utils.get_data(\n dataset=train_dataset_builder,\n split=split_names['train_split'],\n rng=train_ds_rng,\n process_batch_size=local_batch_size,\n preprocess_fn=preproc_fn,\n shuffle_buffer_size=config.shuffle_buffer_size,\n prefetch_size=config.get('prefetch_to_host', 2),\n data_dir=config.get('data_dir'))\n logging.info('image_size = %s', train_ds.element_spec['image'].shape[1:])\n\n # Start prefetching already.\n train_iter = input_utils.start_input_pipeline(\n train_ds, config.get('prefetch_to_device', 1))\n\n write_note('Initializing val dataset(s)...')\n\n # Load in-domain and OOD validation and/or test datasets.\n # Please specify the desired shift (Country Shift or Severity Shift)\n # in the config.\n eval_iter_splits = vit_utils.init_evaluation_datasets(\n use_validation=config.use_validation,\n use_test=config.use_test,\n dataset_names=dataset_names,\n split_names=split_names,\n config=config,\n preproc_fn=preproc_fn,\n batch_size_eval=batch_size_eval,\n local_batch_size_eval=local_batch_size_eval)\n\n ntrain_img = input_utils.get_num_examples(\n train_dataset_builder,\n split=split_names['train_split'],\n process_batch_size=local_batch_size,\n data_dir=config.get('data_dir'))\n steps_per_epoch = ntrain_img / batch_size\n\n if config.get('num_epochs'):\n total_steps = int(config.num_epochs * steps_per_epoch)\n assert not config.get('total_steps'), 'Set either num_epochs or total_steps'\n else:\n total_steps = config.total_steps\n\n logging.info('Total train data points: %d', ntrain_img)\n logging.info(\n 'Running for %d steps, that means %f epochs and %d steps per epoch',\n total_steps, total_steps * batch_size / ntrain_img, steps_per_epoch)\n\n write_note('Initializing model...')\n logging.info('config.model = %s', config.get('model'))\n\n # Specify Gaussian process layer configs.\n gp_config = config.get('gp_layer', {})\n model_dict = vit_utils.initialize_model('sngp', config)\n model, use_gp_layer = model_dict['model'], model_dict['use_gp_layer']\n\n # We want all parameters to be created in host RAM, not on any device, they'll\n # be sent there later as needed, otherwise we already encountered two\n # situations where we allocate them twice.\n @functools.partial(jax.jit, backend='cpu')\n def init(rng):\n image_size = tuple(train_ds.element_spec['image'].shape[2:])\n logging.info('image_size = %s', image_size)\n dummy_input = jnp.zeros((local_batch_size,) + image_size, jnp.float32)\n variables = model.init(rng, dummy_input, train=False)\n # Split model parameters into trainable and untrainable collections.\n states, params = variables.pop('params')\n del variables\n\n # Set bias in the head to a low value, such that loss is small initially.\n params = flax.core.unfreeze(params)\n if use_gp_layer:\n # Modify the head parameter in the GP head.\n params['head']['output_layer']['bias'] = jnp.full_like(\n params['head']['output_layer']['bias'],\n config.get('init_head_bias', 0))\n else:\n params['head']['bias'] = jnp.full_like(\n params['head']['bias'], config.get('init_head_bias', 0))\n\n return params, states\n\n rng, rng_init = jax.random.split(rng)\n params_cpu, states_cpu = init(rng_init)\n\n if jax.process_index() == 0:\n num_params = sum(p.size for p in jax.tree_flatten(params_cpu)[0])\n parameter_overview.log_parameter_overview(params_cpu)\n writer.write_scalars(step=0, scalars={'num_params': num_params})\n\n @functools.partial(jax.pmap, axis_name='batch')\n def evaluation_fn(params, states, images, labels):\n variable_dict = {'params': flax.core.freeze(params), **states}\n logits, out = model.apply(\n variable_dict,\n images,\n train=False,\n mean_field_factor=gp_config.get('mean_field_factor', -1.))\n losses = getattr(train_utils, config.get('loss', 'softmax_xent'))(\n logits=logits, labels=labels, reduction=False)\n loss = jax.lax.psum(losses, axis_name='batch')\n top1_idx = jnp.argmax(logits, axis=1)\n\n # Extracts the label at the highest logit index for each image.\n top1_correct = jnp.take_along_axis(labels, top1_idx[:, None], axis=1)[:, 0]\n\n ncorrect = jax.lax.psum(top1_correct, axis_name='batch')\n n = batch_size_eval\n metric_args = jax.lax.all_gather([\n logits, labels, out['pre_logits']], axis_name='batch')\n return ncorrect, loss, n, metric_args\n\n # Load the optimizer from flax.\n opt_name = config.get('optim_name')\n write_note(f'Initializing {opt_name} optimizer...')\n opt_def = getattr(flax.optim, opt_name)(**config.get('optim', {}))\n\n # We jit this, such that the arrays that are created are created on the same\n # device as the input is, in this case the CPU. Else they'd be on device[0].\n opt_cpu = jax.jit(opt_def.create)(params_cpu)\n\n weight_decay_rules = config.get('weight_decay', []) or []\n rescale_value = config.lr.base if config.get('weight_decay_decouple') else 1.\n weight_decay_fn = train_utils.get_weight_decay_fn(\n weight_decay_rules=weight_decay_rules, rescale_value=rescale_value)\n\n @functools.partial(jax.pmap, axis_name='batch', donate_argnums=(0,))\n def update_fn(opt, states, lr, reset_covmat, images, labels, rng):\n \"\"\"Update step.\"\"\"\n measurements = {}\n\n # Get device-specific loss rng.\n rng, rng_model = jax.random.split(rng, 2)\n rng_model_local = jax.random.fold_in(rng_model, jax.lax.axis_index('batch'))\n\n def loss_fn(params, states, images, labels):\n # Specify mutable collection to update untrainable GP parameters.\n variable_dict = {'params': flax.core.freeze(params), **states}\n model_results, updated_states = model.apply(\n variable_dict,\n images,\n train=True,\n rngs={'dropout': rng_model_local},\n mutable=list(states.keys()),\n mean_field_factor=gp_config.get('mean_field_factor', -1.))\n\n logits, _ = model_results\n loss = getattr(train_utils, config.get('loss', 'sigmoid_xent'))(\n logits=logits, labels=labels)\n return loss, updated_states\n\n # Performs exact covariance update (i.e., reset precision matrix resetting\n # at begining of new epoch) if covmat_momentum is a null value.\n if use_gp_layer and gp_config.get('covmat_momentum', -1.) < 0:\n # Resets precision matrix to Identity * ridge_penalty if at the begining\n # of a new epoch. This should be done before accumulate gradient.\n ridge_penalty = gp_config.get('ridge_penalty', 1.)\n prec_mat_old = states['laplace_covariance']['head']['covmat_layer'][\n 'precision_matrix']\n prec_mat_new = (\n (1. - reset_covmat) * prec_mat_old +\n reset_covmat * jnp.eye(prec_mat_old.shape[0]) * ridge_penalty)\n\n states = flax.core.unfreeze(states)\n states['laplace_covariance']['head']['covmat_layer'][\n 'precision_matrix'] = prec_mat_new\n states = flax.core.freeze(states)\n\n # Implementation considerations compared and summarized at\n # https://docs.google.com/document/d/1g3kMEvqu1DOawaflKNyUsIoQ4yIVEoyE5ZlIPkIl4Lc/edit?hl=en#\n (l, s), g = vit_utils.accumulate_gradient_with_states(\n jax.value_and_grad(loss_fn, has_aux=True), opt.target, states, images,\n labels, config.get('grad_accum_steps'))\n l, g = jax.lax.pmean((l, g), axis_name='batch')\n\n # Log the gradient norm only if we need to compute it anyways (clipping)\n # or if we don't use grad_accum_steps, as they interact badly.\n if config.get('grad_accum_steps', 1) == 1 or grad_clip_norm is not None:\n grads, _ = jax.tree_flatten(g)\n l2_g = jnp.sqrt(sum([jnp.vdot(p, p) for p in grads]))\n measurements['l2_grads'] = l2_g\n\n # Optionally resize the global gradient to a maximum norm. We found this\n # useful in some cases across optimizers, hence it's in the main loop.\n if grad_clip_norm is not None:\n g_factor = jnp.minimum(1.0, grad_clip_norm / l2_g)\n g = jax.tree_map(lambda p: g_factor * p, g)\n opt = opt.apply_gradient(g, learning_rate=lr)\n opt = opt.replace(target=weight_decay_fn(opt.target, lr))\n\n params, _ = jax.tree_flatten(opt.target)\n measurements['l2_params'] = jnp.sqrt(sum([jnp.vdot(p, p) for p in params]))\n measurements['reset_covmat'] = reset_covmat\n\n return opt, s, l, rng, measurements\n\n # Set config checkpoint resume path, if provided in args.\n if config.resume_checkpoint_path is not None:\n config.resume = config.resume_checkpoint_path\n\n default_reinit_params = ('head/output_layer/kernel', 'head/output_layer/bias',\n 'head/kernel', 'head/bias')\n rng, train_loop_rngs = jax.random.split(rng)\n checkpoint_data = checkpoint_utils.maybe_load_checkpoint(\n train_loop_rngs=train_loop_rngs,\n save_checkpoint_path=save_checkpoint_path,\n init_optimizer=opt_cpu,\n init_params=params_cpu,\n init_fixed_model_states=states_cpu,\n default_reinit_params=default_reinit_params,\n config=config)\n train_loop_rngs = checkpoint_data.train_loop_rngs\n opt_cpu = checkpoint_data.optimizer\n states_cpu = checkpoint_data.fixed_model_states\n accumulated_train_time = checkpoint_data.accumulated_train_time\n\n write_note('Adapting the checkpoint model...')\n adapted_params = checkpoint_utils.adapt_upstream_architecture(\n init_params=params_cpu,\n loaded_params=opt_cpu.target)\n opt_cpu = opt_cpu.replace(target=adapted_params)\n\n write_note('Kicking off misc stuff...')\n first_step = int(opt_cpu.state.step) # Might be a DeviceArray type.\n if first_step == 0 and jax.process_index() == 0:\n writer.write_hparams(dict(config))\n chrono = train_utils.Chrono(first_step, total_steps, batch_size,\n accumulated_train_time)\n # Note: switch to ProfileAllHosts() if you need to profile all hosts.\n # (Xprof data become much larger and take longer to load for analysis)\n profiler = periodic_actions.Profile(\n # Create profile after every restart to analyze pre-emption related\n # problems and assure we get similar performance in every run.\n logdir=output_dir, first_profile=first_step + 10)\n\n # Prepare the learning-rate and pre-fetch it to device to avoid delays.\n lr_fn = train_utils.create_learning_rate_schedule(total_steps,\n **config.get('lr', {}))\n\n # TODO(dusenberrymw): According to flax docs, prefetching shouldn't be\n # necessary for TPUs.\n lr_iter = train_utils.prefetch_scalar(\n map(lr_fn, range(total_steps)), config.get('prefetch_to_device', 1))\n\n # Prepare the precision matrix resetting schedule, and pre-fetch it to device.\n reset_covmat_fn = lambda step: float(step % steps_per_epoch == 0)\n reset_covmat_iter = train_utils.prefetch_scalar(\n map(reset_covmat_fn, range(first_step, total_steps)),\n nprefetch=config.get('prefetch_to_device', 1))\n\n write_note(f'Replicating...\\n{chrono.note}')\n opt_repl = flax.jax_utils.replicate(opt_cpu)\n states_repl = flax.jax_utils.replicate(states_cpu)\n\n checkpoint_writer = None\n\n # Note: we return the train loss, val loss, and fewshot best l2s for use in\n # reproducibility unit tests.\n # train_loss = -jnp.inf\n # val_loss = -jnp.inf\n # results = {'dummy': {(0, 1): -jnp.inf}}\n\n write_note(f'First step compilations...\\n{chrono.note}')\n logging.info('first_step = %s', first_step)\n # Advance the iterators if we are restarting from an earlier checkpoint.\n # TODO(dusenberrymw): Look into checkpointing dataset state instead.\n\n # Makes sure log_eval_steps is same as steps_per_epoch. This is because\n # the precision matrix needs to be updated fully (at the end of each epoch)\n # when eval takes place.\n log_eval_steps = steps_per_epoch\n if first_step > 0:\n write_note('Advancing iterators after resuming from a checkpoint...')\n lr_iter = itertools.islice(lr_iter, first_step, None)\n train_iter = itertools.islice(train_iter, first_step, None)\n\n # Using a python integer for step here, because opt.state.step is allocated\n # on TPU during replication.\n for step, train_batch, lr_repl, reset_covmat_repl in zip(\n range(first_step + 1, total_steps + 1), train_iter, lr_iter,\n reset_covmat_iter):\n\n with jax.profiler.TraceAnnotation('train_step', step_num=step, _r=1):\n # TODO(jereliu): Expand to allow precision matrix resetting.\n (opt_repl, states_repl, loss_value, train_loop_rngs,\n extra_measurements) = update_fn(\n opt_repl,\n states_repl,\n lr_repl,\n reset_covmat_repl,\n train_batch['image'],\n train_batch['labels'],\n rng=train_loop_rngs)\n\n if jax.process_index() == 0:\n profiler(step)\n\n # Checkpoint saving\n if train_utils.itstime(\n step, config.get('checkpoint_steps'), total_steps, process=0):\n write_note('Checkpointing...')\n chrono.pause()\n train_utils.checkpointing_timeout(checkpoint_writer,\n config.get('checkpoint_timeout', 1))\n accumulated_train_time = chrono.accum_train_time\n # We need to transfer the weights over now or else we risk keeping them\n # alive while they'll be updated in a future step, creating hard to debug\n # memory errors (see b/160593526). Also, takes device 0's params only.\n # For GP layer, we will also do the same for untrainable parameters\n # (`states`). This is ok since `random features` are frozen throughout\n # pre-training, and `precision matrix` is a finetuning-specific parameters\n # that will be re-learned in the finetuning task.\n opt_cpu = jax.tree_map(lambda x: np.array(x[0]), opt_repl)\n states_cpu = jax.tree_map(lambda x: np.array(x[0]), states_repl)\n\n # Check whether we want to keep a copy of the current checkpoint.\n copy_step = None\n if train_utils.itstime(step, config.get('keep_checkpoint_steps'),\n total_steps):\n write_note('Keeping a checkpoint copy...')\n copy_step = step\n\n # Checkpoint should be a nested dictionary or FLAX datataclasses from\n # `flax.struct`. Both can be present in a checkpoint.\n checkpoint_data = checkpoint_utils.CheckpointData(\n optimizer=opt_cpu,\n fixed_model_states=states_cpu,\n train_loop_rngs=train_loop_rngs,\n accumulated_train_time=accumulated_train_time)\n checkpoint_writer = pool.apply_async(\n checkpoint_utils.checkpoint_trained_model,\n (checkpoint_data, save_checkpoint_path, copy_step))\n chrono.resume()\n\n # Report training progress\n if train_utils.itstime(\n step, config.log_training_steps, total_steps, process=0):\n write_note('Reporting training progress...')\n train_loss = loss_value[0] # Keep to return for reproducibility tests.\n timing_measurements, note = chrono.tick(step)\n write_note(note)\n train_measurements = {}\n train_measurements.update({\n 'learning_rate': lr_repl[0],\n 'training_loss': train_loss,\n })\n train_measurements.update(flax.jax_utils.unreplicate(extra_measurements))\n train_measurements.update(timing_measurements)\n writer.write_scalars(step, train_measurements)\n\n # Report validation performance\n if train_utils.itstime(step, log_eval_steps, total_steps):\n write_note('Evaluating on the validation set...')\n chrono.pause()\n\n all_eval_results = {}\n\n for eval_name, (eval_iter, eval_steps) in eval_iter_splits.items():\n start_time = time.time()\n\n # Runs evaluation loop.\n results_arrs = {\n 'y_true': [],\n 'y_pred': [],\n 'y_pred_entropy': []\n }\n\n for _, batch in zip(range(eval_steps), eval_iter):\n batch_ncorrect, batch_losses, batch_n, batch_metric_args = ( # pylint: disable=unused-variable\n evaluation_fn(\n opt_repl.target, states_repl, batch['image'],\n batch['labels']))\n\n # All results are a replicated array shaped as follows:\n # (local_devices, per_device_batch_size, elem_shape...)\n # with each local device's entry being identical as they got psum'd.\n # So let's just take the first one to the host as numpy.\n\n # Here we parse batch_metric_args to compute uncertainty metrics.\n logits, labels, _ = batch_metric_args\n logits = np.array(logits[0])\n probs = jax.nn.softmax(logits)\n\n # From one-hot to integer labels.\n int_labels = np.argmax(np.array(labels[0]), axis=-1)\n\n probs = np.reshape(probs, (probs.shape[0] * probs.shape[1], -1))\n int_labels = int_labels.flatten()\n y_pred = probs[:, 1]\n results_arrs['y_true'].append(int_labels)\n results_arrs['y_pred'].append(y_pred)\n\n # Entropy is computed at the per-epoch level (see below).\n results_arrs['y_pred_entropy'].append(probs)\n\n results_arrs['y_true'] = np.concatenate(results_arrs['y_true'],\n axis=0)\n results_arrs['y_pred'] = np.concatenate(\n results_arrs['y_pred'], axis=0).astype('float64')\n results_arrs['y_pred_entropy'] = vit_utils.entropy(\n np.concatenate(results_arrs['y_pred_entropy'], axis=0), axis=-1)\n\n time_elapsed = time.time() - start_time\n results_arrs['total_ms_elapsed'] = time_elapsed * 1e3\n results_arrs['dataset_size'] = eval_steps * batch_size_eval\n\n all_eval_results[eval_name] = results_arrs\n\n per_pred_results, metrics_results = vit_utils.evaluate_vit_predictions( # pylint: disable=unused-variable\n dataset_split_to_containers=all_eval_results,\n is_deterministic=True,\n num_bins=15,\n return_per_pred_results=True\n )\n\n # `metrics_results` is a dict of {str: jnp.ndarray} dicts, one for each\n # dataset. Flatten this dict so we can pass to the writer and remove empty\n # entries.\n flattened_metric_results = {}\n for dic in metrics_results.values():\n for key, value in dic.items():\n if value is not None:\n flattened_metric_results[key] = value\n writer.write_scalars(step, flattened_metric_results)\n\n # Optionally log to wandb\n if config.use_wandb:\n wandb.log(metrics_results, step=step)\n\n # Save per-prediction metrics\n results_storage_utils.save_per_prediction_results(\n output_dir, step, per_pred_results, verbose=False)\n\n chrono.resume()\n\n # End of step.\n if config.get('testing_failure_step'):\n # Break early to simulate infra failures in test cases.\n if config.testing_failure_step == step:\n break\n\n write_note(f'Done!\\n{chrono.note}')\n pool.close()\n pool.join()\n writer.close()\n\n if wandb_run is not None:\n wandb_run.finish()\n\n # Return final training loss, validation loss, and fewshot results for\n # reproducibility test cases.\n # return train_loss, val_loss, results\n # TODO(nband): fix result reporting for DR ViT-16 reproducibility unit tests\n\n\nif __name__ == '__main__':\n app.run(main)\n" ]
[ [ "numpy.reshape", "tensorflow.config.experimental.get_visible_devices", "tensorflow.io.gfile.makedirs", "numpy.concatenate", "numpy.array", "tensorflow.config.experimental.set_visible_devices", "tensorflow.random.set_seed" ] ]
Sniperq2/lightkurve
[ "4caf3261dd6c96529704867d4bbf61f7fb86a43b" ]
[ "tests/io/test_cdips.py" ]
[ "import pytest\n\nfrom astropy.io import fits\nimport numpy as np\nfrom numpy.testing import assert_array_equal\n\nfrom lightkurve import search_lightcurve\nfrom lightkurve.io.cdips import read_cdips_lightcurve\nfrom lightkurve.io.detect import detect_filetype\n\[email protected]_data\ndef test_detect_cdips():\n \"\"\"Can we detect the correct format for CDIPS files?\"\"\"\n url = \"https://mast.stsci.edu/api/v0.1/Download/file?uri=mast:HLSP/cdips/s0008/cam3_ccd4/hlsp_cdips_tess_ffi_gaiatwo0005318059532750974720-0008-cam3-ccd4_tess_v01_llc.fits\"\n f = fits.open(url)\n\n assert detect_filetype(f)==\"CDIPS\"\n\n\[email protected]_data\ndef test_read_cdips():\n \"\"\"Can we read CDIPS files?\"\"\"\n url = \"https://mast.stsci.edu/api/v0.1/Download/file?uri=mast:HLSP/cdips/s0008/cam3_ccd4/hlsp_cdips_tess_ffi_gaiatwo0005318059532750974720-0008-cam3-ccd4_tess_v01_llc.fits\"\n f = fits.open(url)\n # Verify different extensions\n fluxes = []\n\n # Test instrumental flux and magnitude, and detrended magnitudes\n exts = [f'IFL{ap}' for ap in [1,2,3]]\n exts.extend([f'IRM{ap}' for ap in [1,2,3]])\n exts.extend([f'TFA{ap}' for ap in [1,2,3]])\n exts.extend([f'PCA{ap}' for ap in [1,2,3]])\n\n for ext in exts:\n lc = read_cdips_lightcurve(url, flux_column=ext)\n assert type(lc).__name__ == \"TessLightCurve\"\n assert lc.meta[\"FLUX_ORIGIN\"] == ext.lower()\n # Are `time` and `flux` consistent with the FITS file?\n assert_array_equal(f[1].data['TMID_BJD'][lc.meta['QUALITY_MASK']],\n lc.time.value)\n assert_array_equal(f[1].data[ext][lc.meta['QUALITY_MASK']],\n lc.flux.value)\n fluxes.append(lc.flux)\n # Different extensions should show different fluxes\n for i in range(11):\n assert not np.array_equal(fluxes[i].value , fluxes[i+1].value)\n\[email protected]_data\ndef test_search_cdips():\n \"\"\"Can we search and download a cdips light curve?\"\"\"\n search = search_lightcurve(\"TIC 93270923\", author=\"CDIPS\", sector=8)\n assert len(search) == 1\n assert search.table[\"author\"][0] == \"CDIPS\"\n lc = search.download()\n assert type(lc).__name__ == \"TessLightCurve\"\n assert lc.sector == 8\n" ]
[ [ "numpy.testing.assert_array_equal", "numpy.array_equal" ] ]
KMKgit/ML
[ "998b6b47584337cb9a3ce5a7e405b973ad2c7a5a" ]
[ "tistory/basic/placeholder.py" ]
[ "import tensorflow as tf\n\na = tf.placeholder(tf.int16)\nb = tf.placeholder(tf.int16)\n\nadd = tf.add(a, b)\nmul = tf.mul(a, b)\n\nwith tf.Session() as sess:\n print (\"Add : %i\" %sess.run(add, feed_dict={a: 2, b: 3}))\n print (\"Mul : %i\" %sess.run(mul, feed_dict={a: 2, b: 3}))" ]
[ [ "tensorflow.Session", "tensorflow.add", "tensorflow.placeholder", "tensorflow.mul" ] ]
isabella232/fuzzbench
[ "f213bbeb57e27f01d18995120dd124406a6e7a2a" ]
[ "analysis/coverage_data_utils.py" ]
[ "# Copyright 2020 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# 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\"\"\"Utility functions for coverage data calculation.\"\"\"\n\nimport collections\nimport json\nimport os\nimport posixpath\nimport tempfile\nimport pandas as pd\n\nfrom analysis import data_utils\nfrom common import filestore_utils\n\n\ndef get_fuzzer_benchmark_key(fuzzer: str, benchmark: str):\n \"\"\"Returns the key in coverage dict for a pair of fuzzer-benchmark.\"\"\"\n return fuzzer + ' ' + benchmark\n\n\ndef get_fuzzer_filestore_path(benchmark_df, fuzzer):\n \"\"\"Gets the filestore_path for |fuzzer| in |benchmark_df|.\"\"\"\n fuzzer_df = benchmark_df[benchmark_df.fuzzer == fuzzer]\n filestore_path = fuzzer_df.experiment_filestore.unique()[0]\n exp_name = fuzzer_df.experiment.unique()[0]\n return posixpath.join(filestore_path, exp_name)\n\n\ndef get_covered_regions_dict(experiment_df):\n \"\"\"Combines json files for different fuzzer-benchmark pair\n in |experiment_df| and returns a dictionary of the covered regions.\"\"\"\n covered_regions_dict = {}\n benchmarks = experiment_df.benchmark.unique()\n for benchmark in benchmarks:\n benchmark_df = experiment_df[experiment_df.benchmark == benchmark]\n fuzzers = benchmark_df.fuzzer.unique()\n for fuzzer in fuzzers:\n fuzzer_covered_regions = get_fuzzer_covered_regions(\n benchmark_df, benchmark, fuzzer)\n key = get_fuzzer_benchmark_key(fuzzer, benchmark)\n covered_regions_dict[key] = fuzzer_covered_regions\n\n return covered_regions_dict\n\n\ndef get_fuzzer_covered_regions(benchmark_df, benchmark, fuzzer):\n \"\"\"Gets the covered regions for |fuzzer| in |benchmark_df| from the json\n file in the bucket.\"\"\"\n with tempfile.TemporaryDirectory() as temp_dir:\n dst_file = os.path.join(temp_dir, 'tmp.json')\n src_filestore_path = get_fuzzer_filestore_path(benchmark_df, fuzzer)\n src_file = posixpath.join(src_filestore_path, 'coverage', 'data',\n benchmark, fuzzer, 'covered_regions.json')\n if filestore_utils.ls(src_file, must_exist=False).retcode:\n # Error occurred, coverage file does not exit. Bail out.\n return {}\n\n filestore_utils.cp(src_file, dst_file)\n with open(dst_file) as json_file:\n return json.load(json_file)\n\n\ndef get_unique_region_dict(benchmark_coverage_dict):\n \"\"\"Returns a dictionary containing the covering fuzzers for each\n unique region, where the |threshold| defines which regions are unique.\"\"\"\n region_dict = collections.defaultdict(list)\n unique_region_dict = {}\n threshold_count = 1\n for fuzzer in benchmark_coverage_dict:\n for region in benchmark_coverage_dict[fuzzer]:\n region_dict[region].append(fuzzer)\n for region, fuzzers in region_dict.items():\n if len(fuzzers) <= threshold_count:\n unique_region_dict[region] = fuzzers\n return unique_region_dict\n\n\ndef get_unique_region_cov_df(unique_region_dict, fuzzer_names):\n \"\"\"Returns a DataFrame where the two columns are fuzzers and the number\n of unique regions covered.\"\"\"\n fuzzers = collections.defaultdict(int)\n for region in unique_region_dict:\n for fuzzer in unique_region_dict[region]:\n fuzzers[fuzzer] += 1\n dict_to_transform = {'fuzzer': [], 'unique_regions_covered': []}\n for fuzzer in fuzzer_names:\n covered_num = fuzzers[fuzzer]\n dict_to_transform['fuzzer'].append(fuzzer)\n dict_to_transform['unique_regions_covered'].append(covered_num)\n return pd.DataFrame(dict_to_transform)\n\n\ndef get_benchmark_cov_dict(coverage_dict, benchmark):\n \"\"\"Returns a dictionary to store the covered regions of each fuzzer.\n Uses a set of tuples to store the covered regions.\"\"\"\n benchmark_cov_dict = {}\n for key_pair, covered_regions in coverage_dict.items():\n current_fuzzer, current_benchmark = key_pair.split()\n if current_benchmark == benchmark:\n covered_regions_in_set = set()\n for region in covered_regions:\n covered_regions_in_set.add(tuple(region))\n benchmark_cov_dict[current_fuzzer] = covered_regions_in_set\n return benchmark_cov_dict\n\n\ndef get_benchmark_aggregated_cov_df(coverage_dict, benchmark):\n \"\"\"Returns a dataframe where each row represents a fuzzer and its\n aggregated coverage number.\"\"\"\n dict_to_transform = {'fuzzer': [], 'aggregated_edges_covered': []}\n for key_pair, covered_regions in coverage_dict.items():\n current_fuzzer, current_benchmark = key_pair.split()\n if current_benchmark == benchmark:\n dict_to_transform['fuzzer'].append(current_fuzzer)\n dict_to_transform['aggregated_edges_covered'].append(\n len(covered_regions))\n return pd.DataFrame(dict_to_transform)\n\n\ndef get_pairwise_unique_coverage_table(benchmark_coverage_dict, fuzzers):\n \"\"\"Returns a table that shows the unique coverage between\n each pair of fuzzers.\n\n The pairwise unique coverage table is a square matrix where each\n row and column represents a fuzzer, and each cell contains a number\n showing the regions covered by the fuzzer of the column but not by\n the fuzzer of the row.\"\"\"\n\n pairwise_unique_coverage_values = []\n for fuzzer_in_row in fuzzers:\n row = []\n for fuzzer_in_col in fuzzers:\n pairwise_unique_coverage_value = get_unique_covered_percentage(\n benchmark_coverage_dict[fuzzer_in_row],\n benchmark_coverage_dict[fuzzer_in_col])\n row.append(pairwise_unique_coverage_value)\n pairwise_unique_coverage_values.append(row)\n\n return pd.DataFrame(pairwise_unique_coverage_values,\n index=fuzzers,\n columns=fuzzers)\n\n\ndef get_unique_covered_percentage(fuzzer_row_covered_regions,\n fuzzer_col_covered_regions):\n \"\"\"Returns the number of regions covered by the fuzzer of the column\n but not by the fuzzer of the row.\"\"\"\n\n unique_region_count = 0\n for region in fuzzer_col_covered_regions:\n if region not in fuzzer_row_covered_regions:\n unique_region_count += 1\n return unique_region_count\n\n\ndef rank_by_average_normalized_score(benchmarks_unique_coverage_list):\n \"\"\"Returns the rank based on average normalized score on unique coverage.\"\"\"\n df_list = [df.set_index('fuzzer') for df in benchmarks_unique_coverage_list]\n combined_df = pd.concat(df_list, axis=1).astype(float).T\n scores = data_utils.experiment_rank_by_average_normalized_score(combined_df)\n return scores\n" ]
[ [ "pandas.concat", "pandas.DataFrame" ] ]
CruxML/vitis-quantizer
[ "52bb2f8acc7b02ca57d1e282c49b9a61780c5592" ]
[ "vitis_quantizer/graph_transformations/transforms_test.py" ]
[ "# Copyright 2019 Xilinx 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\"\"\"Tests for transforms.py API code.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\n\nimport tensorflow as tf\n\nfrom vitis_quantizer.graph_transformations import transforms\n\nLayerNode = transforms.LayerNode\n\n\nclass LayerNodeTest(tf.test.TestCase):\n def testEqualityLayerNode(self):\n conv_layer = {\n \"name\": \"conv2d\",\n \"class_name\": \"Conv2D\",\n \"config\": {\n \"name\": \"conv2d\",\n },\n }\n dense_layer = {\n \"name\": \"dense\",\n \"class_name\": \"Dense\",\n \"config\": {\n \"name\": \"dense\",\n },\n }\n\n self.assertNotEqual(LayerNode(conv_layer), LayerNode(dense_layer))\n\n self.assertEqual(LayerNode(conv_layer), LayerNode(conv_layer))\n self.assertEqual(LayerNode(conv_layer), LayerNode(copy.deepcopy(conv_layer)))\n\n self.assertNotEqual(\n LayerNode(\n conv_layer, input_layers=[LayerNode(conv_layer), LayerNode(dense_layer)]\n ),\n LayerNode(\n conv_layer, input_layers=[LayerNode(conv_layer), LayerNode(conv_layer)]\n ),\n )\n\n self.assertEqual(\n LayerNode(\n conv_layer, input_layers=[LayerNode(conv_layer), LayerNode(dense_layer)]\n ),\n LayerNode(\n conv_layer, input_layers=[LayerNode(conv_layer), LayerNode(dense_layer)]\n ),\n )\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n" ]
[ [ "tensorflow.test.main" ] ]
iteal/wormpose
[ "a92c0459f940d6e1f517b90d3a445ad3c0689ed8" ]
[ "wormpose/commands/calibrate_dataset.py" ]
[ "#!/usr/bin/env python\n\n\"\"\"\nCalculates the image similarity on a random selection of labeled frames from a dataset.\n\"\"\"\n\nimport logging\nimport os\nimport random\nfrom argparse import Namespace\nfrom typing import Tuple\n\nimport h5py\nimport numpy as np\n\nfrom wormpose.commands import _log_parameters\nfrom wormpose.config import default_paths\nfrom wormpose.dataset import Dataset\nfrom wormpose.dataset.image_processing.options import add_image_processing_arguments\nfrom wormpose.dataset.loader import get_dataset_name\nfrom wormpose.dataset.loader import load_dataset\nfrom wormpose.images.scoring.centerline_accuracy_check import CenterlineAccuracyCheck\nfrom wormpose.pose.centerline import skeletons_to_angles\nfrom wormpose.dataset.loaders.resizer import add_resizing_arguments, ResizeOptions\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\nclass _ScoresWriter(object):\n def __init__(self):\n self.all_scores = []\n\n def add(self, kwargs):\n self.all_scores.append(kwargs[\"score\"])\n\n def write(self, results_file):\n with h5py.File(results_file, \"a\") as f:\n f.create_dataset(\"scores\", data=self.all_scores)\n\n\nclass _ImagesAndScoresWriter(_ScoresWriter):\n def __init__(self):\n self.all_synth = []\n self.all_real = []\n super().__init__()\n\n def add(self, kwargs):\n centerline_accuracy: CenterlineAccuracyCheck = kwargs[\"centerline_accuracy\"]\n self.all_real.append(np.array(centerline_accuracy.last_real_image))\n self.all_synth.append(np.array(centerline_accuracy.last_synth_image))\n super().add(kwargs)\n\n def write(self, results_file):\n with h5py.File(results_file, \"a\") as f:\n f.create_dataset(\"real_images\", data=self.all_real)\n f.create_dataset(\"synth_images\", data=self.all_synth)\n super().write(results_file)\n\n\nclass _Calibrator(object):\n def __init__(\n self,\n dataset: Dataset,\n results_dir: str,\n image_shape: Tuple[int, int],\n num_samples: int,\n theta_dims: int,\n ):\n self.dataset = dataset\n self.results_dir = results_dir\n self.image_shape = image_shape\n self.num_samples = num_samples\n self.theta_dims = theta_dims\n\n def __call__(self, video_name: str, writer: _ScoresWriter):\n \"\"\"\n Evaluate image metric score on labelled frames.\n \"\"\"\n features = self.dataset.features_dataset[video_name]\n labelled_thetas = skeletons_to_angles(features.skeletons, theta_dims=self.theta_dims)\n labelled_indexes = features.labelled_indexes\n\n centerline_accuracy = CenterlineAccuracyCheck(\n frame_preprocessing=self.dataset.frame_preprocessing,\n image_shape=self.image_shape,\n )\n\n with self.dataset.frames_dataset.open(video_name) as frames:\n frames_amount = min(self.num_samples, len(labelled_indexes))\n\n random_label_index = np.random.choice(labelled_indexes, frames_amount, replace=False)\n thetas = labelled_thetas[random_label_index]\n\n for theta, index in zip(thetas, random_label_index):\n cur_frame = frames[index]\n\n score, _ = centerline_accuracy(\n theta=theta,\n template_skeleton=features.skeletons[index],\n template_measurements=features.measurements,\n template_frame=cur_frame,\n real_frame_orig=cur_frame,\n )\n writer.add(locals())\n\n results_file = os.path.join(self.results_dir, video_name + \"_calibration.h5\")\n if os.path.exists(results_file):\n os.remove(results_file)\n writer.write(results_file=results_file)\n\n logger.info(\n f\"Evaluated known skeletons reconstruction for {video_name},\"\n f\" average score {np.mean(writer.all_scores):.4f}\"\n )\n return results_file\n\n\ndef _parse_arguments(kwargs: dict):\n if kwargs.get(\"num_samples\") is None:\n kwargs[\"num_samples\"] = 500\n if kwargs.get(\"work_dir\") is None:\n kwargs[\"work_dir\"] = default_paths.WORK_DIR\n if kwargs.get(\"theta_dims\") is None:\n kwargs[\"theta_dims\"] = 100\n if kwargs.get(\"video_names\") is None:\n kwargs[\"video_names\"] = None\n if kwargs.get(\"save_images\") is None:\n kwargs[\"save_images\"] = False\n if kwargs.get(\"random_seed\") is None:\n kwargs[\"random_seed\"] = None\n kwargs[\"resize_options\"] = ResizeOptions(**kwargs)\n\n _log_parameters(logger.info, kwargs)\n return Namespace(**kwargs)\n\n\ndef calibrate(dataset_loader: str, dataset_path: str, **kwargs):\n \"\"\"\n Calculate the image score for a certain number of labelled frames in the dataset,\n this will give an indication on choosing the image similarity threshold when predicting all frames in the dataset.\n\n :param dataset_loader: Name of the dataset loader, for example \"tierpsy\"\n :param dataset_path: Root path of the dataset containing videos of worm\n \"\"\"\n _log_parameters(logger.info, {\"dataset_loader\": dataset_loader, \"dataset_path\": dataset_path})\n args = _parse_arguments(kwargs)\n\n random.seed(args.random_seed)\n np.random.seed(args.random_seed)\n\n dataset_name = get_dataset_name(dataset_path)\n experiment_dir = os.path.join(args.work_dir, dataset_name)\n calibration_results_dir = os.path.join(experiment_dir, default_paths.CALIBRATION_RESULTS_DIR)\n os.makedirs(calibration_results_dir, exist_ok=True)\n\n dataset = load_dataset(\n dataset_loader,\n dataset_path,\n selected_video_names=args.video_names,\n **vars(args),\n )\n\n calibrator = _Calibrator(\n dataset=dataset,\n results_dir=calibration_results_dir,\n image_shape=dataset.image_shape,\n num_samples=args.num_samples,\n theta_dims=args.theta_dims,\n )\n\n writer = _ImagesAndScoresWriter() if kwargs[\"save_images\"] else _ScoresWriter()\n\n for video_name in dataset.video_names:\n results_file = calibrator(video_name=video_name, writer=writer)\n yield video_name, results_file\n\n\ndef main():\n import argparse\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"dataset_loader\", type=str)\n parser.add_argument(\"dataset_path\", type=str)\n parser.add_argument(\n \"--video_names\",\n type=str,\n nargs=\"+\",\n help=\"Only evaluate using a subset of videos. \" \"If not set, will include all videos in dataset_path.\",\n )\n parser.add_argument(\n \"--num_samples\",\n type=int,\n help=\"How many frames to perform the calibration in order to evaluate the image metric\",\n )\n parser.add_argument(\"--theta_dims\", type=int)\n parser.add_argument(\"--work_dir\", type=str, help=\"Root folder for all experiments\")\n parser.add_argument(\n \"--save_images\", default=False, action=\"store_true\", help=\"Also save the images used for the calibration\"\n )\n parser.add_argument(\"--random_seed\", type=int, help=\"Optional random seed for deterministic results\")\n add_resizing_arguments(parser)\n add_image_processing_arguments(parser)\n\n args = parser.parse_args()\n\n list(calibrate(**vars(args)))\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.array", "numpy.mean", "numpy.random.seed", "numpy.random.choice" ] ]
SayakDas10/TicTacToe-Minimax-AI-GUI
[ "a5b6f36496ab148c0e7089b209b9c44bb49e395e" ]
[ "minimax.py" ]
[ "import numpy as np\nimport time\n\nhuman = 'X'\nai = 'O'\n\n\n# Possible valid moves and the depth is calculated from number of empty cells in the board\ndef GetEmptyCells(board):\n empty =[]\n for i in range(len(board[0])):\n for j in range(len(board[1])):\n if board[i][j] == None:\n empty.append([i, j])\n return empty\n\n# To check if a move is a valid move, ie. if a move corresponds to an empty cell or not\ndef ValidMove(board, row, col):\n return True if [row, col] in GetEmptyCells(board) else False\n\ndef CheckWinner(board, player): # to check if someone has won or not\n if board[0][0] == board[1][1] and board[0][0] == board[2][2] and board[0][0] == player: #Check maindiagonal\n return True \n if board[0][2] == board[1][1] and board[0][2] == board[2][0] and board[0][2] == player: #Check counterdiagonal\n return True\n\n for i in range(len(board[0])):\n if board[i][0] == board[i][1] and board[i][0] == board[i][2] and board[i][0] == player: #Check row wise\n return True\n if board[0][i] == board[1][i] and board[0][i] == board[2][i] and board[0][i] == player: #Check column wise\n return True\n \n# static evaluation function, sets a score to the leaf node\ndef GetScore(board):\n if CheckWinner(board, ai):\n score = -1\n elif CheckWinner(board, human):\n score = +1\n else: score = 0\n return score\n\n# THE ULTIMATE ALGOOOO\ndef minimax(board, depth, minimizing):\n if minimizing:\n optimal = [-1, -1, np.inf] # defining default temporary score for ai\n else: optimal = [-1, -1, -np.inf] # defining default temporary score for human\n if depth == 0 or CheckWinner(board, human) or CheckWinner(board, ai): #getting score of a leaf node or the node where a game ends\n return [-1, -1, GetScore(board)]\n \n for position in GetEmptyCells(board): #looping throuh all possible valid moves of the board at a certain position\n row, col = position[0], position[1]\n board[row][col] = ai if minimizing else human #changing board after deciding a valid move\n score = minimax(board, depth - 1, not minimizing) #resursivly calling minimax on the end node\n board[row][col] = None #changing back to previous state\n score[0], score[1] = row, col \n\n if minimizing:\n if score[2] < optimal[2]: #checking the minimum score for ai\n optimal = score\n else:\n if score[2] > optimal[2]: #checking maximum score for human\n optimal = score\n return optimal \n\ndef alpha_beta_minimax(board, depth, alpha, beta, minimizing):\n \n if minimizing:\n optimal = [-1, -1, np.inf] # defining default temporary score for ai\n else: optimal = [-1, -1, -np.inf] # defining default temporary score for human\n if depth == 0 or CheckWinner(board, human) or CheckWinner(board, ai): #getting score of a leaf node or the node where a game ends\n return [-1, -1, GetScore(board)]\n \n for position in GetEmptyCells(board): #looping throuh all possible valid moves of the board at a certain position\n row, col = position[0], position[1]\n board[row][col] = ai if minimizing else human #changing board after deciding a valid move\n score = alpha_beta_minimax(board, depth - 1, alpha, beta, not minimizing) #resursivly calling minimax on the end node\n board[row][col] = None #changing back to previous state\n score[0], score[1] = row, col \n\n if minimizing:\n if score[2] < optimal[2]: #checking the minimum score for ai\n optimal = score\n\n beta = min(beta, optimal[2])\n if beta <= alpha:\n break\n else:\n if score[2] > optimal[2]: #checking maximum score for human\n optimal = score\n \n alpha = max(alpha, optimal[2])\n if beta <= alpha:\n break\n \n return optimal \n\n#utility functions\ndef DisplayBoard(board):\n print('\\n')\n for i in range(len(board[0])):\n print(board[i],'\\n')\n\n\ndef PlayerTurn(board):\n index = int(input('Player Turn: ')) - 1\n row = index // 3\n col = index % 3\n if ValidMove(board, row, col):\n board[row][col] = human\n else: print(\"Wrong Move\")\n return board\n\ndef AITurn(board, choice):\n depth = len(GetEmptyCells(board)) #depth of the tree is the length of empty cell set\n if depth == 9: #if the ai goes first, it chooses a random cell from the board\n row = np.random.randint(0, 1, 2)\n col = np.random.randint(0, 1, 2)\n else:\n #turn = minimax(board, depth, True) #getting the best turn for ai\n turn = minimax(board, depth, True) if choice == 1 else alpha_beta_minimax(board, depth, -np.inf, np.inf, True) #getting the best turn for ai\n row = turn[0]\n col = turn[1]\n if ValidMove(board, row, col):\n print(\"Ai Turn: \")\n board[row][col] = ai\n else: print(\"Wrong Move\")\n return board\n\n#main function\ndef main():\n board = [[None for i in range(3)]for i in range(3)]\n choice = int(input(\"Press 1 for minimax, for minimax with pruning press any number other than 1\\n\"))\n while True:\n PlayerTurn(board)\n DisplayBoard(board)\n if CheckWinner(board, human):\n print(human,\" Won\")\n break\n if len(GetEmptyCells(board)) == 0:\n print(\"Tie Game.\")\n break\n start = time.time()\n AITurn(board, choice)\n print(\"Time: \", (time.time()-start)*1000)\n DisplayBoard(board)\n if CheckWinner(board, ai):\n print(ai,\" Won\")\n break\n\nif __name__ == \"__main__\":\n main()\n\n" ]
[ [ "numpy.random.randint" ] ]
ccatterina/core
[ "162c39258e68ae42fe4e1560ae91ed54f5662409" ]
[ "homeassistant/components/trend/binary_sensor.py" ]
[ "\"\"\"A sensor that monitors trends in other components.\"\"\"\nfrom collections import deque\nimport logging\nimport math\n\nimport numpy as np\nimport voluptuous as vol\n\nfrom homeassistant.components.binary_sensor import (\n DEVICE_CLASSES_SCHEMA,\n ENTITY_ID_FORMAT,\n PLATFORM_SCHEMA,\n BinarySensorEntity,\n)\nfrom homeassistant.const import (\n ATTR_ENTITY_ID,\n ATTR_FRIENDLY_NAME,\n CONF_DEVICE_CLASS,\n CONF_ENTITY_ID,\n CONF_FRIENDLY_NAME,\n CONF_SENSORS,\n STATE_UNAVAILABLE,\n STATE_UNKNOWN,\n)\nfrom homeassistant.core import callback\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers.entity import generate_entity_id\nfrom homeassistant.helpers.event import async_track_state_change_event\nfrom homeassistant.helpers.reload import setup_reload_service\nfrom homeassistant.util import utcnow\n\nfrom . import DOMAIN, PLATFORMS\n\n_LOGGER = logging.getLogger(__name__)\n\nATTR_ATTRIBUTE = \"attribute\"\nATTR_GRADIENT = \"gradient\"\nATTR_MIN_GRADIENT = \"min_gradient\"\nATTR_INVERT = \"invert\"\nATTR_SAMPLE_DURATION = \"sample_duration\"\nATTR_SAMPLE_COUNT = \"sample_count\"\n\nCONF_ATTRIBUTE = \"attribute\"\nCONF_INVERT = \"invert\"\nCONF_MAX_SAMPLES = \"max_samples\"\nCONF_MIN_GRADIENT = \"min_gradient\"\nCONF_SAMPLE_DURATION = \"sample_duration\"\n\nSENSOR_SCHEMA = vol.Schema(\n {\n vol.Required(CONF_ENTITY_ID): cv.entity_id,\n vol.Optional(CONF_ATTRIBUTE): cv.string,\n vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,\n vol.Optional(CONF_FRIENDLY_NAME): cv.string,\n vol.Optional(CONF_INVERT, default=False): cv.boolean,\n vol.Optional(CONF_MAX_SAMPLES, default=2): cv.positive_int,\n vol.Optional(CONF_MIN_GRADIENT, default=0.0): vol.Coerce(float),\n vol.Optional(CONF_SAMPLE_DURATION, default=0): cv.positive_int,\n }\n)\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {vol.Required(CONF_SENSORS): cv.schema_with_slug_keys(SENSOR_SCHEMA)}\n)\n\n\ndef setup_platform(hass, config, add_entities, discovery_info=None):\n \"\"\"Set up the trend sensors.\"\"\"\n\n setup_reload_service(hass, DOMAIN, PLATFORMS)\n\n sensors = []\n\n for device_id, device_config in config[CONF_SENSORS].items():\n entity_id = device_config[ATTR_ENTITY_ID]\n attribute = device_config.get(CONF_ATTRIBUTE)\n device_class = device_config.get(CONF_DEVICE_CLASS)\n friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device_id)\n invert = device_config[CONF_INVERT]\n max_samples = device_config[CONF_MAX_SAMPLES]\n min_gradient = device_config[CONF_MIN_GRADIENT]\n sample_duration = device_config[CONF_SAMPLE_DURATION]\n\n sensors.append(\n SensorTrend(\n hass,\n device_id,\n friendly_name,\n entity_id,\n attribute,\n device_class,\n invert,\n max_samples,\n min_gradient,\n sample_duration,\n )\n )\n if not sensors:\n _LOGGER.error(\"No sensors added\")\n return\n add_entities(sensors)\n\n\nclass SensorTrend(BinarySensorEntity):\n \"\"\"Representation of a trend Sensor.\"\"\"\n\n def __init__(\n self,\n hass,\n device_id,\n friendly_name,\n entity_id,\n attribute,\n device_class,\n invert,\n max_samples,\n min_gradient,\n sample_duration,\n ):\n \"\"\"Initialize the sensor.\"\"\"\n self._hass = hass\n self.entity_id = generate_entity_id(ENTITY_ID_FORMAT, device_id, hass=hass)\n self._name = friendly_name\n self._entity_id = entity_id\n self._attribute = attribute\n self._device_class = device_class\n self._invert = invert\n self._sample_duration = sample_duration\n self._min_gradient = min_gradient\n self._gradient = None\n self._state = None\n self.samples = deque(maxlen=max_samples)\n\n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n return self._name\n\n @property\n def is_on(self):\n \"\"\"Return true if sensor is on.\"\"\"\n return self._state\n\n @property\n def device_class(self):\n \"\"\"Return the sensor class of the sensor.\"\"\"\n return self._device_class\n\n @property\n def device_state_attributes(self):\n \"\"\"Return the state attributes of the sensor.\"\"\"\n return {\n ATTR_ENTITY_ID: self._entity_id,\n ATTR_FRIENDLY_NAME: self._name,\n ATTR_GRADIENT: self._gradient,\n ATTR_INVERT: self._invert,\n ATTR_MIN_GRADIENT: self._min_gradient,\n ATTR_SAMPLE_COUNT: len(self.samples),\n ATTR_SAMPLE_DURATION: self._sample_duration,\n }\n\n @property\n def should_poll(self):\n \"\"\"No polling needed.\"\"\"\n return False\n\n async def async_added_to_hass(self):\n \"\"\"Complete device setup after being added to hass.\"\"\"\n\n @callback\n def trend_sensor_state_listener(event):\n \"\"\"Handle state changes on the observed device.\"\"\"\n new_state = event.data.get(\"new_state\")\n if new_state is None:\n return\n try:\n if self._attribute:\n state = new_state.attributes.get(self._attribute)\n else:\n state = new_state.state\n if state not in (STATE_UNKNOWN, STATE_UNAVAILABLE):\n sample = (new_state.last_updated.timestamp(), float(state))\n self.samples.append(sample)\n self.async_schedule_update_ha_state(True)\n except (ValueError, TypeError) as ex:\n _LOGGER.error(ex)\n\n self.async_on_remove(\n async_track_state_change_event(\n self.hass, [self._entity_id], trend_sensor_state_listener\n )\n )\n\n async def async_update(self):\n \"\"\"Get the latest data and update the states.\"\"\"\n # Remove outdated samples\n if self._sample_duration > 0:\n cutoff = utcnow().timestamp() - self._sample_duration\n while self.samples and self.samples[0][0] < cutoff:\n self.samples.popleft()\n\n if len(self.samples) < 2:\n return\n\n # Calculate gradient of linear trend\n await self.hass.async_add_job(self._calculate_gradient)\n\n # Update state\n self._state = (\n abs(self._gradient) > abs(self._min_gradient)\n and math.copysign(self._gradient, self._min_gradient) == self._gradient\n )\n\n if self._invert:\n self._state = not self._state\n\n def _calculate_gradient(self):\n \"\"\"Compute the linear trend gradient of the current samples.\n\n This need run inside executor.\n \"\"\"\n timestamps = np.array([t for t, _ in self.samples])\n values = np.array([s for _, s in self.samples])\n coeffs = np.polyfit(timestamps, values, 1)\n self._gradient = coeffs[0]\n" ]
[ [ "numpy.polyfit", "numpy.array" ] ]
DYG111/tensorflow-onnx
[ "7d61571c1a66198440eee969463e83d8bd40c267" ]
[ "tests/test_backend.py" ]
[ "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nimport os\nimport tempfile\nimport unittest\nfrom collections import namedtuple\n\nimport numpy as np\nimport tensorflow as tf\nimport tf2onnx.utils\nfrom onnx import helper\nfrom tf2onnx.tfonnx import process_tf_graph\n\nTMPPATH = tempfile.mkdtemp()\n\nBACKEND = \"caffe2\"\n# BACKEND = \"onnxmsrt\"\n# BACKEND = \"cntk\"\n\nNCHW_TO_NHWC = [0, 2, 3, 1]\nNHWC_TO_NCHW = [0, 3, 1, 2]\nHWCN_TO_NCHW = [3, 2, 0, 1]\n\n_STRIDE1x1 = [1, 1, 1, 1]\n_KERNEL3x3 = [3, 3, 1, 1]\n\n# names for input and outputs for tests\n_TFINPUT = \"input\"\n_INPUT = \"input:0\"\n_TFINPUT1 = \"input1\"\n_INPUT1 = \"input1:0\"\n_TFOUTPUT = \"output\"\n_OUTPUT = \"output:0\"\n_OUTPUT1 = \"output1:0\"\n\n\n# pylint: disable=C0111\n\n\ndef make_xval(shape):\n x_val = np.arange(np.prod(shape)).astype(\"float32\").reshape(shape)\n return x_val\n\n\nclass Tf2OnnxBackendTests(unittest.TestCase):\n def setUp(self):\n self.maxDiff = None\n tf.reset_default_graph()\n # reset name generation on every test\n tf2onnx.utils.INTERNAL_NAME = 1\n np.random.seed(1) # Make it reproducible.\n\n arg = namedtuple(\"Arg\", \"input inputs outputs verbose continue_on_error\")\n self._args0 = arg(input=\"test\", inputs=[], outputs=[_OUTPUT],\n verbose=False, continue_on_error=False)\n self._args1 = arg(input=\"test\", inputs=[_INPUT], outputs=[_OUTPUT],\n verbose=False, continue_on_error=False)\n self._args2 = arg(input=\"test\", inputs=[_INPUT, _INPUT1], outputs=[_OUTPUT],\n verbose=False, continue_on_error=False)\n self._args3 = arg(input=\"test\", inputs=[_INPUT, _INPUT1, \"prob:0\"], outputs=[_OUTPUT],\n verbose=False, continue_on_error=False)\n self._args4 = arg(input=\"test\", inputs=[_INPUT, _INPUT1], outputs=[_OUTPUT, _OUTPUT1],\n verbose=False, continue_on_error=False)\n\n @staticmethod\n def assertAllClose(expected, actual, **kwargs):\n np.testing.assert_allclose(expected, actual, **kwargs)\n\n @staticmethod\n def run_onnxcaffe2(onnx_graph, inputs):\n \"\"\"Run test against caffe2 backend.\"\"\"\n import onnx_caffe2.backend\n prepared_backend = onnx_caffe2.backend.prepare(onnx_graph)\n results = prepared_backend.run(inputs)\n return results[0]\n\n @staticmethod\n def run_onnxmsrt(onnx_graph, inputs, output_names, test_name):\n \"\"\"Run test against msrt backend.\"\"\"\n import lotus\n model_path = os.path.join(TMPPATH, test_name + \".pb\")\n with open(model_path, \"wb\") as f:\n f.write(onnx_graph.SerializeToString())\n\n m = lotus.ModelExecutor(model_path)\n results = m.run(output_names, inputs)\n return results[0]\n\n @staticmethod\n def run_onnxcntk(onnx_graph, inputs, test_name):\n \"\"\"Run test against cntk backend.\"\"\"\n import cntk as C\n print(test_name)\n model_path = os.path.join(TMPPATH, test_name + \".pb\")\n with open(model_path, \"wb\") as f:\n f.write(onnx_graph.SerializeToString())\n z = C.Function.load(model_path, format=C.ModelFormat.ONNX)\n input_args = {}\n for arg in z.arguments:\n input_args[arg] = inputs[arg.name]\n results = z.eval(input_args)\n return results\n\n def validate_onnx(self, g, args, input_dict, expected):\n model_proto = g.make_model(\"test\", args.inputs, args.outputs)\n if BACKEND == \"onnxmsrt\":\n y = self.run_onnxmsrt(model_proto, input_dict, args.outputs, self._testMethodName)\n elif BACKEND == \"cntk\":\n y = self.run_onnxcntk(model_proto, input_dict, self._testMethodName)\n elif BACKEND == \"caffe2\":\n y = self.run_onnxcaffe2(model_proto, input_dict)\n elif BACKEND == \"onnxnumpy\":\n y = self.run_onnxnumpy(model_proto, input_dict)\n y = y[args.outputs[0]]\n else:\n raise ValueError(\"unknown backend\")\n return y\n\n def _run(self, output, tf_dict, onnx_dict):\n with tf.Session() as sess:\n expected = sess.run(output, feed_dict=tf_dict)\n g = process_tf_graph(sess.graph)\n actual = self.validate_onnx(g, self._args1, onnx_dict, expected)\n return actual, expected\n\n def _test_expand_dims(self, idx):\n tf.reset_default_graph()\n x_val = make_xval([3, 4])\n x = tf.placeholder(tf.float32, shape=x_val.shape, name=_TFINPUT)\n op = tf.expand_dims(x, idx)\n with tf.Session() as sess:\n output = tf.identity(op, name=_TFOUTPUT)\n sess.run(tf.global_variables_initializer())\n expected = sess.run(output, feed_dict={x: x_val})\n g = process_tf_graph(sess.graph)\n actual = self.validate_onnx(g, self._args1, {_INPUT: x_val}, expected)\n self.assertAllClose(expected, actual)\n\n def test_expand_dims(self):\n for i in [-1, 0, 1, -2]:\n self._test_expand_dims(i)\n\n def test_maxppol(self):\n x_val = make_xval((1, 4, 4, 1))\n x = tf.placeholder(tf.float32, shape=x_val.shape, name=_TFINPUT)\n mp = tf.nn.max_pool(x, [1, 2, 2, 1], _STRIDE1x1, padding=\"VALID\")\n output = tf.identity(mp, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_avgppol(self):\n x_val = make_xval((1, 4, 4, 1))\n x = tf.placeholder(tf.float32, shape=x_val.shape, name=_TFINPUT)\n mp = tf.nn.avg_pool(x, [1, 2, 2, 1], _STRIDE1x1, padding=\"VALID\")\n output = tf.identity(mp, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def _conv_test(self, x_val, w, strides=None, padding=\"VALID\"):\n if strides is None:\n strides = _STRIDE1x1\n tf.reset_default_graph()\n kernel = tf.constant(w, dtype=tf.float32, name='k')\n with tf.Session() as sess:\n x = tf.placeholder(tf.float32, shape=x_val.shape, name=_TFINPUT)\n conv = tf.nn.conv2d(x, kernel, strides=strides, padding=padding)\n output = tf.identity(conv, name=_TFOUTPUT)\n sess.run(tf.global_variables_initializer())\n expected = sess.run(output, feed_dict={x: x_val})\n g = process_tf_graph(sess.graph)\n actual = self.validate_onnx(g, self._args1, {_INPUT: x_val}, expected)\n return expected, actual\n\n def test_conv2d_1(self):\n x_val = make_xval((1, 1, 5, 5)).transpose(NCHW_TO_NHWC)\n w = np.array([[2., 1., 1.],\n [1., 3., 1.],\n [1., 1., 4.]], dtype=np.float32).reshape(_KERNEL3x3)\n expected, actual = self._conv_test(x_val, w)\n self.assertAllClose(expected, actual)\n\n def test_conv2d_2(self):\n x_val = np.array([[4, 3, 1, 0],\n [2, 1, 0, 1],\n [1, 2, 4, 1],\n [3, 1, 0, 2]], dtype=np.float32).reshape([1, 4, 4, 1])\n w = np.array([[1, 0, 1],\n [2, 1, 0],\n [0, 0, 1]], dtype=np.float32).reshape(_KERNEL3x3)\n expected, actual = self._conv_test(x_val, w)\n self.assertAllClose(expected, actual)\n\n def test_conv2d_3(self):\n x_val = make_xval((1, 1, 5, 5)).transpose(NCHW_TO_NHWC)\n w = np.array([[2., 1., 1.],\n [1., 3., 1.],\n [1., 1., 4.]], dtype=np.float32).reshape(_KERNEL3x3)\n expected, actual = self._conv_test(x_val, w)\n self.assertAllClose(expected, actual)\n\n def test_conv2d_4(self):\n x_val = make_xval((1, 1, 5, 5)).transpose(NCHW_TO_NHWC)\n w = np.random.random_sample(_KERNEL3x3).astype(np.float32)\n expected, actual = self._conv_test(x_val, w, padding=\"SAME\")\n self.assertAllClose(expected, actual, rtol=1e-05)\n\n def test_conv2d_5(self):\n x_val = make_xval((1, 1, 5, 5)).transpose(NCHW_TO_NHWC)\n kernel_shape = [3, 3, 1, 2]\n w = np.random.random_sample(kernel_shape).astype(np.float32)\n expected, actual = self._conv_test(x_val, w, padding=\"SAME\")\n self.assertAllClose(expected, actual, rtol=1e-05)\n\n def test_conv2d_6(self):\n x_shape = [1, 35, 35, 288] # out: [1, 17, 17, 384]\n kernel_shape = [3, 3, 288, 384]\n strides = [1, 2, 2, 1]\n x_val = np.arange(1, 1 + np.prod(x_shape)).astype(\"float32\").reshape(x_shape)\n kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype(\"float32\").reshape(kernel_shape)\n expected, actual = self._conv_test(x_val, kernel_val, strides=strides, padding=\"VALID\")\n self.assertAllClose(expected, actual, rtol=1e-05)\n\n def test_conv2d_transpose(self):\n x_shape = [2, 6, 4, 3]\n output_shape = [2, 13, 9, 2]\n kernel_shape = [3, 3, 2, 3]\n strides = [1, 2, 2, 1]\n x_val = make_xval(x_shape)\n kernel_val = make_xval(kernel_shape)\n with tf.Session() as sess:\n x = tf.placeholder(tf.float32, shape=x_shape, name=_TFINPUT)\n f = tf.constant(kernel_val, name=\"kernel\", dtype=tf.float32)\n conv = tf.nn.conv2d_transpose(x, f, output_shape, strides=strides, padding=\"VALID\")\n output = tf.identity(conv, name=_TFOUTPUT)\n sess.run(tf.global_variables_initializer())\n expected = sess.run(output, feed_dict={x: x_val})\n g = process_tf_graph(sess.graph)\n actual = self.validate_onnx(g, self._args1, {_INPUT: x_val}, expected)\n self.assertAllClose(expected, actual, rtol=1e-05)\n\n def test_depthwiseconv_0(self):\n x_shape = [1, 3, 4, 3]\n kernel_shape = [3, 3, 3, 3]\n x_val = np.arange(1, 1 + np.prod(x_shape)).astype(\"float32\").reshape(x_shape)\n kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype(\"float32\").reshape(kernel_shape)\n kernel = tf.constant(kernel_val, dtype=tf.float32, name='k')\n x = tf.placeholder(tf.float32, shape=x_val.shape, name=_TFINPUT)\n conv = tf.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1], padding='VALID')\n output = tf.identity(conv, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n # rtol is a bit high, 2 values have a bit high error. Maybe use different input data.\n self.assertAllClose(expected, actual, rtol=0.08)\n\n def test_depthwiseconv_1(self):\n x_shape = [1, 112, 112, 32]\n kernel_shape = [3, 3, 32, 1]\n x_val = np.arange(1, 1 + np.prod(x_shape)).astype(\"float32\").reshape(x_shape)\n kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype(\"float32\").reshape(kernel_shape)\n kernel = tf.constant(kernel_val, dtype=tf.float32, name='k')\n x = tf.placeholder(tf.float32, shape=x_val.shape, name=_TFINPUT)\n conv = tf.nn.depthwise_conv2d(x, kernel, strides=_STRIDE1x1, padding='VALID')\n output = tf.identity(conv, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n # rtol is a bit high, 2 values have a bit high error. Maybe use different input data.\n self.assertAllClose(expected, actual, rtol=0.08)\n\n @unittest.skip\n def test_lrn(self):\n # FIXME: numerical results are not correct\n x_shape = [1, 3, 4, 3]\n x_val = np.arange(1, 1 + np.prod(x_shape)).astype(\"float32\").reshape(x_shape)\n x = tf.placeholder(tf.float32, shape=x_val.shape, name=_TFINPUT)\n op = tf.nn.local_response_normalization(x_val)\n output = tf.identity(op, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual, rtol=1e-05)\n\n def test_abs(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.abs(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_const(self):\n x_val = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32).reshape((2, 2))\n x = tf.constant(x_val, name=_TFINPUT)\n x_ = tf.identity(x)\n output = tf.add(x_, x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_add(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.add(x, x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_add_bcast(self):\n x1_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x2_val = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], dtype=np.float32).reshape((2, 2, 2))\n # if we'd broadcast 2,2 to 2,1 onnxmsrt will fail\n x1 = tf.placeholder(tf.float32, x1_val.shape, name=\"input\")\n x2 = tf.placeholder(tf.float32, x2_val.shape, name=_TFINPUT1)\n x_ = tf.add(x1, x2)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x1: x1_val, x2: x2_val}, {_INPUT: x1_val, _INPUT1: x2_val})\n self.assertAllClose(expected, actual)\n\n def test_matmul(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.matmul(x, x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_sub(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.subtract(x, x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_multiply(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.multiply(x, x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_div(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.realdiv(x, x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_exp(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.exp(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual, rtol=1e-05)\n\n def test_log(self):\n x_val = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.log(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_gather(self):\n x_val = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32)\n idx = np.array([1, 0, 2], dtype=np.int32)\n idx_flattened = np.array([i * x_val.shape[1] + idx for i in range(0, x_val.shape[0])])\n x = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.gather(tf.reshape(x, [-1]), tf.constant(idx_flattened))\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_neg(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.negative(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_square(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.square(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_min(self):\n x_val1 = np.array([4.0, 16.0, 4.0, 1.6], dtype=np.float32).reshape((2, 2))\n x_val2 = np.array([4.0, 4.0, 4.0, 4.0], dtype=np.float32).reshape((2, 2))\n x1 = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x2 = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT1)\n mi = tf.minimum(x1, x2)\n output = tf.identity(mi, name=_TFOUTPUT)\n actual, expected = self._run(output, {x1: x_val1, x2: x_val2}, {_INPUT: x_val1, _INPUT1: x_val2, })\n self.assertAllClose(expected, actual)\n\n def test_logicaland(self):\n x_val1 = np.array([1, 0, 1, 1], dtype=np.bool).reshape((2, 2))\n x_val2 = np.array([0, 1, 1, 1], dtype=np.bool).reshape((2, 2))\n x1 = tf.placeholder(tf.bool, [2, 2], name=_TFINPUT)\n x2 = tf.placeholder(tf.bool, [2, 2], name=_TFINPUT1)\n mi = tf.logical_and(x1, x2)\n output = tf.identity(mi, name=_TFOUTPUT)\n actual, expected = self._run(output, {x1: x_val1, x2: x_val2}, {_INPUT: x_val1, _INPUT1: x_val2,})\n self.assertAllClose(expected, actual)\n\n def test_greater(self):\n x_val1 = np.array([4, 2, 4, 1], dtype=np.float32).reshape((2, 2))\n x_val2 = np.array([2, 4, 4, 1], dtype=np.float32).reshape((2, 2))\n x1 = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x2 = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT1)\n mi = tf.greater(x1, x2)\n output = tf.identity(mi, name=_TFOUTPUT)\n actual, expected = self._run(output, {x1: x_val1, x2: x_val2}, {_INPUT: x_val1, _INPUT1: x_val2,})\n self.assertAllClose(expected, actual)\n\n def test_sequeeze(self):\n x_val = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32).reshape((2, 2, 1))\n x = tf.placeholder(tf.float32, [2, 2, 1], name=_TFINPUT)\n x_ = tf.squeeze(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_transpose(self):\n x_val = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], dtype=np.float32).reshape((2, 3))\n x = tf.placeholder(tf.float32, [2, 3], name=_TFINPUT)\n x_ = tf.transpose(x) # perm=[1,0])\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_reshape(self):\n x_val = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n shape = tf.constant([1, 4])\n x_ = tf.reshape(x, shape)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertEqual(expected.shape, actual.shape)\n self.assertAllClose(expected, actual)\n\n def test_relu(self):\n x_val = np.array([0.5, 1.0, -0.5, -1.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.nn.relu(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_elu(self):\n x_val = np.array([0.5, 1.0, -0.5, -1.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.nn.elu(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_tanh(self):\n x_val = np.array([0.5, 1.0, -0.5, -1.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.tanh(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual, rtol=1e-05)\n\n def test_relu6(self):\n x_val = np.array([0.5, 1.0, -0.5, -1.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.nn.relu6(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_concat(self):\n x_val1 = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)\n x_val2 = np.array([[7, 8, 9], [10, 11, 12]], dtype=np.float32)\n x_val3 = np.array([[13, 14, 15], [16, 17, 18]], dtype=np.float32)\n x1 = tf.placeholder(tf.float32, x_val1.shape, name=_TFINPUT)\n x2 = tf.placeholder(tf.float32, x_val2.shape, name=_TFINPUT1)\n x3 = tf.placeholder(tf.float32, x_val3.shape, name=\"input3\")\n x_ = tf.concat([x1, x2, x3], 0)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x1: x_val1, x2: x_val2, x3: x_val3},\n {_INPUT: x_val1, _INPUT1: x_val2, \"input3:0\": x_val3})\n self.assertAllClose(expected, actual)\n\n def test_pow(self):\n x_val = np.array([4.0, 16.0, 4.0, 1.6], dtype=np.float32)\n e = np.array([2.0, 2.0, 2.0, 2.0], dtype=np.float32)\n x = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.pow(x, tf.constant(e))\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_embedding_lookup(self):\n x_val1 = np.array([[1]], dtype=np.int32)\n x_val2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=np.float32)\n t = tf.constant(x_val2)\n x = tf.placeholder(tf.int32, x_val1.shape, name=_TFINPUT)\n x_ = tf.nn.embedding_lookup(t, x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val1}, {_INPUT: x_val1})\n self.assertAllClose(expected, actual)\n\n def test_slice(self):\n x_val = np.array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=np.float32)\n t1 = tf.constant([0, 1], dtype=tf.int32)\n t2 = tf.constant([2, 2], dtype=tf.int32)\n x0 = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.slice(x0, t1, t2)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x0: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_split(self):\n x_val = np.linspace(1.0, 5 * 30.0, 5 * 30).astype(np.float32).reshape(5, 30)\n x0 = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_, _, _ = tf.split(x0, [4, 15, 11], 1)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x0: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n @unittest.skipIf(BACKEND == \"caffe2\", \"not supported in caffe2\")\n def test_reducesum(self):\n # not supported by onnx-caffe2\n x_val = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.reduce_sum(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n @unittest.skipIf(BACKEND == \"caffe2\", \"not supported in caffe2\")\n def test_sqrt(self):\n x_val = np.array([4.0, 16.0, 4.0, 1.6], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.sqrt(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n @unittest.skipIf(BACKEND == \"caffe2\", \"not supported in caffe2\")\n def test_rsqrt(self):\n x_val = np.array([4.0, 16.0, 4.0, 1.6], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.rsqrt(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual, rtol=1e-05)\n\n @unittest.skipIf(BACKEND == \"caffe2\", \"not supported in caffe2\")\n def test_reciprocal(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.reciprocal(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual, rtol=1e-04)\n\n @unittest.skipIf(BACKEND == \"caffe2\", \"not supported in caffe2\")\n def test_reducemax(self):\n # not supported by onnx-caffe2\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.reduce_max(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual, rtol=1e-05)\n\n @unittest.skipIf(BACKEND == \"caffe2\", \"not supported in caffe2\")\n def test_reduceprod(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.reduce_prod(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n @unittest.skipIf(BACKEND == \"caffe2\", \"not supported in caffe2\")\n def test_reducemean(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.reduce_mean(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n @unittest.skip\n def test_slice1(self):\n # FIXME: only 1 dimension supported by caffe2 and msrt\n x_val = np.array([[[1, 1, 1], [2, 2, 2]],\n [[3, 3, 3], [4, 4, 4]],\n [[5, 5, 5], [6, 6, 6]]], dtype=np.float32)\n t1 = tf.constant([1, 0, 0], dtype=tf.int32)\n t2 = tf.constant([1, 1, 3], dtype=tf.int32)\n x0 = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.slice(x0, t1, t2)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x0: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n @unittest.skipIf(BACKEND in [\"caffe2\"], \"issue with broadcastnig scalar\")\n def test_pow_scalar(self):\n x_val = np.array([4.0, 16.0, 4.0, 1.6], dtype=np.float32)\n e = np.array(2.0, dtype=np.float32)\n x = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.pow(x, tf.constant(e))\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n @unittest.skipIf(BACKEND == \"caffe2\", \"not supported correctly in caffe2\")\n def test_pad(self):\n x_val = np.array([[1.0, 1.2], [2.3, 3.4], [4.5, 5.7]], dtype=np.float32)\n x = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n paddings = tf.constant([[0, 0, ], [2, 0]])\n op = tf.pad(x, paddings, \"CONSTANT\")\n output = tf.identity(op, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n @unittest.skip\n def test_randomuniform(self):\n # not supported by onnxmsrt or caffe2\n shape = tf.constant([2, 3], name=\"shape\")\n x_ = tf.random_uniform(shape, name=\"rand\", dtype=tf.float32)\n x_ = tf.identity(x_, name=\"output1\")\n x_ = tf.identity(x_, name=\"output2\")\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {}, {})\n self.assertAllClose(expected, actual)\n\n @unittest.skip\n def test_argminmax(self):\n # TODO: fails on onnxmsrt caffe2\n x_val = np.array([0.5, 1.0, -0.5, -1.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.argmin(x, axis=0)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {}, {})\n self.assertAllClose(expected, actual)\n\n def test_cast(self):\n x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))\n x = tf.placeholder(tf.float32, [2, 2], name=_TFINPUT)\n x_ = tf.cast(x, tf.int32)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n @unittest.skip\n def test_onehot(self):\n # FIXME via onnx-ml ?\n x_val = np.array([0, 1, 2], dtype=np.int32)\n depth = 3\n x = tf.placeholder(tf.int32, x_val.shape, name=_TFINPUT)\n x_ = tf.one_hot(x, depth)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n @unittest.skipIf(BACKEND in [\"caffe2\"], \"issue undefined dim 1\")\n def test_flatten0(self):\n x_val = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]], dtype=np.float32)\n x = tf.placeholder(tf.float32, [None, 3, 3], name=_TFINPUT)\n x_ = tf.layers.flatten(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_flatten1(self):\n x_val = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]], dtype=np.float32)\n x = tf.placeholder(tf.float32, [1, 3, 3], name=_TFINPUT)\n x_ = tf.layers.flatten(x)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n def test_cancel_transpose(self):\n x_val = np.array([[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]], dtype=np.float32)\n x = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.identity(x, _TFINPUT)\n x_ = tf.transpose(x_, perm=NHWC_TO_NCHW)\n x_ = tf.transpose(x_, perm=NCHW_TO_NHWC)\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n @unittest.skip\n def test_strided_slice0(self):\n # FIXME: not implemented yet\n x_val = np.array([\n [[1, 1, 1], [2, 2, 2]],\n [[3, 3, 3], [4, 4, 4]],\n [[5, 5, 5], [6, 6, 6]]], dtype=np.float32)\n x = tf.placeholder(tf.float32, x_val.shape, name=_TFINPUT)\n x_ = tf.strided_slice(x, [1, 0, 0], [2, 1, 3], [1, 1, 1])\n output = tf.identity(x_, name=_TFOUTPUT)\n actual, expected = self._run(output, {x: x_val}, {_INPUT: x_val})\n self.assertAllClose(expected, actual)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "tensorflow.concat", "numpy.linspace", "tensorflow.nn.max_pool", "tensorflow.reduce_sum", "tensorflow.minimum", "tensorflow.cast", "numpy.random.random_sample", "tensorflow.nn.conv2d_transpose", "tensorflow.tanh", "tensorflow.pad", "tensorflow.nn.depthwise_conv2d", "tensorflow.argmin", "tensorflow.nn.conv2d", "tensorflow.strided_slice", "tensorflow.greater", "tensorflow.squeeze", "tensorflow.subtract", "tensorflow.reset_default_graph", "tensorflow.add", "tensorflow.nn.local_response_normalization", "tensorflow.square", "tensorflow.Session", "tensorflow.rsqrt", "tensorflow.negative", "tensorflow.reciprocal", "tensorflow.matmul", "tensorflow.realdiv", "tensorflow.nn.elu", "tensorflow.identity", "tensorflow.placeholder", "tensorflow.exp", "tensorflow.global_variables_initializer", "tensorflow.reduce_prod", "tensorflow.nn.avg_pool", "tensorflow.one_hot", "numpy.testing.assert_allclose", "tensorflow.split", "numpy.array", "tensorflow.nn.embedding_lookup", "tensorflow.nn.relu", "tensorflow.reduce_max", "tensorflow.multiply", "tensorflow.constant", "tensorflow.transpose", "numpy.random.seed", "tensorflow.nn.relu6", "tensorflow.slice", "tensorflow.reduce_mean", "tensorflow.layers.flatten", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.log", "numpy.prod", "tensorflow.sqrt", "tensorflow.random_uniform", "tensorflow.abs", "tensorflow.logical_and" ] ]
rballester/ttpy
[ "a2fdf08fae9d34cb1e5ba28482e82e04b249911b" ]
[ "setup.py" ]
[ "#!/usr/bin/env python\n\"\"\"TTPY: Python implementation of the Tensor Train (TT) - Toolbox.\n\nPython implementation of the Tensor Train (TT) - Toolbox. It contains several important packages for working with the\nTT-format in Python. It is able to do TT-interpolation, solve linear systems, eigenproblems, solve dynamical problems.\nSeveral computational routines are done in Fortran (which can be used separatedly), and are wrapped with the f2py tool.\n\"\"\"\n\nfrom numpy.distutils.core import setup\nfrom numpy.distutils.misc_util import Configuration\n\nDOCLINES = (__doc__ or '').split('\\n')\n\nPLATFORMS = [\n 'Windows',\n 'Linux',\n 'Solaris',\n 'Mac OS-X',\n 'Unix',\n]\n\nCLASSIFIERS = \"\"\"\\\nDevelopment Status :: 4 - Beta\nIntended Audience :: Science/Research\nIntended Audience :: Developers\nLicense :: OSI Approved :: MIT License\nProgramming Language :: Fortran\nProgramming Language :: Python\nProgramming Language :: Python :: 2\nProgramming Language :: Python :: 2.6\nProgramming Language :: Python :: 2.7\nProgramming Language :: Python :: Implementation :: CPython\nTopic :: Software Development\nTopic :: Scientific/Engineering\nOperating System :: Microsoft :: Windows\nOperating System :: POSIX\nOperating System :: Unix\nOperating System :: MacOS\n\"\"\"\n\nMAJOR = 1\nMINOR = 1\nMICRO = 0\nISRELEASED = True\nVERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)\n\n\ndef configuration(parent_package='', top_path=None):\n config = Configuration(None, parent_package, top_path)\n config.set_options(\n ignore_setup_xxx_py=True,\n assume_default_configuration=True,\n delegate_options_to_subpackages=True,\n quiet=True,\n )\n config.add_subpackage('tt')\n return config\n\ndef setup_package():\n metadata = dict(\n name='ttpy',\n version=VERSION,\n description = DOCLINES[0],\n long_description = '\\n'.join(DOCLINES[2:]),\n url='https://github.com/oseledets/ttpy',\n download_url='https://github.com/oseledets/ttpy/tarball/v' + VERSION,\n author='Ivan Oseledets',\n maintainer='Ivan Oseledets',\n platforms=PLATFORMS,\n classifiers=[line for line in CLASSIFIERS.split('\\n') if line],\n configuration=configuration,\n )\n\n setup(**metadata)\n\n\nif __name__ == '__main__':\n setup_package()\n" ]
[ [ "numpy.distutils.misc_util.Configuration", "numpy.distutils.core.setup" ] ]
RyanXingQL/MW-GAN
[ "562199344e322919a108048acd55b0dd8820df55" ]
[ "codes/models/modules/Wavelet.py" ]
[ "\r\nimport torch\r\nimport torch.nn as nn\r\n\r\n\r\n\r\ndef default_conv(in_channels, out_channels, kernel_size, bias=True, dilation=1, use_snorm=False):\r\n if use_snorm:\r\n return nn.utils.spectral_norm(nn.Conv2d(\r\n in_channels, out_channels, kernel_size,\r\n padding=(kernel_size//2)+dilation-1, bias=bias, dilation=dilation))\r\n else:\r\n return nn.Conv2d(\r\n in_channels, out_channels, kernel_size,\r\n padding=(kernel_size//2)+dilation-1, bias=bias, dilation=dilation)\r\n\r\n\r\ndef dwt_init(x):\r\n x01 = x[:, :, 0::2, :] / 2\r\n x02 = x[:, :, 1::2, :] / 2\r\n x1 = x01[:, :, :, 0::2]\r\n x2 = x02[:, :, :, 0::2]\r\n x3 = x01[:, :, :, 1::2]\r\n x4 = x02[:, :, :, 1::2]\r\n x_LL = x1 + x2 + x3 + x4\r\n x_HL = -x1 - x2 + x3 + x4\r\n x_LH = -x1 + x2 - x3 + x4\r\n x_HH = x1 - x2 - x3 + x4\r\n\r\n return torch.cat((x_LL, x_HL, x_LH, x_HH), 1)\r\n\r\n\r\ndef iwt_init(x):\r\n r = 2\r\n in_batch, in_channel, in_height, in_width = x.size()\r\n #print([in_batch, in_channel, in_height, in_width])\r\n out_batch, out_channel, out_height, out_width = in_batch, int(\r\n in_channel / (r ** 2)), r * in_height, r * in_width\r\n x1 = x[:, 0:out_channel, :, :] / 2\r\n x2 = x[:, out_channel:out_channel * 2, :, :] / 2\r\n x3 = x[:, out_channel * 2:out_channel * 3, :, :] / 2\r\n x4 = x[:, out_channel * 3:out_channel * 4, :, :] / 2\r\n\r\n\r\n h = torch.zeros([out_batch, out_channel, out_height, out_width]).float().cuda()\r\n\r\n h[:, :, 0::2, 0::2] = x1 - x2 - x3 + x4\r\n h[:, :, 1::2, 0::2] = x1 - x2 + x3 - x4\r\n h[:, :, 0::2, 1::2] = x1 + x2 - x3 - x4\r\n h[:, :, 1::2, 1::2] = x1 + x2 + x3 + x4\r\n\r\n return h\r\n\r\n\r\nclass DWT(nn.Module):\r\n def __init__(self):\r\n super(DWT, self).__init__()\r\n self.requires_grad = False\r\n\r\n def forward(self, x):\r\n return dwt_init(x)\r\n\r\n\r\nclass IWT(nn.Module):\r\n def __init__(self):\r\n super(IWT, self).__init__()\r\n self.requires_grad = False\r\n\r\n def forward(self, x):\r\n return iwt_init(x)\r\n" ]
[ [ "torch.nn.Conv2d", "torch.zeros", "torch.cat" ] ]
lapras-inc/disk-embedding
[ "09b2faaa81f7fc8080a3817961b740232cabe8e4" ]
[ "models/disk_emb_model_orig.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nDisk Embedding Model Original Version.\n\"\"\"\n\nfrom .dag_emb_model import DAGEmbeddingModel, DAGEmbeddingKeyedVectors\nfrom .metric_space import get_metric_space, QuasimetricSpaceBase, SphericalSpace\nfrom .loss_function import get_loss_function\nimport numpy as np\n\ntry:\n from autograd import grad # Only required for optionally verifying gradients while training\n from autograd import numpy as grad_np\n AUTOGRAD_PRESENT = True\nexcept ImportError:\n AUTOGRAD_PRESENT = False\n\n# Cosine clipping epsilon\nEPS = 1e-7\n\nclass DiskEmbeddingModel(DAGEmbeddingModel):\n \"\"\"Class for training, using and evaluating Order Embeddings.\"\"\"\n def __init__(self,\n train_data,\n dim=50,\n init_range=(-0.1, 0.1),\n lr=0.01,\n seed=0,\n logger=None,\n opt='disk_rsgd',\n burn_in=0,\n\n num_negative=1,\n ### How to sample negatives for an edge (u,v)\n neg_sampl_strategy='all', # 'all' (all nodes for negative sampling) or 'true_neg' (only nodes not connected)\n where_not_to_sample='children', # both or ancestors or children. Has no effect if neg_sampl_strategy = 'all'.\n neg_edges_attach='both', # How to form negative edges: 'parent' (u,v') or 'child' (u', v) or 'both'\n always_v_in_neg=False,\n neg_sampling_power=0.0, # 0 for uniform, 1 for unigram, 0.75 for word2vec\n\n metric='euc',\n loss='relu',\n margin=1.0, # Margin for the OE loss.\n radius_range='none',\n\n # ### init_vector_conv: how to convert pretrained vector\n # - poincare, poincare2sphere: PoincareNIPS -> Spherical DE. Uses init_vector_k.\n # - poincare2lorentz: PoincareNIPS -> Hyperbolic DE.\n # - centers: n-1 point-wise embedding models -> DE.\n init_vector_conv='none',\n init_vector_k=0.1, # used to convert initial vector for spherical model. used only if init_vector_conv='poincare2sphere'\n init_vector_eps=1e-5, # used to convert Poincare ball to Lorentz model. used only if init_vector_conv='poincare2lorentz'\n ):\n\n self.metric = get_metric_space(metric, dim-1)\n\n self.actual_dim = dim\n self.nomial_dim = self.metric.nomial_dim + 1\n\n\n self.loss_function = get_loss_function(loss, margin=margin)\n self.margin = margin\n self.radius_range=radius_range\n\n assert radius_range in ['none', 'nonnegative', 'child_of_origin', 'parent_of_origin']\n assert opt == 'disk_rsgd'\n assert neg_sampl_strategy == 'all'\n assert neg_edges_attach == 'both'\n\n assert init_vector_conv in ['none', 'poincare', 'poincare2sphere', 'poincare2lorentz', 'centers']\n self.init_vector_conv = init_vector_conv\n self.init_vector_k = init_vector_k\n self.init_vector_eps = init_vector_eps\n\n # patch keyed vectors to recieve\n def _keyed_vector_generator():\n return DiskEmbeddingKeyedVectors(self.metric)\n\n super().__init__(train_data=train_data,\n dim=self.nomial_dim,\n init_range=init_range,\n lr=lr,\n opt=opt,\n burn_in=burn_in,\n seed=seed,\n logger=logger,\n # BatchClass=DiskEmbeddingBatch,\n KeyedVectorsClass=_keyed_vector_generator,\n num_negative=num_negative,\n neg_sampl_strategy=neg_sampl_strategy,\n where_not_to_sample=where_not_to_sample,\n always_v_in_neg=always_v_in_neg,\n neg_sampling_power=neg_sampling_power,\n neg_edges_attach=neg_edges_attach)\n\n def _clip_vectors(self, vectors, axis=-1):\n radius, centers = np.split(vectors, [1], axis=axis)\n\n # clip centers\n centers = self.metric.clip_vectors(centers, axis=axis)\n\n # clip radius\n if self.radius_range == 'nonnegative':\n radius = np.maximum(0, radius)\n\n elif self.radius_range == 'child_of_origin':\n dist = np.expand_dims(self.metric.compute_distance(np.zeros_like(centers), centers, axis=axis), axis=axis)\n radius = np.minimum(-dist, radius)\n elif self.radius_range == 'parent_of_origin':\n dist = np.expand_dims(self.metric.compute_distance(centers, np.zeros_like(centers), axis=axis), axis=axis)\n radius = np.maximum(dist, radius)\n\n return np.concatenate((radius, centers), axis=axis)\n\n\n def supply_init_vectors(self, vectors):\n vectors = np.asarray(vectors)\n if self.init_vector_conv == 'none':\n self.kv.syn0[:] = vectors\n\n elif self.init_vector_conv in ['poincare', 'poincare2sphere']:\n if not isinstance(self.metric, SphericalSpace):\n raise ValueError(\"init_vector_conv = 'poincare' is only available for Spherical Disk Embeddings.\")\n\n K = self.init_vector_k\n t0 = np.arctan(2*K)\n\n norm = np.linalg.norm(vectors, axis=1)\n\n radii = np.arcsin(np.clip(0.5*(1+norm**2)/norm*np.sin(t0), 0,1)) - t0\n centers = vectors / norm[:,np.newaxis]\n\n self.kv.syn0[:,0] = radii\n self.kv.syn0[:,1:] = centers\n\n elif self.init_vector_conv == 'poincare2lorentz':\n eps = self.init_vector_eps\n norm = np.linalg.norm(vectors, axis=1)\n\n clipped_vectors = np.where(norm[:,np.newaxis] > 1-eps, vectors*(1-eps)/norm[:,np.newaxis], vectors)\n norm = np.clip(norm, 0, 1-eps)\n\n self.kv.syn0[:,1] = (1+norm**2) / (1-norm**2)\n self.kv.syn0[:,2:] = clipped_vectors * 2 / (1-norm[:,np.newaxis]**2)\n\n elif self.init_vector_conv == 'centers':\n self.kv.syn0[:,1:] = vectors\n\n else:\n raise ValueError(\"Unknown conversion method\")\n\n\n\n\n def _sample_pairs(self, n):\n max_size = self.kv.syn0.shape[0]\n\n lefts = self._np_rand.choice(max_size, n)\n\n rights = self._np_rand.choice(max_size-1, n)\n rights[rights >= lefts] += 1 # avoid identical pairs\n\n return np.stack((lefts, rights), axis=1)\n\n def _train_on_batch(self, pos_relations):\n num_pos = len(pos_relations)\n num_neg = int(self.num_negative * num_pos)\n\n pos_left_indices, pos_right_indices = np.array(pos_relations).T\n neg_left_indices, neg_right_indices = self._sample_pairs(num_neg).T\n\n left_indices = np.concatenate((pos_left_indices, neg_left_indices))\n right_indices = np.concatenate((pos_right_indices, neg_right_indices))\n\n labels = np.concatenate((np.ones(num_pos, dtype=bool), np.zeros(num_neg, dtype=bool)))\n left_vectors = self.kv.syn0[left_indices]\n right_vectors = self.kv.syn0[right_indices]\n\n loss, pos_loss, neg_loss = self.compute_loss(left_vectors, right_vectors, labels, True)\n left_gradients, right_gradients = self.compute_loss_gradients(left_vectors, right_vectors, labels)\n\n\n gradients = np.concatenate((left_gradients, right_gradients), axis=0)\n indices = np.concatenate((left_indices, right_indices))\n gradients, indices = self._gather_indices(gradients, indices)\n updates = self.lr * gradients\n\n\n right_updates = self.lr * right_gradients\n\n # update radius\n self.kv.syn0[indices, 0] -= updates[:,0]\n # update center\n self.kv.syn0[indices, 1:] = self.metric.exp_map(self.kv.syn0[indices, 1:], -updates[:,1:], axis=1)\n # clip into subspace\n self.kv.syn0[indices,:] = self._clip_vectors(self.kv.syn0[indices,:], axis=1)\n\n\n if np.abs(self.kv.syn0[0,:]).sum() > 1e20:\n print(\"##### NaN observed!!\")\n print(self.kv.syn0[np.isnan(self.kv.syn0.sum(axis=1))])\n print(\"#####\")\n print(batch.loss_gradients_u)\n raise()\n\n return loss, pos_loss, neg_loss\n\n\n\n @staticmethod\n def _gather_indices(vectors, indices):\n batch_size, dim = vectors.shape\n new_indices, index_map = np.unique(indices, return_inverse=True)\n new_vectors = np.zeros((new_indices.size, dim))\n for src, dst in enumerate(index_map):\n new_vectors[dst,:] += vectors[src,:]\n\n return new_vectors, new_indices\n\n \n def compute_loss(self, left_vectors, right_vectors, labels, return_pos_neg=False):\n \"\"\" compute loss\n\n left_vectors: (n, dim)-array\n vectors for right side hand.\n\n right_vectors: (n, dim)-array\n vectors for left side hand.\n\n labels: labels for each pair.\n 1: positive, 0: negative\n \"\"\"\n\n left_radii = left_vectors[:,0]\n left_centers = left_vectors[:,1:]\n right_radii = right_vectors[:,0]\n right_centers = right_vectors[:,1:]\n dist = self.metric.compute_distance(left_centers, right_centers, axis=1)\n loss_vec = self.loss_function.compute_loss(dist, left_radii, right_radii, labels)\n\n pos_loss = loss_vec[labels].sum()\n neg_loss = loss_vec[~labels].sum()\n loss = pos_loss + neg_loss\n\n if return_pos_neg:\n return loss, pos_loss, neg_loss\n else:\n return loss\n\n\n\n def compute_loss_gradients(self, left_vectors, right_vectors, labels):\n \"\"\" compute loss gradients\n\n left_vectors: (n, dim)-array\n vectors for right side hand.\n\n right_vectors: (n, dim)-array\n vectors for left side hand.\n\n labels: labels for each pair.\n 1: positive, 0: negative\n\n # returns\n grad_left: gradient for left vectors of the pair\n grad_right: gradient for right vectors of the pair\n \"\"\"\n\n labels = np.asarray(labels, dtype=bool)\n\n # left_indices, right_indices = np.array(pairs).T\n # left_vectors = self.kv.syn0[left_indices]\n # right_vectors = self.kv.syn0[right_indices]\n\n # (n, dim-1)\n left_centers = left_vectors[:,1:]\n right_centers = right_vectors[:,1:]\n\n # (n)\n left_radii = left_vectors[:,0]\n right_radii = right_vectors[:,0]\n dist = self.metric.compute_distance(left_centers, right_centers, axis=1)\n\n # (n)\n loss_diff_dist, loss_diff_left_radii, loss_diff_right_radii = self.loss_function.compute_loss_diff(dist, left_radii, right_radii, labels)\n\n # (n, dim-1)\n dist_grad_left_centers = self.metric.compute_distance_grad_u(left_centers, right_centers, axis=1)\n dist_grad_right_centers = self.metric.compute_distance_grad_v(left_centers, right_centers, axis=1)\n\n # (n, dim-1)\n loss_grad_left_centers = loss_diff_dist[:,np.newaxis] * dist_grad_left_centers\n loss_grad_right_centers = loss_diff_dist[:,np.newaxis] * dist_grad_right_centers\n\n # (n, dim)\n loss_grad_left = np.concatenate((loss_diff_left_radii[:,np.newaxis], loss_grad_left_centers), axis=1)\n loss_grad_right = np.concatenate((loss_diff_right_radii[:,np.newaxis], loss_grad_right_centers), axis=1)\n\n return loss_grad_left, loss_grad_right\n \n\nclass DiskEmbeddingKeyedVectors(DAGEmbeddingKeyedVectors):\n\n def __init__(self, metric, *args, **kwargs):\n assert isinstance(metric, QuasimetricSpaceBase)\n self.metric = metric\n\n super().__init__(*args, **kwargs)\n\n def is_a_scores_vector_batch(self, alpha, parent_vectors, other_vectors, rel_reversed):\n if rel_reversed:\n parent_vectors, other_vectors = other_vectors, parent_vectors\n\n distances = self.metric.compute_distance(parent_vectors[:,1:], other_vectors[:,1:], axis=1)\n\n return distances - parent_vectors[:,0] + other_vectors[:,0]\n\n" ]
[ [ "numpy.split", "numpy.maximum", "numpy.minimum", "numpy.arctan", "numpy.unique", "numpy.asarray", "numpy.clip", "numpy.abs", "numpy.linalg.norm", "numpy.stack", "numpy.ones", "numpy.concatenate", "numpy.sin", "numpy.zeros_like", "numpy.array", "numpy.zeros", "numpy.where" ] ]
djeada/kaggle-titanic
[ "b119e8129bcd04abe96ca74e5d0b09e8b2e43ab6" ]
[ "src/random_forest.py" ]
[ "import joblib\nimport os\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import GridSearchCV\n\n\nclass RandomForest:\n def __init__(self, save_path, features_path, values_path):\n self.create_model(features_path, values_path)\n self.save_results(save_path)\n\n def create_model(self, features_path, values_path):\n\n features = pd.read_csv(features_path)\n labels = pd.read_csv(values_path)\n\n model = RandomForestClassifier()\n parameters = {\"n_estimators\": [5, 30, 100], \"max_depth\": [3, 9, 27, 42, None]}\n\n self.results = GridSearchCV(model, parameters, cv=3)\n self.results.fit(features, labels.values.ravel())\n\n def save_results(self, save_path):\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n self.path = os.path.join(save_path, self.__class__.__name__ + \".pkl\")\n joblib.dump(self.results.best_estimator_, self.path)\n\n def mean(self):\n return round(self.results.cv_results_[\"mean_test_score\"], 3)\n\n def std(self):\n return round(self.results.cv_results_[\"std_test_score\"], 3)\n\n def results(self):\n return self.results.cv_results_[\"params\"]\n\n def get_path(self):\n if self.path is not None:\n return self.path\n\n return \"\"\n" ]
[ [ "sklearn.model_selection.GridSearchCV", "pandas.read_csv", "sklearn.ensemble.RandomForestClassifier" ] ]
Gongsta/finding-waldo
[ "5fdab36f15e1018839d1fafbba632f2ecdf0bd40" ]
[ "flann.py" ]
[ "#use: pip install -U opencv-contrib-python==3.4.2.16\n\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\nwaldo = cv2.imread('glasses-cropped.jpg', 0)\nwaldo_background = cv2.imread('find/2.jpg', 0)\n\n#Will return an error if cv2 not installed properly\nsift = cv2.xfeatures2d.SIFT_create()\n\nkp1, des1 = sift.detectAndCompute(waldo, None)\nkp2, des2 = sift.detectAndCompute(waldo_background, None)\n\n#Using FLANN (Fast Library for Approximate Nearest Neighbors). contains a collection of algorithms optimized for fast nearest neighbor search in large datasets and for high dimensional features\n#FLANN PARAMETERS\nFLANN_INDEX_KDTREE = 0\nindex_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\nsearch_params = dict(checks= 50)\n\nflann = cv2.FlannBasedMatcher(index_params, search_params)\n\nmatches = flann.knnMatch(des1, des2, k=2)\n\n#Store all the good matches as per Lowe's ratio test (view documentation)\ngood = []\nfor m, n in matches:\n if m.distance < 0.7*n.distance:\n good.append(m)\n\n\n\nMIN_MATCH_COUNT = 4\n\nif len(good)>MIN_MATCH_COUNT:\n src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)\n dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)\n\n M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)\n matchesMask = mask.ravel().tolist()\n\n h,w = waldo.shape\n pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)\n dst = cv2.perspectiveTransform(pts,M)\n\n waldo_background = cv2.polylines(waldo_background,[np.int32(dst)],True,255,10, cv2.LINE_AA)\n\nelse:\n print(\"Not enough matches are found - %d/%d\" % (len(good),MIN_MATCH_COUNT))\n matchesMask = None\n\ndraw_params = dict(matchColor = (0,255,0), # draw matches in green color\n singlePointColor = None,\n matchesMask = matchesMask, # draw only inliers\n flags = 2)\n\nimg3 = cv2.drawMatches(waldo,kp1,waldo_background,kp2,good,None,**draw_params)\nplt.imshow(img3, 'gray')\nplt.show()\nplt.savefig('FLANN_results/trial6.png', dpi=1000)" ]
[ [ "matplotlib.pyplot.imshow", "numpy.int32", "matplotlib.pyplot.savefig", "numpy.float32", "matplotlib.pyplot.show" ] ]
KingStorm/nussl
[ "78edfdaad16845fc705cefb336a7e6e5923fbcd4" ]
[ "tests/test_transformer_nmf.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport unittest\nimport numpy as np\nimport nussl\n\nimport nimfa\n\n\nclass TransformerNMFUnitTests(unittest.TestCase):\n\n n_attempts = 2\n max_error_pct = 0.05\n n_bases = 2\n n_iters = 100\n\n def test_small_mixture_matrix(self):\n \"\"\"\n A simple example of NMF using euclidean and divergence in nussl with a 4 by 4 matrix\n \"\"\"\n # Make two simple matrices\n for n in range(4, 20, 4):\n a = np.arange(n ** 2).reshape((n, n))\n b = np.add(np.multiply(2., a), 3.)\n\n # Mix them together\n mixture = np.dot(b, a)\n\n # Run with euclidean distance\n dist_type = nussl.transformers.TransformerNMF.EUCLIDEAN\n self.calculate_nmf_error(mixture, self.n_bases, dist_type, self.n_iters, self.n_attempts, n)\n\n # Run with divergence\n dist_type = nussl.transformers.TransformerNMF.KL_DIVERGENCE\n self.calculate_nmf_error(mixture, self.n_bases, dist_type, self.n_iters, self.n_attempts, n)\n\n\n def test_random_matrix(self):\n for n in range(4, 10, 2):\n matrix = np.random.rand(n, n)\n\n # Run on euclidean\n distance_type = nussl.transformers.TransformerNMF.EUCLIDEAN\n self.calculate_nmf_error(matrix, self.n_bases, distance_type, self.n_iters, self.n_attempts, n)\n\n # Run on divergence\n distance_type = nussl.transformers.TransformerNMF.KL_DIVERGENCE\n self.calculate_nmf_error(matrix, self.n_bases, distance_type, self.n_iters, self.n_attempts, n)\n\n def calculate_nmf_error(self, mixture, n_bases, dist_type, iterations, attempts, seed):\n div = nussl.transformers.TransformerNMF.KL_DIVERGENCE\n nimfa_type = 'divergence' if dist_type == div else dist_type\n\n for i in range(attempts):\n # Set up nussl NMF\n nussl_nmf = nussl.TransformerNMF(mixture, n_bases, max_num_iterations=iterations,\n distance_measure=dist_type, seed=seed)\n # Run nussl NMF\n nussl_nmf.transform()\n\n # Set up nimfa NMF\n nimfa_nmf = nimfa.Nmf(mixture, max_iter=iterations, rank=n_bases, update=nimfa_type,\n W=nussl_nmf.template_dictionary,\n H=nussl_nmf.activation_matrix) # init to same matrices as nussl\n\n # Run nimfa NMF\n nmf_fit = nimfa_nmf()\n\n # Dot the results\n nimfa_est = np.dot(nmf_fit.basis(), nmf_fit.coef())\n nussl_est = np.dot(nussl_nmf.template_dictionary, nussl_nmf.activation_matrix)\n\n # calculate errors\n max_nussl_error = np.max(np.abs(nussl_est - mixture) / mixture)\n max_nimfa_error = np.max(np.abs(nimfa_est - mixture) / mixture)\n max_diff = max_nussl_error - max_nimfa_error\n\n # IF nussl's max error is bigger than nimfa's\n # AND nussl's max error bigger than the specified max error (0.05, or 5%)\n # AND the difference between the max errors is larger than 0.05\n # THEN we throw an exception\n # i.e., make sure nussl's results are close to nimfa's\n if max_nussl_error > max_nimfa_error \\\n and max_nussl_error > self.max_error_pct \\\n and max_diff > self.max_error_pct:\n raise Exception('max nussl error is larger than nimfa and self.max_error_pct')\n" ]
[ [ "numpy.dot", "numpy.abs", "numpy.multiply", "numpy.arange", "numpy.random.rand" ] ]
xianpf/xtool
[ "beb6c89eb1a19d386569ab5c428dbc991a3e014c" ]
[ "xtool/qt2image.py" ]
[ "import torch\nfrom PyQt5 import QtWidgets, QtCore\nimport sys\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom PyQt5.QtWidgets import QMainWindow, QComboBox, QLineEdit, QPushButton, QHBoxLayout, QVBoxLayout, QWidget, QLabel, QGroupBox, QSpinBox\nimport numpy as np\nimport matplotlib.patches as patches\nimport cv2\nfrom matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar\n\nclass Window(QMainWindow):\n def __init__(self):\n super().__init__()\n\n # set the title of main window\n self.setWindowTitle('Plot tool')\n\n # # set the size of window\n # self.Width = 800\n # self.height = int(0.618 * self.Width)\n # self.resize(self.Width, self.height)\n\n # create widgets\n self.figure_left = plt.figure('left')\n self.figure_right = plt.figure('right')\n self.figure_right_gt_mask = plt.figure('right_gt_mask')\n\n self.ax_left = self.figure_left.add_subplot(111)\n self.ax_right = self.figure_right.add_subplot(111)\n self.ax_right_down = self.figure_right_gt_mask.add_subplot(111)\n\n self.canvas_left = FigureCanvas(self.figure_left)\n self.canvas_right = FigureCanvas(self.figure_right)\n self.canvas_right_down = FigureCanvas(self.figure_right_gt_mask)\n\n self.toolbar_right_down = NavigationToolbar(self.canvas_right_down, self)\n # self.toolbar = NavigationToolbar(self.canvas, self)\n\n # self.typeBox = QComboBox()\n # self.typeBox.addItem('line chart')\n # self.typeBox.addItem('scatter chart')\n\n # self.titleBox = QLineEdit(\"Graph\", self)\n # self.xLabelBox = QLineEdit(\"x\", self)\n # self.yLabelBox = QLineEdit(\"y\", self)\n\n # self.xBox = QLineEdit(\"1,2,3,4,5\", self)\n # self.yBox = QLineEdit(\"23,32,53,75,23\", self)\n\n # self.btn_plot = QPushButton(\"plot\", self)\n # self.btn_plot.clicked.connect(self.plot)\n\n self.channel_spin = QSpinBox(self)\n self.batch_inx_spin = QSpinBox(self)\n self.tuple_inx_spin = QSpinBox(self)\n self.shape_label = QLabel(self)\n self.channel_spin.valueChanged.connect(self.callback_tensor_update)\n self.batch_inx_spin.valueChanged.connect(self.callback_tensor_update)\n self.tuple_inx_spin.valueChanged.connect(self.callback_tensor_update)\n self.comment_text = 'Comment:'\n self.comment_label = QLabel(self)\n \n self.initUI()\n\n def initUI(self):\n self.setGeometry(1900, 0, 1610, 1000)\n spinsetting_layout = QHBoxLayout()\n spinsetting_layout.addWidget(QLabel(\"Channel\"))\n spinsetting_layout.addWidget(self.channel_spin)\n spinsetting_layout.addWidget(QLabel(\"BatchInx\"))\n spinsetting_layout.addWidget(self.batch_inx_spin)\n spinsetting_layout.addWidget(QLabel(\"TupleInx\"))\n spinsetting_layout.addWidget(self.tuple_inx_spin)\n spinsetting_layout.addWidget(self.shape_label)\n spinsetting_layout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)\n spinsettingHBox = QWidget()\n spinsettingHBox.setLayout(spinsetting_layout)\n\n left_layout = QVBoxLayout()\n left_down_layout = QVBoxLayout()\n left_down_widget = QWidget()\n left_down_widget.setLayout(left_down_layout)\n # left_layout.addWidget(self.toolbar)\n left_layout.addWidget(self.canvas_left)\n left_layout.addWidget(spinsettingHBox)\n left_layout.addWidget(self.comment_label)\n left_layout.addWidget(left_down_widget)\n left_layout.setStretch(0,5)\n left_layout.setStretch(1,1)\n left_layout.setStretch(2,1)\n left_layout.setStretch(3,3)\n # left_widget = QWidget()\n left_widget = QGroupBox(\"Left\")\n left_widget.setLayout(left_layout)\n\n right_layout = QVBoxLayout()\n right_layout.addWidget(self.canvas_right)\n right_layout.addWidget(self.canvas_right_down)\n # right_layout.addWidget(QLabel(\"type of Chart:\"))\n # right_layout.addWidget(self.typeBox)\n # right_layout.addWidget(QLabel(\"title:\"))\n # right_layout.addWidget(self.titleBox)\n # right_layout.addWidget(QLabel(\"x label:\"))\n # right_layout.addWidget(self.xLabelBox)\n # right_layout.addWidget(QLabel(\"y label:\"))\n # right_layout.addWidget(self.yLabelBox)\n\n # right_layout.addWidget(QLabel(\"x value:\"))\n # right_layout.addWidget(self.xBox)\n # right_layout.addWidget(QLabel(\"y value:\"))\n # right_layout.addWidget(self.yBox)\n # right_layout.addStretch(5)\n # right_layout.addWidget(self.btn_plot)\n \n right_down_layout = QVBoxLayout()\n right_down_layout.addWidget(self.toolbar_right_down)\n right_down_widget = QWidget()\n right_down_widget.setLayout(right_down_layout)\n right_layout.addWidget(right_down_widget)\n right_widget = QGroupBox(\"Right\")\n right_widget.setLayout(right_layout)\n\n main_layout = QHBoxLayout()\n main_layout.addWidget(left_widget)\n main_layout.addWidget(right_widget)\n # main_layout.setStretch(0, 4)\n main_layout.setStretch(0, 1)\n main_layout.setStretch(1, 1)\n main_widget = QWidget()\n main_widget.setLayout(main_layout)\n self.setCentralWidget(main_widget)\n\n def plot(self):\n g_type = str(self.typeBox.currentText())\n\n x_data = str(self.xBox.text())\n y_data = str(self.yBox.text())\n\n x = np.array(x_data.split(\",\")).astype(np.float)\n y = np.array(y_data.split(\",\")).astype(np.float)\n\n if len(x) != len(y):\n QMessageBox.question(self, 'Message', \"The size of X and Y is different. \", QMessageBox.Ok, QMessageBox.Ok)\n else:\n # ax = self.figure.add_subplot(111)\n # ax = self.figure_right.add_subplot(111)\n self.ax_right.clear()\n self.ax_right.set(xlabel=str(self.xLabelBox.text()), ylabel=str(self.yLabelBox.text()))\n self.ax_right.set(title=str(self.titleBox.text()))\n\n if g_type == 'line chart':\n self.ax_right.plot(x, y)\n elif g_type == 'scatter chart':\n self.ax_right.scatter(x, y)\n else:\n print(\"error.\")\n\n # self.canvas.draw()\n self.canvas_right.draw()\n # def update_left(self, img):\n # self.ax_left.imshow(img)\n # self.canvas_left.draw()\n\n def update_right(self, img):\n '''from xtool.qt2image import win\n win.update_right((images.tensors.permute(0, 2, 3, 1).detach().cpu().numpy()[0]+128).astype(np.uint8))'''\n # import pdb; pdb.set_trace()\n # if len(img.shape) >= 3:\n # img = img.transpose()\n self.right_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n self.ax_right.imshow(self.right_img)\n self.canvas_right.draw()\n\n def draw_rect_on_right(self, rect=None, clean='all'):\n '''clean: - 'all': 全都清除, 啥也不留\n - 'onlynew': 清除以前的, 保留最新的\n - 'keep': 保留以前的, 并在上面继续画'''\n if clean == 'all':\n self.ax_right.clear()\n self.ax_right.imshow(self.right_img)\n else:\n if rect is not None and len(rect) == 4:\n x1, y1, x2, y2 = rect\n rectpatch = patches.Rectangle((x1,y1),x2-x1,y2-y1,\\\n linewidth=1,edgecolor='r',facecolor='none')\n if clean == 'onlynew':\n self.ax_right.clear()\n self.ax_right.imshow(self.right_img)\n self.ax_right.add_patch(rectpatch)\n elif clean == 'keep':\n self.ax_right.add_patch(rectpatch)\n else:\n print('clean只应该为 \"all\", \"onlynew\", \"keep\"三者之一')\n else:\n print('此处的rect不应该为None')\n import pdb; pdb.set_trace()\n self.canvas_right.draw()\n\n\n def update_right_down(self, img):\n '''from xtool.qt2image import win\n win.update_right((images.tensors.permute(0, 2, 3, 1).detach().cpu().numpy()[0]+128).astype(np.uint8))'''\n # import pdb; pdb.set_trace()\n # if len(img.shape) >= 3:\n # img = img.transpose()\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n self.ax_right_down.imshow(img)\n self.canvas_right_down.draw()\n\n def update_right_process(self, img, work_area):\n # import pdb; pdb.set_trace()\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = cv2.add(img, np.zeros(np.shape(img), dtype=np.float32), mask=work_area)\n self.ax_right_down.imshow(img)\n self.canvas_right_down.draw()\n\n def update_left(self, data):\n '''input should in pattern: tuple(batch, channel, height, width)'''\n self.update_left_input_data = data\n self.channel_spin.setValue(0)\n self.batch_inx_spin.setValue(0)\n self.tuple_inx_spin.setValue(0)\n if isinstance(data, tuple):\n import pdb; pdb.set_trace()\n elif isinstance(data, np.ndarray):\n self.left_nparray_shape = data.shape\n self.shape_label.setText(' nparray:'+str(self.left_nparray_shape))\n if len(self.left_nparray_shape) == 2:\n self.left_img = data\n self.channel_spin.setDisabled(True)\n self.batch_inx_spin.setDisabled(True)\n self.tuple_inx_spin.setDisabled(True)\n elif len(self.left_nparray_shape) == 3:\n self.left_img = data[0]\n self.channel_spin.setDisabled(False)\n self.channel_spin.setMaximum(self.left_nparray_shape[0]-1)\n self.batch_inx_spin.setDisabled(True)\n self.tuple_inx_spin.setDisabled(True)\n elif len(self.left_nparray_shape) == 4:\n self.left_img = data[0][0]\n self.channel_spin.setDisabled(False)\n self.channel_spin.setMaximum(self.left_nparray_shape[1]-1)\n self.batch_inx_spin.setDisabled(False)\n self.batch_inx_spin.setMaximum(self.left_nparray_shape[0]-1)\n self.tuple_inx_spin.setDisabled(True)\n else:\n print('len(self.left_nparray_shape):', len(self.left_nparray_shape))\n import pdb; pdb.set_trace()\n # elif isinstance(data, torch.Tensor):\n # self.update_left(data.detach().cpu().numpy())\n else:\n print('Type:', type(data))\n import pdb; pdb.set_trace()\n self.ax_left.imshow(self.left_img)\n self.canvas_left.draw()\n # import pdb; pdb.set_trace()\n\n def callback_tensor_update(self):\n if self.shape_label.text().startswith(' nparray:'):\n if len(self.left_nparray_shape) == 3:\n self.left_img = self.update_left_input_data[self.channel_spin.value()]\n elif len(self.left_nparray_shape) == 4:\n self.left_img = self.update_left_input_data[self.batch_inx_spin.value()][self.channel_spin.value()]\n self.ax_left.imshow(self.left_img)\n self.canvas_left.draw()\n else:\n import pdb; pdb.set_trace()\n\n def comment(self, text, mode='append'):\n self.comment_text = text if mode == 'refresh' else self.comment_text + text\n self.comment_label.setText(self.comment_text)\n\n\n# if __name__ == '__main__':\n# if QtWidgets.QApplication.instance() is None:\n# app = QtWidgets.QApplication(sys.argv)\n# win = Window()\n# win.show()\n\nif QtWidgets.QApplication.instance() is None:\n app = QtWidgets.QApplication(sys.argv)\nwin = Window()\nwin.show()" ]
[ [ "matplotlib.backends.backend_qt5.NavigationToolbar2QT", "matplotlib.patches.Rectangle", "numpy.shape", "matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg", "matplotlib.pyplot.figure" ] ]
ChrizH/data-science-learning
[ "c5770955256ef535e22346f977fb070db98a135d" ]
[ "cellular automata/blender-scripting/src/conway_4D.py" ]
[ "import bpy\r\nimport sys\r\nimport numpy as np\r\n\r\n# Because Blender is stupid?\r\nfrom __init__ import CONFIG_PATH\r\n\r\nfrom abstract_GOL import AbstractGOL\r\nimport conway_3D\r\nimport gol_utils as utils\r\n\r\n\r\nclass ConwayGOL_4D(AbstractGOL):\r\n def __init__(self, N, config='GOL_4D_standard', seed=None):\r\n \"\"\"\r\n 4D Conway Game of Life\r\n :param N: 4D grid side size (resulting grid will be a NxNxNxN matrix)\r\n :param config: configuration for this GOL instance (cell survival and generation settings)\r\n \"\"\"\r\n super().__init__(config, seed)\r\n self.N = N\r\n self.grid = np.random.choice(2, (N,N,N,N))\r\n \r\n def update(self):\r\n \"\"\"\r\n Update status of the grid\r\n \"\"\"\r\n tmpGrid = self.grid.copy()\r\n for k in range(self.N):\r\n for z in range(self.N):\r\n for y in range(self.N):\r\n for x in range(self.N):\r\n neighbours = self.get_neighbours_count((k, z, y, x))\r\n tmpGrid[k, z, y, x] = self.get_cell_newstate(self.grid[k, z, y, x], neighbours)\r\n self.grid = tmpGrid\r\n\r\n def get_neighbours_count(self, index):\r\n k, z, y, x = index\r\n neighbours_count = self.grid[max(0, k-1):min(k+2,self.N),\r\n max(0, z-1):min(z+2,self.N),\r\n max(0, y-1):min(y+2,self.N),\r\n max(0, x-1):min(x+2,self.N)].sum()\r\n neighbours_count -= self.grid[k, z, y, x]\r\n return neighbours_count\r\n\r\n\r\ndef main(_):\r\n # CONSTANTS\r\n num_frames_change = 2\r\n grid_side = 5\r\n obj_size = 0.7\r\n subdivisions = 10\r\n scale_factor=0.2\r\n\r\n #obj_generator = lambda x,y,z:icosphere_generator(obj_size, subdivisions, x, y, z)\r\n obj_generator = lambda x,y,z: utils.cube_generator(obj_size, x, y, z)\r\n obj_updater = lambda obj, grid, idx: utils.object_updater_hide(obj, grid[idx])\r\n\r\n utils.delete_all()\r\n gol = ConwayGOL_4D(grid_side)\r\n obj_grid = conway_3D.create_3Dgrid(gol, obj_generator)\r\n\r\n bpy.app.handlers.frame_change_pre.clear()\r\n bpy.app.handlers.frame_change_pre.append(lambda x : conway_3D.frame_handler(x, obj_grid, gol,\r\n obj_updater,\r\n num_frames_change))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv[1:])" ]
[ [ "numpy.random.choice" ] ]
Mestway/falx
[ "fcae5e536f44c19780ae9f00b94e397723924757", "fcae5e536f44c19780ae9f00b94e397723924757" ]
[ "design_exploration/utils.py", "falx/table/language.py" ]
[ "import csv\nimport json\nimport os\n\nimport pandas as pd\n\ndef absolute_path(p):\n return os.path.join(os.path.dirname(os.path.abspath(__file__)), p)\n\ndef flatten_object(obj):\n\t\"\"\"flatten an object into paths for easier enumeration. \n\t\tArgs: an object\n\t\tReturns:\n\t\t\ta flat object with a list of pairs \n\t\t\t[(p_1, v_1), ..., (p_k, v_k)], (paths and values)\n\t\tExample:\n\t\t\t{x: 1, y : {z: [a, b], w: c}} will be flatten into\n\t\t\t[(\"/x\", 1), (\"/y/z/0\", a), (\"/y/z/1\", b), (\"/y/w\", c)]\n\t\"\"\"\n\tpaths = []\n\n\tif isinstance(obj, (dict,)):\n\t\tfor f in obj:\n\t\t\tsub_paths = flatten_object(obj[f])\n\t\t\tfor p in sub_paths:\n\t\t\t\tpaths.append((\"/{}{}\".format(f, p[0]), p[1]))\n\telif isinstance(obj, (list,)):\n\t\tfor i, x in enumerate(obj):\n\t\t\tsub_paths = flatten_object(x)\n\t\t\tfor p in sub_paths:\n\t\t\t\tpaths.append((\"/{}{}\".format(i, p[0]), p[1]))\n\telse:\n\t\tpaths = [(\"\", obj)]\n\n\treturn paths\n\ndef reconstruct_object(flat_obj):\n\t\"\"\"reconstruct an object from flatten paths. \n\t\tArgs:\n\t\t\tflat_obj: a flat object with a list of pairs \n\t\t\t\t[(p_1, v_1), ..., (p_k, v_k)], (paths and values)\n\t\tReturns:\n\t\t\tEither a primitive value, a list, or a dict \n\t\t\t(depending on how the path is specified) \n\t\"\"\"\n\theads = list(set([x[0][1:].split('/')[0] for x in flat_obj]))\n\n\t# this is a primitive value\n\tif len(heads) == 1 and heads[0] == \"\":\n\t\treturn flat_obj[0][1]\n\n\t# check if it is a list\n\tif all([v.isdigit() for v in heads]):\n\t\theads = sorted([int(v) for v in heads])\n\t\tretval = list(range(len(heads)))\n\telse:\n\t\tretval = {}\n\n\tfor h in heads:\n\t\t# recursively construct objects from paths\n\t\tprefix = \"/{}\".format(h)\n\t\tsub_paths = [(x[0][len(prefix):], x[1]) for x in flat_obj \n\t\t\t\t\t if x[0].startswith(prefix)]\n\t\tretval[h] = reconstruct_object(sub_paths)\n\n\treturn retval\n\ndef vl2obj(vl_spec):\n\t\"\"\"transforms an vl_spec to an object,\n\t it changes encodings from dict into list\"\"\"\n\tspec = {}\n\tfor f in vl_spec:\n\t\tif f == \"encoding\":\n\t\t\tspec[f] = []\n\t\t\tfor v in vl_spec[f]:\n\t\t\t\tenc = vl_spec[f][v].copy()\n\n\t\t\t\tenc[\"channel\"] = v\n\t\t\t\tspec[f].append(enc)\n\t\telse:\n\t\t\tspec[f] = vl_spec[f]\n\treturn spec\n\ndef obj2vl(spec):\n\t\"\"\"reverse operator for vl2obj\"\"\"\n\tvl_spec = {}\n\tfor f in spec:\n\t\tif f == \"encoding\":\n\t\t\tvl_spec[f] = {}\n\t\t\tfor l in spec[f]:\n\t\t\t\tenc = l.copy()\n\t\t\t\tchannel = enc.pop(\"channel\", None)\n\t\t\t\tvl_spec[f][channel] = enc\n\t\telse:\n\t\t\tvl_spec[f] = spec[f]\n\treturn vl_spec\n\ndef load_vl_spec(vl_spec_path, inline_data=True):\n\t\"\"\"load a vl spec and inline data as 'values' \"\"\"\n\tabs_path = absolute_path(vl_spec_path)\n\twith open(vl_spec_path, \"r\") as f:\n\t\tvl_spec = json.load(f)\n\n\tif inline_data and \"url\" in vl_spec[\"data\"]:\n\t\tdata_path = vl_spec[\"data\"][\"url\"]\n\t\twith open(os.path.join(os.path.dirname(abs_path), data_path), \"r\") as g:\n\t\t\tif data_path.endswith(\".csv\"):\n\t\t\t\tcsv_reader = csv.DictReader(g)\n\t\t\t\tdata = list([row for row in csv_reader])\n\t\t\telif data_path.endswith(\".json\"):\n\t\t\t\tdata = json.load(g)\n\n\t\tvl_spec[\"data\"] = {\"values\": data}\n\n\treturn vl_spec\n\ndef extract_data_props(vl_spec):\n\t\"\"\"extract properties of data \"\"\"\n\tfield_props = []\n\tvspec = vl2obj(vl_spec)\n\tdata = vl_spec[\"data\"][\"values\"]\n\tfor enc in vspec[\"encoding\"]:\n\t\tfield_prop = {}\n\t\tif enc[\"field\"] is not None:\n\t\t\tfield_prop[\"field\"] = enc[\"field\"]\n\t\t\tfield_prop[\"enc_type\"] = enc[\"type\"]\n\t\t\tcolumn_values = [d[field_prop[\"field\"]] for d in data]\n\t\t\tdtype = pd.api.types.infer_dtype(column_values)\n\t\t\tfield_prop[\"dtype\"] = dtype\n\t\t\tif dtype in [\"integer\", \"float\", \"mixed-integer-float\"]:\n\t\t\t\tfield_prop[\"min\"] = min(column_values)\n\t\t\t\tfield_prop[\"max\"] = max(column_values)\n\t\t\tfield_prop[\"cardinality\"] = len(set(column_values))\n\t\t\tfield_props.append(field_prop)\n\treturn field_props\n\n", "import pandas as pd\nimport numpy as np\nfrom abc import ABC, abstractmethod\nimport copy\nimport itertools\n\n\n# two special symbols used in the language\nHOLE = \"_?_\"\nUNKNOWN = \"_UNK_\"\n\n# restrict how many keys can be generated from spread\nSPREAD_MAX_KEYSIZE = 10\n\nclass Node(ABC):\n\tdef __init__(self):\n\t\tsuper(AbstractExpression, self).__init__()\n\n\t@abstractmethod\n\tdef eval(self, inputs):\n\t\t\"\"\"the inputs are dataframes,\n\t\t\tit returns a pandas dataframe representation\"\"\"\n\t\tpass\n\n\t@abstractmethod\n\tdef to_dict(self):\n\t\tpass\n\n\t@abstractmethod\n\tdef infer_domain(self, arg_id, config):\n\t\tpass\n\n\t@abstractmethod\n\tdef infer_output_info(self, inputs):\n\t\tpass\n\n\t@staticmethod\n\tdef load_from_dict(ast):\n\t\t\"\"\"given a dictionary represented AST, load it in to a program form\"\"\"\n\t\tconstructors = {\n\t\t\t\"select\": Select, \"unite\": Unite,\n\t\t\t\"filter\": Filter, \"separate\": Separate,\n\t\t\t\"spread\": Spread, \"gather\": Gather,\n\t\t\t\"group_sum\": GroupSummary,\n\t\t\t\"cumsum\": CumSum,\n\t\t\t\"mutate\": Mutate,\n\t\t\t\"mutate_custom\": MutateCustom,\n\t\t}\n\t\tif ast[\"op\"] == \"table_ref\":\n\t\t\treturn Table(ast[\"children\"][0][\"value\"])\n\t\telse:\n\t\t\tnode = constructors[ast[\"op\"]](\n\t\t\t\t\t\tNode.load_from_dict(ast[\"children\"][0]), \n\t\t\t\t\t\t*[arg[\"value\"] for arg in ast[\"children\"][1:]])\n\t\t\treturn node\n\n\tdef to_stmt_dict(self):\n\t\t\"\"\"translate the expression into a \"\"\"\n\t\tdef _recursive_translate(ast, used_vars):\n\t\t\tif ast[\"op\"] == \"table_ref\":\n\t\t\t\t# create a variable to capture the return variable\n\t\t\t\tstmt_dict = copy.copy(ast)\n\t\t\t\tvar = get_temp_var(used_vars)\n\t\t\t\tstmt_dict[\"return_as\"] = var\n\t\t\t\treturn [stmt_dict], used_vars + [var]\n\t\t\telse:\n\t\t\t\tstmt_dict = copy.copy(ast)\n\n\t\t\t\t# iterate over all possible subtrees\n\t\t\t\tsub_tree_stmts = []\t\n\t\t\t\tfor i, arg in enumerate(ast[\"children\"]):\n\t\t\t\t\t# check if the argument is an ast \n\t\t\t\t\tif isinstance(arg, (dict,)) and arg[\"type\"] == \"node\":\n\t\t\t\t\t\tstmts, used_vars = _recursive_translate(ast[\"children\"][0], used_vars)\n\t\t\t\t\t\tsub_tree_stmts += stmts\n\t\t\t\t\t\t# the subtree is replaced by a reference to the variable\n\t\t\t\t\t\tretvar = stmts[-1][\"return_as\"]\n\t\t\t\t\t\tstmt_dict[\"children\"][i] = {\"value\": retvar, \"type\": \"variable\"}\n\t\t\t\t\n\t\t\t\t# use a temp variable to wrap the current statement, and add it to the coolection\n\t\t\t\tvar = get_temp_var(used_vars)\n\t\t\t\tstmt_dict[\"return_as\"] = var\n\t\t\t\treturn sub_tree_stmts + [stmt_dict], used_vars + [var]\n\n\t\tstmts, _ = _recursive_translate(self.to_dict(), [])\n\t\treturn stmts\n\n\tdef is_abstract(self):\n\t\t\"\"\"Check if the subtree is abstract (contains any holes)\"\"\"\n\t\tdef contains_hole(node):\n\t\t\tfor i, arg in enumerate(node[\"children\"]):\n\t\t\t\tif arg[\"type\"] == \"node\":\n\t\t\t\t\tif contains_hole(arg):\n\t\t\t\t\t\treturn True\n\t\t\t\telif arg[\"value\"] == HOLE:\n\t\t\t\t\t# we find a variable to infer\n\t\t\t\t\treturn True\n\t\t\treturn False\n\t\treturn contains_hole(self.to_dict())\n\t\n\tdef stmt_string(self):\n\t\t\"\"\"generate a string from stmts, for the purpose of pretty printing\"\"\"\n\t\tstmts = self.to_stmt_dict()\n\t\tresult = []\n\t\tfor s in stmts:\n\t\t\tlhs = s['return_as']\n\t\t\tf = s['op']\n\t\t\targ_str = ', '.join([str(x['value']) for x in s[\"children\"]])\n\t\t\tresult.append(f\"{lhs} <- {f}({arg_str})\")\n\n\t\treturn \"; \".join(result)\n\n\nclass Table(Node):\n\tdef __init__(self, data_id):\n\t\tself.data_id = data_id\n\n\tdef infer_domain(self, arg_id, inputs, config):\n\t\tassert False, \"Table has no args to infer domain.\"\n\n\tdef infer_output_info(self, inputs):\n\t\t\"\"\"infer output schema \"\"\"\n\t\tinp = inputs[self.data_id]\n\t\tif isinstance(inp, (list,)):\n\t\t\tcolumns = [key for key in inp[0]]\n\t\t\tdf = pd.DataFrame.from_dict(inp)[list(inp[0].keys())]\n\t\telse:\n\t\t\tdf = inp\n\t\tschema = extract_table_schema(df)\n\t\treturn schema\n\n\tdef eval(self, inputs):\n\t\tinp = inputs[self.data_id]\n\t\tif isinstance(inp, (list,)):\n\t\t\tdf = pd.DataFrame.from_dict(inp)[list(inp[0].keys())]\n\t\telse:\n\t\t\tdf = inp\n\t\treturn df\n\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t\"type\": \"node\",\n\t\t\t\"op\": \"table_ref\",\n\t\t\t\"children\": [\n\t\t\t\tvalue_to_dict(self.data_id, \"table_id\")\n\t\t\t]\n\t\t}\n\n\nclass Select(Node):\n\tdef __init__(self, q, cols):\n\t\tself.q = q\n\t\tself.cols = cols\n\n\tdef infer_domain(self, arg_id, inputs, config):\n\t\tif arg_id == 1:\n\t\t\tinput_schema = self.q.infer_output_info(inputs)\n\t\t\tcol_num = len(input_schema)\n\t\t\tcol_list_candidates = []\n\t\t\tfor size in range(1, col_num + 1):\n\t\t\t\tcol_list_candidates += list(itertools.combinations(list(range(col_num)), size))\n\t\t\treturn col_list_candidates\n\t\telse:\n\t\t\tassert False, \"[Select] No args to infer domain for id > 1.\"\n\n\tdef infer_output_info(self, inputs):\n\t\tschema = self.q.infer_output_info(inputs)\n\t\treturn [s for i, s in enumerate(schema) if i in self.cols]\n\n\tdef eval(self, inputs):\n\t\tdf = self.q.eval(inputs)\n\t\treturn df[[df.columns[i] for i in self.cols]]\n\n\tdef backward_eval(self, output):\n\t\t# the input table should contain every value appear in the output table\n\t\treturn [output]\n\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t\"type\": \"node\",\n\t\t\t\"op\": \"select\",\n\t\t\t\"children\": [self.q.to_dict(), value_to_dict(self.cols, \"col_index_list\")]\n\t\t}\n\n\nclass Unite(Node):\n\tdef __init__(self, q, col1, col2, sep=\"_\"):\n\t\t\"\"\" col1, col2 are column indexes\"\"\"\n\t\tself.q = q\n\t\tself.col1 = col1\n\t\tself.col2 = col2\n\t\tself.sep = sep\n\n\tdef infer_domain(self, arg_id, inputs, config):\n\t\tinput_schema = self.q.infer_output_info(inputs)\n\t\tstr_cols = [i for i, s in enumerate(input_schema)]\n\t\tif arg_id == 1:\n\t\t\treturn str_cols\n\t\tif arg_id == 2:\n\t\t\t# refine the domain according to the first argumnet\n\t\t\t# cannot just do i > self.col1, since it is not commutative\n\t\t\treturn str_cols if self.col1 == HOLE else [i for i in str_cols if i != self.col1]\n\t\telse:\n\t\t\tassert False, \"[Unite] No args to infer domain for id > 2.\"\n\n\tdef infer_output_info(self, inputs):\n\t\tinput_schema = self.q.infer_output_info(inputs)\n\t\treturn [s for i,s in enumerate(input_schema) if i not in [self.col1, self.col2]] + [\"string\"]\n\n\tdef eval(self, inputs):\n\t\tdf = self.q.eval(inputs)\n\t\tret = df.copy()\n\t\tnew_col = get_fresh_col(list(ret.columns))[0]\n\t\tc1, c2 = ret.columns[self.col1], ret.columns[self.col2]\n\t\tret[new_col] = ret[c1].astype(str) + self.sep + ret[c2].astype(str)\n\t\tret = ret.drop(columns=[c1, c2])\n\t\treturn ret\n\n\tdef backward_eval(self, output):\n\t\t# if could be the case that all column in the output \n\t\tpossible_premise = [output]\n\t\tcols = list(output[0].keys())\n\t\treturn output\n\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t\"type\": \"node\",\n\t\t\t\"op\": \"unite\",\n\t\t\t\"children\": [\n\t\t\t\tself.q.to_dict(), \n\t\t\t\tvalue_to_dict(self.col1, \"col_index\"), \n\t\t\t\tvalue_to_dict(self.col2, \"col_index\")]}\n\n\nclass Filter(Node):\n\tdef __init__(self, q, col_index, op, const):\n\t\tself.q = q\n\t\tself.col_index = col_index\n\t\tself.op = op\n\t\tself.const = const\n\n\tdef infer_domain(self, arg_id, inputs, config):\n\t\tif arg_id == 1:\n\t\t\tcol_num = len(self.q.infer_output_info(inputs))\n\t\t\treturn list(range(col_num))\n\t\telif arg_id == 2:\n\t\t\treturn config[\"filer_op\"]\n\t\telif arg_id == 3:\n\t\t\treturn config[\"constants\"]\n\t\telse:\n\t\t\tassert False, \"[Filter] No args to infer domain for id > 3.\"\n\n\tdef infer_output_info(self, inputs):\n\t\treturn self.q.infer_output_info(inputs)\n\n\tdef eval(self, inputs):\n\t\tdf = self.q.eval(inputs)\n\t\tcol = df.columns[self.col_index]\n\t\tif self.op == \"==\":\n\t\t\treturn df[df[col] == self.const].reset_index()\n\t\telif self.op == \"!=\":\n\t\t\treturn df[df[col] != self.const].reset_index()\n\t\telse:\n\t\t\tsys.exit(-1)\n\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t\"type\": \"node\",\n\t\t\t\"op\": \"filter\",\n\t\t\t\"children\": [\n\t\t\t\tself.q.to_dict(), \n\t\t\t\tvalue_to_dict(self.col_index, \"col_index\"), \n\t\t\t\tvalue_to_dict(self.op, \"binop\"), \n\t\t\t\tvalue_to_dict(self.const, \"constant\")\n\t\t\t]}\n\n\nclass Separate(Node):\n\tdef __init__(self, q, col_index):\n\t\tself.q = q\n\t\tself.col_index = col_index\n\n\tdef infer_domain(self, arg_id, inputs, config):\n\t\tif arg_id == 1:\n\t\t\ttry:\n\t\t\t\tdf = self.q.eval(inputs)\n\t\t\texcept Exception as e:\n\t\t\t\tprint(f\"[eval error in infer_domain] {e}\")\n\t\t\t\treturn []\n\t\t\tinput_schema = self.q.infer_output_info(inputs)\n\t\t\tdomain = []\n\t\t\t#TODO: need to improve precisions of type inferene\n\t\t\t# print(df)\n\t\t\t# print(input_schema)\n\t\t\tfor i, s in enumerate(input_schema):\n\t\t\t\tif s != \"string\": \n\t\t\t\t\tcontinue\n\t\t\t\tl = list(df[df.columns[i]])\n\t\t\t\tseparators = [\" \", \"-\", \"_\", \"/\"]\n\t\t\t\tcontain_sep = False\n\t\t\t\tfor sep in separators:\n\t\t\t\t\tif all([sep in str(x) for x in l]):\n\t\t\t\t\t\tcontain_sep = True\n\t\t\t\t\t\tbreak\n\t\t\t\tif contain_sep:\n\t\t\t\t\tdomain.append(i)\n\t\t\treturn domain\n\t\telse:\n\t\t\tassert False, \"[Separate] No args to infer domain for id > 1.\"\n\n\tdef infer_output_info(self, inputs):\n\t\tinput_schema = self.q.infer_output_info(inputs)\n\t\treturn [s for i, s in enumerate(input_schema) if i != self.col_index] + [\"string\", \"string\"]\n\n\tdef eval(self, inputs):\n\t\tdf = self.q.eval(inputs)\n\n\t\tret = df.copy()\n\t\tcol = ret.columns[self.col_index]\n\n\t\t# enable splitting by \"_\", \"-\", and whitespace (but only split once)\n\t\tsplitted = ret[col].str.split(r\"\\s|_|-|/\", n=1, expand=True)\n\t\tnew_col_names = get_fresh_col(list(ret.columns), n=2)\n\t\tret[new_col_names[0]] = splitted[0]\n\t\tret[new_col_names[1]] = splitted[1]\n\t\tret = ret.drop(columns=[col])\n\t\treturn ret\n\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t\"type\": \"node\",\n\t\t\t\"op\": \"separate\",\n\t\t\t\"children\": [self.q.to_dict(), value_to_dict(self.col_index, \"col_index\")]\n\t\t}\n\t\t\n\nclass Spread(Node):\n\tdef __init__(self, q, key, val):\n\t\tself.q = q\n\t\tself.key = key\n\t\tself.val = val\n\n\tdef infer_domain(self, arg_id, inputs, config):\n\t\tschema = self.q.infer_output_info(inputs)\n\t\tif arg_id == 1:\n\t\t\tif self.q.is_abstract():\n\t\t\t\treturn list(range(len(schema)))\n\t\t\telse:\n\t\t\t\t# approximation: only get fields with more than one values\n\t\t\t\t# for the purpose of avoiding empty fields\n\t\t\t\ttry:\n\t\t\t\t\tdf = self.q.eval(inputs)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint(f\"[eval error in infer_domain] {e}\")\n\t\t\t\t\treturn []\n\t\t\t\tcols = []\n\t\t\t\tfor i, c in enumerate(df.columns):\t\t\t\t\t\n\t\t\t\t\tl = list(df[c])\n\t\t\t\t\tvals_cnt = [l.count(x) for x in set(l)]\n\t\t\t\t\t# (1) all values should have the same cardinality\n\t\t\t\t\t# (2) their cardinality should all be greater than 1\n\t\t\t\t\t# (3) there should be at least two distrint value\n\t\t\t\t\tif len(set(vals_cnt)) == 1 and vals_cnt[0] > 1 and vals_cnt[0] != len(l):\n\t\t\t\t\t\tcols.append(i)\n\t\t\t\treturn cols\n\t\tif arg_id == 2:\n\t\t\tif self.key != HOLE:\n\t\t\t\ttry:\n\t\t\t\t\tdf = self.q.eval(inputs)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint(f\"[eval error in infer_domain] {e}\")\n\t\t\t\t\treturn []\n\n\t\t\t\tval_col_domain = []\n\t\t\t\tfor i, vcol in enumerate(df.columns):\n\t\t\t\t\tif i == self.key:\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t# values in the key column\n\t\t\t\t\tkey_values = list(df[df.columns[self.key]])\n\t\t\t\t\tkey_cnt = [key_values.count(x) for x in set(key_values)]\n\t\t\t\t\t\n\t\t\t\t\t# values in the id column (columns outside of key or val)\n\t\t\t\t\tid_cols = [c for k, c in enumerate(df.columns) if k != i and k != self.key]\n\n\t\t\t\t\tif len(id_cols) == 0:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t\tid_value_tuples = [tuple(x) for x in df[id_cols].to_records(index=False)]\n\n\t\t\t\t\t# restrict how many keys can be maximally generated from spread\n\t\t\t\t\tif SPREAD_MAX_KEYSIZE != None and len(set(key_values)) > SPREAD_MAX_KEYSIZE:\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t# print(\"...>>>>>>>>\")\n\t\t\t\t\t# print(id_cols)\n\t\t\t\t\t# print(key_values)\n\t\t\t\t\t# print(set(key_values))\n\t\t\t\t\t# print(key_cnt)\n\t\t\t\t\t# print(set(id_value_tuples))\n\t\t\t\t\t# print(\"{} {} {}\".format(len(set(id_value_tuples)), key_cnt[0], len(set(key_values))))\n\n\t\t\t\t\t# only add the value column into the domain \n\t\t\t\t\t# if #cardinality of key column * #distinct values in id column matches the # of rows tables\n\t\t\t\t\tif len(set(id_value_tuples)) * len(set(key_values)) == len(key_values):\n\t\t\t\t\t\t# if it contains duplicate entries, remove them\n\t\t\t\t\t\tid_key_content = df[id_cols + [df.columns[self.key]]]\n\t\t\t\t\t\tif not id_key_content.duplicated().any():\n\t\t\t\t\t\t\tval_col_domain.append(i)\n\n\t\t\t\treturn val_col_domain #[i for i in range(len(schema)) if i != self.key]\n\t\t\telse:\n\t\t\t\treturn list(range(len(schema)))\n\t\telse:\n\t\t\tassert False, \"[Spread] No args to infer domain for id > 2.\"\n\n\tdef infer_output_info(self, inputs):\n\t\tif self.is_abstract():\n\t\t\treturn None\n\t\telse:\n\t\t\ttry:\n\t\t\t\tschema = extract_table_schema(self.eval(inputs))\n\t\t\t\treturn schema\n\t\t\texcept Exception as e:\n\t\t\t\t#TODO: use this to indicate the domain would be empty\n\t\t\t\tprint(f\"[eval error in infer_domain] {e}\")\n\t\t\t\treturn []\n\n\tdef eval(self, inputs):\n\t\tdef multiindex_pivot(df, columns=None, values=None):\n\t\t\t# a helper function for performing multi-index pivoting\n\t\t #https://github.com/pandas-dev/pandas/issues/23955\n\t\t names = list(df.index.names)\n\t\t df = df.reset_index()\n\t\t list_index = df[names].values\n\t\t tuples_index = [tuple(i) for i in list_index] # hashable\n\t\t df = df.assign(tuples_index=tuples_index)\n\t\t df = df.pivot(index=\"tuples_index\", columns=columns, values=values)\n\t\t tuples_index = df.index # reduced\n\t\t index = pd.MultiIndex.from_tuples(tuples_index, names=names)\n\t\t df.index = index\n\t\t return df\n\t\tdf = self.q.eval(inputs)\n\t\tkey_col, val_col = df.columns[self.key], df.columns[self.val]\n\t\tindex_cols = [c for c in list(df.columns) if c not in [key_col, val_col]]\n\t\tret = df.set_index(index_cols)\n\n\n\t\t# handle some special case\n\t\ttry:\n\t\t\tret = multiindex_pivot(ret, columns=key_col, values=val_col).reset_index()\n\t\texcept:\n\t\t\tret = multiindex_pivot(ret, columns=key_col, values=val_col).reset_index(drop=True)\n\n\t\treturn ret\n\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t\"type\": \"node\",\n\t\t\t\"op\": \"spread\",\n\t\t\t\"children\": [\n\t\t\t\tself.q.to_dict(), \n\t\t\t\tvalue_to_dict(self.key, \"col_index\"), \n\t\t\t\tvalue_to_dict(self.val, \"col_index\")\n\t\t\t]}\n\n\nclass Gather(Node):\n\tdef __init__(self, q, value_columns):\n\t\tself.q = q\n\t\tself.value_columns = value_columns\n\n\tdef infer_domain(self, arg_id, inputs, config):\n\n\t\tif arg_id == 1:\n\t\t\tinput_schema = self.q.infer_output_info(inputs)\n\t\t\tcol_num = len(input_schema)\n\t\t\tcol_list_candidates = []\n\n\t\t\t# at least leave one column as the key column\n\t\t\t# also, choose the maximum list size based on config if the list is too long\n\t\t\t# \t(this prevents exponential enumeration when the table is too wide)\n\t\t\tmax_val_list_size = min(col_num - 1, config[\"gather_max_val_list_size\"])\n\n\t\t\tfw_col_lists = []\n\t\t\tfor size in range(2, max_val_list_size + 1):\n\t\t\t\tfor l in list(itertools.combinations(list(range(col_num)), size)):\n\t\t\t\t\t# only consider these fields together if they have the same type\n\t\t\t\t\tif len(set([input_schema[i] for i in l])) == 1:\n\t\t\t\t\t\tfw_col_lists.append(l)\n\n\t\t\t## this is the gahter neg case: enumerate keys (instead of columns)\n\t\t\t# leave at least two columns as values columns that will be unpivoted\n\t\t\t# also don't exceed col_num - config[\"gather_max_val_list_size\"] \n\t\t\t# (since such query is already covered in gather(..))\n\t\t\t# also don't exceed config[\"gather_max_key_list_size\"] to prevent explosion\n\t\t\tmax_key_list_size = min(col_num - 2, \n\t\t\t\t\t\t\t\t\tcol_num - config[\"gather_max_val_list_size\"] - 1, \n\t\t\t\t\t\t\t\t\tconfig[\"gather_max_key_list_size\"])\n\t\t\t\n\t\t\t# only consider such gather_neg stype if the table size is greater than config[\"gather_max_key_list_size\"]\n\t\t\tbw_col_lists = []\n\t\t\tif max_key_list_size > 0:\t\t\t\n\t\t\t\tfor size in range(1, max_key_list_size + 1):\n\t\t\t\t\tfor l in list(itertools.combinations(list(range(col_num)), size)):\n\t\t\t\t\t\t# only consider these fields together if they have the same type\n\t\t\t\t\t\tif len(set([input_schema[i] for i in range(len(input_schema)) if i not in l])) == 1:\n\t\t\t\t\t\t\tbw_col_lists.append(tuple([x for x in range(col_num) if x not in l]))\n\n\t\t\t# col_list_candidates = [(1,2,3,4,5)]\n\t\t\t# print(col_list_candidates)\n\t\t\tcol_list_candidates = []\n\t\t\tfor i in range(max(len(fw_col_lists), len(bw_col_lists))):\n\t\t\t\tif i < len(bw_col_lists):\n\t\t\t\t\tcol_list_candidates.append(bw_col_lists[i])\n\t\t\t\tif i < len(fw_col_lists):\n\t\t\t\t\tcol_list_candidates.append(fw_col_lists[i])\n\n\t\t\tif not config[\"consider_non_consecutive_gather_keys\"]:\n\t\t\t\t# only consider consecutive columns in this setup, \n\t\t\t\t# this is a hueristic to help narrow down the search space\n\t\t\t\tfiltered = []\n\t\t\t\tfor lst in col_list_candidates:\n\t\t\t\t\tis_consecutive = True\n\t\t\t\t\tfor i, v in enumerate(lst):\n\t\t\t\t\t\tif lst[i] - lst[0] != i - 0:\n\t\t\t\t\t\t\tis_consecutive = False\n\t\t\t\t\tif is_consecutive == True:\n\t\t\t\t\t\tfiltered.append(lst)\n\t\t\t\tcol_list_candidates = filtered\n\n\t\t\treturn col_list_candidates\n\t\telse:\n\t\t\tassert False, \"[Gather] No args to infer domain for id > 1.\"\n\n\tdef infer_output_info(self, inputs):\n\t\tinput_schema = self.q.infer_output_info(inputs)\n\n\t\tgather_schema = list(set([input_schema[i] for i in self.value_columns]))\n\n\t\tval_field_type = \"string\"\n\t\tif len(gather_schema) == 1 and gather_schema[0] == \"number\":\n\t\t\tval_field_type = \"number\"\n\n\t\treturn [s for i, s in enumerate(input_schema) if i not in self.value_columns] + [\"string\"] + [val_field_type]\n\n\tdef eval(self, inputs):\n\t\tdf = self.q.eval(inputs)\n\t\tvalue_vars = [df.columns[idx] for idx in self.value_columns]\n\t\tkey_vars = [c for c in df.columns if c not in value_vars]\n\t\treturn pd.melt(df, id_vars=key_vars, value_vars=value_vars, \n\t\t\t\t\t\tvar_name=\"KEY\", value_name=\"VALUE\")\n\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t\"type\": \"node\",\n\t\t\t\"op\": \"gather\",\n\t\t\t\"children\": [self.q.to_dict(), value_to_dict(self.value_columns, \"col_index_list\")]\n\t\t}\n\nclass GroupSummary(Node):\n\tdef __init__(self, q, group_cols, aggr_col, aggr_func):\n\t\tself.q = q\n\t\tself.group_cols = group_cols\n\t\tself.aggr_col = aggr_col\n\t\tself.aggr_func = aggr_func\n\n\tdef infer_domain(self, arg_id, inputs, config):\n\t\tschema = self.q.infer_output_info(inputs)\n\t\tif arg_id == 1:\n\t\t\t# approximation: only get fields with more than one values\n\t\t\t# for the purpose of avoiding empty fields\n\t\t\ttry:\n\t\t\t\tdf = self.q.eval(inputs)\n\t\t\texcept Exception as e:\n\t\t\t\tprint(f\"[eval error in infer_domain] {e}\")\n\t\t\t\treturn []\n\n\t\t\t# use this list to store primitive table keys, \n\t\t\t# use them to elimiate column combinations that contain no duplicates\n\t\t\ttable_keys = []\n\n\t\t\tcol_num = len(schema)\n\t\t\tcol_list_candidates = []\n\t\t\tfor size in range(1, col_num + 1 - 1):\n\t\t\t\tfor gb_keys in itertools.combinations(list(range(col_num)), size):\n\t\t\t\t\tif any([set(banned).issubset(set(gb_keys)) for banned in table_keys]):\n\t\t\t\t\t\t# current key group is subsumbed by a table key, so all fields will be distinct\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tgb_cols = df[[df.columns[k] for k in gb_keys]]\n\t\t\t\t\tif not gb_cols.duplicated().any():\n\t\t\t\t\t\t# a key group is valid for aggregation \n\t\t\t\t\t\t# if there exists at least a key appear more than once\n\t\t\t\t\t\ttable_keys.append(gb_keys)\n\t\t\t\t\t\tcontinue\n\t\t\n\t\t\t\t\tcol_list_candidates += [gb_keys]\n\t\t\treturn col_list_candidates\n\t\telif arg_id == 2:\n\t\t\tnumber_fields = [i for i,s in enumerate(schema) if s == \"number\"]\n\t\t\tif self.group_cols != HOLE:\n\t\t\t\tcols = [i for i in number_fields if i not in self.group_cols]\n\t\t\telse:\n\t\t\t\tcols = number_fields\n\t\t\t# the special column -1 is used for the purpose of \"count\", no other real intent\n\t\t\tcols += [-1]\n\t\t\treturn cols\n\t\telif arg_id == 3:\n\t\t\tif self.aggr_col != HOLE:\n\t\t\t\tif self.aggr_col == -1:\n\t\t\t\t\treturn [\"count\"] if \"count\" in config[\"aggr_func\"] else []\n\t\t\t\telse:\n\t\t\t\t\treturn [f for f in config[\"aggr_func\"] if f != \"count\"]\n\t\t\telse:\n\t\t\t\treturn config[\"aggr_func\"]\n\t\telse:\n\t\t\tassert False, \"[Gather] No args to infer domain for id > 1.\"\n\n\tdef infer_output_info(self, inputs):\n\t\tinput_schema = self.q.infer_output_info(inputs)\n\t\taggr_type = input_schema[self.aggr_col] if self.aggr_func != \"count\" else \"number\"\n\t\treturn [s for i, s in enumerate(input_schema) if i in self.group_cols] + [aggr_type]\n\n\tdef eval(self, inputs):\n\t\tdf = self.q.eval(inputs)\n\t\tgroup_keys = [df.columns[idx] for idx in self.group_cols]\n\t\ttarget = df.columns[self.aggr_col]\n\n\t\tif self.aggr_func == \"cumsum\":\n\t\t\tres = df\n\t\t\tres[target] = df.groupby(group_keys)[target].transform(pd.Series.cumsum)\n\t\telse:\n\t\t\tres = df.groupby(group_keys).agg({target: self.aggr_func})\n\n\t\tif self.aggr_func == \"mean\":\n\t\t\tres[target] = res[target].round(2)\n\t\tres = res.rename(columns={target: f'{self.aggr_func}_{target}'}).reset_index()\n\t\treturn res\n\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t\"type\": \"node\",\n\t\t\t\"op\": \"group_sum\",\n\t\t\t\"children\": [\n\t\t\t\tself.q.to_dict(), \n\t\t\t\tvalue_to_dict(self.group_cols, \"col_index_list\"),\n\t\t\t\tvalue_to_dict(self.aggr_col, \"col_index\"), \n\t\t\t\tvalue_to_dict(self.aggr_func, \"aggr_func\")\n\t\t\t]}\n\n\nclass CumSum(Node):\n\tdef __init__(self, q, target):\n\t\tself.q = q\n\t\tself.target = target\n\n\tdef infer_domain(self, arg_id, inputs, config):\n\t\tif arg_id == 1:\n\t\t\tinput_schema = self.q.infer_output_info(inputs)\n\t\t\treturn [i for i, s in enumerate(input_schema) if s == \"number\"]\n\t\telse:\n\t\t\tassert False, \"[CumSum] No args to infer domain for id > 1.\"\n\n\tdef infer_output_info(self, inputs):\n\t\tinput_schema = self.q.infer_output_info(inputs)\n\n\t\treturn input_schema + [\"number\"]\n\n\tdef eval(self, inputs):\n\t\tdf = self.q.eval(inputs)\n\t\tret = df.copy()\n\t\t#new_col = get_fresh_col(list(ret.columns))[0]\n\t\tret[\"cumsum\"] = ret[ret.columns[self.target]].cumsum()\n\t\treturn ret\n\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t\"type\": \"node\",\n\t\t\t\"op\": \"cumsum\",\n\t\t\t\"children\": [self.q.to_dict(), value_to_dict(self.target, \"col_index\")]\n\t\t}\n\n\nclass Mutate(Node):\n\tdef __init__(self, q, col1, op, col2):\n\t\tself.q = q\n\t\tself.col1 = col1\n\t\tself.op = op\n\t\tself.col2 = col2\n\n\tdef infer_domain(self, arg_id, inputs, config):\n\t\tif arg_id in [1, 3]:\n\t\t\tinput_schema = self.q.infer_output_info(inputs)\n\t\t\tnumber_fields = [i for i, s in enumerate(input_schema) if s == \"number\"]\n\t\t\tif arg_id == 1:\n\t\t\t\treturn number_fields\n\t\t\telif arg_id == 3:\n\t\t\t\tif self.col1 != HOLE and self.op != HOLE:\n\t\t\t\t\tif self.op == \"-\":\n\t\t\t\t\t\treturn [i for i in number_fields if i != self.col1]\n\t\t\t\t\telif self.op == \"+\":\n\t\t\t\t\t\treturn [i for i in number_fields if i >= self.col1]\n\t\t\t\telse:\n\t\t\t\t\treturn number_fields\n\t\telif arg_id == 2:\n\t\t\treturn config[\"mutate_op\"]\n\t\telse:\n\t\t\tassert False, \"[Mutate] No args to infer domain for id > 3.\"\n\n\tdef infer_output_info(self, inputs):\n\t\tinput_schema = self.q.infer_output_info(inputs)\n\t\treturn input_schema + [\"number\"]\n\n\tdef eval(self, inputs):\n\t\tassert (self.op in [\"-\", \"+\"])\n\t\tdf = self.q.eval(inputs)\n\t\tret = df.copy()\n\t\tnew_col = get_fresh_col(list(ret.columns))[0]\n\t\tc1, c2 = ret.columns[self.col1], ret.columns[self.col2]\n\t\tif self.op == \"+\":\n\t\t\tret[new_col] = (ret[c1] + ret[c2])\n\t\telif self.op == \"-\":\n\t\t\tret[new_col] = (ret[c1] - ret[c2])\n\t\telse:\n\t\t\tprint(\"[ERROR] encounter wrong operator {} in Mutate\".format(self.op))\n\t\t\tsys.exit(-1)\n\t\t#ret = ret.drop(columns=[c1, c2])\n\t\treturn ret\n\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t\"type\": \"node\",\n\t\t\t\"op\": \"mutate\",\n\t\t\t\"children\": [\n\t\t\t\tself.q.to_dict(), \n\t\t\t\tvalue_to_dict(self.col1, \"col_index\"), \n\t\t\t\tvalue_to_dict(self.op, \"binop\"), \n\t\t\t\tvalue_to_dict(self.col2, \"col_index\")\n\t\t\t]}\n\n\nclass MutateCustom(Node):\n\tdef __init__(self, q, col, op, const):\n\t\tself.q = q\n\t\tself.col = col\n\t\tself.op = op\n\t\tself.const = const\n\n\tdef infer_domain(self, arg_id, inputs, config):\n\t\tif arg_id == 1:\n\t\t\tinput_schema = self.q.infer_output_info(inputs)\n\t\t\treturn [i for i, s in enumerate(input_schema) if s == \"string\"]\n\t\telif arg_id == 2:\n\t\t\treturn [\"==\"] #config[\"mutate_op\"]\n\t\telif arg_id == 3:\n\t\t\treturn config[\"constants\"]\n\t\telse:\n\t\t\tassert False, \"[MutateCustom] No args to infer domain for id > 3.\"\n\n\tdef infer_output_info(self, inputs):\n\t\tinput_schema = self.q.infer_output_info(inputs)\n\t\treturn input_schema + [\"number\"]\n\n\tdef eval(self, inputs):\n\t\tassert(self.op == \"==\")\n\t\tdf = self.q.eval(inputs)\n\t\tret = df.copy()\n\t\tnew_col = get_fresh_col(list(ret.columns))[0]\n\t\tc = ret.columns[self.col]\n\t\tif self.op != \"==\":\n\t\t\tprint(\"[ERROR] encounter wrong operator {} in Mutate\".format(self.op))\n\t\t\tsys.exit(-1)\n\t\tret[new_col] = ret[c] == self.const\n\t\t#ret = ret.drop(columns=[c1, c2])\n\t\treturn ret\n\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t\"type\": \"node\",\n\t\t\t\"op\": \"mutate_custom\",\n\t\t\t\"children\": [\n\t\t\t\tself.q.to_dict(), \n\t\t\t\tvalue_to_dict(self.col, \"col_index\"), \n\t\t\t\tvalue_to_dict(self.op, \"binop\"), \n\t\t\t\tvalue_to_dict(self.const, \"constant\")\n\t\t\t]}\n\n#utility functions\n\ndef get_fresh_col(used_columns, n=1):\n\t\"\"\"get a fresh column name used in pandas evaluation\"\"\"\n\tnames = []\n\tfor i in range(0, 1000):\n\t\tif \"COL_{}\".format(i) not in used_columns:\n\t\t\tnames.append(\"COL_{}\".format(i))\n\t\tif len(names) >= n:\n\t\t\tbreak\n\treturn names\n\ndef get_temp_var(used_vars):\n\t\"\"\"get a temp variable name \"\"\"\n\tfor i in range(0, 1000):\n\t\tvar_name = \"t{}\".format(i)\n\t\tif var_name not in used_vars:\n\t\t\treturn var_name\n\ndef value_to_dict(val, val_type):\n\t\"\"\"given the value and its type, dump it to a dict \n\t\tthe helper function to dump values into dict ast\n\t\"\"\"\n\treturn {\"type\": val_type, \"value\": val}\n\ndef extract_table_schema(df):\n\t\"\"\"Given a dataframe, extract it's schema \"\"\"\n\tdef dtype_mapping(dtype):\n\t\t\"\"\"map pandas datatype to c \"\"\"\n\t\tdtype = str(dtype)\n\t\tif dtype == \"object\" or dtype == \"string\":\n\t\t\treturn \"string\"\n\t\telif \"int\" in dtype or \"float\" in dtype:\n\t\t\treturn \"number\"\n\t\telif \"bool\" in dtype:\n\t\t\treturn \"bool\"\n\t\telse:\n\t\t\tprint(f\"[unknown type] {dtype}\")\n\t\t\tsys.exit(-1)\n\n\tschema = [dtype_mapping(s) for s in df.infer_objects().dtypes]\n\treturn schema" ]
[ [ "pandas.api.types.infer_dtype" ], [ "pandas.MultiIndex.from_tuples", "pandas.melt", "pandas.DataFrame.from_dict" ] ]
jinnn-dev/learning-by-annotations
[ "7369973c905d64e09c24e4bcfd7589fbbe9a898e" ]
[ "backend/app/core/polygon_extractor.py" ]
[ "from typing import Union\r\n\r\nimport cv2.cv2\r\nimport imutils\r\nimport numpy as np\r\nfrom imutils import contours\r\n\r\nfrom app.schemas.extractor import GrayGroup, ExtractionResult, ImageDimension\r\nfrom app.schemas.polygon_data import Point\r\nfrom app.utils.colored_printer import ColoredPrinter\r\nfrom app.utils.timer import Timer\r\n\r\n\r\ndef convert_image_to_annotations(file_contents: Union[bytes, str]) -> ExtractionResult:\r\n \"\"\"\r\n Extracts all polygons grouped by gray values of the given file contents.\r\n\r\n :param file_contents: Content of a file\r\n :return: Conversion result\r\n \"\"\"\r\n timer = Timer()\r\n timer.start()\r\n\r\n np_arr = np.fromstring(file_contents, np.uint8)\r\n img_gray = cv2.imdecode(np_arr, cv2.IMREAD_GRAYSCALE)\r\n\r\n time = timer.time_elapsed\r\n ColoredPrinter.print_lined_info(f\"Image-Loading needed {timer.time_elapsed}s\")\r\n\r\n hist = cv2.calcHist([img_gray], [0], None, [256], [0, 256])\r\n available_gray_values = np.unique(np.nonzero(hist))\r\n available_gray_values = available_gray_values[available_gray_values != 0]\r\n time_hist = timer.time_elapsed\r\n ColoredPrinter.print_lined_info(f\"Histo needed {timer.time_elapsed - time}s\")\r\n annotation_groups = []\r\n\r\n for gray_value in available_gray_values:\r\n img_mask = cv2.inRange(img_gray, np.array(gray_value), np.array(gray_value))\r\n found_contours = cv2.findContours(\r\n img_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE\r\n )\r\n found_contours = imutils.grab_contours(found_contours)\r\n (found_contours, _) = contours.sort_contours(found_contours)\r\n annotations = []\r\n for contour in found_contours:\r\n size = cv2.contourArea(contour)\r\n corners = cv2.approxPolyDP(\r\n contour, 0.004 * cv2.arcLength(contour, True), True\r\n ) # Uses Douglas-Peucker algorithm\r\n corners = corners.ravel()\r\n if (\r\n len(corners) > 2 and size > 200.0\r\n ): # Maybe use different Threshold for robuster noise removal\r\n annotation = []\r\n for x, y in zip(corners[0::2], corners[1::2]):\r\n annotation.append(Point(x=float(x), y=float(y)))\r\n annotations.append(annotation)\r\n annotation_groups.append(\r\n GrayGroup(gray_value=int(gray_value), annotations=annotations)\r\n )\r\n ColoredPrinter.print_lined_info(\r\n f\"Feature extraction needed {timer.time_elapsed - time_hist}s\"\r\n )\r\n timer.stop()\r\n ColoredPrinter.print_lined_info(f\"Total conversion time {timer.total_run_time}s\")\r\n height, width = img_gray.shape\r\n return ExtractionResult(\r\n image=ImageDimension(height=height, width=width), annotations=annotation_groups\r\n )\r\n" ]
[ [ "numpy.array", "numpy.fromstring", "numpy.nonzero" ] ]
lrtrct/graby
[ "fa759e47f25beadc5e601939d8c7ea678a0ec5a0" ]
[ "graby.py" ]
[ "#!/usr/bin/python\n\nimport sys\nimport requests\nimport json\nimport pandas as pd\n\ncount = 2122\ncurrency = 'BTC'\n\n###################################################################################\n\n### TO BE UPDATED WITH PERSONAL API KEY (line 25)\n### MORE INFO HERE: https://pro.coinmarketcap.com/signup \n\n###################################################################################\n\n\ncoins_url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?sort=market_cap' \\\n + '&start=1&limit='+ str(count) + '&convert=' + str(currency)\n # + '&start=1&limit='+ str(count) + '&cryptocurrency_type=tokens&convert=' + str(currency)\n\nbtc_url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC&convert=USD'\n\nheader={'X-CMC_PRO_API_KEY':'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'}\n\ncoins_data = requests.get(coins_url,headers=header).json()\nbtc_data = requests.get(btc_url,headers=header).json()\n\ndf = pd.DataFrame([btc_data['data']['BTC']],columns=btc_data['data']['BTC'].keys())\n\ncount = len(coins_data['data'])\n\nfor i in range(count-1):\n df = df.append(coins_data['data'][i+1],ignore_index=True )\n\ndf2 = df.quote.apply(pd.Series)\ndf3 = df2.USD.apply(pd.Series)\ndf4 = df2.BTC.apply(pd.Series)\ndf4 = df4.iloc[1:count]\ndf_quote = pd.concat([df3.iloc[[0]], df4], ignore_index=True)\n\ndf_platform = df.platform.apply(pd.Series)\n\ndf_base = df[df.columns.difference(['quote', 'platform'])]\n\nframes = [df_base, df_quote, df_platform]\nprocessed_df = pd.concat(frames, axis=1)\n\nprocessed_df.to_csv('ccdata.csv')\n" ]
[ [ "pandas.concat" ] ]
darrenreger/zEpid
[ "4b5b4ed81933c92bd17d63364df6673d6f9c2ea6" ]
[ "tests/test_doublyrobust.py" ]
[ "import pytest\nimport numpy as np\nimport pandas as pd\nimport numpy.testing as npt\nfrom sklearn.linear_model import LogisticRegression, LinearRegression\n\nimport zepid as ze\nfrom zepid.causal.doublyrobust import TMLE, AIPTW\n\n\nclass TestTMLE:\n\n @pytest.fixture\n def df(self):\n df = ze.load_sample_data(False)\n df[['cd4_rs1', 'cd4_rs2']] = ze.spline(df, 'cd40', n_knots=3, term=2, restricted=True)\n df[['age_rs1', 'age_rs2']] = ze.spline(df, 'age0', n_knots=3, term=2, restricted=True)\n return df.drop(columns=['cd4_wk45']).dropna()\n\n @pytest.fixture\n def cf(self):\n df = ze.load_sample_data(False)\n df[['cd4_rs1', 'cd4_rs2']] = ze.spline(df, 'cd40', n_knots=3, term=2, restricted=True)\n df[['age_rs1', 'age_rs2']] = ze.spline(df, 'age0', n_knots=3, term=2, restricted=True)\n return df.drop(columns=['dead']).dropna()\n\n @pytest.fixture\n def mf(self):\n df = ze.load_sample_data(False)\n df[['cd4_rs1', 'cd4_rs2']] = ze.spline(df, 'cd40', n_knots=3, term=2, restricted=True)\n df[['age_rs1', 'age_rs2']] = ze.spline(df, 'age0', n_knots=3, term=2, restricted=True)\n return df.drop(columns=['cd4_wk45'])\n\n @pytest.fixture\n def mcf(self):\n df = ze.load_sample_data(False)\n df[['cd4_rs1', 'cd4_rs2']] = ze.spline(df, 'cd40', n_knots=3, term=2, restricted=True)\n df[['age_rs1', 'age_rs2']] = ze.spline(df, 'age0', n_knots=3, term=2, restricted=True)\n return df.drop(columns=['dead'])\n\n def test_drop_missing_data(self):\n df = ze.load_sample_data(False)\n tmle = TMLE(df, exposure='art', outcome='dead')\n assert df.dropna(subset=['cd4_wk45']).shape[0] == tmle.df.shape[0]\n\n def test_error_when_no_models_specified1(self, df):\n tmle = TMLE(df, exposure='art', outcome='dead')\n with pytest.raises(ValueError):\n tmle.fit()\n\n def test_error_when_no_models_specified2(self, df):\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n with pytest.raises(ValueError):\n tmle.fit()\n\n def test_error_when_no_models_specified3(self, df):\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n with pytest.raises(ValueError):\n tmle.fit()\n\n def test_match_r_epsilons(self, df):\n r_epsilons = [-0.016214091, 0.003304079]\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle._epsilon, r_epsilons, rtol=1e-5)\n\n def test_match_r_tmle_riskdifference(self, df):\n r_rd = -0.08440622\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle.risk_difference, r_rd)\n\n def test_match_r_tmle_rd_ci(self, df):\n r_ci = -0.1541104, -0.01470202\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle.risk_difference_ci, r_ci, rtol=1e-5)\n\n def test_match_r_tmle_riskratio(self, df):\n r_rr = 0.5344266\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle.risk_ratio, r_rr)\n\n def test_match_r_tmle_rr_ci(self, df):\n r_ci = 0.2773936, 1.0296262\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle.risk_ratio_ci, r_ci, rtol=1e-5)\n\n def test_match_r_tmle_oddsratio(self, df):\n r_or = 0.4844782\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle.odds_ratio, r_or)\n\n def test_match_r_tmle_or_ci(self, df):\n r_ci = 0.232966, 1.007525\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle.odds_ratio_ci, r_ci, rtol=1e-5)\n\n def test_symmetric_bounds_on_gW(self, df):\n r_rd = -0.08203143\n r_ci = -0.1498092, -0.01425363\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n bound=0.1, print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle.risk_difference, r_rd)\n npt.assert_allclose(tmle.risk_difference_ci, r_ci, rtol=1e-5)\n\n def test_asymmetric_bounds_on_gW(self, df):\n r_rd = -0.08433208\n r_ci = -0.1541296, -0.01453453\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n bound=[0.025, 0.9], print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle.risk_difference, r_rd)\n npt.assert_allclose(tmle.risk_difference_ci, r_ci, rtol=1e-5)\n\n def test_no_risk_with_continuous(self, cf):\n tmle = TMLE(cf, exposure='art', outcome='cd4_wk45')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n bound=[0.025, 0.9], print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n assert tmle.risk_difference is None\n assert tmle.risk_ratio is None\n assert tmle.odds_ratio is None\n assert tmle.risk_difference_ci is None\n assert tmle.risk_ratio_ci is None\n assert tmle.odds_ratio_ci is None\n\n def test_no_ate_with_binary(self, df):\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n bound=[0.025, 0.9], print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n assert tmle.average_treatment_effect is None\n assert tmle.average_treatment_effect_ci is None\n\n def test_match_r_epsilons_continuous(self, cf):\n r_epsilons = [-0.0046411652, 0.0002270186]\n tmle = TMLE(cf, exposure='art', outcome='cd4_wk45')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle._epsilon, r_epsilons, rtol=1e-4, atol=1e-4)\n\n def test_match_r_continuous_outcome(self, cf):\n r_ate = 223.4022\n r_ci = 118.6037, 328.2008\n\n tmle = TMLE(cf, exposure='art', outcome='cd4_wk45')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle.average_treatment_effect, r_ate, rtol=1e-3)\n npt.assert_allclose(tmle.average_treatment_effect_ci, r_ci, rtol=1e-3)\n\n def test_match_r_continuous_outcome_gbounds(self, cf):\n r_ate = 223.3958\n r_ci = 118.4178, 328.3737\n\n tmle = TMLE(cf, exposure='art', outcome='cd4_wk45')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n bound=[0.025, 0.9], print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle.average_treatment_effect, r_ate, rtol=1e-3)\n npt.assert_allclose(tmle.average_treatment_effect_ci, r_ci, rtol=1e-3)\n\n def test_match_r_continuous_poisson(self, cf):\n r_ate = 223.4648\n r_ci = 118.6276, 328.3019\n\n tmle = TMLE(cf, exposure='art', outcome='cd4_wk45')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False, continuous_distribution='poisson')\n tmle.fit()\n npt.assert_allclose(tmle.average_treatment_effect, r_ate, rtol=1e-3)\n npt.assert_allclose(tmle.average_treatment_effect_ci, r_ci, rtol=1e-3)\n\n def test_sklearn_in_tmle(self, df):\n log = LogisticRegression(C=1.0)\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + cd40 + dvl0', custom_model=log)\n tmle.outcome_model('art + male + age0 + cd40 + dvl0', custom_model=log)\n tmle.fit()\n\n # Testing RD match\n npt.assert_allclose(tmle.risk_difference, -0.091372098)\n npt.assert_allclose(tmle.risk_difference_ci, [-0.1595425678, -0.0232016282], rtol=1e-5)\n # Testing RR match\n npt.assert_allclose(tmle.risk_ratio, 0.4998833415)\n npt.assert_allclose(tmle.risk_ratio_ci, [0.2561223823, 0.9756404452], rtol=1e-5)\n # Testing OR match\n npt.assert_allclose(tmle.odds_ratio, 0.4496171689)\n npt.assert_allclose(tmle.odds_ratio_ci, [0.2139277755, 0.944971255], rtol=1e-5)\n\n def test_sklearn_in_tmle2(self, cf):\n log = LogisticRegression(C=1.0)\n lin = LinearRegression()\n tmle = TMLE(cf, exposure='art', outcome='cd4_wk45')\n tmle.exposure_model('male + age0 + cd40 + dvl0', custom_model=log)\n tmle.outcome_model('art + male + age0 + cd40 + dvl0', custom_model=lin)\n tmle.fit()\n\n npt.assert_allclose(tmle.average_treatment_effect, 236.049719, rtol=1e-5)\n npt.assert_allclose(tmle.average_treatment_effect_ci, [135.999264, 336.100175], rtol=1e-5)\n\n def test_missing_binary_outcome(self, mf):\n r_rd = -0.08168098\n r_rd_ci = -0.15163818, -0.01172378\n r_rr = 0.5495056\n r_rr_ci = 0.2893677, 1.0435042\n r_or = 0.4996546\n r_or_ci = 0.2435979, 1.0248642\n\n tmle = TMLE(mf, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.missing_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n\n npt.assert_allclose(tmle.risk_difference, r_rd)\n npt.assert_allclose(tmle.risk_difference_ci, r_rd_ci, rtol=1e-5)\n npt.assert_allclose(tmle.risk_ratio, r_rr)\n npt.assert_allclose(tmle.risk_ratio_ci, r_rr_ci, rtol=1e-5)\n npt.assert_allclose(tmle.odds_ratio, r_or)\n npt.assert_allclose(tmle.odds_ratio_ci, r_or_ci, rtol=1e-5)\n\n def test_no_missing_data(self, df):\n tmle = TMLE(df, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n with pytest.raises(ValueError):\n tmle.missing_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n\n def test_missing_continuous_outcome(self, mcf):\n r_ate = 211.8295\n r_ci = 107.7552, 315.9038\n\n tmle = TMLE(mcf, exposure='art', outcome='cd4_wk45')\n tmle.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.missing_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n tmle.fit()\n npt.assert_allclose(tmle.average_treatment_effect, r_ate, rtol=1e-3)\n npt.assert_allclose(tmle.average_treatment_effect_ci, r_ci, rtol=1e-3)\n\n def test_sklearn_in_tmle_missing(self, mf):\n log = LogisticRegression(C=1.0)\n tmle = TMLE(mf, exposure='art', outcome='dead')\n tmle.exposure_model('male + age0 + cd40 + dvl0', custom_model=log, print_results=False)\n tmle.missing_model('male + age0 + cd40 + dvl0', custom_model=log, print_results=False)\n tmle.outcome_model('art + male + age0 + cd40 + dvl0', custom_model=log, print_results=False)\n tmle.fit()\n\n # Testing RD match\n npt.assert_allclose(tmle.risk_difference, -0.090086, rtol=1e-5)\n npt.assert_allclose(tmle.risk_difference_ci, [-0.160371, -0.019801], rtol=1e-4)\n # Testing RR match\n npt.assert_allclose(tmle.risk_ratio, 0.507997, rtol=1e-5)\n npt.assert_allclose(tmle.risk_ratio_ci, [0.256495, 1.006108], rtol=1e-4)\n # Testing OR match\n npt.assert_allclose(tmle.odds_ratio, 0.457541, rtol=1e-5)\n npt.assert_allclose(tmle.odds_ratio_ci, [0.213980, 0.978331], rtol=1e-4)\n\n\nclass TestAIPTW:\n\n @pytest.fixture\n def df(self):\n df = ze.load_sample_data(False)\n df[['cd4_rs1', 'cd4_rs2']] = ze.spline(df, 'cd40', n_knots=3, term=2, restricted=True)\n df[['age_rs1', 'age_rs2']] = ze.spline(df, 'age0', n_knots=3, term=2, restricted=True)\n return df.drop(columns=['cd4_wk45']).dropna()\n\n @pytest.fixture\n def cf(self):\n df = ze.load_sample_data(False)\n df[['cd4_rs1', 'cd4_rs2']] = ze.spline(df, 'cd40', n_knots=3, term=2, restricted=True)\n df[['age_rs1', 'age_rs2']] = ze.spline(df, 'age0', n_knots=3, term=2, restricted=True)\n return df.drop(columns=['dead']).dropna()\n\n @pytest.fixture\n def dat(self):\n df = pd.DataFrame()\n df['L'] = [1]*10000 + [0]*40000\n df['A'] = [1]*2000 + [0]*8000 + [1]*30000 + [0]*10000\n df['Y'] = [1]*500 + [0]*1500 + [1]*4000 + [0]*4000 + [1]*10000 + [0]*20000 + [1]*4000 + [0]*6000\n return df\n\n def test_drop_missing_data(self):\n df = ze.load_sample_data(False)\n aipw = AIPTW(df, exposure='art', outcome='dead')\n assert df.dropna(subset=['cd4_wk45']).shape[0] == aipw.df.shape[0]\n\n def test_error_when_no_models_specified1(self, df):\n aipw = AIPTW(df, exposure='art', outcome='dead')\n with pytest.raises(ValueError):\n aipw.fit()\n\n def test_error_when_no_models_specified2(self, df):\n aipw = AIPTW(df, exposure='art', outcome='dead')\n aipw.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n with pytest.raises(ValueError):\n aipw.fit()\n\n def test_error_when_no_models_specified3(self, df):\n aipw = AIPTW(df, exposure='art', outcome='dead')\n aipw.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n with pytest.raises(ValueError):\n aipw.fit()\n\n def test_match_rd(self, df):\n aipw = AIPTW(df, exposure='art', outcome='dead')\n aipw.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n aipw.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n aipw.fit()\n npt.assert_allclose(aipw.risk_difference, -0.0848510605)\n\n def test_match_rr(self, df):\n aipw = AIPTW(df, exposure='art', outcome='dead')\n aipw.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n aipw.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n aipw.fit()\n npt.assert_allclose(aipw.risk_ratio, 0.5319812235)\n\n def test_double_robustness(self, dat):\n aipw = AIPTW(dat, exposure='A', outcome='Y')\n aipw.exposure_model('L', print_results=False)\n aipw.outcome_model('L + A + A:L', print_results=False)\n aipw.fit()\n both_correct_rd = aipw.risk_difference\n both_correct_rr = aipw.risk_ratio\n\n aipw = AIPTW(dat, exposure='A', outcome='Y')\n aipw.exposure_model('L', print_results=False)\n aipw.outcome_model('A + L', print_results=False)\n aipw.fit()\n wrong_y_rd = aipw.risk_difference\n wrong_y_rr = aipw.risk_ratio\n\n # Testing\n npt.assert_allclose(both_correct_rd, wrong_y_rd)\n npt.assert_allclose(both_correct_rr, wrong_y_rr)\n\n aipw = AIPTW(dat, exposure='A', outcome='Y')\n aipw.exposure_model('1', print_results=False)\n aipw.outcome_model('A + L + A:L', print_results=False)\n aipw.fit()\n wrong_a_rd = aipw.risk_difference\n wrong_a_rr = aipw.risk_ratio\n\n # Testing\n npt.assert_allclose(both_correct_rd, wrong_a_rd)\n npt.assert_allclose(both_correct_rr, wrong_a_rr)\n\n def test_weighted_rd(self, df):\n df['weights'] = 2\n aipw = AIPTW(df, exposure='art', outcome='dead', weights='weights')\n aipw.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n aipw.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n aipw.fit()\n npt.assert_allclose(aipw.risk_difference, -0.0848510605)\n\n def test_weighted_rr(self, df):\n df['weights'] = 2\n aipw = AIPTW(df, exposure='art', outcome='dead', weights='weights')\n aipw.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n aipw.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n aipw.fit()\n npt.assert_allclose(aipw.risk_ratio, 0.5319812235)\n\n def test_continuous_outcomes(self, cf):\n aipw = AIPTW(cf, exposure='art', outcome='cd4_wk45')\n aipw.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n aipw.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n aipw.fit()\n npt.assert_allclose(aipw.average_treatment_effect, 225.13767, rtol=1e-3)\n npt.assert_allclose(aipw.average_treatment_effect_ci, [118.64677, 331.62858], rtol=1e-3)\n\n def test_poisson_outcomes(self, cf):\n aipw = AIPTW(cf, exposure='art', outcome='cd4_wk45')\n aipw.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n aipw.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n continuous_distribution='poisson', print_results=False)\n aipw.fit()\n npt.assert_allclose(aipw.average_treatment_effect, 225.13767, rtol=1e-3)\n npt.assert_allclose(aipw.average_treatment_effect_ci, [118.64677, 331.62858], rtol=1e-3)\n\n def test_weighted_continuous_outcomes(self, cf):\n cf['weights'] = 2\n aipw = AIPTW(cf, exposure='art', outcome='cd4_wk45', weights='weights')\n aipw.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0', print_results=False)\n aipw.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n aipw.fit()\n npt.assert_allclose(aipw.average_treatment_effect, 225.13767, rtol=1e-3)\n assert aipw.average_treatment_effect_ci is None\n\n def test_bounds(self, df):\n aipw = AIPTW(df, exposure='art', outcome='dead')\n aipw.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n bound=0.1, print_results=False)\n aipw.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n aipw.fit()\n\n npt.assert_allclose(aipw.risk_difference, -0.0819506956)\n npt.assert_allclose(aipw.risk_difference_ci, (-0.1498808287, -0.0140205625))\n\n def test_bounds2(self, df):\n aipw = AIPTW(df, exposure='art', outcome='dead')\n aipw.exposure_model('male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n bound=[0.2, 0.9], print_results=False)\n aipw.outcome_model('art + male + age0 + age_rs1 + age_rs2 + cd40 + cd4_rs1 + cd4_rs2 + dvl0',\n print_results=False)\n aipw.fit()\n\n npt.assert_allclose(aipw.risk_difference, -0.0700780176)\n npt.assert_allclose(aipw.risk_difference_ci, (-0.1277925885, -0.0123634468))\n" ]
[ [ "sklearn.linear_model.LinearRegression", "sklearn.linear_model.LogisticRegression", "pandas.DataFrame", "numpy.testing.assert_allclose" ] ]
omotayo-alade/ml-death-event-prediction
[ "b8b215d1fdf55183dbe7405af703b2d11dcf5b50" ]
[ "src/scripts/ingest/app.py" ]
[ "import numpy as np\nfrom flask import Flask, request, jsonify, render_template\nimport pickle\n\nmodel = pickle.load(open('outputs/models/model.pkl', 'rb'))\n\napp = Flask(__name__, template_folder='template') #Initialize the flask App\n\[email protected]('/')\ndef home():\n return render_template('index.html')\n\[email protected]('/predict',methods=['POST', 'GET'])\ndef predict():\n '''\n For rendering results on HTML GUI\n '''\n lst = [float(x) for x in request.form.values()]\n features = [np.array(lst)]\n result = model.predict_proba(features)\n output = round((result[0][0] * 100), 2)\n\n model_prediction = 'Patient has about {}% chance of survival.'.format(output)\n\n return render_template('index.html', prediction=model_prediction, show_prediction=True)\n\nif __name__ == '__main__':\n app.run(debug=True)" ]
[ [ "numpy.array" ] ]
tongyao-zhu/nslt
[ "fe6ae9a6567bddd31d82c878f8f5b0186ea95243" ]
[ "nslt/utils/misc_utils.py" ]
[ "# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Generally useful utility functions.\"\"\"\nfrom __future__ import print_function\n\nimport codecs\nimport collections\nimport json\nimport math\nimport os\nimport sys\nimport time\n\nimport tensorflow as tf\n\n\ndef check_tensorflow_version():\n if tf.__version__ < \"1.2.1\":\n raise EnvironmentError(\"Tensorflow version must >= 1.2.1\")\n\n\ndef safe_exp(value):\n \"\"\"Exponentiation with catching of overflow error.\"\"\"\n try:\n ans = math.exp(value)\n except OverflowError:\n ans = float(\"inf\")\n return ans\n\n\ndef print_time(s, start_time):\n \"\"\"Take a start time, print elapsed duration, and return a new time.\"\"\"\n print(\"%s, time %ds, %s.\" % (s, (time.time() - start_time), time.ctime()))\n sys.stdout.flush()\n return time.time()\n\n\ndef print_out(s, f=None, new_line=True):\n \"\"\"Similar to print but with support to flush and output to a file.\"\"\"\n if isinstance(s, bytes):\n s = s.decode(\"utf-8\")\n\n if f:\n f.write(s.encode(\"utf-8\"))\n if new_line:\n f.write(b\"\\n\")\n\n # stdout\n print(s, end=\"\", file=sys.stdout)\n if new_line:\n sys.stdout.write(\"\\n\")\n sys.stdout.flush()\n\n\ndef print_hparams(hparams, skip_patterns=None):\n \"\"\"Print hparams, can skip keys based on pattern.\"\"\"\n values = hparams.values()\n for key in sorted(values.keys()):\n if not skip_patterns or all(\n [skip_pattern not in key for skip_pattern in skip_patterns]):\n print_out(\" %s=%s\" % (key, str(values[key])))\n\n\ndef load_hparams(model_dir):\n \"\"\"Load hparams from an existing model directory.\"\"\"\n hparams_file = os.path.join(model_dir, \"hparams\")\n if tf.gfile.Exists(hparams_file):\n print_out(\"hparams exist!\")\n print_out(\"# Loading hparams from %s\" % hparams_file)\n with codecs.getreader(\"utf-8\")(tf.gfile.GFile(hparams_file, \"rb\")) as f:\n try:\n hparams_values = json.load(f)\n hparams = tf.contrib.training.HParams(**hparams_values)\n except ValueError:\n print_out(\" can't load hparams file\")\n return None\n return hparams\n else:\n return None\n\n\ndef maybe_parse_standard_hparams(hparams, hparams_path):\n \"\"\"Override hparams values with existing standard hparams config.\"\"\"\n if not hparams_path:\n return hparams\n\n if tf.gfile.Exists(hparams_path):\n print_out(\"# Loading standard hparams from %s\" % hparams_path)\n with tf.gfile.GFile(hparams_path, \"r\") as f:\n hparams.parse_json(f.read())\n\n return hparams\n\n\ndef save_hparams(out_dir, hparams):\n \"\"\"Save hparams.\"\"\"\n hparams_file = os.path.join(out_dir, \"hparams\")\n print_out(\" saving hparams to %s\" % hparams_file)\n with codecs.getwriter(\"utf-8\")(tf.gfile.GFile(hparams_file, \"wb\")) as f:\n f.write(hparams.to_json())\n\n\ndef debug_tensor(s, msg=None, summarize=10):\n \"\"\"Print the shape and value of a tensor at test time. Return a new tensor.\"\"\"\n if not msg:\n msg = s.name\n return tf.Print(s, [tf.shape(s), s], msg + \" \", summarize=summarize)\n\n\ndef add_summary(summary_writer, global_step, tag, value):\n \"\"\"Add a new summary to the current summary_writer.\n Useful to log things that are not part of the training graph, e.g., tag=BLEU.\n \"\"\"\n summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)])\n summary_writer.add_summary(summary, global_step)\n\n\ndef get_config_proto(log_device_placement=False, allow_soft_placement=True):\n # GPU options:\n # https://www.tensorflow.org/versions/r0.10/how_tos/using_gpu/index.html\n config_proto = tf.ConfigProto(\n log_device_placement=log_device_placement,\n allow_soft_placement=allow_soft_placement)\n config_proto.gpu_options.allow_growth = True\n return config_proto\n\n\ndef format_text(words):\n \"\"\"Convert a sequence words into sentence.\"\"\"\n if (not hasattr(words, \"__len__\") and # for numpy array\n not isinstance(words, collections.Iterable)):\n words = [words]\n return b\" \".join(words)\n\n\ndef format_bpe_text(symbols, delimiter=b\"@@\"):\n \"\"\"Convert a sequence of bpe words into sentence.\"\"\"\n words = []\n word = b\"\"\n if isinstance(symbols, str):\n symbols = symbols.encode()\n delimiter_len = len(delimiter)\n for symbol in symbols:\n if len(symbol) >= delimiter_len and symbol[-delimiter_len:] == delimiter:\n word += symbol[:-delimiter_len]\n else: # end of a word\n word += symbol\n words.append(word)\n word = b\"\"\n return b\" \".join(words)\n" ]
[ [ "tensorflow.shape", "tensorflow.gfile.Exists", "tensorflow.gfile.GFile", "tensorflow.ConfigProto", "tensorflow.Summary.Value", "tensorflow.contrib.training.HParams" ] ]
fuhrmanj/TRANSACT_manuscript
[ "71ca2ec42bdd5d547d4b965aa7f84838bfd5b812" ]
[ "deep_learning_CV/GDSC_HMF_cross_validation_with_combat.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n\n## ComBat correction between GDSC and PDX followed by GDSC cross-validation\n#\n# In this script, I reproduce the pipeline from [Sakelaropoulos et al 2019] \n# for GDSC-PDXE analysis. After correction, I consider one drug and compute \n# for various hyper-parameters of the neural networks the predictive \n# performance by 5-fold cross-validation.\n# The process goes as follows:\n# - we compute a KFold to divide dataset in 5.\n# - for each fold held out and each parameter possible, we train on the\n# remaining folds and predict the response.\n# - the final measure (either pearson correlation or MSE) is computed among\n# the combined held-out samples.\n\n\nn_splits = 5\noutput_folder = './output/GDSC_to_HMF/'\nfigure_folder = './figures/GDSC_HMF_combat/'\n\nimport os, sys, getopt\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nimport functools\nfrom joblib import Parallel, delayed\nimport scipy\nfrom datetime import date\nimport re\nimport uuid\nfrom pickle import dump\nfrom combat.pycombat import pycombat\nsns.set_style(\"whitegrid\")\nsns.set_context('paper')\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import StratifiedKFold, KFold, GroupKFold, GridSearchCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import ParameterGrid\nfrom sklearn.linear_model import ElasticNet\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.utils import shuffle, resample\nfrom joblib import dump, load, Parallel, delayed\nfrom statannot.statannot import add_stat_annotation\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch.utils.data as Data\nfrom torch.utils.data import Dataset, TensorDataset, DataLoader\nfrom torch.utils.data.dataset import random_split\nfrom skorch import NeuralNetClassifier, NeuralNetRegressor\n\nsys.path.insert(0, '../read_data/')\nfrom read_data import read_data\nfrom read_GDSC_response import read_GDSC_response\nfrom read_PDXE_response import read_PDXE_response\nfrom read_TCGA_response import read_TCGA_response\nfrom reformat_df import reformat_df\nimport library_size_normalization\n\nfrom clf_utils import make_network, make_figure_folder\nfrom read_GDSC import read_GDSC_drug_response\n\n\nGDSC_drug_name = None\nGDSC_drug_id = None # Or 1007/1819 for Docetaxel\nrandom_state = None\n\nopts, args = getopt.getopt(sys.argv[1:],\"n:i:r:\",[\"name=\",\"id=\"])\nfor opt, arg in opts:\n if opt in (\"-i\", \"--ifile\"):\n GDSC_drug_id = int(arg)\n elif opt in (\"-n\", \"--ofile\"):\n GDSC_drug_name = arg\n elif opt in (\"-r\", \"--ofile\"):\n random_state = int(arg)\n\nrandom_state = random_state if random_state else 15485\n\ntissues = {\n 'GDSC': ['All'],\n 'HMF': ['All']\n}\nprojects = {\n 'GDSC': [None],\n 'HMF': [None]\n}\n\ndata_sources = ['GDSC', 'HMF']\n\ndata_types = ['rnaseq']\ngenes_filtering = 'mini_cancer'\ndata_normalization = 'library_size' # Can be TPM, \"library_size\" or \"log\". Else will not have any influence.\n\nsource = 'GDSC'\ntarget = 'HMF'\n\nwith_mean = False\nwith_std = False\n\n\n## Import data\ndata_df = read_data(tissues=tissues,\n data_types=[e for e in data_types],\n projects=projects,\n data_sources=data_sources,\n folder_basis='../data/')\n\nfor ds in list(data_df.keys()):\n assert len(data_df[ds].keys()) == 1\n new_key = ('%s_%s'%(ds, list(data_df[ds].keys())[0])).replace('fpkm', 'tpm')\n data_df[new_key] = data_df[ds][list(data_df[ds].keys())[0]]\n del data_df[ds]\n\nsource_data_key = [ds for ds in data_df if source in ds]\nassert len(source_data_key) == 1\nsource_data_key = np.unique(source_data_key)[0]\n\ntarget_data_key = [ds for ds in data_df if target in ds]\nassert len(target_data_key) == 1\ntarget_data_key = np.unique(target_data_key)[0]\n\n\nfor ds in list(data_df.keys()):\n GE_normalized = library_size_normalization.TMM_normalization(data_df[ds].values.astype(float))\n GE_normalized = np.array(GE_normalized)\n GE_normalized = np.log(np.array(GE_normalized)+1)\n data_df[ds] = pd.DataFrame(GE_normalized,\n columns=data_df[ds].columns,\n index=data_df[ds].index)\n\n# remove some genes to avoid ComBat to collapse\nnumber_top_genes = 1700\n\ntop_source_variable_genes = pd.DataFrame(np.var(data_df[source_data_key]), columns=['variance'])\ntop_source_variable_genes = top_source_variable_genes.sort_values('variance', ascending=False)\ntop_source_variable_genes = top_source_variable_genes.head(number_top_genes).index\ntop_target_variable_genes = pd.DataFrame(np.var(data_df[target_data_key]), columns=['variance'])\ntop_target_variable_genes = top_target_variable_genes.sort_values('variance', ascending=False)\ntop_target_variable_genes = top_target_variable_genes.head(number_top_genes).index\ntop_variable_genes = np.intersect1d(top_source_variable_genes, top_target_variable_genes)\n\nfor d in data_df:\n data_df[d] = data_df[d][top_variable_genes]\n\n\n## Correct with ComBat\ndata_corrected = pycombat(pd.concat(list(data_df.values())).T,\n [1]*data_df[source_data_key].shape[0] + [2]*data_df[target_data_key].shape[0])\n\nnormalized_data_df = {\n k : data_corrected[data_df[k].index].T\n for k in data_df\n}\nnormalized_data_df[source_data_key].index = pd.MultiIndex.from_tuples(normalized_data_df[source_data_key].index)\n\n\n# Read response\nif GDSC_drug_name in ['Cetuximab',\n 'Doxorubicin',\n 'Etoposide',\n 'Bleomycin',\n 'Bicalutamide',\n 'Bleomycin (50 uM)', \n 'Pemetrexed',\n 'AICA Ribonucleotide']:\n GDSC_drug_response_file = '/DATA/s.mourragui/data/2019_10_01_cell_model_passport/GDSC1_drug_response.xlsx'\nelse:\n GDSC_drug_response_file = '/DATA/s.mourragui/data/2019_10_01_cell_model_passport/GDSC2_drug_response.xlsx'\nGDSC_drug_response_df = pd.read_excel(GDSC_drug_response_file)\n\nX, y = read_GDSC_drug_response(GDSC_drug_name,\n GDSC_drug_id,\n GDSC_drug_response_df,\n normalized_data_df[source_data_key])\n\ny_values = y.values.astype(np.float32)\nX_values = X.values.astype(np.float32)\n\n## Cross-validation\n# Splitting data\nsplit_folds = KFold(n_splits=5, shuffle=True, random_state=random_state)\nsplit_folds.get_n_splits()\n\n\n# Import parameters\nparam_dict = load(open('./params/sakellaropoulos_param_grid.pkl', 'rb'))\nparameter_grid = ParameterGrid(param_dict)\n\nif GDSC_drug_name not in os.listdir(output_folder):\n os.mkdir(output_folder + GDSC_drug_name)\noutput_folder += GDSC_drug_name + '/'\n\n# Cross-validation for each parameter in the grid\nfor param_idx, param in enumerate(parameter_grid):\n print('START PARAM NUMBER %s'%(param_idx))\n\n param['n_input'] = X_values.shape[1]\n network_folder = make_figure_folder(output_folder, param)\n\n y_predict_nn = np.zeros(y_values.shape[0])\n\n for split_idx, (train_index, valid_index) in enumerate(split_folds.split(X_values, y_values)):\n print('START SPLIT NUMBER %s'%(split_idx))\n X_train, y_train = X_values[train_index], y_values[train_index]\n X_valid, y_valid = X_values[valid_index], y_values[valid_index]\n \n net = make_network(param)\n net = NeuralNetRegressor(\n net,\n max_epochs=param['n_epochs'],\n lr=param['learning_rate'],\n batch_size=param['batch_size'],\n device= 'cuda' if torch.cuda.is_available() else 'cpu',\n optimizer=torch.optim.SGD,\n optimizer__momentum=param['momentum'],\n optimizer__weight_decay=param['l2_penalty'],\n iterator_train__shuffle = True,\n verbose=0\n )\n pipeline = Pipeline([\n ('scaler', StandardScaler(with_mean=with_mean, with_std=with_std)),\n ('net', net)\n ]\n )\n pipeline.fit(X_train,\n y_train)\n y_predict_nn[valid_index] = pipeline.predict(X_valid.astype(np.float32)).flatten()\n \n pipeline_file = 'clf_random-state_%s_split-nbre_%s.pkl'%(random_state,\n split_idx)\n dump(pipeline, '%s/%s'%(network_folder, pipeline_file))\n\n pd.DataFrame(\n y_predict_nn,\n index=y.index\n ).to_csv('%s/prediction_random-state_%s.csv'%(network_folder,\n random_state))\n\n pred_perf = scipy.stats.pearsonr(y_predict_nn, y_values.flatten())\n MSE = mean_squared_error(y_predict_nn, y_values.flatten())\n perf_df = pd.DataFrame([pred_perf[0], MSE], index=['pred_perf', 'MSE']).T\n perf_df.to_csv('%s/pred_perf_random-state_%s.csv'%(network_folder,\n random_state))\n\n dump(param, '%s/param.pkl'%(network_folder))\n\n\n# Cross-validation with ElasticNet\nalpha_values = np.logspace(-5,10,16)\nl1_ratio_values = np.linspace(0,10,11)/10\nparam_grid ={\n 'regression__alpha': alpha_values,\n 'regression__l1_ratio': l1_ratio_values\n}\n\ny_predict_baseline = np.zeros(y_values.shape[0])\nfor split_idx, (train_index, valid_index) in enumerate(split_folds.split(X_values, y_values)):\n X_train, y_train = X_values[train_index], y_values[train_index]\n X_valid, y_valid = X_values[valid_index], y_values[valid_index]\n \n baseline_grid = GridSearchCV(Pipeline([\n ('scaler', StandardScaler(with_mean=with_mean, with_std=with_std)),\n ('regression', ElasticNet())\n ]),\n cv=10,\n n_jobs=30,\n param_grid=param_grid,\n verbose=1,\n scoring='neg_mean_squared_error')\n baseline_grid.fit(X_train, y_train)\n y_predict_baseline[valid_index] = baseline_grid.predict(X_valid)\n\npd.DataFrame(\n y_predict_baseline,\n index=y.index\n).to_csv('%s/baseline_prediction_random-state_%s.csv'%(output_folder,\n random_state))\n\npred_perf_baseline = scipy.stats.pearsonr(y_predict_baseline, y_values.flatten())\nMSE_baseline = mean_squared_error(y_predict_baseline, y_values.flatten())\nperf_df = pd.DataFrame([pred_perf_baseline[0], MSE_baseline], index=['pred_perf', 'MSE']).T\nperf_df.to_csv('%s/baseline_pred_perf_random-state_%s.csv'%(output_folder,\n random_state))\n\n\n## Results processing\nfig_name = '%s%s_%s%s_%s'%(figure_folder,\n GDSC_drug_name,\n '_centered' if with_mean else '',\n '_standardized' if with_std else '',\n random_state)\n\nparam_names = ['hidden', 'input', 'activation', 'hiddenDO', 'inputDO', 'l2pen', 'lr']\ndef parse_folder_results(f):\n param = {}\n for n in param_names:\n param[n] = re.search('%s_([0-9A-Za-z-.]+)'%(n), f)\n param[n] = [param[n].group(1)] if param[n] else ''\n param['folder'] = f\n param_df = pd.DataFrame.from_dict(param)\n \n results_files = ['%s/%s/'%(output_folder, f) + e for e in os.listdir('%s/%s'%(output_folder, f))\n if '.csv' in e and 'pred_perf' in e and (str(random_state) in e or random_state is None)]\n \n if len(results_files) == 0:\n return None\n \n results_df = [pd.read_csv(r, header=0, index_col=0) for r in results_files]\n results_df = pd.concat(results_df)\n results_df.index = [f] * results_df.shape[0]\n \n return results_df\n\n\nrelevant_subfolders = [e for e in os.listdir(output_folder)\n if 'hidden' in e]\n\nresults_df = [parse_folder_results(f) for f in relevant_subfolders]\nresults_df = [df for df in results_df if df is not None]\nresults_df = pd.concat(results_df)\n\nbaseline_df = pd.read_csv('%s/baseline_pred_perf_random-state_%s.csv'%(output_folder, random_state),\n header=0, index_col=0)\n\nresults_df.columns = [('model', e) for e in results_df.columns]\nfor e in ['MSE', 'pred_perf']:\n results_df[('baseline', e)] = baseline_df[e].values[0]\nresults_df.columns = pd.MultiIndex.from_tuples(results_df.columns)\n\nresults_df.to_csv('%s.csv'%(fig_name))\n\nfor x in ['pred_perf', 'MSE']:\n plt.figure(figsize=(10,4.5))\n plt.axhline(baseline_df[x].values[0],\n linewidth=3,\n label='ElasticNet',\n linestyle='dashed',\n color='black',\n alpha=0.6)\n plt.plot(results_df['model'].sort_values(x, ascending=(x=='pred_perf'))[x].values, '+',\n label='Neural network', markersize=10)\n plt.xticks(fontsize=15, color='black')\n plt.xlabel('Cross-validated models', fontsize=20, color='black')\n plt.yticks(fontsize=15, color='black')\n plt.ylabel('Predictive performance' if x == 'pred_perf' else 'Mean Squared Error', fontsize=20, color='black')\n plt.legend(fontsize=15, bbox_to_anchor=(1., 1), loc='upper left')\n plt.tight_layout()\n plt.savefig('%s_CV_%s.png'%(fig_name, x),\n dpi=300)\n plt.clf()\n \nprint('%s models computed'%(results_df.shape[0]))" ]
[ [ "matplotlib.pyplot.legend", "pandas.read_excel", "numpy.linspace", "sklearn.linear_model.ElasticNet", "pandas.MultiIndex.from_tuples", "sklearn.model_selection.KFold", "pandas.DataFrame", "torch.cuda.is_available", "numpy.var", "pandas.read_csv", "matplotlib.pyplot.tight_layout", "numpy.unique", "numpy.intersect1d", "numpy.zeros", "matplotlib.pyplot.figure", "pandas.concat", "numpy.logspace", "matplotlib.pyplot.savefig", "sklearn.model_selection.ParameterGrid", "sklearn.preprocessing.StandardScaler", "pandas.DataFrame.from_dict", "numpy.array", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.yticks", "matplotlib.pyplot.axhline", "matplotlib.pyplot.clf", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks" ] ]
rameshnair007/SR-cycleGAN
[ "a111131fadb2fca45c6655410107e040d6973351" ]
[ "data/colorization_dataset.py" ]
[ "import os.path\nfrom data.base_dataset import BaseDataset, get_transform\nfrom data.image_folder import make_dataset\nfrom skimage import color # require skimage\nfrom PIL import Image\nimport numpy as np\nimport torchvision.transforms as transforms\n\n\nclass ColorizationDataset(BaseDataset):\n \"\"\"This dataset class can load a set of natural images in RGB, and convert RGB format into (L, ab) pairs in Lab color space.\n\n This dataset is required by pix2pix-based colorization model ('--model colorization')\n \"\"\"\n @staticmethod\n def modify_commandline_options(parser, is_train):\n \"\"\"Add new dataset-specific options, and rewrite default values for existing options.\n\n Parameters:\n parser -- original option parser\n is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n Returns:\n the modified parser.\n\n By default, the number of channels for input image is 1 (L) and\n the nubmer of channels for output image is 2 (ab). The direction is from A to B\n \"\"\"\n parser.set_defaults(input_nc=1, output_nc=2, direction='AtoB')\n return parser\n\n def __init__(self, opt):\n \"\"\"Initialize this dataset class.\n\n Parameters:\n opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n \"\"\"\n BaseDataset.__init__(self, opt)\n self.dir = os.path.join(opt.dataroot)\n self.AB_paths = sorted(make_dataset(self.dir, opt.max_dataset_size))\n assert(opt.input_nc == 1 and opt.output_nc == 2 and opt.direction == 'AtoB')\n self.transform = get_transform(self.opt, convert=False)\n\n def __getitem__(self, index):\n \"\"\"Return a data point and its metadata information.\n\n Parameters:\n index - - a random integer for data indexing\n\n Returns a dictionary that contains A, B, A_paths and B_paths\n A (tensor) - - the L channel of an image\n B (tensor) - - the ab channels of the same image\n A_paths (str) - - image paths\n B_paths (str) - - image paths (same as A_paths)\n \"\"\"\n path = self.AB_paths[index]\n im = Image.open(path).convert('RGB')\n im = self.transform(im)\n im = np.array(im)\n lab = color.rgb2lab(im).astype(np.float32)\n lab_t = transforms.ToTensor()(lab)\n A = lab_t[[0], ...] / 50.0 - 1.0\n B = lab_t[[1, 2], ...] / 110.0\n return {'A': A, 'B': B, 'A_paths': path, 'B_paths': path}\n\n def __len__(self):\n \"\"\"Return the total number of images in the dataset.\"\"\"\n return len(self.AB_paths)\n" ]
[ [ "numpy.array" ] ]
skumailraza/AANet-MS
[ "f50613cfdcbe217d8d43ffe0f720615c2ebee07e" ]
[ "nets/feature.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom nets.deform import DeformConv2d\n\n\ndef conv1x1(in_channels, out_channels):\n return nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True))\n\n\n# Used for StereoNet feature extractor\ndef conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1, with_bn_relu=False, leaky_relu=False):\n \"\"\"3x3 convolution with padding\"\"\"\n conv = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=dilation, groups=groups, bias=False, dilation=dilation)\n if with_bn_relu:\n relu = nn.LeakyReLU(0.2, inplace=True) if leaky_relu else nn.ReLU(inplace=True)\n conv = nn.Sequential(conv,\n nn.BatchNorm2d(out_planes),\n relu)\n return conv\n\n\ndef conv5x5(in_channels, out_channels, stride=2,\n dilation=1, use_bn=True):\n bias = False if use_bn else True\n conv = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=stride,\n padding=2, dilation=dilation, bias=bias)\n relu = nn.ReLU(inplace=True)\n if use_bn:\n out = nn.Sequential(conv,\n nn.BatchNorm2d(out_channels),\n relu)\n else:\n out = nn.Sequential(conv, relu)\n return out\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,\n base_width=64, dilation=1, norm_layer=None, leaky_relu=True):\n \"\"\"StereoNet uses leaky relu (alpha = 0.2)\"\"\"\n super(BasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv3x3(inplanes, planes, stride=stride, dilation=dilation)\n self.bn1 = norm_layer(planes)\n self.relu = nn.LeakyReLU(0.2, inplace=True) if leaky_relu else nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes, dilation=dilation)\n self.bn2 = norm_layer(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass StereoNetFeature(nn.Module):\n def __init__(self, num_downsample=3):\n \"\"\"Feature extractor of StereoNet\n Args:\n num_downsample: 2, 3 or 4\n \"\"\"\n super(StereoNetFeature, self).__init__()\n\n self.num_downsample = num_downsample\n\n downsample = nn.ModuleList()\n\n in_channels = 3\n out_channels = 32\n for _ in range(num_downsample):\n downsample.append(conv5x5(in_channels, out_channels))\n in_channels = 32\n\n self.downsample = nn.Sequential(*downsample)\n\n residual_blocks = nn.ModuleList()\n\n for _ in range(6):\n residual_blocks.append(BasicBlock(out_channels, out_channels))\n self.residual_blocks = nn.Sequential(*residual_blocks)\n\n # StereoNet has no bn and relu for last conv layer,\n self.final_conv = conv3x3(out_channels, out_channels)\n\n def forward(self, img):\n out = self.downsample(img) # [B, 32, H/8, W/8]\n out = self.residual_blocks(out) # [B, 32, H/8, W/8]\n out = self.final_conv(out) # [B, 32, H/8, W/8]\n\n return out\n\n\n# Used for PSMNet feature extractor\ndef convbn(in_planes, out_planes, kernel_size, stride, pad, dilation):\n return nn.Sequential(nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,\n padding=dilation if dilation > 1 else pad, dilation=dilation, bias=False),\n nn.BatchNorm2d(out_planes))\n\n\nclass PSMNetBasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride, downsample, pad, dilation):\n super(PSMNetBasicBlock, self).__init__()\n\n self.conv1 = nn.Sequential(convbn(inplanes, planes, 3, stride, pad, dilation),\n nn.ReLU(inplace=True))\n\n self.conv2 = convbn(planes, planes, 3, 1, pad, dilation)\n\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.conv2(out)\n\n if self.downsample is not None:\n x = self.downsample(x)\n\n out += x\n\n return out\n\n\nclass FeaturePyrmaid(nn.Module):\n def __init__(self, in_channel=32):\n super(FeaturePyrmaid, self).__init__()\n\n # self.conv48 = nn.Sequential(nn.Conv2d(128, in_channel, kernel_size=1, bias=False),\n # nn.BatchNorm2d(in_channel),\n # nn.ReLU(inplace=True))\n self.conv24 = nn.Sequential(nn.Conv2d(96, in_channel, kernel_size=1, bias=False),\n nn.BatchNorm2d(in_channel),\n nn.ReLU(inplace=True))\n self.conv12 = nn.Sequential(nn.Conv2d(64, in_channel, kernel_size=1, bias=False),\n nn.BatchNorm2d(in_channel),\n nn.ReLU(inplace=True))\n self.conv6 = nn.Sequential(nn.Conv2d(48, in_channel, kernel_size=1, bias=False),\n nn.BatchNorm2d(in_channel),\n nn.ReLU(inplace=True))\n\n self.out1 = nn.Sequential(nn.Conv2d(in_channel, in_channel * 2, kernel_size=3,\n stride=2, padding=1, bias=False),\n nn.BatchNorm2d(in_channel * 2),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(in_channel * 2, in_channel * 2, kernel_size=1,\n stride=1, padding=0, bias=False),\n nn.BatchNorm2d(in_channel * 2),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n self.out2 = nn.Sequential(nn.Conv2d(in_channel * 2, in_channel * 4, kernel_size=3,\n stride=2, padding=1, bias=False),\n nn.BatchNorm2d(in_channel * 4),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(in_channel * 4, in_channel * 4, kernel_size=1,\n stride=1, padding=0, bias=False),\n nn.BatchNorm2d(in_channel * 4),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n def forward(self, x):\n # x: [B, 32, H, W]\n # if x.size()[1] == 128:\n # x = self.conv48(x)\n if x.size()[1] == 96:\n x = self.conv24(x)\n elif x.size()[1] == 64:\n x = self.conv12(x)\n elif x.size()[1] == 48:\n x = self.conv6(x)\n\n out1 = self.out1(x) # [B, 64, H/2, W/2]\n out2 = self.out2(out1) # [B, 128, H/4, W/4]\n\n return [x, out1, out2]\n\n\nclass FeaturePyramidNetwork(nn.Module):\n def __init__(self, in_channels, out_channels=128,\n num_levels=3):\n # FPN paper uses 256 out channels by default\n super(FeaturePyramidNetwork, self).__init__()\n\n assert isinstance(in_channels, list)\n\n self.in_channels = in_channels\n\n self.lateral_convs = nn.ModuleList()\n self.fpn_convs = nn.ModuleList()\n\n for i in range(num_levels):\n lateral_conv = nn.Conv2d(in_channels[i], out_channels, 1)\n fpn_conv = nn.Sequential(\n nn.Conv2d(out_channels, out_channels, 3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True))\n\n self.lateral_convs.append(lateral_conv)\n self.fpn_convs.append(fpn_conv)\n\n # Initialize weights\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.xavier_uniform_(m.weight, gain=1)\n if hasattr(m, 'bias'):\n nn.init.constant_(m.bias, 0)\n\n def forward(self, inputs):\n # Inputs: resolution high -> low\n assert len(self.in_channels) == len(inputs)\n\n # Build laterals\n laterals = [lateral_conv(inputs[i])\n for i, lateral_conv in enumerate(self.lateral_convs)]\n\n # Build top-down path\n used_backbone_levels = len(laterals)\n for i in range(used_backbone_levels - 1, 0, -1):\n laterals[i - 1] += F.interpolate(\n laterals[i], scale_factor=2, mode='nearest')\n\n # Build outputs\n out = [\n self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels)\n ]\n\n return out\n\n\nclass PSMNetFeature(nn.Module):\n def __init__(self):\n super(PSMNetFeature, self).__init__()\n self.inplanes = 32\n\n self.firstconv = nn.Sequential(convbn(3, 32, 3, 2, 1, 1),\n nn.ReLU(inplace=True),\n convbn(32, 32, 3, 1, 1, 1),\n nn.ReLU(inplace=True),\n convbn(32, 32, 3, 1, 1, 1),\n nn.ReLU(inplace=True)) # H/2\n\n self.layer1 = self._make_layer(PSMNetBasicBlock, 32, 3, 1, 1, 1)\n self.layer2 = self._make_layer(PSMNetBasicBlock, 64, 16, 2, 1, 1) # H/4\n self.layer3 = self._make_layer(PSMNetBasicBlock, 128, 3, 1, 1, 1)\n self.layer4 = self._make_layer(PSMNetBasicBlock, 128, 3, 1, 1, 2)\n\n self.branch1 = nn.Sequential(nn.AvgPool2d((64, 64), stride=(64, 64)),\n convbn(128, 32, 1, 1, 0, 1),\n nn.ReLU(inplace=True))\n\n self.branch2 = nn.Sequential(nn.AvgPool2d((32, 32), stride=(32, 32)),\n convbn(128, 32, 1, 1, 0, 1),\n nn.ReLU(inplace=True))\n\n self.branch3 = nn.Sequential(nn.AvgPool2d((16, 16), stride=(16, 16)),\n convbn(128, 32, 1, 1, 0, 1),\n nn.ReLU(inplace=True))\n\n self.branch4 = nn.Sequential(nn.AvgPool2d((8, 8), stride=(8, 8)),\n convbn(128, 32, 1, 1, 0, 1),\n nn.ReLU(inplace=True))\n\n self.lastconv = nn.Sequential(convbn(320, 128, 3, 1, 1, 1),\n nn.ReLU(inplace=True),\n nn.Conv2d(128, 32, kernel_size=1, padding=0, stride=1, bias=False))\n\n def _make_layer(self, block, planes, blocks, stride, pad, dilation):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion), )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, pad, dilation))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, 1, None, pad, dilation))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n output = self.firstconv(x)\n output = self.layer1(output)\n output_raw = self.layer2(output)\n output = self.layer3(output_raw)\n output_skip = self.layer4(output)\n\n output_branch1 = self.branch1(output_skip)\n output_branch1 = F.interpolate(output_branch1, (output_skip.size()[2], output_skip.size()[3]), mode='bilinear', align_corners=False)\n\n output_branch2 = self.branch2(output_skip)\n output_branch2 = F.interpolate(output_branch2, (output_skip.size()[2], output_skip.size()[3]), mode='bilinear', align_corners=False)\n\n output_branch3 = self.branch3(output_skip)\n output_branch3 = F.interpolate(output_branch3, (output_skip.size()[2], output_skip.size()[3]), mode='bilinear', align_corners=False)\n\n output_branch4 = self.branch4(output_skip)\n output_branch4 = F.interpolate(output_branch4, (output_skip.size()[2], output_skip.size()[3]), mode='bilinear', align_corners=False)\n\n output_feature = torch.cat(\n (output_raw, output_skip, output_branch4, output_branch3, output_branch2, output_branch1), 1)\n output_feature = self.lastconv(output_feature) # [32, H/4, W/4]\n\n return output_feature\n\n\n# GANet feature\nclass BasicConv(nn.Module):\n\n def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, bn=True, relu=True, **kwargs):\n super(BasicConv, self).__init__()\n self.relu = relu\n self.use_bn = bn\n if is_3d:\n if deconv:\n self.conv = nn.ConvTranspose3d(in_channels, out_channels, bias=False, **kwargs)\n else:\n self.conv = nn.Conv3d(in_channels, out_channels, bias=False, **kwargs)\n self.bn = nn.BatchNorm3d(out_channels)\n else:\n if deconv:\n self.conv = nn.ConvTranspose2d(in_channels, out_channels, bias=False, **kwargs)\n else:\n self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)\n self.bn = nn.BatchNorm2d(out_channels)\n\n def forward(self, x):\n x = self.conv(x)\n if self.use_bn:\n x = self.bn(x)\n if self.relu:\n x = F.relu(x, inplace=True)\n return x\n\n\nclass Conv2x(nn.Module):\n\n def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, concat=True, bn=True, relu=True,\n mdconv=False):\n super(Conv2x, self).__init__()\n self.concat = concat\n\n if deconv and is_3d:\n kernel = (3, 4, 4)\n elif deconv:\n kernel = 4\n else:\n kernel = 3\n self.conv1 = BasicConv(in_channels, out_channels, deconv, is_3d, bn=True, relu=True, kernel_size=kernel,\n stride=2, padding=1)\n\n if self.concat:\n if mdconv:\n self.conv2 = DeformConv2d(out_channels * 2, out_channels, kernel_size=3, stride=1)\n else:\n self.conv2 = BasicConv(out_channels * 2, out_channels, False, is_3d, bn, relu, kernel_size=3,\n stride=1, padding=1)\n else:\n self.conv2 = BasicConv(out_channels, out_channels, False, is_3d, bn, relu, kernel_size=3, stride=1,\n padding=1)\n\n def forward(self, x, rem):\n x = self.conv1(x)\n assert (x.size() == rem.size())\n if self.concat:\n x = torch.cat((x, rem), 1)\n else:\n x = x + rem\n x = self.conv2(x)\n return x\n\n\nclass GANetFeature(nn.Module):\n \"\"\"Height and width need to be divided by 48, downsampled by 1/3\"\"\"\n\n def __init__(self, feature_mdconv=False):\n super(GANetFeature, self).__init__()\n print(\"++>> mdconv to use or not :\", feature_mdconv)\n if feature_mdconv:\n self.conv_start = nn.Sequential(\n BasicConv(3, 32, kernel_size=3, padding=1),\n BasicConv(32, 32, kernel_size=5, stride=3, padding=2),\n DeformConv2d(32, 32))\n else:\n self.conv_start = nn.Sequential(\n BasicConv(3, 32, kernel_size=3, padding=1),\n BasicConv(32, 32, kernel_size=5, stride=3, padding=2),\n BasicConv(32, 32, kernel_size=3, padding=1))\n\n self.conv1a = BasicConv(32, 48, kernel_size=3, stride=2, padding=1)\n self.conv2a = BasicConv(48, 64, kernel_size=3, stride=2, padding=1)\n\n if feature_mdconv:\n self.conv3a = DeformConv2d(64, 96, kernel_size=3, stride=2)\n self.conv4a = DeformConv2d(96, 128, kernel_size=3, stride=2)\n else:\n self.conv3a = BasicConv(64, 96, kernel_size=3, stride=2, padding=1)\n self.conv4a = BasicConv(96, 128, kernel_size=3, stride=2, padding=1)\n\n self.deconv4a = Conv2x(128, 96, deconv=True)\n self.deconv3a = Conv2x(96, 64, deconv=True)\n self.deconv2a = Conv2x(64, 48, deconv=True)\n self.deconv1a = Conv2x(48, 32, deconv=True)\n\n self.conv1b = Conv2x(32, 48)\n self.conv2b = Conv2x(48, 64)\n\n if feature_mdconv:\n self.conv3b = Conv2x(64, 96, mdconv=True)\n self.conv4b = Conv2x(96, 128, mdconv=True)\n else:\n self.conv3b = Conv2x(64, 96)\n self.conv4b = Conv2x(96, 128)\n\n self.deconv4b = Conv2x(128, 96, deconv=True)\n self.deconv3b = Conv2x(96, 64, deconv=True)\n self.deconv2b = Conv2x(64, 48, deconv=True)\n self.deconv1b = Conv2x(48, 32, deconv=True)\n\n def forward(self, x):\n x = self.conv_start(x)\n rem0 = x\n x = self.conv1a(x)\n rem1 = x\n x = self.conv2a(x)\n rem2 = x\n x = self.conv3a(x)\n rem3 = x\n x = self.conv4a(x)\n rem4 = x\n x = self.deconv4a(x, rem3)\n rem3 = x\n\n x = self.deconv3a(x, rem2)\n rem2 = x\n x = self.deconv2a(x, rem1)\n rem1 = x\n x = self.deconv1a(x, rem0)\n rem0 = x\n\n x = self.conv1b(x, rem1)\n rem1 = x\n x = self.conv2b(x, rem2)\n rem2 = x\n x = self.conv3b(x, rem3)\n rem3 = x\n # x = self.conv4b(x, rem4)\n #\n # x = self.deconv4b(x, rem3)\n # x = self.deconv3b(x, rem2)\n # x = self.deconv2b(x, rem1)\n # x = self.deconv1b(x, rem0) # [B, 32, H/3, W/3]\n #\n # return x\n x_48 = self.conv4b(x, rem4)\n\n x_24 = self.deconv4b(x_48, rem3)\n # if (p == -4):\n # return x\n x_12 = self.deconv3b(x_24, rem2)\n # if (p == -3):\n # return x\n x_6 = self.deconv2b(x_12, rem1)\n # if (p == -2):\n # return x\n x_3 = self.deconv1b(x_6, rem0)\n\n return [x_24, x_12, x_6, x_3]\n\n\nclass GCNetFeature(nn.Module):\n def __init__(self):\n super(GCNetFeature, self).__init__()\n\n self.inplanes = 32\n self.conv1 = conv5x5(3, 32)\n self.conv2 = self._make_layer(PSMNetBasicBlock, 32, 8, 1, 1, 1)\n self.conv3 = conv3x3(32, 32)\n\n def _make_layer(self, block, planes, blocks, stride, pad, dilation):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion), )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, pad, dilation))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, 1, None, pad, dilation))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x) # [32, H/2, W/2]\n\n return x\n" ]
[ [ "torch.nn.Sequential", "torch.nn.ConvTranspose2d", "torch.cat", "torch.nn.ConvTranspose3d", "torch.nn.init.constant_", "torch.nn.ModuleList", "torch.nn.Conv2d", "torch.nn.AvgPool2d", "torch.nn.functional.relu", "torch.nn.init.xavier_uniform_", "torch.nn.LeakyReLU", "torch.nn.functional.interpolate", "torch.nn.BatchNorm2d", "torch.nn.Conv3d", "torch.nn.ReLU", "torch.nn.BatchNorm3d" ] ]
FXDecroix/decroix_tech_test_dog
[ "53df869b2b2d570afe6c27ed87de48cb6d495cb4" ]
[ "multires_classif/train_multires.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport matplotlib.pyplot as plt\nfrom .set_dataset import load_dataset, split_augment_data\nfrom .set_model import setup_model\nfrom keras.utils import np_utils\nimport pickle\nimport argparse\n\ndef train_model(data_path, res_path, img_resolution, epochs=100, batch_size=32, save_weights=True, save_history=True):\n \n data, labels = load_dataset(data_path, img_resolution)\n #labels = np_utils.to_categorical(labels, num_classes=1)\n \n train_generator, val_generator, len_train, len_val = split_augment_data(data, labels, batch_size)\n \n model = setup_model(img_resolution)\n \n history = model.fit_generator(\n train_generator,\n steps_per_epoch=len_train/batch_size,\n epochs=epochs,\n validation_data=val_generator,\n validation_steps=len_val/batch_size)\n \n if save_weights==True:\n weights_filename = 'weights'+str(img_resolution)+'.h5'\n model.save_weights(os.path.join(res_path,weights_filename))\n if save_history==True:\n history_filename = 'history'+str(img_resolution)+'.p'\n with open(os.path.join(res_path,history_filename), 'wb') as file_pi:\n pickle.dump(history.history, file_pi)\n \n return model, history\n\ndef display_loss_acc_curves(histories, resolutions):\n \n loss_legend = []\n plt.figure(figsize=[8,6])\n for i in range(len(histories)):\n plt.plot(histories[i].history['loss'],linewidth=3.0)\n plt.plot(histories[i].history['val_loss'],linewidth=3.0)\n loss_legend.append('Validation Loss '+ str(resolutions[i]))\n loss_legend.append('Training Loss '+ str(resolutions[i]))\n plt.legend(loss_legend,fontsize=18)\n plt.xlabel('Epochs ',fontsize=16)\n plt.ylabel('Loss',fontsize=16)\n plt.title('Loss Curves',fontsize=16)\n \n acc_legend = []\n plt.figure(figsize=[8,6])\n for i in range(len(histories)):\n plt.plot(histories[i].history['acc'],linewidth=3.0)\n plt.plot(histories[i].history['val_acc'],linewidth=3.0)\n acc_legend.append('Validation Accuracy '+ str(resolutions[i]))\n acc_legend.append('Training accuracy '+ str(resolutions[i]))\n plt.legend(acc_legend,fontsize=18)\n plt.xlabel('Epochs ',fontsize=16)\n plt.ylabel('Loss',fontsize=16)\n plt.title('Accuracy Curves',fontsize=16)\n \n\nif __name__ == '__main__':\n \n # Parse arguments\n \n parser = argparse.ArgumentParser()\n parser.add_argument(\"data_path\", type=str, help=\"path to the data\")\n parser.add_argument(\"res_path\", type=str, help=\"path to the output directory\")\n parser.add_argument(\"-e\", \"--epochs\", type=int, help=\"number of epochs\",default=32)\n parser.add_argument(\"-b\", \"--batch_size\", type=int, help=\"batch_size\",default=100)\n \n args = parser.parse_args()\n data_path = args.data_path\n res_path = args.res_path\n epochs = args.epochs\n batch_size = args.batch_size\n \n # Train models\n\n model256, history256 = train_model(data_path, res_path, 256, epochs=epochs, batch_size=batch_size)\n model512, history512 = train_model(data_path, res_path, 512, epochs=epochs, batch_size=batch_size)\n\n histories = [history256, history512]\n resolutions = [256,512]\n\n # Display loss and accuracy\n \n display_loss_acc_curves(histories, resolutions)\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.ylabel" ] ]
johncolezhang/CV-Project
[ "4a51d5adb32e43962893fd75fe6d68c286875c02" ]
[ "solver.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\nfrom ops import *\nfrom data import *\nfrom net import *\nfrom utils import *\nimport os\nimport time\nimport data\nfrom restore import readfile\n\n\nflags = tf.app.flags\nconf = flags.FLAGS\nclass Solver(object):\n def __init__(self):\n self.device_id = conf.device_id\n self.train_dir = conf.train_dir\n self.samples_dir = conf.samples_dir\n if not os.path.exists(self.train_dir):\n os.makedirs(self.train_dir)\n if not os.path.exists(self.samples_dir):\n os.makedirs(self.samples_dir) \n #datasets params\n self.num_epoch = conf.num_epoch\n self.batch_size = conf.batch_size\n #optimizer parameter\n self.learning_rate = conf.learning_rate\n if conf.use_gpu:\n device_str = '/gpu:' + str(self.device_id)\n else:\n device_str = '/cpu:0'\n with tf.device(device_str):\n #dataset\n self.dataset = DataSet(conf.imgs_list_path, self.num_epoch, self.batch_size)\n self.net = Net(self.dataset.hr_images, self.dataset.lr_images, 'prsr')\n #optimizer\n self.global_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False)\n # decay every 500000 steps with a base of 0.5\n learning_rate = tf.train.exponential_decay(self.learning_rate, self.global_step,\n 500000, 0.5, staircase=True)\n optimizer = tf.train.RMSPropOptimizer(learning_rate, decay=0.95, momentum=0.9, epsilon=1e-8)\n self.train_op = optimizer.minimize(self.net.loss, global_step=self.global_step)\n\n\n def train(self):\n init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\n summary_op = tf.summary.merge_all()\n saver = tf.train.Saver()\n # Create a session for running operations in the Graph.\n config = tf.ConfigProto(allow_soft_placement=True)\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n\n # Initialize the variables (like the epoch counter).\n sess.run(init_op)\n saver.restore(sess, \"../models/model.ckpt-30000\")\n summary_writer = tf.summary.FileWriter(self.train_dir, sess.graph)\n # Start input enqueue threads.\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n iters = 0\n try:\n while not coord.should_stop():\n # Run training steps or whatever\n t1 = time.time()\n _, loss = sess.run([self.train_op, self.net.loss], feed_dict={self.net.train: True})\n t2 = time.time()\n print('step %d, loss = %.2f (%.1f examples/sec; %.3f sec/batch)' % ((iters, loss, self.batch_size/(t2-t1), (t2-t1))))\n # self.sample(sess, mu=1.1, step=iters)\n iters += 1\n if iters % 10 == 0:\n summary_str = sess.run(summary_op, feed_dict={self.net.train: True})\n summary_writer.add_summary(summary_str, iters)\n if iters % 1 == 0:\n #self.sample(sess, mu=1.0, step=iters)\n self.sample(sess, mu=1.1, step=iters)\n #self.sample(sess, mu=100, step=iters)\n if iters % 10000 == 0:\n checkpoint_path = os.path.join(self.train_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=iters)\n except tf.errors.OutOfRangeError:\n checkpoint_path = os.path.join(self.train_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path)\n print('Done training -- epoch limit reached')\n finally:\n # When done, ask the threads to stop.\n coord.request_stop()\n\n # Wait for threads to finish.\n coord.join(threads)\n sess.close()\n\n def predict(self):\n init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\n saver = tf.train.Saver()\n # Create a session for running operations in the Graph.\n config = tf.ConfigProto(allow_soft_placement=True)\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n sess.run(init_op)\n\n saver.restore(sess, \"../models/model.ckpt-30000\")\n\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n try:\n self.sample(sess, mu=1.1, step=0)\n except tf.errors.OutOfRangeError:\n checkpoint_path = os.path.join(self.train_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path)\n print('Done training -- epoch limit reached')\n finally:\n # When done, ask the threads to stop.\n coord.request_stop()\n\n # Start input enqueue threads.\n # coord = tf.train.Coordinator()\n # threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n\n # t1 = time.time()\n # _, loss = sess.run([self.train_op, self.net.loss], feed_dict={self.net.train: True})\n # t2 = time.time()\n # print('loss = %.2f (%.1f examples/sec; %.3f sec/batch)' % (loss, self.batch_size / (t2 - t1), (t2 - t1)))\n\n # image_path = \"../data/000063.jpg\"\n # filename_queue = tf.train.string_input_producer([image_path])\n # reader = tf.WholeFileReader()\n # key, value = reader.read(filename_queue)\n # my_img = tf.image.decode_jpeg(value, 3)\n # hr_imgs = tf.image.resize_images(my_img, [32, 32])\n # lr_imgs = tf.image.resize_images(my_img, [8, 8])\n # hr_imgs = tf.cast(hr_imgs, tf.float32)\n # lr_imgs = tf.cast(lr_imgs, tf.float32)\n\n\n # np_lr_imgs = mpimg.imread(image_path)\n # np_lr_imgs = np_lr_imgs.reshape([32, 32, 3])\n # np_lr_imgs = np.resize(np_lr_imgs, [8, 8, 3]).astype(np.float32)\n #\n # np_lr = []\n # for _ in range(32):\n # np_lr.append(np_lr_imgs)\n # np_lr_imgs = np.array(np_lr)\n\n # min_after_dequeue = 1000\n # capacity = min_after_dequeue + 400 * 32\n # hr_imgs, lr_imgs = tf.train.shuffle_batch([hr_imgs, lr_imgs],\n # batch_size=32, capacity=capacity,\n # min_after_dequeue=min_after_dequeue)\n #\n # np_hr_imgs, np_lr_imgs = sess.run([hr_imgs, lr_imgs])\n #\n # # hr_imgs, lr_imgs, np_hr_imgs, np_lr_imgs = readfile()\n #\n #\n # c_logits = self.net.conditioning_logits\n # p_logits = self.net.prior_logits\n #\n # np_c_logits = sess.run(c_logits, feed_dict={lr_imgs: np_lr_imgs, self.train: False})\n # gen_hr_imgs = np.zeros((1, 32, 32, 3), dtype=np.float32)\n # for i in range(32):\n # for j in range(32):\n # for c in range(3):\n # np_p_logits = sess.run(p_logits, feed_dict={hr_imgs: gen_hr_imgs})\n # new_pixel = logits_2_pixel_value(np_c_logits[:, i, j, c*256:(c+1)*256] + np_p_logits[:, i, j, c*256:(c+1)*256], mu=1.1)\n # gen_hr_imgs[:, i, j, c] = new_pixel\n #\n # coord.join(threads)\n # sess.close()\n\n\n\n\n def sample(self, sess, mu=1.1, step=None):\n c_logits = self.net.conditioning_logits\n p_logits = self.net.prior_logits\n lr_imgs = self.dataset.lr_images\n hr_imgs = self.dataset.hr_images\n np_hr_imgs, np_lr_imgs = sess.run([hr_imgs, lr_imgs])\n gen_hr_imgs = np.zeros((self.batch_size, 32, 32, 3), dtype=np.float32)\n #gen_hr_imgs = np_hr_imgs\n #gen_hr_imgs[:,16:,16:,:] = 0.0\n np_c_logits = sess.run(c_logits, feed_dict={lr_imgs: np_lr_imgs, self.train:False})\n print('iters %d: ' % step)\n \n for i in range(32):\n for j in range(32):\n for c in range(3):\n np_p_logits = sess.run(p_logits, feed_dict={hr_imgs: gen_hr_imgs})\n new_pixel = logits_2_pixel_value(np_c_logits[:, i, j, c*256:(c+1)*256] + np_p_logits[:, i, j, c*256:(c+1)*256], mu=mu)\n gen_hr_imgs[:, i, j, c] = new_pixel\n #\n save_samples(np_lr_imgs, self.samples_dir + '/lr_' + str(mu*10) + '_' + str(step) + '.jpg')\n save_samples(np_hr_imgs, self.samples_dir + '/hr_' + str(mu*10) + '_' + str(step) + '.jpg')\n save_samples(gen_hr_imgs, self.samples_dir + '/generate_' + str(mu*10) + '_' + str(step) + '.jpg')\n\n" ]
[ [ "tensorflow.device", "tensorflow.summary.FileWriter", "tensorflow.local_variables_initializer", "tensorflow.train.RMSPropOptimizer", "tensorflow.train.start_queue_runners", "tensorflow.train.Coordinator", "tensorflow.train.exponential_decay", "tensorflow.ConfigProto", "tensorflow.global_variables_initializer", "tensorflow.constant_initializer", "tensorflow.summary.merge_all", "tensorflow.Session", "tensorflow.train.Saver", "numpy.zeros" ] ]
AaronGrainer/yolact-instance-segmentation
[ "8ea515ae0d0cdecb46aaff2732fe33f8c34a5fd1" ]
[ "yolact.py" ]
[ "import tensorflow as tf\n\nfrom layers.fpn import FeaturePyramidNeck\nfrom layers.head import PredictionModule\nfrom layers.protonet import ProtoNet\nfrom utils.create_prior import make_priors\n\nassert tf.__version__.startswith('2')\n\n\nclass Yolact(tf.keras.Model):\n \"\"\"Creating the YOLCAT Architecture\"\"\"\n\n def __init__(self, input_size, fpn_channels, feature_map_size, num_class, num_mask, aspect_ratio, scales):\n super(Yolact, self).__init__()\n out = ['conv3_block4_out', 'conv4_block6_out', 'conv5_block3_out']\n # use pre-trained ResNet50\n # TODO figure out how pre-trained can be train again\n base_model = tf.keras.applications.ResNet50(input_shape=(550, 550, 3),\n include_top=False,\n layers=tf.keras.layers,\n weights='imagenet')\n\n # Extract certain feature maps for FPN\n self.backbone_resnet = tf.keras.Model(inputs=base_model.input,\n outputs=[base_model.get_layer(x).output for x in out])\n self.backbone_fpn = FeaturePyramidNeck(fpn_channels)\n self.protonet = ProtoNet(num_mask)\n\n # Semantic segmentation branch to boost feature richness\n self.semantic_segmentation = tf.keras.layers.Conv2D(num_class, (1, 1), 1, padding=\"same\",\n kernel_initializer=tf.keras.initializers.glorot_uniform())\n\n self.num_anchor, self.priors = make_priors(\n input_size, feature_map_size, aspect_ratio, scales)\n print(\"prior shape:\", self.priors.shape)\n print(\"num anchor per feature map: \", self.num_anchor)\n\n # Shared prediction head\n self.predictionHead = PredictionModule(\n 256, len(aspect_ratio), num_class, num_mask)\n\n def set_bn(self, mode='train'):\n if mode == 'train':\n for layer in self.backbone_resnet.layers:\n if isinstance(layer, tf.keras.layers.BatchNormalization):\n layer.trainable = False\n else:\n for layer in self.backbone_resnet.layers:\n if isinstance(layer, tf.keras.layers.BatchNormalization):\n layer.trainable = True\n\n def call(self, inputs):\n # backbone(ResNet + FPN)\n c3, c4, c5 = self.backbone_resnet(inputs)\n # print(\"c3: \", c3.shape)\n # print(\"c4: \", c4.shape)\n # print(\"c5: \", c5.shape)\n fpn_out = self.backbone_fpn(c3, c4, c5)\n\n # Protonet branch\n p3 = fpn_out[0]\n protonet_out = self.protonet(p3)\n # print(\"protonet: \", protonet_out.shape)\n\n # Semantic segmentation branch\n seg = self.semantic_segmentation(p3)\n\n # Prediction Head branch\n pred_cls = []\n pred_offset = []\n pred_mask_coef = []\n\n # All output from FPN use same prediction head\n for f_map in fpn_out:\n cls, offset, coef = self.predictionHead(f_map)\n pred_cls.append(cls)\n pred_offset.append(offset)\n pred_mask_coef.append(coef)\n\n pred_cls = tf.concat(pred_cls, axis=1)\n pred_offset = tf.concat(pred_offset, axis=1)\n pred_mask_coef = tf.concat(pred_mask_coef, axis=1)\n\n pred = {\n 'pred_cls': pred_cls,\n 'pred_offset': pred_offset,\n 'pred_mask_coef': pred_mask_coef,\n 'proto_out': protonet_out,\n 'seg': seg\n }\n\n return pred\n" ]
[ [ "tensorflow.keras.applications.ResNet50", "tensorflow.concat", "tensorflow.__version__.startswith", "tensorflow.keras.initializers.glorot_uniform" ] ]
KevinQian97/actionpose-release
[ "0bf7ae1c30d1b2a1a6a18fc662e22da519d41e0c" ]
[ "ops/transforms.py" ]
[ "import torchvision\nimport random\nfrom PIL import Image, ImageOps\nimport numpy as np\nimport numbers\nimport math\nimport torch\nimport os\n\nclass ChannelFlip(object):\n\n def __call__(self, vid):\n return vid.permute(3, 0, 1, 2)\n\nclass Resize(object):\n '''\n Resize the input tensor clipped images to the given size\n '''\n\n def __init__(self, size):\n self.size = size\n\n def resize(self, vid, size, interpolation='bilinear'):\n # NOTE: using bilinear interpolation because we don't work on minibatches\n # at this level\n scale = None\n if isinstance(size, int):\n scale = float(size) / min(vid.shape[-2:])\n size = None\n return torch.nn.functional.interpolate(\n vid, size=size, scale_factor=scale, mode=interpolation, align_corners=False)\n\n def __call__(self, vid):\n return self.resize(vid, self.size)\n\nclass CenterCrop(object):\n def __init__(self, size):\n self.size = size\n\n def crop(self, vid, i, j, h, w):\n return vid[..., i:(i + h), j:(j + w)]\n\n def center_crop(self, vid, output_size):\n h, w = vid.shape[-2:]\n th, tw = output_size\n\n i = int(round((h - th) / 2.))\n j = int(round((w - tw) / 2.))\n return self.crop(vid, i, j, th, tw)\n\n def __call__(self, vid):\n return self.center_crop(vid, self.size)\n\nclass Normalize(object):\n def __init__(self, mean, std, div=False):\n self.mean = torch.as_tensor(mean)\n self.std = torch.as_tensor(std)\n self.div = div\n\n def __call__(self, vid_batch):\n if self.div:\n vid_batch.div_(255.0)\n vid_batch.sub_(self.mean.view(-1, 1, 1, 1)).div_(\n self.std.view(-1, 1, 1, 1))\n return vid_batch\n\nclass GroupRandomCrop(object):\n def __init__(self, size):\n if isinstance(size, numbers.Number):\n self.size = (int(size), int(size))\n else:\n self.size = size\n\n def __call__(self, img_group):\n\n w, h = img_group[0].size\n th, tw = self.size\n\n out_images = list()\n\n x1 = random.randint(0, w - tw)\n y1 = random.randint(0, h - th)\n\n for img in img_group:\n assert(img.size[0] == w and img.size[1] == h)\n if w == tw and h == th:\n out_images.append(img)\n else:\n out_images.append(img.crop((x1, y1, x1 + tw, y1 + th)))\n\n return out_images\n\n\nclass GroupCenterCrop(object):\n def __init__(self, size):\n self.worker = torchvision.transforms.CenterCrop(size)\n\n def __call__(self, img_group):\n return [self.worker(img) for img in img_group]\n\n\nclass GroupRandomHorizontalFlip(object):\n \"\"\"Randomly horizontally flips the given PIL.Image with a probability of 0.5\n \"\"\"\n def __init__(self, is_flow=False):\n self.is_flow = is_flow\n\n def __call__(self, img_group, is_flow=False):\n v = random.random()\n if v < 0.5:\n ret = [img.transpose(Image.FLIP_LEFT_RIGHT) for img in img_group]\n if self.is_flow:\n for i in range(0, len(ret), 2):\n ret[i] = ImageOps.invert(ret[i]) # invert flow pixel values when flipping\n return ret\n else:\n return img_group\n\n\nclass GroupNormalize(object):\n def __init__(self, mean, std):\n self.mean = mean\n self.std = std\n\n def __call__(self, tensor):\n rep_mean = self.mean * (tensor.size()[0]//len(self.mean))\n rep_std = self.std * (tensor.size()[0]//len(self.std))\n\n # TODO: make efficient\n for t, m, s in zip(tensor, rep_mean, rep_std):\n t.sub_(m).div_(s)\n\n return tensor\n\nclass ToFloatTensorInZeroOne(object):\n def __call__(self, img_group):\n res = []\n for x in img_group:\n res.append(x)\n return to_normalized_float_tensor(torch.from_numpy(np.array(res)))\n \n\nclass GroupScale(object):\n \"\"\" Rescales the input PIL.Image to the given 'size'.\n 'size' will be the size of the smaller edge.\n For example, if height > width, then image will be\n rescaled to (size * height / width, size)\n size: size of the smaller edge\n interpolation: Default: PIL.Image.BILINEAR\n \"\"\"\n\n def __init__(self, size, interpolation=Image.BILINEAR):\n self.worker = torchvision.transforms.Resize(size, interpolation)\n\n def __call__(self, img_group):\n return [self.worker(img) for img in img_group]\n\n\nclass GroupOverSample(object):\n def __init__(self, crop_size, scale_size=None, flip=True):\n self.crop_size = crop_size if not isinstance(crop_size, int) else (crop_size, crop_size)\n\n if scale_size is not None:\n self.scale_worker = GroupScale(scale_size)\n else:\n self.scale_worker = None\n self.flip = flip\n\n def __call__(self, img_group):\n\n if self.scale_worker is not None:\n img_group = self.scale_worker(img_group)\n\n image_w, image_h = img_group[0].size\n crop_w, crop_h = self.crop_size\n\n offsets = GroupMultiScaleCrop.fill_fix_offset(False, image_w, image_h, crop_w, crop_h)\n oversample_group = list()\n for o_w, o_h in offsets:\n normal_group = list()\n flip_group = list()\n for i, img in enumerate(img_group):\n crop = img.crop((o_w, o_h, o_w + crop_w, o_h + crop_h))\n normal_group.append(crop)\n flip_crop = crop.copy().transpose(Image.FLIP_LEFT_RIGHT)\n\n if img.mode == 'L' and i % 2 == 0:\n flip_group.append(ImageOps.invert(flip_crop))\n else:\n flip_group.append(flip_crop)\n\n oversample_group.extend(normal_group)\n if self.flip:\n oversample_group.extend(flip_group)\n return oversample_group\n\n\nclass GroupFullResSample(object):\n def __init__(self, crop_size, scale_size=None, flip=True):\n self.crop_size = crop_size if not isinstance(crop_size, int) else (crop_size, crop_size)\n\n if scale_size is not None:\n self.scale_worker = GroupScale(scale_size)\n else:\n self.scale_worker = None\n self.flip = flip\n\n def __call__(self, img_group):\n\n if self.scale_worker is not None:\n img_group = self.scale_worker(img_group)\n\n image_w, image_h = img_group[0].size\n crop_w, crop_h = self.crop_size\n\n w_step = (image_w - crop_w) // 4\n h_step = (image_h - crop_h) // 4\n\n offsets = list()\n offsets.append((0 * w_step, 2 * h_step)) # left\n offsets.append((4 * w_step, 2 * h_step)) # right\n offsets.append((2 * w_step, 2 * h_step)) # center\n\n oversample_group = list()\n for o_w, o_h in offsets:\n normal_group = list()\n flip_group = list()\n for i, img in enumerate(img_group):\n crop = img.crop((o_w, o_h, o_w + crop_w, o_h + crop_h))\n normal_group.append(crop)\n if self.flip:\n flip_crop = crop.copy().transpose(Image.FLIP_LEFT_RIGHT)\n\n if img.mode == 'L' and i % 2 == 0:\n flip_group.append(ImageOps.invert(flip_crop))\n else:\n flip_group.append(flip_crop)\n\n oversample_group.extend(normal_group)\n oversample_group.extend(flip_group)\n return oversample_group\n\n\nclass GroupMultiScaleCrop(object):\n\n def __init__(self, input_size, scales=None, max_distort=1, fix_crop=True, more_fix_crop=True):\n self.scales = scales if scales is not None else [1, .875, .75, .66]\n self.max_distort = max_distort\n self.fix_crop = fix_crop\n self.more_fix_crop = more_fix_crop\n self.input_size = input_size if not isinstance(input_size, int) else [input_size, input_size]\n self.interpolation = Image.BILINEAR\n\n def __call__(self, img_group):\n\n im_size = img_group[0].size\n\n crop_w, crop_h, offset_w, offset_h = self._sample_crop_size(im_size)\n crop_img_group = [img.crop((offset_w, offset_h, offset_w + crop_w, offset_h + crop_h)) for img in img_group]\n ret_img_group = [img.resize((self.input_size[0], self.input_size[1]), self.interpolation)\n for img in crop_img_group]\n return ret_img_group\n\n def _sample_crop_size(self, im_size):\n image_w, image_h = im_size[0], im_size[1]\n\n # find a crop size\n base_size = min(image_w, image_h)\n crop_sizes = [int(base_size * x) for x in self.scales]\n crop_h = [self.input_size[1] if abs(x - self.input_size[1]) < 3 else x for x in crop_sizes]\n crop_w = [self.input_size[0] if abs(x - self.input_size[0]) < 3 else x for x in crop_sizes]\n\n pairs = []\n for i, h in enumerate(crop_h):\n for j, w in enumerate(crop_w):\n if abs(i - j) <= self.max_distort:\n pairs.append((w, h))\n\n crop_pair = random.choice(pairs)\n if not self.fix_crop:\n w_offset = random.randint(0, image_w - crop_pair[0])\n h_offset = random.randint(0, image_h - crop_pair[1])\n else:\n w_offset, h_offset = self._sample_fix_offset(image_w, image_h, crop_pair[0], crop_pair[1])\n\n return crop_pair[0], crop_pair[1], w_offset, h_offset\n\n def _sample_fix_offset(self, image_w, image_h, crop_w, crop_h):\n offsets = self.fill_fix_offset(self.more_fix_crop, image_w, image_h, crop_w, crop_h)\n return random.choice(offsets)\n\n @staticmethod\n def fill_fix_offset(more_fix_crop, image_w, image_h, crop_w, crop_h):\n w_step = (image_w - crop_w) // 4\n h_step = (image_h - crop_h) // 4\n\n ret = list()\n ret.append((0, 0)) # upper left\n ret.append((4 * w_step, 0)) # upper right\n ret.append((0, 4 * h_step)) # lower left\n ret.append((4 * w_step, 4 * h_step)) # lower right\n ret.append((2 * w_step, 2 * h_step)) # center\n\n if more_fix_crop:\n ret.append((0, 2 * h_step)) # center left\n ret.append((4 * w_step, 2 * h_step)) # center right\n ret.append((2 * w_step, 4 * h_step)) # lower center\n ret.append((2 * w_step, 0 * h_step)) # upper center\n\n ret.append((1 * w_step, 1 * h_step)) # upper left quarter\n ret.append((3 * w_step, 1 * h_step)) # upper right quarter\n ret.append((1 * w_step, 3 * h_step)) # lower left quarter\n ret.append((3 * w_step, 3 * h_step)) # lower righ quarter\n\n return ret\n\n\nclass GroupRandomSizedCrop(object):\n \"\"\"Random crop the given PIL.Image to a random size of (0.08 to 1.0) of the original size\n and and a random aspect ratio of 3/4 to 4/3 of the original aspect ratio\n This is popularly used to train the Inception networks\n size: size of the smaller edge\n interpolation: Default: PIL.Image.BILINEAR\n \"\"\"\n def __init__(self, size, interpolation=Image.BILINEAR):\n self.size = size\n self.interpolation = interpolation\n\n def __call__(self, img_group):\n for attempt in range(10):\n area = img_group[0].size[0] * img_group[0].size[1]\n target_area = random.uniform(0.08, 1.0) * area\n aspect_ratio = random.uniform(3. / 4, 4. / 3)\n\n w = int(round(math.sqrt(target_area * aspect_ratio)))\n h = int(round(math.sqrt(target_area / aspect_ratio)))\n\n if random.random() < 0.5:\n w, h = h, w\n\n if w <= img_group[0].size[0] and h <= img_group[0].size[1]:\n x1 = random.randint(0, img_group[0].size[0] - w)\n y1 = random.randint(0, img_group[0].size[1] - h)\n found = True\n break\n else:\n found = False\n x1 = 0\n y1 = 0\n\n if found:\n out_group = list()\n for img in img_group:\n img = img.crop((x1, y1, x1 + w, y1 + h))\n assert(img.size == (w, h))\n out_group.append(img.resize((self.size, self.size), self.interpolation))\n return out_group\n else:\n # Fallback\n scale = GroupScale(self.size, interpolation=self.interpolation)\n crop = GroupRandomCrop(self.size)\n return crop(scale(img_group))\n\n\n\nclass Stack(object):\n\n def __init__(self, roll=False, inc_dim = False):\n self.roll = roll\n self.inc_dim = inc_dim\n\n def __call__(self, img_group):\n if img_group[0].mode == 'L':\n return np.concatenate([np.expand_dims(x, 2) for x in img_group], axis=2)\n elif img_group[0].mode == 'RGB':\n if self.inc_dim:\n res = []\n for x in img_group:\n res.append(np.array(x))\n return np.array(res)\n else:\n if self.roll:\n return np.concatenate([np.array(x)[:, :, ::-1] for x in img_group], axis=2)\n else:\n return np.concatenate(img_group, axis=2)\n\n# class Stack(object):\n\n# def __init__(self, roll=False, inc_dim = False):\n# self.roll = roll\n# self.inc_dim = inc_dim\n\n# def __call__(self, img_group):\n# if img_group[0].mode == 'L':\n# return np.concatenate([np.expand_dims(x, 2) for x in img_group], axis=2)\n# elif img_group[0].mode == 'RGB':\n# if self.roll:\n# return np.concatenate([np.array(x)[:, :, ::-1] for x in img_group], axis=2)\n# elif self.inc_dim:\n# res = []\n# for x in img_group:\n# res.append(np.array(x))\n# return np.array(res)\n# else:\n# return np.concatenate(img_group, axis=2)\n\n\nclass ToTorchFormatTensor(object):\n \"\"\" Converts a PIL.Image (RGB) or numpy.ndarray (H x W x C) in the range [0, 255]\n to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] \"\"\"\n def __init__(self, div=True,inc_dim = False):\n self.div = div\n self.inc_dim = inc_dim\n\n def __call__(self, pic):\n if isinstance(pic, np.ndarray):\n # handle numpy array\n if self.inc_dim:\n img = torch.from_numpy(pic).permute(3, 0, 1, 2).contiguous()\n else:\n img = torch.from_numpy(pic).permute(2, 0, 1).contiguous()\n\n else:\n # handle PIL Image\\\n raise RuntimeError(\"should first stack\")\n img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes()))\n img = img.view(pic.size[1], pic.size[0], len(pic.mode))\n # put it from HWC to CHW format\n # yikes, this transpose takes 80% of the loading time/CPU\n img = img.transpose(0, 1).transpose(0, 2).contiguous()\n return img.to(torch.float32) / 255 if self.div else img.float()\n\n\nclass IdentityTransform(object):\n\n def __call__(self, data):\n return data\n\n\nif __name__ == \"__main__\":\n\n idxs = np.arange(1,10)\n path = \"/data/yijunq/kinetics/imgs/writing/zVY3FB-8K_Q_000316_000326\"\n images = list()\n image_tmpl = 'img_{:05d}.jpg'\n transfomr = torchvision.transforms.Compose([GroupScale([171,128]),\n GroupRandomHorizontalFlip(is_flow=False),\n GroupCenterCrop(112),\n Stack(inc_dim=True)])\n\n for idx in idxs:\n im = [Image.open(os.path.join(path, image_tmpl.format(idx))).convert('RGB')]\n images.extend(im)\n process_data = transfomr(images)\n im = Image.fromarray(process_data[0])\n im.save(\"vis.jpg\")\n print(len(images))\n print(transfomr(images).shape)" ]
[ [ "numpy.expand_dims", "numpy.arange", "torch.from_numpy", "numpy.concatenate", "torch.nn.functional.interpolate", "numpy.array", "torch.as_tensor" ] ]
peterbednar/dlgen
[ "7257dc0d75bed0785c1345807a0db77305986653" ]
[ "dlgen/distance.py" ]
[ "import heapq\nimport numpy as np\n\nfrom conllutils import FORM\nfrom conllutils import Sentence, DependencyTree, Instance\nfrom conllutils import _parse_feats\n\n\nDEL = \"del\"\nINS = \"ins\"\nSUB = \"sub\"\nTRN = \"trn\"\n\n\ndef _normalize(dist, n, m):\n return 2*dist / (n + m + dist) if dist != 0 else 0\n\n\ndef default_token_cost(t1, t2, opr):\n if opr == DEL:\n return 1 # insertion\n if opr == INS:\n return 1 # deletion\n if opr == TRN:\n return 1 # transposition\n return 0 if t1[FORM] == t2[FORM] else 1 # substitution\n\n\ndef levenshtein_distance(s1, s2, cost=default_token_cost, damerau=False, normalize=False, return_oprs=False):\n def _equals(t1, t2):\n return cost(t1, t2, SUB) == 0\n\n if isinstance(s1, Instance):\n s1 = list(s1.tokens())\n if isinstance(s2, Instance):\n s2 = list(s2.tokens())\n\n n = len(s1)\n m = len(s2)\n d = np.zeros((n + 1, m + 1), dtype=np.float)\n\n for i in range(1, n + 1):\n d[i, 0] = d[i-1, 0] + cost(s1[i-1], None, DEL) # deletion\n for j in range(1, m + 1):\n d[0, j] = d[0, j-1] + cost(None, s2[j-1], INS) # insertion\n\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n d[i, j] = min(\n d[i-1, j] + cost(s1[i-1], None, DEL), # deletion\n d[i, j-1] + cost(None, s2[j-1], INS), # insertion\n d[i-1, j-1] + cost(s1[i-1], s2[j-1], SUB) # substitution\n )\n if damerau and i > 1 and j > 1 and _equals(s1[i-1], s2[j-2]) and _equals(s1[i-2], s2[i-1]):\n d[i, j] = min(\n d[i, j],\n d[i-2, j-2] + cost(s1[i-2], s2[i-2], TRN) # transposition\n )\n if not return_oprs:\n if normalize:\n return _normalize(d[n, m], n, m)\n else:\n return d[n, m]\n\n i = n\n j = m\n oprs = []\n while i > 0 or j > 0:\n neighbours = []\n if damerau and i > 1 and j > 1 and _equals(s1[i-1], s2[j-2]) and _equals(s1[i-2], s2[i-1]):\n neighbours.append((TRN, i-2, j-2))\n if i > 0 and j > 0:\n neighbours.append((SUB, i-1, j-1))\n if j > 0:\n neighbours.append((INS, i, j-1))\n if i > 0:\n neighbours.append((DEL, i-1, j))\n opr = min(neighbours, key=lambda x: d[x[1], x[2]])\n if d[opr[1], opr[2]] != d[i, j]:\n if opr[0] == DEL:\n oprs.append((DEL, opr[1]))\n elif opr[0] == INS:\n oprs.append((INS, opr[2]))\n else:\n oprs.append(opr)\n i = opr[1]\n j = opr[2]\n oprs.reverse()\n\n if normalize:\n return _normalize(d[n, m], n, m), oprs\n else:\n return d[n, m], oprs\n\n\nclass _AnnotatedNode(object):\n\n def __init__(self, node):\n self.node = node\n self.index = -1\n self.leftmost = None\n self.children = []\n\n def collect(self):\n return self._collect([], [])\n\n def _collect(self, nodes, l):\n for child in self.children:\n nodes, l = child._collect(nodes, l)\n nodes.append(self.node)\n l.append(self.leftmost.index)\n return nodes, l\n\n @staticmethod\n def build(node, index=0):\n anode = _AnnotatedNode(node)\n for child in node:\n achild = _AnnotatedNode.build(child, index)\n index = achild.index + 1\n anode.children.append(achild)\n anode.index = index\n if anode.children:\n anode.leftmost = anode.children[0].leftmost\n else:\n anode.leftmost = anode\n return anode\n\n\ndef _annotate(root):\n if root is None:\n return [], [], []\n nodes, l = _AnnotatedNode.build(root).collect()\n keyroots = []\n n = len(l)\n for i in range(n):\n is_root = True\n for j in range(i + 1, n):\n if l[i] == l[j]:\n is_root = False\n break\n if is_root:\n keyroots.append(i)\n return nodes, l, keyroots\n\n\ndef _treedist(i, j, l1, l2, nodes1, nodes2, TD, TD_oprs, cost, return_oprs):\n\n def _merge(x1, y1, x2, y2, l):\n d_oprs[x1, y1] = d_oprs[x2, y2] + l\n\n n = i - l1[i] + 2\n m = j - l2[j] + 2\n d = np.zeros((n, m), dtype=np.float)\n if return_oprs:\n d_oprs = np.empty((n, m), dtype=np.object)\n d_oprs.fill([])\n i_off = l1[i] - 1\n j_off = l2[j] - 1\n\n for x in range(1, n):\n d[x, 0] = d[x-1, 0] + cost(nodes1[x+i_off], None, DEL) # delete\n if return_oprs:\n _merge(x, 0, x-1, 0, [(DEL, x+i_off)])\n\n for y in range(1, m):\n d[0, y] = d[0, y-1] + cost(None, nodes2[y+j_off], INS) # insert\n if return_oprs:\n _merge(0, y, 0, y-1, [(INS, y+j_off)])\n\n for x in range(1, n):\n for y in range(1, m):\n xi = x + i_off\n yj = y + j_off\n if l1[i] == l1[xi] and l2[j] == l2[yj]:\n costs = (\n d[x-1, y] + cost(nodes1[xi], None, DEL), # delete\n d[x, y-1] + cost(None, nodes2[yj], INS), # insert\n d[x-1, y-1] + cost(nodes1[xi], nodes2[yj], SUB) # substitute\n )\n min_cost = min(costs)\n d[x, y] = min_cost\n TD[xi, yj] = d[x, y]\n if return_oprs:\n if min_cost == costs[0]:\n _merge(x, y, x-1, y, [(DEL, xi)])\n elif min_cost == costs[1]:\n _merge(x, y, x, y-1, [(INS, yj)])\n else:\n opr = [(SUB, xi, yj)] if d[x, y] != d[x-1, y-1] else []\n _merge(x, y, x-1, y-1, opr)\n TD_oprs[xi, yj] = d_oprs[x, y]\n else:\n x_tmp = l1[xi]-1-i_off\n y_tmp = l2[yj]-1-j_off\n costs = (\n d[x-1, y] + cost(nodes1[xi], None, DEL),\n d[x, y-1] + cost(None, nodes2[yj], INS),\n d[x_tmp, y_tmp] + TD[xi, yj]\n )\n min_cost = min(costs)\n d[x, y] = min_cost\n if return_oprs:\n if min_cost == costs[0]:\n _merge(x, y, x-1, y, [(DEL, xi)])\n elif min_cost == costs[1]:\n _merge(x, y, x, y-1, [(INS, yj)])\n else:\n _merge(x, y, x_tmp, y_tmp, TD_oprs[xi, yj])\n\n\ndef default_node_cost(n1, n2, opr):\n t1 = None if n1 is None else n1.token\n t2 = None if n2 is None else n2.token\n return default_token_cost(t1, t2, opr)\n\n\ndef tree_edit_distance(t1, t2, cost=default_node_cost, normalize=False, return_oprs=False):\n\n def _get_root(t):\n if isinstance(t, DependencyTree):\n return t.root\n if isinstance(t, Sentence):\n return t.as_tree().root\n return t\n\n nodes1, l1, keyroots1 = _annotate(_get_root(t1))\n nodes2, l2, keyroots2 = _annotate(_get_root(t2))\n\n n = len(nodes1)\n m = len(nodes2)\n\n if n == 0 and m == 0:\n dist = 0\n if return_oprs:\n oprs = []\n elif n != 0 and m == 0:\n dist = sum(cost(node, None, DEL) for node in nodes1)\n if return_oprs:\n oprs = [(DEL, i) for i in range(n)]\n elif n == 0 and m != 0:\n dist = sum(cost(None, node, INS) for node in nodes2)\n if return_oprs:\n oprs = [(INS, j) for j in range(m)]\n else:\n TD = np.zeros((n, m), dtype=np.float)\n if return_oprs:\n TD_oprs = np.empty((n, m), dtype=np.object)\n TD_oprs.fill([])\n else:\n TD_oprs = None\n\n for i in keyroots1:\n for j in keyroots2:\n _treedist(i, j, l1, l2, nodes1, nodes2, TD, TD_oprs, cost, return_oprs)\n\n dist = TD[n-1, m-1]\n if return_oprs:\n oprs = TD_oprs[n-1, m-1]\n\n if normalize:\n dist = _normalize(dist, n, m)\n\n if return_oprs:\n return dist, oprs\n else:\n return dist\n\n\ndef default_value_cost(key, v1, v2, opr):\n if opr == DEL:\n return 1\n if opr == INS:\n return 1\n return 1 if v1 != v2 else 0\n\n\ndef dict_edit_distance(d1, d2, cost=default_value_cost, normalize=False, return_oprs=False):\n\n if isinstance(d1, str):\n d1 = _parse_feats(d1)\n if isinstance(d2, str):\n d2 = _parse_feats(d2)\n\n all_keys = set(d1.keys()).union(d2.keys())\n dist = 0\n oprs = set()\n\n for key in all_keys:\n if key not in d2:\n c = cost(key, d1[key], None, DEL) # delete\n opr = (DEL, key)\n elif key not in d1:\n c = cost(key, None, d2[key], INS) # insert\n opr = (INS, key)\n else:\n c = cost(key, d1[key], d2[key], SUB) # substitute\n opr = (SUB, key)\n if c != 0:\n dist += c\n if return_oprs:\n oprs.add(opr)\n\n if normalize:\n dist = dist / len(all_keys) if dist != 0 else 0\n if return_oprs:\n return dist, oprs\n else:\n return dist\n\n\ndef k_nearest_neighbors(itm1, itms2, k=1, distance=levenshtein_distance, return_distance=True):\n knn = heapq.nsmallest(k, [(idx2, distance(itm1, itm2)) for idx2, itm2 in enumerate(itms2)], key=lambda x: x[1])\n if return_distance:\n return knn\n else:\n return [itm2[0] for itm2 in knn]\n" ]
[ [ "numpy.zeros", "numpy.empty" ] ]
czyzi0/mlp
[ "8acded75681b16d20d0d23b157226554b7026a3d" ]
[ "tests/test_utils.py" ]
[ "import numpy as np\nimport pytest\n\nimport mlp.utils as utils\n\n\[email protected]('x, expected_y', [\n (\n np.array([\n [0.8, 0.0, 0.1],\n [0.0, 0.1, 0.9],\n [0.1, 0.2, 0.1],\n ]),\n np.array([\n [1.0, 0.0, 0.0],\n [0.0, 0.0, 1.0],\n [0.0, 1.0, 0.0],\n ]),\n ),\n (\n np.array([\n [0.8, 0.7, 0.9],\n [0.1, 0.1, 0.0],\n [0.2, 0.2, 0.2],\n [23.0, 0.0, -2.0],\n ]),\n np.array([\n [0.0, 0.0, 1.0],\n [1.0, 0.0, 0.0],\n [1.0, 0.0, 0.0],\n [1.0, 0.0, 0.0],\n ]),\n )\n])\ndef test_argmax(x, expected_y):\n y = utils.argmax(x)\n assert np.allclose(expected_y, y)\n\n\[email protected]('array, chunk_size, expected_chunks', [\n (\n np.array([\n [1.0, 1.0],\n [2.0, 2.0],\n [3.0, 3.0],\n [4.0, 4.0],\n [5.0, 5.0],\n [6.0, 6.0],\n [7.0, 7.0],\n [8.0, 8.0],\n ]),\n 3,\n [\n np.array([\n [1.0, 1.0],\n [2.0, 2.0],\n [3.0, 3.0],\n ]),\n np.array([\n [4.0, 4.0],\n [5.0, 5.0],\n [6.0, 6.0],\n ]),\n np.array([\n [7.0, 7.0],\n [8.0, 8.0],\n ]),\n ]\n ),\n (\n np.array([\n [1.0, 1.0],\n [2.0, 2.0],\n [3.0, 3.0],\n [4.0, 4.0],\n [5.0, 5.0],\n [6.0, 6.0],\n [7.0, 7.0],\n [8.0, 8.0],\n ]),\n 2,\n [\n np.array([\n [1.0, 1.0],\n [2.0, 2.0],\n ]),\n np.array([\n [3.0, 3.0],\n [4.0, 4.0],\n ]),\n np.array([\n [5.0, 5.0],\n [6.0, 6.0],\n ]),\n np.array([\n [7.0, 7.0],\n [8.0, 8.0],\n ]),\n ]\n ),\n])\ndef test_chunked(array, chunk_size, expected_chunks):\n chunks = list(utils.chunked(array, chunk_size=chunk_size))\n for expected_chunk, chunk in zip(expected_chunks, chunks):\n assert np.allclose(expected_chunk, chunk)\n\n\[email protected]('array_shape', [\n ((12, 4500)),\n ((100, 1)),\n ((50, 4)),\n ((1500, 12)),\n ((60000, 768)),\n])\ndef test_unison_shuffle(array_shape):\n array1 = np.arange(array_shape[0] * array_shape[1]).reshape(array_shape)\n array2 = np.arange(array_shape[0] * array_shape[1]).reshape(array_shape)\n\n array1, array2 = utils.unison_shuffle(array1, array2)\n\n assert np.allclose(array1, array2)\n\n\[email protected]('array1, array2', [\n (\n np.array([1, 2, 3, 4, 5]),\n np.array([1, 2, 3, 4, 5, 6]),\n ),\n])\ndef test_unison_shuffle_raises_error(array1, array2):\n with pytest.raises(ValueError):\n utils.unison_shuffle(array1, array2)\n\n\[email protected]('iterable, total, verbose', [\n (list(range(100)), 100, False),\n (list(range(100)), 100, True),\n (np.arange(1500), 1500, False),\n (range(300), 300, True),\n (range(300), 300, False),\n (list(range(50)), 50, True),\n])\ndef test_progress_bar(iterable, total, verbose):\n for item1, item2 in zip(iterable, utils.progress_bar(iterable, total=total, verbose=verbose)):\n assert item1 == item2\n" ]
[ [ "numpy.arange", "numpy.array", "numpy.allclose" ] ]
mogproject/spacegraphcats
[ "e21015daa8e2968c3076bd250c553aa20e6d912b" ]
[ "scripts/cluster-vectors.py" ]
[ "#! /usr/bin/env python\nimport numpy\nimport pickle\nimport itertools\nimport time\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\nimport hdbscan\nfrom sklearn.manifold import TSNE\n\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('vectors_file')\n parser.add_argument('-o', '--output', type=argparse.FileType('wb'))\n args = parser.parse_args()\n\n assert args.output, \"please specify output filename for clusters\"\n\n data = numpy.load(args.vectors_file)\n\n # load the k=31 MinHashes for identification, and the mapping between node IDs and \n # data index.\n node_id_to_group_idx = pickle.load(open(args.vectors_file + '.node_ids', 'rb'))\n group_ident = pickle.load(open(args.vectors_file + '.node_mh', 'rb'))\n\n print('loaded data of shape {}'.format(str(data.shape)))\n\n\n print('standardizing')\n data_std = StandardScaler().fit_transform(data)\n\n print('running PCA...')\n start = time.time()\n pca = PCA(n_components=50, svd_solver='full')\n data_pca = pca.fit_transform(data_std)\n end = time.time()\n print('done! ({:.1f}s total)'.format(end - start))\n\n print('running tSNE...')\n start = time.time()\n t = TSNE(n_components=2, perplexity=50).fit_transform(data_pca)\n end = time.time()\n print('done! ({:.1f}s total)'.format(end - start))\n\n print('running HDBSCAN on tSNE results...')\n params = dict(min_cluster_size=15)\n start = time.time()\n h = hdbscan.HDBSCAN(**params).fit_predict(t)\n end = time.time()\n print('done! ({:.1f}s total)'.format(end - start))\n print('got {} clusters'.format(max(h) + 1))\n\n print('saving PCA, tSNE and HDBSCAN results to \\'{}\\''.format(args.output.name))\n\n pickle.dump((data_pca, t, h), args.output)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.load", "sklearn.preprocessing.StandardScaler", "sklearn.decomposition.PCA", "sklearn.manifold.TSNE" ] ]
joaogui1/jax
[ "3575bc7639a8f222417d33adc2112ebe766770af" ]
[ "tests/api_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 contextlib import contextmanager\nimport copy\nfrom functools import partial\nimport re\nimport unittest\nimport types\nimport warnings\nimport weakref\nimport functools\nimport itertools as it\n\nfrom absl import logging\nfrom absl.testing import absltest, parameterized\nimport numpy as np\n\nimport concurrent.futures\n\nimport jax\nimport jax.numpy as jnp\nfrom jax import float0, jit, grad, device_put, jacfwd, jacrev, hessian\nfrom jax import api, core, lax, lax_reference, lazy\nfrom jax.core import Primitive\nfrom jax.interpreters import ad\nfrom jax.interpreters import xla\nfrom jax.interpreters.sharded_jit import PartitionSpec as P\nfrom jax.lib import xla_bridge as xb\nfrom jax import test_util as jtu\nfrom jax import tree_util\nfrom jax import linear_util as lu\nimport jax._src.util\n\nfrom jax.config import config\nconfig.parse_flags_with_absl()\nFLAGS = config.FLAGS\n\n\nclass CPPJitTest(jtu.JaxTestCase):\n \"\"\"Shared tests between the Python and the C++ jax,jit implementations.\n\n Because the Python implementation supports more features, we need to have the\n Python tests that extend the C++ tests (and not the other way around).\n \"\"\"\n\n @property\n def jit(self):\n # Right now, the CPP tests also test the Python code-path when jaxlib is\n # too old.\n # TODO(jblespiau,phawkins): Remove this when jaxlib has been released.\n # This is in the future, because we are making a breaking change to\n # Tensorflow.\n return jax.api._cpp_jit\n\n def test_jit_of_noncallable(self):\n self.assertRaisesRegex(TypeError, \"Expected a callable value.*\",\n lambda: self.jit(3))\n\n def test_jit_of_generator(self):\n\n def gen(x):\n yield x\n\n self.assertRaisesRegex(TypeError,\n \"Expected a function, got a generator function.*\",\n lambda: self.jit(gen))\n\n @parameterized.parameters([\n # Integer support\n (1, 2, 3, 4, 5),\n # Numpy array support\n (\n np.asarray(1, np.int32),\n np.asarray(2, np.int32),\n np.asarray(3, np.int32),\n np.asarray(4, np.int32),\n np.asarray(5, np.int32),\n ),\n ])\n def test_jit_static_args(self, one, two, three, four, five):\n side = []\n # For the CPP jit, we need to clear the cache to prevent cache hits between\n # parameterized tests.\n if hasattr(self.jit, \"cache_clear\"):\n self.jit.cache_clear()\n\n def f(x, y, z, flag=False, flag2=False):\n del flag2 # unused\n assert flag\n side.append(None)\n return 100 * x + 10 * y + z\n\n f1 = self.jit(f, static_argnums=(3, 4))\n assert f1(one, two, three, True, False) == 123\n assert len(side) == 1\n assert f1(one, two, three, True, False) == 123\n assert len(side) == 1 # Obvious cache hit.\n assert f1(two, one, three, True, False) == 213\n assert len(side) == 1 # Should cache hit because same signature.\n assert f1(two, one, three, True, True) == 213\n assert len(side) == 2\n\n side[:] = []\n f2 = self.jit(f, static_argnums=(0, 2, 3, 4))\n assert f2(1, 2, 3, True, False) == 123\n assert len(side) == 1\n assert f2(1, 3, 3, True, False) == 133\n assert len(side) == 1\n assert f2(2, 2, 3, True, False) == 223\n assert len(side) == 2\n assert f2(2, 4, 3, True, False) == 243\n assert len(side) == 2\n assert f2(2, 4, 3, True, True) == 243\n assert len(side) == 3\n assert f2(2, 5, 3, True, True) == 253\n assert len(side) == 3\n\n def test_static_args_equality(self):\n class A():\n\n def __hash__(self):\n return 1\n\n def __eq__(self, other):\n return isinstance(other, A)\n\n side = []\n def f(x, static_arg):\n del static_arg\n side.append(None)\n return x * 100\n\n f1 = self.jit(f, static_argnums=(1,))\n\n self.assertEqual(f1(1, A()), 100)\n self.assertLen(side, 1)\n self.assertEqual(f1(1, A()), 100)\n self.assertLen(side, 1)\n if self.jit == jax.api._cpp_jit:\n self.assertEqual(f1._cpp_jitted_f._cache_size(), 1)\n\n @parameterized.parameters([\n (1, 2, 3),\n (\n np.asarray(1, np.int32),\n np.asarray(2, np.int32),\n np.asarray(3, np.int32),\n ),\n ])\n def test_jit_kwargs(self, one, two, three):\n side = []\n # For the CPP jit, we need to clear the cache to prevent cache hits between\n # parameterized tests.\n if hasattr(self.jit, \"cache_clear\"):\n self.jit.cache_clear()\n\n def f(x, y, z):\n print(x, y, z)\n side.append(None)\n return 100 * x + 10 * y + z\n\n f = self.jit(f)\n assert f(one, two, three) == 123\n assert len(side) == 1\n assert f(one, two, three) == 123\n assert len(side) == 1\n\n assert f(one, two, z=three) == 123\n assert len(side) == 2 # actually recompiles from kwarg\n assert f(one, two, z=three) == 123\n assert len(side) == 2 # but should still cache\n\n f(one, two, z=np.zeros(3)) # doesn't crash\n if config.x64_enabled:\n # In the above call, three is of a new type (int64), thus it should\n # trigger a new compilation.\n assert len(side) == 3\n\n def test_jit_device(self):\n device = xb.devices()[-1]\n x = self.jit(lambda x: x, device=device)(3.)\n self.assertIsInstance(x, xla.DeviceArray)\n self.assertEqual(x.device_buffer.device(), device)\n\n def test_complex_support(self):\n self.assertEqual(self.jit(lambda x: x + 1)(1 + 1j), 2 + 1j)\n\n def test_jit_with_many_args_works(self):\n\n @self.jit\n def f(args_list):\n return sum(args_list)\n\n self.assertEqual(f(list(range(500))), sum(range(500)))\n\n # Jit and Donate arguments\n assertDeleted = lambda self, x: self._assertDeleted(x, True)\n assertNotDeleted = lambda self, x: self._assertDeleted(x, False)\n\n def _assertDeleted(self, x, deleted):\n if hasattr(x, \"device_buffer\"):\n self.assertEqual(x.device_buffer.is_deleted(), deleted)\n else:\n for buffer in x.device_buffers:\n self.assertEqual(buffer.is_deleted(), deleted)\n\n def test_jit_donate_argnums_warning_raised(self):\n x = jnp.array([1.0, 2.0], jnp.float32)\n y = jnp.array([1, 2], jnp.int32)\n f = self.jit(lambda x, y: x.sum() + y.sum(), donate_argnums=(0, 1))\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n f(x, y)\n\n self.assertLen(w, 1)\n self.assertTrue(issubclass(w[-1].category, UserWarning))\n self.assertIn(\n \"Some donated buffers were not usable: f32[2]{0}, s32[2]{0}\",\n str(w[-1].message))\n\n @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n def test_jit_donate_argnums_invalidates_input(self):\n # We can't just use `lambda x: x` because JAX simplifies this away to an\n # empty XLA computation.\n move = self.jit(lambda x: x + x - x, donate_argnums=0)\n x = jnp.ones([])\n y = move(x)\n self.assertDeleted(x)\n self.assertEqual(y, 1.)\n\n @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n def test_jit_donate_argnums_static_argnums(self):\n jit_fun = self.jit(\n lambda a, b, c, d: ((a + b + c), (a + b + d)),\n static_argnums=(0, 1),\n donate_argnums=(2, 3))\n\n c = jax.device_put(jnp.array([1., 1.]))\n d = jax.device_put(jnp.array([1., 1., 1.]))\n e, f = jit_fun(1, 2, c, d)\n np.testing.assert_allclose(e, jnp.array([4., 4.]))\n np.testing.assert_allclose(f, jnp.array([4., 4., 4.]))\n self.assertDeleted(c)\n self.assertDeleted(d)\n\n @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n def test_jnp_array_copy(self):\n # https://github.com/google/jax/issues/3412\n\n @partial(self.jit, donate_argnums=(0,))\n def _test(array):\n return array.at[0].set(77)\n\n x = jnp.asarray([0, 1])\n x_copy = jnp.array(x, copy=True)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n _test(x) # donation\n\n # Gives: RuntimeError: Invalid argument: CopyToHostAsync() called on invalid buffer.\n print(x_copy) # doesn't crash\n\n def test_jit_global_cache(self):\n def f(x):\n assert python_should_be_executing\n return x\n\n python_should_be_executing = True\n self.jit(f)(2)\n python_should_be_executing = False\n self.jit(f)(3)\n\n def test_jit_shallow_copy(self):\n def f(x):\n return copy.copy(x)\n self.jit(f)(1)\n\n def test_jit_deep_copy(self):\n def f(x):\n return copy.deepcopy(x)\n self.jit(f)(1)\n\n def test_disable_jit(self):\n effects = []\n\n @self.jit\n def f(x):\n effects.append(1)\n return x\n\n with api.disable_jit():\n f(2)\n f(2)\n assert len(effects) == 2\n\n f(2)\n f(2)\n assert len(effects) == 3\n\n def test_static_argnum_errors_on_keyword_arguments(self):\n f = self.jit(lambda x: x, static_argnums=0)\n msg = (\"jitted function has static_argnums=(0,), donate_argnums=() but was \"\n \"called with only 0 positional arguments.\")\n with self.assertRaisesRegex(ValueError, re.escape(msg)):\n f(x=4)\n\n def test_static_argnum_on_method(self):\n\n class A:\n\n @functools.partial(self.jit, static_argnums=(0,))\n def my_func_jit(self, x):\n return x+2\n\n A().my_func_jit(3)\n\n def test_static_argnum_on_static_method_is_not_supported(self):\n with self.assertRaisesRegex(TypeError, \"Expected a callable value\"):\n\n class A:\n\n @functools.partial(self.jit, static_argnums=(0,))\n @classmethod\n def my_classmethod_jit(cls, x):\n return x+2\n\n def test_classmethod_is_not_supported(self):\n with self.assertRaisesRegex(TypeError, \"Expected a callable value\"):\n\n class A:\n\n @functools.partial(self.jit)\n @staticmethod\n def my_staticmethod_jit(x):\n return x + 2\n\n def test_concurrent_jit(self):\n @self.jit\n def f(x):\n return x + x - 3.\n\n xs = [np.random.randn(i) for i in range(10)]\n with concurrent.futures.ThreadPoolExecutor() as executor:\n futures = [executor.submit(partial(f, x)) for x in xs]\n ys = [f.result() for f in futures]\n for x, y in zip(xs, ys):\n self.assertAllClose(x * 2 - 3., y)\n\n def test_trivial_computations(self):\n x = jnp.array([1, 2, 3])\n y = self.jit(lambda x: x)(x)\n self.assertIs(x, y)\n\n z1, z2 = self.jit(lambda x: (x, x))(x)\n self.assertIs(z1, z2)\n\n x1, x2 = jnp.array([1, 2]), jnp.array([2, 3])\n z1, z2, z3 = self.jit(lambda x, y: (y, 1, x))(x1, x2)\n self.assertIs(z1, x2)\n self.assertIs(z3, x1)\n self.assertEqual(z2, 1)\n\n def test_jit_bad_input(self):\n def f(x):\n return x\n\n self.assertRaisesRegex(\n TypeError, \".* 'foo' of type <.*'str'> is not a valid JAX type\",\n lambda: self.jit(f)(\"foo\"))\n\n def test_jit_on_all_devices(self):\n # Verifies we can run the same computation on every device present, even\n # if they are, for example, different models of GPU.\n data = np.random.rand(1000).astype(np.float32)\n f = self.jit(jnp.negative)\n for device in jax.local_devices():\n x = device_put(data, device=device)\n np.testing.assert_array_equal(-data, f(x))\n\n def test_jit_nested_donate_ignored(self):\n jit_fun = self.jit(lambda x: self.jit(lambda y: y**2, donate_argnums=0)(x))\n a = jax.device_put(jnp.array(1))\n\n # NOTE(mattjj): stopped raising error here and instead just ignored\n # with self.assertRaisesRegex(ValueError, \"nested.*not supported\"):\n # jit_fun(a)\n\n jit_fun(a) # doesn't crash\n\n def test_jit_reference_dropping(self):\n x = jnp.ones(10)\n f = (lambda x: lambda: x)(x) # reference to x in f's closure\n g = self.jit(f)\n x = weakref.ref(x) # no more strong ref to x in this scope\n assert x() is not None # x is still around\n f() # f runs\n g() # g runs\n g() # g runs a second time\n del f # delete the raw callable\n assert x() is not None # x is still around\n g() # g still runs\n del g # no more references to x\n assert x() is None # x is gone\n\n def test_jit_raises_on_first_invocation_on_non_hashable_static_argnum(self):\n if self.jit != jax.api._python_jit:\n raise unittest.SkipTest(\"this test only applies to _python_jit\")\n f = lambda x, y: x + 3\n jitted_f = self.jit(f, static_argnums=(1,))\n\n msg = (\"Non-hashable static arguments are not supported, as this can lead \"\n \"to unexpected cache-misses. Static argument (index 1) of type \"\n \"<class 'numpy.ndarray'> for function <lambda> is non-hashable.\")\n with self.assertRaisesRegex(ValueError, re.escape(msg)):\n jitted_f(1, np.asarray(1))\n\n def test_cpp_jit_raises_on_non_hashable_static_argnum(self):\n if self.jit != jax.api._cpp_jit:\n raise unittest.SkipTest(\"this test only applies to _cpp_jit\")\n\n f = lambda x, y: x + 3\n jitted_f = jax.api._cpp_jit(f, static_argnums=[1])\n\n jitted_f(1, 1)\n\n msg = (\"Non-hashable static arguments are not supported. An error occured \"\n \"while trying to hash an object of type <class 'numpy.ndarray'>, 1. \"\n \"The error was:\\nTypeError: unhashable type: 'numpy.ndarray'\")\n\n with self.assertRaisesRegex(ValueError, re.escape(msg)):\n jitted_f(1, np.asarray(1))\n\n class HashableWithoutEq:\n\n def __hash__(self):\n return 1\n\n def __eq__(self, other):\n raise NotImplementedError(\n \"A Python error is as is, without stack trace\")\n\n with self.assertRaisesRegex(\n ValueError,\n re.escape(\"static arguments should be comparable using __eq__\")):\n jitted_f(1, HashableWithoutEq())\n\n def test_cpp_jitted_function_returns_PyBuffer(self):\n if self.jit != jax.api._cpp_jit:\n raise unittest.SkipTest(\"this test only applies to _cpp_jit\")\n\n jitted_f = self.jit(lambda a: a + 1)\n jitted_f(1)\n self.assertIsInstance(jitted_f(2), xla._CppDeviceArray)\n\n @jtu.skip_on_devices(\"cpu\")\n def test_explicit_backend(self):\n f = lambda x: x + 1\n jitted_f = jit(f, backend=jtu.device_under_test())\n jitted_f_cpu = jit(f, backend=\"cpu\")\n\n result = jitted_f(1.)\n result_cpu = jitted_f_cpu(1.)\n self.assertEqual(result.device_buffer.platform(), jtu.device_under_test())\n self.assertEqual(result_cpu.device_buffer.platform(), \"cpu\")\n\n @jtu.skip_on_devices(\"cpu\")\n def test_mismatched_nested_backends(self):\n @partial(jit, backend=jtu.device_under_test())\n def f(x):\n return jit(lambda x: x + 1, backend=\"cpu\")(x)\n\n with self.assertRaisesRegex(\n ValueError,\n f\"Outer-jit backend specification {jtu.device_under_test()} must match \"\n f\"explicit inner-jit backend specification cpu.\"):\n f(1.)\n\n def test_omnistaging(self):\n # See https://github.com/google/jax/issues/5206\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n key_list = [None]\n\n def init():\n key, subkey = jax.random.split(key_list[0])\n key_list[0] = key\n return jax.random.normal(subkey, ())\n\n key_list[0] = np.array([2384771982, 3928867769], dtype=np.uint32)\n init()\n self.jit(init)()\n self.assertIsInstance(key_list[0], core.Tracer)\n\nclass PythonJitTest(CPPJitTest):\n\n @property\n def jit(self):\n return jax.api._python_jit\n\n\nclass APITest(jtu.JaxTestCase):\n\n def test_grad_bad_input(self):\n def f(x):\n return x\n\n self.assertRaisesRegex(\n TypeError, \".* 'foo' of type <.*'str'> is not a valid JAX type\",\n lambda: grad(f)(\"foo\"))\n\n def test_grad_argnums(self):\n def f(x, y, z, flag=False):\n assert flag\n return 1.0 * x + 2.0 * y + 3.0 * z\n\n assert grad(f)(1.0, 1.0, 1.0, flag=True) == 1.0\n assert grad(f, argnums=1)(1.0, 1.0, 1.0, flag=True) == 2.0\n assert grad(f, argnums=(2, 0))(1.0, 1.0, 1.0, flag=True) == (3.0, 1.0)\n\n def test_value_and_grad_argnums(self):\n def f(x, y, z, flag=False):\n assert flag\n return 1.0 * x + 2.0 * y + 3.0 * z\n\n y = f(1.0, 1.0, 1.0, flag=True)\n assert api.value_and_grad(f)(1.0, 1.0, 1.0, flag=True) == (y, 1.0)\n assert api.value_and_grad(f, argnums=1)(1.0, 1.0, 1.0, flag=True) == (y, 2.0)\n assert api.value_and_grad(f, argnums=(2, 0))(1.0, 1.0, 1.0, flag=True) == (y, (3.0, 1.0))\n\n def test_grad_of_jit(self):\n side = []\n\n @jit\n def f(x):\n side.append(None)\n return x * x\n\n assert grad(f)(1.0) == 2.0\n assert len(side) == 1\n assert grad(f)(2.0) == 4.0\n assert len(side) == 1\n\n def test_jit_of_grad(self):\n side = []\n\n @jit\n def f(x):\n side.append(None)\n return x * x\n\n g = jit(grad(f))\n assert g(1.0) == 2.0\n assert len(side) == 1\n assert g(2.0) == 4.0\n assert len(side) == 1\n\n def test_bad_input(self):\n def f(x):\n return x\n\n self.assertRaisesRegex(\n TypeError, \".* 'foo' of type <.*'str'> is not a valid JAX type\",\n lambda: grad(f)(\"foo\"))\n\n self.assertRaisesRegex(\n TypeError, \".* 'foo' of type <.*'str'> is not a valid JAX type\",\n lambda: jit(f)(\"foo\"))\n\n def test_grad_tuple_output(self):\n jtu.check_raises(lambda: grad(lambda x: (x,x))(1.0), TypeError,\n \"Gradient only defined for scalar-output functions. \")\n\n def test_grad_unit_output(self):\n jtu.check_raises(lambda: grad(lambda x: ())(np.zeros(3)), TypeError,\n \"Gradient only defined for scalar-output functions. \")\n\n def test_grad_nonscalar_output(self):\n jtu.check_raises(lambda: grad(lambda x: x)(np.zeros(3)), TypeError,\n \"Gradient only defined for scalar-output functions. \")\n\n def test_unwrapped_numpy(self):\n def f(x):\n return np.exp(x)\n\n with self.assertRaisesRegex(Exception, \"The numpy.ndarray conversion .*\"):\n grad(f)(np.zeros(3))\n\n def test_binop_mismatch(self):\n def f(x, y):\n return x + y\n\n jtu.check_raises(\n lambda: f(jnp.zeros(3), jnp.zeros(4)),\n TypeError,\n \"add got incompatible shapes for broadcasting: (3,), (4,).\")\n\n jtu.check_raises(\n lambda: grad(f)(np.zeros(3), np.zeros(4)),\n TypeError,\n \"add got incompatible shapes for broadcasting: (3,), (4,).\")\n\n def test_dot_mismatch(self):\n def f(x, y):\n return jnp.dot(x, y)\n\n self.assertRaisesRegex(\n TypeError, \"Incompatible shapes for dot: got \\\\(3L?,\\\\) and \\\\(4L?,\\\\).\",\n lambda: grad(f)(np.zeros(3), np.zeros(4)))\n\n def test_abstract_error_message(self):\n for castfun in [float, complex, int]:\n def f(x):\n return castfun(x)\n\n self.assertRaisesRegex(\n TypeError,\n f\"[Tt]ry using `x.astype\\\\({castfun.__name__}\\\\)`\",\n lambda: jit(f)(1.0))\n\n def test_switch_value_jit(self):\n def f(x):\n y = x > 0\n if y:\n return x\n else:\n return -x\n\n assert grad(f)(1.0) == 1.0\n assert grad(f)(-1.0) == -1.0\n with self.assertRaisesRegex(core.ConcretizationTypeError,\n \"Abstract tracer value\"):\n jit(f)(1)\n\n def test_range_err(self):\n def f(x, n):\n for i in range(n):\n x = x + i\n return x\n\n assert jit(f, static_argnums=(1,))(0, 5) == 10\n self.assertRaisesRegex(\n TypeError,\n \"('(?:JaxprTracer|DynamicJaxprTracer)' object cannot be interpreted as an integer\"\n \"|Abstract value passed to .*)\",\n lambda: jit(f)(0, 5))\n\n def test_casts(self):\n for castfun in [hex, oct, int]:\n f = lambda x: castfun(x)\n self.assertRaisesRegex(\n TypeError,\n \"('(?:JaxprTracer|DynamicJaxprTracer)' object cannot be interpreted as an integer\"\n \"|Abstract tracer value encountered where concrete value is expected.*)\", lambda: jit(f)(0))\n\n def test_unimplemented_interpreter_rules(self):\n foo_p = Primitive('foo')\n def foo(x):\n return foo_p.bind(x)\n\n jtu.check_raises(lambda: foo(1.0), NotImplementedError,\n \"Evaluation rule for 'foo' not implemented\")\n\n jtu.check_raises(lambda: jit(foo)(1.0), NotImplementedError,\n \"Abstract evaluation for 'foo' not implemented\")\n\n jtu.check_raises(lambda: grad(foo)(1.0), NotImplementedError,\n \"Differentiation rule for 'foo' not implemented\")\n\n foo_p.def_abstract_eval(lambda x: x)\n\n jtu.check_raises(lambda: jit(foo)(1.0), NotImplementedError,\n \"XLA translation rule for primitive 'foo' not found\")\n\n foo_p.def_impl(lambda x: x)\n ad.defjvp(foo_p, lambda g, x: foo(g))\n\n jtu.check_raises(lambda: grad(foo)(1.0), NotImplementedError,\n \"Transpose rule (for reverse-mode differentiation) for 'foo' not implemented\")\n\n def test_device_put_and_get(self):\n x = np.arange(12.).reshape((3, 4)).astype(\"float32\")\n dx = api.device_put(x)\n self.assertIsInstance(dx, xla.DeviceArray)\n x2 = api.device_get(dx)\n self.assertIsInstance(x2, np.ndarray)\n assert np.all(x == x2)\n\n y = [x, (2 * x, 3 * x)]\n dy = api.device_put(y)\n y2 = api.device_get(dy)\n self.assertIsInstance(y2, list)\n self.assertIsInstance(y2[0], np.ndarray)\n assert np.all(y2[0] == x)\n self.assertIsInstance(y2[1], tuple)\n self.assertIsInstance(y2[1][0], np.ndarray)\n assert np.all(y2[1][0] == 2 * x)\n self.assertIsInstance(y2[1][1], np.ndarray)\n assert np.all(y2[1][1] == 3 * x)\n\n def test_device_get_scalar(self):\n x = np.arange(12.).reshape((3, 4)).astype(\"float32\")\n x = api.device_put(x)\n self.assertIsInstance(x, xla.DeviceArray)\n y = [x, 2]\n y2 = api.device_get(y)\n self.assertIsInstance(y2, list)\n self.assertIsInstance(y2[0], np.ndarray)\n assert np.all(y2[0] == x)\n self.assertIsInstance(y2[1], int)\n self.assertEqual(y2[1], 2)\n\n @parameterized.parameters([(3,)], [(2, 0)])\n def test_device_put_across_devices(self, shape):\n if len(api.local_devices()) < 2:\n raise unittest.SkipTest(\"this test requires multiple devices\")\n d1, d2 = api.local_devices()[:2]\n data = np.random.randn(*shape).astype(np.float32)\n x = api.device_put(data, device=d1)\n self.assertEqual(x.device_buffer.device(), d1)\n y = api.device_put(x, device=d2)\n self.assertEqual(y.device_buffer.device(), d2)\n np.testing.assert_array_equal(data, np.array(y))\n # Make sure these don't crash\n api.device_put(x)\n api.device_put(y)\n\n @jtu.skip_on_devices(\"cpu\")\n def test_device_put_across_platforms(self):\n default_device = jax.devices()[0]\n cpu_device = jax.devices(\"cpu\")[0]\n\n np_arr = np.array([1,2,3])\n scalar = 1\n device_arr = jnp.array([1,2,3])\n assert device_arr.device_buffer.device() is default_device\n\n for val in [np_arr, device_arr, scalar]:\n x = api.device_put(val, device=cpu_device)\n self.assertEqual(x.device_buffer.device(), cpu_device)\n\n @jtu.skip_on_devices(\"tpu\")\n def test_jacobian(self):\n R = np.random.RandomState(0).randn\n A = R(4, 3)\n x = R(3)\n\n f = lambda x: jnp.dot(A, x)\n assert np.allclose(jacfwd(f)(x), A)\n assert np.allclose(jacrev(f)(x), A)\n\n f = lambda x: jnp.tanh(jnp.dot(A, x))\n assert np.allclose(jacfwd(f)(x), jacrev(f)(x))\n\n @jtu.skip_on_devices(\"tpu\")\n def test_hessian(self):\n R = np.random.RandomState(0).randn\n A = R(4, 4)\n x = R(4)\n\n f = lambda x: jnp.dot(x, jnp.dot(A, x))\n assert np.allclose(hessian(f)(x), A + A.T)\n\n def test_std_basis(self):\n basis = api._std_basis(jnp.zeros(3))\n assert getattr(basis, \"shape\", None) == (3, 3)\n assert np.allclose(basis, np.eye(3))\n\n basis = api._std_basis(jnp.zeros((3, 3)))\n assert getattr(basis, \"shape\", None) == (9, 3, 3)\n assert np.allclose(basis, np.eye(9).reshape(9, 3, 3))\n\n basis = api._std_basis([0., (jnp.zeros(3), jnp.zeros((3, 4)))])\n assert isinstance(basis, list) and len(basis) == 2\n assert getattr(basis[0], \"shape\", None) == (16,)\n assert isinstance(basis[1], tuple) and len(basis[1]) == 2\n assert getattr(basis[1][0], \"shape\", None) == (16, 3)\n assert getattr(basis[1][1], \"shape\", None) == (16, 3, 4)\n\n @jtu.skip_on_devices(\"tpu\")\n def test_jacobian_on_pytrees(self):\n for jacfun in [jacfwd, jacrev]:\n ans = jacfun(lambda x, y: (x, y))(0., 1.)\n expected = (1., 0.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = jacfun(lambda x, y: (x, y), 1)(0., 1.)\n expected = (0., 1.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = jacfun(lambda x, y: (x, y), (0, 1))(0., 1.)\n expected = ((1., 0.),\n (0., 1.),)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = jacfun(lambda x: x[:2])((1., 2., 3.))\n expected = ((1., 0., 0.),\n (0., 1., 0.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n R = np.random.RandomState(0).randn\n x = R(2)\n y = R(3)\n ans = jacfun(lambda x, y: {'x': x, 'xy': jnp.outer(x, y)})(x, y)\n expected = {'x': np.eye(2),\n 'xy': np.kron(np.eye(2), y[:, None]).reshape(2, 3, 2)}\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @jtu.skip_on_devices(\"tpu\")\n def test_hessian_on_pytrees(self):\n ans = hessian(lambda x: jnp.array(x)**2)((1., 2.))\n expected = ((np.array([2., 0.]), np.array([0., 0.])),\n (np.array([0., 0.]), np.array([0., 2.])))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @jtu.skip_on_devices(\"tpu\")\n def test_issue1372(self):\n def quad(x):\n return jnp.dot(x, x)\n\n def f(x, u):\n return quad(x) + quad(u)\n\n x, u = jnp.ones(5), jnp.ones(2)\n\n rev = jacrev\n fwd = jacfwd\n\n # Diagonal entries\n self.assertEqual(rev(rev(f, 0), 0)(x, u).shape, (5, 5))\n self.assertEqual(rev(fwd(f, 0), 0)(x, u).shape, (5, 5))\n self.assertEqual(fwd(rev(f, 0), 0)(x, u).shape, (5, 5))\n self.assertEqual(fwd(fwd(f, 0), 0)(x, u).shape, (5, 5))\n self.assertEqual(rev(rev(f, 1), 1)(x, u).shape, (2, 2))\n self.assertEqual(rev(fwd(f, 1), 1)(x, u).shape, (2, 2))\n self.assertEqual(fwd(rev(f, 1), 1)(x, u).shape, (2, 2))\n self.assertEqual(fwd(fwd(f, 1), 1)(x, u).shape, (2, 2))\n\n # Off-diagonal entries by reverse-mode on the outside\n self.assertEqual(rev(rev(f, 1), 0)(x, u).shape, (2, 5))\n self.assertEqual(rev(fwd(f, 1), 0)(x, u).shape, (2, 5))\n self.assertEqual(rev(rev(f, 0), 1)(x, u).shape, (5, 2))\n self.assertEqual(rev(fwd(f, 0), 1)(x, u).shape, (5, 2))\n\n # Off-diagonal entries by forward-mode on the outside\n self.assertEqual(fwd(rev(f, 1), 0)(x, u).shape, (2, 5))\n self.assertEqual(fwd(fwd(f, 1), 0)(x, u).shape, (2, 5))\n self.assertEqual(fwd(rev(f, 0), 1)(x, u).shape, (5, 2))\n self.assertEqual(fwd(fwd(f, 0), 1)(x, u).shape, (5, 2))\n\n\n def test_large_device_constant(self):\n ans = jit(lambda x: 2 * x)(jnp.ones(int(2e6))) # doesn't crash\n self.assertAllClose(ans, np.ones(int(2e6)) * 2., check_dtypes=False)\n\n def test_grad_and_aux_basic(self):\n g, aux = grad(lambda x: (x**3, [x**2]), has_aux=True)(3.)\n self.assertAllClose(g, grad(lambda x: x**3)(3.))\n self.assertAllClose(aux, [9.], check_dtypes=False)\n\n def test_grad_and_aux_nested(self):\n def f(x):\n g, aux = grad(lambda x: (x**3, [x**3]), has_aux=True)(x)\n return aux[0]\n\n f2 = lambda x: x**3\n\n self.assertEqual(grad(f)(4.), grad(f2)(4.))\n self.assertEqual(jit(grad(f))(4.), grad(f2)(4.))\n self.assertEqual(jit(grad(jit(f)))(4.), grad(f2)(4.))\n\n def f(x):\n g, aux = grad(lambda x: (x**3, [x**3]), has_aux=True)(x)\n return aux[0] * jnp.sin(x)\n\n f2 = lambda x: x**3 * jnp.sin(x)\n\n self.assertEqual(grad(f)(4.), grad(f2)(4.))\n self.assertEqual(jit(grad(f))(4.), grad(f2)(4.))\n self.assertEqual(jit(grad(jit(f)))(4.), grad(f2)(4.))\n\n def test_grad_and_aux_constant(self):\n g, aux = grad(lambda x: (x**3, [4.]), has_aux=True)(4.)\n self.assertEqual(g, grad(lambda x: x**3)(4.))\n self.assertEqual(aux, [4.])\n\n g, aux = grad(lambda x: (x**3, [x**2, 4.]), has_aux=True)(4.)\n self.assertEqual(g, grad(lambda x: x**3)(4.))\n self.assertEqual(aux, [4.**2, 4.])\n\n def test_grad_and_aux_no_tracers(self):\n # see https://github.com/google/jax/issues/1950\n def f(x):\n aux = dict(identity=x, p1=x+1)\n return x ** 2, aux\n\n _, aux = jax.grad(f, has_aux=True)(3.)\n self.assertIsInstance(aux, dict)\n for val in aux.values():\n self.assertNotIsInstance(val, core.Tracer)\n\n def test_jvp_mismatched_arguments(self):\n self.assertRaisesRegex(\n TypeError,\n (\"primal and tangent arguments to jax.jvp must have the same tree \"\n \"structure\"),\n lambda: api.jvp(lambda x, y: x * y, (np.float32(2),), ()))\n # If primals and tangents must both be tuples or both lists\n self.assertRaisesRegex(\n TypeError,\n (\"primal and tangent arguments to jax.jvp must have the same tree \"\n \"structure\"),\n lambda: api.jvp(lambda x, y: x * y, (np.float32(2),), [np.float32(2)]))\n self.assertRaisesRegex(\n TypeError,\n \"primal and tangent arguments to jax.jvp do not match.\",\n lambda: api.jvp(lambda x: -x, (np.float16(2),), (np.float32(4),)))\n # If primals and tangents are not of the same shape then raise error\n fun = lambda x: x+1\n with self.assertRaisesRegex(\n ValueError, \"jvp called with different primal and tangent shapes\"):\n api.jvp(fun, (jnp.array([1.,2.,3.]),), (jnp.array([1.,2.,3.,4.]),))\n with self.assertRaisesRegex(\n ValueError, \"jvp called with different primal and tangent shapes\"):\n api.jvp(fun, (jnp.float32(10.),), (jnp.array([1.,2.,3.], dtype=jnp.float32),))\n with self.assertRaisesRegex(\n ValueError, \"jvp called with different primal and tangent shapes\"):\n api.jvp(fun, (jnp.array([1.,2.,3.], dtype=jnp.float32),), (jnp.float32(20.),))\n with self.assertRaisesRegex(\n ValueError, \"jvp called with different primal and tangent shapes\"):\n api.jvp(fun, (jnp.array([1.,2.,3.]),), (20.,))\n\n def test_jvp_non_tuple_arguments(self):\n def f(x, y): return x + y\n self.assertRaisesRegex(\n TypeError,\n \"primal and tangent arguments to jax.jvp must be tuples or lists; found float and tuple.\",\n lambda: api.jvp(f, 0., (1.,)))\n self.assertRaisesRegex(\n TypeError,\n \"primal and tangent arguments to jax.jvp must be tuples or lists; found tuple and ndarray.\",\n lambda: api.jvp(f, (0.,), np.array([1., 2.])))\n\n def test_vjp_mismatched_arguments(self):\n _, pullback = api.vjp(lambda x, y: x * y, np.float32(3), np.float32(4))\n self.assertRaisesRegex(\n TypeError,\n \"Tree structure of cotangent input.*does not match\",\n lambda: pullback((np.float32(7), np.float32(100))))\n self.assertRaisesRegex(\n TypeError,\n \"Type of cotangent input to vjp pullback.*is not the expected tangent type\",\n lambda: pullback((np.float16(42))))\n\n def test_jvp_jit_cached(self):\n \"\"\"Bug in caching in presence of JVP and JIT.\"\"\"\n\n def func(x):\n def inner(y):\n return y * x\n\n # Must have two calls to the inner jit (the second one hits the cache)\n res1 = api.jit(inner)(4.)\n res2 = api.jit(inner)(5.)\n return res1 + res2\n\n self.assertAllClose((45., 9.), api.jvp(func, (5.,), (1.,)))\n\n def test_linear_transpose_abstract(self):\n x = types.SimpleNamespace(shape=(3,), dtype=np.float32)\n y = jnp.arange(3, dtype=np.float32)\n transpose_fun = api.linear_transpose(lambda x: 2 * x, x)\n z, = transpose_fun(y)\n self.assertArraysEqual(2 * y, z, check_dtypes=True)\n\n def test_linear_transpose_error(self):\n with self.assertRaisesRegex(\n TypeError, \"linear_transpose only supports float and complex inputs\"):\n api.linear_transpose(lambda x: x, 1)\n\n transpose_fun = api.linear_transpose(lambda x: [x, x], 1.0)\n with self.assertRaisesRegex(TypeError, \"cotangent tree does not match\"):\n transpose_fun(1.0)\n\n transpose_fun = api.linear_transpose(lambda x: jnp.stack([x, x]), 1.0)\n with self.assertRaisesRegex(TypeError, \"cotangent type does not match\"):\n transpose_fun(1.0)\n\n transpose_fun = api.linear_transpose(lambda x: 1j * x, 1.0)\n with self.assertRaisesRegex(TypeError, \"cotangent type does not match\"):\n transpose_fun(1.0)\n\n transpose_fun = api.linear_transpose(lambda x: x, 1.0)\n with self.assertRaisesRegex(TypeError, \"cotangent type does not match\"):\n transpose_fun(1j)\n\n def test_linear_transpose_complex(self):\n f = lambda x: (1 + 2j) * x\n transpose = api.linear_transpose(f, 1j)\n actual, = transpose(3 + 4j)\n expected = -5 + 10j\n self.assertEqual(actual, expected)\n\n def test_complex_grad_raises_error(self):\n self.assertRaises(TypeError, lambda: grad(lambda x: jnp.sin(x))(1 + 2j))\n\n def test_holomorphic_grad(self):\n out = grad(lambda x: jnp.sin(x), holomorphic=True)(1 + 2j)\n expected = 2.0327230070196656 - 3.0518977991518j\n self.assertAllClose(out, expected, check_dtypes=False)\n\n def test_nonholomorphic_grad(self):\n zs = 0.5j * np.arange(5) + np.arange(5)\n\n def f(z):\n return jnp.sum(jnp.cos(jnp.abs(z)))\n\n ans = grad(f)(zs)\n expected = np.array([ 0. +0.j,\n -0.80430663+0.40215331j,\n -0.70368982+0.35184491j,\n 0.1886467 -0.09432335j,\n 0.86873727-0.43436864j])\n self.assertAllClose(ans, expected, check_dtypes=False,\n atol=jtu.default_gradient_tolerance,\n rtol=jtu.default_gradient_tolerance)\n\n def test_complex_output_jacrev_raises_error(self):\n self.assertRaises(TypeError, lambda: jacrev(lambda x: jnp.sin(x))(1 + 2j))\n\n def test_nonholomorphic_jacrev(self):\n # code based on https://github.com/google/jax/issues/603\n zs = 0.5j * np.arange(5) + np.arange(5)\n\n def f(z):\n return jnp.cos(jnp.linalg.norm(2 * z))\n\n ans = jacrev(f)(zs)\n expected = grad(f)(zs)\n self.assertAllClose(ans, expected)\n\n def test_complex_input_jacfwd_raises_error(self):\n self.assertRaises(TypeError, lambda: jacfwd(lambda x: jnp.sin(x))(1 + 2j))\n\n def test_legacy_devicearray_repr(self):\n dx = device_put(3.)\n str(dx.item()) # doesn't crash\n\n def test_devicearray_repr(self):\n x = device_put(jnp.zeros(3))\n self.assertIsInstance(x, xla.DeviceArray)\n repr(x) # doesn't crash\n\n x = device_put(jnp.ones(3) + 1j * jnp.ones(3))\n self.assertIsInstance(x, xla.DeviceArray)\n repr(x) # doesn't crash\n\n def test_devicearray_delete(self):\n x = device_put(1.)\n x.delete()\n self.assertRaisesRegex(RuntimeError, \"DeviceArray has been deleted.\",\n lambda: repr(x))\n\n def test_devicearray_block_until_ready(self):\n x = device_put(1.)\n y = x.block_until_ready()\n # Tests mostly that block_until_ready() does not produce an error.\n self.assertTrue(y is x)\n\n def test_devicearray_weakref_friendly(self):\n x = device_put(1.)\n y = weakref.ref(x)\n self.assertEqual(y(), 1.)\n del x\n self.assertIsNone(y())\n\n def test_namedtuple_transparency(self):\n # See https://github.com/google/jax/issues/446\n Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n\n def f(pt):\n return jnp.sqrt(pt.x ** 2 + pt.y ** 2)\n\n pt = Point(1., 2.)\n\n f(pt) # doesn't crash\n g = api.grad(f)(pt)\n self.assertIsInstance(g, Point)\n\n f_jit = api.jit(f)\n self.assertAllClose(f(pt), f_jit(pt), check_dtypes=False)\n\n def test_namedtuple_subclass_transparency(self):\n # See https://github.com/google/jax/issues/806\n Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n\n class ZeroPoint(Point):\n def is_zero(self):\n return (self.x == 0) and (self.y == 0)\n\n pt = ZeroPoint(0., 0.)\n\n def f(pt):\n return 0. if pt.is_zero() else jnp.sqrt(pt.x ** 2 + pt.y ** 2)\n\n f(pt) # doesn't crash\n _ = api.grad(f)(pt)\n self.assertIsInstance(pt, ZeroPoint)\n\n @parameterized.parameters(1, 2, 3)\n def test_shape_dtype_struct(self, i):\n s = api.ShapeDtypeStruct(shape=(i, 2, 3), dtype=jnp.float32)\n self.assertEqual(s.shape, (i, 2, 3))\n self.assertEqual(s.dtype, jnp.float32)\n self.assertEqual(s.ndim, 3)\n self.assertEqual(s.size, i * 2 * 3)\n self.assertLen(s, i)\n for f in (str, repr):\n self.assertEqual(\n f(s), \"ShapeDtypeStruct(shape=({}, 2, 3), dtype=float32)\".format(i))\n\n def test_shape_dtype_struct_scalar(self):\n s = api.ShapeDtypeStruct(shape=(), dtype=jnp.float32)\n self.assertEmpty(s.shape)\n self.assertEqual(s.size, 1)\n self.assertEqual(s.ndim, 0)\n with self.assertRaisesRegex(TypeError, \"len[(][)] of unsized object\"):\n _ = len(s)\n\n def test_eval_shape(self):\n def fun(x, y):\n return jnp.tanh(jnp.dot(x, y) + 3.)\n\n x = jnp.ones((2, 3))\n y = jnp.ones((3, 4))\n out_shape = api.eval_shape(fun, x, y)\n\n self.assertEqual(out_shape.shape, (2, 4))\n\n def test_eval_shape_constants(self):\n def fun():\n x = jnp.ones((2, 3))\n y = jnp.ones((3, 4))\n return jnp.tanh(jnp.dot(x, y) + 3.)\n\n out_shape = api.eval_shape(fun)\n\n self.assertEqual(out_shape.shape, (2, 4))\n\n def test_eval_shape_tuple_unpacking(self):\n def fun(x, y):\n a, b = x\n return a + b + y\n\n x = (jnp.ones(2), jnp.ones(2))\n y = 3.\n out_shape = api.eval_shape(fun, x, y)\n\n self.assertEqual(out_shape.shape, (2,))\n\n def test_eval_shape_tuple_itemgetting(self):\n def fun(x, y):\n return x[0] + x[1] + y\n\n x = (jnp.ones(2), jnp.ones(2))\n y = 3.\n out_shape = api.eval_shape(fun, x, y)\n\n self.assertEqual(out_shape.shape, (2,))\n\n def test_eval_shape_output_dict(self):\n def fun(x, y):\n return {'hi': x[0] + x[1] + y}\n\n x = (jnp.ones(2), jnp.ones(2))\n y = 3.\n out_shape = api.eval_shape(fun, x, y)\n out_shape = tree_util.tree_map(np.shape, out_shape)\n\n self.assertEqual(out_shape, {'hi': (2,)})\n\n def test_eval_shape_shape_error(self):\n def fun(x, y):\n return jnp.tanh(jnp.dot(x, y) + 3.)\n\n x = jnp.ones((3, 3))\n y = jnp.ones((4, 4))\n\n self.assertRaises(TypeError, lambda: api.eval_shape(fun, x, y))\n\n def test_eval_shape_duck_typing(self):\n def fun(A, b, x):\n return jnp.dot(A, x) + b\n\n class MyArgArray(object):\n def __init__(self, shape, dtype):\n self.shape = shape\n self.dtype = dtype\n\n A = MyArgArray((3, 4), jnp.float32)\n b = MyArgArray((5,), jnp.float32)\n x = MyArgArray((4, 5), jnp.float32)\n out_shape = api.eval_shape(fun, A, b, x)\n\n self.assertEqual(out_shape.shape, (3, 5))\n\n def test_issue_871(self):\n T = jnp.array([[1., 2.], [3., 4.], [5., 6.]])\n x = jnp.array([1, 2, 3])\n msg = (\"linearized function called on tangent values inconsistent with \"\n \"the original primal values\")\n\n y, f_jvp = api.linearize(jnp.sum, x)\n with self.assertRaisesRegex(ValueError, msg):\n f_jvp(T)\n\n y, f_jvp = api.linearize(api.jit(jnp.sum), x)\n with self.assertRaisesRegex(ValueError, msg):\n f_jvp(T)\n\n def test_partial_eval_lower(self):\n # this is a simplified model of a bug that arose when we first used @jit in\n # a jvp rule. it's in this file because we want to use make_jaxpr.\n\n # NOTE(mattjj): I no longer understand what this was meant to test. My guess\n # is it was related to staging out the broadcast into a jaxpr to be\n # transposed, but after #1749 that's no longer a problem. After changing\n # make_jaxpr (and jit) to stage out sub-calls fully, this test started to\n # fail; I left it in as skipped because deleting tests feels wrong.\n raise unittest.SkipTest(\"obsolete test\")\n\n @api.jit\n def f(a, b, c):\n a = lax.broadcast(a, (2,))\n return lax.select(a, b, c)\n\n a = np.ones((3, 3), dtype=np.bool_)\n b = np.ones((2, 3, 3))\n c = np.ones((2, 3, 3))\n\n jaxpr = api.make_jaxpr(lambda b, c: f(a, b, c))(b, c)\n subjaxpr = next(eqn.params[\"call_jaxpr\"] for eqn in jaxpr.jaxpr.eqns\n if \"call_jaxpr\" in eqn.params)\n self.assertEqual(len(subjaxpr.eqns), 1)\n\n def test_grad_of_int_errors(self):\n # Errors without allow_int=True\n dfn = grad(lambda x: x ** 2)\n self.assertRaisesRegex(\n TypeError,\n (r\"grad requires real- or complex-valued inputs \\(input dtype that is a \"\n r\"sub-dtype of np.floating or np.complexfloating\\), but got int.*.\"),\n lambda: dfn(3))\n\n def test_jvp_of_int_identity(self):\n primals = (1,)\n tangents = (np.zeros(shape=(), dtype=float0),)\n\n _, out = api.jvp(lambda x: x, primals, tangents)\n self.assertEqual(out, np.zeros(shape=(), dtype=float0))\n\n def test_jvp_of_int_add(self):\n primals = (2,)\n tangents = (np.zeros(shape=(), dtype=float0),)\n\n _, out_tangent = api.jvp(lambda x: x+1, primals, tangents)\n self.assertEqual(out_tangent, np.zeros(shape=(), dtype=float0))\n\n def test_jit_jvp_of_int(self):\n primals = (2,)\n tangents = (np.zeros(shape=(), dtype=float0),)\n\n _, out_tangent = api.jvp(jax.jit(lambda x: x+1), primals, tangents)\n self.assertEqual(out_tangent, np.zeros(shape=(), dtype=float0))\n\n def test_vjp_of_int_index(self):\n primal, fn_vjp = api.vjp(lambda x, i: x[i], np.ones(2)*2, 1)\n tangent_x, tangent_i = fn_vjp(1.)\n self.assertEqual(primal, 2.)\n self.assertAllClose(tangent_x, jnp.array([0., 1.]))\n self.assertEqual(tangent_i, np.zeros(shape=(), dtype=float0))\n\n def test_vjp_of_int_shapes(self):\n out, fn_vjp = api.vjp(lambda x: lax.reshape(x, (2, 2)), np.ones((4, 1),\n dtype=int))\n tangent, = fn_vjp(out)\n self.assertArraysEqual(tangent, np.zeros(shape=(4, 1), dtype=float0))\n\n def test_jit_vjp_of_int(self):\n primal, fn_vjp = api.vjp(lambda x, y: x+y, 2, 1)\n tangent_x, tangent_i = jax.jit(fn_vjp)(1)\n self.assertEqual(primal, 3)\n self.assertEqual(tangent_x, np.zeros(shape=(), dtype=float0))\n self.assertEqual(tangent_i, np.zeros(shape=(), dtype=float0))\n\n def test_vjp_of_int_fulllike(self):\n # Regression test for tangent and cotangent mismatch in convert_element_type\n # transpose rule wrt a ConstVar\n f = lax.full_like\n out, vjp = api.vjp(f, np.zeros((2, 2)), 1)\n self.assertAllClose(out, jnp.ones((2, 2)))\n tangent_x, tangent_y = vjp(out)\n self.assertAllClose(tangent_x, jnp.zeros((2, 2)))\n self.assertEqual(tangent_y, np.zeros(shape=(), dtype=float0))\n\n def test_grad_of_int(self):\n # Need real-valued output, but testing integer input.\n out = api.grad(lambda x: x+0., allow_int=True)(1)\n self.assertEqual(out, np.zeros(shape=(), dtype=float0))\n\n def test_grad_of_bool(self):\n def cond(pred):\n return lax.cond(pred, lambda _: 1., lambda _: 2., 1.)\n value, grd = api.value_and_grad(cond, allow_int=True)(True)\n self.assertEqual(value, 1.)\n self.assertEqual(grd, np.zeros(shape=(), dtype=float0))\n\n def test_grad_of_int_index(self):\n grad_x, grad_i = api.grad(lambda x, i: x[i], argnums=(0, 1),\n allow_int=True)(np.ones(2), 1)\n self.assertAllClose(grad_x, jnp.array([0., 1.]))\n self.assertEqual(grad_i, np.zeros(shape=(), dtype=float0))\n\n def test_jit_grad_of_int(self):\n grad_f = api.grad(lambda x, i: x[i], argnums=(0, 1), allow_int=True)\n grad_x, grad_i = jax.jit(grad_f)(np.ones(2), 1)\n self.assertAllClose(grad_x, jnp.array([0., 1.]))\n self.assertEqual(grad_i, np.zeros(shape=(), dtype=float0))\n\n def test_float0_reshape(self):\n # dtype-agnostic operations are supported\n float0_array = jax.grad(lambda x: jnp.sum(x+0.),\n allow_int=True)(np.ones((2, 4), dtype=int))\n\n self.assertArraysEqual(float0_array.reshape((4, 2)),\n np.zeros((4, 2), dtype=float0))\n self.assertArraysEqual(float0_array.transpose(),\n np.zeros((4, 2), dtype=float0))\n\n def test_float0_error(self):\n # float0 is incompatible with other dtypes\n float0_array = jax.grad(lambda x: x+0., allow_int=True)(1)\n error_text = \"float0s do not support any operations by design\"\n\n with self.assertRaisesRegex(TypeError, error_text):\n # dispatch via DeviceArray\n _ = float0_array + jnp.zeros(())\n\n with self.assertRaisesRegex(TypeError, error_text):\n # dispatch via lax\n _ = lax.add(float0_array, jnp.zeros(()))\n\n def test_grad_complex_result_errors(self):\n dfn = grad(lambda x: x ** 2 + 1j)\n self.assertRaisesRegex(\n TypeError,\n (r\"grad requires real-valued outputs \\(output dtype that is a \"\n r\"sub-dtype of np.floating\\), but got complex.*\"),\n lambda: dfn(3.))\n\n def test_holomorphic_grad_of_float_errors(self):\n dfn = grad(lambda x: x ** 2, holomorphic=True)\n self.assertRaisesRegex(\n TypeError,\n (r\"grad with holomorphic=True requires inputs with complex dtype, \"\n r\"but got float.*\"),\n lambda: dfn(3.))\n\n def test_holomorphic_jacrev_of_float_errors(self):\n dfn = jacrev(lambda x: x ** 2, holomorphic=True)\n self.assertRaisesRegex(\n TypeError,\n (r\"jacrev with holomorphic=True requires inputs with complex dtype, \"\n r\"but got float.*\"),\n lambda: dfn(3.))\n\n def test_holomorphic_jacfwd_of_float_errors(self):\n dfn = jacfwd(lambda x: x ** 2, holomorphic=True)\n self.assertRaisesRegex(\n TypeError,\n (r\"jacfwd with holomorphic=True requires inputs with complex dtype, \"\n r\"but got float.*\"),\n lambda: dfn(3.))\n\n def test_jacfwd_of_complex_errors(self):\n dfn = jacfwd(lambda x: x ** 2)\n self.assertRaisesRegex(\n TypeError,\n (r\"jacfwd requires real-valued inputs \\(input dtype that is a \"\n r\"sub-dtype of np.floating\\), but got complex.*\"),\n lambda: dfn(3. + 1j))\n\n def test_xla_computation(self):\n # these tests basically check the examples in the xla_computation docstring\n\n def e(x):\n return jnp.sin(jnp.cos(x))\n c = api.xla_computation(e)(2.)\n self.assertIn('cosine', c.as_hlo_text())\n self.assertIn('sine', c.as_hlo_text())\n\n def f(x):\n return x - lax.psum(x, 'i')\n axis_env = [('i', 4)]\n c = api.xla_computation(f, axis_env=axis_env)(2)\n self.assertIn('all-reduce', c.as_hlo_text())\n self.assertIn('replica_groups={{0,1,2,3}}', c.as_hlo_text())\n\n def g(x):\n rowsum = lax.psum(x, 'i')\n colsum = lax.psum(x, 'j')\n allsum = lax.psum(x, ('i', 'j'))\n return rowsum, colsum, allsum\n axis_env = [('i', 4), ('j', 2)]\n c = api.xla_computation(g, axis_env=axis_env)(5.)\n self.assertIn('all-reduce', c.as_hlo_text())\n self.assertIn('replica_groups={{0,2,4,6},{1,3,5,7}}', c.as_hlo_text())\n self.assertIn('replica_groups={{0,1},{2,3},{4,5},{6,7}}', c.as_hlo_text())\n self.assertIn('replica_groups={{0,1,2,3,4,5,6,7}}', c.as_hlo_text())\n\n def h(x):\n rowsum = lax.psum(x, 'i', axis_index_groups=[[0, 1], [2, 3]])\n colsum = lax.psum(x, 'j')\n return rowsum, colsum\n axis_env = [('i', 4), ('j', 2)]\n c = api.xla_computation(h, axis_env=axis_env)(5.)\n self.assertIn('all-reduce', c.as_hlo_text())\n self.assertIn('replica_groups={{0,2},{4,6},{1,3},{5,7}}', c.as_hlo_text())\n self.assertIn('replica_groups={{0,1},{2,3},{4,5},{6,7}}', c.as_hlo_text())\n\n def test_xla_computation_args(self):\n def foo(x, y, z):\n return x + y + z\n\n c = api.xla_computation(foo)(1., 2., 3.)\n self.assertEqual(len(c.program_shape().parameter_shapes()), 3)\n\n c = api.xla_computation(foo, tuple_args=True)(1., 2., 3.)\n param_shapes = c.program_shape().parameter_shapes()\n self.assertEqual(len(param_shapes), 1)\n self.assertEqual(param_shapes[0].xla_element_type(),\n xb.xla_client.PrimitiveType.TUPLE)\n\n def test_xla_computation_duck_typing(self):\n def foo(x, y, z):\n return x + y + z\n\n x = jax.ShapeDtypeStruct((), np.float32)\n y = jax.ShapeDtypeStruct((), np.float32)\n z = jax.ShapeDtypeStruct((), np.float32)\n\n c = api.xla_computation(foo)(x, y, z)\n self.assertEqual(len(c.program_shape().parameter_shapes()), 3)\n\n c = api.xla_computation(foo, tuple_args=True)(1., 2., 3.)\n param_shapes = c.program_shape().parameter_shapes()\n self.assertEqual(len(param_shapes), 1)\n self.assertEqual(param_shapes[0].xla_element_type(),\n xb.xla_client.PrimitiveType.TUPLE)\n\n def test_staging_out_multi_replica(self):\n def f(x):\n return api.pmap(jnp.mean)(x)\n xla_comp = api.xla_computation(f)\n xla_comp(jnp.arange(8)).as_hlo_text() # doesn't crash\n\n def test_xla_computation_instantiate_constant_outputs(self):\n def f():\n return jnp.zeros((3, 4))\n\n if config.omnistaging_enabled:\n xla_comp = api.xla_computation(f)()\n else:\n xla_comp = api.xla_computation(f, instantiate_const_outputs=True)()\n out_shape, = xla_comp.program_shape().result_shape().tuple_shapes()\n self.assertEqual(out_shape.dimensions(), (3, 4))\n\n def test_xla_computation_static_argnums(self):\n def f(x, y):\n return x + y\n\n xla_comp = api.xla_computation(f, static_argnums=(1,))(2, 3)\n hlo_text = xla_comp.as_hlo_text()\n self.assertIn(\"constant(3)\", hlo_text)\n # The static arguments should be removed from the function being compiled,\n # thus the function should have only a single argument.\n self.assertIn(\"parameter.1\", hlo_text)\n self.assertNotIn(\"parameter.2\", hlo_text)\n\n def test_xla_computation_return_shape(self):\n _, shape_tree = api.xla_computation(lambda x: (x + 1, jnp.zeros(2, jnp.float32)),\n return_shape=True)(np.int32(1))\n expected = (api.ShapeDtypeStruct(shape=(), dtype=jnp.int32),\n api.ShapeDtypeStruct(shape=(2,), dtype=jnp.float32))\n self.assertEqual(shape_tree, expected)\n\n def test_xla_computation_partitioned(self):\n def f(x, y):\n return jnp.dot(x, y) + 1\n\n x = jax.ShapeDtypeStruct((8, 8), np.float32)\n y = jax.ShapeDtypeStruct((8, 16), np.float32)\n xla_comp = api.xla_computation(f, in_parts=(P(2, 2), None),\n out_parts=P(4, 1))(x, y)\n hlo_text = xla_comp.as_hlo_text()\n self.assertIn('sharding={devices=[2,2]0,1,2,3}', hlo_text)\n self.assertIn('sharding={replicated}', hlo_text)\n self.assertIn('sharding={{devices=[4,1]0,1,2,3}}', hlo_text)\n\n def test_xla_computation_replicated_and_partitioned(self):\n def f(x, y):\n return jnp.dot(x, y), lax.psum(x, 'i')\n\n x = jax.ShapeDtypeStruct((8, 8), np.float32)\n y = jax.ShapeDtypeStruct((8, 16), np.float32)\n axis_env = [('i', 4)]\n xla_comp = api.xla_computation(f, axis_env=axis_env,\n in_parts=(P(2, 2), None),\n out_parts=(P(4, 1), None))(x, y)\n hlo_text = xla_comp.as_hlo_text()\n self.assertIn('all-reduce', hlo_text)\n self.assertIn('replica_groups={{0,1,2,3}}', hlo_text)\n self.assertIn('sharding={devices=[2,2]0,1,2,3}', hlo_text)\n self.assertIn('sharding={replicated}', hlo_text)\n self.assertIn('sharding={{devices=[4,1]0,1,2,3}, {replicated}}', hlo_text)\n\n def test_xla_computation_psum_constant(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test requires omnistaging\")\n f = lambda: jax.lax.psum(1, \"i\")\n api.xla_computation(f, axis_env=[(\"i\", 2)])() # doesn't crash\n\n @jtu.skip_on_devices(\"cpu\", \"gpu\")\n def test_xla_computation_donate_argnums(self):\n api.xla_computation(lambda x: None, donate_argnums=(0,))(3) # doesn't crash\n\n def test_concurrent_device_get_and_put(self):\n def f(x):\n for _ in range(100):\n y = jax.device_put(x)\n x = jax.device_get(y)\n return x\n\n xs = [np.random.randn(i) for i in range(10)]\n with concurrent.futures.ThreadPoolExecutor() as executor:\n futures = [executor.submit(partial(f, x)) for x in xs]\n ys = [f.result() for f in futures]\n for x, y in zip(xs, ys):\n self.assertAllClose(x, y)\n\n def test_dtype_warning(self):\n # cf. issue #1230\n if config.x64_enabled:\n raise unittest.SkipTest(\"test only applies when x64 is disabled\")\n\n def check_warning(warn, nowarn):\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n\n nowarn() # get rid of extra startup warning\n\n prev_len = len(w)\n nowarn()\n assert len(w) == prev_len\n\n warn()\n assert len(w) > 0\n msg = str(w[-1].message)\n expected_prefix = \"Explicitly requested dtype \"\n self.assertEqual(expected_prefix, msg[:len(expected_prefix)])\n\n prev_len = len(w)\n nowarn()\n assert len(w) == prev_len\n\n check_warning(lambda: jnp.array([1, 2, 3], dtype=\"float64\"),\n lambda: jnp.array([1, 2, 3], dtype=\"float32\"))\n check_warning(lambda: jnp.array([1, 2, 3], dtype=\"float64\"),\n lambda: jnp.array([1, 2, 3], dtype=float))\n check_warning(lambda: jnp.ones(3, dtype=np.float64),\n lambda: jnp.ones(3))\n check_warning(lambda: jnp.ones(3, dtype=np.float64),\n lambda: jnp.ones(3, dtype=float))\n check_warning(lambda: jnp.ones_like(3, dtype=np.int64),\n lambda: jnp.ones_like(3, dtype=np.int32))\n check_warning(lambda: jnp.zeros(3, dtype=\"int64\"),\n lambda: jnp.zeros(3, dtype=\"int32\"))\n check_warning(lambda: jnp.zeros_like(3, dtype=\"float64\"),\n lambda: jnp.zeros_like(3, dtype=\"float32\"))\n check_warning(lambda: jnp.full((2, 3), 1, dtype=\"int64\"),\n lambda: jnp.full((2, 3), 1))\n check_warning(lambda: jnp.ones(3).astype(\"float64\"),\n lambda: jnp.ones(3).astype(\"float32\"))\n check_warning(lambda: jnp.eye(3, dtype=np.float64),\n lambda: jnp.eye(3))\n check_warning(lambda: jnp.arange(3, dtype=np.float64),\n lambda: jnp.arange(3, dtype=np.float32))\n check_warning(lambda: jnp.linspace(0, 3, dtype=np.float64),\n lambda: jnp.linspace(0, 3, dtype=np.float32))\n check_warning(lambda: jnp.tri(2, dtype=\"float64\"),\n lambda: jnp.tri(2, dtype=\"float32\"))\n check_warning(lambda: jnp.arange(1).astype(\"float64\"),\n lambda: jnp.arange(1).astype(float))\n check_warning(lambda: jnp.arange(1.0).astype(\"int64\"),\n lambda: jnp.arange(1.0).astype(int))\n\n def test_vmap_preserves_docstr(self):\n def superfun(a):\n \"\"\"Does things with stuff.\"\"\"\n pass\n\n self.assertRegex(api.vmap(superfun).__doc__, \"\\n\".join([\n \"Vectorized version of superfun.*\",\n \"\",\n \"Original documentation:\",\n \"\",\n superfun.__doc__,\n ]))\n\n def test_vmap_in_axes_list(self):\n # https://github.com/google/jax/issues/2367\n dictionary = {'a': 5., 'b': jnp.ones(2)}\n x = jnp.zeros(3)\n y = jnp.arange(3.)\n\n\n def f(dct, x, y):\n return dct['a'] + dct['b'] + x + y\n\n out1 = api.vmap(f, (None, 0, 0))(dictionary, x, y)\n out2 = api.vmap(f, [None, 0, 0])(dictionary, x, y)\n self.assertAllClose(out1, out2)\n\n def test_vmap_in_axes_tree_prefix_error(self):\n # https://github.com/google/jax/issues/795\n self.assertRaisesRegex(\n ValueError,\n \"vmap in_axes specification must be a tree prefix of the corresponding \"\n r\"value, got specification \\(0, 0\\) for value tree \"\n r\"PyTreeDef\\(tuple, \\[\\*\\]\\).\",\n lambda: api.vmap(lambda x: x, in_axes=(0, 0))(jnp.ones(3))\n )\n\n def test_vmap_in_axes_leaf_types(self):\n with self.assertRaisesRegex(\n TypeError, r\"vmap in_axes must be an int, None, or .*\"):\n api.vmap(lambda x: x, in_axes=(jnp.array([1., 2.]),))(jnp.array([1., 2.]))\n\n def test_vmap_out_axes_leaf_types(self):\n with self.assertRaisesRegex(\n TypeError, r\"vmap out_axes must be an int, None, or .*\"):\n api.vmap(lambda x: x, out_axes=(jnp.array([1., 2.]),))(jnp.array([1., 2.]))\n\n def test_vmap_unbatched_object_passthrough_issue_183(self):\n # https://github.com/google/jax/issues/183\n fun = lambda f, x: f(x)\n vfun = api.vmap(fun, (None, 0))\n ans = vfun(lambda x: x + 1, jnp.arange(3))\n self.assertAllClose(ans, np.arange(1, 4), check_dtypes=False)\n\n def test_vmap_mismatched_axis_sizes_error_message_issue_705(self):\n # https://github.com/google/jax/issues/705\n def h(a, b):\n return jnp.sum(a) + jnp.sum(b)\n\n X = np.random.randn(10, 4)\n U = np.random.randn(10, 2)\n\n with self.assertRaisesRegex(\n ValueError,\n \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n r\"arg 0 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n r\"arg 1 has shape \\(10, 2\\) and axis 1 is to be mapped\" \"\\n\"\n \"so\\n\"\n \"arg 0 has an axis to be mapped of size 10\\n\"\n \"arg 1 has an axis to be mapped of size 2\"):\n api.vmap(h, in_axes=(0, 1))(X, U)\n\n with self.assertRaisesRegex(\n ValueError,\n \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n r\"arg 0 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n r\"arg 1 has shape \\(10, 2\\) and axis 1 is to be mapped\" \"\\n\"\n r\"arg 2 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n \"so\\n\"\n \"args 0, 2 have axes to be mapped of size 10\\n\"\n \"arg 1 has an axis to be mapped of size 2\"):\n api.vmap(lambda x, y, z: None, in_axes=(0, 1, 0))(X, U, X)\n\n with self.assertRaisesRegex(\n ValueError,\n \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n \"the tree of axis sizes is:\\n\"\n r\"\\(10, \\[2, 2\\]\\)\"):\n api.vmap(h, in_axes=(0, 1))(X, [U, U])\n\n with self.assertRaisesRegex(\n ValueError, \"vmap got arg 0 of rank 0 but axis to be mapped 0\"):\n # The mapped inputs cannot be scalars\n api.vmap(lambda x: x)(1.)\n\n with self.assertRaisesRegex(\n ValueError, \"vmap must have at least one non-None value in in_axes\"):\n # If the output is mapped, there must be a non-None in_axes\n api.vmap(lambda x: x, in_axes=None)(jnp.array([1., 2.]))\n\n with self.assertRaisesRegex(\n ValueError, \"vmap got arg 0 of rank 1 but axis to be mapped 1\"):\n api.vmap(lambda x: x, in_axes=1)(jnp.array([1., 2.]))\n\n # Error is: TypeError: only integer scalar arrays can be converted to a scalar index\n with self.assertRaisesRegex(\n ValueError,\n \"vmap out_axes specification must be a tree prefix of the \"\n \"corresponding value.*\"):\n api.vmap(lambda x: x, in_axes=0, out_axes=(2, 3))(jnp.array([1., 2.]))\n\n with self.assertRaisesRegex(\n ValueError, \"vmap has mapped output but out_axes is None\"):\n # If the output is mapped, then there must be some out_axes specified\n api.vmap(lambda x: x, out_axes=None)(jnp.array([1., 2.]))\n\n def test_vmap_structured_in_axes(self):\n\n A, B, C, D = 2, 3, 4, 5\n K = 6 # batch size\n x = np.ones((K, A, B)) # batch axis in different locations\n y = np.ones((B, K, C))\n z = np.ones((C, D, K))\n\n def foo(tree_arg):\n x, (y, z) = tree_arg\n return jnp.dot(x, jnp.dot(y, z))\n\n tree = (x, (y, z))\n vfoo = api.vmap(foo, in_axes=((0, (1, 2)),))\n self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n\n Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n tree = (x, Point(y, z))\n vfoo = api.vmap(foo, in_axes=((0, Point(1, 2)),))\n self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n\n def foo(tree_arg):\n x, dct = tree_arg\n y, z = dct['a'], dct['b']\n return jnp.dot(x, jnp.dot(y, z))\n\n tree = (x, {'a': y, 'b': z})\n vfoo = api.vmap(foo, in_axes=((0, {'a': 1, 'b': 2}),))\n self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n\n tree = (x, collections.OrderedDict([('a', y), ('b', z)]))\n vfoo = api.vmap(\n foo, in_axes=((0, collections.OrderedDict([('a', 1), ('b', 2)])),))\n self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n\n def test_pmap_global_cache(self):\n def f(x, y):\n return x, y\n\n x = np.ones((1, 1, 1))\n\n # All defaults\n with jtu.assert_num_jit_and_pmap_compilations(1):\n for _ in range(2):\n api.pmap(f)(x, x)\n\n # With axis name\n with jtu.assert_num_jit_and_pmap_compilations(1):\n for _ in range(2):\n api.pmap(f, 'i')(x, x)\n\n # With in_axes and out_axes\n if config.omnistaging_enabled:\n for x_in, y_in, x_out, y_out in it.product(*((0, 1, 2) for _ in range(4))):\n with jtu.assert_num_jit_and_pmap_compilations(1):\n for _ in range(2):\n api.pmap(f, 'i', in_axes=(x_in, y_in), out_axes=(x_out, y_out))(x, x)\n\n # Forward-mode AD on the outside\n with jtu.assert_num_jit_and_pmap_compilations(1):\n for _ in range(2):\n api.jvp(api.pmap(f), (x, x), (x, x))\n\n # Reverse-mode AD on the outside. One compilation for forward, one for backward.\n with jtu.assert_num_jit_and_pmap_compilations(2):\n for _ in range(2):\n api.vjp(api.pmap(f), x, x)[1]((x, x))\n\n def test_device_array_repr(self):\n rep = jnp.ones(()) + 1.\n self.assertStartsWith(repr(rep), \"DeviceArray\")\n\n def test_device_array_hash(self):\n rep = jnp.ones(()) + 1.\n self.assertIsInstance(rep, jax.interpreters.xla._DeviceArray)\n msg = \"JAX DeviceArray, like numpy.ndarray, is not hashable.\"\n with self.assertRaisesRegex(TypeError, msg):\n hash(rep)\n with self.assertRaisesRegex(TypeError, msg):\n hash(rep.device_buffer)\n\n def test_grad_without_enough_args_error_message(self):\n # https://github.com/google/jax/issues/1696\n def f(x, y): return x + y\n df = api.grad(f, argnums=0)\n self.assertRaisesRegex(\n TypeError,\n \"differentiating with respect to argnums=0 requires at least 1 \"\n \"positional arguments to be passed by the caller, but got only 0 \"\n \"positional arguments.\",\n lambda: partial(df, x=0.)(y=1.))\n\n def test_grad_of_jit_compilation_caching(self):\n if not hasattr(self, \"assertLogs\"):\n raise unittest.SkipTest(\"test requires assertLogs (python 3)\")\n\n lax.add(1, 2) # make sure some initial warnings are already printed\n\n sin = api.jit(jnp.sin)\n\n prev_level = logging.get_verbosity()\n try:\n logging.set_verbosity('DEBUG')\n with self.assertLogs(level=logging.DEBUG) as l:\n ans1 = api.grad(sin)(2.)\n ans2 = api.grad(sin)(3.)\n finally:\n logging.set_verbosity(prev_level)\n self.assertLen(l.output, 2)\n\n self.assertAllClose(ans1, np.cos(2.), check_dtypes=False)\n self.assertAllClose(ans2, np.cos(3.), check_dtypes=False)\n\n def test_trivial_computations(self):\n x = jnp.array([1, 2, 3])\n y = api.jit(lambda x: x)(x)\n self.assertIs(x, y)\n\n z1, z2 = api.jit(lambda x: (x, x))(x)\n self.assertIs(z1, z2)\n\n x1, x2 = jnp.array([1, 2]), jnp.array([2, 3])\n z1, z2, z3 = api.jit(lambda x, y: (y, 1, x))(x1, x2)\n self.assertIs(z1, x2)\n self.assertIs(z3, x1)\n self.assertEqual(z2, 1)\n\n def test_nested_jit_hoisting(self):\n @api.jit\n def f(x, y):\n z = 2 * x\n return y + z, 3\n\n @api.jit\n def g(x):\n return f(2, x)\n\n jaxpr_subcomp = xla.jaxpr_subcomp\n\n jaxprs = []\n def jaxpr_subcomp_and_collect(c, jaxpr, *args, **kwargs):\n jaxprs.append(jaxpr)\n return jaxpr_subcomp(c, jaxpr, *args, **kwargs)\n\n try:\n xla.jaxpr_subcomp = jaxpr_subcomp_and_collect\n ans = g(3)\n finally:\n xla.jaxpr_subcomp = jaxpr_subcomp\n\n self.assertEqual(ans, (7, 3))\n self.assertLen(jaxprs, 2)\n outer_jaxpr, inner_jaxpr = jaxprs\n\n self.assertLen(outer_jaxpr.eqns, 1)\n self.assertEqual(outer_jaxpr.eqns[0].primitive.name, 'xla_call')\n subjaxpr_1 = outer_jaxpr.eqns[0].params[\"call_jaxpr\"]\n self.assertEqual(str(subjaxpr_1), str(inner_jaxpr))\n self.assertLen(inner_jaxpr.eqns, 2)\n self.assertEqual(inner_jaxpr.eqns[0].primitive.name, 'mul')\n self.assertEqual(inner_jaxpr.eqns[1].primitive.name, 'add')\n\n def test_primitive_compilation_cache(self):\n with jtu.count_primitive_compiles() as count:\n lax.add(1, 2)\n lax.add(2, 3)\n self.assertEqual(count[0], 1)\n\n def test_arange_jit(self):\n # see https://github.com/google/jax/issues/553\n def fun(x):\n r = jnp.arange(x.shape[0])[x]\n return r\n\n jit(fun)(jnp.array([0, 1, 2], dtype=jnp.int32)) # doesn't crash\n\n def helper_save_tracer(self, x):\n self._saved_tracer = x\n return x\n\n def test_escaped_tracers_different_top_level_traces(self):\n api.jit(self.helper_save_tracer)(0.)\n with self.assertRaisesRegex(\n core.UnexpectedTracerError, \"Encountered an unexpected tracer\"):\n api.jit(lambda x: self._saved_tracer)(0.)\n\n def test_escaped_tracers_cant_lift_sublevels(self):\n api.jit(self.helper_save_tracer)(0.)\n with self.assertRaisesRegex(\n core.UnexpectedTracerError,\n re.compile(\n \"Encountered an unexpected tracer\",\n re.DOTALL)):\n api.jit(lambda x: x)(self._saved_tracer)\n\n def test_escaped_tracers_tracer_from_higher_level(self):\n api.grad(self.helper_save_tracer)(0.)\n with self.assertRaisesRegex(\n core.UnexpectedTracerError,\n re.compile(\n \"Encountered an unexpected tracer.*Tracer from a higher level\",\n re.DOTALL)):\n api.grad(lambda x: x)(self._saved_tracer)\n\n def test_escaped_tracers_incompatible_sublevel(self):\n def func1(x):\n api.jit(self.helper_save_tracer)(0.)\n # Use the tracer\n return x + self._saved_tracer\n with self.assertRaisesRegex(\n core.UnexpectedTracerError,\n re.compile(\"Encountered an unexpected tracer\",\n re.DOTALL)):\n api.jit(func1)(2.)\n\n def test_escaped_tracers_cant_lift(self):\n def func1(x):\n api.grad(self.helper_save_tracer)(0.)\n return x + self._saved_tracer\n with self.assertRaisesRegex(\n core.UnexpectedTracerError,\n re.compile(\"Encountered an unexpected tracer.*Can't lift\",\n re.DOTALL)):\n api.grad(func1)(2.)\n\n def test_escaped_tracers_not_among_input_tracers(self):\n def func1(x):\n api.grad(self.helper_save_tracer)(x)\n # Use the tracer\n return x + self._saved_tracer\n\n with self.assertRaisesRegex(\n core.UnexpectedTracerError,\n re.compile(\n \"Encountered an unexpected tracer.*Tracer not among input tracers\",\n re.DOTALL)):\n api.jit(func1)(2.)\n\n def test_escaped_tracer_omnistaging(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test is omnistaging-specific\")\n\n count = 1\n\n @jit\n def f():\n nonlocal count\n count = jnp.add(count, 1)\n f() # leaked a tracer! but currently undetected\n\n def f(x, c):\n jnp.add(count, 1)\n return None, None\n\n @jit\n def g():\n lax.scan(f, None, None, length=2)\n\n with self.assertRaisesRegex(core.UnexpectedTracerError,\n \"was created on line\"):\n g()\n\n def test_escaped_tracer_omnistaging_top_trace(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test is omnistaging-specific\")\n\n count = 1\n\n def f(_, __):\n nonlocal count\n count = jnp.add(count, 1)\n return None, None\n\n lax.scan(f, None, None, length=2) # leaked a tracer! (of level 1!)\n\n with self.assertRaisesRegex(core.UnexpectedTracerError,\n \"was created on line\"):\n # The following call will try and raise the ones array to the count tracer\n # level, which is no longer live.\n jax.jit(jnp.add)(jnp.ones(()), count)\n\n def test_pmap_static_kwarg_error_message(self):\n # https://github.com/google/jax/issues/3007\n def f(a, b):\n return a + b\n\n g = jax.pmap(f, static_broadcasted_argnums=(1,))\n\n msg = (r\"pmapped function has static_broadcasted_argnums=\\(1,\\) but was \"\n r\"called with only 1 positional argument. All static broadcasted \"\n r\"arguments must be passed positionally.\")\n with self.assertRaisesRegex(ValueError, msg):\n g(jnp.ones((1, 1)), b=1)\n\n def test_vmap_unmapped_last(self):\n @partial(jax.vmap, out_axes=-1)\n def f(x):\n return np.zeros((2,))\n f(np.zeros((5,)))\n\n # TODO(jakevdp): re-enable this if possible.\n @unittest.skipIf(True, \"broken by convert_element_type change.\")\n def test_xla_constant_dedup(self):\n y = np.array([7, 14], dtype=np.float32)\n def f(x):\n return x + y + y\n\n x = np.array([1, 2], dtype=np.float32)\n hlo_lines = jax.xla_computation(f)(x).as_hlo_text().split('\\n')\n hlo_lines = set([s.strip() for s in hlo_lines])\n self.assertIn('constant.1 = f32[2]{0} constant({7, 14})', hlo_lines)\n self.assertNotIn('constant.2 = f32[2]{0} constant({7, 14})', hlo_lines)\n\n def test_omnistaging_flag(self):\n if FLAGS.jax_omnistaging:\n jaxpr = api.make_jaxpr(lambda: jnp.add(1, 1))()\n self.assertLen(jaxpr.jaxpr.eqns, 1)\n else:\n # omnistaging can be enabled programmatically without setting the flag,\n # but that shouldn't happen in tests\n jaxpr = api.make_jaxpr(lambda: jnp.add(1, 1))()\n self.assertLen(jaxpr.jaxpr.eqns, 0)\n\n def test_eval_context(self):\n @jit\n def f():\n with core.eval_context():\n assert jnp.add(1, 1) == 2\n\n f() # doesn't crash\n\n def test_concrete_error_because_arg(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test is omnistaging-specific\")\n\n @jax.jit\n def f(x, y):\n if x > y:\n return x\n else:\n return y\n\n msg = r\"at flattened positions \\[0, 1\\]\"\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f(1, 2)\n\n def test_concrete_error_because_const(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test is omnistaging-specific\")\n\n @jax.jit\n def f():\n assert jnp.add(1, 1) > 0\n\n msg = \"on these lines\"\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f()\n\n # TODO(jakevdp): re-enable this if possible.\n @unittest.skipIf(True, \"broken by convert_element_type change.\")\n def test_xla_computation_zeros_doesnt_device_put(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test is omnistaging-specific\")\n\n count = 0\n def device_put_and_count(*args, **kwargs):\n nonlocal count\n count += 1\n return orig_device_put(*args, **kwargs)\n orig_device_put, xla.device_put = xla.device_put, device_put_and_count\n try:\n api.xla_computation(lambda: jnp.zeros(3))()\n finally:\n xla.device_put = orig_device_put\n self.assertEqual(count, 0)\n\n def test_join_concrete_arrays_with_omnistaging(self):\n # https://github.com/google/jax/issues/4622\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test is omnistaging-specific\")\n\n x = jnp.array([1., 2., 3.])\n y = jnp.array([1., 2., 4.])\n\n @jit\n def f():\n core.lattice_join(core.ConcreteArray(x), core.ConcreteArray(y))\n\n f() # doesn't crash\n\n def test_linearize_aval_error(self):\n # https://github.com/google/jax/issues/4622\n f = lambda x: x\n\n # these should not error\n _, f_jvp = api.linearize(f, 1.)\n f_jvp(1.)\n _, f_jvp = api.linearize(f, np.ones(2, np.int32))\n f_jvp(np.zeros(2, float0))\n\n # these should error\n _, f_jvp = api.linearize(f, 1.)\n with self.assertRaisesRegex(ValueError, \"tangent values inconsistent\"):\n f_jvp(1)\n _, f_jvp = api.linearize(f, np.ones(2, np.int32))\n with self.assertRaisesRegex(ValueError, \"tangent values inconsistent\"):\n f_jvp(np.ones(2, np.int32))\n\n def test_grad_of_token_consuming_primitive(self):\n # https://github.com/google/jax/issues/5463\n tokentest_p = core.Primitive(\"tokentest\")\n tokentest_p.def_impl(partial(xla.apply_primitive, tokentest_p))\n tokentest_p.def_abstract_eval(lambda x, y: x)\n xla.translations[tokentest_p] = lambda c, x, y: x\n ad.defjvp(tokentest_p, (lambda g, x, token: x), None)\n\n token = jax.lax.create_token(123)\n arr = jnp.ones((3, 2))\n res, vjp_fun = jax.vjp(lambda x: tokentest_p.bind(x, token), arr)\n # Should not crash.\n vjp_fun(arr)\n\n def test_leak_checker_catches_a_jit_leak(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n with core.checking_leaks():\n lst = []\n\n @jit\n def f(x):\n lst.append(x)\n return x\n\n with self.assertRaisesRegex(Exception, r\"Leaked trace\"):\n f(3)\n\n def test_leak_checker_catches_a_pmap_leak(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n with core.checking_leaks():\n lst = []\n\n @api.pmap\n def f(x):\n lst.append(x)\n return x\n\n with self.assertRaisesRegex(Exception, r\"Leaked trace\"):\n f(np.ones(1))\n\n def test_leak_checker_catches_a_grad_leak(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n with core.checking_leaks():\n lst = []\n\n def f(x):\n lst.append(x)\n return x\n\n with self.assertRaisesRegex(Exception, r\"Leaked trace\"):\n api.grad(f)(3.)\n\n def test_leak_checker_avoids_false_positives(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n with core.checking_leaks():\n @jit\n def f(x):\n return x\n f(3) # doesn't crash\n api.vmap(f)(np.arange(3)) # doesn't crash\n api.grad(f)(3.) # doesn't crash\n\n @api.pmap\n def f(x):\n return x\n f(np.ones(1)) # doesn't crash\n api.vmap(f)(np.ones((1, 1))) # doesn't crash\n\n def test_leak_checker_catches_a_scan_leak(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n with core.checking_leaks():\n lst = []\n\n to_scan = lambda c, x: (lst.append(c) or jnp.sin(c), None)\n\n with self.assertRaisesRegex(Exception, r\"Leaked trace\"):\n lax.scan(to_scan, 1., np.arange(3.))\n\n def test_leak_checker_avoids_false_positives_scan(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n with core.checking_leaks():\n to_scan = lambda c, x: (jnp.sin(c), None)\n lax.scan(to_scan, 1., np.arange(3.)) # doesn't crash\n\n def test_leak_checker_avoids_false_positives_scan_jvp(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n with core.checking_leaks():\n to_scan = lambda c, x: (c, None)\n\n def f(x):\n lax.scan(to_scan, x, None, length=1)\n api.jvp(f, (3.,), (1.,)) # doesn't crash\n\n def test_leak_checker_avoids_false_positives_scan_vmap(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n with core.checking_leaks():\n to_scan = lambda c, _: (1., None)\n\n @api.vmap\n def f(x):\n lax.scan(to_scan, x, None, length=1)\n f(np.arange(5.)) # doesn't crash\n\n def test_leak_checker_avoids_false_positives_scan_vmap_2(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n with core.checking_leaks():\n to_scan = lambda c, _: (c, None)\n\n @api.vmap\n def f(x):\n lax.scan(to_scan, x, None, length=1)\n f(np.arange(5.)) # doesn't crash\n\n def test_default_backend(self):\n first_local_device = api.local_devices()[0]\n self.assertEqual(first_local_device.platform, api.default_backend())\n\n\nclass RematTest(jtu.JaxTestCase):\n\n def test_remat_basic(self):\n @api.remat\n def g(x):\n return lax.sin(lax.sin(x)), 3.\n\n def f(x):\n x, _ = g(x)\n return x\n\n ans = f(2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans, f_lin = api.linearize(f, 2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = f_lin(3.)\n expected = np.cos(np.sin(2.)) * np.cos(2.) * 3.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n sin_calls = []\n cos_calls = []\n sin_impl = lax.sin_p.impl\n cos_impl = lax.cos_p.impl\n try:\n lax.sin_p.def_impl(lambda x: sin_calls.append(1) or sin_impl(x))\n lax.cos_p.def_impl(lambda x: cos_calls.append(1) or cos_impl(x))\n f_lin(3.)\n finally:\n lax.sin_p.def_impl(sin_impl)\n lax.cos_p.def_impl(cos_impl)\n self.assertEqual(len(sin_calls), 1)\n self.assertEqual(len(cos_calls), 2)\n\n def test_remat_freevars(self):\n def f1(x):\n y = 2 * jnp.sin(x)\n z = jnp.cos(x) * jnp.sin(y)\n return z\n\n def f2(x):\n y = 2 * jnp.sin(x)\n z = api.remat(lambda x: jnp.cos(x) * jnp.sin(y))(x)\n return z\n\n ans, f_lin = api.linearize(f2, 2.)\n expected, f_lin_expected = api.linearize(f1, 2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = f_lin(3.)\n expected = f_lin_expected(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_grad_python_control_flow(self):\n @partial(api.remat, concrete=True)\n def g(x):\n if x > 0:\n return lax.sin(x), 3.\n else:\n return lax.cos(x), 4.\n\n def f(x):\n x, _ = g(x)\n return x\n\n ans = f(2.)\n expected = np.sin(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(f)(2.)\n expected = np.cos(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_jit(self):\n @api.remat\n def g(x):\n return lax.sin(lax.sin(x))\n\n def f_(x):\n return g(x)\n f = api.jit(f_)\n\n ans = f(2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(f)(2.)\n expected = np.cos(np.sin(2.)) * np.cos(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(f_))(2.)\n expected = np.cos(np.sin(2.)) * np.cos(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_vmap(self):\n @api.remat\n def g(x):\n return lax.sin(lax.sin(x))\n\n x = np.arange(3.)\n\n ans = api.vmap(g)(x)\n expected = np.sin(np.sin(x))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jacfwd(g)(x)\n expected = np.diag(np.cos(np.sin(x)) * np.cos(x))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jacrev(g)(x)\n expected = np.diag(np.cos(np.sin(x)) * np.cos(x))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_higher_order_autodiff(self):\n def f(x):\n return lax.cos(lax.sin(x))\n g = api.remat(f)\n\n ans = api.grad(api.grad(g))(3.)\n expected = api.grad(api.grad(f))(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_scan(self):\n to_scan = lambda c, x: (jnp.sin(c), None)\n\n def f_noremat(x):\n y, _ = lax.scan(to_scan, x, np.arange(3.))\n return y\n\n def f_yesremat(x):\n y, _ = lax.scan(api.remat(to_scan), x, np.arange(3.))\n return y\n\n ans = f_yesremat(4.)\n expected = f_noremat(4.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(f_yesremat)(4.)\n expected = api.grad(f_noremat)(4.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n jaxpr = api.make_jaxpr(api.linearize(f_yesremat, 4.)[1])(1.)\n scan_eqn, = jaxpr.jaxpr.eqns\n self.assertIn(' cos ', str(scan_eqn.params['jaxpr']))\n\n jaxpr = api.make_jaxpr(api.vjp(f_yesremat, 4.)[1])(1.)\n scan_eqn, = jaxpr.jaxpr.eqns\n self.assertIn(' cos ', str(scan_eqn.params['jaxpr']))\n\n def test_remat_no_redundant_flops(self):\n # see https://github.com/google/jax/pull/1749#issuecomment-558267584\n\n @api.jit\n def g(x):\n return f(2., x)\n\n @api.remat\n def f(x, y):\n return jnp.sin(x) * y\n\n # We swap out sin_p's impl rule to count how many times it's invoked\n called = []\n sin_impl = lax.sin_p.impl\n try:\n lax.sin_p.def_impl(lambda x: called.append(1) or sin_impl(x))\n api.grad(g)(3.)\n finally:\n lax.sin_p.def_impl(sin_impl)\n num_calls = len(called)\n self.assertLessEqual(num_calls, 1)\n\n def test_remat_binomial_checkpointing(self):\n def binom_checkpoint(funs):\n if len(funs) == 1:\n return funs[0]\n else:\n f1 = binom_checkpoint(funs[:len(funs)//2])\n f2 = binom_checkpoint(funs[len(funs)//2:])\n return api.remat(lambda x: f1(f2(x)))\n\n f1 = binom_checkpoint([jnp.sin, jnp.sin, jnp.sin, jnp.sin])\n f2 = lambda x: jnp.sin(jnp.sin(jnp.sin(jnp.sin(x))))\n x = 4.\n self.assertAllClose(f1(x), f2(x), check_dtypes=False)\n self.assertAllClose(api.grad(f1)(x), api.grad(f2)(x), check_dtypes=False)\n\n def test_remat_symbolic_zeros(self):\n # code from https://github.com/google/jax/issues/1907\n\n key = jax.random.PRNGKey(0)\n key, split = jax.random.split(key)\n n = 5\n\n def func(D0):\n def shift(R, dR, **unused_kwargs):\n return R + dR\n\n def apply_fn(R):\n return D0 * R\n\n Rinit = jax.random.uniform(split, (n,3), minval=0.0, maxval=5.0,\n dtype=jnp.float32)\n\n def move(R,i):\n F = apply_fn(R)\n return shift(R, 0.001 * F), jnp.array([0.])\n\n move = api.remat(move)\n R, temp = lax.scan(move, Rinit, jnp.arange(2))\n return R[0, 0]\n\n api.grad(func)(5.0) # doesn't crash\n\n def test_remat_jit2(self):\n @api.jit\n def f(x):\n y = 2 * x\n\n @api.remat\n def g():\n return y\n\n return g()\n\n self.assertAllClose(f(3), 6, check_dtypes=False)\n\n def test_remat_nontrivial_env(self):\n # simplified from https://github.com/google/jax/issues/2030\n\n @api.remat\n def foo(state, dt=0.5, c=1):\n u, u_t = state\n u_tt = c**2 * u\n u_t = u_t + u_tt * dt\n return (u, u_t)\n\n @partial(api.jit, static_argnums=(1,))\n def _multi_step(state, count, dt, c):\n f = lambda s, _: (foo(s, dt, c), _)\n return lax.scan(f, state, None, count)\n\n def multi_step(state, count, dt=1/jnp.sqrt(2), c=1):\n return _multi_step(state, count, dt, c)\n\n def loss(u0, target, steps, dt=1/jnp.sqrt(2), c=1):\n init = (u0, jnp.zeros_like(u0))\n (uf, _), _ = multi_step(init, steps, dt, c)\n return ((uf - target) ** 2).mean()\n\n target = jnp.zeros((128, 128))\n u0 = jnp.ones_like(target)\n loss(u0, target, 10) # doesn't crash\n\n def test_remat_jit3(self):\n # https://github.com/google/jax/issues/2180\n def f(w, x):\n a = jnp.dot(x, w)\n b = jnp.einsum(\"btd,bTd->btT\", a, a)\n c = jnp.einsum(\"btT,btd->btd\", b, a)\n return jnp.sum(c)\n\n w = jnp.ones([1, 1])\n x = jnp.ones([1, 1, 1])\n f = api.remat(f)\n api.grad(f)(w, x) # doesn't crash\n\n @api.jit\n def mul(a, b):\n return a * b\n\n def f(w, x):\n a = mul(w, x)\n b = mul(a, a)\n return b\n\n w = 1.\n x = 1.\n f = api.remat(f)\n api.grad(f)(w, x) # doesn't crash\n\n def test_remat_scan2(self):\n # https://github.com/google/jax/issues/1963\n\n def scan_bug(x0):\n f = lambda x, _: (x + 1, None)\n def scanned_f(x, _):\n return lax.scan(f, x, xs=None, length=1)[0], None\n x, _ = jax.remat(scanned_f)(x0, None)\n return x\n\n jax.grad(scan_bug)(1.0) # doesn't crash\n\n def test_remat_jit_static_argnum(self):\n # https://github.com/google/jax/issues/2833\n if config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works without omnistaging\") # see next test\n\n def f(a_bool, y):\n if a_bool:\n return y + 1\n else:\n return y\n\n api.jit(api.remat(f, concrete=True), static_argnums=0)(True, 1) # no crash\n\n\n def test_remat_jit_static_argnum_omnistaging(self):\n # https://github.com/google/jax/issues/2833\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\") # see previous test\n\n def named_call(f):\n def named_f(*args):\n f_ = lu.wrap_init(lambda: (f(*args),))\n out, = core.call_p.bind(f_)\n return out\n return named_f\n\n def f(a_bool, y):\n if a_bool:\n return y + 1\n else:\n return y\n\n api.jit(named_call(f), static_argnums=0)(True, 1) # no crash\n\n def test_remat_eval_counter(self):\n # https://github.com/google/jax/issues/2737\n add_one_p = Primitive('add_one')\n add_one = add_one_p.bind\n\n num_evals = 0\n\n @contextmanager\n def assertEvals(n):\n start = num_evals\n yield\n assert num_evals - start == n\n\n def add_one_impl(x):\n nonlocal num_evals\n num_evals += 1\n return x + 1\n add_one_p.def_impl(add_one_impl)\n\n def add_one_jvp(pin, tin):\n pout = add_one(pin[0])\n return pout, pout * tin[0]\n ad.primitive_jvps[add_one_p] = add_one_jvp\n\n add_one_p.def_abstract_eval(lambda x: x)\n\n v = np.zeros((1,))\n\n f = jax.remat(add_one)\n g = jax.remat(lambda x: add_one(f(x)))\n\n # 2 calls needed to evaluate g\n with assertEvals(2):\n _, vjp = jax.vjp(g, v)\n # 2 calls made while transposing g, 1 call made while transposing f\n with assertEvals(3):\n vjp(v)\n\n @jax._src.util.curry\n def call(f, *args):\n return jax.core.call(\n jax.linear_util.wrap_init(lambda *args: [f(*args)]),\n *args, name='foo')[0]\n\n f = call(add_one)\n g = jax.remat(lambda x: add_one(f(x)))\n\n # 2 calls needed to evaluate g\n with assertEvals(2):\n _, vjp = jax.vjp(g, v)\n # 2 calls made while transposing g, no reevaluation for transposition of f\n with assertEvals(2):\n vjp(v)\n\n def test_escaped_tracer_remat(self):\n # b/169779185\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n def f():\n seq = [jnp.zeros([])]\n def g():\n seq[0] += 1 # this is line 7 btw\n return seq[0]\n\n api.remat(g)()\n api.remat(g)()\n\n with self.assertRaisesRegex(core.UnexpectedTracerError, \"global state\"):\n api.jit(f)()\n\n\nclass JaxprTest(jtu.JaxTestCase):\n\n def test_scalar_literals(self):\n jaxpr = api.make_jaxpr(lambda x: x + 2)(42)\n self.assertLen(jaxpr.jaxpr.constvars, 0)\n\n def test_const(self):\n def fun(x):\n return (x, 1., np.zeros(1))\n\n if config.omnistaging_enabled:\n expected = \"\"\"\n { lambda a ; b.\n let\n in (b, 1.0, a) }\n \"\"\"\n else:\n expected = \"\"\"\n { lambda b ; a.\n let\n in (a, 1.0, b) }\n \"\"\"\n\n jaxpr = api.make_jaxpr(fun)(0.)\n self.assertMultiLineStrippedEqual(expected, str(jaxpr))\n\n def test_cond(self):\n def f(x):\n return lax.cond(x >= 0.,\n x + 1.,\n lambda xt: xt + x,\n x + 2.,\n lambda xf: xf - x)\n if config.omnistaging_enabled:\n expected = \"\"\"\n { lambda ; a.\n let b = ge a 0.0\n c = add a 1.0\n d = add a 2.0\n e = convert_element_type[ new_dtype=int32 ] b\n f = cond[ branches=( { lambda ; e_ a b c.\n let d = sub c a\n in (d,) }\n { lambda ; a f_ b c.\n let d = add b a\n in (d,) } )\n linear=(False, False, False, False) ] e a a c d\n in (f,) }\n \"\"\"\n else:\n expected = \"\"\"\n { lambda ; a.\n let b = ge a 0.0\n c = convert_element_type[ new_dtype=int32 ] b\n d = add a 1.0\n e = add a 2.0\n f = cond[ branches=( { lambda ; e_ c a b.\n let d = sub b c\n in (d,) }\n { lambda ; c f_ a b.\n let d = add a c\n in (d,) } )\n linear=(False, False, False, False) ] c a a d e\n in (f,) }\n \"\"\"\n jaxpr = api.make_jaxpr(f)(3.)\n self.assertMultiLineStrippedEqual(expected, str(jaxpr))\n\n def test_make_jaxpr_static_argnums(self):\n def f(x, y):\n return x + y\n\n jaxpr = api.make_jaxpr(f, static_argnums=(1,))(2, 3)\n self.assertIn('3', str(jaxpr))\n\n def test_make_jaxpr_return_shape(self):\n _, shape_tree = api.make_jaxpr(lambda x: (x + 1, jnp.zeros(2, jnp.float32)),\n return_shape=True)(np.int32(1))\n expected = (api.ShapeDtypeStruct(shape=(), dtype=jnp.int32),\n api.ShapeDtypeStruct(shape=(2,), dtype=jnp.float32))\n self.assertEqual(shape_tree, expected)\n\n def test_make_jaxpr_axis_env(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n def f(x):\n return x - lax.psum(x, 'i')\n jaxpr = api.make_jaxpr(f, axis_env=[('i', 4)])(2)\n self.assertIn('psum', str(jaxpr))\n\n\nclass LazyTest(jtu.JaxTestCase):\n\n @contextmanager\n def count_compiles(self):\n\n make_computation_builder = xb.make_computation_builder\n count = [0]\n\n def make_computation_builder_and_count(*args, **kwargs):\n count[0] += 1\n return make_computation_builder(*args, **kwargs)\n\n xb.make_computation_builder = make_computation_builder_and_count\n try:\n yield count\n finally:\n xb.make_computation_builder = make_computation_builder\n\n @jtu.skip_on_devices(\"tpu\")\n def test_lazy_jit_closed_over_values(self):\n if not core.skip_checks:\n raise unittest.SkipTest(\"oom test skipped when core.skip_checks is False\")\n\n y = jnp.arange(int(1e12)) # will likely oom if materialized\n ans = jit(lambda x: (x + y)[1])(1)\n self.assertEqual(ans, 2)\n\n def test_jit_forces_arguments(self):\n\n @api.jit\n def f(x):\n assert python_should_be_executing\n return jnp.sum(x)\n\n x = jnp.zeros(10, dtype=jnp.int32)\n assert not lazy.is_trivial(x._lazy_expr)\n\n python_should_be_executing = True\n _ = f(x)\n\n python_should_be_executing = False # should not recompile\n x = np.zeros(10, dtype=np.int32)\n _ = f(x)\n\n @parameterized.parameters(jtu.cases_from_list(range(10000)))\n def test_random_lazy_program(self, seed):\n\n def random_array(rng):\n kind = rng.choice(['arr', 'iota', 'eye', 'tri'])\n if kind == 'arr':\n dtype = [np.float32, np.int32][rng.choice(2)]\n dim = rng.randint(4)\n shape = rng.randint(4, size=dim)\n np_x = np.asarray(rng.randn(*shape), dtype=dtype)\n jax_x = jnp.array(np_x, dtype=dtype)\n elif kind == 'iota':\n dtype = [np.float32, np.int32][rng.choice(2)]\n size = rng.randint(5)\n np_x = np.arange(size, dtype=dtype)\n jax_x = lax.iota(dtype, size)\n elif kind == 'eye':\n dtype = [np.float32, np.int32][rng.choice(2)]\n N = rng.randint(2, 5)\n M = None if rng.rand() < 0.5 else rng.randint(2, 5)\n k = rng.choice([-1, 0, 1])\n np_x = np.eye(N, M, k, dtype=dtype)\n jax_x = jnp.eye(N, M, k, dtype=dtype)\n elif kind == 'tri':\n dtype = [np.float32, np.int32][rng.choice(2)]\n N = rng.randint(2, 5)\n M = None if rng.rand() < 0.5 else rng.randint(2, 5)\n k = rng.choice([-1, 0, 1])\n np_x = np.tri(N, M, k, dtype=dtype)\n jax_x = jnp.tri(N, M, k, dtype=dtype)\n else:\n assert False\n assert type(np_x) is np.ndarray and xla.type_is_device_array(jax_x)\n return np_x, jax_x\n\n def random_op(rng, shape):\n kind = rng.choice(['transpose', 'broadcast', 'reshape'])\n if kind == 'transpose':\n perm = tuple(rng.permutation(len(shape)))\n return Op(partial(np.transpose, axes=perm),\n partial(lax.transpose, permutation=perm))\n elif kind == 'broadcast':\n n = rng.randint(1, 3)\n new_sizes = rng.randint(1, 4, size=n)\n new_ndim = n + len(shape)\n bcast_dims = tuple(sorted(rng.permutation(new_ndim)[:len(shape)]))\n shape_iter = iter(shape)\n new_sizes = iter(rng.randint(1, 4, size=n))\n new_shape = [next(shape_iter) if i in bcast_dims else next(new_sizes)\n for i in range(new_ndim)]\n return Op(partial(lax_reference.broadcast_in_dim, shape=new_shape,\n broadcast_dimensions=bcast_dims),\n partial(lax.broadcast_in_dim, shape=new_shape,\n broadcast_dimensions=bcast_dims))\n elif kind == 'reshape':\n new_shape = list(shape)\n for _ in range(rng.randint(1, 3)):\n loc = len(new_shape) and rng.randint(len(new_shape))\n new_shape.insert(loc, 1)\n new_shape = tuple(new_shape)\n return Op(partial(np.reshape, newshape=new_shape),\n partial(lax.reshape, new_sizes=new_shape))\n else:\n assert False\n Op = collections.namedtuple('Op', ['np_fn', 'jax_fn'])\n\n rng = np.random.RandomState(seed)\n np_x, jax_x = _, orig_x = random_array(rng)\n ops = []\n with jtu.count_primitive_compiles() as count:\n for _ in range(rng.randint(5)):\n op = random_op(rng, np.shape(np_x))\n np_x = op.np_fn(np_x)\n jax_x = op.jax_fn(jax_x)\n ops.append(op)\n self.assertEqual(count[0], 0)\n\n kind = rng.choice(['closure', 'npy_value', 'force', 'add'])\n if kind == 'closure':\n result = api.jit(lambda x: x + jax_x)(0)\n self.assertAllClose(np_x, result, check_dtypes=False)\n elif kind == 'npy_value':\n self.assertAllClose(np_x, jax_x, check_dtypes=False)\n elif kind == 'force':\n result = xla._force(jax_x)\n self.assertAllClose(np_x, result, check_dtypes=False)\n elif kind == 'add':\n result = jax_x + np.zeros(jax_x.shape, dtype=jax_x.dtype)\n self.assertAllClose(np_x, result, check_dtypes=False)\n else:\n assert False\n\n @jit\n def apply_ops(x):\n for op in ops:\n x = op.jax_fn(x)\n return x\n\n jit_result = apply_ops(orig_x)\n self.assertAllClose(jit_result, np_x, check_dtypes=False)\n\n @jit\n def apply_ops_closure():\n x = orig_x\n for op in ops:\n x = op.jax_fn(x)\n return x\n\n jit_result = apply_ops_closure()\n self.assertAllClose(jit_result, np_x, check_dtypes=False)\n\n def test_constant_forcing_computations_cached(self):\n # from https://github.com/google/jax/issues/1909\n xla._lazy_force_computation.cache_clear() # clear force compile cache\n big_lazy_x = np.ones((api.device_count(), 100))\n f = api.pmap(lambda x: 2 * x)\n _ = f(big_lazy_x)\n\n with self.count_compiles() as count:\n _ = f(big_lazy_x)\n self.assertEqual(count[0], 0)\n\n def test_zeros_ones_compilation(self):\n w = jnp.ones(3) + jnp.ones(3) # ensure + has a cache entry\n w.block_until_ready()\n\n xla._lazy_force_computation.cache_clear() # clear force compile cache\n\n with self.count_compiles() as count:\n x = jnp.ones(3) + jnp.zeros(3)\n y = jnp.ones(3) + jnp.ones(3)\n\n self.assertEqual(1, count[0])\n self.assertAllClose(x, np.ones(3), check_dtypes=False)\n self.assertAllClose(y, np.ones(3) + np.ones(3), check_dtypes=False)\n\nclass CustomJVPTest(jtu.JaxTestCase):\n\n def test_basic(self):\n @api.custom_jvp\n def f(x):\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n x = 3.\n self.assertAllClose(f(x), jnp.sin(x))\n self.assertAllClose(api.jvp(f, (x,), (1.,)),\n (jnp.sin(x), 2 * jnp.cos(x)))\n self.assertAllClose(api.grad(f)(x), 2 * jnp.cos(x))\n\n def test_invariance(self):\n @api.custom_jvp\n def f(x):\n return jnp.cos(2 * x) / 2.\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return (f(x), 3 * g)\n f.defjvp(f_jvp)\n def f2(x):\n y, _ = api.jvp(f, (x,), (x,))\n return y\n def f3(x):\n y, _ = api.jvp(f2, (x,), (x,))\n return y\n x = 1.\n self.assertAllClose(api.jvp(f, (x,), (x,)),\n api.jvp(f2, (x,), (x,)),\n check_dtypes=False)\n self.assertAllClose(api.jvp(f, (x,), (x,)),\n api.jvp(f3, (x,), (x,)),\n check_dtypes=False)\n\n def test_python_control_flow(self):\n @api.custom_jvp\n def f(x):\n if x > 0:\n return jnp.sin(x)\n else:\n return jnp.cos(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n if x > 0:\n return f(x), 2 * g\n else:\n return f(x), 3 * g\n f.defjvp(f_jvp)\n x = 2.\n self.assertAllClose(f(x), jnp.sin(x))\n self.assertAllClose(f(-x), jnp.cos(-x))\n self.assertAllClose(api.jvp(f, (x,), (1.,)),\n (jnp.sin(x), 2.),\n check_dtypes=False)\n self.assertAllClose(api.jvp(f, (-x,), (1.,)),\n (jnp.cos(-x), 3.),\n check_dtypes=False)\n self.assertAllClose(api.grad(f)(x), 2., check_dtypes=False)\n self.assertAllClose(api.grad(f)(-x), 3., check_dtypes=False)\n\n def test_vmap(self):\n @api.custom_jvp\n def f(x):\n assert jnp.ndim(x) == 0\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n assert jnp.ndim(x) == jnp.ndim(g) == 0\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n x = jnp.arange(3.)\n xx = jnp.arange(6.).reshape(2, 3)\n\n # vmap of f\n self.assertAllClose(api.vmap(f)(x), jnp.sin(x))\n self.assertAllClose(api.vmap(api.vmap(f))(xx), jnp.sin(xx))\n\n # vmap of jvp of f\n self.assertAllClose(api.vmap(lambda x: api.jvp(f, (x,), (x,)))(x),\n (jnp.sin(x), 2 * jnp.cos(x) * x))\n self.assertAllClose(api.vmap(api.vmap(lambda x: api.jvp(f, (x,), (x,))))(xx),\n (jnp.sin(xx), 2 * jnp.cos(xx) * xx))\n\n # jvp of vmap of f\n self.assertAllClose(api.jvp(api.vmap(f), (x,), (x,)),\n (jnp.sin(x), 2 * jnp.cos(x) * x))\n self.assertAllClose(api.jvp(api.vmap(api.vmap(f)), (xx,), (xx,)),\n (jnp.sin(xx), 2 * jnp.cos(xx) * xx))\n\n # vmap of jvp of vmap of f\n self.assertAllClose(api.vmap(lambda x: api.jvp(api.vmap(f), (x,), (x,)))(xx),\n (jnp.sin(xx), 2 * jnp.cos(xx) * xx))\n\n def test_jit(self):\n @api.custom_jvp\n def f(x):\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n x = 3.\n\n # jit\n self.assertAllClose(api.jit(f)(x), jnp.sin(x))\n self.assertAllClose(api.jit(api.jit(f))(x), jnp.sin(x))\n\n # jit of jvp\n self.assertAllClose(api.jit(lambda x: api.jvp(f, (x,), (x,)))(x),\n (jnp.sin(x), 2 * jnp.cos(x) * x),\n check_dtypes=False)\n\n # jvp of jit\n self.assertAllClose(api.jvp(api.jit(f), (x,), (x,)),\n (jnp.sin(x), 2 * jnp.cos(x) * x),\n check_dtypes=False)\n\n def test_pytrees(self):\n @api.custom_jvp\n def f(x):\n return {'b': jnp.sin(x['a'])}\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), {'b': 2 * jnp.cos(x['a']) * g['a']}\n f.defjvp(f_jvp)\n x = {'a': 3.}\n self.assertAllClose(f(x)['b'], jnp.sin(x['a']))\n self.assertAllClose(api.jvp(f, (x,), (x,)),\n ({'b': jnp.sin(x['a'])},\n {'b': 2 * jnp.cos(x['a']) * x['a']}),\n check_dtypes=False)\n\n def test_kwargs(self):\n # from https://github.com/google/jax/issues/1938\n @api.custom_jvp\n def my_fun(x, y, c=1.):\n return c * (x + y)\n def my_jvp(primals, tangents):\n x, y, c = primals\n t_x, t_y, t_c = tangents\n return my_fun(x, y, c), t_c\n my_fun.defjvp(my_jvp)\n f = lambda x, y: jnp.square(my_fun(x, y, c=2.)).sum()\n f(10., 5.) # doesn't crash\n api.jvp(f, (10., 5.), (1., 1.)) # doesn't crash\n\n def test_initial_style(self):\n @api.custom_jvp\n def f(x):\n return 3 * x\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * g\n f.defjvp(f_jvp)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.grad(foo)(3.)\n expected = 2.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.jit(foo))(3.)\n expected = 2.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(foo))(3.)\n expected = 2.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(foo))(3.)\n expected = 0.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(api.jit(foo)))(3.)\n expected = 0.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.jit(api.grad(foo)))(3.)\n expected = 0.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(api.grad(foo)))(3.)\n expected = 0.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_initial_style_vmap(self):\n @api.custom_jvp\n def f(x):\n assert jnp.ndim(x) == 0\n return 3 * x\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * g\n f.defjvp(f_jvp)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.vmap(foo)(jnp.ones(3))\n expected = 3. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.vmap(api.jit(foo))(jnp.ones(3))\n expected = 3. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.vmap(foo))(jnp.ones(3))\n expected = 3. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(api.jit(foo))(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.jit(api.vmap(foo))(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.jit(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_closed_over_tracers_error_message(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n def f(x):\n @api.custom_jvp\n def g(y):\n return x + y\n def g_jvp(primals, tangents):\n return g(x), 2 * primals[0]\n g.defjvp(g_jvp)\n return g(1.)\n\n self.assertRaises(ad.CustomJVPException, lambda: api.jvp(f, (3.,), (1.,)))\n self.assertRaises(ad.CustomJVPException, lambda: api.grad(f)(3.))\n\n def test_nondiff_arg(self):\n @partial(api.custom_jvp, nondiff_argnums=(0,))\n def app(f, x):\n return f(x)\n def app_jvp(f, primals, tangents):\n (x,), (t,) = primals, tangents\n return app(f, x), 3 * t\n app.defjvp(app_jvp)\n\n ans = app(lambda x: 2 * x, 1)\n expected = 2\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jvp(lambda x: app(lambda y: 2 * y, x), (1.,), (1.,))\n expected = (2., 3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg_jit_tracer(self):\n @partial(api.custom_jvp, nondiff_argnums=(0,))\n def f(x, y):\n return x * y\n def f_jvp(x, primals, tangents):\n (y,), (t_y,) = primals, tangents\n return f(x, y), 5 * t_y\n f.defjvp(f_jvp)\n\n @jit\n def g(x, y):\n return f(x, y)\n\n ans = api.jvp(lambda y: g(2., y), (3.,), (1.,))\n expected = (6., 5.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg_hiding_jvp_tracer(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n def f(x):\n @partial(api.custom_jvp, nondiff_argnums=(0,))\n def g(h, x):\n return h(x)\n @g.defjvp\n def g_jvp(h, primals, tangents):\n x, = primals\n t, = tangents\n return g(h, x), 2. * t\n h = lambda y: x + y # capture x\n return g(h, x)\n\n with self.assertRaisesRegex(ad.CustomJVPException, \"Detected differentiation\"):\n api.jvp(f, (2.,), (1.,))\n\n def test_vmap_axes(self):\n raise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n\n def test_pmap(self):\n raise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n\n def test_missing_jvp_rule_error_message(self):\n @api.custom_jvp\n def foo(x):\n return x ** 2\n\n self.assertRaisesRegex(\n AttributeError,\n r\"No JVP defined for custom_jvp function foo using defjvp.\",\n lambda: foo(2))\n self.assertRaisesRegex(\n AttributeError,\n r\"No JVP defined for custom_jvp function foo using defjvp.\",\n lambda: api.jvp(foo, (2.,), (1.,)))\n self.assertRaisesRegex(\n AttributeError,\n r\"No JVP defined for custom_jvp function foo using defjvp.\",\n lambda: api.grad(foo)(2.))\n\n def test_jvp_rule_inconsistent_pytree_structures_error_message(self):\n @api.custom_jvp\n def f(x):\n return (x**2,)\n\n @f.defjvp\n def foo_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return f(x), [2 * x * t, x]\n\n f(2.) # doesn't crash\n self.assertRaisesRegex(\n TypeError,\n re.escape(\n \"Custom JVP rule must produce primal and tangent outputs \"\n \"with equal container (pytree) structures, but got \"\n \"{} and {} respectively.\".format(\n tree_util.tree_structure((1,)),\n tree_util.tree_structure([1, 2]))\n ),\n lambda: api.jvp(f, (2.,), (1.,)))\n\n def test_primal_tangent_aval_disagreement_error_message(self):\n @api.custom_jvp\n def f(x):\n return x ** 2\n\n @f.defjvp\n def foo_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return f(x), jnp.reshape(t, (1,))\n\n f(2.) # doesn't crash\n self.assertRaisesRegex(\n TypeError,\n re.escape(\n \"Custom JVP rule must produce primal and tangent outputs \"\n \"with equal shapes and dtypes, but got float32[] and float32[1] \"\n \"respectively.\"),\n lambda: api.jvp(f, (jnp.float32(2.),), (jnp.float32(1.),)))\n\n def test_jvp_rule_doesnt_return_pair_error_message(self):\n # https://github.com/google/jax/issues/2516\n\n @api.custom_jvp\n def f(x):\n return x ** 2\n\n @f.defjvp\n def foo_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return t\n\n f(2.) # doesn't crash\n self.assertRaisesRegex(\n TypeError,\n re.escape(\n \"Custom JVP rule must produce a pair (list or tuple of length two) \"\n \"representing primal and tangent outputs, got 1.0\"),\n lambda: api.jvp(f, (2.,), (1.,)))\n\n def test_multiple_rule_invocations(self):\n @jax.custom_jvp\n def expit(x):\n return 1 / (1 + lax.exp(-x))\n\n @expit.defjvp\n def _expit_jvp(primals, tangents):\n (x,), (t,) = primals, tangents\n ans = expit(x)\n t_out = t * ans * (1 - ans)\n return ans, t_out\n\n def scanned_fun(c, _):\n return [expit(c[0])] + [c[i-1] + c[i] for i in range(1, len(c))], None\n\n def foo(x):\n c, _ = lax.scan(scanned_fun, [x, 0., 0., 0., 0.], None, length=10)\n return c[-1]\n\n # just make sure these don't crash\n foo(3.)\n grad(foo)(3.)\n grad(lambda x: jax.vmap(foo)(x).sum())(jnp.arange(3.))\n\n def test_hard_stuff(self):\n arr = jnp.ones((5, 2, 2))\n api.jit(jax.vmap(jnp.linalg.det))(arr) # doesn't crash\n\n def test_hard_stuff2(self):\n @jax.custom_jvp\n def f(x):\n return lax.tie_in(x, np.zeros(x.shape, x.dtype))\n\n @f.defjvp\n def f_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return f(x), t\n\n # don't crash\n jax.jit(jax.vmap(f))(jnp.arange(3.))\n jax.jit(jax.vmap(jax.grad(f)))(jnp.arange(3.))\n jax.jit(jax.grad(lambda x: jax.vmap(f)(x).sum()))(jnp.arange(3.))\n jax.grad(lambda x: jax.vmap(f)(x).sum())(jnp.arange(3.))\n jax.jvp(jax.vmap(f), (jnp.arange(3.),), (jnp.ones(3),))\n\n def test_hard_stuff3(self):\n @jax.custom_jvp\n def relu(x):\n return jnp.maximum(x, 0)\n\n @relu.defjvp\n def _relu_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return relu(x), lax.select(x > 0, t, lax.full_like(t, 0))\n\n def scanned_fun(c, _):\n return [relu(c[0])] + [c[i-1] + c[i] for i in range(1, len(c))], None\n\n def f(x):\n c, _ = lax.scan(scanned_fun, [x, 0., 0., 0., 0.], None, length=10)\n return c[-1]\n\n # don't crash\n jax.jit(jax.vmap(f))(jnp.arange(3.))\n jax.jit(jax.vmap(jax.grad(f)))(jnp.arange(3.))\n jax.jit(jax.grad(lambda x: jax.vmap(f)(x).sum()))(jnp.arange(3.))\n jax.grad(lambda x: jax.vmap(f)(x).sum())(jnp.arange(3.))\n jax.jvp(jax.jit(jax.vmap(f)), (jnp.arange(3.),), (jnp.ones(3),))\n\n def test_eval_shape(self):\n @jax.custom_jvp\n def expit(x):\n return 1 / (1 + lax.exp(-x))\n\n @expit.defjvp\n def _expit_jvp(primals, tangents):\n (x,), (t,) = primals, tangents\n ans = expit(x)\n t_out = t * ans * (1 - ans)\n return ans, t_out\n\n # don't crash\n api.eval_shape(expit, jnp.ones((2, 3)))\n api.eval_shape(api.grad(lambda x: expit(x).sum()), jnp.ones((2, 3)))\n\n def test_jaxpr_zeros(self):\n # from https://github.com/google/jax/issues/2657\n @api.custom_jvp\n def f(A, b):\n return A @ b\n\n def f_jvp(primals, tangents):\n A, b = primals\n dA, db = tangents\n z = f(A, b)\n dz = A @ db + dA @ b\n return z, dz\n\n f.defjvp(f_jvp)\n\n def experiment(theta):\n def step(q, _):\n z = f(jnp.eye(3), jnp.ones(3) * theta)\n q += z[0]\n return q, q\n\n q = 0.\n q, _ = lax.scan(step, q, None, 4)\n return q\n\n grad(experiment)(1.) # doesn't crash\n\n def test_linear_in_scan(self):\n @api.custom_jvp\n def f(x):\n return -x\n\n @f.defjvp\n def f_jvp(primals, tangents):\n x, = primals\n x_dot, = tangents\n return f(x), f(x_dot)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.grad(foo)(3.)\n expected = -1.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_jvps_first_rule_is_none(self):\n # https://github.com/google/jax/issues/3389\n @api.custom_jvp\n def f(x, y):\n return x ** 2 * y\n\n f.defjvps(None, lambda x_dot, primal_out, x, y: 2 * x * y * x_dot)\n ans = grad(f, 1)(2., 3.) # doesn't crash\n expected = 12.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_concurrent_initial_style(self):\n # https://github.com/google/jax/issues/3843\n def unroll(param, sequence):\n def scan_f(prev_state, inputs):\n return prev_state, jax.nn.sigmoid(param * inputs)\n return jnp.sum(jax.lax.scan(scan_f, None, sequence)[1])\n\n def run():\n return jax.grad(unroll)(jnp.array(1.0), jnp.array([1.0]))\n\n expected = run()\n\n # we just don't want this to crash\n n_workers = 2\n with concurrent.futures.ThreadPoolExecutor(max_workers=n_workers) as e:\n futures = []\n for _ in range(n_workers):\n futures.append(e.submit(run))\n results = [f.result() for f in futures]\n for ans in results:\n self.assertAllClose(ans, expected)\n\n def test_nondiff_argnums_vmap_tracer(self):\n # https://github.com/google/jax/issues/3964\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n @partial(jax.custom_jvp, nondiff_argnums=(0, 2))\n def sample(shape, param, seed):\n return jax.random.uniform(key=seed, shape=shape, minval=param)\n\n @sample.defjvp\n def sample_jvp(shape, seed, primals, tangents):\n param, = primals\n dparam, = tangents\n dparam = jnp.broadcast_to(dparam, shape)\n samples = sample(shape, param, seed)\n return samples, samples * dparam # dummy jvp for proof of concept\n\n # check these don't crash\n jax.vmap(lambda seed: sample((2,3), 1., seed))(\n jax.random.split(jax.random.PRNGKey(1), 10))\n jax.jvp(lambda x: sample((2, 3), x, jax.random.PRNGKey(1)),\n (1.,), (1.,))\n\n def test_fun_with_nested_calls_2(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n def call(f, *args):\n f = api.custom_jvp(f)\n f.defjvp(lambda primals, tangents: (f(*primals), sum(tangents)))\n return f(*args)\n\n def fun_with_nested_calls_2(x):\n def bar(y):\n def baz(w):\n q = call(lambda x: y, x)\n q = q + call(lambda: y)\n q = q + call(lambda y: w + y, y)\n q = call(lambda w: call(jnp.sin, x) * y, 1.0) + q\n return q\n return api.jit(baz)(x)\n return call(bar, x)\n\n # test these don't crash\n self.assertAllClose(api.jit(fun_with_nested_calls_2)(3.),\n fun_with_nested_calls_2(3.))\n api.vmap(fun_with_nested_calls_2)(jnp.arange(3.))\n\n def test_closure_with_vmap(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n # https://github.com/google/jax/issues/3822\n alpha = np.float32(2.)\n\n def sample(seed):\n @api.custom_jvp\n def f(alpha):\n return jax.random.gamma(seed, alpha, shape=[])\n\n @f.defjvp\n def f_jvp(primal, tangent):\n alpha = primal\n dalpha = tangent\n sample = f(alpha)\n partial_alpha = lax.random_gamma_grad(alpha, sample)\n return sample, partial_alpha * dalpha\n return f(alpha)\n\n api.vmap(sample)(jax.random.split(jax.random.PRNGKey(1), 3)) # don't crash\n\n def test_float0(self):\n @api.custom_jvp\n def f(x, y):\n return x, y\n def f_jvp(primals, _):\n # we need a defined (non-float0) tangent to trigger the rule\n return primals, (2., 1)\n f.defjvp(f_jvp)\n\n primals = (2., 3)\n tangents = (np.ones(()), np.zeros((), float0),)\n expected_tangents = (2., np.zeros((), float0))\n self.assertArraysEqual(api.jvp(f, primals, tangents),\n (primals, expected_tangents))\n\n def test_float0_initial_style(self):\n @api.custom_jvp\n def f(x, y):\n return x, y\n def f_jvp(primals, _):\n x, y = primals\n return (x, y), (2., 1)\n f.defjvp(f_jvp)\n\n def foo(x, y):\n out, _ = lax.scan(lambda c, _: (f(*c), None), (x, y), None, length=1)\n return out\n\n primals = (2., 3)\n tangents = (np.ones(()), np.zeros((), float0),)\n expected_tangents = (2., np.zeros((), float0))\n self.assertArraysEqual(api.jvp(foo, primals, tangents),\n (primals, expected_tangents))\n\n def test_remat(self):\n @api.custom_jvp\n def f(x):\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n @api.remat\n def g(x):\n return f(f(x))\n\n ans = g(2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(g)(2.)\n expected = 4. * api.grad(lambda x: jnp.sin(jnp.sin(x)))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_higher_order(self):\n @api.custom_jvp\n def f(x):\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n def g(x):\n return f(f(x))\n\n ans = api.grad(api.grad(api.remat(g)))(2.)\n expected = api.grad(api.grad(g))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.remat(api.grad(g)))(2.)\n expected = api.grad(api.grad(g))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(api.grad(api.remat(g))))(2.)\n expected = api.grad(api.grad(api.grad(g)))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_initial_style_vmap_2(self):\n # This is like test_initial_style_vmap except the primal function closes\n # over an array constant.\n y = jnp.array([1., 2., 3.])\n\n @api.custom_jvp\n def f(x):\n assert jnp.ndim(x) == 0\n return 3 * x * jnp.sum(y)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * g\n f.defjvp(f_jvp)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(api.jit(foo))(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.jit(api.vmap(foo))(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.jit(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n\nclass CustomVJPTest(jtu.JaxTestCase):\n\n def test_basic(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n x = 3.\n self.assertAllClose(f(x), jnp.sin(x))\n self.assertAllClose(api.grad(f)(x), 2 * jnp.cos(x))\n self.assertAllClose(api.value_and_grad(f)(x),\n (jnp.sin(x), 2 * jnp.cos(x)))\n\n def test_invariance(self):\n @api.custom_vjp\n def f(x):\n return jnp.cos(2 * x) / 2.\n def f_fwd(x):\n return (f(x), x)\n def f_rev(x, g):\n return (g * 3,)\n f.defvjp(f_fwd, f_rev)\n def f2(x):\n y, _ = api.value_and_grad(f)(x)\n return y\n def f3(x):\n y, _ = api.value_and_grad(f2)(x)\n return y\n x = 1.\n self.assertAllClose(f(x), f2(x), check_dtypes=False)\n self.assertAllClose(f(x), f3(x), check_dtypes=False)\n self.assertAllClose(api.grad(f)(x), api.grad(f2)(x),\n check_dtypes=False)\n self.assertAllClose(api.grad(f)(x), api.grad(f3)(x),\n check_dtypes=False)\n\n def test_python_control_flow(self):\n @api.custom_vjp\n def f(x):\n if x > 0:\n return jnp.sin(x)\n else:\n return jnp.cos(x)\n def f_fwd(x):\n if x > 0:\n return f(x), x\n else:\n return f(x), x\n def f_rev(x, g):\n if x > 0:\n return (2 * g,)\n else:\n return (3 * g,)\n f.defvjp(f_fwd, f_rev)\n x = 2.\n self.assertAllClose(f(x), jnp.sin(x))\n self.assertAllClose(f(-x), jnp.cos(-x))\n self.assertAllClose(api.value_and_grad(f)(x), (jnp.sin(x), 2.),\n check_dtypes=False)\n self.assertAllClose(api.value_and_grad(f)(-x), (jnp.cos(-x), 3.),\n check_dtypes=False)\n\n def test_vmap(self):\n @api.custom_vjp\n def f(x):\n assert jnp.ndim(x) == 0\n return jnp.sin(x)\n def f_fwd(x):\n assert jnp.ndim(x) == 0\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n x = jnp.arange(3.)\n xx = jnp.arange(6.).reshape(2, 3)\n\n # vmap of f\n self.assertAllClose(api.vmap(f)(x), jnp.sin(x))\n self.assertAllClose(api.vmap(api.vmap(f))(xx), jnp.sin(xx))\n\n # vmap of grad of f\n self.assertAllClose(api.vmap(api.grad(f))(x), 2 * jnp.cos(x))\n self.assertAllClose(api.vmap(api.value_and_grad(f))(x),\n (jnp.sin(x), 2 * jnp.cos(x)))\n self.assertAllClose(api.vmap(api.vmap(api.grad(f)))(xx), 2 * jnp.cos(xx))\n self.assertAllClose(api.vmap(api.vmap(api.value_and_grad(f)))(xx),\n (jnp.sin(xx), 2 * jnp.cos(xx)))\n\n # grad of vmap of f\n self.assertAllClose(api.grad(lambda x: api.vmap(f)(x).sum())(x),\n 2 * jnp.cos(x))\n self.assertAllClose(api.grad(lambda x: api.vmap(api.vmap(f))(x).sum())(xx),\n 2 * jnp.cos(xx))\n\n # vmap of grad of vmap of f\n self.assertAllClose(api.vmap(api.grad(lambda x: api.vmap(f)(x).sum()))(xx),\n 2 * jnp.cos(xx))\n\n def test_jit(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n x = 3.\n\n # jit\n self.assertAllClose(api.jit(f)(x), jnp.sin(x))\n self.assertAllClose(api.jit(api.jit(f))(x), jnp.sin(x))\n\n # jit of grad\n self.assertAllClose(api.jit(api.grad(f))(x), 2 * jnp.cos(x),\n check_dtypes=False)\n\n # grad of jit\n self.assertAllClose(api.grad(api.jit(f))(x), 2 * jnp.cos(x),\n check_dtypes=False)\n\n def test_pytrees(self):\n @api.custom_vjp\n def f(x):\n return {'b': jnp.sin(x['a'])}\n def f_fwd(x):\n return f(x), {'r': jnp.cos(x['a'])}\n def f_bwd(res, g):\n cos_x = res['r']\n return ({'a': 2 * cos_x * g['b']},)\n f.defvjp(f_fwd, f_bwd)\n x = {'a': 3.}\n self.assertAllClose(f(x)['b'], jnp.sin(x['a']))\n self.assertAllClose(api.grad(lambda x: f(x)['b'])(x),\n {'a': 2 * jnp.cos(x['a'])})\n\n def test_jvp_error(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n self.assertRaisesRegex(\n TypeError,\n r\"can't apply forward-mode autodiff \\(jvp\\) to a custom_vjp function.\",\n lambda: api.jvp(f, (3.,), (1.,)))\n self.assertRaisesRegex(\n TypeError,\n r\"can't apply forward-mode autodiff \\(jvp\\) to a custom_vjp function.\",\n lambda: api.jvp(api.vmap(f), (jnp.arange(3.),), (jnp.ones(3),)))\n\n def test_kwargs(self):\n # from https://github.com/google/jax/issues/1938\n @api.custom_vjp\n def my_fun(x, y, c=1.):\n return c * (x + y)\n my_fun.defvjp(lambda x, y, c=1.: (my_fun(c, y, c), None),\n lambda _, g: (g, g, g))\n f = lambda x, y: jnp.square(my_fun(x, y, c=2.)).sum()\n f(10., 5.) # doesn't crash\n api.grad(f)(10., 5.) # doesn't crash\n\n def test_initial_style(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.grad(foo)(3.)\n expected = 2. * jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(foo))(3.)\n expected = -2. * jnp.sin(3.)\n self.assertAllClose(ans, expected)\n\n def test_initial_style_vmap(self):\n @api.custom_vjp\n def f(x):\n assert jnp.ndim(x) == 0\n return 3 * x\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.vmap(foo)(jnp.arange(3.))\n expected = 3. * jnp.arange(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.arange(3.))\n expected = 2. * jnp.cos(jnp.arange(3.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg(self):\n @partial(api.custom_vjp, nondiff_argnums=(0,))\n def app(f, x):\n return f(x)\n def app_fwd(f, x):\n return app(f, x), jnp.cos(x)\n def app_rev(f, cos_x, g):\n return (cos_x * g,)\n app.defvjp(app_fwd, app_rev)\n\n ans = app(lambda x: 2 * x, 1)\n expected = 2\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.value_and_grad(lambda x: app(lambda y: 2 * y, x))(1.)\n expected = (2., jnp.cos(1.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg_tracer(self):\n # This test is now skipped because we decided not to support this behavior\n # anymore (namely, nondiff args can't be tracers), but\n # test_closed_over_tracer is a replacement test for analogous behavior that\n # we do support\n raise unittest.SkipTest(\"removed support for tracers in nondiff args\")\n\n @partial(api.custom_vjp, nondiff_argnums=(0,))\n def f(x, y):\n return x * y\n def f_fwd(x, y):\n return f(x, y), jnp.cos(y)\n def f_rev(x, cos_y, g):\n return (cos_y * g,)\n f.defvjp(f_fwd, f_rev)\n\n @jit\n def g(x, y):\n return f(x, y)\n\n ans = g(2, 3.)\n expected = 6.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(g, 1)(2., 3.)\n expected = jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_closed_over_tracer(self):\n # This test is similar to test_nondiff_arg_tracer except it uses lexical\n # closure rather than the nondiff_argnums mechanism. We decided to disallow\n # tracers in nondiff_argnums to greatly simplify bookkeeping while still\n # supporting the cases for which it is necessary.\n def outer(x):\n @api.custom_vjp\n def f(y):\n return x * y\n def f_fwd(y):\n return f(y), jnp.cos(y)\n def f_rev(cos_y, g):\n return (cos_y * g,)\n f.defvjp(f_fwd, f_rev)\n return f\n\n @jit\n def g(x, y):\n return outer(x)(y)\n\n ans = g(2, 3.)\n expected = 6.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(g, 1)(2., 3.)\n expected = jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_closed_over_tracer2(self):\n def outer(x):\n @api.custom_vjp\n def f(y):\n return x * y\n def f_fwd(y):\n return f(y), jnp.cos(y)\n def f_rev(cos_y, g):\n return (cos_y * g,)\n f.defvjp(f_fwd, f_rev)\n return f\n\n @api.vmap\n def g(x):\n return outer(x)(3.)\n\n ans = g(np.arange(3.))\n expected = np.arange(3.) * 3\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_closed_over_tracer3(self):\n def outer(x):\n @api.custom_vjp\n def f(y):\n return x * y\n def f_fwd(y):\n return f(y), (x, jnp.cos(y))\n def f_rev(res, g):\n x, cos_y = res\n return (cos_y * g * x,)\n f.defvjp(f_fwd, f_rev)\n return api.grad(f)\n\n @api.vmap\n def g(x):\n return outer(x)(3.)\n\n ans = g(np.arange(3.))\n expected = np.cos(3.) * np.arange(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg_tracer_error(self):\n # This is similar to the old (now skipped) test_nondiff_arg_tracer, except\n # we're testing for the error message that that usage pattern now raises.\n\n @partial(api.custom_vjp, nondiff_argnums=(0,))\n def f(x, y):\n return x * y\n def f_fwd(x, y):\n return f(x, y), jnp.cos(y)\n def f_rev(x, cos_y, g):\n return (cos_y * g,)\n f.defvjp(f_fwd, f_rev)\n\n @jit\n def g(x, y):\n return f(x, y)\n\n with self.assertRaisesRegex(core.UnexpectedTracerError, \"custom_vjp\"):\n _ = g(2, 3.)\n with self.assertRaisesRegex(core.UnexpectedTracerError, \"custom_vjp\"):\n _ = api.grad(g, 1)(2., 3.)\n\n def test_vmap_axes(self):\n raise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n\n def test_pmap(self):\n raise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n\n def test_missing_vjp_rule_error(self):\n @api.custom_vjp\n def foo(x):\n return x ** 2\n\n self.assertRaisesRegex(\n AttributeError,\n r\"No VJP defined for custom_vjp function foo using defvjp.\",\n lambda: foo(2))\n self.assertRaisesRegex(\n AttributeError,\n r\"No VJP defined for custom_vjp function foo using defvjp.\",\n lambda: api.grad(foo)(2.))\n\n def test_vjp_rule_inconsistent_pytree_structures_error(self):\n @api.custom_vjp\n def f(x):\n return x\n\n def foo_fwd(x):\n return x, None\n\n def foo_bwd(_, g):\n return (g, g)\n\n f.defvjp(foo_fwd, foo_bwd)\n\n f(2) # doesn't crash\n self.assertRaisesRegex(\n TypeError,\n re.escape(\n \"Custom VJP rule must produce an output with the same container \"\n \"(pytree) structure as the args tuple of the primal function, \"\n \"and in particular must produce a tuple of length equal to the \"\n \"number of arguments to the primal function, but got VJP output \"\n \"structure {} for primal input structure {}.\".format(\n tree_util.tree_structure((1, 1)),\n tree_util.tree_structure((1,)))\n ),\n lambda: api.grad(f)(2.))\n\n def test_vjp_bwd_returns_non_tuple_error(self):\n @api.custom_vjp\n def f(x):\n return x\n\n def foo_fwd(x):\n return x, None\n\n def foo_bwd(_, g):\n return 2. * g # Should be a tuple\n\n f.defvjp(foo_fwd, foo_bwd)\n with self.assertRaisesRegex(TypeError, \"Custom VJP rule .* must produce a tuple\"):\n api.grad(f)(3.)\n\n def test_issue2511(self):\n arr = jnp.ones((5, 2, 2))\n foo = lambda x: api.vmap(jnp.linalg.det, (0,))(x)\n api.jit(foo)(arr) # doesn't crash\n\n def test_lowering_out_of_traces(self):\n # https://github.com/google/jax/issues/2578\n\n class F(collections.namedtuple(\"F\", [\"a\"])):\n def __call__(self, x):\n return jax.nn.relu(self.a) * x\n\n @jax.jit\n def g(f, x):\n return f(x)\n\n jax.grad(g, argnums=(1,))(F(2.0), 0.) # doesn't crash\n\n def test_nondiff_argnums_stop_gradient(self):\n # This test is now skipped because we decided not to support this behavior\n # anymore (namely, nondiff args can't be tracers), but test_clip_gradient is\n # a replacement showing behavior we do support.\n raise unittest.SkipTest(\"removed support for tracers in nondiff args\")\n\n # https://github.com/google/jax/issues/2784\n @partial(api.custom_vjp, nondiff_argnums=(0, 1))\n def _clip_gradient(lo, hi, x):\n return x # identity function\n\n def clip_gradient_fwd(lo, hi, x):\n # return x, None\n return x, (hi, )\n\n def clip_gradient_bwd(lo, hi, _, g):\n return (jnp.clip(g, lo, hi),)\n\n _clip_gradient.defvjp(clip_gradient_fwd, clip_gradient_bwd)\n\n def clip_gradient(x):\n lo = -1\n hi = x + 1 # causes things to break\n return _clip_gradient(lo, hi, x)\n\n jax.grad(clip_gradient)(1.) # doesn't crash\n\n def test_clip_gradient(self):\n # https://github.com/google/jax/issues/2784\n @api.custom_vjp\n def _clip_gradient(lo, hi, x):\n return x # identity function when not differentiating\n\n def clip_gradient_fwd(lo, hi, x):\n return x, (lo, hi,)\n\n def clip_gradient_bwd(res, g):\n lo, hi = res\n return (None, None, jnp.clip(g, lo, hi),)\n\n _clip_gradient.defvjp(clip_gradient_fwd, clip_gradient_bwd)\n\n def clip_gradient(x):\n lo = -0.1\n hi = x + 0.1\n return _clip_gradient(lo, hi, x)\n\n g = jax.grad(clip_gradient)(0.1) # doesn't crash\n self.assertAllClose(g, jnp.array(0.2))\n\n def test_nestable_vjp(self):\n # Verify that https://github.com/google/jax/issues/3667 is resolved.\n def f(x):\n return x ** 2\n\n @api.custom_vjp\n def g(x):\n return f(x)\n\n def g_fwd(x):\n y, f_vjp = api.vjp(f, x)\n return y, f_vjp\n\n def g_bwd(f_vjp, y_bar):\n return f_vjp(y_bar)\n\n g.defvjp(g_fwd, g_bwd)\n\n # Check that VJP can be nested in simple situations. For this to pass,\n # vjp has to return a PyTree.\n _, g_vjp = api.vjp(g, 1.0)\n y, = g_vjp(1.0)\n self.assertAllClose(y, jnp.array(2.0))\n\n # Check that VJP can be nested in complex situations. For this to pass,\n # vjp can't treat the closed-over tracer x as a static argument.\n @jit\n def z(x):\n _, g_vjp = api.vjp(g, x)\n return g_vjp\n y, = z(1.0)(3.0)\n self.assertAllClose(y, jnp.array(6.0))\n\n def test_initial_style_vmap_2(self):\n # https://github.com/google/jax/issues/4173\n x = jnp.ones((10, 3))\n\n # Create the custom function\n @api.custom_vjp\n def custom_fun(x):\n return x.sum()\n\n def forward(x):\n return x.sum(), (jnp.ones_like(x),)\n\n def backward(res, g):\n return g * res[0],\n\n custom_fun.defvjp(forward, backward)\n\n def train_fun(x):\n\n def summed_fun(x):\n return api.vmap(custom_fun)(x).sum()\n\n return api.grad(summed_fun)(x)\n\n def scan_body(carry, inputs):\n x = carry\n return carry, train_fun(x)\n\n scan_range = jnp.arange(4)\n lax.scan(scan_body, x, scan_range) # don't crash\n\n def test_initial_style_vmap_3(self):\n # This is like test_initial_style_vmap except the primal function closes\n # over an array constant.\n y = jnp.array([1., 2., 3.])\n\n @api.custom_vjp\n def f(x):\n assert jnp.ndim(x) == 0\n return 3 * x * jnp.sum(y)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.vmap(foo)(jnp.arange(3.))\n expected = 3. * jnp.arange(3.) * 6\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.arange(3.))\n expected = 2. * jnp.cos(jnp.arange(3.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_bwd_closes_over_tracer(self):\n def f(y):\n @jax.custom_vjp\n def f(x):\n return 2. * jnp.sin(x)\n\n def fwd(x):\n return f(x), ()\n\n def bwd(_, g):\n return (2. * jnp.cos(y) * g,) # capture!\n\n f.defvjp(fwd, bwd)\n\n return jax.grad(f)(1.)\n\n ans = jax.jit(f)(2.)\n self.assertAllClose(ans, 2. * jnp.cos(2.))\n\n ans = jax.vmap(f)(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.jit(jax.vmap(f))(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.vmap(jax.jit(f))(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.grad(f)(4.)\n self.assertAllClose(ans, -2. * jnp.sin(4.))\n\n def test_fwd_closes_over_tracer(self):\n def f(y):\n @jax.custom_vjp\n def f(x):\n return 2. * jnp.sin(x)\n\n def fwd(x):\n return f(x), y\n\n def bwd(y, g):\n return (2. * jnp.cos(y) * g,) # capture!\n\n f.defvjp(fwd, bwd)\n\n return jax.grad(f)(1.)\n\n ans = jax.jit(f)(2.)\n self.assertAllClose(ans, 2. * jnp.cos(2.))\n\n ans = jax.vmap(f)(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.jit(jax.vmap(f))(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.vmap(jax.jit(f))(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.grad(f)(4.)\n self.assertAllClose(ans, -2. * jnp.sin(4.))\n\n def test_float0(self):\n @api.custom_vjp\n def f(x, _):\n return x\n def f_fwd(x, _):\n # we need a defined (non-float0) tangent to trigger the rule\n return x, (2., 1)\n def f_rev(*_):\n return (2., 1)\n f.defvjp(f_fwd, f_rev)\n\n x = 2.\n y = 3\n self.assertEqual(api.grad(f, allow_int=True, argnums=(0, 1))(x, y),\n (2., np.zeros(shape=(), dtype=float0)))\n\n def test_float0_initial_style(self):\n @api.custom_vjp\n def f(x):\n return x\n def f_fwd(x):\n return x, (2., x)\n def f_rev(*_):\n return ((2., 1),)\n f.defvjp(f_fwd, f_rev)\n\n def foo(x, y):\n out, _ = lax.scan(lambda c, _: (f(c), None), (x, y), None, length=1)\n return out[0]\n\n x = 2.\n y = 3\n self.assertEqual(api.grad(foo, allow_int=True, argnums=(0, 1))(x, y),\n (2., np.zeros(shape=(), dtype=float0)))\n\n def test_remat(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n @api.remat\n def g(x):\n return f(f(x))\n\n ans = g(2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(g)(2.)\n expected = 4. * api.grad(lambda x: jnp.sin(jnp.sin(x)))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_higher_order(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n def g(x):\n return f(f(x))\n\n ans = api.grad(api.grad(api.remat(g)))(2.)\n expected = api.grad(api.grad(g))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.remat(api.grad(g)))(2.)\n expected = api.grad(api.grad(g))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(api.grad(api.remat(g))))(2.)\n expected = api.grad(api.grad(api.grad(g)))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_bwd_nones(self):\n @api.custom_vjp\n def f(x, y):\n return x * jnp.sin(y)\n def f_fwd(x, y):\n return f(x, y), jnp.cos(y)\n def f_rev(cos, g):\n return (None, 2 * cos * g)\n f.defvjp(f_fwd, f_rev)\n\n ans = api.grad(lambda x: f(x, x))(3.)\n expected = 2 * jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_bwd_nones_vmap(self):\n @api.custom_vjp\n def f(x, y):\n return x * jnp.sin(y)\n def f_fwd(x, y):\n return f(x, y), jnp.cos(y)\n def f_rev(cos, g):\n return (None, 2 * cos * g)\n f.defvjp(f_fwd, f_rev)\n\n ans = api.grad(lambda x: api.vmap(f)(x, x).sum())(jnp.arange(3.))\n expected = 2 * jnp.cos(jnp.arange(3.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_bwd_nones_pytree(self):\n @api.custom_vjp\n def f(xs, y):\n x1, x2 = xs\n return x1 * x2 * jnp.sin(y)\n def f_fwd(xs, y):\n return f(xs, y), jnp.cos(y)\n def f_rev(cos, g):\n return (None, 2 * cos * g)\n f.defvjp(f_fwd, f_rev)\n\n ans = api.grad(lambda x: f((x, x), x))(3.)\n expected = 2 * jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_vjp_closure_4521(self):\n # https://github.com/google/jax/issues/4521\n @api.custom_vjp\n def g(x, y):\n return None\n def g_fwd(x, y):\n return None, y\n def g_bwd(residuals, z_bar):\n assert False\n\n g.defvjp(g_fwd, g_bwd)\n\n def f(xs, y):\n v_g = api.vmap(g, in_axes=(0, None), out_axes=None)\n v_g(xs, y)\n\n def scan_body(xs, _):\n y = jnp.zeros(1)\n _, vjp_f = api.vjp(f, xs, y)\n vjp_f(None)\n return xs, None\n\n lax.scan(scan_body, jnp.ones(5), None, 100) # doesn't crash\n\n def test_float0_bwd_none(self):\n @api.custom_vjp\n def f(i, x):\n return jnp.sin(x)\n def f_fwd(i, x):\n return f(i, x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (None, 2 * cos_x * g)\n f.defvjp(f_fwd, f_rev)\n\n ans = api.grad(f, 1)(jnp.array([1, 2]), 3.) # doesn't crash\n expected = 2 * jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_gradient(self):\n @api.custom_gradient\n def f(x):\n return x ** 2, lambda g: (g * x,)\n\n self.assertAllClose(f(3.), 9., check_dtypes=False)\n self.assertAllClose(api.grad(f)(3.), 3., check_dtypes=False)\n self.assertAllClose(api.grad(api.grad(f))(3.), 1., check_dtypes=False)\n\n def test_custom_gradient_2(self):\n @api.custom_gradient\n def f(x, y):\n return x * y, lambda g: (y, x)\n\n self.assertAllClose(f(3., 4.), 12., check_dtypes=False)\n self.assertAllClose(api.grad(f, argnums=(0, 1))(3., 4.), (4., 3.),\n check_dtypes=False)\n\n def test_custom_gradient_3(self):\n @api.custom_gradient\n def f(x):\n vjp = lambda g: (jnp.cos(x) * jnp.array([3., 4., 5.]),)\n return jnp.sum(jnp.sin(x)), vjp\n\n self.assertAllClose(f(jnp.arange(3)), jnp.sum(jnp.sin(jnp.arange(3.))),\n check_dtypes=False)\n self.assertAllClose(\n api.grad(f)(jnp.arange(3.)),\n api.grad(lambda x: jnp.sum(jnp.sin(x)))(jnp.arange(3.)) * jnp.array([3., 4., 5.]),\n check_dtypes=False)\n\n def test_custom_gradient_can_return_singleton_value_in_vjp(self):\n @api.custom_gradient\n def f(x):\n return x ** 2, lambda g: g * x\n\n self.assertAllClose(f(3.), 9., check_dtypes=False)\n self.assertAllClose(api.grad(f)(3.), 3., check_dtypes=False)\n self.assertAllClose(api.grad(api.grad(f))(3.), 1., check_dtypes=False)\n\n def test_closure_convert(self):\n def minimize(objective_fn, x0):\n converted_fn, aux_args = api.closure_convert(objective_fn, x0)\n return _minimize(converted_fn, x0, *aux_args)\n\n @partial(api.custom_vjp, nondiff_argnums=(0,))\n def _minimize(objective_fn, x0, *args):\n _ = objective_fn(x0, *args)\n return jnp.cos(x0)\n\n def fwd(objective_fn, x0, *args):\n y = _minimize(objective_fn, x0, *args)\n return y, (y, args)\n\n def rev(objective_fn, res, g):\n y, args = res\n x0_bar = 17. * y\n args_bars = [42. * a for a in args]\n return (x0_bar, *args_bars)\n\n _minimize.defvjp(fwd, rev)\n\n def obj(c, x):\n return jnp.sum((x - c) ** 2.)\n\n def solve(c, x):\n def closure(x):\n return obj(c, x)\n return jnp.sum(minimize(closure, x))\n\n c, x = jnp.ones(2), jnp.zeros(2)\n self.assertAllClose(solve(c, x), 2.0, check_dtypes=False)\n g_c, g_x = api.grad(solve, argnums=(0, 1))(c, x)\n self.assertAllClose(g_c, 42. * jnp.ones(2), check_dtypes=False)\n self.assertAllClose(g_x, 17. * jnp.ones(2), check_dtypes=False)\n\n\nclass InvertibleADTest(jtu.JaxTestCase):\n\n def test_invertible_basic(self):\n def f(x):\n return (jnp.exp(x) * 4) * x\n\n finv = jax.invertible(f)\n\n x = jnp.ones((5,))\n\n if config.omnistaging_enabled:\n expected = \"\"\"\n { lambda ; a b.\n let c = exp a\n d = mul c 4.0\n e = mul d a\n f = mul b a\n g = div e a\n h = mul b g\n i = div g 4.0\n j = mul f 4.0\n _ = log i\n k = mul j i\n l = add_any h k\n in (l,) }\n \"\"\"\n else:\n expected = \"\"\"\n { lambda ; a b.\n let c = exp a\n d = mul c 4.0\n e = mul d a\n f = div e a\n g = mul b f\n h = mul b a\n i = mul h 4.0\n j = div f 4.0\n k = mul i j\n l = add_any g k\n in (l,) }\n \"\"\"\n\n jaxpr = jax.make_jaxpr(lambda p, ct: jax.vjp(finv, p)[1](ct))(x, x)\n self.assertMultiLineStrippedEqual(expected, str(jaxpr))\n\n self.assertAllClose(jax.value_and_grad(lambda x: np.sum(f(x)))(x),\n jax.value_and_grad(lambda x: np.sum(finv(x)))(x),\n check_dtypes=True)\n\n def test_invertible_blocks(self):\n # NB: This is the reversible ResNet block\n def mk_reversible_block(f, g):\n @jax.custom_ivjp\n def rev_block(x1, x2):\n y1 = f(x2) + x1\n y2 = g(y1) + x2\n return y1, y2\n\n @rev_block.defivjp\n def rev_block_ivjp(xs, ys, dys):\n (y1, y2) = ys\n (dy1, dy2) = dys\n\n dgo, dx2 = dy2, dy2\n go, gvjp = jax.vjp(g, y1)\n dy1 += gvjp(dgo)[0]\n del gvjp\n x2 = y2 - go\n\n dfo, dx1 = dy1, dy1\n fo, fvjp = jax.vjp(f, x2)\n dx2 += fvjp(dfo)[0]\n del fvjp\n x1 = y1 - fo\n\n return (x1, x2), (dx1, dx2)\n\n return rev_block\n\n rev_block = mk_reversible_block(jnp.sin, jnp.cos)\n\n def g(x1, x2):\n for i in range(2):\n x1, x2 = rev_block(x1, x2)\n return x1, x2\n\n def reduce(f, x1, x2):\n y1, y2 = f(x1, x2)\n return np.sum(y1) + np.sum(y2)\n\n x = np.ones((1,))\n # FIXME: This breaks when argnums is left as default (i.e. 0), because JVP prunes\n # zero tangents from call primitives.\n self.assertAllClose(jax.value_and_grad(partial(reduce, jax.invertible(g)), argnums=(0, 1))(x, x + 2),\n jax.value_and_grad(partial(reduce, g), argnums=(0, 1))(x, x + 2),\n check_dtypes=True)\n\n def test_invertible_partial_diff(self):\n # Check that we don't have to differentiate with respect to inputs\n # of the invertible function.\n def f(x, y):\n return (jnp.exp(x) * 4) * x, y + 4\n\n finv = jax.invertible(f)\n o = np.ones((5,))\n self.assertAllClose(jax.value_and_grad(lambda x: np.sum(f(x, o)[0]))(o),\n jax.value_and_grad(lambda x: np.sum(finv(x, o)[0]))(o),\n check_dtypes=True)\n\n def test_invertible_pytree(self):\n def f(x, y):\n return jnp.exp(x[0]) * x[1] + y\n\n finv = jax.invertible(f)\n o = np.ones((5,))\n self.assertAllClose(jax.value_and_grad(lambda x: np.sum(f((x, x), x)[0]))(o),\n jax.value_and_grad(lambda x: np.sum(finv((x, x), x)[0]))(o),\n check_dtypes=True)\n\n\nclass DeprecatedCustomTransformsTest(jtu.JaxTestCase):\n\n def test_defvjp_all(self):\n foo_p = Primitive('foo')\n def foo(x): return 2. * foo_p.bind(x)\n\n ad.defvjp_all(foo_p, lambda x: (x**2, lambda g: (4 * g * jnp.sin(x),)))\n val_ans, grad_ans = api.value_and_grad(foo)(3.)\n self.assertAllClose(val_ans, 2 * 3.**2, check_dtypes=False)\n self.assertAllClose(grad_ans, 4 * 2 * np.sin(3.), check_dtypes=False)\n\n def test_defvjp_all_const(self):\n foo_p = Primitive('foo')\n def foo(x): return foo_p.bind(x)\n\n ad.defvjp_all(foo_p, lambda x: (x**2, lambda g: (12.,)))\n val_ans, grad_ans = api.value_and_grad(foo)(3.)\n self.assertAllClose(val_ans, 9., check_dtypes=False)\n self.assertAllClose(grad_ans, 12.)\n\n def test_defvjp_all_higher_order_revmode(self):\n foo_p = Primitive('foo')\n def foo(x): return 2. * foo_p.bind(x)\n\n ad.defvjp_all(foo_p, lambda x: (x**2, lambda g: (g * x ** 2,)))\n ans = api.grad(api.grad(foo))(3.)\n self.assertAllClose(ans, 2 * 2 * 3., check_dtypes=False)\n\n def test_defvjp_all_multiple_arguments(self):\n # also tests passing in symbolic zero tangents b/c we differentiate wrt only\n # the first argument in one case\n\n foo_p = Primitive('foo')\n def foo(x, y): return foo_p.bind(x, y)\n\n def vjpfun(x, y):\n out = x**2 + y**3\n vjp = lambda g: (g + x + y, g * x * 9.)\n return out, vjp\n\n ad.defvjp_all(foo_p, vjpfun)\n val_ans, grad_ans = api.value_and_grad(foo)(3., 4.)\n self.assertAllClose(val_ans, 3.**2 + 4.**3, check_dtypes=False)\n self.assertAllClose(grad_ans, 1. + 3. + 4., check_dtypes=False)\n\n ans = api.grad(foo, (0, 1))(3., 4.)\n self.assertAllClose(ans, (1. + 3. + 4., 1. * 3. * 9.), check_dtypes=False)\n\n def test_defvjp_all_custom_transforms(self):\n @api.custom_transforms\n def foo(x):\n return jnp.sin(x)\n\n api.defvjp_all(foo, lambda x: (jnp.sin(x), lambda g: (g * x,)))\n val_ans, grad_ans = api.value_and_grad(foo)(3.)\n self.assertAllClose(val_ans, np.sin(3.), check_dtypes=False)\n self.assertAllClose(grad_ans, 3., check_dtypes=False)\n\n # TODO(mattjj): add defvjp_all test with pytree arguments\n\n def test_defvjp(self):\n @api.custom_transforms\n def foo(x, y):\n return jnp.sin(x * y)\n\n api.defvjp(foo, None, lambda g, _, x, y: g * x * y)\n val_ans, grad_ans = api.value_and_grad(foo)(3., 4.)\n self.assertAllClose(val_ans, np.sin(3. * 4.), check_dtypes=False)\n self.assertAllClose(grad_ans, 0., check_dtypes=False)\n\n ans_0, ans_1 = api.grad(foo, (0, 1))(3., 4.)\n self.assertAllClose(ans_0, 0., check_dtypes=False)\n self.assertAllClose(ans_1, 3. * 4., check_dtypes=False)\n\n def test_defvjp_higher_order(self):\n @api.custom_transforms\n def foo(x):\n return jnp.sin(2. * x)\n\n api.defvjp(foo, lambda g, _, x: g * jnp.cos(x))\n ans = api.grad(api.grad(foo))(2.)\n expected = api.grad(api.grad(jnp.sin))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_defvjp_use_ans(self):\n @api.custom_transforms\n def foo(x, y):\n return jnp.sin(x * y)\n\n api.defvjp(foo, None, lambda g, ans, x, y: g * x * y + jnp.cos(ans))\n val_ans, grad_ans = api.value_and_grad(foo, 1)(3., 4.)\n self.assertAllClose(val_ans, np.sin(3. * 4.), check_dtypes=False)\n self.assertAllClose(grad_ans, 3. * 4. + np.cos(np.sin(3. * 4)),\n check_dtypes=False)\n\n def test_custom_transforms_eval_with_pytrees(self):\n @api.custom_transforms\n def f(x):\n a, b = x[0], x[1]\n return {'hi': 2 * a, 'bye': 2 * b}\n\n ans = f((1, 2))\n self.assertEqual(ans, {'hi': 2 * 1, 'bye': 2 * 2})\n\n def test_custom_transforms_jit_with_pytrees(self):\n @api.custom_transforms\n def f(x):\n a, b = x[0], x[1]\n return {'hi': 2 * a, 'bye': 2 * b}\n\n ans = jit(f)((1, 2))\n self.assertEqual(ans, {'hi': 2 * 1, 'bye': 2 * 2})\n\n def test_custom_transforms_jit_with_pytrees_consts(self):\n # The purpose of this test is to exercise the custom_transforms default\n # translation rule in how it deals with constants that are too large to be\n # treated as literals (at the time of writing).\n z = np.arange(10.)\n\n @api.custom_transforms\n def f(x):\n a, b = x[0], x[1]\n return {'hi': 2 * a, 'bye': z * b}\n\n ans = jit(f)((1, 2))\n self.assertAllClose(ans, {'hi': 2 * 1, 'bye': z * 2}, check_dtypes=False)\n\n def test_custom_transforms_jvp_with_pytrees(self):\n @api.custom_transforms\n def f(x):\n a, b = x[0], x[1]\n return {'hi': 2 * a, 'bye': 2 * b}\n\n ans, out_tangent = api.jvp(f, ((1., 2.),), ((3., 4.),))\n self.assertEqual(ans, {'hi': 2 * 1, 'bye': 2 * 2})\n self.assertEqual(out_tangent, {'hi': 2 * 3, 'bye': 2 * 4})\n\n def test_custom_transforms_vmap_with_pytrees(self):\n raise unittest.SkipTest(\"Test deprecated custom_transforms\")\n @api.custom_transforms\n def f(x):\n a, b = x[0], x[1]\n return {'hi': 2 * a, 'bye': 2 * b}\n\n ans = api.vmap(f)((np.arange(3), np.ones((3, 2))))\n expected = {'hi': 2 * np.arange(3), 'bye': 2 * np.ones((3, 2))}\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_transforms_jvp_with_closure(self):\n def f(x):\n @api.custom_transforms\n def g(y):\n return x * y\n return g(x)\n\n ans = api.grad(f)(1.)\n expected = 2.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_vjp_zeros(self):\n @api.custom_transforms\n def f(x, y):\n return 2 * x, 3 * y\n\n def f_vjp(x, y):\n return (2 * x, 3 * y), lambda ts: (4 * ts[0], 5 * ts[1])\n\n api.defvjp_all(f, f_vjp, )\n api.grad(lambda x, y: f(x, y)[0])(1., 2.) # doesn't crash\n\n def test_custom_transforms_vjp_nones(self):\n core.skip_checks = True # Fails with checks\n # issue raised by jsnoek@ and jumper@\n @jax.custom_transforms\n def solve(a, b):\n return jnp.dot(jnp.linalg.inv(a), b)\n # print(solve(a, b))\n\n def solve_vjp(a, b):\n x = solve(a, b)\n def vjp(x_tangent):\n dx = jnp.dot(solve(a, x_tangent), x.T)\n out = (dx, b * 0.)\n return out\n return x, vjp\n jax.defvjp_all(solve, solve_vjp)\n gf = grad(lambda a,b: jnp.sum(solve(a, b)))\n\n n = 3\n a_in = jnp.linspace(0, 1, n)[:, None]\n a = jnp.dot(a_in, a_in.T) + jnp.eye(n) * 0.1\n real_x = np.random.RandomState(0).randn(n)\n b = jnp.dot(a + jnp.eye(a.shape[0]), real_x)\n print(gf(a, b)) # doesn't crash\n\n\nclass BufferDonationTest(jtu.JaxTestCase):\n\n @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n def test_pmap_donate_argnums_invalidates_input(self):\n move = api.pmap(lambda x: x + x - x, donate_argnums=0)\n n = jax.local_device_count()\n x = api.pmap(lambda x: x)(jnp.ones([n]))\n y = move(x)\n self.assertDeleted(x)\n np.testing.assert_allclose(y, [1.] * n)\n\n def test_pmap_nested_donate_ignored(self):\n pmap_fun = jit(lambda x: api.pmap(lambda y: y ** 2, donate_argnums=0)(x))\n a = api.pmap(lambda x: x)(jnp.array([1]))\n\n # NOTE(mattjj): stopped raising error here and instead just ignored\n # with self.assertRaisesRegex(ValueError, \"nested.*not supported\"):\n # pmap_fun(a)\n\n pmap_fun(a) # doesn't crash\n\n assertDeleted = lambda self, x: self._assertDeleted(x, True)\n assertNotDeleted = lambda self, x: self._assertDeleted(x, False)\n\n def _assertDeleted(self, x, deleted):\n if hasattr(x, \"device_buffer\"):\n self.assertEqual(x.device_buffer.is_deleted(), deleted)\n else:\n for buffer in x.device_buffers:\n self.assertEqual(buffer.is_deleted(), deleted)\n\n\nclass NamedCallTest(jtu.JaxTestCase):\n\n def test_default_name(self):\n\n @api.named_call\n def my_test_function(x):\n return x**2\n\n @jax.jit\n def f(x):\n return my_test_function(x)\n\n c = jax.xla_computation(f)(2)\n self.assertIn(\"my_test_function\", c.as_hlo_text())\n\n def test_non_jaxtype_arg(self):\n # For the test to fail without the invalid JaxType filter we need to pass\n # in a valid JaxType that forces the invalid Jaxtype to be raised to an\n # abstract value.\n def f(not_a_jaxtype, a_jaxtype):\n # then Jax needs to try and evaluate the abstractified non-JaxType\n if not_a_jaxtype:\n return a_jaxtype\n return 0\n\n f = api.named_call(f, name=\"test\")\n out = jax.jit(f, static_argnums=(0,))(\"not a Jaxtype\", 1)\n self.assertEqual(out, 1)\n\n @parameterized.parameters(jax.jit, jax.grad, jax.vmap, jax.remat)\n def test_jax_transforms(self, transform):\n f = jnp.sum\n x = jnp.array([1.])\n\n unnamed_out = transform(f)(x)\n named_out = transform(api.named_call(f, name=\"test\"))(x)\n\n self.assertEqual(unnamed_out, named_out)\n\n def test_static_argnums(self):\n f = api.named_call(lambda x, y: y if x else None, name=\"test\")\n f = jax.jit(f, static_argnums=(0,))\n out = f(True, 5)\n self.assertEqual(out, 5)\n\n def test_partial_eval(self):\n f = api.named_call(lambda x, y: y if x else None, name=\"test\")\n f = jax.jit(functools.partial(f, True))\n out = f(5)\n self.assertEqual(out, 5)\n\n\nif __name__ == '__main__':\n absltest.main(testLoader=jtu.JaxTestLoader())\n" ]
[ [ "numpy.asarray", "numpy.all", "numpy.random.randn", "numpy.tri", "numpy.exp", "numpy.arange", "numpy.eye", "numpy.float16", "numpy.sin", "numpy.float32", "numpy.zeros", "numpy.random.rand", "numpy.testing.assert_allclose", "numpy.array", "numpy.random.RandomState", "numpy.sum", "numpy.int32", "numpy.cos", "numpy.ones", "numpy.shape" ] ]
Naveenal/PythonRobotics
[ "7e697d8e5311e652c539b0a6d883f8af6185b4ed" ]
[ "PathPlanning/RRTStar/rrt_star.py" ]
[ "\"\"\"\n\nPath planning Sample Code with RRT*\n\nauthor: Atsushi Sakai(@Atsushi_twi)\n\n\"\"\"\n\nimport math\nimport os\nimport sys\n\nimport matplotlib.pyplot as plt\n\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) +\n \"/../RRT/\")\n\ntry:\n from rrt import RRT\nexcept ImportError:\n raise\n\nshow_animation = True\n\n\nclass RRTStar(RRT):\n \"\"\"\n Class for RRT Star planning\n \"\"\"\n\n class Node(RRT.Node):\n def __init__(self, x, y):\n super().__init__(x, y)\n self.cost = 0.0\n\n def __init__(self, start, goal, obstacle_list, rand_area,\n expand_dis=3.0,\n path_resolution=1.0,\n goal_sample_rate=20,\n max_iter=300,\n connect_circle_dist=50.0\n ):\n super().__init__(start, goal, obstacle_list,\n rand_area, expand_dis, path_resolution, goal_sample_rate, max_iter)\n \"\"\"\n Setting Parameter\n\n start:Start Position [x,y]\n goal:Goal Position [x,y]\n obstacleList:obstacle Positions [[x,y,size],...]\n randArea:Random Sampling Area [min,max]\n\n \"\"\"\n self.connect_circle_dist = connect_circle_dist\n self.goal_node = self.Node(goal[0], goal[1])\n\n def planning(self, animation=True, search_until_max_iter=True):\n \"\"\"\n rrt star path planning\n\n animation: flag for animation on or off\n search_until_maxiter: search until max iteration for path improving or not\n \"\"\"\n\n self.node_list = [self.start]\n for i in range(self.max_iter):\n print(\"Iter:\", i, \", number of nodes:\", len(self.node_list))\n rnd = self.get_random_node()\n nearest_ind = self.get_nearest_node_index(self.node_list, rnd)\n new_node = self.steer(self.node_list[nearest_ind], rnd, self.expand_dis)\n\n if self.check_collision(new_node, self.obstacle_list):\n near_inds = self.find_near_nodes(new_node)\n new_node = self.choose_parent(new_node, near_inds)\n if new_node:\n self.node_list.append(new_node)\n self.rewire(new_node, near_inds)\n\n if animation and i % 5 == 0:\n self.draw_graph(rnd)\n\n if (not search_until_max_iter) and new_node: # check reaching the goal\n last_index = self.search_best_goal_node()\n if last_index:\n return self.generate_final_course(last_index)\n\n print(\"reached max iteration\")\n\n last_index = self.search_best_goal_node()\n if last_index:\n return self.generate_final_course(last_index)\n\n return None\n\n def choose_parent(self, new_node, near_inds):\n if not near_inds:\n return None\n\n # search nearest cost in near_inds\n costs = []\n for i in near_inds:\n near_node = self.node_list[i]\n t_node = self.steer(near_node, new_node)\n if t_node and self.check_collision(t_node, self.obstacle_list):\n costs.append(self.calc_new_cost(near_node, new_node))\n else:\n costs.append(float(\"inf\")) # the cost of collision node\n min_cost = min(costs)\n\n if min_cost == float(\"inf\"):\n print(\"There is no good path.(min_cost is inf)\")\n return None\n\n min_ind = near_inds[costs.index(min_cost)]\n new_node = self.steer(self.node_list[min_ind], new_node)\n new_node.parent = self.node_list[min_ind]\n new_node.cost = min_cost\n\n return new_node\n\n def search_best_goal_node(self):\n dist_to_goal_list = [self.calc_dist_to_goal(n.x, n.y) for n in self.node_list]\n goal_inds = [dist_to_goal_list.index(i) for i in dist_to_goal_list if i <= self.expand_dis]\n\n # safe_goal_inds = goal_inds\n safe_goal_inds = []\n for goal_ind in goal_inds:\n t_node = self.steer(self.node_list[goal_ind], self.goal_node)\n if self.check_collision(t_node, self.obstacle_list):\n safe_goal_inds.append(goal_ind)\n\n if not safe_goal_inds:\n return None\n\n min_cost = min([self.node_list[i].cost for i in goal_inds])\n for i in goal_inds:\n if self.node_list[i].cost == min_cost:\n return i\n\n return None\n\n def find_near_nodes(self, new_node):\n nnode = len(self.node_list) + 1\n r = self.connect_circle_dist * math.sqrt((math.log(nnode) / nnode))\n dist_list = [(node.x - new_node.x) ** 2 +\n (node.y - new_node.y) ** 2 for node in self.node_list]\n near_inds = [dist_list.index(i) for i in dist_list if i <= r ** 2]\n return near_inds\n\n def rewire(self, new_node, near_inds):\n for i in near_inds:\n near_node = self.node_list[i]\n edge_node = self.steer(new_node, near_node)\n if not edge_node:\n continue\n edge_node.cost = self.calc_new_cost(new_node, near_node)\n\n no_collision = self.check_collision(edge_node, self.obstacle_list)\n improved_cost = near_node.cost > edge_node.cost\n\n if no_collision and improved_cost:\n near_node = edge_node\n near_node.parent = new_node\n self.propagate_cost_to_leaves(new_node)\n\n def calc_new_cost(self, from_node, to_node):\n d, _ = self.calc_distance_and_angle(from_node, to_node)\n return from_node.cost + d\n\n def propagate_cost_to_leaves(self, parent_node):\n\n for node in self.node_list:\n if node.parent == parent_node:\n node.cost = self.calc_new_cost(parent_node, node)\n self.propagate_cost_to_leaves(node)\n\n\ndef main():\n print(\"Start \" + __file__)\n\n # ====Search Path with RRT====\n obstacle_list = [\n (5, 5, 1),\n (3, 6, 2),\n (3, 8, 2),\n (3, 10, 2),\n (7, 5, 2),\n (9, 5, 2),\n (8, 10, 1),\n ] # [x,y,size(radius)]\n\n # Set Initial parameters\n rrt_star = RRTStar(start=[0, 0],\n goal=[6, 10],\n rand_area=[-2, 15],\n obstacle_list=obstacle_list)\n path = rrt_star.planning(animation=show_animation)\n\n if path is None:\n print(\"Cannot find path\")\n else:\n print(\"found path!!\")\n\n # Draw final path\n if show_animation:\n rrt_star.draw_graph()\n plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')\n plt.grid(True)\n plt.pause(0.01) # Need for Mac\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "matplotlib.pyplot.plot", "matplotlib.pyplot.show", "matplotlib.pyplot.pause", "matplotlib.pyplot.grid" ] ]
calearning/testGithubClone
[ "bea30a8aa7e2a6dbdece1d5559c8cbc8fb39a7b5" ]
[ "generate_documentation_images.py" ]
[ "from __future__ import print_function, division\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\nfrom imgaug import parameters as iap\nimport numpy as np\nfrom scipy import ndimage, misc\n#from skimage import data\n#import matplotlib.pyplot as plt\n#from matplotlib import gridspec\n#import six\n#import six.moves as sm\nimport os\nimport PIL.Image\nimport math\nfrom skimage import data\n\ntry:\n from cStringIO import StringIO as BytesIO\nexcept ImportError:\n from io import BytesIO\n\nDOCS_IMAGES_BASE_PATH = os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n \"docs\",\n \"images\"\n)\n\ndef main():\n chapter_examples_basics()\n chapter_examples_keypoints()\n chapter_augmenters()\n\ndef save(chapter_dir, filename, image, quality=None):\n dir_fp = os.path.join(DOCS_IMAGES_BASE_PATH, chapter_dir)\n if not os.path.exists(dir_fp):\n os.makedirs(dir_fp)\n file_fp = os.path.join(dir_fp, filename)\n\n image_jpg = compress_to_jpg(image, quality=quality)\n image_jpg_decompressed = decompress_jpg(image_jpg)\n\n # If the image file already exists and is (practically) identical,\n # then don't save it again to avoid polluting the repository with tons\n # of image updates.\n # Not that we have to compare here the results AFTER jpg compression\n # and then decompression. Otherwise we compare two images of which\n # image (1) has never been compressed while image (2) was compressed and\n # then decompressed.\n if os.path.isfile(file_fp):\n image_saved = ndimage.imread(file_fp, mode=\"RGB\")\n #print(\"arrdiff\", arrdiff(image_jpg_decompressed, image_saved))\n same_shape = (image_jpg_decompressed.shape == image_saved.shape)\n d_avg = arrdiff(image_jpg_decompressed, image_saved) if same_shape else -1\n if same_shape and d_avg <= 1.0:\n print(\"[INFO] Did not save image '%s/%s', because the already saved image is basically identical (d_avg=%.4f)\" % (chapter_dir, filename, d_avg,))\n return\n\n with open(file_fp, \"w\") as f:\n f.write(image_jpg)\n\ndef arrdiff(arr1, arr2):\n nb_cells = np.prod(arr2.shape)\n d_avg = np.sum(np.power(np.abs(arr1 - arr2), 2)) / nb_cells\n return d_avg\n\ndef compress_to_jpg(image, quality=75):\n quality = quality if quality is not None else 75\n im = PIL.Image.fromarray(image)\n out = BytesIO()\n im.save(out, format=\"JPEG\", quality=quality)\n jpg_string = out.getvalue()\n out.close()\n return jpg_string\n\ndef decompress_jpg(image_compressed):\n img_compressed_buffer = BytesIO()\n img_compressed_buffer.write(image_compressed)\n img = ndimage.imread(img_compressed_buffer, mode=\"RGB\")\n img_compressed_buffer.close()\n return img\n\ndef grid(images, rows, cols, border=1, border_color=255):\n nb_images = len(images)\n cell_height = max([image.shape[0] for image in images])\n cell_width = max([image.shape[1] for image in images])\n channels = set([image.shape[2] for image in images])\n assert len(channels) == 1\n nb_channels = list(channels)[0]\n if rows is None and cols is None:\n rows = cols = int(math.ceil(math.sqrt(nb_images)))\n elif rows is not None:\n cols = int(math.ceil(nb_images / rows))\n elif cols is not None:\n rows = int(math.ceil(nb_images / cols))\n assert rows * cols >= nb_images\n\n cell_height = cell_height + 1 * border\n cell_width = cell_width + 1 * border\n\n width = cell_width * cols\n height = cell_height * rows\n grid = np.zeros((height, width, nb_channels), dtype=np.uint8)\n cell_idx = 0\n for row_idx in range(rows):\n for col_idx in range(cols):\n if cell_idx < nb_images:\n image = images[cell_idx]\n border_top = border_right = border_bottom = border_left = border\n #if row_idx > 1:\n border_top = 0\n #if col_idx > 1:\n border_left = 0\n image = np.pad(image, ((border_top, border_bottom), (border_left, border_right), (0, 0)), mode=\"constant\", constant_values=border_color)\n\n cell_y1 = cell_height * row_idx\n cell_y2 = cell_y1 + image.shape[0]\n cell_x1 = cell_width * col_idx\n cell_x2 = cell_x1 + image.shape[1]\n grid[cell_y1:cell_y2, cell_x1:cell_x2, :] = image\n cell_idx += 1\n\n grid = np.pad(grid, ((border, 0), (border, 0), (0, 0)), mode=\"constant\", constant_values=border_color)\n\n return grid\n\ndef checkerboard(size):\n img = data.checkerboard()\n img3d = np.tile(img[..., np.newaxis], (1, 1, 3))\n return misc.imresize(img3d, size)\n\n###############################\n# Examples: Basics\n###############################\n\ndef chapter_examples_basics():\n \"\"\"Generate all example images for the chapter `Examples: Basics`\n in the documentation.\"\"\"\n chapter_examples_basics_simple()\n chapter_examples_basics_heavy()\n\ndef chapter_examples_basics_simple():\n import imgaug as ia\n from imgaug import augmenters as iaa\n\n # Example batch of images.\n # The array has shape (32, 64, 64, 3) and dtype uint8.\n images = np.array(\n [ia.quokka(size=(64, 64)) for _ in range(32)],\n dtype=np.uint8\n )\n\n seq = iaa.Sequential([\n iaa.Fliplr(0.5), # horizontal flips\n iaa.Crop(percent=(0, 0.1)), # random crops\n # Small gaussian blur with random sigma between 0 and 0.5.\n # But we only blur about 50% of all images.\n iaa.Sometimes(0.5,\n iaa.GaussianBlur(sigma=(0, 0.5))\n ),\n # Strengthen or weaken the contrast in each image.\n iaa.ContrastNormalization((0.75, 1.5)),\n # Add gaussian noise.\n # For 50% of all images, we sample the noise once per pixel.\n # For the other 50% of all images, we sample the noise per pixel AND\n # channel. This can change the color (not only brightness) of the\n # pixels.\n iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5),\n # Make some images brighter and some darker.\n # In 20% of all cases, we sample the multiplier once per channel,\n # which can end up changing the color of the images.\n iaa.Multiply((0.8, 1.2), per_channel=0.2),\n # Apply affine transformations to each image.\n # Scale/zoom them, translate/move them, rotate them and shear them.\n iaa.Affine(\n scale={\"x\": (0.8, 1.2), \"y\": (0.8, 1.2)},\n translate_percent={\"x\": (-0.2, 0.2), \"y\": (-0.2, 0.2)},\n rotate=(-25, 25),\n shear=(-8, 8)\n )\n ], random_order=True) # apply augmenters in random order\n\n ia.seed(1)\n images_aug = seq.augment_images(images)\n\n # ------------\n\n save(\n \"examples_basics\",\n \"simple.jpg\",\n grid(images_aug, cols=8, rows=4)\n )\n\ndef chapter_examples_basics_heavy():\n import imgaug as ia\n from imgaug import augmenters as iaa\n import numpy as np\n\n # Example batch of images.\n # The array has shape (32, 64, 64, 3) and dtype uint8.\n images = np.array(\n [ia.quokka(size=(64, 64)) for _ in range(32)],\n dtype=np.uint8\n )\n\n # Sometimes(0.5, ...) applies the given augmenter in 50% of all cases,\n # e.g. Sometimes(0.5, GaussianBlur(0.3)) would blur roughly every second\n # image.\n sometimes = lambda aug: iaa.Sometimes(0.5, aug)\n\n # Define our sequence of augmentation steps that will be applied to every image.\n seq = iaa.Sequential(\n [\n #\n # Apply the following augmenters to most images.\n #\n iaa.Fliplr(0.5), # horizontally flip 50% of all images\n iaa.Flipud(0.2), # vertically flip 20% of all images\n\n # crop some of the images by 0-10% of their height/width\n sometimes(iaa.Crop(percent=(0, 0.1))),\n\n # Apply affine transformations to some of the images\n # - scale to 80-120% of image height/width (each axis independently)\n # - translate by -20 to +20 relative to height/width (per axis)\n # - rotate by -45 to +45 degrees\n # - shear by -16 to +16 degrees\n # - order: use nearest neighbour or bilinear interpolation (fast)\n # - mode: use any available mode to fill newly created pixels\n # see API or scikit-image for which modes are available\n # - cval: if the mode is constant, then use a random brightness\n # for the newly created pixels (e.g. sometimes black,\n # sometimes white)\n sometimes(iaa.Affine(\n scale={\"x\": (0.8, 1.2), \"y\": (0.8, 1.2)},\n translate_percent={\"x\": (-0.2, 0.2), \"y\": (-0.2, 0.2)},\n rotate=(-45, 45),\n shear=(-16, 16),\n order=[0, 1],\n cval=(0, 255),\n mode=ia.ALL\n )),\n\n #\n # Execute 0 to 5 of the following (less important) augmenters per\n # image. Don't execute all of them, as that would often be way too\n # strong.\n #\n iaa.SomeOf((0, 5),\n [\n # Convert some images into their superpixel representation,\n # sample between 20 and 200 superpixels per image, but do\n # not replace all superpixels with their average, only\n # some of them (p_replace).\n sometimes(\n iaa.Superpixels(\n p_replace=(0, 1.0),\n n_segments=(20, 200)\n )\n ),\n\n # Blur each image with varying strength using\n # gaussian blur (sigma between 0 and 3.0),\n # average/uniform blur (kernel size between 2x2 and 7x7)\n # median blur (kernel size between 3x3 and 11x11).\n iaa.OneOf([\n iaa.GaussianBlur((0, 3.0)),\n iaa.AverageBlur(k=(2, 7)),\n iaa.MedianBlur(k=(3, 11)),\n ]),\n\n # Sharpen each image, overlay the result with the original\n # image using an alpha between 0 (no sharpening) and 1\n # (full sharpening effect).\n iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)),\n\n # Same as sharpen, but for an embossing effect.\n iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)),\n\n # Search in some images either for all edges or for\n # directed edges. These edges are then marked in a black\n # and white image and overlayed with the original image\n # using an alpha of 0 to 0.7.\n sometimes(iaa.OneOf([\n iaa.EdgeDetect(alpha=(0, 0.7)),\n iaa.DirectedEdgeDetect(\n alpha=(0, 0.7), direction=(0.0, 1.0)\n ),\n ])),\n\n # Add gaussian noise to some images.\n # In 50% of these cases, the noise is randomly sampled per\n # channel and pixel.\n # In the other 50% of all cases it is sampled once per\n # pixel (i.e. brightness change).\n iaa.AdditiveGaussianNoise(\n loc=0, scale=(0.0, 0.05*255), per_channel=0.5\n ),\n\n # Either drop randomly 1 to 10% of all pixels (i.e. set\n # them to black) or drop them on an image with 2-5% percent\n # of the original size, leading to large dropped\n # rectangles.\n iaa.OneOf([\n iaa.Dropout((0.01, 0.1), per_channel=0.5),\n iaa.CoarseDropout(\n (0.03, 0.15), size_percent=(0.02, 0.05),\n per_channel=0.2\n ),\n ]),\n\n # Invert each image's chanell with 5% probability.\n # This sets each pixel value v to 255-v.\n iaa.Invert(0.05, per_channel=True), # invert color channels\n\n # Add a value of -10 to 10 to each pixel.\n iaa.Add((-10, 10), per_channel=0.5),\n\n # Change brightness of images (50-150% of original value).\n iaa.Multiply((0.5, 1.5), per_channel=0.5),\n\n # Improve or worsen the contrast of images.\n iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5),\n\n # Convert each image to grayscale and then overlay the\n # result with the original with random alpha. I.e. remove\n # colors with varying strengths.\n iaa.Grayscale(alpha=(0.0, 1.0)),\n\n # In some images move pixels locally around (with random\n # strengths).\n sometimes(\n iaa.ElasticTransformation(alpha=(0.5, 3.5), sigma=0.25)\n ),\n\n # In some images distort local areas with varying strength.\n sometimes(iaa.PiecewiseAffine(scale=(0.01, 0.05)))\n ],\n # do all of the above augmentations in random order\n random_order=True\n )\n ],\n # do all of the above augmentations in random order\n random_order=True\n )\n\n ia.seed(1)\n images_aug = seq.augment_images(images)\n\n # ------------\n\n save(\n \"examples_basics\",\n \"heavy.jpg\",\n grid(images_aug, cols=8, rows=4)\n )\n\n###############################\n# Examples: Keypoints\n###############################\n\ndef chapter_examples_keypoints():\n \"\"\"Generate all example images for the chapter `Examples: Keypoints`\n in the documentation.\"\"\"\n chapter_examples_keypoints_simple()\n\ndef chapter_examples_keypoints_simple():\n import imgaug as ia\n from imgaug import augmenters as iaa\n\n ia.seed(1)\n\n image = ia.quokka(size=(256, 256))\n keypoints = ia.KeypointsOnImage([\n ia.Keypoint(x=65, y=100),\n ia.Keypoint(x=75, y=200),\n ia.Keypoint(x=100, y=100),\n ia.Keypoint(x=200, y=80)\n ], shape=image.shape)\n\n seq = iaa.Sequential([\n iaa.Multiply((1.2, 1.5)), # change brightness, doesn't affect keypoints\n iaa.Affine(\n rotate=10,\n scale=(0.5, 0.7)\n ) # rotate by exactly 10deg and scale to 50-70%, affects keypoints\n ])\n\n # Make our sequence deterministic.\n # We can now apply it to the image and then to the keypoints and it will\n # lead to the same augmentations.\n # IMPORTANT: Call this once PER BATCH, otherwise you will always get the\n # exactly same augmentations for every batch!\n seq_det = seq.to_deterministic()\n\n # augment keypoints and images\n image_aug = seq_det.augment_images([image])[0]\n keypoints_aug = seq_det.augment_keypoints([keypoints])[0]\n\n # print coordinates before/after augmentation (see below)\n for i in range(len(keypoints.keypoints)):\n before = keypoints.keypoints[i]\n after = keypoints_aug.keypoints[i]\n print(\"Keypoint %d: (%d, %d) -> (%d, %d)\" % (\n i, before.x, before.y, after.x, after.y)\n )\n\n # image with keypoints before/after augmentation (shown below)\n image_before = keypoints.draw_on_image(image, size=7)\n image_after = keypoints_aug.draw_on_image(image_aug, size=7)\n\n # ------------\n\n save(\n \"examples_keypoints\",\n \"simple.jpg\",\n grid([image_before, image_after], cols=2, rows=1),\n quality=90\n )\n\n###############################\n# Overview of augmenters\n###############################\n\ndef run_and_save_augseq(filename, augseq, images, cols, rows, quality=75, seed=1):\n ia.seed(seed)\n # augseq may be a single seq (applied to all images) or a list (one seq per\n # image).\n # use type() here instead of isinstance, because otherwise Sequential is\n # also interpreted as a list\n if type(augseq) == list:\n # one augmenter per image specified\n assert len(augseq) == len(images)\n images_aug = [augseq[i].augment_image(images[i]) for i in range(len(images))]\n else:\n # calling N times augment_image() is here critical for random order in\n # Sequential\n images_aug = [augseq.augment_image(images[i]) for i in range(len(images))]\n save(\n \"overview_of_augmenters\",\n filename,\n grid(images_aug, cols=cols, rows=rows),\n quality=quality\n )\n\ndef chapter_augmenters():\n chapter_augmenters_sequential()\n chapter_augmenters_someof()\n chapter_augmenters_oneof()\n chapter_augmenters_sometimes()\n chapter_augmenters_withcolorspace()\n chapter_augmenters_withchannels()\n chapter_augmenters_noop()\n chapter_augmenters_lambda()\n chapter_augmenters_assertlambda()\n chapter_augmenters_assertshape()\n chapter_augmenters_scale()\n chapter_augmenters_cropandpad()\n chapter_augmenters_pad()\n chapter_augmenters_crop()\n chapter_augmenters_fliplr()\n chapter_augmenters_flipud()\n chapter_augmenters_superpixels()\n chapter_augmenters_changecolorspace()\n chapter_augmenters_grayscale()\n chapter_augmenters_gaussianblur()\n chapter_augmenters_averageblur()\n chapter_augmenters_medianblur()\n chapter_augmenters_convolve()\n chapter_augmenters_sharpen()\n chapter_augmenters_emboss()\n chapter_augmenters_edgedetect()\n chapter_augmenters_directededgedetect()\n chapter_augmenters_add()\n chapter_augmenters_addelementwise()\n chapter_augmenters_additivegaussiannoise()\n chapter_augmenters_multiply()\n chapter_augmenters_multiplyelementwise()\n chapter_augmenters_dropout()\n chapter_augmenters_coarsedropout()\n chapter_augmenters_invert()\n chapter_augmenters_contrastnormalization()\n chapter_augmenters_affine()\n chapter_augmenters_piecewiseaffine()\n chapter_augmenters_elastictransformation()\n\ndef chapter_augmenters_sequential():\n aug = iaa.Sequential([\n iaa.Affine(translate_px={\"x\":-40}),\n iaa.AdditiveGaussianNoise(scale=0.2*255)\n ])\n run_and_save_augseq(\n \"sequential.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\n aug = iaa.Sequential([\n iaa.Affine(translate_px={\"x\":-40}),\n iaa.AdditiveGaussianNoise(scale=0.2*255)\n ], random_order=True)\n run_and_save_augseq(\n \"sequential_random_order.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\ndef chapter_augmenters_someof():\n aug = iaa.SomeOf(2, [\n iaa.Affine(rotate=45),\n iaa.AdditiveGaussianNoise(scale=0.2*255),\n iaa.Add(50, per_channel=True),\n iaa.Sharpen(alpha=0.5)\n ])\n run_and_save_augseq(\n \"someof.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\n aug = iaa.SomeOf((0, None), [\n iaa.Affine(rotate=45),\n iaa.AdditiveGaussianNoise(scale=0.2*255),\n iaa.Add(50, per_channel=True),\n iaa.Sharpen(alpha=0.5)\n ])\n run_and_save_augseq(\n \"someof_0_to_none.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\n aug = iaa.SomeOf(2, [\n iaa.Affine(rotate=45),\n iaa.AdditiveGaussianNoise(scale=0.2*255),\n iaa.Add(50, per_channel=True),\n iaa.Sharpen(alpha=0.5)\n ], random_order=True)\n run_and_save_augseq(\n \"someof_random_order.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\ndef chapter_augmenters_oneof():\n aug = iaa.OneOf([\n iaa.Affine(rotate=45),\n iaa.AdditiveGaussianNoise(scale=0.2*255),\n iaa.Add(50, per_channel=True),\n iaa.Sharpen(alpha=0.5)\n ])\n run_and_save_augseq(\n \"oneof.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\ndef chapter_augmenters_sometimes():\n aug = iaa.Sometimes(0.5, iaa.GaussianBlur(sigma=2.0))\n run_and_save_augseq(\n \"sometimes.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2,\n seed=2\n )\n\n aug = iaa.Sometimes(\n 0.5,\n iaa.GaussianBlur(sigma=2.0),\n iaa.Sequential([iaa.Affine(rotate=45), iaa.Sharpen(alpha=1.0)])\n )\n run_and_save_augseq(\n \"sometimes_if_else.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\ndef chapter_augmenters_withcolorspace():\n aug = iaa.WithColorspace(\n to_colorspace=\"HSV\",\n from_colorspace=\"RGB\",\n children=iaa.WithChannels(0, iaa.Add((10, 50)))\n )\n run_and_save_augseq(\n \"withcolorspace.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\ndef chapter_augmenters_withchannels():\n aug = iaa.WithChannels(0, iaa.Add((10, 100)))\n run_and_save_augseq(\n \"withchannels.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\n aug = iaa.WithChannels(0, iaa.Affine(rotate=(0, 45)))\n run_and_save_augseq(\n \"withchannels_affine.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\ndef chapter_augmenters_noop():\n aug = iaa.Noop()\n run_and_save_augseq(\n \"noop.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\ndef chapter_augmenters_lambda():\n def img_func(images, random_state, parents, hooks):\n for img in images:\n img[::4] = 0\n return images\n\n def keypoint_func(keypoints_on_images, random_state, parents, hooks):\n return keypoints_on_images\n\n aug = iaa.Lambda(img_func, keypoint_func)\n run_and_save_augseq(\n \"lambda.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\ndef chapter_augmenters_assertlambda():\n pass\n\ndef chapter_augmenters_assertshape():\n pass\n\ndef chapter_augmenters_scale():\n aug = iaa.Scale({\"height\": 32, \"width\": 64})\n run_and_save_augseq(\n \"scale_32x64.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\n aug = iaa.Scale({\"height\": 32, \"width\": \"keep-aspect-ratio\"})\n run_and_save_augseq(\n \"scale_32xkar.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\n aug = iaa.Scale((0.5, 1.0))\n run_and_save_augseq(\n \"scale_50_to_100_percent.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\n aug = iaa.Scale({\"height\": (0.5, 0.75), \"width\": [16, 32, 64]})\n run_and_save_augseq(\n \"scale_h_uniform_w_choice.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\ndef chapter_augmenters_cropandpad():\n aug = iaa.CropAndPad(percent=(-0.25, 0.25))\n run_and_save_augseq(\n \"cropandpad_percent.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\n aug = iaa.CropAndPad(\n percent=(0, 0.2),\n pad_mode=[\"constant\", \"edge\"],\n pad_cval=(0, 128)\n )\n run_and_save_augseq(\n \"cropandpad_mode_cval.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n aug = iaa.CropAndPad(\n px=((0, 30), (0, 10), (0, 30), (0, 10)),\n pad_mode=ia.ALL,\n pad_cval=(0, 128)\n )\n run_and_save_augseq(\n \"cropandpad_pad_complex.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(32)], cols=8, rows=4\n )\n\n aug = iaa.CropAndPad(\n px=(-10, 10),\n sample_independently=False\n )\n run_and_save_augseq(\n \"cropandpad_correlated.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\ndef chapter_augmenters_pad():\n pass\n\ndef chapter_augmenters_crop():\n pass\n\ndef chapter_augmenters_fliplr():\n aug = iaa.Fliplr(0.5)\n run_and_save_augseq(\n \"fliplr.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\ndef chapter_augmenters_flipud():\n aug = iaa.Flipud(0.5)\n run_and_save_augseq(\n \"flipud.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\ndef chapter_augmenters_superpixels():\n aug = iaa.Superpixels(p_replace=0.5, n_segments=64)\n run_and_save_augseq(\n \"superpixels_50_64.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\n aug = iaa.Superpixels(p_replace=(0.1, 1.0), n_segments=(16, 128))\n run_and_save_augseq(\n \"superpixels.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\n #ps = [1/8*i for i in range(8)]\n ps = np.linspace(0, 1.0, num=8)\n run_and_save_augseq(\n \"superpixels_vary_p.jpg\",\n [iaa.Superpixels(p_replace=p, n_segments=64) for p in ps],\n [ia.quokka(size=(64, 64)) for _ in range(8)], cols=8, rows=1,\n quality=75\n )\n\n ns = [16*i for i in range(1, 9)]\n run_and_save_augseq(\n \"superpixels_vary_n.jpg\",\n [iaa.Superpixels(p_replace=1.0, n_segments=n) for n in ns],\n [ia.quokka(size=(64, 64)) for _ in range(8)], cols=8, rows=1,\n quality=75\n )\n\ndef chapter_augmenters_changecolorspace():\n aug = iaa.Sequential([\n iaa.ChangeColorspace(from_colorspace=\"RGB\", to_colorspace=\"HSV\"),\n iaa.WithChannels(0, iaa.Add((50, 100))),\n iaa.ChangeColorspace(from_colorspace=\"HSV\", to_colorspace=\"RGB\")\n ])\n run_and_save_augseq(\n \"changecolorspace.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\ndef chapter_augmenters_grayscale():\n aug = iaa.Grayscale(alpha=(0.0, 1.0))\n run_and_save_augseq(\n \"grayscale.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\n #alphas = [1/8*i for i in range(8)]\n alphas = np.linspace(0, 1.0, num=8)\n run_and_save_augseq(\n \"grayscale_vary_alpha.jpg\",\n [iaa.Grayscale(alpha=alpha) for alpha in alphas],\n [ia.quokka(size=(64, 64)) for _ in range(8)], cols=8, rows=1,\n quality=75\n )\n\ndef chapter_augmenters_gaussianblur():\n aug = iaa.GaussianBlur(sigma=(0.0, 3.0))\n run_and_save_augseq(\n \"gaussianblur.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(16)], cols=4, rows=4,\n quality=75\n )\n\ndef chapter_augmenters_averageblur():\n aug = iaa.AverageBlur(k=(2, 11))\n run_and_save_augseq(\n \"averageblur.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(16)], cols=4, rows=4,\n quality=75\n )\n\n aug = iaa.AverageBlur(k=((5, 11), (1, 3)))\n run_and_save_augseq(\n \"averageblur_mixed.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(16)], cols=4, rows=4,\n quality=75\n )\n\ndef chapter_augmenters_medianblur():\n aug = iaa.MedianBlur(k=(3, 11))\n run_and_save_augseq(\n \"medianblur.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(16)], cols=4, rows=4,\n quality=75\n )\n\n # median doesnt support this\n #aug = iaa.MedianBlur(k=((5, 11), (1, 3)))\n #run_and_save_augseq(\n # \"medianblur_mixed.jpg\", aug,\n # [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2,\n # quality=75\n #)\n\ndef chapter_augmenters_convolve():\n matrix = np.array([[0, -1, 0],\n [-1, 4, -1],\n [0, -1, 0]])\n aug = iaa.Convolve(matrix=matrix)\n run_and_save_augseq(\n \"convolve.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2,\n quality=50\n )\n\n def gen_matrix(image, nb_channels, random_state):\n matrix_A = np.array([[0, -1, 0],\n [-1, 4, -1],\n [0, -1, 0]])\n matrix_B = np.array([[0, 0, 0],\n [0, -4, 1],\n [0, 2, 1]])\n if random_state.rand() < 0.5:\n return [matrix_A] * nb_channels\n else:\n return [matrix_B] * nb_channels\n aug = iaa.Convolve(matrix=gen_matrix)\n run_and_save_augseq(\n \"convolve_callable.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2\n )\n\ndef chapter_augmenters_sharpen():\n aug = iaa.Sharpen(alpha=(0.0, 1.0), lightness=(0.75, 2.0))\n run_and_save_augseq(\n \"sharpen.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n #alphas = [1/8*i for i in range(8)]\n alphas = np.linspace(0, 1.0, num=8)\n run_and_save_augseq(\n \"sharpen_vary_alpha.jpg\",\n [iaa.Sharpen(alpha=alpha, lightness=1.0) for alpha in alphas],\n [ia.quokka(size=(64, 64)) for _ in range(8)], cols=8, rows=1,\n quality=90\n )\n\n #lightnesses = [1/8*i for i in range(8)]\n lightnesses = np.linspace(0.75, 1.5, num=8)\n run_and_save_augseq(\n \"sharpen_vary_lightness.jpg\",\n [iaa.Sharpen(alpha=1.0, lightness=lightness) for lightness in lightnesses],\n [ia.quokka(size=(64, 64)) for _ in range(8)], cols=8, rows=1,\n quality=90\n )\n\ndef chapter_augmenters_emboss():\n aug = iaa.Emboss(alpha=(0.0, 1.0), strength=(0.5, 1.5))\n run_and_save_augseq(\n \"emboss.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n #alphas = [1/8*i for i in range(8)]\n alphas = np.linspace(0, 1.0, num=8)\n run_and_save_augseq(\n \"emboss_vary_alpha.jpg\",\n [iaa.Emboss(alpha=alpha, strength=1.0) for alpha in alphas],\n [ia.quokka(size=(64, 64)) for _ in range(8)], cols=8, rows=1\n )\n\n #strength = [0.5+(0.5/8)*i for i in range(8)]\n strength = np.linspace(0.5, 1.5, num=8)\n run_and_save_augseq(\n \"emboss_vary_strength.jpg\",\n [iaa.Emboss(alpha=1.0, strength=strength) for strength in strength],\n [ia.quokka(size=(64, 64)) for _ in range(8)], cols=8, rows=1\n )\n\ndef chapter_augmenters_edgedetect():\n aug = iaa.EdgeDetect(alpha=(0.0, 1.0))\n run_and_save_augseq(\n \"edgedetect.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n #alphas = [1/8*i for i in range(8)]\n alphas = np.linspace(0, 1.0, num=8)\n run_and_save_augseq(\n \"edgedetect_vary_alpha.jpg\",\n [iaa.EdgeDetect(alpha=alpha) for alpha in alphas],\n [ia.quokka(size=(64, 64)) for _ in range(8)], cols=8, rows=1\n )\n\ndef chapter_augmenters_directededgedetect():\n aug = iaa.DirectedEdgeDetect(alpha=(0.0, 1.0), direction=(0.0, 1.0))\n run_and_save_augseq(\n \"directededgedetect.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n #alphas = [1/8*i for i in range(8)]\n alphas = np.linspace(0, 1.0, num=8)\n run_and_save_augseq(\n \"directededgedetect_vary_alpha.jpg\",\n [iaa.DirectedEdgeDetect(alpha=alpha, direction=0) for alpha in alphas],\n [ia.quokka(size=(64, 64)) for _ in range(8)], cols=8, rows=1\n )\n\n #strength = [0.5+(0.5/8)*i for i in range(8)]\n directions = np.linspace(0.0, 1.0, num=8)\n run_and_save_augseq(\n \"directededgedetect_vary_direction.jpg\",\n [iaa.DirectedEdgeDetect(alpha=1.0, direction=direction) for direction in directions],\n [ia.quokka(size=(64, 64)) for _ in range(8)], cols=8, rows=1\n )\n\ndef chapter_augmenters_add():\n aug = iaa.Add((-40, 40))\n run_and_save_augseq(\n \"add.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2,\n quality=75\n )\n\n aug = iaa.Add((-40, 40), per_channel=0.5)\n run_and_save_augseq(\n \"add_per_channel.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2,\n quality=75\n )\n\ndef chapter_augmenters_addelementwise():\n aug = iaa.AddElementwise((-40, 40))\n run_and_save_augseq(\n \"addelementwise.jpg\", aug,\n [ia.quokka(size=(512, 512)) for _ in range(1)], cols=1, rows=1,\n quality=90\n )\n\n aug = iaa.AddElementwise((-40, 40), per_channel=0.5)\n run_and_save_augseq(\n \"addelementwise_per_channel.jpg\", aug,\n [ia.quokka(size=(512, 512)) for _ in range(1)], cols=1, rows=1,\n quality=90\n )\n\ndef chapter_augmenters_additivegaussiannoise():\n aug = iaa.AdditiveGaussianNoise(scale=(0, 0.2*255))\n run_and_save_augseq(\n \"additivegaussiannoise.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2,\n quality=90\n )\n\n aug = iaa.AdditiveGaussianNoise(scale=0.2*255)\n run_and_save_augseq(\n \"additivegaussiannoise_large.jpg\", aug,\n [ia.quokka(size=(512, 512)) for _ in range(1)], cols=1, rows=1,\n quality=90\n )\n\n aug = iaa.AdditiveGaussianNoise(scale=0.2*255, per_channel=True)\n run_and_save_augseq(\n \"additivegaussiannoise_per_channel.jpg\", aug,\n [ia.quokka(size=(512, 512)) for _ in range(1)], cols=1, rows=1,\n quality=90\n )\n\ndef chapter_augmenters_multiply():\n aug = iaa.Multiply((0.5, 1.5))\n run_and_save_augseq(\n \"multiply.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n aug = iaa.Multiply((0.5, 1.5), per_channel=0.5)\n run_and_save_augseq(\n \"multiply_per_channel.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\ndef chapter_augmenters_multiplyelementwise():\n aug = iaa.MultiplyElementwise((0.5, 1.5))\n run_and_save_augseq(\n \"multiplyelementwise.jpg\", aug,\n [ia.quokka(size=(512, 512)) for _ in range(1)], cols=1, rows=1,\n quality=90\n )\n\n aug = iaa.MultiplyElementwise((0.5, 1.5), per_channel=True)\n run_and_save_augseq(\n \"multiplyelementwise_per_channel.jpg\", aug,\n [ia.quokka(size=(512, 512)) for _ in range(1)], cols=1, rows=1,\n quality=90\n )\n\ndef chapter_augmenters_dropout():\n aug = iaa.Dropout(p=(0, 0.2))\n run_and_save_augseq(\n \"dropout.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2,\n quality=75\n )\n\n aug = iaa.Dropout(p=(0, 0.2), per_channel=0.5)\n run_and_save_augseq(\n \"dropout_per_channel.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2,\n quality=75\n )\n\ndef chapter_augmenters_coarsedropout():\n aug = iaa.CoarseDropout(0.02, size_percent=0.5)\n run_and_save_augseq(\n \"coarsedropout.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2,\n quality=75\n )\n\n aug = iaa.CoarseDropout((0.0, 0.05), size_percent=(0.02, 0.25))\n run_and_save_augseq(\n \"coarsedropout_both_uniform.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2,\n quality=75,\n seed=2\n )\n\n aug = iaa.CoarseDropout(0.02, size_percent=0.15, per_channel=0.5)\n run_and_save_augseq(\n \"coarsedropout_per_channel.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2,\n quality=75,\n seed=2\n )\n\ndef chapter_augmenters_invert():\n aug = iaa.Invert(0.5)\n run_and_save_augseq(\n \"invert.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n aug = iaa.Invert(0.25, per_channel=0.5)\n run_and_save_augseq(\n \"invert_per_channel.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\ndef chapter_augmenters_contrastnormalization():\n aug = iaa.ContrastNormalization((0.5, 1.5))\n run_and_save_augseq(\n \"contrastnormalization.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n aug = iaa.ContrastNormalization((0.5, 1.5), per_channel=0.5)\n run_and_save_augseq(\n \"contrastnormalization_per_channel.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\ndef chapter_augmenters_affine():\n aug = iaa.Affine(scale=(0.5, 1.5))\n run_and_save_augseq(\n \"affine_scale.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n aug = iaa.Affine(scale={\"x\": (0.5, 1.5), \"y\": (0.5, 1.5)})\n run_and_save_augseq(\n \"affine_scale_independently.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n aug = iaa.Affine(translate_percent={\"x\": (-0.2, 0.2), \"y\": (-0.2, 0.2)})\n run_and_save_augseq(\n \"affine_translate_percent.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n aug = iaa.Affine(translate_px={\"x\": (-20, 20), \"y\": (-20, 20)})\n run_and_save_augseq(\n \"affine_translate_px.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n aug = iaa.Affine(rotate=(-45, 45))\n run_and_save_augseq(\n \"affine_rotate.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n aug = iaa.Affine(shear=(-16, 16))\n run_and_save_augseq(\n \"affine_shear.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\n aug = iaa.Affine(translate_percent={\"x\": -0.20}, mode=ia.ALL, cval=(0, 255))\n run_and_save_augseq(\n \"affine_fill.jpg\", aug,\n [ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2\n )\n\ndef chapter_augmenters_piecewiseaffine():\n aug = iaa.PiecewiseAffine(scale=(0.01, 0.05))\n run_and_save_augseq(\n \"piecewiseaffine.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2,\n quality=75\n )\n\n aug = iaa.PiecewiseAffine(scale=(0.01, 0.05))\n run_and_save_augseq(\n \"piecewiseaffine_checkerboard.jpg\", aug,\n [checkerboard(size=(128, 128)) for _ in range(8)], cols=4, rows=2,\n quality=75\n )\n\n scales = np.linspace(0.0, 0.3, num=8)\n run_and_save_augseq(\n \"piecewiseaffine_vary_scales.jpg\",\n [iaa.PiecewiseAffine(scale=scale) for scale in scales],\n [checkerboard(size=(128, 128)) for _ in range(8)], cols=8, rows=1,\n quality=75\n )\n\n gridvals = [2, 4, 6, 8, 10, 12, 14, 16]\n run_and_save_augseq(\n \"piecewiseaffine_vary_grid.jpg\",\n [iaa.PiecewiseAffine(scale=0.05, nb_rows=g, nb_cols=g) for g in gridvals],\n [checkerboard(size=(128, 128)) for _ in range(8)], cols=8, rows=1,\n quality=75\n )\n\ndef chapter_augmenters_elastictransformation():\n aug = iaa.ElasticTransformation(alpha=(0, 5.0), sigma=0.25)\n run_and_save_augseq(\n \"elastictransformations.jpg\", aug,\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2,\n quality=75\n )\n\n alphas = np.linspace(0.0, 5.0, num=8)\n run_and_save_augseq(\n \"elastictransformations_vary_alpha.jpg\",\n [iaa.ElasticTransformation(alpha=alpha, sigma=0.25) for alpha in alphas],\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=8, rows=1,\n quality=75\n )\n\n sigmas = np.linspace(0.01, 1.0, num=8)\n run_and_save_augseq(\n \"elastictransformations_vary_sigmas.jpg\",\n [iaa.ElasticTransformation(alpha=2.5, sigma=sigma) for sigma in sigmas],\n [ia.quokka(size=(128, 128)) for _ in range(8)], cols=8, rows=1,\n quality=75\n )\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "scipy.misc.imresize", "scipy.ndimage.imread", "numpy.pad", "numpy.linspace", "numpy.abs", "numpy.tile", "numpy.prod", "numpy.array", "numpy.zeros" ] ]
sandyz1000/Text-Generation-LSTM
[ "c7043eb7020bef43f535134c1cd01799c7ec86ac" ]
[ "doc2vec.py" ]
[ "from __future__ import print_function\n\nimport codecs\nimport time\nimport os\nimport gensim\nimport numpy as np\nfrom nltk.tokenize import RegexpTokenizer, PunktSentenceTokenizer\nfrom six.moves import cPickle\nfrom pathlib import Path\n\nDATA_DIR = Path(\"corpus\")\nSAVE_DIR = Path('save') # directory to store models\n\n\nclass Doc2Vector(object):\n \"\"\"\n # Text Generation using Bidirectional LSTM and Doc2Vec models 2/3\n\n If you have reached directly this page, I suggest to start reading the first part of this\n article. It describes how to create a RNN model to generate a text, word after word.\n\n I finished the first part of the article explaining I will try to improve the generation\n of sentences, by detecting patterns in the sequences of sentences, not only in the\n sequences of words.\n\n It could be an improvement, because doing that, the context of a paragraph (is it a\n description of a countryside? a dialog between characters? which people are involved?\n what are the previous actions? etc.) could emerge and can be used to select wisely the\n next sentence of the text.\n\n The process will be similar to the previous one, however, I will have to vectorize all\n sentences in the text, and try to find patterns in sequences of these vectors.\n\n In order to do that, we will use **Doc2Vec**.\n\n Doc2Vec\n\n Doc2Vec is able to vectorize a paragraph of text. If you do not know it, I suggest to\n have a look on the gensim web site, that describes how its work and what you’re allowed\n to do with it.\n\n In a short, we will transform each sentences of our text in a vector of a specific space.\n The great thing of the approach is we will be able to compare them ; by example,\n to retrieve the most similar sentence of a given one.\n\n Last but not least, the dimension of the vectors will be the same, whatever is the number\n of words in their linked sentence.\n\n It is exactly what we are looking for: I will be able to train a new LSTM, trying to\n catch pattern from sequences of vectors of the same dimensions.\n\n I have to be honest: I am not sure we can perform such task with enough accuracy,\n but let’s have some tests. It is an experiment, at worst, it will be a good exercice.``\n\n So, once all sentences will be converted to vectors, we will try to **train a new\n bidirectional LSTM**. It purpose will be to predict the best vector, next to a sequence\n of vectors.\n\n Then how will we generate text ?\n\n Pretty easy: thanks to our previous LSTM model, we will generate sentences as candidates\n to be the next phrase. We will infer their vectors using the **trained doc2Vec model**,\n then pick the closest one to the prediction of our new LSTM model.\n\n \"\"\"\n\n def __init__(self, file_list, do_save=False):\n self.FILE_LIST = file_list\n self.word_tokenizer = RegexpTokenizer(r'\\w+')\n self.sent_tokenizer = PunktSentenceTokenizer()\n self.do_save = do_save\n self.d2v_model = None\n\n def save_sentence_vector(self, d2v_model, sentences, do_save=True):\n if do_save:\n sentences_vector = []\n t = 500\n for i, sent in enumerate(sentences):\n if i % t == 0:\n print(\"sentence-{0} : {1} \\n ***** \".format(i, sent))\n sentences_vector.append(d2v_model.infer_vector(sent, alpha=0.001,\n min_alpha=0.001,\n steps=10000))\n\n # save the sentences_vector\n sentences_vector_file = SAVE_DIR / 'sentences_vector_500_a001_ma001_s10000.pkl'\n with open(os.path.join(sentences_vector_file), 'wb') as f:\n cPickle.dump(sentences_vector, f)\n else:\n sentences_vector_file = SAVE_DIR / 'sentences_vector_500_a001_ma001_s10000.pkl'\n with open(os.path.join(sentences_vector_file), 'rb') as f:\n sentences_vector = cPickle.load(f)\n\n return sentences_vector\n\n def create_sentences(self):\n \"\"\" create sentences from files \"\"\"\n sentences = []\n for file_name in self.FILE_LIST:\n input_file = DATA_DIR / file_name\n\n with codecs.open(input_file, \"r\") as f:\n data = f.read()\n\n # use NLTK sentence tokenizer\n doc = self.sent_tokenizer.tokenize(data)\n sents = [self.word_tokenizer.tokenize(sent) for sent in doc]\n sentences.append(sents)\n # sentences = sentences + sents\n\n return sentences\n\n def doc2vec(self, do_save=False):\n sentences_label = []\n sentences = self.create_sentences()\n\n # create labels\n for i in range(np.array(sentences).shape[0]):\n sentences_label.append(\"ID\" + str(i))\n\n # Here are some insights for the used parameters:\n #\n # - **dimensions**: 300 dimensions seem to work well for classic subjects. In my case,\n # after few tests, I prefer to choose 500 dimensions,\n\n # - **epochs**: below 10 epochs, results are not good enough (similarity are not working\n # well), and bigger number of epochs creates to much similar vectors. So I chose 20\n # epochs for the training.\n\n # - **min_count**: I want to integrate all words in the training, even those with very\n # few occurrence. Indeed, I assume that, for my exercice, specific words could be\n # important. I set the value to 0, but 3 to 5 should be OK.\n\n # - **sample**: *0.0*. I do not want to downsample randomly higher-frequency words,\n # so I disabled it.\n\n # - **hs and dm**: Each time I want to infer a new vector from the trained model,\n # for a given sentence, I want to have the same output vector. In order to do that (\n # strangely it’s not so intuitive), I need to use a distributed bag of words as *training\n # algorithm (dm=0)* and *hierarchical softmax (hs=1)*. Indeed, for my purpose,\n # distributive memory and negative sampling seems to give less good results.\"\"\"\n\n if self.do_save:\n self.train_doc2vec_model(sentences, sentences_label, size=500, sample=0.0,\n alpha=0.025, min_alpha=0.001, min_count=0,\n window=10, epoch=20, dm=0, hs=1,\n save_file=DATA_DIR / 'doc2vec.w2v')\n\n # load the model\n self.d2v_model = gensim.models.doc2vec.Doc2Vec.load(DATA_DIR / 'doc2vec.w2v')\n sentences_vector = self.save_sentence_vector(self.d2v_model, sentences, do_save)\n nb_sequenced_sentences = 15\n vector_dim = 500\n\n X_train = np.zeros((len(sentences), nb_sequenced_sentences, vector_dim), dtype=np.float)\n y_train = np.zeros((len(sentences), vector_dim), dtype=np.float)\n\n t = 1000\n for i in range(len(sentences_label) - nb_sequenced_sentences - 1):\n if i % t == 0:\n print(\"new sequence: \", i)\n\n for k in range(nb_sequenced_sentences):\n sent = sentences_label[i + k]\n vect = sentences_vector[i + k]\n\n if i % t == 0:\n print(\" \", k + 1, \"th vector for this sequence. Sentence \", sent,\n \"(vector dim = \", len(vect), \")\")\n\n for j in range(len(vect)):\n X_train[i, k, j] = vect[j]\n\n senty = sentences_label[i + nb_sequenced_sentences]\n vecty = sentences_vector[i + nb_sequenced_sentences]\n if i % t == 0:\n print(\" y vector for this sequence \", senty, \": (vector dim = \", len(vecty), \")\")\n for j in range(len(vecty)):\n y_train[i, j] = vecty[j]\n\n return X_train, y_train\n\n def train_doc2vec_model(self, data, docLabels, size=300, sample=0.000001, dm=0, hs=1,\n window=10, min_count=0, workers=8, alpha=0.024, min_alpha=0.024,\n epoch=15, save_file='doc2vec.w2v'):\n \"\"\" Train doc to vec model \"\"\"\n\n class LabeledLineSentence(object):\n def __init__(self, doc_list, labels_list):\n self.labels_list = labels_list\n self.doc_list = doc_list\n\n def __iter__(self):\n for idx, doc in enumerate(self.doc_list):\n yield gensim.models.doc2vec.LabeledSentence(doc, [self.labels_list[idx]])\n\n startime = time.time()\n\n print(\"{0} articles loaded for model\".format(len(data)))\n\n it = LabeledLineSentence(data, docLabels)\n\n model = gensim.models.Doc2Vec(size=size, sample=sample, dm=dm, window=window,\n min_count=min_count, workers=workers, alpha=alpha,\n min_alpha=min_alpha, hs=hs) # use fixed learning rate\n model.build_vocab(it)\n for epoch in range(epoch):\n print(\"Training epoch {}\".format(epoch + 1))\n model.train(it, total_examples=model.corpus_count, epochs=model.iter)\n # model.alpha -= 0.002 # decrease the learning rate\n # model.min_alpha = model.alpha # fix the learning rate, no decay\n\n # saving the created model\n\n model.save(os.path.join(save_file))\n print('model saved')" ]
[ [ "numpy.array" ] ]
Dr-Awkward/UdacityImageClassifier
[ "7daf65f62c0bd8e23467472e4bea18fbd1323636" ]
[ "train.py" ]
[ "# Imports here\nimport torch\nfrom torch import nn as nn\nfrom torch import optim as optim\nimport nnModel\nimport helpers.DataLoader\nimport argparse\n\n#######################################################\n# Train a Neural Network using transfer learning:\n# 1. Get the directory to the image files to train with\n# 2. Set the directory to save checkpoints\n# 3. Choose the architecture\n# 4. Set the hyperparameters\n# 5. Choose GPU for training\n\n# Create the parser and add the arguments\nparser = argparse.ArgumentParser(description=\"Train a Neural Network using transfer learning\")\n# 1. Get the directory to the image files to train with\nparser.add_argument('data_directory', default='./flowers',\n help=\"The relative path to the image files to train on. It should include two folders: 'train' and 'test' for training.\")\n# 2. Get the directory to the image files to train with\nparser.add_argument('--save_dir', default='./',\n help=\"The relative path to save the neural network checkpoint\") \n# 3. Choose the architecture\nparser.add_argument('--arch', default=\"vgg19\",\n help=\"The architecture you wish to train the model with. Can be: vgg19 or densenet161\")\n# 4. Set the hyperparameters: Learning Rate, Hidden Units, Training Epochs, Training batch size\nparser.add_argument('--learning_rate', type=float, default=\"0.001\",\n help=\"The learning rate for the model\")\nparser.add_argument('--hidden_units', type=int, default=512,\n help=\"The number of units in the hidden layer\")\nparser.add_argument('--epochs', type=int, default=15,\n help=\"The amount of training epochs you wish to use\")\nparser.add_argument('--batch_size', type=int, default=32,\n help=\"The size of the batches you want to use for training\")\n# 5. Choose the GPU for training\nparser.add_argument('--gpu', default=False, action='store_true',\n help=\"If you would like to use the GPU for training. Default is False\")\n\n# Collect the arguments\nargs = parser.parse_args()\ndata_directory = args.data_directory\nsave_directory = args.save_dir\narch = args.arch\nlearning_rate = args.learning_rate\nhidden_units = args.hidden_units\nepochs = args.epochs\nbatch_size = args.batch_size\ngpu = args.gpu\n\n# Get the image data from the files and create the data loaders\ntrain_dataloaders, valid_dataloaders, test_dataloaders, train_datasets = helpers.DataLoader.load_image_data(data_directory, batch_size)\n \n# Create the model. Returns 0 if model cant be created\nmodel = nnModel.create_model(arch, hidden_units)\n\n# If we sucessfully create a model continue with the training\nif model != 0:\n # Define the loss function and optimizer\n criterion = nn.NLLLoss()\n optimizer = optim.Adam(model.classifier.parameters(), learning_rate) \n\n # Train the model with validation\n nnModel.train_model(model, train_dataloaders, valid_dataloaders, criterion, optimizer, epochs, gpu)\n\n # Save the model\n nnModel.save_model(model, train_datasets, learning_rate, batch_size, epochs, criterion, optimizer, hidden_units, arch)\n" ]
[ [ "torch.nn.NLLLoss" ] ]
google/crystalvalue
[ "719226fb302d414e94fcdb3ac4b468977f3529ec" ]
[ "src/synthetic_data.py" ]
[ "# Copyright 2021 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# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Module for creating synthetic data for testing crystal value pipeline.\"\"\"\n\nimport logging\n\nfrom typing import Optional\n\nfrom google.cloud import bigquery\nimport numpy as np\nimport pandas as pd\n\nfrom src import feature_engineering\n\nlogging.getLogger().setLevel(logging.INFO)\n\n_CUSTOMER_SEARCHES = frozenset([\n 'cool', 'car', 'amazing', 'beach', 'blue', 'car', 'drive', 'to', 'the',\n 'seaside', 'shiny'\n])\n\n\ndef create_synthetic_data(bigquery_client: Optional[bigquery.Client] = None,\n dataset_id: Optional[str] = None,\n table_name: Optional[str] = 'synthetic_data',\n row_count: int = 100000,\n start_date: str = '2018-01-01',\n end_date: str = '2021-01-01',\n load_table_to_bigquery: bool = True,\n location: str = 'europe-west4') -> pd.DataFrame:\n \"\"\"Creates a synthetic transaction dataset with an option to load to Bigquery.\n\n The transaction dataset contains customer ids which can make multiple\n transactions. There is also additional information from the transaction\n including a numerical, categorical and a text column.\n\n Args:\n bigquery_client: The Bigquery client. Only required if\n load_table_to_bigquery is True.\n dataset_id: The Bigquery dataset_id within the project_id to load data to.\n Only required if load_table_to_bigquery is True.\n table_name: The Bigquery table name to load data to. Only required if\n load_table_to_bigquery is True.\n row_count: The number of rows in the dataset to generate.\n start_date: The start date of the transactions.\n end_date: The end date of the transactions.\n load_table_to_bigquery: Whether to load the data to Bigquery.\n location: The location of the dataset to load in Bigquery.\n\n Returns:\n The created dataset.\n \"\"\"\n\n date_list = pd.date_range(\n start=start_date, end=end_date, freq='1D').strftime('%Y-%m-%d').tolist()\n date_list = date_list * int((row_count / 100))\n\n data = pd.DataFrame({\n 'customer_id':\n np.random.poisson(row_count / 3, size=row_count),\n 'date':\n date_list[:row_count],\n 'numeric_column':\n np.random.exponential(5, size=row_count),\n 'bool_column':\n np.random.rand(row_count) > 0.5,\n 'categorical_column':\n np.random.poisson(3, size=row_count),\n 'text_column': [\n ' '.join(np.random.choice(list(_CUSTOMER_SEARCHES), 3))\n for i in range(row_count)\n ]\n }).round(3)\n data['value'] = data['numeric_column'] * data['categorical_column']\n data['categorical_column'] = [\n f'category_ {str(i)}' for i in data['categorical_column']\n ]\n\n if load_table_to_bigquery:\n feature_engineering.run_load_table_to_bigquery(\n data, bigquery_client, dataset_id, table_name, location)\n\n return data\n" ]
[ [ "numpy.random.rand", "numpy.random.poisson", "numpy.random.exponential", "pandas.date_range" ] ]
b0nce/strange_boostings
[ "c9f03c0a7e2dfb0292b178db5fdfc99f9c7e58eb" ]
[ "strangeboostings/gradient_based.py" ]
[ "import lightgbm as lgb\r\nimport numpy as np\r\nfrom scipy.special import expit as sigmoid\r\nfrom sklearn.base import clone, BaseEstimator, ClassifierMixin\r\nfrom sklearn.linear_model import SGDClassifier\r\nfrom sklearn.utils.validation import check_X_y, check_array, check_is_fitted\r\nfrom sklearn.utils.multiclass import unique_labels\r\n\r\n\r\nclass LGBMLinearClassifier(BaseEstimator, ClassifierMixin):\r\n def __init__(self, lightgbm_model=None, linear_model=None, random_state=None):\r\n assert lightgbm_model is None or isinstance(\r\n lightgbm_model, lgb.LGBMClassifier\r\n ), f\"Only LGBMClassifier isntances are allowed!\"\r\n self.lightgbm_model = lightgbm_model\r\n self.linear_model = linear_model\r\n self.random_state = random_state\r\n\r\n def _validate_data(self, X, y=None, reset=True, **check_array_params):\r\n if hasattr(self, \"n_features_in_\"):\r\n if self.n_features_in_ != check_array(X).shape[1]:\r\n raise ValueError(f\"Input has incorrect shape: {X.shape}\")\r\n else:\r\n self.n_features_in_ = check_array(X).shape[1]\r\n if y is not None:\r\n return check_X_y(X, y)\r\n else:\r\n return check_array(X)\r\n\r\n def fit(self, X, y, valset=None):\r\n X, y = self._validate_data(X, y)\r\n if valset is not None:\r\n valset = self._validate_data(*valset)\r\n self.classes_ = unique_labels(y)\r\n\r\n if self.lightgbm_model is not None:\r\n self.lightgbm_model_ = clone(self.lightgbm_model)\r\n else:\r\n self.lightgbm_model_ = lgb.LGBMClassifier(\r\n boosting_type=\"dart\", class_weight=\"balanced\", random_state=self.random_state\r\n )\r\n if self.linear_model is not None:\r\n self.linear_model_ = clone(self.linear_model)\r\n else:\r\n self.linear_model_ = SGDClassifier(loss=\"modified_huber\", random_state=self.random_state)\r\n\r\n self.lightgbm_model_.fit(X, y, eval_set=valset, verbose=False)\r\n X_contrib = self.lightgbm_model_.booster_.predict(X, pred_contrib=True)\r\n self.linear_model_.fit(X_contrib, y)\r\n\r\n return self\r\n\r\n def predict(self, X):\r\n check_is_fitted(self)\r\n X = self._validate_data(X)\r\n return self.linear_model_.predict(self.lightgbm_model_.booster_.predict(X, pred_contrib=True))\r\n\r\n def predict_proba(self, X):\r\n check_is_fitted(self)\r\n X = self._validate_data(X)\r\n try:\r\n return self.linear_model_.predict_proba(self.self.lightgbm_model_.booster_.predict(X, pred_contrib=True))\r\n except AttributeError:\r\n pred = self.linear_model_.decision_function(self.lightgbm_model_.booster_.predict(X, pred_contrib=True))\r\n return np.repeat([[-1, 0]], len(pred), axis=0) + sigmoid(pred)[:, None]\r\n" ]
[ [ "sklearn.utils.validation.check_is_fitted", "sklearn.utils.validation.check_array", "scipy.special.expit", "sklearn.base.clone", "sklearn.utils.validation.check_X_y", "sklearn.utils.multiclass.unique_labels", "sklearn.linear_model.SGDClassifier" ] ]
ricklentz/avalanche
[ "ee3baf287d6bd11cb4640d8ad8fd778269920124" ]
[ "avalanche/evaluation/metrics/loss.py" ]
[ "################################################################################\n# Copyright (c) 2021 ContinualAI. #\n# Copyrights licensed under the MIT License. #\n# See the accompanying LICENSE file for terms. #\n# #\n# Date: 30-12-2020 #\n# Author(s): Lorenzo Pellegrini #\n# E-mail: [email protected] #\n# Website: www.continualai.org #\n################################################################################\n\nfrom typing import List, Dict\n\nimport torch\nfrom torch import Tensor\n\nfrom avalanche.evaluation import PluginMetric, Metric, GenericPluginMetric\nfrom avalanche.evaluation.metrics.mean import Mean\nfrom avalanche.evaluation.metric_utils import phase_and_task\nfrom collections import defaultdict\n\n\nclass Loss(Metric[float]):\n \"\"\"\n The standalone Loss metric. This is a general metric\n used to compute more specific ones.\n\n Instances of this metric keeps the running average loss\n over multiple <prediction, target> pairs of Tensors,\n provided incrementally.\n The \"prediction\" and \"target\" tensors may contain plain labels or\n one-hot/logit vectors.\n\n Each time `result` is called, this metric emits the average loss\n across all predictions made since the last `reset`.\n\n The reset method will bring the metric to its initial state. By default\n this metric in its initial state will return a loss value of 0.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Creates an instance of the loss metric.\n\n By default this metric in its initial state will return a loss\n value of 0. The metric can be updated by using the `update` method\n while the running loss can be retrieved using the `result` method.\n \"\"\"\n self._mean_loss = defaultdict(Mean)\n \"\"\"\n The mean utility that will be used to store the running accuracy\n for each task label.\n \"\"\"\n\n @torch.no_grad()\n def update(self, loss: Tensor, patterns: int, task_label: int) -> None:\n \"\"\"\n Update the running loss given the loss Tensor and the minibatch size.\n\n :param loss: The loss Tensor. Different reduction types don't affect\n the result.\n :param patterns: The number of patterns in the minibatch.\n :param task_label: the task label associated to the current experience\n :return: None.\n \"\"\"\n self._mean_loss[task_label].update(torch.mean(loss), weight=patterns)\n\n def result(self, task_label=None) -> Dict[int, float]:\n \"\"\"\n Retrieves the running average loss per pattern.\n\n Calling this method will not change the internal state of the metric.\n :param task_label: None to return metric values for all the task labels.\n If an int, return value only for that task label\n :return: The running loss, as a float.\n \"\"\"\n assert task_label is None or isinstance(task_label, int)\n if task_label is None:\n return {k: v.result() for k, v in self._mean_loss.items()}\n else:\n return {task_label: self._mean_loss[task_label].result()}\n\n def reset(self, task_label=None) -> None:\n \"\"\"\n Resets the metric.\n\n :param task_label: None to reset all metric values. If an int,\n reset metric value corresponding to that task label.\n :return: None.\n \"\"\"\n assert task_label is None or isinstance(task_label, int)\n if task_label is None:\n self._mean_loss = defaultdict(Mean)\n else:\n self._mean_loss[task_label].reset()\n\n\nclass LossPluginMetric(GenericPluginMetric[float]):\n def __init__(self, reset_at, emit_at, mode):\n self._loss = Loss()\n super(LossPluginMetric, self).__init__(\n self._loss, reset_at, emit_at, mode\n )\n\n def reset(self, strategy=None) -> None:\n if self._reset_at == \"stream\" or strategy is None:\n self._metric.reset()\n else:\n self._metric.reset(phase_and_task(strategy)[1])\n\n def result(self, strategy=None) -> float:\n if self._emit_at == \"stream\" or strategy is None:\n return self._metric.result()\n else:\n return self._metric.result(phase_and_task(strategy)[1])\n\n def update(self, strategy):\n # task labels defined for each experience\n task_labels = strategy.experience.task_labels\n if len(task_labels) > 1:\n # task labels defined for each pattern\n # fall back to single task case\n task_label = 0\n else:\n task_label = task_labels[0]\n self._loss.update(\n strategy.loss, patterns=len(strategy.mb_y), task_label=task_label\n )\n\n\nclass MinibatchLoss(LossPluginMetric):\n \"\"\"\n The minibatch loss metric.\n This plugin metric only works at training time.\n\n This metric computes the average loss over patterns\n from a single minibatch.\n It reports the result after each iteration.\n\n If a more coarse-grained logging is needed, consider using\n :class:`EpochLoss` instead.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Creates an instance of the MinibatchLoss metric.\n \"\"\"\n super(MinibatchLoss, self).__init__(\n reset_at=\"iteration\", emit_at=\"iteration\", mode=\"train\"\n )\n\n def __str__(self):\n return \"Loss_MB\"\n\n\nclass EpochLoss(LossPluginMetric):\n \"\"\"\n The average loss over a single training epoch.\n This plugin metric only works at training time.\n\n The loss will be logged after each training epoch by computing\n the loss on the predicted patterns during the epoch divided by\n the overall number of patterns encountered in that epoch.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Creates an instance of the EpochLoss metric.\n \"\"\"\n\n super(EpochLoss, self).__init__(\n reset_at=\"epoch\", emit_at=\"epoch\", mode=\"train\"\n )\n\n def __str__(self):\n return \"Loss_Epoch\"\n\n\nclass RunningEpochLoss(LossPluginMetric):\n \"\"\"\n The average loss across all minibatches up to the current\n epoch iteration.\n This plugin metric only works at training time.\n\n At each iteration, this metric logs the loss averaged over all patterns\n seen so far in the current epoch.\n The metric resets its state after each training epoch.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Creates an instance of the RunningEpochLoss metric.\n \"\"\"\n\n super(RunningEpochLoss, self).__init__(\n reset_at=\"epoch\", emit_at=\"iteration\", mode=\"train\"\n )\n\n def __str__(self):\n return \"RunningLoss_Epoch\"\n\n\nclass ExperienceLoss(LossPluginMetric):\n \"\"\"\n At the end of each experience, this metric reports\n the average loss over all patterns seen in that experience.\n This plugin metric only works at eval time.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Creates an instance of ExperienceLoss metric\n \"\"\"\n super(ExperienceLoss, self).__init__(\n reset_at=\"experience\", emit_at=\"experience\", mode=\"eval\"\n )\n\n def __str__(self):\n return \"Loss_Exp\"\n\n\nclass StreamLoss(LossPluginMetric):\n \"\"\"\n At the end of the entire stream of experiences, this metric reports the\n average loss over all patterns seen in all experiences.\n This plugin metric only works at eval time.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Creates an instance of StreamLoss metric\n \"\"\"\n super(StreamLoss, self).__init__(\n reset_at=\"stream\", emit_at=\"stream\", mode=\"eval\"\n )\n\n def __str__(self):\n return \"Loss_Stream\"\n\n\ndef loss_metrics(\n *,\n minibatch=False,\n epoch=False,\n epoch_running=False,\n experience=False,\n stream=False\n) -> List[PluginMetric]:\n \"\"\"\n Helper method that can be used to obtain the desired set of\n plugin metrics.\n\n :param minibatch: If True, will return a metric able to log\n the minibatch loss at training time.\n :param epoch: If True, will return a metric able to log\n the epoch loss at training time.\n :param epoch_running: If True, will return a metric able to log\n the running epoch loss at training time.\n :param experience: If True, will return a metric able to log\n the loss on each evaluation experience.\n :param stream: If True, will return a metric able to log\n the loss averaged over the entire evaluation stream of experiences.\n\n :return: A list of plugin metrics.\n \"\"\"\n\n metrics = []\n if minibatch:\n metrics.append(MinibatchLoss())\n\n if epoch:\n metrics.append(EpochLoss())\n\n if epoch_running:\n metrics.append(RunningEpochLoss())\n\n if experience:\n metrics.append(ExperienceLoss())\n\n if stream:\n metrics.append(StreamLoss())\n\n return metrics\n\n\n__all__ = [\n \"Loss\",\n \"MinibatchLoss\",\n \"EpochLoss\",\n \"RunningEpochLoss\",\n \"ExperienceLoss\",\n \"StreamLoss\",\n \"loss_metrics\",\n]\n" ]
[ [ "torch.mean", "torch.no_grad" ] ]
dillondaudert/cullpdb_dssp
[ "3dd9623390f5a5ae9c0b2a9aa09e829b268419ef" ]
[ "proteindatasets/cpdb2/make_tfrecords.py" ]
[ "# convert a pandas DataFrame of amino acid sequence, secondary structure\n# sequence pairs into TF records\nfrom pathlib import Path\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.model_selection import KFold\nfrom features import prot_to_vector\n\nHOME = str(Path.home())\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\ndef _floats_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(value=value))\n\ndef cpdb2_to_tfrecord():\n \"\"\"\n Convert a pandas dataframe of protein, structure string pairs to TFRecord\n format.\n Create 5 pairs of training, validation data using 5-fold cross validation.\n \"\"\"\n\n data = pd.read_csv(HOME+\"/data/dssp/cpdb_dssp_14335.csv\")\n\n folds = 5\n\n kf = KFold(folds)\n\n\n curr_fold = 0\n\n for train_inds, valid_inds in kf.split(np.arange(data.shape[0])):\n curr_fold += 1\n print(\"Creating fold %d: Train %d, Valid %d\\n\" % (curr_fold, train_inds.size, valid_inds.size))\n\n train_file = HOME+\"/data/cpdb2/cpdb2_14335_train_%d.tfrecords\" % curr_fold\n valid_file = HOME+\"/data/cpdb2/cpdb2_14335_valid_%d.tfrecords\" % curr_fold\n\n print(\"Writing \", train_file)\n train_writer = tf.python_io.TFRecordWriter(train_file)\n for index in train_inds:\n # convert the strings to\n try:\n sample = data.iloc[index]\n seq_id = bytes(sample.dssp_id, \"utf-8\")\n seq_data = prot_to_vector(sample.seq, kind=\"aa\").reshape(-1)\n label_data = prot_to_vector(sample.ss, kind=\"ss\").reshape(-1)\n seq_len = len(sample.seq)\n\n tf_example = tf.train.Example(features=tf.train.Features(feature={\n \"dssp_id\": _bytes_feature(seq_id),\n \"seq_len\": _int64_feature(seq_len),\n \"seq_data\": _floats_feature(seq_data),\n \"label_data\": _floats_feature(label_data)}))\n\n train_writer.write(tf_example.SerializeToString())\n\n except Exception as e:\n print(\"Exception encountered while processing index %d\" % index)\n print(e)\n print(sample.dssp_id)\n# train_writer.close()\n# quit()\n\n\n train_writer.close()\n\n #\n print(\"Writing \", valid_file)\n valid_writer = tf.python_io.TFRecordWriter(valid_file)\n for index in valid_inds:\n # convert the strings to\n try:\n sample = data.iloc[index]\n seq_id = bytes(sample.dssp_id, \"utf-8\")\n seq_data = prot_to_vector(sample.seq, kind=\"aa\").reshape(-1)\n label_data = prot_to_vector(sample.ss, kind=\"ss\").reshape(-1)\n seq_len = len(sample.seq)\n\n tf_example = tf.train.Example(features=tf.train.Features(feature={\n \"dssp_id\": _bytes_feature(seq_id),\n \"seq_len\": _int64_feature(seq_len),\n \"seq_data\": _floats_feature(seq_data),\n \"label_data\": _floats_feature(label_data)}))\n\n valid_writer.write(tf_example.SerializeToString())\n\n except Exception as e:\n print(\"Exception encountered while processing index %d\" % index)\n print(e)\n print(sample.dssp_id)\n# valid_writer.close()\n# quit()\n\n\n valid_writer.close()\n\n\n print(\"Finished.\")\n" ]
[ [ "pandas.read_csv", "numpy.arange", "sklearn.model_selection.KFold", "tensorflow.python_io.TFRecordWriter", "tensorflow.train.BytesList", "tensorflow.train.FloatList", "tensorflow.train.Int64List" ] ]
sonofhypnos/rl-2048-game
[ "7d964fb2c1792fa9715a6487c0980dbd8474b13f" ]
[ "agent.py" ]
[ "\nimport torch\nimport numpy as np\nimport os\n\nclass DQNAgent:\n \n def __init__(self, env, model, target_model, optimizer, loss_function, experience_replay, learning_rate=3e-4, gamma=0.99):\n \n self.env = env\n self.learning_rate = learning_rate\n self.gamma = gamma\n self.epsilon = 0.999\n self.experience_replay = experience_replay\n self.device = 'cuda' if torch.cuda.is_available() else 'cpu'\n self.model = model.to(self.device)\n self.target_model = target_model.to(self.device)\n self.optimizer = optimizer\n self.loss_function = loss_function\n\n @staticmethod\n def scaling_rewards(rewards, interval_max=1, interval_min=-1):\n '''\n Scaling reward's range to (interval_min, interval_max)\n '''\n m = (interval_max - interval_min) / (rewards.max() - rewards.min())\n b = interval_min - m * rewards.min()\n return m * rewards + b\n \n @staticmethod\n def epsilon_greedy_policy(q_value, epsilon): \n '''\n when random number greater than epsilon, choose action from q value else explosion.\n '''\n if(np.random.randn() > epsilon):\n _action = torch.argmax(q_value)\n else:\n _action = np.random.randint(0, 4)\n return _action\n\n def get_action(self, state):\n\n state = torch.FloatTensor(state).float().unsqueeze(0).to(self.device)\n qvals = self.model(state)\n \n # choose action from policy\n action = DQNAgent.epsilon_greedy_policy(qvals, self.epsilon)\n\n return action\n\n def compute_loss(self, batch):\n states, actions, rewards, next_states, dones = batch\n states = torch.FloatTensor(states).to(self.device)\n actions = torch.LongTensor(actions).to(self.device)\n rewards = torch.FloatTensor(rewards).to(self.device)\n\n rewards = DQNAgent.scaling_rewards(rewards)\n next_states = torch.FloatTensor(next_states).to(self.device)\n dones = torch.FloatTensor(dones)\n\n # get current q-value from main model.\n curr_Q = self.model(states)\n predict = curr_Q.gather(dim=1, index = actions.long().unsqueeze(dim=1)).squeeze() \n \n with torch.no_grad(): \n # get next q-value from target model.\n next_Q = self.target_model(next_states)\n \n max_next_Q = torch.max(next_Q, dim=1)[0]\n expected_Q = rewards + self.gamma * max_next_Q\n loss = self.loss_function(predict, expected_Q.detach())\n \n return loss\n\n def save_checkpoint(self, epoch, PATH='./checkpoint'):\n save_path = PATH + os.sep + f'ep-{epoch}-checkpoint.pk'\n checkpoint_dict = {\n 'epoch': epoch,\n 'model_state_dict': self.model.state_dict(),\n 'target_model_state_dict': self.model.state_dict(),\n 'optimizer_state_dict': self.optimizer.state_dict()\n }\n\n torch.save(checkpoint_dict, save_path)\n\n def load_checkpoint(self, checkpoint_path):\n\n checkpoint = torch.load(checkpoint_path)\n self.model.load_state_dict(checkpoint['model_state_dict'])\n self.target_model.load_state_dict(checkpoint['target_model_state_dict'])\n self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n\n def update(self, batch_size):\n\n batch = self.experience_replay.sample(batch_size)\n loss = self.compute_loss(batch)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()" ]
[ [ "torch.LongTensor", "torch.max", "torch.load", "torch.argmax", "numpy.random.randn", "torch.FloatTensor", "torch.cuda.is_available", "numpy.random.randint", "torch.no_grad", "torch.save" ] ]
rubind/qhy_imaging
[ "c742467b9f74801c590420b4acd3137a26f97666" ]
[ "compute_linearity.py" ]
[ "import glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.io import fits\nimport tqdm\n\nxs = []\nys = []\n\nfor fl in tqdm.tqdm(glob.glob(\"img*fits\")):\n f = fits.open(fl)\n dat = f[0].data\n exptime = f[0].header[\"EXPTIME\"]\n #exptime = np.around(exptime*1000)/1000.\n\n in_ap = []\n out_ap = []\n\n\n print(exptime)\n for i in range(4500, 5000):\n for j in range(2500, 3000):\n dist2 = (i - 4744)**2 + (j - 2765)**2\n if dist2 < 30**2:\n in_ap.append(dat[j,i])\n elif dist2 < 45**2:\n out_ap.append(dat[j,i])\n \n f.close()\n\n print(exptime, np.median(in_ap), np.median(out_ap))\n\n plt.plot(exptime, (np.mean(in_ap) - np.mean(out_ap))/exptime, '.', color = 'b')\n xs.append(exptime)\n ys.append((np.mean(in_ap) - np.mean(out_ap))/exptime)\n \nplt.xscale('log')\nplt.xlabel(\"Exposure Time (s)\")\nplt.ylabel(\"Background-Subtracted Average LED (ADU/second)\")\nplt.savefig(\"counts_vs_time.pdf\")\nplt.close()\n\nxs = np.array(xs)\nys = np.array(ys)\n\ninds = np.argsort(xs)\nxs = xs[inds]\nys = ys[inds]\n\nf = open(\"linearity.txt\", 'w')\nfor i in range(len(xs)):\n f.write(str(xs[i]) + \" \" + str(ys[i]) + '\\n')\nf.close()\n" ]
[ [ "numpy.median", "matplotlib.pyplot.savefig", "numpy.mean", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.close", "numpy.argsort", "matplotlib.pyplot.xscale", "numpy.array", "matplotlib.pyplot.ylabel" ] ]
fquirin/larynx
[ "bc586b60f11dc2c228e07a47736e7a54597f0ad1" ]
[ "larynx/hifi_gan.py" ]
[ "import logging\nimport typing\n\nimport numpy as np\nimport onnxruntime\n\nfrom .audio import audio_float_to_int16, inverse, transform\nfrom .constants import SettingsType, VocoderModel, VocoderModelConfig\n\n_LOGGER = logging.getLogger(\"hifi_gan\")\n\n# -----------------------------------------------------------------------------\n\n\nclass HiFiGanVocoder(VocoderModel):\n def __init__(self, config: VocoderModelConfig):\n super(HiFiGanVocoder, self).__init__(config)\n self.config = config\n\n # Load model\n if config.model_path.is_file():\n # Model path is a file\n generator_path = config.model_path\n else:\n # Model path is a directory\n generator_path = config.model_path / \"generator.onnx\"\n\n _LOGGER.debug(\"Loading HiFi-GAN model from %s\", generator_path)\n self.generator = onnxruntime.InferenceSession(\n str(generator_path), sess_options=config.session_options\n )\n\n self.mel_channels = 80\n\n # Initialize denoiser\n self.denoiser_strength = config.denoiser_strength\n self.bias_spec: typing.Optional[np.ndarray] = None\n\n if self.denoiser_strength > 0:\n self.maybe_init_denoiser()\n\n def mels_to_audio(\n self, mels: np.ndarray, settings: typing.Optional[SettingsType] = None\n ) -> np.ndarray:\n \"\"\"Convert mel spectrograms to WAV audio\"\"\"\n audio = self.generator.run(None, {\"mel\": mels})[0].squeeze(0)\n\n denoiser_strength = self.denoiser_strength\n if settings:\n denoiser_strength = float(\n settings.get(\"denoiser_strength\", denoiser_strength)\n )\n\n if denoiser_strength > 0:\n self.maybe_init_denoiser()\n _LOGGER.debug(\"Running denoiser (strength=%s)\", denoiser_strength)\n audio = self.denoise(audio, denoiser_strength)\n\n audio_norm = audio_float_to_int16(audio)\n return audio_norm.squeeze(0)\n\n def denoise(self, audio: np.ndarray, denoiser_strength: float) -> np.ndarray:\n assert self.bias_spec is not None\n\n audio_spec, audio_angles = transform(audio)\n audio_spec_denoised = audio_spec - (self.bias_spec * denoiser_strength)\n audio_spec_denoised = np.clip(audio_spec_denoised, a_min=0.0, a_max=None)\n audio_denoised = inverse(audio_spec_denoised, audio_angles)\n\n return audio_denoised\n\n def maybe_init_denoiser(self):\n if self.bias_spec is None:\n _LOGGER.debug(\"Initializing denoiser\")\n mel_zeros = np.zeros(shape=(1, self.mel_channels, 88), dtype=np.float32)\n bias_audio = self.generator.run(None, {\"mel\": mel_zeros})[0].squeeze(0)\n bias_spec, _ = transform(bias_audio)\n\n self.bias_spec = bias_spec[:, :, 0][:, :, None]\n" ]
[ [ "numpy.zeros", "numpy.clip" ] ]
rouault/s100py
[ "1a12839b35fe85748283d2a7202257c029e09efc" ]
[ "tests/s104/s104_test.py" ]
[ "from collections import namedtuple\nimport pytest\n\nimport os\n\nimport datetime\nimport numpy\nimport h5py\n\nfrom s100py import s104\n\npath_to_current_file = os.path.realpath(__file__)\ncurrent_directory = os.path.dirname(path_to_current_file)\npath_to_s104file = os.path.join(current_directory, \"test_s104.h5\")\n\n\ndef h5py_string_comp(h5py_val, cmp_str):\n # h5py <3.0 returns a string, >3.0 returns bytes\n return h5py_val in (cmp_str, bytes(cmp_str, \"utf-8\"))\n\n\nInputData = namedtuple(\n 'InputData',\n ['height_001',\n 'trend_001',\n 'height_002',\n 'trend_002',\n 'grid_properties',\n 'metadata',\n 'datetime_value',\n 'data_coding_format',\n 'update_meta',\n 'expected_chunks',\n 'expected_groupf'])\n\n\[email protected]\ndef input_data():\n height_001 = numpy.array([[ 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.37,\n 0.45, 0.44, 0.48, 0. , 0. , 0. , 0. , 0. , 0.44,\n 0.43, 0.45, 0.36, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35], [ 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.37, 0.37, 0.42, 0.46, 0.48, 0.49, 0. , 0. , 0.45,\n 0.45, 0.38, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35,\n 0.35, 0.35]])\n\n trend_001 = numpy.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3]])\n\n height_002 = numpy.array([[ 0.1 , 0.1 , 0.1 , 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 , 0.1 , 0.1 , 0.1 ,\n 0.1 , 0.1 , 0.1 , 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 , 0.1 , 0.1 , 0.1 ,\n 0.1 , 0.1 , 0.1 , 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 , 0.1 , 0.1 , 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.16,\n 0.23, 0.22, 0.26, 0. , 0. , 0. , 0. , 0. , 0.24,\n 0.23, 0.25, 0.15, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14,\n 0.14, 0.14, 0.14, 0.14, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14,\n 0.14, 0.14], [ 0.1 , 0.1 , 0.1 , 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 , 0.1 , 0.1 , 0.1 ,\n 0.1 , 0.1 , 0.1 , 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 , 0.1 , 0.1 , 0.1 ,\n 0.1 , 0.1 , 0.1 , 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 , 0.1 , 0.1 , 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,\n 0.11, 0.11, 0.11, 0.11, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,\n 0.12, 0.12, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.15, 0.15, 0.2 , 0.24, 0.25, 0.26, 0. , 0. , 0.25,\n 0.24, 0.17, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14,\n 0.14, 0.14, 0.14, 0.14, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,\n 0.13, 0.13, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14,\n 0.14, 0.14]])\n\n trend_002 = numpy.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1]])\n\n grid_properties = {\n 'maxx': 139.1660,\n 'minx': 139.1932,\n 'miny': 4.806799,\n 'maxy': 9.593201,\n 'cellsize_x': 0.013597488,\n 'cellsize_y': 0.013595581,\n 'nx': 2,\n 'ny': 353\n }\n\n metadata = {\n 'horizontalCRS': 3855,\n 'metadata': 'MD_s104_test.XML',\n 'geographicIdentifier': 'Palau',\n 'waterLevelHeightUncertainty': -1.0,\n 'verticalUncertainty': -1.0,\n 'horizontalPositionUncertainty': -1.0,\n 'timeUncertainty': -1.0,\n 'waterLevelTrendThreshold': 0.02,\n 'verticalCS': 6499,\n 'verticalCoordinateBase': 2,\n 'verticalDatumReference': 2,\n 'verticalDatum': 1027,\n 'commonPointRule': 4,\n 'interpolationType': 10,\n 'typeOfWaterLevelData': 5,\n 'methodWaterLevelProduct': 'ADCIRC_Hydrodynamic_Model_Forecasts',\n 'datetimeOfFirstRecord': '2020-09-26T16:00:00'\n\n }\n\n datetime_value = datetime.datetime(2020, 9, 26, 15, 0, 0)\n\n data_coding_format = 2\n\n update_meta = {\n 'dateTimeOfLastRecord': '2020-09-26T17:00:00',\n 'numberOfGroups': 2,\n 'numberOfTimes': 2,\n 'timeRecordInterval': 3600,\n 'num_instances': 1\n }\n\n expected_chunks = '2,353'\n\n expected_groupf = numpy.array([\n ('waterLevelHeight', 'Water level height', 'meters', '-9999', 'H5T_FLOAT', '-99.99', '99.99', 'closedInterval'),\n ('waterLevelTrend', 'Water level trend', '', '0', 'H5T_ENUM', '1', '3', 'closedInterval'),\n ('waterLevelTime', 'Water level time', 'DateTime', '', 'H5T_C_S1', '19000101T000000Z', '21500101T000000Z', 'closedInterval')],\n dtype=[('code', 'O'), ('name', 'O'), ('uom.name', 'O'), ('fillValue', 'O'), ('datatype', 'O'), ('lower', 'O'), ('upper', 'O'), ('closure', 'O')])\n\n return InputData(height_001, trend_001, height_002, trend_002, grid_properties, metadata, datetime_value, data_coding_format, update_meta, expected_chunks, expected_groupf)\n\n\ndef test_create_s104_dcf2(input_data):\n data_file = s104.utils.create_s104(path_to_s104file)\n\n s104.utils.add_metadata(input_data.metadata, data_file)\n s104.utils.add_data_from_arrays(input_data.height_001, input_data.trend_001, data_file, input_data.grid_properties,\n input_data.datetime_value, input_data.data_coding_format)\n s104.utils.add_data_from_arrays(input_data.height_002, input_data.trend_002, data_file, input_data.grid_properties,\n input_data.datetime_value, input_data.data_coding_format)\n s104.utils.update_metadata(data_file, input_data.grid_properties, input_data.update_meta)\n\n s104.utils.write_data_file(data_file)\n\n assert os.path.isfile(path_to_s104file)\n h5_file = h5py.File(path_to_s104file, \"r\")\n\n assert 'Group_F/WaterLevel' in h5_file\n assert 'Group_F/featureCode' in h5_file\n assert 'WaterLevel/WaterLevel.01/uncertainty' in h5_file\n assert 'WaterLevel/axisNames' in h5_file\n assert h5_file['Group_F/WaterLevel'].attrs['chunking'] == input_data.expected_chunks\n assert numpy.allclose(h5_file['WaterLevel/WaterLevel.01/Group_001/values']['waterLevelHeight'],\n input_data.height_001)\n assert numpy.allclose(h5_file['WaterLevel/WaterLevel.01/Group_001/values']['waterLevelTrend'],\n input_data.trend_001)\n assert numpy.allclose(h5_file['WaterLevel/WaterLevel.01/Group_002/values']['waterLevelHeight'],\n input_data.height_002)\n assert numpy.allclose(h5_file['WaterLevel/WaterLevel.01/Group_002/values']['waterLevelTrend'],\n input_data.trend_002)\n assert h5_file['WaterLevel/WaterLevel.01/'].attrs['numPointsLongitudinal'] == input_data.height_001.shape[0]\n assert h5_file['WaterLevel/WaterLevel.01/'].attrs['numPointsLatitudinal'] == input_data.height_001.shape[1]\n\n assert all([h5py_string_comp(actual, expected) for actual, expected in zip(h5_file['Group_F/WaterLevel'][()][0],\n input_data.expected_groupf[0])])\n assert all([h5py_string_comp(actual, expected) for actual, expected in zip(h5_file['Group_F/WaterLevel'][()][1],\n input_data.expected_groupf[1])])\n assert all([h5py_string_comp(actual, expected) for actual, expected in zip(h5_file['Group_F/WaterLevel'][()][2],\n input_data.expected_groupf[2])])\n" ]
[ [ "numpy.array", "numpy.allclose" ] ]
obeychoi0120/Yolov5-GradCAM
[ "3f46c1f1daf64e0da782214667172cde4ab9dd35" ]
[ "yolov5/models/tf.py" ]
[ "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nTensorFlow, Keras and TFLite versions of YOLOv5\nAuthored by https://github.com/zldrobit in PR https://github.com/ultralytics/yolov5/pull/1127\n\nUsage:\n $ python models/tf.py --weights yolov5s.pt\n\nExport:\n $ python path/to/export.py --weights yolov5s.pt --include saved_model pb tflite tfjs\n\"\"\"\n\nimport argparse\nimport logging\nimport sys\nfrom copy import deepcopy\nfrom pathlib import Path\n\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[1] # YOLOv5 root directory\nif str(ROOT) not in sys.path:\n sys.path.append(str(ROOT)) # add ROOT to PATH\n# ROOT = ROOT.relative_to(Path.cwd()) # relative\n\nimport numpy as np\nimport tensorflow as tf\nimport torch\nimport torch.nn as nn\nfrom tensorflow import keras\n\nfrom models.common import Bottleneck, BottleneckCSP, Concat, Conv, C3, DWConv, Focus, SPP, SPPF, autopad\nfrom models.experimental import CrossConv, MixConv2d, attempt_load\nfrom models.yolo import Detect\nfrom utils.general import make_divisible, print_args, set_logging\nfrom utils.activations import SiLU\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass TFBN(keras.layers.Layer):\n # TensorFlow BatchNormalization wrapper\n def __init__(self, w=None):\n super(TFBN, self).__init__()\n self.bn = keras.layers.BatchNormalization(\n beta_initializer=keras.initializers.Constant(w.bias.numpy()),\n gamma_initializer=keras.initializers.Constant(w.weight.numpy()),\n moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()),\n moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()),\n epsilon=w.eps)\n\n def call(self, inputs):\n return self.bn(inputs)\n\n\nclass TFPad(keras.layers.Layer):\n def __init__(self, pad):\n super(TFPad, self).__init__()\n self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]])\n\n def call(self, inputs):\n return tf.pad(inputs, self.pad, mode='constant', constant_values=0)\n\n\nclass TFConv(keras.layers.Layer):\n # Standard convolution\n def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):\n # ch_in, ch_out, weights, kernel, stride, padding, groups\n super(TFConv, self).__init__()\n assert g == 1, \"TF v2.2 Conv2D does not support 'groups' argument\"\n assert isinstance(k, int), \"Convolution with multiple kernels are not allowed.\"\n # TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding)\n # see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch\n\n conv = keras.layers.Conv2D(\n c2, k, s, 'SAME' if s == 1 else 'VALID', use_bias=False if hasattr(w, 'bn') else True,\n kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),\n bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy()))\n self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])\n self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity\n\n # YOLOv5 activations\n if isinstance(w.act, nn.LeakyReLU):\n self.act = (lambda x: keras.activations.relu(x, alpha=0.1)) if act else tf.identity\n elif isinstance(w.act, nn.Hardswish):\n self.act = (lambda x: x * tf.nn.relu6(x + 3) * 0.166666667) if act else tf.identity\n elif isinstance(w.act, (nn.SiLU, SiLU)):\n self.act = (lambda x: keras.activations.swish(x)) if act else tf.identity\n else:\n raise Exception(f'no matching TensorFlow activation found for {w.act}')\n\n def call(self, inputs):\n return self.act(self.bn(self.conv(inputs)))\n\n\nclass TFFocus(keras.layers.Layer):\n # Focus wh information into c-space\n def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):\n # ch_in, ch_out, kernel, stride, padding, groups\n super(TFFocus, self).__init__()\n self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv)\n\n def call(self, inputs): # x(b,w,h,c) -> y(b,w/2,h/2,4c)\n # inputs = inputs / 255. # normalize 0-255 to 0-1\n return self.conv(tf.concat([inputs[:, ::2, ::2, :],\n inputs[:, 1::2, ::2, :],\n inputs[:, ::2, 1::2, :],\n inputs[:, 1::2, 1::2, :]], 3))\n\n\nclass TFBottleneck(keras.layers.Layer):\n # Standard bottleneck\n def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None): # ch_in, ch_out, shortcut, groups, expansion\n super(TFBottleneck, self).__init__()\n c_ = int(c2 * e) # hidden channels\n self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)\n self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2)\n self.add = shortcut and c1 == c2\n\n def call(self, inputs):\n return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))\n\n\nclass TFConv2d(keras.layers.Layer):\n # Substitution for PyTorch nn.Conv2D\n def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None):\n super(TFConv2d, self).__init__()\n assert g == 1, \"TF v2.2 Conv2D does not support 'groups' argument\"\n self.conv = keras.layers.Conv2D(\n c2, k, s, 'VALID', use_bias=bias,\n kernel_initializer=keras.initializers.Constant(w.weight.permute(2, 3, 1, 0).numpy()),\n bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None, )\n\n def call(self, inputs):\n return self.conv(inputs)\n\n\nclass TFBottleneckCSP(keras.layers.Layer):\n # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks\n def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):\n # ch_in, ch_out, number, shortcut, groups, expansion\n super(TFBottleneckCSP, self).__init__()\n c_ = int(c2 * e) # hidden channels\n self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)\n self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2)\n self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3)\n self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4)\n self.bn = TFBN(w.bn)\n self.act = lambda x: keras.activations.relu(x, alpha=0.1)\n self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])\n\n def call(self, inputs):\n y1 = self.cv3(self.m(self.cv1(inputs)))\n y2 = self.cv2(inputs)\n return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3))))\n\n\nclass TFC3(keras.layers.Layer):\n # CSP Bottleneck with 3 convolutions\n def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):\n # ch_in, ch_out, number, shortcut, groups, expansion\n super(TFC3, self).__init__()\n c_ = int(c2 * e) # hidden channels\n self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)\n self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)\n self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)\n self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])\n\n def call(self, inputs):\n return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))\n\n\nclass TFSPP(keras.layers.Layer):\n # Spatial pyramid pooling layer used in YOLOv3-SPP\n def __init__(self, c1, c2, k=(5, 9, 13), w=None):\n super(TFSPP, self).__init__()\n c_ = c1 // 2 # hidden channels\n self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)\n self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2)\n self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding='SAME') for x in k]\n\n def call(self, inputs):\n x = self.cv1(inputs)\n return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3))\n\n\nclass TFSPPF(keras.layers.Layer):\n # Spatial pyramid pooling-Fast layer\n def __init__(self, c1, c2, k=5, w=None):\n super(TFSPPF, self).__init__()\n c_ = c1 // 2 # hidden channels\n self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)\n self.cv2 = TFConv(c_ * 4, c2, 1, 1, w=w.cv2)\n self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding='SAME')\n\n def call(self, inputs):\n x = self.cv1(inputs)\n y1 = self.m(x)\n y2 = self.m(y1)\n return self.cv2(tf.concat([x, y1, y2, self.m(y2)], 3))\n\n\nclass TFDetect(keras.layers.Layer):\n def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None): # detection layer\n super(TFDetect, self).__init__()\n self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32)\n self.nc = nc # number of classes\n self.no = nc + 5 # number of outputs per anchor\n self.nl = len(anchors) # number of detection layers\n self.na = len(anchors[0]) // 2 # number of anchors\n self.grid = [tf.zeros(1)] * self.nl # init grid\n self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32)\n self.anchor_grid = tf.reshape(self.anchors * tf.reshape(self.stride, [self.nl, 1, 1]),\n [self.nl, 1, -1, 1, 2])\n self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)]\n self.training = False # set to False after building model\n self.imgsz = imgsz\n for i in range(self.nl):\n ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]\n self.grid[i] = self._make_grid(nx, ny)\n\n def call(self, inputs):\n z = [] # inference output\n x = []\n for i in range(self.nl):\n x.append(self.m[i](inputs[i]))\n # x(bs,20,20,255) to x(bs,3,20,20,85)\n ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]\n x[i] = tf.transpose(tf.reshape(x[i], [-1, ny * nx, self.na, self.no]), [0, 2, 1, 3])\n\n if not self.training: # inference\n y = tf.sigmoid(x[i])\n xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy\n wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]\n # Normalize xywh to 0-1 to reduce calibration error\n xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)\n wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)\n y = tf.concat([xy, wh, y[..., 4:]], -1)\n z.append(tf.reshape(y, [-1, 3 * ny * nx, self.no]))\n\n return x if self.training else (tf.concat(z, 1), x)\n\n @staticmethod\n def _make_grid(nx=20, ny=20):\n # yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])\n # return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()\n xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny))\n return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32)\n\n\nclass TFUpsample(keras.layers.Layer):\n def __init__(self, size, scale_factor, mode, w=None): # warning: all arguments needed including 'w'\n super(TFUpsample, self).__init__()\n assert scale_factor == 2, \"scale_factor must be 2\"\n self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * 2, x.shape[2] * 2), method=mode)\n # self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode)\n # with default arguments: align_corners=False, half_pixel_centers=False\n # self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x,\n # size=(x.shape[1] * 2, x.shape[2] * 2))\n\n def call(self, inputs):\n return self.upsample(inputs)\n\n\nclass TFConcat(keras.layers.Layer):\n def __init__(self, dimension=1, w=None):\n super(TFConcat, self).__init__()\n assert dimension == 1, \"convert only NCHW to NHWC concat\"\n self.d = 3\n\n def call(self, inputs):\n return tf.concat(inputs, self.d)\n\n\ndef parse_model(d, ch, model, imgsz): # model_dict, input_channels(3)\n LOGGER.info('\\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))\n anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']\n na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors\n no = na * (nc + 5) # number of outputs = anchors * (classes + 5)\n\n layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out\n for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args\n m_str = m\n m = eval(m) if isinstance(m, str) else m # eval strings\n for j, a in enumerate(args):\n try:\n args[j] = eval(a) if isinstance(a, str) else a # eval strings\n except NameError:\n pass\n\n n = max(round(n * gd), 1) if n > 1 else n # depth gain\n if m in [nn.Conv2d, Conv, Bottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3]:\n c1, c2 = ch[f], args[0]\n c2 = make_divisible(c2 * gw, 8) if c2 != no else c2\n\n args = [c1, c2, *args[1:]]\n if m in [BottleneckCSP, C3]:\n args.insert(2, n)\n n = 1\n elif m is nn.BatchNorm2d:\n args = [ch[f]]\n elif m is Concat:\n c2 = sum([ch[-1 if x == -1 else x + 1] for x in f])\n elif m is Detect:\n args.append([ch[x + 1] for x in f])\n if isinstance(args[1], int): # number of anchors\n args[1] = [list(range(args[1] * 2))] * len(f)\n args.append(imgsz)\n else:\n c2 = ch[f]\n\n tf_m = eval('TF' + m_str.replace('nn.', ''))\n m_ = keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)]) if n > 1 \\\n else tf_m(*args, w=model.model[i]) # module\n\n torch_m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module\n t = str(m)[8:-2].replace('__main__.', '') # module type\n np = sum([x.numel() for x in torch_m_.parameters()]) # number params\n m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params\n LOGGER.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print\n save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist\n layers.append(m_)\n ch.append(c2)\n return keras.Sequential(layers), sorted(save)\n\n\nclass TFModel:\n def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, model=None, imgsz=(640, 640)): # model, channels, classes\n super(TFModel, self).__init__()\n if isinstance(cfg, dict):\n self.yaml = cfg # model dict\n else: # is *.yaml\n import yaml # for torch hub\n self.yaml_file = Path(cfg).name\n with open(cfg) as f:\n self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict\n\n # Define model\n if nc and nc != self.yaml['nc']:\n print('Overriding %s nc=%g with nc=%g' % (cfg, self.yaml['nc'], nc))\n self.yaml['nc'] = nc # override yaml value\n self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz)\n\n def predict(self, inputs, tf_nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45,\n conf_thres=0.25):\n y = [] # outputs\n x = inputs\n for i, m in enumerate(self.model.layers):\n if m.f != -1: # if not from previous layer\n x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers\n\n x = m(x) # run\n y.append(x if m.i in self.savelist else None) # save output\n\n # Add TensorFlow NMS\n if tf_nms:\n boxes = self._xywh2xyxy(x[0][..., :4])\n probs = x[0][:, :, 4:5]\n classes = x[0][:, :, 5:]\n scores = probs * classes\n if agnostic_nms:\n nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres)\n return nms, x[1]\n else:\n boxes = tf.expand_dims(boxes, 2)\n nms = tf.image.combined_non_max_suppression(\n boxes, scores, topk_per_class, topk_all, iou_thres, conf_thres, clip_boxes=False)\n return nms, x[1]\n\n return x[0] # output only first tensor [1,6300,85] = [xywh, conf, class0, class1, ...]\n # x = x[0][0] # [x(1,6300,85), ...] to x(6300,85)\n # xywh = x[..., :4] # x(6300,4) boxes\n # conf = x[..., 4:5] # x(6300,1) confidences\n # cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1)) # x(6300,1) classes\n # return tf.concat([conf, cls, xywh], 1)\n\n @staticmethod\n def _xywh2xyxy(xywh):\n # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1)\n return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1)\n\n\nclass AgnosticNMS(keras.layers.Layer):\n # TF Agnostic NMS\n def call(self, input, topk_all, iou_thres, conf_thres):\n # wrap map_fn to avoid TypeSpec related error https://stackoverflow.com/a/65809989/3036450\n return tf.map_fn(lambda x: self._nms(x, topk_all, iou_thres, conf_thres), input,\n fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32),\n name='agnostic_nms')\n\n @staticmethod\n def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25): # agnostic NMS\n boxes, classes, scores = x\n class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32)\n scores_inp = tf.reduce_max(scores, -1)\n selected_inds = tf.image.non_max_suppression(\n boxes, scores_inp, max_output_size=topk_all, iou_threshold=iou_thres, score_threshold=conf_thres)\n selected_boxes = tf.gather(boxes, selected_inds)\n padded_boxes = tf.pad(selected_boxes,\n paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]],\n mode=\"CONSTANT\", constant_values=0.0)\n selected_scores = tf.gather(scores_inp, selected_inds)\n padded_scores = tf.pad(selected_scores,\n paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],\n mode=\"CONSTANT\", constant_values=-1.0)\n selected_classes = tf.gather(class_inds, selected_inds)\n padded_classes = tf.pad(selected_classes,\n paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],\n mode=\"CONSTANT\", constant_values=-1.0)\n valid_detections = tf.shape(selected_inds)[0]\n return padded_boxes, padded_scores, padded_classes, valid_detections\n\n\ndef representative_dataset_gen(dataset, ncalib=100):\n # Representative dataset generator for use with converter.representative_dataset, returns a generator of np arrays\n for n, (path, img, im0s, vid_cap) in enumerate(dataset):\n input = np.transpose(img, [1, 2, 0])\n input = np.expand_dims(input, axis=0).astype(np.float32)\n input /= 255.0\n yield [input]\n if n >= ncalib:\n break\n\n\ndef run(weights=ROOT / 'yolov5s.pt', # weights path\n imgsz=(640, 640), # inference size h,w\n batch_size=1, # batch size\n dynamic=False, # dynamic batch size\n ):\n # PyTorch model\n im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image\n model = attempt_load(weights, map_location=torch.device('cpu'), inplace=True, fuse=False)\n y = model(im) # inference\n model.info()\n\n # TensorFlow model\n im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image\n tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)\n y = tf_model.predict(im) # inference\n\n # Keras model\n im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)\n keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im))\n keras_model.summary()\n\n\ndef parse_opt():\n parser = argparse.ArgumentParser()\n parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')\n parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')\n parser.add_argument('--batch-size', type=int, default=1, help='batch size')\n parser.add_argument('--dynamic', action='store_true', help='dynamic batch size')\n opt = parser.parse_args()\n opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand\n print_args(FILE.stem, opt)\n return opt\n\n\ndef main(opt):\n set_logging()\n run(**vars(opt))\n\n\nif __name__ == \"__main__\":\n opt = parse_opt()\n main(opt)\n" ]
[ [ "tensorflow.concat", "tensorflow.zeros", "torch.zeros", "tensorflow.image.non_max_suppression", "tensorflow.stack", "tensorflow.keras.activations.swish", "tensorflow.keras.Sequential", "tensorflow.pad", "torch.device", "tensorflow.image.combined_non_max_suppression", "tensorflow.keras.Input", "tensorflow.keras.activations.relu", "tensorflow.gather", "tensorflow.argmax", "tensorflow.shape", "tensorflow.split", "tensorflow.reduce_max", "tensorflow.constant", "tensorflow.nn.relu6", "tensorflow.range", "tensorflow.reshape", "tensorflow.sigmoid", "tensorflow.keras.layers.MaxPool2D", "tensorflow.expand_dims", "tensorflow.image.resize" ] ]
samrullo/deep-learning-from-scratch-3
[ "47f17a9d25c8d40ac635fde7a0e3aa3937ce5ac0", "47f17a9d25c8d40ac635fde7a0e3aa3937ce5ac0" ]
[ "practice/steps/step_18_enable_backprop_context.py", "practice/steps/step_02_00.py" ]
[ "\"\"\"\nhere we introduce technics to save memory\nFor instance in neural networks often we are only interested\nin the gradients of parameters and input variables only\nthe gradients of intermediary variables can be thrown away\nto make room in the memory\n\"\"\"\nimport weakref\nimport numpy as np\nimport contextlib\n\n\[email protected]\ndef using_config(name, value):\n old_value = getattr(Config, name)\n setattr(Config, name, value)\n try:\n yield\n finally:\n setattr(Config, name, old_value)\n\n\ndef no_grad():\n return using_config('enable_backprop', False)\n\n\nclass Config:\n enable_backprop = True\n\n\ndef as_array(data):\n if np.isscalar(data):\n return np.array(data)\n else:\n return data\n\n\nclass Variable:\n def __init__(self, data):\n if not isinstance(data, np.ndarray):\n raise TypeError(f\"{type(data)} type is not supported\")\n self.data = data\n self.grad = None\n self.creator = None\n self.generation = 0\n\n def set_creator(self, creator_func):\n self.creator = creator_func\n self.generation = self.creator.generation + 1\n\n def backward(self, retain_grad=False):\n if self.grad is None:\n self.grad = np.ones_like(self.data)\n\n funcs = []\n seen_set = set()\n\n def add_func(f):\n if f not in seen_set:\n funcs.append(f)\n seen_set.add(f)\n funcs.sort(key=lambda _func: _func.generation)\n\n add_func(self.creator)\n while funcs:\n f = funcs.pop()\n inputs, outputs = f.inputs, f.outputs\n gys = [out().grad for out in outputs]\n gxs = f.backward(*gys)\n if not isinstance(gxs, tuple):\n gxs = (gxs,)\n for x, gx in zip(inputs, gxs):\n if x.grad is None:\n x.grad = gx\n else:\n x.grad = x.grad + gx\n if x.creator is not None:\n add_func(x.creator)\n # if retain_grad is not True, throw away grads of all variables ahead of this one\n if not retain_grad:\n for output in outputs:\n output().grad = None\n\n\nclass Function:\n def __call__(self, *inputs):\n xs = [x.data for x in inputs]\n\n ys = self.forward(*xs)\n if not isinstance(ys, tuple):\n ys = (ys,)\n outputs = [Variable(as_array(y)) for y in ys]\n\n if Config.enable_backprop:\n self.generation = max([x.generation for x in inputs])\n for output in outputs:\n output.set_creator(self)\n\n self.inputs = inputs\n self.outputs = [weakref.ref(output) for output in outputs]\n return outputs if len(outputs) > 1 else outputs[0]\n\n def forward(self, *xs):\n raise NotImplementedError()\n\n def backward(self, *y_grads):\n raise NotImplementedError()\n\n\nclass Add(Function):\n def forward(self, x0, x1):\n return x0 + x1\n\n def backward(self, *y_grads):\n gy, = y_grads\n return gy, gy\n\n\ndef add(x0, x1):\n return Add()(x0, x1)\n\n\nclass Square(Function):\n def forward(self, x):\n return x ** 2\n\n def backward(self, *y_grads):\n gy, = y_grads\n x, = self.inputs\n return gy * 2 * x.data\n\n\ndef square(x):\n return Square()(x)\n\n\nif __name__ == \"__main__\":\n x = Variable(np.ones((100, 100, 100)))\n y = square(square(square(x)))\n y.backward()\n print(f\"x.grad : {x.grad[0:5, 0:5, 0:5]}\")\n\n with no_grad():\n x = Variable(np.ones((100, 100, 100)))\n y = square(square(square(x)))\n print(f\"y.data : {y.data[0:5, 0:5, 0:5]}\")\n", "import numpy as np\nfrom practice.steps.step_01 import Variable\n\n\nclass Function:\n def __call__(self, input):\n x = input.data\n y = x ** 2\n output = Variable(y)\n return output\n\n\nif __name__ == \"__main__\":\n import logging\n\n logging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)s: %(message)s [in %(pathname)s %(lineno)s]')\n my_var = Variable(np.array(7))\n my_func = Function()\n my_out = my_func(my_var)\n logging.info(f\"my output of the function is : {my_out.data}\")\n" ]
[ [ "numpy.array", "numpy.ones_like", "numpy.isscalar", "numpy.ones" ], [ "numpy.array" ] ]
finkbeiner-lab/GEDI-ORDER
[ "d1e9266ba3fccc1df26a348f89fd160599e7a9f5" ]
[ "deprecated/transfer/store_viz_stacks.py" ]
[ "import os\nimport platform\n\nfrom imageio import imread, imwrite\nimport numpy as np\nimport pandas as pd\n\nfrom deprecated.transfer.grads import Grads\nfrom deprecated.transfer.grad_ops import GradOps\nimport glob\nimport param_gedi as param\nfrom pympler import asizeof\n\n\nos_type = platform.system()\nif os_type == 'Linux':\n prefix = '/mnt/finkbeinerlab'\nif os_type == 'Darwin':\n prefix = '/Volumes/data'\n\n\ndef mem(obj, name):\n m = asizeof.asizeof(obj)\n print(name, m)\n\n\ndef batches_from_fold(source_fold, dead_fold, live_fold, batch_size, parser=lambda x: x):\n # check_files = check_output(['find {}'.format(os.path.join(source_fold, '*.tif'))], shell=True).decode().split()\n check_files = glob.glob(os.path.join(source_fold, '*.tif'))\n\n files = []\n lbls = []\n for file in check_files:\n fn = file.split('/')[-1]\n cur_lbl = [0] * 2\n if os.path.exists(os.path.join(dead_fold, fn)):\n cur_lbl[0] += 1\n if os.path.exists(os.path.join(live_fold, fn)):\n cur_lbl[1] += 1\n\n if cur_lbl[0] != cur_lbl[1]:\n files.append(file)\n lbls.append(cur_lbl)\n else:\n print('Couldn\\'t find label for image at {}'.format(file))\n\n for i in range(0, len(files), batch_size):\n print('batch from fold 1')\n _files = files[i:i + batch_size]\n _names = list(map(lambda file: '.'.join(file.split('/')[-1].split('.')[:-1]), _files))\n _lbls = lbls[i:i + batch_size]\n _imgs = list(map(lambda file: parser(imread(file)), _files))\n print('batch from fold 2')\n\n yield tuple(map(np.array, (_imgs, _lbls, _names)))\n\n\n# @profile\ndef batches_from_fold_no_labels(source_fold, dead_fold, live_fold, batch_size, parser=lambda x: x):\n # check_files = check_output(['find {}'.format(os.path.join(source_fold, '**', '*.tif'))], shell=True).decode().split()\n check_files = glob.glob(os.path.join(source_fold, '*.tif'))\n files = []\n lbls = []\n for file in check_files:\n # fn = file.split('/')[-1]\n cur_lbl = [0, 1]\n # if os.path.exists(os.path.join(dead_fold, fn)):\n # cur_lbl[0] += 1\n # if os.path.exists(os.path.join(live_fold, fn)):\n # cur_lbl[1] += 1\n\n if cur_lbl[0] != cur_lbl[1]:\n files.append(file)\n lbls.append(cur_lbl)\n else:\n print('Couldn\\'t find label for image at {}'.format(file))\n\n for i in range(0, len(files), batch_size):\n _files = files[i:i + batch_size]\n _names = list(map(lambda file: '.'.join(file.split('/')[-1].split('.')[:-1]), _files))\n _lbls = lbls[i:i + batch_size]\n _imgs = list(map(lambda file: parser(imread(file)), _files))\n\n yield tuple(map(np.array, (_imgs, _lbls, _names)))\n\n\n# @profile\ndef save_batch(g, imgs, lbls, base_path, conf_mat_paths, fnames=None, makepaths=True, layer_name='block5_conv3'):\n \"\"\"\n Method computes the Guided GradCAM visualization of an image for both classes; saves these representations as a three-channel (image;correct_label_grad;wrong_label_grad) tif image\n\n Args:\n g: Grads object\n imgs: image data tensor\n lbls: array of one-hots\n base_path: directory within which to write\n conf_mat_paths: confusion matrix subpath names (first dimension corresponds to label, second corresponds to correctness of prediction)\n fnames: optional list of filenames to save with; defaults to integer index of each base image\n makepaths: whether to build the directory tree specified by base_path/conf_mat_paths\n layer_name: name of layer to differentiate wrt. for GradCAM\n\n Returns: list of the indices of images which were written\n\n \"\"\"\n\n ggcam_gen = g.gen_ggcam_stacks(imgs, lbls, layer_name, ret_preds=True)\n writes = []\n res_dict = {'filename': [], 'label': [], 'prediction': []}\n for i, lbl in enumerate(lbls):\n g_stack, preds = next(ggcam_gen)\n\n path_stem = os.path.join(base_path, conf_mat_paths[np.argmax(lbl)][\n np.argmax(preds)]) # using confusion matrix path at [true label (0/1)][predicted correctly? (0/1)]\n filename = '{}.tif'.format(i if fnames is None else fnames[i])\n\n if makepaths:\n os.makedirs(path_stem, exist_ok=True)\n try:\n imwrite(os.path.join(path_stem, filename), g_stack)\n writes.append(i)\n if fnames is not None:\n res_dict['filename'].append(fnames[i])\n res_dict['label'].append(np.argmax(lbl))\n res_dict['prediction'].append(np.argmax(preds))\n except:\n print('Could not write image at index {}'.format(i))\n mem(ggcam_gen, 'ggcam')\n mem(g_stack, 'g_strack')\n mem(writes, 'writes')\n mem(res_dict, 'res_dict')\n mem(imgs, 'imgs2')\n return res_dict\n\n\n# @profile\ndef process_fold(g, source_fold, dead_fold, live_fold, dest_path, conf_mat_paths, batch_size=10, parser=lambda x: x,\n layer_name='block5_conv3', has_labels=True):\n pred_df = pd.DataFrame({'filename': [], 'label': [], 'prediction': []})\n if has_labels:\n batch_gen = batches_from_fold(source_fold, dead_fold, live_fold, batch_size=batch_size, parser=parser)\n else:\n batch_gen = batches_from_fold_no_labels(source_fold, dead_fold, live_fold, batch_size=batch_size, parser=parser)\n for imgs, lbls, names in batch_gen:\n print('save batch, {}'.format(names[0]))\n d = save_batch(g, imgs, lbls, dest_path, conf_mat_paths, fnames=names, makepaths=True, layer_name=layer_name)\n print('df')\n df = pd.DataFrame(d)\n if not has_labels:\n df.labels = -1\n print('pred df')\n\n pred_df = pd.concat((pred_df, df), ignore_index=True)\n mem(batch_gen, 'batch_gen')\n mem(pred_df, 'pred_df')\n mem(imgs, 'imgs')\n mem(lbls, 'lbls')\n mem(d, 'd')\n mem(g, 'g')\n\n print('to csv')\n\n pred_df.to_csv(os.path.join(dest_path, dest_path.split('/')[-1] + '.csv'))\n return 0\n\n\np = param.Param()\n\n# g = Grads(prefix + '/robodata/Gennadi/tf_to_k_v2.h5')\n# timestamp = 'vgg16_2020_04_20_15_05_47' #2drop, 2bn\n# timestamp = 'vgg16_2020_04_21_10_08_00' #1drop, 2bn\n# import_path = os.path.join(p.models_dir, \"{}.h5\".format(timestamp))\nimport_path = os.path.join(p.base_gedi_dropout_bn)\nguidedbool = True\n\ng = Grads(import_path, guidedbool=guidedbool)\ngops = GradOps(vgg_normalize=True)\n\n# main_fold = prefix + '/robodata/GalaxyTEMP/BSMachineLearning_TestCuration'\n# main_fold = prefix +'/robodata/JeremyTEMP/GalaxyTEMP/GXYTMPShijieHEK/ObjectCrops'\nmain_fold = prefix + '/robodata/Gennadi/batches16bit/10'\n# source_fold_prefix = os.path.join(main_fold, 'batches')\nsource_fold_prefix = os.path.join(main_fold)\n# dead_fold = os.path.join(main_fold, 'master', 'DEAD')\n# live_fold = os.path.join(main_fold, 'master', 'LIVE')\n# dest_path_prefix = prefix + '/robodata/Gennadi/batches_grads2'\n# conf_mat_paths = [['dead_true', 'dead_false'], ['live_false', 'live_true']]\n\n\n# main_fold = prefix + '/robodata/Josh/Gradcam/ObjectCrops'\n# main_fold = prefix + '/robodata/JeremyTEMP/GEDICNNpaper/HumanIncorrectCNNcorrectImages'\n# '/robodata/JaslinTemp/GalaxyData/LINCS-diMNs/LINCS072017RGEDI-A/Galaxy-wholeplate/Galaxy/CroppedImages/LINCS072017RGEDI-A'\n# main_fold = prefix + '/robodata/JeremyTEMP/GalaxyTEMP/ShortTimeGEDI/ObjectCrops'\n# source_fold_prefix = main_fold\ndead_fold = os.path.join(main_fold, 'master', 'DEAD')\nlive_fold = os.path.join(main_fold, 'master', 'LIVE')\n# dest_path_prefix = prefix + '/robodata/Josh/Gradcam/results/batches_grads_2020-5-18'\n# dest_path_prefix = prefix + '/robodata/Josh/Gradcam/results/GXYTMPShijieHEK'\ndest_path_prefix = prefix + '/robodata/Josh/Gradcam/results/batches16bit'\nconf_mat_paths = [['dead_true', 'dead_false'], ['live_false', 'live_true']]\n\nbatch_size = 10\nparser = lambda img: gops.img_parse(img)\nlayer_name = 'block5_conv3'\nLABELLED = False\n# layer_name = 'block1_conv1'\n\n# # Example usage\n# process_fold(g, source_fold, dead_fold, live_fold, dest_path, conf_mat_paths, batch_size=batch_size, parser=parser, layer_name=layer_name)\nsubdirs = glob.glob(os.path.join(main_fold, '**'))\nwells = [w.split('/')[-1] for w in subdirs]\n# wells = [w for w in wells if w not in ['E5', 'B2', 'H10', 'B8', 'F7', 'H9', 'H3', 'C1', 'B10', 'E11', 'G4', 'F12', 'G12', 'D11', 'G9', 'G3', 'C10']]\n# wells = ['HumanIncorrectDeadNoInnerSoma', 'HumanIncorrectLiveNoInnerSoma', 'HumanCorrectLiveInnerSoma']\n# for well in map(str, range(3, 20 + 1)):\nfor well in ['10']:\n print('Running {}'.format(well))\n cur_source_fold = os.path.join(source_fold_prefix, well)\n cur_dest_path = os.path.join(dest_path_prefix, well)\n\n process_fold(g, cur_source_fold, dead_fold, live_fold, cur_dest_path, conf_mat_paths, batch_size=batch_size,\n parser=parser, layer_name=layer_name, has_labels=LABELLED)\n" ]
[ [ "pandas.concat", "numpy.argmax", "pandas.DataFrame" ] ]
cosmo-epfl/sklearn-cosmo
[ "1bf9bcfbc38e7881e06496cf780085b3575aaec4" ]
[ "skcosmo/_selection.py" ]
[ "\"\"\"\nSequential selection\n\"\"\"\n\nimport numbers\nimport warnings\nfrom abc import abstractmethod\n\nimport numpy as np\nimport scipy\nfrom scipy.linalg import eigh\nfrom scipy.sparse.linalg import eigsh\nfrom sklearn.base import (\n BaseEstimator,\n MetaEstimatorMixin,\n)\nfrom sklearn.feature_selection._base import SelectorMixin\nfrom sklearn.utils import (\n check_array,\n check_random_state,\n safe_mask,\n)\nfrom sklearn.utils._tags import _safe_tags\nfrom sklearn.utils.validation import check_is_fitted\n\nfrom .utils import (\n X_orthogonalizer,\n Y_feature_orthogonalizer,\n Y_sample_orthogonalizer,\n get_progress_bar,\n no_progress_bar,\n pcovr_covariance,\n pcovr_kernel,\n)\n\n\nclass GreedySelector(SelectorMixin, MetaEstimatorMixin, BaseEstimator):\n \"\"\"\n\n Transformer that adds, via greedy forward selection,\n features or samples to form a subset. At each stage, the model scores each\n feature or sample (without an estimator) and chooses that with the maximum score.\n\n Parameters\n ----------\n\n selection_type : str, {'feature', 'sample'}\n whether to choose a subset of columns ('feature') or rows ('sample').\n Stored in :py:attr:`self._axis_name` (as text) and :py:attr:`self._axis`\n (as 0 or 1 for 'sample' or 'feature', respectively).\n\n n_to_select : int or float, default=None\n The number of selections to make. If `None`, half of the features or samples are\n selected. If integer, the parameter is the absolute number of selections\n to make. If float between 0 and 1, it is the fraction of the total dataset to\n select. Stored in :py:attr:`self.n_to_select`.\n\n score_threshold : float, default=None\n Threshold for the score. If `None` selection will continue until the\n n_to_select is chosen. Otherwise will stop when the score falls below the threshold.\n Stored in :py:attr:`self.score_threshold`.\n\n score_threshold_type : str, default=\"absolute\"\n How to interpret the ``score_threshold``. When \"absolute\", the score used by\n the selector is compared to the threshold directly. When \"relative\", at each iteration,\n the score used by the selector is compared proportionally to the score of the first\n selection, i.e. the selector quits when ``current_score / first_score < threshold``.\n Stored in :py:attr:`self.score_threshold_type`.\n\n progress_bar: bool, default=False\n option to use `tqdm <https://tqdm.github.io/>`_\n progress bar to monitor selections. Stored in :py:attr:`self.report_progress`.\n\n full : bool, default=False\n In the case that all non-redundant selections are exhausted, choose\n randomly from the remaining features. Stored in :py:attr:`self.full`.\n\n random_state: int or RandomState instance, default=0\n\n Attributes\n ----------\n n_selected_ : int\n Counter tracking the number of selections that have been made\n X_selected_ : ndarray,\n Matrix containing the selected samples or features, for use in fitting\n y_selected_ : ndarray,\n In sample selection, the matrix containing the selected targets, for use in fitting\n\n\n \"\"\"\n\n def __init__(\n self,\n selection_type,\n n_to_select=None,\n score_threshold=None,\n score_threshold_type=\"absolute\",\n progress_bar=False,\n full=False,\n random_state=0,\n ):\n\n self.selection_type = selection_type\n self.n_to_select = n_to_select\n self.score_threshold = score_threshold\n self.score_threshold_type = score_threshold_type\n self._first_score = None\n if self.score_threshold_type not in [\"relative\", \"absolute\"]:\n raise ValueError(\n \"invalid score_threshold_type, expected one of 'relative' or 'absolute'\"\n )\n\n self.full = full\n self.progress_bar = progress_bar\n self.random_state = random_state\n\n def fit(self, X, y=None, warm_start=False):\n \"\"\"Learn the features to select.\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Training vectors.\n y : ndarray of shape (n_samples,), default=None\n Target values.\n warm_start : bool\n Whether the fit should continue after having already\n run, after increasing n_to_select.\n Assumes it is called with the same X and y\n\n Returns\n -------\n self : object\n \"\"\"\n tags = self._get_tags()\n\n if self.selection_type == \"feature\":\n self._axis = 1\n elif self.selection_type == \"sample\":\n self._axis = 0\n else:\n raise ValueError(\"Only feature and sample selection supported.\")\n\n if self.full and self.score_threshold is not None:\n raise ValueError(\n \"You cannot specify both `score_threshold` and `full=True`.\"\n )\n\n if self.progress_bar is True:\n self.report_progress = get_progress_bar()\n elif self.progress_bar is False:\n self.report_progress = no_progress_bar\n\n params = dict(\n accept_sparse=\"csc\",\n force_all_finite=not tags.get(\"allow_nan\", True),\n )\n if self._axis == 1:\n params[\"ensure_min_features\"] = 2\n else:\n params[\"ensure_min_samples\"] = 2\n\n if y is not None:\n params[\"multi_output\"] = True\n X, y = self._validate_data(X, y, **params)\n\n if len(y.shape) == 1:\n # force y to have multi_output 2D format even when it's 1D, since\n # many functions, most notably PCov routines, assume an array storage\n # format, most notably to compute (y @ y.T)\n y = y.reshape((len(y), 1))\n else:\n X = check_array(X, **params)\n\n n_to_select_from = X.shape[self._axis]\n\n error_msg = (\n \"n_to_select must be either None, an \"\n f\"integer in [1, n_{self.selection_type}s - 1] \"\n \"representing the absolute \"\n f\"number of {self.selection_type}s, or a float in (0, 1] \"\n f\"representing a percentage of {self.selection_type}s to \"\n f\"select. Got {self.n_to_select} {self.selection_type}s and \"\n f\"an input with {n_to_select_from} {self.selection_type}.\"\n )\n\n if self.n_to_select is None:\n n_iterations = n_to_select_from // 2\n elif isinstance(self.n_to_select, numbers.Integral):\n if not 0 < self.n_to_select < n_to_select_from:\n raise ValueError(error_msg)\n n_iterations = self.n_to_select\n elif isinstance(self.n_to_select, numbers.Real):\n if not 0 < self.n_to_select <= 1:\n raise ValueError(error_msg)\n n_iterations = int(n_to_select_from * self.n_to_select)\n else:\n raise ValueError(error_msg)\n\n if warm_start:\n if not hasattr(self, \"n_selected_\") or getattr(self, \"n_selected_\") == 0:\n raise ValueError(\n \"Cannot fit with warm_start=True without having been previously initialized\"\n )\n self._continue_greedy_search(X, y, n_iterations)\n else:\n self._init_greedy_search(X, y, n_iterations)\n\n n_iterations -= self.n_selected_\n\n for n in self.report_progress(range(n_iterations)):\n\n new_idx = self._get_best_new_selection(self.score, X, y)\n if new_idx is not None:\n self._update_post_selection(X, y, new_idx)\n else:\n warnings.warn(\n f\"Score threshold of {self.score_threshold} reached.\"\n f\"Terminating search at {self.n_selected_} / {self.n_to_select}.\"\n )\n self.X_selected_ = np.take(\n self.X_selected_, np.arange(self.n_selected_), axis=self._axis\n )\n\n if hasattr(self, \"y_selected_\"):\n self.y_selected_ = self.y_selected_[:n]\n\n self.selected_idx_ = self.selected_idx_[:n]\n self._postprocess(X, y)\n return self\n\n self._postprocess(X, y)\n return self\n\n def transform(self, X, y=None):\n \"\"\"Reduce X to the selected features.\n\n Parameters\n ----------\n X : ndarray of shape [n_samples, n_features]\n The input samples.\n y : ignored\n\n Returns\n -------\n X_r : ndarray\n The selected subset of the input.\n \"\"\"\n\n if len(X.shape) == 1:\n X = X.reshape(-1, 1)\n\n mask = self.get_support()\n\n # note: we use _safe_tags instead of _get_tags because this is a\n # public Mixin.\n X = self._validate_data(\n X,\n dtype=None,\n accept_sparse=\"csr\",\n force_all_finite=not _safe_tags(self, key=\"allow_nan\"),\n reset=False,\n ensure_2d=self._axis,\n )\n\n if len(mask) != X.shape[self._axis]:\n raise ValueError(\"X has a different shape than during fitting.\")\n\n if self._axis == 1:\n return X[:, safe_mask(X, mask)]\n else:\n return X[safe_mask(X, mask)]\n\n @abstractmethod\n def score(self, X, y):\n \"\"\"\n A single str or a callable to evaluate the features or samples\n that is overwritten by the subclass.\n It is assumed that the next selection is that which maximizes the score.\n\n NOTE that when using custom scorers, each scorer should return a single\n value. Metric functions returning a list/array of values can be wrapped\n into multiple scorers that return one value each.\n\n\n Parameters\n ----------\n X : ndarray of shape [n_samples, n_features]\n The input samples.\n y : ignored\n\n Returns\n -------\n score : ndarray of (n_to_select_from_)\n Scores of the given features or samples\n \"\"\"\n pass\n\n def get_support(self, indices=False, ordered=False):\n \"\"\"Get a mask, or integer index, of the subset\n\n Parameters\n ----------\n indices : bool, default=False\n If True, the return value will be an array of integers, rather\n than a bool mask.\n\n ordered : bool, default=False\n With indices, if True, the return value will be an array of integers, rather\n than a bool mask, in the order in which they were selected.\n\n Returns\n -------\n support : An index that selects the retained subset from a original vectors.\n If indices is False, this is a bool array of shape [# input],\n in which an element is True iff its corresponding feature or sample is selected\n for retention. If indices is True, this is an integer array of shape\n [# n_to_select] whose values are indices into the input vectors.\n\n \"\"\"\n check_is_fitted(self, [\"support_\", \"selected_idx_\"])\n if indices:\n if ordered:\n return self.selected_idx_\n else:\n return list(sorted(self.selected_idx_))\n else:\n return self._get_support_mask()\n\n def _init_greedy_search(self, X, y, n_to_select):\n \"\"\"Initializes the search. Prepares an array to store the selected features.\"\"\"\n\n self.n_selected_ = 0\n\n sel_shape = list(X.shape)\n sel_shape[self._axis] = n_to_select\n\n self.X_selected_ = np.zeros(sel_shape, float)\n\n if y is not None and self._axis == 0:\n self.y_selected_ = np.zeros(\n (n_to_select, y.reshape(y.shape[0], -1).shape[1]), float\n )\n self.selected_idx_ = np.zeros((n_to_select), int)\n\n def _continue_greedy_search(self, X, y, n_to_select):\n \"\"\"Continues the search. Prepares an array to store the selected features.\"\"\"\n\n n_pad = [(0, 0), (0, 0)]\n n_pad[self._axis] = (0, n_to_select - self.n_selected_)\n\n self.X_selected_ = np.pad(\n self.X_selected_,\n n_pad,\n \"constant\",\n constant_values=0.0,\n )\n\n if hasattr(self, \"y_selected_\"):\n self.y_selected_ = np.pad(\n self.y_selected_,\n n_pad,\n \"constant\",\n constant_values=0.0,\n )\n\n old_idx = self.selected_idx_.copy()\n self.selected_idx_ = np.zeros((n_to_select), int)\n self.selected_idx_[: self.n_selected_] = old_idx\n\n def _get_best_new_selection(self, scorer, X, y):\n scores = scorer(X, y)\n\n max_score_idx = np.argmax(scores)\n if self.score_threshold is not None:\n if self._first_score is None:\n self._first_score = scores[max_score_idx]\n\n if self.score_threshold_type == \"absolute\":\n if scores[max_score_idx] < self.score_threshold:\n return None\n\n if self.score_threshold_type == \"relative\":\n if scores[max_score_idx] / self._first_score < self.score_threshold:\n return None\n\n return max_score_idx\n\n def _update_post_selection(self, X, y, last_selected):\n \"\"\"\n Saves the most recently selected feature and increments the feature counter\n \"\"\"\n\n if self._axis == 1:\n self.X_selected_[:, self.n_selected_] = np.take(\n X, last_selected, axis=self._axis\n )\n else:\n self.X_selected_[self.n_selected_] = np.take(\n X, last_selected, axis=self._axis\n )\n\n if hasattr(self, \"y_selected_\"):\n self.y_selected_[self.n_selected_] = y[last_selected]\n\n self.selected_idx_[self.n_selected_] = last_selected\n self.n_selected_ += 1\n\n def _get_support_mask(self):\n \"\"\"\n Get the boolean mask indicating which subset has been selected\n\n Raises\n ------\n NotFittedError\n If the selector has not yet been fitted\n\n Returns\n -------\n support : bool ndarray of shape [# input]\n An element is True iff its corresponding feature or sample is selected for\n retention.\n \"\"\"\n check_is_fitted(self, [\"support_\"])\n return self.support_\n\n def _postprocess(self, X, y):\n \"\"\"Post-process X and / or y when selection is finished\"\"\"\n self.support_ = np.full(X.shape[self._axis], False)\n self.support_[self.selected_idx_] = True\n\n def _more_tags(self):\n return {\n \"requires_y\": False,\n }\n\n\nclass _CUR(GreedySelector):\n \"\"\"Transformer that performs Greedy Selection by choosing features\n which maximize the magnitude of the right or left singular vectors, consistent with\n classic CUR matrix decomposition.\n\n **WARNING**: This base class should never be directly instantiated.\n Instead, use :py:class:`skcosmo.feature_selection.CUR` and\n :py:class:`skcosmo.sample_selection.CUR`,\n which have the same constructor signature.\n\n Parameters\n ----------\n recompute_every : int\n number of steps after which to recompute the pi score\n defaults to 1, if 0 no re-computation is done\n\n k : int\n number of eigenvectors to compute the importance score with, defaults to 1\n\n tolerance: float\n threshold below which scores will be considered 0, defaults to 1E-12\n\n\n Attributes\n ----------\n\n X_current_ : ndarray (n_samples, n_features)\n The original matrix orthogonalized by previous selections\n\n \"\"\"\n\n def __init__(\n self,\n selection_type,\n recompute_every=1,\n k=1,\n tolerance=1e-12,\n n_to_select=None,\n score_threshold=None,\n score_threshold_type=\"absolute\",\n progress_bar=False,\n full=False,\n random_state=0,\n ):\n\n self.k = k\n self.tolerance = tolerance\n self.recompute_every = recompute_every\n\n super().__init__(\n selection_type=selection_type,\n n_to_select=n_to_select,\n score_threshold=score_threshold,\n score_threshold_type=score_threshold_type,\n progress_bar=progress_bar,\n full=full,\n random_state=random_state,\n )\n\n def score(self, X, y=None):\n r\"\"\"\n Returns the importance score of the given samples or features.\n\n NOTE: This function does not compute the importance score each time it\n is called, in order to avoid unnecessary computations. This is done\n by :py:func:`self._compute_pi`.\n\n Parameters\n ----------\n X : ndarray of shape [n_samples, n_features]\n The input samples.\n\n y : ignored\n\n Returns\n -------\n score : ndarray of (n_to_select_from_)\n :math:`\\pi` importance for the given samples or features\n\n \"\"\"\n\n return self.pi_\n\n def _init_greedy_search(self, X, y, n_to_select):\n \"\"\"\n Initializes the search. Prepares an array to store the selected\n features and computes their initial importance score.\n \"\"\"\n\n self.X_current_ = X.copy()\n self.pi_ = self._compute_pi(self.X_current_)\n\n super()._init_greedy_search(X, y, n_to_select)\n\n def _continue_greedy_search(self, X, y, n_to_select):\n \"\"\"\n Continues the search. Prepares an array to store the selected\n features, orthogonalizes the features by those already selected,\n and computes their initial importance.\n \"\"\"\n\n for c in self.selected_idx_:\n\n if self.recompute_every != 0 and (\n np.linalg.norm(np.take(self.X_current_, [c], axis=self._axis))\n > self.tolerance\n ):\n self._orthogonalize(last_selected=c)\n\n self.pi_ = self._compute_pi(self.X_current_)\n\n super()._continue_greedy_search(X, y, n_to_select)\n\n def _compute_pi(self, X, y=None):\n \"\"\"\n For feature selection, the importance score :math:`\\\\pi` is the sum over\n the squares of the first :math:`k` components of the right singular vectors\n\n .. math::\n\n \\\\pi_j =\n \\\\sum_i^k \\\\left(\\\\mathbf{U}_\\\\mathbf{C}\\\\right)_{ij}^2.\n\n where :math:`\\\\mathbf{C} = \\\\mathbf{X}^T\\\\mathbf{X}`.\n\n For sample selection, the importance score :math:`\\\\pi` is the sum over\n the squares of the first :math:`k` components of the right singular vectors\n\n .. math::\n\n \\\\pi_j =\n \\\\sum_i^k \\\\left(\\\\mathbf{U}_\\\\mathbf{K}\\\\right)_{ij}^2.\n\n where :math:`\\\\mathbf{K} = \\\\mathbf{X}\\\\mathbf{X}^T`.\n\n Parameters\n ----------\n X : ndarray of shape [n_samples, n_features]\n The input samples.\n\n y : ignored\n\n Returns\n -------\n pi : ndarray of (n_to_select_from_)\n :math:`\\\\pi` importance for the given samples or features\n \"\"\"\n\n if self._axis == 0:\n U, _, _ = scipy.sparse.linalg.svds(X, k=self.k, return_singular_vectors=\"u\")\n U = np.real(U)\n new_pi = (U[:, : self.k] ** 2.0).sum(axis=1)\n else:\n _, _, Vt = scipy.sparse.linalg.svds(\n X, k=self.k, return_singular_vectors=\"vh\"\n )\n new_pi = (np.real(Vt) ** 2.0).sum(axis=0)\n\n return new_pi\n\n def _update_post_selection(self, X, y, last_selected):\n \"\"\"\n Saves the most recently selected feature, increments the feature counter,\n and, if the CUR is iterative (if recompute_every>0), orthogonalizes the remaining features by\n the most recently selected.\n \"\"\"\n super()._update_post_selection(X, y, last_selected)\n\n if self.recompute_every != 0:\n self._orthogonalize(last_selected)\n\n if self.n_selected_ % self.recompute_every == 0:\n self.pi_ = self._compute_pi(self.X_current_)\n\n self.pi_[last_selected] = 0.0\n\n def _orthogonalize(self, last_selected):\n\n if self._axis == 1:\n self.X_current_ = X_orthogonalizer(\n x1=self.X_current_, c=last_selected, tol=self.tolerance\n )\n else:\n self.X_current_ = X_orthogonalizer(\n x1=self.X_current_.T, c=last_selected, tol=self.tolerance\n ).T\n\n\nclass _PCovCUR(GreedySelector):\n \"\"\"Transformer that performs Greedy Selection by choosing features\n which maximize the magnitude of the right or left augmented singular vectors.\n This is done by employing the augmented kernel and covariance matrices,\n\n **WARNING**: This base class should never be directly instantiated.\n Instead, use :py:class:`skcosmo.feature_selection.PCovCUR` and\n :py:class:`skcosmo.sample_selection.PCovCUR`,\n which have the same constructor signature.\n\n Parameters\n ----------\n recompute_every : int\n number of steps after which to recompute the pi score\n defaults to 1, if 0 no re-computation is done\n\n k : int\n number of eigenvectors to compute the importance score with, defaults to 1\n\n tolerance: float\n threshold below which scores will be considered 0, defaults to 1E-12\n\n mixing: float, default=0.5\n The PCovR mixing parameter, as described in PCovR as\n :math:`{\\\\alpha}`. Stored in :py:attr:`self.mixing`.\n\n Attributes\n ----------\n\n X_current_ : ndarray (n_samples, n_features)\n The original matrix orthogonalized by previous selections\n\n y_current_ : ndarray (n_samples, n_properties)\n The targets orthogonalized by a regression on\n the previous selections.\n\n \"\"\"\n\n def __init__(\n self,\n selection_type,\n mixing=0.5,\n recompute_every=1,\n k=1,\n tolerance=1e-12,\n n_to_select=None,\n score_threshold=None,\n score_threshold_type=\"absolute\",\n progress_bar=False,\n full=False,\n random_state=0,\n ):\n self.mixing = mixing\n\n self.k = k\n self.recompute_every = recompute_every\n self.tolerance = tolerance\n\n super().__init__(\n selection_type=selection_type,\n n_to_select=n_to_select,\n score_threshold=score_threshold,\n score_threshold_type=score_threshold_type,\n progress_bar=progress_bar,\n full=full,\n random_state=random_state,\n )\n\n def score(self, X, y=None):\n \"\"\"\n Returns the importance score of the given samples or features.\n\n NOTE: This function does not compute the importance score each time it\n is called, in order to avoid unnecessary computations. This is done\n by :py:func:`self._compute_pi`.\n\n Parameters\n ----------\n X : ignored\n\n y : ignored\n\n Returns\n -------\n score : ndarray of (n_to_select_from_)\n :math:`\\\\pi` importance for the given samples or features\n\n \"\"\"\n\n return self.pi_\n\n def _init_greedy_search(self, X, y, n_to_select):\n \"\"\"\n Initializes the search. Prepares an array to store the selected\n features and computes their initial importance score.\n \"\"\"\n\n self.X_ref_ = X\n self.y_ref_ = y\n self.X_current_ = X.copy()\n if y is not None:\n self.y_current_ = y.copy()\n else:\n self.y_current_ = None\n self.pi_ = self._compute_pi(self.X_current_, self.y_current_)\n\n super()._init_greedy_search(X, y, n_to_select)\n\n def _continue_greedy_search(self, X, y, n_to_select):\n \"\"\"\n Continues the search. Prepares an array to store the selected\n features, orthogonalizes the features by those already selected,\n and computes their initial importance.\n \"\"\"\n\n for c in self.selected_idx_:\n\n if self.recompute_every != 0 and (\n np.linalg.norm(np.take(self.X_current_, [c], axis=self._axis))\n > self.tolerance\n ):\n self._orthogonalize(last_selected=c)\n\n self.pi_ = self._compute_pi(self.X_current_, self.y_current_)\n\n super()._continue_greedy_search(X, y, n_to_select)\n\n def _update_post_selection(self, X, y, last_selected):\n \"\"\"\n Saves the most recently selected feature, increments the feature counter,\n and, if the CUR is iterative (if recompute_every>0), orthogonalizes the remaining features by\n the most recently selected.\n \"\"\"\n super()._update_post_selection(X, y, last_selected)\n\n if self.recompute_every != 0:\n self._orthogonalize(last_selected)\n\n if self.n_selected_ % self.recompute_every == 0:\n self.pi_ = self._compute_pi(self.X_current_, self.y_current_)\n\n self.pi_[last_selected] = 0.0\n\n def _compute_pi(self, X, y=None):\n r\"\"\"\n For feature selection, the importance score :math:`\\pi` is the sum over\n the squares of the first :math:`k` components of the right singular vectors\n\n .. math::\n\n \\pi_j =\n \\sum_i^k \\left(\\mathbf{U}_\\mathbf{\\tilde{C}}\\right)_{ij}^2.\n\n where :math:`{\\mathbf{\\tilde{C}} = \\alpha \\mathbf{X}^T\\mathbf{X} +\n (1 - \\alpha)(\\mathbf{X}^T\\mathbf{X})^{-1/2}\\mathbf{X}^T\n \\mathbf{\\hat{Y}\\hat{Y}}^T\\mathbf{X}(\\mathbf{X}^T\\mathbf{X})^{-1/2}}`\n for some mixing parameter :math:`{\\alpha}`. When :math:`{\\alpha = 1}`,\n this defaults to the covariance matrix\n :math:`{\\mathbf{C} = \\mathbf{X}^T\\mathbf{X}}` used in CUR.\n\n For sample selection, the importance score :math:`\\pi` is the sum over\n the squares of the first :math:`k` components of the right singular vectors\n\n .. math::\n\n \\pi_j =\n \\sum_i^k \\left(\\mathbf{U}_\\mathbf{\\tilde{K}}\\right)_{ij}^2.\n\n where :math:`{\\mathbf{\\tilde{K}} = \\alpha \\mathbf{XX}^T +\n (1 - \\alpha)\\mathbf{\\hat{Y}\\hat{Y}}^T}` for some mixing parameter\n :math:`{\\alpha}`. When :math:`{\\alpha = 1}`, this defaults to the Gram\n matrix :math:`{\\mathbf{K} = \\mathbf{X}\\mathbf{X}^T}`.\n\n Parameters\n ----------\n X : ndarray of shape [n_samples, n_features]\n The input samples.\n\n y : ignored\n\n Returns\n -------\n pi : ndarray of (n_to_select_from_)\n :math:`\\pi` importance for the given samples or features\n \"\"\"\n\n if self._axis == 0:\n pcovr_distance = pcovr_kernel(\n self.mixing,\n X,\n y,\n )\n else:\n pcovr_distance = pcovr_covariance(\n self.mixing,\n X,\n y,\n rcond=1e-12,\n rank=None,\n )\n\n if self.k < pcovr_distance.shape[0] - 1:\n v, U = eigsh(pcovr_distance, k=self.k, tol=1e-12)\n else:\n v, U = eigh(pcovr_distance)\n U = U[:, np.flip(np.argsort(v))]\n pi = (np.real(U)[:, : self.k] ** 2.0).sum(axis=1)\n\n return pi\n\n def _orthogonalize(self, last_selected):\n\n if self._axis == 1:\n self.X_current_ = X_orthogonalizer(\n x1=self.X_current_, c=last_selected, tol=self.tolerance\n )\n else:\n self.X_current_ = X_orthogonalizer(\n x1=self.X_current_.T, c=last_selected, tol=self.tolerance\n ).T\n if self.y_current_ is not None:\n if self._axis == 1:\n self.y_current_ = Y_feature_orthogonalizer(\n self.y_current_, X=self.X_selected_, tol=self.tolerance\n )\n else:\n self.y_current_ = Y_sample_orthogonalizer(\n self.y_ref_,\n self.X_ref_,\n y_ref=self.y_selected_[: self.n_selected_],\n X_ref=self.X_selected_[: self.n_selected_],\n tol=self.tolerance,\n )\n\n\nclass _FPS(GreedySelector):\n \"\"\"\n Transformer that performs Greedy Selection using Farthest Point Sampling.\n\n **WARNING**: This base class should never be directly instantiated.\n Instead, use :py:class:`skcosmo.feature_selection.FPS` and\n :py:class:`skcosmo.sample_selection.FPS`,\n which have the same constructor signature.\n\n Parameters\n ----------\n\n initialize: int, list of int, or 'random', default=0\n Index of the first selection(s). If 'random', picks a random\n value when fit starts. Stored in :py:attr:`self.initialize`.\n\n\n \"\"\"\n\n def __init__(\n self,\n selection_type,\n initialize=0,\n n_to_select=None,\n score_threshold=None,\n score_threshold_type=\"absolute\",\n progress_bar=False,\n full=False,\n random_state=0,\n ):\n self.initialize = initialize\n\n super().__init__(\n selection_type=selection_type,\n n_to_select=n_to_select,\n score_threshold=score_threshold,\n score_threshold_type=score_threshold_type,\n progress_bar=progress_bar,\n full=full,\n random_state=random_state,\n )\n\n def score(self, X, y=None):\n \"\"\"\n Returns the Haussdorf distances of all samples to previous selections\n\n NOTE: This function does not compute the importance score each time it\n is called, in order to avoid unnecessary computations. The haussdorf\n distance is updated in :py:func:`self._update_haussdorf`\n\n Parameters\n ----------\n X : ignored\n y : ignored\n\n Returns\n -------\n haussdorf : Haussdorf distances\n \"\"\"\n return self.haussdorf_\n\n def get_distance(self):\n \"\"\"\n\n Traditional FPS employs a column-wise Euclidean\n distance for feature selection, which can be expressed using the covariance matrix\n :math:`\\\\mathbf{C} = \\\\mathbf{X} ^ T \\\\mathbf{X}`\n\n .. math::\n \\\\operatorname{d}_c(i, j) = C_{ii} - 2 C_{ij} + C_{jj}.\n\n For sample selection, this is a row-wise Euclidean distance, which can\n be expressed in terms of the Gram matrix :math:`\\\\mathbf{K} = \\\\mathbf{X} \\\\mathbf{X} ^ T`\n\n .. math::\n \\\\operatorname{d}_r(i, j) = K_{ii} - 2 K_{ij} + K_{jj}.\n\n Returns\n -------\n\n haussdorf : ndarray of shape (`n_to_select_from_`)\n the minimum distance from each point to the set of selected\n points. once a point is selected, the distance is not updated;\n the final list will reflect the distances when selected.\n\n \"\"\"\n return self.haussdorf_\n\n def get_select_distance(self):\n \"\"\"\n\n Returns\n -------\n\n haussdorf_at_select : ndarray of shape (`n_to_select`)\n at the time of selection, the minimum distance from each\n selected point to the set of previously selected points.\n\n \"\"\"\n mask = self.get_support(indices=True, ordered=True)\n return self.haussdorf_at_select_[mask]\n\n def _init_greedy_search(self, X, y, n_to_select):\n \"\"\"\n Initializes the search. Prepares an array to store the selections,\n makes the initial selection (unless provided), and\n computes the starting haussdorf distances.\n \"\"\"\n\n super()._init_greedy_search(X, y, n_to_select)\n\n self.norms_ = (X**2).sum(axis=abs(self._axis - 1))\n self.haussdorf_ = np.full(X.shape[self._axis], np.inf)\n self.haussdorf_at_select_ = np.full(X.shape[self._axis], np.inf)\n\n if self.initialize == \"random\":\n random_state = check_random_state(self.random_state)\n initialize = random_state.randint(X.shape[self._axis])\n self.selected_idx_[0] = initialize\n self._update_post_selection(X, y, self.selected_idx_[0])\n elif isinstance(self.initialize, numbers.Integral):\n initialize = self.initialize\n self.selected_idx_[0] = initialize\n self._update_post_selection(X, y, self.selected_idx_[0])\n elif isinstance(self.initialize, list) and all(\n [isinstance(i, numbers.Integral) for i in self.initialize]\n ):\n for i, val in enumerate(self.initialize):\n self.selected_idx_[i] = val\n self._update_post_selection(X, y, self.selected_idx_[i])\n else:\n raise ValueError(\"Invalid value of the initialize parameter\")\n\n def _update_haussdorf(self, X, y, last_selected):\n\n self.haussdorf_at_select_[last_selected] = self.haussdorf_[last_selected]\n\n # distances of all points to the new point\n if self._axis == 1:\n new_dist = (\n self.norms_ + self.norms_[last_selected] - 2 * X[:, last_selected].T @ X\n )\n else:\n new_dist = (\n self.norms_ + self.norms_[last_selected] - 2 * X[last_selected] @ X.T\n )\n\n # update in-place the Haussdorf distance list\n np.minimum(self.haussdorf_, new_dist, self.haussdorf_)\n\n def _update_post_selection(self, X, y, last_selected):\n \"\"\"\n Saves the most recent selections, increments the counter,\n and, recomputes haussdorf distances.\n \"\"\"\n self._update_haussdorf(X, y, last_selected)\n super()._update_post_selection(X, y, last_selected)\n\n\nclass _PCovFPS(GreedySelector):\n \"\"\"\n Transformer that performs Greedy Selection using PCovR-weighted\n Farthest Point Sampling.\n In PCov-FPS, a modified covariance or Gram matrix\n is used to express the distances.\n\n For sample selection, this is a modified kernel matrix.\n\n Parameters\n ----------\n\n mixing: float, default=0.5\n The PCovR mixing parameter, as described in PCovR as\n :math:`{\\\\alpha}`\n\n initialize: int or 'random', default=0\n Index of the first selection. If 'random', picks a random\n value when fit starts.\n\n \"\"\"\n\n def __init__(\n self,\n selection_type,\n mixing=0.5,\n initialize=0,\n n_to_select=None,\n score_threshold=None,\n score_threshold_type=\"absolute\",\n progress_bar=False,\n full=False,\n random_state=0,\n ):\n if mixing == 1.0:\n raise ValueError(\n \"Mixing = 1.0 corresponds to traditional FPS.\"\n \"Please use the FPS class.\"\n )\n\n self.mixing = mixing\n self.initialize = initialize\n\n super().__init__(\n selection_type=selection_type,\n n_to_select=n_to_select,\n score_threshold=score_threshold,\n score_threshold_type=score_threshold_type,\n progress_bar=progress_bar,\n full=full,\n random_state=random_state,\n )\n\n def score(self, X, y=None):\n \"\"\"\n Returns the Haussdorf distances of all samples to previous selections\n\n NOTE: This function does not compute the importance score each time it\n is called, in order to avoid unnecessary computations. The haussdorf\n distance is updated in :py:func:`self._update_haussdorf`\n\n Parameters\n ----------\n X : ignored\n y : ignored\n\n Returns\n -------\n haussdorf : Haussdorf distances\n \"\"\"\n return self.haussdorf_\n\n def get_distance(self):\n \"\"\"\n\n Returns\n -------\n\n haussdorf : ndarray of shape (`n_to_select_from_`)\n the minimum distance from each point to the set of selected\n points. once a point is selected, the distance is not updated;\n the final list will reflect the distances when selected.\n\n \"\"\"\n return self.haussdorf_\n\n def get_select_distance(self):\n \"\"\"\n\n Returns\n -------\n\n haussdorf_at_select : ndarray of shape (`n_to_select`)\n at the time of selection, the minimum distance from each\n selected point to the set of previously selected points.\n\n \"\"\"\n mask = self.get_support(indices=True, ordered=True)\n return self.haussdorf_at_select_[mask]\n\n def _init_greedy_search(self, X, y, n_to_select):\n \"\"\"\n Initializes the search. Prepares an array to store the selections,\n makes the initial selection (unless provided), and\n computes the starting haussdorf distances.\n \"\"\"\n\n super()._init_greedy_search(X, y, n_to_select)\n\n if self._axis == 1:\n self.pcovr_distance_ = pcovr_covariance(mixing=self.mixing, X=X, Y=y)\n else:\n self.pcovr_distance_ = pcovr_kernel(mixing=self.mixing, X=X, Y=y)\n\n self.norms_ = np.diag(self.pcovr_distance_)\n\n if self.initialize == \"random\":\n random_state = check_random_state(self.random_state)\n initialize = random_state.randint(X.shape[self._axis])\n elif isinstance(self.initialize, numbers.Integral):\n initialize = self.initialize\n else:\n raise ValueError(\"Invalid value of the initialize parameter\")\n\n self.selected_idx_[0] = initialize\n self.haussdorf_ = np.full(X.shape[self._axis], np.inf)\n self.haussdorf_at_select_ = np.full(X.shape[self._axis], np.inf)\n self._update_post_selection(X, y, self.selected_idx_[0])\n\n def _update_haussdorf(self, X, y, last_selected):\n\n self.haussdorf_at_select_[last_selected] = self.haussdorf_[last_selected]\n\n # distances of all points to the new point\n new_dist = (\n self.norms_\n + self.norms_[last_selected]\n - 2 * np.take(self.pcovr_distance_, last_selected, axis=self._axis)\n )\n\n # update in-place the Haussdorf distance list\n np.minimum(self.haussdorf_, new_dist, self.haussdorf_)\n\n def _update_post_selection(self, X, y, last_selected):\n \"\"\"\n Saves the most recent selections, increments the counter,\n and, recomputes haussdorf distances.\n \"\"\"\n self._update_haussdorf(X, y, last_selected)\n super()._update_post_selection(X, y, last_selected)\n\n def _more_tags(self):\n \"\"\"\n Pass that this method requires a target vector\n \"\"\"\n return {\n \"requires_y\": True,\n }\n" ]
[ [ "numpy.diag", "sklearn.utils.check_random_state", "sklearn.utils.validation.check_is_fitted", "numpy.pad", "numpy.minimum", "numpy.take", "sklearn.utils.check_array", "numpy.arange", "sklearn.utils._tags._safe_tags", "sklearn.utils.safe_mask", "numpy.full", "scipy.sparse.linalg.svds", "scipy.linalg.eigh", "numpy.real", "numpy.argmax", "numpy.argsort", "numpy.zeros", "scipy.sparse.linalg.eigsh" ] ]
qnl/pyEPR
[ "3b3d2a1d534bc8f965b9b1f4fafc3a46fe75a5fa" ]
[ "pyEPR/ansys.py" ]
[ "'''\npyEPR.ansys\n 2014-present\n\nPurpose:\n Handles Ansys interaction and control from version 2014 onward.\n Tested most extensively with V2016 and V2019R3.\n\n@authors:\n Originally contributed by Phil Reinhold.\n Developed further by Zlatko Minev, Zaki Leghtas, and the pyEPR team.\n For the base version of hfss.py, see https://github.com/PhilReinhold/pyHFSS\n'''\n\n# Python 2.7 and 3 compatibility\nfrom __future__ import (division, print_function)\n\nfrom typing import List\n\nimport atexit\nimport os\nimport re\nimport signal\nimport tempfile\nimport time\nimport types\nfrom collections.abc import Iterable\nfrom copy import copy\nfrom numbers import Number\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nfrom sympy.parsing import sympy_parser\nimport io\n\nfrom . import logger\n\n# Handle a few usually troublesome to import packages, which the use may not have\n# installed yet\ntry:\n import pythoncom\nexcept (ImportError, ModuleNotFoundError):\n pass\n\ntry:\n # TODO: Replace `win32com` with Linux compatible package.\n # See Ansys python files in IronPython internal.\n from win32com.client import Dispatch, CDispatch\nexcept (ImportError, ModuleNotFoundError):\n pass\n\ntry:\n from pint import UnitRegistry\n ureg = UnitRegistry()\n Q = ureg.Quantity\nexcept(ImportError, ModuleNotFoundError):\n ureg = \"Pint module not installed. Please install.\"\n\n\n##############################################################################\n###\n\nBASIS_ORDER = {\"Zero Order\": 0,\n \"First Order\": 1,\n \"Second Order\": 2,\n \"Mixed Order\": -1}\n\n# UNITS\n# LENGTH_UNIT --- HFSS UNITS\n# #Assumed default input units for ansys hfss\nLENGTH_UNIT = 'meter'\n# LENGTH_UNIT_ASSUMED --- USER UNITS\n# if a user inputs a blank number with no units in `parse_fix`,\n# we can assume the following using\nLENGTH_UNIT_ASSUMED = 'mm'\n\n\ndef simplify_arith_expr(expr):\n try:\n out = repr(sympy_parser.parse_expr(str(expr)))\n return out\n except:\n print(\"Couldn't parse\", expr)\n raise\n\n\ndef increment_name(base, existing):\n if not base in existing:\n return base\n n = 1\n def make_name(): return base + str(n)\n while make_name() in existing:\n n += 1\n return make_name()\n\n\ndef extract_value_unit(expr, units):\n \"\"\"\n :type expr: str\n :type units: str\n :return: float\n \"\"\"\n try:\n return Q(expr).to(units).magnitude\n except Exception:\n try:\n return float(expr)\n except Exception:\n return expr\n\n\ndef extract_value_dim(expr):\n \"\"\"\n type expr: str\n \"\"\"\n return str(Q(expr).dimensionality)\n\n\ndef parse_entry(entry, convert_to_unit=LENGTH_UNIT):\n '''\n Should take a list of tuple of list... of int, float or str...\n For iterables, returns lists\n '''\n if not isinstance(entry, list) and not isinstance(entry, tuple):\n return extract_value_unit(entry, convert_to_unit)\n else:\n entries = entry\n _entry = []\n for entry in entries:\n _entry.append(parse_entry(entry, convert_to_unit=convert_to_unit))\n return _entry\n\n\ndef fix_units(x, unit_assumed=None):\n '''\n Convert all numbers to string and append the assumed units if needed.\n For an itterable, returns a list\n '''\n unit_assumed = LENGTH_UNIT_ASSUMED if unit_assumed is None else unit_assumed\n if isinstance(x, str):\n # Check if there are already units defined, assume of form 2.46mm or 2.0 or 4.\n if x[-1].isdigit() or x[-1] == '.': # number\n return x + unit_assumed\n else: # units are already appleid\n return x\n\n elif isinstance(x, Number):\n return fix_units(str(x)+unit_assumed, unit_assumed=unit_assumed)\n\n elif isinstance(x, Iterable): # hasattr(x, '__iter__'):\n return [fix_units(y, unit_assumed=unit_assumed) for y in x]\n else:\n return x\n\n\ndef parse_units(x):\n '''\n Convert number, string, and lists/arrays/tuples to numbers scaled\n in HFSS units.\n\n Converts to LENGTH_UNIT = meters [HFSS UNITS]\n Assumes input units LENGTH_UNIT_ASSUMED = mm [USER UNITS]\n\n [USER UNITS] ----> [HFSS UNITS]\n '''\n return parse_entry(fix_units(x))\n\n\ndef unparse_units(x):\n '''\n Undo effect of parse_unit.\n\n Converts to LENGTH_UNIT_ASSUMED = mm [USER UNITS]\n Assumes input units LENGTH_UNIT = meters [HFSS UNITS]\n\n [HFSS UNITS] ----> [USER UNITS]\n '''\n return parse_entry(fix_units(x, unit_assumed=LENGTH_UNIT), LENGTH_UNIT_ASSUMED)\n\n\ndef parse_units_user(x):\n '''\n Convert from user assuemd units to user assumed units\n [USER UNITS] ----> [USER UNITS]\n '''\n return parse_entry(fix_units(x, LENGTH_UNIT_ASSUMED), LENGTH_UNIT_ASSUMED)\n\n\nclass VariableString(str):\n def __add__(self, other):\n return var(\"(%s) + (%s)\" % (self, other))\n\n def __radd__(self, other):\n return var(\"(%s) + (%s)\" % (other, self))\n\n def __sub__(self, other):\n return var(\"(%s) - (%s)\" % (self, other))\n\n def __rsub__(self, other):\n return var(\"(%s) - (%s)\" % (other, self))\n\n def __mul__(self, other):\n return var(\"(%s) * (%s)\" % (self, other))\n\n def __rmul__(self, other):\n return var(\"(%s) * (%s)\" % (other, self))\n\n def __div__(self, other):\n return var(\"(%s) / (%s)\" % (self, other))\n\n def __rdiv__(self, other):\n return var(\"(%s) / (%s)\" % (other, self))\n\n def __truediv__(self, other):\n return var(\"(%s) / (%s)\" % (self, other))\n\n def __rtruediv__(self, other):\n return var(\"(%s) / (%s)\" % (other, self))\n\n def __pow__(self, other):\n return var(\"(%s) ^ (%s)\" % (self, other))\n\n def __rpow__(self, other):\n return var(\"(%s) ^ (%s)\" % (other, self))\n\n def __neg__(self):\n return var(\"-(%s)\" % self)\n\n def __abs__(self):\n return var(\"abs(%s)\" % self)\n\n\ndef var(x):\n if isinstance(x, str):\n return VariableString(simplify_arith_expr(x))\n return x\n\n\n_release_fns = []\n\n\ndef _add_release_fn(fn):\n global _release_fns\n _release_fns.append(fn)\n atexit.register(fn)\n signal.signal(signal.SIGTERM, fn)\n signal.signal(signal.SIGABRT, fn)\n\n\ndef release():\n '''\n Release COM connection to HFSS.\n '''\n global _release_fns\n for fn in _release_fns:\n fn()\n time.sleep(0.1)\n\n # Note that _GetInterfaceCount is a memeber\n refcount = pythoncom._GetInterfaceCount() # pylint: disable=no-member\n\n if refcount > 0:\n print(\"Warning! %d COM references still alive\" % (refcount))\n print(\"HFSS will likely refuse to shut down\")\n\n\nclass COMWrapper(object):\n def __init__(self):\n _add_release_fn(self.release)\n\n def release(self):\n for k, v in self.__dict__.items():\n if isinstance(v, CDispatch):\n setattr(self, k, None)\n\n\nclass HfssPropertyObject(COMWrapper):\n prop_holder = None\n prop_tab = None\n prop_server = None\n\n\ndef make_str_prop(name, prop_tab=None, prop_server=None):\n return make_prop(name, prop_tab=prop_tab, prop_server=prop_server)\n\n\ndef make_int_prop(name, prop_tab=None, prop_server=None):\n return make_prop(name, prop_tab=prop_tab, prop_server=prop_server, prop_args=[\"MustBeInt:=\", True])\n\n\ndef make_float_prop(name, prop_tab=None, prop_server=None):\n return make_prop(name, prop_tab=prop_tab, prop_server=prop_server, prop_args=[\"MustBeInt:=\", False])\n\n\ndef make_prop(name, prop_tab=None, prop_server=None, prop_args=None):\n def set_prop(self, value, prop_tab=prop_tab, prop_server=prop_server, prop_args=prop_args):\n prop_tab = self.prop_tab if prop_tab is None else prop_tab\n prop_server = self.prop_server if prop_server is None else prop_server\n if isinstance(prop_tab, types.FunctionType):\n prop_tab = prop_tab(self)\n if isinstance(prop_server, types.FunctionType):\n prop_server = prop_server(self)\n if prop_args is None:\n prop_args = []\n self.prop_holder.ChangeProperty(\n [\"NAME:AllTabs\",\n [\"NAME:\"+prop_tab,\n [\"NAME:PropServers\", prop_server],\n [\"NAME:ChangedProps\",\n [\"NAME:\"+name, \"Value:=\", value] + prop_args]]])\n\n def get_prop(self, prop_tab=prop_tab, prop_server=prop_server):\n prop_tab = self.prop_tab if prop_tab is None else prop_tab\n prop_server = self.prop_server if prop_server is None else prop_server\n if isinstance(prop_tab, types.FunctionType):\n prop_tab = prop_tab(self)\n if isinstance(prop_server, types.FunctionType):\n prop_server = prop_server(self)\n return self.prop_holder.GetPropertyValue(prop_tab, prop_server, name)\n\n return property(get_prop, set_prop)\n\n\ndef set_property(prop_holder, prop_tab, prop_server, name, value, prop_args=None):\n '''\n More general non obj oriented, functionatl verison\n prop_args = [] by default\n '''\n if not isinstance(prop_server, list):\n prop_server = [prop_server]\n return prop_holder.ChangeProperty(\n [\"NAME:AllTabs\",\n [\"NAME:\"+prop_tab,\n [\"NAME:PropServers\", *prop_server],\n [\"NAME:ChangedProps\",\n [\"NAME:\"+name, \"Value:=\", value] + (prop_args or [])]]])\n\n\nclass HfssApp(COMWrapper):\n def __init__(self, ProgID='AnsoftHfss.HfssScriptInterface'):\n '''\n Connect to IDispatch-based COM object.\n Parameter is the ProgID or CLSID of the COM object.\n This is found in the regkey.\n\n Version changes for Ansys HFSS for the main object\n v2016 - 'Ansoft.ElectronicsDesktop'\n v2017 and subsequent - 'AnsoftHfss.HfssScriptInterface'\n\n '''\n super(HfssApp, self).__init__()\n self._app = Dispatch(ProgID)\n\n def get_app_desktop(self):\n return HfssDesktop(self, self._app.GetAppDesktop())\n # in v2016, there is also getApp - which can be called with HFSS\n\n\nclass HfssDesktop(COMWrapper):\n def __init__(self, app, desktop):\n \"\"\"\n :type app: HfssApp\n :type desktop: Dispatch\n \"\"\"\n super(HfssDesktop, self).__init__()\n self.parent = app\n self._desktop = desktop\n\n # ansys version, needed to check for command changes,\n # since some commands have changed over the years\n self.version = self.get_version()\n\n def close_all_windows(self):\n self._desktop.CloseAllWindows()\n\n def project_count(self):\n return self._desktop.Count()\n\n def get_active_project(self):\n return HfssProject(self, self._desktop.GetActiveProject())\n\n def get_projects(self):\n return [HfssProject(self, p) for p in self._desktop.GetProjects()]\n\n def get_project_names(self):\n return self._desktop.GetProjectList()\n\n def get_messages(self, project_name=\"\", design_name=\"\", level=0):\n \"\"\"Use: Collects the messages from a specified project and design.\n Syntax: GetMessages <ProjectName>, <DesignName>, <SeverityName>\n Return Value: A simple array of strings.\n\n Parameters:\n <ProjectName>\n Type:<string>\n Name of the project for which to collect messages.\n An incorrect project name results in no messages (design is ignored)\n An empty project name results in all messages (design is ignored)\n\n <DesignName>\n Type: <string>\n Name of the design in the named project for which to collect messages\n An incorrect design name results in no messages for the named project\n An empty design name results in all messages for the named project\n\n <SeverityName>\n Type: <integer>\n Severity is 0-3, and is tied in to info/warning/error/fatal types as follows:\n 0 is info and above\n 1 is warning and above\n 2 is error and fatal\n 3 is fatal only (rarely used)\n \"\"\"\n return self._desktop.GetMessages(project_name, design_name, level)\n\n def get_version(self):\n return self._desktop.GetVersion()\n\n def new_project(self):\n return HfssProject(self, self._desktop.NewProject())\n\n def open_project(self, path):\n ''' returns error if already open '''\n return HfssProject(self, self._desktop.OpenProject(path))\n\n def set_active_project(self, name):\n self._desktop.SetActiveProject(name)\n\n @property\n def project_directory(self):\n return self._desktop.GetProjectDirectory()\n\n @project_directory.setter\n def project_directory(self, path):\n self._desktop.SetProjectDirectory(path)\n\n @property\n def library_directory(self):\n return self._desktop.GetLibraryDirectory()\n\n @library_directory.setter\n def library_directory(self, path):\n self._desktop.SetLibraryDirectory(path)\n\n @property\n def temp_directory(self):\n return self._desktop.GetTempDirectory()\n\n @temp_directory.setter\n def temp_directory(self, path):\n self._desktop.SetTempDirectory(path)\n\n\nclass HfssProject(COMWrapper):\n def __init__(self, desktop, project):\n \"\"\"\n :type desktop: HfssDesktop\n :type project: Dispatch\n \"\"\"\n super(HfssProject, self).__init__()\n self.parent = desktop\n self._project = project\n #self.name = project.GetName()\n self._ansys_version = self.parent.version\n\n def close(self):\n self._project.Close()\n\n def make_active(self):\n self.parent.set_active_project(self.name)\n\n def get_designs(self):\n return [HfssDesign(self, d) for d in self._project.GetDesigns()]\n\n def save(self, path=None):\n if path is None:\n self._project.Save()\n else:\n self._project.SaveAs(path, True)\n\n def simulate_all(self):\n self._project.SimulateAll()\n\n def import_dataset(self, path):\n self._project.ImportDataset(path)\n\n def rename_design(self, design, rename):\n if design in self.get_designs():\n design.rename_design(design.name, rename)\n else:\n raise ValueError('%s design does not exist' % design.name)\n\n def duplicate_design(self, target, source):\n src_design = self.get_design(source)\n return src_design.duplicate(name=target)\n\n def get_variable_names(self):\n return [VariableString(s) for s in self._project.GetVariables()]\n\n def get_variables(self):\n \"\"\" Returns the project variables only, which start with $. These are global variables. \"\"\"\n return {VariableString(s): self.get_variable_value(s) for s in self._project.GetVariables()}\n\n def get_variable_value(self, name):\n return self._project.GetVariableValue(name)\n\n def create_variable(self, name, value):\n self._project.ChangeProperty(\n [\"NAME:AllTabs\",\n [\"NAME:ProjectVariableTab\",\n [\"NAME:PropServers\", \"ProjectVariables\"],\n [\"Name:NewProps\",\n [\"NAME:\" + name,\n \"PropType:=\", \"VariableProp\",\n \"UserDef:=\", True,\n \"Value:=\", value]]]])\n\n def set_variable(self, name, value):\n if name not in self._project.GetVariables():\n self.create_variable(name, value)\n else:\n self._project.SetVariableValue(name, value)\n return VariableString(name)\n\n def get_path(self):\n if self._project:\n return self._project.GetPath()\n else:\n raise Exception('''Error: HFSS Project does not have a path.\n Either there is no HFSS project open, or it is not saved.''')\n\n def new_design(self, name, type):\n name = increment_name(name, [d.GetName()\n for d in self._project.GetDesigns()])\n return HfssDesign(self, self._project.InsertDesign(\"HFSS\", name, type, \"\"))\n\n def get_design(self, name):\n return HfssDesign(self, self._project.GetDesign(name))\n\n def get_active_design(self):\n d = self._project.GetActiveDesign()\n if d is None:\n raise EnvironmentError(\"No Design Active\")\n return HfssDesign(self, d)\n\n def new_dm_design(self, name):\n return self.new_design(name, \"DrivenModal\")\n\n def new_em_design(self, name):\n return self.new_design(name, \"Eigenmode\")\n\n @property # v2016\n def name(self):\n return self._project.GetName()\n\n\nclass HfssDesign(COMWrapper):\n\n def __init__(self, project, design):\n super(HfssDesign, self).__init__()\n self.parent = project\n self._design = design\n self.name = design.GetName()\n self._ansys_version = self.parent._ansys_version\n\n try:\n # This funciton does not exist if the desing is not HFSS\n self.solution_type = design.GetSolutionType()\n except Exception as e:\n logger.debug(\n f'Exception occured at design.GetSolutionType() {e}. Assuming Q3D design')\n self.solution_type = 'Q3D'\n\n if design is None:\n return\n self._setup_module = design.GetModule(\"AnalysisSetup\")\n self._solutions = design.GetModule(\"Solutions\")\n self._fields_calc = design.GetModule(\"FieldsReporter\")\n self._output = design.GetModule(\"OutputVariable\")\n self._boundaries = design.GetModule(\"BoundarySetup\")\n self._reporter = design.GetModule(\"ReportSetup\")\n self._modeler = design.SetActiveEditor(\"3D Modeler\")\n self._optimetrics = design.GetModule(\"Optimetrics\")\n self._mesh = design.GetModule(\"MeshSetup\")\n self.modeler = HfssModeler(self, self._modeler,\n self._boundaries, self._mesh)\n self.optimetrics = Optimetrics(self)\n\n def add_message(self, message:str, severity:int=0):\n \"\"\"\n Add a message to HFSS log with severity and context to message window.\n\n Keyword Args:\n severity (int) : 0 = Informational, 1 = Warning, 2 = Error, 3 = Fatal..\n \"\"\"\n project = self.parent\n desktop = project.parent\n oDesktop = desktop._desktop\n oDesktop.AddMessage(project.name, self.name, severity, message)\n\n def rename_design(self, name):\n old_name = self._design.GetName()\n self._design.RenameDesignInstance(old_name, name)\n\n def copy_to_project(self, project):\n project.make_active()\n project._project.CopyDesign(self.name)\n project._project.Paste()\n return project.get_active_design()\n\n def duplicate(self, name=None):\n dup = self.copy_to_project(self.parent)\n if name is not None:\n dup.rename_design(name)\n return dup\n\n def get_setup_names(self):\n return self._setup_module.GetSetups()\n\n def get_setup(self, name=None):\n \"\"\"\n :rtype: HfssSetup\n \"\"\"\n setups = self.get_setup_names()\n if not setups:\n raise EnvironmentError(\" *** No Setups Present ***\")\n if name is None:\n name = setups[0]\n elif name not in setups:\n raise EnvironmentError(\n \"Setup {} not found: {}\".format(name, setups))\n\n if self.solution_type == \"Eigenmode\":\n return HfssEMSetup(self, name)\n elif self.solution_type == \"DrivenModal\":\n return HfssDMSetup(self, name)\n elif self.solution_type == \"Q3D\":\n return AnsysQ3DSetup(self, name)\n \n def create_q3d_setup(self, freq_ghz=5., name=\"Setup\", save_fields=False, enabled=True,\n max_passes=15, min_passes=2, min_converged_passes=2, percent_error=0.5,\n percent_refinement=30, auto_increase_solution_order=True, solution_order=\"High\",\n solver_type='Iterative'):\n name = increment_name(name, self.get_setup_names())\n self._setup_module.InsertSetup(\n \"Matrix\", [\n f\"NAME:{name}\",\n \"AdaptiveFreq:=\", f\"{freq_ghz}GHz\",\n \"SaveFields:=\", save_fields,\n \"Enabled:=\", enabled,\n [\n \"NAME:Cap\",\n \"MaxPass:=\", max_passes,\n \"MinPass:=\", min_passes,\n \"MinConvPass:=\", min_converged_passes,\n \"PerError:=\", percent_error,\n \"PerRefine:=\", percent_refinement,\n \"AutoIncreaseSolutionOrder:=\", auto_increase_solution_order,\n \"SolutionOrder:=\", solution_order,\n \"Solver Type:=\", solver_type\n ]\n ])\n return AnsysQ3DSetup(self, name)\n\n def create_dm_setup(self, freq_ghz=1, name=\"Setup\", max_delta_s=0.1, max_passes=10,\n min_passes=1, min_converged=1, pct_refinement=30,\n basis_order=-1):\n\n name = increment_name(name, self.get_setup_names())\n self._setup_module.InsertSetup(\n \"HfssDriven\", [\n \"NAME:\"+name,\n \"Frequency:=\", str(freq_ghz)+\"GHz\",\n \"MaxDeltaS:=\", max_delta_s,\n \"MaximumPasses:=\", max_passes,\n \"MinimumPasses:=\", min_passes,\n \"MinimumConvergedPasses:=\", min_converged,\n \"PercentRefinement:=\", pct_refinement,\n \"IsEnabled:=\", True,\n \"BasisOrder:=\", basis_order\n ])\n return HfssDMSetup(self, name)\n\n def create_em_setup(self, name=\"Setup\", min_freq_ghz=1, n_modes=1, max_delta_f=0.1,\n max_passes=10, min_passes=1, min_converged=1, pct_refinement=30,\n basis_order=-1):\n\n name = increment_name(name, self.get_setup_names())\n self._setup_module.InsertSetup(\n \"HfssEigen\", [\n \"NAME:\"+name,\n \"MinimumFrequency:=\", str(min_freq_ghz)+\"GHz\",\n \"NumModes:=\", n_modes,\n \"MaxDeltaFreq:=\", max_delta_f,\n \"ConvergeOnRealFreq:=\", True,\n \"MaximumPasses:=\", max_passes,\n \"MinimumPasses:=\", min_passes,\n \"MinimumConvergedPasses:=\", min_converged,\n \"PercentRefinement:=\", pct_refinement,\n \"IsEnabled:=\", True,\n \"BasisOrder:=\", basis_order\n ])\n return HfssEMSetup(self, name)\n\n def delete_setup(self, name):\n if name in self.get_setup_names():\n self._setup_module.DeleteSetups(name)\n\n def delete_full_variation(self, DesignVariationKey=\"All\", del_linked_data=False):\n \"\"\"\n DeleteFullVariation\n Use: Use to selectively make deletions or delete all solution data.\n Command: HFSS>Results>Clean Up Solutions...\n Syntax: DeleteFullVariation Array(<parameters>), boolean\n Parameters: All | <DataSpecifierArray>\n If, All, all data of existing variations is deleted.\n Array(<DesignVariationKey>, )\n <DesignVariationKey>\n Type: <string>\n Design variation string.\n <Boolean>\n Type: boolean\n Whether to also delete linked data.\n \"\"\"\n self._design.DeleteFullVariation(\"All\", False)\n\n def get_nominal_variation(self):\n \"\"\"\n Use: Gets the nominal variation string\n Return Value: Returns a string representing the nominal variation\n Returns string such as \"Height='0.06mm' Lj='13.5nH'\"\n \"\"\"\n return self._design.GetNominalVariation()\n\n def create_variable(self, name, value, postprocessing=False):\n if postprocessing == True:\n variableprop = \"PostProcessingVariableProp\"\n else:\n variableprop = \"VariableProp\"\n\n self._design.ChangeProperty(\n [\"NAME:AllTabs\",\n [\"NAME:LocalVariableTab\",\n [\"NAME:PropServers\", \"LocalVariables\"],\n [\"Name:NewProps\",\n [\"NAME:\" + name,\n \"PropType:=\", variableprop,\n \"UserDef:=\", True,\n \"Value:=\", value]]]])\n\n def _variation_string_to_variable_list(self, variation_string: str, for_prop_server=True):\n \"\"\"Example:\n Takes\n \"Cj='2fF' Lj='13.5nH'\"\n for for_prop_server=True into\n [['NAME:Cj', 'Value:=', '2fF'], ['NAME:Lj', 'Value:=', '13.5nH']]\n or for for_prop_server=False into\n [['Cj', '2fF'], ['Lj', '13.5nH']]\n \"\"\"\n s = variation_string\n s = s.split(' ')\n s = [s1.strip().strip(\"''\").split(\"='\") for s1 in s]\n\n if for_prop_server:\n local, project = [], []\n\n for arr in s:\n to_add = [f'NAME:{arr[0]}', \"Value:=\", arr[1]]\n if arr[0][0] == '$':\n project += [to_add] # global variable\n else:\n local += [to_add] # local variable\n\n return local, project\n\n else:\n return s\n\n def set_variables(self, variation_string: str):\n \"\"\"\n Set all variables to match a solved variaiton string.\n\n Args:\n variation_string (str) : Variaiton string such as\n \"Cj='2fF' Lj='13.5nH'\"\n \"\"\"\n assert isinstance(variation_string, str)\n\n content = [\"NAME:ChangedProps\"]\n local, project = self._variation_string_to_variable_list(\n variation_string)\n #print('\\nlocal=', local, '\\nproject=', project)\n\n if len(project) > 0:\n self._design.ChangeProperty(\n [\"NAME:AllTabs\",\n [\"NAME:ProjectVariableTab\",\n [\"NAME:PropServers\",\n \"ProjectVariables\"\n ],\n content + project\n ]\n ])\n\n if len(local) > 0:\n self._design.ChangeProperty(\n [\"NAME:AllTabs\",\n [\"NAME:LocalVariableTab\",\n [\"NAME:PropServers\",\n \"LocalVariables\"\n ],\n content + local\n ]\n ])\n\n def set_variable(self, name: str, value: str, postprocessing=False):\n \"\"\"Warning: THis is case sensitive,\n\n Arguments:\n name {str} -- Name of variable to set, such as 'Lj_1'.\n This is not the same as as 'LJ_1'.\n You must use the same casing.\n value {str} -- Value, such as '10nH'\n\n Keyword Arguments:\n postprocessing {bool} -- Postprocessingh variable only or not.\n (default: {False})\n\n Returns:\n VariableString\n \"\"\"\n # TODO: check if variable does not exist and quit if it doesn't?\n if name not in self.get_variable_names():\n self.create_variable(name, value, postprocessing=postprocessing)\n else:\n self._design.SetVariableValue(name, value)\n\n return VariableString(name)\n\n def get_variable_value(self, name):\n \"\"\" Can only access the design variables, i.e., the local ones\n Cannot access the project (global) variables, which start with $. \"\"\"\n return self._design.GetVariableValue(name)\n\n def get_variable_names(self):\n \"\"\" Returns the local design variables.\n Does not return the project (global) variables, which start with $. \"\"\"\n return [VariableString(s) for s in\n self._design.GetVariables()+self._design.GetPostProcessingVariables()]\n\n def get_variables(self):\n \"\"\" Returns dictionary of local design variables and their values.\n Does not return the project (global) variables and their values,\n whose names start with $. \"\"\"\n local_variables = self._design.GetVariables(\n )+self._design.GetPostProcessingVariables()\n return {lv: self.get_variable_value(lv) for lv in local_variables}\n\n def copy_design_variables(self, source_design):\n ''' does not check that variables are all present '''\n\n # don't care about values\n source_variables = source_design.get_variables()\n\n for name, value in source_variables.items():\n self.set_variable(name, value)\n\n def get_excitations(self):\n self._boundaries.GetExcitations()\n\n def _evaluate_variable_expression(self, expr, units):\n \"\"\"\n :type expr: str\n :type units: str\n :return: float\n \"\"\"\n try:\n sexp = sympy_parser.parse_expr(expr)\n except SyntaxError:\n return Q(expr).to(units).magnitude\n\n sub_exprs = {fs: self.get_variable_value(fs.name)\n for fs in sexp.free_symbols}\n\n return float(sexp.subs({fs: self._evaluate_variable_expression(e, units)\n for fs, e in sub_exprs.items()}))\n\n def eval_expr(self, expr, units=\"mm\"):\n return str(self._evaluate_variable_expression(expr, units)) + units\n\n def Clear_Field_Clac_Stack(self):\n self._fields_calc.CalcStack(\"Clear\")\n\n\nclass HfssSetup(HfssPropertyObject):\n prop_tab = \"HfssTab\"\n passes = make_int_prop(\"Passes\") # see EditSetup\n n_modes = make_int_prop(\"Modes\")\n pct_refinement = make_float_prop(\"Percent Refinement\")\n delta_f = make_float_prop(\"Delta F\")\n min_freq = make_float_prop(\"Min Freq\")\n basis_order = make_str_prop(\"Basis Order\")\n\n def __init__(self, design, setup:str):\n \"\"\"\n :type design: HfssDesign\n :type setup: Dispatch\n\n :COM Scripting Help: \"Analysis Setup Module Script Commands\"\n\n Get properties:\n setup.parent._design.GetProperties(\"HfssTab\",'AnalysisSetup:Setup1')\n \"\"\"\n super(HfssSetup, self).__init__()\n self.parent = design\n self.prop_holder = design._design\n self._setup_module = design._setup_module\n self._reporter = design._reporter\n self._solutions = design._solutions\n self.name = setup\n self.solution_name = setup + \" : LastAdaptive\"\n #self.solution_name_pass = setup + \" : AdaptivePass\"\n self.prop_server = \"AnalysisSetup:\" + setup\n self.expression_cache_items = []\n self._ansys_version = self.parent._ansys_version\n\n def analyze(self, name=None):\n '''\n Use: Solves a single solution setup and all of its frequency sweeps.\n Command: Right-click a solution setup in the project tree, and then click Analyze\n on the shortcut menu.\n Syntax: Analyze(<SetupName>)\n Parameters: <setupName>\n Return Value: None\n -----------------------------------------------------\n\n Will block the until the analysis is completly done.\n Will raise a com_error if analysis is aborted in HFSS.\n '''\n if name is None:\n name = self.name\n logger.info(f'Analyzing setup {name}')\n return self.parent._design.Analyze(name)\n\n def solve(self, name=None):\n '''\n Use: Performs a blocking simulation.\n The next script command will not be executed\n until the simulation is complete.\n\n Command: HFSS>Analyze\n Syntax: Solve <SetupNameArray>\n Return Value: Type: <int>\n -1: simulation error\n 0: normal completion\n Parameters: <SetupNameArray>: Array(<SetupName>, <SetupName>, ...)\n <SetupName>\n Type: <string>\n Name of the solution setup to solve.\n Example:\n return_status = oDesign.Solve Array(\"Setup1\", \"Setup2\")\n -----------------------------------------------------\n\n HFSS abort: still returns 0 , since termination by user.\n\n '''\n if name is None:\n name = self.name\n return self.parent._design.Solve(name)\n\n def insert_sweep(self, start_ghz, stop_ghz, count=None, step_ghz=None,\n name=\"Sweep\", type=\"Fast\", save_fields=False):\n\n if not type in ['Fast', 'Interpolating', 'Discrete']:\n logger.error(\n \"insert_sweep: Error type was not in ['Fast', 'Interpolating', 'Discrete']\")\n\n name = increment_name(name, self.get_sweep_names())\n params = [\n \"NAME:\"+name,\n \"IsEnabled:=\", True,\n \"Type:=\", type,\n \"SaveFields:=\", save_fields,\n \"SaveRadFields:=\", False,\n # \"GenerateFieldsForAllFreqs:=\"\n \"ExtrapToDC:=\", False,\n ]\n\n # not sure hwen extacyl this changed between 2016 and 2019\n if self._ansys_version >= '2019':\n if count:\n params.extend([\n \"RangeType:=\", 'LinearCount',\n \"RangeStart:=\", f\"{start_ghz:f}GHz\",\n \"RangeEnd:=\", f\"{stop_ghz:f}GHz\",\n \"RangeCount:=\", count])\n if step_ghz:\n params.extend([\n \"RangeType:=\", 'LinearStep',\n \"RangeStart:=\", f\"{start_ghz:f}GHz\",\n \"RangeEnd:=\", f\"{stop_ghz:f}GHz\",\n \"RangeStep:=\", step_ghz])\n\n if (count and step_ghz) or ((not count) and (not step_ghz)):\n logger.error('ERROR: you should provide either step_ghz or count \\\n when inserting an HFSS driven model freq sweep. \\\n YOu either provided both or neither! See insert_sweep.')\n else:\n params.extend([\n \"StartValue:=\", \"%fGHz\" % start_ghz,\n \"StopValue:=\", \"%fGHz\" % stop_ghz])\n if step_ghz is not None:\n params.extend([\n \"SetupType:=\", \"LinearSetup\",\n \"StepSize:=\", \"%fGHz\" % step_ghz])\n else:\n params.extend([\n \"SetupType:=\", \"LinearCount\",\n \"Count:=\", count])\n\n self._setup_module.InsertFrequencySweep(self.name, params)\n\n return HfssFrequencySweep(self, name)\n\n def delete_sweep(self, name):\n self._setup_module.DeleteSweep(self.name, name)\n\n# def add_fields_convergence_expr(self, expr, pct_delta, phase=0):\n# \"\"\"note: because of hfss idiocy, you must call \"commit_convergence_exprs\"\n# after adding all exprs\"\"\"\n# assert isinstance(expr, NamedCalcObject)\n# self.expression_cache_items.append(\n# [\"NAME:CacheItem\",\n# \"Title:=\", expr.name+\"_conv\",\n# \"Expression:=\", expr.name,\n# \"Intrinsics:=\", \"Phase='{}deg'\".format(phase),\n# \"IsConvergence:=\", True,\n# \"UseRelativeConvergence:=\", 1,\n# \"MaxConvergenceDelta:=\", pct_delta,\n# \"MaxConvergeValue:=\", \"0.05\",\n# \"ReportType:=\", \"Fields\",\n# [\"NAME:ExpressionContext\"]])\n\n# def commit_convergence_exprs(self):\n# \"\"\"note: this will eliminate any convergence expressions not added\n# through this interface\"\"\"\n# args = [\n# \"NAME:\"+self.name,\n# [\"NAME:ExpressionCache\", self.expression_cache_items]\n# ]\n# self._setup_module.EditSetup(self.name, args)\n\n def get_sweep_names(self):\n return self._setup_module.GetSweeps(self.name)\n\n def get_sweep(self, name=None):\n sweeps = self.get_sweep_names()\n if not sweeps:\n raise EnvironmentError(\"No Sweeps Present\")\n if name is None:\n name = sweeps[0]\n elif name not in sweeps:\n raise EnvironmentError(\n \"Sweep {} not found in {}\".format(name, sweeps))\n return HfssFrequencySweep(self, name)\n\n def add_fields_convergence_expr(self, expr, pct_delta, phase=0):\n \"\"\"note: because of hfss idiocy, you must call \"commit_convergence_exprs\"\n after adding all exprs\"\"\"\n assert isinstance(expr, NamedCalcObject)\n self.expression_cache_items.append(\n [\"NAME:CacheItem\",\n \"Title:=\", expr.name+\"_conv\",\n \"Expression:=\", expr.name,\n \"Intrinsics:=\", \"Phase='{}deg'\".format(phase),\n \"IsConvergence:=\", True,\n \"UseRelativeConvergence:=\", 1,\n \"MaxConvergenceDelta:=\", pct_delta,\n \"MaxConvergeValue:=\", \"0.05\",\n \"ReportType:=\", \"Fields\",\n [\"NAME:ExpressionContext\"]])\n\n def commit_convergence_exprs(self):\n \"\"\"note: this will eliminate any convergence expressions not added through this interface\"\"\"\n args = [\n \"NAME:\"+self.name,\n [\"NAME:ExpressionCache\", self.expression_cache_items]\n ]\n self._setup_module.EditSetup(self.name, args)\n\n def get_convergence(self, variation=\"\", pre_fn_args=[], overwrite=True):\n '''\n Returns converge as a dataframe\n Variation should be in the form\n variation = \"scale_factor='1.2001'\" ...\n '''\n # TODO: (Daniel) I think this data should be store in a more comfortable datatype (dictionary maybe?)\n # Write file\n temp = tempfile.NamedTemporaryFile()\n temp.close()\n temp = temp.name + '.conv'\n self.parent._design.ExportConvergence(\n self.name, variation, *pre_fn_args, temp, overwrite)\n\n # Read File\n temp = Path(temp)\n if not temp.is_file():\n logger.error(f'''ERROR! Error in trying to read temporary convergence file.\n `get_convergence` did not seem to have the file written {str(temp)}.\n Perhaps there was no convergence? Check to see if there is a CONV available for this current variation. If the nominal design is not solved, it will not have a CONV., but will show up as a variation\n Check for error messages in HFSS.\n Retuning None''')\n return None, ''\n text = temp.read_text()\n\n # Parse file\n text2 = text.split(r'==================')\n if len(text) >= 3:\n df = pd.read_csv(io.StringIO(\n text2[3].strip()), sep='|', skipinitialspace=True, index_col=0).drop('Unnamed: 3', 1)\n else:\n logger.error(f'ERROR IN reading in {temp}:\\n{text}')\n df = None\n\n return df, text\n\n def get_mesh_stats(self, variation=\"\"):\n ''' variation should be in the form\n variation = \"scale_factor='1.2001'\" ...\n '''\n temp = tempfile.NamedTemporaryFile()\n temp.close()\n # print(temp.name0\n # seems broken in 2016 because of extra text added to the top of the file\n self.parent._design.ExportMeshStats(\n self.name, variation, temp.name + '.mesh', True)\n try:\n df = pd.read_csv(temp.name+'.mesh', delimiter='|', skipinitialspace=True,\n skiprows=7, skipfooter=1, skip_blank_lines=True, engine='python')\n df = df.drop('Unnamed: 9', 1)\n except Exception as e:\n print(\"ERROR in MESH reading operation.\")\n print(e)\n print('ERROR! Error in trying to read temporary MESH file ' + temp.name +\n '\\n. Check to see if there is a mesh available for this current variation.\\\n If the nominal design is not solved, it will not have a mesh., \\\n but will show up as a variation.')\n df = None\n return df\n\n def get_profile(self, variation=\"\"):\n fn = tempfile.mktemp()\n self.parent._design.ExportProfile(self.name, variation, fn, False)\n df = pd.read_csv(fn, delimiter='\\t', skipinitialspace=True, skiprows=6,\n skipfooter=1, skip_blank_lines=True, engine='python')\n # just borken down by new lines\n return df\n\n def get_fields(self):\n return HfssFieldsCalc(self)\n\n\nclass HfssDMSetup(HfssSetup):\n \"\"\"\n Driven modal setup\n \"\"\"\n solution_freq = make_float_prop(\"Solution Freq\")\n delta_s = make_float_prop(\"Delta S\")\n solver_type = make_str_prop(\"Solver Type\")\n\n def setup_link(self, linked_setup):\n '''\n type: linked_setup <HfssSetup>\n '''\n args = [\"NAME:\" + self.name,\n [\"NAME:MeshLink\",\n \"Project:=\", \"This Project*\",\n \"Design:=\", linked_setup.parent.name,\n \"Soln:=\", linked_setup.solution_name,\n self._map_variables_by_name(),\n \"ForceSourceToSolve:=\", True,\n \"PathRelativeTo:=\", \"TargetProject\",\n ],\n ]\n self._setup_module.EditSetup(self.name, args)\n\n def _map_variables_by_name(self):\n ''' does not check that variables are all present '''\n # don't care about values\n project_variables = self.parent.parent.get_variable_names()\n design_variables = self.parent.get_variable_names()\n\n # build array\n args = [\"NAME:Params\", ]\n for name in project_variables:\n args.extend([str(name)+\":=\", str(name)])\n for name in design_variables:\n args.extend([str(name)+\":=\", str(name)])\n return args\n\n def get_solutions(self):\n return HfssDMDesignSolutions(self, self.parent._solutions)\n\n\nclass HfssEMSetup(HfssSetup):\n \"\"\"\n Eigenmode setup\n \"\"\"\n min_freq = make_float_prop(\"Min Freq\")\n n_modes = make_int_prop(\"Modes\")\n delta_f = make_float_prop(\"Delta F\")\n\n def get_solutions(self):\n return HfssEMDesignSolutions(self, self.parent._solutions)\n\n\nclass AnsysQ3DSetup(HfssSetup):\n \"\"\"\n Q3D setup\n \"\"\"\n prop_tab = \"CG\"\n max_pass = make_int_prop(\"Max. Number of Passes\")\n min_pass = make_int_prop(\"Min. Number of Passes\")\n pct_error = make_int_prop(\"Percent Error\")\n frequency = make_str_prop(\"Adaptive Freq\", 'General') # e.g., '5GHz'\n n_modes = 0 # for compatability with eigenmode\n\n def get_frequency_Hz(self):\n return int(ureg(self.frequency).to('Hz').magnitude)\n\n def get_solutions(self):\n return HfssQ3DDesignSolutions(self, self.parent._solutions)\n\n def get_convergence(self, variation=\"\"):\n '''\n Returns df\n # Triangle Delta %\n Pass\n 1 164 NaN\n '''\n return super().get_convergence(variation, pre_fn_args=['CG'])\n\n def get_matrix(self, variation='', pass_number=0, frequency=None,\n MatrixType='Maxwell',\n solution_kind='LastAdaptive', # AdpativePass\n ACPlusDCResistance=False,\n soln_type=\"C\"):\n '''\n Arguments:\n -----------\n variation : an empty string returns nominal variation.\n Otherwise need the list\n frequency : in Hz\n soln_type = \"C\", \"AC RL\" and \"DC RL\"\n solution_kind = 'LastAdaptive' # AdaptivePass\n Internals:\n -----------\n Uses self.solution_name = Setup1 : LastAdaptive\n\n Returns:\n ---------------------\n df_cmat, user_units, (df_cond, units_cond), design_variation\n '''\n if frequency is None:\n frequency = self.get_frequency_Hz()\n\n temp = tempfile.NamedTemporaryFile()\n temp.close()\n path = temp.name+'.txt'\n # <FileName>, <SolnType>, <DesignVariationKey>, <Solution>, <Matrix>, <ResUnit>,\n # <IndUnit>, <CapUnit>, <CondUnit>, <Frequency>, <MatrixType>, <PassNumber>,\n # <ACPlusDCResistance>\n self.parent._design.ExportMatrixData(path, soln_type, variation,\n f'{self.name}:{solution_kind}',\n \"Original\", \"ohm\", \"nH\", \"fF\", \"mSie\",\n frequency, MatrixType,\n pass_number, ACPlusDCResistance)\n\n df_cmat, user_units, (df_cond, units_cond), design_variation = \\\n self.load_q3d_matrix(path)\n return df_cmat, user_units, (df_cond, units_cond), design_variation\n\n @staticmethod\n def _readin_Q3D_matrix(path:str):\n \"\"\"\n Read in the txt file created from q3d export\n and output the capacitance matrix\n\n When exporting pick \"save as type: data table\"\n\n See Zlatko\n\n RETURNS: Dataframe\n\n Example file:\n ```\n DesignVariation:$BBoxL='650um' $boxH='750um' $boxL='2mm' $QubitGap='30um' \\\n $QubitH='90um' \\$QubitL='450um' Lj_1='13nH'\n Setup1:LastAdaptive\n Problem Type:C\n C Units:farad, G Units:mSie\n Reduce Matrix:Original\n Frequency: 5.5E+09 Hz\n\n Capacitance Matrix\n ground_plane\tQ1_bus_Q0_connector_pad\tQ1_bus_Q2_connector_pad\tQ1_pad_bot\tQ1_pad_top1\tQ1_readout_connector_pad\n ground_plane\t2.8829E-13\t-3.254E-14\t-3.1978E-14\t-4.0063E-14\t-4.3842E-14\t-3.0053E-14\n Q1_bus_Q0_connector_pad\t-3.254E-14\t4.7257E-14\t-2.2765E-16\t-1.269E-14\t-1.3351E-15\t-1.451E-16\n Q1_bus_Q2_connector_pad\t-3.1978E-14\t-2.2765E-16\t4.5327E-14\t-1.218E-15\t-1.1552E-14\t-5.0414E-17\n Q1_pad_bot\t-4.0063E-14\t-1.269E-14\t-1.218E-15\t9.5831E-14\t-3.2415E-14\t-8.3665E-15\n Q1_pad_top1\t-4.3842E-14\t-1.3351E-15\t-1.1552E-14\t-3.2415E-14\t9.132E-14\t-1.0199E-15\n Q1_readout_connector_pad\t-3.0053E-14\t-1.451E-16\t-5.0414E-17\t-8.3665E-15\t-1.0199E-15\t3.9884E-14\n\n Conductance Matrix\n ground_plane\tQ1_bus_Q0_connector_pad\tQ1_bus_Q2_connector_pad\tQ1_pad_bot\tQ1_pad_top1\tQ1_readout_connector_pad\n ground_plane\t0\t0\t0\t0\t0\t0\n Q1_bus_Q0_connector_pad\t0\t0\t0\t0\t0\t0\n Q1_bus_Q2_connector_pad\t0\t0\t0\t0\t0\t0\n Q1_pad_bot\t0\t0\t0\t0\t0\t0\n Q1_pad_top1\t0\t0\t0\t0\t0\t0\n Q1_readout_connector_pad\t0\t0\t0\t0\t0\t0\n ```\n \"\"\"\n\n text = Path(path).read_text()\n\n\n s1 = text.split('Capacitance Matrix')\n assert len(s1) == 2, \"Copuld not split text to `Capacitance Matrix`\"\n\n s2 = s1[1].split('Conductance Matrix')\n\n df_cmat = pd.read_csv(io.StringIO(\n s2[0].strip()), delim_whitespace=True, skipinitialspace=True, index_col=0)\n units = re.findall(r'C Units:(.*?),', text)[0]\n\n if len(s2) > 1:\n df_cond = pd.read_csv(io.StringIO(\n s2[1].strip()), delim_whitespace=True, skipinitialspace=True, index_col=0)\n units_cond = re.findall(r'G Units:(.*?)\\n', text)[0]\n else:\n df_cond = None\n\n var = re.findall(r'DesignVariation:(.*?)\\n', text) # this changed circe v2020\n if len(var) <1: # didnt find\n var = re.findall(r'Design Variation:(.*?)\\n', text)\n if len(var) <1: # didnt find\n # May not be present if there are no design variations to begin \n # with and no variables in the design. \n pass #logger.error(f'Failed to parse Q3D matrix Design Variation:\\nFile:{path}\\nText:{text}')\n\n var = ['']\n design_variation = var[0]\n\n return df_cmat, units, design_variation, df_cond, units_cond\n\n @staticmethod\n def load_q3d_matrix(path, user_units='fF'):\n \"\"\"Load Q3D capcitance file exported as Maxwell matrix.\n Exports also conductance conductance.\n Units are read in automatically and converted to user units.\n\n Arguments:\n path {[str or Path]} -- [path to file text with matrix]\n\n Returns:\n df_cmat, user_units, (df_cond, units_cond), design_variation\n\n dataframes: df_cmat, df_cond\n \"\"\"\n df_cmat, Cunits, design_variation, df_cond, units_cond = AnsysQ3DSetup._readin_Q3D_matrix(\n path)\n\n # Unit convert\n q = ureg.parse_expression(Cunits).to(user_units)\n df_cmat = df_cmat * q.magnitude # scale to user units\n\n #print(\"Imported capacitance matrix with UNITS: [%s] now converted to USER UNITS:[%s] from file:\\n\\t%s\"%(Cunits, user_units, path))\n\n return df_cmat, user_units, (df_cond, units_cond), design_variation\n\n\nclass HfssDesignSolutions(COMWrapper):\n def __init__(self, setup, solutions):\n '''\n :type setup: HfssSetup\n '''\n super(HfssDesignSolutions, self).__init__()\n self.parent = setup\n self._solutions = solutions\n self._ansys_version = self.parent._ansys_version\n\n def get_valid_solution_list(self):\n '''\n Gets all available solution names that exist in a design.\n Return example:\n ('Setup1 : AdaptivePass', 'Setup1 : LastAdaptive')\n '''\n return self._solutions.GetValidISolutionList()\n\n def list_variations(self, setup_name: str = None):\n \"\"\"\n Get a list of solved variations.\n\n Args:\n setup_name(str) : Example name (\"Setup1 : LastAdaptive\") Defaults to None.\n\n Returns:\n An array of strings corresponding to solved variations.\n\n .. code-block:: python\n\n (\"Cj='2fF' Lj='12nH'\",\n \"Cj='2fF' Lj='12.5nH'\",\n \"Cj='2fF' Lj='13nH'\",\n \"Cj='2fF' Lj='13.5nH'\",\n \"Cj='2fF' Lj='14nH'\")\n \"\"\"\n if setup_name is None:\n setup_name = str(self.parent.solution_name)\n return self._solutions.ListVariations(setup_name)\n\n\nclass HfssEMDesignSolutions(HfssDesignSolutions):\n\n def eigenmodes(self, lv=\"\"):\n '''\n Returns the eigenmode data of freq and kappa/2p\n '''\n fn = tempfile.mktemp()\n #print(self.parent.solution_name, lv, fn)\n self._solutions.ExportEigenmodes(self.parent.solution_name, lv, fn)\n data = np.genfromtxt(fn, dtype='str')\n # Update to Py 3:\n # np.loadtxt and np.genfromtxt operate in byte mode, which is the default string type in Python 2.\n # But Python 3 uses unicode, and marks bytestrings with this b.\n # getting around the very annoying fact that\n if np.size(np.shape(data)) == 1:\n # in Python a 1D array does not have shape (N,1)\n data = np.array([data])\n else: # but rather (N,) ....\n pass\n if np.size(data[0, :]) == 6: # checking if values for Q were saved\n # eigvalue=(omega-i*kappa/2)/2pi\n kappa_over_2pis = [2*float(ii) for ii in data[:, 3]]\n # so kappa/2pi = 2*Im(eigvalue)\n else:\n kappa_over_2pis = None\n\n # print(data[:,1])\n freqs = [float(ii) for ii in data[:, 1]]\n return freqs, kappa_over_2pis\n\n \"\"\"\n Export eigenmodes vs pass number\n Did not figre out how to set pass number in a hurry.\n\n\n import tempfile\n self = epr_hfss.solutions\n\n '''\n HFSS: Exports a tab delimited table of Eigenmodes in HFSS. Not in HFSS-IE.\n <setupName> <solutionName> <DesignVariationKey>\n <filename>\n Return Value: None\n\n Parameters:\n <SolutionName>\n Type: <string>\n Name of the solutions within the solution setup.\n <DesignVariationKey>\n Type: <string>\n Design variation string.\n '''\n setup = self.parent\n fn = tempfile.mktemp()\n variation_list=''\n soln_name = f'{setup.name} : AdaptivePas'\n available_solns = self._solutions.GetValidISolutionList()\n if not(soln_name in available_solns):\n logger.error(f'ERROR Tried to export freq vs pass number, but solution `{soln_name}` was not in avaialbe `{available_solns}`. Returning []')\n #return []\n self._solutions.ExportEigenmodes(soln_name, ['Pass:=5'], fn) # ['Pass:=5'] fails can do with ''\n \"\"\"\n\n def set_mode(self, n, phase=0, FieldType='EigenStoredEnergy'):\n '''\n Indicates which source excitations should be used for fields post processing.\n HFSS>Fields>Edit Sources\n\n Mode count starts at 1\n\n Amplitude is set to 1\n\n No error is thorwn if a number exceeding number of modes is set\n\n FieldType -- EigenStoredEnergy or EigenPeakElecticField\n '''\n n_modes = int(self.parent.n_modes)\n\n if n < 1:\n err = f'ERROR: You tried to set a mode < 1. {n}/{n_modes}'\n logger.error(err)\n raise Exception(err)\n\n if n > n_modes:\n err = f'ERROR: You tried to set a mode > number of modes {n}/{n_modes}'\n logger.error(err)\n raise Exception(err)\n\n if self._ansys_version >= '2019':\n # THIS WORKS FOR v2019R2\n self._solutions.EditSources(\n [\n [\n \"FieldType:=\", \"EigenPeakElectricField\"\n ],\n [\n \"Name:=\", \"Modes\",\n \"Magnitudes:=\", [\"1\" if i + 1 ==\n n else \"0\" for i in range(n_modes)],\n \"Phases:=\", [str(phase) if i + 1 ==\n n else \"0\" for i in range(n_modes)]\n ]\n ])\n else:\n # The syntax has changed for AEDT 18.2.\n # see https://ansyshelp.ansys.com/account/secured?returnurl=/Views/Secured/Electronics/v195//Subsystems/HFSS/Subsystems/HFSS%20Scripting/HFSS%20Scripting.htm\n\n self._solutions.EditSources(\n \"EigenStoredEnergy\",\n [\"NAME:SourceNames\", \"EigenMode\"],\n [\"NAME:Modes\", n_modes],\n [\"NAME:Magnitudes\"] + [1 if i + 1 ==\n n else 0 for i in range(n_modes)],\n [\"NAME:Phases\"] + [phase if i + 1 ==\n n else 0 for i in range(n_modes)],\n [\"NAME:Terminated\"],\n [\"NAME:Impedances\"]\n )\n\n def has_fields(self, variation_string=None):\n '''\n Determine if fields exist for a particular solution.\n\n variation_string : str | None\n This must the string that describes the variaiton in hFSS, not 0 or 1, but\n the string of variables, such as\n \"Cj='2fF' Lj='12.75nH'\"\n If None, gets the nominal variation\n '''\n if variation_string is None:\n variation_string = self.parent.parent.get_nominal_variation()\n\n return bool(self._solutions.HasFields(self.parent.solution_name, variation_string))\n\n def create_report(self, plot_name, xcomp, ycomp, params, pass_name='LastAdaptive'):\n '''\n pass_name: AdaptivePass, LastAdaptive\n\n Example\n ------------------------------------------------------\n Exammple plot for a single vareiation all pass converge of mode freq\n .. code-block python\n ycomp = [f\"re(Mode({i}))\" for i in range(1,1+epr_hfss.n_modes)]\n params = [\"Pass:=\", [\"All\"]]+variation\n setup.create_report(\"Freq. vs. pass\", \"Pass\", ycomp, params, pass_name='AdaptivePass')\n '''\n assert isinstance(ycomp, list)\n assert isinstance(params, list)\n\n setup = self.parent\n reporter = setup._reporter\n return reporter.CreateReport(plot_name, \"Eigenmode Parameters\", \"Rectangular Plot\",\n f\"{setup.name} : {pass_name}\", [], params,\n [\"X Component:=\", xcomp,\n \"Y Component:=\", ycomp], [])\n\n\nclass HfssDMDesignSolutions(HfssDesignSolutions):\n pass\n\n\nclass HfssQ3DDesignSolutions(HfssDesignSolutions):\n pass\n\n\nclass HfssFrequencySweep(COMWrapper):\n prop_tab = \"HfssTab\"\n start_freq = make_float_prop(\"Start\")\n stop_freq = make_float_prop(\"Stop\")\n step_size = make_float_prop(\"Step Size\")\n count = make_float_prop(\"Count\")\n sweep_type = make_str_prop(\"Type\")\n\n def __init__(self, setup, name):\n \"\"\"\n :type setup: HfssSetup\n :type name: str\n \"\"\"\n super(HfssFrequencySweep, self).__init__()\n self.parent = setup\n self.name = name\n self.solution_name = self.parent.name + \" : \" + name\n self.prop_holder = self.parent.prop_holder\n self.prop_server = self.parent.prop_server + \":\" + name\n self._ansys_version = self.parent._ansys_version\n\n def analyze_sweep(self):\n self.parent.analyze(self.solution_name)\n\n def get_network_data(self, formats):\n if isinstance(formats, str):\n formats = formats.split(\",\")\n formats = [f.upper() for f in formats]\n\n fmts_lists = {'S': [], 'Y': [], 'Z': []}\n\n for f in formats:\n fmts_lists[f[0]].append((int(f[1]), int(f[2])))\n\n ret = [None] * len(formats)\n freq = None\n\n for data_type, list in fmts_lists.items():\n if list:\n fn = tempfile.mktemp()\n self.parent._solutions.ExportNetworkData(\n [], self.parent.name + \" : \" + self.name,\n 2, fn, [\"all\"], False, 0,\n data_type, -1, 1, 15\n )\n with open(fn) as f:\n f.readline()\n colnames = f.readline().split()\n array = np.loadtxt(fn, skiprows=2)\n # WARNING for python 3 probably need to use genfromtxt\n if freq is None:\n freq = array[:, 0]\n for i, j in list:\n real_idx = colnames.index(\n \"%s[%d,%d]_Real\" % (data_type, i, j))\n imag_idx = colnames.index(\n \"%s[%d,%d]_Imag\" % (data_type, i, j))\n c_arr = array[:, real_idx] + 1j*array[:, imag_idx]\n ret[formats.index(\"%s%d%d\" % (data_type, i, j))] = c_arr\n\n return freq, ret\n\n def create_report(self, name, expr):\n existing = self.parent._reporter.GetAllReportNames()\n name = increment_name(name, existing)\n var_names = self.parent.parent.get_variable_names()\n var_args = sum([[\"%s:=\" % v_name, [\"Nominal\"]]\n for v_name in var_names], [])\n self.parent._reporter.CreateReport(\n name, \"Modal Solution Data\", \"Rectangular Plot\",\n self.solution_name, [\"Domain:=\", \"Sweep\"], [\n \"Freq:=\", [\"All\"]] + var_args,\n [\"X Component:=\", \"Freq\", \"Y Component:=\", [expr]], [])\n return HfssReport(self.parent.parent, name)\n\n def get_report_arrays(self, expr):\n r = self.create_report(\"Temp\", expr)\n return r.get_arrays()\n\n\nclass HfssReport(COMWrapper):\n def __init__(self, design, name):\n \"\"\"\n :type design: HfssDesign\n :type name: str\n \"\"\"\n super(HfssReport, self).__init__()\n self.parent_design = design\n self.name = name\n\n def export_to_file(self, filename):\n filepath = os.path.abspath(filename)\n self.parent_design._reporter.ExportToFile(self.name, filepath)\n\n def get_arrays(self):\n fn = tempfile.mktemp(suffix=\".csv\")\n self.export_to_file(fn)\n return np.loadtxt(fn, skiprows=1, delimiter=',').transpose()\n # warning for python 3 probably need to use genfromtxt\n\n\nclass Optimetrics(COMWrapper):\n \"\"\"\n Optimetrics script commands executed by the \"Optimetrics\" module.\n\n Example use:\n .. code-block python\n opti = Optimetrics(pinfo.design)\n names = opti.get_setup_names()\n print('Names of optimetrics: ', names)\n opti.solve_setup(names[0])\n\n Note that running optimetrics requires the license for Optimetrics by Ansys.\n \"\"\"\n\n def __init__(self, design):\n super(Optimetrics, self).__init__()\n\n self.design = design # parent\n self._optimetrics = self.design._optimetrics # <COMObject GetModule>\n self.setup_names = None\n\n def get_setup_names(self):\n \"\"\"\n Return list of Optimetrics setup names\n \"\"\"\n self.setup_names = list(self._optimetrics.GetSetupNames())\n return self.setup_names.copy()\n\n def solve_setup(self, setup_name: str):\n \"\"\"\n Solves the specified Optimetrics setup.\n Corresponds to: Right-click the setup in the project tree, and then click\n Analyze on the shortcut menu.\n\n setup_name (str) : name of setup, should be in get_setup_names\n\n Blocks execution until ready to use.\n\n Note that this requires the license for Optimetrics by Ansys.\n \"\"\"\n return self._optimetrics.SolveSetup(setup_name)\n\n def create_setup(self, variable, swp_params, name=\"ParametricSetup1\", swp_type='linear_step',\n setup_name=None,\n save_fields=True, copy_mesh=True, solve_with_copied_mesh_only=True,\n setup_type='parametric'\n ):\n \"\"\"\n Inserts a new parametric setup.\n\n\n For type_='linear_step' swp_params is start, stop, step:\n swp_params = (\"12.8nH\" \"13.6nH\", \"0.2nH\")\n\n Corresponds to ui access:\n Right-click the Optimetrics folder in the project tree,\n and then click Add> Parametric on the shortcut menu.\n \"\"\"\n setup_name = setup_name or self.design.get_setup_names()[0]\n print(\n f\"Inserting optimetrics setup `{name}` for simulation setup: `{setup_name}`\")\n\n if setup_type != 'parametric':\n raise NotImplementedError()\n\n if swp_type == 'linear_step':\n assert len(swp_params) == 3\n # e.g., \"LIN 12.8nH 13.6nH 0.2nH\"\n swp_str = f\"LIN {swp_params[0]} {swp_params[1]} {swp_params[2]}\"\n else:\n raise NotImplementedError()\n\n self._optimetrics.InsertSetup(\"OptiParametric\",\n [\n f\"NAME:{name}\",\n \"IsEnabled:=\"\t\t, True,\n [\n \"NAME:ProdOptiSetupDataV2\",\n \"SaveFields:=\"\t\t, save_fields,\n \"CopyMesh:=\"\t\t, copy_mesh,\n \"SolveWithCopiedMeshOnly:=\", solve_with_copied_mesh_only,\n ],\n [\n \"NAME:StartingPoint\"\n ],\n \"Sim. Setups:=\"\t\t, [setup_name],\n [\n \"NAME:Sweeps\",\n [\n \"NAME:SweepDefinition\",\n \"Variable:=\"\t\t, variable,\n \"Data:=\"\t\t, swp_str,\n \"OffsetF1:=\"\t\t, False,\n \"Synchronize:=\"\t\t, 0\n ]\n ],\n [\n \"NAME:Sweep Operations\"\n ],\n [\n \"NAME:Goals\"\n ]\n ])\n\n\nclass HfssModeler(COMWrapper):\n def __init__(self, design, modeler, boundaries, mesh):\n \"\"\"\n :type design: HfssDesign\n \"\"\"\n super(HfssModeler, self).__init__()\n self.parent = design\n self._modeler = modeler\n self._boundaries = boundaries\n self._mesh = mesh # Mesh module\n\n def set_units(self, units, rescale=True):\n self._modeler.SetModelUnits(\n [\"NAME:Units Parameter\", \"Units:=\", units, \"Rescale:=\", rescale])\n\n def get_units(self):\n \"\"\"Get the model units.\n Return Value: A string contains current model units. \"\"\"\n return str(self._modeler.GetModelUnits())\n\n def get_all_properties(self, obj_name, PropTab='Geometry3DAttributeTab'):\n '''\n Get all properties for modeler PropTab, PropServer\n '''\n PropServer = obj_name\n properties = {}\n for key in self._modeler.GetProperties(PropTab, PropServer):\n properties[key] = self._modeler.GetPropertyValue(\n PropTab, PropServer, key)\n return properties\n\n def _attributes_array(self,\n name=None,\n nonmodel=False,\n wireframe=False,\n color=None,\n transparency=0.9,\n material=None, # str\n solve_inside=None, # bool\n coordinate_system=\"Global\"):\n arr = [\"NAME:Attributes\", \"PartCoordinateSystem:=\", coordinate_system]\n if name is not None:\n arr.extend([\"Name:=\", name])\n\n if nonmodel or wireframe:\n flags = 'NonModel' if nonmodel else '' # can be done smarter\n if wireframe:\n flags += '#' if len(flags) > 0 else ''\n flags += 'Wireframe'\n arr.extend([\"Flags:=\", flags])\n\n if color is not None:\n arr.extend([\"Color:=\", \"(%d %d %d)\" % color])\n if transparency is not None:\n arr.extend([\"Transparency:=\", transparency])\n if material is not None:\n arr.extend([\"MaterialName:=\", material])\n if solve_inside is not None:\n arr.extend([\"SolveInside:=\", solve_inside])\n\n return arr\n\n def _selections_array(self, *names):\n return [\"NAME:Selections\", \"Selections:=\", \",\".join(names)]\n\n def mesh_length(self, name_mesh, objects: list, MaxLength='0.1mm', **kwargs):\n '''\n \"RefineInside:=\"\t, False,\n \"Enabled:=\"\t\t, True,\n \"RestrictElem:=\"\t, False,\n \"NumMaxElem:=\"\t\t, \"1000\",\n \"RestrictLength:=\"\t, True,\n \"MaxLength:=\"\t\t, \"0.1mm\"\n\n Example use:\n modeler.assign_mesh_length('mesh2', [\"Q1_mesh\"], MaxLength=0.1)\n '''\n assert isinstance(objects, list)\n\n arr = [f\"NAME:{name_mesh}\",\n \"Objects:=\", objects,\n 'MaxLength:=', MaxLength]\n ops = ['RefineInside', 'Enabled', 'RestrictElem',\n 'NumMaxElem', 'RestrictLength']\n for key, val in kwargs.items():\n if key in ops:\n arr += [key+':=', str(val)]\n else:\n logger.error('KEY `{key}` NOT IN ops!')\n\n self._mesh.AssignLengthOp(arr)\n\n def mesh_reassign(self, name_mesh, objects: list):\n assert isinstance(objects, list)\n self._mesh.ReassignOp(name_mesh, [\"Objects:=\", objects])\n\n def mesh_get_names(self, kind=\"Length Based\"):\n ''' \"Length Based\", \"Skin Depth Based\", ...'''\n return list(self._mesh.GetOperationNames(kind))\n\n def mesh_get_all_props(self, mesh_name):\n # TODO: make mesh tis own class with preperties\n prop_tab = 'MeshSetupTab'\n prop_server = f'MeshSetup:{mesh_name}'\n prop_names = self.parent._design.GetProperties(\n 'MeshSetupTab', prop_server)\n dic = {}\n for name in prop_names:\n dic[name] = self._modeler.GetPropertyValue(\n prop_tab, prop_server, name)\n return dic\n\n def draw_box_corner(self, pos, size, **kwargs):\n name = self._modeler.CreateBox(\n [\"NAME:BoxParameters\",\n \"XPosition:=\", str(pos[0]),\n \"YPosition:=\", str(pos[1]),\n \"ZPosition:=\", str(pos[2]),\n \"XSize:=\", str(size[0]),\n \"YSize:=\", str(size[1]),\n \"ZSize:=\", str(size[2])],\n self._attributes_array(**kwargs)\n )\n return Box(name, self, pos, size)\n\n def draw_box_center(self, pos, size, **kwargs):\n \"\"\"\n Creates a 3-D box centered at pos [x0, y0, z0], with width\n size [xwidth, ywidth, zwidth] along each respective direction.\n\n Args:\n pos (list): Coordinates of center of box, [x0, y0, z0]\n size (list): Width of box along each direction, [xwidth, ywidth, zwidth]\n \"\"\"\n corner_pos = [var(p) - var(s)/2 for p, s in zip(pos, size)]\n return self.draw_box_corner(corner_pos, size, **kwargs)\n\n def draw_polyline(self, points, closed=True, **kwargs):\n \"\"\"\n Draws a closed or open polyline.\n If closed = True, then will make into a sheet.\n points : need to be in the correct units\n\n For optional arguments, see _attributes_array; these include:\n ```\n nonmodel=False,\n wireframe=False,\n color=None,\n transparency=0.9,\n material=None, # str\n solve_inside=None, # bool\n coordinate_system=\"Global\"\n ```\n \"\"\"\n pointsStr = [\"NAME:PolylinePoints\"]\n indexsStr = [\"NAME:PolylineSegments\"]\n for ii, point in enumerate(points):\n pointsStr.append([\"NAME:PLPoint\",\n \"X:=\", str(point[0]),\n \"Y:=\", str(point[1]),\n \"Z:=\", str(point[2])])\n indexsStr.append([\"NAME:PLSegment\", \"SegmentType:=\",\n \"Line\", \"StartIndex:=\", ii, \"NoOfPoints:=\", 2])\n if closed:\n pointsStr.append([\"NAME:PLPoint\",\n \"X:=\", str(points[0][0]),\n \"Y:=\", str(points[0][1]),\n \"Z:=\", str(points[0][2])])\n params_closed = [\"IsPolylineCovered:=\",\n True, \"IsPolylineClosed:=\", True]\n else:\n indexsStr = indexsStr[:-1]\n params_closed = [\"IsPolylineCovered:=\",\n True, \"IsPolylineClosed:=\", False]\n\n name = self._modeler.CreatePolyline(\n [\"NAME:PolylineParameters\",\n *params_closed,\n pointsStr,\n indexsStr],\n self._attributes_array(**kwargs)\n )\n\n if closed:\n return Polyline(name, self, points)\n else:\n return OpenPolyline(name, self, points)\n\n def draw_rect_corner(self, pos, x_size=0, y_size=0, z_size=0, **kwargs):\n size = [x_size, y_size, z_size]\n assert 0 in size\n axis = \"XYZ\"[size.index(0)]\n w_idx, h_idx = {\n 'X': (1, 2),\n 'Y': (2, 0),\n 'Z': (0, 1)\n }[axis]\n\n name = self._modeler.CreateRectangle(\n [\"NAME:RectangleParameters\",\n \"XStart:=\", str(pos[0]),\n \"YStart:=\", str(pos[1]),\n \"ZStart:=\", str(pos[2]),\n \"Width:=\", str(size[w_idx]),\n \"Height:=\", str(size[h_idx]),\n \"WhichAxis:=\", axis],\n self._attributes_array(**kwargs)\n )\n return Rect(name, self, pos, size)\n\n def draw_rect_center(self, pos, x_size=0, y_size=0, z_size=0, **kwargs):\n \"\"\"\n Creates a rectangle centered at pos [x0, y0, z0].\n It is assumed that the rectangle lies parallel to the xy, yz, or xz plane.\n User inputs 2 of 3 of the following: x_size, y_size, and z_size\n depending on how the rectangle is oriented.\n\n Args:\n pos (list): Coordinates of rectangle center, [x0, y0, z0]\n x_size (int, optional): Width along the x direction. Defaults to 0.\n y_size (int, optional): Width along the y direction. Defaults to 0.\n z_size (int, optional): Width along the z direction]. Defaults to 0.\n \"\"\"\n corner_pos = [var(p) - var(s)/2. for p,\n s in zip(pos, [x_size, y_size, z_size])]\n return self.draw_rect_corner(corner_pos, x_size, y_size, z_size, **kwargs)\n\n def draw_cylinder(self, pos, radius, height, axis, **kwargs):\n assert axis in \"XYZ\"\n return self._modeler.CreateCylinder(\n [\"NAME:CylinderParameters\",\n \"XCenter:=\", pos[0],\n \"YCenter:=\", pos[1],\n \"ZCenter:=\", pos[2],\n \"Radius:=\", radius,\n \"Height:=\", height,\n \"WhichAxis:=\", axis,\n \"NumSides:=\", 0],\n self._attributes_array(**kwargs))\n\n def draw_cylinder_center(self, pos, radius, height, axis, **kwargs):\n axis_idx = [\"X\", \"Y\", \"Z\"].index(axis)\n edge_pos = copy(pos)\n edge_pos[axis_idx] = var(pos[axis_idx]) - var(height)/2\n return self.draw_cylinder(edge_pos, radius, height, axis, **kwargs)\n\n def draw_wirebond(self, pos, ori, width, height='0.1mm', z=0,\n wire_diameter=\"0.02mm\", NumSides=6,\n **kwargs):\n '''\n Args:\n pos: 2D positon vector (specify center point)\n ori: should be normed\n z: z postion\n\n # TODO create Wirebond class\n psoition is the origin of one point\n ori is the orientation vector, which gets normalized\n '''\n p = np.array(pos)\n o = np.array(ori)\n pad1 = p-o*width/2.\n name = self._modeler.CreateBondwire([\"NAME:BondwireParameters\",\n \"WireType:=\", \"Low\",\n \"WireDiameter:=\", wire_diameter,\n \"NumSides:=\", NumSides,\n \"XPadPos:=\", pad1[0],\n \"YPadPos:=\", pad1[1],\n \"ZPadPos:=\", z,\n \"XDir:=\", ori[0],\n \"YDir:=\", ori[1],\n \"ZDir:=\", 0,\n \"Distance:=\", width,\n \"h1:=\", height,\n \"h2:=\", \"0mm\",\n \"alpha:=\", \"80deg\",\n \"beta:=\", \"80deg\",\n \"WhichAxis:=\", \"Z\"],\n self._attributes_array(**kwargs))\n\n return name\n\n def draw_region(self, Padding, PaddingType=\"Percentage Offset\", name='Region',\n material=\"\\\"vacuum\\\"\"):\n \"\"\"\n PaddingType : 'Absolute Offset', \"Percentage Offset\"\n \"\"\"\n # TODO: Add option to modify these\n RegionAttributes = [\n \"NAME:Attributes\",\n \"Name:=\"\t\t, name,\n \"Flags:=\"\t\t, \"Wireframe#\",\n \"Color:=\"\t\t, \"(255 0 0)\",\n \"Transparency:=\"\t, 1,\n \"PartCoordinateSystem:=\", \"Global\",\n \"UDMId:=\"\t\t, \"\",\n \"IsAlwaysHiden:=\"\t, False,\n \"MaterialValue:=\"\t, material,\n \"SolveInside:=\"\t\t, True\n ]\n\n self._modeler.CreateRegion(\n [\n \"NAME:RegionParameters\",\n \"+XPaddingType:=\"\t, PaddingType,\n \"+XPadding:=\"\t\t, Padding[0][0],\n \"-XPaddingType:=\"\t, PaddingType,\n \"-XPadding:=\"\t\t, Padding[0][1],\n \"+YPaddingType:=\"\t, PaddingType,\n \"+YPadding:=\"\t\t, Padding[1][0],\n \"-YPaddingType:=\"\t, PaddingType,\n \"-YPadding:=\"\t\t, Padding[1][1],\n \"+ZPaddingType:=\"\t, PaddingType,\n \"+ZPadding:=\"\t\t, Padding[2][0],\n \"-ZPaddingType:=\"\t, PaddingType,\n \"-ZPadding:=\"\t\t, Padding[2][1]\n ],\n RegionAttributes)\n\n def unite(self, names, keep_originals=False):\n self._modeler.Unite(\n self._selections_array(*names),\n [\"NAME:UniteParameters\", \"KeepOriginals:=\", keep_originals]\n )\n return names[0]\n\n def intersect(self, names, keep_originals=False):\n self._modeler.Intersect(\n self._selections_array(*names),\n [\"NAME:IntersectParameters\", \"KeepOriginals:=\", keep_originals]\n )\n return names[0]\n\n def translate(self, name, vector):\n self._modeler.Move(\n self._selections_array(name),\n [\"NAME:TranslateParameters\",\n \"TranslateVectorX:=\", vector[0],\n \"TranslateVectorY:=\", vector[1],\n \"TranslateVectorZ:=\", vector[2]]\n )\n\n def get_boundary_assignment(self, boundary_name: str):\n # Gets a list of face IDs associated with the given boundary or excitation assignment.\n objects = self._boundaries.GetBoundaryAssignment(boundary_name)\n # Gets an object name corresponding to the input face id. Returns the name of the corresponding object name.\n objects = [self._modeler.GetObjectNameByFaceID(k) for k in objects]\n return objects\n\n def append_PerfE_assignment(self, boundary_name: str, object_names: list):\n '''\n This will create a new boundary if need, and will\n otherwise append given names to an exisiting boundary\n '''\n # enforce\n boundary_name = str(boundary_name)\n if isinstance(object_names, str):\n object_names = [object_names]\n object_names = list(object_names) # enforce list\n\n # do actual work\n if boundary_name not in self._boundaries.GetBoundaries(): # GetBoundariesOfType(\"Perfect E\")\n # need to make a new boundary\n self.assign_perfect_E(object_names, name=boundary_name)\n else:\n # need to append\n objects = list(self.get_boundary_assignment(boundary_name))\n self._boundaries.ReassignBoundary([\"NAME:\" + boundary_name,\n \"Objects:=\", list(set(objects + object_names))])\n\n def append_mesh(self, mesh_name: str, object_names: list, old_objs: list,\n **kwargs):\n '''\n This will create a new boundary if need, and will\n otherwise append given names to an exisiting boundary\n old_obj = circ._mesh_assign\n '''\n mesh_name = str(mesh_name)\n if isinstance(object_names, str):\n object_names = [object_names]\n object_names = list(object_names) # enforce list\n\n if mesh_name not in self.mesh_get_names(): # need to make a new boundary\n objs = object_names\n self.mesh_length(mesh_name, object_names, **kwargs)\n else: # need to append\n objs = list(set(old_objs + object_names))\n self.mesh_reassign(mesh_name, objs)\n\n return objs\n\n def assign_perfect_E(self, obj:List[str], name:str='PerfE'):\n '''\n Assign a boundary condition to a list of objects.\n\n Arg:\n objs (List[str]): Takes a name of an object or a list of object names.\n name(str): If `name` is not specified `PerfE` is appended to object name for the name.\n '''\n if not isinstance(obj, list):\n obj = [obj]\n if name == 'PerfE':\n name = str(obj)+'_'+name\n name = increment_name(name, self._boundaries.GetBoundaries())\n self._boundaries.AssignPerfectE(\n [\"NAME:\"+name, \"Objects:=\", obj, \"InfGroundPlane:=\", False])\n\n def _make_lumped_rlc(self, r, l, c, start, end, obj_arr, name=\"LumpRLC\"):\n name = increment_name(name, self._boundaries.GetBoundaries())\n params = [\"NAME:\"+name]\n params += obj_arr\n params.append([\"NAME:CurrentLine\",\n # for some reason here it seems to swtich to use the model units, rather than meters\n \"Start:=\", fix_units(start, unit_assumed=LENGTH_UNIT),\n \"End:=\", fix_units(end, unit_assumed=LENGTH_UNIT)])\n params += [\"UseResist:=\", r != 0, \"Resistance:=\", r,\n \"UseInduct:=\", l != 0, \"Inductance:=\", l,\n \"UseCap:=\", c != 0, \"Capacitance:=\", c]\n self._boundaries.AssignLumpedRLC(params)\n\n def _make_lumped_port(self, start, end, obj_arr, z0=\"50ohm\", name=\"LumpPort\"):\n start = fix_units(start, unit_assumed=LENGTH_UNIT)\n end = fix_units(end, unit_assumed=LENGTH_UNIT)\n\n name = increment_name(name, self._boundaries.GetBoundaries())\n params = [\"NAME:\"+name]\n params += obj_arr\n params += [\"RenormalizeAllTerminals:=\", True, \"DoDeembed:=\", False,\n [\"NAME:Modes\", [\"NAME:Mode1\",\n \"ModeNum:=\", 1,\n \"UseIntLine:=\", True,\n [\"NAME:IntLine\",\n \"Start:=\", start,\n \"End:=\", end],\n \"CharImp:=\", \"Zpi\",\n \"AlignmentGroup:=\", 0,\n \"RenormImp:=\", \"50ohm\"]],\n \"ShowReporterFilter:=\", False, \"ReporterFilter:=\", [True],\n \"FullResistance:=\", \"50ohm\", \"FullReactance:=\", \"0ohm\"]\n\n self._boundaries.AssignLumpedPort(params)\n\n def get_face_ids(self, obj):\n return self._modeler.GetFaceIDs(obj)\n\n def get_object_name_by_face_id(self, ID: str):\n ''' Gets an object name corresponding to the input face id. '''\n return self._modeler.GetObjectNameByFaceID(ID)\n\n def get_vertex_ids(self, obj):\n \"\"\"\n Get the vertex IDs of given an object name\n oVertexIDs = oEditor.GetVertexIDsFromObject(“Box1”)\n \"\"\"\n return self._modeler.GetVertexIDsFromObject(obj)\n\n def eval_expr(self, expr, units=\"mm\"):\n if not isinstance(expr, str):\n return expr\n return self.parent.eval_expr(expr, units)\n\n def get_objects_in_group(self, group):\n \"\"\"\n Use: Returns the objects for the specified group.\n Return Value: The objects in the group.\n Parameters: <groupName> Type: <string>\n One of <materialName>, <assignmentName>, \"Non Model\",\n \"Solids\", \"Unclassi­fied\", \"Sheets\", \"Lines\"\n \"\"\"\n return list(self._modeler.GetObjectsInGroup(group))\n\n def set_working_coordinate_system(self, cs_name=\"Global\"):\n \"\"\"\n Use: Sets the working coordinate system.\n Command: Modeler>Coordinate System>Set Working CS\n \"\"\"\n self._modeler.SetWCS(\n [\n \"NAME:SetWCS Parameter\",\n \"Working Coordinate System:=\", cs_name,\n \"RegionDepCSOk:=\"\t, False # this one is prob not needed, but comes with the record tool\n ])\n\n def create_relative_coorinate_system_both(self, cs_name,\n origin=[\"0um\", \"0um\", \"0um\"],\n XAxisVec=[\"1um\", \"0um\", \"0um\"],\n YAxisVec=[\"0um\", \"1um\", \"0um\"]):\n \"\"\"\n Use: Creates a relative coordinate system. Only the Name attribute of the <AttributesArray> parameter is supported.\n Command: Modeler>Coordinate System>Create>Relative CS->Offset\n Modeler>Coordinate System>Create>Relative CS->Rotated\n Modeler>Coordinate System>Create>Relative CS->Both\n\n Current cooridnate system is set right after this.\n\n cs_name : name of coord. sys\n If the name already exists, then a new coordinate system with _1 is created.\n\n origin, XAxisVec, YAxisVec: 3-vectors\n You can also pass in params such as origin = [0,1,0] rather than [\"0um\",\"1um\",\"0um\"], but these will be interpreted in default units, so it is safer to be explicit. Explicit over implicit.\n \"\"\"\n self._modeler.CreateRelativeCS(\n [\n \"NAME:RelativeCSParameters\",\n \"Mode:=\"\t\t, \"Axis/Position\",\n \"OriginX:=\"\t\t, origin[0],\n \"OriginY:=\"\t\t, origin[1],\n \"OriginZ:=\"\t\t, origin[2],\n \"XAxisXvec:=\"\t\t, XAxisVec[0],\n \"XAxisYvec:=\"\t\t, XAxisVec[1],\n \"XAxisZvec:=\"\t\t, XAxisVec[2],\n \"YAxisXvec:=\"\t\t, YAxisVec[0],\n \"YAxisYvec:=\"\t\t, YAxisVec[1],\n \"YAxisZvec:=\"\t\t, YAxisVec[1]\n ],\n [\n \"NAME:Attributes\",\n \"Name:=\"\t\t, cs_name\n ])\n\n def subtract(self, blank_name, tool_names, keep_originals=False):\n selection_array = [\"NAME:Selections\",\n \"Blank Parts:=\", blank_name,\n \"Tool Parts:=\", \",\".join(tool_names)]\n self._modeler.Subtract(\n selection_array,\n [\"NAME:UniteParameters\", \"KeepOriginals:=\", keep_originals]\n )\n return blank_name\n\n def _fillet(self, radius, vertex_index, obj):\n vertices = self._modeler.GetVertexIDsFromObject(obj)\n if isinstance(vertex_index, list):\n to_fillet = [int(vertices[v]) for v in vertex_index]\n else:\n to_fillet = [int(vertices[vertex_index])]\n# print(vertices)\n# print(radius)\n self._modeler.Fillet([\"NAME:Selections\", \"Selections:=\", obj],\n [\"NAME:Parameters\",\n [\"NAME:FilletParameters\",\n \"Edges:=\", [],\n \"Vertices:=\", to_fillet,\n \"Radius:=\", radius,\n \"Setback:=\", \"0mm\"]])\n\n def _fillet_edges(self, radius, edge_index, obj):\n edges = self._modeler.GetEdgeIDsFromObject(obj)\n if isinstance(edge_index, list):\n to_fillet = [int(edges[e]) for e in edge_index]\n else:\n to_fillet = [int(edges[edge_index])]\n\n self._modeler.Fillet([\"NAME:Selections\", \"Selections:=\", obj],\n [\"NAME:Parameters\",\n [\"NAME:FilletParameters\",\n \"Edges:=\", to_fillet,\n \"Vertices:=\", [],\n \"Radius:=\", radius,\n \"Setback:=\", \"0mm\"]])\n\n def _fillets(self, radius, vertices, obj):\n self._modeler.Fillet([\"NAME:Selections\", \"Selections:=\", obj],\n [\"NAME:Parameters\",\n [\"NAME:FilletParameters\",\n \"Edges:=\", [],\n \"Vertices:=\", vertices,\n \"Radius:=\", radius,\n \"Setback:=\", \"0mm\"]])\n\n def _sweep_along_path(self, to_sweep, path_obj):\n \"\"\"\n Adds thickness to path_obj by extending to a new dimension.\n to_sweep acts as a putty knife that determines the thickness.\n\n Args:\n to_sweep (polyline): Small polyline running perpendicular to path_obj\n whose length is the desired resulting thickness\n path_obj (polyline): Original polyline; want to broaden this\n \"\"\"\n self.rename_obj(path_obj, str(path_obj)+'_path')\n new_name = self.rename_obj(to_sweep, path_obj)\n names = [path_obj, str(path_obj)+'_path']\n self._modeler.SweepAlongPath(self._selections_array(*names),\n [\"NAME:PathSweepParameters\",\n \"DraftAngle:=\"\t\t, \"0deg\",\n \"DraftType:=\"\t\t, \"Round\",\n \"CheckFaceFaceIntersection:=\", False,\n \"TwistAngle:=\"\t\t, \"0deg\"])\n return Polyline(new_name, self)\n\n def sweep_along_vector(self, names, vector):\n self._modeler.SweepAlongVector(self._selections_array(*names),\n [\"NAME:VectorSweepParameters\",\n \"DraftAngle:=\"\t\t, \"0deg\",\n \"DraftType:=\"\t\t, \"Round\",\n \"CheckFaceFaceIntersection:=\", False,\n \"SweepVectorX:=\"\t, vector[0],\n \"SweepVectorY:=\"\t, vector[1],\n \"SweepVectorZ:=\"\t, vector[2]\n ])\n\n def rename_obj(self, obj, name):\n self._modeler.ChangeProperty([\"NAME:AllTabs\",\n [\"NAME:Geometry3DAttributeTab\",\n [\"NAME:PropServers\", str(obj)],\n [\"NAME:ChangedProps\", [\"NAME:Name\", \"Value:=\", str(name)]]]])\n return name\n\n\nclass ModelEntity(str, HfssPropertyObject):\n prop_tab = \"Geometry3DCmdTab\"\n model_command = None\n transparency = make_float_prop(\n \"Transparent\", prop_tab=\"Geometry3DAttributeTab\", prop_server=lambda self: self)\n material = make_str_prop(\n \"Material\", prop_tab=\"Geometry3DAttributeTab\", prop_server=lambda self: self)\n wireframe = make_float_prop(\n \"Display Wireframe\", prop_tab=\"Geometry3DAttributeTab\", prop_server=lambda self: self)\n coordinate_system = make_str_prop(\"Coordinate System\")\n\n def __new__(self, val, *args, **kwargs):\n return str.__new__(self, val)\n\n def __init__(self, val, modeler):\n \"\"\"\n :type val: str\n :type modeler: HfssModeler\n \"\"\"\n super(ModelEntity, self).__init__(\n ) # val) #Comment out keyword to match arguments\n self.modeler = modeler\n self.prop_server = self + \":\" + self.model_command + \":1\"\n\n\nclass Box(ModelEntity):\n model_command = \"CreateBox\"\n position = make_float_prop(\"Position\")\n x_size = make_float_prop(\"XSize\")\n y_size = make_float_prop(\"YSize\")\n z_size = make_float_prop(\"ZSize\")\n\n def __init__(self, name, modeler, corner, size):\n \"\"\"\n :type name: str\n :type modeler: HfssModeler\n :type corner: [(VariableString, VariableString, VariableString)]\n :param size: [(VariableString, VariableString, VariableString)]\n \"\"\"\n super(Box, self).__init__(name, modeler)\n self.modeler = modeler\n self.prop_holder = modeler._modeler\n self.corner = corner\n self.size = size\n self.center = [c + s/2 for c, s in zip(corner, size)]\n faces = modeler.get_face_ids(self)\n self.z_back_face, self.z_front_face = faces[0], faces[1]\n self.y_back_face, self.y_front_face = faces[2], faces[4]\n self.x_back_face, self.x_front_face = faces[3], faces[5]\n\n\nclass Rect(ModelEntity):\n model_command = \"CreateRectangle\"\n # TODO: Add a rotated rectangle object.\n # Will need to first create rect, then apply rotate operation.\n\n def __init__(self, name, modeler, corner, size):\n super(Rect, self).__init__(name, modeler)\n self.prop_holder = modeler._modeler\n self.corner = corner\n self.size = size\n self.center = [c + s/2 if s else c for c, s in zip(corner, size)]\n\n def make_center_line(self, axis):\n '''\n Returns `start` and `end` list of 3 coordinates\n '''\n axis_idx = [\"x\", \"y\", \"z\"].index(axis.lower())\n start = [c for c in self.center]\n start[axis_idx] -= self.size[axis_idx]/2\n start = [self.modeler.eval_expr(s) for s in start]\n end = [c for c in self.center]\n end[axis_idx] += self.size[axis_idx]/2\n end = [self.modeler.eval_expr(s) for s in end]\n return start, end\n\n def make_rlc_boundary(self, axis, r=0, l=0, c=0, name=\"LumpRLC\"):\n start, end = self.make_center_line(axis)\n self.modeler._make_lumped_rlc(\n r, l, c, start, end, [\"Objects:=\", [self]], name=name)\n\n def make_lumped_port(self, axis, z0=\"50ohm\", name=\"LumpPort\"):\n start, end = self.make_center_line(axis)\n self.modeler._make_lumped_port(\n start, end, [\"Objects:=\", [self]], z0=z0, name=name)\n\n\nclass Polyline(ModelEntity):\n '''\n Assume closed polyline, which creates a polygon.\n '''\n\n model_command = \"CreatePolyline\"\n\n def __init__(self, name, modeler, points=None):\n super(Polyline, self).__init__(name, modeler)\n self.prop_holder = modeler._modeler\n if points is not None:\n self.points = points\n self.n_points = len(points)\n else:\n pass\n # TODO: points = collection of points\n# axis = find_orth_axis()\n\n# TODO: find the plane of the polyline for now, assume Z\n# def find_orth_axis():\n# X, Y, Z = (True, True, True)\n# for point in points:\n# X =\n\n def unite(self, list_other):\n union = self.modeler.unite(self + list_other)\n return Polyline(union, self.modeler)\n\n def make_center_line(self, axis): # Expects to act on a rectangle...\n # first : find center and size\n center = [0, 0, 0]\n\n for point in self.points:\n center = [center[0]+point[0]/self.n_points,\n center[1]+point[1]/self.n_points,\n center[2]+point[2]/self.n_points]\n size = [2*(center[0]-self.points[0][0]),\n 2*(center[1]-self.points[0][1]),\n 2*(center[1]-self.points[0][2])]\n axis_idx = [\"x\", \"y\", \"z\"].index(axis.lower())\n start = [c for c in center]\n start[axis_idx] -= size[axis_idx]/2\n start = [self.modeler.eval_var_str(\n s, unit=LENGTH_UNIT) for s in start] # TODO\n end = [c for c in center]\n end[axis_idx] += size[axis_idx]/2\n end = [self.modeler.eval_var_str(s, unit=LENGTH_UNIT) for s in end]\n return start, end\n\n def make_rlc_boundary(self, axis, r=0, l=0, c=0, name=\"LumpRLC\"):\n name = str(self)+'_'+name\n start, end = self.make_center_line(axis)\n self.modeler._make_lumped_rlc(\n r, l, c, start, end, [\"Objects:=\", [self]], name=name)\n\n def fillet(self, radius, vertex_index):\n self.modeler._fillet(radius, vertex_index, self)\n\n def vertices(self):\n return self.modeler.get_vertex_ids(self)\n\n def rename(self, new_name):\n '''\n Warning: The increment_name only works if the sheet has not been stracted or used as a tool elsewhere.\n These names are not checked; they require modifying get_objects_in_group.\n\n '''\n new_name = increment_name(new_name, self.modeler.get_objects_in_group(\n \"Sheets\")) # this is for a clsoed polyline\n\n # check to get the actual new name in case there was a suibtracted ibjet with that namae\n face_ids = self.modeler.get_face_ids(str(self))\n self.modeler.rename_obj(self, new_name) # now rename\n if len(face_ids) > 0:\n new_name = self.modeler.get_object_name_by_face_id(face_ids[0])\n return Polyline(str(new_name), self.modeler)\n\n\nclass OpenPolyline(ModelEntity): # Assume closed polyline\n model_command = \"CreatePolyline\"\n show_direction = make_prop(\n 'Show Direction', prop_tab=\"Geometry3DAttributeTab\", prop_server=lambda self: self)\n\n def __init__(self, name, modeler, points=None):\n super(OpenPolyline, self).__init__(name, modeler)\n self.prop_holder = modeler._modeler\n if points is not None:\n self.points = points\n self.n_points = len(points)\n else:\n pass\n# axis = find_orth_axis()\n\n# TODO: find the plane of the polyline for now, assume Z\n# def find_orth_axis():\n# X, Y, Z = (True, True, True)\n# for point in points:\n# X =\n def vertices(self):\n return self.modeler.get_vertex_ids(self)\n\n def fillet(self, radius, vertex_index):\n self.modeler._fillet(radius, vertex_index, self)\n\n def fillets(self, radius, do_not_fillet=[]):\n '''\n do_not_fillet : Index list of verteces to not fillete\n '''\n raw_list_vertices = self.modeler.get_vertex_ids(self)\n list_vertices = []\n for vertex in raw_list_vertices[1:-1]: # ignore the start and finish\n list_vertices.append(int(vertex))\n list_vertices = list(map(int, np.delete(list_vertices,\n np.array(do_not_fillet, dtype=int)-1)))\n #print(list_vertices, type(list_vertices[0]))\n if len(list_vertices) != 0:\n self.modeler._fillets(radius, list_vertices, self)\n else:\n pass\n\n def sweep_along_path(self, to_sweep):\n return self.modeler._sweep_along_path(to_sweep, self)\n\n def rename(self, new_name):\n '''\n Warning: The increment_name only works if the sheet has not been stracted or used as a tool elsewher.\n These names are not checked - They require modifying get_objects_in_group\n '''\n new_name = increment_name(\n new_name, self.modeler.get_objects_in_group(\"Lines\"))\n # , self.points)\n return OpenPolyline(self.modeler.rename_obj(self, new_name), self.modeler)\n\n def copy(self, new_name):\n new_obj = OpenPolyline(self.modeler.copy(self), self.modeler)\n return new_obj.rename(new_name)\n\n\nclass HfssFieldsCalc(COMWrapper):\n def __init__(self, setup):\n \"\"\"\n :type setup: HfssSetup\n \"\"\"\n self.setup = setup\n super(HfssFieldsCalc, self).__init__()\n self.parent = setup\n self.Mag_E = NamedCalcObject(\"Mag_E\", setup)\n self.Mag_H = NamedCalcObject(\"Mag_H\", setup)\n self.Mag_Jsurf = NamedCalcObject(\"Mag_Jsurf\", setup)\n self.Mag_Jvol = NamedCalcObject(\"Mag_Jvol\", setup)\n self.Vector_E = NamedCalcObject(\"Vector_E\", setup)\n self.Vector_H = NamedCalcObject(\"Vector_H\", setup)\n self.Vector_Jsurf = NamedCalcObject(\"Vector_Jsurf\", setup)\n self.Vector_Jvol = NamedCalcObject(\"Vector_Jvol\", setup)\n self.ComplexMag_E = NamedCalcObject(\"ComplexMag_E\", setup)\n self.ComplexMag_H = NamedCalcObject(\"ComplexMag_H\", setup)\n self.ComplexMag_Jsurf = NamedCalcObject(\"ComplexMag_Jsurf\", setup)\n self.ComplexMag_Jvol = NamedCalcObject(\"ComplexMag_Jvol\", setup)\n self.P_J = NamedCalcObject(\"P_J\", setup)\n\n self.named_expression = {} # dictionary to hold additional named expressions\n\n def clear_named_expressions(self):\n self.parent.parent._fields_calc.ClearAllNamedExpr()\n\n def declare_named_expression(self, name):\n \"\"\"\"\n If a named epression has been created in the fields calculator, this\n function can be called to initialize the name to work with the fields object\n \"\"\"\n self.named_expression[name] = NamedCalcObject(name, self.setup)\n\n def use_named_expression(self, name):\n \"\"\"\n Expression can be used to access dictionary of named expressions,\n Alternately user can access dictionary directly via named_expression()\n \"\"\"\n return self.named_expression[name]\n\n\nclass CalcObject(COMWrapper):\n def __init__(self, stack, setup):\n \"\"\"\n :type stack: [(str, str)]\n :type setup: HfssSetup\n \"\"\"\n super(CalcObject, self).__init__()\n self.stack = stack\n self.setup = setup\n self.calc_module = setup.parent._fields_calc\n\n def _bin_op(self, other, op):\n if isinstance(other, (int, float)):\n other = ConstantCalcObject(other, self.setup)\n\n stack = self.stack + other.stack\n stack.append((\"CalcOp\", op))\n return CalcObject(stack, self.setup)\n\n def _unary_op(self, op):\n stack = self.stack[:]\n stack.append((\"CalcOp\", op))\n return CalcObject(stack, self.setup)\n\n def __add__(self, other):\n return self._bin_op(other, \"+\")\n\n def __radd__(self, other):\n return self + other\n\n def __sub__(self, other):\n return self._bin_op(other, \"-\")\n\n def __rsub__(self, other):\n return (-self) + other\n\n def __mul__(self, other):\n return self._bin_op(other, \"*\")\n\n def __rmul__(self, other):\n return self*other\n\n def __div__(self, other):\n return self._bin_op(other, \"/\")\n\n def __rdiv__(self, other):\n other = ConstantCalcObject(other, self.setup)\n return other/self\n\n def __pow__(self, other):\n return self._bin_op(other, \"Pow\")\n\n def dot(self, other):\n return self._bin_op(other, \"Dot\")\n\n def __neg__(self):\n return self._unary_op(\"Neg\")\n\n def __abs__(self):\n return self._unary_op(\"Abs\")\n\n def __mag__(self):\n return self._unary_op(\"Mag\")\n\n def mag(self):\n return self._unary_op(\"Mag\")\n\n def smooth(self):\n return self._unary_op(\"Smooth\")\n\n def conj(self):\n return self._unary_op(\"Conj\") # make this right\n\n def scalar_x(self):\n return self._unary_op(\"ScalarX\")\n\n def scalar_y(self):\n return self._unary_op(\"ScalarY\")\n\n def scalar_z(self):\n return self._unary_op(\"ScalarZ\")\n\n def norm_2(self):\n\n return (self.__mag__()).__pow__(2)\n # return self._unary_op(\"ScalarX\")**2+self._unary_op(\"ScalarY\")**2+self._unary_op(\"ScalarZ\")**2\n\n def real(self):\n return self._unary_op(\"Real\")\n\n def imag(self):\n return self._unary_op(\"Imag\")\n\n def complexmag(self):\n return self._unary_op(\"CmplxMag\")\n\n def _integrate(self, name, type):\n stack = self.stack + [(type, name), (\"CalcOp\", \"Integrate\")]\n return CalcObject(stack, self.setup)\n\n def _maximum(self, name, type):\n stack = self.stack + [(type, name), (\"CalcOp\", \"Maximum\")]\n return CalcObject(stack, self.setup)\n\n def getQty(self, name):\n stack = self.stack + [(\"EnterQty\", name)]\n return CalcObject(stack, self.setup)\n\n def integrate_line(self, name):\n return self._integrate(name, \"EnterLine\")\n\n def integrate_line_tangent(self, name):\n ''' integrate line tangent to vector expression \\n\n name = of line to integrate over '''\n self.stack = self.stack + [(\"EnterLine\", name),\n (\"CalcOp\", \"Tangent\"),\n (\"CalcOp\", \"Dot\")]\n return self.integrate_line(name)\n\n def line_tangent_coor(self, name, coordinate):\n ''' integrate line tangent to vector expression \\n\n name = of line to integrate over '''\n if coordinate not in ['X', 'Y', 'Z']:\n raise ValueError\n self.stack = self.stack + [(\"EnterLine\", name),\n (\"CalcOp\", \"Tangent\"),\n (\"CalcOp\", \"Scalar\"+coordinate)]\n return self.integrate_line(name)\n\n def integrate_surf(self, name=\"AllObjects\"):\n return self._integrate(name, \"EnterSurf\")\n\n def integrate_vol(self, name=\"AllObjects\"):\n return self._integrate(name, \"EnterVol\")\n\n def maximum_vol(self, name='AllObjects'):\n return self._maximum(name, 'EnterVol')\n\n def times_eps(self):\n stack = self.stack + [(\"ClcMaterial\", (\"Permittivity (epsi)\", \"mult\"))]\n return CalcObject(stack, self.setup)\n\n def times_mu(self):\n stack = self.stack + [(\"ClcMaterial\", (\"Permeability (mu)\", \"mult\"))]\n return CalcObject(stack, self.setup)\n\n def write_stack(self):\n for fn, arg in self.stack:\n if np.size(arg) > 1 and fn not in ['EnterVector']:\n getattr(self.calc_module, fn)(*arg)\n else:\n getattr(self.calc_module, fn)(arg)\n\n def save_as(self, name):\n \"\"\"if the object already exists, try clearing your\n named expressions first with fields.clear_named_expressions\"\"\"\n self.write_stack()\n self.calc_module.AddNamedExpr(name)\n return NamedCalcObject(name, self.setup)\n\n def evaluate(self, phase=0, lv=None, print_debug=False): # , n_mode=1):\n self.write_stack()\n if print_debug:\n print('---------------------')\n print('writing to stack: OK')\n print('-----------------')\n #self.calc_module.set_mode(n_mode, 0)\n setup_name = self.setup.solution_name\n\n if lv is not None:\n args = lv\n else:\n args = []\n\n args.append(\"Phase:=\")\n args.append(str(int(phase)) + \"deg\")\n\n if isinstance(self.setup, HfssDMSetup):\n args.extend([\"Freq:=\", self.setup.solution_freq])\n\n self.calc_module.ClcEval(setup_name, args)\n return float(self.calc_module.GetTopEntryValue(setup_name, args)[0])\n\n\nclass NamedCalcObject(CalcObject):\n def __init__(self, name, setup):\n self.name = name\n stack = [(\"CopyNamedExprToStack\", name)]\n super(NamedCalcObject, self).__init__(stack, setup)\n\n\nclass ConstantCalcObject(CalcObject):\n def __init__(self, num, setup):\n stack = [(\"EnterScalar\", num)]\n super(ConstantCalcObject, self).__init__(stack, setup)\n\n\nclass ConstantVecCalcObject(CalcObject):\n def __init__(self, vec, setup):\n stack = [(\"EnterVector\", vec)]\n super(ConstantVecCalcObject, self).__init__(stack, setup)\n\n\ndef get_active_project():\n ''' If you see the error:\n \"The requested operation requires elevation.\"\n then you need to run your python as an admin.\n '''\n import ctypes\n import os\n try:\n is_admin = os.getuid() == 0\n except AttributeError:\n is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0\n if not is_admin:\n print('\\033[93m WARNING: you are not runnning as an admin! \\\n You need to run as an admin. You will probably get an error next.\\\n \\033[0m')\n\n app = HfssApp()\n desktop = app.get_app_desktop()\n return desktop.get_active_project()\n\n\ndef get_active_design():\n project = get_active_project()\n return project.get_active_design()\n\n\ndef get_report_arrays(name: str):\n d = get_active_design()\n r = HfssReport(d, name)\n return r.get_arrays()\n\n\ndef load_ansys_project(proj_name: str, project_path: str = None, extension: str = '.aedt'):\n '''\n Utility function to load an Ansys project.\n\n Args:\n proj_name : None --> get active. (make sure 2 run as admin)\n extension : `aedt` is for 2016 version and newer\n '''\n if project_path:\n # convert slashes correctly for system\n project_path = Path(project_path)\n\n # Checks\n assert project_path.is_dir(), \"ERROR! project_path is not a valid directory \\N{loudly crying face}.\\\n Check the path, and especially \\\\ charecters.\"\n\n project_path /= project_path / Path(proj_name + extension)\n\n if (project_path).is_file():\n logger.info('\\tFile path to HFSS project found.')\n else:\n raise Exception(\n \"ERROR! Valid directory, but invalid project filename. \\N{loudly crying face} Not found!\\\n Please check your filename.\\n%s\\n\" % project_path)\n\n if (project_path/'.lock').is_file():\n logger.warning(\n '\\t\\tFile is locked. \\N{fearful face} If connection fails, delete the .lock file.')\n\n app = HfssApp()\n logger.info(\"\\tOpened Ansys App\")\n\n desktop = app.get_app_desktop()\n logger.info(f\"\\tOpened Ansys Desktop v{desktop.get_version()}\")\n #logger.debug(f\"\\tOpen projects: {desktop.get_project_names()}\")\n\n if proj_name is not None:\n if proj_name in desktop.get_project_names():\n desktop.set_active_project(proj_name)\n project = desktop.get_active_project()\n else:\n project = desktop.open_project(str(project_path))\n else:\n project = desktop.get_active_project()\n logger.info(\n f\"\\tOpened Ansys Project\\n\\tFolder: {project.get_path()}\\n\\tProject: {project.name}\")\n\n return app, desktop, project\n" ]
[ [ "pandas.read_csv", "numpy.genfromtxt", "numpy.size", "numpy.shape", "numpy.array", "numpy.loadtxt" ] ]
marvinquiet/bart2
[ "f158bb4fcfc21aabe6f0b2a665911e2b6a4e5a7d" ]
[ "bart2/RPRegress.py" ]
[ "import argparse,math,os,sys,tables\nimport numpy as np\nfrom operator import itemgetter\nfrom sklearn import linear_model, model_selection, metrics\nimport random\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\nUNCHANGED,DOWN,UP,TARGET = 0,1,2,3\nstatdict = { UNCHANGED:'.', DOWN:'DOWN', UP:'UP', TARGET:'TARGET' }\n\nclass dataset(object):\n def __init__(self):\n self.index = None\n self.info = None # include chrom and TSS and gene symbol\n self.x = None\n self.y = None\n self.bwdir = None \n self.bwfiles = None\n self.rpfiles = None \n\ndef gene_sym(symfile):\n \"\"\"\n One representative of each gene symbol is chosen. \n\n \"\"\"\n # TODO: change the selection from the first to the longest gene body\n\n # return {\"refseq\":[\"symbol\",\"chr\"]}\n fp = open(symfile)\n symdict = {} # {\"gene_symbol\": [\"refseq_ID\", \"chr\"]} the first refseq ID in the TSS file\n\n for line in fp:\n f = line.strip().split('\\t')\n g = f[3]\n IDs = g.split(':')\n if IDs[1] not in symdict:\n symdict[IDs[1]] = [IDs[0], f[0]]\n \n rsymdict = {}\n for elem in symdict:\n rsymdict[symdict[elem][0]] = [elem,symdict[elem][1]]\n fp.close()\n\n return rsymdict\n\ndef logtransform(x):\n xt = np.array(x)\n pcount = 1\n xt += pcount \n med = np.median( xt,0 )\n x = np.log2(xt) - np.log2(med)\n return x\n\ndef sqrttransform(x):\n xt = np.array(x)\n med = np.median( xt,0 )\n x = np.sqrt(xt) - np.sqrt(med)\n return x\n\ndef read_hdf5( h5file, sample_name):\n \"\"\" Apply motif stat function to all data in motif_file_name. \n Data in numpy array val corresponds to idx entries. If idx if None all entries are used.\"\"\" \n a = h5file.get_node(\"/\", sample_name )\n m = a.read()\n return m\n\ndef getSampleNames_hdf5(h5file):\n samplenames = []\n for array in h5file.walk_nodes(\"/\",\"Array\"):\n if array.name not in samplenames:\n samplenames.append(array.name)\n else:\n continue\n #samplenames = samplenames[340:]\n return samplenames\n\ndef readregpotfiles(sym,genome,samplenames,h5file):\n\n # make list of regulatory potential file\n # read in regulatory potential from files in directory \n\n index = None\n x = None\n nsamples = len(samplenames)\n\n refseqID = read_hdf5( h5file, 'refseqID' )\n print(refseqID)\n symID = read_hdf5(h5file, 'symbol')\n print(symID)\n chrom = read_hdf5(h5file, 'chr')\n start = read_hdf5(h5file, 'start')\n for k,name in enumerate(samplenames):\n if index == None:\n index = {}\n info = {}\n i = 0\n for j,geneid in enumerate(refseqID):\n geneid = geneid.decode(\"utf-8\") # gene symbol\n if geneid in sym:\n symid = sym[geneid][0]\n if symid not in index:\n index[symid] = i\n info[symid] = [chrom[j].decode(\"utf-8\"),start[j]]\n i += 1\n ngenes = len(index)\n x = np.zeros((ngenes,nsamples))\n print(np.shape(x))\n \n RP = read_hdf5( h5file, name )\n for i,geneid in enumerate(refseqID):\n geneid = geneid.decode(\"utf-8\")\n if geneid in sym:\n symid = sym[geneid][0]\n rp = RP[i]\n try:\n x[index[symid],k] = rp ### float num was ignored here, e.g., 'chr', 'refseqID', 'start', 'symbol'\n except:\n pass\n \n z = dataset() \n z.rpfiles = samplenames \n z.x = x # x.shape = ngenes,nsamples # x is RP not relative RP, change to relative RP\n print(np.median(x, axis=1))\n\n z.index = index # {symbol:'start position'}\n z.info = info # {'symbol':[chr,start]}\n return z\n\n\ndef read_genelistOnly(sym, fname, index, exptype):\n \n status = np.zeros( len(index) )\n genenames = np.ndarray(shape=(len(index)),dtype=object)\n print(list(index.keys())[0:20])\n\n train_chroms = ['chr1','chr3','chr5','chr7','chr9','chr11','chr13','chr15','chr17','chr19','chr21']\n test_chroms = ['chr2','chr4','chr6','chr8','chr10','chr12','chr14','chr16','chr18','chr20','chr22']\n train_index = []\n test_index = []\n\n fp = open(fname).readlines()\n genes = [g.strip() for g in fp]\n\n allgenes = list(sym.keys())\n print(allgenes[0:20])\n\n for ag in allgenes:\n if exptype == 'Gene_Only':\n try:\n i = index[sym[ag][0]]\n if sym[ag][1] in train_chroms:\n train_index.append(i)\n elif sym[ag][1] in test_chroms:\n test_index.append(i)\n #print i\n if sym[ag][0] in genes:\n #print sym[ag][0]\n status[i] = TARGET\n else:\n status[i] = UNCHANGED\n genenames[i] = ag\n except:\n continue\n else:\n try:\n i = index[sym[ag][0]]\n if sym[ag][1] in train_chroms:\n train_index.append(i)\n elif sym[ag][1] in test_chroms:\n test_index.append(i)\n else:\n pass\n if ag in genes:\n status[i] = TARGET\n else:\n status[i] = UNCHANGED\n genenames[i] = ag\n except:\n continue\n\n print('file: %s\\ttarget: %d\\tunchanged: %d\\n' % ( fname, sum( status == TARGET ), sum( status == UNCHANGED ) ))\n # print(genenames[0:20])\n return (genenames, status,train_index,test_index) \n\ndef dataset_annotation(annotationf):\n # get the cell annotation for each datasetID\n inf = open(annotationf,'rU')\n ann = {}\n for line in inf:\n if line.startswith('datasetID'):\n pass\n else:\n line = line.strip().split('\\t')\n ID = line[0] # dataset id -> GSM id\n info = [line[4],line[5],line[7]] # CellLineName, Tissue/Organ, DetailedTissue\n try:\n ann[ID] = info\n except:\n ann[ID] = 'NA'\n return ann\n\ndef lasso_test(x,y):\n # given x,y, return auc score\n LR_l1 = linear_model.LogisticRegression(penalty='l1', tol=0.01)\n LR_l1.fit(x,y)\n #np.mean( model_selection.cross_val_score( LR_l1, X_train, y_train, scoring='roc_auc', cv=5 ))\n yhat = LR_l1.predict_log_proba(x)\n fpr, tpr, thresholds = metrics.roc_curve(y, yhat[:,1], pos_label=1)\n auc = metrics.auc(fpr,tpr)\n selected_features = len([i for i in LR_l1.coef_[0] if i !=0])\n return auc,selected_features\n \ndef lasso_test_best_alpha(x,y,prename):\n # given x,y, return alpha used for adaptive lasso\n alphas = [i for i in np.logspace(-2,1,10)]\n alpha_cvs = []\n plt.figure()\n for alpha in alphas:\n LR_l1 = linear_model.LogisticRegression(penalty='l1', tol=0.01,fit_intercept=True,C=alpha);print(alpha)\n cvs_scores = model_selection.cross_val_score( LR_l1, x, y, scoring='roc_auc', cv=5 )\n alpha_cvs.append(cvs_scores)\n \n LR_l1.fit(x,y)\n yhat = LR_l1.predict_log_proba(x)\n fpr, tpr, thresholds = metrics.roc_curve(y, yhat[:,1], pos_label=1)\n auc = metrics.auc(fpr,tpr)\n selected_features = len([i for i in estimator.coef_[0] if i !=0])\n print(alpha,np.mean(cvs_scores),auc,selected_features)\n # plot the auc figs\n y_mean = np.mean(cvs_scores)\n y_err = np.std(cvs_scores)\n plt.errorbar(alpha,y_mean,y_err,color='r',ecolor='grey',fmt='o',capsize=4)\n plt.ylim([0,1])\n plt.xscale('log')\n plt.savefig(prename+'_alpha_auc.png',bbox_inches='tight',pad_inches=0.1,transparent=True)\n plt.close()\n #alpha_cvs_mean = [i.mean() for i in alpha_cvs]\n #best_alpha = alphas[alpha_cvs_mean.index(max(alpha_cvs_mean))]\n return alphas,alpha_cvs\n\n\ndef best_alpha(x,y):\n # given x,y, return alpha used for adaptive lasso\n alphas = [i for i in np.logspace(-2,1,10)]\n #alphas = [0.005,0.01,0.02,0.05,0.1,0.2,0.5,1,2]\n alpha_cvs = []\n \n for alpha in alphas:\n LR_l1 = linear_model.LogisticRegression(penalty='l1', tol=0.01,fit_intercept=True,C=alpha)\n cvs_scores = model_selection.cross_val_score( LR_l1, x, y, scoring='roc_auc', cv=5 )\n alpha_cvs.append(cvs_scores) \n print(' =best-alpha= ',alpha, '==mean-cvs==',np.mean(cvs_scores))\n alpha_cvs_mean = [i.mean() for i in alpha_cvs]\n best_alpha = alphas[alpha_cvs_mean.index(max(alpha_cvs_mean))]\n \n return best_alpha,max(alpha_cvs_mean)\n\n\ndef adaptive_lasso(x,y,samplefiles,name,maxsamples,ann,genenames):\n # test of adaptive lasso\n g = lambda w:np.sqrt(np.abs(w))\n gprime = lambda w: 1.0/(2.*np.sqrt(np.abs(w))+np.finfo(float).eps)\n n_samples,n_features = x.shape\n \n n_lasso_iterations = 10\n weights = np.ones(n_features)\n selected_features = n_features\n \n print('Run adaptive lasso for 10 rounds...')\n print('Round, Alpha, Features number ')\n for k in range(n_lasso_iterations):\n if selected_features >maxsamples: \n alpha=0.02\n else:\n alpha=0.2\n X_w = x / weights\n #alpha,best_cvs = best_alpha(X_w,y) # TODO: if you need to select best alpha for each step later\n #alpha = 0.1\n\n # set fixed seed and default solver\n estimator = linear_model.LogisticRegression(penalty='l1', tol=0.01, fit_intercept=True, C=alpha, random_state=2019, solver=\"liblinear\")\n estimator.fit(X_w,y)\n coef_ = estimator.coef_/weights\n weights = gprime(coef_)\n selected_features = len([i for i in coef_[0] if i !=0])\n print('{}, {}, {}'.format(k,alpha,selected_features))\n\n rand_idx = list(range(x.shape[0]))\n random.shuffle( rand_idx )\n # xt = np.multiply(x,coef_);print(xt.shape)\n xt,yt = X_w[rand_idx,:], y[rand_idx]\n cvs_scores = model_selection.cross_val_score(estimator ,xt,yt, scoring='roc_auc', cv=5 )\n best_cvs = np.mean(cvs_scores)\n yhat = estimator.predict_log_proba(xt)\n fpr, tpr, thresholds = metrics.roc_curve(yt, yhat[:,1], pos_label=1)\n auc = metrics.auc(fpr,tpr)\n \n# print(k,'alpha',alpha)\n# print(k,'best_cvs',best_cvs)\n# print(k,'auc',auc)\n# print(k,'selected_features',selected_features)\n\n outf = open('{}_adaptive_lasso_Info.txt'.format(name),'w')\n for coef in sorted([ i for i in coef_[0] if i!=0], key=abs, reverse=True):\n samplefile = samplefiles[list(coef_[0]).index(coef)]\n dataID = samplefile.split('_')[0]\n if dataID in list(ann.keys()):\n annInfo = ann[dataID]\n else:\n annInfo = ['NA','NA','NA']\n outf.write('{}\\t{}\\t{}\\n'.format(dataID, coef, '\\t'.join(annInfo)))\n\n outf.write('AUC = {}\\n'.format(auc))\n outf.write('best_cvs = {}\\n'.format(best_cvs))\n outf.write('selected_features = {}\\n'.format(selected_features))\n return auc,selected_features\n\ndef main(args):\n '''\n Input arguments from command line.\n\n '''\n # read all parameters from arguments\n gxfile = args.expr # input gene symbols/refseqID\n name = args.name # output name\n exptype = args.exptype\n\n genome = args.genome # species\n symfile = args.sym\n annotation = args.annotation\n\n rp_hdf5 = args.histRP\n transform = args.transform\n\n maxsamples = args.maxsamples\n\n # TODO: symfile is the refseqID annotation file, change to gene symbol file?\n sym = gene_sym(symfile) # {\"resfseq\": {\"gene_symbol\", \"chr\"}}\n\n h5file = tables.open_file( rp_hdf5, driver=\"H5FD_CORE\")\n samplenames = getSampleNames_hdf5(h5file)\n z = readregpotfiles(sym,genome,samplenames,h5file)\n h5file.close()\n \n if transform == 'log':\n z.x = logtransform(z.x)\n if transform == 'sqrt':\n z.x = sqrttransform(z.x)\n\n (genenames,z.y,train_index,test_index) = read_genelistOnly(sym, gxfile, z.index, exptype)\n\n sys.stdout.flush()\n print('Do regrssion with TARGET genes...')\n y = 1*( z.y == TARGET )\n\n x = z.x[:,:-5] # remove the last few columns: refseq, start, chr, etc...\n print(\"Adaptive lasso RP matrix shape...\")\n print(\"{}\\n\".format(np.shape(x)))\n ann = dataset_annotation(annotation)\n try:\n auc,selected_features = adaptive_lasso(x,y,z.rpfiles,name,maxsamples,ann,genenames)\n except:\n pass\n finally:\n sys.stderr.write(\"\"\"\\nERROR: bart2 exited with errors!\nPlease check whether you selected the correct species or uploaded the correct gene list!\\n\"\"\")\n sys.exit(1)\n\n print(\"Adaptive lasso regression AUC score and selected features...\")\n print(auc)\n print(selected_features)\n sys.stdout.flush()\n \nif __name__ == \"__main__\":\n try:\n parser = argparse.ArgumentParser(description=\"\"\"Regression of regulatory potential to gene expression changes.\"\"\")\n # related to input file type\n parser.add_argument( '-e','--expr', dest='expr', required = True, type = str, help = 'The related differential expression file')\n parser.add_argument( '--exptype', dest='exptype', required = True, choices=['Gene_Response','Gene_Only'], type = str, \\\n help = 'Gene_Response includes 2 columns, one is the geneID, and the other is 1/0, 1 for target and 0 for un-target; \\\n Gene_Only includes 1 column, only the gene list of the targets. \\\n Only official gene symbol or refseqID are allowd for the geneID.')\n\n parser.add_argument( '-r','--historicalRP', dest='histRP', required = True, type = str, \\\n help = 'The file with hdf5 format which contain the H3K27ac RP information')\n # transform method\n parser.add_argument('-t', '--transform', dest=\"transform\", type=str, default='sqrt', choices=['sqrt', 'log'], required=True, \\\n help='Use sqrt transform or log transform on RP ')\n parser.add_argument( '-a', dest='annotation', required=True, type=str, help='The annotation file for each dataset' )\n\n parser.add_argument( '-m', dest='sym', type=str, required=True, help='refseqTSS is six columns: <chromosome name> <TSS> <TSS+1> <refseq:genesymbok> <score> <strand>')\n # parser.add_argument( '-m', dest='sym', type=str, required=True, help='genesymbolTSS is six columns: <chromosome name> <TSS-1> <TSS+1> <genesymbol> <score> <strand>')\n parser.add_argument( '-g','--genome', dest=\"genome\", type=str, default='hg38', choices=['mm9','hg19','hg38','mm10'], required=False, help='genome')\n parser.add_argument( '--maxsamples', dest='maxsamples', type=int, default=20, required=False, \\\n help='Maximum number of samples to include in regression model.' )\n parser.add_argument( '-a', dest='annotation', required=True, type=str, help='The annotation file for each dataset' )\n\n parser.add_argument( '-n','--name', dest='name',required = True, type = str, help = 'The prefix of the output names')\n\n args = parser.parse_args()\n main(args)\n\n except KeyboardInterrupt:\n sys.stderr.write(\"User interrupted me!\\n\")\n sys.exit(0)\n" ]
[ [ "numpy.sqrt", "numpy.mean", "numpy.finfo", "numpy.std", "matplotlib.pyplot.errorbar", "matplotlib.pyplot.close", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.logspace", "matplotlib.pyplot.ylim", "numpy.median", "sklearn.metrics.roc_curve", "matplotlib.pyplot.savefig", "sklearn.metrics.auc", "numpy.array", "numpy.log2", "sklearn.model_selection.cross_val_score", "sklearn.linear_model.LogisticRegression", "numpy.abs", "matplotlib.use", "numpy.ones", "numpy.shape", "matplotlib.pyplot.xscale" ] ]
iclr2022submission4/cgca
[ "3e6ea65c0ebf72a8291dde3ffdb06b50e4d2900a" ]
[ "utils/marching_cube.py" ]
[ "import mcubes\nimport torch\nimport trimesh\n\ndef marching_cube(\n query_points: torch.Tensor,\n df: torch.Tensor,\n march_th,\n upsample=1,\n voxel_size=None\n):\n \"\"\"\n Args:\n query_points: (N, 3) torch tensor\n df: (N) torch tensor\n march_th: threshold for marching cube algorithm\n upsample: required for upsampling the resolution of the marching cube\n\n Returns:\n mesh (trimesh object): obtained mesh from marching cube algorithm\n \"\"\"\n df_points = query_points.clone().detach().cpu()\n offset = df_points.min(dim=0).values\n df_points = df_points - offset\n df_coords = torch.round(upsample * df_points).long() + 1\n march_bbox = df_coords.max(dim=0).values + 2 # out max\n voxels = torch.ones(march_bbox.tolist()).to(df.device)\n voxels[df_coords[:, 0], df_coords[:, 1], df_coords[:, 2]] = df.clone().detach().cpu()\n\n v, t = mcubes.marching_cubes(voxels.cpu().detach().numpy(), march_th)\n v = (v - 1) / upsample\n v += offset.cpu().numpy()\n if voxel_size is not None:\n v *= voxel_size\n mesh = trimesh.Trimesh(v, t)\n return mesh\n\n\ndef marching_cubes_sparse_voxel(coord: torch.Tensor, voxel_size=None):\n return marching_cube(\n query_points=coord.float(),\n df=torch.zeros(coord.shape[0]),\n march_th=0.5,\n upsample=1,\n voxel_size=voxel_size\n )\n\ndef marching_cubes_occ_grid(occ: torch.Tensor, threshold=0.5, scale=None):\n \"\"\"\n :param occ: tensor H x W x D\n :param scale: tuple of scale_min, scale_max\n :return: normalized mesh, where each vertices are in [0, 1]\n \"\"\"\n grid_shape = torch.tensor(occ.shape) + 2\n padded_grid = torch.zeros(grid_shape.tolist())\n padded_grid[1:-1, 1:-1, 1:-1] = occ\n v, t = mcubes.marching_cubes(padded_grid.cpu().detach().numpy(), threshold)\n v = (v - 1) / (occ.shape[0] - 1)\n\n if scale is not None:\n scale_min, scale_max = scale[0], scale[1]\n v = (scale_max - scale_min) * v\n v = v + scale_min\n return trimesh.Trimesh(v, t)\n\n" ]
[ [ "torch.round", "torch.zeros", "torch.tensor" ] ]
jeffra/triton
[ "3195aca4522377ca6eabf4f9ca9054fa245bbba0" ]
[ "python/examples/einsum.py" ]
[ "import triton\nimport torch\nfrom torch.utils.cpp_extension import load\nimport numpy as np\n#import utils\nfrom time import time\n\ntorch.manual_seed(0)\n\n#torch.backends.cudnn.benchmark = True\n\nconfigs = []\n\n# Matrix multiplication\nMNK = [\n (512, 512 ,512), \n (2048, 2048, 2048),\n #(8192, 8192, 8192),\n \n (64, 64, 64000),\n (64, 64, 128000),\n (256, 256, 64000),\n (256, 256, 128000),\n\n (1536, 16, 1536),\n (1536, 32, 1536),\n (1536, 64, 1536),\n # (1536, 128, 1536),\n # (4096, 16, 4096),\n # (4096, 32, 4096),\n # (4096, 64, 4096),\n # (4096, 128, 4096),\n \n # (127008, 768, 576) \n ]\nfor M, N, K in MNK:\n matmul = lambda a, b: torch.matmul(a, b)\n configs += [([M, K], [K, N], [M, N], matmul, 'mk,kn->mn', dict(), None, None, None)]\n#for M, N, K in MNK:\n# matmul = lambda a, b: torch.matmul(a.t(), b)\n# configs += [([M, K], [M, N], [K, N], None, 'mk,mn->kn', dict(), None, None, None)]\n#for M, N, K in MNK:\n# matmul = lambda a, b: torch.matmul(a, b.t())\n# configs += [([M, N], [K, N], [M, K], None, 'mn,kn->mk', dict(), None, None, None)]\n\n# Relative attention\nNTHSE = [\n (16, 512, 1, 64, 64), \n # (16, 512, 1, 128, 128),\n # (16, 512, 1, 256, 256),\n # (16, 512, 1, 256, 512),\n (16, 512, 8, 64, 64), \n # (16, 512, 8, 128, 128),\n # (16, 512, 8, 256, 256),\n # (16, 512, 8, 256, 512),\n\n # (64, 1024, 1, 64, 64), \n (64, 1024, 1, 128, 128),\n # (64, 1024, 1, 256, 256),\n # (64, 1024, 1, 256, 512),\n # (64, 1024, 8, 64, 64), \n (64, 1024, 8, 128, 128),\n # (64, 1024, 8, 256, 256),\n # (64, 1024, 8, 256, 512),\n\n # (128, 1024, 1, 64, 64), \n # (128, 1024, 1, 128, 128),\n # (128, 1024, 1, 256, 256),\n (128, 1024, 1, 256, 512),\n # (128, 1024, 8, 64, 64), \n # (128, 1024, 8, 128, 128),\n # (128, 1024, 8, 256, 256),\n #(128, 1024, 8, 256, 512)\n ]\n#for N, T, H, S, E in NTHSE:\n# configs += [([N, T, H, S], [H, E, S], [N, H, T, E], None, 'nths,hes->nhte', dict(), None, None, None)]\n#for N, T, H, S, E in NTHSE:\n# configs += [([N, H, T, E], [N, T, H, S], [H, E, S], None, 'nhte,nths->hes', dict(), None, None, None)]\n#for N, T, H, S, E in NTHSE:\n# configs += [([N, H, T, E], [H, E, S], [N, T, H, S], None, 'nhte,hes->nths', dict(), None, None, None)]\n\n# 1D Dense convolution\nNCHKR = [\n #(1, 1152, 12602, 512, 3)\n ]\nfor N, C, H, K, R in NCHKR:\n torch_fn = lambda a, b: torch.nn.functional.conv1d(a, b.permute(2, 0, 1))\n configs += [([N, C, H], \n [C, R, K], \n [N, K, H - R + 1], \n torch_fn, \n 'nc(h+r),crk->nkh',\n dict(), None, None, None)]\n\n# 2D Dense convolution\nNCHWKRS = [\n #(8, 64, 128, 128, 768, 3, 3),\n #(128, 3, 32, 32, 64, 3, 3),\n #(1, 1024, 32, 112, 112, 1024, 3, 3),\n #(8, 512, 32, 32, 1024, 3, 3)\n ]\nfor N, C, G, H, W, K, R, S in NCHWKRS:\n stride = 2\n torch_fn = lambda a, b: torch.nn.functional.conv2d(a, b.permute(3, 0, 1, 2), stride=stride, groups=G)\n P = (H - R + 1) // stride\n Q = (W - S + 1) // stride\n transform_a = lambda a: a.view(N, G, C // G, H, W)\n transform_b = lambda b: b.view(C // G, R, S, G, K // G)\n transform_c = lambda c: c.view(N, K, P, Q)\n configs += [([N, C, H, W], \n [C // G, R, S, K], \n [N, G, K // G, P, Q], \n torch_fn, \n 'ngc(h*2+r)(w*2+s),crsgk->ngkhw',\n dict(), transform_a, transform_b, transform_c)]\n\n\n# 3D Dense Convolution\nNCDHWKTRS = [\n #(8, 32, 27, 100, 100, 64, 3, 3, 3),\n #(8, 64, 23, 48, 48, 256, 3, 3, 3),\n #(8, 256, 19, 22, 22, 640, 3, 3, 3),\n #(8, 640, 15, 36, 36, 384, 3, 3, 3)\n ]\nfor N, C, D, H, W, K, T, R, S in NCDHWKTRS:\n torch_fn = lambda a, b: torch.nn.functional.conv3d(a, b.permute(4, 0, 1, 2, 3))\n configs += [([N, C, D, H, W], \n [C, T, R, S, K], \n [N, K, D - T + 1, H - R + 1, W - R + 1], \n torch_fn, \n 'nc(d+t)(h+r)(w+s),ctrsk->nkdhw',\n dict(), None, None, None)]\n\n\n# Shift convolution\nshift_cuda = torch.utils.cpp_extension.load(\n 'shift_cuda', ['kernels/shift_cuda.cpp', \n 'kernels/shift_cuda_kernel.cu'],\n extra_cflags=['-O3'])\nclass shift(torch.autograd.Function):\n @staticmethod\n def forward(ctx, x, shift):\n ctx.save_for_backward(shift)\n return shift_cuda.forward(x, shift)\n\n @staticmethod\n def backward(ctx, grad_output):\n shift, = ctx.saved_tensors\n grad_output = shift_cuda.backward(grad_output, shift)\n\n return grad_output, None\n\nNCHWKRS = [\n #(8, 64, 128, 128, 128, 3, 3),\n #(8, 128, 64, 64, 256, 3, 3),\n #(8, 256, 32, 32, 512, 3, 3),\n #(8, 512, 32, 32, 1024, 3, 3)\n ]\nfor N, C, H, W, K, R, S in NCHWKRS:\n shift_h = np.random.randint(R, size=C, dtype=np.int32) - R//2\n shift_w = np.random.randint(S, size=C, dtype=np.int32) - S//2\n def shift_conv(a, b, **kwargs):\n shift_h, shift_w = kwargs['sh'], kwargs['sw']\n shift_torch = np.column_stack((shift_w*-1, shift_h*-1))\n shift_torch = torch.from_numpy(shift_torch).cuda()\n a = shift.apply(a, shift_torch)\n b = b.permute(1, 0)\n b = b.reshape(b.shape[0], b.shape[1], 1, 1)\n return torch.nn.functional.conv2d(a, b)\n configs += [([N, C, H, W], \n [C, K], \n [N, K, H, W], \n shift_conv, \n 'nc(h + sh[c])(w + sw[c]),ck->nkhw',\n {'sh': shift_h, 'sw': shift_w},\n None, None, None)]\n\n# Benchmark\ntorch.set_num_threads(1)\nfor a_shape, b_shape, c_shape, torch_fn, expr, arrays, \\\n transform_a, transform_b, transform_c in configs:\n dtype = torch.cuda.FloatTensor\n # initialize input tensors\n a = torch.rand(*a_shape).type(dtype).cuda()\n b = torch.rand(*b_shape).type(dtype).cuda()\n # reference output\n if torch_fn:\n rc = torch_fn(a, b, **arrays)\n else:\n rc = torch.einsum(expr, a, b)\n # triton output\n ta = a if transform_a is None else transform_a(a)\n tb = b if transform_b is None else transform_b(b)\n tc = torch.empty(c_shape, device=a.device)\n triton.ops.einsum(expr, ta, tb, tc, arrays = arrays, bench = True)\n ctx = triton.ops._einsum.registry[tc]\n tc = tc if transform_c is None else transform_c(tc)\n # performance relative to equivalent matrix multiplication\n B, M, N, K = ctx.matmul_B, ctx.matmul_M, ctx.matmul_N, ctx.matmul_K\n cmp_eqbmm = True\n if cmp_eqbmm:\n a = torch.rand(B, M, K).type(dtype).cuda()\n b = torch.rand(B, K, N).type(dtype).cuda()\n c = torch.empty((B, M, N), device=a.device).cuda()\n tmmc = triton.ops.einsum('bmk,bkn->bmn', a, b, c, bench = True)\n ratio = triton.ops._einsum.registry[tmmc].forward_ms / ctx.forward_ms\n cmp_str = f'({ratio:4.2f})'\n else:\n cmp_str = ''\n # test and benchmark\n bench = 2. * B * M * N * K / ctx.forward_ms * 1e-3\n diff = (tc - rc).abs().max() / rc.abs().max()\n print(f'{expr:>15}; {str(a_shape):>20}; {str(b_shape):>20}; {bench:4.2f} {cmp_str}; {diff:4.2f}')\n" ]
[ [ "torch.utils.cpp_extension.load", "torch.empty", "torch.manual_seed", "torch.nn.functional.conv2d", "torch.einsum", "torch.from_numpy", "torch.matmul", "torch.set_num_threads", "torch.rand", "numpy.column_stack", "numpy.random.randint" ] ]
colonel8377/hkust_machine_learning
[ "80d880a8bd6a0139d5d5409000f836900855b0ba" ]
[ "top1/src/models/model.py" ]
[ "import torch\nimport logging\nimport os\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import CrossEntropyLoss\nfrom transformers import (RobertaConfig, RobertaModel)\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S',\n level=logging.INFO)\n\n\nclass Model(nn.Module):\n def __init__(self, args):\n super(Model, self).__init__()\n args.out_size = len(args.dense_features)\n self.dropout = nn.Dropout(args.hidden_dropout_prob)\n self.args = args\n\n # 创建BERT模型,并且导入预训练模型\n config = RobertaConfig.from_pretrained(args.pretrained_model_path)\n config.output_hidden_states = True\n args.hidden_size = config.hidden_size\n args.num_hidden_layers = config.num_hidden_layers\n self.text_layer = RobertaModel.from_pretrained(args.pretrained_model_path, config=config)\n self.text_linear = nn.Linear(args.text_dim + args.vocab_dim_v1 * len(args.text_features), args.hidden_size)\n logger.info(\"Load linear from %s\", os.path.join(args.pretrained_model_path, \"linear.bin\"))\n self.text_linear.load_state_dict(torch.load(os.path.join(args.pretrained_model_path, \"linear.bin\")))\n logger.info(\"Load embeddings from %s\", os.path.join(args.pretrained_model_path, \"embeddings.bin\"))\n self.text_embeddings = nn.Embedding.from_pretrained(\n torch.load(os.path.join(args.pretrained_model_path, \"embeddings.bin\"))['weight'], freeze=True)\n args.out_size += args.hidden_size * 2\n\n # 创建fusion-layer模型,随机初始化\n config = RobertaConfig()\n config.num_hidden_layers = 4\n config.intermediate_size = 2048\n config.hidden_size = 512\n config.num_attention_heads = 16\n config.vocab_size = 5\n self.text_layer_1 = RobertaModel(config=config)\n self.text_layer_1.apply(self._init_weights)\n self.text_linear_1 = nn.Linear(args.text_dim_1 + args.hidden_size, 512)\n self.text_linear_1.apply(self._init_weights)\n self.norm = nn.BatchNorm1d(args.text_dim_1 + args.hidden_size)\n args.out_size += 1024\n\n # 创建分类器,随机初始化\n self.classifier = ClassificationHead(args)\n self.classifier.apply(self._init_weights)\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=0.02)\n\n def forward(self, dense_features, text_features, text_ids, text_masks, text_features_1, text_masks_1, labels=None):\n outputs = []\n # 获取浮点数,作为分类器的输入\n outputs.append(dense_features.float())\n # 获取BERT模型的hidden state,并且做max pooling和mean pooling作为分类器的输入\n text_masks = text_masks.float()\n text_embedding = self.text_embeddings(text_ids).view(text_ids.size(0), text_ids.size(1), -1)\n text_features = torch.cat((text_features.float(), text_embedding), -1)\n text_features = torch.relu(self.text_linear(self.dropout(text_features)))\n hidden_states = self.text_layer(inputs_embeds=text_features, attention_mask=text_masks)[0]\n embed_mean = (hidden_states * text_masks.unsqueeze(-1)).sum(1) / text_masks.sum(1).unsqueeze(-1)\n embed_mean = embed_mean.float()\n embed_max = hidden_states + (1 - text_masks).unsqueeze(-1) * (-1e10)\n embed_max = embed_max.max(1)[0].float()\n outputs.append(embed_mean)\n outputs.append(embed_max)\n # 获取fusion-layer的hidden state,并且做max pooling和mean pooling作为分类器的输入\n text_masks_1 = text_masks_1.float()\n text_features_1 = torch.cat((text_features_1.float(), hidden_states), -1)\n bs, le, dim = text_features_1.size()\n text_features_1 = self.norm(text_features_1.view(-1, dim)).view(bs, le, dim)\n text_features_1 = torch.relu(self.text_linear_1(text_features_1))\n hidden_states = self.text_layer_1(inputs_embeds=text_features_1, attention_mask=text_masks_1)[0]\n embed_mean = (hidden_states * text_masks_1.unsqueeze(-1)).sum(1) / text_masks_1.sum(1).unsqueeze(-1)\n embed_mean = embed_mean.float()\n embed_max = hidden_states + (1 - text_masks_1).unsqueeze(-1) * (-1e10)\n embed_max = embed_max.max(1)[0].float()\n outputs.append(embed_mean)\n outputs.append(embed_max)\n\n # 将特征输入分类器,得到20分类的logits\n final_hidden_state = torch.cat(outputs, -1)\n logits = self.classifier(final_hidden_state)\n\n # 返回loss或概率结果\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits, labels)\n return loss\n else:\n prob = torch.softmax(logits, -1)\n age_probs = prob.view(-1, 10, 2).sum(2)\n gender_probs = prob.view(-1, 10, 2).sum(1)\n return age_probs, gender_probs\n\n\nclass ClassificationHead(nn.Module):\n \"\"\"Head for sentence-level classification tasks.\"\"\"\n\n def __init__(self, args):\n super().__init__()\n self.norm = nn.BatchNorm1d(args.out_size)\n self.dense = nn.Linear(args.out_size, args.linear_layer_size[0])\n self.norm_1 = nn.BatchNorm1d(args.linear_layer_size[0])\n self.dropout = nn.Dropout(args.hidden_dropout_prob)\n self.dense_1 = nn.Linear(args.linear_layer_size[0], args.linear_layer_size[1])\n self.norm_2 = nn.BatchNorm1d(args.linear_layer_size[1])\n self.out_proj = nn.Linear(args.linear_layer_size[1], args.num_label)\n\n def forward(self, features, **kwargs):\n x = self.norm(features)\n x = self.dropout(x)\n x = self.dense(x)\n x = torch.relu(self.norm_1(x))\n x = self.dropout(x)\n x = self.dense_1(x)\n x = torch.relu(self.norm_2(x))\n x = self.dropout(x)\n x = self.out_proj(x)\n return x\n" ]
[ [ "torch.nn.BatchNorm1d", "torch.nn.CrossEntropyLoss", "torch.nn.Dropout", "torch.softmax", "torch.cat", "torch.nn.Linear" ] ]
podaac/l2ss-py
[ "d5005665e1fac53aebc1d0f620e72e46386beb8a" ]
[ "podaac/subsetter/xarray_enhancements.py" ]
[ "# Copyright 2019, by the California Institute of Technology.\n# ALL RIGHTS RESERVED. United States Government Sponsorship acknowledged.\n# Any commercial use must be negotiated with the Office of Technology\n# Transfer at the California Institute of Technology.\n#\n# This software may be subject to U.S. export control laws. By accepting\n# this software, the user agrees to comply with all applicable U.S. export\n# laws and regulations. User has the responsibility to obtain export\n# licenses, or other export authority as may be required before exporting\n# such information to foreign countries or providing access to foreign\n# persons.\n\n\"\"\"\n======================\nxarray_enhancements.py\n======================\n\nFunctions which improve upon existing xarray functionality, optimized\nfor this specific use-case.\n\"\"\"\n\nimport logging\n\nimport numpy as np\nimport xarray as xr\n\n\ndef get_indexers_from_1d(cond):\n \"\"\"\n Get indexers from a dataset with 1 dimension.\n\n Parameters\n ----------\n cond : xarray.Dataset\n Contains the result of the initial lat lon condition.\n\n Returns\n -------\n dict\n Indexer dictionary for the provided condition.\n \"\"\"\n cols = cond.values\n\n if not cols.any():\n logging.info(\"No data within the given bounding box.\")\n\n indexers = {\n cond.dims[0]: np.where(cols)[0]\n }\n return indexers\n\n\ndef get_indexers_from_nd(cond, cut):\n \"\"\"\n Get indexers from a dataset with more than 1 dimensions.\n\n Parameters\n ----------\n cond : xarray.Dataset\n Contains the result of the initial lat lon condition.\n cut : bool\n True if the scanline should be cut.\n\n Returns\n -------\n dict\n Indexer dictionary for the provided condition.\n \"\"\"\n\n rows = np.any(cond.values.squeeze(), axis=1)\n if cut:\n cols = np.any(cond.values.squeeze(), axis=0)\n else:\n cols = np.ones(len(cond.values[0]))\n\n # If the subsetted area is equal to the original area\n if np.all(rows) & np.all(cols):\n logging.info(\"Subsetted area equal to the original granule.\")\n\n # If the subsetted area is empty\n if not np.any(rows) | np.any(cols):\n logging.info(\"No data within the given bounding box.\")\n\n cond_shape_list = list(cond.shape)\n cond_list = list(cond.dims)\n output = [idx for idx, element in enumerate(cond_shape_list) if cond_shape_list[idx] == 1]\n for i in output:\n cond_list.pop(i)\n\n indexers = {\n cond_list[0]: np.where(rows)[0],\n cond_list[1]: np.where(cols)[0]\n }\n\n return indexers\n\n\ndef copy_empty_dataset(dataset):\n \"\"\"\n Copy an dataset into a new, empty dataset. This dataset should:\n * Contain the same structure as the input dataset (only include\n requested variables, if variable subset)\n * Contain the same global metadata as the input dataset\n * Contain a history field which describes this subset operation.\n\n Parameters\n ----------\n dataset: xarray.Dataset\n The dataset to copy into a empty dataset.\n\n Returns\n -------\n xarray.Dataset\n The new dataset which has no data.\n \"\"\"\n # Create a dict object where each key is a variable in the dataset and the value is an\n # array initialized to the fill value for that variable or NaN if there is no fill value\n # attribute for the variable\n empty_data = {k: np.full(v.shape, dataset.variables[k].attrs.get('_FillValue', np.nan)) for k, v in\n dataset.items()}\n\n # Create a copy of the dataset filled with the empty data. Then select the first index along each\n # dimension and return the result\n return dataset.copy(data=empty_data).isel({dim: slice(0, 1, 1) for dim in dataset.dims})\n\n\ndef cast_type(var, var_type):\n \"\"\"\n Type cast a variable into a var type.\n\n Parameters\n ----------\n var: xarray.core.dataarray.DataArray\n The dataarray to be type casted.\n var_type: string\n New type the variable will be type casted to.\n Returns\n -------\n xarray.core.dataarray.DataArray\n The newly type casted variable.\n \"\"\"\n\n return var.astype(var_type)\n\n\ndef where(dataset, cond, cut):\n \"\"\"\n Return a dataset which meets the given condition.\n\n This is a modification of the existing xarray 'where' function.\n https://github.com/pydata/xarray/blob/master/xarray/core/common.py#L999\n\n Parameters\n ----------\n dataset : xarray.Dataset\n The dataset to filter and return.\n cond : DataArray or Dataset with boolean dtype\n Locations at which to preserve this object's values.\n cut : boolean\n True if the scanline should be cut, False if the scanline should\n not be cut.\n\n Returns\n -------\n xarray.Dataset\n The filtered Dataset\n\n Notes\n -----\n The `cond` variable contains a boolean mask of valid data indices.\n However in that mask, True represents valid data and False\n represents invalid data.\n \"\"\"\n if cond.values.ndim == 1:\n indexers = get_indexers_from_1d(cond)\n else:\n indexers = get_indexers_from_nd(cond, cut)\n # If any of the indexer dimensions are empty, return an empty dataset\n if not all(len(value) > 0 for value in indexers.values()):\n return copy_empty_dataset(dataset)\n\n indexed_cond = cond.isel(**indexers)\n indexed_ds = dataset.isel(**indexers)\n new_dataset = indexed_ds.where(indexed_cond)\n\n # Cast all variables to their original type\n for variable_name, variable in new_dataset.data_vars.items():\n original_type = indexed_ds[variable_name].dtype\n new_type = variable.dtype\n\n # Check if variable has no _FillValue. If so, use original data\n if '_FillValue' not in variable.attrs:\n\n if original_type != new_type:\n new_dataset[variable_name] = xr.apply_ufunc(cast_type, variable,\n str(original_type), dask='allowed',\n keep_attrs=True)\n\n # Replace nans with values from original dataset. If the\n # variable has more than one dimension, copy the entire\n # variable over, otherwise use a NaN mask to copy over the\n # relevant values.\n if len(variable.shape) > 1:\n new_dataset[variable_name] = indexed_ds[variable_name]\n else:\n nan_mask = np.isnan(variable.data)\n if nan_mask.any():\n variable.data[nan_mask] = indexed_ds[variable_name][nan_mask]\n\n new_dataset[variable_name].attrs = indexed_ds[variable_name].attrs\n variable.attrs = indexed_ds[variable_name].attrs\n new_dataset[variable_name].encoding['_FillValue'] = None\n variable.encoding['_FillValue'] = None\n\n else:\n # Manually replace nans with FillValue\n variable.data[np.isnan(variable.data)] = variable.attrs.get(\"_FillValue\")\n\n if original_type != new_type:\n new_dataset[variable_name] = xr.apply_ufunc(cast_type, variable,\n str(original_type), dask='allowed',\n keep_attrs=True)\n\n return new_dataset\n" ]
[ [ "numpy.all", "numpy.isnan", "numpy.where", "numpy.any" ] ]
NullConvergence/torch_temp
[ "29a0d7190f0be6124f51bd85b8320cd8b3cef29a" ]
[ "mtorch/core/model/metrics/epoch_accuracy.py" ]
[ "import torch\nfrom .base import BaseMetric\n\n\nclass EpochAccuracy(BaseMetric):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def forward(self, output, targets, *args, **kwargs):\n assert output.size(0) == targets.size(0)\n with torch.no_grad():\n _, pred = output.max(1)\n correct = pred.eq(targets).sum().item()\n\n return 100*(correct / targets.size(0))\n\n def get_name(self):\n return \"EpochAccuracy\"\n" ]
[ [ "torch.no_grad" ] ]
nifs-software/nifs-retrieve
[ "4ff9d70a1d2301d7b5762162586388ae67046ad2" ]
[ "demos/rawdata/bolometer.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom nifs.retrieve.rawdata import RawData\n\n\n# Bolomgeter の ショット番号=48000, サブショット番号=1, チャンネル番号=1 のデータを取得\ndata = RawData.retrieve(\"Bolometer\", 48000, 1, 1)\n\nrange = data.params[\"Range\"] # レンジ取得\nrangefactor = data.params[\"RangeFactor\"] # 倍率\nresolution = data.params[\"Resolution(bit)\"] # 解像度(bit数)\nvolt = (range * rangefactor * 2) / (2 ** resolution) # 生データを電圧に変換する際の係数\n\nval = data.get_val() # 生データ (デジタイザーのイメージデータを int の配列にしたもの)\nvoltdata = (val - ((2 ** resolution) / 2)) * volt # オフセットを引いて先にもとめた係数をかけ、電圧の配列を得る\n\nclk = data.params[\"ClockSpeed\"] # サンプリングクロックの取得\ntimedata = np.arange(0.0, len(val)) / clk # 電圧データと同じ長さの配列を作り、サンプリングクロックで割る(サンプリング時刻の配列を得る)\n\nplt.title(\"Bolometer\")\nplt.xlabel(\"t [sec]\")\nplt.ylabel(\"v [V]\")\nplt.plot(timedata, voltdata)\nplt.show()\n" ]
[ [ "matplotlib.pyplot.title", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
tolkien/misc
[ "84651346a3a0053b6a2af31db26c227a34da33c8" ]
[ "tf/example/tf-math-fn.py" ]
[ "# -*- coding: utf-8 -*-\nimport tensorflow as tf\nimport functions\n\nc2, c3 = tf.constant([1.2, 5.6]), tf.constant([-4, -1, 7])\nv2, v3 = tf.Variable([2.3, 4.5]), tf.Variable([-2, 3, 5])\n\nprint('-----------add_n------------') # same shape aod dtype 덧셈\nfunctions.showOperation(tf.add_n([c2, v2])) # [ 3.5 10.10000038]\nfunctions.showOperation(tf.add_n([c3, v3, v3])) # [-8 5 17]\n\nprint('-----------abs------------')\nfunctions.showOperation(tf.abs(c2)) # [ 1.20000005 5.5999999 ]\nfunctions.showOperation(tf.abs([c3, v3])) # [[4 1 7] [2 3 5]]\n\nprint('-----------neg------------')\nfunctions.showOperation(tf.neg(c2)) # [-1.20000005 -5.5999999 ]\nfunctions.showOperation(tf.neg([c3, v3])) # [[ 4 1 -7] [ 2 -3 -5]]\n\nprint('-----------sign------------')\nfunctions.showOperation(tf.sign(c2)) # [ 1. 1.]\nfunctions.showOperation(tf.sign([c3, v3])) # [[-1 -1 1] [-1 1 1]]\n\nprint('-----------square------------')\nfunctions.showOperation(tf.square(c2)) # [ 1.44000006 31.3599987 ]\nfunctions.showOperation(tf.square([c3, v3])) # [[16 1 49] [ 4 9 25]]\n\nprint('-----------round------------')\nfunctions.showOperation(tf.round(c2)) # [ 1. 6.]\nfunctions.showOperation(tf.round([c3, v3])) # [[-4 -1 7] [-2 3 5]]\n\nprint('-----------sqrt------------') # 정수 사용 불가. 음수는 nan.\nfunctions.showOperation(tf.sqrt(c2)) # [ 1.44000006 31.3599987 ]\nfunctions.showOperation(tf.sqrt([c2, v2])) # [[ 1.09544516 2.36643171] [ 1.5165751 2.12132025]]\n\nprint('-----------pow------------') # 갯수 일치 주의\nfunctions.showOperation(tf.pow(c2, 2)) # [ 1.44000006 31.3599987 ]\n# [[ 1.44000006 175.61599731] [ 5.28999996 91.125 ]]\nfunctions.showOperation(tf.pow([c2, v2], [2, 3]))\n# [[ 1.44000006 175.61599731] [ 5.28999996 91.125 ]]\nfunctions.showOperation(tf.pow([c2, v2], [[2, 3], [2, 3]]))\n\nprint('-----------exp------------') # 정수 사용 불가. 음수 동작.\nfunctions.showOperation(tf.exp(c2)) # [ 3.320117 270.4263916]\nfunctions.showOperation(tf.exp([c2, v2])) # [[ 3.320117 270.4263916 ] [ 9.97418213 90.01712799]]\n\nprint('-----------log------------') # 정수 사용 불가. 음수는 nan.\nfunctions.showOperation(tf.log(c2)) # [ 0.18232159 1.72276664]\nfunctions.showOperation(tf.log([c2, v2])) # [[ 0.18232159 1.72276664] [ 0.83290911 1.50407743]]\n\nprint('-----------ceil------------') # 정수 사용 불가.\nfunctions.showOperation(tf.ceil(c2)) # [ 2. 6.]\nfunctions.showOperation(tf.ceil([c2, v2])) # [[ 2. 6.] [ 3. 5.]]\n\nprint('-----------floor------------') # 정수 사용 불가.\nfunctions.showOperation(tf.floor(c2)) # [ 1. 5.]\nfunctions.showOperation(tf.floor([c2, v2])) # [[ 1. 5.] [ 2. 4.]]\n\nprint('-----------maximum------------')\nfunctions.showOperation(tf.maximum(c2, v2)) # [ 2.29999995 5.5999999 ]\n# [[ 2.29999995 5.5999999 ] [ 2.29999995 5.5999999 ]]. [c2, c3] is error because shape is different.\nfunctions.showOperation(tf.maximum([c2, c2], [v2, v2]))\n\nprint('-----------minimum------------')\nfunctions.showOperation(tf.minimum(c2, v2)) # [ 1.20000005 4.5 ]\n# [[ 1.20000005 4.5 ] [ 1.20000005 4.5 ]]\nfunctions.showOperation(tf.minimum([c2, c2], [v2, v2]))\n\nprint('-----------sin------------') # 정수 사용 불가.\nfunctions.showOperation(tf.sin(c2)) # [ 0.93203908 -0.63126671]\n# [[ 0.93203908 -0.63126671] [ 0.74570525 -0.97753012]]\nfunctions.showOperation(tf.sin([c2, v2]))\n\nprint('-----------cos------------') # 정수 사용 불가.\nfunctions.showOperation(tf.cos(c2)) # [ 0.36235771 0.7755658 ]\n# [[ 0.36235774 0.77556586] [-0.66627598 -0.21079579]]\nfunctions.showOperation(tf.cos([c2, v2]))\n\nprint('-----------tan------------') # 정수 사용 불가.\nfunctions.showOperation(tf.tan(c2)) # [ 2.5721519 -0.81394345]\n# [[ 2.5721519 -0.81394345] [-1.1192137 4.63733196]]\nfunctions.showOperation(tf.tan([c2, v2]))\n\nc4 = tf.constant([[1, 3, 5], [0, 2, 4]])\nv4 = tf.Variable([[1, 2], [3, 7], [8, 9]])\n\nprint('-----------matmul------------') # (2x3)*(3x2) = (2x2), (3x2)*(2x3) = (3x3)\nfunctions.showOperation(tf.matmul(c4, v4)) # [[50 68] [38 50]]\nfunctions.showOperation(tf.matmul(v4, c4)) # [[ 1 7 13] [ 3 23 43] [ 8 42 76]]\n\n\n\"\"\"출처: http://pythonkim.tistory.com/67?category=574914 [파이쿵]\"\"\"\n" ]
[ [ "tensorflow.sign", "tensorflow.minimum", "tensorflow.add_n", "tensorflow.Variable", "tensorflow.floor", "tensorflow.square", "tensorflow.ceil", "tensorflow.matmul", "tensorflow.pow", "tensorflow.exp", "tensorflow.neg", "tensorflow.round", "tensorflow.tan", "tensorflow.sin", "tensorflow.constant", "tensorflow.cos", "tensorflow.maximum", "tensorflow.log", "tensorflow.sqrt", "tensorflow.abs" ] ]
cmlab-mira/MedicalPro
[ "3918c95197fd24406ce2117cc7ff9ce21bb8c620" ]
[ "src/preprocess/mr_ct_both_data_split.py" ]
[ "import argparse\nimport logging\nimport pandas as pd\nfrom pathlib import Path\n\n\ndef main(args):\n mr_df = pd.read_csv(args.mr_csv.as_posix())\n ct_df = pd.read_csv(args.ct_csv.as_posix())\n\n output_dir = args.output_dir\n if not output_dir.is_dir():\n output_dir.mkdir(parents=True)\n split_csv_path = output_dir / 'pretrain.csv'\n\n df = pd.concat([ct_df, mr_df])\n df.to_csv(split_csv_path, index=False)\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser(description=\"Merge the data split files of both mr and ct.\")\n parser.add_argument('mr_csv', type=Path, help='The path of the mr data split file.')\n parser.add_argument('ct_csv', type=Path, help='The path of the ct data split file.')\n parser.add_argument('output_dir', type=Path, help='The output directory of the data split files.')\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(format='%(asctime)s | %(name)-4s | %(levelname)-4s | %(message)s',\n level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')\n args = _parse_args()\n main(args)\n" ]
[ [ "pandas.concat" ] ]
stevenpclark/aoc2021
[ "726009e5a2a87025943a736e8676784ca7cdc8bd" ]
[ "03/03.py" ]
[ "import numpy as np\n\ndef filter_data(data, use_most_common):\n _, nc = data.shape\n for c in range(nc):\n nr, _ = data.shape\n if nr <= 1:\n break\n \n col_score = sum(data[:,c])/nr\n if use_most_common:\n keep_val = col_score >= 0.5\n else:\n keep_val = col_score < 0.5\n\n mask = data[:,c] == keep_val\n data = data[mask, :]\n\n x = 0\n for n in data[0,:]:\n x = (x << 1) + n\n\n return x\n\n\ndef main():\n fn = 'input.txt'\n #fn = 'test.txt'\n\n lines = np.loadtxt(fn, dtype=str)\n num_lines = len(lines)\n\n data = np.array([[int(c) for c in s] for s in lines])\n\n gamma_list = (np.sum(data, axis=0)/num_lines > 0.5).astype(int)\n gamma = 0\n epsilon = 0\n for n in gamma_list:\n gamma = (gamma << 1) + n\n epsilon = (epsilon << 1) + (1-n)\n\n print(gamma*epsilon)\n\n rating1 = filter_data(data, use_most_common=True)\n rating2 = filter_data(data, use_most_common=False)\n\n print(rating1*rating2)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.sum", "numpy.loadtxt" ] ]
tokusumi/ml-management-tools
[ "7b075306d9df26b4f454f3af9e9c377b60683bba" ]
[ "mlflow/models/cnn.py" ]
[ "from tensorflow import keras\n\n\ndef build_model(hp):\n model = keras.Sequential()\n model.add(\n keras.layers.Conv2D(\n hp.Choice(\"filter\", values=[16, 32, 64]),\n 3,\n activation=hp.Choice(\n \"activation\",\n values=[\"tanh\", \"softplus\", \"relu\"],\n ),\n input_shape=(32, 32, 3),\n )\n )\n model.add(\n keras.layers.Conv2D(\n 2 * hp.Choice(\"filter\", values=[16, 32, 64]),\n 3,\n activation=hp.Choice(\"activation\", values=[\"tanh\", \"softplus\", \"relu\"]),\n )\n )\n if hp.Boolean(\"batchnorm\"):\n model.add(keras.layers.BatchNormalization())\n\n model.add(keras.layers.MaxPooling2D(pool_size=2))\n model.add(keras.layers.Flatten())\n model.add(\n keras.layers.Dense(\n hp.Int(\"units\", min_value=32, max_value=512, step=32), activation=\"relu\"\n )\n )\n model.add(\n keras.layers.Dropout(\n hp.Float(\"dropout\", min_value=0.25, max_value=0.75, step=0.25)\n )\n )\n model.add(keras.layers.Dense(10, activation=\"softmax\"))\n model.compile(\n optimizer=keras.optimizers.Adam(\n hp.Choice(\"learning_rate\", values=[1e-2, 1e-3, 1e-4])\n ),\n loss=\"sparse_categorical_crossentropy\",\n metrics=[\"acc\"],\n )\n return model\n" ]
[ [ "tensorflow.keras.layers.Dense", "tensorflow.keras.Sequential", "tensorflow.keras.layers.BatchNormalization", "tensorflow.keras.layers.MaxPooling2D", "tensorflow.keras.layers.Flatten" ] ]
pecheurs/FER2013_project
[ "f07b8f3b8084e4702e13cdcd0e876bb77d153665" ]
[ "Facial_Expression_Recognition/VGGandResNet.py" ]
[ "'''Train Fer2013 with PyTorch.'''\r\n# 10 crop for data enhancement\r\nfrom __future__ import print_function\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport torch.nn.functional as F\r\nimport torch.backends.cudnn as cudnn\r\nimport torchvision\r\nimport transforms as transforms\r\nimport numpy as np\r\nimport os\r\nimport argparse\r\nimport utils\r\nfrom fer import FER2013\r\nfrom torch.autograd import Variable\r\nfrom models import *\r\nimport os\r\n\r\nlog_path = 'resnet34_learning_rate.txt'\r\nlog_path_Train = 'resnet34_train_results.txt'\r\nlog_path_PublicTest = 'resnet34_public_test_results.txt'\r\nlog_path_PrivateTest = 'resnet34_private_test_results.txt'\r\nf = open(log_path, 'a')\r\nf_Train = open(log_path_Train, 'a')\r\nf_PublicTest = open(log_path_PublicTest, 'a')\r\nf_PrivateTest = open(log_path_PrivateTest, 'a')\r\n# Training\r\ndef train(epoch):\r\n print('\\nEpoch: %d' % epoch)\r\n global Train_acc\r\n net.train()\r\n train_loss = 0\r\n correct = 0\r\n total = 0\r\n\r\n if epoch > learning_rate_decay_start and learning_rate_decay_start >= 0:\r\n frac = (epoch - learning_rate_decay_start) // learning_rate_decay_every\r\n decay_factor = learning_rate_decay_rate ** frac\r\n current_lr = opt.lr * decay_factor\r\n utils.set_lr(optimizer, current_lr) # set the decayed rate\r\n else:\r\n current_lr = opt.lr\r\n print('learning_rate: %s' % str(current_lr))\r\n f.write(str(current_lr) + '\\n')\r\n torch.cuda.empty_cache()\r\n\r\n for batch_idx, (inputs, targets) in enumerate(trainloader):\r\n if use_cuda:\r\n inputs, targets = inputs.cuda(), targets.cuda()\r\n optimizer.zero_grad()\r\n inputs, targets = Variable(inputs), Variable(targets)\r\n outputs = net(inputs)\r\n loss = criterion(outputs, targets)\r\n loss.backward()\r\n utils.clip_gradient(optimizer, 0.1)\r\n optimizer.step()\r\n train_loss += loss.item()\r\n _, predicted = torch.max(outputs.data, 1)\r\n total += targets.size(0)\r\n correct += predicted.eq(targets.data).cpu().sum()\r\n\r\n utils.progress_bar(batch_idx, len(trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\r\n % (train_loss/(batch_idx+1), correct.__float__()/total, correct, total))\r\n Train_acc = correct.__float__()/total\r\n print(str(Train_acc))\r\n f_Train.write(str(Train_acc)+'\\n')\r\n\r\n\r\ndef PublicTest(epoch):\r\n global PublicTest_acc\r\n global best_PublicTest_acc\r\n global best_PublicTest_acc_epoch\r\n net.eval()\r\n PublicTest_loss = 0\r\n correct = 0\r\n total = 0\r\n torch.cuda.empty_cache()\r\n with torch.no_grad():\r\n for batch_idx, (inputs, targets) in enumerate(PublicTestloader):\r\n bs, ncrops, c, h, w = np.shape(inputs)\r\n inputs = inputs.view(-1, c, h, w)\r\n if use_cuda:\r\n inputs, targets = inputs.cuda(), targets.cuda()\r\n # inputs, targets = Variable(inputs, volatile=True), Variable(targets)\r\n outputs = net(inputs)\r\n outputs_avg = outputs.view(bs, ncrops, -1).mean(1) # avg over crops\r\n loss = criterion(outputs_avg, targets)\r\n PublicTest_loss += loss.data\r\n _, predicted = torch.max(outputs_avg.data, 1)\r\n total += targets.size(0)\r\n correct += predicted.eq(targets.data).cpu().sum()\r\n\r\n utils.progress_bar(batch_idx, len(PublicTestloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\r\n % (PublicTest_loss / (batch_idx + 1), correct.__float__() / total, correct, total))\r\n\r\n # Save checkpoint.\r\n PublicTest_acc = correct.__float__()/total\r\n f_PublicTest.write(str(PublicTest_acc) + '\\n')\r\n print(str(PublicTest_acc))\r\n if PublicTest_acc > best_PublicTest_acc:\r\n print('Saving..')\r\n print(\"best_PublicTest_acc: %0.3f\" % PublicTest_acc)\r\n state = {\r\n 'net': net.state_dict() if torch.cuda.is_available() else net,\r\n 'acc': PublicTest_acc,\r\n 'epoch': epoch,\r\n }\r\n if not os.path.isdir(path):\r\n os.mkdir(path)\r\n torch.save(state, os.path.join(path, 'PublicTest_model.t7'))\r\n best_PublicTest_acc = PublicTest_acc\r\n best_PublicTest_acc_epoch = epoch\r\n\r\n\r\ndef PrivateTest(epoch):\r\n global PrivateTest_acc\r\n global best_PrivateTest_acc\r\n global best_PrivateTest_acc_epoch\r\n net.eval()\r\n PrivateTest_loss = 0\r\n correct = 0\r\n total = 0\r\n torch.cuda.empty_cache()\r\n with torch.no_grad():\r\n for batch_idx, (inputs, targets) in enumerate(PrivateTestloader):\r\n bs, ncrops, c, h, w = np.shape(inputs)\r\n inputs = inputs.view(-1, c, h, w)\r\n if use_cuda:\r\n inputs, targets = inputs.cuda(), targets.cuda()\r\n # inputs, targets = Variable(inputs, volatile=True), Variable(targets)\r\n outputs = net(inputs)\r\n outputs_avg = outputs.view(bs, ncrops, -1).mean(1) # avg over crops\r\n loss = criterion(outputs_avg, targets)\r\n PrivateTest_loss += loss.item()\r\n _, predicted = torch.max(outputs_avg.data, 1)\r\n total += targets.size(0)\r\n correct += predicted.eq(targets.data).cpu().sum()\r\n\r\n utils.progress_bar(batch_idx, len(PublicTestloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\r\n % (PrivateTest_loss / (batch_idx + 1), correct.__float__() / total, correct, total))\r\n # Save checkpoint.\r\n PrivateTest_acc = correct.__float__() / total\r\n print(str(PrivateTest_acc))\r\n f_PrivateTest.write(str(PrivateTest_acc) + '\\n')\r\n if PrivateTest_acc > best_PrivateTest_acc:\r\n print('Saving..')\r\n print(\"best_PrivateTest_acc: %0.3f\" % PrivateTest_acc)\r\n state = {\r\n 'net': net.state_dict() if torch.cuda.is_available() else net,\r\n\t 'best_PublicTest_acc': best_PublicTest_acc,\r\n 'best_PrivateTest_acc': PrivateTest_acc,\r\n \t 'best_PublicTest_acc_epoch': best_PublicTest_acc_epoch,\r\n 'best_PrivateTest_acc_epoch': epoch,\r\n }\r\n if not os.path.isdir(path):\r\n os.mkdir(path)\r\n torch.save(state, os.path.join(path,'PrivateTest_model.t7'))\r\n best_PrivateTest_acc = PrivateTest_acc\r\n best_PrivateTest_acc_epoch = epoch\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\r\n print(device)\r\n\r\n parser = argparse.ArgumentParser(description='PyTorch Fer2013 CNN Training')\r\n parser.add_argument('--model', type=str, default='ResNet34', help='VGG19 ResNet18 34 50')\r\n parser.add_argument('--dataset', type=str, default='FER2013', help='FER2013')\r\n parser.add_argument('--bs', default=1024, type=int, help='batch size')\r\n parser.add_argument('--lr', default=0.01, type=float, help='learning rate')\r\n parser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')\r\n opt = parser.parse_args()\r\n\r\n use_cuda = torch.cuda.is_available()\r\n best_PublicTest_acc = 0 # best PublicTest accuracy\r\n best_PublicTest_acc_epoch = 0\r\n best_PrivateTest_acc = 0 # best PrivateTest accuracy\r\n best_PrivateTest_acc_epoch = 0\r\n start_epoch = 0 # start from epoch 0 or last checkpoint epoch\r\n\r\n learning_rate_decay_start = 80 # 50\r\n learning_rate_decay_every = 5 # 5\r\n learning_rate_decay_rate = 0.9 # 0.9\r\n\r\n cut_size = 44\r\n total_epoch = 250\r\n\r\n path = os.path.join(opt.model)\r\n print(opt.model)\r\n\r\n # Data\r\n print('==> Preparing data..')\r\n transform_train = transforms.Compose([\r\n transforms.RandomCrop(44),\r\n transforms.RandomHorizontalFlip(),\r\n transforms.ToTensor(),\r\n ])\r\n\r\n transform_test = transforms.Compose([\r\n transforms.TenCrop(cut_size),\r\n transforms.Lambda(lambda crops: torch.stack([transforms.ToTensor()(crop) for crop in crops])),\r\n ])\r\n\r\n # batch_size=opt.bs\r\n\r\n trainset = FER2013(split='Training', transform=transform_train)\r\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=32, shuffle=True)\r\n PublicTestset = FER2013(split='PublicTest', transform=transform_test)\r\n PublicTestloader = torch.utils.data.DataLoader(PublicTestset, batch_size=32, shuffle=False)\r\n PrivateTestset = FER2013(split='PrivateTest', transform=transform_test)\r\n PrivateTestloader = torch.utils.data.DataLoader(PrivateTestset, batch_size=32, shuffle=False)\r\n\r\n # Model\r\n if opt.model == 'VGG19':\r\n net = VGG('VGG19')\r\n elif opt.model == 'VGG16':\r\n net = VGG('VGG16')\r\n elif opt.model == 'VGG13':\r\n net = VGG('VGG13')\r\n elif opt.model == 'VGG16':\r\n net = VGG('VGG16')\r\n elif opt.model == 'ResNet18':\r\n net = ResNet18()\r\n elif opt.model == 'ResNet34':\r\n net = ResNet34()\r\n elif opt.model == 'ResNet50':\r\n net = ResNet50()\r\n\r\n if opt.resume:\r\n # Load checkpoint.\r\n print('==> Resuming from checkpoint..')\r\n assert os.path.isdir(path), 'Error: no checkpoint directory found!'\r\n checkpoint = torch.load(os.path.join(path, 'PrivateTest_model.t7'))\r\n\r\n net.load_state_dict(checkpoint['net'])\r\n best_PublicTest_acc = checkpoint['best_PublicTest_acc']\r\n best_PrivateTest_acc = checkpoint['best_PrivateTest_acc']\r\n best_PrivateTest_acc_epoch = checkpoint['best_PublicTest_acc_epoch']\r\n best_PrivateTest_acc_epoch = checkpoint['best_PrivateTest_acc_epoch']\r\n start_epoch = checkpoint['best_PrivateTest_acc_epoch'] + 1\r\n else:\r\n print('==> Building model..')\r\n\r\n if use_cuda:\r\n net.cuda()\r\n\r\n criterion = nn.CrossEntropyLoss()\r\n optimizer = optim.SGD(net.parameters(), lr=opt.lr, momentum=0.9, weight_decay=5e-4)\r\n\r\n for epoch in range(start_epoch, total_epoch):\r\n train(epoch)\r\n PublicTest(epoch)\r\n PrivateTest(epoch)\r\n\r\n print(\"best_PublicTest_acc: %0.3f\" % best_PublicTest_acc)\r\n print(\"best_PublicTest_acc_epoch: %d\" % best_PublicTest_acc_epoch)\r\n print(\"best_PrivateTest_acc: %0.3f\" % best_PrivateTest_acc)\r\n print(\"best_PrivateTest_acc_epoch: %d\" % best_PrivateTest_acc_epoch)\r\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.max", "torch.utils.data.DataLoader", "torch.cuda.empty_cache", "torch.no_grad", "numpy.shape", "torch.cuda.is_available", "torch.autograd.Variable" ] ]
mcx/brax
[ "c7735f34a48c3499516c3359d016057ed653f810" ]
[ "brax/jumpy.py" ]
[ "# Copyright 2022 The Brax 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# pylint:disable=redefined-builtin\n\"\"\"Numpy backend for JAX that is called for non-jit/non-jax arrays.\"\"\"\n\nfrom typing import Any, Callable, List, Optional, Sequence, Tuple, TypeVar, Union\n\nimport jax\nfrom jax import core\nfrom jax import custom_jvp\nfrom jax import numpy as jnp\nimport numpy as onp\n\nndarray = Union[onp.ndarray, jnp.ndarray] # pylint:disable=invalid-name\ntree_map = jax.tree_map # works great with jax or numpy as-is\npi = onp.pi\ninf = onp.inf\nfloat32 = onp.float32\nint32 = onp.int32\n\n\ndef _in_jit() -> bool:\n \"\"\"Returns true if currently inside a jax.jit call.\"\"\"\n return core.cur_sublevel().level > 0\n\n\ndef _which_np(*args):\n \"\"\"Returns np or jnp depending on args.\"\"\"\n for a in args:\n if isinstance(a, jnp.ndarray) and not isinstance(a, onp.ndarray):\n return jnp\n return onp\n\n\nF = TypeVar('F', bound=Callable)\n\n\ndef vmap(fun: F, include: Optional[Sequence[bool]] = None) -> F:\n \"\"\"Creates a function which maps ``fun`` over argument axes.\"\"\"\n if _in_jit():\n in_axes = 0\n if include:\n in_axes = [0 if inc else None for inc in include]\n return jax.vmap(fun, in_axes=in_axes)\n\n def _batched(*args, include=include):\n if include is not None and len(include) != len(args):\n raise RuntimeError('Len of `args` list must match length of `include`.')\n\n # by default, vectorize over every arg\n if include is None:\n include = [True for _ in args]\n\n # determine number of parallel evaluations to unroll into serial evals\n batch_size = None\n for a, inc in zip(args, include):\n if inc:\n flat_args, _ = jax.tree_flatten(a)\n batch_size = flat_args[0].shape[0]\n break\n\n # rebuild b_args for each serial evaluation\n rets = []\n for b_idx in range(batch_size):\n b_args = []\n for a, inc in zip(args, include):\n if inc:\n b_args.append(take(a, b_idx))\n else:\n b_args.append(a)\n rets.append(fun(*b_args))\n\n return jax.tree_map(lambda *x: onp.stack(x), *rets)\n\n return _batched\n\n\nCarry = TypeVar('Carry')\nX = TypeVar('X')\nY = TypeVar('Y')\n\n\ndef scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\n init: Carry,\n xs: X,\n length: Optional[int] = None,\n reverse: bool = False,\n unroll: int = 1) -> Tuple[Carry, Y]:\n \"\"\"Scan a function over leading array axes while carrying along state.\"\"\"\n if _in_jit():\n return jax.lax.scan(f, init, xs, length, reverse, unroll)\n else:\n xs_flat, xs_tree = jax.tree_flatten(xs)\n carry = init\n ys = []\n maybe_reversed = reversed if reverse else lambda x: x\n for i in maybe_reversed(range(length)):\n xs_slice = [x[i] for x in xs_flat]\n carry, y = f(carry, jax.tree_unflatten(xs_tree, xs_slice))\n ys.append(y)\n stacked_y = jax.tree_map(lambda *y: onp.vstack(y), *maybe_reversed(ys))\n return carry, stacked_y\n\n\ndef while_loop(cond_fun: Callable[[X], Any],\n body_fun: Callable[[X], X],\n init_val: X) -> X:\n \"\"\"Call body_fun while cond_fun is true, starting with init_val.\"\"\"\n if _in_jit():\n return jax.lax.while_loop(cond_fun, body_fun, init_val)\n else:\n val = init_val\n while cond_fun(val):\n val = body_fun(val)\n return val\n\n\ndef fori_loop(lower: int, upper: int, body_fun: Callable[[X], X],\n init_val: X) -> X:\n \"\"\"Call body_fun over range from lower to upper, starting with init_val.\"\"\"\n if _in_jit():\n return jax.lax.fori_loop(lower, upper, body_fun, init_val)\n else:\n val = init_val\n for _ in range(lower, upper):\n val = body_fun(val)\n return val\n\n\ndef take(tree: Any, i: Union[ndarray, Sequence[int]], axis: int = 0) -> Any:\n \"\"\"Returns tree sliced by i.\"\"\"\n np = _which_np(i)\n if isinstance(i, list) or isinstance(i, tuple):\n i = np.array(i, dtype=int)\n return jax.tree_map(lambda x: np.take(x, i, axis=axis, mode='clip'), tree)\n\n\ndef norm(x: ndarray,\n axis: Optional[Union[Tuple[int, ...], int]] = None) -> ndarray:\n \"\"\"Returns the array norm.\"\"\"\n return _which_np(x, axis).linalg.norm(x, axis=axis)\n\n\ndef index_update(x: ndarray, idx: ndarray, y: ndarray) -> ndarray:\n \"\"\"Pure equivalent of x[idx] = y.\"\"\"\n if _which_np(x) is jnp:\n return x.at[idx].set(y)\n x = onp.copy(x)\n x[idx] = y\n return x\n\n\ndef safe_norm(x: ndarray,\n axis: Optional[Union[Tuple[int, ...], int]] = None) -> ndarray:\n \"\"\"Calculates a linalg.norm(x) that's safe for gradients at x=0.\n\n Avoids a poorly defined gradient for jnp.linal.norm(0) see\n https://github.com/google/jax/issues/3058 for details\n\n Args:\n x: A jnp.array\n axis: The axis along which to compute the norm\n\n Returns:\n Norm of the array x.\n \"\"\"\n np = _which_np(x)\n if np is jnp:\n is_zero = jnp.allclose(x, 0.)\n # temporarily swap x with ones if is_zero, then swap back\n x = jnp.where(is_zero, jnp.ones_like(x), x)\n n = jnp.linalg.norm(x, axis=axis)\n n = jnp.where(is_zero, 0., n)\n else:\n n = onp.linalg.norm(x, axis=axis)\n return n\n\n\ndef any(a: ndarray, axis: Optional[int] = None) -> ndarray:\n \"\"\"Test whether any array element along a given axis evaluates to True.\"\"\"\n return _which_np(a).any(a, axis=axis)\n\n\ndef all(a: ndarray, axis: Optional[int] = None) -> ndarray:\n \"\"\"Test whether all array elements along a given axis evaluate to True.\"\"\"\n return _which_np(a).all(a, axis=axis)\n\n\ndef mean(a: ndarray, axis: Optional[int] = None) -> ndarray:\n \"\"\"Compute the arithmetic mean along the specified axis.\"\"\"\n return _which_np(a).mean(a, axis=axis)\n\n\ndef var(a: ndarray, axis: Optional[int] = None) -> ndarray:\n \"\"\"Compute the variance along the specified axis.\"\"\"\n return _which_np(a).var(a, axis=axis)\n\n\ndef arange(start: int, stop: int) -> ndarray:\n \"\"\"Return evenly spaced values within a given interval.\"\"\"\n return _which_np().arange(start, stop)\n\n\ndef dot(x: ndarray, y: ndarray) -> ndarray:\n \"\"\"Returns dot product of two arrays.\"\"\"\n return _which_np(x, y).dot(x, y)\n\n\ndef outer(a: ndarray, b: ndarray) -> ndarray:\n \"\"\"Compute the outer product of two vectors.\"\"\"\n return _which_np(a, b).outer(a, b)\n\n\ndef matmul(x1: ndarray, x2: ndarray) -> ndarray:\n \"\"\"Matrix product of two arrays.\"\"\"\n return _which_np(x1, x2).matmul(x1, x2)\n\n\ndef inv(a: ndarray) -> ndarray:\n \"\"\"Compute the (multiplicative) inverse of a matrix.\"\"\"\n return _which_np(a).linalg.inv(a)\n\n\ndef square(x: ndarray) -> ndarray:\n \"\"\"Return the element-wise square of the input.\"\"\"\n return _which_np(x).square(x)\n\n\ndef tile(x: ndarray, reps: Union[Tuple[int, ...], int]) -> ndarray:\n \"\"\"Construct an array by repeating A the number of times given by reps.\"\"\"\n return _which_np(x).tile(x, reps)\n\n\ndef repeat(a: ndarray, repeats: Union[int, ndarray]) -> ndarray:\n \"\"\"Repeat elements of an array.\"\"\"\n return _which_np(a, repeats).repeat(a, repeats=repeats)\n\n\ndef floor(x: ndarray) -> ndarray:\n \"\"\"Returns the floor of the input, element-wise..\"\"\"\n return _which_np(x).floor(x)\n\n\ndef cross(x: ndarray, y: ndarray) -> ndarray:\n \"\"\"Returns cross product of two arrays.\"\"\"\n return _which_np(x, y).cross(x, y)\n\n\ndef sin(angle: ndarray) -> ndarray:\n \"\"\"Returns trigonometric sine, element-wise.\"\"\"\n return _which_np(angle).sin(angle)\n\n\ndef cos(angle: ndarray) -> ndarray:\n \"\"\"Returns trigonometric cosine, element-wise.\"\"\"\n return _which_np(angle).cos(angle)\n\n\ndef arctan2(x1: ndarray, x2: ndarray) -> ndarray:\n \"\"\"Returns element-wise arc tangent of x1/x2 choosing the quadrant correctly.\"\"\"\n return _which_np(x1, x2).arctan2(x1, x2)\n\n\ndef arccos(x: ndarray) -> ndarray:\n \"\"\"Trigonometric inverse cosine, element-wise.\"\"\"\n return _which_np(x).arccos(x)\n\n\n@custom_jvp\ndef safe_arccos(x: ndarray) -> ndarray:\n \"\"\"Trigonometric inverse cosine, element-wise with safety clipping in grad.\"\"\"\n return _which_np(x).arccos(x)\n\n\n@safe_arccos.defjvp\ndef _safe_arccos_jvp(primal, tangent):\n x, = primal\n x_dot, = tangent\n primal_out = safe_arccos(x)\n tangent_out = -x_dot / sqrt(1. - clip(x, -1 + 1e-7, 1 - 1e-7)**2.)\n return primal_out, tangent_out\n\n\ndef arcsin(x: ndarray) -> ndarray:\n \"\"\"Trigonometric inverse sine, element-wise.\"\"\"\n return _which_np(x).arcsin(x)\n\n\ndef logical_not(x: ndarray) -> ndarray:\n \"\"\"Returns the truth value of NOT x element-wise.\"\"\"\n return _which_np(x).logical_not(x)\n\n\ndef logical_and(x1: ndarray, x2: ndarray) -> ndarray:\n \"\"\"Returns the truth value of x1 AND x2 element-wise.\"\"\"\n return _which_np(x1, x2).logical_and(x1, x2)\n\n\ndef logical_or(x1: ndarray, x2: ndarray) -> ndarray:\n \"\"\"Returns the truth value of x1 OR x2 element-wise.\"\"\"\n return _which_np(x1, x2).logical_or(x1, x2)\n\n\ndef multiply(x1: ndarray, x2: ndarray) -> ndarray:\n \"\"\"Multiply arguments element-wise.\"\"\"\n return _which_np(x1, x2).multiply(x1, x2)\n\n\ndef minimum(x1: ndarray, x2: ndarray) -> ndarray:\n \"\"\"Element-wise minimum of array elements.\"\"\"\n return _which_np(x1, x2).minimum(x1, x2)\n\n\ndef maximum(x1: ndarray, x2: ndarray) -> ndarray:\n \"\"\"Element-wise maximum of array elements.\"\"\"\n return _which_np(x1, x2).maximum(x1, x2)\n\n\ndef amin(x: ndarray) -> ndarray:\n \"\"\"Returns the minimum along a given axis.\"\"\"\n return _which_np(x).amin(x)\n\n\ndef amax(x: ndarray) -> ndarray:\n \"\"\"Returns the maximum along a given axis.\"\"\"\n return _which_np(x).amax(x)\n\n\ndef exp(x: ndarray) -> ndarray:\n \"\"\"Returns the exponential of all elements in the input array.\"\"\"\n return _which_np(x).exp(x)\n\n\ndef sign(x: ndarray) -> ndarray:\n \"\"\"Returns an element-wise indication of the sign of a number.\"\"\"\n return _which_np(x).sign(x)\n\n\ndef sum(a: ndarray, axis: Optional[int] = None):\n \"\"\"Returns sum of array elements over a given axis.\"\"\"\n return _which_np(a).sum(a, axis=axis)\n\n\ndef random_prngkey(seed: int) -> ndarray:\n \"\"\"Returns a PRNG key given a seed.\"\"\"\n if _which_np() is jnp:\n return jax.random.PRNGKey(seed)\n else:\n rng = onp.random.default_rng(seed)\n return rng.integers(low=0, high=2**32, dtype='uint32', size=2)\n\n\ndef random_uniform(rng: ndarray,\n shape: Tuple[int, ...] = (),\n low: Optional[float] = 0.0,\n high: Optional[float] = 1.0) -> ndarray:\n \"\"\"Sample uniform random values in [low, high) with given shape/dtype.\"\"\"\n if _which_np(rng) is jnp:\n return jax.random.uniform(rng, shape=shape, minval=low, maxval=high)\n else:\n return onp.random.default_rng(rng).uniform(size=shape, low=low, high=high)\n\n\ndef random_split(rng: ndarray, num: int = 2) -> ndarray:\n \"\"\"Splits a PRNG key into num new keys by adding a leading axis.\"\"\"\n if _which_np(rng) is jnp:\n return jax.random.split(rng, num=num)\n else:\n rng = onp.random.default_rng(rng)\n return rng.integers(low=0, high=2**32, dtype='uint32', size=(num, 2))\n\n\ndef randint(rng: ndarray, shape: Tuple[int, ...] = (),\n low: Optional[int] = 0, high: Optional[int] = 1) -> ndarray:\n \"\"\"Sample integers in [low, high) with given shape.\"\"\"\n if _which_np(rng) is jnp:\n return jax.random.randint(rng, shape=shape, minval=low, maxval=high)\n else:\n return onp.random.default_rng(rng).integers(low=low, high=high, size=shape)\n\n\ndef choice(rng: ndarray,\n a: Union[int, Any],\n shape: Tuple[int, ...] = (),\n replace: bool = True,\n p: Optional[Any] = None,\n axis: int = 0) -> ndarray:\n \"\"\"Generate sample(s) from given array.\"\"\"\n if _which_np(rng) is jnp:\n return jax.random.choice(\n rng, a, shape=shape, replace=replace, p=p, axis=axis)\n else:\n return onp.random.default_rng(rng).choice(\n a, size=shape, replace=replace, p=p, axis=axis)\n\n\ndef segment_sum(data: ndarray,\n segment_ids: ndarray,\n num_segments: Optional[int] = None) -> ndarray:\n \"\"\"Computes the sum within segments of an array.\"\"\"\n if _which_np(data, segment_ids) is jnp:\n s = jax.ops.segment_sum(data, segment_ids, num_segments)\n else:\n if num_segments is None:\n num_segments = onp.amax(segment_ids) + 1\n s = onp.zeros((num_segments,) + data.shape[1:])\n onp.add.at(s, segment_ids, data)\n return s\n\n\ndef top_k(operand: ndarray, k: int) -> ndarray:\n \"\"\"Returns top k values and their indices along the last axis of operand.\"\"\"\n if _which_np(operand) is jnp:\n return jax.lax.top_k(operand, k)\n else:\n ind = onp.argpartition(operand, -k)[-k:]\n return operand[ind], ind\n\n\ndef stack(x: List[ndarray], axis=0) -> ndarray:\n \"\"\"Join a sequence of arrays along a new axis.\"\"\"\n return _which_np(*x).stack(x, axis=axis)\n\n\ndef concatenate(x: Sequence[ndarray], axis=0) -> ndarray:\n \"\"\"Join a sequence of arrays along an existing axis.\"\"\"\n return _which_np(*x).concatenate(x, axis=axis)\n\n\ndef sqrt(x: ndarray) -> ndarray:\n \"\"\"Returns the non-negative square-root of an array, element-wise.\"\"\"\n return _which_np(x).sqrt(x)\n\n\ndef where(condition: ndarray, x: ndarray, y: ndarray) -> ndarray:\n \"\"\"Return elements chosen from `x` or `y` depending on `condition`.\"\"\"\n return _which_np(condition, x, y).where(condition, x, y)\n\n\ndef cond(pred, true_fun: Callable[..., bool], false_fun: Callable[..., bool],\n *operands: Any):\n \"\"\"Conditionally apply true_fun or false_fun to operands.\"\"\"\n if _in_jit():\n return jax.lax.cond(pred, true_fun, false_fun, *operands)\n else:\n if pred:\n return true_fun(operands)\n else:\n return false_fun(operands)\n\n\ndef diag(v: ndarray, k: int = 0) -> ndarray:\n \"\"\"Extract a diagonal or construct a diagonal array.\"\"\"\n return _which_np(v).diag(v, k)\n\n\ndef clip(a: ndarray, a_min: ndarray, a_max: ndarray) -> ndarray:\n \"\"\"Clip (limit) the values in an array.\"\"\"\n return _which_np(a, a_min, a_max).clip(a, a_min, a_max)\n\n\ndef eye(n: int) -> ndarray:\n \"\"\"Return a 2-D array with ones on the diagonal and zeros elsewhere.\"\"\"\n return _which_np().eye(n)\n\n\ndef zeros(shape, dtype=float) -> ndarray:\n \"\"\"Return a new array of given shape and type, filled with zeros.\"\"\"\n return _which_np().zeros(shape, dtype=dtype)\n\n\ndef zeros_like(a: ndarray) -> ndarray:\n \"\"\"Return an array of zeros with the same shape and type as a given array.\"\"\"\n return _which_np(a).zeros_like(a)\n\n\ndef ones(shape, dtype=float) -> ndarray:\n \"\"\"Return a new array of given shape and type, filled with ones.\"\"\"\n return _which_np().ones(shape, dtype=dtype)\n\n\ndef ones_like(a: ndarray) -> ndarray:\n \"\"\"Return an array of ones with the same shape and type as a given array.\"\"\"\n return _which_np(a).ones_like(a)\n\n\ndef reshape(a: ndarray, newshape: Union[Tuple[int, ...], int]) -> ndarray:\n \"\"\"Gives a new shape to an array without changing its data.\"\"\"\n return _which_np(a).reshape(a, newshape)\n\n\ndef atleast_1d(*arys) -> ndarray:\n \"\"\"Ensure arrays are all at least 1d (dimensions added to beginning).\"\"\"\n return _which_np(*arys).atleast_1d(*arys)\n\n\ndef atleast_2d(*arys) -> ndarray:\n \"\"\"Ensure arrays are all at least 2d (dimensions added to beginning).\"\"\"\n return _which_np(*arys).atleast_2d(*arys)\n\n\ndef atleast_3d(*arys) -> ndarray:\n \"\"\"Ensure arrays are all at least 3d (dimensions added to beginning).\"\"\"\n return _which_np(*arys).atleast_3d(*arys)\n\n\ndef array(object: Any, dtype=None) -> ndarray:\n \"\"\"Creates an array given a list.\"\"\"\n try:\n np = _which_np(*object)\n except TypeError:\n np = _which_np(object) # object is not iterable (e.g. primitive type)\n return np.array(object, dtype)\n\n\ndef abs(a: ndarray) -> ndarray:\n \"\"\"Calculate the absolute value element-wise.\"\"\"\n return _which_np(a).abs(a)\n\n\ndef meshgrid(*xi,\n copy: bool = True,\n sparse: bool = False,\n indexing: str = 'xy') -> ndarray:\n \"\"\"Create N-D coordinate matrices from 1D coordinate vectors.\"\"\"\n if _which_np(xi[0]) is jnp:\n return jnp.meshgrid(*xi, copy=copy, sparse=sparse, indexing=indexing)\n return onp.meshgrid(*xi, copy=copy, sparse=sparse, indexing=indexing)\n" ]
[ [ "numpy.add.at", "numpy.amax", "numpy.vstack", "numpy.linalg.norm", "numpy.stack", "numpy.copy", "numpy.argpartition", "numpy.meshgrid", "numpy.zeros", "numpy.random.default_rng" ] ]
Ophois47/Tensor-IMDB
[ "24c605756f2498861991b03ec96f7d6f2893d448" ]
[ "TensorReview.py" ]
[ "import tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\n\ndata = keras.datasets.imdb\n\n(train_data, train_labels), (test_data, test_labels) = data.load_data(num_words=88000)\n\nword_index = data.get_word_index()\n\nword_index = {k:(v+3) for k, v in word_index.items()}\nword_index[\"<PAD>\"] = 0\nword_index[\"<START>\"] = 1\nword_index[\"<UNK>\"] = 2\nword_index[\"<UNUSED>\"] = 3\n\nreverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\n\ntrain_data = keras.preprocessing.sequence.pad_sequences(train_data, value=word_index[\"<PAD>\"], padding=\"post\", maxlen=250)\ntest_data = keras.preprocessing.sequence.pad_sequences(test_data, value=word_index[\"<PAD>\"], padding=\"post\", maxlen=250)\n\ndef decode_review(text):\n return \" \".join([reverse_word_index.get(i, \"?\") for i in text])\n\ndef review_encode(s):\n encoded = [1]\n\n for word in s:\n if word.lower() in word_index:\n encoded.append(word_index[word.lower()])\n else:\n encoded.append(2)\n\n return encoded\n\n\nmodel = keras.models.load_model(\"model.h5\")\n\nwith open(\"TextReview.txt\", encoding=\"utf-8\") as f:\n for line in f.readlines():\n nline = line.replace(\",\", \"\").replace(\".\", \"\").replace(\"(\", \"\").replace(\")\", \"\").replace(\":\", \"\").replace(\"\\\"\", \"\").strip().split(\" \")\n encode = review_encode(nline)\n encode = keras.preprocessing.sequence.pad_sequences([encode], value=word_index[\"<PAD>\"], padding=\"post\", maxlen=250)\n predict = model.predict(encode)\n print(line)\n print(encode)\n print(predict[0])\n\n" ]
[ [ "tensorflow.keras.models.load_model", "tensorflow.keras.preprocessing.sequence.pad_sequences" ] ]
VecchioID/perceptual_decisions
[ "33f6712aa65d53f6b9c3a45c62fe1a31fe208d94" ]
[ "main.py" ]
[ "# -*- coding=utf-8 -*-\n# written by kai zhao\n# This is souce code for Cui, L., Tang, S., Zhao, K., Pan, J., Zhang, Z., Si, B., & Xu, N. L. (2021). \n# Asymmetrical choice-related ensemble activity in direct and indirect-pathway striatal neurons drives perceptual decisions. bioRxiv.\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.core.fromnumeric import mean\nimport scipy.io as io\nimport random\nimport numba\nfrom numba import jit\nimport time\n\ntime_start = time.time()\n\n\n@jit(nopython=True)\ndef relu(V):\n theta = -40.0 \n k = 1\n return k * np.log(1 + np.exp((V - theta) / k))\n\n\n@jit(nopython=True)\ndef prefer_neurons(perdefinedAmp, prefer, q, sigma):\n dt = 0.001\n I = perdefinedAmp\n sig = sigma\n cortexResponse = np.zeros(3000)\n delta = I * (1. / (1. + np.exp(prefer * (q - 10.) / sig)))\n\n for i in range(1000):\n cortexResponse[i + 1] = cortexResponse[i] + (delta - cortexResponse[i]) * dt / 0.01\n cortexResponse[1000:3000] = 0.\n return cortexResponse\n\n\ndef optogenetic(I_stim):\n return I_stim\n\n\n@jit(nopython=True)\ndef brain_model(f_cortex_L, f_cortex_R, I_D1L_Inhi, I_D2L_Inhi, I_PVL_Inhi):\n T = 3.0\n dt = 0.001\n n = int(T / dt)\n t = np.linspace(0., T, n)\n tau = 0.05\n E = -55.\n E1 = -65.\n E2 = 0.\n\n V_D1L_contra = np.ones(n) * E\n V_D1L_ipsi = np.ones(n) * E\n V_D2L_contra = np.ones(n) * E\n V_D2L_ipsi = np.ones(n) * E\n V_PVL = np.ones(n) * E\n\n V_D1R_contra = np.ones(n) * E\n V_D1R_ipsi = np.ones(n) * E\n V_D2R_contra = np.ones(n) * E\n V_D2R_ipsi = np.ones(n) * E\n V_PVR = np.ones(n) * E\n\n f_D1L_contra = np.ones(n) * relu(-55.)\n f_D1L_ipsi = np.ones(n) * relu(-55.)\n f_D2L_contra = np.ones(n) * relu(-55.)\n f_D2L_ipsi = np.ones(n) * relu(-55.)\n\n f_D1R_contra = np.ones(n) * relu(-55.)\n f_D1R_ipsi = np.ones(n) * relu(-55.)\n f_D2R_contra = np.ones(n) * relu(-55.)\n f_D2R_ipsi = np.ones(n) * relu(-55.)\n\n I_D1Lcontra_extern = np.zeros(n)\n I_D1Lcontra_intern = np.zeros(n)\n I_D1Lipsi_extern = np.zeros(n)\n I_D1Lipsi_intern = np.zeros(n)\n I_D2Lcontra_extern = np.zeros(n)\n I_D2Lcontra_intern = np.zeros(n)\n I_D2Lipsi_extern = np.zeros(n)\n I_D2Lipsi_intern = np.zeros(n)\n\n I_D1Rcontra_extern = np.zeros(n)\n I_D1Rcontra_intern = np.zeros(n)\n I_D1Ripsi_extern = np.zeros(n)\n I_D1Ripsi_intern = np.zeros(n)\n I_D2Rcontra_extern = np.zeros(n)\n I_D2Rcontra_intern = np.zeros(n)\n I_D2Ripsi_extern = np.zeros(n)\n I_D2Ripsi_intern = np.zeros(n)\n\n I_PVL_self_inhi = np.zeros(n)\n I_D1Lcontra_self_inhi = np.zeros(n)\n I_D1Lipsi_self_inhi = np.zeros(n)\n I_D2Lcontra_self_inhi = np.zeros(n)\n I_D2Lipsi_self_inhi = np.zeros(n)\n\n I_PVR_self_inhi = np.zeros(n)\n I_D1Rcontra_self_inhi = np.zeros(n)\n I_D1Ripsi_self_inhi = np.zeros(n)\n I_D2Rcontra_self_inhi = np.zeros(n)\n I_D2Ripsi_self_inhi = np.zeros(n)\n\n w_self_inhi = 0.6\n w_PV_D1D2_Wweights = 29.4\n w_D1Lipsi_D1Lcontra = 0.01\n w_D2Lcontra_D1Lcontra = 0.01\n w_D2Lipsi_D1Lcontra = 0.01\n w_PVL_D1Lcontra = w_PV_D1D2_Wweights\n\n w_D1Lcontra_D1Lipsi = 0.01\n w_D2Lcontra_D1Lipsi = 0.01\n w_D2Lipsi_D1Lipsi = 0.01\n w_PVL_D1Lipsi = w_PV_D1D2_Wweights\n\n w_D1Lcontra_D2Lcontra = 0.01\n w_D1Lipsi_D2Lcontra = 0.01\n w_D2Lipsi_D2Lcontra = 0.01\n w_PVL_D2Lcontra = w_PV_D1D2_Wweights\n\n w_D1Lcontra_D2Lipsi = 0.01\n w_D1Lipsi_D2Lipsi = 0.01\n w_D2Lcontra_D2Lipsi = 0.01\n w_PVL_D2Lipsi = w_PV_D1D2_Wweights\n\n prep_L = np.zeros(n)\n f_PVL = np.ones(n) * relu(-55.)\n I_PVL_extern = np.zeros(n)\n f_PVR = np.ones(n) * relu(-55.)\n I_PVR_extern = np.zeros(n)\n w_cortexL_PVL = 0.015 # 2.352\n w_cortexR_PVL = 0.015\n\n w_cortexL_D1Lcontra = 0.80\n w_cortexL_D2Lcontra = 0.70\n w_cortexL_D1Lipsi = 0.12\n w_cortexL_D2Lipsi = 0.06\n\n w_cortexR_D1Lcontra = 0.051\n w_cortexR_D2Lcontra = 0.04\n w_cortexR_D1Lipsi = 0.60\n w_cortexR_D2Lipsi = 0.456\n\n w_cortexL_D1Rcontra = 0.051\n w_cortexL_D2Rcontra = 0.04\n w_cortexL_D1Ripsi = 0.60\n w_cortexL_D2Ripsi = 0.456\n\n w_cortexR_D1Rcontra = 0.80\n w_cortexR_D2Rcontra = 0.70\n w_cortexR_D1Ripsi = 0.12\n w_cortexR_D2Ripsi = 0.06\n\n sigma = 0.05\n noise_tau = 0.2\n sigma_bis = sigma * np.sqrt(2. / noise_tau)\n sqrtdt = np.sqrt(dt)\n\n for i in range(n - 1):\n I_PVL_extern[i] = (E2 - V_PVL[i]) * (f_cortex_L[i] * w_cortexL_PVL + f_cortex_R[i] * w_cortexR_PVL)\n I_alpha_ext = I_PVL_extern\n I_PVL_self_inhi[i] = (E1 - V_PVL[i]) * f_PVL[i] * w_self_inhi\n V_PVL[i + 1] = V_PVL[i] + (E - V_PVL[i] + I_alpha_ext[i] + I_PVL_self_inhi[\n i] - I_PVL_Inhi) * dt / tau + sigma_bis * sqrtdt * np.random.randn()\n if V_PVL[i + 1] < -65:\n V_PVL[i + 1] = -65\n f_PVL[i + 1] = relu(V_PVL[i + 1])\n\n I_D1Lcontra_extern[i] = (E2 - V_D1L_contra[i]) * (\n f_cortex_L[i] * w_cortexL_D1Lcontra + f_cortex_R[i] * w_cortexR_D1Lcontra)\n I_alpha_ext = I_D1Lcontra_extern\n I_D1Lcontra_intern[i] = (E1 - V_D1L_contra[i]) * (\n f_D1L_ipsi[i] * w_D1Lipsi_D1Lcontra + f_D2L_contra[i] * w_D2Lcontra_D1Lcontra + f_D2L_ipsi[\n i] * w_D2Lipsi_D1Lcontra + f_PVL[i] * w_PVL_D1Lcontra + f_D1R_contra[i] * 0.0)\n I_alpha_int = I_D1Lcontra_intern\n I_D1Lcontra_self_inhi[i] = (E1 - V_D1L_contra[i]) * f_D1L_contra[i] * w_self_inhi\n V_D1L_contra[i + 1] = V_D1L_contra[i] + (\n E - V_D1L_contra[i] + I_alpha_ext[i] + I_alpha_int[i] + I_D1Lcontra_self_inhi[\n i] - I_D1L_Inhi) * dt / tau + sigma_bis * sqrtdt * np.random.randn()\n if V_D1L_contra[i + 1] < -65:\n V_D1L_contra[i + 1] = -65\n f_D1L_contra[i + 1] = relu(V_D1L_contra[i + 1])\n\n I_D1Lipsi_extern[i] = (E2 - V_D1L_ipsi[i]) * (\n f_cortex_L[i] * w_cortexL_D1Lipsi + f_cortex_R[i] * w_cortexR_D1Lipsi)\n I_alpha_ext = I_D1Lipsi_extern\n I_D1Lipsi_intern[i] = (E1 - V_D1L_ipsi[i]) * (\n f_D1L_contra[i] * w_D1Lcontra_D1Lipsi + f_D2L_contra[i] * w_D2Lcontra_D1Lipsi + f_D2L_ipsi[\n i] * w_D2Lipsi_D1Lipsi + f_PVL[i] * w_PVL_D1Lipsi)\n I_alpha_int = I_D1Lipsi_intern\n I_D1Lipsi_self_inhi[i] = (E1 - V_D1L_ipsi[i]) * f_D1L_ipsi[i] * w_self_inhi\n\n V_D1L_ipsi[i + 1] = V_D1L_ipsi[i] + (E - V_D1L_ipsi[i] + I_alpha_ext[i] + I_alpha_int[i] + I_D1Lipsi_self_inhi[\n i] - I_D1L_Inhi) * dt / tau + sigma_bis * sqrtdt * np.random.randn()\n if V_D1L_ipsi[i + 1] < -65:\n V_D1L_ipsi[i + 1] = -65\n\n f_D1L_ipsi[i + 1] = relu(V_D1L_ipsi[i + 1])\n\n I_D2Lcontra_extern[i] = (E2 - V_D2L_contra[i]) * (\n f_cortex_L[i] * w_cortexL_D2Lcontra + f_cortex_R[i] * w_cortexR_D2Lcontra)\n I_alpha_ext = I_D2Lcontra_extern\n I_D2Lcontra_intern[i] = (E1 - V_D2L_contra[i]) * (\n f_D1L_contra[i] * w_D1Lcontra_D2Lcontra + f_D1L_ipsi[i] * w_D1Lipsi_D2Lcontra + f_D2L_ipsi[\n i] * w_D2Lipsi_D2Lcontra + f_PVL[i] * w_PVL_D2Lcontra + f_D2R_contra[i] * 0.0)\n I_alpha_int = I_D2Lcontra_intern\n I_D2Lcontra_self_inhi[i] = (E1 - V_D2L_contra[i]) * f_D2L_contra[i] * w_self_inhi\n\n V_D2L_contra[i + 1] = V_D2L_contra[i] + (\n E - V_D2L_contra[i] + I_alpha_ext[i] + I_alpha_int[i] + I_D2Lcontra_self_inhi[\n i] - I_D2L_Inhi) * dt / tau + sigma_bis * sqrtdt * np.random.randn()\n if V_D2L_contra[i + 1] < -65:\n V_D2L_contra[i + 1] = -65\n\n f_D2L_contra[i + 1] = relu(V_D2L_contra[i + 1])\n\n I_D2Lipsi_extern[i] = (E2 - V_D2L_ipsi[i]) * (\n f_cortex_L[i] * w_cortexL_D2Lipsi + f_cortex_R[i] * w_cortexR_D2Lipsi)\n I_alpha_ext = I_D2Lipsi_extern\n I_D2Lipsi_intern[i] = (E1 - V_D2L_ipsi[i]) * (\n f_D1L_contra[i] * w_D1Lcontra_D2Lipsi + f_D1L_ipsi[i] * w_D1Lipsi_D2Lipsi + f_D2L_contra[\n i] * w_D2Lcontra_D2Lipsi + f_PVL[i] * w_PVL_D2Lipsi)\n I_alpha_int = I_D2Lipsi_intern\n I_D2Lipsi_self_inhi[i] = (E1 - V_D2L_ipsi[i]) * f_D2L_ipsi[i] * w_self_inhi\n\n V_D2L_ipsi[i + 1] = V_D2L_ipsi[i] + (E - V_D2L_ipsi[i] + I_alpha_ext[i] + I_alpha_int[i] + I_D2Lipsi_self_inhi[\n i] - I_D2L_Inhi) * dt / tau + sigma_bis * sqrtdt * np.random.randn()\n if V_D2L_ipsi[i + 1] < -65:\n V_D2L_ipsi[i + 1] = -65\n\n f_D2L_ipsi[i + 1] = relu(V_D2L_ipsi[i + 1])\n\n I_PVR_extern[i] = (E2 - V_PVR[i]) * (f_cortex_L[i] * w_cortexL_PVL + f_cortex_R[i] * w_cortexR_PVL)\n I_alpha_ext = I_PVR_extern\n I_PVR_self_inhi[i] = (E1 - V_PVR[i]) * f_PVR[i] * w_self_inhi\n V_PVR[i + 1] = V_PVR[i] + (E - V_PVR[i] + I_alpha_ext[i] + I_PVR_self_inhi[\n i]) * dt / tau + sigma_bis * sqrtdt * np.random.randn()\n if V_PVR[i + 1] < -65:\n V_PVR[i + 1] = -65\n f_PVR[i + 1] = relu(V_PVR[i + 1])\n\n I_D1Rcontra_extern[i] = (E2 - V_D1R_contra[i]) * (\n f_cortex_L[i] * w_cortexL_D1Rcontra + f_cortex_R[i] * w_cortexR_D1Rcontra)\n I_alpha_ext = I_D1Rcontra_extern\n I_D1Rcontra_intern[i] = (E1 - V_D1R_contra[i]) * (\n f_D1R_ipsi[i] * w_D1Lipsi_D1Lcontra + f_D2R_contra[i] * w_D2Lcontra_D1Lcontra + f_D2R_ipsi[\n i] * w_D2Lipsi_D1Lcontra + f_PVR[i] * w_PVL_D1Lcontra + f_D1L_contra[i] * 0.0)\n I_alpha_int = I_D1Rcontra_intern\n I_D1Rcontra_self_inhi[i] = (E1 - V_D1R_contra[i]) * f_D1R_contra[i] * w_self_inhi\n\n V_D1R_contra[i + 1] = V_D1R_contra[i] + (\n E - V_D1R_contra[i] + I_alpha_ext[i] + I_alpha_int[i] + I_D1Rcontra_self_inhi[\n i]) * dt / tau + sigma_bis * sqrtdt * np.random.randn()\n if V_D1R_contra[i + 1] < -65:\n V_D1R_contra[i + 1] = -65\n f_D1R_contra[i + 1] = relu(V_D1R_contra[i + 1])\n\n I_D1Ripsi_extern[i] = (E2 - V_D1R_ipsi[i]) * (\n f_cortex_L[i] * w_cortexL_D1Ripsi + f_cortex_R[i] * w_cortexR_D1Ripsi)\n I_alpha_ext = I_D1Ripsi_extern\n I_D1Ripsi_intern[i] = (E1 - V_D1R_ipsi[i]) * (\n f_D1R_contra[i] * w_D1Lcontra_D1Lipsi + f_D2R_contra[i] * w_D2Lcontra_D1Lipsi + f_D2R_ipsi[\n i] * w_D2Lipsi_D1Lipsi + f_PVR[i] * w_PVL_D1Lipsi)\n I_alpha_int = I_D1Ripsi_intern\n I_D1Ripsi_self_inhi[i] = (E1 - V_D1R_ipsi[i]) * f_D1R_ipsi[i] * w_self_inhi\n V_D1R_ipsi[i + 1] = V_D1R_ipsi[i] + (E - V_D1R_ipsi[i] + I_alpha_ext[i] + I_alpha_int[i] + I_D1Ripsi_self_inhi[\n i]) * dt / tau + sigma_bis * sqrtdt * np.random.randn()\n if V_D1R_ipsi[i + 1] < -65:\n V_D1R_ipsi[i + 1] = -65\n f_D1R_ipsi[i + 1] = relu(V_D1R_ipsi[i + 1])\n\n I_D2Rcontra_extern[i] = (E2 - V_D2R_contra[i]) * (\n f_cortex_L[i] * w_cortexL_D2Rcontra + f_cortex_R[i] * w_cortexR_D2Rcontra)\n I_alpha_ext = I_D2Rcontra_extern\n I_D2Rcontra_intern[i] = (E1 - V_D2R_contra[i]) * (\n f_D1R_contra[i] * w_D1Lcontra_D2Lcontra + f_D1R_ipsi[i] * w_D1Lipsi_D2Lcontra + f_D2R_ipsi[\n i] * w_D2Lipsi_D2Lcontra + f_PVR[i] * w_PVL_D2Lcontra + f_D2L_contra[i] * 0.0)\n I_alpha_int = I_D2Rcontra_intern\n I_D2Rcontra_self_inhi[i] = (E1 - V_D2R_contra[i]) * f_D2R_contra[i] * w_self_inhi\n V_D2R_contra[i + 1] = V_D2R_contra[i] + (\n E - V_D2R_contra[i] + I_alpha_ext[i] + I_alpha_int[i] + I_D2Rcontra_self_inhi[\n i]) * dt / tau + sigma_bis * sqrtdt * np.random.randn()\n if V_D2R_contra[i + 1] < -65:\n V_D2R_contra[i + 1] = -65\n f_D2R_contra[i + 1] = relu(V_D2R_contra[i + 1])\n\n I_D2Ripsi_extern[i] = (E2 - V_D2R_ipsi[i]) * (\n f_cortex_L[i] * w_cortexL_D2Ripsi + f_cortex_R[i] * w_cortexR_D2Ripsi)\n I_alpha_ext = I_D2Ripsi_extern\n I_D2Ripsi_intern[i] = (E1 - V_D2R_ipsi[i]) * (\n f_D1R_contra[i] * w_D1Lcontra_D2Lipsi + f_D1R_ipsi[i] * w_D1Lipsi_D2Lipsi + f_D2R_contra[\n i] * w_D2Lcontra_D2Lipsi + f_PVR[i] * w_PVL_D2Lipsi)\n I_alpha_int = I_D2Ripsi_intern\n I_D2Ripsi_self_inhi[i] = (E1 - V_D2R_ipsi[i]) * f_D2R_ipsi[i] * w_self_inhi\n V_D2R_ipsi[i + 1] = V_D2R_ipsi[i] + (E - V_D2R_ipsi[i] + I_alpha_ext[i] + I_alpha_int[i] + I_D2Ripsi_self_inhi[\n i]) * dt / tau + sigma_bis * sqrtdt * np.random.randn()\n if V_D2R_ipsi[i + 1] < -65:\n V_D2R_ipsi[i + 1] = -65\n f_D2R_ipsi[i + 1] = relu(V_D2R_ipsi[i + 1])\n return f_D1L_contra, f_D1L_ipsi, f_D2L_contra, f_D2L_ipsi, f_D1R_contra, f_D1R_ipsi, f_D2R_contra, f_D2R_ipsi\n\n\n@jit(nopython=True)\ndef SNr_model(f_D1L_contra, f_D1L_ipsi, f_D2L_contra, f_D2L_ipsi, f_D1R_contra, f_D1R_ipsi, f_D2R_contra, f_D2R_ipsi):\n T = 3.0\n dt = 0.001\n n = int(T / dt)\n t = np.linspace(0., T, n)\n tau = 0.1\n E = -55.\n E1 = -65.\n E2 = 0.\n V_middle_init = -50.\n\n w_D2_middle = 0.1\n w_middle_SNr = 0.01\n w_d1_snr = 0.055\n\n w_snr_self_inhi = 0.01\n w_snr_eachother_inhi = 0.01\n\n I_SNrL_inhi = np.zeros(n)\n I_SNrL_exci = np.zeros(n)\n I_SNrR_inhi = np.zeros(n)\n I_SNrR_exci = np.zeros(n)\n V_SNrL = np.ones(n) * E\n V_SNrR = np.ones(n) * E\n\n I_from_SNrL_inhi = np.zeros(n)\n I_SNrL_self_inhi = np.zeros(n)\n I_SNrR_self_inhi = np.zeros(n)\n I_from_SNrR_inhi = np.zeros(n)\n\n f_SNrL = np.ones(n) * relu(-55.)\n f_SNrR = np.ones(n) * relu(-55.)\n\n sigma = 0.035\n noise_tau = 0.05\n sigma_bis = sigma * np.sqrt(2. / noise_tau)\n sqrtdt = np.sqrt(dt)\n for i in range(n - 1):\n I_SNrL_inhi[i] = (E1 - V_SNrL[i]) * w_d1_snr * (f_D1L_contra[i] + f_D1L_ipsi[i])\n I_from_SNrR_inhi[i] = (E1 - V_SNrL[i]) * f_SNrR[i] * w_snr_eachother_inhi\n I_SNrL_self_inhi[i] = (E1 - V_SNrL[i]) * w_snr_self_inhi * f_SNrL[i]\n I_SNrL_exci[i] = (E2 - V_SNrL[i]) * w_middle_SNr * (f_D2L_contra[i] + f_D2L_ipsi[i])\n\n V_SNrL[i + 1] = V_SNrL[i] + (\n E - V_SNrL[i] + I_SNrL_inhi[i] + I_SNrL_exci[i] + I_from_SNrR_inhi[i] + I_SNrL_self_inhi[\n i]) * dt / tau + sigma_bis * sqrtdt * np.random.randn()\n if V_SNrL[i + 1] < -65:\n V_SNrL[i + 1] = -65\n f_SNrL[i + 1] = relu(V_SNrL[i + 1])\n\n I_SNrR_inhi[i] = (E1 - V_SNrR[i]) * w_d1_snr * (f_D1R_contra[i] + f_D1R_ipsi[i])\n I_from_SNrL_inhi[i] = (E1 - V_SNrR[i]) * f_SNrL[i] * w_snr_eachother_inhi\n I_SNrR_self_inhi[i] = (E1 - V_SNrR[i]) * w_snr_self_inhi * f_SNrR[i]\n I_SNrR_exci[i] = (E2 - V_SNrR[i]) * w_middle_SNr * (f_D2R_contra[i] + f_D2R_ipsi[i])\n\n V_SNrR[i + 1] = V_SNrR[i] + (\n E - V_SNrR[i] + I_SNrR_inhi[i] + I_SNrR_exci[i] + I_from_SNrL_inhi[i] + I_SNrR_self_inhi[\n i]) * dt / tau + sigma_bis * sqrtdt * np.random.randn()\n if V_SNrR[i + 1] < -65:\n V_SNrR[i + 1] = -65\n f_SNrR[i + 1] = relu(V_SNrR[i + 1])\n\n return f_SNrL, f_SNrR\n\n\n@jit(nopython=True)\ndef confidence_model(freq):\n dt = 0.001\n sigma = 0.05\n tau = 0.05\n sigma_bis = sigma * np.sqrt(2. / tau)\n sqrtdt = np.sqrt(dt)\n\n x = random.uniform(0, 1)\n freq = freq - 10\n prob = 0.5 * np.exp(-(np.power(freq, 2) / 5.)) + sigma_bis * sqrtdt * np.random.randn()\n if x < prob:\n select_prefer = 1.\n else:\n select_prefer = -1.\n return select_prefer\n\n\ndef main_loop(stim_value, total_Sessions, Trial_repeat, I_D1L_Inhi, I_D2L_Inhi, I_PVL_Inhi):\n t_start = 300\n t_end = 3000\n\n freq = [0.0, 2.86, 5.71, 8.57, 11.43, 14.29, 17.14, 20.00]\n\n arr_rightward = np.array([])\n total_SNrL = np.array([])\n total_SNrR = np.array([])\n for session in range(total_Sessions):\n rightward = np.array([])\n SNrL_var = np.array([])\n SNrR_var = np.array([])\n for i in range(8):\n left_choice = 0\n right_choice = 0\n for trials in range(Trial_repeat):\n prefer_prob = confidence_model(freq[i])\n\n f_cortex_L = prefer_neurons(20., prefer_prob, freq[i], 0.000001)\n f_cortex_R = prefer_neurons(20., -1. * prefer_prob, freq[i], 0.000001)\n f_cortex_L[0] = 0.\n f_cortex_R[0] = 0.\n\n f_D1L_contra, f_D1L_ipsi, f_D2L_contra, f_D2L_ipsi, f_D1R_contra, f_D1R_ipsi, f_D2R_contra, f_D2R_ipsi = brain_model(\n f_cortex_L, f_cortex_R, I_D1L_Inhi, I_D2L_Inhi, I_PVL_Inhi)\n\n SNrL, SNrR = SNr_model(f_D1L_contra, f_D1L_ipsi, f_D2L_contra, f_D2L_ipsi, f_D1R_contra, f_D1R_ipsi,\n f_D2R_contra, f_D2R_ipsi)\n\n var = SNrL[t_start:t_end] - SNrR[t_start:t_end]\n single_var = np.abs(SNrL[t_start:t_end] - SNrR[t_start:t_end])\n index = np.where(single_var > 0.00)\n if var[index[0][0]] >= 0:\n left_choice = left_choice + 1\n else:\n right_choice = right_choice + 1\n rightward = np.append(rightward, right_choice)\n\n arr_rightward = np.append(arr_rightward, rightward, axis=0)\n\n arr_rightward = arr_rightward.reshape((total_Sessions, 8))\n locals()['arr_rightward_' + str(stim_value)] = arr_rightward\n io.savemat('arr_rightward_' + str(stim_value) + '.mat',\n {'arr_rightward_' + str(stim_value): eval('arr_rightward_' + str(stim_value))})\n\n\nnum_split = 1\ntotal_Sessions = 22\nTrial_repeat = 1000\nrange_of_stim_I_current = np.linspace(4.5, 4.5, num_split)\nprint(range_of_stim_I_current)\n\nfor i in range(num_split):\n D1L_Inhi = 0\n D2L_Inhi = 0\n PVL_Inhi = 0\n Semi_Inhi = 0\n D1L_Exci = 0\n D2L_Exci = 0\n\n if D1L_Inhi:\n I_D1L_Inhi = range_of_stim_I_current[i]\n else:\n I_D1L_Inhi = 0.\n\n if D2L_Inhi:\n I_D2L_Inhi = range_of_stim_I_current[i]\n else:\n I_D2L_Inhi = 0.\n\n if PVL_Inhi:\n I_PVL_Inhi = range_of_stim_I_current[i]\n else:\n I_PVL_Inhi = 0.\n\n if Semi_Inhi:\n I_D1L_Inhi = range_of_stim_I_current[i]\n I_D2L_Inhi = range_of_stim_I_current[i]\n I_PVL_Inhi = range_of_stim_I_current[i]\n elif D1L_Inhi or D2L_Inhi or PVL_Inhi:\n I_D1L_Inhi\n I_D2L_Inhi\n I_PVL_Inhi\n else:\n I_D1L_Inhi = 0.\n I_D2L_Inhi = 0.\n I_PVL_Inhi = 0.\n\n if D1L_Exci:\n I_D1L_Inhi = -range_of_stim_I_current[i]\n elif D1L_Inhi or Semi_Inhi:\n I_D1L_Inhi\n else:\n I_D1L_Inhi = 0.\n\n if D2L_Exci:\n I_D2L_Inhi = -range_of_stim_I_current[i]\n elif D2L_Inhi or Semi_Inhi:\n I_D2L_Inhi\n else:\n I_D2L_Inhi = 0.\n\n stim_value = i + 1\n main_loop(stim_value, total_Sessions, Trial_repeat, I_D1L_Inhi, I_D2L_Inhi, I_PVL_Inhi)\nplt.show()\ntime_end = time.time()\nprint('Time total cost', time_end - time_start, 's')\n" ]
[ [ "numpy.sqrt", "numpy.linspace", "numpy.abs", "numpy.power", "numpy.ones", "numpy.append", "numpy.random.randn", "numpy.exp", "numpy.array", "numpy.zeros", "numpy.where", "matplotlib.pyplot.show" ] ]
SAP-samples/security-research-dp-hierarchical-text
[ "100a010502013cedcf73c88ec128e8b4d1ab5700" ]
[ "dph/core/parameters/parameters.py" ]
[ "import tensorflow as tf\n\n\nclass Parameters(object):\n def __init__(self):\n self.experiment_name = \"\"\n self.dataset = None\n self.batch_size_train = 32\n self.batch_size_val = 32\n self.num_epochs = 30\n self.features = None\n self.seed = 42\n self.learning_rate = None\n self.patience = 3\n self.num_gpu = len(tf.config.list_physical_devices('GPU')) or 1\n\n def from_dict(self, parameters):\n if parameters is not None:\n for parameter_name, value in parameters.items():\n self.__setattr__(parameter_name, value)\n\n def get_parameters(self):\n return self.__dict__\n\n\nclass DPParameters(Parameters):\n def __init__(self, noise_multiplier, clipnorm, microbatch_size=1):\n super(DPParameters, self).__init__()\n self.sigma = None\n self.experiment_name = \"dp_\"\n self.noise_multiplier = noise_multiplier\n self.clipnorm = clipnorm\n # Set num_microbatches_per_gpu to batch_size by default\n self.microbatch_size = microbatch_size\n self.hidden_dropout_prob = 0\n self.batch_size_train *= 2\n self.batch_size_val *= 2\n self.num_epochs = 100\n\n\nclass AdamWParameters(Parameters):\n def __init__(self):\n super(AdamWParameters, self).__init__()\n self.num_epochs = 2\n self.experiment_name = \"w_\"\n" ]
[ [ "tensorflow.config.list_physical_devices" ] ]
pulkit4tech/Tracking-Visually-Salient-Object
[ "c9d67a2f8eb2929e11155a036bf791d922a992da" ]
[ "tracking.py" ]
[ "import cv2\nimport numpy as np\nimport copy\n\n\nclass MultipleObjectsTracker:\n \"\"\"Multiple-objects tracker\n This class implements an algorithm for tracking multiple objects in\n a video sequence.\n The algorithm combines a saliency map for object detection and\n mean-shift tracking for object tracking.\n \"\"\"\n\n def __init__(self, min_area=400, min_shift2=5):\n \"\"\"Constructor\n This method initializes the multiple-objects tracking algorithm.\n :param min_area: Minimum area for a proto-object contour to be\n considered a real object\n :param min_shift2: Minimum distance for a proto-object to drift\n from frame to frame ot be considered a real\n object\n \"\"\"\n self.object_roi = []\n self.object_box = []\n\n self.min_cnt_area = min_area\n self.min_shift2 = min_shift2\n\n # Setup the termination criteria, either 100 iteration or move by at\n # least 1 pt\n self.term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,\n 100, 1)\n\n def advance_frame(self, frame, proto_objects_map):\n \"\"\"Advances the algorithm by a single frame\n This method tracks all objects via the following steps:\n - adds all bounding boxes from saliency map as potential\n targets\n - finds bounding boxes from previous frame in current frame\n via mean-shift tracking\n - combines the two lists by removing duplicates\n certain targets are discarded:\n - targets that are too small\n - targets that don't move\n :param frame: New input RGB frame\n :param proto_objects_map: corresponding proto-objects map of the\n frame\n :returns: frame annotated with bounding boxes around all objects\n that are being tracked\n \"\"\"\n self.tracker = copy.deepcopy(frame)\n\n # build a list of all bounding boxes\n box_all = []\n\n # append to the list all bounding boxes found from the\n # current proto-objects map\n box_all = self._append_boxes_from_saliency(proto_objects_map, box_all)\n\n # find all bounding boxes extrapolated from last frame\n # via mean-shift tracking\n box_all = self._append_boxes_from_meanshift(frame, box_all)\n\n # only keep those that are both salient and in mean shift\n if len(self.object_roi) == 0:\n group_thresh = 0 # no previous frame: keep all form saliency\n else:\n group_thresh = 1 # previous frame + saliency\n box_grouped, _ = cv2.groupRectangles(box_all, group_thresh, 0.1)\n\n # update mean-shift bookkeeping for remaining boxes\n self._update_mean_shift_bookkeeping(frame, box_grouped)\n\n # draw remaining boxes\n for (x, y, w, h) in box_grouped:\n cv2.rectangle(self.tracker, (x, y), (x + w, y + h),\n (0, 255, 0), 2)\n\n return self.tracker\n\n def _append_boxes_from_saliency(self, proto_objects_map, box_all):\n \"\"\"Adds to the list all bounding boxes found with the saliency map\n A saliency map is used to find objects worth tracking in each\n frame. This information is combined with a mean-shift tracker\n to find objects of relevance that move, and to discard everything\n else.\n :param proto_objects_map: proto-objects map of the current frame\n :param box_all: append bounding boxes from saliency to this list\n :returns: new list of all collected bounding boxes\n \"\"\"\n # find all bounding boxes in new saliency map\n box_sal = []\n cnt_sal, _ = cv2.findContours(proto_objects_map, 1, 2)\n for cnt in cnt_sal:\n # discard small contours\n if cv2.contourArea(cnt) < self.min_cnt_area:\n continue\n\n # otherwise add to list of boxes found from saliency map\n box = cv2.boundingRect(cnt)\n box_all.append(box)\n\n return box_all\n\n def _append_boxes_from_meanshift(self, frame, box_all):\n \"\"\"Adds to the list all bounding boxes found with mean-shift tracking\n Mean-shift tracking is used to track objects from frame to frame.\n This information is combined with a saliency map to discard\n false-positives and focus only on relevant objects that move.\n :param frame: current RGB image frame\n :box_all: append bounding boxes from tracking to this list\n :returns: new list of all collected bounding boxes\n \"\"\"\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n for i in xrange(len(self.object_roi)):\n roi_hist = copy.deepcopy(self.object_roi[i])\n box_old = copy.deepcopy(self.object_box[i])\n\n dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)\n ret, box_new = cv2.meanShift(dst, tuple(box_old), self.term_crit)\n self.object_box[i] = copy.deepcopy(box_new)\n\n # discard boxes that don't move\n (xo, yo, wo, ho) = box_old\n (xn, yn, wn, hn) = box_new\n\n co = [xo + wo / 2, yo + ho / 2]\n cn = [xn + wn / 2, yn + hn / 2]\n if (co[0] - cn[0])**2 + (co[1] - cn[1])**2 >= self.min_shift2:\n box_all.append(box_new)\n\n return box_all\n\n def _update_mean_shift_bookkeeping(self, frame, box_grouped):\n \"\"\"Preprocess all valid bounding boxes for mean-shift tracking\n This method preprocesses all relevant bounding boxes (those that\n have been detected by both mean-shift tracking and saliency) for\n the next mean-shift step.\n :param frame: current RGB input frame\n :param box_grouped: list of bounding boxes\n \"\"\"\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n self.object_roi = []\n self.object_box = []\n for box in box_grouped:\n (x, y, w, h) = box\n hsv_roi = hsv[y:y + h, x:x + w]\n mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)),\n np.array((180., 255., 255.)))\n roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0, 180])\n cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)\n\n self.object_roi.append(roi_hist)\n self.object_box.append(box)\n" ]
[ [ "numpy.array" ] ]
andresDatyra/superset
[ "dd3aaaa42e293f9d21cb6ca614bd84b561e0e9dc" ]
[ "tests/utils_tests.py" ]
[ "# 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# isort:skip_file\nimport unittest\nimport uuid\nfrom datetime import date, datetime, time, timedelta\nfrom decimal import Decimal\nimport hashlib\nimport json\nimport os\nimport re\nfrom unittest.mock import Mock, patch\nfrom tests.fixtures.birth_names_dashboard import load_birth_names_dashboard_with_slices\n\nimport numpy\nimport pytest\nfrom flask import Flask, g\nimport marshmallow\nfrom sqlalchemy.exc import ArgumentError\n\nimport tests.test_app\nfrom superset import app, db, security_manager\nfrom superset.exceptions import CertificateException, SupersetException\nfrom superset.models.core import Database, Log\nfrom superset.models.dashboard import Dashboard\nfrom superset.models.slice import Slice\nfrom superset.utils.core import (\n base_json_conv,\n cast_to_num,\n convert_legacy_filters_into_adhoc,\n create_ssl_cert_file,\n format_timedelta,\n get_form_data_token,\n get_iterable,\n get_email_address_list,\n get_or_create_db,\n get_stacktrace,\n json_int_dttm_ser,\n json_iso_dttm_ser,\n JSONEncodedDict,\n memoized,\n merge_extra_filters,\n merge_request_params,\n parse_ssl_cert,\n parse_js_uri_path_item,\n split,\n TimeRangeEndpoint,\n validate_json,\n zlib_compress,\n zlib_decompress,\n)\nfrom superset.utils import schema\nfrom superset.views.utils import (\n build_extra_filters,\n get_form_data,\n get_time_range_endpoints,\n)\nfrom tests.base_tests import SupersetTestCase\nfrom tests.fixtures.world_bank_dashboard import load_world_bank_dashboard_with_slices\n\nfrom .fixtures.certificates import ssl_certificate\n\n\ndef mock_to_adhoc(filt, expressionType=\"SIMPLE\", clause=\"where\"):\n result = {\"clause\": clause.upper(), \"expressionType\": expressionType}\n\n if expressionType == \"SIMPLE\":\n result.update(\n {\"comparator\": filt[\"val\"], \"operator\": filt[\"op\"], \"subject\": filt[\"col\"]}\n )\n elif expressionType == \"SQL\":\n result.update({\"sqlExpression\": filt[clause]})\n\n return result\n\n\nclass TestUtils(SupersetTestCase):\n def test_json_int_dttm_ser(self):\n dttm = datetime(2020, 1, 1)\n ts = 1577836800000.0\n assert json_int_dttm_ser(dttm) == ts\n assert json_int_dttm_ser(date(2020, 1, 1)) == ts\n assert json_int_dttm_ser(datetime(1970, 1, 1)) == 0\n assert json_int_dttm_ser(date(1970, 1, 1)) == 0\n assert json_int_dttm_ser(dttm + timedelta(milliseconds=1)) == (ts + 1)\n\n with self.assertRaises(TypeError):\n json_int_dttm_ser(\"this is not a date\")\n\n def test_json_iso_dttm_ser(self):\n dttm = datetime(2020, 1, 1)\n dt = date(2020, 1, 1)\n t = time()\n assert json_iso_dttm_ser(dttm) == dttm.isoformat()\n assert json_iso_dttm_ser(dt) == dt.isoformat()\n assert json_iso_dttm_ser(t) == t.isoformat()\n\n with self.assertRaises(TypeError):\n json_iso_dttm_ser(\"this is not a date\")\n\n def test_base_json_conv(self):\n assert isinstance(base_json_conv(numpy.bool_(1)), bool) is True\n assert isinstance(base_json_conv(numpy.int64(1)), int) is True\n assert isinstance(base_json_conv(numpy.array([1, 2, 3])), list) is True\n assert isinstance(base_json_conv(set([1])), list) is True\n assert isinstance(base_json_conv(Decimal(\"1.0\")), float) is True\n assert isinstance(base_json_conv(uuid.uuid4()), str) is True\n assert isinstance(base_json_conv(timedelta(0)), str) is True\n\n def test_zlib_compression(self):\n json_str = '{\"test\": 1}'\n blob = zlib_compress(json_str)\n got_str = zlib_decompress(blob)\n self.assertEqual(json_str, got_str)\n\n @patch(\"superset.utils.core.to_adhoc\", mock_to_adhoc)\n def test_merge_extra_filters(self):\n # does nothing if no extra filters\n form_data = {\"A\": 1, \"B\": 2, \"c\": \"test\"}\n expected = {**form_data, \"adhoc_filters\": [], \"applied_time_extras\": {}}\n merge_extra_filters(form_data)\n self.assertEqual(form_data, expected)\n # empty extra_filters\n form_data = {\"A\": 1, \"B\": 2, \"c\": \"test\", \"extra_filters\": []}\n expected = {\n \"A\": 1,\n \"B\": 2,\n \"c\": \"test\",\n \"adhoc_filters\": [],\n \"applied_time_extras\": {},\n }\n merge_extra_filters(form_data)\n self.assertEqual(form_data, expected)\n # copy over extra filters into empty filters\n form_data = {\n \"extra_filters\": [\n {\"col\": \"a\", \"op\": \"in\", \"val\": \"someval\"},\n {\"col\": \"B\", \"op\": \"==\", \"val\": [\"c1\", \"c2\"]},\n ]\n }\n expected = {\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": \"someval\",\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", \"c2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"==\",\n \"subject\": \"B\",\n },\n ],\n \"applied_time_extras\": {},\n }\n merge_extra_filters(form_data)\n self.assertEqual(form_data, expected)\n # adds extra filters to existing filters\n form_data = {\n \"extra_filters\": [\n {\"col\": \"a\", \"op\": \"in\", \"val\": \"someval\"},\n {\"col\": \"B\", \"op\": \"==\", \"val\": [\"c1\", \"c2\"]},\n ],\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"G1\", \"g2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"!=\",\n \"subject\": \"D\",\n }\n ],\n }\n expected = {\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"G1\", \"g2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"!=\",\n \"subject\": \"D\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": \"someval\",\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", \"c2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"==\",\n \"subject\": \"B\",\n },\n ],\n \"applied_time_extras\": {},\n }\n merge_extra_filters(form_data)\n self.assertEqual(form_data, expected)\n # adds extra filters to existing filters and sets time options\n form_data = {\n \"extra_filters\": [\n {\"col\": \"__time_range\", \"op\": \"in\", \"val\": \"1 year ago :\"},\n {\"col\": \"__time_col\", \"op\": \"in\", \"val\": \"birth_year\"},\n {\"col\": \"__time_grain\", \"op\": \"in\", \"val\": \"years\"},\n {\"col\": \"A\", \"op\": \"like\", \"val\": \"hello\"},\n {\"col\": \"__time_origin\", \"op\": \"in\", \"val\": \"now\"},\n {\"col\": \"__granularity\", \"op\": \"in\", \"val\": \"90 seconds\"},\n ]\n }\n expected = {\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": \"hello\",\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"like\",\n \"subject\": \"A\",\n }\n ],\n \"time_range\": \"1 year ago :\",\n \"granularity_sqla\": \"birth_year\",\n \"time_grain_sqla\": \"years\",\n \"granularity\": \"90 seconds\",\n \"druid_time_origin\": \"now\",\n \"applied_time_extras\": {\n \"__time_range\": \"1 year ago :\",\n \"__time_col\": \"birth_year\",\n \"__time_grain\": \"years\",\n \"__time_origin\": \"now\",\n \"__granularity\": \"90 seconds\",\n },\n }\n merge_extra_filters(form_data)\n self.assertEqual(form_data, expected)\n\n @patch(\"superset.utils.core.to_adhoc\", mock_to_adhoc)\n def test_merge_extra_filters_ignores_empty_filters(self):\n form_data = {\n \"extra_filters\": [\n {\"col\": \"a\", \"op\": \"in\", \"val\": \"\"},\n {\"col\": \"B\", \"op\": \"==\", \"val\": []},\n ]\n }\n expected = {\"adhoc_filters\": [], \"applied_time_extras\": {}}\n merge_extra_filters(form_data)\n self.assertEqual(form_data, expected)\n\n @patch(\"superset.utils.core.to_adhoc\", mock_to_adhoc)\n def test_merge_extra_filters_ignores_nones(self):\n form_data = {\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": \"\",\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": None,\n }\n ],\n \"extra_filters\": [{\"col\": \"B\", \"op\": \"==\", \"val\": []}],\n }\n expected = {\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": \"\",\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": None,\n }\n ],\n \"applied_time_extras\": {},\n }\n merge_extra_filters(form_data)\n self.assertEqual(form_data, expected)\n\n @patch(\"superset.utils.core.to_adhoc\", mock_to_adhoc)\n def test_merge_extra_filters_ignores_equal_filters(self):\n form_data = {\n \"extra_filters\": [\n {\"col\": \"a\", \"op\": \"in\", \"val\": \"someval\"},\n {\"col\": \"B\", \"op\": \"==\", \"val\": [\"c1\", \"c2\"]},\n {\"col\": \"c\", \"op\": \"in\", \"val\": [\"c1\", 1, None]},\n ],\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": \"someval\",\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", \"c2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"==\",\n \"subject\": \"B\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", 1, None],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"c\",\n },\n ],\n }\n expected = {\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": \"someval\",\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", \"c2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"==\",\n \"subject\": \"B\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", 1, None],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"c\",\n },\n ],\n \"applied_time_extras\": {},\n }\n merge_extra_filters(form_data)\n self.assertEqual(form_data, expected)\n\n @patch(\"superset.utils.core.to_adhoc\", mock_to_adhoc)\n def test_merge_extra_filters_merges_different_val_types(self):\n form_data = {\n \"extra_filters\": [\n {\"col\": \"a\", \"op\": \"in\", \"val\": [\"g1\", \"g2\"]},\n {\"col\": \"B\", \"op\": \"==\", \"val\": [\"c1\", \"c2\"]},\n ],\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": \"someval\",\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", \"c2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"==\",\n \"subject\": \"B\",\n },\n ],\n }\n expected = {\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": \"someval\",\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", \"c2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"==\",\n \"subject\": \"B\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"g1\", \"g2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n ],\n \"applied_time_extras\": {},\n }\n merge_extra_filters(form_data)\n self.assertEqual(form_data, expected)\n form_data = {\n \"extra_filters\": [\n {\"col\": \"a\", \"op\": \"in\", \"val\": \"someval\"},\n {\"col\": \"B\", \"op\": \"==\", \"val\": [\"c1\", \"c2\"]},\n ],\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"g1\", \"g2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", \"c2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"==\",\n \"subject\": \"B\",\n },\n ],\n }\n expected = {\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"g1\", \"g2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", \"c2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"==\",\n \"subject\": \"B\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": \"someval\",\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n ],\n \"applied_time_extras\": {},\n }\n merge_extra_filters(form_data)\n self.assertEqual(form_data, expected)\n\n @patch(\"superset.utils.core.to_adhoc\", mock_to_adhoc)\n def test_merge_extra_filters_adds_unequal_lists(self):\n form_data = {\n \"extra_filters\": [\n {\"col\": \"a\", \"op\": \"in\", \"val\": [\"g1\", \"g2\", \"g3\"]},\n {\"col\": \"B\", \"op\": \"==\", \"val\": [\"c1\", \"c2\", \"c3\"]},\n ],\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"g1\", \"g2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", \"c2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"==\",\n \"subject\": \"B\",\n },\n ],\n }\n expected = {\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"g1\", \"g2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", \"c2\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"==\",\n \"subject\": \"B\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"g1\", \"g2\", \"g3\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n },\n {\n \"clause\": \"WHERE\",\n \"comparator\": [\"c1\", \"c2\", \"c3\"],\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"==\",\n \"subject\": \"B\",\n },\n ],\n \"applied_time_extras\": {},\n }\n merge_extra_filters(form_data)\n self.assertEqual(form_data, expected)\n\n def test_merge_request_params_when_url_params_undefined(self):\n form_data = {\"since\": \"2000\", \"until\": \"now\"}\n url_params = {\"form_data\": form_data, \"dashboard_ids\": \"(1,2,3,4,5)\"}\n merge_request_params(form_data, url_params)\n self.assertIn(\"url_params\", form_data.keys())\n self.assertIn(\"dashboard_ids\", form_data[\"url_params\"])\n self.assertNotIn(\"form_data\", form_data.keys())\n\n def test_merge_request_params_when_url_params_predefined(self):\n form_data = {\n \"since\": \"2000\",\n \"until\": \"now\",\n \"url_params\": {\"abc\": \"123\", \"dashboard_ids\": \"(1,2,3)\"},\n }\n url_params = {\"form_data\": form_data, \"dashboard_ids\": \"(1,2,3,4,5)\"}\n merge_request_params(form_data, url_params)\n self.assertIn(\"url_params\", form_data.keys())\n self.assertIn(\"abc\", form_data[\"url_params\"])\n self.assertEqual(\n url_params[\"dashboard_ids\"], form_data[\"url_params\"][\"dashboard_ids\"]\n )\n\n def test_format_timedelta(self):\n self.assertEqual(format_timedelta(timedelta(0)), \"0:00:00\")\n self.assertEqual(format_timedelta(timedelta(days=1)), \"1 day, 0:00:00\")\n self.assertEqual(format_timedelta(timedelta(minutes=-6)), \"-0:06:00\")\n self.assertEqual(\n format_timedelta(timedelta(0) - timedelta(days=1, hours=5, minutes=6)),\n \"-1 day, 5:06:00\",\n )\n self.assertEqual(\n format_timedelta(timedelta(0) - timedelta(days=16, hours=4, minutes=3)),\n \"-16 days, 4:03:00\",\n )\n\n def test_json_encoded_obj(self):\n obj = {\"a\": 5, \"b\": [\"a\", \"g\", 5]}\n val = '{\"a\": 5, \"b\": [\"a\", \"g\", 5]}'\n jsonObj = JSONEncodedDict()\n resp = jsonObj.process_bind_param(obj, \"dialect\")\n self.assertIn('\"a\": 5', resp)\n self.assertIn('\"b\": [\"a\", \"g\", 5]', resp)\n self.assertEqual(jsonObj.process_result_value(val, \"dialect\"), obj)\n\n def test_validate_json(self):\n valid = '{\"a\": 5, \"b\": [1, 5, [\"g\", \"h\"]]}'\n self.assertIsNone(validate_json(valid))\n invalid = '{\"a\": 5, \"b\": [1, 5, [\"g\", \"h]]}'\n with self.assertRaises(SupersetException):\n validate_json(invalid)\n\n def test_memoized_on_functions(self):\n watcher = {\"val\": 0}\n\n @memoized\n def test_function(a, b, c):\n watcher[\"val\"] += 1\n return a * b * c\n\n result1 = test_function(1, 2, 3)\n result2 = test_function(1, 2, 3)\n self.assertEqual(result1, result2)\n self.assertEqual(watcher[\"val\"], 1)\n\n def test_memoized_on_methods(self):\n class test_class:\n def __init__(self, num):\n self.num = num\n self.watcher = 0\n\n @memoized\n def test_method(self, a, b, c):\n self.watcher += 1\n return a * b * c * self.num\n\n instance = test_class(5)\n result1 = instance.test_method(1, 2, 3)\n result2 = instance.test_method(1, 2, 3)\n self.assertEqual(result1, result2)\n self.assertEqual(instance.watcher, 1)\n instance.num = 10\n self.assertEqual(result2, instance.test_method(1, 2, 3))\n\n def test_memoized_on_methods_with_watches(self):\n class test_class:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.watcher = 0\n\n @memoized(watch=(\"x\", \"y\"))\n def test_method(self, a, b, c):\n self.watcher += 1\n return a * b * c * self.x * self.y\n\n instance = test_class(3, 12)\n result1 = instance.test_method(1, 2, 3)\n result2 = instance.test_method(1, 2, 3)\n self.assertEqual(result1, result2)\n self.assertEqual(instance.watcher, 1)\n result3 = instance.test_method(2, 3, 4)\n self.assertEqual(instance.watcher, 2)\n result4 = instance.test_method(2, 3, 4)\n self.assertEqual(instance.watcher, 2)\n self.assertEqual(result3, result4)\n self.assertNotEqual(result3, result1)\n instance.x = 1\n result5 = instance.test_method(2, 3, 4)\n self.assertEqual(instance.watcher, 3)\n self.assertNotEqual(result5, result4)\n result6 = instance.test_method(2, 3, 4)\n self.assertEqual(instance.watcher, 3)\n self.assertEqual(result6, result5)\n instance.x = 10\n instance.y = 10\n result7 = instance.test_method(2, 3, 4)\n self.assertEqual(instance.watcher, 4)\n self.assertNotEqual(result7, result6)\n instance.x = 3\n instance.y = 12\n result8 = instance.test_method(1, 2, 3)\n self.assertEqual(instance.watcher, 4)\n self.assertEqual(result1, result8)\n\n @patch(\"superset.utils.core.to_adhoc\", mock_to_adhoc)\n def test_convert_legacy_filters_into_adhoc_where(self):\n form_data = {\"where\": \"a = 1\"}\n expected = {\n \"adhoc_filters\": [\n {\"clause\": \"WHERE\", \"expressionType\": \"SQL\", \"sqlExpression\": \"a = 1\"}\n ]\n }\n convert_legacy_filters_into_adhoc(form_data)\n self.assertEqual(form_data, expected)\n\n @patch(\"superset.utils.core.to_adhoc\", mock_to_adhoc)\n def test_convert_legacy_filters_into_adhoc_filters(self):\n form_data = {\"filters\": [{\"col\": \"a\", \"op\": \"in\", \"val\": \"someval\"}]}\n expected = {\n \"adhoc_filters\": [\n {\n \"clause\": \"WHERE\",\n \"comparator\": \"someval\",\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"in\",\n \"subject\": \"a\",\n }\n ]\n }\n convert_legacy_filters_into_adhoc(form_data)\n self.assertEqual(form_data, expected)\n\n @patch(\"superset.utils.core.to_adhoc\", mock_to_adhoc)\n def test_convert_legacy_filters_into_adhoc_having(self):\n form_data = {\"having\": \"COUNT(1) = 1\"}\n expected = {\n \"adhoc_filters\": [\n {\n \"clause\": \"HAVING\",\n \"expressionType\": \"SQL\",\n \"sqlExpression\": \"COUNT(1) = 1\",\n }\n ]\n }\n convert_legacy_filters_into_adhoc(form_data)\n self.assertEqual(form_data, expected)\n\n @patch(\"superset.utils.core.to_adhoc\", mock_to_adhoc)\n def test_convert_legacy_filters_into_adhoc_having_filters(self):\n form_data = {\"having_filters\": [{\"col\": \"COUNT(1)\", \"op\": \"==\", \"val\": 1}]}\n expected = {\n \"adhoc_filters\": [\n {\n \"clause\": \"HAVING\",\n \"comparator\": 1,\n \"expressionType\": \"SIMPLE\",\n \"operator\": \"==\",\n \"subject\": \"COUNT(1)\",\n }\n ]\n }\n convert_legacy_filters_into_adhoc(form_data)\n self.assertEqual(form_data, expected)\n\n @patch(\"superset.utils.core.to_adhoc\", mock_to_adhoc)\n def test_convert_legacy_filters_into_adhoc_present_and_empty(self):\n form_data = {\"adhoc_filters\": [], \"where\": \"a = 1\"}\n expected = {\n \"adhoc_filters\": [\n {\"clause\": \"WHERE\", \"expressionType\": \"SQL\", \"sqlExpression\": \"a = 1\"}\n ]\n }\n convert_legacy_filters_into_adhoc(form_data)\n self.assertEqual(form_data, expected)\n\n @patch(\"superset.utils.core.to_adhoc\", mock_to_adhoc)\n def test_convert_legacy_filters_into_adhoc_present_and_nonempty(self):\n form_data = {\n \"adhoc_filters\": [\n {\"clause\": \"WHERE\", \"expressionType\": \"SQL\", \"sqlExpression\": \"a = 1\"}\n ],\n \"filters\": [{\"col\": \"a\", \"op\": \"in\", \"val\": \"someval\"}],\n \"having\": \"COUNT(1) = 1\",\n \"having_filters\": [{\"col\": \"COUNT(1)\", \"op\": \"==\", \"val\": 1}],\n }\n expected = {\n \"adhoc_filters\": [\n {\"clause\": \"WHERE\", \"expressionType\": \"SQL\", \"sqlExpression\": \"a = 1\"}\n ]\n }\n convert_legacy_filters_into_adhoc(form_data)\n self.assertEqual(form_data, expected)\n\n def test_parse_js_uri_path_items_eval_undefined(self):\n self.assertIsNone(parse_js_uri_path_item(\"undefined\", eval_undefined=True))\n self.assertIsNone(parse_js_uri_path_item(\"null\", eval_undefined=True))\n self.assertEqual(\"undefined\", parse_js_uri_path_item(\"undefined\"))\n self.assertEqual(\"null\", parse_js_uri_path_item(\"null\"))\n\n def test_parse_js_uri_path_items_unquote(self):\n self.assertEqual(\"slashed/name\", parse_js_uri_path_item(\"slashed%2fname\"))\n self.assertEqual(\n \"slashed%2fname\", parse_js_uri_path_item(\"slashed%2fname\", unquote=False)\n )\n\n def test_parse_js_uri_path_items_item_optional(self):\n self.assertIsNone(parse_js_uri_path_item(None))\n self.assertIsNotNone(parse_js_uri_path_item(\"item\"))\n\n def test_get_stacktrace(self):\n with app.app_context():\n app.config[\"SHOW_STACKTRACE\"] = True\n try:\n raise Exception(\"NONONO!\")\n except Exception:\n stacktrace = get_stacktrace()\n self.assertIn(\"NONONO\", stacktrace)\n\n app.config[\"SHOW_STACKTRACE\"] = False\n try:\n raise Exception(\"NONONO!\")\n except Exception:\n stacktrace = get_stacktrace()\n assert stacktrace is None\n\n def test_split(self):\n self.assertEqual(list(split(\"a b\")), [\"a\", \"b\"])\n self.assertEqual(list(split(\"a,b\", delimiter=\",\")), [\"a\", \"b\"])\n self.assertEqual(list(split(\"a,(b,a)\", delimiter=\",\")), [\"a\", \"(b,a)\"])\n self.assertEqual(\n list(split('a,(b,a),\"foo , bar\"', delimiter=\",\")),\n [\"a\", \"(b,a)\", '\"foo , bar\"'],\n )\n self.assertEqual(\n list(split(\"a,'b,c'\", delimiter=\",\", quote=\"'\")), [\"a\", \"'b,c'\"]\n )\n self.assertEqual(list(split('a \"b c\"')), [\"a\", '\"b c\"'])\n self.assertEqual(list(split(r'a \"b \\\" c\"')), [\"a\", r'\"b \\\" c\"'])\n\n def test_get_or_create_db(self):\n get_or_create_db(\"test_db\", \"sqlite:///superset.db\")\n database = db.session.query(Database).filter_by(database_name=\"test_db\").one()\n self.assertIsNotNone(database)\n self.assertEqual(database.sqlalchemy_uri, \"sqlite:///superset.db\")\n self.assertIsNotNone(\n security_manager.find_permission_view_menu(\"database_access\", database.perm)\n )\n # Test change URI\n get_or_create_db(\"test_db\", \"sqlite:///changed.db\")\n database = db.session.query(Database).filter_by(database_name=\"test_db\").one()\n self.assertEqual(database.sqlalchemy_uri, \"sqlite:///changed.db\")\n db.session.delete(database)\n db.session.commit()\n\n def test_get_or_create_db_invalid_uri(self):\n with self.assertRaises(ArgumentError):\n get_or_create_db(\"test_db\", \"yoursql:superset.db/()\")\n\n def test_get_time_range_endpoints(self):\n self.assertEqual(\n get_time_range_endpoints(form_data={}),\n (TimeRangeEndpoint.INCLUSIVE, TimeRangeEndpoint.EXCLUSIVE),\n )\n\n self.assertEqual(\n get_time_range_endpoints(\n form_data={\"time_range_endpoints\": [\"inclusive\", \"inclusive\"]}\n ),\n (TimeRangeEndpoint.INCLUSIVE, TimeRangeEndpoint.INCLUSIVE),\n )\n\n self.assertEqual(\n get_time_range_endpoints(form_data={\"datasource\": \"1_druid\"}),\n (TimeRangeEndpoint.INCLUSIVE, TimeRangeEndpoint.EXCLUSIVE),\n )\n\n slc = Mock()\n slc.datasource.database.get_extra.return_value = {}\n\n self.assertEqual(\n get_time_range_endpoints(form_data={\"datasource\": \"1__table\"}, slc=slc),\n (TimeRangeEndpoint.UNKNOWN, TimeRangeEndpoint.INCLUSIVE),\n )\n\n slc.datasource.database.get_extra.return_value = {\n \"time_range_endpoints\": [\"inclusive\", \"inclusive\"]\n }\n\n self.assertEqual(\n get_time_range_endpoints(form_data={\"datasource\": \"1__table\"}, slc=slc),\n (TimeRangeEndpoint.INCLUSIVE, TimeRangeEndpoint.INCLUSIVE),\n )\n\n self.assertIsNone(get_time_range_endpoints(form_data={}, slc=slc))\n\n with app.app_context():\n app.config[\"SIP_15_GRACE_PERIOD_END\"] = date.today() + timedelta(days=1)\n\n self.assertEqual(\n get_time_range_endpoints(form_data={\"datasource\": \"1__table\"}, slc=slc),\n (TimeRangeEndpoint.INCLUSIVE, TimeRangeEndpoint.INCLUSIVE),\n )\n\n app.config[\"SIP_15_GRACE_PERIOD_END\"] = date.today()\n\n self.assertEqual(\n get_time_range_endpoints(form_data={\"datasource\": \"1__table\"}, slc=slc),\n (TimeRangeEndpoint.INCLUSIVE, TimeRangeEndpoint.EXCLUSIVE),\n )\n\n def test_get_iterable(self):\n self.assertListEqual(get_iterable(123), [123])\n self.assertListEqual(get_iterable([123]), [123])\n self.assertListEqual(get_iterable(\"foo\"), [\"foo\"])\n\n @pytest.mark.usefixtures(\"load_world_bank_dashboard_with_slices\")\n def test_build_extra_filters(self):\n world_health = db.session.query(Dashboard).filter_by(slug=\"world_health\").one()\n layout = json.loads(world_health.position_json)\n filter_ = db.session.query(Slice).filter_by(slice_name=\"Region Filter\").one()\n world = db.session.query(Slice).filter_by(slice_name=\"World's Population\").one()\n box_plot = db.session.query(Slice).filter_by(slice_name=\"Box plot\").one()\n treemap = db.session.query(Slice).filter_by(slice_name=\"Treemap\").one()\n\n filter_scopes = {\n str(filter_.id): {\n \"region\": {\"scope\": [\"ROOT_ID\"], \"immune\": [treemap.id]},\n \"country_name\": {\n \"scope\": [\"ROOT_ID\"],\n \"immune\": [treemap.id, box_plot.id],\n },\n }\n }\n\n default_filters = {\n str(filter_.id): {\n \"region\": [\"North America\"],\n \"country_name\": [\"United States\"],\n }\n }\n\n # immune to all filters\n assert (\n build_extra_filters(layout, filter_scopes, default_filters, treemap.id)\n == []\n )\n\n # in scope\n assert build_extra_filters(\n layout, filter_scopes, default_filters, world.id\n ) == [\n {\"col\": \"region\", \"op\": \"==\", \"val\": \"North America\"},\n {\"col\": \"country_name\", \"op\": \"in\", \"val\": [\"United States\"]},\n ]\n\n assert build_extra_filters(\n layout, filter_scopes, default_filters, box_plot.id\n ) == [{\"col\": \"region\", \"op\": \"==\", \"val\": \"North America\"}]\n\n def test_ssl_certificate_parse(self):\n parsed_certificate = parse_ssl_cert(ssl_certificate)\n self.assertEqual(parsed_certificate.serial_number, 12355228710836649848)\n self.assertRaises(CertificateException, parse_ssl_cert, \"abc\" + ssl_certificate)\n\n def test_ssl_certificate_file_creation(self):\n path = create_ssl_cert_file(ssl_certificate)\n expected_filename = hashlib.md5(ssl_certificate.encode(\"utf-8\")).hexdigest()\n self.assertIn(expected_filename, path)\n self.assertTrue(os.path.exists(path))\n\n def test_get_email_address_list(self):\n self.assertEqual(get_email_address_list(\"a@a\"), [\"a@a\"])\n self.assertEqual(get_email_address_list(\" a@a \"), [\"a@a\"])\n self.assertEqual(get_email_address_list(\"a@a\\n\"), [\"a@a\"])\n self.assertEqual(get_email_address_list(\",a@a;\"), [\"a@a\"])\n self.assertEqual(\n get_email_address_list(\",a@a; b@b c@c a-c@c; d@d, f@f\"),\n [\"a@a\", \"b@b\", \"c@c\", \"a-c@c\", \"d@d\", \"f@f\"],\n )\n\n def test_get_form_data_default(self) -> None:\n with app.test_request_context():\n form_data, slc = get_form_data()\n\n self.assertEqual(\n form_data,\n {\"time_range_endpoints\": get_time_range_endpoints(form_data={}),},\n )\n\n self.assertEqual(slc, None)\n\n def test_get_form_data_request_args(self) -> None:\n with app.test_request_context(\n query_string={\"form_data\": json.dumps({\"foo\": \"bar\"})}\n ):\n form_data, slc = get_form_data()\n\n self.assertEqual(\n form_data,\n {\n \"foo\": \"bar\",\n \"time_range_endpoints\": get_time_range_endpoints(form_data={}),\n },\n )\n\n self.assertEqual(slc, None)\n\n def test_get_form_data_request_form(self) -> None:\n with app.test_request_context(data={\"form_data\": json.dumps({\"foo\": \"bar\"})}):\n form_data, slc = get_form_data()\n\n self.assertEqual(\n form_data,\n {\n \"foo\": \"bar\",\n \"time_range_endpoints\": get_time_range_endpoints(form_data={}),\n },\n )\n\n self.assertEqual(slc, None)\n\n def test_get_form_data_request_args_and_form(self) -> None:\n with app.test_request_context(\n data={\"form_data\": json.dumps({\"foo\": \"bar\"})},\n query_string={\"form_data\": json.dumps({\"baz\": \"bar\"})},\n ):\n form_data, slc = get_form_data()\n\n self.assertEqual(\n form_data,\n {\n \"baz\": \"bar\",\n \"foo\": \"bar\",\n \"time_range_endpoints\": get_time_range_endpoints(form_data={}),\n },\n )\n\n self.assertEqual(slc, None)\n\n def test_get_form_data_globals(self) -> None:\n with app.test_request_context():\n g.form_data = {\"foo\": \"bar\"}\n form_data, slc = get_form_data()\n delattr(g, \"form_data\")\n\n self.assertEqual(\n form_data,\n {\n \"foo\": \"bar\",\n \"time_range_endpoints\": get_time_range_endpoints(form_data={}),\n },\n )\n\n self.assertEqual(slc, None)\n\n @pytest.mark.usefixtures(\"load_birth_names_dashboard_with_slices\")\n def test_log_this(self) -> None:\n # TODO: Add additional scenarios.\n self.login(username=\"admin\")\n slc = self.get_slice(\"Girls\", db.session)\n dashboard_id = 1\n\n resp = self.get_json_resp(\n f\"/superset/explore_json/{slc.datasource_type}/{slc.datasource_id}/\"\n + f'?form_data={{\"slice_id\": {slc.id}}}&dashboard_id={dashboard_id}',\n {\"form_data\": json.dumps(slc.viz.form_data)},\n )\n\n record = (\n db.session.query(Log)\n .filter_by(action=\"explore_json\", slice_id=slc.id)\n .order_by(Log.dttm.desc())\n .first()\n )\n\n self.assertEqual(record.dashboard_id, dashboard_id)\n self.assertEqual(json.loads(record.json)[\"dashboard_id\"], str(dashboard_id))\n self.assertEqual(json.loads(record.json)[\"form_data\"][\"slice_id\"], slc.id)\n\n self.assertEqual(\n json.loads(record.json)[\"form_data\"][\"viz_type\"],\n slc.viz.form_data[\"viz_type\"],\n )\n\n def test_schema_validate_json(self):\n valid = '{\"a\": 5, \"b\": [1, 5, [\"g\", \"h\"]]}'\n self.assertIsNone(schema.validate_json(valid))\n invalid = '{\"a\": 5, \"b\": [1, 5, [\"g\", \"h]]}'\n self.assertRaises(marshmallow.ValidationError, schema.validate_json, invalid)\n\n def test_schema_one_of_case_insensitive(self):\n validator = schema.OneOfCaseInsensitive(choices=[1, 2, 3, \"FoO\", \"BAR\", \"baz\"])\n self.assertEqual(1, validator(1))\n self.assertEqual(2, validator(2))\n self.assertEqual(\"FoO\", validator(\"FoO\"))\n self.assertEqual(\"FOO\", validator(\"FOO\"))\n self.assertEqual(\"bar\", validator(\"bar\"))\n self.assertEqual(\"BaZ\", validator(\"BaZ\"))\n self.assertRaises(marshmallow.ValidationError, validator, \"qwerty\")\n self.assertRaises(marshmallow.ValidationError, validator, 4)\n\n def test_cast_to_num(self) -> None:\n assert cast_to_num(\"5\") == 5\n assert cast_to_num(\"5.2\") == 5.2\n assert cast_to_num(10) == 10\n assert cast_to_num(10.1) == 10.1\n assert cast_to_num(None) is None\n assert cast_to_num(\"this is not a string\") is None\n\n def test_get_form_data_token(self):\n assert get_form_data_token({\"token\": \"token_abcdefg1\"}) == \"token_abcdefg1\"\n generated_token = get_form_data_token({})\n assert re.match(r\"^token_[a-z0-9]{8}$\", generated_token) is not None\n" ]
[ [ "numpy.int64", "numpy.array", "numpy.bool_" ] ]
JustinYuu/pytorch-CIFAR10-playground
[ "854ffcb7857fb1c114f6ac28a0a8fd7f935d7c40" ]
[ "net/resnext.py" ]
[ "import torch.nn as nn\r\nimport torch\r\nimport torch.nn.functional as F\r\n\r\n\r\nclass BottleNeck(nn.Module):\r\n expansion = 2\r\n\r\n def __init__(self, in_channel, cardinality, bottleneck_width, stride=1):\r\n super(BottleNeck, self).__init__()\r\n group_width = bottleneck_width * cardinality\r\n self.left = nn.Sequential(\r\n nn.Conv2d(in_channel, group_width, kernel_size=1, bias=False),\r\n nn.BatchNorm2d(group_width),\r\n nn.ReLU(True),\r\n nn.Conv2d(group_width, group_width, kernel_size=3, stride=stride, padding=1, groups=cardinality,\r\n bias=False),\r\n nn.BatchNorm2d(group_width),\r\n nn.ReLU(True),\r\n nn.Conv2d(group_width, group_width * self.expansion, kernel_size=1, bias=False),\r\n nn.BatchNorm2d(group_width * self.expansion)\r\n # without ReLU\r\n )\r\n self.shortcut = None\r\n if stride != 1 or in_channel != group_width * self.expansion:\r\n self.shortcut = nn.Sequential(\r\n nn.Conv2d(in_channel, group_width * self.expansion, kernel_size=1, stride=stride, bias=False),\r\n nn.BatchNorm2d(group_width * self.expansion)\r\n )\r\n\r\n def forward(self, x):\r\n out = self.left(x)\r\n residual = x if self.shortcut is None else self.shortcut(x)\r\n out += residual\r\n return F.relu(out)\r\n\r\n\r\nclass ResNeXt(nn.Module):\r\n def __init__(self, cardinality, bottleneck_width, num_classes=10):\r\n super(ResNeXt, self).__init__()\r\n self.in_channel = 64\r\n self.bottleneck_width = bottleneck_width\r\n self.cardinality = cardinality\r\n self.pre = nn.Sequential(\r\n nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False), # 32*32*64\r\n nn.BatchNorm2d(64),\r\n nn.ReLU(True)\r\n )\r\n self.layer1 = self.make_layer(3, stride=1) # 32*32\r\n self.layer2 = self.make_layer(4, stride=2) # 16*16\r\n self.layer3 = self.make_layer(6, stride=2) # 8*8\r\n self.layer4 = self.make_layer(3, stride=2) # 4*4\r\n self.fc = nn.Linear(cardinality * bottleneck_width * 16, num_classes)\r\n\r\n def make_layer(self, block_num, stride):\r\n layers = []\r\n layers.append(BottleNeck(self.in_channel, self.cardinality, self.bottleneck_width, stride))\r\n self.in_channel = BottleNeck.expansion * self.cardinality * self.bottleneck_width\r\n for i in range(1, block_num):\r\n layers.append(BottleNeck(self.in_channel, self.cardinality, self.bottleneck_width, 1))\r\n self.in_channel = BottleNeck.expansion * self.cardinality * self.bottleneck_width\r\n self.bottleneck_width = self.bottleneck_width * 2\r\n return nn.Sequential(*layers)\r\n\r\n def forward(self, x):\r\n out = self.pre(x)\r\n out = self.layer1(out)\r\n out = self.layer2(out)\r\n out = self.layer3(out)\r\n out = self.layer4(out)\r\n out = F.avg_pool2d(out, 4)\r\n out = out.view(out.size(0), -1)\r\n out = self.fc(out)\r\n return out\r\n\r\n\r\ndef ResNeXt50_32x4d():\r\n return ResNeXt(cardinality=32, bottleneck_width=4)\r\n\r\n\r\ndef ResNeXt50_8x14d():\r\n return ResNeXt(cardinality=8, bottleneck_width=14)\r\n\r\n\r\ndef ResNeXt50_4x24d():\r\n return ResNeXt(cardinality=4, bottleneck_width=24)\r\n\r\n\r\ndef ResNeXt50_2x40d():\r\n return ResNeXt(cardinality=2, bottleneck_width=40)\r\n\r\n\r\ndef ResNeXt50_1x64d():\r\n return ResNeXt(cardinality=1, bottleneck_width=64)\r\n" ]
[ [ "torch.nn.Sequential", "torch.nn.functional.avg_pool2d", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.functional.relu", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
janash/molecool
[ "ab573caecfc47a481349f7694654c3d0491e25b9" ]
[ "molecool/tests/test_measure.py" ]
[ "\"\"\"\nTests for the measure module.\n\"\"\"\n\n# imports\nimport pytest\n\nimport molecool\nimport numpy as np\n\ndef test_calculate_distance():\n\n r1 = np.array([0, 0, 0])\n r2 = np.array([0, 1, 0])\n\n expected_distance = 1\n\n calculated_distance = molecool.calculate_distance(r1, r2)\n\n assert expected_distance == calculated_distance\n\n# Write a test for the calculate_angle function\n# use points (0, 0, -1) (0, 0, 0) (1, 0, 0)\n# expected angle is 90 degrees\n\ndef test_calculate_angle():\n\n r1 = np.array([1, 0, 0])\n r2 = np.array([0, 0, 0])\n r3 = np.array([0, 1, 0])\n\n expected_value = 90\n\n calculated_value = molecool.calculate_angle(r1, r2, r3, degrees=True)\n\n assert pytest.approx(expected_value) == calculated_value\n\[email protected](\"p1, p2, p3, expected_angle\", [\n (np.array([np.sqrt(2)/2, np.sqrt(2)/2, 0]), np.array([0, 0, 0]), np.array([1, 0, 0]), 45),\n (np.array([0, 0, -1]), np.array([0, 1, 0]), np.array([1, 0, 0]), 60 ),\n (np.array([np.sqrt(3)/2, (1/2), 0]), np.array([0, 0, 0]), np.array([1, 0, 0]), 30),\n])\ndef test_calculate_angle_many(p1, p2, p3, expected_angle):\n\n calculated_angle = molecool.calculate_angle(p1, p2, p3, degrees=True)\n\n assert expected_angle == pytest.approx(calculated_angle), F'{calculated_angle} {expected_angle}'\n" ]
[ [ "numpy.array", "numpy.sqrt" ] ]
kirichoi/pySME
[ "4879a80cefe131568f8c4d91b52f97fe0c79d315" ]
[ "pysme.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCopyright (c) 2019 Kiri Choi\r\n\r\npySME is a Python script to run R SME package \r\n(https://cran.r-project.org/web/packages/sme/index.html). SME package generates\r\nsmoothing-splines mixed-effects models from metabolomics data. This script \r\nfollows methodology given by Berk et al. (2011) and utilizes bootstrapping to \r\napproximate p-values. Running this script requires R with SME package installed.\r\n\r\n\"\"\"\r\n\r\nimport os\r\nimport numpy as np\r\nfrom scipy import interpolate\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import cm\r\nfrom rpy2.robjects.packages import importr\r\nfrom rpy2.robjects import pandas2ri\r\nimport statsmodels.stats.multitest as smm\r\nimport time\r\nimport copy\r\nimport smeutils\r\n\r\nsmePack = importr('sme', lib_loc=\"C:/Users/user/Documents/R/win-library/3.6\")\r\nstatsPack = importr('stats')\r\n\r\n# Settings ====================================================================\r\n\r\n# Input files\r\ninfo = pd.read_csv('./sme_info.csv')\r\ndata = pd.read_csv('./sme_data.csv')\r\n\r\ninfo_arr = np.array(info)\r\ndata_fid = np.array(data.columns)\r\ndata_arr = np.array(data)\r\nselIdx = np.arange(len(data_fid))\r\n\r\n# Parameters\r\nRUN = True\r\nN = 12 # Number of subjects\r\nt_n = 4 # Number of time points\r\niplN = 100 # Number of interpolated time points\r\nn_bootstrap = 500 # Number of bootstrap sampling\r\nselIdx = selIdx[:] # List of metabolites to analyze\r\nrelative = False # Scale data to initial values\r\ncorrectOutlier = False\r\nSAVE = False\r\nUSEMEAN = True\r\n\r\n# SME Parameters\r\nctra = \"AICc\" # Criteria\r\ninit_l_mc = 1e-8 # Initial lambda_mu\r\ninit_l_vc = 1e-8 # Initial lambda_v\r\ninit_l_mt = 5e-8 # Initial lambda_mu\r\ninit_l_vt = 5e-8 # Initial lambda_v\r\nmaxIter = 100000 # Maximum iteration\r\ndeltaEM = 1e-3 # Threshold for expetation maximization\r\ndeltaNM = 1e-3 # Threshold for nelder mead\r\nnormalizeTime = True\r\n\r\nseed = 1234 # RNG seed\r\n\r\nshowFig = False # Flag to plot figures\r\nfigSize = (20,16) # Size of figures\r\nplotLegend = False # Flag to plot legend\r\ncolorMap = 'viridis' # kwarg for colormap\r\nplotSMEMeanOnly = False # Only plot SME mean trace\r\nmergePlot = True # Merge multiple plots\r\nplotHeatmap = False # Plot heatmap comparing two data groups\r\n\r\nt = np.array([1,3,5,7])\r\niplT = np.linspace(1, 7, iplN)\r\niplTIdx = np.empty(t_n)\r\n\r\nfor i in range(t_n):\r\n iplTIdx[i] = np.where(iplT == t[i])[0]\r\niplTIdx = iplTIdx.astype(int)\r\n\r\nsel = np.array([data_fid[selIdx]]).flatten() \r\n\r\n#==============================================================================\r\n\r\nnp.random.seed(seed) # Set seed\r\n\r\n#==============================================================================\r\n\r\nif relative:\r\n data = smeutils.normalizeData(data, N, t_n, data_fid)\r\n\r\n#==============================================================================\r\n\r\nt0 = time.time()\r\n\r\nfulldataRaw = pd.concat([info,data], axis=1)\r\nfulldataRaw = fulldataRaw.astype('float64')\r\n\r\nfulldata = copy.deepcopy(fulldataRaw)\r\nfulldata = fulldata.drop(fulldata.index[16]) # ind 5 has an outlier\r\n\r\nif correctOutlier:\r\n fulldata = smeutils.correctOutlier(fulldata, sel, t, t_n)\r\n\r\n# Initialize ==================================================================\r\n\r\ngrp0_f = fulldata[(fulldata.grp == 0)]['ind']\r\ngrp1_f = fulldata[(fulldata.grp == 1)]['ind']\r\ngrp0 = np.unique(fulldata[(fulldata.grp == 0)]['ind'])\r\ngrp1 = np.unique(fulldata[(fulldata.grp == 1)]['ind'])\r\n\r\npandas2ri.activate()\r\nfd_ri = pandas2ri.py2ri(fulldata)\r\n\r\nfd_rigrp0 = fd_ri.rx(fd_ri.rx2(\"grp\").ro == 0, True)\r\nfd_rigrp1 = fd_ri.rx(fd_ri.rx2(\"grp\").ro == 1, True)\r\n\r\nfd_rigrp0tme = fd_rigrp0.rx2(\"tme\")\r\nfd_rigrp0ind = fd_rigrp0.rx2(\"ind\")\r\nfd_rigrp1tme = fd_rigrp1.rx2(\"tme\")\r\nfd_rigrp1ind = fd_rigrp1.rx2(\"ind\")\r\n\r\nys0mu = np.empty((len(sel), iplN))\r\nys1mu = np.empty((len(sel), iplN))\r\nys0vHat = np.empty((len(sel), len(grp0), iplN))\r\nys1vHat = np.empty((len(sel), len(grp1), iplN))\r\n\r\nl2 = np.empty(len(sel))\r\nse = np.empty(len(sel))\r\nse0 = np.empty((len(sel), len(grp0)))\r\nse1 = np.empty((len(sel), len(grp1)))\r\nsem = np.empty(len(sel))\r\ntval = np.empty(len(sel))\r\n\r\nys0v = np.empty((len(sel), len(grp0), t_n))\r\nys1v = np.empty((len(sel), len(grp1), t_n))\r\nys0eta = np.empty((len(sel), len(grp0), t_n))\r\nys1eta = np.empty((len(sel), len(grp1), t_n))\r\n\r\nys0mubs = np.empty((n_bootstrap, len(sel), iplN))\r\nys1mubs = np.empty((n_bootstrap, len(sel), iplN))\r\nys0vHatbs = np.empty((n_bootstrap, len(sel), len(grp0), iplN))\r\nys1vHatbs = np.empty((n_bootstrap, len(sel), len(grp1), iplN))\r\n\r\nl2bs = np.empty((n_bootstrap, len(sel)))\r\nsebs = np.empty((n_bootstrap, len(sel)))\r\nse0bs = np.empty((n_bootstrap, len(sel), len(grp0)))\r\nse1bs = np.empty((n_bootstrap, len(sel), len(grp1)))\r\nsembs = np.empty((n_bootstrap, len(sel)))\r\ntvalbs = np.empty((n_bootstrap, len(sel)))\r\npval = np.empty(len(sel))\r\n\r\nt1 = time.time()\r\n\r\nprint(t1 - t0)\r\n\r\n\r\n# SME =========================================================================\r\n\r\nif RUN:\r\n for m_i in range(len(sel)):\r\n fd_rigrp0obj = fd_rigrp0.rx2(sel[m_i])\r\n fd_rigrp1obj = fd_rigrp1.rx2(sel[m_i])\r\n \r\n fit0 = smePack.sme(fd_rigrp0obj, \r\n fd_rigrp0tme, \r\n fd_rigrp0ind, \r\n criteria=ctra, \r\n maxIter=maxIter, \r\n deltaEM=deltaEM, \r\n deltaNM=deltaNM, \r\n initial_lambda_mu=init_l_mc, \r\n initial_lambda_v=init_l_mc,\r\n normalizeTime=normalizeTime)\r\n fit1 = smePack.sme(fd_rigrp1obj, \r\n fd_rigrp1tme, \r\n fd_rigrp1ind, \r\n criteria=ctra, \r\n maxIter=maxIter, \r\n deltaEM=deltaEM, \r\n deltaNM=deltaNM, \r\n initial_lambda_mu=init_l_mt, \r\n initial_lambda_v=init_l_vt,\r\n normalizeTime=normalizeTime)\r\n \r\n fit0coef = np.array(fit0.rx2('coefficients'))\r\n fit1coef = np.array(fit1.rx2('coefficients'))\r\n \r\n spl0mu = interpolate.CubicSpline(t, fit0coef[0], bc_type='natural')\r\n ys0mu[m_i] = spl0mu(iplT)\r\n spl1mu = interpolate.CubicSpline(t, fit1coef[0], bc_type='natural')\r\n ys1mu[m_i] = spl1mu(iplT)\r\n \r\n l2[m_i] = np.sqrt(np.trapz(np.square(ys0mu[m_i] - ys1mu[m_i]), x=iplT))\r\n \r\n for g0 in range(len(grp0)):\r\n spl0 = interpolate.CubicSpline(t, fit0coef[g0 + 1] + fit0coef[0], bc_type='natural')\r\n ys0vHat[m_i][g0] = spl0(iplT)\r\n ys0v[m_i][g0] = ys0mu[m_i][iplTIdx] - ys0vHat[m_i][g0][iplTIdx]\r\n ys0eta[m_i][g0] = fulldataRaw.loc[fulldataRaw.ind == grp0[g0], sel[m_i]] - ys0vHat[m_i][g0][iplTIdx]\r\n se0[m_i][g0] = np.trapz(np.square(ys0mu[m_i] - ys0vHat[m_i][g0]), x=iplT)\r\n \r\n for g1 in range(len(grp1)):\r\n spl1 = interpolate.CubicSpline(t, fit1coef[g1 + 1] + fit1coef[0], bc_type='natural')\r\n ys1vHat[m_i][g1] = spl1(iplT)\r\n ys1v[m_i][g1] = ys1mu[m_i][iplTIdx] - ys1vHat[m_i][g1][iplTIdx]\r\n ys1eta[m_i][g1] = fulldataRaw.loc[fulldataRaw.ind == grp1[g1], sel[m_i]] - ys1vHat[m_i][g1][iplTIdx]\r\n se1[m_i][g1] = np.trapz(np.square(ys1mu[m_i] - ys1vHat[m_i][g1]), x=iplT)\r\n \r\n se[m_i] = np.sqrt(np.mean(se0[m_i])/len(grp0) + np.mean(se1[m_i])/len(grp1))\r\n \r\n sem = 0.\r\n \r\n tval = np.divide(l2, se + sem)\r\n \r\n ys0vFlat = ys0v.reshape((ys0v.shape[0], -1))\r\n ys0etaFlat = ys0eta.reshape((ys0eta.shape[0], -1))\r\n ys0etaFlat = np.delete(ys0etaFlat, 13, 1) # ind 5 has an outlier\r\n ys1vFlat = ys1v.reshape((ys1v.shape[0], -1))\r\n ys1etaFlat = ys1eta.reshape((ys1eta.shape[0], -1))\r\n \r\n t2 = time.time()\r\n print(t2 - t1)\r\n \r\n \r\n# Bootstrapping ===============================================================\r\n \r\n fulldataS = []\r\n \r\n for bcount in range(n_bootstrap):\r\n \r\n print(\"Bootstrap run: \" + str(bcount))\r\n \r\n fulldataC = copy.deepcopy(fulldataRaw)\r\n \r\n for m_i in range(len(sel)):\r\n if USEMEAN:\r\n for Di in range(N):\r\n ysmuMean = (ys0mu[m_i][iplTIdx] + ys1mu[m_i][iplTIdx])/2\r\n if Di in grp0:\r\n fulldataC[sel[m_i]][np.arange(0,t_n*N,N)+Di] = (ysmuMean \r\n + np.random.choice(ys0vFlat[m_i], size=t_n) \r\n + np.random.choice(ys0etaFlat[m_i], size=t_n))\r\n else:\r\n fulldataC[sel[m_i]][np.arange(0,t_n*N,N)+Di] = (ysmuMean \r\n + np.random.choice(ys1vFlat[m_i], size=t_n) \r\n + np.random.choice(ys1etaFlat[m_i], size=t_n))\r\n else:\r\n ct_rand = np.random.rand()\r\n for Di in range(N):\r\n if ct_rand < 0.5:\r\n if Di in grp0:\r\n fulldataC[sel[m_i]][np.arange(0,t_n*N,N)+Di] = (ys0mu[m_i][iplTIdx] \r\n + np.random.choice(ys0vFlat[m_i], size=t_n) \r\n + np.random.choice(ys0etaFlat[m_i], size=t_n))\r\n else:\r\n fulldataC[sel[m_i]][np.arange(0,t_n*N,N)+Di] = (ys0mu[m_i][iplTIdx] \r\n + np.random.choice(ys1vFlat[m_i], size=t_n) \r\n + np.random.choice(ys1etaFlat[m_i], size=t_n))\r\n else:\r\n if Di in grp0:\r\n fulldataC[sel[m_i]][np.arange(0,t_n*N,N)+Di] = (ys1mu[m_i][iplTIdx] \r\n + np.random.choice(ys0vFlat[m_i], size=t_n) \r\n + np.random.choice(ys0etaFlat[m_i], size=t_n))\r\n else:\r\n fulldataC[sel[m_i]][np.arange(0,t_n*N,N)+Di] = (ys1mu[m_i][iplTIdx]\r\n + np.random.choice(ys1vFlat[m_i], size=t_n)\r\n + np.random.choice(ys1etaFlat[m_i], size=t_n))\r\n \r\n fulldataC = fulldataC.drop(fulldataC.index[16]) # ind 5 has an outlier\r\n fulldataS.append(fulldataC)\r\n \r\n fd_ri = pandas2ri.py2ri(fulldataC)\r\n \r\n fd_rigrp0 = fd_ri.rx(fd_ri.rx2(\"grp\").ro == 0, True)\r\n fd_rigrp1 = fd_ri.rx(fd_ri.rx2(\"grp\").ro == 1, True)\r\n \r\n for m_i in range(len(sel)):\r\n fd_rigrp0objbs = fd_rigrp0.rx2(sel[m_i])\r\n fd_rigrp1objbs = fd_rigrp1.rx2(sel[m_i])\r\n \r\n fit0 = smePack.sme(fd_rigrp0objbs, \r\n fd_rigrp0tme, \r\n fd_rigrp0ind, \r\n criteria=ctra, \r\n maxIter=maxIter, \r\n deltaEM=deltaEM, \r\n deltaNM=deltaNM, \r\n initial_lambda_mu=init_l_mc, \r\n initial_lambda_v=init_l_vc,\r\n normalizeTime=normalizeTime)\r\n fit1 = smePack.sme(fd_rigrp1objbs, \r\n fd_rigrp1tme, \r\n fd_rigrp1ind, \r\n criteria=ctra, \r\n maxIter=maxIter, \r\n deltaEM=deltaEM, \r\n deltaNM=deltaNM, \r\n initial_lambda_mu=init_l_mt, \r\n initial_lambda_v=init_l_vt,\r\n normalizeTime=normalizeTime)\r\n \r\n fit0coefbs = np.array(fit0.rx2('coefficients'))\r\n fit1coefbs = np.array(fit1.rx2('coefficients'))\r\n \r\n spl0mubs = interpolate.CubicSpline(t, fit0coefbs[0], bc_type='natural')\r\n ys0mubs[bcount][m_i] = spl0mubs(iplT)\r\n spl1mubs = interpolate.CubicSpline(t, fit1coefbs[0], bc_type='natural')\r\n ys1mubs[bcount][m_i] = spl1mubs(iplT)\r\n \r\n l2bs[bcount][m_i] = np.sqrt(np.trapz(np.square(ys0mubs[bcount][m_i] - ys1mubs[bcount][m_i]), x=iplT))\r\n \r\n for g0 in range(len(grp0)):\r\n spl0bs = interpolate.CubicSpline(t, fit0coefbs[g0 + 1] + fit0coefbs[0], bc_type='natural')\r\n ys0vHatbs[bcount][m_i][g0] = spl0bs(iplT)\r\n se0bs[bcount][m_i][g0] = np.trapz(np.square(ys0mubs[bcount][m_i] - ys0vHatbs[bcount][m_i][g0]), x=iplT)\r\n \r\n for g1 in range(len(grp1)):\r\n spl1bs = interpolate.CubicSpline(t, fit1coefbs[g1 + 1] + fit1coefbs[0], bc_type='natural')\r\n ys1vHatbs[bcount][m_i][g1] = spl1bs(iplT)\r\n se1bs[bcount][m_i][g1] = np.trapz(np.square(ys1mubs[bcount][m_i] - ys1vHatbs[bcount][m_i][g1]), x=iplT)\r\n \r\n sebs[bcount][m_i] = np.sqrt(np.mean(se0bs[bcount][m_i])/len(grp0) + np.mean(se1bs[bcount][m_i])/len(grp1))\r\n \r\n sembs = 0.\r\n \r\n tvalbs[bcount] = np.divide(l2bs[bcount], sebs[bcount] + sembs)\r\n \r\n\r\n t3 = time.time()\r\n print(t3 - t2) \r\n \r\n for m_i in range(len(sel)):\r\n pval[m_i] = (tvalbs[:,m_i] >= tval[m_i]).sum()/n_bootstrap\r\n \r\n pvalCorr = smm.multipletests(pval, alpha=0.05, method='fdr_bh')[1]\r\n \r\n print('p-value: ' + str(len(np.where(pval <= 0.05)[0])))\r\n print(np.where(pval <= 0.05)[0])\r\n\r\n\r\n# Plotting ====================================================================\r\n\r\ncmap1 = cm.get_cmap(colorMap, 2)\r\ncmap2 = cm.get_cmap(colorMap, N)\r\ncmap3 = cm.get_cmap(colorMap, len(sel))\r\ncmap_grp0 = cm.get_cmap('viridis', len(grp0))\r\ncmap_grp1 = cm.get_cmap('viridis', len(grp1))\r\n\r\n\r\ndef plotC(idx):\r\n \"\"\"\r\n Plots data points, individual, and mean curve of control group\r\n \r\n :param idx: index of the selection\r\n \"\"\"\r\n \r\n fdgrp0tme_arr = np.array(fulldata[fulldata.grp == 0][\"tme\"])\r\n fdgrp0sel_arr = np.array(fulldata[fulldata.grp == 0][sel])\r\n \r\n plt.figure(figsize=figSize)\r\n \r\n if not plotSMEMeanOnly:\r\n for g0 in range(len(grp0)):\r\n tmeIdx = np.where(grp0_f == grp0[g0])\r\n plt.plot(fdgrp0tme_arr[tmeIdx], fdgrp0sel_arr[:,idx][tmeIdx], color=cmap_grp0(g0), marker='o', linestyle='')\r\n plt.plot(iplT, ys0vHat[idx][g0], color=cmap_grp0(g0), linestyle='dashed')\r\n \r\n plt.plot(iplT, ys0mu[idx], lw=3, color=cmap1(0))\r\n plt.show()\r\n\r\n\r\ndef plotT(idx):\r\n \"\"\"\r\n Plots data points, individual, and mean curve of treatment group\r\n \r\n :param idx: index of the selection\r\n \"\"\"\r\n \r\n fdgrp1tme_arr = np.array(fulldata[fulldata.grp == 1][\"tme\"])\r\n fdgrp1sel_arr = np.array(fulldata[fulldata.grp == 1][sel])\r\n \r\n plt.figure(figsize=figSize)\r\n \r\n if not plotSMEMeanOnly:\r\n for g1 in range(len(grp1)):\r\n tmeIdx = np.where(grp1_f == grp1[g1])\r\n plt.plot(fdgrp1tme_arr[tmeIdx], fdgrp1sel_arr[:,idx][tmeIdx], color=cmap_grp1(g1), marker='o', linestyle='')\r\n plt.plot(iplT, ys1vHat[idx][g1], color=cmap_grp1(g1), linestyle='dashed')\r\n \r\n plt.plot(iplT, ys1mu[idx], lw=3, color=cmap1(1))\r\n plt.show()\r\n\r\n\r\ndef plotCT(idx):\r\n \"\"\"\r\n Plots data points, individual, and mean curve of both control and treatment group\r\n \r\n :param idx: index of the selection\r\n \"\"\"\r\n \r\n fdgrp0tme_arr = np.array(fulldata[fulldata.grp == 0][\"tme\"])\r\n fdgrp0sel_arr = np.array(fulldata[fulldata.grp == 0][sel])\r\n \r\n fdgrp1tme_arr = np.array(fulldata[fulldata.grp == 1][\"tme\"])\r\n fdgrp1sel_arr = np.array(fulldata[fulldata.grp == 1][sel])\r\n \r\n plt.figure(figsize=figSize)\r\n \r\n if not plotSMEMeanOnly:\r\n for g0 in range(len(grp0)):\r\n tmeIdx = np.where(grp0_f == grp0[g0])\r\n plt.plot(fdgrp0tme_arr[tmeIdx], fdgrp0sel_arr[:,idx][tmeIdx], color=cmap1(0), marker='o', linestyle='')\r\n plt.plot(iplT, ys0vHat[idx][g0], color=cmap1(0), linestyle='dashed')\r\n for g1 in range(len(grp1)):\r\n tmeIdx = np.where(grp1_f == grp1[g1])\r\n plt.plot(fdgrp1tme_arr[tmeIdx], fdgrp1sel_arr[:,idx][tmeIdx], color=cmap1(1), marker='o', linestyle='')\r\n plt.plot(iplT, ys1vHat[idx][g1], color=cmap1(len(sel)), linestyle='dashed')\r\n \r\n plt.plot(iplT, ys0mu[idx], lw=3, color=cmap1(0))\r\n plt.plot(iplT, ys1mu[idx], lw=3, color=cmap1(1))\r\n plt.show()\r\n\r\n\r\ndef plotCTbs(bcount, idx):\r\n \"\"\"\r\n Plots data points, individual, and mean curve of both control and treatment group for a bootstrapping sample\r\n \r\n :param bcount: index of bootstrapping sample\r\n :param idx: index of the selection\r\n \"\"\" \r\n \r\n fdgrp0tme_arr = np.array(fulldataS[bcount][fulldataS[bcount].grp == 0][\"tme\"])\r\n fdgrp0sel_arr = np.array(fulldataS[bcount][fulldataS[bcount].grp == 0][sel])\r\n \r\n fdgrp1tme_arr = np.array(fulldataS[bcount][fulldataS[bcount].grp == 1][\"tme\"])\r\n fdgrp1sel_arr = np.array(fulldataS[bcount][fulldataS[bcount].grp == 1][sel])\r\n \r\n plt.figure(figsize=figSize)\r\n \r\n if not plotSMEMeanOnly:\r\n for g0 in range(len(grp0)):\r\n tmeIdx = np.where(grp0_f == grp0[g0])\r\n plt.plot(fdgrp0tme_arr[tmeIdx], fdgrp0sel_arr[:,idx][tmeIdx], color=cmap1(0), marker='o', linestyle='')\r\n plt.plot(iplT, ys0vHatbs[bcount][idx][g0], color=cmap1(0), linestyle='dashed')\r\n for g1 in range(len(grp1)):\r\n tmeIdx = np.where(grp1_f == grp1[g1])\r\n plt.plot(fdgrp1tme_arr[tmeIdx], fdgrp1sel_arr[:,idx][tmeIdx], color=cmap1(1), marker='o', linestyle='')\r\n plt.plot(iplT, ys1vHatbs[bcount][idx][g1], color=cmap1(len(sel)), linestyle='dashed')\r\n \r\n plt.plot(iplT, ys0mubs[bcount][idx], lw=3, color=cmap1(0))\r\n plt.plot(iplT, ys1mubs[bcount][idx], lw=3, color=cmap1(1))\r\n plt.show()\r\n\r\ndef exportOutput(path=None):\r\n \"\"\"\r\n Export an output to specified path\r\n \r\n \"\"\"\r\n \r\n if path:\r\n outputdir = path\r\n else:\r\n outputdir = os.path.join(os.getcwd(), 'output')\r\n \r\n if not os.path.exists(outputdir):\r\n os.mkdir(outputdir)\r\n \r\n fulldataRaw.to_csv(os.path.join(outputdir, 'fulldataRaw.csv'))\r\n fulldata.to_csv(os.path.join(outputdir, 'fulldata.csv'))\r\n \r\n df = pd.DataFrame(ys0mu)\r\n df.to_csv(os.path.join(outputdir, 'ys0mu.csv'))\r\n df = pd.DataFrame(ys1mu)\r\n df.to_csv(os.path.join(outputdir, 'ys1mu.csv'))\r\n \r\n if not os.path.exists(os.path.join(outputdir, 'ys0vHat')):\r\n os.mkdir(os.path.join(outputdir, 'ys0vHat'))\r\n if not os.path.exists(os.path.join(outputdir, 'ys1vHat')):\r\n os.mkdir(os.path.join(outputdir, 'ys1vHat'))\r\n \r\n for i in range(len(ys0vHat)):\r\n df1 = pd.DataFrame(ys0vHat[i])\r\n df1.to_csv(os.path.join(os.path.join(outputdir, 'ys0vHat'), 'ys0vHat_' + str(i) + '.csv'))\r\n df2 = pd.DataFrame(ys1vHat[i])\r\n df2.to_csv(os.path.join(os.path.join(outputdir, 'ys1vHat'), 'ys1vHat_' + str(i) + '.csv'))\r\n\r\n df = pd.DataFrame(pval)\r\n df.to_csv(os.path.join(outputdir, 'pval.csv'))\r\n \r\nif RUN and SAVE:\r\n exportOutput()\r\n\r\n\r\n" ]
[ [ "numpy.linspace", "pandas.DataFrame", "numpy.mean", "numpy.where", "numpy.divide", "numpy.square", "pandas.read_csv", "numpy.unique", "numpy.arange", "scipy.interpolate.CubicSpline", "matplotlib.pyplot.figure", "pandas.concat", "numpy.random.choice", "numpy.delete", "numpy.random.rand", "matplotlib.pyplot.show", "numpy.array", "numpy.random.seed", "matplotlib.cm.get_cmap", "numpy.empty" ] ]
ashwinwadte/sagemaker-deployment
[ "c453bce0a4dfcf45a8eb546048f7080d533cabeb" ]
[ "Project/serve/predict.py" ]
[ "import argparse\nimport json\nimport os\nimport pickle\nimport sys\nimport sagemaker_containers\nimport pandas as pd\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data\n\nfrom model import LSTMClassifier\n\nfrom utils import review_to_words, convert_and_pad\n\ndef model_fn(model_dir):\n \"\"\"Load the PyTorch model from the `model_dir` directory.\"\"\"\n print(\"Loading model.\")\n\n # First, load the parameters used to create the model.\n model_info = {}\n model_info_path = os.path.join(model_dir, 'model_info.pth')\n with open(model_info_path, 'rb') as f:\n model_info = torch.load(f)\n\n print(\"model_info: {}\".format(model_info))\n\n # Determine the device and construct the model.\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = LSTMClassifier(model_info['embedding_dim'], model_info['hidden_dim'], model_info['vocab_size'])\n\n # Load the store model parameters.\n model_path = os.path.join(model_dir, 'model.pth')\n with open(model_path, 'rb') as f:\n model.load_state_dict(torch.load(f))\n\n # Load the saved word_dict.\n word_dict_path = os.path.join(model_dir, 'word_dict.pkl')\n with open(word_dict_path, 'rb') as f:\n model.word_dict = pickle.load(f)\n\n model.to(device).eval()\n\n print(\"Done loading model.\")\n return model\n\ndef input_fn(serialized_input_data, content_type):\n print('Deserializing the input data.')\n if content_type == 'text/plain':\n data = serialized_input_data.decode('utf-8')\n return data\n raise Exception('Requested unsupported ContentType in content_type: ' + content_type)\n\ndef output_fn(prediction_output, accept):\n print('Serializing the generated output.')\n return str(prediction_output)\n\ndef predict_fn(input_data, model):\n print('Inferring sentiment of input data.')\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n \n if model.word_dict is None:\n raise Exception('Model has not been loaded properly, no word_dict.')\n \n # TODO: Process input_data so that it is ready to be sent to our model.\n # You should produce two variables:\n # data_X - A sequence of length 500 which represents the converted review\n # data_len - The length of the review\n \n words = review_to_words(input_data)\n data_X, data_len = convert_and_pad(model.word_dict, words)\n\n # Using data_X and data_len we construct an appropriate input tensor. Remember\n # that our model expects input data of the form 'len, review[500]'.\n data_pack = np.hstack((data_len, data_X))\n data_pack = data_pack.reshape(1, -1)\n \n data = torch.from_numpy(data_pack)\n data = data.to(device)\n\n # Make sure to put the model into evaluation mode\n model.eval()\n\n # TODO: Compute the result of applying the model to the input data. The variable `result` should\n # be a numpy array which contains a single integer which is either 1 or 0\n with torch.no_grad():\n output = model(data)\n\n result = np.round(output.numpy())\n\n return result\n" ]
[ [ "numpy.hstack", "torch.load", "torch.from_numpy", "torch.no_grad", "torch.cuda.is_available" ] ]
bt2901/TopicNet
[ "cab4c5a5fa259a5709e736c819598caf84841206" ]
[ "topicnet/cooking_machine/models/blei_lafferty_score.py" ]
[ "import numpy as np\n\nfrom typing import Callable\n\nfrom .base_score import BaseScore\n\n\nclass BleiLaffertyScore(BaseScore):\n \"\"\"\n This score implements method described in 2009 paper\n Blei, David M., and John D. Lafferty. \"Topic models.\" Text Mining.\n Chapman and Hall/CRC, 2009. 101-124.\n At the core this score helps to discover tokens that are most likely\n to describe given topic. Summing up that score helps to estimate how\n well the model distinguishes between topics. The higher this score - better\n \"\"\"\n def __init__(\n self,\n name: str = None,\n num_top_tokens: int = 30,\n should_compute: Callable[[int], bool] = None):\n \"\"\"\n\n Parameters\n ----------\n name:\n name of the score\n num_top_tokens : int\n now many tokens we consider to be\n\n \"\"\"\n super().__init__(name=name, should_compute=should_compute)\n\n self.num_top_tokens = num_top_tokens\n\n def __repr__(self):\n return f'{self.__class__.__name__}(num_top_tokens={self.num_top_tokens})'\n\n def _compute_blei_scores(self, phi):\n \"\"\"\n Computes Blei score \n phi[wt] * [log(phi[wt]) - 1/T sum_k log(phi[wk])]\n\n Parameters\n ----------\n phi : pd.Dataframe\n phi matrix of the model\n\n Returns\n -------\n score : pd.Dataframe\n wheighted phi matrix\n\n \"\"\" # noqa: W291\n\n topic_number = phi.shape[1]\n blei_eps = 1e-42\n log_phi = np.log(phi + blei_eps)\n numerator = np.sum(log_phi, axis=1)\n numerator = numerator[:, np.newaxis]\n\n if hasattr(log_phi, \"values\"):\n multiplier = log_phi.values - numerator / topic_number\n else:\n multiplier = log_phi - numerator / topic_number\n\n scores = phi * multiplier\n return scores\n\n def call(self, model, **kwargs):\n modalities = list(model.class_ids.keys())\n\n score = 0\n for modality in modalities:\n phi = model.get_phi(class_ids=modality)\n modality_scores = np.sort(self._compute_blei_scores(phi).values)\n score += np.sum(modality_scores[-self.num_top_tokens:, :])\n if modalities is None:\n phi = model.get_phi()\n modality_scores = np.sort(self._compute_blei_scores(phi).values)\n score = np.sum(modality_scores[-self.num_top_tokens:, :])\n return score\n" ]
[ [ "numpy.log", "numpy.sum" ] ]
Stefanlarsson95/CV2
[ "9be422cdfe75f2c9571367c27808b3ae2b8a824b" ]
[ "old_camera_calibration.py" ]
[ "import numpy as np\nimport cv2\nimport glob\nfrom matplotlib import pyplot as plt\nfrom stereovision.blockmatchers import *\nfrom stereovision.calibration import *\nfrom stereovision.ui_utils import *\n\nblock_matcher = StereoSGBM() # alt StereoBM() Todo fix\ncalibration = StereoCalibration(input_folder='old_stereo_calibration')\n\n\ndef plot_disparuty():\n imgL = cv2.imread('capture/left.jpg*', 0)\n imgR = cv2.imread('capture/right.jpg*', 0)\n\n stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)\n disparity = stereo.compute(imgL, imgR)\n plt.imshow(disparity, 'gray')\n plt.show()\n\n\ndef show_corners():\n import glob\n Nx_cor = 9 # Number of corners to find\n Ny_cor = 6\n # Prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\n objp = np.zeros((Nx_cor * Ny_cor, 3), np.float32)\n objp[:, :2] = np.mgrid[0:Nx_cor, 0:Ny_cor].T.reshape(-1, 2)\n objpoints = [] # 3d points in real world space\n imgpoints = [] # 2d points in image plane.\n images = glob.glob(\n 'capture/right/right*') # Make a list of paths to calibration images\n # Step through the list and search for chessboard corners\n img_w_corner = []\n corners_not_found = [] # Calibration images in which OpenCV failed to find corners\n print('Calculating corners')\n for idx, fname in enumerate(images):\n print('frame: {}'.format(idx))\n img = cv2.imread(fname)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Conver to grayscale\n ret, corners = cv2.findChessboardCorners(gray, (Nx_cor, Ny_cor), None) # Find the corners\n # If found, add object points, image points\n if ret:\n objpoints.append(objp)\n imgpoints.append(corners)\n cv2.drawChessboardCorners(img, (Nx_cor, Ny_cor), corners, True)\n img_w_corner.append(img)\n else:\n corners_not_found.append(fname)\n print('Calculation done!')\n cv2.namedWindow(\"Corners\", cv2.WINDOW_AUTOSIZE)\n for img_pt in img_w_corner:\n # Draw corners\n cv2.imshow(\"Corners\", cv2.rotate(img_pt, 2))\n if (cv2.waitKey(3000) & 0xFF) == 27:\n break\n cv2.destroyAllWindows()\n\n\ndef generate_calibrator(indir='capture', outdir='old_stereo_calibration', rows=6, columns=9, square_size=1.8):\n image_size = (720, 1280-500)\n print('Stating camera calibrator...')\n print('Importing files...')\n files_left = glob.glob(indir + '/left/*')\n # files_left.sort()\n files_right = glob.glob(indir + '/right/*')\n # files_right.sort()\n images_left = [cv2.imread(img)[:, 250:1280-250] for img in files_left]\n images_right = [cv2.imread(img)[:, 250:1280-250] for img in files_right]\n assert len(images_left) == len(images_right), 'Number of left/right images does not match!'\n\n images = [pair for pair in zip(images_left, images_right)]\n\n print('Creating image calibrator...')\n # create calibrator object\n calibrator = StereoCalibrator(rows, columns, square_size, image_size)\n\n # add image pairs to calibrator\n for i, img in enumerate(images):\n print('scanning image pair: {}'.format(i))\n gray_left = cv2.cvtColor(img[0], cv2.COLOR_BGR2GRAY)\n gray_right = cv2.cvtColor(img[1], cv2.COLOR_BGR2GRAY)\n ret_left, _ = cv2.findChessboardCorners(gray_left, (rows, columns), None) # Find the corners\n ret_right, _ = cv2.findChessboardCorners(gray_right, (rows, columns), None) # Find the corners\n if not (ret_left and ret_right):\n print('No chessboard found in image pair {}'.format(i))\n continue\n calibrator.add_corners((img[0], img[1]))\n # run calibrator\n print('Generating calibration...')\n calibration = calibrator.calibrate_cameras()\n\n print('Calculating average error: ', end='')\n avg_error = calibrator.check_calibration(calibration)\n print(avg_error)\n\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n\n calibration.export(outdir)\n\n\ndef show_rectified(indir='capture'):\n files_left = glob.glob(indir + '/left/*')\n # files_left.sort()\n files_right = glob.glob(indir + '/right/*')\n # files_right.sort()\n images_left = [cv2.imread(img) for img in files_left]\n images_right = [cv2.imread(img) for img in files_right]\n assert len(images_left) == len(images_right), 'Number of left/right images does not match!'\n images = [pair for pair in zip(images_left, images_right)]\n\n cv2.namedWindow(\"Calibration\", cv2.WINDOW_AUTOSIZE)\n\n for pairs in images:\n rectified_pair = calibration.rectify(pairs)\n\n left = rectified_pair[0]\n right = rectified_pair[1]\n # left = cv2.rotate(left, 1)\n # right = cv2.rotate(right, 1)\n cv2.imshow(\"Calibration\", np.hstack([left, right]))\n if (cv2.waitKey(3000) & 0xFF) == 27:\n cv2.destroyAllWindows()\n break\n\n cv2.destroyAllWindows()\n\n\ndef BMtune(indir='capture'):\n block_matcher = StereoSGBM()\n\n files_left = glob.glob(indir + '/left/*')\n # files_left.sort()\n files_right = glob.glob(indir + '/right/*')\n # files_right.sort()\n images_left = [cv2.imread(img) for img in files_left]\n images_right = [cv2.imread(img) for img in files_right]\n assert len(images_left) == len(images_right), 'Number of left/right images does not match!'\n images = [pair for pair in zip(images_left, images_right)]\n\n rectified_pair = calibration.rectify(images[10])\n cv2.namedWindow(\"Calibration\", cv2.WINDOW_AUTOSIZE)\n\n cv2.imshow(\"Calibration\", cv2.rotate(np.vstack(rectified_pair), 2))\n if (cv2.waitKey(3000) & 0xFF) == 27:\n cv2.destroyAllWindows()\n return\n\n bm_tuner = BMTuner(block_matcher, calibration, rectified_pair)\n\n for pair in images:\n rectified_pair = calibration.rectify(pair)\n bm_tuner.tune_pair(rectified_pair)\n\n for param in block_matcher.parameter_maxima:\n print(\"{}\\n\".format(bm_tuner.report_settings(param)))\n\n\nif __name__ == '__main__':\n generate_calibrator()\n # show_corners()\n show_rectified()\n # BMtune()\n" ]
[ [ "numpy.hstack", "matplotlib.pyplot.imshow", "matplotlib.pyplot.show", "numpy.zeros", "numpy.vstack" ] ]
FSLobao/Spectrum-Cortex
[ "e3eca47a776c6da5769e97e72d9a94be42c6bcfa" ]
[ "compute_channel_distance.py" ]
[ "#!/usr/bin/python3\n\n# # Compute the distance between traces for clustering\n\n# Import standard libraries\nimport pandas as pd\nimport numpy as np\nfrom scipy import signal\nfrom scipy.cluster.hierarchy import dendrogram, linkage\n\nimport matplotlib.pyplot as plt\nimport h5py\n\n# Import specific libraries used by the cortex system\nimport h5_spectrum as H5\nimport cortex_names as cn\nimport cortex_lib as cl\n\n# TODO: This could be improved by testing the similarity before merging and so allow for separation of co channel emissions\n\ndef _main():\n\n # constant to activate the demonstration plot\n PLOT_COMPARISON = True\n\n cl.log_message(\"Starting channel distance processing\")\n\n # open file with h5Py method\n input_file_name = cn.FOLDER_TO_STORE_FILES+'/'+cn.DATA_FILENAME\n input_file = h5py.File(input_file_name)\n\n input_group_name = H5.CHANNEL_DATA_GROUP+\"/\"+cn.CHANNEL_MEAN_LEVEL_CATALOG\n input_group = input_file[input_group_name]\n\n # create dictionary to store channel traces\n channel_traces = {}\n channel_frequency = {}\n\n # create dataframe to store chanel info\n channel_info = pd.DataFrame()\n\n # loop through all channels, load data into the traces dictionary and extract reference information into the channel info dataframe\n for channel_id in input_group:\n\n # TODO: Channels should have attributes and those should be verified to confirm the proper funcyion\n one_channel = input_group[channel_id][1]\n\n channel_width = len(one_channel)\n\n # ignore channels that are too small\n if channel_width > cn.MINIMUM_CHANNEL_WIDTH:\n\n # find maximum\n maximum_level = np.max(one_channel)\n\n # locate the index for the maximum\n index_of_maximum = np.argmax(one_channel)\n # handle multiple maximum case\n if isinstance(index_of_maximum, np.ndarray):\n index_of_maximum = np.mean(index_of_maximum)\n\n frequency_at_peak = input_group[channel_id][0][index_of_maximum]\n\n # transform level to relative a scale where the maximum equals to 1\n channel_traces[channel_id] = np.array(one_channel/maximum_level, dtype='float64')\n channel_frequency[channel_id] = (np.array(input_group[channel_id][0], dtype='float64')-frequency_at_peak)/1000\n\n channel_info.loc[channel_id, 'Max Index'] = index_of_maximum\n channel_info.loc[channel_id, 'Bin Width'] = channel_width\n channel_info.loc[channel_id, 'Min Value'] = np.min(channel_traces[channel_id])\n channel_info.loc[channel_id, 'Max Value'] = maximum_level\n channel_info.loc[channel_id, 'Frequency Max Value'] = frequency_at_peak\n # close file since all data has been loaded into memory\n input_file.close()\n\n # create a list of keys used for the channels trace designation on the corresponding dictionary\n channel_list = list(channel_traces.keys())\n\n # create array to store the condensed distance matrix\n number_of_channels = len(channel_list)\n condensed_distance = np.empty(int(round(((number_of_channels**2)-number_of_channels)/2, 0)))\n c_d_index = 0\n\n # loop though channels to compute distance between then\n for ref_channel_index in range(0, number_of_channels):\n\n # get key and trace from index\n ref_channel_id = channel_list[ref_channel_index]\n\n cl.log_message(\"Starting channel {}\".format(ref_channel_id))\n\n # defines the lower limit to the reference channel level range\n min_ref_level = channel_info.loc[ref_channel_id, 'Min Value']\n\n #PLOT_THRESHOLD = 0.3\n #plot_this = (min_ref_level < PLOT_THRESHOLD)\n\n # loop through all channels and compute the distance\n for target_channel_index in range(ref_channel_index+1, number_of_channels):\n\n if PLOT_COMPARISON:\n percentage_string = \"\\r{}%\".format(round(100.0*(target_channel_index/number_of_channels), ndigits=1))\n print(percentage_string, end=\"\\r\", flush=True)\n\n # get key and trace from index\n target_channel_id = channel_list[target_channel_index]\n target_channel_trace = channel_traces[target_channel_id]\n\n # defines the lower limit to the reference channel level range\n min_target_level = channel_info.loc[target_channel_id, 'Min Value']\n\n #plot_that = (min_target_level < PLOT_THRESHOLD)\n #plot_all = plot_this and plot_that\n\n #if (target_channel_id == '462574') and (ref_channel_id == '451011'):\n # print('gotcha')\n\n # Cut the channels in the level axis such as that both have the same range. Equivalent to raise noise\n # If the reference channel has larger minimum reference level\n if min_ref_level > min_target_level:\n # Means that the peak value of the reference channel is lower, closer to the noise level\n # cut the target channel to the same range as the reference channel and copy the reference to the work variable\n target_channel_trace = target_channel_trace[target_channel_trace[:] >= min_ref_level]\n work_ref_channel_trace = channel_traces[ref_channel_id]\n\n elif min_ref_level < min_target_level:\n # else, if the reference channel has smaller minimum referecence level\n # cut the reference channel to the same range as the target channel and leave the target channel as it is\n work_ref_channel_trace = channel_traces[ref_channel_id][channel_traces[ref_channel_id][:] >= min_target_level]\n\n else:\n # else, both are the same, and just update the work variable reference\n work_ref_channel_trace = channel_traces[ref_channel_id]\n\n # After level cut, assign first trace on the correlation process to be the longest.\n # The correlation values are not affected by the order but their relative indexing to the result is.\n # For the implemented method of alignment, the first trace should be the largest\n \n if work_ref_channel_trace.size > target_channel_trace.size:\n smaller_trace = target_channel_trace.view()\n larger_trace = work_ref_channel_trace.view()\n\n if PLOT_COMPARISON:\n figure_file_name = \"./Images/\"+figure1_name+\".png\"\n figure1_name = \"Comparison_{}-{} \".format(ref_channel_id, target_channel_id)\n plt.figure(figure1_name)\n\n sp1 = plt.subplot(311)\n plt.title('Channel [{}] (wider)'.format(ref_channel_id))\n plt.ylabel('Norm. Level')\n plt.plot(channel_traces[ref_channel_id], 'r-o')\n plt.setp(sp1.get_xticklabels(), visible=False)\n\n sp2 = plt.subplot(312, sharex=sp1, sharey=sp1)\n plt.title('Channel [{}] (narrower)'.format(target_channel_id))\n plt.ylabel('Norm. Level')\n plt.plot(channel_traces[target_channel_id], 'b-^')\n plt.setp(sp2.get_xticklabels(), visible=False)\n\n else:\n smaller_trace = work_ref_channel_trace.view()\n larger_trace = target_channel_trace.view()\n\n if PLOT_COMPARISON:\n figure1_name = \"Comparison_{}-{} \".format(ref_channel_id, target_channel_id)\n plt.figure(figure1_name)\n\n sp1 = plt.subplot(311)\n plt.title('Channel [{}] (wider)'.format(target_channel_id))\n plt.ylabel('Norm. Level')\n plt.plot(channel_traces[target_channel_id], 'r-o')\n plt.setp(sp1.get_xticklabels(), visible=False)\n\n sp2 = plt.subplot(312, sharex=sp1, sharey=sp1)\n plt.title('Channel [{}] (narrower)'.format(ref_channel_id))\n plt.ylabel('Norm. Level')\n plt.plot(channel_traces[ref_channel_id], 'b-^')\n plt.setp(sp2.get_xticklabels(), visible=False)\n\n \"\"\"\n larger_trace = work_ref_channel_trace.view()\n smaller_trace = target_channel_trace.view()\n \"\"\"\n\n # computes the cross correlation between channels\n correlation = signal.correlate(larger_trace, smaller_trace, mode='full', method='fft')\n peak_correlation_index = np.argmax(correlation)\n\n # compute the length of distance to be cutted out from the beginning of one of the traces such as to align it both at maximum correlation\n total_trace_shift = peak_correlation_index-(smaller_trace.size-1)\n size_difference = larger_trace.size - smaller_trace.size\n\n # if the total shift is negative\n if total_trace_shift < 0:\n # smaller trace needs to be moved to the left,\n # cut the begin of the smaller trace by the total shift\n smaller_trace = smaller_trace[-total_trace_shift:]\n # cut the larger trace to the same size as the second\n larger_trace = larger_trace[0:(larger_trace.size-size_difference+total_trace_shift)]\n # else, smaller trace needs to be moved to the right\n else:\n end_offset = size_difference-total_trace_shift\n # if shift is equal or smaller than the difference in size of the traces\n if end_offset >= 0:\n # cut the begin of the larger trace by the required shift\n # cut the end of the larger trace to match the sizes\n larger_trace = larger_trace[total_trace_shift:larger_trace.size-end_offset]\n # else, smaller trace needs to be moved to the right but will overflow the larger trace\n else:\n # cut the smaller trace by the difference from the shift and size difference\n smaller_trace = smaller_trace[0:smaller_trace.size+end_offset]\n # cut the begin of the first trace by to match the second trace\n larger_trace = larger_trace[size_difference-end_offset:]\n\n # Compute the error. Uses RMSE as an normalized approximation of the euclidian distance (RSSE)\n # The use of mean is necessary due to the variable number of bins\n\n rms_distance = np.sqrt(np.mean((smaller_trace-larger_trace)**2))\n\n channel_info.loc[ref_channel_id, target_channel_id] = rms_distance\n\n condensed_distance[c_d_index] = rms_distance\n c_d_index += 1\n\n\n if PLOT_COMPARISON:\n sp3 = plt.subplot(313, sharex=sp1, sharey=sp1)\n plt.title('Traces aligned and cropped for comparison')\n plt.ylabel('Norm. Level')\n plt.xlabel('Frequency bin index')\n plt.plot(larger_trace, 'r-o', smaller_trace, 'b-^')\n plt.setp(sp3.get_xticklabels(), visible=True)\n plt.tight_layout()\n\n figure_file_name = \"./Images/Compare/\"+figure1_name+\".png\"\n plt.savefig(figure_file_name)\n\n #plt.show()\n\n plt.close(figure1_name)\n\n \"\"\"\n if ref_channel_id == '450188': # '466862':\n\n half_trace_length = int(work_ref_channel_trace.size/2)\n if 2*half_trace_length < work_ref_channel_trace.size:\n ref_index = np.arange(-half_trace_length, half_trace_length+1, 1)\n else:\n ref_index = np.arange(-half_trace_length, half_trace_length, 1)\n\n half_trace_length = int(target_channel_trace.size/2)\n if 2*half_trace_length < target_channel_trace.size:\n target_index = np.arange(-half_trace_length, half_trace_length+1, 1)\n else:\n target_index = np.arange(-half_trace_length, half_trace_length, 1)\n\n half_trace_length = int(correlation.size/2)\n if 2*half_trace_length < correlation.size:\n cor_index = np.arange(-half_trace_length, half_trace_length+1, 1)\n else:\n cor_index = np.arange(-half_trace_length, half_trace_length, 1)\n\n ref_index = np.arange(0, larger_trace.size, 1)\n target_index = np.arange(0, target_channel_trace.size, 1)\n cor_index = np.arange(0, correlation.size, 1)\n\n plt.figure(1)\n plt.subplot(211)\n plt.plot(larger_trace, 'r-', smaller_trace, 'b-')\n\n plt.subplot(212)\n plt.plot(correlation, 'g-')\n plt.show()\n\n plt.plot(larger_trace, 'r-', smaller_trace, 'b-',correlation/np.max(correlation), 'g-')\n plt.show()\n\n if is_it_autocorrelation:\n autocorrelation = np.max(correlation)-np.min(correlation)\n is_it_autocorrelation = False\n channel_info.loc[ref_channel_id, target_channel_id] = 1.0\n else:\n # store the relative correlation peak as reference for the channel similarity\n channel_info.loc[ref_channel_id, target_channel_id] = (np.max(correlation)-np.min(correlation))/autocorrelation\n \"\"\"\n\n print(\"\\n\")\n\n # perform grouping by the distance and plot dendograms\n NUMBER_OF_GROUPS = 6\n figure2_name = \"Dendogram cut p={}\".format(NUMBER_OF_GROUPS)\n plt.figure(figure2_name, figsize=(8, 6), dpi=80, frameon=False)\n linkage_matrix = linkage(condensed_distance, method=\"complete\", optimal_ordering=True)\n cut_dendo = dendrogram(linkage_matrix,\n labels=channel_list,\n truncate_mode='lastp',\n p=NUMBER_OF_GROUPS,\n leaf_rotation=90.,\n leaf_font_size=9.,\n show_contracted=True)\n\n figure_file_name = \"./Images/\"+figure2_name+\".png\"\n plt.savefig(figure_file_name)\n\n figure3_name = \"Dendogram Complete\"\n plt.figure(figure3_name, figsize=(8, 6), dpi=80, frameon=False)\n complete_dendo = dendrogram(linkage_matrix,\n labels=channel_list,\n leaf_rotation=90.,\n leaf_font_size=8.)\n\n figure_file_name = \"./Images/\"+figure3_name+\".png\"\n plt.savefig(figure_file_name)\n\n # creata a description of the channels on each group that compose a specific branch\n leaves = complete_dendo['ivl']\n branch_id = 0\n branch_dict = {branch_id:[]}\n number_of_leaves_in_branche = int(cut_dendo['ivl'][branch_id][1:-1])-1\n number_of_leaves_already_considered = 0\n\n for leave_index, channel_id in enumerate(leaves):\n if leave_index > number_of_leaves_in_branche+number_of_leaves_already_considered:\n branch_id += 1\n number_of_leaves_in_branche = int(cut_dendo['ivl'][branch_id][1:-1])-1\n number_of_leaves_already_considered = leave_index\n branch_dict[branch_id] = []\n\n branch_dict[branch_id] = branch_dict[branch_id]+[channel_id]\n\n classified_groups = pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in branch_dict.items() ]))\n\n cl.table_dataframe(classified_groups)\n\n plt.show()\n\n plt.close(figure2_name)\n plt.close(figure3_name)\n\n cl.table_dataframe(channel_info)\n\n channel_ref_index = 0\n group_referece = 1\n\n \"\"\"\n # identify channel within each group that has the highest signal to noise ratio to represent the group\n for group_size_string in cut_dendo['ivl']:\n group_size = int(group_size_string[1:-1])\n channel_id = complete_dendo['ivl'][channel_ref_index]\n minimum_channel_level = channel_info.loc[channel_id, 'Min Value']\n channel_group_reference = channel_id\n for channel_index in range(1,group_size):\n channel_ref_index += 1\n channel_id = complete_dendo['ivl'][channel_ref_index]\n current_channel_level = channel_info.loc[channel_id, 'Min Value']\n if minimum_channel_level > current_channel_level:\n minimum_channel_level = current_channel_level\n channel_group_reference = channel_id\n channel_ref_index += 1\n\n plt.figure(\"Channel {}. Reference to group {}\".format(channel_group_reference, group_referece))\n plt.plot(channel_frequency[channel_group_reference],\n channel_traces[channel_group_reference]*channel_info.loc[channel_group_reference, 'Max Value'])\n plt.ylabel(\"Level [dB\\u03BCV/m]\")\n plt.xlabel(\"Frequency[kHz]\")\n\n group_referece += 1\n\n #dendrogram(linkage_matrix, labels=channel_list, leaf_rotation=90., leaf_font_size=12.)\n\n \n \"\"\"\n\n # store the dataframe with the data.\n output_file_name = cn.FOLDER_TO_STORE_FILES+'/'+cn.DATA_FILENAME\n file_data_store = pd.HDFStore(output_file_name)\n output_group_name = H5.CHANNEL_DATA_GROUP+\"/\"+cn.INTER_CHANNEL_DISTANCES\n file_data_store[output_group_name] = channel_info\n output_group_name = H5.CHANNEL_DATA_GROUP+\"/\"+cn.INTER_CHANNEL_DISTANCES_CONDENSED_MATRIX\n file_data_store[output_group_name] = pd.DataFrame(condensed_distance)\n file_data_store.close()\n\n cl.log_message(\"Finish processing\")\n\nif __name__ == '__main__':\n _main()\n" ]
[ [ "pandas.Series", "scipy.signal.correlate", "pandas.DataFrame", "matplotlib.pyplot.plot", "numpy.max", "numpy.mean", "matplotlib.pyplot.tight_layout", "numpy.argmax", "matplotlib.pyplot.subplot", "matplotlib.pyplot.close", "scipy.cluster.hierarchy.linkage", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "numpy.min", "matplotlib.pyplot.savefig", "pandas.HDFStore", "scipy.cluster.hierarchy.dendrogram", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel" ] ]
teamILLO/SDPS-Net
[ "83736700c917325ed419a10d8b6219ce475f4f75" ]
[ "datasets/UPS_Custom_Dataset.py" ]
[ "from __future__ import division\nimport os\nimport numpy as np\nimport scipy.io as sio\nfrom imageio import imread\n\nimport torch\nimport torch.utils.data as data\n\nfrom datasets import pms_transforms\nfrom . import util\nnp.random.seed(0)\n\nclass UPS_Custom_Dataset(data.Dataset):\n def __init__(self, args, split='train'):\n self.root = os.path.join(args.bm_dir)\n self.split = split\n self.args = args\n self.objs = util.readList(os.path.join(self.root, 'objects.txt'), sort=False)\n args.log.printWrite('[%s Data] \\t%d objs. Root: %s' % (split, len(self.objs), self.root))\n\n def _getMask(self, obj):\n mask = imread(os.path.join(self.root, obj, 'mask.png'))\n if mask.ndim > 2: mask = mask[:,:,0]\n mask = mask.reshape(mask.shape[0], mask.shape[1], 1)\n return mask / 255.0\n\n def __getitem__(self, index):\n obj = self.objs[index]\n names = util.readList(os.path.join(self.root, obj, 'names.txt'))\n img_list = [os.path.join(self.root, obj, names[i]) for i in range(len(names))]\n\n if self.args.have_l_dirs:\n dirs = np.genfromtxt(os.path.join(self.root, obj, 'light_directions.txt'))\n else:\n dirs = np.zeros((len(names), 3))\n dirs[:,2] = 1\n \n if self.args.have_l_ints:\n ints = np.genfromtxt(os.path.join(self.root, obj, 'light_intensities.txt'))\n else:\n ints = np.ones((len(names), 3))\n\n imgs = []\n for idx, img_name in enumerate(img_list):\n img = imread(img_name).astype(np.float32) / 255.0\n imgs.append(img)\n img = np.concatenate(imgs, 2)\n h, w, c = img.shape\n\n if self.args.have_gt_n:\n normal_path = os.path.join(self.root, obj, 'normal.png')\n normal = imread(normal_path).astype(np.float32) / 255.0 * 2 - 1\n else:\n normal = np.zeros((h, w, 3))\n\n mask = self._getMask(obj)\n img = img * mask.repeat(img.shape[2], 2)\n\n item = {'normal': normal, 'img': img, 'mask': mask}\n\n downsample = 4 \n for k in item.keys():\n item[k] = pms_transforms.imgSizeToFactorOfK(item[k], downsample)\n\n for k in item.keys(): \n item[k] = pms_transforms.arrayToTensor(item[k])\n\n item['dirs'] = torch.from_numpy(dirs).view(-1, 1, 1).float()\n item['ints'] = torch.from_numpy(ints).view(-1, 1, 1).float()\n item['obj'] = obj\n item['path'] = os.path.join(self.root, obj)\n return item\n\n def __len__(self):\n return len(self.objs)\n" ]
[ [ "numpy.concatenate", "numpy.zeros", "torch.from_numpy", "numpy.random.seed" ] ]
aangelopoulos/conformal_classification
[ "db3a42f47d4f3a4cab33bbf577a1257c08366dfd" ]
[ "experiments/table3.py" ]
[ "import os, sys, inspect\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\nfrom conformal import * \nfrom utils import *\nimport numpy as np\nfrom scipy.special import softmax\nfrom scipy.stats import median_absolute_deviation as mad\nimport torch\nimport torchvision\nimport torchvision.transforms as tf\nimport random\nimport torch.backends.cudnn as cudnn\nimport itertools\nfrom tqdm import tqdm\nimport pandas as pd\nimport pdb\n\ndef trial(model, logits, alpha, kreg, lamda, randomized, n_data_conf, n_data_val, bsz, naive_bool):\n logits_cal, logits_val = split2(logits, n_data_conf, n_data_val) # A new random split for every trial\n # Prepare the loaders\n loader_cal = torch.utils.data.DataLoader(logits_cal, batch_size = bsz, shuffle=False, pin_memory=True)\n loader_val = torch.utils.data.DataLoader(logits_val, batch_size = bsz, shuffle=False, pin_memory=True)\n # Conformalize the model\n conformal_model = ConformalModelLogits(model, loader_cal, alpha=alpha, kreg=kreg, lamda=lamda, randomized=randomized, allow_zero_sets=True, naive=naive_bool)\n # Collect results\n top1_avg, top5_avg, cvg_avg, sz_avg = validate(loader_val, conformal_model, print_bool=False)\n return top1_avg, top5_avg, cvg_avg, sz_avg\n\ndef experiment(modelname, datasetname, datasetpath, num_trials, alpha, kreg, lamda, randomized, n_data_conf, n_data_val, bsz, predictor):\n ### Experiment logic\n naive_bool = predictor == 'Naive'\n if predictor in ['Naive', 'APS']:\n lamda = 0 # No regularization.\n\n ### Data Loading\n logits = get_logits_dataset(modelname, datasetname, datasetpath)\n\n ### Instantiate and wrap model\n model = get_model(modelname)\n\n ### Perform experiment\n top1s = np.zeros((num_trials,))\n top5s = np.zeros((num_trials,))\n coverages = np.zeros((num_trials,))\n sizes = np.zeros((num_trials,))\n for i in tqdm(range(num_trials)):\n top1_avg, top5_avg, cvg_avg, sz_avg = trial(model, logits, alpha, kreg, lamda, randomized, n_data_conf, n_data_val, bsz, naive_bool)\n top1s[i] = top1_avg\n top5s[i] = top5_avg\n coverages[i] = cvg_avg\n sizes[i] = sz_avg\n print(f'\\n\\tTop1: {np.median(top1s[0:i+1]):.3f}, Top5: {np.median(top5s[0:i+1]):.3f}, Coverage: {np.median(coverages[0:i+1]):.3f}, Size: {np.median(sizes[0:i+1]):.3f}\\033[F', end='')\n print('')\n return np.median(top1s), np.median(top5s), np.median(coverages), np.median(sizes), mad(top1s), mad(top5s), mad(coverages), mad(sizes)\n\ndef _fix_randomness(seed):\n np.random.seed(seed=seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n random.seed(seed)\n\ndef _format_appendix_table(df):\n kregs = df.kreg.unique()\n lamdas = df[\"lambda\"].unique()\n num_kreg = len(kregs)\n num_lamda = len(lamdas)\n latex_table = '''\\\\begin{table}[t] \\n \n\\\\centering \\n\n\\\\tiny \\n\n\\\\begin{tabular}{l'''\n for i in range(num_kreg):\n latex_table += \"c\"\n\n latex_table += '''} \\n\n\\\\toprule\\n\n$k_{reg} | \\lambda$ & '''\n for i in range(num_lamda):\n latex_table += str(lamdas[i]) + ' '\n if i < (num_lamda - 1):\n latex_table += ' & '\n\n latex_table += \"\\\\\\\\\\n\"\n latex_table += \"\\\\midrule\\n\"\n\n for kreg in kregs:\n latex_table += str(kreg) + ' & '\n for i in range(num_lamda):\n latex_table += str(df[(df[\"lambda\"] == lamdas[i]) & (df[\"kreg\"] == kreg)][\"Size\"].item()) + ' '\n if i < (num_lamda - 1):\n latex_table += ' & '\n latex_table += \"\\\\\\\\\\n\"\n\n latex_table += \"\\\\bottomrule\\n\"\n latex_table += \"\\\\end{tabular}\\n\"\n latex_table += \"\\\\caption{Table caption.}\\n\"\n latex_table += \"\\\\label{table:parameters}\\n\"\n latex_table += \"\\\\end{table}\\n\"\n \n return latex_table\n\nif __name__ == \"__main__\":\n ### Fix randomness \n _fix_randomness(seed=0)\n\n ### Configure experiment\n modelnames = ['ResNet152']\n alphas = [0.10]\n kregs = [1, 2, 3, 4, 5, 6, 10, 20, 50, 100, 500]\n lamdas = [0, 0.0001, 0.001, 0.01, 0.02, 0.05, 0.2, 0.5, 0.7, 1.0]\n predictors = ['RAPS']\n params = list(itertools.product(modelnames, alphas, predictors,kregs, lamdas))\n m = len(params)\n datasetname = 'Imagenet'\n datasetpath = '/scratch/group/ilsvrc/val/'\n num_trials = 10\n randomized = True\n n_data_conf = 2000\n n_data_val = 2000\n bsz = 64\n cudnn.benchmark = True\n\n ### Perform the experiment\n df = pd.DataFrame(columns = [\"Model\",\"Predictor\",\"Top1\",\"Top5\",\"alpha\",\"kreg\",\"lambda\",\"Coverage\",\"Size\"])\n for i in range(m):\n _fix_randomness(seed=0)\n modelname, alpha, predictor, kreg, lamda = params[i]\n print(f'Model: {modelname} | Desired coverage: {1-alpha} | kreg: {kreg} | lambda: {lamda} ')\n\n out = experiment(modelname, datasetname, datasetpath, num_trials, params[i][1], kreg, lamda, randomized, n_data_conf, n_data_val, bsz, predictor) \n df = df.append({\"Model\": modelname,\n \"Predictor\": predictor,\n \"Top1\": np.round(out[0],3),\n \"Top5\": np.round(out[1],3),\n \"alpha\": alpha,\n \"kreg\": kreg,\n \"lambda\": lamda,\n \"Coverage\": np.round(out[2],3),\n \"Size\": np.round(out[3],3)}, ignore_index=True) \n\n ### Print the TeX table\n table = open(\"./outputs/appendix_parameter_table.tex\", 'w')\n table.write(_format_appendix_table(df))\n table.close()\n" ]
[ [ "torch.cuda.manual_seed", "numpy.random.seed", "torch.manual_seed", "numpy.median", "torch.utils.data.DataLoader", "pandas.DataFrame", "scipy.stats.median_absolute_deviation", "numpy.round", "numpy.zeros" ] ]
cesaraugustomt/sniper-using-yolov5
[ "7883acbd26dd017679478060c19566dadb3440a2" ]
[ "test.py" ]
[ "import argparse\nimport json\nimport os\nfrom pathlib import Path\nfrom threading import Thread\n\nimport numpy as np\nimport torch\nimport yaml\nfrom tqdm import tqdm\n\nfrom models.experimental import attempt_load\nfrom utils.datasets import create_dataloader\nfrom utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, check_requirements, \\\n box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, set_logging, increment_path, colorstr\nfrom utils.metrics import ap_per_class, ConfusionMatrix\nfrom utils.plots import plot_images, output_to_target, plot_study_txt\nfrom utils.torch_utils import select_device, time_synchronized\n\n\ndef test(data,\n weights=None,\n batch_size=32,\n imgsz=640,\n conf_thres=0.001,\n iou_thres=0.6, # for NMS\n save_json=False,\n single_cls=False,\n augment=False,\n verbose=False,\n model=None,\n dataloader=None,\n save_dir=Path(''), # for saving images\n save_txt=False, # for auto-labelling\n save_hybrid=False, # for hybrid auto-labelling\n save_conf=False, # save auto-label confidences\n plots=True,\n log_imgs=0, # number of logged images\n compute_loss=None):\n\n # Initialize/load model and set device\n training = model is not None\n if training: # called by train.py\n device = next(model.parameters()).device # get model device\n\n else: # called directly\n set_logging()\n device = select_device(opt.device, batch_size=batch_size)\n\n # Directories\n save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run\n (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir\n\n # Load model\n model = attempt_load(weights, map_location=device) # load FP32 model\n imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size\n\n # Multi-GPU disabled, incompatible with .half() https://github.com/ultralytics/yolov5/issues/99\n # if device.type != 'cpu' and torch.cuda.device_count() > 1:\n # model = nn.DataParallel(model)\n\n # Half\n half = device.type != 'cpu' # half precision only supported on CUDA\n if half:\n model.half()\n\n # Configure\n model.eval()\n is_coco = data.endswith('coco.yaml') # is COCO dataset\n with open(data) as f:\n data = yaml.load(f, Loader=yaml.SafeLoader) # model dict\n check_dataset(data) # check\n nc = 1 if single_cls else int(data['nc']) # number of classes\n iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for [email protected]:0.95\n niou = iouv.numel()\n\n # Logging\n log_imgs, wandb = min(log_imgs, 100), None # ceil\n try:\n import wandb # Weights & Biases\n except ImportError:\n log_imgs = 0\n\n # Dataloader\n if not training:\n img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img\n _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once\n path = data['test'] if opt.task == 'test' else data['val'] # path to val/test images\n dataloader = create_dataloader(path, imgsz, batch_size, model.stride.max(), opt, pad=0.5, rect=True,\n prefix=colorstr('test: ' if opt.task == 'test' else 'val: '))[0]\n\n seen = 0\n confusion_matrix = ConfusionMatrix(nc=nc)\n names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)}\n coco91class = coco80_to_coco91_class()\n s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', '[email protected]', '[email protected]:.95')\n p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.\n loss = torch.zeros(3, device=device)\n jdict, stats, ap, ap_class, wandb_images = [], [], [], [], []\n for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):\n img = img.to(device, non_blocking=True)\n img = img.half() if half else img.float() # uint8 to fp16/32\n img /= 255.0 # 0 - 255 to 0.0 - 1.0\n targets = targets.to(device)\n nb, _, height, width = img.shape # batch size, channels, height, width\n\n with torch.no_grad():\n # Run model\n t = time_synchronized()\n inf_out, train_out = model(img, augment=augment) # inference and training outputs\n t0 += time_synchronized() - t\n\n # Compute loss\n if compute_loss:\n loss += compute_loss([x.float() for x in train_out], targets)[1][:3] # box, obj, cls\n\n # Run NMS\n targets[:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels\n lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling\n t = time_synchronized()\n output = non_max_suppression(inf_out, conf_thres=conf_thres, iou_thres=iou_thres, labels=lb)\n t1 += time_synchronized() - t\n\n # Statistics per image\n for si, pred in enumerate(output):\n labels = targets[targets[:, 0] == si, 1:]\n nl = len(labels)\n tcls = labels[:, 0].tolist() if nl else [] # target class\n path = Path(paths[si])\n seen += 1\n\n if len(pred) == 0:\n if nl:\n stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))\n continue\n\n # Predictions\n predn = pred.clone()\n scale_coords(img[si].shape[1:], predn[:, :4], shapes[si][0], shapes[si][1]) # native-space pred\n\n # Append to text file\n if save_txt:\n gn = torch.tensor(shapes[si][0])[[1, 0, 1, 0]] # normalization gain whwh\n for *xyxy, conf, cls in predn.tolist():\n xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh\n line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format\n with open(save_dir / 'labels' / (path.stem + '.txt'), 'a') as f:\n f.write(('%g ' * len(line)).rstrip() % line + '\\n')\n\n # W&B logging\n if plots and len(wandb_images) < log_imgs:\n box_data = [{\"position\": {\"minX\": xyxy[0], \"minY\": xyxy[1], \"maxX\": xyxy[2], \"maxY\": xyxy[3]},\n \"class_id\": int(cls),\n \"box_caption\": \"%s %.3f\" % (names[cls], conf),\n \"scores\": {\"class_score\": conf},\n \"domain\": \"pixel\"} for *xyxy, conf, cls in pred.tolist()]\n boxes = {\"predictions\": {\"box_data\": box_data, \"class_labels\": names}} # inference-space\n wandb_images.append(wandb.Image(img[si], boxes=boxes, caption=path.name))\n\n # Append to pycocotools JSON dictionary\n if save_json:\n # [{\"image_id\": 42, \"category_id\": 18, \"bbox\": [258.15, 41.29, 348.26, 243.78], \"score\": 0.236}, ...\n image_id = int(path.stem) if path.stem.isnumeric() else path.stem\n box = xyxy2xywh(predn[:, :4]) # xywh\n box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner\n for p, b in zip(pred.tolist(), box.tolist()):\n jdict.append({'image_id': image_id,\n 'category_id': coco91class[int(p[5])] if is_coco else int(p[5]),\n 'bbox': [round(x, 3) for x in b],\n 'score': round(p[4], 5)})\n\n # Assign all predictions as incorrect\n correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)\n if nl:\n detected = [] # target indices\n tcls_tensor = labels[:, 0]\n\n # target boxes\n tbox = xywh2xyxy(labels[:, 1:5])\n scale_coords(img[si].shape[1:], tbox, shapes[si][0], shapes[si][1]) # native-space labels\n if plots:\n confusion_matrix.process_batch(pred, torch.cat((labels[:, 0:1], tbox), 1))\n\n # Per target class\n for cls in torch.unique(tcls_tensor):\n ti = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1) # prediction indices\n pi = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1) # target indices\n\n # Search for detections\n if pi.shape[0]:\n # Prediction to target ious\n ious, i = box_iou(predn[pi, :4], tbox[ti]).max(1) # best ious, indices\n\n # Append detections\n detected_set = set()\n for j in (ious > iouv[0]).nonzero(as_tuple=False):\n d = ti[i[j]] # detected target\n if d.item() not in detected_set:\n detected_set.add(d.item())\n detected.append(d)\n correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn\n if len(detected) == nl: # all targets already located in image\n break\n\n # Append statistics (correct, conf, pcls, tcls)\n stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))\n\n # Plot images\n if plots and batch_i < 3:\n f = save_dir / f'test_batch{batch_i}_labels.jpg' # labels\n Thread(target=plot_images, args=(img, targets, paths, f, names), daemon=True).start()\n f = save_dir / f'test_batch{batch_i}_pred.jpg' # predictions\n Thread(target=plot_images, args=(img, output_to_target(output), paths, f, names), daemon=True).start()\n\n # Compute statistics\n stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy\n if len(stats) and stats[0].any():\n p, r, ap, f1, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)\n p, r, ap50, ap = p[:, 0], r[:, 0], ap[:, 0], ap.mean(1) # [P, R, [email protected], [email protected]:0.95]\n mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()\n nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class\n else:\n nt = torch.zeros(1)\n\n # Print results\n pf = '%20s' + '%12.3g' * 6 # print format\n print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))\n\n # Print results per class\n if (verbose or (nc <= 20 and not training)) and nc > 1 and len(stats):\n for i, c in enumerate(ap_class):\n print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))\n\n # Print speeds\n t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple\n if not training:\n print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)\n\n # Plots\n if plots:\n confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))\n if wandb and wandb.run:\n wandb.log({\"Images\": wandb_images})\n wandb.log({\"Validation\": [wandb.Image(str(f), caption=f.name) for f in sorted(save_dir.glob('test*.jpg'))]})\n\n # Save JSON\n if save_json and len(jdict):\n w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights\n anno_json = '../coco/annotations/instances_val2017.json' # annotations json\n pred_json = str(save_dir / f\"{w}_predictions.json\") # predictions json\n print('\\nEvaluating pycocotools mAP... saving %s...' % pred_json)\n with open(pred_json, 'w') as f:\n json.dump(jdict, f)\n\n try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n from pycocotools.coco import COCO\n from pycocotools.cocoeval import COCOeval\n\n anno = COCO(anno_json) # init annotations api\n pred = anno.loadRes(pred_json) # init predictions api\n eval = COCOeval(anno, pred, 'bbox')\n if is_coco:\n eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate\n eval.evaluate()\n eval.accumulate()\n eval.summarize()\n map, map50 = eval.stats[:2] # update results ([email protected]:0.95, [email protected])\n except Exception as e:\n print(f'pycocotools unable to run: {e}')\n\n # Return results\n if not training:\n s = f\"\\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}\" if save_txt else ''\n print(f\"Results saved to {save_dir}{s}\")\n model.float() # for training\n maps = np.zeros(nc) + map\n for i, c in enumerate(ap_class):\n maps[c] = ap[i]\n return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(prog='test.py')\n parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')\n parser.add_argument('--data', type=str, default='data/coco128.yaml', help='*.data path')\n parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch')\n parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')\n parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')\n parser.add_argument('--iou-thres', type=float, default=0.6, help='IOU threshold for NMS')\n parser.add_argument('--task', default='val', help=\"'val', 'test', 'study'\")\n parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')\n parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')\n parser.add_argument('--augment', action='store_true', help='augmented inference')\n parser.add_argument('--verbose', action='store_true', help='report mAP by class')\n parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')\n parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')\n parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')\n parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')\n parser.add_argument('--project', default='runs/test', help='save to project/name')\n parser.add_argument('--name', default='exp', help='save to project/name')\n parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')\n opt = parser.parse_args()\n opt.save_json |= opt.data.endswith('coco.yaml')\n opt.data = check_file(opt.data) # check file\n print(opt)\n check_requirements()\n\n if opt.task in ['val', 'test']: # run normally\n test(opt.data,\n opt.weights,\n opt.batch_size,\n opt.img_size,\n opt.conf_thres,\n opt.iou_thres,\n opt.save_json,\n opt.single_cls,\n opt.augment,\n opt.verbose,\n save_txt=opt.save_txt | opt.save_hybrid,\n save_hybrid=opt.save_hybrid,\n save_conf=opt.save_conf,\n )\n\n elif opt.task == 'study': # run over a range of settings and save/plot\n for weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:\n f = 'study_%s_%s.txt' % (Path(opt.data).stem, Path(weights).stem) # filename to save to\n x = list(range(320, 800, 64)) # x axis\n y = [] # y axis\n for i in x: # img-size\n print('\\nRunning %s point %s...' % (f, i))\n r, _, t = test(opt.data, weights, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json,\n plots=False)\n y.append(r + t) # results and times\n np.savetxt(f, y, fmt='%10.4g') # save\n os.system('zip -r study.zip study_*.txt')\n plot_study_txt(f, x) # plot\n" ]
[ [ "torch.linspace", "torch.Tensor", "torch.zeros", "torch.cat", "torch.tensor", "numpy.concatenate", "torch.unique", "torch.no_grad", "numpy.savetxt", "numpy.zeros" ] ]
benmaier/networks2021-hons-softwaredemo
[ "f50112bb785123e4beed7077ef75283d72579a20" ]
[ "16_netwulf_epipack_sim.py" ]
[ "# 16\n# start a stochastic simulation on a netwulf-stylized network\n\nimport tacoma as tc\nfrom demo_utils import disp\nimport networkx as nx\nimport netwulf as nw\n\ndtu = tc.load_json_taco('~/.tacoma/dtu_1_weeks.taco')\n\n\ndtu_agg = tc.aggregated_network(dtu)\n\n\nlinks = []\n\nfor key, val in dtu_agg.items():\n links.append((key[0],key[1],val))\n\n\nnetwork, config, _ = nw.load(\"dtu_agg.json\")\n\nimport epipack as epk\nimport epipack.plottools as epl\nimport numpy as np\nimport matplotlib.pyplot as pl\n\ncomp = list(\"SEIAR\")\n\nlatent_period = 2 #d\nR0 = 3\ninfectious_period = 6 #d\np = 0.8\n\nI0 = 1e-4\n\nmodel = epk.StochasticEpiModel(comp,N=dtu.N,edge_weight_tuples=links)\n\nk = model.out_degree\n\nk0 = np.mean(k)\n\ninf_rate = R0 / infectious_period / k0\n\n\nmodel.set_link_transmission_processes([\n (\"I\", \"S\", inf_rate, \"I\", \"E\"),\n (\"A\", \"S\", inf_rate, \"A\", \"E\"),\n ])\n\nmodel.set_node_transition_processes([\n (\"E\", (1-p)/latent_period ,\"A\"),\n (\"E\", p/latent_period ,\"I\"),\n (\"I\", 1/infectious_period ,\"R\"),\n (\"A\", 1/infectious_period ,\"R\"),\n ])\n\n\nmodel.set_random_initial_conditions({\n 'S': dtu.N - 10,\n 'I': 10,\n })\n\nt, result = model.simulate(100)\n\nepl.plot(t, result)\npl.legend()\npl.show()\n\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.show", "numpy.mean" ] ]
ubiquity6/OldMVSNet
[ "27465945c52b8221860b623158a56a641dee5522" ]
[ "mvsnet/preprocess.py" ]
[ "#!/usr/bin/env python\n\"\"\"\nCopyright 2019, Yao Yao, HKUST.\nTraining preprocesses.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport os\nimport time\nimport glob\nimport random\nimport math\nimport re\nimport sys\nimport imageio\n\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nimport scipy.io\nimport urllib\nfrom tensorflow.python.lib.io import file_io\nFLAGS = tf.app.flags.FLAGS\n\ndef center_image(img):\n \"\"\" normalize image input \"\"\"\n img = img.astype(np.float32)\n var = np.var(img, axis=(0,1), keepdims=True)\n mean = np.mean(img, axis=(0,1), keepdims=True)\n return (img - mean) / (np.sqrt(var) + 0.00000001)\n\ndef scale_camera(cam, scale=1):\n \"\"\" resize input in order to produce sampled depth map \"\"\"\n new_cam = np.copy(cam)\n # focal: \n new_cam[1][0][0] = cam[1][0][0] * scale\n new_cam[1][1][1] = cam[1][1][1] * scale\n # principle point:\n new_cam[1][0][2] = cam[1][0][2] * scale\n new_cam[1][1][2] = cam[1][1][2] * scale\n return new_cam\n\ndef scale_mvs_camera(cams, scale=1):\n \"\"\" resize input in order to produce sampled depth map \"\"\"\n for view in range(FLAGS.view_num):\n cams[view] = scale_camera(cams[view], scale=scale)\n return cams\n\ndef scale_image(image, scale=1, interpolation='linear'):\n \"\"\" resize image using cv2 \"\"\"\n if interpolation == 'linear':\n return cv2.resize(image, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR)\n if interpolation == 'nearest':\n return cv2.resize(image, None, fx=scale, fy=scale, interpolation=cv2.INTER_NEAREST)\n\ndef scale_mvs_input(images, cams, depth_image=None, scale=1):\n \"\"\" resize input to fit into the memory \"\"\"\n for view in range(FLAGS.view_num):\n images[view] = scale_image(images[view], scale=scale)\n cams[view] = scale_camera(cams[view], scale=scale)\n\n if depth_image is None:\n return images, cams\n else:\n depth_image = scale_image(depth_image, scale=scale, interpolation='nearest')\n return images, cams, depth_image\n\ndef crop_mvs_input(images, cams, depth_image=None):\n \"\"\" resize images and cameras to fit the network (can be divided by base image size) \"\"\"\n\n # crop images and cameras\n for view in range(FLAGS.view_num):\n h, w = images[view].shape[0:2]\n new_h = h\n new_w = w\n if new_h > FLAGS.max_h:\n new_h = FLAGS.max_h\n else:\n new_h = int(math.ceil(h / FLAGS.base_image_size) * FLAGS.base_image_size)\n if new_w > FLAGS.max_w:\n new_w = FLAGS.max_w\n else:\n new_w = int(math.ceil(w / FLAGS.base_image_size) * FLAGS.base_image_size)\n start_h = int(math.ceil((h - new_h) / 2))\n start_w = int(math.ceil((w - new_w) / 2))\n finish_h = start_h + new_h\n finish_w = start_w + new_w\n images[view] = images[view][start_h:finish_h, start_w:finish_w]\n cams[view][1][0][2] = cams[view][1][0][2] - start_w\n cams[view][1][1][2] = cams[view][1][1][2] - start_h\n\n # crop depth image\n if not depth_image is None:\n depth_image = depth_image[start_h:finish_h, start_w:finish_w]\n return images, cams, depth_image\n else:\n return images, cams\n\ndef mask_depth_image(depth_image, min_depth, max_depth):\n \"\"\" mask out-of-range pixel to zero \"\"\"\n # print ('mask min max', min_depth, max_depth)\n ret, depth_image = cv2.threshold(depth_image, min_depth, 100000, cv2.THRESH_TOZERO)\n ret, depth_image = cv2.threshold(depth_image, max_depth, 100000, cv2.THRESH_TOZERO_INV)\n depth_image = np.expand_dims(depth_image, 2)\n return depth_image\n\ndef load_cam(file, interval_scale=1, max_d = None):\n \"\"\" read camera txt file \"\"\"\n cam = np.zeros((2, 4, 4))\n words = file.read().split()\n # read extrinsic\n for i in range(0, 4):\n for j in range(0, 4):\n extrinsic_index = 4 * i + j + 1\n cam[0][i][j] = words[extrinsic_index]\n\n # read intrinsic\n for i in range(0, 3):\n for j in range(0, 3):\n intrinsic_index = 3 * i + j + 18\n cam[1][i][j] = words[intrinsic_index]\n \n if len(words) == 29:\n cam[1][3][0] = words[27]\n cam[1][3][1] = float(words[28]) * interval_scale\n if max_d is None:\n cam[1][3][2] = FLAGS.max_d\n else:\n cam[1][3][2] = max_d\n cam[1][3][3] = cam[1][3][0] + cam[1][3][1] * cam[1][3][2]\n elif len(words) == 30:\n cam[1][3][0] = words[27]\n cam[1][3][1] = float(words[28]) * interval_scale\n cam[1][3][2] = words[29]\n cam[1][3][3] = cam[1][3][0] + cam[1][3][1] * cam[1][3][2]\n elif len(words) == 31:\n cam[1][3][0] = words[27]\n cam[1][3][1] = float(words[28]) * interval_scale\n cam[1][3][2] = words[29]\n cam[1][3][3] = words[30]\n else:\n cam[1][3][0] = 0\n cam[1][3][1] = 0\n cam[1][3][2] = 0\n cam[1][3][3] = 0\n return cam\n\ndef load_cam_from_path(path, interval_scale = 1.0, max_d = None):\n return load_cam(open(path), interval_scale, max_d)\n\ndef pose_string(cam):\n row_0 = cam[0,0,:]\n row_1 = cam[0,1,:]\n row_2 = cam[0,2,:]\n pose_string = ''\n pose_string += str(row_0[0]) + ' '\n pose_string += str(row_0[1])+ ' '\n pose_string += str(row_0[2])+ ' '\n pose_string += str(row_0[3]/1000)+ ' '\n pose_string += str(row_1[0])+ ' '\n pose_string += str(row_1[1])+ ' '\n pose_string += str(row_1[2])+ ' '\n pose_string += str(row_1[3]/1000)+ ' '\n pose_string += str(row_2[0])+ ' '\n pose_string += str(row_2[1])+ ' '\n pose_string += str(row_2[2])+ ' '\n pose_string += str(row_2[3]/1000)\n pose_string += '\\n'\n print(pose_string)\n return pose_string\n\n\ndef write_visualization_depth_map(image, file_path):\n file_path_scaled = file_path.replace('.png', '_scaled.png')\n # rescales the image so max distance is 6.5 meters, making contrast more visible\n image_scaled = np.clip(image*50, 0, 65535).astype(np.uint16)\n imageio.imsave(file_path_scaled, image_scaled)\n\ndef write_depth_map(file_path, image, visualization = False):\n # convert to int and clip to range of [0, 2^16 -1]\n image = np.clip(image, 0, 65535).astype(np.uint16)\n imageio.imsave(file_path, image)\n if visualization:\n write_visualization_depth_map(image, file_path)\n\n\n\n\ndef write_confidence_map(file_path, image):\n # we convert probabilities in range [0,1] to ints in range [0, 2^16-1]\n scale_factor = 65535\n image *= scale_factor\n image = np.clip(image, 0, 65535).astype(np.uint16)\n imageio.imsave(file_path, image)\n\ndef write_cam(file, cam):\n # f = open(file, \"w\")\n f = file_io.FileIO(file, \"w\")\n\n f.write('extrinsic\\n')\n for i in range(0, 4):\n for j in range(0, 4):\n f.write(str(cam[0][i][j]) + ' ')\n f.write('\\n')\n f.write('\\n')\n\n f.write('intrinsic\\n')\n for i in range(0, 3):\n for j in range(0, 3):\n f.write(str(cam[1][i][j]) + ' ')\n f.write('\\n')\n\n f.write('\\n' + str(cam[1][3][0]) + ' ' + str(cam[1][3][1]) + ' ' + str(cam[1][3][2]) + ' ' + str(cam[1][3][3]) + '\\n')\n\n f.close()\n\ndef load_pfm(file):\n color = None\n width = None\n height = None\n scale = None\n data_type = None\n header = str(file.readline()).rstrip()\n\n if header == 'PF':\n color = True\n elif header == 'Pf':\n color = False\n else:\n raise Exception('Not a PFM file.')\n dim_match = re.match(r'^(\\d+)\\s(\\d+)\\s$', file.readline())\n if dim_match:\n width, height = map(int, dim_match.groups())\n else:\n raise Exception('Malformed PFM header.')\n # scale = float(file.readline().rstrip())\n scale = float((file.readline()).rstrip())\n if scale < 0: # little-endian\n data_type = '<f'\n else:\n data_type = '>f' # big-endian\n data_string = file.read()\n data = np.fromstring(data_string, data_type)\n # data = np.fromfile(file, data_type)\n shape = (height, width, 3) if color else (height, width)\n data = np.reshape(data, shape)\n data = cv2.flip(data, 0)\n return data\n\ndef write_pfm(file, image, scale=1):\n file = file_io.FileIO(file, mode='wb')\n color = None\n\n if image.dtype.name != 'float32':\n raise Exception('Image dtype must be float32.')\n\n image = np.flipud(image) \n\n if len(image.shape) == 3 and image.shape[2] == 3: # color image\n color = True\n elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # greyscale\n color = False\n else:\n raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.')\n\n file.write('PF\\n' if color else 'Pf\\n')\n file.write('%d %d\\n' % (image.shape[1], image.shape[0]))\n\n endian = image.dtype.byteorder\n\n if endian == '<' or endian == '=' and sys.byteorder == 'little':\n scale = -scale\n\n file.write('%f\\n' % scale)\n\n image_string = image.tostring()\n file.write(image_string) \n\n file.close()\n\ndef gen_dtu_resized_path(dtu_data_folder, mode='training'):\n \"\"\" generate data paths for dtu dataset \"\"\"\n sample_list = []\n \n # parse camera pairs\n cluster_file_path = dtu_data_folder + '/Cameras/pair.txt'\n \n # cluster_list = open(cluster_file_path).read().split()\n cluster_list = file_io.FileIO(cluster_file_path, mode='r').read().split()\n\n # 3 sets\n training_set = [2, 6, 7, 8, 14, 16, 18, 19, 20, 22, 30, 31, 36, 39, 41, 42, 44,\n 45, 46, 47, 50, 51, 52, 53, 55, 57, 58, 60, 61, 63, 64, 65, 68, 69, 70, 71, 72,\n 74, 76, 83, 84, 85, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,\n 101, 102, 103, 104, 105, 107, 108, 109, 111, 112, 113, 115, 116, 119, 120,\n 121, 122, 123, 124, 125, 126, 127, 128]\n validation_set = [3, 5, 17, 21, 28, 35, 37, 38, 40, 43, 56, 59, 66, 67, 82, 86, 106, 117]\n\n data_set = []\n if mode == 'training':\n data_set = training_set\n elif mode == 'validation':\n data_set = validation_set\n\n # for each dataset\n for i in data_set:\n\n image_folder = os.path.join(dtu_data_folder, ('Rectified/scan%d_train' % i))\n cam_folder = os.path.join(dtu_data_folder, 'Cameras/train')\n depth_folder = os.path.join(dtu_data_folder, ('Depths/scan%d_train' % i))\n\n if mode == 'training':\n # for each lighting\n for j in range(0, 7):\n # for each reference image\n for p in range(0, int(cluster_list[0])):\n paths = []\n # ref image\n ref_index = int(cluster_list[22 * p + 1])\n ref_image_path = os.path.join(\n image_folder, ('rect_%03d_%d_r5000.png' % ((ref_index + 1), j)))\n ref_cam_path = os.path.join(cam_folder, ('%08d_cam.txt' % ref_index))\n paths.append(ref_image_path)\n paths.append(ref_cam_path)\n # view images\n for view in range(FLAGS.view_num - 1):\n view_index = int(cluster_list[22 * p + 2 * view + 3])\n view_image_path = os.path.join(\n image_folder, ('rect_%03d_%d_r5000.png' % ((view_index + 1), j)))\n view_cam_path = os.path.join(cam_folder, ('%08d_cam.txt' % view_index))\n paths.append(view_image_path)\n paths.append(view_cam_path)\n # depth path\n depth_image_path = os.path.join(depth_folder, ('depth_map_%04d.pfm' % ref_index))\n paths.append(depth_image_path)\n sample_list.append(paths)\n elif mode == 'validation':\n j = 3\n # for each reference image\n for p in range(0, int(cluster_list[0])):\n paths = []\n # ref image\n ref_index = int(cluster_list[22 * p + 1])\n ref_image_path = os.path.join(\n image_folder, ('rect_%03d_%d_r5000.png' % ((ref_index + 1), j)))\n ref_cam_path = os.path.join(cam_folder, ('%08d_cam.txt' % ref_index))\n paths.append(ref_image_path)\n paths.append(ref_cam_path)\n # view images\n for view in range(FLAGS.view_num - 1):\n view_index = int(cluster_list[22 * p + 2 * view + 3])\n view_image_path = os.path.join(\n image_folder, ('rect_%03d_%d_r5000.png' % ((view_index + 1), j)))\n view_cam_path = os.path.join(cam_folder, ('%08d_cam.txt' % view_index))\n paths.append(view_image_path)\n paths.append(view_cam_path)\n # depth path\n depth_image_path = os.path.join(depth_folder, ('depth_map_%04d.pfm' % ref_index))\n paths.append(depth_image_path)\n sample_list.append(paths)\n \n return sample_list\n\ndef gen_dtu_mvs_path(dtu_data_folder, mode='training'):\n \"\"\" generate data paths for dtu dataset \"\"\"\n sample_list = []\n \n # parse camera pairs\n cluster_file_path = dtu_data_folder + '/Cameras/pair.txt'\n cluster_list = open(cluster_file_path).read().split()\n\n # 3 sets\n training_set = [2, 6, 7, 8, 14, 16, 18, 19, 20, 22, 30, 31, 36, 39, 41, 42, 44,\n 45, 46, 47, 50, 51, 52, 53, 55, 57, 58, 60, 61, 63, 64, 65, 68, 69, 70, 71, 72,\n 74, 76, 83, 84, 85, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,\n 101, 102, 103, 104, 105, 107, 108, 109, 111, 112, 113, 115, 116, 119, 120,\n 121, 122, 123, 124, 125, 126, 127, 128]\n validation_set = [3, 5, 17, 21, 28, 35, 37, 38, 40, 43, 56, 59, 66, 67, 82, 86, 106, 117]\n evaluation_set = [1, 4, 9, 10, 11, 12, 13, 15, 23, 24, 29, 32, 33, 34, 48, 49, 62, 75, 77, \n 110, 114, 118]\n\n # for each dataset\n data_set = []\n if mode == 'training':\n data_set = training_set\n elif mode == 'validation':\n data_set = validation_set\n elif mode == 'evaluation':\n data_set = evaluation_set\n\n # for each dataset\n for i in data_set:\n\n image_folder = os.path.join(dtu_data_folder, ('Rectified/scan%d' % i))\n cam_folder = os.path.join(dtu_data_folder, 'Cameras')\n depth_folder = os.path.join(dtu_data_folder, ('Depths/scan%d' % i))\n\n if mode == 'training':\n # for each lighting\n for j in range(0, 7):\n # for each reference image\n for p in range(0, int(cluster_list[0])):\n paths = []\n # ref image\n ref_index = int(cluster_list[22 * p + 1])\n ref_image_path = os.path.join(\n image_folder, ('rect_%03d_%d_r5000.png' % ((ref_index + 1), j)))\n ref_cam_path = os.path.join(cam_folder, ('%08d_cam.txt' % ref_index))\n paths.append(ref_image_path)\n paths.append(ref_cam_path)\n # view images\n for view in range(FLAGS.view_num - 1):\n view_index = int(cluster_list[22 * p + 2 * view + 3])\n view_image_path = os.path.join(\n image_folder, ('rect_%03d_%d_r5000.png' % ((view_index + 1), j)))\n view_cam_path = os.path.join(cam_folder, ('%08d_cam.txt' % view_index))\n paths.append(view_image_path)\n paths.append(view_cam_path)\n # depth path\n depth_image_path = os.path.join(depth_folder, ('depth_map_%04d.pfm' % ref_index))\n paths.append(depth_image_path)\n sample_list.append(paths)\n else:\n # for each reference image\n j = 5\n for p in range(0, int(cluster_list[0])):\n paths = []\n # ref image\n ref_index = int(cluster_list[22 * p + 1])\n ref_image_path = os.path.join(\n image_folder, ('rect_%03d_%d_r5000.png' % ((ref_index + 1), j)))\n ref_cam_path = os.path.join(cam_folder, ('%08d_cam.txt' % ref_index))\n paths.append(ref_image_path)\n paths.append(ref_cam_path)\n # view images\n for view in range(FLAGS.view_num - 1):\n view_index = int(cluster_list[22 * p + 2 * view + 3])\n view_image_path = os.path.join(\n image_folder, ('rect_%03d_%d_r5000.png' % ((view_index + 1), j)))\n view_cam_path = os.path.join(cam_folder, ('%08d_cam.txt' % view_index))\n paths.append(view_image_path)\n paths.append(view_cam_path)\n # depth path\n depth_image_path = os.path.join(depth_folder, ('depth_map_%04d.pfm' % ref_index))\n paths.append(depth_image_path)\n sample_list.append(paths)\n \n return sample_list\n\n\n\ndef gen_data(data_root, val_ratio = 0.1):\n \"\"\" The data_root directory should contain multiple sessions, which are then parsed into\n the data structure that the train data generator expects \"\"\"\n session_list = os.listdir(data_root)\n \n\n\n\n\ndef gen_mvs_list(mode='training'):\n \"\"\"output paths in a list: [[I1_path1, C1_path, I2_path, C2_path, ...(, D1_path)], [...], ...]\"\"\"\n sample_list = []\n if FLAGS.train_dtu:\n dtu_sample_list = gen_dtu_mvs_path(FLAGS.dtu_data_root, mode=mode)\n sample_list = sample_list + dtu_sample_list\n return sample_list\n\n# for testing\ndef gen_pipeline_mvs_list(dense_folder):\n \"\"\" mvs input path list \"\"\"\n image_folder = os.path.join(dense_folder, 'images')\n cam_folder = os.path.join(dense_folder, 'cams')\n cluster_list_path = os.path.join(dense_folder, 'pair.txt')\n cluster_list = open(cluster_list_path).read().split()\n\n # for each dataset\n mvs_list = []\n pos = 1\n for i in range(int(cluster_list[0])):\n paths = []\n # ref image\n ref_index = int(cluster_list[pos])\n pos += 1\n ref_image_path = os.path.join(image_folder, ('%08d.jpg' % ref_index))\n ref_cam_path = os.path.join(cam_folder, ('%08d_cam.txt' % ref_index))\n paths.append(ref_image_path)\n paths.append(ref_cam_path)\n # view images\n all_view_num = int(cluster_list[pos])\n pos += 1\n check_view_num = min(FLAGS.view_num - 1, all_view_num)\n for view in range(check_view_num):\n view_index = int(cluster_list[pos + 2 * view])\n view_image_path = os.path.join(image_folder, ('%08d.jpg' % view_index))\n view_cam_path = os.path.join(cam_folder, ('%08d_cam.txt' % view_index))\n paths.append(view_image_path)\n paths.append(view_cam_path)\n pos += 2 * all_view_num\n # depth path\n mvs_list.append(paths)\n return mvs_list\n" ]
[ [ "numpy.expand_dims", "numpy.sqrt", "numpy.clip", "numpy.reshape", "tensorflow.python.lib.io.file_io.FileIO", "numpy.flipud", "numpy.copy", "numpy.fromstring", "numpy.mean", "numpy.var", "numpy.zeros" ] ]
vanvalenlab/kiosk-redis-consumer
[ "0f0a76664b8b500abfcd5b8c0bdb4348eea0e799" ]
[ "redis_consumer/consumers/base_consumer_test.py" ]
[ "# Copyright 2016-2021 The Van Valen Lab at the California Institute of\n# Technology (Caltech), with support from the Paul Allen Family Foundation,\n# Google, & National Institutes of Health (NIH) under Grant U24CA224309-01.\n# All rights reserved.\n#\n# Licensed under a modified 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.github.com/vanvalenlab/kiosk-redis-consumer/LICENSE\n#\n# The Work provided may be used for non-commercial academic purposes only.\n# For any other use of the Work, including commercial use, please contact:\n# [email protected]\n#\n# Neither the name of Caltech nor the names of its contributors may be used\n# to endorse or promote products derived from this software without specific\n# prior written permission.\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 base consumers\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport os\nimport random\nimport time\n\nimport numpy as np\n\nimport pytest\n\nfrom redis_consumer import consumers\nfrom redis_consumer.grpc_clients import GrpcModelWrapper\nfrom redis_consumer import settings\n\nfrom redis_consumer.testing_utils import _get_image\nfrom redis_consumer.testing_utils import Bunch\nfrom redis_consumer.testing_utils import DummyStorage\nfrom redis_consumer.testing_utils import redis_client # pylint: disable=unused-import\nfrom redis_consumer.testing_utils import make_model_metadata_of_size\n\n\nclass TestConsumer(object):\n # pylint: disable=R0201,W0621\n def test_get_redis_hash(self, mocker, redis_client):\n mocker.patch.object(settings, 'EMPTY_QUEUE_TIMEOUT', 0.01)\n queue = 'q'\n consumer = consumers.Consumer(redis_client, None, queue)\n\n # test emtpy queue\n assert consumer.get_redis_hash() is None\n\n # test that invalid items are not processed and are removed.\n item = 'item to process'\n redis_client.lpush(queue, item)\n # is_valid_hash returns True by default\n assert consumer.get_redis_hash() == item\n assert redis_client.llen(consumer.processing_queue) == 1\n assert redis_client.lpop(consumer.processing_queue) == item\n # queue should be empty, get None again\n assert consumer.get_redis_hash() is None\n\n # test invalid hash is failed and removed from queue\n mocker.patch.object(consumer, 'is_valid_hash', return_value=False)\n redis_client.lpush(queue, 'invalid')\n assert consumer.get_redis_hash() is None # invalid hash, returns None\n # invalid has was removed from the processing queue\n assert redis_client.llen(consumer.processing_queue) == 0\n # invalid hash was not returend to the work queue\n assert redis_client.llen(consumer.queue) == 0\n\n # test llen returns 1 but item is gone by the time the pop happens\n mocker.patch.object(redis_client, 'llen', lambda x: 1)\n assert consumer.get_redis_hash() is None\n\n def test_purge_processing_queue(self, redis_client):\n queue = 'q'\n keys = ['abc', 'def', 'xyz']\n consumer = consumers.Consumer(redis_client, None, queue)\n # set keys in processing queue\n for key in keys:\n redis_client.lpush(consumer.processing_queue, key)\n\n consumer.purge_processing_queue()\n\n assert redis_client.llen(consumer.processing_queue) == 0\n assert redis_client.llen(consumer.queue) == len(keys)\n\n def test_update_key(self, redis_client):\n consumer = consumers.Consumer(redis_client, None, 'q')\n key = 'redis-hash'\n status = 'updated_status'\n new_value = 'some value'\n consumer.update_key(key, {\n 'status': status,\n 'new_field': new_value\n })\n redis_values = redis_client.hgetall(key)\n assert redis_values.get('status') == status\n assert redis_values.get('new_field') == new_value\n\n with pytest.raises(ValueError):\n consumer.update_key('redis-hash', 'data')\n\n def test_handle_error(self, redis_client):\n consumer = consumers.Consumer(redis_client, None, 'q')\n err = Exception('test exception')\n key = 'redis-hash'\n consumer._handle_error(err, key)\n\n redis_values = redis_client.hgetall(key)\n assert isinstance(redis_values, dict)\n assert 'status' in redis_values and 'reason' in redis_values\n assert redis_values.get('status') == 'failed'\n\n def test__put_back_hash(self, redis_client):\n queue = 'q'\n\n # test emtpy queue\n consumer = consumers.Consumer(redis_client, None, queue)\n consumer._put_back_hash('DNE') # should be None, shows warning\n\n # put back the proper item\n item = 'redis_hash1'\n redis_client.lpush(consumer.processing_queue, item)\n consumer = consumers.Consumer(redis_client, None, queue)\n consumer._put_back_hash(item)\n assert redis_client.llen(consumer.processing_queue) == 0\n assert redis_client.llen(consumer.queue) == 1\n assert redis_client.lpop(consumer.queue) == item\n\n # put back the wrong item\n other = 'otherhash'\n redis_client.lpush(consumer.processing_queue, other, item)\n consumer = consumers.Consumer(redis_client, None, queue)\n consumer._put_back_hash(item)\n assert redis_client.llen(consumer.processing_queue) == 0\n assert redis_client.llen(consumer.queue) == 2\n assert redis_client.lpop(consumer.queue) == item\n assert redis_client.lpop(consumer.queue) == other\n\n def test_consume(self, mocker, redis_client):\n mocker.patch.object(settings, 'EMPTY_QUEUE_TIMEOUT', 0)\n queue = 'q'\n keys = [str(x) for x in range(1, 10)]\n err = OSError('thrown on purpose')\n i = 0\n\n consumer = consumers.Consumer(redis_client, DummyStorage(), queue)\n\n def throw_error(*_, **__):\n raise err\n\n def finish(*_, **__):\n return consumer.final_status\n\n def fail(*_, **__):\n return consumer.failed_status\n\n def in_progress(*_, **__):\n return 'another status'\n\n # empty redis queue\n spy = mocker.spy(time, 'sleep')\n assert redis_client.llen(consumer.queue) == 0\n consumer.consume()\n spy.assert_called_once_with(settings.EMPTY_QUEUE_TIMEOUT)\n\n # OK now let's fill the queue\n redis_client.lpush(consumer.queue, *keys)\n\n # test that _consume is called on each hash\n mocker.patch.object(consumer, '_consume', finish)\n spy = mocker.spy(consumer, '_consume')\n consumer.consume()\n spy.assert_called_once_with(keys[i])\n i += 1\n\n # error inside _consume calls _handle_error\n mocker.patch.object(consumer, '_consume', throw_error)\n spy = mocker.spy(consumer, '_handle_error')\n consumer.consume()\n spy.assert_called_once_with(err, keys[i])\n i += 1\n\n # status is in progress calls sleep\n mocker.patch.object(consumer, '_consume', in_progress)\n spy = mocker.spy(consumer, '_put_back_hash')\n consumer.consume()\n spy.assert_called_with(keys[i])\n i += 1\n\n # failed and done statuses call lrem\n spy = mocker.spy(redis_client, 'lrem')\n for status in (finish, fail):\n mocker.patch.object(consumer, '_consume', status)\n consumer.consume()\n spy.assert_called_with(consumer.processing_queue, 1, keys[i])\n i += 1\n\n def test__consume(self):\n with np.testing.assert_raises(NotImplementedError):\n consumer = consumers.Consumer(None, None, 'q')\n consumer._consume('predict:new:hash.tiff')\n\n\nclass TestTensorFlowServingConsumer(object):\n # pylint: disable=R0201,W0613,W0621\n\n def test_is_valid_hash(self, mocker, redis_client):\n storage = DummyStorage()\n mocker.patch.object(redis_client, 'hget', lambda x, y: x.split(':')[-1])\n\n consumer = consumers.TensorFlowServingConsumer(redis_client, storage, 'predict')\n\n assert consumer.is_valid_hash(None) is False\n assert consumer.is_valid_hash('file.ZIp') is False\n assert consumer.is_valid_hash('predict:1234567890:file.ZIp') is False\n assert consumer.is_valid_hash('track:123456789:file.zip') is False\n assert consumer.is_valid_hash('predict:123456789:file.zip') is False\n assert consumer.is_valid_hash('predict:1234567890:file.tiff') is True\n assert consumer.is_valid_hash('predict:1234567890:file.png') is True\n\n def test_download_image(self, redis_client):\n storage = DummyStorage()\n consumer = consumers.TensorFlowServingConsumer(redis_client, storage, 'q')\n\n image = consumer.download_image('test.tif')\n assert isinstance(image, np.ndarray)\n assert not os.path.exists('test.tif')\n\n def test_detect_dimension_order(self, mocker, redis_client):\n storage = DummyStorage()\n consumer = consumers.TensorFlowServingConsumer(redis_client, storage, 'q')\n\n model_input_shape = (-1, 32, 32, 1)\n\n mocked_metadata = make_model_metadata_of_size(model_input_shape)\n mocker.patch.object(consumer, 'get_model_metadata', mocked_metadata)\n\n input_pairs = [\n ((1, 32, 32, 1), 'YXC'), # channels last\n ((1, 1, 32, 32), 'CYX'), # channels first\n ]\n\n for shape, expected_dim_order in input_pairs:\n # check channels last\n img = np.ones(shape)\n dim_order = consumer.detect_dimension_order(img, 'model', '1')\n np.testing.assert_array_equal(dim_order, expected_dim_order)\n\n # Test again for 3D models\n model_input_shape = (-1, 5, 32, 32, 1)\n\n mocked_metadata = make_model_metadata_of_size(model_input_shape)\n mocker.patch.object(consumer, 'get_model_metadata', mocked_metadata)\n\n input_pairs = [\n ((1, 10, 32, 32, 1), 'ZYXC'), # channels last\n ((1, 1, 10, 32, 32), 'CZYX'), # channels first\n ]\n\n for shape, expected_dim_order in input_pairs:\n # check channels last\n img = np.ones(shape)\n dim_order = consumer.detect_dimension_order(img, 'model', '1')\n np.testing.assert_array_equal(dim_order, expected_dim_order)\n\n def test_validate_model_input(self, mocker, redis_client):\n storage = DummyStorage()\n consumer = consumers.TensorFlowServingConsumer(redis_client, storage, 'q')\n\n model_input_shape = (-1, 32, 32, 1)\n\n mocked_metadata = make_model_metadata_of_size(model_input_shape)\n mocker.patch.object(consumer, 'get_model_metadata', mocked_metadata)\n\n # test valid channels last shapes\n valid_input_shapes = [\n (1, 32, 32, 1), # exact same shape\n (1, 64, 64, 1), # bigger\n (1, 16, 16, 1), # smaller\n (1, 33, 31, 1), # mixed\n ]\n for shape in valid_input_shapes:\n # check channels last\n img = np.ones(shape)\n valid_img = consumer.validate_model_input(img, 'model', '1')\n np.testing.assert_array_equal(img, valid_img)\n\n # should also work for channels first\n img = np.rollaxis(img, -1, 1)\n valid_img = consumer.validate_model_input(img, 'model', '1')\n expected_img = np.rollaxis(img, 0, img.ndim)\n np.testing.assert_array_equal(expected_img, valid_img)\n\n # test invalid shapes\n invalid_input_shapes = [\n (32, 32, 1), # no batch dimension\n (1, 32, 1), # rank too small\n (1, 32, 32, 32, 1), # rank too large\n (1, 32, 32, 2), # wrong channels\n (1, 16, 64, 2), # wrong channels with mixed shape\n (1, 32, settings.MAX_IMAGE_WIDTH + 1, 1), # width too large\n (1, settings.MAX_IMAGE_HEIGHT + 1, 32, 1), # height too large\n ]\n for shape in invalid_input_shapes:\n img = np.ones(shape)\n with pytest.raises(ValueError):\n consumer.validate_model_input(img, 'model', '1')\n\n # test multiple inputs/metadata\n count = 3\n model_input_shape = [(-1, 32, 32, 1)] * count\n mocked_metadata = make_model_metadata_of_size(model_input_shape)\n mocker.patch.object(consumer, 'get_model_metadata', mocked_metadata)\n image = [np.ones(s) for s in valid_input_shapes[:count]]\n valid_img = consumer.validate_model_input(image, 'model', '1')\n # each image should be validated\n for i, j in zip(image, valid_img):\n np.testing.assert_array_equal(i, j)\n\n # metadata and image counts do not match\n for c in [count + 1, count - 1]:\n with pytest.raises(ValueError):\n image = [np.ones(s) for s in valid_input_shapes[:c]]\n consumer.validate_model_input(image, 'model', '1')\n\n # correct number of inputs, but one invalid entry\n with pytest.raises(ValueError):\n image = [np.ones(s) for s in valid_input_shapes[:count]]\n # set a random entry to be invalid\n i = random.randint(0, count - 1)\n image[i] = np.ones(random.choice(invalid_input_shapes))\n consumer.validate_model_input(image, 'model', '1')\n\n # Test optional channels parameter\n model_input_shape = (-1, 32, 32, 2)\n\n mocked_metadata = make_model_metadata_of_size(model_input_shape)\n mocker.patch.object(consumer, 'get_model_metadata', mocked_metadata)\n\n valid_channels = [[0, 1], [1, 0], [3, 2]]\n # extra channels in the image (png)\n image = np.ones((1, 32, 32, 4))\n for c in valid_channels:\n consumer.validate_model_input(image, 'model', '1', channels=c)\n\n # test too few and too many channels\n invalid_channels = [\n [3], # too few channels\n list(range(image.shape[-1] + 1)), # too many channels\n [0, 100], # channel out of range\n ]\n for c in invalid_channels:\n with pytest.raises(ValueError):\n consumer.validate_model_input(image, 'model', '1', channels=c)\n\n def test__get_predict_client(self, redis_client):\n stg = DummyStorage()\n consumer = consumers.TensorFlowServingConsumer(redis_client, stg, 'q')\n\n with pytest.raises(ValueError):\n consumer._get_predict_client('model_name', 'model_version')\n\n consumer._get_predict_client('model_name', 1)\n\n def test_get_model_metadata(self, mocker, redis_client):\n model_shape = (-1, 216, 216, 1)\n model_dtype = 'DT_FLOAT'\n model_input_name = 'input_1'\n model_version = 3\n model_name = 'good model'\n model = '{}:{}'.format(model_name, model_version)\n\n # load model metadata into client\n cached_metadata = {\n model_input_name: {\n 'dtype': model_dtype,\n 'tensorShape': {\n 'dim': [\n {'size': str(x)}\n for x in model_shape\n ]\n }\n }\n }\n redis_client.hset(model, 'metadata', json.dumps(cached_metadata))\n\n def _get_predict_client(model_name, model_version):\n return Bunch(get_model_metadata=lambda: {\n 'metadata': {\n 'signature_def': {\n 'signatureDef': {\n 'serving_default': {\n 'inputs': cached_metadata\n }\n }\n }\n }\n })\n\n def _get_predict_client_multi(model_name, model_version):\n newdata = cached_metadata.copy()\n newdata['input_2'] = newdata[model_input_name]\n return Bunch(get_model_metadata=lambda: {\n 'metadata': {\n 'signature_def': {\n 'signatureDef': {\n 'serving_default': {\n 'inputs': newdata\n }\n }\n }\n }\n })\n\n def _get_bad_predict_client(model_name, model_version):\n return Bunch(get_model_metadata=dict)\n\n stg = DummyStorage()\n consumer = consumers.TensorFlowServingConsumer(redis_client, stg, 'q')\n\n for client in (_get_predict_client, _get_predict_client_multi):\n mocker.patch.object(consumer, '_get_predict_client', client)\n\n # test cached input\n metadata = consumer.get_model_metadata(model_name, model_version)\n for m in metadata:\n assert m['in_tensor_dtype'] == model_dtype\n assert m['in_tensor_name'] == model_input_name\n assert m['in_tensor_shape'] == ','.join(str(x) for x in\n model_shape)\n\n # test stale cache\n metadata = consumer.get_model_metadata('another model', 0)\n for m in metadata:\n assert m['in_tensor_dtype'] == model_dtype\n assert m['in_tensor_name'] == model_input_name\n assert m['in_tensor_shape'] == ','.join(str(x) for x in\n model_shape)\n\n with pytest.raises(KeyError):\n mocker.patch.object(consumer, '_get_predict_client',\n _get_bad_predict_client)\n consumer.get_model_metadata('model', 1)\n\n def test_get_image_scale(self, mocker, redis_client):\n stg = DummyStorage()\n consumer = consumers.TensorFlowServingConsumer(redis_client, stg, 'q')\n image = _get_image(256, 256, 1)\n\n # test no scale provided\n expected = 2\n mocker.patch.object(consumer, 'detect_scale', lambda *x: expected)\n scale = consumer.get_image_scale(None, image, 'some hash')\n assert scale == expected\n\n # test scale provided\n expected = 1.2\n scale = consumer.get_image_scale(expected, image, 'some hash')\n assert scale == expected\n\n # test scale provided is too large\n with pytest.raises(ValueError):\n scale = settings.MAX_SCALE + 0.1\n consumer.get_image_scale(scale, image, 'some hash')\n\n # test scale provided is too small\n with pytest.raises(ValueError):\n scale = settings.MIN_SCALE - 0.1\n consumer.get_image_scale(scale, image, 'some hash')\n\n def test_get_grpc_app(self, mocker, redis_client):\n stg = DummyStorage()\n consumer = consumers.TensorFlowServingConsumer(redis_client, stg, 'q')\n\n get_metadata = make_model_metadata_of_size()\n get_mock_client = lambda *x: Bunch(predict=lambda *x: None)\n mocker.patch.object(consumer, 'get_model_metadata', get_metadata)\n mocker.patch.object(consumer, '_get_predict_client', get_mock_client)\n\n app = consumer.get_grpc_app('model:0', lambda x: x)\n\n assert isinstance(app, GrpcModelWrapper)\n\n def test_detect_scale(self, mocker, redis_client):\n # pylint: disable=W0613\n shape = (1, 256, 256, 1)\n consumer = consumers.TensorFlowServingConsumer(redis_client, None, 'q')\n\n image = _get_image(shape[1] * 2, shape[2] * 2, shape[3])\n\n expected_scale = random.uniform(0.5, 1.5)\n # model_mpp = random.uniform(0.5, 1.5)\n\n mock_app = Bunch(\n predict=lambda *x, **y: expected_scale,\n # model_mpp=model_mpp,\n model=Bunch(get_batch_size=lambda *x: 1))\n\n mocker.patch.object(consumer, 'get_grpc_app', lambda *x: mock_app)\n\n mocker.patch.object(settings, 'SCALE_DETECT_ENABLED', False)\n scale = consumer.detect_scale(image)\n assert scale == 1 # model_mpp\n\n mocker.patch.object(settings, 'SCALE_DETECT_ENABLED', True)\n scale = consumer.detect_scale(image)\n assert scale == expected_scale # * model_mpp\n\n\nclass TestZipFileConsumer(object):\n # pylint: disable=R0201,W0613,W0621\n def test_is_valid_hash(self, mocker, redis_client):\n consumer = consumers.ZipFileConsumer(\n redis_client, DummyStorage(), 'predict')\n\n def get_file_from_hash(redis_hash, _):\n return redis_hash.split(':')[-1]\n\n mocker.patch.object(redis_client, 'hget', get_file_from_hash)\n\n assert consumer.is_valid_hash(None) is False\n assert consumer.is_valid_hash('file.ZIp') is True\n assert consumer.is_valid_hash('predict:1234567890:file.ZIp') is True\n assert consumer.is_valid_hash('track:123456789:file.zip') is True\n assert consumer.is_valid_hash('predict:123456789:file.zip') is True\n assert consumer.is_valid_hash('predict:1234567890:file.tiff') is False\n assert consumer.is_valid_hash('predict:1234567890:file.png') is False\n\n def test__upload_archived_images(self, mocker, redis_client):\n N = 3\n storage = DummyStorage(num=N)\n consumer = consumers.ZipFileConsumer(redis_client, storage, 'predict')\n # mocker.patch.object(consumer.storage, 'download')\n hvalues = {'input_file_name': 'test.zip', 'children': 'none'}\n redis_hash = 'predict:redis_hash:f.zip'\n hsh = consumer._upload_archived_images(hvalues, redis_hash)\n assert len(hsh) == N\n\n def test__upload_finished_children(self, mocker, redis_client):\n finished_children = ['predict:1.tiff', 'predict:2.zip', '']\n N = 3\n storage = DummyStorage(num=N)\n consumer = consumers.ZipFileConsumer(redis_client, storage, 'predict')\n mocker.patch.object(consumer, '_get_output_file_name', lambda x: x)\n\n path, url = consumer._upload_finished_children(\n finished_children, 'predict:redis_hash:f.zip')\n assert path and url\n\n def test__get_output_file_name(self, mocker, redis_client):\n # TODO: bad coverage\n mocker.patch.object(settings, 'GRPC_BACKOFF', 0)\n storage = DummyStorage()\n queue = 'q'\n\n consumer = consumers.ZipFileConsumer(redis_client, storage, queue)\n\n # happy path\n key = 'some key'\n expected = 'output.zip'\n redis_client.hset(key, 'output_file_name', expected)\n assert consumer._get_output_file_name(key) == expected\n\n # handling missing output file\n key = 'key without output file'\n spy = mocker.spy(redis_client, 'ttl')\n\n # add key without output file but before it is expired\n redis_client.hset(key, 'some field', 'some value')\n with pytest.raises(ValueError):\n consumer._get_output_file_name(key)\n assert spy.spy_return == -1\n\n # expire key\n redis_client.expire(key, 10) # TTL should be -1\n with pytest.raises(ValueError):\n consumer._get_output_file_name(key)\n assert spy.spy_return == 10\n\n # key does not exist\n with pytest.raises(ValueError):\n consumer._get_output_file_name('randomkey') # TTL should be -2\n assert spy.spy_return == -2\n\n def test__parse_failures(self, mocker, redis_client):\n N = 3\n storage = DummyStorage(num=N)\n\n keys = [str(x) for x in range(4)]\n consumer = consumers.ZipFileConsumer(redis_client, storage, 'predict')\n for key in keys:\n redis_client.lpush(consumer.queue, key)\n redis_client.hset(key, 'reason', 'reason{}'.format(key))\n\n spy = mocker.spy(redis_client, 'hget')\n parsed = consumer._parse_failures(keys)\n spy.assert_called_with(keys[-1], 'reason')\n for key in keys:\n assert '{0}=reason{0}'.format(key) in parsed\n\n # no failures\n failed_children = ['']\n parsed = consumer._parse_failures(failed_children)\n assert parsed == ''\n\n def test__cleanup(self, mocker, redis_client):\n N = 3\n queue = 'predict'\n done = [str(i) for i in range(N)]\n failed = [str(i) for i in range(N + 1, N * 2)]\n storage = DummyStorage(num=N)\n consumer = consumers.ZipFileConsumer(redis_client, storage, queue)\n\n redis_hash = 'some job hash'\n\n mocker.patch.object(consumer, '_upload_finished_children',\n lambda *x: ('a', 'b'))\n\n for item in done:\n redis_client.hset(item, 'total_time', 1) # summary field\n for item in failed:\n redis_client.hset(item, 'reason', 1) # summary field\n\n children = done + failed\n\n consumer._cleanup(redis_hash, children, done, failed)\n\n assert redis_client.hget(redis_hash, 'total_jobs') == str(len(children))\n for key in children:\n assert redis_client.ttl(key) > 0 # all keys are expired\n\n def test__consume(self, mocker, redis_client):\n N = 3\n storage = DummyStorage(num=N)\n children = list('abcdefg')\n queue = 'q'\n test_hash = 0\n consumer = consumers.ZipFileConsumer(redis_client, storage, queue)\n\n # test finished statuses are returned\n for status in (consumer.failed_status, consumer.final_status, 'weird'):\n test_hash += 1\n redis_client.hset(test_hash, 'status', status)\n result = consumer._consume(test_hash)\n assert result == status\n\n # test `status` = \"new\"\n dummy = lambda *x: children\n mocker.patch.object(consumer, '_cleanup', dummy)\n mocker.patch.object(consumer, '_upload_archived_images', dummy)\n mocker.patch.object(consumer, '_upload_finished_children', dummy)\n\n test_hash += 1\n redis_client.hset(test_hash, 'status', 'new')\n result = consumer._consume(test_hash)\n assert result == 'waiting'\n assert redis_client.hget(test_hash, 'children') == ','.join(children)\n\n # test `status` = \"waiting\"\n status = 'waiting'\n test_hash += 1\n children = ['done', 'failed', 'waiting', 'move-to-done']\n child_statuses = ['done', 'failed', 'waiting', 'done']\n data = {'status': status, 'children': ','.join(children)}\n redis_client.hmset(test_hash, data)\n for child, child_status in zip(children, child_statuses):\n redis_client.hset(child, 'status', child_status)\n\n result = consumer._consume(test_hash)\n assert result == status\n hvals = redis_client.hgetall(test_hash)\n done_children = set(hvals.get('children:done', '').split(','))\n assert done_children == {'done', 'move-to-done'}\n assert hvals.get('children:failed') == 'failed'\n\n # set the \"waiting\" child to \"done\"\n redis_client.hset('waiting', 'status', consumer.final_status)\n result = consumer._consume(test_hash)\n assert result == consumer.final_status\n hvals = redis_client.hgetall(test_hash)\n done_children = set(hvals.get('children:done', '').split(','))\n assert done_children == {'done', 'move-to-done', 'waiting'}\n assert hvals.get('children:failed') == 'failed'\n" ]
[ [ "numpy.testing.assert_array_equal", "numpy.rollaxis", "numpy.testing.assert_raises", "numpy.ones" ] ]
hyydrra/OmniAnomaly
[ "9aa05298f97ea6c01c4fce40c34b7d77e5f3dbd2" ]
[ "main.py" ]
[ "# -*- coding: utf-8 -*-\nimport logging\nimport os\nimport pickle\nimport sys\nimport time\nimport warnings\nfrom argparse import ArgumentParser\nfrom pprint import pformat, pprint\n\nimport numpy as np\nimport tensorflow as tf\nfrom tfsnippet.examples.utils import MLResults, print_with_title\nfrom tfsnippet.scaffold import VariableSaver\nfrom tfsnippet.utils import get_variables_as_dict, register_config_arguments, Config\n\nfrom omni_anomaly.eval_methods import pot_eval, bf_search\nfrom omni_anomaly.model import OmniAnomaly\nfrom omni_anomaly.prediction import Predictor\nfrom omni_anomaly.training import Trainer\nfrom omni_anomaly.utils import get_data_dim, get_data, save_z\n\n\nclass ExpConfig(Config):\n # dataset configuration\n dataset = \"machine-1-1\"\n x_dim = get_data_dim(dataset)\n\n # model architecture configuration\n use_connected_z_q = True\n use_connected_z_p = True\n\n # model parameters\n z_dim = 3\n rnn_cell = 'GRU' # 'GRU', 'LSTM' or 'Basic'\n rnn_num_hidden = 500\n window_length = 100\n dense_dim = 500\n posterior_flow_type = 'nf' # 'nf' or None\n nf_layers = 20 # for nf\n max_epoch = 10\n train_start = 0\n max_train_size = None # `None` means full train set\n batch_size = 50\n l2_reg = 0.0001\n initial_lr = 0.001\n lr_anneal_factor = 0.5\n lr_anneal_epoch_freq = 40\n lr_anneal_step_freq = None\n std_epsilon = 1e-4\n\n # evaluation parameters\n test_n_z = 1\n test_batch_size = 50\n test_start = 0\n max_test_size = None # `None` means full test set\n\n # the range and step-size for score for searching best-f1\n # may vary for different dataset\n bf_search_min = -400.\n bf_search_max = 400.\n bf_search_step_size = 1.\n\n valid_step_freq = 100\n gradient_clip_norm = 10.\n\n early_stop = True # whether to apply early stop method\n\n # pot parameters\n # recommend values for `level`:\n # SMAP: 0.07\n # MSL: 0.01\n # SMD group 1: 0.0050\n # SMD group 2: 0.0075\n # SMD group 3: 0.0001\n level = 0.01\n\n # outputs config\n save_z = False # whether to save sampled z in hidden space\n get_score_on_dim = False # whether to get score on dim. If `True`, the score will be a 2-dim ndarray\n save_dir = 'model'\n restore_dir = None # If not None, restore variables from this dir\n result_dir = 'result' # Where to save the result file\n train_score_filename = 'train_score.pkl'\n test_score_filename = 'test_score.pkl'\n\n\ndef main():\n logging.basicConfig(\n level='INFO',\n format='%(asctime)s [%(levelname)s] %(name)s: %(message)s'\n )\n\n # prepare the data\n (x_train, _), (x_test, y_test) = \\\n get_data(config.dataset, config.max_train_size, config.max_test_size, train_start=config.train_start,\n test_start=config.test_start)\n\n # construct the model under `variable_scope` named 'model'\n with tf.variable_scope('model') as model_vs:\n model = OmniAnomaly(config=config, name=\"model\")\n\n # construct the trainer\n trainer = Trainer(model=model,\n model_vs=model_vs,\n max_epoch=config.max_epoch,\n batch_size=config.batch_size,\n valid_batch_size=config.test_batch_size,\n initial_lr=config.initial_lr,\n lr_anneal_epochs=config.lr_anneal_epoch_freq,\n lr_anneal_factor=config.lr_anneal_factor,\n grad_clip_norm=config.gradient_clip_norm,\n valid_step_freq=config.valid_step_freq)\n\n # construct the predictor\n predictor = Predictor(model, batch_size=config.batch_size, n_z=config.test_n_z,\n last_point_only=True)\n\n with tf.Session().as_default():\n\n if config.restore_dir is not None:\n # Restore variables from `save_dir`.\n saver = VariableSaver(get_variables_as_dict(model_vs), config.restore_dir)\n saver.restore()\n\n if config.max_epoch > 0:\n # train the model\n train_start = time.time()\n best_valid_metrics = trainer.fit(x_train)\n train_time = (time.time() - train_start) / config.max_epoch\n best_valid_metrics.update({\n 'train_time': train_time\n })\n else:\n best_valid_metrics = {}\n\n # get score of train set for POT algorithm\n train_score, train_z, train_pred_speed = predictor.get_score(x_train)\n if config.train_score_filename is not None:\n with open(os.path.join(config.result_dir, config.train_score_filename), 'wb') as file:\n pickle.dump(train_score, file)\n if config.save_z:\n save_z(train_z, 'train_z')\n\n if x_test is not None:\n # get score of test set\n test_start = time.time()\n test_score, test_z, pred_speed = predictor.get_score(x_test)\n test_time = time.time() - test_start\n if config.save_z:\n save_z(test_z, 'test_z')\n best_valid_metrics.update({\n 'pred_time': pred_speed,\n 'pred_total_time': test_time\n })\n if config.test_score_filename is not None:\n with open(os.path.join(config.result_dir, config.test_score_filename), 'wb') as file:\n pickle.dump(test_score, file)\n\n if y_test is not None and len(y_test) >= len(test_score):\n if config.get_score_on_dim:\n # get the joint score\n test_score = np.sum(test_score, axis=-1)\n train_score = np.sum(train_score, axis=-1)\n\n # get best f1\n t, th = bf_search(test_score, y_test[-len(test_score):],\n start=config.bf_search_min,\n end=config.bf_search_max,\n step_num=int(abs(config.bf_search_max - config.bf_search_min) /\n config.bf_search_step_size),\n display_freq=50)\n # get pot results\n pot_result = pot_eval(train_score, test_score, y_test[-len(test_score):], level=config.level)\n\n # output the results\n best_valid_metrics.update({\n 'best-f1': t[0],\n 'precision': t[1],\n 'recall': t[2],\n 'TP': t[3],\n 'TN': t[4],\n 'FP': t[5],\n 'FN': t[6],\n 'latency': t[-1],\n 'threshold': th\n })\n best_valid_metrics.update(pot_result)\n results.update_metrics(best_valid_metrics)\n\n if config.save_dir is not None:\n # save the variables\n var_dict = get_variables_as_dict(model_vs)\n saver = VariableSaver(var_dict, config.save_dir)\n saver.save()\n print('=' * 30 + 'result' + '=' * 30)\n pprint(best_valid_metrics)\n\n\nif __name__ == '__main__':\n\n # get config obj\n config = ExpConfig()\n\n # parse the arguments\n arg_parser = ArgumentParser()\n register_config_arguments(config, arg_parser)\n arg_parser.parse_args(sys.argv[1:])\n config.x_dim = get_data_dim(config.dataset)\n\n print_with_title('Configurations', pformat(config.to_dict()), after='\\n')\n\n # open the result object and prepare for result directories if specified\n results = MLResults(config.result_dir)\n results.save_config(config) # save experiment settings for review\n results.make_dirs(config.save_dir, exist_ok=True)\n with warnings.catch_warnings():\n # suppress DeprecationWarning from NumPy caused by codes in TensorFlow-Probability\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning, module='numpy')\n main()\n" ]
[ [ "tensorflow.variable_scope", "numpy.sum", "tensorflow.Session" ] ]
hieunq95/keras-rl
[ "d965ea951220b5ede5ea1e11fab7d7eb45a8c2c5" ]
[ "rl/core.py" ]
[ "# -*- coding: utf-8 -*-\nimport warnings\nfrom copy import deepcopy\n\nimport numpy as np\nfrom keras.callbacks import History\n\nfrom rl.callbacks import (\n CallbackList,\n TestLogger,\n TrainEpisodeLogger,\n TrainIntervalLogger,\n Visualizer\n)\n\n\nclass Agent(object):\n \"\"\"Abstract base class for all implemented agents.\n\n Each agent interacts with the environment (as defined by the `Env` class) by first observing the\n state of the environment. Based on this observation the agent changes the environment by performing\n an action.\n\n Do not use this abstract base class directly but instead use one of the concrete agents implemented.\n Each agent realizes a reinforcement learning algorithm. Since all agents conform to the same\n interface, you can use them interchangeably.\n\n To implement your own agent, you have to implement the following methods:\n\n - `forward`\n - `backward`\n - `compile`\n - `load_weights`\n - `save_weights`\n - `layers`\n\n # Arguments\n processor (`Processor` instance): See [Processor](#processor) for details.\n \"\"\"\n def __init__(self, processor=None):\n self.processor = processor\n self.training = False\n self.step = 0\n\n def get_config(self):\n \"\"\"Configuration of the agent for serialization.\n\n # Returns\n Dictionnary with agent configuration\n \"\"\"\n return {}\n\n def fit(self, env, nb_steps, action_repetition=1, callbacks=None, verbose=1,\n visualize=False, nb_max_start_steps=0, start_step_policy=None, log_interval=10000,\n nb_max_episode_steps=None):\n \"\"\"Trains the agent on the given environment.\n\n # Arguments\n env: (`Env` instance): Environment that the agent interacts with. See [Env](#env) for details.\n nb_steps (integer): Number of training steps to be performed.\n action_repetition (integer): Number of times the agent repeats the same action without\n observing the environment again. Setting this to a value > 1 can be useful\n if a single action only has a very small effect on the environment.\n callbacks (list of `keras.callbacks.Callback` or `rl.callbacks.Callback` instances):\n List of callbacks to apply during training. See [callbacks](/callbacks) for details.\n verbose (integer): 0 for no logging, 1 for interval logging (compare `log_interval`), 2 for episode logging\n visualize (boolean): If `True`, the environment is visualized during training. However,\n this is likely going to slow down training significantly and is thus intended to be\n a debugging instrument.\n nb_max_start_steps (integer): Number of maximum steps that the agent performs at the beginning\n of each episode using `start_step_policy`. Notice that this is an upper limit since\n the exact number of steps to be performed is sampled uniformly from [0, max_start_steps]\n at the beginning of each episode.\n start_step_policy (`lambda observation: action`): The policy\n to follow if `nb_max_start_steps` > 0. If set to `None`, a random action is performed.\n log_interval (integer): If `verbose` = 1, the number of steps that are considered to be an interval.\n nb_max_episode_steps (integer): Number of steps per episode that the agent performs before\n automatically resetting the environment. Set to `None` if each episode should run\n (potentially indefinitely) until the environment signals a terminal state.\n\n # Returns\n A `keras.callbacks.History` instance that recorded the entire training process.\n \"\"\"\n if not self.compiled:\n raise RuntimeError('Your tried to fit your agent but it hasn\\'t been compiled yet. Please call `compile()` before `fit()`.')\n if action_repetition < 1:\n raise ValueError('action_repetition must be >= 1, is {}'.format(action_repetition))\n\n self.training = True\n\n callbacks = [] if not callbacks else callbacks[:]\n\n if verbose == 1:\n callbacks += [TrainIntervalLogger(interval=log_interval)]\n elif verbose > 1:\n callbacks += [TrainEpisodeLogger()]\n if visualize:\n callbacks += [Visualizer()]\n history = History()\n callbacks += [history]\n callbacks = CallbackList(callbacks)\n if hasattr(callbacks, 'set_model'):\n callbacks.set_model(self)\n else:\n callbacks._set_model(self)\n callbacks._set_env(env)\n params = {\n 'nb_steps': nb_steps,\n }\n if hasattr(callbacks, 'set_params'):\n callbacks.set_params(params)\n else:\n callbacks._set_params(params)\n self._on_train_begin()\n callbacks.on_train_begin()\n\n episode = np.int16(0)\n self.step = np.int16(0)\n observation = None\n episode_reward = None\n episode_step = None\n did_abort = False\n try:\n while self.step < nb_steps:\n if observation is None: # start of a new episode\n callbacks.on_episode_begin(episode)\n episode_step = np.int16(0)\n episode_reward = np.float32(0)\n\n # Obtain the initial observation by resetting the environment.\n self.reset_states()\n observation = deepcopy(env.reset())\n if self.processor is not None:\n observation = self.processor.process_observation(observation)\n assert observation is not None\n\n # Perform random starts at beginning of episode and do not record them into the experience.\n # This slightly changes the start position between games.\n nb_random_start_steps = 0 if nb_max_start_steps == 0 else np.random.randint(nb_max_start_steps)\n for _ in range(nb_random_start_steps):\n if start_step_policy is None:\n action = env.action_space.sample()\n else:\n action = start_step_policy(observation)\n if self.processor is not None:\n action = self.processor.process_action(action)\n callbacks.on_action_begin(action)\n observation, reward, done, info = env.step(action)\n observation = deepcopy(observation)\n if self.processor is not None:\n observation, reward, done, info = self.processor.process_step(observation, reward, done, info)\n callbacks.on_action_end(action)\n if done:\n warnings.warn('Env ended before {} random steps could be performed at the start. You should probably lower the `nb_max_start_steps` parameter.'.format(nb_random_start_steps))\n observation = deepcopy(env.reset())\n if self.processor is not None:\n observation = self.processor.process_observation(observation)\n break\n\n # At this point, we expect to be fully initialized.\n assert episode_reward is not None\n assert episode_step is not None\n assert observation is not None\n\n # Run a single step.\n callbacks.on_step_begin(episode_step)\n # This is were all of the work happens. We first perceive and compute the action\n # (forward step) and then use the reward to improve (backward step).\n action = self.forward(observation)\n if self.processor is not None:\n action = self.processor.process_action(action)\n reward = np.float32(0)\n accumulated_info = {}\n done = False\n for _ in range(action_repetition):\n callbacks.on_action_begin(action)\n observation, r, done, info = env.step(action)\n observation = deepcopy(observation)\n if self.processor is not None:\n observation, r, done, info = self.processor.process_step(observation, r, done, info)\n for key, value in info.items():\n if not np.isreal(value):\n continue\n if key not in accumulated_info:\n accumulated_info[key] = np.zeros_like(value)\n accumulated_info[key] += value\n callbacks.on_action_end(action)\n reward += r\n if done:\n break\n if nb_max_episode_steps and episode_step >= nb_max_episode_steps - 1:\n # Force a terminal state.\n done = True\n metrics = self.backward(reward, terminal=done)\n episode_reward += reward\n\n step_logs = {\n 'action': action,\n 'observation': observation,\n 'reward': reward,\n 'metrics': metrics,\n 'episode': episode,\n 'info': accumulated_info,\n }\n callbacks.on_step_end(episode_step, step_logs)\n episode_step += 1\n self.step += 1\n\n if done:\n # We are in a terminal state but the agent hasn't yet seen it. We therefore\n # perform one more forward-backward call and simply ignore the action before\n # resetting the environment. We need to pass in `terminal=False` here since\n # the *next* state, that is the state of the newly reset environment, is\n # always non-terminal by convention.\n self.forward(observation)\n self.backward(0., terminal=False)\n\n # This episode is finished, report and reset.\n episode_logs = {\n 'episode_reward': episode_reward,\n 'nb_episode_steps': episode_step,\n 'nb_steps': self.step,\n }\n callbacks.on_episode_end(episode, episode_logs)\n\n episode += 1\n observation = None\n episode_step = None\n episode_reward = None\n \n except KeyboardInterrupt:\n # We catch keyboard interrupts here so that training can be be safely aborted.\n # This is so common that we've built this right into this function, which ensures that\n # the `on_train_end` method is properly called.\n did_abort = True\n callbacks.on_train_end(logs={'did_abort': did_abort})\n self._on_train_end()\n\n return history\n\n def test(self, env, nb_episodes=1, action_repetition=1, callbacks=None, visualize=True,\n nb_max_episode_steps=None, nb_max_start_steps=0, start_step_policy=None, verbose=1):\n \"\"\"Callback that is called before training begins.\n\n # Arguments\n env: (`Env` instance): Environment that the agent interacts with. See [Env](#env) for details.\n nb_episodes (integer): Number of episodes to perform.\n action_repetition (integer): Number of times the agent repeats the same action without\n observing the environment again. Setting this to a value > 1 can be useful\n if a single action only has a very small effect on the environment.\n callbacks (list of `keras.callbacks.Callback` or `rl.callbacks.Callback` instances):\n List of callbacks to apply during training. See [callbacks](/callbacks) for details.\n verbose (integer): 0 for no logging, 1 for interval logging (compare `log_interval`), 2 for episode logging\n visualize (boolean): If `True`, the environment is visualized during training. However,\n this is likely going to slow down training significantly and is thus intended to be\n a debugging instrument.\n nb_max_start_steps (integer): Number of maximum steps that the agent performs at the beginning\n of each episode using `start_step_policy`. Notice that this is an upper limit since\n the exact number of steps to be performed is sampled uniformly from [0, max_start_steps]\n at the beginning of each episode.\n start_step_policy (`lambda observation: action`): The policy\n to follow if `nb_max_start_steps` > 0. If set to `None`, a random action is performed.\n log_interval (integer): If `verbose` = 1, the number of steps that are considered to be an interval.\n nb_max_episode_steps (integer): Number of steps per episode that the agent performs before\n automatically resetting the environment. Set to `None` if each episode should run\n (potentially indefinitely) until the environment signals a terminal state.\n\n # Returns\n A `keras.callbacks.History` instance that recorded the entire training process.\n \"\"\"\n if not self.compiled:\n raise RuntimeError('Your tried to test your agent but it hasn\\'t been compiled yet. Please call `compile()` before `test()`.')\n if action_repetition < 1:\n raise ValueError('action_repetition must be >= 1, is {}'.format(action_repetition))\n\n self.training = False\n self.step = 0\n\n callbacks = [] if not callbacks else callbacks[:]\n\n if verbose >= 1:\n callbacks += [TestLogger()]\n if visualize:\n callbacks += [Visualizer()]\n history = History()\n callbacks += [history]\n callbacks = CallbackList(callbacks)\n if hasattr(callbacks, 'set_model'):\n callbacks.set_model(self)\n else:\n callbacks._set_model(self)\n callbacks._set_env(env)\n params = {\n 'nb_episodes': nb_episodes,\n }\n if hasattr(callbacks, 'set_params'):\n callbacks.set_params(params)\n else:\n callbacks._set_params(params)\n\n self._on_test_begin()\n callbacks.on_train_begin()\n for episode in range(nb_episodes):\n callbacks.on_episode_begin(episode)\n episode_reward = 0.\n episode_step = 0\n\n # Obtain the initial observation by resetting the environment.\n self.reset_states()\n observation = deepcopy(env.reset())\n if self.processor is not None:\n observation = self.processor.process_observation(observation)\n assert observation is not None\n\n # Perform random starts at beginning of episode and do not record them into the experience.\n # This slightly changes the start position between games.\n nb_random_start_steps = 0 if nb_max_start_steps == 0 else np.random.randint(nb_max_start_steps)\n for _ in range(nb_random_start_steps):\n if start_step_policy is None:\n action = env.action_space.sample()\n else:\n action = start_step_policy(observation)\n if self.processor is not None:\n action = self.processor.process_action(action)\n callbacks.on_action_begin(action)\n observation, r, done, info = env.step(action)\n observation = deepcopy(observation)\n if self.processor is not None:\n observation, r, done, info = self.processor.process_step(observation, r, done, info)\n callbacks.on_action_end(action)\n if done:\n warnings.warn('Env ended before {} random steps could be performed at the start. You should probably lower the `nb_max_start_steps` parameter.'.format(nb_random_start_steps))\n observation = deepcopy(env.reset())\n if self.processor is not None:\n observation = self.processor.process_observation(observation)\n break\n\n # Run the episode until we're done.\n done = False\n while not done:\n callbacks.on_step_begin(episode_step)\n\n action = self.forward(observation)\n if self.processor is not None:\n action = self.processor.process_action(action)\n reward = 0.\n accumulated_info = {}\n for _ in range(action_repetition):\n callbacks.on_action_begin(action)\n observation, r, d, info = env.step(action)\n observation = deepcopy(observation)\n if self.processor is not None:\n observation, r, d, info = self.processor.process_step(observation, r, d, info)\n callbacks.on_action_end(action)\n reward += r\n for key, value in info.items():\n if not np.isreal(value):\n continue\n if key not in accumulated_info:\n accumulated_info[key] = np.zeros_like(value)\n accumulated_info[key] += value\n if d:\n done = True\n break\n if nb_max_episode_steps and episode_step >= nb_max_episode_steps - 1:\n done = True\n self.backward(reward, terminal=done)\n episode_reward += reward\n\n step_logs = {\n 'action': action,\n 'observation': observation,\n 'reward': reward,\n 'episode': episode,\n 'info': accumulated_info,\n }\n callbacks.on_step_end(episode_step, step_logs)\n episode_step += 1\n self.step += 1\n\n # We are in a terminal state but the agent hasn't yet seen it. We therefore\n # perform one more forward-backward call and simply ignore the action before\n # resetting the environment. We need to pass in `terminal=False` here since\n # the *next* state, that is the state of the newly reset environment, is\n # always non-terminal by convention.\n self.forward(observation)\n self.backward(0., terminal=False)\n\n # Report end of episode.\n episode_logs = {\n 'episode_reward': episode_reward,\n 'nb_steps': episode_step,\n }\n callbacks.on_episode_end(episode, episode_logs)\n callbacks.on_train_end()\n self._on_test_end()\n\n return history\n\n def reset_states(self):\n \"\"\"Resets all internally kept states after an episode is completed.\n \"\"\"\n pass\n\n def forward(self, observation):\n \"\"\"Takes the an observation from the environment and returns the action to be taken next.\n If the policy is implemented by a neural network, this corresponds to a forward (inference) pass.\n\n # Argument\n observation (object): The current observation from the environment.\n\n # Returns\n The next action to be executed in the environment.\n \"\"\"\n raise NotImplementedError()\n\n def backward(self, reward, terminal):\n \"\"\"Updates the agent after having executed the action returned by `forward`.\n If the policy is implemented by a neural network, this corresponds to a weight update using back-prop.\n\n # Argument\n reward (float): The observed reward after executing the action returned by `forward`.\n terminal (boolean): `True` if the new state of the environment is terminal.\n\n # Returns\n List of metrics values\n \"\"\"\n raise NotImplementedError()\n\n def compile(self, optimizer, metrics=[]):\n \"\"\"Compiles an agent and the underlaying models to be used for training and testing.\n\n # Arguments\n optimizer (`keras.optimizers.Optimizer` instance): The optimizer to be used during training.\n metrics (list of functions `lambda y_true, y_pred: metric`): The metrics to run during training.\n \"\"\"\n raise NotImplementedError()\n\n def load_weights(self, filepath):\n \"\"\"Loads the weights of an agent from an HDF5 file.\n\n # Arguments\n filepath (str): The path to the HDF5 file.\n \"\"\"\n raise NotImplementedError()\n\n def save_weights(self, filepath, overwrite=False):\n \"\"\"Saves the weights of an agent as an HDF5 file.\n\n # Arguments\n filepath (str): The path to where the weights should be saved.\n overwrite (boolean): If `False` and `filepath` already exists, raises an error.\n \"\"\"\n raise NotImplementedError()\n\n @property\n def layers(self):\n \"\"\"Returns all layers of the underlying model(s).\n\n If the concrete implementation uses multiple internal models,\n this method returns them in a concatenated list.\n\n # Returns\n A list of the model's layers\n \"\"\"\n raise NotImplementedError()\n\n @property\n def metrics_names(self):\n \"\"\"The human-readable names of the agent's metrics. Must return as many names as there\n are metrics (see also `compile`).\n\n # Returns\n A list of metric's names (string)\n \"\"\"\n return []\n\n def _on_train_begin(self):\n \"\"\"Callback that is called before training begins.\"\n \"\"\"\n pass\n\n def _on_train_end(self):\n \"\"\"Callback that is called after training ends.\"\n \"\"\"\n pass\n\n def _on_test_begin(self):\n \"\"\"Callback that is called before testing begins.\"\n \"\"\"\n pass\n\n def _on_test_end(self):\n \"\"\"Callback that is called after testing ends.\"\n \"\"\"\n pass\n\n\nclass Processor(object):\n \"\"\"Abstract base class for implementing processors.\n\n A processor acts as a coupling mechanism between an `Agent` and its `Env`. This can\n be necessary if your agent has different requirements with respect to the form of the\n observations, actions, and rewards of the environment. By implementing a custom processor,\n you can effectively translate between the two without having to change the underlaying\n implementation of the agent or environment.\n\n Do not use this abstract base class directly but instead use one of the concrete implementations\n or write your own.\n \"\"\"\n\n def process_step(self, observation, reward, done, info):\n \"\"\"Processes an entire step by applying the processor to the observation, reward, and info arguments.\n\n # Arguments\n observation (object): An observation as obtained by the environment.\n reward (float): A reward as obtained by the environment.\n done (boolean): `True` if the environment is in a terminal state, `False` otherwise.\n info (dict): The debug info dictionary as obtained by the environment.\n\n # Returns\n The tupel (observation, reward, done, reward) with with all elements after being processed.\n \"\"\"\n observation = self.process_observation(observation)\n reward = self.process_reward(reward)\n info = self.process_info(info)\n return observation, reward, done, info\n\n def process_observation(self, observation):\n \"\"\"Processes the observation as obtained from the environment for use in an agent and\n returns it.\n\n # Arguments\n observation (object): An observation as obtained by the environment\n\n # Returns\n Observation obtained by the environment processed\n \"\"\"\n return observation\n\n def process_reward(self, reward):\n \"\"\"Processes the reward as obtained from the environment for use in an agent and\n returns it.\n\n # Arguments\n reward (float): A reward as obtained by the environment\n\n # Returns\n Reward obtained by the environment processed\n \"\"\"\n return reward\n\n def process_info(self, info):\n \"\"\"Processes the info as obtained from the environment for use in an agent and\n returns it.\n\n # Arguments\n info (dict): An info as obtained by the environment\n\n # Returns\n Info obtained by the environment processed\n \"\"\"\n return info\n\n def process_action(self, action):\n \"\"\"Processes an action predicted by an agent but before execution in an environment.\n\n # Arguments\n action (int): Action given to the environment\n\n # Returns\n Processed action given to the environment\n \"\"\"\n return action\n\n def process_state_batch(self, batch):\n \"\"\"Processes an entire batch of states and returns it.\n\n # Arguments\n batch (list): List of states\n\n # Returns\n Processed list of states\n \"\"\"\n return batch\n\n @property\n def metrics(self):\n \"\"\"The metrics of the processor, which will be reported during training.\n\n # Returns\n List of `lambda y_true, y_pred: metric` functions.\n \"\"\"\n return []\n\n @property\n def metrics_names(self):\n \"\"\"The human-readable names of the agent's metrics. Must return as many names as there\n are metrics (see also `compile`).\n \"\"\"\n return []\n\n\n# Note: the API of the `Env` and `Space` classes are taken from the OpenAI Gym implementation.\n# https://github.com/openai/gym/blob/master/gym/core.py\n\n\nclass Env(object):\n \"\"\"The abstract environment class that is used by all agents. This class has the exact\n same API that OpenAI Gym uses so that integrating with it is trivial. In contrast to the\n OpenAI Gym implementation, this class only defines the abstract methods without any actual\n implementation.\n\n To implement your own environment, you need to define the following methods:\n\n - `step`\n - `reset`\n - `render`\n - `close`\n\n Refer to the [Gym documentation](https://gym.openai.com/docs/#environments).\n \"\"\"\n reward_range = (-np.inf, np.inf)\n action_space = None\n observation_space = None\n\n def step(self, action):\n \"\"\"Run one timestep of the environment's dynamics.\n Accepts an action and returns a tuple (observation, reward, done, info).\n\n # Arguments\n action (object): An action provided by the environment.\n\n # Returns\n observation (object): Agent's observation of the current environment.\n reward (float) : Amount of reward returned after previous action.\n done (boolean): Whether the episode has ended, in which case further step() calls will return undefined results.\n info (dict): Contains auxiliary diagnostic information (helpful for debugging, and sometimes learning).\n \"\"\"\n raise NotImplementedError()\n\n def reset(self):\n \"\"\"\n Resets the state of the environment and returns an initial observation.\n\n # Returns\n observation (object): The initial observation of the space. Initial reward is assumed to be 0.\n \"\"\"\n raise NotImplementedError()\n\n def render(self, mode='human', close=False):\n \"\"\"Renders the environment.\n The set of supported modes varies per environment. (And some\n environments do not support rendering at all.)\n\n # Arguments\n mode (str): The mode to render with.\n close (bool): Close all open renderings.\n \"\"\"\n raise NotImplementedError()\n\n def close(self):\n \"\"\"Override in your subclass to perform any necessary cleanup.\n Environments will automatically close() themselves when\n garbage collected or when the program exits.\n \"\"\"\n raise NotImplementedError()\n\n def seed(self, seed=None):\n \"\"\"Sets the seed for this env's random number generator(s).\n\n # Returns\n Returns the list of seeds used in this env's random number generators\n \"\"\"\n raise NotImplementedError()\n\n def configure(self, *args, **kwargs):\n \"\"\"Provides runtime configuration to the environment.\n This configuration should consist of data that tells your\n environment how to run (such as an address of a remote server,\n or path to your ImageNet data). It should not affect the\n semantics of the environment.\n \"\"\"\n raise NotImplementedError()\n\n def __del__(self):\n self.close()\n\n def __str__(self):\n return '<{} instance>'.format(type(self).__name__)\n\n\nclass Space(object):\n \"\"\"Abstract model for a space that is used for the state and action spaces. This class has the\n exact same API that OpenAI Gym uses so that integrating with it is trivial.\n\n Please refer to [Gym Documentation](https://gym.openai.com/docs/#spaces)\n \"\"\"\n\n def sample(self, seed=None):\n \"\"\"Uniformly randomly sample a random element of this space.\n \"\"\"\n raise NotImplementedError()\n\n def contains(self, x):\n \"\"\"Return boolean specifying if x is a valid member of this space\n \"\"\"\n raise NotImplementedError()\n" ]
[ [ "numpy.int16", "numpy.zeros_like", "numpy.float32", "numpy.isreal", "numpy.random.randint" ] ]
zeta1999/Gradient-Free-Optimizers
[ "f6b58e248a6fdfaa7c7d774ae4c0d9b4b67b5e47" ]
[ "gradient_free_optimizers/optimizers/sequence_model/exp_imp_based_opt.py" ]
[ "# Author: Simon Blanke\n# Email: [email protected]\n# License: MIT License\n\n\nimport numpy as np\nfrom scipy.stats import norm\n\nfrom .smbo import SMBO\n\n\ndef normalize(array):\n num = array - array.min()\n den = array.max() - array.min()\n\n if den == 0:\n return np.random.random_sample(array.shape)\n else:\n return ((num / den) + 0) / 1\n\n\nclass ExpectedImprovementBasedOptimization(SMBO):\n def __init__(\n self,\n search_space,\n initialize={\"grid\": 4, \"random\": 2, \"vertices\": 4},\n xi=0.01,\n warm_start_smbo=None,\n sampling={\"random\": 1000000},\n warnings=100000000,\n rand_rest_p=0.03,\n ):\n super().__init__(search_space, initialize)\n self.new_positions = []\n self.xi = xi\n self.warm_start_smbo = warm_start_smbo\n self.sampling = sampling\n self.warnings = warnings\n self.rand_rest_p = rand_rest_p\n\n def _sampling(self):\n if self.sampling is False:\n return self.all_pos_comb\n elif \"random\" in self.sampling:\n return self.random_sampling()\n\n def _expected_improvement(self):\n self.pos_comb = self._sampling()\n mu, sigma = self.regr.predict(self.pos_comb, return_std=True)\n # mu_sample = self.regr.predict(self.X_sample)\n mu = mu.reshape(-1, 1)\n sigma = sigma.reshape(-1, 1)\n\n Y_sample = normalize(np.array(self.Y_sample)).reshape(-1, 1)\n imp = mu - np.max(Y_sample) - self.xi\n Z = np.divide(imp, sigma, out=np.zeros_like(sigma), where=sigma != 0)\n\n exploit = imp * norm.cdf(Z)\n explore = sigma * norm.pdf(Z)\n\n exp_imp = exploit + explore\n exp_imp[sigma == 0.0] = 0.0\n\n return exp_imp[:, 0]\n\n def _propose_location(self):\n X_sample = np.array(self.X_sample)\n Y_sample = np.array(self.Y_sample)\n\n try:\n Y_sample = normalize(Y_sample).reshape(-1, 1)\n self.regr.fit(X_sample, Y_sample)\n except ValueError:\n print(\"Error: Surrogate model cannot fit to samples\")\n\n exp_imp = self._expected_improvement()\n\n index_best = list(exp_imp.argsort()[::-1])\n all_pos_comb_sorted = self.pos_comb[index_best]\n pos_best = all_pos_comb_sorted[0]\n\n return pos_best\n\n @SMBO.track_nth_iter\n @SMBO.track_X_sample\n def iterate(self):\n return self._propose_location()\n\n def evaluate(self, score_new):\n self.score_new = score_new\n\n self._evaluate_new2current(score_new)\n self._evaluate_current2best()\n\n self.Y_sample.append(score_new)\n\n if np.isnan(score_new) or np.isinf(score_new):\n del self.X_sample[-1]\n del self.Y_sample[-1]\n" ]
[ [ "scipy.stats.norm.cdf", "scipy.stats.norm.pdf", "numpy.isnan", "numpy.random.random_sample", "numpy.max", "numpy.zeros_like", "numpy.array", "numpy.isinf" ] ]
DavidBakerEffendi/palestine-israel-twitter
[ "5620009e06375d66f395d04a7b94bf11ab0f97b6" ]
[ "components/__init__.py" ]
[ "import numpy as np\nimport plotly as py\nimport plotly.graph_objs as go\nimport random\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nimport datetime as dt\n\nfrom typing import Dict\n\n\ndef plotly_wordcloud(words: Dict[str, int]):\n lower, upper = 15, 45\n frequency = [((x - min(words.values())) / (max(words.values()) - min(words.values()))) * (upper - lower) + lower\n for x in words.values()]\n\n if np.isnan(np.sum(frequency)):\n frequency = [100]\n\n percent = list(map(lambda x: x / sum(frequency), frequency))\n\n length = len(words.keys())\n colors = [py.colors.DEFAULT_PLOTLY_COLORS[random.randrange(1, 10)] for _ in range(length)]\n\n xs = list(range(length))\n ys = random.choices(range(length), k=length)\n\n data = go.Scatter(\n x=xs,\n y=ys,\n mode='text',\n text=list(words.keys()),\n hovertext=['{0} ({1})'.format(w, format(p, '.2%')) for w, _, p in zip(words, frequency, percent)],\n hoverinfo='text',\n textfont={'size': frequency, 'color': colors}\n )\n layout = go.Layout({\n 'xaxis': {'showgrid': False, 'showticklabels': False, 'zeroline': False},\n 'yaxis': {'showgrid': False, 'showticklabels': False, 'zeroline': False}\n },\n paper_bgcolor='rgba(0,0,0,0)',\n plot_bgcolor='rgba(0,0,0,0)',\n autosize=True,\n margin={'t': 0.5, 'b': 0.5, 'l': 0, 'r': 0},\n )\n padding = 0.3\n fig = go.Figure(\n data=[data],\n layout=layout,\n layout_yaxis_range=[min(ys) - padding, max(ys) + padding],\n layout_xaxis_range=[min(xs) - padding, max(xs) + padding]\n )\n\n return fig\n\n\ndef bin_by_date(twitter_info: dict, key: str):\n bins = {}\n for d, x in twitter_info.items():\n bins[d] = create_binned_lists(x[key])\n return bins\n\n\ndef create_binned_lists(info: dict, no_bins=6.0):\n interval = 100.0 / float(no_bins)\n bins = {}\n i = 0\n while i < 100:\n bins[i] = []\n for x, y in info.items():\n if i + interval >= y > i:\n bins[i].append(x)\n i += interval\n return bins\n\n\ndef create_similarity_dict(xs, ys) -> Dict[str, float]:\n sim = {}\n for x, fx in xs:\n for y, fy in ys:\n if x == y:\n sim[x] = np.abs(fx - fy)\n # At this point, the lower the score the higher the match\n if len(sim) == 0:\n return sim\n a = min(sim.values())\n b = max(sim.values())\n for x, y in sim.items():\n # Flip the match and make it from 0-100\n sim[x] = (1.0 - ((y - a) / (b - a))) * 100\n return dict(sorted(sim.items(), key=lambda i: i[1], reverse=True))\n\n\ndef create_sentiment_graph(twitter_info: dict, media_info: dict):\n return dcc.Graph(\n id='sentiment-graph',\n figure=go.Figure(\n layout={\n 'title': 'Twitter vs Media Sentiment',\n 'xaxis_title': \"Date\",\n 'yaxis_title': \"Sentiment\",\n },\n data=[\n go.Scatter(\n name='Twitter Sentiment',\n x=list(twitter_info.keys()),\n y=[x['sentiment'].mean() for x in twitter_info.values()],\n error_y=dict(\n array=[x['sentiment'].std() for x in twitter_info.values()],\n visible=True)\n ),\n go.Scatter(\n name='Media Sentiment',\n x=list(media_info.keys()),\n y=[x['sentiment'].mean() for x in media_info.values()],\n error_y=dict(\n array=[x['sentiment'].std() for x in media_info.values()],\n visible=True)\n )\n ]\n )\n )\n\n\ndef create_similarity_graph(twitter_info: dict, media_info: dict):\n similarity_info = {\n 'key_phrases': [],\n 'emotional_traits': [],\n 'behavioral_traits': []\n }\n for key in similarity_info.keys():\n for d in twitter_info.keys():\n sims = np.nanmean(\n list(create_similarity_dict(twitter_info[d][key].items(), media_info[d][key].items()).values()))\n similarity_info[key].append(np.nan_to_num(sims))\n return dcc.Graph(\n id='sim-graph',\n figure=go.Figure(\n layout={\n 'title': 'Key Phrases and Trait Similarity',\n 'xaxis_title': \"Date\",\n 'yaxis_title': \"Similarity\",\n },\n data=[\n go.Scatter(\n name='Key Phrases',\n x=list(twitter_info.keys()),\n y=similarity_info['key_phrases']\n ),\n go.Scatter(\n name='Emotional Traits',\n x=list(twitter_info.keys()),\n y=similarity_info['emotional_traits']\n ),\n go.Scatter(\n name='Behavioral Traits',\n x=list(twitter_info.keys()),\n y=similarity_info['behavioral_traits']\n )\n ]\n )\n )\n\n\ndef create_word_lists(twitter_info: dict, media_info: dict, key: str):\n iter_obj = []\n for d in twitter_info.keys():\n iter_obj.append((d, twitter_info[d][key].items(), media_info[d][key].items()))\n\n def make_list_item(text: str, freq: float):\n if freq > 80:\n col = \"danger\"\n elif 80 >= freq > 60:\n col = \"warning\"\n elif 60 >= freq > 40:\n col = \"success\"\n elif 40 >= freq > 20:\n col = \"info\"\n else:\n col = \"secondary\"\n return dbc.ListGroupItem(text, color=col)\n\n if key == \"key_phrases\":\n title = \"Key Phrases\"\n elif key == \"emotional_traits\":\n title = \"Emotional Traits\"\n else:\n title = \"Behavioral Traits\"\n\n return [\n dbc.Tab(\n label=\"{}-05\".format(dt.datetime.fromisoformat(d).day),\n children=[\n dbc.Card([\n dbc.CardBody([\n html.H4(title, className=\"card-title text-center\"),\n dbc.Row([\n dbc.Col(width=\"4\",\n children=[html.H5(\"Twitter\", className=\"text-center\"),\n dbc.ListGroup([make_list_item(x, f) for x, f in xs], flush=True)]\n ),\n dbc.Col(width=\"4\",\n children=[html.H5(\"Matches\", className=\"text-center\"),\n dbc.ListGroup([make_list_item(z, f)\n for z, f in create_similarity_dict(xs, ys).items()],\n flush=True)]\n ),\n dbc.Col(width=\"4\",\n children=[html.H5(\"Media\", className=\"text-center\"),\n dbc.ListGroup([make_list_item(y, f) for y, f in ys], flush=True)]\n ),\n ], justify=\"center\", )\n ], style={\"maxHeight\": \"400px\", \"overflow\": \"scroll\"}\n ),\n ]),\n ]\n )\n for d, xs, ys in iter_obj\n ]\n\n\ndef create_wordcloud_tabs(twitter_info: dict, media_info: dict, key: str):\n return [\n dbc.Tab(\n dbc.Card([\n dbc.CardHeader(\"Twitter\"),\n dbc.CardBody(\n dbc.Row([\n dbc.Col(dcc.Graph(id='twitter-{}-{}-wordcloud'.format(key, d),\n figure=plotly_wordcloud(x[key])), width=\"12\", lg=\"auto\"),\n dbc.Col([\n html.H5(\"Top Results\"),\n html.Ul(\n [html.Li(\"{}\".format(phrase, p)) for phrase, p in\n list(sorted(x[key].items(), key=lambda item: item[1], reverse=True))[:15]]\n )]\n , width=\"4\")\n ]),\n ),\n dbc.CardHeader(\"Media\"),\n dbc.CardBody(\n dbc.Row([\n dbc.Col(dcc.Graph(id='media-{}-{}-wordcloud'.format(key, d),\n figure=plotly_wordcloud(y[key])), width=\"12\", lg=\"auto\"),\n dbc.Col([\n html.H5(\"Top Results\"),\n html.Ul(\n [html.Li(\"{}\".format(phrase, p)) for phrase, p in\n list(sorted(y[key].items(), key=lambda item: item[1], reverse=True))[:15]]\n )]\n , width=\"4\")\n ]),\n ),\n ],\n className=\"mt-2\",\n ),\n label=\"{}-05\".format(dt.datetime.fromisoformat(d).day)\n )\n for (d, x), y in zip(twitter_info.items(), media_info.values())\n ]\n" ]
[ [ "numpy.abs", "numpy.sum", "numpy.nan_to_num" ] ]
rastaman/what2017
[ "6d134fe87ecdd90a333225822175f003da67fd80" ]
[ "matching/nearest_neighbor.py" ]
[ "'''\nA nearest neighbor learning algorithm to identify closest matching profiles\nusing the TensorFlow library.\n\nAuthor: Detonateur Team\nProject: https://github.com/rastaman/what2017/\n'''\n\nfrom __future__ import print_function\n\nfrom beacoachmate import input_data\nimport numpy as np\nimport tensorflow as tf\n\n# Import test data\nbeacoachmate_datas = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n\nXtr, Ytr = beacoachmate_datas.train.next_batch(1000) # 1000 for training (nn candidates)\nXte, Yte = beacoachmate_datas.test.next_batch(200) # 200 for testing\n\n# tf Graph Input\nxtr = tf.placeholder(\"vector\", [8])\nxte = tf.placeholder(\"vector\", [8])\n\n# Nearest Neighbor calculation using L1 Distance\n# Calculate L1 Distance\ndistance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))), reduction_indices=1)\n# Prediction: Get min distance index (Nearest neighbor)\npred = tf.arg_min(distance, 0)\n\naccuracy = 0.\n\n# Initialize the variables (i.e. assign their default value)\ninit = tf.global_variables_initializer()\n\n# Start training\nwith tf.Session() as sess:\n\n # Run the initializer\n sess.run(init)\n\n # loop over test data\n for i in range(len(Xte)):\n # Get nearest neighbor\n nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})\n # Get nearest neighbor class label and compare it to its true label\n print(\"Test\", i, \"Prediction:\", np.argmax(Ytr[nn_index]), \\\n \"True Class:\", np.argmax(Yte[i]))\n # Calculate accuracy\n if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):\n accuracy += 1. / len(Xte)\n print(\"Done!\")\n print(\"Accuracy:\", accuracy)\n" ]
[ [ "tensorflow.negative", "tensorflow.arg_min", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "numpy.argmax", "tensorflow.Session" ] ]
PBonnema/Applied-AI-Assignments
[ "f5804a4cea899b7a77981a7d1329750726a6444a" ]
[ "Programming NNs/neuralNetwork.py" ]
[ "from neuron import Neuron\nfrom inputNeuron import InputNeuron\nfrom biasNeuron import BiasNeuron\n\nimport numpy as np\n\nclass NeuronInfo():\n \"\"\"Represents the information needed to instantiate a single neuron.\n So this class doesn't model the neuron itself. It is just a helper class to specify the topology of the network.\n \"\"\"\n def __init__(self, activation_function = None, activation_function_derivative = None, weights = None):\n \"\"\"\n `activation_function` -- A function that accepts a single number as an argument and returns a single number.\n This is the activation function of the neuron.\\n\n `activation_function_derivative` -- a function with the same signature as `activation_function` that also returns a single number.\n It is the derivative of the activation function which is used during the training phase.\\n\n `weights` -- An array of numbers containing the weights of the connections leading to this neuron.\n The last element is the weight for the connection with the bias in the previous layer of the neuron.\n \"\"\"\n self.activation_function = activation_function\n self.activation_function_derivative = activation_function_derivative\n self.weights = weights\n\nclass NeuralNetwork:\n \"\"\"Represents a feed-forward neural network that supports a training phase using the back-propagation algorithm.\n `activate()` will run a set of input values through the network and return an array of output values.\n `train()` will train the network given a set of inputs and corresponding expected responses.\n \n The topology of the network is fixed and specified as parameters to `__init__()`.\n Any number of input and output neurons and any number of hidden layers of any size are supported.\n \"\"\"\n @staticmethod\n def __activate_layer(layer):\n for neuron in layer:\n neuron.activate()\n\n @staticmethod\n def __randomize_layer(layer, rng, min, max):\n for neuron in layer:\n neuron.randomize_weights(rng, min, max)\n\n @staticmethod\n def __update_layer(layer, learning_rate):\n for neuron in layer:\n neuron.update(learning_rate)\n\n def __init__(self, input_count, hidden_neurons, output_neurons):\n \"\"\"Creates and initializes the neural network.\n \n `input_count` -- The number of inputs for this network.\n `hidden_neurons` -- A 2-d list of `NeuronInfo` instances. Each row represents a hidden layer.\n The layers can be of different lenghts.\n `output_neurons` -- a 1-d list of `NeuronInfo` instances. This represents output neurons.\n \"\"\"\n # Initialize the input layer. The last element of the all layers will be the bias neuron.\n self.__input_layer = [InputNeuron() for i in range(input_count)] + [BiasNeuron()]\n\n # Initialize the hidden layers.\n self.__hidden_layers = []\n last_layer = self.__input_layer\n for infos in hidden_neurons:\n # The last element of the all layers will be the bias neuron.\n layer = [Neuron(last_layer, info.weights, info.activation_function, info.activation_function_derivative) for info in infos] + [BiasNeuron()]\n last_layer = layer\n self.__hidden_layers.append(layer)\n\n # Initialize the output layer.\n self.__output_layer = [Neuron(last_layer, info.weights, info.activation_function, info.activation_function_derivative) for info in output_neurons]\n\n def __repr__(self):\n return 'input:\\n{}\\nhidden:\\n{}\\noutput:\\n{}'.format(self.__input_layer, '\\n'.join(repr(l) for l in self.__hidden_layers), self.__output_layer)\n\n def randomize(self, rng, min, max):\n \"\"\"Randomizes all the weights in the network to be in the interval [`min`, `max`).\n \n `rng` - A `numpy.random.RandomState` instance.\n `min` - The lower bound of the interval that the weigts can be in.\n `max` - The upper bound of the interval that the weigts can be in.\n \"\"\"\n for hidden_layer in self.__hidden_layers:\n NeuralNetwork.__randomize_layer(hidden_layer, rng, min, max)\n NeuralNetwork.__randomize_layer(self.__output_layer, rng, min, max)\n\n def activate(self, inputs):\n \"\"\"Activates the network by inputting all `inputs` to the input layer, activating all layers 1 by 1\n and finally returns the outputs as a 1-d array of numbers.\n \"\"\"\n # Input the values into the network.\n for input_neuron, input in zip(self.__input_layer, inputs):\n input_neuron.set_output(input)\n\n # Active the network.\n for hidden_layer in self.__hidden_layers:\n NeuralNetwork.__activate_layer(hidden_layer)\n\n NeuralNetwork.__activate_layer(self.__output_layer)\n\n # Sample the output.\n output = np.empty(len(self.__output_layer))\n for i, output_neuron in enumerate(self.__output_layer):\n output[i] = output_neuron.get_output()\n return output\n\n def train(self, inputs, desired_outputs, learning_rate, max_epochs):\n \"\"\"Trains the network using the back-propagation algorithm.\n \n `inputs` -- A 2-d array of numbers containing a set of input values to train with.\n `desired_outputs` -- A 2-d array of numbers containing the expected responses.\n `learning_rate` -- The learning rate. A ratio of the weight delta that is calculated for each weight.\n Set higher to learn faster and to escape local minima. Set lower to prevent overshooting.\n `max_loops` -- The number of training cycles that will be performed. A training cycle consists of\n doing back-propagation once for each row of `inputs`. The algorithm stops before this point if the error reaches `0`.\n \"\"\"\n error = float('inf')\n errors = np.empty(max_epochs)\n for epoch in range(max_epochs):\n error = 0\n for input, desired_output in zip(inputs, desired_outputs):\n # Run the network with the input to determine its actual output\n # This call also makes sure that the interal sum values of the neurons are up to date for this particular input sample.\n actual_output = self.activate(input)\n error += ((desired_output - actual_output) ** 2).sum()\n\n # Now compare the output to the expected response and update the network\n for neuron, actual, desired in zip(self.__output_layer, actual_output, desired_output):\n # The cost of the output neurons is (actual - desired) because this is the derivative of our cost function w.r.t the activation value of our output neurons\n # since the cost function itself is (1/2 * (desired - actual) ^ 2).\n neuron.add_cost(actual - desired)\n neuron.update(learning_rate)\n \n for layer in reversed(self.__hidden_layers):\n NeuralNetwork.__update_layer(layer, learning_rate)\n\n errors[epoch] = error\n if error == 0:\n break\n\n return errors" ]
[ [ "numpy.empty" ] ]
SherwinRF/greyatom-python-for-data-science
[ "25c1917de00e0f3c2a9b0012b169d194bd339423" ]
[ "Make-Sense-of-Census/code.py" ]
[ "# --------------\r\n# Importing header files\r\nimport numpy as np\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\n#New record\r\nnew_record=[[50, 9, 4, 1, 0, 0, 40, 0]]\r\nnew_record = np.asarray(new_record)\r\n\r\n#Reading file\r\ndata = np.genfromtxt(path, delimiter=\",\", skip_header=1)\r\n\r\n#Code starts here\r\ncensus = np.concatenate( (new_record, data) )\r\nprint(census.shape)\r\n\r\n# Operations on Country's Age\r\nage = census[:,0]\r\nmax_age = age.max()\r\nmin_age = age.min()\r\nage_mean = np.mean(age)\r\nage_std = np.std(age)\r\nprint( max_age, min_age, age_mean, age_std )\r\n\r\n# Finding Minority Race\r\nrace_0 = census[census[:,2] == 0]\r\nrace_1 = census[census[:,2] == 1]\r\nrace_2 = census[census[:,2] == 2]\r\nrace_3 = census[census[:,2] == 3]\r\nrace_4 = census[census[:,2] == 4]\r\n\r\nlen_0 = len(race_0)\r\nlen_1 = len(race_1)\r\nlen_2 = len(race_2)\r\nlen_3 = len(race_3)\r\nlen_4 = len(race_4)\r\n\r\nminority_race = 0\r\nif len_0 == min(len_0,len_1,len_2,len_3,len_4): minority_race = 0\r\nelif len_1 == min(len_0,len_1,len_2,len_3,len_4): minority_race = 1\r\nelif len_2 == min(len_0,len_1,len_2,len_3,len_4): minority_race = 2\r\nelif len_3 == min(len_0,len_1,len_2,len_3,len_4): minority_race = 3\r\nelif len_4 == min(len_0,len_1,len_2,len_3,len_4): minority_race = 4\r\nprint(minority_race)\r\n\r\n# Finding work hours of senoir citizens\r\nsenior_citizens = census[age > 60]\r\nworking_hours_sum = np.sum( senior_citizens[:,6] )\r\nsenior_citizens_len = len(senior_citizens)\r\navg_working_hours = working_hours_sum/senior_citizens_len\r\nprint(working_hours_sum, avg_working_hours)\r\n\r\n# Finding avg. high & low pay & income\r\nhigh = census[ census[:,1] > 10 ]\r\nlow = census[ census[:,1] <= 10 ]\r\navg_pay_high = np.mean(high[:,7])\r\navg_pay_low = np.mean(low[:,7])\r\nprint(avg_pay_high, avg_pay_low)\r\n" ]
[ [ "numpy.asarray", "numpy.genfromtxt", "numpy.concatenate", "numpy.std", "numpy.mean", "numpy.sum" ] ]
specmicp/relaxNMR
[ "ae37111806a91c6a0b7f4e46ac6f8877819df350" ]
[ "relaxNMR/core/ilt.py" ]
[ "# Copyright (c) 2020 Fabien Georget <[email protected]>, EPFL\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# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software without\n# 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\n# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"The inverse Laplace transform\"\"\"\n\nimport numpy as np\n\nfrom scipy.optimize import nnls\n\nfrom relaxNMR.core.signal import ComplexSignal, MagnitudeSignal,\\\n FittedSignal, FittedSignalCollection\n\n\ndef kernel_T2(tau, T):\n \"\"\"The T2 exponential decay\"\"\"\n return np.exp(-tau/T)\n\n\ndef logarithm_Tspace(Trange, nb_T):\n \"\"\"Generate a set of relaxation times logarithmically spaced.\n\n :param Trange: minimum and maximum\n :type Trange: 2-tuple\n :param nb_T: the number of discrete relaxation times, <= number of times in the signal\n :type nb_T: int\n \"\"\"\n return np.logspace(np.log10(Trange[0]), np.log10(Trange[1]), num=nb_T)\n\n\ndef ILT_fit_collection(collection, Trange, alpha, nb_T=None, kernel=kernel_T2):\n \"\"\"Fit a collection usingin the inverse Laplace transform.\n\n\n :param collection: a collection of NMR signals\n :type collection: :class:relaxNMR:core:signal:SignalCollection\n :param Trange: Minimum and maximum relaxation times\n :type Trange: 2-tuple\n :param alpha: Regularisation parameter\n :type alpha: float\n :param nb_T: the number of discrete relaxation times, <= number of times in the signal\n :type nb_T: int\n :param kernel: the kernel of the Fredholm equation\n :type kernel: function\n\n \"\"\"\n fitter = ILTFitter1D(Trange, alpha, collection[0], nb_T, kernel)\n fitted_signals = FittedSignalCollection()\n for signal in collection:\n fit, rnorm = fitter.invert(signal)\n fitted_signals.append(fit)\n return fitted_signals\n\ndef ILT_fit(signal, Trange, alpha, nb_T=None, kernel=kernel_T2):\n fitter = ILTFitter1D(Trange, alpha, signal, nb_T, kernel)\n fit, _ = fitter.invert(signal)\n return fit\n\nclass ILTFitter1D:\n \"\"\"Use this class to do a 1D inverse laplace transform.\n\n Use non-negative constraint and Tikhinov regularization.\"\"\"\n def __init__(self, Trange, alpha, signal, nb_T=None, kernel=kernel_T2):\n \"\"\"\n Create a ILT fitter. This instance will be valid for any signal with\n the same type and the same times as the provided signal.\n\n :param Trange: Minimum and maximum relaxation times\n :type Trange: 2-tuple\n :param alpha: Regularisation parameter\n :type alpha: float\n :param signal: One of the signal to invert\n :type signal: :class:relaxNMR:core:signal:Signal\n :param nb_T: the number of discrete relaxation times, <= number of times in the signal\n :type nb_T: int\n :param kernel: the kernel of the Fredholm equation\n :type kernel: function\n\n \"\"\"\n self.nb_tau = signal.size\n self.tau = signal.tau\n\n if nb_T is None:\n self.nb_T = self.nb_tau\n else:\n if nb_T > self.nb_tau:\n raise ValueError(\"The number of T2s specified is bigger than the signal\")\n self.nb_T = nb_T\n\n if isinstance(signal, ComplexSignal):\n self.has_offset = False\n else:\n self.has_offset = True\n\n self.Ts = logarithm_Tspace(Trange, self.nb_T)\n self.alpha = alpha\n self._set_kernel(signal.tau)\n\n def _set_kernel(self, tau):\n \"\"\"Create the kernel used in the fitting.\"\"\"\n nb_T = self.nb_T\n nb_tau = self.nb_tau\n\n if self.has_offset:\n K = np.zeros((nb_tau+nb_T, nb_T+1))\n else:\n K = np.zeros((nb_tau+nb_T, nb_T))\n\n for j in range(nb_T):\n K[:nb_tau, j] = kernel_T2(tau, self.Ts[j])\n\n # regularization\n K[nb_tau:, :nb_T] = np.sqrt(self.alpha) * np.eye(nb_T)\n if self.has_offset:\n K[:nb_tau, nb_T] = np.ones((nb_tau, ))\n\n self.K = K\n\n def invert(self, signal):\n \"\"\"\n Invert the signal\n\n Assume that signal is similar to the signal use to create the filter\n (i.e. similar class, similar size)\n \"\"\"\n assert(signal.size == self.nb_tau)\n rhs = np.concatenate([signal.signal, np.zeros(self.nb_T)])\n\n X, rnorm = nnls(self.K, rhs)\n As = X[:self.nb_T]\n if self.has_offset:\n offset = X[self.nb_T]\n else:\n offset = 0.0\n\n return FittedSignal(self.tau, As, self.K, self.Ts, offset=offset), rnorm\n" ]
[ [ "numpy.sqrt", "numpy.eye", "scipy.optimize.nnls", "numpy.ones", "numpy.log10", "numpy.exp", "numpy.zeros" ] ]
chenchr/PoseNet
[ "d8c0d1071db21652a7cb4b2715747ef346c8f706" ]
[ "models/PoseNetC.py" ]
[ "import torch\nimport torch.nn as nn\nimport math\nfrom corr.functions.corr import CorrFunction\n\n__all__ = [\n 'PoseNetC', 'posenetc', 'posenetc_bn'\n]\n\ndef conv(batchNorm, in_planes, out_planes, kernel_size=3, stride=1):\n if batchNorm:\n return nn.Sequential(\n nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=(kernel_size-1)//2, bias=False),\n nn.BatchNorm2d(out_planes),\n nn.LeakyReLU(0.1,inplace=True)\n )\n else:\n return nn.Sequential(\n nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=(kernel_size-1)//2, bias=True),\n nn.LeakyReLU(0.1,inplace=True)\n )\n\ndef predict_flow(in_planes):\n return nn.Conv2d(in_planes,2,kernel_size=3,stride=1,padding=1,bias=True)\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nclass PoseNetC(nn.Module):\n expansion = 1\n\n def __init__(self,batchNorm=True):\n super(PoseNetC,self).__init__()\n\n self.batchNorm = batchNorm\n self.conv1 = conv(self.batchNorm, 3, 64, kernel_size=7, stride=2)\n self.conv2 = conv(self.batchNorm, 64, 128, kernel_size=5, stride=2)\n self.conv3 = conv(self.batchNorm, 128, 256, kernel_size=5, stride=2)\n self.conv_redir = conv(self.batchNorm, 256, 32, kernel_size=1, stride=1)\n self.corr = CorrFunction(20,1,20,1,2)\n self.LU_after_corr = nn.LeakyReLU(0.1,inplace=True)\n self.conv3_1 = conv(self.batchNorm, 473, 256)\n # self.conv3_1 = conv(self.batchNorm, 441, 256)\n self.conv4 = conv(self.batchNorm, 256, 512, stride=2)\n self.conv4_1 = conv(self.batchNorm, 512, 512)\n self.conv5 = conv(self.batchNorm, 512, 512, stride=2)\n self.conv5_1 = conv(self.batchNorm, 512, 512)\n self.conv6 = conv(self.batchNorm, 512, 1024, stride=2)\n self.conv6_1 = conv(self.batchNorm,1024, 1024)\n\n self.pose_pred = nn.Conv2d(1024, 6, kernel_size=3, padding=0)\n\n self.qua_weight = nn.Parameter(torch.ones(1))\n self.t_weight = nn.Parameter(torch.ones(1))\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n nn.init.kaiming_normal(m.weight.data) # default mode is 'fan_in'\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def trainable_parameters(self):\n ll = [param for name, param in self.named_parameters() if param.requires_grad == True]\n # print(\"ll:\")\n # print(ll)\n return ll\n\n\n def forward(self, x):\n ima, imb= x[:,0:3,:,:], x[:,3:6,:,:]\n\n # print('batch shape: {}'.format(x.data.shape))\n # im_test1, im_test2 = x[0, 0:3, :, :].data.cpu().numpy(), x[0, 3:6, :, :].data.cpu().numpy()\n # im_test1, im_test2 = [np.transpose(im1, (1,2,0)) for im1 in [im_test1, im_test2]]\n # im_test1, im_test2 = [(im1 + 1)/2 for im1 in [im_test1, im_test2]]\n # print('max: {}, min: {}'.format(np.max(im_test1), np.min(im_test1)))\n # print('image shape: {}'.format(im_test1.shape))\n # plt.subplot(2,1,1)\n # plt.imshow(im_test2)\n # plt.subplot(2,1,2)\n # plt.imshow(im_test1)\n # plt.show()\n\n out_conv2a = self.conv2(self.conv1(ima))\n out_conv2b = self.conv2(self.conv1(imb))\n out_conv3_1a = self.conv3(out_conv2a)\n out_conv3_1b = self.conv3(out_conv2b)\n\n out_corr_lu = self.LU_after_corr(self.corr(out_conv3_1a, out_conv3_1b))\n out_redir = self.conv_redir(out_conv3_1a)\n concat473 = torch.cat((out_corr_lu, out_redir), 1)\n\n out_conv3 = self.conv3_1(concat473)\n # out_conv3 = self.conv3_1(out_corr_lu)\n\n out_conv4 = self.conv4_1(self.conv4(out_conv3))\n out_conv5 = self.conv5_1(self.conv5(out_conv4))\n out_conv6 = self.conv6_1(self.conv6(out_conv5))\n\n pose = self.pose_pred(out_conv6)\n pose = pose.mean(3).mean(2)\n\n return pose, self.qua_weight, self.t_weight\n\n\n\n\ndef posenetc(path=None):\n model = PoseNetC(batchNorm=False)\n if path is not None:\n data = torch.load(path)\n if 'state_dict' in data.keys():\n model.load_state_dict(data['state_dict'])\n else:\n model.load_state_dict(data)\n return model\n\ndef posenetc_bn(path=None):\n model = PoseNetC(batchNorm=True)\n if path is not None:\n data = torch.load(path)\n if 'state_dict' in data.keys():\n model.load_state_dict(data['state_dict'])\n else:\n model.load_state_dict(data)\n return model" ]
[ [ "torch.nn.init.kaiming_normal", "torch.ones", "torch.load", "torch.cat", "torch.nn.Conv2d", "torch.nn.LeakyReLU", "torch.nn.BatchNorm2d" ] ]
samgregoost/oil_spill_ocean_detection
[ "6b6f364b48081482f484a990afad7d70bf97b773" ]
[ "read_MITSceneParsingData.py" ]
[ "__author__ = 'charlie'\nimport numpy as np\nimport os\nimport random\nfrom six.moves import cPickle as pickle\nfrom tensorflow.python.platform import gfile\nimport glob\n\nimport TensorflowUtils as utils\n\n# DATA_URL = 'http://sceneparsing.csail.mit.edu/data/ADEChallengeData2016.zip'\nDATA_URL = 'http://data.csail.mit.edu/places/ADEchallenge/ADEChallengeData2016.zip'\n\n\ndef read_dataset(data_dir):\n pickle_filename = \"MITSceneParsing.pickle\"\n pickle_filepath = os.path.join(data_dir, pickle_filename)\n if not os.path.exists(pickle_filepath):\n utils.maybe_download_and_extract(data_dir, DATA_URL, is_zipfile=True)\n SceneParsing_folder = os.path.splitext(DATA_URL.split(\"/\")[-1])[0]\n result = create_image_lists(os.path.join(data_dir, SceneParsing_folder))\n print (\"Pickling ...\")\n with open(pickle_filepath, 'wb') as f:\n pickle.dump(result, f, pickle.HIGHEST_PROTOCOL)\n else:\n print (\"Found pickle file!\")\n\n with open(pickle_filepath, 'rb') as f:\n result = pickle.load(f)\n training_records = result['training']\n validation_records = result['validation']\n del result\n\n return training_records, validation_records\n\n\ndef create_image_lists(image_dir):\n if not gfile.Exists(image_dir):\n print(\"Image directory '\" + image_dir + \"' not found.\")\n return None\n directories = ['training', 'validation']\n image_list = {}\n\n for directory in directories:\n file_list = []\n image_list[directory] = []\n file_glob = os.path.join(image_dir, \"images\", directory, '*.' + 'jpg')\n file_list.extend(glob.glob(file_glob))\n\n if not file_list:\n print('No files found')\n else:\n for f in file_list:\n filename = os.path.splitext(f.split(\"\\\\\")[-1])[0]\n annotation_file = os.path.join(image_dir, \"annotations\", directory, filename + '.jpeg')\n if os.path.exists(annotation_file):\n record = {'image': f, 'annotation': annotation_file, 'filename': filename}\n image_list[directory].append(record)\n else:\n print(\"Annotation file not found for %s - Skipping\" % annotation_file)\n\n random.shuffle(image_list[directory])\n no_of_images = len(image_list[directory])\n print ('No. of %s files: %d' % (directory, no_of_images))\n\n return image_list\n" ]
[ [ "tensorflow.python.platform.gfile.Exists" ] ]
rahulrawat11/neuralmonkey
[ "8d194701448a7d318396ecf6a82eb2dc6dec9dec" ]
[ "neuralmonkey/decoders/sequence_labeler.py" ]
[ "from typing import cast, Iterable, List, Optional, Union\n\nimport tensorflow as tf\n\nfrom neuralmonkey.dataset import Dataset\nfrom neuralmonkey.model.model_part import ModelPart, FeedDict\nfrom neuralmonkey.encoders.recurrent import RecurrentEncoder\nfrom neuralmonkey.encoders.facebook_conv import SentenceEncoder\nfrom neuralmonkey.vocabulary import Vocabulary\nfrom neuralmonkey.decorators import tensor\n\n\nclass SequenceLabeler(ModelPart):\n \"\"\"Classifier assing a label to each encoder's state.\"\"\"\n\n def __init__(self,\n name: str,\n encoder: Union[RecurrentEncoder, SentenceEncoder],\n vocabulary: Vocabulary,\n data_id: str,\n dropout_keep_prob: float = 1.0,\n save_checkpoint: Optional[str] = None,\n load_checkpoint: Optional[str] = None) -> None:\n ModelPart.__init__(self, name, save_checkpoint, load_checkpoint)\n\n self.encoder = encoder\n self.vocabulary = vocabulary\n self.data_id = data_id\n self.dropout_keep_prob = dropout_keep_prob\n\n self.rnn_size = int(encoder.states.get_shape()[-1])\n self.max_output_len = self.encoder.input_sequence.max_length\n\n # pylint: disable=no-self-use\n @tensor\n def train_targets(self) -> tf.Tensor:\n return tf.placeholder(tf.int32, shape=[None, None],\n name=\"labeler_targets\")\n\n @tensor\n def train_weights(self) -> tf.Tensor:\n return tf.placeholder(tf.float32, shape=[None, None],\n name=\"labeler_padding_weights\")\n\n @tensor\n def train_mode(self) -> tf.Tensor:\n return tf.placeholder(tf.bool, name=\"train_mode\")\n # pylint: enable=no-self-use\n\n @property\n def train_loss(self) -> tf.Tensor:\n return self.cost\n\n @property\n def runtime_loss(self) -> tf.Tensor:\n return self.cost\n\n @tensor\n def cost(self) -> tf.Tensor:\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=self.train_targets, logits=self.logits)\n\n # loss is now of shape [batch, time]. Need to mask it now by\n # element-wise multiplication with weights placeholder\n weighted_loss = loss * self.train_weights\n return tf.reduce_sum(weighted_loss)\n\n @tensor\n def decoded(self) -> tf.Tensor:\n # [:, :, 1:] -- bans generating the PAD symbol (index 0 in\n # the vocabulary;\n #\n # tf.argmax(l[:, :, 1:], 2) -- argmax along the vocabulary dim\n #\n # +1 -- because the [:, :, 1:] removed a symbol from argmax\n # consideration, we need to compensate for the shortened array.\n\n # pylint: disable=unsubscriptable-object\n return tf.argmax(self.logits[:, :, 1:], 2) + 1\n # pylint: enable=unsubscriptable-object\n\n @tensor\n def logprobs(self) -> tf.Tensor:\n return tf.nn.log_softmax(self.logits)\n\n @tensor\n def logits(self) -> tf.Tensor:\n vocabulary_size = len(self.vocabulary)\n\n weights = tf.get_variable(\n name=\"state_to_word_W\",\n shape=[self.rnn_size, vocabulary_size],\n initializer=tf.random_uniform_initializer(-0.5, 0.5))\n\n biases = tf.get_variable(\n name=\"state_to_word_b\",\n shape=[vocabulary_size],\n initializer=tf.zeros_initializer())\n\n weights_direct = tf.get_variable(\n name=\"emb_to_word_W\",\n shape=[self.encoder.input_sequence.dimension, vocabulary_size],\n initializer=tf.random_uniform_initializer(-0.5, 0.5))\n\n # To multiply 3-D matrix (encoder hidden states) by a 2-D matrix\n # (weights), we use 1-by-1 convolution (similar trick can be found in\n # attention computation)\n\n # TODO dropout needs to be revisited\n\n encoder_states = tf.expand_dims(self.encoder.states, 2)\n weights_4d = tf.expand_dims(tf.expand_dims(weights, 0), 0)\n\n multiplication = tf.nn.conv2d(\n encoder_states, weights_4d, [1, 1, 1, 1], \"SAME\")\n multiplication_3d = tf.squeeze(multiplication, squeeze_dims=[2])\n\n biases_3d = tf.expand_dims(tf.expand_dims(biases, 0), 0)\n\n embedded_inputs = tf.expand_dims(self.encoder.input_sequence.data, 2)\n dweights_4d = tf.expand_dims(tf.expand_dims(weights_direct, 0), 0)\n\n dmultiplication = tf.nn.conv2d(\n embedded_inputs, dweights_4d, [1, 1, 1, 1], \"SAME\")\n dmultiplication_3d = tf.squeeze(dmultiplication, squeeze_dims=[2])\n\n logits = multiplication_3d + dmultiplication_3d + biases_3d\n return logits\n\n def feed_dict(self, dataset: Dataset, train: bool = False) -> FeedDict:\n fd = {} # type: FeedDict\n\n sentences = cast(Iterable[List[str]],\n dataset.get_series(self.data_id, allow_none=True))\n\n fd[self.train_mode] = train\n\n if sentences is not None:\n vectors, paddings = self.vocabulary.sentences_to_tensor(\n list(sentences), self.max_output_len, pad_to_max_len=False,\n train_mode=train)\n\n fd[self.train_targets] = vectors.T\n fd[self.train_weights] = paddings.T\n\n return fd\n" ]
[ [ "tensorflow.nn.log_softmax", "tensorflow.random_uniform_initializer", "tensorflow.reduce_sum", "tensorflow.zeros_initializer", "tensorflow.expand_dims", "tensorflow.placeholder", "tensorflow.squeeze", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.argmax", "tensorflow.nn.conv2d" ] ]
azadyasar/GPT2
[ "913590671d731e59815e61bb52645ee291daa970" ]
[ "src/gpt2/data/corpus.py" ]
[ "import torch\nimport threading\nimport time\nfrom gpt2.data import Dataset, VocabYTTM, VocabSP\nfrom typing import Dict, Any, List, Optional, Union\n\nclass TokenizedCorpus(Dataset):\n def __init__(self,\n corpus_path: str,\n vocab: Union[VocabSP, VocabYTTM],\n seq_len: int,\n repeat: bool = True):\n self.corpus_fp = open(corpus_path, 'r', encoding='utf-8')\n self.vocab = vocab\n self.seq_len = seq_len\n self.repeat = repeat\n self.buffer = \"\"\n self.buffer_pointer = 0\n\n def skip(self, count: int):\n for _ in range(count):\n if not self.corpus_fp.readline():\n # Raise error when all sequences are fetched.\n if not self.repeat:\n raise StopIteration()\n\n # Or, move to the first of the corpus.\n self.corpus_fp.seek(0)\n self.corpus_fp.readline()\n\n def _fetch_one(self) -> Dict[str, List[int]]:\n while True:\n # Read subword-tokenized sequence from corpus.\n line = self.corpus_fp.readline()\n if not line or len(line) == 0:\n print(f\"Consumed all of the corpus: {self.corpus_fp.name}\")\n if not self.repeat:\n raise StopIteration()\n \n print(\"Rewinding\")\n self.corpus_fp.seek(0)\n return self._fetch_one()\n indices = self.vocab.encode(line)\n if len(indices) + 2 > self.seq_len:\n indices = indices[:self.seq_len - 2]\n\n # Decorate the sequence with additional tokens.\n indices = [self.vocab.bos_idx] + indices + [self.vocab.eos_idx]\n indices += [self.vocab.pad_idx] * (self.seq_len - len(indices) + 1)\n\n return {'input': indices[:-1], 'output': indices[1:]}\n\n def fetch(self, batch: Optional[int] = None) -> Dict[str, torch.Tensor]:\n if batch is None:\n data = self._fetch_one()\n else:\n data = [self._fetch_one() for _ in range(batch)]\n data = {k: [d[k] for d in data] for k in data[0]}\n\n return {k: torch.tensor(v, dtype=torch.long) for k, v in data.items()}\n\n def where(self) -> Dict[str, Any]:\n return {'offset': self.corpus_fp.tell()}\n\n def assign(self, where: Dict[str, Any]):\n self.corpus_fp.seek(where['offset'])\n" ]
[ [ "torch.tensor" ] ]
city292/NAS-Projects
[ "b3977da52d4e017463d7019cc7fb5181b6faf87e" ]
[ "exps/vis/test.py" ]
[ "# python ./exps/vis/test.py\nimport os, sys\nfrom pathlib import Path\nimport torch\nimport numpy as np\nfrom collections import OrderedDict\nlib_dir = (Path(__file__).parent / '..' / '..' / 'lib').resolve()\nif str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir))\n\n\ndef test_nas_api():\n from nas_102_api import ArchResults\n xdata = torch.load('/home/dxy/FOR-RELEASE/NAS-Projects/output/NAS-BENCH-102-4/simplifies/architectures/000157-FULL.pth')\n for key in ['full', 'less']:\n print ('\\n------------------------- {:} -------------------------'.format(key))\n archRes = ArchResults.create_from_state_dict(xdata[key])\n print(archRes)\n print(archRes.arch_idx_str())\n print(archRes.get_dataset_names())\n print(archRes.get_comput_costs('cifar10-valid'))\n # get the metrics\n print(archRes.get_metrics('cifar10-valid', 'x-valid', None, False))\n print(archRes.get_metrics('cifar10-valid', 'x-valid', None, True))\n print(archRes.query('cifar10-valid', 777))\n\nif __name__ == '__main__':\n test_nas_api()\n" ]
[ [ "torch.load" ] ]
Online-Trio/projecide_squad
[ "58d8bcd64240d9d8d2b918564e4558ed6eee4ecd" ]
[ "compute_answers_files/model_qa_prediction.py" ]
[ "from settings_file import *\nimport nltk\nfrom tensorflow.python.ops import math_ops, nn_ops\nfrom nltk.corpus import stopwords\nimport spacy\ntry:\n nlp = spacy.load(\"en_core_web_lg\")\nexcept:\n spacy.cli.download(\"en_core_web_lg\")\n nlp = spacy.load(\"en_core_web_lg\")\n\nTOP_K_ANSWERS = 4\nMAX_ANSWER_LEN = 18 # empirically observed from training set\n\n\"\"\"\nWhenever a custom object is defined (custom loss function in our case), Tensorflow requires to know the definition of \nthat object before loading the model. So if model.compile() contains custom_loss_fn then it must appear in a dictionary\nwith the same name and definition to be passed as argument to model.load(). \nThe two functions below are copied from base_project/src/model_definition.py only for this purpose. More info there. \n\"\"\"\n\ndef weighted_cross_entropy_with_logits_modified(labels, logits, pos_weight, neg_weights, name=None):\n log_weight = neg_weights + (pos_weight - neg_weights) * labels\n return math_ops.add(\n (1 - labels) * logits * neg_weights,\n log_weight * (math_ops.log1p(math_ops.exp(-math_ops.abs(logits))) +\n nn_ops.relu(-logits)), # pylint: disable=invalid-unary-operand-type\n name=name)\n\ndef custom_loss_fn(y_true, y_pred):\n pos_weight = tf.constant(1.0)\n neg_weight = tf.constant(0.0)\n bn_crossentropy = weighted_cross_entropy_with_logits_modified(y_true, y_pred, pos_weight, neg_weight)\n return tf.reduce_mean(bn_crossentropy, axis=-1)\n\ncustom_objects = {'custom_loss_fn': custom_loss_fn}\n\n\ndef load_model():\n print()\n print(\"Loading model...\")\n cwd = os.getcwd()\n model = tf.keras.models.load_model(cwd + UTILS_ROOT + \"saved_model\", custom_objects=custom_objects)\n print(\"Model loaded!\")\n return model\n\n\"\"\"\nSTOPWORDS are defined to better evaluate the similarity between different answers proposals and question.\n\"\"\"\n\ntry:\n STOPWORDS = set(stopwords.words('english'))\nexcept LookupError:\n nltk.download('stopwords')\n STOPWORDS = set(stopwords.words('english'))\n\n\ndef remove_stopwords(text: str) -> str:\n return ' '.join([x for x in text.split() if x and x not in STOPWORDS])\n\n\n# Load the pre-trained model and make predictions\ndef make_predictions(model, input_df, x_input_context, x_input_pos_enc, x_input_match, x_input_question):\n\n \"\"\"\n Predict a probability for each sample with the pre-trained model\n \"\"\"\n print(\"Make predictions...\")\n y_start, y_end = model.predict((x_input_context, x_input_pos_enc, x_input_match, x_input_question))\n predicted_start_indexes = []\n predicted_end_indexes = []\n for i in range(len(input_df)):\n indexes_start = np.argsort(y_start[i, :])[-TOP_K_ANSWERS:]\n indexes_end = np.argsort(y_end[i, :])[-TOP_K_ANSWERS:]\n predicted_start_indexes.append(indexes_start)\n predicted_end_indexes.append(indexes_end)\n\n \"\"\"\n Create all the possible [start, end] indexes for each context picked from the TOP_K starts and ends.\n Check start <= end. Check that the answer is no more than 25 words\n \"\"\"\n span_candidates = []\n for sample_id in range(len(input_df)):\n sample_candidates = []\n for i in range(TOP_K_ANSWERS):\n for j in range(TOP_K_ANSWERS):\n if predicted_start_indexes[sample_id][i] <= predicted_end_indexes[sample_id][j] and predicted_end_indexes[sample_id][j] - predicted_start_indexes[sample_id][i] < MAX_ANSWER_LEN:\n sample_candidates.append([predicted_start_indexes[sample_id][i], predicted_end_indexes[sample_id][j]])\n span_candidates.append(sample_candidates)\n\n \"\"\"\n Evaluate the [start, end] tuple based on the similarity between the question and the extracted sentence.\n \"\"\"\n print(\"Choose the best answer\")\n best_couples_list = []\n for sample_id in tqdm.tqdm(range(len(input_df))):\n question_encoding = nlp(remove_stopwords(input_df.loc[sample_id, 'question']))\n best_couple = [0, 0] # starting couple only for debug purposes\n best_sim = 0\n for couple in span_candidates[sample_id]:\n # extract a sentence from indexes\n sentence_extraction = ' '.join((input_df.loc[sample_id, 'context'].split(' '))[int(couple[0]):int(couple[1]) + 1])\n sentence_encoding = nlp(remove_stopwords(sentence_extraction))\n try:\n # verify the similarity between the current answer and the question\n sim = question_encoding.similarity(sentence_encoding)\n if sim > best_sim:\n best_sim = sim\n best_couple = couple\n except UserWarning:\n pass\n best_couples_list.append(best_couple)\n return best_couples_list\n\n\ndef format_predictions(input_df, best_couples_list):\n \"\"\"\n 'input_df' : the original dataframe to extract the answer text from start and end indexes.\n 'best_couples_list' : list of pairs containing, for each query, the start and the end index of the answer in the relative context\n\n return: ordered list of start-end index answer. Return a dict {id: answer}-like\n \"\"\"\n predictions_pairs = []\n for i, row in input_df.iterrows():\n list_of_words = row['context'].split()\n selected_words = list_of_words[best_couples_list[i][0]:best_couples_list[i][1] + 1]\n build_sentence = ' '.join(selected_words)\n predictions_pairs.append((row['id'], build_sentence))\n return predictions_pairs\n\n\ndef predict(model, input_df, x_input_context, x_input_pos_enc, x_input_match, x_input_question):\n best_couples_list = make_predictions(model, input_df, x_input_context, x_input_pos_enc, x_input_match, x_input_question)\n predictions_pairs = format_predictions(input_df, best_couples_list)\n return dict(predictions_pairs)\n\n" ]
[ [ "tensorflow.python.ops.math_ops.abs", "tensorflow.python.ops.nn_ops.relu" ] ]
charnley/bayes-mndo
[ "38662dd738af7cba73f98ffacc5c719aaa9a036d" ]
[ "src/hmc_optim.py" ]
[ "# %%\nimport json\nimport os\nimport pathlib\nfrom datetime import datetime\nfrom functools import partial\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom chemhelp import mndo, units\nfrom data import load_data, prepare_params\nfrom hmc_utils import get_nuts_kernel, sample_chain, trace_fn_nuts\nfrom objective import jacobian_parallel, penalty\n\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n\nmols_atoms, mols_coords, _, _, reference = load_data(query_size=100, offset=110)\nref_energies = reference[\"binding_energy\"].values\n\n# Switch from Hartree to KCal/Mol\nref_energies *= units.hartree_to_kcalmol\n\ndh = 1e-5\nn_procs = 2\nmethod = \"MNDO\"\n\n# NOTE we probably can refactor to remove the duplication of input files\nfilename = \"_tmp_molecules\"\nscrdir = \"_tmp_optim\"\n\npathlib.Path(scrdir).mkdir(parents=True, exist_ok=True)\n\n# TODO JCK At some point we need to evaluate non-zero molecules\nn_molecules = len(mols_atoms)\nmols_charges = np.zeros(n_molecules)\nmols_names = np.arange(n_molecules)\n\nmndo.write_input_file(\n mols_atoms,\n mols_coords,\n mols_charges,\n mols_names,\n method,\n os.path.join(scrdir, filename),\n read_params=True,\n)\n\n# %%\nwith open(\"parameters/parameters-mndo-mean.json\", \"r\") as f:\n mean_params = json.loads(f.read())\n\nwith open(\"parameters/parameters-mndo-std.json\", \"r\") as f:\n scale_params = json.loads(f.read())\n\nparam_keys, _ = prepare_params(mols_atoms, mean_params)\nparam_values = [tf.random.truncated_normal([], stddev=1.0) for _ in param_keys]\n\nroot = os.path.abspath(__file__).split(\"/src\", 1)[0]\n\nkwargs = {\n \"param_keys\": param_keys,\n \"filename\": filename,\n \"n_procs\": n_procs,\n \"dh\": dh,\n \"ref_props\": ref_energies,\n \"mean_params\": mean_params,\n \"scale_params\": scale_params,\n \"binary\": root + \"/mndo/mndo99_binary\",\n \"scr\": scrdir,\n}\n\n# %%\[email protected]_gradient\ndef target_log_prob_fn(*param_vals):\n log_likelihood = -penalty(param_vals, **kwargs)\n\n def grad_fn(*dys):\n # grad = jacobian(param_vals, **kwargs)\n grad = jacobian_parallel(param_vals, **kwargs)\n return grad.tolist()\n\n return log_likelihood, grad_fn\n\n\ndef real_target_log_prob_fn(*param_vals):\n res = tf.py_function(target_log_prob_fn, inp=param_vals, Tout=tf.float64)\n # Avoid tripping up sample_chain due to loss of output shape in tf.py_function\n # when used in a tf.function context. https://tinyurl.com/y9ttqdpt\n res.set_shape(param_vals[0].shape[:-1]) # assumes parameter is vector-valued\n return res\n\n\n# %%\nstep_size = tf.cast(5e-3, tf.float64)\nn_adapt_steps = 100\n\n# with tf.GradientTape() as tape:\n# tape.watch(param_values)\n# lp = real_target_log_prob_fn(*param_values)\n# print(tape.gradient(lp, param_values))\n\n# %%\nnow = datetime.now().strftime(\"%Y.%m.%d-%H:%M:%S\")\nlog_dir = f\"runs/hmc-mndo/{now}\"\nsummary_writer = tf.summary.create_file_writer(log_dir)\n\n# %%\nchain, trace, final_kernel_results = sample_chain(\n num_results=30,\n current_state=param_values,\n kernel=get_nuts_kernel(real_target_log_prob_fn, step_size, n_adapt_steps),\n return_final_kernel_results=True,\n trace_fn=partial(trace_fn_nuts, summary_writer=summary_writer),\n)\n\nwith open(\"parameters/parameters-opt-hmc.json\", \"w\") as f:\n json.dump([list(x) for x in chain], f)\n" ]
[ [ "tensorflow.random.truncated_normal", "numpy.arange", "tensorflow.cast", "tensorflow.py_function", "numpy.zeros", "tensorflow.summary.create_file_writer" ] ]
ovvladimir/Opencv_two_cameras
[ "d4ba432aff78db133396ccfc04073ea9374b13ef" ]
[ "main.py" ]
[ "import numpy as np\nimport argparse\nimport pickle\nimport cv2\nimport os\nfrom threading import Thread\nimport pyttsx3\n\nfrom usbcamvideostream import USBCamVideoStream\nfrom fps import FPS\n\nfps = FPS().start()\nblock = True\nname = None\nframes = []\n\n\ndef voice():\n if os.name == 'nt':\n engine = pyttsx3.init(driverName='sapi5')\n engine.say('О-о! Привет, Владимир!')\n engine.runAndWait()\n else:\n # os.system(\"echo 'О! Привет Владимир!' | RHVoice-test -p Aleksandr\")\n os.system(\"spd-say -o rhvoice -y Aleksandr -r 30 -w 'О-о! Привет, Владимир!'\")\n\n\nap = argparse.ArgumentParser()\nap.add_argument(\n \"-d\", \"--detector\", # required=True,\n default='face_detection_model',\n help=\"path to OpenCV's deep learning face detector\")\nap.add_argument(\n \"-m\", \"--embedding-model\", # required=True,\n default='face_embedding_model/openface_nn4.small2.v1.t7',\n help=\"path to OpenCV's deep learning face embedding model\")\nap.add_argument(\n \"-r\", \"--recognizer\", # required=True,\n default='output/recognizer.pickle',\n help=\"path to model trained to recognize faces\")\nap.add_argument(\n \"-l\", \"--le\", # required=True,\n default='output/le.pickle',\n help=\"path to label encoder\")\nap.add_argument(\n \"-c\", \"--confidence\", type=float, default=0.5,\n help=\"minimum probability to filter weak detections\")\nargs = vars(ap.parse_args())\n\nconfidence_ = args[\"confidence\"]\nprint(\"[INFO] загрузка детектора лица...\")\nprotoPath = os.path.sep.join([args[\"detector\"], \"deploy.prototxt\"])\nmodelPath = os.path.sep.join([args[\"detector\"], \"res10_300x300_ssd_iter_140000.caffemodel\"])\ndetector = cv2.dnn.readNetFromCaffe(protoPath, modelPath)\nprint(\"[INFO] загрузка распознавателя лица...\")\nembedder = cv2.dnn.readNetFromTorch(args[\"embedding_model\"])\nrecognizer = pickle.loads(open(args[\"recognizer\"], \"rb\").read())\nle = pickle.loads(open(args[\"le\"], \"rb\").read())\nprint(\"[INFO] запуск видео потока...\")\n\nleft_eye = USBCamVideoStream(src=0).start()\nright_eye = USBCamVideoStream(src=1).start() # для raspberry src=2\ncv2.waitKey(1000)\n\nrun = True\n'''\nif not right_eye.stream.isOpened():\n print('[ERROR] не работает правая камера')\n run = False\nif not left_eye.stream.isOpened():\n print('[ERROR] не работает левая камера')\n run = False\n'''\nwidth = 960\nh, w = 480, 640\n# h, w = left_eye.frame.shape[:2]\nw, h = (width, int(h * width / float(w)))\n\nwhile run:\n frames.clear()\n for streams in (left_eye, right_eye):\n if not streams.ret:\n break\n frame = streams.retrieves()\n frame = cv2.resize(frame, (w, h)) # interpolation=cv2.INTER_AREA\n frames.append(frame)\n\n imageBlob = cv2.dnn.blobFromImage(\n cv2.resize(frame, (300, 300)), 1.0, (300, 300),\n (104.0, 177.0, 123.0), swapRB=False, crop=False)\n\n detector.setInput(imageBlob)\n detections = detector.forward()\n\n for i in range(detections.shape[2]):\n confidence = detections[0, 0, i, 2]\n if confidence > confidence_:\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n face = frame[startY:endY, startX:endX]\n (fH, fW) = face.shape[:2]\n if fW < 20 or fH < 20:\n continue\n faceBlob = cv2.dnn.blobFromImage(cv2.resize(\n face, (96, 96)), 1.0 / 255, (96, 96), (0, 0, 0), swapRB=True, crop=False)\n embedder.setInput(faceBlob)\n vec = embedder.forward()\n preds = recognizer.predict_proba(vec)[0]\n j = np.argmax(preds)\n proba = preds[j]\n name = le.classes_[j]\n text = \"{}: {:.2f}%\".format(name, proba * 100)\n y = startY - 10 if startY - 10 > 10 else startY + 10\n # cv2.rectangle(frame, (startX, startY), (endX, endY), (255, 0, 0), 2)\n # cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 0, 0), 2)\n\n fps.update()\n for (frameW, nameW) in zip(frames, (\"Left Eye\", \"Right Eye\")):\n cv2.imshow(nameW, frameW)\n key = cv2.waitKey(1) & 0xFF\n if key == 27:\n break\n\n if name == 'vladimir' and proba > 0.8 and block:\n Thread(target=voice, name='voice').start()\n block = False\n\nfps.stop()\nprint(\"[INFO] пройденное время: {:.2f}\".format(fps.elapsed()))\nprint(\"[INFO] приблизительно FPS: {:.2f}\".format(fps.fps()))\n\ncv2.destroyAllWindows()\nleft_eye.stop()\nright_eye.stop()\n" ]
[ [ "numpy.array", "numpy.argmax" ] ]