void pAOSOAutostepGradTree::get_is_leaf( VecInt& is_leaf ) { is_leaf.clear(); is_leaf.resize(nodes_.size()); std::list<pAOSOAutostepGradNode>::iterator it = nodes_.begin(); for (int i = 0; it!=nodes_.end(); ++it, ++i) { if (it->left_==0 && it->right_==0) is_leaf[i] = 1; else is_leaf[i] = 0; } // for i }
std::string VAL::EndGameWorldStateFormatter::asString(const VecInt& gameHistory, WorldState & ws, const VecVecVecKey& kb) { ostringstream os; int scoreIndex = proc->getFunctionId("score"); int cardCount = proc->typeCardinalities[proc->typeNameIds["card"]]; // int slotCount = proc->typeCardinalities[proc->typeNameIds["slot"]]; VecInt cardRow(cardCount, -1); NumScalar p1Score = ws.getFluentValue(scoreIndex, 1); NumScalar p2Score = ws.getFluentValue(scoreIndex, 2); os << "Score 1: " << p1Score << " Score 2: " << p2Score << "\n"; //assert((unsigned)cardCount <= gameHistory.size()); if ((unsigned) cardCount < gameHistory.size()) { for (unsigned i = 1; i <= (int) cardRow.size(); i++) { int index = gameHistory[i]; VecInt args = proc->operatorIndexToVector(index); // os << proc->getOperatorName(args[0]) << " " << proc->asString(args) << "\n"; cardRow[i - 1] = args[3] + 1; // c0=1 c1=2, etc. } } os << proc->asString(cardRow, LIST) << "\n"; return os.str(); }
void addMatrixRows(MatDoub U, int c, MatDoub &Ui) { int j=0; for(int i=0; i<C.size(); i++) { if(C[i] == c) Ui[i][0] = U[j++][0]; else Ui[i][0] = 0; } }
int GoalVisitController::encodeFact(const proposition* p) { const parameter_symbol_list& vsl = *p->getArgs(); VecInt indexes; for (parameter_symbol_list::const_iterator itr = vsl.begin(); itr != vsl.end(); itr++) { const string& arg = (*itr)->getName(); ostringstream os; StringToInt::const_iterator index = params.find(arg); if (index == params.end()) { index = objectTbl.find(arg); //labels.push_back((*itr)->getName()); //} else { assert (index != objectTbl.end()); // reference to a constant in action def that hasn't been defined } os << index->second; indexes.push_back(index->second); labels.push_back(os.str()); } int factNum = getIndex(this->offsets, mults, p->getHead()->getName(), indexes); cout << "(" << factNum << ")"; return factNum; }
int GoalVisitController::getIndex(const StringToBounds& offsets, const PredicateMultTable& multTbl, const string& name, const VecInt& args) { const PredicateMultTable::const_iterator itr = multTbl.find(name); assert (itr != multTbl.end()); const VecInt& mults = itr->second; const StringToBounds::const_iterator bitr = offsets.find(name); assert (bitr != offsets.end()); const Bounds& bounds = bitr->second; assert (args.size() == mults.size()); int result = bounds.lower; for (unsigned i = 0; i < mults.size(); i++) { result += mults[i]*args[i]; } return result; }
long makeDivisible(VecInt& vec, long p2e, long p2r, long q, double alpha) { assert(((p2e % p2r == 0) && (q % p2e == 1)) || ((p2r % p2e == 0) && (q % p2r == 1))); long maxU =0; ZZ maxZ; for (long i=0; i<vec.length(); i++) { ZZ z, z2; conv(z, vec[i]); long u=0, v=0; long zMod1=0, zMod2=0; if (p2r < p2e && alpha>0) { zMod1 = rem(z,p2r); if (zMod1 > p2r/2) zMod1 -= p2r; // map to the symmetric interval // make z divisible by p^r by adding a multiple of q z2 = z - to_ZZ(zMod1)*q; zMod2 = rem(z2,p2e); // z mod p^e, still divisible by p^r if (zMod2 > p2e/2) zMod2 -= p2e; // map to the symmetric interval zMod2 /= -p2r; // now z+ p^r*zMod2=0 (mod p^e) and |zMod2|<=p^{r(e-1)}/2 u = ceil(alpha * zMod2); v = zMod2 - u; // = floor((1-alpha) * zMod2) z = z2 + u*p2r + to_ZZ(q)*v*p2r; } else { // r >= e or alpha==0, use only mulitples of q zMod1 = rem(z,p2e); if (zMod1 > p2e/2) zMod1 -= p2e; // map to the symmetric interval z -= to_ZZ(zMod1) * q; } if (abs(u) > maxU) maxU = abs(u); if (abs(z) > maxZ) maxZ = abs(z); if (rem(z,p2e) != 0) { // sanity check cerr << "**error: original z["<<i<<"]=" << vec[i] << std::dec << ", p^r="<<p2r << ", p^e="<<p2e << endl; cerr << "z' = z - "<<zMod1<<"*q = "<< z2<<endl; cerr << "z''=z' +" <<u<<"*p^r +"<<v<<"*p^r*q = "<<z<<endl; exit(1); } conv(vec[i], z); // convert back to native format } return maxU; }
FunctionKey NewConditionController::getGroundedProp(proposition* p, const VecInt& args) { //FunctionKey result(p->getHead()->getName(),VecInt(p->getArgs()->size())); //const parameter_symbol_list& psl = *p->getArgs(); const VecInt& argMap = p->argMap; unsigned argsize = p->getArgs()->size(); FunctionKey intArgs(argsize + 1); // = result.args; intArgs[0] = p->getHeadId(); //cout << "GettingPredHeadId: " << intArgs[0] << "\n"; for (unsigned i = 0; i < argsize; i++) { if (argMap[i] >= 0) { assert(argMap[i] < (int)args.size()); intArgs[i + 1] = args[argMap[i]]; } else if (argMap[i] == UVAL) { intArgs[i + 1] = UVAL; // Unknown val } else { intArgs[i + 1] = -1 - argMap[i]; } } return intArgs; }
/* Utility method used by RandomWalk algorithm to resize the Graph Laplacian for each community, com, within the network. */ void getSubMatrix(int com, vector<node> &Nodes) { int dummy = -1000; int rows = 0; Rh.resize(R.nrows(), R.nrows()); Rh = R; //--- NR style for( int i=0; i< C.size(); i++) { if( C[i] == com ) Nodes.push_back(node(rows++,0.0,0.0)); else { for( int k=0; k<Rh.nrows(); k++) { Rh[i][k] = dummy; Rh[k][i] = dummy; } } } datain = Rh.getMatrixArray(); data [Rh.nrows()*Rh.nrows()]; int ind = 0; for(int i=0; i < Rh.nrows()*Rh.ncols(); i++) { double ele = datain[i]; if(ele != dummy) data[ind++] = ele; } Ri.resize(rows,rows); Ri = MatDoub( rows, rows, data ); }
std::string RackoWorldStateFormatter::asString(const VecInt & gameHistory, WorldState & ws, const VecVecVecKey & kb) { ostringstream os; // Number of slot objects is (# slots per player)*2 + 1. (Extra 1 is "dealer"). // Integer division by two gives # slots per player. // unsigned slotCount = (unsigned) (proc->typeCardinalities[proc->typeNameIds["slot"]] / 2); unsigned slotCount = proc->itemCount("slot"); unsigned slotsPerPlayer = (slotCount - 1) / 2; // Subtract 1 for dealer; half of remaining are opponent's slots unsigned dealerSlotId = slotsPerPlayer; // Because slots are named d1 ... dn, dealer, u1, ... un; so dealer is in middle unsigned cardCount = proc->itemCount("card"); // os << "Racko World with " << slotCount << " slots and " << cardCount << " cards"; // os << " head id for 'at': " << proc->predicateId("at"); int atIndex = proc->predicateId("at"); int topIndex = proc->predicateId("top"); VecInt args(2, 0); int whoseTurn = ws.getWhoseTurn(); int minSlot = (whoseTurn == 2) ? 0 : dealerSlotId + 1; int oppMinSlot = (whoseTurn == 1) ? 0 : dealerSlotId + 1; os << "History\n"; for (unsigned m = slotCount + 1; m < gameHistory.size(); m++) { string oName; VecInt oArgs; proc->decodeOperator(gameHistory[m], oName, oArgs); if (oName == "swap-top") { if (oArgs[0] != whoseTurn) { os << "(Opponent) "; } int slotArg = getSlotArg(oArgs[3], slotsPerPlayer); os << "Swapped " << (oArgs[2] + 1) << " for " << (oArgs[4] + 1) << " into " << (char) (('A' + (slotArg))) << "\n"; } else if (oName == "swap-drawn") { if (oArgs[0] != whoseTurn) { os << "(Opponent) "; } int slotArg = getSlotArg(oArgs[2], slotsPerPlayer); os << "Swapped " << (oArgs[3] + 1) << " out of " << (char) (('A' + (slotArg))) << " for drawn "; if (oArgs[0] == whoseTurn) { os << (oArgs[4] + 1) << "\n"; } else { os << "card\n"; } } else if (oName == "pass") { if (oArgs[0] != whoseTurn) { os << "(Opponent) "; } os << "Discarded " << (oArgs[2] + 1) << "\n"; } else { // os << setw(3) << m << " " << oName << "\n"; } } os << "\n\n"; switch (whoseTurn) { case 0: // chance os << "Chance: "; args[1] = slotCount; // This will be the slot 'dealer' for (int c = 0; c < (int) (((((cardCount))))); c++) { args[0] = c; int index = ws.getIndex(args, atIndex); if (ws.getTruthValue(index) == KNOWN_TRUE) { os << " " << std::setw(3) << (c + 1); //" fact: " << proc->getFact(index); } } os << "\n"; break; case 1: case 2: os << "Current Player " << whoseTurn << "\n"; for (int s = minSlot; s < (int) ((((((minSlot + slotsPerPlayer)))))); s++) { os << " " << (char) (((((('A' + s - minSlot)))))) << ": "; //" fact: " << proc->getFact(index); args[1] = s; for (int c = 0; c < (int) (((((cardCount))))); c++) { args[0] = c; int index = ws.getIndex(args, atIndex); if (ws.getTruthValue(index) == KNOWN_TRUE) { os << std::setw(3) << (c + 1); //" fact: " << proc->getFact(index); } } os << "\n"; } if (false) for (int s = oppMinSlot; s < (int) ((((((oppMinSlot + slotCount)))))); s++) { os << " " << (char) (((((('A' + s - oppMinSlot)))))) << ": "; //" fact: " << proc->getFact(index); args[1] = s; for (int c = 0; c < (int) (((((cardCount))))); c++) { args[0] = c; int index = ws.getIndex(args, atIndex); if (ws.getTruthValue(index) == KNOWN_TRUE) { os << std::setw(3) << (c + 1); //" fact: " << proc->getFact(index); } } os << "\n"; } os << "\n"; break; } for (unsigned c = 0; c < cardCount; c++) { if (ws.getTruthValue(topIndex, c) == KNOWN_TRUE) { os << "Top: " << (c + 1) << "\n"; } } int drawnIndex = proc->predHeadTbl["drawn"]; for (unsigned c = 0; c < cardCount; c++) { for (unsigned ithDraw = 0; ithDraw < cardCount; ithDraw++) { if (ws.getTruthValue(drawnIndex, c, ithDraw) == KNOWN_TRUE) { os << "Drawn: " << (c + 1) << "\n"; } } } return os.str(); }
std::string VAL::GopsWorldStateFormatter::asString(const VecInt & gameHistory, WorldState & ws, const VecVecVecKey & kb) { ostringstream os; int scoreIndex = proc->getFunctionId("score"); string oName; VecInt oArgs; int slotCount = proc->typeCardinalities[proc->typeNameIds["slot"]]; unsigned biddingRoundCount = (slotCount - 1) / 3; // Subtract 1 for dealer, divide by 3 because for every bidding round, there // is the card to bid on plus one card per player to bid with VecVecInt startingHands(3); VecVecInt results(3); for (unsigned i = 0; i < 3; i++) { startingHands[i] = VecInt(biddingRoundCount, 0); results[i] = VecInt(biddingRoundCount, 0); } int biddingRoundId = 0; int currentBiddable = -1; for (unsigned i = 1; i < gameHistory.size(); i++) { proc->decodeOperator(gameHistory[i], oName, oArgs, true); int cardId = oArgs[0] + 1; if (oName == "deal") { //os << i << " Deal " << (oArgs[0] + 1) << "\n"; if (i <= biddingRoundCount) { startingHands[0][i - 1] = cardId; } else { int pid = 2 - ((i - biddingRoundCount - 1) % 2); startingHands[pid][(i - biddingRoundCount - 1) / 2] = cardId; } } else if (oName == "announce") { currentBiddable = cardId; } else if (oName == "bid1") { results[1][biddingRoundId] = cardId; } else if (oName == "bid2") { results[2][biddingRoundId] = cardId; } else if (oName == "determine") { int p1Bid = oArgs[0] + 1; int p2Bid = oArgs[1] + 1; results[0][biddingRoundId] = (p2Bid > p1Bid) + 1; // 1 if p1 won it; 2 if p2 won it biddingRoundId++; } } std::string labels[] = { "won by", "p1 bid", "p2 bid" }; // for (unsigned i = 0; i < 3; i++) { // if (i > 0 && i != ws.getWhoseTurn()) continue; // Don't print the other guys cards // os << labels[i] << " "; // for (int j = 0; j < biddingRoundCount; j++) { // os << startingHands[i][j] << " "; // } // os << "\n"; // } os << "\n"; os << "card: "; for (int i = 0; i < biddingRoundId; i++) { os << setw(2) << startingHands[0][i] << " "; } os << "\n"; //labels[0] = "W "; for (unsigned i = 0; i < 3; i++) { os << labels[i] << ": "; for (int j = 0; j < biddingRoundId; j++) { os << setw(2) << results[i][j] << " "; } os << "\n"; } os << "Currently bidding on: " << currentBiddable << "\n"; NumScalar p1Score = ws.getFluentValue(scoreIndex, 1); NumScalar p2Score = ws.getFluentValue(scoreIndex, 2); switch (ws.getWhoseTurn()) { case 0: os << "Player 1 score: " << setw(2) << p1Score << "\nPlayer 2 score: " << setw(2) << p2Score << "\n"; break; case 1: os << "My score: " << setw(2) << p1Score << "\nOpponent score: " << setw(2) << p2Score << "\n"; break; case 2: os << "Opponent Score: " << setw(2) << p1Score << "\nMy score: " << setw(2) << p2Score << "\n"; break; } return os.str(); }
int main () { MLData tr; //tr.X = Mat(6,2,CV_32FC1,X1); //tr.Y = Mat(6,1,CV_32FC1,Y1); tr.X = Mat(6,2,CV_32FC1,X2); tr.Y = Mat(6,1,CV_32FC1,Y2); tr.var_type.resize(2); tr.var_type[0] = VAR_NUM; tr.var_type[1] = VAR_NUM; tr.problem_type = PROBLEM_CLS; tr.preprocess(); // AOTO Boost pVbExtSamp11VTLogitBoost ab; ab.param_.J = 4; ab.param_.T = 10; ab.param_.v = 0.1; ab.param_.ns = 1; ab.param_.ratio_si_ = 1.0; ab.param_.ratio_fi_ = 0.8; ab.param_.ratio_ci_ = 0.8; ab.train(&tr); MLData te; te.X = tr.X; ab.predict(&te, 2); cout << "predictY = " << te.Y << endl; MLData te2; te2.X = tr.X; ab.predict(&te2, 6); cout << "predictY = " << te2.Y << endl; int TT = -1; TT = ab.get_num_iter(); cout << endl; cout << "TT = " << TT << endl << endl; //cout << "train loss = " << ab.get_train_loss() << endl; MLData te3; te3.X = tr.X; ab.predict(&te3); cout << "predictY = " << te3.Y << endl; VecIdx nr_wts, nr_wtc; ab.get_nr(nr_wts,nr_wtc); for (int i = 0; i < TT; ++i) { VecInt ind; ab.get_cc(i, ind); cout << "node_cc.size() = " << ind.size() << "\n"; } for (int i = 0; i < TT; ++i) { VecInt ind; ab.get_sc(i, ind); cout << "node_sc.size() = " << ind.size() << "\n"; } return 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); }
/* Utility method used by the RandomWalk algorithm to invert the Graph Laplacian and accummulate the random-path contributions from each source-sink node pair, in accordance with [2] (see method declarations above). */ void calculateRandomWalk(int c, vector<node> Nodes) { queue<node> termNodes; for(int i=0; i<Nodes.size(); i++) termNodes.push(Nodes[i]); int N = Nodes.size(); S.resize(N,1); V.resize(N,1); T.resize(N,N); Rc.resize((N-1),(N-1)); Vi.resize(C.size(),1); //--- Remove arbitrary termination ('sink') state '0'. removeMatrixRow(0,Rc); //--- Invert Matrix. LUdcmp lu( Rc ); Ti.resize(Rc.nrows(),Rc.nrows()); lu.inverse( Ti ); for(int i=0; i< T.nrows(); i++) { for(int j=0; j< T.nrows(); j++) { T[i][j] = 0; } } //--- Add back arbitrary termination ('sink') state '0'. addMatrixRow(Ti,0,T); while ( !termNodes.empty() ) { node termNode = termNodes.front(); termNodes.pop(); for(int t=0; t< Nodes.size(); t++) { //--- Take the next start ('source') state. node startNode = Nodes[t]; if( startNode.k != termNode.k ) { for(int i=0; i<S.nrows(); i++) { S[i][0] = 0; V[i][0] = 0; Vi[i][0] = 0; } S[startNode.k][0] = 1; S[termNode.k][0] = -1; //--- V = T * S for(int i=0; i<T.nrows(); i++) { double sum = 0.0; for(int j=0; j<T.nrows(); j++) { sum += T[i][j] * S[j][0]; } V[i][0] = sum; } addMatrixRows(V, c, Vi); //--- Edge Betweenness, i.e. //--- the currents (potential differences) alone each edge! for(int i=0; i<elist.size(); i++) { if( !elist[i].removed ) { int Ni = elist[i].so-1; int Nj = elist[i].si-1; totallist[i+1].we += fabs(Vi[Ni][0] - Vi[Nj][0]); } }//elist }//Nodes }//startNodes } }
void mergeSorted(const VecInt& a, const VecInt& b, VecInt& out) { VecInt::const_iterator i = a.begin(); VecInt::const_iterator j = b.begin(); while(i!= a.end() && j != b.end()) { while(i!= a.end() && j!=b.end() && *i <= *j) { out.push_back(*i); i++; } while(i!= a.end() && j!= b.end() && *j <= *i) { out.push_back(*j); j++; } } for( ; i!=a.end(); ++i) out.push_back(*i); for( ; j!=b.end(); ++j) out.push_back(*j); }