0

I am trying to write a version of scipy.stats.truncnorm with easier-to-use parameters (true range, mu and sig), by implementing scipy.stats.rv_continuous. I provide code for _argcheck, _get_support, _pdf, and _rvs, but get the error

_parse_args() missing 4 required positional arguments: 'a', 'b', 'mu', and 'sig'

I suspect it has to do with shapes, or implementing _parse_args, but can't figure out how to solve it (I have seen How do you use scipy.stats.rv_continuous?).

I am using scipy v 1.5.2 and Python 3.8.5.

Code:

from scipy.stats import *
import scipy.stats

class truncgauss_gen(rv_continuous):
    ''' a and b are bounds of true support
    mu is mean
    sig is std dev
    '''
    def _argcheck(self, a, b, sig): return (a < b) and (sig > 0)
        
    def _get_support(self, a, b):   return a, b
        
    def _pdf(self, x, a, b, mu, sig):   return scipy.stats.truncnorm.pdf(x, (a - mu) / sig, (b - mu) / sig, ac=mu, scale=sig)

    def _rvs(self, a, b, mu, sig, size):    return scipy.stats.truncnorm.rvs((a - mu) / sig, (b - mu) / sig, ac=mu, scale=sig, size=size)
    
        
truncgauss = truncgauss_gen(name='truncgauss', momtype=1)

if __name__ == '__main__':
    print(scipy.__version__)    
    
    tg = truncgauss()
    dat = tg.rvs(a=-5.1, b=10.07, mu=2.3, n=10)
    print(dat)

Traceback:

1.5.2
Traceback (most recent call last):
  File "testDistr.py", line 41, in <module>
    tg = truncgauss()
  File ".../opt/anaconda3/lib/python3.8/site-packages/scipy/stats/_distn_infrastructure.py", line 780, in __call__
    return self.freeze(*args, **kwds)
  File ".../opt/anaconda3/lib/python3.8/site-packages/scipy/stats/_distn_infrastructure.py", line 777, in freeze
    return rv_frozen(self, *args, **kwds)
  File ".../opt/anaconda3/lib/python3.8/site-packages/scipy/stats/_distn_infrastructure.py", line 424, in __init__
    shapes, _, _ = self.dist._parse_args(*args, **kwds)
TypeError: _parse_args() missing 4 required positional arguments: 'a', 'b', 'mu', and 'sig'
Mister Mak
  • 276
  • 1
  • 9

1 Answers1

1

Not really sure what the problem was, but passing all of the variables to each function as below seems to work.

class truncG_gen(rv_continuous):
    def _argcheck(self, a, b, mu, sig): return (a < b) and (sig > 0)
        
    def _get_support(self, a, b, mu, sig):  return a, b
        
    def _pdf(self, x, a, b, mu, sig):   return scipy.stats.truncnorm.pdf(x, (a - mu) / sig, (b - mu) / sig, loc=mu, scale=sig)

    def _cdf(self, x, a, b, mu, sig):   return scipy.stats.truncnorm.cdf(x, (a - mu) / sig, (b - mu) / sig, loc=mu, scale=sig)
    
    def _rvs(self, a, b, mu, sig, size=None, random_state=None):
        return scipy.stats.truncnorm.rvs((a - mu) / sig, (b - mu) / sig, loc=mu, scale=sig, size=size, random_state=random_state)

truncG = truncG_gen(name='truncG', momtype=1)
'''
Mister Mak
  • 276
  • 1
  • 9