What does the C++ map() function do - arduino

I am currently looking at the following code (which can be found here)
void MPU6050::CalibrateAccel(uint8_t Loops,uint8_t OffsetSaveAddress) {
double kP = 0.15;
double kI = 8;
float x;
x = (100 - map(Loops, 1, 5, 20, 0)) * .01;
kP *= x;
kI *= x;
PID( 0x3B, OffsetSaveAddress, kP, kI, Loops);
}
Specifically I am struggling to understand what the line:
x = (100 - map(Loops, 1, 5, 20, 0)) * .01;
is doing?
The best matching function I can find for map() is here but it doesn't appear to match the integer parameters that are being passed into the function.
Obviously ideally I would run this code but unfortunately I am yet unable to get this to compile.
Have I correctly found the function being invoked and what is the behaviour of this function with the given parameters? I assume this is a map() function similar to any other typical map function in other languages/frameworks such as python, jquery etc.
Could anyone guide me in the right direction?

map defined in math, re-maps a number from one range to another. Syntax is map(value, fromLow, fromHigh, toLow, toHigh)
So, map(Loops, 1, 5, 20, 0)) means the value of variable Loops will be initially searched between (1,5) but result will be between 20 to 0 since it is remapped.

Related

Memoization code for "Longest Common Substring" doesn't work as expected

I was able to think of a recursive solution for the problem "Longest Common Substring" but when I try to memoize it, it doesn't seem to work as I expected it to, and throws a wrong answer.
Here is the recursive code.
int lcs(string X, string Y,int i, int j, int count)
{
if (i == 0 || j == 0)
return count;
if (X[i - 1] == Y[j - 1])
count = lcs(X,Y,i - 1, j - 1, count + 1);
count = max(count,max(lcs(X,Y,i, j-1, 0),lcs(X,Y,i - 1, j, 0)));
return count;
}
int longestCommonSubstr(string S1, string S2, int n, int m)
{
return lcs(S1,S2,n,m,0,dp);
}
And here is the memoized code.
int lcs(string X, string Y,int i, int j, int count,vector<vector<vector<int>>>& dp)
{
if (i == 0 || j == 0)
return count;
if(dp[i - 1][j - 1][count] != -1)
return dp[i - 1][j - 1][count];
if (X[i - 1] == Y[j - 1])
count = lcs(X, Y, i - 1, j - 1, count + 1, dp);
count = max(count,max(lcs(X,Y,i, j-1, 0,dp),lcs(X,Y,i - 1, j, 0,dp)));
return dp[i-1][j-1][count]=count;
}
int longestCommonSubstr(string S1, string S2, int n, int m)
{
int maxSize=max(n,m);
vector<vector<vector<int>>> dp(n,vector<vector<int>>(m,vector<int>(maxSize,-1)));
return lcs(S1,S2,n,m,0,dp);
}
I do know that the problem can be solved using a 2D DP vector as well but my objective was to convert my original recursive solution to a memoized solution and not write a solution from scratch. And as I have 3 parameters which are changing, so it should use a 3D DP table.
Can anyone figure out what's wrong or help me out with a 3D DP solution with recursive code same or similar to mine.
Note:-
An interesting observation, the max function for some reason works from left to right on my Mac system and on Ubuntu running under parallels as well, but the same function works from right to left in Windows machine and in online compilers. I do not know the reason but I would be happy to know about it. I'm running the code in an M1 Mac, I don't know if the ARM compiler is different from x86 Mac compiler or not.
Another thing, the memoized code gives different answers depending upon which recursive call is called first on the line,
count = max(count,max(lcs(X,Y,i, j-1, 0),lcs(X,Y,i - 1, j, 0)));
If I swap the positions of the function call statements then it gives a correct output but for that specific test case and probably similar cases.
This Memo solution gives TLE as well in large test cases, and I do not know why.
I recently started studying DP and this is the only question which I wasn't able to solve by just modifying the original recursive solution. It has been two days and I just can't figure out the proper reasons.
Submission Link:- https://practice.geeksforgeeks.org/problems/longest-common-substring1452/1/#
Any help in this regard would be great.

Halide: Using constant_exterior() + vectorize() in OpenCL

