Unusual piecewise functions in stan

Hi,
I was hoping to get some advice on how to code an unusual piecewise function in stan.

I have a scalar predictor variable x that is predicting a vector variable \vec{y}. It does so in a piecewise way with an unknown number of changepoints x_1,x_2... x_n. This is linked to a piecewise vector constant function \vec{v}(x)=\vec{v_1},\vec{v_2},...\vec{v_{n-1}}. Additionally there is a scalar part to the function that looks like f(x) = 1 - Betacdf(x,\alpha,\beta) .

For x_n<x<x_{n+1} we get the formula for y

\vec{y}(x)=\vec{v_n}[f(x)-f(x_{n+1})]+\vec{y}(x_{n+1})

and \vec{y}(1) = \vec{0}

If there were 0 changepoints, then we would simply get the relationship.
\vec{y}(x)=\vec{v}f(x)

For graphical demonstration, I have an image of y (in 2 dimensional space) evaluated at a set of x values in a case with 2 change points. Note that the vectors come out of the endpoints of the previous vector.

Does anybody have any advice for creating a piecewise function like this in Stan, particularly for an unknown number of changepoints? I think I would need a parameter for an unknown number of changepoints (perhaps with geometric prior), a set of \vec{v} parameters, an \alpha and \beta parameter, and values of x (data) as inputs.

I don’t know anything about piecewise functions and your example seems to be one of the more complex ones. However I can say that the following is a Stan red flag.

I think this implies that you have an unknown discrete parameter and Stan doesn’t deal with those. You need to find a way to mathematically marginalize the discrete parameter out of the likelihood. This comes up a lot on the forum here with models that try to model count data with missing values. If you have a low upper bound on the number of potential change points you might be able to model the number of change points but it’s not going to be pretty.