gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _repr_cov_params(self, dist=None):
    if dist is None:
        dist = self
    if self._cov_type == "chol":
        chol = get_variable_name(self.chol)
        return r"\mathit{{chol}}={}".format(chol)
    elif self._cov_type == "cov":
        cov = get_variable_name(self.cov)
        return r"\mathit{{cov}}={}".format(cov)
    elif self._cov_type == "tau":
        tau = get_variable_name(self.tau)
        return r"\mathit{{tau}}={}".format(tau)


# Traceback (AttributeError)
Traceback (most recent call last):
File "fail.py", line 9, in <module>
print(d.distribution._repr_latex_())
File "/nix/store/4c6ihiawh232fszikcyxhdk32rzk4l28-python3-3.7.2-env/lib/python3.7/site-packages/pymc3/distributions/multivariate.py", line 286, in _repr_latex_
.format(name, name_mu, self._repr_cov_params(dist)))
File "/nix/store/4c6ihiawh232fszikcyxhdk32rzk4l28-python3-3.7.2-env/lib/python3.7/site-packages/pymc3/distributions/multivariate.py", line 145, in _repr_cov_params
chol = get_variable_name(self.chol)
AttributeError: 'MvNormal' object has no attribute 'chol'

# Fixed code
def _repr_cov_params(self, dist=None):
    if dist is None:
        dist = self
    if self._cov_type == "chol":
        chol = get_variable_name(self.chol_cov)
        return r"\mathit{{chol}}={}".format(chol)
    elif self._cov_type == "cov":
        cov = get_variable_name(self.cov)
        return r"\mathit{{cov}}={}".format(cov)
    elif self._cov_type == "tau":
        tau = get_variable_name(self.tau)
        return r"\mathit{{tau}}={}".format(tau)
# Buggy code
def logp(self, value):
    """
    Calculate log-probability of TruncatedNormal distribution at specified value.

    Parameters
    ----------
    value : numeric
        Value(s) for which log-probability is calculated. If the log probabilities for multiple
        values are desired the values must be provided in a numpy array or theano tensor

    Returns
    -------
    TensorVariable
    """
    mu = self.mu
    sigma = self.sigma

    norm = self._normalization()
    logp = Normal.dist(mu=mu, sigma=sigma).logp(value) - norm

    bounds = [sigma > 0]
    if self.lower is not None:
        bounds.append(value >= self.lower)
    if self.upper is not None:
        bounds.append(value <= self.upper)
    return bound(logp, *bounds)


# Traceback (ValueError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Applications/anaconda3/envs/Fit2/lib/python3.6/site-packages/pymc3/distributions/continuous.py", line 578, in random
[self.mu, self.sd, self.lower, self.upper], point=point, size=size)
File "/Applications/anaconda3/envs/Fit2/lib/python3.6/site-packages/pymc3/distributions/distribution.py", line 321, in draw_values
evaluated[param_idx] = _draw_value(param, point=point, givens=givens.values(), size=size)
File "/Applications/anaconda3/envs/Fit2/lib/python3.6/site-packages/pymc3/distributions/distribution.py", line 418, in _draw_value
raise ValueError('Unexpected type in draw_value: %s' % type(param))
ValueError: Unexpected type in draw_value: <class 'NoneType'>

# Fixed code
def logp(self, value):
    """
    Calculate log-probability of TruncatedNormal distribution at specified value.

    Parameters
    ----------
    value : numeric
        Value(s) for which log-probability is calculated. If the log probabilities for multiple
        values are desired the values must be provided in a numpy array or theano tensor

    Returns
    -------
    TensorVariable
    """
    mu = self.mu
    sigma = self.sigma

    norm = self._normalization()
    logp = Normal.dist(mu=mu, sigma=sigma).logp(value) - norm

    bounds = [sigma > 0]
    if self.lower_check is not None:
        bounds.append(value >= self.lower)
    if self.upper_check is not None:
        bounds.append(value <= self.upper)
    return bound(logp, *bounds)
# Buggy code
def _normalization(self):
    mu, sigma = self.mu, self.sigma

    if self.lower is None and self.upper is None:
        return 0.0

    if self.lower is not None and self.upper is not None:
        lcdf_a = normal_lcdf(mu, sigma, self.lower)
        lcdf_b = normal_lcdf(mu, sigma, self.upper)
        lsf_a = normal_lccdf(mu, sigma, self.lower)
        lsf_b = normal_lccdf(mu, sigma, self.upper)

        return tt.switch(
            self.lower > 0,
            logdiffexp(lsf_a, lsf_b),
            logdiffexp(lcdf_b, lcdf_a),
        )

    if self.lower is not None:
        return normal_lccdf(mu, sigma, self.lower)
    else:
        return normal_lcdf(mu, sigma, self.upper)


# Traceback (ValueError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Applications/anaconda3/envs/Fit2/lib/python3.6/site-packages/pymc3/distributions/continuous.py", line 578, in random
[self.mu, self.sd, self.lower, self.upper], point=point, size=size)
File "/Applications/anaconda3/envs/Fit2/lib/python3.6/site-packages/pymc3/distributions/distribution.py", line 321, in draw_values
evaluated[param_idx] = _draw_value(param, point=point, givens=givens.values(), size=size)
File "/Applications/anaconda3/envs/Fit2/lib/python3.6/site-packages/pymc3/distributions/distribution.py", line 418, in _draw_value
raise ValueError('Unexpected type in draw_value: %s' % type(param))
ValueError: Unexpected type in draw_value: <class 'NoneType'>

# Fixed code
def _normalization(self):
    mu, sigma = self.mu, self.sigma

    if self.lower_check is None and self.upper_check is None:
        return 0.0

    if self.lower_check is not None and self.upper_check is not None:
        lcdf_a = normal_lcdf(mu, sigma, self.lower)
        lcdf_b = normal_lcdf(mu, sigma, self.upper)
        lsf_a = normal_lccdf(mu, sigma, self.lower)
        lsf_b = normal_lccdf(mu, sigma, self.upper)

        return tt.switch(
            self.lower > 0,
            logdiffexp(lsf_a, lsf_b),
            logdiffexp(lcdf_b, lcdf_a),
        )

    if self.lower_check is not None:
        return normal_lccdf(mu, sigma, self.lower)
    else:
        return normal_lcdf(mu, sigma, self.upper)
# Buggy code
def __new__(cls, *args, **kwargs):
    # resolves the parent instance
    instance = super().__new__(cls)
    if cls.get_contexts():
        potential_parent = cls.get_contexts()[-1]
        # We have to make sure that the context is a _DrawValuesContext
        # and not a Model
        if isinstance(potential_parent, cls):
            instance._parent = potential_parent
        else:
            instance._parent = None
    else:
        instance._parent = None
    return instance


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-7300cc3c60ce> in <module>()
8
9 with model:
---> 10     pm.sample_prior_predictive(50)
11

~/anaconda3/lib/python3.6/site-packages/pymc3-3.5-py3.6.egg/pymc3/sampling.py in sample_prior_predictive(samples, model, vars, random_seed)
1332     names = get_default_varnames(model.named_vars, include_transformed=False)
1333     # draw_values fails with auto-transformed variables. transform them later!
-> 1334     values = draw_values([model[name] for name in names], size=samples)
1335
1336     data = {k: v for k, v in zip(names, values)}

~/anaconda3/lib/python3.6/site-packages/pymc3-3.5-py3.6.egg/pymc3/distributions/distribution.py in draw_values(params, point, size)
310     while to_eval or missing_inputs:
311         if to_eval == missing_inputs:
--> 312             raise ValueError('Cannot resolve inputs for {}'.format([str(params[j]) for j in to_eval]))
313         to_eval = set(missing_inputs)
314         missing_inputs = set()

ValueError: Cannot resolve inputs for ['chol_packed']

# Fixed code
def __new__(cls, *args, **kwargs):
    # resolves the parent instance
    instance = super().__new__(cls)
    if cls.get_contexts():
        potential_parent = cls.get_contexts()[-1]
        # We have to make sure that the context is a _DrawValuesContext
        # and not a Model
        if isinstance(potential_parent, _DrawValuesContext):
            instance._parent = potential_parent
        else:
            instance._parent = None
    else:
        instance._parent = None
    return instance
# Buggy code
def __init__(self):
    if self.parent is not None:
        # All _DrawValuesContext instances that are in the context of
        # another _DrawValuesContext will share the reference to the
        # drawn_vars dictionary. This means that separate branches
        # in the nested _DrawValuesContext context tree will see the
        # same drawn values
        self.drawn_vars = self.parent.drawn_vars
    else:
        self.drawn_vars = dict()


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-7300cc3c60ce> in <module>()
8
9 with model:
---> 10     pm.sample_prior_predictive(50)
11

~/anaconda3/lib/python3.6/site-packages/pymc3-3.5-py3.6.egg/pymc3/sampling.py in sample_prior_predictive(samples, model, vars, random_seed)
1332     names = get_default_varnames(model.named_vars, include_transformed=False)
1333     # draw_values fails with auto-transformed variables. transform them later!
-> 1334     values = draw_values([model[name] for name in names], size=samples)
1335
1336     data = {k: v for k, v in zip(names, values)}

~/anaconda3/lib/python3.6/site-packages/pymc3-3.5-py3.6.egg/pymc3/distributions/distribution.py in draw_values(params, point, size)
310     while to_eval or missing_inputs:
311         if to_eval == missing_inputs:
--> 312             raise ValueError('Cannot resolve inputs for {}'.format([str(params[j]) for j in to_eval]))
313         to_eval = set(missing_inputs)
314         missing_inputs = set()

ValueError: Cannot resolve inputs for ['chol_packed']

# Fixed code
def __init__(self):
    if self.parent is not None:
        # All _DrawValuesContext instances that are in the context of
        # another _DrawValuesContext will share the reference to the
        # drawn_vars dictionary. This means that separate branches
        # in the nested _DrawValuesContext context tree will see the
        # same drawn values.
        # The drawn_vars keys shall be (RV, size) tuples
        self.drawn_vars = self.parent.drawn_vars
    else:
        self.drawn_vars = dict()
# Buggy code
def to_tuple(shape):
    """Convert ints, arrays, and Nones to tuples"""
    if shape is None:
        return tuple()
    return tuple(np.atleast_1d(shape))


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-7300cc3c60ce> in <module>()
8
9 with model:
---> 10     pm.sample_prior_predictive(50)
11

~/anaconda3/lib/python3.6/site-packages/pymc3-3.5-py3.6.egg/pymc3/sampling.py in sample_prior_predictive(samples, model, vars, random_seed)
1332     names = get_default_varnames(model.named_vars, include_transformed=False)
1333     # draw_values fails with auto-transformed variables. transform them later!
-> 1334     values = draw_values([model[name] for name in names], size=samples)
1335
1336     data = {k: v for k, v in zip(names, values)}

~/anaconda3/lib/python3.6/site-packages/pymc3-3.5-py3.6.egg/pymc3/distributions/distribution.py in draw_values(params, point, size)
310     while to_eval or missing_inputs:
311         if to_eval == missing_inputs:
--> 312             raise ValueError('Cannot resolve inputs for {}'.format([str(params[j]) for j in to_eval]))
313         to_eval = set(missing_inputs)
314         missing_inputs = set()

