Eigen3 : trying to allocate a cube matrix : execution failure - eigen3

I define a "cube" variable made of 4 nxm dynamic matrix.
Then I define a variable of "cube" type providing the nxm dimensions.
Compilation is ok but I get a crash # exe.
May I ask you some hints please ?
Regards
Sylvain
Here is the code :
typedef Matrix<Matrix<scomplex, Dynamic, Dynamic>, 4, 1> aCube;
aCube myCube = aCube( 15, 12);
Here is the ouput :
tstEigen: /usr/local/include/Eigen/src/Core/PlainObjectBase.h:285:
void Eigen::PlainObjectBase::resize(Eigen::Index,
Eigen::Index) [with Derived =
Eigen::Matrix, -1, -1>, 4, 1>;
Eigen::Index = long int]: Assertion `(!(RowsAtCompileTime!=Dynamic) ||
(rows==RowsAtCompileTime)) && (!(ColsAtCompileTime!=Dynamic) ||
(cols==ColsAtCompileTime)) && (!(RowsAtCompileTime==Dynamic &&
MaxRowsAtCompileTime!=Dynamic) || (rows<=MaxRowsAtCompileTime)) &&
(!(ColsAtCompileTime==Dynamic && MaxColsAtCompileTime!=Dynamic) ||
(cols<=MaxColsAtCompileTime)) && rows>=0 && cols>=0 && "Invalid sizes
when resizing a matrix or array."' failed.
Eventually, chtz put the bug in my ear. See below the working code :
typedef Matrix<Matrix<scomplex, Dynamic, Dynamic>, Dynamic, 1> aCube;
aCube myCube = aCube( 5);
for ( int i = 0; i < myCube.rows(); i++)
{
myCube(i) = Matrix<scomplex, Dynamic, Dynamic>::Zero(4,2);
}
Thanks so much for helping.

Related

Passing array's element values to lowest or highest functions in pine script

I am trying to pass dynamic values to lowest and highest built-in functions in pine script from arrays. Below is the code
int[] pArray = array.new_int(0)
pArray is populated with int elements. Here is the code below that works.
fromInd = array.min(pArray)
lowest = ta.lowest(MACDHist,array.get(pArray,0))
Debug = label.new(bar_index+1, close, 'pArray: ' + str.tostring(pArray) + str.tostring(fromInd))
The output of above code on the chart is
pArray: [2, 15, 40]2
2 is the 0th index value of pArray that is printed outside of the array in the end. However when I change the label to output 'lowest' value (shown below) nothing prints to chart but everything compiles well with no errors or warnings.
Debug = label.new(bar_index+1, close, 'pArray: ' + str.tostring(pArray) + str.tostring(lowest))
The output of 'array.get(id, index)' is series int because pArray is initialized to int. I also typecasted the 'array.get(id, index)' argument by enclosing it with 'int()' but nothing is working for the last line code except when hard coded.
'ta.lowest(source, length)' accepts series int arguments for length and it can also accept dynamic lengths as shown by tradingview https://www.tradingview.com/blog/en/pine-functions-support-dynamic-length-arguments-20554/
What am I doing wrong here? Thanks in advance.
I tried a variation of a solution posted by first user below with code
//#version=5
indicator("Dynamic INT array length", overlay = false, max_bars_back = 5000)
[a, b, hist] = ta.macd(close, 26, 12, 9)
int[] lengths = array.new_int()
int[] nlengths = array.new_int()
for i = 0 to 10
if hist[i] > 0
array.unshift(lengths, i)
else
array.unshift(nlengths,i)
lowest = ta.lowest(hist, array.get(lengths,0))
plot(lowest)
plot(hist, color = color.red)
debug = label.new(x = bar_index, y = 0, style = label.style_label_left, text = str.tostring(lowest) + " " + str.tostring(lengths) + " " + str.tostring(array.get(lengths,0)))
label.delete(debug[1])
and Im getting an error when using 'ta.lowest(hist, array.min(lengths))' where it says
Invalid value of the 'length' argument (0.0) in the "lowest" function. It must be > 0.
I tried all variations of the condition hist[i] > 0 within the for loop but nothing is printing and it has the same error. Let me know if there is an easy fix for this. Thanks.
It should be working, at a guess, normally I'd say there must be something going on with how the array is populated, but it doesn't seem to be the case here given the array output. It's unlikely, but possible you've found a bug, or an even possibly an exception that isn't being picked up by the compiler.
//#version=5
indicator("Dynamic INT array length", overlay = false, max_bars_back = 5000)
int[] lengths = array.new_int()
for i = 0 to 10
array.unshift(lengths, int(math.random(30, 50)))
[a, b, hist] = ta.macd(close, 26, 12, 9)
lowest = ta.lowest(hist, array.min(lengths))
plot(lowest)
plot(hist, color = color.red)
debug = label.new(x = bar_index, y = 0, style = label.style_label_left, text = str.tostring(lowest) + " " + str.tostring(lengths) + " " + str.tostring(array.min(lengths)))
label.delete(debug[1])
Follow up answer :
There's actually two things you need to take care of. If you consider when hist has been < 0 for a while (ie at least 10 bars). The first time hist crosses the zero line, your lengths array will only have one value : zero, and it can't be used in ta.lowest(). The second issue you will have is, if hist has been under zero the entire 10 bar window, the lengths array will be empty and array.get(lengths, 0) will give you the out of bounds indexing error.
You'll have to decide how to handle these specific circumstances, but the following of how you could account for it. For example using a length of 5 when the array has only one value of 0 and populating the arrays with na values to avoid the empty array problem.
//#version=5
indicator("Dynamic INT array length", overlay = false, max_bars_back = 5000)
[a, b, hist] = ta.macd(close, 26, 12, 9)
int[] lengths = array.new_int()
int[] nlengths = array.new_int()
for i = 0 to 10
if hist[i] > 0
array.unshift(lengths, i)
array.unshift(nlengths, na)
else
array.unshift(nlengths,i)
array.unshift(lengths, na)
int len = na
if array.get(lengths, 0) > 0
len := array.get(lengths, 0)
else
len := 5
lowest = ta.lowest(hist, len)
plot(lowest)
plot(hist, color = color.red)
debug = label.new(x = bar_index, y = 0, style = label.style_label_left, text = str.tostring(lowest) + " " + str.tostring(lengths) + " " + str.tostring(array.get(lengths,0)))
label.delete(debug[1])

Testing intermediate variables in a large file using Frama-c

I am trying to use Frama-c to check some properties of a C function that I have. The function is quite large and there are some intermediate variables that I need to check. (I am following this and this manual)
My program has the following structure:
There are 15 return statements spread throughout the program.
The variables I need to check are assigned values at several places in the program, depending on the path of the program.
my_function(){
intermediate var 1=xx;
//#assert var 1>some_value;
intermediate var 2=yy;
return var 4;
intermediate var 1=xx;
//#assert var 1>some_value;
return var 4;
intermediate var 2=xx;
intermediate var 1=yy;
//#assert var 1>some_value;
return var 4;
}
Explanation: I need to check certain properties related to var 1, var 2 and var 4. I tried 2 approaches.
use assert whenever var 1 is set as above.
Problem with this was that Frama-C checks only the first assert.
use annotations in the beginning.
/*# requires \valid(var 1);
ensures var 1 > some_value;
*/
In this case, Frama-C returns an error.
Question: How can I check the properties for intermediate problems? Is there a sample program?
*I haven't included my original function as it is very long.
As Virgile has mentioned, your question is not very clear, but I assume you are trying to validate some properties of var1 and var2.
This book provides some nice examples and I think the following should help you.
int abs(int val){
int res;
if(val < 0){
//# assert val < 0 ;
res = - val;
//# assert \at(val, Pre) >= 0 ==> res == val && \at(val, Pre) < 0 ==> res == -val;
} else {
//# assert !(val < 0) ;
res = val;
//# assert \at(val, Pre) >= 0 ==> res == val && \at(val, Pre) < 0 ==> res == -val;
}
return res;
}
The author has used the concept of Hoare triples in this scenario, where you check (assert) a certain property by asserting its requirements (pre-condition) for a property and check if a property holds after the corresponding statements are executed.
Hope this helps.

Move Zeroes in Scala

I'm working on "Move Zeroes" of leetcode with scala. https://leetcode.com/problems/move-zeroes/description/
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of the array.
I have a solution which works well in IntelliJ but get the same Array with input while executing in Leetcode, also I'm not sure whether it is done in-place... Something wrong with my code ?
Thanks
def moveZeroes(nums: Array[Int]): Array[Int] = {
val lengthOrig = nums.length
val lengthFilfter = nums.filter(_ != 0).length
var numsWithoutZero = nums.filter(_ != 0)
var numZero = lengthOrig - lengthFilfter
while (numZero > 0){
numsWithoutZero = numsWithoutZero :+ 0
numZero = numZero - 1
}
numsWithoutZero
}
And one more thing: the template code given by leetcode returns Unit type but mine returns Array.
def moveZeroes(nums: Array[Int]): Unit = {
}
While I agree with #ayush, Leetcode is explicitly asking you to use mutable states. You need to update the input array so that it contains the changes. Also, they ask you to do that in a minimal number of operations.
So, while it is not idiomatic Scala code, I suggest you a solution allong these lines:
def moveZeroes(nums: Array[Int]): Unit = {
var i = 0
var lastNonZeroFoundAt = 0
while (i < nums.size) {
if(nums(i) != 0) {
nums(lastNonZeroFoundAt) = nums(i)
lastNonZeroFoundAt += 1
}
i += 1
i = lastNonZeroFoundAt
while(i < nums.size) {
nums(i) = 0
i += 1
}
}
As this is non-idomatic Scala, writing such code is not encouraged and thus, a little bit difficult to read. The C++ version that is shown in the solutions may actually be easier to read and help you to understand my code above:
void moveZeroes(vector<int>& nums) {
int lastNonZeroFoundAt = 0;
// If the current element is not 0, then we need to
// append it just in front of last non 0 element we found.
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[lastNonZeroFoundAt++] = nums[i];
}
}
// After we have finished processing new elements,
// all the non-zero elements are already at beginning of array.
// We just need to fill remaining array with 0's.
for (int i = lastNonZeroFoundAt; i < nums.size(); i++) {
nums[i] = 0;
}
}
Your answer gives TLE (Time Limit Exceeded) error in LeetCode..I do not know what the criteria is for that to occur..However i see a lot of things in your code that are not perfect .
Pure functional programming discourages use of any mutable state and rather focuses on using val for everything.
I would try it this way --
def moveZeroes(nums: Array[Int]): Array[Int] = {
val nonZero = nums.filter(_ != 0)
val numZero = nums.length - nonZero.length
val zeros = Array.fill(numZero){0}
nonZero ++ zeros
}
P.S - This also gives TLE in Leetcode but still i guess in terms of being functional its better..Open for reviews though.

AS3: Create a function that accepts both Array and Vector as an argument

I'm trying to create a function that will work for any array-like object in Flash but I'm really struggling to find a way to let the compiler know what I'm doing. I need to use functions like indexOf on the argument, but unless it is cast to the correct data type the compiler doesn't know that method is available. It's frustrating because Vector and Array share pretty much the same interface but there isn't an Interface to reflect that!
At the moment I've got this:
private function deleteFirst(tV:* , tVal:*):void {
trace(tV)
var tIndex:int
if (tV is Array) {
var tArray:Array = tV as Array
tIndex = tArray.indexOf(tVal)
if (tIndex >= 0) tArray.splice(tIndex, 1)
} else if (tV is Vector.<*>) {
var tVObj:Vector.<*> = tV as Vector.<*>
tIndex = tVObj.indexOf(tVal)
if (tIndex >= 0) tVObj.splice(tIndex, 1)
} else if (tV is Vector.<Number>) {
var tVNum:Vector.<Number> = tV as Vector.<Number>
tIndex = tVNum.indexOf(tVal)
if (tIndex >= 0) tVNum.splice(tIndex, 1)
} else if (tV is Vector.<int>) {
var tVInt:Vector.<int> = tV as Vector.<int>
tIndex = tVInt.indexOf(tVal)
if (tIndex >= 0) tVInt.splice(tIndex, 1)
} else if (tV is Vector.<uint>) {
var tVUInt:Vector.<uint> = tV as Vector.<uint>
tIndex = tVUInt.indexOf(tVal)
if (tIndex >= 0) tVUInt.splice(tIndex, 1)
}
trace(tV)
}
It kind of works but it's not exactly elegant! I'm wondering if there's a trick I'm missing. Ideally I'd do this by extending the base class, but I don't think that's possible with Vector.
Thanks
I would be very careful about mixing and matching Vectors and Arrays. The biggest difference between them is that Arrays are sparse, and Vectors are dense.
That said, here is your very compact generic removal function that will work on ANY "set" class that has indexOf and splice...
function deleteFirst( set:Object, elem:Object ) : Boolean
{
if ( ("indexOf" in set) && ("splice" in set) )
{
var idx:int = set.indexOf( elem );
if ( idx >= 0 )
{
set.splice( idx, 1 );
return true;
}
}
return false;
}
You can test the code with this code
var arr:Array = [ 1, 2, 3, 4, 5 ];
var vec:Vector.<int> = new Vector.<int>();
vec.push( 1, 2, 3, 4, 5 );
deleteFirst( arr, 2 ); // will remove 2
deleteFirst( vec, 3 ); // will remove 3
deleteFirst( "aaa4", "4" ); // nothing, cuz String doesn't have splice
trace( arr );
trace( vec );
UPDATE - For #Arron only, I've made the below change. Note that getting exceptions is good. They are informative and help reveal issues with the code path.
function deleteFirst( set:Object, elem:Object ) : Boolean
{
var idx:int = set.indexOf( elem );
if ( idx >= 0 )
{
set.splice( idx, 1 );
return true;
}
return false;
}
There! Now it's even simpler. You get an exception that tells you what's wrong!
This is definitely a short-coming of AS3, I don't think there is any elegant solution.
However, one code simplification you can make:
Since the syntax for indexOf() and splice() is the same for both arrays and vectors, you don't need that big if/else ladder to cast every type. You can simply call indexOf() and splice() on the object without any casting. Of course, you don't get any code-hints in your IDE, but it will work the same as you currently have. Example:
function deleteFirst(arrayOrVector:* , searchValue:*):* {
if (arrayOrVector is Array || arrayOrVector is Vector.<*> || arrayOrVector is Vector.<Number> || arrayOrVector is Vector.<int> || arrayOrVector is Vector.<uint>) {
var index:int = arrayOrVector.indexOf(searchValue)
if (index >= 0)
arrayOrVector.splice(index, 1)
}else
throw new ArgumentError("Argument 'arrayOrVector' must be an array or a vector, but was type " + getQualifiedClassName(arrayOrVector));
return arrayOrVector;
}
You can even skip the whole if/else type check and it would still work, it would just make the code more confusing, and you would get a slightly more confusing error if you called the function with an argument other than array or vector (like "indexOf not found on type Sprite" if you passed a sprite object by accident).
Also it's worth mentioning that, while this doesn't help you with number base type vectors, with other vectors you can sort of use Vector.<*> as a generic vector reference. You can assign a reference using the Vector global function with wildcard (Vector.<*>(myVector)) and it will return a reference to the original vector instead of a new copy as it usually does. If you don't mind returning a copy of number based type vectors instead of always modifying the original vector, you can still take advantage of this to simplify your code:
function deleteFirst(arrayOrVector:* , searchValue:*):* {
if (arrayOrVector is Array) {
var array:Array = arrayOrVector;
var index:int = array.indexOf(searchValue)
if (index >= 0)
array.splice(index, 1)
return array;
}else if(arrayOrVector is Vector.<*> || arrayOrVector is Vector.<Number> || arrayOrVector is Vector.<int> || arrayOrVector is Vector.<uint>) {
var vector:Vector.<*> = Vector.<*>(arrayOrVector);
index = vector.indexOf(searchValue);
if (index >= 0)
vector.splice(index, 1);
return vector;
}
throw new ArgumentError("Argument 'arrayOrVector' must be an array or a vector, but was type " + getQualifiedClassName(arrayOrVector));
}

Actionscript 3 dynamic multidimensional array

Okay so this is my code
var no:int = 0;
var elem:int = 0;
loadedData = myLoader.data.split(/\r\n|\n|\r/);
for (var i:int = 0; i < loadedData.length; i++)
{
if (loadedData[i] != '')
{
if (loadedData[i] != ',')
{
if(patterns[no] == undefined) patterns[no] = [];
trace(no);
trace(elem);
obstacleData[i] = loadedData[i].split(",");
trace(patterns[no]);
patterns[no][elem] = obstacleData[i][0];
patterns[no][elem + 1] = obstacleData[i][1];
elem += 2;
trace('Pattern' , no, ': ', patterns[no]);
}
else if (loadedData[i] == ',')
{
no += 1;
elem = 0;
patterns[no] = 0;
}
}
}
The problem is at this line
patterns[no][elem] = obstacleData[i][0];
I'm getting the error: [Fault] exception, information=ReferenceError: Error #1056: Cannot create property 0 on Number.
I've read around on this and multidimensional arrays just seem to be so much more complicated on AS3 compared to other languages where you just create a multidimensional array and it works.
I feel like I've done something really obvious wrong and will feel like an idiot upon someone telling me but I really need help on this one since I'm new to this whole AS3 way of creating multidimensional arrays.
Just in case the output for the code when run is as so:
0
0
Pattern 0 : 300,60
0
2
300,60
Pattern 0 : 300,60,350,90
1
0
0 <--- This might be the problem?
[Fault] exception, information=ReferenceError: Error #1056: Cannot create property 0 on Number.
Maybe the error is caused by the line
patterns[no] = 0;
I think you want to assign an empty array or maybe null and check for null later.

Resources