import numpy as np

def bwlp(fsize, tc, n, option='circle'):
    from dftshift import dftshift

    rows, cols = fsize[0], fsize[1]
    mh, mw = rows//2, cols//2
    rr, cc = np.meshgrid(np.arange(-mh,rows-mh), np.arange(-mw,cols-mw), indexing='ij') # center
    if option.upper() == 'SQUARE':
        H = 1./(1.+(np.sqrt(2)-1)*(np.maximum(abs(1.*rr/rows) , np.abs(1.*cc/cols))*tc)**(2*n))
    else:
        aux = np.sqrt(((((1.*rr)/rows)**2 + ((1.*cc)/cols)**2) * tc) **(2*n))
        H = 1./(1+(np.sqrt(2)-1)*aux)
    H = dftshift(H)
    return H

"""
Explanation: Function bwlp
Synopse
Low-Pass Butterworth frequency filter.


H = iabwlp(fsize, tc, n, option='circle')


H: Image. 


fsize: Image. Filter size: a col vector: first element: rows, second: cols, etc. uses same convention as the return of size.

tc: Double. Cutoff period.
n: Double. Filter order.
option: String. Filter options. Possible values: 'circle' or 'square'.
End of explanation
"""


testing = (__name__ == "__main__")
if testing:
    ! jupyter nbconvert --to python bwlp.ipynb
    import numpy as np
    import sys,os
    ia898path = os.path.abspath('../../')
    if ia898path not in sys.path:
        sys.path.append(ia898path)
    import ia898.src as ia

"""
Explanation: Description
This function generates a frequency domain Low Pass Butterworth Filter with cutoff period tc and order n. 
At the cutoff period the filter amplitude is about 0.7 of the amplitude at H(0,0). This function returns the mask filter with H(0,0). 
As the larger the filter order, sharper will be the amplitude transition at cutoff period. The minimum cutoff period is always 2 pixels, 
despite of the size of the frequency filter.
Examples
End of explanation
"""


if testing:

    H2_10 = ia.bwlp([100,100],2,2) # cutoff period: 2 pixels, order: 10
    ia.adshow(ia.dftview(H2_10))

if testing:
    H4_1 = ia.bwlp([100,100],4,1) # cutoff period: 4, order: 1
    ia.adshow(ia.dftview(H4_1))

if testing:
    H8_100 = ia.bwlp([100,100],8,100) # cutoff period: 8, order: 100
    ia.adshow(ia.dftview(H8_100))

if testing:
    H4_1box = ia.bwlp([100,100],4,1,'square') # cutoff period: 4, order: 1
    ia.adshow(ia.dftview(H4_1box))

"""
Explanation: Example 1
End of explanation
"""


