001/*
002 * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.tribuo.util.onnx;
018
019import com.google.protobuf.ByteString;
020import ai.onnx.proto.OnnxMl;
021
022import java.nio.charset.StandardCharsets;
023
024/**
025 * The spec for an attribute, used to produce the attribute proto at construction time.
026 */
027public final class ONNXAttribute {
028
029    /**
030     * Value used to denote a varaidic input in an ONNX operator
031     */
032    public static final int VARIADIC_INPUT = -1;
033
034    private final String name;
035    private final OnnxMl.AttributeProto.AttributeType type;
036    private final boolean mandatory;
037
038    /**
039     * Constructs an attribute placeholder of the appropriate name and type.
040     *
041     * @param name The name of the attribute.
042     * @param type The type of the attribute.
043     * @param mandatory Is this attribute mandatory?
044     */
045    public ONNXAttribute(String name, OnnxMl.AttributeProto.AttributeType type, boolean mandatory) {
046        this.name = name;
047        this.type = type;
048        this.mandatory = mandatory;
049    }
050
051    /**
052     * Gets the attribute's name.
053     *
054     * @return The attribute's name.
055     */
056    public String getName() {
057        return name;
058    }
059
060    /**
061     * Gets the attribute's type.
062     *
063     * @return The attribute's type.
064     */
065    public OnnxMl.AttributeProto.AttributeType getType() {
066        return type;
067    }
068
069    /**
070     * Is this attribute mandatory?
071     * @return True if the attribute is mandatory for this operation.
072     */
073    public boolean isMandatory() {
074        return mandatory;
075    }
076
077    /**
078     * Builds the attribute proto using the supplied value.
079     * <p>
080     * Throws {@link IllegalArgumentException} if the value type does not match the expected type, and
081     * throws {@link UnsupportedOperationException} if the value type is not supported. Currently supported
082     * types are primitives, strings and arrays of primitives and strings. ONNX attributes only support
083     * float and int as primitives.
084     * @param value The value
085     * @return The AttributeProto.
086     */
087    public OnnxMl.AttributeProto build(Object value) {
088        OnnxMl.AttributeProto.Builder builder = OnnxMl.AttributeProto.newBuilder();
089
090        builder.setName(name);
091        builder.setType(type);
092        switch (type) {
093            case FLOAT:
094                if (value instanceof Float) {
095                    builder.setF((Float) value);
096                } else {
097                    throw new IllegalArgumentException("Expected Float, found " + value.getClass() + " with value " + value);
098                }
099                break;
100            case INT:
101                if (value instanceof Integer) {
102                    builder.setI((Integer) value);
103                } else {
104                    throw new IllegalArgumentException("Expected Integer, found " + value.getClass() + " with value " + value);
105                }
106                break;
107            case STRING:
108                if (value instanceof String) {
109                    builder.setS(ByteString.copyFrom((String) value, StandardCharsets.UTF_8));
110                } else {
111                    throw new IllegalArgumentException("Expected String, found " + value.getClass() + " with value " + value);
112                }
113                break;
114            case FLOATS:
115                if (value instanceof float[]) {
116                    float[] arr = (float[]) value;
117                    for (int i = 0; i < arr.length; i++) {
118                        builder.addFloats(arr[i]);
119                    }
120                } else {
121                    throw new IllegalArgumentException("Expected float[], found " + value.getClass() + " with value " + value);
122                }
123                break;
124            case INTS:
125                if (value instanceof int[]) {
126                    int[] arr = (int[]) value;
127                    for (int i = 0; i < arr.length; i++) {
128                        builder.addInts(arr[i]);
129                    }
130                } else {
131                    throw new IllegalArgumentException("Expected int[], found " + value.getClass() + " with value " + value);
132                }
133                break;
134            case STRINGS:
135                if (value instanceof String[]) {
136                    String[] arr = (String[]) value;
137                    for (int i = 0; i < arr.length; i++) {
138                        builder.addStrings(ByteString.copyFrom(arr[i], StandardCharsets.UTF_8));
139                    }
140                } else {
141                    throw new IllegalArgumentException("Expected String[], found " + value.getClass() + " with value " + value);
142                }
143                break;
144            case TENSOR:
145                if (value instanceof OnnxMl.TensorProto) {
146                    builder.setT((OnnxMl.TensorProto) value);
147                } else {
148                    throw new IllegalArgumentException("Expected TensorProto, found " + value.getClass() + " with value " + value);
149                }
150                break;
151            case GRAPH:
152            case SPARSE_TENSOR:
153            case TENSORS:
154            case GRAPHS:
155            case SPARSE_TENSORS:
156            case UNDEFINED:
157                throw new UnsupportedOperationException("Type: " + type + " is not supported.");
158        }
159
160        return builder.build();
161    }
162
163    @Override
164    public String toString() {
165        return "ONNXAttribute(name='" + name + "',type=" + type + ",mandatory="+mandatory+")";
166    }
167}