Error message in jags - Attempt to redefine node - jags

I'm trying to run a non-homogeneous Markov Chain in JAGS. I have something wrong because when I run my code I get the following error:
RUNTIME ERROR:
Compilation error on line 5.
Attempt to redefine node y[2,2,1]
I'd appreciate any help.
model
{
for (t in 2:T){
for (m in 1:M){
y[t,x[t-1,m],m]~dcat(p[t,m,x[t-1,m],1:J])
#Individual transition data where m represents individual index
y[t,x[t-1,m],m]<-x[t,m]
}}
#hyper parameter
for (t in 2:T){
for (m in 1:M){
for (i in 1:I){
for (j in 1:J){
p[t,m,i,j]<-phi[t,m,i,j]/sum(phi[t,m,i,1:J])
}}}}
for (t in 2:T){
for (m in 1:M){
for (i in 1:I){
for (j in 1:J){
log(phi[t,m,i,j])<-gamma1[t,j]+gamma2[t,i,j]+beta[i,j]*age[t,m]
}}}}
#define the component with multivariate normal
for (t in 2:T){
gamma1[t,1:J]~dmnorm(gamma1[t-1,1:J],W1[1:J,1:J])
}
gamma1[1,1:J]~dmnorm(mu.gamma1[1:J],W1[1:J,1:J])
for (t in 2:T){
for (i in 1:I){
gamma2[t,i,1:J]~dmnorm(gamma2[t-1,i,1:J],W2[1:J,1:J])
}}
for (i in 1:I){
gamma2[1,i,1:J]~dmnorm(mu.gamma2[i,1:J],W2[1:J,1:J])
}
for (i in 1:I){
beta[i,1:J]~dmnorm(mu.beta[i,1:J],W.beta[1:J,1:J])
}
W1[1:J,1:J]~dwish(R[1:J,1:J],5)
W2[1:J,1:J]~dwish(R[1:J,1:J],5)
W.beta[1:J,1:J]~dwish(R[1:J,1:J],5)
#loglikelihood
for (t in 2:T){
for (m in 1:M){
llike[t,m]<-log(p[t,m,x[t-1,m],x[t,m]])
}}
for (t in 2:T){
sumllike.t[t]<-sum(llike[t,1:M])
}
#Deviance
D<--2*sum(sumllike.t[2:T])
}

Related

Running a stateful Hedgehog generator

