#----------------------------------------------------------------------
# Python interface for ISPACK3
# Copyright (C) 2023--2024 Toshiki Matsushima <toshiki@gfd-dennou.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
# 
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA.
#----------------------------------------------------------------------
from mpi4py import MPI
import numpy as np
#import time
import ispack3 as isp

jm  = 2**10
ntr = 10
mm  = jm-1
im  = jm*2
nm  = mm+1
nn  = nm
nt = mm

ig=1

eps = im*10**(-14)

it, t, r = isp.sxini1(mm, nm, im)
p, jc = isp.sxini2(mm, nm, jm, ig, r)
c = isp.sxinic(mm, nt)
d = isp.sxinid(mm, nt)

g_shape = (jm,im)
W_shape = (jm*im)

s_shape = ((2*nt+1-mm)*mm+nt+1,)
sy_shape = ((2*nt+3-mm)*mm+nt+2,)

G = isp.aligned_array(g_shape, align=64)
W = isp.aligned_array(W_shape, dtype=np.float64, align=64)

S = np.empty(s_shape, dtype=np.float64)

np.random.seed(0)
S = 2 * np.random.rand(*S.shape) - 1

SD = np.zeros(s_shape, dtype=np.float64)
SD[0] = 0.0

SX = np.empty(s_shape, dtype=np.float64)
SXD = np.empty(s_shape, dtype=np.float64)
SXR = np.empty(sy_shape, dtype=np.float64)
SY = np.empty(sy_shape, dtype=np.float64)
SYD = np.empty(s_shape, dtype=np.float64)

isp.sxclap(mm,nt,S,SD,d,iflag=2)
isp.sxclap(mm,nt,SD,S,d,iflag=1)

isp.sxcs2x(mm,nt,SD,SX)
isp.sxcrpk(mm,nt,nt+1,SX,SXR)
isp.sxcs2y(mm,nt,SD,SY,c)

isp.sxts2g(mm,nm,nt+1,im,jm,SXR,G,it,t,p,r,jc,W,ipow=1)
isp.sxtg2s(mm,nm,nt+1,im,jm,SXR,G,it,t,p,r,jc,W,ipow=1)
isp.sxts2g(mm,nm,nt+1,im,jm,SY,G,it,t,p,r,jc,W,ipow=1)
isp.sxtg2s(mm,nm,nt+1,im,jm,SY,G,it,t,p,r,jc,W,ipow=1)

isp.sxcy2s(mm,nt,SY,SYD,c)
isp.sxcrpk(mm,nt+1,nt,SXR,SX)
isp.sxcs2x(mm,nt,SX,SXD)

SD = SXD + SYD

l = np.arange(len(S))
n, m = isp.sxl2nm(nt, l)
    
SL_values = np.zeros_like(S, dtype=np.float64)
SL_values[m == 0] = np.abs(SD[m == 0] - S[m == 0])
SL_values[m > 0] = np.sqrt((SD[m > 0] - S[m > 0])**2 + (SD[m < 0] - S[m < 0])**2)

SLMAX = np.max(SL_values)
LAS = l[np.argmax(SL_values)]

SLAMAX = np.sum(SL_values**2)

n, m = isp.sxl2nm(mm, LAS)

print("maxerror=", SLMAX, "(n=", n, ", m=", m, ")" )
print("rmserror=", np.sqrt(SLAMAX/((mm+1)*(mm+2)/2) ) )
print("gradient and divergence check:")
if(SLMAX <= eps ):
    print('** OK')
else:
    print('** Fail')
