Ejemplo n.º 1
0
void Eigsym::eig(const MatDoub &A, MatDoub &V, VecDoub &lambda) {
	unsigned int n = A.ncols();	/* size of the matrix */
	double a[n*n]; 	/* store initial matrix */
	double w[n];		/* store eigenvalues */
	int matz = 1;		/* return both eigenvalues as well as eigenvectors */
	double x[n*n]; 	/* store eigenvectors */

	for(unsigned int i=0; i<n; i++) {
		for(unsigned int j=0; j<n; j++) {
			a[i*n+j] = A[i][j];
		}
	}

	unsigned int ierr = 0;

	ierr = rs ( n, a, w, matz, x );

	V.assign(n,n,0.0);
	lambda.resize(n);
	for(unsigned int i=0; i<n; i++) {
		lambda[i] = w[i];
		for(unsigned int j=0; j<n; j++) {
			V[j][i] = x[i*n+j];
		}
	}
}
/*
 Calculate the eigenvalues, betai, and eigenvectors, u, for
 the current Modularity matrix Bgi.
 */
void calculateEigenVectors() {

    int Ng = Bgi.ncols();

    if(u.ncols() != Ng) {
        u.resize(Ng,Ng);
        betai.resize(Ng);
    }

    u.resize(Ng,Ng);
    betai.resize(Ng);

    Symmeig h(Bgi, true);

    for(int i=0; i<Ng; i++) {
        betai[i] = h.d[i];
        for(int j=0; j<Ng; j++) {
            u[j][i] = h.z[j][i];
        }
    }


}
/*
 Utility method used by the Spectral method fine-tune an initial
 given community split.
 */
void modifySplit( double tol, int countmax ) {

    double qmax  = 0;
    double qold  = 0;
    int count    = 0;
    int Ng       = si.size();

    visited.resize(Ng);

    VecDoub Gsi(Ng);
    MatDoub GSI(Ng,2);

    for(int i=0; i<Ng; i++) {
        Gsi[i]    = si[i];
        GSI[i][0] = SI[i][0];
        GSI[i][1] = SI[i][1];
    }

    maxModularity( qmax );

    while( count < countmax ) {

        if( qmax > qold ) {
            for(int i=0; i<Ng; i++) {
                Gsi[i]    = si[i];
                GSI[i][0] = SI[i][0];
                GSI[i][1] = SI[i][1];
            }
        }

        qold = qmax;
        qmax = 0.0;

        maxModularity(qmax);

        count++;

    }

    for(int i=0; i<Ng; i++) {
        si[i]    = Gsi[i];
        SI[i][0] = GSI[i][0];
        SI[i][1] = GSI[i][1];
    }

}
/*
 Update the index vectors, si and SI, for each node in the
 current split such that:

 si(i) =  1 if eigenvector_max(i) > 0
       = -1 if eigenvector_max(i) < 0

 SI(i,0) = 1
 SI(i,1) = 0 if eigenvector_max(i) > 0
         = 0
         = 1 if eigenvector_max(i) < 0
 */
void maximiseIndexVectors( int ind ) {

    int Ng = u.ncols();

    si.resize(Ng);

    SI.resize(Ng,2);

    for(int i=0; i<Ng; i++) {

        if(u[i][ind] < 0) {
            si[i]    = -1;
            SI[i][0] =  0;
            SI[i][1] =  1;
        } else {
            si[i]    =  1;
            SI[i][0] =  1;
            SI[i][1] =  0;
        }

    }

}
/*
 Calculate the split of nodes belonging to the last group of nodes
 with negative eigenvector values.
 */