ValueError: Cannot resolve inputs for ['chol_packed']

# Fixed code
def to_tuple(shape):
    """Convert ints, arrays, and Nones to tuples"""
    if shape is None:
        return tuple()
    temp = np.atleast_1d(shape)
    if temp.size == 0:
        return tuple()
    else:
        return tuple(temp)
# Buggy code
def _comp_samples(self, point=None, size=None):
    try:
        samples = self.comp_dists.random(point=point, size=size)
    except AttributeError:
        samples = np.column_stack(
            [comp_dist.random(point=point, size=size) for comp_dist in self.comp_dists]
        )

    return np.squeeze(samples)


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-7300cc3c60ce> in <module>()
8
9 with model:
---> 10     pm.sample_prior_predictive(50)
11

~/anaconda3/lib/python3.6/site-packages/pymc3-3.5-py3.6.egg/pymc3/sampling.py in sample_prior_predictive(samples, model, vars, random_seed)
1332     names = get_default_varnames(model.named_vars, include_transformed=False)
1333     # draw_values fails with auto-transformed variables. transform them later!
-> 1334     values = draw_values([model[name] for name in names], size=samples)
1335
1336     data = {k: v for k, v in zip(names, values)}

~/anaconda3/lib/python3.6/site-packages/pymc3-3.5-py3.6.egg/pymc3/distributions/distribution.py in draw_values(params, point, size)
310     while to_eval or missing_inputs:
311         if to_eval == missing_inputs:
--> 312             raise ValueError('Cannot resolve inputs for {}'.format([str(params[j]) for j in to_eval]))
313         to_eval = set(missing_inputs)
314         missing_inputs = set()

ValueError: Cannot resolve inputs for ['chol_packed']

# Fixed code
def _comp_samples(self, point=None, size=None):
    if self._comp_dists_vect or size is None:
        try:
            return self.comp_dists.random(point=point, size=size)
        except AttributeError:
            samples = np.array(
                [
                    comp_dist.random(point=point, size=size)
                    for comp_dist in self.comp_dists
                ]
            )
            samples = np.moveaxis(samples, 0, samples.ndim - 1)
    else:
        # We must iterate the calls to random manually
        size = to_tuple(size)
        _size = int(np.prod(size))
        try:
            samples = np.array(
                [self.comp_dists.random(point=point, size=None) for _ in range(_size)]
            )
            samples = np.reshape(samples, size + samples.shape[1:])
        except AttributeError:
            samples = np.array(
                [
                    [comp_dist.random(point=point, size=None) for _ in range(_size)]
                    for comp_dist in self.comp_dists
                ]
            )
            samples = np.moveaxis(samples, 0, samples.ndim - 1)
            samples = np.reshape(samples, size + samples[1:])

    if samples.shape[-1] == 1:
        return samples[..., 0]
    else:
        return samples
# Buggy code
def __init__(self, eta, n, sd_dist, *args, **kwargs):
    self.n = n
    self.eta = eta

    if "transform" in kwargs:
        raise ValueError("Invalid parameter: transform.")
    if "shape" in kwargs:
        raise ValueError("Invalid parameter: shape.")

    shape = n * (n + 1) // 2

    if sd_dist.shape.ndim not in [0, 1]:
        raise ValueError("Invalid shape for sd_dist.")

    transform = transforms.CholeskyCovPacked(n)

    kwargs["shape"] = shape
    kwargs["transform"] = transform
    super().__init__(*args, **kwargs)

    self.sd_dist = sd_dist
    self.diag_idxs = transform.diag_idxs

    self.mode = floatX(np.zeros(shape))
    self.mode[self.diag_idxs] = 1


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-7300cc3c60ce> in <module>()
8
9 with model:
---> 10     pm.sample_prior_predictive(50)
11

~/anaconda3/lib/python3.6/site-packages/pymc3-3.5-py3.6.egg/pymc3/sampling.py in sample_prior_predictive(samples, model, vars, random_seed)
1332     names = get_default_varnames(model.named_vars, include_transformed=False)
1333     # draw_values fails with auto-transformed variables. transform them later!
-> 1334     values = draw_values([model[name] for name in names], size=samples)
1335
1336     data = {k: v for k, v in zip(names, values)}

~/anaconda3/lib/python3.6/site-packages/pymc3-3.5-py3.6.egg/pymc3/distributions/distribution.py in draw_values(params, point, size)
310     while to_eval or missing_inputs:
311         if to_eval == missing_inputs:
--> 312             raise ValueError('Cannot resolve inputs for {}'.format([str(params[j]) for j in to_eval]))
313         to_eval = set(missing_inputs)
314         missing_inputs = set()

ValueError: Cannot resolve inputs for ['chol_packed']

# Fixed code
def __init__(self, eta, n, sd_dist, *args, **kwargs):
    self.n = n
    self.eta = eta

    if "transform" in kwargs and kwargs["transform"] is not None:
        raise ValueError("Invalid parameter: transform.")
    if "shape" in kwargs:
        raise ValueError("Invalid parameter: shape.")

    shape = n * (n + 1) // 2

    if sd_dist.shape.ndim not in [0, 1]:
        raise ValueError("Invalid shape for sd_dist.")

    transform = transforms.CholeskyCovPacked(n)

    kwargs["shape"] = shape
    kwargs["transform"] = transform
    super().__init__(*args, **kwargs)

    self.sd_dist = sd_dist
    self.diag_idxs = transform.diag_idxs

    self.mode = floatX(np.zeros(shape))
    self.mode[self.diag_idxs] = 1