I can't generate an OpenCL implementation with Halide when I choose a constant_exterior() type of boundary condition with vectorize scheduling.
When compiling, I get the following error:
Error:
Vector of bool not valid in OpenCL C (yet)
I don't understand why it would need to use a boolean vector..
My function looks something like this:
void dummy_step()
{
Var x("x"), y("y"), c("c");
Func src("src");
Func dst("dst");
// input parameters
ImageParam image(UInt(8), 3, "inputImage");
Param<int> W;
Param<int> H;
// boundary condition
src = constant_exterior(image, 0, 0, W, 0, H);
Expr x0 = cast<int>(x + y);
Expr y0 = cast<int>(x - y);
dst(x, y, c) = cast<uint8_t>(clamp(src(x0, y0, c), 0.0f, 255.0f));
// scheduling
dst.vectorize(x, 4).gpu_tile(x, y, 16, 8).compute_root();
dst.compile_to_file("test", {image, W, H});
}
If I remove .vectorize(x, 4), the code compiles. If I use another boundary condition, let's say, src = repeat_edge(image, 0, W, 0, H); it also works.
constant_exterior checks if each x coordinate in the vector is within the bounds in order to mux between the constant exterior value and the interior values. The result of this check is a vector of booleans. repeat_edge doesn't need to do that check - it can just clamp the coordinates directly using min and max operations.
I suggest not vectorizing this part of the code using a schedule like so:
src.compute_at(dst, x);
dst.vectorize(x, 4).gpu_tile(x, y, 16, 8).compute_root();

Get index of first "true" in vector