void splitN(MatDoub Bg, VecInt keys, int dummy, double tol) {

    cout << "> In splitN method... " << endl;

    int N = Bg.nrows();
    MatDoub Bgii(N,N);
    MatDoub Bgiii(N,N);
    VecInt  keysi_n (N);

    //--- Starting from the group Modularity matrix Bg,
    //--- resize matrices: Bgi, keysi_p, keysi_n, u and betai.
    Bgiii  = Bg;
    int Ng = 0;

    for(int i=0; i<keys.size(); i++) {
        if(keys[i] != dummy) {
            Ng++;
        } else {
            for(int k=0; k<Bgiii.nrows(); k++) {
                Bgiii[i][k] = dummy;
                Bgiii[k][i] = dummy;
            }
        }
    }

    keysi_n.resize(Ng);
    VecInt keysi_p(Ng);

    int k=0;
    for(int i=0; i<keys.size(); i++) {
        if(keys[i] != dummy)
            keysi_n[k++] = keys[i];
    }

    Bgii.resize(Ng,Ng);
    removeMatrixRow(Bgiii,Bgii);

    Bgi.resize(Bgii.nrows(),Bgii.nrows());

    //--- Calculate the Modularity matrix Bgi for the new node group
    calculateB(Bgii, Bgi);

    u.resize(Ng,Ng);
    betai.resize(Ng);

    //--- Calculate eigenvectors, and values, from Bgi...
    calculateEigenVectors();

    int ind = 0;
    findLeadingEigenVectors(ind);

    //--- Check that maximum eigenvalue is greater than the tolerance.
    cout << "> max EigenValue is " << betai[ind] << " with ind " << ind << endl;
    if(betai[ind] > tol ) {

        //--- set up the index vectors, si and SI, for the initial split
        maximiseIndexVectors(ind);

        double deltaQ_old = 0.0;
        double deltaQ_new = 0.0;

        int cp = 0;
        int cn = 0;

        //--- Calculate the Spectral Modularity
        deltaModularity(deltaQ_old);
        cout << "> Spectral Q: " << deltaQ_old << endl;

        double diff = fabs(deltaQ_old);
        int count   = 0;

        //--- Fine tuning stage to maximum deltaModularity for the initial split
        while( diff > tol ) {

            modifySplit( tol, Ng );

            deltaModularity(deltaQ_new);
            cout << "> Modified Q: " << deltaQ_new << endl;

            diff = fabs( deltaQ_new - deltaQ_old );

            deltaQ_old = deltaQ_new;

        }

        //--- Keep recorded of maximum fine-tuned Modularity value.
        specQ += deltaQ_old;
        for(int i=0; i<Ng; i++) {
            si[i] = si[i];
            if(si[i] > 0) cp++;
            else          cn++;
        }

        if(cp < 1 || cn < 1) {
            cout << "> Stop splitting. " << endl;
            return;
        }

        int Ncomn = maxCommunity() + 1;
        int Ncomp = Ncomn + 1;

        cout << "> node list " << endl;
        for(int i=0; i<keysi_n.size(); i++) {
            if( si[i] < 0) {
                keysi_n[i] = keysi_n[i];
                keysi_p[i] = dummy;
                n[(int)keysi_n[i]].c = Ncomn;
                cout << "> Node: " << keysi_n[i] << " c = " << n[(int)keysi_n[i]].c << endl;
            } else {
                keysi_p[i] = keysi_n[i];
                keysi_n[i] = dummy;
                cout << "> Node: " << keysi_p[i] << " c = " << n[(int)keysi_p[i]].c << endl;
            }
        }

        //--- Recursively split the group of positive eigenvector nodes
        splitP(Bgii, keysi_p, dummy, tol);

        //--- Recursively split the group of negative eigenvector nodes
        splitN(Bgii, keysi_n, dummy, tol);

    } else {
        cout << "> Stop splitting. " << endl;
        return ;
    }


}
//--- MAIN PROGRAM
//-------------------------------------------------------------------------------------
int main(int argc, char * argv[]) {

    int seed;
    int a_type;
    int w_type;
    string title;
    string if_weighted;
    string if_help;
    const char *file_network;
    const char *file_names;

    if ( argc != 5 ) {
        printHelpMessage( argv[0] );
    }

    if_help = argv[1];
    if( if_help.compare("-h") == 0 || if_help.compare("-help") == 0 ) {
        printHelpMessage( argv[0] );
    }

    seed = atoi(argv[1]);
    cout << "> seed is " << seed << endl;

    //--- Initialize random seed:
    _rand.setSeed(seed);

    a_type = atoi(argv[2]);

    if( a_type < 1 || a_type > 3 ) {
        cout << "argument 2: the type of algorithm to run needs to be either (1,2,3): " << endl;
        cout << "          : 1 = Geodesic edge Betweenness" << endl;
        cout << "          : 2 = Random edge Betweenness"   << endl;
        cout << "          : 3 = Spectral Betweenness"      << endl;
        exit(1);
    }

    switch(a_type) {

    case 1:
        cout << "> Using Geodesic edge Betweenness." << endl;
        title = "Geodesic edge Betweenness.";
        break;

    case 2:
        cout << "> Using Random edge Betweenness." << endl;
        title = "RandomWalk edge Betweenness.";
        break;

    case 3:
        cout << "> Using Spectral Betweenness." << endl;
        title = "Spectral Betweenness.";
        break;

    default:
        break;

    }

    if_weighted = argv[3];

    if( if_weighted.compare("w") == 0 ) {
        w_type = 3;
        cout << "> Using a weighted network " << endl;
    } else {
        if( if_weighted.compare("nw") == 0 ) {
            w_type = 2;
            cout << "> Using a non-weighted network " << endl;
        } else {
            cout << "argument 3: specify if network file is weighted or not: " << endl;
            cout << "          : w  = Using a weighted network file " << endl;
            cout << "          : nw = Using a non-weighted network file " << endl;
            exit(1);
        }
    }

    file_network = argv[4];

    //--- Default values for parameters which may be modified from the commandline
    ihelper = Helper();
    reader.readFile(file_network, w_type);
    Gn      = reader.getNodeSet();
    Gelist  = reader.getEdgeSet();

    vector<int> key_listi;
    vector<int> key_listj;
    vector<int> key_listk;

    cout << "> The Global node list..." << endl;
    for(int i=1; i<Gn.size(); i++) {
        key_listi.push_back(Gn[i].ID);
        key_listj.push_back(Gn[i].ID);
        key_listk.push_back(-1);
        Gn[i].print();
        Gn[i].printEdges();
    }

    //--- To use getSubSample, comment following two lines, and
    //--- uncomment getSubSample(key_listj).
    n     = Gn;
    elist = Gelist;
    //getSubSample(key_listj);

    //cout << "The sub-node list ... " << endl;
    //for(int i=1; i<n.size(); i++){
    //n[i].print();
    //n[i].printEdges();
    //}

    cout << "> The Global edge list..." << endl;
    for(int i=0; i<elist.size(); i++) {
        elist[i].print();
    }

    forcytoscape = new fstream("OUT/communities_newman.txt",ios_base::out);
    (*forcytoscape) << "communities" << endl;

    removededges = new fstream("OUT/removededges.txt",ios_base::out);
    (*removededges) << "Removed Edges" << endl;
    (*removededges) << "so \t IDso \t si \t IDsi \t we \t Globalweight \t key" << endl;

    totallist = ihelper.cloneEdgeList(elist);

    com_max      = 0;
    specQ        = 0.0;
    double Q     = 0.0;
    double Q_SD     = 0.0;
    double Q_old = 0.0;
    double Q_SD_old = 0.0;

    int loop       = elist.size();
    int E          = loop;
    double Q_max   = 0.0;
    double Q_limit = 1.0;
    bool stopping  = false;

    int N = n.size()-1;

    R.resize(N,N);
    Ri.resize(N,N);
    A.resize(N,N);
    Ai.resize(N,N);
    Bi.resize(N,N);
    C.resize(N);

    S.resize(N,1);
    V.resize(N,1);
    T.resize(N,N);
    Ti.resize(N,N);
    Rc.resize((N-1),(N-1));
    Vi.resize(C.size(),1);

    B.resize(N,N);
    Bm.resize(N,N);
    Bgi.resize(N,N);

    keys_p.resize(N);
    keys_n.resize(N);

    u.resize(N,N);  //eigenvectors
    betai.resize(N);//eigenvalues

    SI.resize(N,2);
    si.resize(N);
    visited.resize(N);

    setupMatrices();

    cout << "> Running " << title.c_str() << endl;

    cstart = clock();

    if( a_type == 3 ) {
        //--- Calculate betweenness using the Spectral algorithm
        calculateSpectralModularity();
    } else {

        while( loop !=0 && !stopping ) {

            int old_max_com = com_max;

            //--- Calculate betweenness using Geodesic or RandomWalk algorithms
            if( a_type == 1 )
                calculateEdgeBetweennessGeodesic();
            else
                calculateEdgeBetweennessRandom();

            //--- Calculate the Modularity
            Q_old = Q;
            Q_SD_old = Q_SD;
            Q     = 0.0;
            Q_SD   = 0.0;

            Modularity(Q, Q_SD);

            //--- Store networks state if Modularity has increased during this iteraction
            if(com_max > old_max_com) {
                vec_mod.push_back(Q);
                vec_mod_err.push_back(Q_SD);
                vec_com_max.push_back(com_max);
                vec_nodes.push_back(storeNodes());
            }


            //--- Record the maximum Modularity value
            if( Q > Q_max ) {
                Q_max = Q;
            } else {
                if( Q_max > 0.0 && (Q_max - Q)/Q_max > Q_limit ) stopping = true;
            }


            //--- Find edge with maximum edge betweenness score and remove
            edge _max;
            _max = totallist[1].Clone();
            for(int i=1; i<totallist.size(); i++) {

                if( totallist[i].removed == false ) {

                    if(totallist[i].we >= _max.we) {

                        if(totallist[i].we > _max.we)
                            _max = totallist[i];
                        else {
                            int rdm = rand()%2;
                            if(rdm == 1) _max = totallist[i];
                        }
                    }
                }
                totallist[i].we = 0;
            }

            //--- Record the removed edges.
            _max.print( removededges );

            n[elist[_max.key-1].so].removeEdge(_max.key);
            n[elist[_max.key-1].si].removeEdge(_max.key);
            n[elist[_max.key-1].so].setDegree( (n[elist[_max.key-1].so].getDegree() - 1) );
            n[elist[_max.key-1].si].setDegree( (n[elist[_max.key-1].si].getDegree() - 1) );
            totallist[_max.key].removed = true;
            elist[_max.key-1].removed   = true;
            --loop;

            //--- Calculate the remaining processor time
            DrawProgressBar( 20, ((double)E - (double)loop)/(double)E );

        }
    }

    //--- Recored the CPU-time taken
    cend = clock();
    double cpu_time_used = ((double) (cend - cstart)) / CLOCKS_PER_SEC;
    cout << "" << endl;
    cout << "> cputime: " << cpu_time_used << " seconds " << endl;
    cout << "> Network (nodes): " << N << " (edges): " << E << endl;

    if( a_type != 3 ) {

        //--- Print all stored Modularity values
        modularityscore = new fstream("OUT/modularityscore.txt",ios_base::out);
        (*modularityscore) << title.c_str() << endl;
        for(int i=0; i<vec_mod.size(); i++) {
            (*modularityscore) << vec_mod[i] << " " << vec_mod_err[i] << " " << vec_com_max[i] << endl;
        }
        modularityscore->close();

        int ind   = findMax(vec_mod);
        int com   = 1;
        int _size = 0;
        int c_max = com_max;

        //--- Print node communities for maximum Modularity value, for Geodesic or RandomWalk runs
        communityout = new fstream("OUT/communityout.txt",ios_base::out);
        (*communityout) << "Max Q: " << vec_mod[ind] << " +- " << vec_mod_err[ind] << endl;
        (*communityout) << "cputime: " << cpu_time_used << " seconds " << endl;
        (*communityout) << "Network (nodes): " << N << " (edges): " << E << endl;

        while(com<(c_max+1)) {
            _size = 0;
            for(int i=0; i<vec_nodes[ind].size(); i++) {
                if(vec_nodes[ind][i].c == com ) {
                    (*communityout) << vec_nodes[ind][i].ID << "\t" << vec_nodes[ind][i].c << endl;
                    //vec_nodes[ind][i].print( communityout );
                    _size++;
                }
            }
            if(_size != 0)
                (*communityout) << "community: " << com << " size: " << _size << endl;
            com++;
        }

        for(int i=0; i<vec_nodes[ind].size(); i++) {
            for(int j=0; j<key_listi.size(); j++) {
                if(vec_nodes[ind][i].ID == key_listi[j]) {
                    key_listk[j] = vec_nodes[ind][i].c;
                    break;
                }
            }
        }

        //--- Print node communities for maximum Modularity for the consensus matrix
        consensusout = new fstream("OUT/consensusout.txt",ios_base::out);
        (*consensusout) << "key list" << endl;
        for(int i=0; i<key_listi.size(); i++) {
            if(key_listk[i] == -1 && key_listj[i] != -1)
                key_listj[i] = -1;
            (*consensusout) << key_listi[i] << " " << key_listj[i] << " " << key_listk[i] << endl;
            //(*consensusout) << key_listi[i] << " = " << key_listk[i] << endl;
            (*forcytoscape) << key_listi[i] << " = " << key_listk[i] << endl;
            cout << key_listi[i] << " " << key_listj[i] << " " << key_listk[i] << endl;
        }
    } else {

        int com   = 1;
        int _size = 0;
        int c_max = maxCommunity();

        //--- Store node communities for maximum Modularity for the Spectral Modularity run
        communityout = new fstream("OUT/communityout.txt",ios_base::out);
        (*communityout) << "communityout" << endl;
        (*communityout) << "Max Q: " << specQ << endl;
        (*communityout) << "cputime: " << cpu_time_used << " seconds " << endl;
        (*communityout) << "Network (nodes): " << N << " (edges): " << E << endl;
        while(com<(c_max+1)) {
            _size = 0;
            for(int i=0; i<n.size(); i++) {
                if(n[i].c == com ) {
                    n[i].print( communityout );
                    _size++;
                }
            }
            if(_size != 0)
                (*communityout) << "community: " << com << " size: " << _size << endl;
            com++;
        }

        for(int i=1; i<n.size(); i++) {
            for(int j=0; j<key_listi.size(); j++) {
                if(n[i].ID == key_listi[j]) {
                    key_listk[j] = n[i].c;
                    break;
                }
            }
        }

        //--- Print node communities for maximum Modularity the consensus matrix
        consensusout = new fstream("OUT/consensusout.txt",ios_base::out);
        (*consensusout) << "key list" << endl;
        for(int i=0; i<key_listi.size(); i++) {
            if(key_listk[i] == -1 && key_listj[i] != -1)
                key_listj[i] = -1;
            (*consensusout) << key_listi[i] << " " << key_listj[i] << " " << key_listk[i] << endl;
            //(*consensusout) << key_listi[i] << " = " << key_listk[i] << endl;
            (*forcytoscape) << key_listi[i] << " = " << key_listk[i] << endl;
            cout << key_listi[i] << " " << key_listj[i] << " " << key_listk[i] << endl;
        }


    }


    //--- Remove data structures
    communityout->close();
    forcytoscape->close();
    vec_mod.clear();
    vec_mod_err.clear();
    vec_nodes.clear();

    exit(1);

}
Ejemplo n.º 7
0
 solver_wave(VecDoub ppara1,Doub ssavedt,VecDoub dDI,VecDoub eexcitimes,VecDoub iinf, VecDoub ssup):para1(ppara1),savedt(ssavedt),DI(dDI),excitimes(eexcitimes),inf(iinf),sup(ssup),para(NDIM,0.0),u(NX,0.0),v(NX,0.0),w(NX,0.0),d(NX,0.0),xfi(NX,0.0),xso(NX,0.0),xsi(NX,0.0),nexcs(NEXCITE,0),v70(100),v30(100)
 {
     //tvmm=10;
     uo=0.0;
     um=1.0;
     una=0.23;
     //t=0.0;
     
     savepoints=int(TOTALTIME/savedt);
     for (int j=0; j<NX; j++) {
         u[j]=0;
         v[j]=1;
         w[j]=1;
         d[j]=0;
     }
     for (int i=0; i<NDIM; i++) {
         para[i]=exp(para1[i])/(exp(para1[i])+1);
         para[i]=inf[i]+para[i]*(sup[i]-inf[i]);
         //printf("para[%i] is %f\n",i,para[i]);
     }
     numt=int(TOTALTIME/DT);
     
     uc=para[0]; //threshold
     uv=para[1]; //fast gate threshold, determines whethere tvm or tvmm is active (chaos 8)
     uw=para[2]; //slow gate threshold
     ud=para[3]; //threshold
     tvm=para[4]; //controls minimum diastolic interval where CV occurs (chaos 8)
     tvp=para[5]; //fast gate closing time
     twm=para[6]; //slow gate opening time (changes APD shape?)
     twp=para[7]; //slow gate closing time (shifts APD up/down?)
     tsp=para[8]; //d-gate variables
     tsm=para[9];
     ucsi=para[10];
     xk=para[11]; //typically around 10
     td=para[12]; //fast current time variable, determines max CV
     to=para[13]; //ungated time constant
     tsoa=para[14]; //curve shape/APD, ungated time, adjusts DI
     tsob=para[15]; //ungated time. Easily adjusts DI, changes APD
     uso=para[16];
     xtso=para[17];
     tsi=para[18]; //slow current time variable, max APD
     D=para[19]; //related to density, mostly changes CV, but can effect everything
     tvmm=para[20]; //controls the steepness of the CV curve (chaos 8)
     //um=para[21]; //related to maximum AP, set to 1
     //una=para[21]; //threshold. Um,una have little effect on APD
     
     for (int i=0; i<NEXCITE; i++) {
         nexcs[i]=int(excitimes[i]/DT);
         //printf("%f, %f \n",nexcs[i]*DT,excitimes[i]);
     }
     
     //voltage.resize(savepoints, NX);
     v70.resize(savepoints);
     v30.resize(savepoints);
     //for (int i=0; i<savepoints; i++)
     //for (int j=0; j<NX; j++)
     //{
     //   voltage[i][j]=0.0;
     //}
     success=true;
 }