/*
 *  ******************************************************************************
 *  *
 *  *
 *  * This program and the accompanying materials are made available under the
 *  * terms of the Apache License, Version 2.0 which is available at
 *  * https://www.apache.org/licenses/LICENSE-2.0.
 *  *
 *  *  See the NOTICE file distributed with this work for additional
 *  *  information regarding copyright ownership.
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *  * License for the specific language governing permissions and limitations
 *  * under the License.
 *  *
 *  * SPDX-License-Identifier: Apache-2.0
 *  *****************************************************************************
 */

package org.deeplearning4j.nn.conf.weightnoise;

import lombok.Data;
import org.deeplearning4j.nn.api.Layer;
import org.deeplearning4j.nn.api.ParamInitializer;
import org.deeplearning4j.nn.conf.distribution.Distribution;
import org.deeplearning4j.nn.conf.distribution.Distributions;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.transforms.pairwise.arithmetic.AddOp;
import org.nd4j.linalg.api.ops.impl.transforms.pairwise.arithmetic.MulOp;
import org.nd4j.linalg.factory.Nd4j;
import org.deeplearning4j.nn.workspace.LayerWorkspaceMgr;
import org.deeplearning4j.nn.workspace.ArrayType;
import org.nd4j.shade.jackson.annotation.JsonProperty;

@Data
public class WeightNoise implements IWeightNoise {

    private Distribution distribution;
    private boolean applyToBias;
    private boolean additive;

    /**
     * @param distribution Distribution for additive noise
     */
    public WeightNoise(Distribution distribution) {
        this(distribution, false, true);
    }

    /**
     * @param distribution Distribution for noise
     * @param additive     If true: noise is added to weights. If false: noise is multiplied by weights
     */
    public WeightNoise(Distribution distribution, boolean additive) {
        this(distribution, false, additive);
    }

    /**
     * @param distribution Distribution for noise
     * @param applyToBias  If true: apply to biases also. If false (default): apply only to weights
     * @param additive     If true: noise is added to weights. If false: noise is multiplied by weights
     */
    public WeightNoise(@JsonProperty("distribution") Distribution distribution,
                       @JsonProperty("applyToBias") boolean applyToBias,
                       @JsonProperty("additive") boolean additive) {
        this.distribution = distribution;
        this.applyToBias = applyToBias;
        this.additive = additive;
    }

    @Override
    public INDArray getParameter(Layer layer, String paramKey, int iteration, int epoch, boolean train, LayerWorkspaceMgr workspaceMgr) {

        ParamInitializer init = layer.conf().getLayer().initializer();
        INDArray param = layer.getParam(paramKey);
        if (train && init.isWeightParam(layer.conf().getLayer(), paramKey) ||
                (applyToBias && init.isBiasParam(layer.conf().getLayer(), paramKey))) {

            org.nd4j.linalg.api.rng.distribution.Distribution dist = Distributions.createDistribution(distribution);
            INDArray noise = dist.sample(param.ulike());
            INDArray out = workspaceMgr.createUninitialized(ArrayType.INPUT, param.dataType(), param.shape(), param.ordering());

            if (additive) {
                Nd4j.getExecutioner().exec(new AddOp(param, noise,out));
            } else {
                Nd4j.getExecutioner().exec(new MulOp(param, noise, out));
            }
            return out;
        }
        return param;
    }

    @Override
    public WeightNoise clone() {
        return new WeightNoise(distribution, applyToBias, additive);
    }
}
