# Vectorizing slow theano variable operations

**URL:** <https://discourse.pymc.io/t/vectorizing-slow-theano-variable-operations/10315>\
**Category:** version agnostic\
**Tags:** theano, aesara\
**Created:** [September 6, 2022, 10:31am UTC](https://discourse.pymc.io/t/vectorizing-slow-theano-variable-operations/10315 "2022-09-06T10:31:55Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![randomson](https://avatars.discourse-cdn.com/v4/letter/r/e19b73/32.png) [@randomson](https://discourse.pymc.io/u/randomson)\
**Post date:** [September 6, 2022, 10:31am UTC](https://discourse.pymc.io/t/vectorizing-slow-theano-variable-operations/10315/1 "2022-09-06T10:31:55Z")

</div>

I am trying to compute the function below with theano/aesara in an preferably vectorized manner:

![image](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/4/44e6dcdc57bd1f1c2a9128ddf0333824c3b0be11.png)

The solution i have is not vectorized and therefore way too slow:

```auto
def apply_adstock_with_lag(x, L, P, D):
    """
    params:
    x: original array
    L: length
    P: peak, delay in effect
    D: decay, retain
    """
    x = np.append(np.zeros(L - 1), x)

    weights = [0 for _ in range(L)]
    for l in range(L):
        weight = D **((l - P)** 2)
        weights[L - 1 - l] = weight
    weights = np.array(weights)
    adstocked_x = []
    for i in range(L - 1, len(x)):
        x_array = x[i - L + 1:i + 1]
        xi = sum(x_array * weights) / sum(weights)
        adstocked_x.append(xi)
    adstocked_x = tt.as_tensor_variable(adstocked_x)
    return adstocked_x

```

An similar function although simplier and its vectorized solution can be found below, note that this is much much quicker probably due to the vectorized operations:

![image](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/d/d3b90f07e3c680fa6f5eba80eb8131d16e831f13.png)

```auto
def adstock_geometric_theano_pymc3(x, theta):
    x = tt.as_tensor_variable(x)

    def adstock_geometric_recurrence_theano(index, input_x, decay_x, theta):
        return tt.set_subtensor(decay_x[index], tt.sum(input_x + theta * decay_x[index - 1]))

    len_observed = x.shape[0]

    x_decayed = tt.zeros_like(x)
    x_decayed = tt.set_subtensor(x_decayed[0], x[0])

    output, _ = theano.scan(
        fn=adstock_geometric_recurrence_theano,
        sequences=[tt.arange(1, len_observed), x[1:len_observed]],
        outputs_info=x_decayed,
        non_sequences=theta,
        n_steps=len_observed - 1
    )

    return output[-1]

```

I cant come up with the vectorized solution to my adstock-function, can anyone give it a go?
