xref: /petsc/src/dm/impls/network/networkview.c (revision 6e4289a0dd4d962ed977e39cfbc50d2f2c3b3d96)
1 #include <petsc/private/dmnetworkimpl.h> /*I  "petscdmnetwork.h"  I*/
2 
3 static PetscErrorCode DMView_Network_CSV(DM dm, PetscViewer viewer)
4 {
5   DM              dmcoords;
6   PetscInt        nsubnets, i, subnet, nvertices, nedges, vertex, edge;
7   PetscInt        vertexOffsets[2], globalEdgeVertices[2];
8   PetscScalar     vertexCoords[2];
9   const PetscInt *vertices, *edges, *edgeVertices;
10   Vec             allVertexCoords;
11   PetscMPIInt     rank;
12   MPI_Comm        comm;
13 
14   PetscFunctionBegin;
15   // Get the network containing coordinate information
16   PetscCall(DMGetCoordinateDM(dm, &dmcoords));
17   // Get the coordinate vector for the network
18   PetscCall(DMGetCoordinatesLocal(dm, &allVertexCoords));
19   // Get the MPI communicator and this process' rank
20   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
21   PetscCallMPI(MPI_Comm_rank(comm, &rank));
22   // Start synchronized printing
23   PetscCall(PetscViewerASCIIPushSynchronized(viewer));
24 
25   // Write the header
26   PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "Type,Rank,ID,X,Y,Z,Name,Color\n"));
27 
28   // Iterate each subnetwork (Note: We need to get the global number of subnets apparently)
29   PetscCall(DMNetworkGetNumSubNetworks(dm, NULL, &nsubnets));
30   for (subnet = 0; subnet < nsubnets; subnet++) {
31     // Get the subnetwork's vertices and edges
32     PetscCall(DMNetworkGetSubnetwork(dm, subnet, &nvertices, &nedges, &vertices, &edges));
33 
34     // Write out each vertex
35     for (i = 0; i < nvertices; i++) {
36       vertex = vertices[i];
37       // Get the offset into the coordinate vector for the vertex
38       PetscCall(DMNetworkGetLocalVecOffset(dmcoords, vertex, ALL_COMPONENTS, vertexOffsets));
39       vertexOffsets[1] = vertexOffsets[0] + 1;
40       // Remap vertex to the global value
41       PetscCall(DMNetworkGetGlobalVertexIndex(dm, vertex, &vertex));
42       // Get the vertex position from the coordinate vector
43       PetscCall(VecGetValues(allVertexCoords, 2, vertexOffsets, vertexCoords));
44 
45       // TODO: Determine vertex color/name
46       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "Node,%" PetscInt_FMT ",%" PetscInt_FMT ",%lf,%lf,0,%" PetscInt_FMT "\n", (PetscInt)rank, vertex, (double)PetscRealPart(vertexCoords[0]), (double)PetscRealPart(vertexCoords[1]), vertex));
47     }
48 
49     // Write out each edge
50     for (i = 0; i < nedges; i++) {
51       edge = edges[i];
52       PetscCall(DMNetworkGetConnectedVertices(dm, edge, &edgeVertices));
53       PetscCall(DMNetworkGetGlobalVertexIndex(dm, edgeVertices[0], &globalEdgeVertices[0]));
54       PetscCall(DMNetworkGetGlobalVertexIndex(dm, edgeVertices[1], &globalEdgeVertices[1]));
55       PetscCall(DMNetworkGetGlobalEdgeIndex(dm, edge, &edge));
56 
57       // TODO: Determine edge color/name
58       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "Edge,%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ",0,%" PetscInt_FMT "\n", (PetscInt)rank, edge, globalEdgeVertices[0], globalEdgeVertices[1], edge));
59     }
60   }
61   // End synchronized printing
62   PetscCall(PetscViewerFlush(viewer));
63   PetscCall(PetscViewerASCIIPopSynchronized(viewer));
64   PetscFunctionReturn(PETSC_SUCCESS);
65 }
66 
67 #include <petscdraw.h>
68 static PetscErrorCode DMView_Network_Matplotlib(DM dm, PetscViewer viewer)
69 {
70   PetscMPIInt rank, size, rank2;
71   MPI_Comm    comm;
72   char        filename[PETSC_MAX_PATH_LEN + 1], proccall[PETSC_MAX_PATH_LEN + 500], scriptFile[PETSC_MAX_PATH_LEN + 1], streamBuffer[256];
73   PetscViewer csvViewer;
74   FILE       *processFile = NULL;
75   PetscBool   isnull;
76   PetscDraw   draw;
77 
78   PetscFunctionBegin;
79   // Deal with the PetscDraw we are given
80   PetscCall(PetscViewerDrawGetDraw(viewer, 1, &draw));
81   PetscCall(PetscDrawIsNull(draw, &isnull));
82   PetscCall(PetscDrawSetVisible(draw, PETSC_FALSE));
83 
84   // Clear the file name buffer so all communicated bytes are well-defined
85   PetscCall(PetscMemzero(filename, sizeof(filename)));
86 
87   // Get the MPI communicator and this process' rank
88   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
89   PetscCallMPI(MPI_Comm_rank(comm, &rank));
90   PetscCallMPI(MPI_Comm_size(comm, &size));
91 
92   // Generate and broadcast the temporary file name from rank 0
93   if (rank == 0) {
94 #if defined(PETSC_HAVE_TMPNAM_S)
95     // Acquire a temporary file to write to and open an ASCII/CSV viewer
96     PetscCheck(tmpnam_s(filename, sizeof(filename)) == 0, comm, PETSC_ERR_SYS, "Could not acquire temporary file");
97 #elif defined(PETSC_HAVE_MKSTEMP) && __STDC_VERSION__ > 199901L
98     PetscBool isSharedTmp, isTmpOverridden;
99     size_t    numChars;
100     // Same thing, but for POSIX systems on which tmpnam is deprecated
101     // Note: Configure may detect mkstemp but it will not be defined if compiling for C99, so check additional defines to see if we can use it
102     // Mkstemp requires us to explicitly specify part of the path, but some systems may not like putting files in /tmp/ so have an option for it
103     PetscCall(PetscOptionsGetString(NULL, NULL, "-dmnetwork_view_tmpdir", filename, sizeof(filename), &isTmpOverridden));
104     // If not specified by option try using a shared tmp on the system
105     if (!isTmpOverridden) {
106       PetscCall(PetscGetTmp(comm, filename, sizeof(filename)));
107       PetscCall(PetscSharedTmp(comm, &isSharedTmp));
108     }
109     // Validate that if tmp is not overridden it is at least shared
110     PetscCheck(isTmpOverridden || isSharedTmp, comm, PETSC_ERR_SUP_SYS, "Temporary file directory is not shared between ranks, try using -dmnetwork_view_tmpdir to specify a shared directory");
111     // Make sure the filename ends with a '/'
112     PetscCall(PetscStrlen(filename, &numChars));
113     if (filename[numChars - 1] != '/') {
114       filename[numChars]     = '/';
115       filename[numChars + 1] = 0;
116     }
117     // Perform the actual temporary file creation
118     PetscCall(PetscStrlcat(filename, "XXXXXX", sizeof(filename)));
119     PetscCheck(mkstemp(filename) != -1, comm, PETSC_ERR_SYS, "Could not acquire temporary file");
120 #else
121     // Same thing, but for older C versions which don't have the safe form
122     PetscCheck(tmpnam(filename) != NULL, comm, PETSC_ERR_SYS, "Could not acquire temporary file");
123 #endif
124     // Broadcast the filename to all other MPI ranks
125     for (rank2 = 1; rank2 < size; rank2++) PetscCallMPI(MPI_Send(filename, PETSC_MAX_PATH_LEN, MPI_BYTE, rank2, 0, comm));
126   } else {
127     // Receive the file name
128     PetscCallMPI(MPI_Recv(filename, PETSC_MAX_PATH_LEN, MPI_BYTE, 0, 0, comm, MPI_STATUS_IGNORE));
129   }
130 
131   PetscCall(PetscViewerASCIIOpen(PETSC_COMM_WORLD, filename, &csvViewer));
132   PetscCall(PetscViewerPushFormat(csvViewer, PETSC_VIEWER_ASCII_CSV));
133 
134   // Use the CSV viewer to write out the local network
135   PetscCall(DMView_Network_CSV(dm, csvViewer));
136 
137   // Close the viewer
138   PetscCall(PetscViewerDestroy(&csvViewer));
139 
140   // Get the value of $PETSC_DIR
141   PetscCall(PetscStrreplace(PETSC_COMM_WORLD, "${PETSC_DIR}/share/petsc/bin/dmnetwork_view.py", scriptFile, sizeof(scriptFile)));
142   PetscCall(PetscFixFilename(scriptFile, scriptFile));
143   // Generate the system call for 'python3 $PETSC_DIR/share/petsc/dmnetwork_view.py <file>'
144   PetscCall(PetscArrayzero(proccall, sizeof(proccall)));
145   PetscCall(PetscSNPrintf(proccall, sizeof(proccall), "%s %s %s %s", PETSC_PYTHON_EXE, scriptFile, (isnull ? "-tx" : ""), filename));
146 
147 #if defined(PETSC_HAVE_POPEN)
148   // Perform the call to run the python script (Note: while this is called on all ranks POpen will only run on rank 0)
149   PetscCall(PetscPOpen(PETSC_COMM_WORLD, NULL, proccall, "r", &processFile));
150   if (processFile != NULL) {
151     while (fgets(streamBuffer, sizeof(streamBuffer), processFile) != NULL) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "%s", streamBuffer));
152   }
153   PetscCall(PetscPClose(PETSC_COMM_WORLD, processFile));
154 #else
155   // Same thing, but using the standard library for systems that don't have POpen/PClose (only run on rank 0)
156   if (rank == 0) {
157     PetscCheck(system(proccall) == 0, comm, PETSC_ERR_SYS, "Failed to call viewer script");
158     // Barrier so that all ranks wait until the call completes
159     PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
160   }
161 #endif
162   // Clean up the temporary file we used using rank 0
163   if (rank == 0) PetscCheck(remove(filename) == 0, comm, PETSC_ERR_SYS, "Failed to delete temporary file");
164   PetscFunctionReturn(PETSC_SUCCESS);
165 }
166 
167 PetscErrorCode DMView_Network(DM dm, PetscViewer viewer)
168 {
169   PetscBool         iascii, isdraw;
170   PetscViewerFormat format;
171 
172   PetscFunctionBegin;
173   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
174   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
175   PetscCall(PetscViewerGetFormat(viewer, &format));
176 
177   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
178   if (isdraw) {
179     PetscCall(DMView_Network_Matplotlib(dm, viewer));
180     PetscFunctionReturn(PETSC_SUCCESS);
181   }
182 
183   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
184   if (iascii) {
185     const PetscInt *cone, *vtx, *edges;
186     PetscInt        vfrom, vto, i, j, nv, ne, nsv, p, nsubnet;
187     DM_Network     *network = (DM_Network *)dm->data;
188     PetscMPIInt     rank;
189 
190     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
191     if (format == PETSC_VIEWER_ASCII_CSV) {
192       PetscCall(DMView_Network_CSV(dm, viewer));
193       PetscFunctionReturn(PETSC_SUCCESS);
194     }
195 
196     nsubnet = network->cloneshared->Nsubnet; /* num of subnetworks */
197     if (!rank) {
198       PetscCall(PetscPrintf(PETSC_COMM_SELF, "  NSubnets: %" PetscInt_FMT "; NEdges: %" PetscInt_FMT "; NVertices: %" PetscInt_FMT "; NSharedVertices: %" PetscInt_FMT ".\n", nsubnet, network->cloneshared->NEdges, network->cloneshared->NVertices,
199                             network->cloneshared->Nsvtx));
200     }
201 
202     PetscCall(DMNetworkGetSharedVertices(dm, &nsv, NULL));
203     PetscCall(PetscViewerASCIIPushSynchronized(viewer));
204     PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "  [%d] nEdges: %" PetscInt_FMT "; nVertices: %" PetscInt_FMT "; nSharedVertices: %" PetscInt_FMT "\n", rank, network->cloneshared->nEdges, network->cloneshared->nVertices, nsv));
205 
206     for (i = 0; i < nsubnet; i++) {
207       PetscCall(DMNetworkGetSubnetwork(dm, i, &nv, &ne, &vtx, &edges));
208       if (ne) {
209         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "     Subnet %" PetscInt_FMT ": nEdges %" PetscInt_FMT ", nVertices(include shared vertices) %" PetscInt_FMT "\n", i, ne, nv));
210         for (j = 0; j < ne; j++) {
211           p = edges[j];
212           PetscCall(DMNetworkGetConnectedVertices(dm, p, &cone));
213           PetscCall(DMNetworkGetGlobalVertexIndex(dm, cone[0], &vfrom));
214           PetscCall(DMNetworkGetGlobalVertexIndex(dm, cone[1], &vto));
215           PetscCall(DMNetworkGetGlobalEdgeIndex(dm, edges[j], &p));
216           PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "       edge %" PetscInt_FMT ": %" PetscInt_FMT " ----> %" PetscInt_FMT "\n", p, vfrom, vto));
217         }
218       }
219     }
220 
221     /* Shared vertices */
222     PetscCall(DMNetworkGetSharedVertices(dm, NULL, &vtx));
223     if (nsv) {
224       PetscInt        gidx;
225       PetscBool       ghost;
226       const PetscInt *sv = NULL;
227 
228       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "     SharedVertices:\n"));
229       for (i = 0; i < nsv; i++) {
230         PetscCall(DMNetworkIsGhostVertex(dm, vtx[i], &ghost));
231         if (ghost) continue;
232 
233         PetscCall(DMNetworkSharedVertexGetInfo(dm, vtx[i], &gidx, &nv, &sv));
234         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "       svtx %" PetscInt_FMT ": global index %" PetscInt_FMT ", subnet[%" PetscInt_FMT "].%" PetscInt_FMT " ---->\n", i, gidx, sv[0], sv[1]));
235         for (j = 1; j < nv; j++) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "                                           ----> subnet[%" PetscInt_FMT "].%" PetscInt_FMT "\n", sv[2 * j], sv[2 * j + 1]));
236       }
237     }
238     PetscCall(PetscViewerFlush(viewer));
239     PetscCall(PetscViewerASCIIPopSynchronized(viewer));
240   } else PetscCheck(iascii, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMNetwork writing", ((PetscObject)viewer)->type_name);
241   PetscFunctionReturn(PETSC_SUCCESS);
242 }
243