// merge Strongly Connected Component // return vertex map between old vertex and corresponding new merged vertex void GraphUtil::mergeSCC(Graph& g, int* on, vector<int>& reverse_topo_sort) { vector<int> sn; hash_map< int, pair<int, int> > order; int ind = 0; multimap<int, int> sccmap; // each vertex id correspond with a scc num int scc = 0; int vid; int origsize = g.num_vertices(); // cout << " inside MergeSCC "<< endl; for (int i = 0; i < origsize; i++) { vid = i; if (g[vid].visited) continue; tarjan(g, vid, ind, order, sn, sccmap, scc); } // cout << " inside MergeSCC after tarjan "<< endl; // no component need to merge if (scc == origsize) { for (int i = 0; i < origsize; i++) on[i] = i; // topological sort topological_sort(g, reverse_topo_sort); // update graph's topological id for (int i = 0; i < reverse_topo_sort.size(); i++) g[reverse_topo_sort[i]].topo_id = reverse_topo_sort.size()-i-1; return; } hash_map<int, vector<int> > inlist, outlist; g.extract(inlist, outlist); multimap<int,int>::iterator mit; mit = sccmap.begin(); int num_comp; int maxid = g.num_vertices()-1; while (mit != sccmap.end()) { num_comp = mit->first; if (++sccmap.lower_bound(num_comp) == sccmap.upper_bound(num_comp)) { on[mit->second] = mit->second; ++mit; continue; } maxid++; inlist[maxid] = vector<int>(); outlist[maxid] = vector<int>(); for (; mit != sccmap.upper_bound(num_comp); ++mit) { on[mit->second] = maxid; vector<int> vec = inlist[mit->second]; vector<int>::iterator vit, vit1; vector<int> vec1; bool hasEdge = false; // copy all incoming edges for (vit = vec.begin(); vit != vec.end(); vit++) { hasEdge = false; vec1 = outlist[*vit]; for (vit1 = vec1.begin(); vit1 != vec1.end(); vit1++) { if (*vit1 == maxid) { hasEdge = true; break; } } if (!hasEdge && (*vit != maxid)) { inlist[maxid].push_back(*vit); outlist[*vit].push_back(maxid); } } // copy all outgoing edges vec = outlist[mit->second]; for (vit = vec.begin(); vit != vec.end(); vit++) { hasEdge = false; vec1 = inlist[*vit]; for (vit1 = vec1.begin(); vit1 != vec1.end(); vit1++) if (*vit1 == maxid) { hasEdge = true; break; } if (!hasEdge && (*vit != maxid)) { outlist[maxid].push_back(*vit); inlist[*vit].push_back(maxid); } } // delete old vertex vec = inlist[mit->second]; for (vit = vec.begin(); vit != vec.end(); vit++) { for (vit1 = outlist[*vit].begin(); vit1 != outlist[*vit].end(); ) if (*vit1 == mit->second) outlist[*vit].erase(vit1); else vit1++; } vec = outlist[mit->second]; for (vit = vec.begin(); vit != vec.end(); vit++) { for (vit1 = inlist[*vit].begin(); vit1 != inlist[*vit].end(); ) if (*vit1 == mit->second) inlist[*vit].erase(vit1); else vit1++; } outlist.erase(mit->second); inlist.erase(mit->second); } } g = Graph(inlist, outlist); // topological sort topological_sort(g, reverse_topo_sort); // update graph's topological id for (int i = 0; i < reverse_topo_sort.size(); i++) g[reverse_topo_sort[i]].topo_id = reverse_topo_sort.size()-i-1; // update index map hash_map<int,int> indexmap; hash_map<int, vector<int> >::iterator hit; int k; for (hit = outlist.begin(), k=0; hit != outlist.end(); hit++, k++) { indexmap[hit->first] = k; } for (k = 0; k < origsize; k++) on[k] = indexmap[on[k]]; /* cout << "Index Map" << endl; for (int i = 0; i < origsize; i++) cout << on[i] << " "; cout << endl; cout << "roots: " << g.getRoots().size() << endl; */ }
// build maximal weighted spanning tree and rank the vertices based on tc size of their BFS tree void GraphUtil::buildMaxWST(Graph& g, ReducedGraph& sptree, vector<int>& rank) { ReducedGraph::iterator rit; vector<int>::iterator vit; map<int,int>::iterator mit; SparseVec::iterator svit; int gsize = g.num_vertices(); map<int,pair<int,int> > pred_succ; SparseVec weight = SparseVec(gsize,map<int,int>()); multimap<int,int> mrank; int tree_tc = 0; for (int i = 0; i < gsize; i++) { if(i%100==0) printf("buildMaxWST %d\n",i); ReducedGraph tree; tree_tc = BFSTree(g, i, tree); #ifdef ALLPATHS treestat(tree, pred_succ, i, gsize); #endif for (rit = tree.begin(); rit != tree.end(); rit++) { for (vit = rit->second.begin(); vit != rit->second.end(); vit++) #ifdef ALLPATHS weight[rit->first][*vit] += pred_succ[rit->first].first*pred_succ[*vit].second; #else weight[rit->first][*vit] += 1; #endif } #ifdef ALLPATHS map<int,pair<int,int> >().swap(pred_succ); #endif ReducedGraph().swap(tree); mrank.insert(make_pair(tree_tc,i)); } // set ranking results // rank.clear(); vector<int>().swap(rank); multimap<int,int>::const_reverse_iterator mcit; for (mcit = mrank.rbegin(); mcit != mrank.rend(); mcit++) rank.push_back(mcit->second); // mrank.clear(); multimap<int,int>().swap(mrank); multimap<int,pair<int,int> > wmap; multimap<int,pair<int,int> >::reverse_iterator mmit; for (int i = 0; i < weight.size(); i++) { for (mit = weight[i].begin(); mit != weight[i].end(); mit++) { wmap.insert(make_pair(mit->second,make_pair(i,mit->first))); } } // weight.clear(); SparseVec().swap(weight); // greedy algorithm to extract maximal weight spanning tree int numedge = 0; Graph tree = Graph(gsize); pair<int,int> edge; for (mmit = wmap.rbegin(); mmit != wmap.rend(); mmit++) { edge = mmit->second; if (tree.in_edges(edge.second).size()>0 || checkPath(tree,edge.second,edge.first)) continue; tree.addEdge(edge.first,edge.second); numedge++; if (numedge>=(gsize-1)) break; } // compute all pairs shortest paths in the spanning tree // computeShortestDistance(tree,treedist); EdgeList el; for (int i = 0; i < gsize; i++) { el = tree.out_edges(i); if (el.size()>0) sptree[i] = vector<int>(el.begin(),el.end()); // sptree.push_back(vector<int>(el.begin(),el.end())); // sptree.insert(el.begin(),el.end()); } }
int GraphUtil::buildSpanningTree2(Graph& g, SparseVec& treedist, SparseVec& dist, ReducedGraph& sptree) { ReducedGraph::iterator rit; vector<int>::iterator vit; map<int,int>::iterator mit; SparseVec::iterator svit; int gsize = g.num_vertices(); SparseVec weight = SparseVec(gsize,map<int,int>()); for (int i = 0; i < gsize; i++) { ReducedGraph tree; BFSTree(g, i, tree); for (rit = tree.begin(); rit != tree.end(); rit++) { for (vit = rit->second.begin(); vit != rit->second.end(); vit++) weight[rit->first][*vit] += 1; } tree.clear(); } // for test /* cout << "weight summary "; Util::printSparseVec(weight); */ multimap<int,pair<int,int> > wmap; multimap<int,pair<int,int> >::reverse_iterator mmit; for (int i = 0; i < weight.size(); i++) { for (mit = weight[i].begin(); mit != weight[i].end(); mit++) { wmap.insert(make_pair(mit->second,make_pair(i,mit->first))); } } weight.clear(); // greedy algorithm to extract maximal weight spanning tree int numedge = 0; Graph tree = Graph(gsize); pair<int,int> edge; for (mmit = wmap.rbegin(); mmit != wmap.rend(); mmit++) { // for test // cout << "(" << mmit->second.first << "," << mmit->second.second << ")" << mmit->first << endl; edge = mmit->second; if (tree.in_edges(edge.second).size()>0 || checkPath(tree,edge.second,edge.first)) continue; tree.addEdge(edge.first,edge.second); numedge++; if (numedge>=(gsize-1)) break; } // for test // tree.writeGraph(cout); computeShortestDistance(tree,treedist); int tnum = 0; EdgeList el; for (int i = 0; i < gsize; i++) { treedist[i].erase(i); tnum += treedist[i].size(); for (mit = treedist[i].begin(); mit != treedist[i].end(); ) { if (mit->second != dist[i][mit->first]) { treedist[i].erase(mit++); } else mit++; } el = tree.out_edges(i); sptree[i] = vector<int>(el.begin(),el.end()); // sptree.push_back(vector<int>(el.begin(),el.end())); } // for test // Util::printSparseVec(treedist); return tnum; }
int main(int argc, char *argv[]) { int returnierr=0; #ifdef EPETRA_MPI // Initialize MPI MPI_Init(&argc,&argv); int size; // Number of MPI processes, My process ID MPI_Comm_size(MPI_COMM_WORLD, &size); if (size > 1) { cout << "This example cannot be run on more than one processor!" << endl; MPI_Finalize(); returnierr = -1; return returnierr; } #endif bool verbose = false; // Check if we should print results to standard out if (argc>1) if (argv[1][0]=='-' && argv[1][1]=='v') verbose = true; #ifdef EPETRA_MPI Epetra_MpiComm Comm(MPI_COMM_WORLD); #else Epetra_SerialComm Comm; #endif if (!verbose) Comm.SetTracebackMode(0); // This should shut down any error traceback reporting if (verbose) { cout << EpetraExt::EpetraExt_Version() << endl << endl; cout << Comm << endl << flush; } Comm.Barrier(); int NumMyElements = 3; Epetra_Map Map( NumMyElements, 0, Comm ); Epetra_CrsGraph Graph( Copy, Map, 1 ); int index[2]; index[0] = 2; Graph.InsertGlobalIndices( 0, 1, &index[0] ); index[0] = 0; index[1] = 2; Graph.InsertGlobalIndices( 1, 2, &index[0] ); index[0] = 1; Graph.InsertGlobalIndices( 2, 1, &index[0] ); Graph.FillComplete(); // Create an Epetra::CrsMatrix Epetra_CrsMatrix Matrix( Copy, Graph ); double value[2]; index[0] = 2; value[0] = 3.0; Matrix.ReplaceMyValues( 0, 1, &value[0], &index[0] ); index[0] = 0; index[1] = 2; value[0] = 2.0; value[1] = 2.5; Matrix.ReplaceMyValues( 1, 2, &value[0], &index[0] ); index[0] = 1; value[0] = 1.0; Matrix.ReplaceMyValues( 2, 1, &value[0], &index[0] ); Matrix.FillComplete(); EpetraExt::AmesosBTF_CrsMatrix BTFTrans( 0.0, true, verbose ); Epetra_CrsMatrix & NewMatrix = BTFTrans( Matrix ); if (verbose) { cout << "*************** PERFORMING BTF TRANSFORM ON CRS_MATRIX **************" <<endl<<endl; cout << "CrsMatrix *before* BTF transform: " << endl << endl; cout << Matrix << endl; } BTFTrans.fwd(); if (verbose) { cout << "CrsMatrix *after* BTF transform: " << endl << endl; cout << NewMatrix << endl; } #ifdef EPETRA_MPI MPI_Finalize(); #endif return returnierr; }
int test_bug2554(Epetra_Comm& Comm, bool verbose) { //This function contains code submitted by Joe Young to //expose bug 2554. The bug has now been fixed, so this //function executes without problem. It will be kept as //a regression test. // Construct maps that do not have consecutive indices int RowIndices[3]; if (Comm.MyPID() == 0) { RowIndices[0] = 1; RowIndices[1] = 2; RowIndices[2] = 3; } else { RowIndices[0] = 4; RowIndices[1] = 5; RowIndices[2] = 6; } Epetra_Map RowMap(-1, 3, RowIndices, 0, Comm); // Construct a graph with two entries per line Epetra_CrsGraph Graph(Copy, RowMap, 2); for (int i = 0; i < RowMap.NumMyElements(); i++) { int ig = RowIndices[i]; Graph.InsertGlobalIndices(ig, 1, &ig); } Graph.FillComplete(); // Make some matrix out of this Epetra_FECrsMatrix *Matrix=new Epetra_FECrsMatrix(Copy, Graph); // Fill it up with ones Matrix->PutScalar(1.0); // Create a rhs and lhs Epetra_Vector *rhs=new Epetra_Vector(RowMap); Epetra_Vector *lhs=new Epetra_Vector(RowMap); rhs->PutScalar(2.0); lhs->PutScalar(0.0); // Create a solver and problem; AztecOO *solver=new AztecOO(); Epetra_LinearProblem *problem=new Epetra_LinearProblem(); // Load the problem into the solver problem->SetOperator(Matrix); problem->SetRHS(rhs); problem->SetLHS(lhs); solver->SetProblem(*problem, true); // Set some options solver->SetAztecOption(AZ_solver,AZ_cg); solver->SetAztecOption(AZ_precond,AZ_ls); solver->SetAztecOption(AZ_poly_ord,9); // Solve the problem solver->Iterate(50,1e-12); // Delete the matrix, lhs, rhs delete Matrix; delete lhs; delete rhs; /* Somehow, C++ reallocates objects in the same location where they were previously allocated. So, we need to trick it. If we don't do this, the error will not appear. */ int *dummy=new int[1000]; double *dummy2=new double[1000]; // Reallocate all of them Matrix=new Epetra_FECrsMatrix(Copy, Graph); rhs=new Epetra_Vector(RowMap); lhs=new Epetra_Vector(RowMap); Matrix->PutScalar(1.0); rhs->PutScalar(2.0); lhs->PutScalar(0.0); // Load the problem into the solver problem->SetOperator(Matrix); problem->SetRHS(rhs); problem->SetLHS(lhs); //For the following call to SetProblem, we must pass 'true' for //the optional bool argument which would otherwise default to false. //Passing 'true' forces it to internally reset the preconditioner. solver->SetProblem(*problem, true); // Solve the problem solver->Iterate(50,1e-12); // Clean up some memory solver->UnsetLHSRHS(); // Make sure this function works delete problem; delete solver; delete [] dummy; delete [] dummy2; delete Matrix; delete lhs; delete rhs; return(0); }
void TrackUnionStream::ProcessInput(GraphTime aFrom, GraphTime aTo, uint32_t aFlags) { if (IsFinishedOnGraphThread()) { return; } AutoTArray<bool,8> mappedTracksFinished; AutoTArray<bool,8> mappedTracksWithMatchingInputTracks; for (uint32_t i = 0; i < mTrackMap.Length(); ++i) { mappedTracksFinished.AppendElement(true); mappedTracksWithMatchingInputTracks.AppendElement(false); } bool allFinished = !mInputs.IsEmpty(); bool allHaveCurrentData = !mInputs.IsEmpty(); for (uint32_t i = 0; i < mInputs.Length(); ++i) { MediaStream* stream = mInputs[i]->GetSource(); if (!stream->IsFinishedOnGraphThread()) { // XXX we really should check whether 'stream' has finished within time aTo, // not just that it's finishing when all its queued data eventually runs // out. allFinished = false; } if (!stream->HasCurrentData()) { allHaveCurrentData = false; } bool trackAdded = false; for (StreamTracks::TrackIter tracks(stream->GetStreamTracks()); !tracks.IsEnded(); tracks.Next()) { bool found = false; for (uint32_t j = 0; j < mTrackMap.Length(); ++j) { TrackMapEntry* map = &mTrackMap[j]; if (map->mInputPort == mInputs[i] && map->mInputTrackID == tracks->GetID()) { bool trackFinished = false; StreamTracks::Track* outputTrack = mTracks.FindTrack(map->mOutputTrackID); found = true; if (!outputTrack || outputTrack->IsEnded() || !mInputs[i]->PassTrackThrough(tracks->GetID())) { trackFinished = true; } else { CopyTrackData(tracks.get(), j, aFrom, aTo, &trackFinished); } mappedTracksFinished[j] = trackFinished; mappedTracksWithMatchingInputTracks[j] = true; break; } } if (!found && mInputs[i]->AllowCreationOf(tracks->GetID())) { bool trackFinished = false; trackAdded = true; uint32_t mapIndex = AddTrack(mInputs[i], tracks.get(), aFrom); CopyTrackData(tracks.get(), mapIndex, aFrom, aTo, &trackFinished); mappedTracksFinished.AppendElement(trackFinished); mappedTracksWithMatchingInputTracks.AppendElement(true); } } if (trackAdded) { for (MediaStreamListener* l : mListeners) { l->NotifyFinishedTrackCreation(Graph()); } } } for (int32_t i = mTrackMap.Length() - 1; i >= 0; --i) { if (mappedTracksFinished[i]) { EndTrack(i); } else { allFinished = false; } if (!mappedTracksWithMatchingInputTracks[i]) { for (auto listener : mTrackMap[i].mOwnedDirectListeners) { // Remove listeners while the entry still exists. RemoveDirectTrackListenerImpl(listener, mTrackMap[i].mOutputTrackID); } mTrackMap.RemoveElementAt(i); } } if (allFinished && mAutofinish && (aFlags & ALLOW_FINISH)) { // All streams have finished and won't add any more tracks, and // all our tracks have actually finished and been removed from our map, // so we're finished now. FinishOnGraphThread(); } else { mTracks.AdvanceKnownTracksTime(GraphTimeToStreamTimeWithBlocking(aTo)); } if (allHaveCurrentData) { // We can make progress if we're not blocked mHasCurrentData = true; } }
int main() { bool test = false, simulateBathy = false; if (test) { runTests(); return 0; } acousticParams.insert({ "debug", "0" }); acousticParams.insert({ "cellSize", "5" }); acousticParams.insert({ "fishmodel", "0" }); acousticParams.insert({ "suppressionRangeFactor", "1"}), acousticParams.insert({ "suppressionMethod", "suppression.quick"}), acousticParams.insert({ "userSensors", "100,100,0,0,100,0,0,200" }); acousticParams.insert({ "numOptimalSensors", "10" }); acousticParams.insert({ "numProjectedSensors", "2" }); acousticParams.insert({ "bias", "2" }); acousticParams.insert({ "ousdx", ".1" }); acousticParams.insert({ "ousdy", ".1" }); acousticParams.insert({ "oucor", "0" }); acousticParams.insert({ "mux", ".5" }); acousticParams.insert({ "muy", ".5" }); acousticParams.insert({ "fishmodel", "1" }); acousticParams.insert({ "minDepth", "15" }); acousticParams.insert({ "maxDepth", "30" }); acousticParams.insert({ "meanRelativePosition", "1" }); acousticParams.insert({ "relativePositionSD", "1" }); // acousticParams.insert({"inputFile", "himbsyn.bathy.v19.grd"}); acousticParams.insert({"inputFile", "himbsyn.bathytopo.1km.v19.grd"}); // acousticParams.insert({ "inputFile", "pal_5m.asc" }); acousticParams.insert({ "inputFileType", "netcdf" }); acousticParams.insert({ "seriesName", "z" }); acousticParams.insert({ "timestamp", "-1" }); acousticParams.insert({ "logScaleGraphColoring", "1" }); acousticParams.insert({ "contourDepths", "0,-20,-40,-80" }); double suppressionRangeFactor = std::stod(acousticParams["suppressionRangeFactor"]), ousdx = std::stod(acousticParams["ousdx"]), ousdy = std::stod(acousticParams["ousdy"]), oucor = std::stod(acousticParams["oucor"]), mux = std::stod(acousticParams["mux"]), muy = std::stod(acousticParams["muy"]), fishmodel = std::stod(acousticParams["fishmodel"]), networkSparsity = 0, absRecoveryRate = 0, uniqueRecoveryRate = 0, goodnessGridComputationTime = 0, totalComputationTime = 0; int startRow = 450, startCol = 340, // 450,340,201,201 (1km)netcdf rowDist = 1001, // 100 0 800 1500 (5m)netcdf colDist = 1001, // 300 200 501 501 (palmyra) asc height = 1000, width = 1000, bias = 2, sensorDetectionRange = 4, sensorDetectionDiameter = 2 * sensorDetectionRange + 1, sensorPeakDetectionProbability = 1, SDofSensorDetectionRange = 1, i = 0, row = 0, col = 0, cellSize = std::stoi(acousticParams["cellSize"]), numOptimalSensors = std::stoi(acousticParams["numOptimalSensors"]), numProjectedSensors = std::stoi(acousticParams["numProjectedSensors"]), numSensorsToPlace = numOptimalSensors + numProjectedSensors, suppressionDiameter = (2 * ceil(sensorDetectionRange * suppressionRangeFactor)) + 1; // Set the global border size border = sensorDetectionRange; omp_set_num_threads(numThreads); Eigen::setNbThreads(numThreads); clock_t begin, end, vizBegin, vizEnd; // TODO(Greg) Data validation // Parse User Sensor Placements std::cout << "\nReading userSensor List...\n"; std::vector<std::string> userSensors; parseCDString(&userSensors, acousticParams["userSensors"], ','); Eigen::MatrixXd userSensorList; userSensorList.resize(userSensors.size()/2, 4); for (i = 0; i < userSensorList.rows(); i ++) { row = std::stoi(userSensors[2 * i]); col = std::stoi(userSensors[2 * i + 1]); if (row < 0 || col < 0 || row >= rowDist || col >= colDist) { printError("A user-defined sensor is out of bounds.", 1, acousticParams["timestamp"]); } // Translate user points to our internal grid userSensorList(i, 0) = row; userSensorList(i, 1) = col; } begin = clock(); // Compute contour depth meta data (used for graphical output) std::vector<std::string> contourLevels; parseCDString(&contourLevels, acousticParams["contourDepths"], ','); // Note the number of contours we need to graph acousticParams.insert({ "numContourDepths", std::to_string(contourLevels.size()) }); // TODO(Greg) Sort is broken, throws segfaults. Possibly b/c file doesn't // exist (tried with pal5m.asc). fix plx. // sort(&contourLevels, &contourLevels + numContourDepths); // File path variables std::string outputDataFilePath = "data/", outputDataFileType = ".dat", bathymetryTitle = "Topography", habitatTitle = "Habitat", goodnessTitle = "Goodness", coverageTitle = "Acoustic Coverage", bathymetryFilePath = outputDataFilePath + bathymetryTitle + outputDataFileType, habitatFilePath = outputDataFilePath + habitatTitle + outputDataFileType, goodnessFilePath = outputDataFilePath + goodnessTitle + outputDataFileType, coverageFilePath = outputDataFilePath + coverageTitle + outputDataFileType; Grid bGrid(rowDist + 2 * border, colDist + 2 * border, "Behavior"); Grid gGrid(rowDist + 2 * border, colDist + 2 * border, "Goodness"); Grid tGrid(rowDist + 2 * border, colDist + 2 * border, "Topography"); Grid cGrid(rowDist + 2 * border, colDist + 2 * border, "Coverage"); Eigen::MatrixXd suppressionReference; Eigen::MatrixXd distanceGradient; Eigen::MatrixXd detectionGradient; distanceGradient.resize(sensorDetectionDiameter, sensorDetectionDiameter); distanceGradient.setConstant(0); detectionGradient.resize(sensorDetectionDiameter, sensorDetectionDiameter); detectionGradient.setConstant(0); // Create a gradient of distances to avoid redundant computation makeDistGradient(&distanceGradient, sensorDetectionRange); // Create a gradient of probability of detection (due to sensorRange) to // avoid redundant computation makeDetectionGradient(&detectionGradient, & distanceGradient, sensorPeakDetectionProbability, SDofSensorDetectionRange); // Fetch or simulate topography std::cout << "Getting topography..."; if (simulateBathy) { // Simulate topography simulatetopographyGrid(&tGrid, rowDist, colDist); } else { // Fetch actual topography getBathy(&tGrid, acousticParams["inputFile"], acousticParams["inputFileType"], size_t(startRow), size_t(startCol), size_t(rowDist), size_t(colDist), acousticParams["seriesName"], acousticParams["timestamp"]); } std::cout << bGrid.data; // Fill in Behavior Grid std::cout << "\nGetting Behavior..."; populateBehaviorGrid(&tGrid, &bGrid, bias, cellSize, ousdx, ousdy, oucor, mux, muy, fishmodel); // Initalize the Coverage Grid cGrid.data.block(border, border, rowDist, colDist).setConstant(1); // Mr. Gaeta, START THE CLOCK! vizBegin = clock(); std::cout << "\nGetting Goodness...\nBias: " << bias << "\n"; // Calculate good sensor locations calculateGoodnessGrid(&tGrid, &bGrid, &gGrid, &suppressionReference, &detectionGradient, &distanceGradient, bias, sensorDetectionRange, border, border, rowDist, colDist); vizEnd = clock(); goodnessGridComputationTime = static_cast<double>(end - begin) / CLOCKS_PER_SEC; std::cout << "Copying goodness grid...\n"; Grid UGGrid(&gGrid, "Unsuppressed Goodness"); // Find optimal placements std::cout << "\nPlacing Sensors...\n"; Eigen::MatrixXd bestSensors; bestSensors.resize(numSensorsToPlace, 4); //============================ gGrid.name = "x1"; Graph x1Graph = Graph(&gGrid); x1Graph.writeMat(); // Grab the top n sensor r,c locations and recovery rates. selectTopSensorLocations(&tGrid, &bGrid, &gGrid, &UGGrid, &bestSensors, &userSensorList, &suppressionReference, &detectionGradient, &distanceGradient, numSensorsToPlace, sensorDetectionRange, bias, suppressionRangeFactor, suppressionDiameter, sensorPeakDetectionProbability, SDofSensorDetectionRange, acousticParams["timestamp"]); gGrid.name = "x2"; Graph x2Graph = Graph(&gGrid); x2Graph.writeMat(); std::cout << bestSensors << "\n"; std::cout << "Computing Statistics...\n"; getStats(&UGGrid, &gGrid, &bestSensors, sensorDetectionRange, &networkSparsity, &absRecoveryRate, &uniqueRecoveryRate, &cGrid); gGrid.name = "x3"; Graph x3Graph = Graph(&gGrid); x3Graph.writeMat(); gGrid.name = "Goodness"; // Generate graphs std::cout<< "\nWriting Graphs..."; Graph gGraph = Graph(&UGGrid); Graph tGraph = Graph(&tGrid); Graph bGraph = Graph(&bGrid); Graph cGraph = Graph(&cGrid); try { // Print the matrix & data files for Topography Grid tGraph.writeMat(); tGraph.writeDat(); // Print the contour file used by all graphs. // (Do this just once as it takes a loooong time). tGraph.printContourFile(&contourLevels); // Graph the Topography Grid with contour lines. bool plotSensors = true; tGraph.printContourGraph(width, height, &contourLevels, plotSensors, &userSensorList, &bestSensors, numProjectedSensors, false); // Print the matrix & data files for Bathymetry Grid bGraph.writeMat(); bGraph.writeDat(); // Graph Behavior Grid with contour lines. bGraph.printContourGraph(width, height, &contourLevels, plotSensors, &userSensorList, &bestSensors, numProjectedSensors, false); // Print the matrix & data files for Goodness Grid gGraph.writeMat(); gGraph.writeDat(); // Graph Goodness Grid with contour lines. gGraph.printContourGraph(width, height, &contourLevels, plotSensors, &userSensorList, &bestSensors, numProjectedSensors, false); // Print the matrix & data files for Goodness Grid cGraph.writeMat(); cGraph.writeDat(); // Graph Goodness Grid with contour lines. cGraph.printContourGraph(width, height, &contourLevels, plotSensors, &userSensorList, &bestSensors, numProjectedSensors, false); } catch (int e) { std::cout << "Error:" << e << "\n"; return 0; } end = clock(); goodnessGridComputationTime = static_cast<double>(vizEnd - vizBegin) / CLOCKS_PER_SEC; std::cout << "\nVisibility calculation took " << goodnessGridComputationTime << " s"; totalComputationTime = static_cast<double>(end - begin) / CLOCKS_PER_SEC; std::cout << "\nEntire Run took " << totalComputationTime << " s"; return 0; }
void GraphToFibers::_updateOutput() { _outNodePositions.clearList(); _outNodePositions.selectItemAt(-1); _outEdgePositions.clearList(); _outEdgePositions.selectItemAt(-1); _outEdgeConnections.clearList(); _outEdgeConnections.selectItemAt(-1); int nodeCount = 0; int edgeCount = 0; int currentEdgePositionNum = 0; // Work on a local copy of the graph, because the smoothing will change it Graph* vesselGraph = NULL; ML_CHECK_NEW(vesselGraph, Graph(_inGraph)); vesselGraph->purifyGraph(); //vesselGraph->setRootIdToAllChildren(); vesselGraph->closeSkeletonGaps(); // smooth the graph const int numSmoothingPasses = 3; const float smoothingFactor = 0.7; //const Graph::EdgeIterator endEdge(); for (Graph::EdgeIterator iter = vesselGraph->beginEdge(); iter != vesselGraph->endEdge(); ++iter) { static_cast<VesselEdge*>(*iter)->smooth(numSmoothingPasses, smoothingFactor, smoothingFactor); } // Iterate over all root nodes for (Graph::ConstNodeIterator iter = vesselGraph->beginRoot(); iter != vesselGraph->endRoot(); iter++) { } // Iterate over all nodes for (Graph::ConstNodeIterator i = vesselGraph->beginNode(); i != vesselGraph->endNode(); i++) { const VesselNode* thisNode = *i; const Vector3 thisNodePos = thisNode->getPos(); //thisNode->getDepNode(); // Get dependent node via edge with index i. //thisNode->edges(); //thisNode->getId(); //thisNode->getLabel(); // Add node markers XMarker thisNodeMarker(thisNodePos); std::string nodeName = "Node #" + mlPDF::intToString(nodeCount); thisNodeMarker.setName(nodeName.c_str()); thisNodeMarker.type = 0; _outNodePositions.appendItem(thisNodeMarker); // Add edge markers & connections const size_t thisNodeEdgesNum = thisNode->getEdgeNum(); // Get Number of edges dependent to the node. for (size_t e = 0; e < thisNodeEdgesNum; e++) { const VesselEdge* thisNodeEdge = thisNode->getDepEdge(e); // Get the pointer of edge with index i. if (thisNodeEdge) { bool newBranch = true; const size_t numSkeletons = thisNodeEdge->numSkeletons(); for (size_t s = 0; s < numSkeletons; s++) { const Skeleton* thisSkeleton = thisNodeEdge->skeleton(s); Vector3 thisSkeletonPos = thisSkeleton->getPos(); XMarker thisVesselEdgeMarker(thisSkeletonPos); thisVesselEdgeMarker.type = 0; // edgeCount; std::string edgeName = "Centerlines"; //std::string edgeName = "Edge #" + mlPDF::intToString(edgeCount); thisVesselEdgeMarker.setName(edgeName.c_str()); _outEdgePositions.appendItem(thisVesselEdgeMarker); /* if (s < numSkeletons - 1) { IndexPair thisVesselEdgeConnection((int)s, (int)s + 1); thisVesselEdgeConnection.type = edgeCount; _outEdgeConnections.appendItem(thisVesselEdgeConnection); } */ if (!newBranch) { IndexPair thisVesselEdgeConnection(currentEdgePositionNum - 1, currentEdgePositionNum); thisVesselEdgeConnection.type = 0; _outEdgeConnections.appendItem(thisVesselEdgeConnection); } currentEdgePositionNum++; newBranch = false; } edgeCount++; } } nodeCount++; } ML_DELETE(vesselGraph); _outNodePositionsFld->touch(); _outEdgePositionsFld->touch(); _outEdgeConnectionsFld->touch(); _createFibers(); }
void TDSPSingleEcho::Draw(Option_t *o, Double_t x0, Double_t x1, UInt_t num) { TGraph *a = Graph(NULL,x0,x1,num); a->Draw(o); a->GetXaxis()->SetTitle("#tau / #mu s"); gPad->Update(); }
void AudioCaptureStream::ProcessInput(GraphTime aFrom, GraphTime aTo, uint32_t aFlags) { if (!mStarted) { return; } uint32_t inputCount = mInputs.Length(); StreamTracks::Track* track = EnsureTrack(mTrackId); // Notify the DOM everything is in order. if (!mTrackCreated) { for (uint32_t i = 0; i < mListeners.Length(); i++) { MediaStreamListener* l = mListeners[i]; AudioSegment tmp; l->NotifyQueuedTrackChanges( Graph(), mTrackId, 0, TrackEventCommand::TRACK_EVENT_CREATED, tmp); l->NotifyFinishedTrackCreation(Graph()); } mTrackCreated = true; } if (IsFinishedOnGraphThread()) { return; } // If the captured stream is connected back to a object on the page (be it an // HTMLMediaElement with a stream as source, or an AudioContext), a cycle // situation occur. This can work if it's an AudioContext with at least one // DelayNode, but the MSG will mute the whole cycle otherwise. if (InMutedCycle() || inputCount == 0) { track->Get<AudioSegment>()->AppendNullData(aTo - aFrom); } else { // We mix down all the tracks of all inputs, to a stereo track. Everything // is {up,down}-mixed to stereo. mMixer.StartMixing(); AudioSegment output; for (uint32_t i = 0; i < inputCount; i++) { MediaStream* s = mInputs[i]->GetSource(); for (StreamTracks::TrackIter track(s->GetStreamTracks(), MediaSegment::AUDIO); !track.IsEnded(); track.Next()) { AudioSegment* inputSegment = track->Get<AudioSegment>(); StreamTime inputStart = s->GraphTimeToStreamTimeWithBlocking(aFrom); StreamTime inputEnd = s->GraphTimeToStreamTimeWithBlocking(aTo); if (track->IsEnded() && inputSegment->GetDuration() <= inputEnd) { // If the input track has ended and we have consumed all its data it // can be ignored. continue; } AudioSegment toMix; toMix.AppendSlice(*inputSegment, inputStart, inputEnd); // Care for streams blocked in the [aTo, aFrom] range. if (inputEnd - inputStart < aTo - aFrom) { toMix.AppendNullData((aTo - aFrom) - (inputEnd - inputStart)); } toMix.Mix(mMixer, MONO, Graph()->GraphRate()); } } // This calls MixerCallback below mMixer.FinishMixing(); } // Regardless of the status of the input tracks, we go foward. mTracks.AdvanceKnownTracksTime(GraphTimeToStreamTimeWithBlocking((aTo))); }
int main(int argc, char* argv[]) { //GameSquareFactory* gameSquareFactory = new GameSquareFactory; Factory factory = Factory(); Graph graph = Graph(); GameSquare *test = graph.getSquare(0,0); GameSquare *danger = graph.getSquare(0,1); danger->addDanger(10); danger = graph.getSquare(1,2); danger->addDanger(10); danger = graph.getSquare(2,0); danger->addDanger(10); danger = graph.getSquare(3,1); danger->addDanger(10); danger = graph.getSquare(4,1); danger->addDanger(10); danger = graph.getSquare(2,4); danger->addDanger(10); danger = graph.getSquare(3,7); danger->addDanger(10); danger = graph.getSquare(4,5); danger->addDanger(10); danger = graph.getSquare(5,9); danger->addDanger(10); danger = graph.getSquare(6,13); danger->addDanger(10); danger = graph.getSquare(7,17); danger->addDanger(10); danger = graph.getSquare(8,13); danger->addDanger(10); danger = graph.getSquare(9,19); danger->addDanger(10); danger = graph.getSquare(10,15); danger->addDanger(10); danger = graph.getSquare(9,14); danger->addDanger(10); danger = graph.getSquare(5,9); danger->addDanger(10); graph.pathFinder(10,10); int nextX; int nextY; while (test->getXPos() != 10 || test->getYPos()!=10) { nextX = test->previous.x; nextY = test->previous.y; std::cout << nextX << "," << nextY << std::endl; test = graph.getSquare(nextX,nextY); } //std::cout <<graph.squares.size() << std::endl; //graph->buildWorld(); //GameObject* array[3]; array[0] = factory.createObject("Enemy"); array[0]->setXPos(0);array[0]->setYPos(10); array[0]->setNextXPos(1);array[0]->setNextYPos(11); //array[0]->setNewXPos(1); array[1] = factory.createObject("Defender"); array[1]->setXPos(1);array[1]->setYPos(1); array[2] = factory.createObject("DefenderBase"); array[2]->setXPos(10);array[2]->setYPos(10); //std::cout << array[0]->getCurrentHealth() << std::endl; //std::cout << array[1]->getCurrentHealth() << std::endl; //std::cout << array[2]->getCurrentHealth() << std::endl; //opengl stuff, test rendering game objects... glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640,480); glutCreateWindow("Project Practice OpenGL"); initGL(640,480); //glutIdleFunc(update); glutIdleFunc(update); //glutFullScreen(); //glutTimerFunc(100,timer,0); glutDisplayFunc(render); glutKeyboardFunc(keyboard); glutSpecialFunc(special); glutMouseFunc(mouse); glutMainLoop(); }
// The MediaStreamGraph guarantees that this is actually one block, for // AudioNodeStreams. void AudioNodeStream::ProduceOutput(GraphTime aFrom, GraphTime aTo) { if (mMarkAsFinishedAfterThisBlock) { // This stream was finished the last time that we looked at it, and all // of the depending streams have finished their output as well, so now // it's time to mark this stream as finished. FinishOutput(); } StreamBuffer::Track* track = EnsureTrack(); AudioSegment* segment = track->Get<AudioSegment>(); uint16_t outputCount = std::max(uint16_t(1), mEngine->OutputCount()); mLastChunks.SetLength(outputCount); if (mInCycle) { // XXX DelayNode not supported yet so just produce silence for (uint16_t i = 0; i < outputCount; ++i) { mLastChunks[i].SetNull(WEBAUDIO_BLOCK_SIZE); } } else { for (uint16_t i = 0; i < outputCount; ++i) { mLastChunks[i].SetNull(0); } // We need to generate at least one input uint16_t maxInputs = std::max(uint16_t(1), mEngine->InputCount()); OutputChunks inputChunks; inputChunks.SetLength(maxInputs); for (uint16_t i = 0; i < maxInputs; ++i) { ObtainInputBlock(inputChunks[i], i); } bool finished = false; if (maxInputs <= 1 && mEngine->OutputCount() <= 1) { mEngine->ProduceAudioBlock(this, inputChunks[0], &mLastChunks[0], &finished); } else { mEngine->ProduceAudioBlocksOnPorts(this, inputChunks, mLastChunks, &finished); } if (finished) { mMarkAsFinishedAfterThisBlock = true; } } if (mDisabledTrackIDs.Contains(AUDIO_NODE_STREAM_TRACK_ID)) { for (uint32_t i = 0; i < mLastChunks.Length(); ++i) { mLastChunks[i].SetNull(WEBAUDIO_BLOCK_SIZE); } } if (mKind == MediaStreamGraph::EXTERNAL_STREAM) { segment->AppendAndConsumeChunk(&mLastChunks[0]); } else { segment->AppendNullData(mLastChunks[0].GetDuration()); } for (uint32_t j = 0; j < mListeners.Length(); ++j) { MediaStreamListener* l = mListeners[j]; AudioChunk copyChunk = mLastChunks[0]; AudioSegment tmpSegment; tmpSegment.AppendAndConsumeChunk(©Chunk); l->NotifyQueuedTrackChanges(Graph(), AUDIO_NODE_STREAM_TRACK_ID, mSampleRate, segment->GetDuration(), 0, tmpSegment); } }
int Young1(const Epetra_Comm& Comm, bool verbose) { //This is a test case submitted by Joe Young with bug 2421. It runs //only on 2 processors. if (Comm.NumProc() != 2) { return(0); } // Give rows 0-2 to proc 0 and 3-5 to proc 1 int RowIndices[3]; if (Comm.MyPID() == 0) { RowIndices[0] = 0; RowIndices[1] = 1; RowIndices[2] = 2; } else { RowIndices[0] = 3; RowIndices[1] = 4; RowIndices[2] = 5; } Epetra_Map RangeMap(-1, 3, RowIndices, 0, Comm); Epetra_Map & RowMap = RangeMap; // Define a second map that gives col 0 to proc 0 and col 1 to proc 1 int ColIndices[1]; if (Comm.MyPID() == 0) { ColIndices[0] = 0; } else { ColIndices[0] = 1; } Epetra_Map DomainMap(-1, 1, ColIndices, 0, Comm); // Construct a graph where both processors only insert into local // elements Epetra_FECrsGraph BrokenGraph(Copy, RowMap, 2); for (int i = 0; i < RangeMap.NumMyElements(); i++) { int ig = RowIndices[i]; int jgs[2] = { 0, 1 }; BrokenGraph.InsertGlobalIndices(1, &ig, 2, jgs); } BrokenGraph.GlobalAssemble(DomainMap, RangeMap); // Check the size of the matrix that would be created from the graph int numCols1 = BrokenGraph.NumGlobalCols(); if (verbose) { std::cout << "Number of global rows in the graph where only " "local elements were inserted: " << BrokenGraph.NumGlobalRows() << std::endl; std::cout << "Number of global cols in the graph where only " "local elements were inserted: " << BrokenGraph.NumGlobalCols() << std::endl; } // Construct a graph where both processors insert into global elements Epetra_FECrsGraph Graph(Copy, RowMap, 2); for (int i = 0; i < 6; i++) { int ig = i; int jgs[2] = { 0, 1 }; Graph.InsertGlobalIndices(1, &ig, 2, jgs); } Graph.GlobalAssemble(DomainMap, RangeMap); // Check the size of the matrix that would be created from the graph int numCols2 = Graph.NumGlobalCols(); if (verbose) { std::cout << "Number of global rows in the graph where " "global elements were inserted: " << Graph.NumGlobalRows() << std::endl; std::cout << "Number of global cols in the graph where " "global elements were inserted: " << Graph.NumGlobalCols() << std::endl; } if (numCols1 != numCols2) return(-1); return(0); }
void TrackUnionStream::CopyTrackData(StreamTracks::Track* aInputTrack, uint32_t aMapIndex, GraphTime aFrom, GraphTime aTo, bool* aOutputTrackFinished) { TrackMapEntry* map = &mTrackMap[aMapIndex]; TRACE_AUDIO_CALLBACK_COMMENT( "Input stream %p track %i -> TrackUnionStream %p track %i", map->mInputPort->GetSource(), map->mInputTrackID, this, map->mOutputTrackID); StreamTracks::Track* outputTrack = mTracks.FindTrack(map->mOutputTrackID); MOZ_ASSERT(outputTrack && !outputTrack->IsEnded(), "Can't copy to ended track"); MediaSegment* segment = map->mSegment; MediaStream* source = map->mInputPort->GetSource(); GraphTime next; *aOutputTrackFinished = false; for (GraphTime t = aFrom; t < aTo; t = next) { MediaInputPort::InputInterval interval = map->mInputPort->GetNextInputInterval(t); interval.mEnd = std::min(interval.mEnd, aTo); StreamTime inputEnd = source->GraphTimeToStreamTimeWithBlocking(interval.mEnd); if (aInputTrack->IsEnded() && aInputTrack->GetEnd() <= inputEnd) { *aOutputTrackFinished = true; break; } if (interval.mStart >= interval.mEnd) { break; } StreamTime ticks = interval.mEnd - interval.mStart; next = interval.mEnd; StreamTime outputStart = outputTrack->GetEnd(); if (interval.mInputIsBlocked) { segment->AppendNullData(ticks); STREAM_LOG( LogLevel::Verbose, ("TrackUnionStream %p appending %lld ticks of null data to track %d", this, (long long)ticks, outputTrack->GetID())); } else if (InMutedCycle()) { segment->AppendNullData(ticks); } else { if (source->IsSuspended()) { segment->AppendNullData(aTo - aFrom); } else { MOZ_ASSERT(outputTrack->GetEnd() == GraphTimeToStreamTimeWithBlocking(interval.mStart), "Samples missing"); StreamTime inputStart = source->GraphTimeToStreamTimeWithBlocking(interval.mStart); segment->AppendSlice(*aInputTrack->GetSegment(), inputStart, inputEnd); } } ApplyTrackDisabling(outputTrack->GetID(), segment); for (TrackBound<MediaStreamTrackListener>& b : mTrackListeners) { if (b.mTrackID != outputTrack->GetID()) { continue; } b.mListener->NotifyQueuedChanges(Graph(), outputStart, *segment); } outputTrack->GetSegment()->AppendFrom(segment); } }
uint32_t TrackUnionStream::AddTrack(MediaInputPort* aPort, StreamTracks::Track* aTrack, GraphTime aFrom) { STREAM_LOG(LogLevel::Verbose, ("TrackUnionStream %p adding track %d for " "input stream %p track %d, desired id %d", this, aTrack->GetID(), aPort->GetSource(), aTrack->GetID(), aPort->GetDestinationTrackId())); TrackID id; if (IsTrackIDExplicit(id = aPort->GetDestinationTrackId())) { MOZ_ASSERT(id >= mNextAvailableTrackID && mUsedTracks.BinaryIndexOf(id) == mUsedTracks.NoIndex, "Desired destination id taken. Only provide a destination ID " "if you can assure its availability, or we may not be able " "to bind to the correct DOM-side track."); #ifdef DEBUG for (size_t i = 0; mInputs[i] != aPort; ++i) { MOZ_ASSERT(mInputs[i]->GetSourceTrackId() != TRACK_ANY, "You are adding a MediaInputPort with a track mapping " "while there already exist generic MediaInputPorts for this " "destination stream. This can lead to TrackID collisions!"); } #endif mUsedTracks.InsertElementSorted(id); } else if ((id = aTrack->GetID()) && id > mNextAvailableTrackID && mUsedTracks.BinaryIndexOf(id) == mUsedTracks.NoIndex) { // Input id available. Mark it used in mUsedTracks. mUsedTracks.InsertElementSorted(id); } else { // No desired destination id and Input id taken, allocate a new one. id = mNextAvailableTrackID; // Update mNextAvailableTrackID and prune any mUsedTracks members it now // covers. while (1) { if (!mUsedTracks.RemoveElementSorted(++mNextAvailableTrackID)) { // Not in use. We're done. break; } } } // Round up the track start time so the track, if anything, starts a // little later than the true time. This means we'll have enough // samples in our input stream to go just beyond the destination time. StreamTime outputStart = GraphTimeToStreamTimeWithBlocking(aFrom); nsAutoPtr<MediaSegment> segment; segment = aTrack->GetSegment()->CreateEmptyClone(); for (uint32_t j = 0; j < mListeners.Length(); ++j) { MediaStreamListener* l = mListeners[j]; l->NotifyQueuedTrackChanges(Graph(), id, outputStart, TrackEventCommand::TRACK_EVENT_CREATED, *segment, aPort->GetSource(), aTrack->GetID()); } segment->AppendNullData(outputStart); StreamTracks::Track* track = &mTracks.AddTrack(id, outputStart, segment.forget()); STREAM_LOG(LogLevel::Debug, ("TrackUnionStream %p added track %d for input stream %p track %d, start ticks %lld", this, track->GetID(), aPort->GetSource(), aTrack->GetID(), (long long)outputStart)); TrackMapEntry* map = mTrackMap.AppendElement(); map->mEndOfConsumedInputTicks = 0; map->mEndOfLastInputIntervalInInputStream = -1; map->mEndOfLastInputIntervalInOutputStream = -1; map->mInputPort = aPort; map->mInputTrackID = aTrack->GetID(); map->mOutputTrackID = track->GetID(); map->mSegment = aTrack->GetSegment()->CreateEmptyClone(); for (int32_t i = mPendingDirectTrackListeners.Length() - 1; i >= 0; --i) { TrackBound<DirectMediaStreamTrackListener>& bound = mPendingDirectTrackListeners[i]; if (bound.mTrackID != map->mOutputTrackID) { continue; } MediaStream* source = map->mInputPort->GetSource(); map->mOwnedDirectListeners.AppendElement(bound.mListener); DisabledTrackMode currentMode = GetDisabledTrackMode(bound.mTrackID); if (currentMode != DisabledTrackMode::ENABLED) { bound.mListener->IncreaseDisabled(currentMode); } STREAM_LOG(LogLevel::Debug, ("TrackUnionStream %p adding direct listener " "%p for track %d. Forwarding to input " "stream %p track %d.", this, bound.mListener.get(), bound.mTrackID, source, map->mInputTrackID)); source->AddDirectTrackListenerImpl(bound.mListener.forget(), map->mInputTrackID); mPendingDirectTrackListeners.RemoveElementAt(i); } return mTrackMap.Length() - 1; }
Graph read_edgelist(FILE* instream, integer_t n, bool directed) { std::auto_ptr<igraph_t> result(new igraph_t); IGRAPH_TRY(igraph_read_graph_edgelist(result.get(), instream, n, directed)); return Graph(result.release()); }
void TrackUnionStream::CopyTrackData(StreamTracks::Track* aInputTrack, uint32_t aMapIndex, GraphTime aFrom, GraphTime aTo, bool* aOutputTrackFinished) { TrackMapEntry* map = &mTrackMap[aMapIndex]; StreamTracks::Track* outputTrack = mTracks.FindTrack(map->mOutputTrackID); MOZ_ASSERT(outputTrack && !outputTrack->IsEnded(), "Can't copy to ended track"); MediaSegment* segment = map->mSegment; MediaStream* source = map->mInputPort->GetSource(); GraphTime next; *aOutputTrackFinished = false; for (GraphTime t = aFrom; t < aTo; t = next) { MediaInputPort::InputInterval interval = map->mInputPort->GetNextInputInterval(t); interval.mEnd = std::min(interval.mEnd, aTo); StreamTime inputEnd = source->GraphTimeToStreamTimeWithBlocking(interval.mEnd); StreamTime inputTrackEndPoint = STREAM_TIME_MAX; if (aInputTrack->IsEnded() && aInputTrack->GetEnd() <= inputEnd) { inputTrackEndPoint = aInputTrack->GetEnd(); *aOutputTrackFinished = true; } if (interval.mStart >= interval.mEnd) { break; } StreamTime ticks = interval.mEnd - interval.mStart; next = interval.mEnd; StreamTime outputStart = outputTrack->GetEnd(); if (interval.mInputIsBlocked) { // Maybe the input track ended? segment->AppendNullData(ticks); STREAM_LOG(LogLevel::Verbose, ("TrackUnionStream %p appending %lld ticks of null data to track %d", this, (long long)ticks, outputTrack->GetID())); } else if (InMutedCycle()) { segment->AppendNullData(ticks); } else { if (source->IsSuspended()) { segment->AppendNullData(aTo - aFrom); } else { MOZ_ASSERT(outputTrack->GetEnd() == GraphTimeToStreamTimeWithBlocking(interval.mStart), "Samples missing"); StreamTime inputStart = source->GraphTimeToStreamTimeWithBlocking(interval.mStart); segment->AppendSlice(*aInputTrack->GetSegment(), std::min(inputTrackEndPoint, inputStart), std::min(inputTrackEndPoint, inputEnd)); } } ApplyTrackDisabling(outputTrack->GetID(), segment); for (uint32_t j = 0; j < mListeners.Length(); ++j) { MediaStreamListener* l = mListeners[j]; // Separate Audio and Video. if (segment->GetType() == MediaSegment::AUDIO) { l->NotifyQueuedAudioData(Graph(), outputTrack->GetID(), outputStart, *static_cast<AudioSegment*>(segment), map->mInputPort->GetSource(), map->mInputTrackID); } } for (TrackBound<MediaStreamTrackListener>& b : mTrackListeners) { if (b.mTrackID != outputTrack->GetID()) { continue; } b.mListener->NotifyQueuedChanges(Graph(), outputStart, *segment); } outputTrack->GetSegment()->AppendFrom(segment); } }
for(int i=0;i<str.length();i++){ num*=10; num+=str[i]-'0'; } return num; } class Solver{ public: bool read(Graph &g){ cin >> num_node; g = Graph(num_node); if(cin.eof()) return false; for(int i=2;i<=num_node;i++){ for(int j=1;j<i;j++){ string cost; cin >> cost; if(cost.compare("x")==0) continue; int num=myatoi(cost); g.insert(i,j,num); g.insert(j,i,num);
TEST_F(GeneratorsBenchmark, benchmarkGraphBuilder) { // parameters for Erdös-Renyi count n = 25000; double p = 0.001; count m_expected = p * n * (n + 1) / 2; Graph G; GraphBuilder builder; // prepare a random generator for each possible thread int maxThreads = omp_get_max_threads(); std::vector< std::function<double()> > randomPerThread; std::random_device device; std::uniform_int_distribution<uint64_t> intDist; for (int tid = 0; tid < maxThreads; tid++) { auto seed = intDist(device); std::mt19937_64 gen(seed); std::uniform_real_distribution<double> dist{0.0, std::nexttoward(1.0, 2.0)}; auto rdn = std::bind(dist, gen); randomPerThread.push_back(rdn); } count m_actual; uint64_t t1, t2; // half parallel way m_actual = 0; t1 = timeOnce([&]() { builder = GraphBuilder(n); builder.parallelForNodePairs([&](node u, node v) { int tid = omp_get_thread_num(); double rdn = randomPerThread[tid](); if (rdn <= p) { builder.addHalfEdge(u, v); } }); }); t2 = timeOnce([&]() { G = builder.toGraph(true); }); m_actual = G.numberOfEdges(); EXPECT_NEAR(m_actual / (double) m_expected, 1.0, 0.1); std::cout << "parallelForNodePairs + toGraphSequentiel:\t\t" << t1 << " + " << t2 << " = " << (t1 + t2) << " ms\n"; // fully parallel way m_actual = 0; t1 = timeOnce([&]() { builder = GraphBuilder(n); builder.parallelForNodePairs([&](node u, node v) { int tid = omp_get_thread_num(); double rdn = randomPerThread[tid](); if (rdn <= p) { builder.addHalfEdge(u, v); } }); }); t2 = timeOnce([&]() { G = builder.toGraph(true, false); }); m_actual = G.numberOfEdges(); EXPECT_NEAR(m_actual / (double) m_expected, 1.0, 0.1); std::cout << "parallelForNodePairs + toGraphParallel:\t\t" << t1 << " + " << t2 << " = " << (t1 + t2) << " ms\n"; // old way t1 = timeOnce([&]() { G = Graph(n); G.forNodePairs([&](node u, node v) { if (randomPerThread[0]() <= p) { G.addEdge(u, v); } }); }); m_actual = G.numberOfEdges(); EXPECT_NEAR(m_actual / (double) m_expected, 1.0, 0.1); std::cout << "forNodePairs + Graph.addEdge:\t\t\t\t" << t1 << " ms\n"; }
void Scene::UpdateTransforms() { SceneGraphNode rootNode = Graph()->RootNode(); std::for_each(rootNode.childNodes.begin(), rootNode.childNodes.end(), ProcessTransform); }