first commit
[synclust.git] / src / adapters / a.connexity.c
1 #include <R.h>
2 #include <Rdefines.h>
3 #include "sources/connexity.h"
4
5 // explore the connectivity of a graph (NIix = neighborhoods indices)
6 SEXP getConnectedComponents(
7 SEXP NIix_
8 ) {
9 // extract NIix list vectors in a jagged array
10 int n = LENGTH(NIix_);
11 int* lengthNIix = (int*)malloc(n*sizeof(int));
12 int** NIix = (int**)malloc(n*sizeof(int*));
13 for (int i=0; i<n; i++)
14 {
15 lengthNIix[i] = LENGTH(VECTOR_ELT(NIix_,i));
16 SEXP tmp;
17 PROTECT(tmp = AS_INTEGER(VECTOR_ELT(NIix_,i)));
18 NIix[i] = (int*)malloc(lengthNIix[i]*sizeof(int));
19 for (int j=0; j<lengthNIix[i]; j++)
20 NIix[i][j] = INTEGER(tmp)[j];
21 UNPROTECT(1);
22 // WARNING: R indices start at 1,
23 // so we must lower every index right now to avoid future bug
24 for (int j=0; j<lengthNIix[i]; j++)
25 NIix[i][j]--;
26 }
27
28 // Main call (no R libraries)
29 int* connexComps = getConnectedComponents_core(NIix, lengthNIix, n);
30
31 // free memory
32 for (int i=0; i<n; i++)
33 free(NIix[i]);
34 free(NIix);
35 free(lengthNIix);
36
37 // transfer result in an R object
38 SEXP cc;
39 PROTECT(cc = NEW_INTEGER(n));
40 int* pcc = INTEGER_POINTER(cc);
41 for (int i=0; i<n; i++)
42 pcc[i] = connexComps[i];
43
44 // free remaining memory
45 free(connexComps);
46 UNPROTECT(1);
47
48 return cc;
49 }