# Buggy code
def forward_val(self, y, point=None):
    y[self.diag_idxs] = np.log(y[self.diag_idxs])
    return y


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-7300cc3c60ce> in <module>()
8
9 with model:
---> 10     pm.sample_prior_predictive(50)
11

~/anaconda3/lib/python3.6/site-packages/pymc3-3.5-py3.6.egg/pymc3/sampling.py in sample_prior_predictive(samples, model, vars, random_seed)
1332     names = get_default_varnames(model.named_vars, include_transformed=False)
1333     # draw_values fails with auto-transformed variables. transform them later!
-> 1334     values = draw_values([model[name] for name in names], size=samples)
1335
1336     data = {k: v for k, v in zip(names, values)}

~/anaconda3/lib/python3.6/site-packages/pymc3-3.5-py3.6.egg/pymc3/distributions/distribution.py in draw_values(params, point, size)
310     while to_eval or missing_inputs:
311         if to_eval == missing_inputs:
--> 312             raise ValueError('Cannot resolve inputs for {}'.format([str(params[j]) for j in to_eval]))
313         to_eval = set(missing_inputs)
314         missing_inputs = set()

ValueError: Cannot resolve inputs for ['chol_packed']

# Fixed code
def forward_val(self, y, point=None):
    y[..., self.diag_idxs] = np.log(y[..., self.diag_idxs])
    return y
# Buggy code
def __call__(self, *args, **kwargs):
    if "observed" in kwargs:
        raise ValueError(
            "Observed Bound distributions are not supported. "
            "If you want to model truncated data "
            "you can use a pm.Potential in combination "
            "with the cumulative probability function. See "
            "pymc3/examples/censored_data.py for an example."
        )
    first, args = args[0], args[1:]

    if issubclass(self.distribution, Continuous):
        return _ContinuousBounded(
            first, self.distribution, self.lower, self.upper, *args, **kwargs
        )
    elif issubclass(self.distribution, Discrete):
        return _DiscreteBounded(
            first, self.distribution, self.lower, self.upper, *args, **kwargs
        )
    else:
        raise ValueError("Distribution is neither continuous nor discrete.")


# Traceback (IndexError)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-18-c9645cb7d458> in <module>()
3 with example:
4     BoundPoisson = pm.Bound(pm.Poisson, upper = 6)
----> 5     y = BoundPoisson(name = "y", mu = 1)

~/miniconda3/lib/python3.6/site-packages/pymc3/distributions/bound.py in __call__(self, *args, **kwargs)
209                              'with the cumulative probability function. See '
210                              'pymc3/examples/censored_data.py for an example.')
--> 211         first, args = args[0], args[1:]
212
213         if issubclass(self.distribution, Continuous):

IndexError: tuple index out of range

# Fixed code
def __call__(self, name, *args, **kwargs):
    if "observed" in kwargs:
        raise ValueError(
            "Observed Bound distributions are not supported. "
            "If you want to model truncated data "
            "you can use a pm.Potential in combination "
            "with the cumulative probability function. See "
            "pymc3/examples/censored_data.py for an example."
        )

    if issubclass(self.distribution, Continuous):
        return _ContinuousBounded(
            name, self.distribution, self.lower, self.upper, *args, **kwargs
        )
    elif issubclass(self.distribution, Discrete):
        return _DiscreteBounded(
            name, self.distribution, self.lower, self.upper, *args, **kwargs
        )
    else:
        raise ValueError("Distribution is neither continuous nor discrete.")
# Buggy code
def __init__(self, distribution, lower, upper, transform="infer", *args, **kwargs):
    self.dist = distribution.dist(*args, **kwargs)

    self.__dict__.update(self.dist.__dict__)
    self.__dict__.update(locals())

    if hasattr(self.dist, "mode"):
        self.mode = self.dist.mode

    if transform == "infer":
        default = self.dist.default()

        if not np.isinf(lower) and not np.isinf(upper):
            self.transform = transforms.interval(lower, upper)
            if default <= lower or default >= upper:
                self.testval = 0.5 * (upper + lower)

        if not np.isinf(lower) and np.isinf(upper):
            self.transform = transforms.lowerbound(lower)
            if default <= lower:
                self.testval = lower + 1

        if np.isinf(lower) and not np.isinf(upper):
            self.transform = transforms.upperbound(upper)
            if default >= upper:
                self.testval = upper - 1


# Traceback (AttributeError)
Traceback (most recent call last):
File "garch_example.py", line 40, in <module>
beta1 = BoundedNormal('beta1', 0, sd=1e6)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/distributions/continuous.py", line 1102, in __call__
*args, **kwargs)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/distributions/distribution.py", line 27, in __new__
return model.Var(name, dist, data)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/model.py", line 288, in Var
transform=dist.transform)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/model.py", line 689, in __init__
transformed_name = "{}_{}_".format(name, transform.name)
AttributeError: 'int' object has no attribute 'name'

# Fixed code
def __init__(self, distribution, lower, upper, transform="infer", *args, **kwargs):
    self.dist = distribution.dist(*args, **kwargs)
    self.__dict__.update(self.dist.__dict__)
    self.__dict__.update(locals())

    if hasattr(self.dist, "mode"):
        self.mode = self.dist.mode

    if transform == "infer":
        self.transform, self.testval = self._infer(lower, upper)
# Buggy code
def __init__(self, distribution, lower=-np.inf, upper=np.inf):
    self.distribution = distribution
    self.lower = lower
    self.upper = upper


