How to multiple two Eigen tensors along batch dimension? - eigen

For example, I have a tensor A(2,3,4) and tensor B(3,4) and want to make koefs multiplication(not Contraction operation) of A along dimension 0( batch dimension) with B. How to do this without for loop?

If I understand your question, you could first reshape B to (1,3,4) and then use broadcasting to replicate the values along axis 0. Don't know if this is very efficient, but it works.
auto A = Tensor<float, 3>(2, 3, 4);
A.setValues({
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
},{
{ 10,20,30,40 },
{ 50,60,70,80 },
{ 90,100,110,120 },
}
});
auto W = Tensor<float, 2>(3,4);
W.setValues({
{ 1,2,3,4 },
{ 5,6,7,8 },
{ 9,10,11,12 }
});
auto three_dims = Eigen::array<int, 3>({ 1,3,4 });
auto bcast = Eigen::array<int, 3>({ 2,1,1 });
auto X = W.reshape(three_dims).broadcast(bcast);
auto Y = A*X;
std::cout << Y << std::endl;
Prints:
1 25 81 4 36 100 9 49 121 16 64 144
10 250 810 40 360 1000 90 490 1210 160 640 1440

Related

Spiral in sampled x-y plane

Let’s say I have the following 3D discretized space, in which the indexes of the samples/nodes are sequential as it is shown in the picture.
Now consider only the horizontal middle layer.
My objective is to find a programmatically and iterative rule/s that allow me to run a spiral (like the image or similar, it can start in any direction) over the mid-layer, starting from node 254, as it is shown on the image:
As you can see in the picture, the yellow crosses show the nodes to be explored. In the first lap these nodes are consecutive while in the second they are separated by 1 node and so on.
I started to solve the problem as follows (pseudocode):
I considered size(y) = y = 13
Size(z) = z = 3
Lap 1:
254 – z * y = 215
254 – z * (y + 1) = 212
254 – z = 251
254 + z * (y - 1) = 290
254 + z * y = 293
254 + z * (y + 1) = 296
254 + z = 257
254 – z * (y – 1) = 218
Lap 2:
254 – 3 * z * y = 137
254 – 3 * z * (y + 2/3) = 131
…
But I think there may be a simpler, more general rule.
each direction has constant index increment:
const int dx = 39;
const int dy = 3;
const int dz = 1;
so to make a spiral you just start from start index and increment in current direction i-times then rotate by 90 deg and do the same ... then increment i and do this until desired size is hit ...
You should also add range checking so your spiral will not go outside your array as that would screw things up. By checking actual x,y,z coordinates. So either compute them in parallel or infer them from ix using modular arithmetics so for example something like (C++):
const int dx = 39;
const int dy = 3;
const int dz = 1;
int cw[4]={-dx,-dy,+dx,+dy}; // CW rotation
int ix=254; // start point (center of spiral)
int dir=0; // direction cw[dir]
int n=5; // size
int i,j,k,x,y,z,a; // temp
for (k=0,i=1;i<=n;i+=k,k^=1,dir++,dir&=3)
for (j=1;j<=i;j++)
{
int a=ix-1;
z = a% 3; a/= 3; // 3 is z-resolution
y = a%13; a/=13; // 13 is y-resolution
x = a;
if ((x>=0)&&(x<13)&&(y>=0)&&(y<13)&&(z>=0)&&(z<3))
{
// here use point ix
// Form1->mm_log->Lines->Add(AnsiString().sprintf("%i (%i,%i,%i) %i",ix,x,y,z,i));
}
ix+=cw[dir];
}
producing this output
ix x,y,z i
254 (6,6,1) 1
215 (5,6,1) 1
212 (5,5,1) 2
251 (6,5,1) 2
290 (7,5,1) 2
293 (7,6,1) 2
296 (7,7,1) 3
257 (6,7,1) 3
218 (5,7,1) 3
179 (4,7,1) 3
176 (4,6,1) 3
173 (4,5,1) 3
170 (4,4,1) 4
209 (5,4,1) 4
248 (6,4,1) 4
287 (7,4,1) 4
326 (8,4,1) 4
329 (8,5,1) 4
332 (8,6,1) 4
335 (8,7,1) 4
338 (8,8,1) 5
299 (7,8,1) 5
260 (6,8,1) 5
221 (5,8,1) 5
182 (4,8,1) 5
143 (3,8,1) 5
140 (3,7,1) 5
137 (3,6,1) 5
134 (3,5,1) 5
131 (3,4,1) 5
In case you want CCW spiral either reverse the cw[] or instead of dir++ do dir--
In case you want to have changeable screw width then you just increment i by the actual width instead of just by one.
Based on #Spektre answer, this code worked for me:
const int x_res = 13;
const int y_res = 13;
const int z_res = 3;
const int dx = 39;
const int dy = 3;
const int dz = 1;
int cw[4]={-dx,-dy,+dx,+dy}; // CW rotation
int ix=254; // start point (center of spiral)
int dir=0; // direction cw[dir]
int n=30; // size
int i,j,k;
cout << ix << endl;
// first "lap" (consecutive nodes)
for (k=0,i=1;i<=2;i+=k,k^=1,dir++,dir&=3)
for (j=1;j<=i;j++)
{
ix+=cw[dir];
cout << ix << endl;
}
i-=1;
int width = 2; //screw width
i+=width;
int dist = 1; //nodes separation
int node_count = 0; //nodes counter
for (k=k,i=i;i<=n;i+=k,k^=width,dir++,dir&=3)
{
if (dir==1)
{
dist+=1;
}
for (j=1;j<=i;j++)
{
ix+=cw[dir];
node_count +=1;
if ((0 < ix) && (ix <= x_res*y_res*z_res))
{
if (node_count == dist)
{
cout << ix << endl;
node_count = 0;
}
}
else return 0;
}
}
return 0;
with this output:
254 215 212 251 290 293 296 257 218 179 140 134 128 206 284 362 368 374 380 302
224 146 68 59 50 83 200 317 434 443 452 461 386 269 152 35