How do I efficiently calculate the index of the first "true" value in an OpenCL vector:
float4 f = (float4)(1, 2, 3, 4);
int i = firstTrue(f > 2);
In the example I would like to get i=2 because 3 is the first value greater than 2.
I have looked at all functions in http://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/ but have found nothing.
Is this such an uncommon operation?
How do I calculate this (on my own) without much branching/code duplication?
I'm not aware of a built-in function that does exactly what you want, but I have some ideas on how you could do it. There might be a simpler solution, but I've only had one cup of coffee so far. The idea is to leverage the "count leading zeros" function "clz". You just need to convert the results of your conditional into bit positions in an integer.
Create a boolean vector with true/false state set by the comparison
Do a dot product of that against an integer vector with pre-defined values that correspond to bit positions.
The first bit set will correspond to the index you're asking for. Use clz() or a bithack to find that bit index.
In code, something like this (untested and might need adjusting):
float4 f = (float4)(1, 2, 3, 4);
int4 greater = (f > 2);
int4 bits = (int4)(8, 4, 2, 1);
int sum = dot(greater, bits); // maybe this needs to use float
int index = clz(sum); // might need offset applied
You'll need to offset or invert the result from clz to get 0,1,2,3 but that's just addition or subtraction.
Working Code
int firstTrue(int4 v) {
return 4 - (clz(0) - clz((v.x & 8) | (v.y & 4) | (v.z & 2) | (v.w & 1));
}

How to make recursive nested loops which use loop variables inside?

I need to make a nested loop with an arbitrary depth. Recursive loops seem the right way, but I don't know how to use the loop variables in side the loop. For example, once I specify the depth to 3, it should work like
count = 1
for i=1, Nmax-2
for j=i+1, Nmax-1
for k=j+1,Nmax
function(i,j,k,0,0,0,0....) // a function having Nmax arguments
count += 1
end
end
end
I want to make a subroutine which takes the depth of the loops as an argument.
UPDATE:
I implemented the scheme proposed by Zoltan. I wrote it in python for simplicity.
count = 0;
def f(CurrentDepth, ArgSoFar, MaxDepth, Nmax):
global count;
if CurrentDepth > MaxDepth:
count += 1;
print count, ArgSoFar;
else:
if CurrentDepth == 1:
for i in range(1, Nmax + 2 - MaxDepth):
NewArgs = ArgSoFar;
NewArgs[1-1] = i;
f(2, NewArgs, MaxDepth, Nmax);
else:
for i in range(ArgSoFar[CurrentDepth-1-1] + 1, Nmax + CurrentDepth - MaxDepth +1):
NewArgs = ArgSoFar;
NewArgs[CurrentDepth-1] = i;
f(CurrentDepth + 1, NewArgs, MaxDepth, Nmax);
f(1,[0,0,0,0,0],3,5)
and the results are
1 [1, 2, 3, 0, 0]
2 [1, 2, 4, 0, 0]
3 [1, 2, 5, 0, 0]
4 [1, 3, 4, 0, 0]
5 [1, 3, 5, 0, 0]
6 [1, 4, 5, 0, 0]
7 [2, 3, 4, 0, 0]
8 [2, 3, 5, 0, 0]
9 [2, 4, 5, 0, 0]
10 [3, 4, 5, 0, 0]
There may be a better way to do this, but so far this one works fine. It seems easy to do this in fortran. Thank you so much for your help!!!
Here's one way you could do what you want. This is pseudo-code, I haven't written enough to compile and test it but you should get the picture.
Define a function, let's call it fun1 which takes inter alia an integer array argument, perhaps like this
<type> function fun1(indices, other_arguments)
integer, dimension(:), intent(in) :: indices
...
which you might call like this
fun1([4,5,6],...)
and the interpretation of this is that the function is to use a loop-nest 3 levels deep like this:
do ix = 1,4
do jx = 1,5
do kx = 1,6
...
Of course, you can't write a loop nest whose depth is determined at run-time (not in Fortran anyway) so you would flatten this into a single loop along the lines of
do ix = 1, product(indices)
If you need the values of the individual indices inside the loop you'll need to unflatten the linearised index. Note that all you are doing is writing the code to transform array indices from N-D into 1-D and vice versa; this is what the compiler does for you when you can specify the rank of an array at compile time. If the inner loops aren't to run over the whole range of the indices you'll have to do something more complicated, careful coding required but not difficult.
Depending on what you are actually trying to do this may or may not be either a good or even satisfactory approach. If you are trying to write a function to compute a value at each element in an array whose rank is not known when you write the function then the preceding suggestion is dead flat wrong, in this case you would want to write an elemental function. Update your question if you want further information.
you can define your function to have a List argument, which is initially empty
void f(int num,List argumentsSoFar){
// call f() for num+1..Nmax
for(i = num+1 ; i < Nmax ; i++){
List newArgs=argumentsSoFar.clone();
newArgs.add(i);
f(i,newArgs);
}
if (num+1==Nmax){
// do the work with your argument list...i think you wanted to arrive here ;)
}
}
caveat: the stack should be able to handle Nmax depth function calls
Yet another way to achieve what you desire is based on the answer by High Performance Mark, but can be made more general:
subroutine nestedLoop(indicesIn)
! Input indices, of arbitrary rank
integer,dimension(:),intent(in) :: indicesIn
! Internal indices, here set to length 5 for brevity, but set as many as you'd like
integer,dimension(5) :: indices = 0
integer :: i1,i2,i3,i4,i5
indices(1:size(indicesIn)) = indicesIn
do i1 = 0,indices(1)
do i2 = 0,indices(2)
do i3 = 0,indices(3)
do i4 = 0,indices(4)
do i5 = 0,indices(5)
! Do calculations here:
! myFunc(i1,i2,i3,i4,i5)
enddo
enddo
enddo
enddo
enddo
endsubroutine nestedLoop
You now have nested loops explicitly coded, but these are 1-trip loops unless otherwise desired. Note that if you intend to construct arrays of rank that depends on the nested loop depth, you can go up to rank of 7, or 15 if you have a compiler that supports it (Fortran 2008). You can now try:
call nestedLoop([1])
call nestedLoop([2,3])
call nestedLoop([1,2,3,2,1])
You can modify this routine to your liking and desired applicability, add exception handling etc.
From an OOP approach, each loop could be represented by a "Loop" object - this object would have the ability to be constructed while containing another instance of itself. You could then theoretically nest these as deep as you need to.
Loop1 would execute Loop2 would execute Loop3.. and onwards.

How to define a parameter recursively in GAMS?

I need to define a set of parameters that have a natural recursive relation.
Here is a MWE where I try to define the factorial function over a set of (nine) parameters S:
$title TitleOfProblem
set S / s1*s9 /;
alias(S, S1, S2);
set delta1(S1,S2);
delta1(S1,S2) = yes$(ord(S1) + 1 = ord(S2));
parameter f(S);
f(S) = 1$(ord(S) = 1) + (ord(S) * sum(S1$(delta1(S1, S)), f(S1)))$(ord(S) > 1);
display f;
"delta1" is a relation containing pairs of elements in sorted order that differ by 1. Logically, the definition of f matches the definition of the factorial function (for inputs 1 to 9), but GAMS doesn't seem to like that f is defined recursively. The output of GAMS compilation looks something like this:
f(S) = 1$(ord(S) = 1) + (ord(S) * sum(S1$(delta1(S1, S)), f(S1)))$(ord(S) > 1);
$141
141 Symbol neither initialized nor assigned
A wild shot: You may have spurious commas in the explanatory
text of a declaration. Check symbol reference list.
Question:
Is it possible to recursively define a parameter in GAMS? If not, what is a work-around?
(P.S. Someone with enough rep should create a tag "GAMS" and add it to this question.)
Someone showed me a solution for my example using a while loop. However, this solution is specific to factorial and does not generalize to an arbitrary recursive function.
$title factorial
set S / s1*s9 /;
parameter f(S);
parameter temp;
Loop(S,
temp=ord(s);
f(S)=ord(s);
While(temp > 1,
f(S) = f(S) * (temp-1);
temp = temp - 1;
);
);
display f;

Resources