# Traceback (AttributeError)
Traceback (most recent call last):
File "garch_example.py", line 40, in <module>
beta1 = BoundedNormal('beta1', 0, sd=1e6)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/distributions/continuous.py", line 1102, in __call__
*args, **kwargs)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/distributions/distribution.py", line 27, in __new__
return model.Var(name, dist, data)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/model.py", line 288, in Var
transform=dist.transform)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/model.py", line 689, in __init__
transformed_name = "{}_{}_".format(name, transform.name)
AttributeError: 'int' object has no attribute 'name'

# Fixed code
def __init__(self, *args, **kwargs):
    first, args = args[0], args[1:]
    super(self, _BoundedDist).__init__(
        first, distribution, lower, upper, *args, **kwargs
    )
# Buggy code
def dist(self, *args, **kwargs):
    return Bounded.dist(self.distribution, self.lower, self.upper, *args, **kwargs)


# Traceback (AttributeError)
Traceback (most recent call last):
File "garch_example.py", line 40, in <module>
beta1 = BoundedNormal('beta1', 0, sd=1e6)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/distributions/continuous.py", line 1102, in __call__
*args, **kwargs)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/distributions/distribution.py", line 27, in __new__
return model.Var(name, dist, data)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/model.py", line 288, in Var
transform=dist.transform)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/model.py", line 689, in __init__
transformed_name = "{}_{}_".format(name, transform.name)
AttributeError: 'int' object has no attribute 'name'

# Fixed code
def dist(cls, *args, **kwargs):
    return Bounded.dist(distribution, lower, upper, *args, **kwargs)
# Buggy code
def __init__(self, mu=0.0, sd=None, tau=None, alpha=1, *args, **kwargs):
    super(SkewNormal, self).__init__(*args, **kwargs)
    self.mu = mu
    self.tau, self.sd = get_tau_sd(tau=tau, sd=sd)
    self.alpha = alpha
    self.mean = mu + self.sd * (2 / np.pi) ** 0.5 * alpha / (1 + alpha**2) ** 0.5
    self.variance = self.sd**2 * (1 - (2 * alpha**2) / ((1 + alpha**2) * np.pi))

    assert_negative_support(tau, "tau", "SkewNormal")
    assert_negative_support(sd, "sd", "SkewNormal")


# Traceback (AttributeError)
Traceback (most recent call last):
File "garch_example.py", line 40, in <module>
beta1 = BoundedNormal('beta1', 0, sd=1e6)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/distributions/continuous.py", line 1102, in __call__
*args, **kwargs)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/distributions/distribution.py", line 27, in __new__
return model.Var(name, dist, data)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/model.py", line 288, in Var
transform=dist.transform)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/model.py", line 689, in __init__
transformed_name = "{}_{}_".format(name, transform.name)
AttributeError: 'int' object has no attribute 'name'

# Fixed code
def __init__(self, *args, **kwargs):
    first, args = args[0], args[1:]
    super(self, _BoundedDist).__init__(
        first, distribution, lower, upper, *args, **kwargs
    )
# Buggy code
def run(n=1000):
    if n == "short":
        n = 50
    with garch:
        tr = sample(n)


# Traceback (AttributeError)
Traceback (most recent call last):
File "garch_example.py", line 40, in <module>
beta1 = BoundedNormal('beta1', 0, sd=1e6)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/distributions/continuous.py", line 1102, in __call__
*args, **kwargs)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/distributions/distribution.py", line 27, in __new__
return model.Var(name, dist, data)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/model.py", line 288, in Var
transform=dist.transform)
File "/Users/**/anaconda3/envs/py35/lib/python3.5/site-packages/pymc3/model.py", line 689, in __init__
transformed_name = "{}_{}_".format(name, transform.name)
AttributeError: 'int' object has no attribute 'name'

# Fixed code
def run(n=1000):
    if n == "short":
        n = 50
    with get_garch_model():
        tr = sample(n, n_init=10000)
    return tr
# Buggy code
def random(self, point=None, size=None, repeat=None):
    def random_choice(*args, **kwargs):
        w = kwargs.pop("w")
        w /= w.sum(axis=-1, keepdims=True)
        k = w.shape[-1]

        if w.ndim > 1:
            return np.row_stack([np.random.choice(k, p=w_) for w_ in w])
        else:
            return np.random.choice(k, p=w, *args, **kwargs)

    w = draw_values([self.w], point=point)

    w_samples = generate_samples(
        random_choice,
        w=w,
        broadcast_shape=w.shape[:-1] or (1,),
        dist_shape=self.shape,
        size=size,
    ).squeeze()
    comp_samples = self._comp_samples(point=point, size=size, repeat=repeat)

    if comp_samples.ndim > 1:
        return np.squeeze(comp_samples[np.arange(w_samples.size), w_samples])
    else:
        return np.squeeze(comp_samples[w_samples])


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-16-2fd0a2e33b32> in <module>()
5
6 with model:
----> 7     pp_trace = pm.sample_ppc(trace, PP_SAMPLES, random_seed=SEED)

/Users/fonnescj/Repos/pymc3/pymc3/sampling.py in sample_ppc(trace, samples, model, vars, size, random_seed, progressbar)
537             param = trace[idx]
538             for var in vars:
--> 539                 vals = var.distribution.random(point=param, size=size)
540                 ppc[var.name].append(vals)
541     finally:

/Users/fonnescj/Repos/pymc3/pymc3/distributions/mixture.py in random(self, point, size, repeat)
130         w_samples = generate_samples(random_choice,
131                                      w=w,
--> 132                                      broadcast_shape=w.shape[:-1] or (1,),
133                                      dist_shape=self.shape,
134                                      size=size).squeeze()

AttributeError: 'list' object has no attribute 'shape'

