#-------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# 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.
#
#-------------------------------------------------------------

arima_residuals = function(Matrix[Double] weights, Matrix[Double] X, Integer p, Integer P, Integer q, Integer Q, Integer s, String solver) return (Matrix[Double] errs, Matrix[Double] combined_weights){
  combined_weights = weights
  if (p>0 & P>0)
    combined_weights = rbind(combined_weights, matrix(weights[1:p,] %*% t(weights[p+1:p+P,]), rows=p*P, cols=1))
  b = X[,2:ncol(X)]%*%combined_weights
  errs = X[,1] - b
}

X = matrix(1, 1000, 1)
p = 2
d = 0
q = 0
P = 0
D = 0
Q = 0
s = 0
totparamcols = p+P+Q+q+p*P
num_rows = nrow(X)

if(num_rows <= d)
  print("non-seasonal differencing order should be smaller than length of the time-series")
if(num_rows <= s*D)
  print("seasonal differencing order should be smaller than number of observations divided by length of season")

Z = cbind (X[1:nrow(X),], matrix(0, nrow(X), totparamcols))
weights = matrix("0.459982 0.673987", 2, 1)

f1 = arima_residuals(weights, Z, p, P, q, Q, s, "")
f2 = arima_residuals(weights, Z, p, P, q, Q, s, "")
print("out:  " + sum(f1-f2))
