Hi all,

yesterday me and a colleague found ourselves writing, for the millionth time, a hansl function implementing the so-called "soft thresholding" operator, and I was thinking that, although it's very easy, it'd be nice if it were a builtin function. So I wrote a hansl function that IMO is quite nice and general (works with scalars, series and matrices) and is in the attached script, along with a few usage examples[*].

Note that the function could be made more general, for example introducing the scalar rho as in https://www.sciencedirect.com/topics/computer-science/soft-thresholding , eq. (11.46) or allowing for "hard thresholding", like in the Mathematica function "wthresh", but maybe not for now.

What I'm asking the community is:

1) Is it worthwhile having a dedicated function for this at all?

2) If so, should we have this as a builtin function[**], or should it just be in extra?

3) Does anyone have better ideas on the function's signature?

[*] I know, it could have written in a cooler way by usign the sgn() function and conditional assignment, but hey.

[**] We already have a C version for scalars in plugins/regls.c.

-------------------------------------------------------
  Riccardo (Jack) Lucchetti
  Dipartimento di Scienze Economiche e Sociali (DiSES)

  Università Politecnica delle Marche
  (formerly known as Università di Ancona)

  r.lucche...@univpm.it
  http://www2.econ.univpm.it/servizi/hpp/lucchetti
-------------------------------------------------------
set verbose off
set seed 20250405

function numeric sthresh(numeric x, numeric a)
    
    errorif(min(a) < 0, "a must be non-negative")
    
    errcond = (typeof(a) != 1) && (typeof(x) != typeof(a))
    errorif(errcond, "non-matching types")
    if typeof(x) == 3
        # x is matrix
        matrix ret = x .> a ? (x-a) : (x .< -a) ? (x + a) : 0
    else
        ret = x > a ? (x-a) : (x < -a) ? (x + a) : 0
    endif

    return ret
end function

### usage example

nulldata 10
scal_a = 1
ser_x = normal()
ser_a = 0.5*(obs < 6)

# should be scalars (2, -2, 0)

sctest1 = sthresh( 3, scal_a)
sctest2 = sthresh(-3, scal_a)
sctest3 = sthresh(-1, scal_a)
print sctest1 sctest2 sctest3

# should be series

sertest1 = sthresh(ser_x, scal_a)
sertest2 = sthresh(ser_x, ser_a)
print ser_x ser_a sertest1 sertest2 -o

# should be matrix

mtest1 = sthresh({ser_x}, scal_a)
mtest2 = sthresh({ser_x}, {ser_a})
print mtest1 ~ mtest2


_______________________________________________
Gretl-users mailing list -- gretl-users@gretlml.univpm.it
To unsubscribe send an email to gretl-users-le...@gretlml.univpm.it
Website: 
https://gretlml.univpm.it/postorius/lists/gretl-users.gretlml.univpm.it/

Reply via email to