# Fixed code
def random(self, point=None, size=None, repeat=None):
    def random_choice(*args, **kwargs):
        w = kwargs.pop("w")
        w /= w.sum(axis=-1, keepdims=True)
        k = w.shape[-1]

        if w.ndim > 1:
            return np.row_stack([np.random.choice(k, p=w_) for w_ in w])
        else:
            return np.random.choice(k, p=w, *args, **kwargs)

    w = draw_values([self.w], point=point)[0]

    w_samples = generate_samples(
        random_choice,
        w=w,
        broadcast_shape=w.shape[:-1] or (1,),
        dist_shape=self.shape,
        size=size,
    ).squeeze()
    comp_samples = self._comp_samples(point=point, size=size, repeat=repeat)

    if comp_samples.ndim > 1:
        return np.squeeze(comp_samples[np.arange(w_samples.size), w_samples])
    else:
        return np.squeeze(comp_samples[w_samples])
# Buggy code
def forward(self, x):
    a = self.a
    r = tt.log(x - a)
    return r


# Traceback (MissingInputError)
Traceback (most recent call last):

File "<ipython-input-1-e7f2b743f1a1>", line 5, in <module>
pm.sample(1000)

File "/usr/local/lib/python3.5/dist-packages/pymc3/sampling.py", line 273, in sample
return sample_func(**sample_args)[discard:]

File "/usr/local/lib/python3.5/dist-packages/pymc3/sampling.py", line 288, in _sample
for it, strace in enumerate(sampling):

File "/usr/local/lib/python3.5/dist-packages/tqdm/_tqdm.py", line 862, in __iter__
for obj in iterable:

File "/usr/local/lib/python3.5/dist-packages/pymc3/sampling.py", line 367, in _iter_sample
_update_start_vals(start, model.test_point, model)

File "/usr/local/lib/python3.5/dist-packages/pymc3/sampling.py", line 483, in _update_start_vals
b[tname] = transform_func[0].forward(a[name]).eval()

File "/usr/local/lib/python3.5/dist-packages/theano/gof/graph.py", line 516, in eval
self._fn_cache[inputs] = theano.function(inputs, self)

File "/usr/local/lib/python3.5/dist-packages/theano/compile/function.py", line 326, in function
output_keys=output_keys)

File "/usr/local/lib/python3.5/dist-packages/theano/compile/pfunc.py", line 486, in pfunc
output_keys=output_keys)

File "/usr/local/lib/python3.5/dist-packages/theano/compile/function_module.py", line 1807, in orig_function
output_keys=output_keys).create(

File "/usr/local/lib/python3.5/dist-packages/theano/compile/function_module.py", line 1446, in __init__
accept_inplace)

File "/usr/local/lib/python3.5/dist-packages/theano/compile/function_module.py", line 177, in std_fgraph
update_mapping=update_mapping)

File "/usr/local/lib/python3.5/dist-packages/theano/gof/fg.py", line 174, in __init__
self.__import_r__(output, reason="init")

File "/usr/local/lib/python3.5/dist-packages/theano/gof/fg.py", line 345, in __import_r__
self.__import__(variable.owner, reason=reason)

File "/usr/local/lib/python3.5/dist-packages/theano/gof/fg.py", line 390, in __import__
raise MissingInputError(error_msg, variable=r)

MissingInputError: Input 0 of the graph (indices start from 0), used to compute sigmoid(a1_interval__), was not provided and not given a value. Use the Theano flag exception_verbosity='high', for more information on this error.

# Fixed code
def forward(self, x):
    a = self.a
    return tt.log(x - a)
# Buggy code
def forward(self, x):
    b = self.b
    r = tt.log(b - x)
    return r


# Traceback (MissingInputError)
Traceback (most recent call last):

File "<ipython-input-1-e7f2b743f1a1>", line 5, in <module>
pm.sample(1000)

File "/usr/local/lib/python3.5/dist-packages/pymc3/sampling.py", line 273, in sample
return sample_func(**sample_args)[discard:]

File "/usr/local/lib/python3.5/dist-packages/pymc3/sampling.py", line 288, in _sample
for it, strace in enumerate(sampling):

File "/usr/local/lib/python3.5/dist-packages/tqdm/_tqdm.py", line 862, in __iter__
for obj in iterable:

File "/usr/local/lib/python3.5/dist-packages/pymc3/sampling.py", line 367, in _iter_sample
_update_start_vals(start, model.test_point, model)

File "/usr/local/lib/python3.5/dist-packages/pymc3/sampling.py", line 483, in _update_start_vals
b[tname] = transform_func[0].forward(a[name]).eval()

File "/usr/local/lib/python3.5/dist-packages/theano/gof/graph.py", line 516, in eval
self._fn_cache[inputs] = theano.function(inputs, self)

File "/usr/local/lib/python3.5/dist-packages/theano/compile/function.py", line 326, in function
output_keys=output_keys)

File "/usr/local/lib/python3.5/dist-packages/theano/compile/pfunc.py", line 486, in pfunc
output_keys=output_keys)

File "/usr/local/lib/python3.5/dist-packages/theano/compile/function_module.py", line 1807, in orig_function
output_keys=output_keys).create(

File "/usr/local/lib/python3.5/dist-packages/theano/compile/function_module.py", line 1446, in __init__
accept_inplace)

File "/usr/local/lib/python3.5/dist-packages/theano/compile/function_module.py", line 177, in std_fgraph
update_mapping=update_mapping)

File "/usr/local/lib/python3.5/dist-packages/theano/gof/fg.py", line 174, in __init__
self.__import_r__(output, reason="init")

File "/usr/local/lib/python3.5/dist-packages/theano/gof/fg.py", line 345, in __import_r__
self.__import__(variable.owner, reason=reason)

