% Upsample by replicating neighbouring pixel values.

% Copyright 2020 The MathWorks, Inc.

classdef upsampleBy2Layer < nnet.layer.Layer
    properties (Constant)
        % factor to upsample the input.
        UpSampleFactor = 2
    end
    
    methods
        function layer = upsampleBy2Layer(name)
            
            % Set layer name.
            layer.Name = name;
            
            % Set layer description.
            layer.Description = "upSamplingLayer with factor " + layer.UpSampleFactor;
            
        end
        
        function Z = predict(layer, X)
            % Z = predict(layer, X) forwards the input data X through the
            % layer and outputs the result Z.
            if coder.target('MATLAB')
                Z = repelem(X,layer.UpSampleFactor,layer.UpSampleFactor);
            else
                numChannels = size(X, 3);
                numBatches = size(X, 4);
                Zsize = coder.const([size(X, 1) size(X, 2) numChannels numBatches] .* [layer.UpSampleFactor layer.UpSampleFactor 1 1]);
                Z = coder.nullcopy(zeros(Zsize, 'like', X));
                
                coder.gpu.kernel(-1, -1);
                for iBatch = 1:numBatches
                    for iChannel = 1:numChannels
                        Z(:, :, iChannel, iBatch) = repelem(X(:, :, iChannel, iBatch), layer.UpSampleFactor, layer.UpSampleFactor);
                    end
                end
            end
        end
    end
end