int main() { struct node node_dat[NODES]; int matrix[NODES][NODES]; int times; int start = 0; int end = 5; int i; if( adjacency("graph2.dat", matrix) == -1 ) { fprintf(stderr, "Can't open file: graph2.dat\n"); return -1; } for( i = 0; i < NODES; i++ ) { node_dat[i].dist = INF; node_dat[i].flag = 0; } times = dijkstra(start, end, node_dat, matrix); printf("%d : Distance = %d\n", end, node_dat[end].dist); printf(" Comparison %d\n", times); return 0; }
void prim() { auto V = std::vector<Vertex>(N); auto E = std::vector<Edge>{ }; auto T = std::vector<Vertex>{ }; // generate city graph based on distance table createGraph(E, V); for(int t = V.size()-1; t >= 0; t--){ V[t].key = Vertex::max_key; V[t].parent_index = Vertex::undef; } //int randomIndex = rand() % V.size(); //V[randomIndex].key = 0; V[0].key = 0; auto Q = V; auto A = std::vector<Edge>{ }; while(Q.size()-1 > 0){ int smallest = Vertex::max_key; int erase = 0; int pos = 0; for (int x = 0; x < Q.size(); x++) { if (Q[x].key < smallest) { smallest = Q[x].key; pos = x; } } auto u = Q[pos]; Q.erase(Q.begin()+pos); if(u.parent_index != Vertex::undef){ A.push_back(Edge(u.index, u.parent_index)); } adjacency(E,u.index,T); int smallestEdge = Vertex::max_key; int indicator = 0; for(int j = 0; j < T.size(); j++){ if(weight(u.index,T[j].index) < smallestEdge){ smallestEdge = weight(u.index,T[j].index); indicator = j; } } T[indicator].parent_index = u.index; T[indicator].key = weight(u.index,T[indicator].index); A.push_back(Edge(u.index, T[indicator].index)); eraseEdge(E,u.index,T[indicator].index); } std::cout << "Minimal graph: E = {"; for (int i = 0; i < A.size(); i++){ std::cout << "(" << A[i].vi1 << "," << A[i].vi2 << ")" << ","; } std::cout << "\b" << "}"; std::cout << "\n" << "Minimal costs: " << totalWeight(A) << "\n"; }
void testAdjacency(double * expr, int * nSamples, int * nGenes, int * corType, int * adjType, double * power, double * maxPOutliers, double * quick, int * fallback, int * cosine, double * adj, int * errCode, int * warn, int * nThreads) { adjacency(expr, * nSamples, * nGenes, * corType, * adjType, * power, *maxPOutliers, *quick, *fallback, *cosine, 0, adj, errCode, warn, nThreads, 1, 0); }
int SwapHeavierToLighterNeighbours::balance(Graph &theWeightedGraph) { // check to see a domain partitioner has been set DomainPartitioner *thePartitioner = this->getDomainPartitioner(); if (thePartitioner == 0) { opserr << "SwapHeavierToLighterNeighbours::balance"; opserr << "- No DomainPartitioner has been set\n"; return -1; } int res = 0; for (int ii=0; ii<numReleases; ii++) { VertexIter &theVertices = theWeightedGraph.getVertices(); Vertex *vertexPtr; while ((vertexPtr = theVertices()) != 0) { int vertexTag = vertexPtr->getTag(); double vertexLoad = vertexPtr->getWeight(); const ID &adjacency = vertexPtr->getAdjacency(); int size = adjacency.Size(); for (int j=0; j<size; j++) { int otherVertexTag = adjacency(j); Vertex *otherVertexPtr = theWeightedGraph.getVertexPtr(otherVertexTag); double otherVertexLoad = otherVertexPtr->getWeight(); if (vertexLoad > otherVertexLoad && otherVertexLoad != 0) if (vertexLoad/otherVertexLoad > factorGreater) { res = thePartitioner-> swapBoundary(vertexTag,otherVertexTag); if (res < 0) { opserr << "WARNING SwapHeavierToLighterNeighbours"; opserr << "::balance - DomainPartitioner returned "; opserr << res << endln; return res; } } if (vertexLoad != 0 && otherVertexLoad == 0) { res = thePartitioner-> swapBoundary(vertexTag,otherVertexTag); if (res < 0) { opserr << "WARNING SwapHeavierToLighterNeighbours"; opserr << "::balance - DomainPartitioner returned "; opserr << res << endln; return res; } } } } } return res; }
bool Digraph<T, Allocator>::is_linked(T v1, T v2) { vector<T> neighbors = adjacency(v1); for (typename vector<T>::iterator it = neighbors.begin(); it != neighbors.end(); ++it) { if (v2 == *it) return true; } return false; }
bool Digraph<T, Allocator>::is_reach(T start, T finish) { if (start == finish) return true; vector<T> neighbors = adjacency(start); queue<T> achievable; fill_achievable(neighbors, achievable); while (!achievable.empty()) { T v = achievable.front(); achievable.pop(); if (finish == v) return true; else { vector<T> neighbors = adjacency(v); fill_achievable(neighbors, achievable); } } return false; }
AbstractDigraph<T, Allocator> *Digraph<T, Allocator>::get_transpose() { AbstractDigraph<T, Allocator>* tr_graph = new Digraph<T, Allocator>(); for(AbstractIterator<T> *v = begin(VERTEX); *v != &*end(VERTEX); ++*v) { Vertex<T>& verticle = static_cast<Vertex<T>&>(**v); vector<T> adjVerticles = adjacency(verticle.getValue()); typename vector<T>::iterator it; for (it = adjVerticles.begin(); it != adjVerticles.end(); ++it) { tr_graph->add_link(*it, verticle.getValue()); } } return tr_graph; }
// On copy apply for type matrix<int>! bool labelAdjacencyMap::apply(const matrix<int>& src,image& dest) const { sparseMatrix<int> adj; usePalette colorizer; if (adjacency(src,adj)) { const parameters& par = getParameters(); palette pal; if (par.minColors) { computeMinPalette(adj,pal); } else { computeMaxPalette(adj,pal); } return colorizer.apply(src,pal,dest); } return false; };
void Goodfellow::Create( uint32_t numCompartments ) { N = numCompartments; stateDim = 2*N; mu.setZero(N); double muMin = 0.2; double muMax = 0.3; mu(0) = 0.6; if( N >= 2 ) { mu(1) = muMax; for(uint32_t i=2;i<N;++i) mu(i) = muMax - ((muMax-muMin)*i)/(N-1); } adjacency.setZero(N,N); for(uint32_t i=0;i<N;++i) for(uint32_t j=0;j<N;++j) adjacency(i,j) = (i==j)?0.0:1.0; }
bool graph<V,E>::isConnected() { if(vertices.size()==0) return true; matrix<int> adjacency = adjacency_matrix(); bool discovered[vertices.size()]; for(int i=0;i<vertices.size();i++) discovered[i]=false; stack<int> DFSstack; DFSstack.push(0); while(DFSstack.size()) { int now = DFSstack.top(); DFSstack.pop(); if(!discovered[now]) { discovered[now] = true; for(int i=0;i<vertices.size();i++) if(adjacency(now,i)==1) DFSstack.push(i); } } for(int i=0;i<vertices.size();i++) if(!discovered[i]) return false; return true; }
int main (int argc, char **argv) { graph *g = gengraph(7); g = adjacency(g, 0, 1); g = adjacency(g, 0, 2); g = adjacency(g, 1, 5); g = adjacency(g, 2, 3); g = adjacency(g, 2, 4); g = adjacency(g, 3, 6); printf("bfs\n"); bfs(g, 0, printnode, NULL); printf("dfs\n"); dfs(g, 0, printnode, NULL); exit(0); }
int Metis::partition(Graph &theGraph, int numPart) { // first we check that the options are valid if (checkOptions() == false) return -1; // now we get room for the data structures metis needs int numVertex = theGraph.getNumVertex(); int numEdge = theGraph.getNumEdge(); int *options = new int [5]; int *partition = new int [numVertex+1]; int *xadj = new int [numVertex+2]; int *adjncy = new int [2*numEdge]; int *vwgts = 0; int *ewgts = 0; int numbering = 0; int weightflag = 0; // no weights on our graphs yet if (START_VERTEX_NUM == 0) numbering = 0; else if (START_VERTEX_NUM == 1) numbering = 1; else { opserr << "WARNING Metis::partition - No partitioning done"; opserr << " vertex numbering must start at 0 or 1\n"; return (-2); } int edgecut; if ((options == 0) || (partition == 0) || (xadj == 0) || (adjncy == 0)) { opserr << "WARNING Metis::partition - No partitioning done"; opserr << " as ran out of memory\n"; return (-2); } // we build these data structures int indexEdge = 0; xadj[0] = 0; Vertex *vertexPtr; for (int vertex =0; vertex<numVertex; vertex++) { vertexPtr = theGraph.getVertexPtr(vertex+START_VERTEX_NUM); // check we don't have an invalid vertex numbering scheme // if so WARNING message, clean up and return -2 if (vertexPtr == 0) { opserr << "WARNING Metis::partition - No partitioning done"; opserr << " Metis requires consequtive Vertex Numbering\n"; delete [] options; delete [] partition; delete [] xadj; delete [] adjncy; return -2; } const ID&adjacency = vertexPtr->getAdjacency(); int degree = adjacency.Size(); for (int i=0; i<degree; i++) { adjncy[indexEdge++] = adjacency(i)-START_VERTEX_NUM; } xadj[vertex+1] = indexEdge; } if (defaultOptions == true) options[0] = 0; else { options[0] =1; options[1] = myCoarsenTo; options[2] = myMtype; options[3] = myIPtype; options[4] = myRtype; } int j; // we now the metis routines if (myPtype == 1) PMETIS(&numVertex, xadj, adjncy, vwgts, ewgts, &weightflag, &numPart, options, &numbering, &edgecut, partition); else KMETIS(&numVertex, xadj, adjncy, vwgts, ewgts, &weightflag, &numPart, options, &numbering, &edgecut, partition); // we set the vertex colors to correspond to the partitioned scheme for (int vert =0; vert<numVertex; vert++) { vertexPtr = theGraph.getVertexPtr(vert+START_VERTEX_NUM); vertexPtr->setColor(partition[vert]+1); // start colors at 1 } // clean up the space and return delete [] options; delete [] partition; delete [] xadj; delete [] adjncy; return 0; }
/** * Evaluates the Levenshtein distance between the strings `a` and `b` using the * Wagner-Fischer algorithm. This is the number of single-character edits * required to change the first string into the second. * * @param a[in] * the first string * @param b[in] * the second string * @param ignore_case[in,opt] * ignore differences in character case * @param print_matrix[in,opt] * print the matrix holding prefix distances to stdout * @return * the Levenshtein distance between `a` and `b` */ size_t levenshtein(char const* a, char const* b, bool ignore_case, bool print_matrix) { size_t len_a = strlen(a); //!< Length of string `a` size_t len_b = strlen(b); //!< Length of string `b` //! Adjacency matrix for holding edit distances between prefix strings. std::vector<size_t> adjacency((len_a + 1) * (len_b + 1), 0); //! Convenience function for setting and retreiving data in the matrix. auto idx = [&](size_t x, size_t y) -> size_t& { return adjacency[(len_a + 1) * y + x]; }; // Initialize the first row with the edit distance from the substring // prefixes of `a` to an empty string. for (size_t ii = 1; ii <= len_a; ++ii) { idx(ii, 0) = ii; } // Initialize the first column with the edit distance from the substring // prefixes of `b` to an empty string. for (size_t jj = 1; jj <= len_b; ++jj) { idx(0, jj) = jj; } for (size_t ii = 0; ii < len_a; ++ii) { for (size_t jj = 0; jj < len_b; ++jj) { //! Convert both characters to upper case if ignoring case. int ch_a = ignore_case ? std::toupper(a[ii]) : a[ii]; int ch_b = ignore_case ? std::toupper(b[jj]) : b[jj]; // If the characters match then there is no edit and the cost // is unchanged from the previous characters in both strings. if (ch_a == ch_b) { idx(ii + 1, jj + 1) = idx(ii, jj); } // Otherwise the cost is the minimum of the cost of deletion, // insertion, or substitution. else { size_t deletion_cost = idx(ii, jj + 1) + 1; size_t insertion_cost = idx(ii + 1, jj) + 1; size_t substitution_cost = idx(ii, jj) + 1; idx(ii + 1, jj + 1) = std::min({deletion_cost, insertion_cost, substitution_cost}); } } } // Print the adjacency matrix to stdout. if (print_matrix) { fprintf(stdout, " "); for (size_t jj = 0; jj < len_b; ++jj) { fprintf(stdout, " %1.1s ", b + jj); } fprintf(stdout, "\n"); for (size_t ii = 0; ii <= len_a; ++ii) { fprintf(stdout, " %1.1s ", ii ? a + ii - 1 : ""); for (size_t jj = 0; jj <= len_b; ++jj) { fprintf(stdout, "%2llu ", (unsigned long long)idx(ii, jj)); } fprintf(stdout, "\n"); } fprintf(stdout, "\n"); } // Return the edit distance from `a` to `b`. return idx(len_a, len_b); }
int main(void) { std::string filePath = "CNN-DocTermCountMatrix.txt"; Matrix& X_Ori = loadMatrix(filePath); int NSample = min(20, X_Ori.getRowDimension()); Matrix& X = X_Ori.getSubMatrix(0, NSample - 1, 0, X_Ori.getColumnDimension() - 1); // disp(X.getSubMatrix(0, 10, 0, 100)); println(sprintf("%d samples loaded", X.getRowDimension())); GraphOptions& options = *new GraphOptions(); options.graphType = "nn"; std::string type = options.graphType; double NN = options.graphParam; fprintf("Graph type: %s with NN: %d\n", type.c_str(), (int)NN); // Parameter setting for text data options.kernelType = "cosine"; options.graphDistanceFunction = "cosine"; // Parameter setting for image data /*options.kernelType = "rbf"; options.graphDistanceFunction = "euclidean";*/ options.graphNormalize = true; options.graphWeightType = "heat"; bool show = true && !false; // Test adjacency function - pass tic(); std::string DISTANCEFUNCTION = options.graphDistanceFunction; Matrix& A = adjacency(X, type, NN, DISTANCEFUNCTION); fprintf("Elapsed time: %.2f seconds.\n", toc()); std::string adjacencyFilePath = "adjacency.txt"; saveMatrix(adjacencyFilePath, A); if (show) disp(A.getSubMatrix(0, 4, 0, 4)); // Test laplacian function - pass tic(); Matrix& L = laplacian(X, type, options); fprintf("Elapsed time: %.2f seconds.\n", toc()); std::string LaplacianFilePath = "Laplacian.txt"; saveMatrix(LaplacianFilePath, L); if (show) disp(L.getSubMatrix(0, 4, 0, 4)); // Test local learning regularization - pass NN = options.graphParam; std::string DISTFUNC = options.graphDistanceFunction; std::string KernelType = options.kernelType; double KernelParam = options.kernelParam; double lambda = 0.001; tic(); Matrix& LLR_text = calcLLR(X, NN, DISTFUNC, KernelType, KernelParam, lambda); fprintf("Elapsed time: %.2f seconds.\n", toc()); std::string LLRFilePath = "localLearningRegularization.txt"; saveMatrix(LLRFilePath, LLR_text); if (show) display(LLR_text.getSubMatrix(0, 4, 0, 4)); return EXIT_SUCCESS; }
int DomainPartitioner::partition(int numParts, bool usingMain, int mainPartitionTag, int specialElementTag) { usingMainDomain = usingMain; mainPartition = mainPartitionTag; // first we ensure the partitioned domain has numpart subdomains // with tags 1 through numparts for (int i=1; i<=numParts; i++) { if (i != mainPartition) { Subdomain *subdomainPtr = myDomain->getSubdomainPtr(i); if (subdomainPtr == 0) { opserr << "DomainPartitioner::partition - No Subdomain: "; opserr << i << " exists\n"; return -1; } } } // we get the ele graph from the domain and partition it // Graph &theEleGraph = myDomain->getElementGraph(); // theElementGraph = new Graph(myDomain->getElementGraph()); theElementGraph = &(myDomain->getElementGraph()); int theError = thePartitioner.partition(*theElementGraph, numParts); if (theError < 0) { opserr << "DomainPartitioner::partition"; opserr << " - the graph partioner failed to partition the "; opserr << "element graph\n"; return -10+theError; } /* print graph */ // opserr << "DomainPartitioner::partition - eleGraph: \n"; // theElementGraph->Print(opserr, 4); VertexIter &theVertices1 = theElementGraph->getVertices(); Vertex *vertexPtr = 0; bool moreThanOne = false; vertexPtr = theVertices1(); int vertexOnePartition = 0; if (vertexPtr != 0) vertexOnePartition = vertexPtr->getColor(); while ((moreThanOne == false) && ((vertexPtr = theVertices1()) != 0)) { int partition = vertexPtr->getColor(); if (partition != vertexOnePartition ) { moreThanOne = true; } } if (moreThanOne == false) { opserr <<"DomainPartitioner::partition - too few elements for model to be partitioned\n"; return -1; } int specialElementColor = 1; if (specialElementTag != 0) { bool found = false; VertexIter &theVerticesSpecial = theElementGraph->getVertices(); while ((found == false) && ((vertexPtr = theVerticesSpecial()) != 0)) { int eleTag = vertexPtr->getRef(); if (eleTag == specialElementTag) { found = true; int vertexColor = vertexPtr->getColor(); if (vertexColor != 1) // specialElementColor = vertexColor; vertexPtr->setColor(1); } } } // we create empty graphs for the numParts subdomains, // in the graphs we place the vertices for the elements on the boundaries // we do not invoke the destructor on the individual graphs as // this would invoke the destructor on the individual vertices if (theBoundaryElements != 0) delete [] theBoundaryElements; theBoundaryElements = new Graph * [numParts]; if (theBoundaryElements == 0) { opserr << "DomainPartitioner::partition(int numParts)"; opserr << " - ran out of memory\n"; numPartitions = 0; return -1; } for (int l=0; l<numParts; l++) { theBoundaryElements[l] = new Graph(2048); // graphs can grow larger; just an estimate if (theBoundaryElements[l] == 0) { opserr << "DomainPartitioner::partition(int numParts)"; opserr << " - ran out of memory\n"; numPartitions = 0; return -1; } } numPartitions = numParts; // opserr << "DomainPartitioner::partition() - nodes \n"; // we now create a MapOfTaggedObjectStorage to store the NodeLocations // and create a new NodeLocation for each node; adding it to the map object theNodeLocations = new MapOfTaggedObjects(); if (theNodeLocations == 0) { opserr << "DomainPartitioner::partition(int numParts)"; opserr << " - ran out of memory creating MapOfTaggedObjectStorage for node locations\n"; numPartitions = 0; return -1; } NodeIter &theNodes = myDomain->getNodes(); Node *nodePtr; while ((nodePtr = theNodes()) != 0) { NodeLocations *theNodeLocation = new NodeLocations(nodePtr->getTag()); if (theNodeLocation == 0) { opserr << "DomainPartitioner::partition(int numParts)"; opserr << " - ran out of memory creating NodeLocation for node: " << nodePtr->getTag() << endln; numPartitions = 0; return -1; } if (theNodeLocations->addComponent(theNodeLocation) == false) { opserr << "DomainPartitioner::partition(int numParts)"; opserr << " - failed to add NodeLocation to Map for Node: " << nodePtr->getTag() << endln; numPartitions = 0; return -1; } } // // we now iterate through the vertices of the element graph // to see if the vertex is a boundary vertex or not - if it is // we add to the appropriate graph created above. We also set the // value the color variable of each of the external nodes connected // to the element to a value which will indicate that that node will // have to be added to the subdomain. // VertexIter &theVertexIter = theElementGraph->getVertices(); while ((vertexPtr = theVertexIter()) != 0) { int eleTag = vertexPtr->getRef(); int vertexColor = vertexPtr->getColor(); const ID &adjacency = vertexPtr->getAdjacency(); int size = adjacency.Size(); for (int i=0; i<size; i++) { Vertex *otherVertex = theElementGraph->getVertexPtr(adjacency(i)); if (otherVertex->getColor() != vertexColor) { theBoundaryElements[vertexColor-1]->addVertex(vertexPtr,false); i = size; } } Element *elePtr = myDomain->getElement(eleTag); const ID &nodes = elePtr->getExternalNodes(); size = nodes.Size(); for (int j=0; j<size; j++) { int nodeTag = nodes(j); TaggedObject *theTaggedObject = theNodeLocations->getComponentPtr(nodeTag); if (theTaggedObject == 0) { opserr << "DomainPartitioner::partition(int numParts)"; opserr << " - failed to find NodeLocation in Map for Node: " << nodePtr->getTag() << " -- A BUG!!\n"; numPartitions = 0; return -1; } NodeLocations *theNodeLocation = (NodeLocations *)theTaggedObject; theNodeLocation->addPartition(vertexColor); } } // now go through the MP_Constraints and ensure the retained node is in every // partition the constrained node is in MP_ConstraintIter &theMPs = myDomain->getMPs(); MP_Constraint *mpPtr; while ((mpPtr = theMPs()) != 0) { int retained = mpPtr->getNodeRetained(); int constrained = mpPtr->getNodeConstrained(); TaggedObject *theRetainedObject = theNodeLocations->getComponentPtr(retained); TaggedObject *theConstrainedObject = theNodeLocations->getComponentPtr(constrained); if (theRetainedObject == 0 || theConstrainedObject == 0) { opserr << "DomainPartitioner::partition(int numParts)"; if (theRetainedObject == 0) opserr << " - failed to find NodeLocation in Map for Node: " << retained << " -- A BUG!!\n"; if (theConstrainedObject == 0) opserr << " - failed to find NodeLocation in Map for Node: " << constrained << " -- A BUG!!\n"; numPartitions = 0; return -1; } NodeLocations *theRetainedLocation = (NodeLocations *)theRetainedObject; NodeLocations *theConstrainedLocation = (NodeLocations *)theConstrainedObject; ID &theConstrainedNodesPartitions = theConstrainedLocation->nodePartitions; int numPartitions = theConstrainedNodesPartitions.Size(); for (int i=0; i<numPartitions; i++) { theRetainedLocation->addPartition(theConstrainedNodesPartitions(i)); } } // we now add the nodes, TaggedObjectIter &theNodeLocationIter = theNodeLocations->getComponents(); TaggedObject *theNodeObject; while ((theNodeObject = theNodeLocationIter()) != 0) { NodeLocations *theNodeLocation = (NodeLocations *)theNodeObject; int nodeTag = theNodeLocation->getTag(); ID &nodePartitions = theNodeLocation->nodePartitions; int numPartitions = theNodeLocation->numPartitions; for (int i=0; i<numPartitions; i++) { int partition = nodePartitions(i); if (partition != mainPartition) { Subdomain *theSubdomain = myDomain->getSubdomainPtr(partition); if (numPartitions == 1) { Node *nodePtr = myDomain->removeNode(nodeTag); theSubdomain->addNode(nodePtr); } else { Node *nodePtr = myDomain->getNode(nodeTag); theSubdomain->addExternalNode(nodePtr); } } } } // we now move the elements VertexIter &theVertices = theElementGraph->getVertices(); while ((vertexPtr = theVertices()) != 0) { // move the element int partition = vertexPtr->getColor(); if (partition != mainPartition) { int eleTag = vertexPtr->getRef(); // opserr << "removing ele: " << eleTag << endln; Element *elePtr = myDomain->removeElement(eleTag); // opserr << *elePtr; if (elePtr != 0) { // opserr << "adding ele - start\n"; Subdomain *theSubdomain = myDomain->getSubdomainPtr(partition); theSubdomain->addElement(elePtr); // opserr << "adding ele - done\n"; } else { opserr << "DomainPartitioner::partioner - element GONE! - eleTag " << eleTag << endln; } } } // now we go through the load patterns and move NodalLoad // 1) make sure each subdomain has a copy of the partitioneddomains load patterns. // 2) move nodal loads // 3) move SP_Constraints LoadPatternIter &theLoadPatterns = myDomain->getLoadPatterns(); LoadPattern *theLoadPattern; while ((theLoadPattern = theLoadPatterns()) != 0) { int loadPatternTag = theLoadPattern->getTag(); // check that each subdomain has a loadPattern with a similar tag and class tag for (int i=1; i<=numParts; i++) { if (i != mainPartition) { Subdomain *theSubdomain = myDomain->getSubdomainPtr(i); LoadPattern *loadPatternCopy = theSubdomain->getLoadPattern(loadPatternTag); if (loadPatternCopy == 0) { LoadPattern *newLoadPattern = theLoadPattern->getCopy(); if (newLoadPattern == 0) { opserr << "DomaiPartitioner::partition - out of memory creating LoadPatterns\n"; return -1; } theSubdomain->addLoadPattern(newLoadPattern); } } } // now remove any nodal loads that correspond to internal nodes in a subdomain // and add them to the appropriate loadpattern in the subdomain NodalLoadIter &theNodalLoads = theLoadPattern->getNodalLoads(); NodalLoad *theNodalLoad; while ((theNodalLoad = theNodalLoads()) != 0) { int nodeTag = theNodalLoad->getNodeTag(); TaggedObject *theTaggedObject = theNodeLocations->getComponentPtr(nodeTag); if (theTaggedObject == 0) { opserr << "DomainPartitioner::partition(int numParts)"; opserr << " - failed to find NodeLocation in Map for Node: " << nodeTag << " -- A BUG!!\n"; numPartitions = 0; return -1; } NodeLocations *theNodeLocation = (NodeLocations *)theTaggedObject; ID &nodePartitions = theNodeLocation->nodePartitions; int numPartitions = theNodeLocation->numPartitions; for (int i=0; i<numPartitions; i++) { int partition = nodePartitions(i); if (partition != mainPartition) { if (numPartitions == 1) { Subdomain *theSubdomain = myDomain->getSubdomainPtr(partition); theLoadPattern->removeNodalLoad(theNodalLoad->getTag()); if ((theSubdomain->addNodalLoad(theNodalLoad, loadPatternTag)) != true) opserr << "DomainPartitioner::partition() - failed to add Nodal Load\n"; } } } } SP_ConstraintIter &theSPs = theLoadPattern->getSPs(); SP_Constraint *spPtr; while ((spPtr = theSPs()) != 0) { int nodeTag = spPtr->getNodeTag(); TaggedObject *theTaggedObject = theNodeLocations->getComponentPtr(nodeTag); if (theTaggedObject == 0) { opserr << "DomainPartitioner::partition(int numParts)"; opserr << " - failed to find NodeLocation in Map for Node: " << nodeTag << " -- A BUG!!\n"; numPartitions = 0; return -1; } NodeLocations *theNodeLocation = (NodeLocations *)theTaggedObject; ID &nodePartitions = theNodeLocation->nodePartitions; int numPartitions = theNodeLocation->numPartitions; for (int i=0; i<numPartitions; i++) { int partition = nodePartitions(i); if (partition != mainPartition) { Subdomain *theSubdomain = myDomain->getSubdomainPtr(partition); if (numPartitions == 1) theLoadPattern->removeSP_Constraint(spPtr->getTag()); int res = theSubdomain->addSP_Constraint(spPtr, loadPatternTag); if (res < 0) opserr << "DomainPartitioner::partition() - failed to add SP Constraint\n"; } } } ElementalLoadIter &theLoads = theLoadPattern->getElementalLoads(); ElementalLoad *theLoad; while ((theLoad = theLoads()) != 0) { int loadEleTag = theLoad->getElementTag(); SubdomainIter &theSubdomains = myDomain->getSubdomains(); Subdomain *theSub; bool added = false; while (((theSub = theSubdomains()) != 0) && (added == false)) { bool res = theSub->hasElement(loadEleTag); if (res == true) { theLoadPattern->removeElementalLoad(theLoad->getTag()); theSub->addElementalLoad(theLoad, loadPatternTag); if (res < 0) opserr << "DomainPartitioner::partition() - failed to add ElementalLoad\n"; added = true; } } } } // add the single point constraints, SP_ConstraintIter &theDomainSP = myDomain->getSPs(); SP_Constraint *spPtr; while ((spPtr = theDomainSP()) != 0) { int nodeTag = spPtr->getNodeTag(); TaggedObject *theTaggedObject = theNodeLocations->getComponentPtr(nodeTag); if (theTaggedObject == 0) { opserr << "DomainPartitioner::partition(int numParts)"; opserr << " - failed to find NodeLocation in Map for Node: " << nodeTag << " -- A BUG!!\n"; numPartitions = 0; return -1; } NodeLocations *theNodeLocation = (NodeLocations *)theTaggedObject; ID &nodePartitions = theNodeLocation->nodePartitions; int numPartitions = theNodeLocation->numPartitions; for (int i=0; i<numPartitions; i++) { int partition = nodePartitions(i); if (partition != mainPartition) { Subdomain *theSubdomain = myDomain->getSubdomainPtr(partition); if (numPartitions == 1) { myDomain->removeSP_Constraint(spPtr->getTag()); } int res = theSubdomain->addSP_Constraint(spPtr); if (res < 0) opserr << "DomainPartitioner::partition() - failed to add SP Constraint\n"; } } } // move MP_Constraints - add an MP_Constraint to every partition a constrained node is in MP_ConstraintIter &moreMPs = myDomain->getMPs(); while ((mpPtr = moreMPs()) != 0) { int constrained = mpPtr->getNodeConstrained(); TaggedObject *theConstrainedObject = theNodeLocations->getComponentPtr(constrained); NodeLocations *theConstrainedLocation = (NodeLocations *)theConstrainedObject; ID &theConstrainedNodesPartitions = theConstrainedLocation->nodePartitions; int numPartitions = theConstrainedLocation->numPartitions; for (int i=0; i<numPartitions; i++) { int partition = theConstrainedNodesPartitions(i); if (partition != mainPartition) { Subdomain *theSubdomain = myDomain->getSubdomainPtr(partition); if (numPartitions == 1) myDomain->removeMP_Constraint(mpPtr->getTag()); int res = theSubdomain->addMP_Constraint(mpPtr); if (res < 0) opserr << "DomainPartitioner::partition() - failed to add MP Constraint\n"; } } } // now we go through all the subdomains and tell them to update // their analysis for the new layouts SubdomainIter &theSubDomains = myDomain->getSubdomains(); Subdomain *theSubDomain; while ((theSubDomain = theSubDomains()) != 0) theSubDomain->domainChange(); // we invoke change on the PartitionedDomain myDomain->domainChange(); myDomain->clearElementGraph(); // we are done partitionFlag = true; return 0; }
void tomSimilarity(double * expr, int * nSamples, int * nGenes, int * corType, int * adjType, double * power, int * tomType, int * denomType, double * maxPOutliers, double * quick, int * fallback, int * cosine, int * replaceMissing, double * tom, int * warn, int * nThreads, int * verbose, int * indent) { // Rprintf("Starting tomSimilarity...\n"); double * adj; int ng = *nGenes, ns = *nSamples; size_t matSize = ( (size_t)ng) * ( (size_t) ng); int err = 0; char spaces[2* *indent+1]; for (int i=0; i<2* *indent; i++) spaces[i] = ' '; spaces[2* *indent] = '\0'; /* int size=4000; int success = 0; double * pt; while ( (pt=malloc(size*size*sizeof(double)))!=NULL ) { size+=1000; success = 1; free(pt); } size -= 1000; if ((*verbose > 0) && success) Rprintf("%sRough guide to maximum array size: about %d x %d array of doubles..\n", spaces, size, size); */ if (*verbose > 0) Rprintf("%sTOM calculation: adjacency..\n", spaces); if (* tomType==TomTypeNone) // just calculate adjacency. { adjacency(expr, ns, ng, *corType, *adjType, *power, *maxPOutliers, *quick, *fallback, *cosine, *replaceMissing, tom, &err, warn, nThreads, *verbose, *indent); if (*verbose > 0) Rprintf("\n"); if (err) error(AdjErrors[err]); return; } if ((adj = malloc(matSize * sizeof(double))) == NULL) error("Memmory allocation error."); if ((* tomType == TomTypeSigned) && (* adjType == AdjTypeUnsigned)) * adjType = AdjTypeUnsignedKeepSign; if ((* tomType == TomTypeUnsigned) && (* adjType == AdjTypeUnsignedKeepSign)) * adjType = AdjTypeUnsigned; adjacency(expr, ns, ng, * corType, * adjType, * power, * maxPOutliers, * quick, *fallback, *cosine, *replaceMissing, adj, & err, warn, nThreads, *verbose, *indent); // Rprintf("TOM 1\n"); if (err) { Rprintf("TOM: exit because 'adjacency' reported an error.\n"); free(adj); error(AdjErrors[err]); } else { tomSimilarityFromAdj(adj, nGenes, tomType, denomType, tom, verbose, indent); free(adj); } }
const ID & MyRCM::number(Graph &theGraph, int startVertex) { // first check our size, if not same make new if (numVertex != theGraph.getNumVertex()) { // delete the old if (theRefResult != 0) delete theRefResult; numVertex = theGraph.getNumVertex(); theRefResult = new ID(numVertex); if (theRefResult == 0) { opserr << "ERROR: MyRCM::number - Out of Memory\n"; theRefResult = new ID(0); numVertex = 0; return *theRefResult; } } // see if we can do quick return if (numVertex == 0) return *theRefResult; // we first set the Tmp of all vertices to -1, indicating // they have not yet been added. Vertex *vertexPtr; VertexIter &vertexIter = theGraph.getVertices(); while ((vertexPtr = vertexIter()) != 0) vertexPtr->setTmp(-1); // we now set up; setting our markers and getting first vertex if (startVertex != -1) startVertexTag = startVertex; if (startVertexTag != -1) { vertexPtr = theGraph.getVertexPtr(startVertexTag); if (vertexPtr == 0) { opserr << "WARNING: MyRCM::number - No vertex with tag "; opserr << startVertexTag << "Exists - using first come from iter\n"; startVertexTag = -1; } } // if no starting vertex use the first one we get from the VertexIter VertexIter &vertexIter2 = theGraph.getVertices(); if (startVertexTag == -1) vertexPtr = vertexIter2(); int currentMark = numVertex-1; // marks current vertex visiting. int nextMark = currentMark -1; // indiactes where to put next Tag in ID. (*theRefResult)(currentMark) = vertexPtr->getTag(); vertexPtr->setTmp(currentMark); // we continue till the ID is full while (nextMark >= 0) { // get the current vertex and its adjacency vertexPtr = theGraph.getVertexPtr((*theRefResult)(currentMark)); const ID &adjacency = vertexPtr->getAdjacency(); // go through the vertices adjacency and add vertices which // have not yet been Tmp'ed to the (*theRefResult) int size = adjacency.Size(); for (int i=0; i<size; i++) { int vertexTag = adjacency(i); vertexPtr = theGraph.getVertexPtr(vertexTag); if ((vertexPtr->getTmp()) == -1) { vertexPtr->setTmp(nextMark); (*theRefResult)(nextMark--) = vertexTag; } } // go to the next vertex // we decrement because we are doing reverse Cuthill-McKee currentMark--; // check to see if graph is disconneted if ((currentMark == nextMark) && (currentMark >= 0)) { opserr << "WARNING: MyRCM::number - Disconnected graph\n"; // loop over iter till we get a vertex not yet Tmped while (((vertexPtr = vertexIter2()) != 0) && (vertexPtr->getTmp() != -1)) ; nextMark--; vertexPtr->setTmp(currentMark); (*theRefResult)(currentMark) = vertexPtr->getTag(); } } // now set the vertex references instead of the vertex tags // in the result, we change the Tmp to indicate number and return for (int i=0; i<numVertex; i++) { int vertexTag = (*theRefResult)(i); vertexPtr = theGraph.getVertexPtr(vertexTag); vertexPtr->setTmp(i+1); // 1 through numVertex (*theRefResult)(i) = vertexPtr->getTag(); } theGraph.Print(opserr, 3); opserr << *theRefResult; return *theRefResult; }
const ID & MyRCM::number(Graph &theGraph, const ID &startVertices) { // first check our size, if not same make new if (numVertex != theGraph.getNumVertex()) { // delete the old if (theRefResult != 0) delete theRefResult; numVertex = theGraph.getNumVertex(); theRefResult = new ID(numVertex); if (theRefResult == 0) { opserr << "ERROR: MyRCM::number - Out of Memory\n"; theRefResult = new ID(0); numVertex = 0; return *theRefResult; } } // see if we can do quick return if (numVertex == 0) return *theRefResult; ID copyStart(startVertices); // we determine which node to start with int minStartVertexTag =0; int minAvgProfile = 0; int startVerticesSize = startVertices.Size(); for (int j=0; j<startVerticesSize; j++) { // we first set the Tmp of all vertices to -1, indicating // they have not yet been added. Vertex *vertexPtr; VertexIter &vertexIter = theGraph.getVertices(); while ((vertexPtr = vertexIter()) != 0) vertexPtr->setTmp(-1); // we now set up; setting our markers and set first vertices VertexIter &vertexIter2 = theGraph.getVertices(); int currentMark = numVertex-1; // marks current vertex visiting. int nextMark = currentMark-1; for (int k=0; k<startVerticesSize; k++) if (k != j) copyStart(k) = 0; else copyStart(k) = 1; vertexPtr = theGraph.getVertexPtr(startVertices(j)); (*theRefResult)(currentMark) = vertexPtr->getTag(); vertexPtr->setTmp(currentMark); int numFromStart = 1; int avgProfile = 1; while (numFromStart < startVerticesSize) { // get the current vertex and its adjacency vertexPtr = theGraph.getVertexPtr((*theRefResult)(currentMark)); const ID &adjacency = vertexPtr->getAdjacency(); // go through the vertices adjacency and add vertices which // have not yet been Tmp'ed to the (*theRefResult) int size = adjacency.Size(); for (int i=0; i<size; i++) { int vertexTag = adjacency(i); int loc =startVertices.getLocation(vertexTag); if (loc >= 0) { vertexPtr = theGraph.getVertexPtr(vertexTag); if ((vertexPtr->getTmp()) == -1) { vertexPtr->setTmp(nextMark); copyStart(loc) = 1; numFromStart++; avgProfile += currentMark - nextMark; (*theRefResult)(nextMark--) = vertexTag; } } } // go to the next vertex // we decrement because we are doing reverse Cuthill-McKee currentMark--; // check to see if graph is disconneted if (currentMark == nextMark && numFromStart < startVerticesSize) { // loop over iter till we get a vertex not yet included for (int l=0; l<startVerticesSize; l++) if (copyStart(l) == 0) { int vertexTag = startVertices(l); vertexPtr = theGraph.getVertexPtr(vertexTag); nextMark--; copyStart(l) = 1; vertexPtr->setTmp(currentMark); numFromStart++; (*theRefResult)(currentMark) = vertexPtr->getTag(); l =startVerticesSize; } } } currentMark = numVertex-1; // set current to the first again nextMark = numVertex - startVerticesSize -1; // we continue till the ID is full while (nextMark >= 0) { // get the current vertex and its adjacency vertexPtr = theGraph.getVertexPtr((*theRefResult)(currentMark)); const ID &adjacency = vertexPtr->getAdjacency(); // go through the vertices adjacency and add vertices which // have not yet been Tmp'ed to the (*theRefResult) int size = adjacency.Size(); for (int i=0; i<size; i++) { int vertexTag = adjacency(i); vertexPtr = theGraph.getVertexPtr(vertexTag); if ((vertexPtr->getTmp()) == -1) { vertexPtr->setTmp(nextMark); avgProfile += currentMark - nextMark; (*theRefResult)(nextMark--) = vertexTag; } } // go to the next vertex // we decrement because we are doing reverse Cuthill-McKee currentMark--; // check to see if graph is disconneted if ((currentMark == nextMark) && (currentMark >= 0)) { // loop over iter till we get a vertex not yet Tmped while (((vertexPtr = vertexIter2()) != 0) && (vertexPtr->getTmp() != -1)) ; nextMark--; vertexPtr->setTmp(currentMark); (*theRefResult)(currentMark) = vertexPtr->getTag(); } } if (j == 0 || minAvgProfile > avgProfile) { minStartVertexTag = startVertices(j); minAvgProfile = avgProfile; } } // now we numebr based on minStartVErtexTag // we first set the Tmp of all vertices to -1, indicating // they have not yet been added. Vertex *vertexPtr; VertexIter &vertexIter = theGraph.getVertices(); while ((vertexPtr = vertexIter()) != 0) vertexPtr->setTmp(-1); // we now set up; setting our markers and set first vertices VertexIter &vertexIter2 = theGraph.getVertices(); int currentMark = numVertex-1; // marks current vertex visiting. int nextMark = currentMark-1; vertexPtr = theGraph.getVertexPtr(minStartVertexTag); (*theRefResult)(currentMark) = vertexPtr->getTag(); vertexPtr->setTmp(currentMark); currentMark--; int loc = startVertices.getLocation(minStartVertexTag); for (int k=0; k<startVerticesSize; k++) if (k != loc) copyStart(k) = 0; int numFromStart = 1; while (numFromStart < startVerticesSize) { // get the current vertex and its adjacency vertexPtr = theGraph.getVertexPtr((*theRefResult)(currentMark)); const ID &adjacency = vertexPtr->getAdjacency(); // go through the vertices adjacency and add vertices which // have not yet been Tmp'ed to the (*theRefResult) int size = adjacency.Size(); for (int i=0; i<size; i++) { int vertexTag = adjacency(i); int loc =startVertices.getLocation(vertexTag); if (loc >= 0) { vertexPtr = theGraph.getVertexPtr(vertexTag); if ((vertexPtr->getTmp()) == -1) { vertexPtr->setTmp(nextMark); copyStart(loc) = 1; numFromStart++; (*theRefResult)(nextMark--) = vertexTag; } } } // go to the next vertex // we decrement because we are doing reverse Cuthill-McKee currentMark--; // check to see if graph is disconneted if (currentMark == nextMark && numFromStart < startVerticesSize) { // loop over iter till we get a vertex not yet included for (int l=0; l<startVerticesSize; l++) if (copyStart(l) == 0) { int vertexTag = startVertices(l); vertexPtr = theGraph.getVertexPtr(vertexTag); nextMark--; copyStart(l) = 1; vertexPtr->setTmp(currentMark); numFromStart++; (*theRefResult)(currentMark) = vertexPtr->getTag(); l =startVerticesSize; } } } currentMark = numVertex-1; // set current to the first again nextMark = numVertex - startVerticesSize -1; currentMark = numVertex-1; // set current to the first again // we continue till the ID is full while (nextMark >= 0) { // get the current vertex and its adjacency vertexPtr = theGraph.getVertexPtr((*theRefResult)(currentMark)); const ID &adjacency = vertexPtr->getAdjacency(); // go through the vertices adjacency and add vertices which // have not yet been Tmp'ed to the (*theRefResult) int size = adjacency.Size(); for (int i=0; i<size; i++) { int vertexTag = adjacency(i); vertexPtr = theGraph.getVertexPtr(vertexTag); if ((vertexPtr->getTmp()) == -1) { vertexPtr->setTmp(nextMark); (*theRefResult)(nextMark--) = vertexTag; } } // go to the next vertex // we decrement because we are doing reverse Cuthill-McKee currentMark--; // check to see if graph is disconneted if ((currentMark == nextMark) && (currentMark >= 0)) { opserr << "WARNING: MyRCM::number - Disconnected graph "; // loop over iter till we get a vertex not yet Tmped while (((vertexPtr = vertexIter2()) != 0) && (vertexPtr->getTmp() != -1)) ; nextMark--; vertexPtr->setTmp(currentMark); (*theRefResult)(currentMark) = vertexPtr->getTag(); } } // now set the vertex references instead of the vertex tags // in the result, we change the Tmp to indicate number and return for (int m=0; m<numVertex; m++) { int vertexTag = (*theRefResult)(m); vertexPtr = theGraph.getVertexPtr(vertexTag); vertexPtr->setTmp(m+1); // 1 through numVertex (*theRefResult)(m) = vertexPtr->getTag(); } return *theRefResult; }