1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| #include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_permutation.h>
void weightedSample(gsl_rng* r, double* liste, double* weights, double* target, int sizeOfListe, int nTrials);
int main(int argc, char* argv[]){
int i =0;
int seed = atoi(argv[1]);
// Random generator
const gsl_rng_type *T;
gsl_rng *r;
gsl_rng_env_setup();
T=gsl_rng_default;
r=gsl_rng_alloc(T);
gsl_rng_set(r, seed);
int K = 5; // longueur de liste et de weights
double liste[5] = {2, 4, 6, 8, 10}; // vector of elements from which to choose
double weights[5] = {1.2, 0.6, 0.3, 0.15, 0.05}; // A vector of probability weights for obtaining the elements of the vector being sampled
unsigned int N = 20; // nombre d'essais
double target[20] = {0}; //
weightedSample(r, liste, weights, target, K, N); // performs N weighted_random_sampling + shuffling of 'liste' (size K), stock the output in 'target'
for(i=0; i<N; i++){
printf("%.lf ", target[i]);
}
printf("\n");
return(0);
}
void weightedSample(gsl_rng* r, double* liste, double* weights, double* target, int sizeOfListe, int nTrials){
int i = 0;
int* n = NULL;
int* sampledListe = NULL;
n = malloc(sizeOfListe * sizeof(double)); // will contain the number of succes after N nTrials for each of the sizeOfListe elements of liste
sampledListe = malloc(nTrials * sizeof(int)); // if n={0, 3, 1, 1}, sampledListe={1, 1, 1, 4, 5}
gsl_ran_multinomial(r, sizeOfListe, nTrials, weights, n); // return in 'n' the number of success for the sizeOfListe elements of liste
int nValues = 0;
int tmp = 0;
int tmp2 = 0;
for(i=0; i<sizeOfListe; i++){ // loop along the list called 'n' resulting from gsl_ran_multinomial
nValues = n[i];
if(nValues != 0){
tmp2 = 0;
do{
sampledListe[tmp] = i;
tmp++;
tmp2++;
}while(tmp2 < nValues);
}
}
// shuffle values of the sampledListe: obtaining something like {1, 4, 1, 5, 1} from the initial {1, 1, 1, 4, 5}
gsl_permutation* p = gsl_permutation_alloc (nTrials);
gsl_permutation_init (p);
gsl_ran_shuffle(r, p -> data, nTrials, sizeof(size_t));
tmp = 0;
for(i=0; i<nTrials; i++){
tmp=gsl_permutation_get(p, i);
target[i]=liste[sampledListe[tmp]];
}
free(n);
free(sampledListe);
gsl_permutation_free(p);
} |
Partager