I've taken the following tree generator:
genTree0 :: MonadGen m => m (Tree String)
genTree0 =
Gen.recursive Gen.choice
[ Node "X" [] ]
[ Node "X" <$> Gen.list (Range.linear 0 20) genTree0 ]
and rewritten it into a stateful one:
genTree1 :: (MonadGen m, MonadState Int m) => m (Tree String)
genTree1 =
Gen.recursive Gen.choice
[ (`Node` []) <$> next ]
[ Node <$> next <*> Gen.list (Range.linear 0 20) genTree1 ]
where
next :: MonadState Int m => m String
next = fmap show (get <* modify (+1))
But whereas I could before write e.g.
Gen.sample genTree >= putStrLn . drawTree
I can no longer do that with the stateful version, because surely I have not initialized the state:
> Gen.sample genTree
<interactive>:149:12: error:
• No instance for (MonadState Int Identity)
arising from a use of ‘genTree’
Trying to fix this (assuming but not being fully convinced that GenT and StateT commute),
> Gen.sample (evalStateT genTree 0)
<interactive>:5:23: error:
• Could not deduce (MonadGen
(StateT Int (Hedgehog.Internal.Gen.GenT Identity)))
I think there's a very small, last part related to type families that I'm not grokking. What could that be? If, for example, I add
genTree1 :: ( MonadGen m
, MonadState Int m
, GenBase m ~ Identity)
=> m (Tree String)
(simply because I've seen this before)
I get another error instead,
> Gen.sample (runStateT genTree 0)
<interactive>:15:23: error:
• Couldn't match type ‘GenBase (StateT Int (GenT Identity))’
with ‘Identity’
Unfortunately, at this point, I just start guessing wrong at which constraint to apply.
Update: In another vein, I've tried to construct a specific monad transformer stack, since genTree0 and genTree1 have quite general signatures:
newtype StateGen s a = StateGen { runStateGen :: StateT s (GenT IO) a }
deriving ( Functor, Applicative, Monad
, MonadState s
, MonadGen
, MonadIO
)
but this is also slightly wrong wrt. at least MonadGen.
What must I type here, to get going, and better yet, where can I learn a better way than guessing?

Returning a bare struct from C to Haskell in c2hs

I'm trying to bind to a C function that returns a struct (by value). I know I can wrap it manually using the FFI, but can't figure out how to coax c2hs into generating the correct code. It seems to think my function is returning a pointer.
Here's a simple example:
module Point where
#c
struct point {
int x;
int y;
};
struct point get_zero(void);
#endc
data Point = Point { x :: Int, y :: Int }
instance Storable Point where
sizeOf _ = {#sizeof point#}
alignment _ = {#alignof point#}
peek p = point <$> liftA fromIntegral ({#get point.x #} p)
<*> liftA fromIntegral ({#get point.y #} p)
poke p s = do {#set point.x #} p (fromIntegral $ x s)
{#set point.y #} p (fromIntegral $ y s)
{#pointer *point as PointPtr -> Point#}
-- Causes error:
{#fun get_zero as ^ { } -> `Point'#}
The error:
c2hs: Errors during expansion of binding hooks:
Point.chs:25: (column 28) [ERROR] >>> Missing "out" marshaller!
There is no default marshaller for this combination of Haskell and C type:
Haskell type: Point
C type : (Ptr ())
It is not possible currently. You can make a wrapper that returns the result by pointer:
void get_zero_wrapper(struct point* p) {
*p = get_zero();
}
Note that you have to allocate space for the structure, e.g. using alloca.
There is a proposal to support passing and returning C structures by value in FFI. But it is unlikely to be implemented in near future because it didn't get enough attention from the community. The proposal needs more careful design, e.g. it is not clear how it will work with other language features.

Trying to make my typeclass/instance. GHC says "Could not deduce..."

I am trying to make a simple graph structure and I wrote the following. But GHG raises error and I stacked there. This is the first time I make my own typeclass so maybe I am doing something terribly wrong. Can somebody explain what is wrong?
I found a similar question but I don't think it applies to my case.:
Error binding type variables in instance of typeclass
class Link l where
node :: (Node n) => l -> n
class Node n where
links :: (Link l) => n -> [l]
data (Node n) => SimpleLink n =
SimpleLink
{ simpleLinkNode :: n
} deriving (Show, Read, Eq)
instance (Node n) => Link (SimpleLink n) where
node = simpleLinkNode
data (Link l) => SimpleNode l =
SimpleNode
{ simpleNodeLinks :: [l]
} deriving (Show, Read, Eq)
instance (Link l) => Node (SimpleNode l) where
links = simpleNodeLinks
This is the error message I've got:
***.hs:13:10:Could not deduce (n ~ n1)
from the context (Node n)
bound by the instance declaration
at ***.hs:12:10-40
or from (Node n1)
bound by the type signature for
node :: Node n1 => SimpleLink n -> n1
at ***.hs:13:3-23
`n' is a rigid type variable bound by
the instance declaration
at ***.hs:12:16
`n1' is a rigid type variable bound by
the type signature for node :: Node n1 => SimpleLink n -> n1
at ***.hs:13:3
Expected type: SimpleLink n -> n1
Actual type: SimpleLink n -> n
In the expression: simpleLinkNode
In an equation for `node': node = simpleLinkNode
***.hs:21:11:Could not deduce (l ~ l1)
from the context (Link l)
bound by the instance declaration
at ***.hs:20:10-40
or from (Link l1)
bound by the type signature for
links :: Link l1 => SimpleNode l -> [l1]
at ***.hs:21:3-25
`l' is a rigid type variable bound by
the instance declaration
at ***.hs:20:16
`l1' is a rigid type variable bound by
the type signature for links :: Link l1 => SimpleNode l -> [l1]
at ***.hs:21:3
Expected type: SimpleNode l -> [l1]
Actual type: SimpleNode l -> [l]
In the expression: simpleNodeLinks
In an equation for `links': links = simpleNodeLinks
Edit 1
I tried some of Daniel's suggestions.
But I couldn't make them work.
constructor class
Got: "`n' is not applied to enough type arguments"
class Link l n where
node :: Node n l => l n -> n l
class Node n l where
links :: Link l n => n l -> [l n]
multi-parameter type class (MPTC)
Got: "Cycle in class declarations (via superclasses)"
class (Node n) => Link l n where
node :: l -> n
class (Link l) => Node n l where
links :: n -> [l]
MPTC with functional dependencies
Got: "Cycle in class declarations (via superclasses)"
class (Node n) => Link l n | l -> n where
node :: l -> n
class (Link l) => Node n l | n -> l where
links :: n -> [l]
Goal (Edit 2)
What I want to implement is a directed acyclic graph structure like the following (more specifically, a Factor graph).
(source: microsoft.com)
There are two kinds of node (white circle and red square) and they connect only to the different type of node, meaning that there are two kinds of links.
I want different version of nodes and links which have data (arrays) attached to them. I also want "vanilla" DAG which has only one type of node and link. But for traversing them, I want only one interface to do that.
The signature of the class methods
class Link l where
node :: (Node n) => l -> n
class Node n where
links :: (Link l) => n -> [l]
say that "whatever type the caller desires, node resp. links can produce it, as long as it's a member of Link resp. Node", but the implementation says that only one specific type of value can be produced.
It's fundamentally different from interfaces in OOP, where the implementation decides the type and the caller has to take it, here the caller decides.
You are running into kind problems with your constructor class attempt. Your classes take two parameters, l of kind kl and n of kind kn. The kinds of the arguments to (->) must both be *, the kind of types. So for l n to be a well-kinded argument of (->), l must be a type constructor taking an argument of kind kn and creating a result of kind *, i.e.
l :: kn -> *
Now you try to make the result type of node be n l, so that would mean
n :: kl -> *
But above we saw that kl = kn -> *, which yields
n :: (kn -> *) -> *
resp. kn = (kn -> *) -> *, which is an infinite kind. Infinite kinds, like infinite types, are not allowed. But kind-inference is implemented only very rudimentary, so the compiler assumes that the argument to l has kind *, but sees from n l that n has kind kl -> *, hence as an argument to l, n has the wrong kind, it is not applied to enough type arguments.
The normal use of constructor classes is a single-parameter class
class Link l where
node :: l nod -> nod
class Node n where
links :: n lin -> [lin]
-- note that we don't have constraints here, because the kinds don't fit
instance Link SimpleLink where
node = simpleLinkNode
instance Node SimpleNode where
links = simpleNodeLinks
You have to remove the DatatypeContexts from the data declarations,
They have been removed from the language (they are available via an extension)
They were never useful anyway
then the above compiles. I don't think it would help you, though. As Chris Kuklewicz observed, your types chase their own tail, you'd use them as
SimpleLink (SimpleNode (SimpleLink (SimpleNode ... {- ad infinitum -})))
For the multiparameter classes, you can't have each a requirement of the other, as the compiler says, that causes a dependency cycle (also, in your constraints you use them with only one parameter,
class Node n => Link l n where ...
which is malformed, the compiler would refuse that if the cycle is broken).
You could resolve the cycle by merging the classes,
class NodeLinks l n | l -> n, n -> l where
node :: l -> n
links :: n -> l
but you'd still have the problems that your types aren't useful for that.
I don't understand your goal well enough to suggest a viable solution, sorry.
Can somebody explain what is wrong?
An initial issue before I explain the error messages: Polymorphic data types are good, but in the end there has to be concrete type being used.
With SimpleNode of kind * -> * and SimpleLinks of kind * -> * there is no concrete type:
SimpleNode (SimpleLink (SimpleNode (SimpleLink (SimpleNode (...
You cannot have and infinite type in Haskell, though newtype and data get you closer:
type G0 = SimpleNode (SimpleLink G0) -- illegal
newtype G1 = G1 (SimpleNode (SimpleLink G1)) -- legal
data G2 = G2 (SimpleNode (SimpleLink G2)) -- legal
Perhaps you need to rethink your data types before creating the type class.
Now on to the error message explanation: Your type class Link defines a function node
class Link l where
node :: (Node n) => l -> n
The node is a magical OOP factory that, given the type and value of l, can then make any type n (bounded by Node n) the caller of node wishes. This n has nothing to do with the n in your instance:
instance (Node n) => Link (SimpleLink n) where
node = simpleLinkNode
To repeat myself: the n in the instance above is not the same n as in the node :: (Node n) => l -> n definition. The compiler makes a related but fresh name n1 and gives you the error:
`n' is a rigid type variable bound by
the instance declaration
at ***.hs:12:16
`n1' is a rigid type variable bound by
the type signature for node :: Node n1 => SimpleLink n -> n1
at ***.hs:13:3
The n in the instance is taken from the type (SimpleLink n) of the input to the node function. The n1 is the type that the caller of node is demanding that this magical factory produce. If n and n1 were the same then the compiler would be happy...but your definition of the type class and instance do not constrain this and thus the code snippet is rejected.
The analogous story is repeated for the error in SimpleLink. There is no silver-bullet fix for this. I expect that you need to rethink and redesign this, probably after reading other people's code in order to learn ways to accomplish your goal.
What is your goal? Graph data structures can be quite varied and the details matter.
I am breaking stack overflow etiquette and adding a second answer to keep this separate. This is a simple code example for a bipartite undirected graph with unlabeled edges, which might be useful to model a Factor Graph:
-- Bipartite graph representation, unlabeled edges
-- Data types to hold information about nodes, e.g. ID number
data VariableVertex = VV { vvID :: Int } deriving (Show)
data FactorVertex = FV { fvID :: Int } deriving (Show)
-- Node holds itself and a list of neighbors of the oppostite type
data Node selfType adjacentType =
N { self :: selfType
, adj :: [Node adjacentType selfType] }
-- A custom Show for Node to prevent infinite output
instance (Show a, Show b) => Show (Node a b) where
show (N x ys) = "Node "++ show x ++ " near " ++ show (map self ys)
-- Type aliases for the two node types that will be used
type VariableNode = Node VariableVertex FactorVertex
type FactorNode = Node FactorVertex VariableVertex
data FactorGraph = FG [VariableNode] [FactorNode] deriving (Show)
v1 = N (VV 1) [f1,f2]
v2 = N (VV 2) [f2]
v3 = N (VV 3) [f1,f3]
f1 = N (FV 1) [v1,v3]
f2 = N (FV 2) [v1,v2]
f3 = N (FV 3) [v3]
g = FG [v1,v2,v3] [f1,f2,f3]
With the hint from Chris Kuklewicz (http://stackoverflow.com/a/11450715/727827), I got the code I wanted in the first place.
However, I think Crhis's answer (using *Vertex to hold data) is simple and better. I am leaving this here to clarify what I wanted.
class NodeClass n where
adjacent :: n a b -> [n b a]
data Node selfType adjacentType =
N
{ selfNode :: selfType
, adjNode :: [Node adjacentType selfType] }
data NodeWithData selfType adjacentType =
NWD
{ selfNodeWithData :: selfType
, adjNodeWithData :: [NodeWithData adjacentType selfType]
, getDataWithData :: [Double]
}
instance NodeClass Node where
adjacent = adjNode
instance NodeClass NodeWithData where
adjacent = adjNodeWithData
data VariableVertex = VV { vvID :: Int } deriving (Show)
data FactorVertex = FV { fvID :: Int } deriving (Show)
type VariableNode = Node VariableVertex FactorVertex
type FactorNode = Node FactorVertex VariableVertex
type VariableNodeWithData = NodeWithData VariableVertex FactorVertex
type FactorNodeWithData = NodeWithData FactorVertex VariableVertex

Haskell data type error

I have this function:
data Memory = Memory
{visited::[Point]
,dfsstack::[Point]
,currentPoz::Point
}deriving(Eq)
perceiveAndAct :: SVal -> [Cardinal] -> a -> (Action, a)
perceiveAndAct s cs m
| elem W cs == True && elem N cs == True && elem E cs == True && elem S cs == False = (Just S, Memory (visited m) (dfsstack m) (currentPoz m))
putting m instead of Memory (visited m) (dfsstack m) (currentPoz m) works fine, else it gives me that:
Couldn't match expected type `(a, b)'
against inferred type `Memory -> Point'
In the first argument of `fst', namely `currentPoz'
In the first argument of `($)', namely `fst currentPoz'
In the expression: fst currentPoz $ currentPoz m
What could be the problem?
The type you gave perceiveAndAct is very polymorphic. Compare:
id :: a -> a
id m = m -- the only correct implementation
id m = Memory (visited m) (dfsstack m) (currentPoz m) -- type error
-- only works for Memory, not all possible a
idMemory :: Memory -> Memory
id m = m -- this is fine
id m = Memory (visited m) (dfsstack m) (currentPoz m) -- also correct
However, I'm a little confused, since the type error you pasted does not match the type error I get when I make the change you claimed you made. Perhaps you'd better paste the exact code you use that gives an error together with the exact error you got, rather than the correct code and the error for some invisible code we can't see.
visited, dfsstack, and currentPoz are functions, and they don't construct lists.
You want to write Memory [m] [m] m, instead.
visited, dfsstack, and currentPoz are functions which, given someData :: Memory, can extract each of these elements.
You'll also need to change the type of perceiveAndAct's argument "m" from :: a to :: Point

parsec-3.1.0 with custom token datatype

parsec-3.1.0 ( http://hackage.haskell.org/package/parsec-3.1.0 )
works with any token type. However there are combinators like Text.Parsec.Char.satisfy that are only defined for Char datatype. There doesn't seem to be any more general counterpart available.
Should I define my own versions or did I miss something?
Perhaps there are different parser libraries in Haskell that allows:
custom token types
custom parser state (I need to parse stateful format - Wavefront OBJ)
Generalized versions of oneOf, noneOf, and anyChar can be built out of a generalized satisfy, easily enough:
oneOfT :: (Eq t, Show t, Stream s m t) => [t] -> ParsecT s u m t
oneOfT ts = satisfyT (`elem` ts)
noneOfT :: (Eq t, Show t, Stream s m t) => [t] -> ParsecT s u m t
noneOfT ts = satisfyT (not . (`elem` ts))
anyT :: (Show t, Stream s m t) => ParsecT s u m t
anyT = satisfyT (const True)
satisfyT :: (Show t, Stream s m t) => (t -> Bool) -> ParsecT s u m t
satisfyT p = tokenPrim showTok nextPos testTok
where
showTok t = show t
testTok t = if p t then Just t else Nothing
nextPos p t s = -- however you update position for your token stream
It might seem that the generalization of these seems missing, but you'll notice that these generalizations here make certain assumptions about the type t that may not be true for someone's token type. It is assumed to be an instance of Show and Eq, yet I can imagine token types for which they are displayed some other way than show, and that membership in a class of tokens might be achieved via some method other than == and elem.
Lastly, once your token type is no longer a Char, how you choose to represent position, and thus updated it, is highly dependent on your representation of tokens and streams.
Hence, I can see why a more generalized form doesn't exist.

Resources