r"""Log transform a dense tensor

    See `tf.log()` in tensorflow.

    Args:
      tensor: A `Tensor` ( automatically given by chain )
      opt:
        name: If provided, replace current tensor's name.

    Returns:
        A `Tensor`.
494567
def sg_log(tensor, opt):
    
    """
    return tf.log(tensor + tf.sg_eps, name=opt.name)
939871
def load(filename, compressed=True, prealloc=None):
        
        # switch load based on file ext
        _, file_ext = os.path.splitext(filename)
        if compressed:
            if file_ext != COMPRESSED_TENSOR_EXT:
                raise ValueError('Can only load compressed tensor with %s extension' %(COMPRESSED_TENSOR_EXT))
            data = np.load(filename)['arr_0']
        else:
            if file_ext != TENSOR_EXT:
                raise ValueError('Can only load tensor with .npy extension')
            data = np.load(filename)
            
        # fill prealloc tensor
        if prealloc is not None:
            prealloc.reset()
            prealloc.add_batch(data)
            return prealloc
            
        # init new tensor
        tensor = Tensor(data.shape, data.dtype, data=data)
        return tensor
1302554
def reconstruct(self, t:Tensor, x:Tensor=None):
        ""
        return self[0].reconstruct(t,x) if has_arg(self[0].reconstruct, 'x') else self[0].reconstruct(t)
745126
def shape(tensor):
    '''
    
    '''
    temp_s = tensor.get_shape()
    return tuple([temp_s[i].value for i in range(0, len(temp_s))])
168004
def write_numpy_to_dense_tensor(file, array, labels=None):
    """"""

    # Validate shape of array and labels, resolve array and label types
    if not len(array.shape) == 2:
        raise ValueError("Array must be a Matrix")
    if labels is not None:
        if not len(labels.shape) == 1:
            raise ValueError("Labels must be a Vector")
        if labels.shape[0] not in array.shape:
            raise ValueError("Label shape {} not compatible with array shape {}".format(
                             labels.shape, array.shape))
        resolved_label_type = _resolve_type(labels.dtype)
    resolved_type = _resolve_type(array.dtype)

    # Write each vector in array into a Record in the file object
    record = Record()
    for index, vector in enumerate(array):
        record.Clear()
        _write_feature_tensor(resolved_type, record, vector)
        if labels is not None:
            _write_label_tensor(resolved_label_type, record, labels[index])
        _write_recordio(file, record.SerializeToString())
472051
def _as_graph_element(self):
    """"""
    if self.is_sequence():
      raise TypeError('A Pretty Tensor that holds a sequence cannot be '
                      'represented as a graph element.')
    else:
      # Self might be holding something else that isn't a true tensor, so
      # if the 'tensor' can behave like a graph element, look for its
      # _AsGraphElement method and call it. Graph elements themselves may not
      # have or need this method, so just return other items directly.
      obj = self.tensor
      conv_fn = getattr(obj, '_as_graph_element', None)
      if conv_fn and isinstance(conv_fn, collections.Callable):
        obj = conv_fn()
      return obj
224123
def _call(self, x):
        """"""
        result = self.sess.run(self.output_tensor,
                               feed_dict={self.input_tensor: np.asarray(x)})

        return result
1004246
def _dtype(cls, tensor: tf.Tensor) -> tf.Tensor:
        ''''''
        if tensor.dtype != tf.float32:
            tensor = tf.cast(tensor, tf.float32)
        return tensor
350567
def create_tensorprod_function(funcs):
    """"""
    dim = len(funcs)

    def tensprod_rule(order, part=None):
        """Tensor product rule."""
        order = order*numpy.ones(dim, int)
        values = [funcs[idx](order[idx]) for idx in range(dim)]

        abscissas = [numpy.array(_[0]).flatten() for _ in values]
        abscissas = chaospy.quad.combine(abscissas, part=part).T

        weights = [numpy.array(_[1]).flatten() for _ in values]
        weights = numpy.prod(chaospy.quad.combine(weights, part=part), -1)

        return abscissas, weights

    return tensprod_rule
1134096
def set_tensor_final(self, tensor_name):
    
    tensor = self._name_to_tensor(tensor_name)
    self._final_tensors.add(tensor)
349059
def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None):
    """"""
    del weight_collections
    text_batch = tf.reshape(inputs.get(self), shape=[-1])
    m = module.Module(self.module_spec, trainable=self.trainable and trainable)
    return m(text_batch)
1082336
def cumprod_to_tensor_axis(self, cumprod):
    """"""
    try:
      return len(self) - 1 - self.cumprod[::-1].index(cumprod)
    except ValueError:
      return None
307308
def _summary(self, name, tensor):
    
    if tensor.shape.ndims == 0:
      return tf.summary.scalar(name, tensor)
    else:
      return tf.summary.histogram(name, tensor)
844667
def dense(x, units, **kwargs):
  """"""
  layer_collection = kwargs.pop("layer_collection", None)
  activations = layers().Dense(units, **kwargs)(x)
  if layer_collection:
    # We need to find the layer parameters using scope name for the layer, so
    # check that the layer is named. Otherwise parameters for different layers
    # may get mixed up.
    layer_name = tf.get_variable_scope().name
    if (not layer_name) or ("name" not in kwargs):
      raise ValueError(
          "Variable scope and layer name cannot be empty. Actual: "
          "variable_scope={}, layer name={}".format(
              layer_name, kwargs.get("name", None)))

    layer_name += "/" + kwargs["name"]
    layer_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,
                                     scope=layer_name)
    assert layer_params
    if len(layer_params) == 1:
      layer_params = layer_params[0]

    tf.logging.info(
        "Registering dense layer to collection for tensor: {}".format(
            layer_params))

    x_shape = x.shape.as_list()
    if len(x_shape) == 3:
      # Handle [batch, time, depth] inputs by folding batch and time into
      # one dimension: reshaping inputs to [batchxtime, depth].
      x_2d = tf.reshape(x, [-1, x_shape[2]])
      activations_shape = activations.shape.as_list()
      activations_2d = tf.reshape(activations, [-1, activations_shape[2]])
      layer_collection.register_fully_connected_multi(
          layer_params, x_2d, activations_2d, num_uses=x_shape[1])
      activations = tf.reshape(activations_2d, activations_shape)
    else:
      layer_collection.register_fully_connected(layer_params, x, activations)
  return activations
759880
def tensor_layout(self, arg):
    
    if isinstance(arg, Tensor):
      arg = arg.shape
    return self.layout_rules.tensor_layout(arg, self.shape)
608715
def forward(self,
                inputs: torch.Tensor,
                tags: torch.Tensor,
                mask: torch.ByteTensor = None) -> torch.Tensor:
        
        # pylint: disable=arguments-differ
        if mask is None:
            mask = torch.ones(*tags.size(), dtype=torch.long)

        log_denominator = self._input_likelihood(inputs, mask)
        log_numerator = self._joint_likelihood(inputs, tags, mask)

        return torch.sum(log_numerator - log_denominator)
558780
def _output(cls, fluents: Sequence[FluentPair]) -> Sequence[tf.Tensor]:
        ''''''
        output = []
        for _, fluent in fluents:
            tensor = fluent.tensor
            if tensor.dtype != tf.float32:
                tensor = tf.cast(tensor, tf.float32)
            output.append(tensor)
        return tuple(output)