Re: Problem with compile fct. and Thread
- To: mathgroup at smc.vnet.net
- Subject: [mg124578] Re: Problem with compile fct. and Thread
- From: "Oleksandr Rasputinov" <oleksandr_rasputinov at hmamail.com>
- Date: Wed, 25 Jan 2012 07:06:19 -0500 (EST)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- References: <jfm01p$js0$1@smc.vnet.net>
On Tue, 24 Jan 2012 10:10:01 -0000, kristoph <kristophs.post at web.de> wrote:
> Hi
>
> I get an error when trying to compute the following "toy" code:
>
> (*the compile function*)
> test=Compile[{{bw,_Real},{regData,_Real,1},{leg,_Integer}},
> Module[{h,tab2,xMat},
> h=1;
> tab2=Table[(regData[[i]]-regData[[j]]),{i,1,leg},{j,1,leg}];
> xMat=Thread[{1.,tab2[[h]]}]
> ]
> ,CompilationOptions->{"InlineExternalDefinitions"->True}];
>
> (*generating random sample data*)
> leg=100;
> data=RandomReal[{0,1},leg];
> bw=.1;
>
> (*using the compile function with the above generated data, produces
> the error*)
> test[bw, data, leg]
>
> The function "test" works fine if I construct the matrix "xMat" using
> the function Table. However, I prefer Thread because it is twice as
> fast.
>
> I just do not see where my mistake is. I do appreciate any
> suggestions. Thanks in advance.
> Cheers,
> Kris
>
The problem again is with the types of various expressions, but this time
it is caused by a call out of the compiled code in evaluating Thread[...].
In such cases one must explicitly specify the return type one expects for
expressions matching a given pattern using the third argument of Compile,
which in this case should be {{_Thread, _Real, 2}}:
test = Compile[
{{bw, _Real}, {regData, _Real, 1}, {leg, _Integer}},
Module[{h = 1, tab2 = {{0., 0.}}, xMat = {{0., 0.}}},
tab2 = Table[
regData[[i]] - regData[[j]],
{i, 1, leg}, {j, 1, leg}
];
xMat = Thread[{1., tab2[[h]]}]
], {{_Thread, _Real, 2}},
CompilationOptions -> {"InlineExternalDefinitions" -> True}
];
A better way to write it is to avoid the call out of compiled code
altogether. There also isn't any reason to use xMat here and it introduces
a needless copy operation on the final result, so one may as well remove
this too, ending up with the following:
test2 = Compile[
{{bw, _Real}, {regData, _Real, 1}, {leg, _Integer}},
Module[{h = 1, tab2 = {{0., 0.}}},
tab2 = Table[
regData[[i]] - regData[[j]],
{i, 1, leg}, {j, 1, leg}
];
Transpose[{
ConstantArray[1., Length@tab2[[h]]],
tab2[[h]]
}]
], CompilationOptions -> {"InlineExternalDefinitions" -> True}
];
As is probably clear by now, the use of compiled code is not without its
difficulties. (Also, incidentally, "InlineExternalDefinitions" -> True
doesn't serve any purpose for this example, but I left it in anyway.)