How to generate Set Y with multiple elements in CPLEX?

I have written this code to generate a Set Y, with single element
int m=3 ;
range I= 1..m;
int w[i in I]=i;
int q= min(i in I)w[i] ;
int W=1000;
int Ea[I];
{int} B={381,198,291};
{int} E ={rand(f) | f in B: f>0};
execute
{
writeln("E is ", E)
var j=1
for(var k in E)
{
Ea[j]=k; //Array Ea has same values as set E
j=j+1;
}
}
int ok[i in I]=(sum(i in I)Ea[i]*w[i]<=W-q);
{int} Y= {sum(i in I)Ea[i]*w[i]|x in 0..W-q , i in I: ok[i]==1 } ;
execute{
writeln(Y);
}
The output of above code and variable values are
E is {93 42 31}
Y is {270}
Variable Values
How can I generate multiple elements in Set Y, since the rand function has been used while calculating E?
You can use arrays for several casts:
{int} B={381,198,291};
range casts=1..10;
{int} E[c in casts] ={rand(f) | f in B: f>0};
execute
{
writeln(E);
}
int Y[c in casts]= sum(e in E[c]) e;
execute{
writeln(Y);
}
gives
[{93 42 31} {378 131 243} {25 177 61} {4 48 212} {276 1 256} {289 138 264}
{366 192 177} {138 150 164} {125 163 246} {315 180 240}]
[166 752 263 264 533 691 735 452 534 735]

Rust - How can I search a vec for a subset - and find the start index of the subvec?

If I have a vec, how can I search this to find whether it contains another vec - and return the index where this subvec begins?
let mut haystack = vec!(0, 0, 0, 1, 48, 120, 49, 49, 1, 0);
let mut needle = vec!(48, 120, 49, 49);
Such that it returns 4 (the starting index of this subset in the original) (or rather, it would return a Result which contains 4 in this case - and which would error if it is not found at all).
This is a classic string search problem. #Willem Van Onsem suggested the KMP algorithm, but you should start with the naive algorithm.
For every index of haystack, try to compare the string of the same length as needle and starting at this index in haystack to needle itself.
Have a look at this:
0 0 0 1 48 120 49 49 1 0
48 120 49 49
x fail
48 120 49 49
x fail
48 120 49 49
x fail
48 120 49 49
x fail
48 120 49 49
- - - - match!
x means that the elements are different, - that they are the same. On every x, shift to the next element of haystack (that's the difference with KMP which may shift more than one element at once).
In Rust, you will write something like:
fn find1(haystack: &Vec<i32>, needle: &Vec<i32>) -> i64 {
for i in 0..haystack.len()-needle.len()+1 { // last indices of haystack are too far right to get a match
let mut j = 0;
while j < needle.len() { // check every char of needle
if needle[j] != haystack[i+j] { // doesn't match
break; // try the next i
}
j += 1; // else: match so far
}
if j == needle.len() { // no break: a full match was found
return i as i64;
}
}
return -1; // not a single full match
}
Of course, you can use some of Rust features to shorten the code (and avoid the C-like style above):
fn find2(haystack: &Vec<i32>, needle: &Vec<i32>) -> Option<usize> {
for i in 0..haystack.len()-needle.len()+1 {
if haystack[i..i+needle.len()] == needle[..] {
return Some(i);
}
}
None
}
Or the functional style if you prefer:
fn find3(haystack: &Vec<i32>, needle: &Vec<i32>) -> Option<usize> {
(0..haystack.len()-needle.len()+1)
.filter(|&i| haystack[i..i+needle.len()] == needle[..]).next()
}
If you understand the naive algorithm and its naive implementation, you can move to faster algorithms.
I would use the windows iterator like:
fn find(haystack: &Vec<i32>, needle: &Vec<i32>) -> Option<usize> {
for (position, window) in haystack.windows(needle.len()).enumerate() {
if window == needle {
return Some(position);
}
}
None
}

How do I make this program work for input >10 for the USACO Training Pages Square Palindromes?

Problem Statement -
Given a number base B (2 <= B <= 20 base 10), print all the integers N (1 <= N <= 300 base 10) such that the square of N is palindromic when expressed in base B; also print the value of that palindromic square. Use the letters 'A', 'B', and so on to represent the digits 10, 11, and so on.
Print both the number and its square in base B.
INPUT FORMAT
A single line with B, the base (specified in base 10).
SAMPLE INPUT
10
OUTPUT FORMAT
Lines with two integers represented in base B. The first integer is the number whose square is palindromic; the second integer is the square itself. NOTE WELL THAT BOTH INTEGERS ARE IN BASE B!
SAMPLE OUTPUT
1 1
2 4
3 9
11 121
22 484
26 676
101 10201
111 12321
121 14641
202 40804
212 44944
264 69696
My code works for all inputs <=10, however, gives me some weird output for inputs >10.
My Code-
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int baseToBase(int num, int base) //accepts a number in base 10 and the base to be converted into as arguments
{
int result=0, temp=0, i=1;
while(num>0)
{
result = result + (num%base)*pow(10, i);
i++;
num = num/base;
}
result/=10;
return result;
}
long long int isPalin(int n, int base) //checks the palindrome
{
long long int result=0, temp, num=n*n, x=n*n;
num = baseToBase(num, base);
x = baseToBase(x, base);
while(num)
{
temp=num%10;
result = result*10 + temp;
num/=10;
}
if(x==result)
return x;
else
return 0;
}
int main()
{
int base, i, temp;
long long int sq;
cin >> base;
for(i=1; i<=300; i++)
{
temp=baseToBase(i, base);
sq=isPalin(i, base);
if(sq!=0)
cout << temp << " " << sq << endl;
}
return 0;
}
For input = 11, the answer should be
1 1
2 4
3 9
6 33
11 121
22 484
24 565
66 3993
77 5335
101 10201
111 12321
121 14641
202 40804
212 44944
234 53535
While my answer is
1 1
2 4
3 9
6 33
11 121
22 484
24 565
66 3993
77 5335
110 10901
101 10201
111 12321
121 14641
209 40304
202 40804
212 44944
227 50205
234 53535
There is a difference in my output and the required one as 202 shows under 209 and 110 shows up before 101.
Help appreciated, thanks!
a simple example for B = 11 to show error in your base conversion is for i = 10 temp should be A but your code calculates temp = 10. Cause in we have only 10 symbols 0-9 to perfectly show every number in base 10 or lower but for bases greater than that you have to use other symbols to represent a different digit like 'A', 'B' and so on. problem description clearly states that. Hope You will be able to fix your code now by modifying your int baseToBase(int num, int base)function.

Generating number within range with equal probability with dice

I've been thinking about this but can't seem to figure it out. I need to pick a random integer between 1 to 50 (inclusive) in such a way that each of the integer in it would be equally likely. I will have to do this using a 8 sided dice and a 15 sided dice.
I've read somewhat similar questions related to random number generators with dices but I am still confused. I think it is somewhere along the line of partitioning the numbers into sets. Then, I would roll a die, and then, depending on the outcome, decide which die to roll again.
Can someone help me with this?
As a simple - not necessarily "optimal" solution, roll the 8 sided die, then the 15 sided:
8 sided 15 sided 1..50 result
1 or 2 1..15 1..15
3 or 4 1..15 16..30 (add 15 to 15-sided roll)
5 or 6 1..15 31..45 (add 30 to 15-sided roll)
7 or 8 1..5 46..50 (add 45 to 15-sided roll)
7 or 8 6..15 start again / reroll both dice
lets say you have two functions: d8(), which returns a number from 0 to 7, and d15(), which returns a number from 0 to 14. You want to write a d50() that returns a number from 0 to 49.
Of all the simple ways, this one is probably the most efficient in terms of how many dice you have to roll, and something like this will work for all combinations of dice you have and dice you want:
int d50()
{
int result;
do
{
result = d8()*8+d8(); //random from 0 to 63
} while(result >=50);
return result;
}
If you want really constant time, you can do this:
int d50()
{
int result = d15();
int result = result*15+d15(); //0 to 225
int result = result*8+d8(); //0 to 1799
return result/36; //integer division rounds down
}
This way combines dice until the number of possibilities (1800) is evenly divisible by 50, so the same number of possibilities correspond to each result. This works OK in this case, but doesn't work if the prime factors of the dice you have (2, 3, and 5 in this case), don't cover the factors of the dice you want (2, 5)
I think that you can consider each dice result as a subdivision of a bigger interval. So throwing one 8 sided dice you choose one out the 8 major interval that divide your range of value. Throwing a 15 sided dice means selecting one out the 15 sub-interval and so on.
Considering that 15 = 3*5, 8 = 2*2*2 and 50 = 2*5*5 you can choose 36 = 3*3*2*2 as an handy multiple of 50 so that:
15*15*8 = 50*36 = 1800
You can even think of expressing the numbers from 0 to 1799 in base 15 and choose ramdomly the three digits:
choice = [0-7]*15^2 + [0-14]*15^1 + [0-14]*15^0
So my proposal, with a test of the distribution, is (in the c++ language):
#include <iostream>
#include <random>
#include <map>
int main() {
std::map<int, int> hist;
int result;
std::random_device rd;
std::mt19937 gen(rd()); // initialiaze the random generator
std::uniform_int_distribution<> d8(0, 7); // istantiate the dices
std::uniform_int_distribution<> d15(0, 14);
for (int i = 0; i < 20000; ++i) { // make a lot of throws...
result = d8(gen) * 225;
result += d15(gen) * 15; // add to result
result += d15(gen);
++hist[ result / 36 + 1]; // count each result
}
for (auto p : hist) { // show the occurences of each result
std::cout << p.first << " : " << p.second << '\n';
}
return 0;
}
The output should be something like this:
1 : 387
2 : 360
3 : 377
4 : 393
5 : 402
...
48 : 379
49 : 378
50 : 420

Resources