IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C Discussion :

Problème gestion de mémoire interfaçage code C/R


Sujet :

C

  1. #1
    Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2016
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2016
    Messages : 6
    Points : 2
    Points
    2
    Par défaut Problème gestion de mémoire interfaçage code C/R
    Bonjour à tous,

    Je viens ici car je ne comprends vraiment pas pourquoi mon code ne marche pas et qu'après 3 jours dessus je sature ...
    Alors en fait j'ai un code R qui utilise des fonctions codées en C pour gagner du temps de calcul.
    Sauf que quasiment à chaque fois que je lance le script R cela plante (fatal error ou alors tourne en boucle mais n'affiche rien) ou m'affiche une erreur du type :

    malloc: *** error for object 0x123456c99 : incorrect checksum for freed object - object was probably modified after being freed.

    J'en déduis donc qu'il y a un problème de gestion de mémoire dans le code C mais je n'arrive vraiment pas à voir lequel (je précise que je suis pas un expert en C ...).

    Pour les courageux qui prendront le temps de le lire parce qu'il est assez long, voici le code C :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    #include <stdio.h>
    #include <stdlib.h>
    #include "R.h"
    #include "Rinternals.h"
    #include <math.h>
    #include <string.h>
    #include <time.h>
    #include <assert.h>
     
    /*
     * Signatures des fonctions
     */
     
    double log2(double x) ;
    void nrerror(char error_text[]);
    int ** alloc2ii(int nl, int nc);
    void free2ii(int **tab, int nl);
    int *ivector(long nl, long nh);
    double *dvector(long nl, long nh);
    void free_ivector(int *v, long nl, long nh);
    void free_dvector(double *v, long nl, long nh);
    void moveLine(int **toEmpty, int **toFill, int nCol, int* nRowsE, int* nRowsF,
    		int lineToMove);
    void moveObservations(int ** toEmpty, int ** toFill, int nCol, int* nRowsE,
    		int* nRowsF, int modaCritique, int varCritique);
    void afficheMat(int **tab, int nRow, int nCol);
    void copyMat(int ** original, int ** copy, int nobs, int nvar);
    void copyVect(int * original, int * copy, int nCol);
    void afficheVect(int * vect, int nCol);
    typedef struct split split;
    split initSplit(int nRows, int nCol, int * nbModa, int ** father,
    		int modaCritique);
    void free_split(split split);
    void copySplit(split original, split copy);
    double distSplits(split splitRef, split splitMes, int nobs);
    double entropyVariable(int ** data, int nObs, int numVar, int nbModa);
    double calcEntropy(int ** data, int nObs, int nVar, int * nbModa);
    double calcGainEntropy(split split, double entropyFather, int nCol,
    		int * nbModa);
    void afficheSplit(split split, int nbModa, int nbCol);
    split initSearch2(split split, int nObs, int nCol, int numVariable, int *nbModa,
    		int *nbSplits);
    int nb_ones(int * tab, int n);
    split nextSplit(split split, int nCol, int * nbModa);
    split splitData(int ** data, int nbObs, int nbCol, int *nbModa,
    		double threshold) ;
    void split_R(int *dt, int *no, int *nv, int *nbm, double *thresh, int *bestVar,
    		int *tab, double *dev) ;
    /*
     * Constants
     */
     
    #define NR_END 1
    #define FREE_ARG char*
    #define NSTACK 50
    #define M 7
    #define SWAP(a,b) itemp=(a);(a)=(b);(b)=itemp;
    #define M_LOG2E 1.44269504088896340736 //log2(e)
     
    /*
     * Fonctions accessoires
     */
     
    /*
     * log en base 2
     */
    double log2(double x) {
    	return log(x) * M_LOG2E;
    }
     
    /*
     * Gestion de la mÈmoire
     */
     
    void nrerror(char error_text[])
    /* Numerical Recipes standard error handler */
    {
    	fprintf(stderr, "Numerical Recipes run-time error...\n");
    	fprintf(stderr, "%s\n", error_text);
    	fprintf(stderr, "...now exiting to system...\n");
    	exit(1);
    }
     
    int **alloc2ii(int nl, int nc) {
    	/* allocate a double pointer */
    	int i;
     
    	int **tab;
     
     
    	tab = (int **) calloc(nl, sizeof(int *));
    	assert(tab != NULL);
    	for (i = 0; i < nl; i++) {
    		tab[i] = (int *) calloc(nc, sizeof(int));
    		assert(tab[i] != NULL);
    	}
     
    	return tab;
    }
     
    void free2ii(int **tab, int nl) {
    	/* liberate a double pointer */
    	int i;
     
     
    	if (tab != NULL) {
            for (i = 0; i < nl; i++){
                if (tab[i] != NULL)
                    free(tab[i]);
            }
    	}
    	free(tab);
    	tab = NULL;
     
     
    }
     
    int *ivector(long nl, long nh)
    /* allocate an int vector with subscript range v[nl..nh] */
    {
    	int *v;
     
    	v = (int *) malloc((size_t) ((nh - nl + 1 + NR_END) * sizeof(int)));
    	if (!v)
    		nrerror("allocation failure in ivector()");
     
    	return v - nl + NR_END;
    }
     
    double *dvector(long nl, long nh)
    /* allocate a double vector with subscript range v[nl..nh] */
    {
    	double *v;
     
    	v = (double *) malloc((size_t) ((nh - nl + 1 + NR_END) * sizeof(double)));
    	if (!v)
    		nrerror("allocation failure in dvector()");
     
    	return v - nl + NR_END;
    }
     
    void free_ivector(int *v, long nl, long nh)
    /* free an int vector allocated with ivector() */
    {
    	free((FREE_ARG) (v + nl - NR_END));
    }
     
    void free_dvector(double *v, long nl, long nh)
    /* free a double vector allocated with dvector() */
    {
    	free((FREE_ARG) (v + nl - NR_END));
    }
     
    /*
     * Manipulation de matrices
     */
     
    void moveLine(int **toEmpty, int **toFill, int nCol, int *nRowsE, int *nRowsF,
    		int lineToMove) {
    // deplace une ligne de la matrice toEmpty vers la matrice toFill
    	int j;
     
    	for (j = 0; j < nCol; j++) {
    		toFill[*nRowsF][j] = toEmpty[lineToMove][j];
    		toEmpty[lineToMove][j] = toEmpty[*nRowsE - 1][j];
    	}
    	*nRowsE = *nRowsE - 1;
    	(*nRowsF)++;
     
    }
     
    void moveObservations(int **toEmpty, int **toFill, int nCol, int *nRowsE,
    		int *nRowsF, int modaCritique, int varCritique) {
    	// Deplace de toEmpty vers toFill toutes les observations qui prennet la modaCritique pour la varCritique
    	int i;
     
    	for (i = 0; i < *nRowsE; i++) {
    		if (toEmpty[i][varCritique] == modaCritique) {
    			moveLine(toEmpty, toFill, nCol, nRowsE, nRowsF, i);
    			i--; // Comme l'observation nRowsE-1 a pris la place de l'observation i, il faut la tester en tant que nouvelle observation i.
    		}
    	}
     
    }
     
    void afficheMat(int **tab, int nRow, int nCol) {
        FILE * fic;
        char *fileout;
        fileout="merde.txt";
        fic = fopen(fileout,"w+");
        if (fic == NULL) fprintf(stdout,"Problem accessing output file: %s\n",fileout);
     
    	int i, j;
     
    	fprintf(fic,"affichage matrice \n");
    	fprintf(fic,"\n");
    	for (i = 0; i < nRow; i++) {
    		for (j = 0; j < nCol; j++) {
    			fprintf(fic,"%d", tab[i][j]);
    			fprintf(fic," ; ");
    		}
    		fprintf(fic,"\n");
    	}
        fclose(fic);
     
    }
     
    void copyMat(int **original, int **copy, int nobs, int nvar) {
    	int i, j;
    	for (i = 0; i < nobs; i++) {
    		for (j = 0; j < nvar; j++) {
    			copy[i][j] = original[i][j];
    		}
    	}
     
    }
     
    void copyVect(int *original, int *copy, int nCol) {
    	int i;
     
    	for (i = 0; i < nCol; i++) {
    		copy[i] = original[i];
    	}
     
    }
     
    void afficheVect(int *vect, int nCol) {
        FILE * fic;
        char *fileout;
        fileout="merde.txt";
        fic = fopen(fileout,"w+");
        if (fic == NULL) fprintf(stdout,"Problem accessing output file: %s\n",fileout);
     
    	int j;
    fprintf(fic,"affichage vecteur \n");
    	for (j = 0; j < nCol; j++) {
    		fprintf(fic,"%d", vect[j]);
    		fprintf(fic," ; ");
    	}
        fprintf(fic,"\n");
        fclose(fic);
     
    }
     
    /*
     * La structure "Split"
     */
     
    struct split {
    	// beaucoup de fonctions ont pu etre simplifiees grace a cette structure !
    	int nCol;
    	int nRowsL;
    	int nRowsR;
    	int *tab;
    	int varCritique;
    	int **left;
    	int **right;
    	double entropyFather;
    	double gainEntropy;
    	int **father;
    	int *nbModaFather;
    };
     
    split initSplit(int nRows, int nCol, int *nbModa, int **father,
    		int modaCritique) {
     
    	split res;
    	int **left;
    	int **right;
    	int *tab;
     
     
    	// allocations memoire
    	left = alloc2ii(nRows, nCol);
    	right = alloc2ii(nRows, nCol);
    	tab = ivector(0, nbModa[modaCritique]);
     
    	res.nCol = nCol;
    	res.nRowsL = 0;
    	res.nRowsR = 0;
    	res.tab = tab;
    	res.varCritique = modaCritique;
    	res.left = left;
    	res.right = right;
    	res.gainEntropy = 0.0;
     
        /* Liberation memoire ?
        free2ii(left,nRows);
        free2ii(right,nRows);
        free_ivector(tab,0,nbModa[modaCritique]);
        */
     
    	return res;
    }
     
    void free_split(split split) {
    	free2ii(split.left, split.nRowsL);
    	free2ii(split.right, split.nRowsR);
    	free_ivector(split.tab, 0, split.nbModaFather[split.varCritique]);
    }
     
     
    void copySplit(split original, split copy) {
    	copy.nRowsL = original.nRowsL;
    	copy.nRowsR = original.nRowsR;
    	copyVect(original.tab, copy.tab, original.nCol);
    	copy.varCritique = original.varCritique;
    	copyMat(original.left, copy.left, original.nRowsL, original.nCol);
    	copyMat(original.right, copy.right, original.nRowsR, original.nCol);
    	copy.entropyFather = original.entropyFather;
    	copy.gainEntropy = original.entropyFather;
    	copy.father = original.father;
    	copyVect(original.nbModaFather, copy.nbModaFather, original.nCol);
    }
    /*
     * Distance entre deux splits
     * Utile pour calculer l'importance des variables
     */
    double distSplits(split splitRef, split splitMes, int nobs) {
    	double res = 0;
    	int i, id, **pos, nbLRef, nbLMes, nbRRef, nbRMes;
    	nbLRef = splitRef.nRowsL;
    	nbLMes = splitMes.nRowsL;
    	nbRRef = splitRef.nRowsR;
    	nbRMes = splitMes.nRowsR;
     
    	pos = alloc2ii(nobs, 2);
     
    	/*
    	 * Preparation du tableau pos
    	 * pos[id][0]=0 (resp 1) si l'ident id est a gauche (resp a droite) pour le split splitRef
    	 * pos[id][1]=0 (resp 1) si l'ident id est a gauche (resp a droite) pour le split splitMes
    	 */
    	for (i = 0; i < nbLRef; i++) {
    		id = splitRef.left[i][0];
    		pos[id][0] = 0;
    	}
    	for (i = 0; i < nbLMes; i++) {
    		id = splitMes.left[i][0];
    		pos[id][1] = 0;
    	}
    	for (i = 0; i < nbRRef; i++) {
    		id = splitRef.right[i][0];
    		pos[id][0] = 1;
    	}
    	for (i = 0; i < nbRMes; i++) {
    		id = splitMes.right[i][0];
    		pos[id][1] = 1;
    	}
     
    	/*
    	 * Decompte du nombre de predictions communes pour splitRef et splitMes
    	 */
    	int nbGoodPredictions = 0;
    	for (i = 0; i < nobs; i++) {
    		if (pos[i][0] == pos[i][1]) {
    			nbGoodPredictions++;
    		}
    	}
     
    	res = nbGoodPredictions / nobs;
     
        // Liberation memoire ?
        free2ii(pos,nobs);
     
    	return res;
    }
     
    /*
     * Calculs de deviance
     */
     
    double entropyVariable(int **data, int nObs, int numVar, int nbModa) {
     
    	/* Computes entropy of the numVar-th variable in a table of nObs number of lines, nVar number of variables,
    	 * nbModa is the number of modalities for the variable numVar.
    	 *  */
     
    	int i;
     
    	//int realNbModa;
    	double ent, *freq, sumPlogP, plogP;
    	/* allocation memoire */
    	freq = dvector(0, nbModa + 1);
     
    	// vecteur des frequences des modalites
    	for (i = 0; i < nbModa + 1; i++) {
    		freq[i] = 0;
    	}
    	//realNbModa = 0;
    	sumPlogP = 0.0;
    	for (i = 0; i < nObs; i++) {
    		freq[data[i][numVar]]++;
    	}
     
    	for (i = 0; i < nbModa + 1; i++) {
    		freq[i] = freq[i] / nObs;
     
    	/*		printf("\n i=");
    		 printf("%d", i);
    		 printf("\n freq[i]= ");
    		 printf("%f", freq[i]);*/
     
    		if (freq[i] > 0.00001) {
    			plogP = freq[i] * log(freq[i]);			// traditionnellement, log2 au lieu de log
    			sumPlogP += plogP;
     
    		/*	 printf("\n plogP = ");
    			 printf("%f", plogP);
    			 printf("\n sumPlogP = ");
    			 printf("%f", sumPlogP);*/
     
    		}
    	}
    	ent = -sumPlogP;
     
    	/* liberation memoire */
    	free_dvector(freq, 0, nbModa+1);
     
    	return (ent);
    }
     
    double calcEntropy(int **data, int nObs, int nVar, int *nbModa) {
     
    	/* Computes entropy of nObs number of lines, nVar number of variables, nbModa is the vector of the number of modalities.
    	 * The first column is considered to be the identifier and not taken into account for computation.
    	 *  */
     
    	int i;
     
    	double ent;
     
    	ent = 0.0;
    	for (i = 1; i < nVar; i++)
    	// We don't use the first variable which is the ident
    			{
    		ent = ent + entropyVariable(data, nObs, i, nbModa[i]);
    	}
    	return (ent);
    }
     
    double calcGainEntropy(split split, double entropyFather, int nCol,
    		int *nbModa) {
    	double res;
     
    	int nG, nD;
     
    	nG = split.nRowsL;
    	nD = split.nRowsR;
    	res = entropyFather
    			- (nG * calcEntropy(split.left, split.nRowsL, nCol, nbModa)
    					+ nD * calcEntropy(split.right, split.nRowsR, nCol, nbModa))
    					/ (nG + nD);
     
    	/*old version = entropyFather
    					- calcEntropy(currentSplit.left, currentSplit.nRowsL, nbCol,
    							nbModa)
    					- calcEntropy(currentSplit.right, currentSplit.nRowsR, nbCol,
    							nbModa);*/
     
    	return res;
    }
     
    void afficheSplit(split split, int nbModa, int nbCol) {
        FILE * fic;
        char *fileout;
        fileout="merde.txt";
        fic = fopen(fileout,"w+");
        if (fic == NULL) fprintf(stdout,"Problem accessing output file: %s\n",fileout);
     
    	fprintf(fic,"\n Affichage du Split:");
     
    	fprintf(fic,"\n var Critique=%d", split.varCritique);
    	fprintf(fic,"\n tableau du Split:");
    	afficheVect(split.tab, nbModa);
    	fprintf(fic,"\n left:");
    	afficheMat(split.left, split.nRowsL, nbCol);
    	fprintf(fic,"\n right:");
    	afficheMat(split.right, split.nRowsR, nbCol);
    	fprintf(fic,"\n gainEntropy=%f \n", split.gainEntropy);
        fclose(fic);
    }
     
    /*
     * Initialise la recherche du meilleur split pour une variable donnee
     */
     
    split initSearch2(split split, int nObs, int nCol, int numVariable, int *nbModa,
    		int *nbSplits) {
    	// prepare left, right, tab and compute nbSplits
     
    	int *tab;
     
    	int nModa, i;
     
    	nModa = nbModa[numVariable];
    	tab = ivector(0, nModa);
    	*nbSplits = (int) pow((double) 2, (nModa - 1)) - 1;
    	for (i = 1; i < nModa; i++) {
    		tab[i] = 0;
    	}
    	tab[0] = 1;
    	copyVect(tab, split.tab, nModa);
    	split.varCritique = numVariable;
    	copyMat(split.father, split.left, nObs, nCol);
    	split.nRowsL = nObs;
    	split.nRowsR = 0;
    	moveObservations(split.left, split.right, nCol, &(split.nRowsL),
    			&(split.nRowsR), 0, numVariable);
     
         //Liberation memoire ?
        //free_ivector(tab,0,nModa);
     
     
    	return split;
    }
     
    /*
     * Passage au prochain split selon une variable
     */
     
    int nb_ones(int *tab, int n) {
    	/* compte les '1' dans un tableau d'entiers; n=taille du tableau */
    	int res, i;
     
    	res = 0;
    	for (i = 0; i < n; i++) {
    		if (tab[i] == 1) {
    			res++;
    		}
    	}
    	return (res);
    }
     
    // NextSplit en utilisant la structure split
    split nextSplit(split split, int nCol, int *nbModa) {
     
    	int nbOnes, bitToChange, nModa;
    	nModa = nbModa[split.varCritique];
    	/* Determine la modalite a changer de cote */
    	nbOnes = nb_ones(split.tab, nModa);
    	bitToChange = 0;
    	if (nbOnes % 2 != 0) {
    		while (split.tab[bitToChange] == 0) {
    			bitToChange++;
    		}
    		bitToChange++;
    	}
     
    	// Retrouve dans quelle direction il faut deplacer des individus
    	int nodeToEmpty = split.tab[bitToChange];
    	// =0 si on deplace des individus de Left vers Right, 1 sinon
    	if (nodeToEmpty == 0) {
    		moveObservations(split.left, split.right, nCol, &(split.nRowsL),
    				&(split.nRowsR), bitToChange, split.varCritique);
    		/// Attention, bitToChange entier ou valeur de la moda ?! -> Modalites codÈes par des entiers!
    	} else {
    		moveObservations(split.right, split.left, nCol, &(split.nRowsR),
    				&(split.nRowsL), bitToChange, split.varCritique);
    	}
     
    	// Met a jour le tableau d'entiers
    	split.tab[bitToChange] = 1 - split.tab[bitToChange];
     
    	// Calcule l'entropy
    	split.gainEntropy = calcGainEntropy(split, split.entropyFather, nCol,
    			nbModa);
     
    	return split;
    }
     
    /*
     * Fonction principale
     */
     
    split splitData(int **data, int nbObs, int nbCol, int *nbModa,
    		double threshold) {
    	/*
    	 *  trouve le meilleur split du jeu de donnees data, variables nominales, modalites codees 0..n .
    	 *  premiere colonne = identifiant.
    	 *  *nbModa vecteur des nb de Moda.
    	 *  threshold seuil (gain minimal d'entropie pour qu'un split soit retenu)
    	 *  Solutions:
    	 *  retourne le split optimal
    	 *  */
     
     
     
    	int i, j, nbSplits;
    	double entropyFather, bestGainEntropy, deltaEntropy;
     
    	split bestSplit = initSplit(nbObs, nbCol, nbModa, data, 1);
    	split currentSplit = initSplit(nbObs, nbCol, nbModa, data, 1);
    	bestSplit.father = data;
    	bestSplit.entropyFather = calcEntropy(data, nbObs, nbCol, nbModa);
    	currentSplit.father = data;
    	currentSplit.entropyFather = bestSplit.entropyFather;
     
       /* FILE * fic;
        char *fileout;
        fileout="merde.txt";
        fic = fopen(fileout,"w+");
        if (fic == NULL) fprintf(stdout,"Problem accessing output file: %s\n",fileout);
        
    	fprintf(fic,"\n welcome in splitData!\n ");
    */
    	bestGainEntropy = threshold;
    	entropyFather = calcEntropy(data, nbObs, nbCol, nbModa);
     
    	for (i = 1; i < nbCol; i++) {
    		// La colonne i=0 est l'identifiant
     
    		currentSplit = initSearch2(currentSplit, nbObs, nbCol, i, nbModa,
    				&nbSplits);
     
    		deltaEntropy=calcGainEntropy(currentSplit,entropyFather,nbCol,nbModa);
     
    		currentSplit.gainEntropy = deltaEntropy;
     
    		// code avec souci
    		/*	if (deltaEntropy > bestGainEntropy) {
    		 afficheVect(currentSplit.tab, nbModa[i]);
    		 bestSplit = initSplit(nbObs, nbCol, nbModa, data, i);
    		 copySplit(currentSplit, bestSplit);
    		 bestGainEntropy = deltaEntropy;
    		 }
    		 */
    		//alternative
    		if (deltaEntropy > bestGainEntropy) {
    			//afficheVect(currentSplit.tab, nbModa[i]);
    			copyMat(currentSplit.left, bestSplit.left, currentSplit.nRowsL,
    					nbCol);
    			copyMat(currentSplit.right, bestSplit.right, currentSplit.nRowsR,
    					nbCol);
    			bestSplit.tab = ivector(0, nbModa[i]);
    			copyVect(currentSplit.tab, bestSplit.tab, nbModa[i]);
     
    			bestSplit.gainEntropy = deltaEntropy;
    			bestSplit.nRowsL = currentSplit.nRowsL;
    			bestSplit.nRowsR = currentSplit.nRowsR;
    			bestSplit.varCritique = i;
    			bestGainEntropy = deltaEntropy;
    		}
     
    		//fin de l'alternative
    		for (j = 1; j < nbSplits; j++) {
    			currentSplit = nextSplit(currentSplit, nbCol, nbModa);
     
    			deltaEntropy=calcGainEntropy(currentSplit,entropyFather,nbCol,nbModa);
    			currentSplit.gainEntropy = deltaEntropy;
    /*
    				fprintf(fic,"\n Essai de split, i=%d, j=%d, gainEnt=%f", i, j,
    			 deltaEntropy);
     
    			 fprintf(fic,"\n tab: \n");
    			 afficheVect(currentSplit.tab, nbModa[i]);
    			 fprintf(fic,"\n matrice left: \n");
    			 afficheMat(currentSplit.left, currentSplit.nRowsL, nbCol);
    			 fprintf(fic,"\n entropyLeft=%f",
    			 calcEntropy(currentSplit.left, currentSplit.nRowsL, nbCol,
    			 nbModa));
    			 fprintf(fic,"\n entropyRight=%f",
    			 calcEntropy(currentSplit.right, currentSplit.nRowsR, nbCol,
    			 nbModa));
    			 fprintf(fic,"\n gainEntropy=%f", deltaEntropy);
    */
    			if (deltaEntropy > bestGainEntropy) {
    				afficheVect(currentSplit.tab, nbModa[i]);
    				copyMat(currentSplit.left, bestSplit.left, currentSplit.nRowsL,
    						nbCol);
    				copyMat(currentSplit.right, bestSplit.right,
    						currentSplit.nRowsR, nbCol);
    				bestSplit.tab = ivector(0, nbModa[i]);
    				copyVect(currentSplit.tab, bestSplit.tab, nbModa[i]);
     
    				bestSplit.gainEntropy = deltaEntropy;
    				bestSplit.nRowsL = currentSplit.nRowsL;
    				bestSplit.nRowsR = currentSplit.nRowsR;
    				bestSplit.varCritique = i;
    				bestGainEntropy = deltaEntropy;
    			}
    		}
    	}
      /*
    		fprintf(fic,"\n in splitData, meilleur Split trouve:");
    	 afficheSplit(bestSplit, nbModa[bestSplit.varCritique], nbCol);
        fclose(fic);
       */
     
    	// Renvoie la solution
    	//*gainEntropy = bestSplit.gainEntropy; // =0 si aucun split n'a ete trouve
    	free_split(currentSplit);
    	return (bestSplit);
    }
     
    /*
     * Fonction appelee par R
     */
     
    void split_R(int *dt, int *no, int *nv, int *nbm, double *thresh, int *bestVar,
    		int *tab, double *dev) {
    	/*
    	 dt		data set		first column=ident, moda 0...nbm(i)-1 for any variable i.
    	 no			number of observations
    	 nv			number of variables
    	 nbm		vector of number of categories
    	 thresh		threshold
     
    	 RESULTS:
    	 bestVar 	index of the best variable.
    	 tab		Coordinate for optimal split: tab[i]=0 if obs with bestVar=moda i goes to left node, =1 otherwise.
    	 dev		deviance
    	 */
     
    	int i, j, nobs, nvar;
    	int **data;
    	double threshold;
    	split bestSplit;
     
    	nvar = *nv;
    	nobs = *no;
    	threshold = *thresh;
     
    //	Rprintf("Hello, nbmod first var= %d \n",nbmod[1]);
    //	fprintf(stdout,"Number of observations : %d\n",nobs);
    //	fprintf(stdout,"Number of variables    : %d\n",nvar);
     
    	data = alloc2ii(nobs, nvar); /* contient les donnees dans le format matriciel*/
    	bestSplit = initSplit(nobs, nvar, nbm, data, 1);
     
    	/* les donnees en format matriciel */
    	for (i = 0; i < nobs; i++)
    		for (j = 0; j < nvar; j++)
    			data[i][j] = dt[j * nobs + i];
     
    	bestSplit = splitData(data, nobs, nvar, nbm, threshold);
     
    // Results
    	*bestVar = bestSplit.varCritique;
    	copyVect(bestSplit.tab, tab, nvar);
    	*dev = bestSplit.gainEntropy;
     
    //Liberation memoire
    	free2ii(data, nobs);
    	free_split(bestSplit);
    }
    Vu la taille cela risque de freiner beaucoup de monde mais je remercie d'avance ceux qui prendront le temps de lire et de m'éclairer.

  2. #2
    Expert confirmé
    Inscrit en
    Mars 2005
    Messages
    1 431
    Détails du profil
    Informations forums :
    Inscription : Mars 2005
    Messages : 1 431
    Points : 4 182
    Points
    4 182
    Par défaut
    Il y a deux soucis avec ta requête :

    1. le code est en effet beaucoup trop long ;
    2. on ne peut pas le tester.


    Commente tout et décommente progressivement jusqu'à ce que le dysfonctionnement se manifeste, ce afin d'isoler les sections qui sont en cause.

  3. #3
    Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2016
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2016
    Messages : 6
    Points : 2
    Points
    2
    Par défaut
    En fait dans tout le code que j'ai mis il y a une seule fonction utilisée par R, la fonction split_R qui se trouve à la fin. Cependant dans cette fonction je fais appel à la fonction principale du code C, la fonction splitData qui elle utilise toutes les autres fonctions plus haut ...

    Je n'ai pas mis le code R parce que je me trouve sur le forum C mais le voici :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    split.node2<-function (xx, N, crit0 = "anova") 
    {
      if (mode(xx) != "character") {
        #if (!is.loaded("cubt")) 
        #library.dynam("cubt", "cubt", lib.loc = .libPaths())
        n1 = as.integer(ncol(xx))
        n2 = as.integer(nrow(xx))
        if (crit0 == "anova") 
          n3 = 0
        else n3 = length(unique(as.vector(xx)))
        res1 = as.double(numeric(1))
        res2 = as.integer(numeric(1))
        res3 = as.double(numeric(1))
        res = .C("split_R", as.double(as.matrix(xx)), n2, n1, as.integer(n3), 
                 res1, res2, res3)
        res1 = res[[5]]
        res2 = res[[6]]
        res3 = res[[7]]
        out = list(var = paste("x", res2, sep = ""), n = n2, 
                   dev = res3, yval = "", splits.cutleft = paste("<", 
                                                                 signif(res1, 4), sep = ""), splits.cutright = paste(">", 
                                                                                                                     signif(res1, 4), sep = ""), coord = res2, seuil = res1)
      }
      else {
        critmax = 0
        nbm = as.integer(lapply(lapply(as.data.frame(xx),unique),length))
        id = seq(0,nrow(xx)-1,1)
        mat<-matrix(as.integer(xx),ncol=ncol(xx))
        mat = cbind(id,mat)
        n1 = as.integer(ncol(mat))
        n2 = as.integer(nrow(mat))
        nnn = as.double(numeric(1))
        bestVar = as.integer(numeric(1))
        dev = as.double(numeric(1))
        tab = integer(max(nbm))
        seuil = as.double(numeric(1))
        #print(c(n2, n1, nbm, seuil, bestVar, tab, dev))
        #print(as.integer(as.matrix(mat)))
        res = .C("split_R", as.integer(as.matrix(mat)), n2, n1, nbm, seuil, bestVar, tab, dev)
        bestVar = res[[6]]
        tab = res[[7]]
        dev = res[[8]]
        # Recuperer les modalites de la meilleure var #
        print(bestVar)
        mod = sort(unique(xx[, bestVar]))
        # Recuperer les modalites de gauche #
        mod.l = mod[which(tab == 1)]
     
        out = list(var = paste("x", bestVar, sep = ""), n = nrow(xx), dev = dev, yval = "", 
                   splits.cutleft = paste(" in {", paste(mod.l, collapse = " "), 
                                          "}", sep = ""), 
                   splits.cutright = paste(" not in {", paste(mod.l, collapse = " "), 
                                           "}", sep = ""), 
                   coord = bestVar, seuil = mod.l)
      }
      out
    }
     
    gendata2=function (model = 1, ncl = 3, n = 100, dim = 9, et = 0.2, disp = TRUE, 
              graph = FALSE) 
    {
      Don = NULL
      if (model == 1) {
        ncl = 3
        if (disp == T) {
          p = matrix(0.05, ncol = 5, nrow = 5)
          diag(p) = 0.8
          p = p[c(-2, -4), ]
        }
        else {
          p = matrix(0.15, ncol = 5, nrow = 5)
          diag(p) = 0.4
          p = p[c(-2, -4), ]
        }
        for (j in 1:ncl) {
          Don1 = NULL
          for (jj in 1:dim) Don1 = cbind(Don1, sample(1:5, 
                                                      floor(n/ncl), prob = p[j, ], replace = TRUE))
          Don = rbind(Don, cbind(rep(j, floor(n/ncl)), Don1))
        }
      }
      if (model == 2) {
        ncl = 4
        eff.cl = floor(n/ncl)
        tout = 1:4
        pair = c(2, 4)
        impair = c(1, 3)
        y = rep(1:4, each = eff.cl)
        x1 = x2 = x3 = rep(NA, n)
        x1[y == 1] = sample(impair, eff.cl, r = T)
        x1[y == 2] = sample(impair, eff.cl, r = T)
        x1[y == 3] = sample(pair, eff.cl, r = T)
        x1[y == 4] = sample(pair, eff.cl, r = T)
        x2[y == 1] = sample(impair, eff.cl, r = T)
        x2[y == 2] = sample(pair, eff.cl, r = T)
        x2[y == 3] = sample(tout, eff.cl, r = T)
        x2[y == 4] = sample(tout, eff.cl, r = T)
        x3[y == 1] = sample(tout, eff.cl, r = T)
        x3[y == 2] = sample(tout, eff.cl, r = T)
        x3[y == 3] = sample(impair, eff.cl, r = T)
        x3[y == 4] = sample(pair, eff.cl, r = T)
        Don = cbind(y, x1, x2, x3)
        if (disp == F) {
          Don = cbind(Don, matrix(sample(1:4, 6 * nrow(Don), 
                                         r = T), ncol = 6))
          dim = 9
        }
        else dim = 3
      }
      if (model == 3) {
        p = c(0.8, 0.2)
        ncl = 4
        eff.cl = floor(n/ncl)
        tout = 1:4
        pair = c(2, 4)
        impair = c(1, 3)
        y = rep(1:4, each = eff.cl)
        x1 = x2 = x3 = rep(NA, n)
        x1[y == 1] = sample(impair, eff.cl, r = T, prob = p)
        x1[y == 2] = sample(impair, eff.cl, r = T, prob = p)
        x1[y == 3] = sample(pair, eff.cl, r = T, prob = p)
        x1[y == 4] = sample(pair, eff.cl, r = T, prob = p)
        x2[y == 1] = sample(impair, eff.cl, r = T, prob = p)
        x2[y == 2] = sample(pair, eff.cl, r = T, prob = p)
        x2[y == 3] = sample(tout, eff.cl, r = T)
        x2[y == 4] = sample(tout, eff.cl, r = T)
        x3[y == 1] = sample(tout, eff.cl, r = T)
        x3[y == 2] = sample(tout, eff.cl, r = T)
        x3[y == 3] = sample(impair, eff.cl, r = T, prob = p)
        x3[y == 4] = sample(pair, eff.cl, r = T, prob = p)
        Don = cbind(y, x1, x2, x3)
        if (disp == F) {
          Don = cbind(Don, matrix(sample(1:4, 6 * nrow(Don), 
                                         r = T), ncol = 6))
          dim = 9
        }
        else dim = 3
      }
      Don = data.frame(Don)
      colnames(Don) = c("y", paste("x", 1:dim, sep = ""))
      if (graph) 
        boxplot(rowSums(Don[, -1]) ~ Don$y)
      Don
    }
     
     
    miseEnFormeNominal<-function(x){
      x<-as.matrix(x)
      for (i in 1:ncol(x)) {
        x[,i]<-as.character(x[,i])
      }
      return (x)
    }
     
    dyn.load(file.choose())      # choisir le fichier .dll ou .so selon l'environnement de travail
     
    Don=gendata2(model=2,dim=3)
    Don=miseEnFormeNominal(Don[,-1])
     
    split.node2(Don,nrow(Don),crit0="entropy")
    Pour les personnes qui souhaitent tester le code il faut au préalable compiler le code C en utilisant la commande R CMD SHLIB nomfichier.c puis lancer le script R.


    Les fonctions qui gèrent l'allocation de mémoire et la libération de mémoire vous semble-t-elle bonnes ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    #define NR_END 1
    #define FREE_ARG char*
    int **alloc2ii(int nl, int nc) {
    	/* allocate a double pointer */
    	int i;
     
    	int **tab;
     
     
    	tab = (int **) calloc(nl, sizeof(int *));
    	assert(tab != NULL);
    	for (i = 0; i < nl; i++) {
    		tab[i] = (int *) calloc(nc, sizeof(int));
    		assert(tab[i] != NULL);
    	}
     
    	return tab;
    }
     
    void free2ii(int **tab, int nl) {
    	/* liberate a double pointer */
    	int i;
     
     
    	if (tab != NULL) {
            for (i = 0; i < nl; i++){
                if (tab[i] != NULL)
                    free(tab[i]);
            }
    	}
    	free(tab);
    	tab = NULL;
     
     
    }
     
    int *ivector(long nl, long nh)
    /* allocate an int vector with subscript range v[nl..nh] */
    {
    	int *v;
     
    	v = (int *) malloc((size_t) ((nh - nl + 1 + NR_END) * sizeof(int)));
    	if (!v)
    		nrerror("allocation failure in ivector()");
     
    	return v - nl + NR_END;
    }
     
    double *dvector(long nl, long nh)
    /* allocate a double vector with subscript range v[nl..nh] */
    {
    	double *v;
     
    	v = (double *) malloc((size_t) ((nh - nl + 1 + NR_END) * sizeof(double)));
    	if (!v)
    		nrerror("allocation failure in dvector()");
     
    	return v - nl + NR_END;
    }
     
    void free_ivector(int *v, long nl, long nh)
    /* free an int vector allocated with ivector() */
    {
    	free((FREE_ARG) (v + nl - NR_END));
    }
     
    void free_dvector(double *v, long nl, long nh)
    /* free a double vector allocated with dvector() */
    {
    	free((FREE_ARG) (v + nl - NR_END));
    }

  4. #4
    Expert confirmé
    Inscrit en
    Mars 2005
    Messages
    1 431
    Détails du profil
    Informations forums :
    Inscription : Mars 2005
    Messages : 1 431
    Points : 4 182
    Points
    4 182
    Par défaut
    Ce que je veux dire c'est que comme on ne peut exécuter ton programme sans les dépendances, il faut forcément se taper tout ou partie des 750 lignes du wall of code et que comme tu t'en es douté ça ne fait bander personne.


    Trois remarques cela dit sur tes routines de gestion mémoire citées ci-avant :

    • return v - nl + NR_END; WAT?! pour quelle raison ne renvoies-tu pas directement l'adresse du bloc alloué ? Pourquoi cette arithmétique ici, sur l'adresse originelle ? Ça ressemble fortement à un recipe for disaster.
    • Pourquoi ce cast (inutile et inquiétant) sur les arguments de tes free ?
    • Ne caste jamais la valeur de retour de *alloc en langage C.

    Corrige déjà cela. Le reste me semble ok et tu vérifies le résultat de tes opérations d'allocation, ce qui est sage.

  5. #5
    Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2016
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2016
    Messages : 6
    Points : 2
    Points
    2
    Par défaut
    D'accord je vais corriger ça mais les fonctions ivector, dvector, free_ivector, free_dvector ont été créées par mon prof en fait.

Discussions similaires

  1. Problème de gestion de mémoire
    Par Baud10 dans le forum MFC
    Réponses: 6
    Dernier message: 04/01/2008, 10h49
  2. Validité d'un code VBA+SQL pour gestion de mémoire
    Par stefposs dans le forum VBA Access
    Réponses: 2
    Dernier message: 27/09/2007, 13h32
  3. Problème de gestion de mémoire (segfault)
    Par Michaël dans le forum C
    Réponses: 7
    Dernier message: 26/05/2007, 09h30
  4. Réponses: 5
    Dernier message: 27/03/2007, 09h51
  5. [C# 2.0] Problème gestion mémoire
    Par Stéphane-M dans le forum Windows Forms
    Réponses: 13
    Dernier message: 21/09/2006, 14h36

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo