Re: Error in topological.sort(graph, mode = "out") : At core/properties/dag.c:114 : The graph has cycles; topological sorting is only possible in acyclic graphs, Invalid value

211 views
Skip to first unread message

Chris Paciorek

unread,
Sep 23, 2023, 4:21:39 PM9/23/23
to Yotsuba, nimble-users
Hi Yotsuba, 

I don't think you need the nimbleFunction to do the indexing. Can't you just write the for loop like this?

```
    for(i in 2:N){
        d[i] ~ dnorm(y[i],1)
        y[i] <- x[i-1]
        x[i] <- y[i]*scale+mu
    }
```

Using that representation, there is not a problem with cycles in the model graph. 

And actually you don't even really need `y`; you could just have

```
    for(i in 2:N){
        d[i] ~ dnorm(x[i-1],1)
        x[i] <- x[i-1]*scale+mu
    }
```
By having `y[i]` depend on the entire `x` vector, you're inducing unnecessary dependence in the model structure.

-chris

On Sat, Sep 23, 2023 at 1:48 AM Yotsuba <yotsuba...@gmail.com> wrote:
Dear all

I want to calculate like the example below in a model, where x is given some initial value and some processing is added to it. 
I want to use the processed x for the calculation in the next loop. This model is an example, the actual processing done on x is more complex. 
This kind of modeling will lead to errors like this.
Error in topological.sort(graph, mode = "out") : At core/properties/dag.c:114 : The graph has cycles; topological sorting is only possible in acyclic graphs, Invalid value
I think this error means that the nodes have been cycled, but due to the structure of my model, I want to use the same variable name created in the previous loop in the next loop, so I can't get out of the error.
 I would like to know if you have any suggestions.

mymodel<- nimbleCode({
  mu ~ dnorm(1,3)   #priors
  scal ~ dnorm(0.1,1)
  for (i in 2:N){
    y[i] <- get_prev_index(vec = x[1:N], index = i-1) # get x from previous loop. x and y are values that are provided and calculated in the model.
    d[i] ~ dnorm(y[i],1)  # calculate likelihood. d is data.
    x[i] <- y[i]*scal + mu # generate x to use next loop
  }
})
get_prev_index <- nimbleFunction(run = function(vec = double(2), index = integer(1)) {
    vec2 <- vec[index]
    return(vec2)
  })

Many thanks!
Yotsuba

--
You received this message because you are subscribed to the Google Groups "nimble-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nimble-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nimble-users/3fd08cca-3e61-4a16-8645-6a74055099f2n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages