Stable release of RBC
[RBC.git] / utils.cu
1 #ifndef UTILS_CU
2 #define UTILS_CU
3
4 #include<sys/time.h>
5 #include<stdio.h>
6 #include "utils.h"
7 #include "defs.h"
8
9 //Returns a length l subset of a random permutation of [0,...,n-1]
10 //using the knuth shuffle.
11 //Input variable x is assumed to be alloced and of size l.
12 void subRandPerm(int l, int n, int *x){
13 int i,ri, *y;
14 y = (int*)calloc(n,sizeof(*y));
15
16 struct timeval t3;
17 gettimeofday(&t3,NULL);
18 srand(t3.tv_usec);
19
20 for(i=0;i<n;i++)
21 y[i]=i;
22
23 for(i=0;i<MIN(l,n-1);i++){ //The n-1 bit is necessary because you can't swap the last
24 //element with something larger.
25 ri=randBetween(i+1,n);
26 swap(&y[i],&y[ri]);
27 }
28
29 for(i=0;i<l;i++)
30 x[i]=y[i];
31 free(y);
32 }
33
34 //Generates a random permutation of 0, ... , n-1 using the knuth shuffle.
35 //This should probably be merged with subRandPerm.
36 void randPerm(int n, int *x){
37 int i,ri;
38
39 struct timeval t3;
40 gettimeofday(&t3,NULL);
41 srand(t3.tv_usec);
42
43 for(i=0;i<n;i++){
44 x[i]=i;
45 }
46
47 for(i=0;i<n-1;i++){
48 ri=randBetween(i+1,n);
49 swap(&x[i],&x[ri]);
50 }
51 }
52
53 void swap(int *a, int *b){
54 int t;
55 t=*a; *a=*b; *b=t;
56 }
57
58 //generates a rand int in rand [a,b)
59 int randBetween(int a, int b){
60 int val,c;
61
62 if(b<=a){
63 fprintf(stderr,"misuse of randBetween.. exiting\n");
64 exit(1);
65 }
66 c= b-a;
67
68 while(c<= (val= rand()/(int)(((unsigned)RAND_MAX + 1) / c)));
69 val=val+a;
70
71 return val;
72 }
73
74
75 void printMat(matrix A){
76 int i,j;
77 for(i=0;i<A.r;i++){
78 for(j=0;j<A.c;j++)
79 printf("%6.4f ",(float)A.mat[IDX(i,j,A.ld)]);
80 printf("\n");
81 }
82 }
83
84
85 void printMatWithIDs(matrix A, int *id){
86 int i,j;
87 for(i=0;i<A.r;i++){
88 for(j=0;j<A.c;j++)
89 printf("%6.4f ",(float)A.mat[IDX(i,j,A.ld)]);
90 printf("%d ",id[i]);
91 printf("\n");
92 }
93 }
94
95
96 void printCharMat(charMatrix A){
97 int i,j;
98 for(i=0;i<A.r;i++){
99 for(j=0;j<A.c;j++)
100 printf("%d ",(char)A.mat[IDX(i,j,A.ld)]);
101 printf("\n");
102 }
103 }
104
105 void printVector(real *x, int d){
106 int i;
107
108 for(i=0 ; i<d; i++)
109 printf("%6.2f ",x[i]);
110 printf("\n");
111 }
112
113
114 void copyVector(real *x, real *y, int d){
115 int i;
116
117 for(i=0;i<d;i++)
118 x[i]=y[i];
119 }
120
121
122 void copyMat(matrix *x, matrix *y){
123 int i,j;
124
125 x->r=y->r; x->pr=y->pr; x->c=y->c; x->pc=y->pc; x->ld=y->ld;
126 for(i=0; i<y->r; i++){
127 for(j=0; j<y->c; j++){
128 x->mat[IDX( i, j, x->ld )] = y->mat[IDX( i, j, y->ld )];
129 }
130 }
131 }
132
133
134 real distL1(matrix x, matrix y, int k, int l){
135 int i;
136 real ans=0;
137
138 for(i=0;i<x.c;i++)
139 ans+=abs(x.mat[IDX(k,i,x.ld)]-y.mat[IDX(l,i,x.ld)]);
140 return ans;
141 }
142
143 double timeDiff(struct timeval start, struct timeval end){
144 return (double)(end.tv_sec+end.tv_usec/1e6 - start.tv_sec - start.tv_usec/1e6);
145 }
146
147
148
149 #endif