Debian Codegraph @

rdfwriter/utils.go

raw symbols SCIP
1 package rdfwriter
2
3 import (
4 "fmt"
5 "github.com/spdx/gordf/rdfloader/parser"
6 "github.com/spdx/gordf/uri"
7 "strings"
8 )
9
10 // returns an adjacency list from a list of triples
11 // Params:
12 // triples: might be unordered
13 // Output:
14 // adjList: adjacency list which maps subject to object for each triple
15 func GetAdjacencyList(triples []*parser.Triple) (adjList map[*parser.Node][]*parser.Node) {
16 // triples are analogous to the edges of a graph.
17 // For a (Subject, Predicate, Object) triple,
18 // it forms a directed edge from Subject to Object
19 // Graphically,
20 // predicate
21 // (Subject) ---------------> (Object)
22
23 // initialising the adjacency list:
24 adjList = make(map[*parser.Node][]*parser.Node)
25 for _, triple := range triples {
26 // create a new entry in the adjList if the key is not already seen.
27 if adjList[triple.Subject] == nil {
28 adjList[triple.Subject] = []*parser.Node{}
29 }
30
31 // the key is already seen and we can directly append the child
32 adjList[triple.Subject] = append(adjList[triple.Subject], triple.Object)
33
34 // ensure that there is a key entry for all the children.
35 if adjList[triple.Object] == nil {
36 adjList[triple.Object] = []*parser.Node{}
37 }
38 }
39 return adjList
40 }
41
42 // Params:
43 // triples: might be unordered
44 // Output:
45 // recoveryDS: subject to triple mapping that will help retrieve the
46 // triples after sorting the Subject: Object pairs.
47 func GetNodeToTriples(triples []*parser.Triple) (recoveryDS map[string][]*parser.Triple) {
48 // triples are analogous to the edges of a graph.
49 // For a (Subject, Predicate, Object) triple,
50 // it forms a directed edge from Subject to Object
51 // Graphically,
52 // predicate
53 // (Subject) ---------------> (Object)
54
55 // initialising the recoveryDS:
56 recoveryDS = make(map[string][]*parser.Triple)
57 for _, triple := range triples {
58 // create a new entry in the recoverDS if the key is not already seen.
59 if recoveryDS[triple.Subject.String()] == nil {
60 recoveryDS[triple.Subject.String()] = []*parser.Triple{}
61 }
62
63 // the key is already seen and we can directly append the child
64 recoveryDS[triple.Subject.String()] = append(recoveryDS[triple.Subject.String()], triple)
65
66 // ensure that there is a key entry for all the children.
67 if recoveryDS[triple.Object.String()] == nil {
68 recoveryDS[triple.Object.String()] = []*parser.Triple{}
69 }
70 }
71 return removeDuplicateTriples(recoveryDS)
72 }
73
74 func getUniqueTriples(triples []*parser.Triple) []*parser.Triple {
75 set := map[string]*parser.Triple{}
76 for _, triple := range triples {
77 set[triple.Hash()] = triple
78 }
79 var retList []*parser.Triple
80 for key := range set {
81 retList = append(retList, set[key])
82 }
83 return retList
84 }
85
86 func removeDuplicateTriples(nodeToTriples map[string][]*parser.Triple) map[string][]*parser.Triple {
87 retMap := map[string][]*parser.Triple{}
88 for key := range nodeToTriples {
89 retMap[key] = getUniqueTriples(nodeToTriples[key])
90 }
91 return retMap
92 }
93
94 // same as dfs function. Just that after each every neighbor of the node is visited, it is appended in a queue.
95 // Params:
96 // node: Current node to perform dfs on.
97 // lastIdx: index where a new node should be added in the resultList
98 // visited: if visited[node] is true, we've already serviced the node before.
99 // resultList: list of all the nodes after topological sorting.
100 func topologicalSortHelper(node *parser.Node, lastIndex *int, adjList map[*parser.Node][]*parser.Node, visited *map[*parser.Node]bool, resultList *[]*parser.Node) (err error) {
101 if node == nil {
102 return
103 }
104
105 // checking if the node exist in the graph
106 _, exists := adjList[node]
107 if !exists {
108 return fmt.Errorf("node%v doesn't exist in the graph", *node)
109 }
110 if (*visited)[node] {
111 // this node is already visited.
112 // the program enters here when the graph has at least one cycle..
113 return
114 }
115
116 // marking current node as visited
117 (*visited)[node] = true
118
119 // visiting all the neighbors of the node and it's children recursively
120 for _, neighbor := range adjList[node] {
121 // recurse neighbor only if and only if it is not visited yet.
122 if !(*visited)[neighbor] {
123 err = topologicalSortHelper(neighbor, lastIndex, adjList, visited, resultList)
124 if err != nil {
125 return err
126 }
127 }
128 }
129
130 if *lastIndex >= len(adjList) {
131 // there is at least one node which is a neighbor of some node
132 // whose entry doesn't exist in the adjList
133 return fmt.Errorf("found more nodes than the number of keys in the adjacency list")
134 }
135
136 // appending from left to right to get a reverse sorted output
137 (*resultList)[*lastIndex] = node
138 *lastIndex++
139 return nil
140 }
141
142 // A wrapper function to initialize the data structures required by the
143 // topological sort algorithm. It provides an interface to directly get the
144 // sorted triples without knowing the internal variables required for sorting.
145 // Note: it sorts in reverse order.
146 // Params:
147 // adjList : adjacency list: a map with key as the node and value as a
148 // list of it's neighbor nodes.
149 // Assumes: all the nodes in the graph are present in the adjList keys.
150 func topologicalSort(adjList map[*parser.Node][]*parser.Node) ([]*parser.Node, error) {
151 // variable declaration
152 numberNodes := len(adjList)
153 resultList := make([]*parser.Node, numberNodes) // this will be returned
154 visited := make(map[*parser.Node]bool, numberNodes)
155 lastIndex := 0
156
157 // iterate through nodes and perform a dfs starting from that node.
158 for node := range adjList {
159 if !visited[node] {
160 err := topologicalSortHelper(node, &lastIndex, adjList, &visited, &resultList)
161 if err != nil {
162 return resultList, err
163 }
164 }
165 }
166 return resultList, nil
167 }
168
169 // Interface for user to provide a list of triples and get the
170 // sorted one as the output
171 func TopologicalSortTriples(triples []*parser.Triple) (sortedTriples []*parser.Triple, err error) {
172 adjList := GetAdjacencyList(triples)
173 recoveryDS := GetNodeToTriples(triples)
174 sortedNodes, err := topologicalSort(adjList)
175 if err != nil {
176 return sortedTriples, fmt.Errorf("error sorting the triples: %v", err)
177 }
178
179 // initialized a slice
180 sortedTriples = []*parser.Triple{}
181
182 for _, subjectNode := range sortedNodes {
183 // append all the triples associated with the subjectNode
184 for _, triple := range recoveryDS[subjectNode.String()] {
185 sortedTriples = append(sortedTriples, triple)
186 }
187 }
188 return sortedTriples, nil
189 }
190
191 func DisjointSet(triples []*parser.Triple) map[*parser.Node]*parser.Node {
192 nodeStringMap := map[string]*parser.Node{}
193 parentString := map[string]*parser.Node{}
194 for _, triple := range triples {
195 parentString[triple.Object.String()] = triple.Subject
196 nodeStringMap[triple.Object.String()] = triple.Object
197 if _, exists := parentString[triple.Subject.String()]; !exists {
198 parentString[triple.Subject.String()] = nil
199 nodeStringMap[triple.Subject.String()] = triple.Subject
200 }
201 }
202
203 parent := make(map[*parser.Node]*parser.Node)
204 for keyString := range parentString {
205 node := nodeStringMap[keyString]
206 parent[node] = parentString[keyString]
207 }
208 return parent
209 }
210
211 // a schemaDefinition is a dictionary which maps the abbreviation defined in the root tag.
212 // for example: if the root tag is =>
213 // <rdf:RDF
214 // xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"/>
215 // the schemaDefinition will contain:
216 // {"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#"}
217 // this function will output a reverse map that is:
218 // {"http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf"}
219 func invertSchemaDefinition(schemaDefinition map[string]uri.URIRef) map[string]string {
220 invertedMap := make(map[string]string)
221 for abbreviation := range schemaDefinition {
222 _uri := schemaDefinition[abbreviation]
223 invertedMap[strings.Trim(_uri.String(), "#")] = abbreviation
224 }
225 return invertedMap
226 }
227
228 // return true if the target is in the given list
229 func any(target string, list []string) bool {
230 for _, s := range list {
231 if s == target {
232 return true
233 }
234 }
235 return false
236 }
237
238 // from the inverted schema definition, returns the name of the prefix used for
239 // the rdf name space. Return defaults to "rdf"
240 func getRDFNSAbbreviation(invSchemaDefinition map[string]string) string {
241 rdfNSAbbrev := "rdf"
242 if abbrev, exists := invSchemaDefinition[parser.RDFNS]; exists {
243 rdfNSAbbrev = abbrev
244 }
245 return rdfNSAbbrev
246 }
247
248 // given an expanded uri, returns abbreviated form for the same.
249 // For example:
250 // http://www.w3.org/1999/02/22-rdf-syntax-ns#Description will be abbreviated to rdf:Description
251 func shortenURI(uri string, invSchemaDefinition map[string]string) (string, error) {
252 // Logic: Every uri with a fragment created by the uri.URIRef has if of
253 // type baseURI#fragment. This function splits the uri by # character and
254 // replaces the baseURI with the abbreviated form from the inverseSchemaDefinition
255
256 splitIndex := strings.LastIndex(uri, "#")
257 if splitIndex == -1 {
258 return "", fmt.Errorf("uri doesn't have two parts of type schemaName:tagName. URI: %s", uri)
259 }
260
261 baseURI := strings.Trim(uri[:splitIndex], "#")
262 fragment := strings.TrimSuffix(uri[splitIndex+1:], "#") // removing the trailing #.
263 fragment = strings.TrimSpace(fragment)
264 if len(fragment) == 0 {
265 return "", fmt.Errorf(`fragment "%v" doesn't exist`, fragment)
266 }
267 if abbrev, exists := invSchemaDefinition[baseURI]; exists {
268 if abbrev == "" {
269 return fragment, nil
270 }
271 return fmt.Sprintf("%s:%s", abbrev, fragment), nil
272 }
273 return "", fmt.Errorf("declaration of URI(%s) not found in the schemaDefinition", baseURI)
274 }
275
276 // from a given adjacency list, return a list of root-nodes which will be used
277 // to generate string forms of the nodes to be written.
278 func GetRootNodes(triples []*parser.Triple) (rootNodes []*parser.Node) {
279
280 // In a disjoint set, indices with root nodes will point to nil
281 // that means, if disjointSet[node] is nil, the node has no parent
282 // and it is one of the root nodes.
283 var parent map[*parser.Node]*parser.Node
284 parent = DisjointSet(triples)
285
286 for node := range parent {
287 if parent[node] == nil {
288 rootNodes = append(rootNodes, node)
289 }
290 }
291 return rootNodes
292 }
293
294 // returns the triples that are not associated with tags of schemaName "rdf".
295 func getRestTriples(triples []*parser.Triple) (restTriples []*parser.Triple) {
296 rdfTypeURI := parser.RDFNS + "type"
297 rdfNodeIDURI := parser.RDFNS + "nodeID"
298 for _, triple := range triples {
299 if !any(triple.Predicate.ID, []string{rdfNodeIDURI, rdfTypeURI}) {
300 restTriples = append(restTriples, triple)
301 }
302 }
303 return restTriples
304 }