All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yahoo.tensor.functions.Diag Maven / Gradle / Ivy

Go to download

Library for use in Java components of Vespa. Shared code which do not fit anywhere else.

There is a newer version: 8.409.18
Show newest version
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.tensor.functions;

import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.evaluation.Name;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * A tensor generator which returns a tensor of any dimension filled with 1 in the diagonal and 0 elsewhere.
 *
 * @author bratseth
 */
public class Diag extends CompositeTensorFunction {

    private final TensorType type;
    private final Function, Double> diagFunction;

    public Diag(TensorType type) {
        this.type = type;
        this.diagFunction = ScalarFunctions.equal(dimensionNames().toList());
    }

    @Override
    public List> arguments() { return List.of(); }

    @Override
    public TensorFunction withArguments(List> arguments) {
        if ( arguments.size() != 0)
            throw new IllegalArgumentException("Diag must have 0 arguments, got " + arguments.size());
        return this;
    }

    @Override
    public PrimitiveTensorFunction toPrimitive() {
        return new Generate<>(type, diagFunction);
    }

    private Stream dimensionNames() {
        return type.dimensions().stream().map(TensorType.Dimension::name);
    }

    @Override
    public String toString(ToStringContext context) {
        return "diag(" + dimensionNames().collect(Collectors.joining(",")) + ")" + diagFunction;
    }

    @Override
    public int hashCode() { return Objects.hash("diag", type, diagFunction); }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy