Assuming many variables at once - maple

I'm trying to set up the following constraints:
assume(E1A::integer,E2A::integer,...,E2B::integer,...,E3C::integer)
additionally(E1A>=0,E2A>=0,...,E3C>=0)
additionally(E1A<=3,E2A<=3,...,E3C<=3)
is there any way to do this without typing out all the terms E1A, E2A,...,E3C? I tried doing
for i from 0 to 3 do (assume(EiA::integer)) end do
as a shortcut, but Maple didn't like that, presumably because it didn't view the i as an indexing variable.

You can form names by concatenation.
restart:
assume( seq( cat(`E`,i,`A`)::integer, i=1..3 ) );
And now, to test,
[ seq( cat(`E`,i,`A`), i=1..3 ) ]:
map( about, % ):
Originally E1A, renamed E1A~:
is assumed to be: integer
Originally E2A, renamed E2A~:
is assumed to be: integer
Originally E3A, renamed E3A~:
is assumed to be: integer
You can also nest seq, eg,
restart:
assume( seq( seq( cat(`E`,i,abc)::integer, i=1..3), abc=[A,B,C] ) );
[ seq( seq( cat(`E`,i,abc), i=1..3), abc=[A,B,C] ) ]:
map( about, % ):

With the elementwise operator and the concatenation operator you can get all your assuming down to one line:
assume(E||(1..3)||A ::~ AndProp(integer, RealRange(0,3)));

Related

How to define a sequence with condtions on the index?

I need to deal with the sequence a[i][j] with i<j, but I do not know if there exists a command to do this.
I am trying to manipulate as in the screenshot below, but it is still keeping the cases j<i.
The approach of generating the full set (i=1..n and j=1..n) and then removing the unwanted portion is unnecessarily inefficient.
Here are two more efficient ways (as well as that way using minus, but fixed to use the double-seq).
n:=4:
{seq( seq( d[i][j], j=i..n ), i=1..n )};
{d[1][1], d[1][2], d[1][3], d[1][4],
d[2][2], d[2][3], d[2][4],
d[3][3], d[3][4], d[4][4]}
{seq( seq( d[i][j], i=1..j ), j=1..n )};
{d[1][1], d[1][2], d[1][3], d[1][4],
d[2][2], d[2][3], d[2][4],
d[3][3], d[3][4], d[4][4]}
# The next is less efficient
{seq( seq( d[i][j], j=1..n ), i=1..n )}
minus {seq( seq( d[i][j], j=1..i-1 ), i=1..n )};
{d[1][1], d[1][2], d[1][3], d[1][4],
d[2][2], d[2][3], d[2][4],
d[3][3], d[3][4], d[4][4]}
For this question, I would go with the first method in #acer's answer. But just in case, if the condition on the indices were a bit complicated such that you could not quickly come up with an easy formulation that can be used to create your indices in the 1st method in that answer or to write as set minus of two indices set etc. then you can use the select command in Maple and the original condition that you have as a boolean function. Here is how it would work in your case.
n := 4:
idxs := select( pair -> pair[1] < pair[2], [ seq( seq( [i, j], j = 1..n ), i = 1..n ) ] );
You knew how to generate all [i, j]'s with no restriction, the second argument of the select command above. And your condition on them is; if you pick up a pair, its 1st element being less than its 2nd element. So we wrote the 1st argument of select above which is a boolean function, for each pair, if the condition holds, it returns true otherwise returns false. The select command picks up the elements of its 2nd arguments that give true under the function in its 1st argument. Now that you have the list of indices, you can use a single seq to use them.
{ seq( d[ pair[1] ][ pair[2] ], pair in idxs ) };
Here is the screenshot of the outputs.

Scala Slick: cannot get parameters in query

I have just spent hours on this. I'm trying to make a pretty complicated query in PostgreSQL through Slick in Scala, but Slick will NEVER take any of my parameters into account. If I try something as simple as:
def get(location: String) = {
val query = sql"select * from cities_v where name = $location limit 10"
println(query.toString)
}
The output will be:
SQLActionBuilder(Vector(select * from cities_v where name = ? limit 10),<function2>)
If instead, I try the literal insert:
def get(location: String) = {
val query = sql"select * from cities_v where name = #$location limit 10"
println(query.toString)
}
The output will be:
SQLActionBuilder(Vector(select * from cities_v where name = , ville, limit 10),<function2>
Slick will ALWAYS add commas around any literal argument, no matter where it is placed, even if it's the only argument in the query, as in:
sql"#$q"
Now, what I'd like is make more complex queries, with calculations and function calls within Postgres. But I can't get anywhere given that Slick won't let me use any of my variables.
I tried setting all sorts of implicits, some that extend GetResult some that extend StatementParameters, Slick seems to ignore all them and either replaces my arguments with ? or surrounds them with commas, thereby rendering all of my queries invalid. I would like to add that the #$ is not great because it does not provide sanitization. I'd like to stick with Slick because it's asynchronous, but I'm not sure where to go from here.
These are my version numbers, according to build.sbt:
"postgresql" % "postgresql" % "9.1-901-1.jdbc4",
"com.typesafe.slick" % "slick_2.12" % "3.2.3",
What am I doing wrong?
There is nothing wrong with that ? appears in you result statements. It is just parametrized query, and each ? represents placeholder for future value.
Just run you queries against any database and check results.

SBT Compiler crash using Scala-Breeze

I am writing a code to perform kernel K-Means (aka https://en.wikipedia.org/wiki/K-means_clustering, but with a trick). I need to generate data, and as a first simple generator I tried to implement a Gaussian Mixture Model. Here are my code:
package p02kmeans
import breeze.linalg._
import breeze.stats.distributions._
/**
* First data generation is simple, gaussian mixture model.
*/
object Data {
class GaussianClassParam (
val mean: Double,
val sd: Double)
/**
* #param proportion marginal probability for each label
* #param param param[j][k] returns the GaussianClassParam for the k class of the j variable
* #param nObs number of observations to be generated
* #result DenseMatrix_ij where i is the observation index and j is the variable number
*/
def gaussianMixture(
proportion: DenseVector[Double],
param: Vector[Vector[GaussianClassParam]],
nObs: Int)
: DenseMatrix[Double] = {
val nVar = param.size
val multiSampler = Multinomial(proportion) // sampler for the latent class
val varSamplerVec = param.map(v => v.map(c => Gaussian(c.mean, c.sd)))
val zi = DenseVector.fill[Int](nObs)(multiSampler.sample)
val data = DenseMatrix.tabulate[Double](nObs, nVar)((i, j) => varSamplerVec(j)(zi(i)).sample)
return data
}
}
When I try to compile my code (I use Scala-Ide and sbt eclipse on Windows 10) I get 2 errors:
Error in Scala compiler: assertion failed: List(method apply$mcI$sp, method apply$mcI$sp)
SBT builder crashed while compiling. The error message is 'assertion failed: List(method apply$mcI$sp, method apply$mcI$sp)'. Check Error Log for details.
The error is triggered by the line:
val data = DenseMatrix.tabulate[Double](nObs, nVar)((i, j) => varSamplerVec(j)(zi(i)).sample)
And disappear with:
val data = DenseMatrix.tabulate[Double](nObs, nVar)((i, j) => 12.0)
Could you help me debug this ?
My sbt configuration:
name := "Sernel"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
"org.scalanlp" %% "breeze" % "0.13.1",
"org.scalanlp" %% "breeze-natives" % "0.13.1",
"org.scalanlp" %% "breeze-viz" % "0.13.1"
)
I have the same errors on my OSX setup.
If you want to test the whole package (as, if you want to reproduce the error), the code is available on Github: https://github.com/vkubicki/sernel, and I am available to provide directions :).
It seems like it's a compiler bug (I suppose in scala macroses as Breeze is using those). You could try to perform total clean in the project (maybe even including .ivy2 folder - this could be a difference between your MacOS and Windows setup) and also update your scala to 2.11.11 (or maybe even 2.12.x)
However, similar issue with Scala 2.11.6 (and something tells me it's inherited in subsequent versions of Scala) wasn't fixed: https://issues.scala-lang.org/browse/SI-9284
So probably, you'll have to repeatedly perform cleaning sometimes or maybe try some other NumPy analogs like: scalala, Nd4j/Ndjs.
It could also help to try another IDE (IDEA/Atom) or try to use "bare" SBT as Eclipse is probably interfering by calling Scala's compiler front-end.

A simple model in Winbugs but it says "This chain contains uninitialized variables"

I have some simple time to event data, no covariates. I was trying to fit a Weibull distribution to it. So I have the following code. Everything looks good until I load my initials. It says "this chain contains uninitialized variables". But I don't understand. I think Weibull dist only has 2 parameters, and I already specified them all. Could you please advise? Thanks!
model
{
for(i in 1 : N) {
t[i] ~ dweib(r, mu)I(t.cen[i],)
}
mu ~ dexp(0.001)
r ~ dexp(0.001)
}
# Data
list(
t.cen=c(0,3.91,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,21.95,23.98,33.08),
t=c(2.34,NA,5.16,5.63,6.17,6.8,7.03,8.05,8.13,8.36,8.83,10.16,
10.55,10.94,11.48,11.95,13.05,13.59,16.02,20.08,NA,NA,
NA),
N=23
)
# Initial values
list(
r=3,mu=3
)
The other uninitialised variables are the missing (NA) values in the vector of t. Remember that the BUGS language makes no distinction between data and parameters, and that supplying something as data with the value NA is equivalent to not supplying it as data.

Multiple commands in one, Matlab

Sometimes it is desired to make several calls in one command. A simple example could be strrep. Assume you want to replace all parentheses with brackets, all commas with dots and then remove all double quotations. The following pseudo code could then be desired:
strrep(myString, '()', '[]', ',', '.', '"', '')
Is there any way to accomplish this? You could of course go with:
strrep(strrep(strrep(myString, '()', '[]'), ',', '.'), '"', '')
Or save the strings in a cell array and use this in a for loop, but both solutions are incredibly ugly.
The most desired answer, is one that is generic for all functions that work in a similar way.
To directly answer your question, there is really no consistent way of doing this, no. It really depends on the function. If you search the documentation you will often find a way to do this. With strings, at least, you can usually pass cell arrays in place of strings to perform operations on multiple strings, and in this case multiple operations on the same string.
A Solution for This Particular Example
You can easily use regexprep to do this for you. You can pass a cell array of the expressions to match with a corresponding cell array of the replacement values.
regexprep('abc', {'a', 'b', 'c'}, {'1', '2', '3'});
%// '123'
For your specific example, you would do something like:
regexprep(myString, {'\(\)', ',', '"'}, {'[]', '.', ''})
And as an example:
myString = 'This, is a () "string"';
regexprep(myString, {'\(\)', ',', '"'}, {'[]', '.', ''})
%// 'This. is a [] string'
If you don't want to worry about escaping all of the expressions to be regex-compatible, you can use regexptranslate to do that for you.
expressions = regexptranslate('escape', {'()', ',', '"'});
regexprep(myString, expressions, {'[]', '.', ''});
Say you want function foo to work like this:
foo(Variable,Parameter1,Value1);
foo(Variable,Parameter1_1,Value1,Parameter2,Value2,...);
then using recursion:
function[Variable]=FooBar(Variable,varargin)
N=nargin-1; %\\ Count the input parameters
if N>=2
Parameter=varargin{1};
Value=varargin{2};
% Process the first Parameter-value pair
Variable=FooBar(Variable,varargin{3:N}); %\\ Cut first Parameter-Value pair off and pass the rest to foo again
end
This approach allows you to use chain of single parameters, pairs, triplets, quadruplets, etc.
In this perticullar example the pairs are executed as LIFO stack and last unpaired Parameter is ignored. You can also add some conditions to implement foo(IN,Parameter1,Value1,Modifier,Parameter2,Value2,...) and many other properties...
For your perticullar example:
function[MyString]=FooBar(MyString,varargin)
N=nargin-1; %\\ Count the input parameters
if N>=2
Parameter=varargin{1};
Value=varargin{2};
MyString=regexprep(MyString,Parameter,Value)
MyString=FooBar(MyString,varargin{3:N});%\\ Cut first Parameter-Value pair off and pass the rest to foo again
end
Examples:
>> myString='This, is a () "string"';
FooBar(myString,'()','[]','"','',',','.')
ans = This. is a [] string
>> myString='This, is a ("string")';
FooBar(myString,'()','[]','"','',',','.')
ans = This. is a (string)
>> myString='This, is a ("string")';
FooBar(myString,'(','[',')',']','"','',',','.')
ans = This. is a [string]
As already said by #Suever your example can be solved by regexprep and #thewaywewalk has hinted that there is no "general" soluction for all function calls.
Note I do not advocate this as a good way to code -> but its a quirky question and thus here is a suitable quirky solution....
There is lots of reason why you shouldn't do this - namely a nightmare to debug but you could in theory do this with an "intelligent" self calling function...
% Create your own function which takes the following inputs:
% fHandle - function handle to the function of choice
% property - your starting variable
% varargin - a cell array (or single var) of variables to
% pass into the fHandle on each call
% see examples below...
function output = multipleCalls ( fHandle, property, varargin )
% call your primary function using feval and your inputs
% with the 1st group of inputs from the 1st varargin
if iscell ( varargin{1} )
output = feval ( fHandle, property, varargin{1}{:} );
else
output = feval ( fHandle, property, varargin{1} );
end
% remove the varargin variable which has just been used.
varargin(1) = [];
% are they aremore multiple call?
if ~isempty ( varargin )
% if so self call to apply the subsequent calls.
output = multipleCalls ( fHandle, output, varargin{:} );
end
end
% modifying your example to use this method:
multipleCalls( #strrep, 'This, is a () "string"', { '()', '[]' }, { ',', '.' }, { '"', '' } )
% Its probably a longer command and is it any clearer -> probably not...
% Here is another example:
% Create a silly anonymous function
sillyFunction = #(a,b) a + b
% Then you can use it in the same way:
% Where 0 is what you start with and then
% each time you want to add 1, then 2, then 3 and finally 4
multipleCalls ( sillyFunction, 0, 1, 2, 3, 4 )