Convert a {@link INDArray}
to a {@link TF_Tensor}
using zero copy.
It will use the underlying
pointer with in nd4j.
@param tensor the tensor to use
@return
326428
public INDArray ndArrayFromTensor(TF_Tensor tensor) {
        int rank = TF_NumDims(tensor);

        int[] ndShape;
        if (rank == 0) {
            // scalar
            ndShape = new int[] { 1 };
        } else {
            ndShape = new int[rank];
            for (int i = 0; i < ndShape.length; i++) {
                ndShape[i] = (int) TF_Dim(tensor,i);
            }
        }

        int tfType = TF_TensorType(tensor);
        DataType nd4jType = typeFor(tfType);

        int length = ArrayUtil.prod(ndShape);
        INDArray array;
        if (nd4jType == DataType.UTF8) {
            String[] strings = new String[length];
            BytePointer data = new BytePointer(TF_TensorData(tensor)).capacity(TF_TensorByteSize(tensor));
            BytePointer str = new BytePointer((Pointer)null);
            SizeTPointer size = new SizeTPointer(1);
            TF_Status status = TF_NewStatus();
            for (int i = 0; i < length; i++) {
                long offset = data.position(8 * i).getLong();
                TF_StringDecode(data.position(8 * length + offset), data.capacity() - data.position(), str, size, status);
                if (TF_GetCode(status) != TF_OK) {
                    throw new IllegalStateException("ERROR: Unable to convert tensor " + TF_Message(status).getString());
                }
                strings[i] = str.position(0).capacity(size.get()).getString();
            }
            TF_DeleteStatus(status);
            array = Nd4j.create(strings);
        } else {
            Pointer pointer = TF_TensorData(tensor).capacity(length);
            Indexer indexer = indexerForType(nd4jType,pointer);
            DataBuffer d = Nd4j.createBuffer(indexer.pointer(),nd4jType,length,indexer);
            array = Nd4j.create(d,ndShape);
        }
        Nd4j.getAffinityManager().tagLocation(array, AffinityManager.Location.HOST);
        return array;
    }
57309
public static INDArray ndArrayDimFromInt(int... dimensions){
        if (dimensions == null || dimensions.length == 0)
            return Nd4j.empty(DataType.INT);
        else
            return Nd4j.createFromArray(dimensions);
    }
1173545
public Tensor forward() {
        VarTensor[] varBeliefs = inf.getOutput().varBeliefs;
        double l2dist = s.zero();

        for (Var v : vc.getVars()) {
            if (v.getType() == VarType.PREDICTED) {
                VarTensor marg = varBeliefs[v.getId()];
                int goldState = vc.getState(v);
                for (int c=0; c<marg.size(); c++) {
                    double goldMarg = (c == goldState) ? s.one() : s.zero();
                    double predMarg = marg.getValue(c);
                    double diff = s.minus(Math.max(goldMarg, predMarg), Math.min(goldMarg, predMarg));
                    l2dist = s.plus(l2dist, s.times(diff, diff));
                }
            }
        }
        if (s.lt(l2dist, s.zero())) {
            log.warn("L2 distance shouldn't be less than 0: " + l2dist);
        }
        y = Tensor.getScalarTensor(s, l2dist);
        return y;        
    }
106848
@Override
    public Tensor forward() {
        Tensor x = modInX.getOutput();
        Tensor w = modInW.getOutput();
        y = new Tensor(x); // copy
        y.elemMultiply(w);
        return y;
    }
120061
def export_to_tf_tensor(self, x, laid_out_x):
    
    return self.combine_slices(laid_out_x.all_slices, x.shape)
1372953
def zeroed(self, tol=1e-3):
        
        new_tensor = self.copy()
        new_tensor[abs(new_tensor) < tol] = 0
        return new_tensor
1055196
private Tensor getMsgs(VarTensor[] inMsgs, int tf) {
        Algebra s = inMsgs[0].getAlgebra();
        EdgeScores es = new EdgeScores(n, s.zero());
        for (VarTensor inMsg : inMsgs) {
            LinkVar link = (LinkVar) inMsg.getVars().get(0);            
            double val = inMsg.getValue(tf);
            es.setScore(link.getParent(), link.getChild(), val);
        }
        return es.toTensor(s);
    }
1076725
private DenseTensor fastInnerProductRightAligned(Tensor other, long maxKeyNum, long keyNumIncrement, 
      int[] newDims, int[] newSizes) {        
    DenseTensorBuilder resultBuilder = new DenseTensorBuilder(newDims, newSizes);
    int otherSize = other.size();
    double[] otherValues = other.getValues();
    // Iterate over the keys of this, then (hopefully sparsely) iterate over the 
    // keys of {@code other},
    double innerProd;
    int otherIndex;
    int finalIndex = (int) (maxKeyNum / keyNumIncrement);
    long myKeyNum;
    for (int i = 0; i < finalIndex; i++) {
      myKeyNum = i * keyNumIncrement;
      innerProd = 0.0;
      for (otherIndex = 0; otherIndex < otherSize; otherIndex++) {
        long otherKeyNum = other.indexToKeyNum(otherIndex);
        double otherValue = otherValues[otherIndex];
        innerProd += values[(int) (myKeyNum + otherKeyNum)] * otherValue;
      }
      resultBuilder.putByKeyNum(i, innerProd);
    }
    return resultBuilder.buildNoCopy();
  }