File "/usr/local/lib/python3.5/dist-packages/theano/gof/fg.py", line 390, in __import__
raise MissingInputError(error_msg, variable=r)

MissingInputError: Input 0 of the graph (indices start from 0), used to compute sigmoid(a1_interval__), was not provided and not given a value. Use the Theano flag exception_verbosity='high', for more information on this error.

# Fixed code
def forward(self, x):
    b = self.b
    return tt.log(b - x)
# Buggy code
def random(self, point=None, size=None, repeat=None):
    sd = draw_values([self.sd], point=point)
    return generate_samples(
        stats.halfnorm.rvs, loc=0.0, scale=sd, dist_shape=self.shape, size=size
    )


# Traceback (TypeError)
TypeError Traceback (most recent call last)
in ()
1 ann_input.set_value(X_test)
2 ann_output.set_value(Y_test)
----> 3 ppc = pm.sample_ppc(trace, model=neural_network, samples=500, progressbar=False)
4

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\sampling.py in sample_ppc(trace, samples, model, vars, size, random_seed, progressbar)
526 for var in vars:
527 ppc[var.name].append(var.distribution.random(point=param,
--> 528 size=size))
529
530 return {k: np.asarray(v) for k, v in ppc.items()}

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\discrete.py in random(self, point, size, repeat)
152
153 def random(self, point=None, size=None, repeat=None):
--> 154 p = draw_values([self.p], point=point)
155 return generate_samples(stats.bernoulli.rvs, p,
156 dist_shape=self.shape,

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\distribution.py in draw_values(params, point)
183 if not isinstance(node, (tt.sharedvar.TensorSharedVariable,
184 tt.TensorConstant)):
--> 185 givens[name] = (node, draw_value(node, point=point))
186 values = [None for _ in params]
187 for i, param in enumerate(params):

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\distribution.py in draw_value(param, point, givens)
251 except:
252 shape = param.shape
--> 253 if len(shape) == 0 and len(value) == 1:
254 value = value[0]
255 return value

TypeError: object of type 'TensorVariable' has no len()

# Fixed code
def random(self, point=None, size=None, repeat=None):
    sd = draw_values([self.sd], point=point)[0]
    return generate_samples(
        stats.halfnorm.rvs, loc=0.0, scale=sd, dist_shape=self.shape, size=size
    )
# Buggy code
def random(self, point=None, size=None, repeat=None):
    lam = draw_values([self.lam], point=point)
    return generate_samples(
        np.random.exponential, scale=1.0 / lam, dist_shape=self.shape, size=size
    )


# Traceback (TypeError)
TypeError Traceback (most recent call last)
in ()
1 ann_input.set_value(X_test)
2 ann_output.set_value(Y_test)
----> 3 ppc = pm.sample_ppc(trace, model=neural_network, samples=500, progressbar=False)
4

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\sampling.py in sample_ppc(trace, samples, model, vars, size, random_seed, progressbar)
526 for var in vars:
527 ppc[var.name].append(var.distribution.random(point=param,
--> 528 size=size))
529
530 return {k: np.asarray(v) for k, v in ppc.items()}

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\discrete.py in random(self, point, size, repeat)
152
153 def random(self, point=None, size=None, repeat=None):
--> 154 p = draw_values([self.p], point=point)
155 return generate_samples(stats.bernoulli.rvs, p,
156 dist_shape=self.shape,

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\distribution.py in draw_values(params, point)
183 if not isinstance(node, (tt.sharedvar.TensorSharedVariable,
184 tt.TensorConstant)):
--> 185 givens[name] = (node, draw_value(node, point=point))
186 values = [None for _ in params]
187 for i, param in enumerate(params):

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\distribution.py in draw_value(param, point, givens)
251 except:
252 shape = param.shape
--> 253 if len(shape) == 0 and len(value) == 1:
254 value = value[0]
255 return value

TypeError: object of type 'TensorVariable' has no len()

# Fixed code
def random(self, point=None, size=None, repeat=None):
    lam = draw_values([self.lam], point=point)[0]
    return generate_samples(
        np.random.exponential, scale=1.0 / lam, dist_shape=self.shape, size=size
    )
# Buggy code
def random(self, point=None, size=None, repeat=None):
    beta = draw_values([self.beta], point=point)
    return generate_samples(self._random, beta, dist_shape=self.shape, size=size)


# Traceback (TypeError)
TypeError Traceback (most recent call last)
in ()
1 ann_input.set_value(X_test)
2 ann_output.set_value(Y_test)
----> 3 ppc = pm.sample_ppc(trace, model=neural_network, samples=500, progressbar=False)
4

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\sampling.py in sample_ppc(trace, samples, model, vars, size, random_seed, progressbar)
526 for var in vars:
527 ppc[var.name].append(var.distribution.random(point=param,
--> 528 size=size))
529
530 return {k: np.asarray(v) for k, v in ppc.items()}

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\discrete.py in random(self, point, size, repeat)
152
153 def random(self, point=None, size=None, repeat=None):
--> 154 p = draw_values([self.p], point=point)
155 return generate_samples(stats.bernoulli.rvs, p,
156 dist_shape=self.shape,

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\distribution.py in draw_values(params, point)
183 if not isinstance(node, (tt.sharedvar.TensorSharedVariable,
184 tt.TensorConstant)):
--> 185 givens[name] = (node, draw_value(node, point=point))
186 values = [None for _ in params]
187 for i, param in enumerate(params):

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\distribution.py in draw_value(param, point, givens)
251 except:
252 shape = param.shape
--> 253 if len(shape) == 0 and len(value) == 1:
254 value = value[0]
255 return value

TypeError: object of type 'TensorVariable' has no len()

# Fixed code
def random(self, point=None, size=None, repeat=None):
    beta = draw_values([self.beta], point=point)[0]
    return generate_samples(self._random, beta, dist_shape=self.shape, size=size)
# Buggy code
def random(self, point=None, size=None, repeat=None):
    p = draw_values([self.p], point=point)
    return generate_samples(stats.bernoulli.rvs, p, dist_shape=self.shape, size=size)


# Traceback (TypeError)
TypeError Traceback (most recent call last)
in ()
1 ann_input.set_value(X_test)
2 ann_output.set_value(Y_test)
----> 3 ppc = pm.sample_ppc(trace, model=neural_network, samples=500, progressbar=False)
4

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\sampling.py in sample_ppc(trace, samples, model, vars, size, random_seed, progressbar)
526 for var in vars:
527 ppc[var.name].append(var.distribution.random(point=param,
--> 528 size=size))
529
530 return {k: np.asarray(v) for k, v in ppc.items()}

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\discrete.py in random(self, point, size, repeat)
152
153 def random(self, point=None, size=None, repeat=None):
--> 154 p = draw_values([self.p], point=point)
155 return generate_samples(stats.bernoulli.rvs, p,
156 dist_shape=self.shape,

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\distribution.py in draw_values(params, point)
183 if not isinstance(node, (tt.sharedvar.TensorSharedVariable,
184 tt.TensorConstant)):
--> 185 givens[name] = (node, draw_value(node, point=point))
186 values = [None for _ in params]
187 for i, param in enumerate(params):

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\distribution.py in draw_value(param, point, givens)
251 except:
252 shape = param.shape
--> 253 if len(shape) == 0 and len(value) == 1:
254 value = value[0]
255 return value

TypeError: object of type 'TensorVariable' has no len()

# Fixed code
def random(self, point=None, size=None, repeat=None):
    p = draw_values([self.p], point=point)[0]
    return generate_samples(stats.bernoulli.rvs, p, dist_shape=self.shape, size=size)
# Buggy code
def random(self, point=None, size=None, repeat=None):
    mu = draw_values([self.mu], point=point)
    return generate_samples(stats.poisson.rvs, mu, dist_shape=self.shape, size=size)


# Traceback (TypeError)
TypeError Traceback (most recent call last)
in ()
1 ann_input.set_value(X_test)
2 ann_output.set_value(Y_test)
----> 3 ppc = pm.sample_ppc(trace, model=neural_network, samples=500, progressbar=False)
4

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\sampling.py in sample_ppc(trace, samples, model, vars, size, random_seed, progressbar)
526 for var in vars:
527 ppc[var.name].append(var.distribution.random(point=param,
--> 528 size=size))
529
530 return {k: np.asarray(v) for k, v in ppc.items()}

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\discrete.py in random(self, point, size, repeat)
152
153 def random(self, point=None, size=None, repeat=None):
--> 154 p = draw_values([self.p], point=point)
155 return generate_samples(stats.bernoulli.rvs, p,
156 dist_shape=self.shape,

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\distribution.py in draw_values(params, point)
183 if not isinstance(node, (tt.sharedvar.TensorSharedVariable,
184 tt.TensorConstant)):
--> 185 givens[name] = (node, draw_value(node, point=point))
186 values = [None for _ in params]
187 for i, param in enumerate(params):

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\distribution.py in draw_value(param, point, givens)
251 except:
252 shape = param.shape
--> 253 if len(shape) == 0 and len(value) == 1:
254 value = value[0]
255 return value

TypeError: object of type 'TensorVariable' has no len()

# Fixed code
def random(self, point=None, size=None, repeat=None):
    mu = draw_values([self.mu], point=point)[0]
    return generate_samples(stats.poisson.rvs, mu, dist_shape=self.shape, size=size)
# Buggy code
def random(self, point=None, size=None, repeat=None):
    p = draw_values([self.p], point=point)
    return generate_samples(np.random.geometric, p, dist_shape=self.shape, size=size)


# Traceback (TypeError)
TypeError Traceback (most recent call last)
in ()
1 ann_input.set_value(X_test)
2 ann_output.set_value(Y_test)
----> 3 ppc = pm.sample_ppc(trace, model=neural_network, samples=500, progressbar=False)
4

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\sampling.py in sample_ppc(trace, samples, model, vars, size, random_seed, progressbar)
526 for var in vars:
527 ppc[var.name].append(var.distribution.random(point=param,
--> 528 size=size))
529
530 return {k: np.asarray(v) for k, v in ppc.items()}

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\discrete.py in random(self, point, size, repeat)
152
153 def random(self, point=None, size=None, repeat=None):
--> 154 p = draw_values([self.p], point=point)
155 return generate_samples(stats.bernoulli.rvs, p,
156 dist_shape=self.shape,

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\distribution.py in draw_values(params, point)
183 if not isinstance(node, (tt.sharedvar.TensorSharedVariable,
184 tt.TensorConstant)):
--> 185 givens[name] = (node, draw_value(node, point=point))
186 values = [None for _ in params]
187 for i, param in enumerate(params):

C:\Users\Nikos\Documents\Lasagne\python-3.4.4.amd64\lib\site-packages\pymc3\distributions\distribution.py in draw_value(param, point, givens)
251 except:
252 shape = param.shape
--> 253 if len(shape) == 0 and len(value) == 1:
254 value = value[0]
255 return value

TypeError: object of type 'TensorVariable' has no len()

# Fixed code
def random(self, point=None, size=None, repeat=None):
    p = draw_values([self.p], point=point)[0]
    return generate_samples(np.random.geometric, p, dist_shape=self.shape, size=size)