class_docstr: Natural Policy Gradient Optimization.
  
  Args:
      env_spec (EnvSpec): Environment specification.
      policy (garage.tf.policies.StochasticPolicy): Policy.
      baseline (garage.tf.baselines.Baseline): The baseline.
      sampler (garage.sampler.Sampler): Sampler.
      scope (str): Scope for identifying the algorithm.
          Must be specified if running multiple algorithms
          simultaneously, each using different environments
          and policies.
      discount (float): Discount.
      gae_lambda (float): Lambda used for generalized advantage
          estimation.
      center_adv (bool): Whether to rescale the advantages
          so that they have mean 0 and standard deviation 1.
      positive_adv (bool): Whether to shift the advantages
          so that they are always positive. When used in
          conjunction with center_adv the advantages will be
          standardized before shifting.
      fixed_horizon (bool): Whether to fix horizon.
      pg_loss (str): A string from: 'vanilla', 'surrogate',
          'surrogate_clip'. The type of loss functions to use.
      lr_clip_range (float): The limit on the likelihood ratio between
          policies, as in PPO.
      max_kl_step (float): The maximum KL divergence between old and new
          policies, as in TRPO.
      optimizer (object): The optimizer of the algorithm. Should be the
          optimizers in garage.tf.optimizers.
      optimizer_args (dict): The arguments of the optimizer.
      policy_ent_coeff (float): The coefficient of the policy entropy.
          Setting it to zero would mean no entropy regularization.
      use_softplus_entropy (bool): Whether to estimate the softmax
          distribution of the entropy to prevent the entropy from being
          negative.
      use_neg_logli_entropy (bool): Whether to estimate the entropy as the
          negative log likelihood of the action.
      stop_entropy_gradient (bool): Whether to stop the entropy gradient.
      entropy_method (str): A string from: 'max', 'regularized',
          'no_entropy'. The type of entropy method to use. 'max' adds the
          dense entropy to the reward for each time step. 'regularized' adds
          the mean entropy to the surrogate objective. See
          https://arxiv.org/abs/1805.00909 for more details.
      name (str): The name of the algorithm.
  
  Note:
      sane defaults for entropy configuration:
          - entropy_method='max', center_adv=False, stop_gradient=True
            (center_adv normalizes the advantages tensor, which will
            significantly alleviate the effect of entropy. It is also
            recommended to turn off entropy gradient so that the agent
            will focus on high-entropy actions instead of increasing the
            variance of the distribution.)
          - entropy_method='regularized', stop_gradient=False,
            use_neg_logli_entropy=False
docstr: Build policy loss and other output tensors.
  
  Args:
      i (namedtuple): Collection of variables to compute policy loss.
  
  Returns:
      tf.Tensor: Policy loss.
      tf.Tensor: Mean policy KL divergence.
docstr_tok: ["Build","policy","loss","and","other","output","tensors",".","Args",":","i","(","namedtuple",")",":","Collection","of","variables","to","compute","policy","loss",".","Returns",":","tf.Tensor",":","Policy","loss",".","tf.Tensor",":","Mean","policy","KL","divergence","."]
code: def _build_policy_loss(self, i):
      """Build policy loss and other output tensors.
  
      Args:
          i (namedtuple): Collection of variables to compute policy loss.
  
      Returns:
          tf.Tensor: Policy loss.
          tf.Tensor: Mean policy KL divergence.
  
      """
      policy_entropy = self._build_entropy_term(i)
      rewards = i.reward_var
  
      if self._maximum_entropy:
          with tf.name_scope("augmented_rewards"):
              rewards = i.reward_var + (
                  self._policy_ent_coeff * policy_entropy
              )
  
      with tf.name_scope("policy_loss"):
          adv = compute_advantages(
              self._discount,
              self._gae_lambda,
              self.max_episode_length,
              i.baseline_var,
              rewards,
              name="adv",
          )
  
          adv = tf.reshape(adv, [-1, self.max_episode_length])
          # Optionally normalize advantages
          eps = tf.constant(1e-8, dtype=tf.float32)
          if self._center_adv:
              adv = center_advs(adv, axes=[0], eps=eps)
  
          if self._positive_adv:
              adv = positive_advs(adv, eps)
  
          old_policy_dist = self._old_policy_network.dist
          policy_dist = self._policy_network.dist
  
          with tf.name_scope("kl"):
              kl = old_policy_dist.kl_divergence(policy_dist)
              pol_mean_kl = tf.reduce_mean(kl)
  
          # Calculate vanilla loss
          with tf.name_scope("vanilla_loss"):
              ll = policy_dist.log_prob(
                  i.action_var, name="log_likelihood"
              )
              vanilla = ll * adv
  
          # Calculate surrogate loss
          with tf.name_scope("surrogate_loss"):
              lr = tf.exp(ll - old_policy_dist.log_prob(i.action_var))
              surrogate = lr * adv
  
          # Finalize objective function
          with tf.name_scope("loss"):
              if self._pg_loss == "vanilla":
                  # VPG uses the vanilla objective
                  obj = tf.identity(vanilla, name="vanilla_obj")
              elif self._pg_loss == "surrogate":
                  # TRPO uses the standard surrogate objective
                  obj = tf.identity(surrogate, name="surr_obj")
              elif self._pg_loss == "surrogate_clip":
                  lr_clip = tf.clip_by_value(
                      lr,
                      1 - self._lr_clip_range,
                      1 + self._lr_clip_range,
                      name="lr_clip",
                  )
                  surr_clip = lr_clip * adv
                  obj = tf.minimum(
                      surrogate, surr_clip, name="surr_obj"
                  )
  
              if self._entropy_regularzied:
                  obj += self._policy_ent_coeff * policy_entropy
  
              # filter only the valid values
              obj = tf.boolean_mask(obj, i.valid_var)
              # Maximize E[surrogate objective] by minimizing
              # -E_t[surrogate objective]
              loss = -tf.reduce_mean(obj)
  
          # Diagnostic functions
          self._f_policy_kl = (
              tf.compat.v1.get_default_session().make_callable(
                  pol_mean_kl,
                  feed_list=flatten_inputs(self._policy_opt_inputs),
              )
          )
  
          self._f_rewards = (
              tf.compat.v1.get_default_session().make_callable(
                  rewards,
                  feed_list=flatten_inputs(self._policy_opt_inputs),
              )
          )
  
          returns = discounted_returns(
              self._discount, self.max_episode_length, rewards
          )
          self._f_returns = (
              tf.compat.v1.get_default_session().make_callable(
                  returns,
                  feed_list=flatten_inputs(self._policy_opt_inputs),
              )
          )
  
          return loss, pol_mean_kl
  
imports: import collections
  from dowel import logger, tabular
  import numpy
  import tensorflow
  from garage import log_performance, make_optimizer
  from garage.np import explained_variance_1d, pad_batch_array
  from garage.np.algos import RLAlgorithm
  from garage.tf import center_advs, compile_function, compute_advantages, discounted_returns, flatten_inputs, graph_inputs, positive_advs
  from garage.tf.optimizers import FirstOrderOptimizer
label_desc: Use image node_id 7 for calling the NPO obj's underlying member method code with example usage: obj._build_policy_loss(i) and returns: loss,  pol_mean_kl