134794
def to_array(tensor):  # type: (TensorProto) -> np.ndarray[Any]
    
    if tensor.HasField("segment"):
        raise ValueError(
            "Currently not supporting loading segments.")
    if tensor.data_type == TensorProto.UNDEFINED:
        raise ValueError("The data type is not defined.")

    tensor_dtype = tensor.data_type
    np_dtype = mapping.TENSOR_TYPE_TO_NP_TYPE[tensor_dtype]
    storage_type = mapping.TENSOR_TYPE_TO_STORAGE_TENSOR_TYPE[tensor_dtype]
    storage_np_dtype = mapping.TENSOR_TYPE_TO_NP_TYPE[storage_type]
    storage_field = mapping.STORAGE_TENSOR_TYPE_TO_FIELD[storage_type]
    dims = tensor.dims

    if tensor.data_type == TensorProto.STRING:
        utf8_strings = getattr(tensor, storage_field)
        ss = list(s.decode('utf-8') for s in utf8_strings)
        return np.asarray(ss).astype(np_dtype).reshape(dims)

    if tensor.HasField("raw_data"):
        # Raw_bytes support: using frombuffer.
        return np.frombuffer(
            tensor.raw_data,
            dtype=np_dtype).reshape(dims)
    else:
        data = getattr(tensor, storage_field),  # type: Sequence[np.complex64]
        if (tensor_dtype == TensorProto.COMPLEX64
                or tensor_dtype == TensorProto.COMPLEX128):
            data = combine_pairs_to_complex(data)
        return (
            np.asarray(
                data,
                dtype=storage_np_dtype)
            .astype(np_dtype)
            .reshape(dims)
        )
302387
@Override
    public INDArray toDense() {
        // TODO support view conversion
        INDArray result = Nd4j.zeros(shape());

        switch (data().dataType()) {
            case DOUBLE:
                for (int i = 0; i < length; i++) {
                    int[] idx = getUnderlyingIndicesOf(i).asInt();
                    double value = values.getDouble(i);
                    result.putScalar(idx, value);
                }
                break;
            case FLOAT:
                for (int i = 0; i < length; i++) {
                    int[] idx = getUnderlyingIndicesOf(i).asInt();
                    float value = values.getFloat(i);
                    result.putScalar(idx, value);
                }
                break;
            default:
                throw new UnsupportedOperationException();
        }
        return result;
    }
746558
@Override
    public INDArray getLFactor(INDArray A) {
        // FIXME: int cast
        if (A.rows() > Integer.MAX_VALUE || A.columns() > Integer.MAX_VALUE)
            throw new ND4JArraySizeException();

        int m = (int) A.rows();
        int n = (int) A.columns();

        INDArray L = Nd4j.create(m, n);
        for (int r = 0; r < m; r++) {
            for (int c = 0; c < n; c++) {
                if (r > c && r < m && c < n) {
                    L.putScalar(r, c, A.getFloat(r, c));
                } else if (r < c) {
                    L.putScalar(r, c, 0.f);
                } else {
                    L.putScalar(r, c, 1.f);
                }
            }
        }
        return L;
    }
1171498
@Override
    public INDArray scalar(double value) {
        if (Nd4j.dataType() == DataType.DOUBLE)
            return create(new double[] {value}, new int[0], new int[0], 0);
        else
            return scalar((float) value);
    }
86093
public static TensorFactory getFactory() {
    return new TensorFactory() {
      @Override
      public TensorBuilder getBuilder(int[] dimNums, int[] dimSizes) {
        return new SparseTensorBuilder(dimNums, dimSizes);
      }
    };
  }
479620
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:
    """"""
    # Note: Relying on fact that vdot flattens arrays
    N = rank(tensor0)
    axes = list(range(N))
    return tf.tensordot(tf.math.conj(tensor0), tensor1, axes=(axes, axes))
993366
@Override
    public Tensor forward() {
        Tensor x = modIn.getOutput();
        y = x.select(dim, idx);
        return y;
    }
991631
@Override
    public Tensor forward() {
        Tensor x = modInX.getOutput();
        y = new Tensor(x); // copy
        y.exp();
        return y;
    }
818913
public static Tensor toTensor(INDArray arr) {
        FlatBufferBuilder bufferBuilder = new FlatBufferBuilder(1024);
        long[] strides = getArrowStrides(arr);
        int shapeOffset = createDims(bufferBuilder,arr);
        int stridesOffset = Tensor.createStridesVector(bufferBuilder,strides);

        Tensor.startTensor(bufferBuilder);

        addTypeTypeRelativeToNDArray(bufferBuilder,arr);
        Tensor.addShape(bufferBuilder,shapeOffset);
        Tensor.addStrides(bufferBuilder,stridesOffset);

        Tensor.addData(bufferBuilder,addDataForArr(bufferBuilder,arr));
        int endTensor = Tensor.endTensor(bufferBuilder);
        Tensor.finishTensorBuffer(bufferBuilder,endTensor);
        return Tensor.getRootAsTensor(bufferBuilder.dataBuffer());
    }