Skip to content

Commit 9b139f7

Browse files
committed
Introduce anomaly detection pipeline with tuned clustering
1 parent 02b8d78 commit 9b139f7

20 files changed

+1895
-356
lines changed

domains/anomaly-detection/AnomalyDetectionExploration.ipynb

Lines changed: 779 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
#!/usr/bin/env bash
2+
3+
# Pipeline that coordinates anomaly detection using the Graph Data Science Library of Neo4j.
4+
# It requires an already running Neo4j graph database with already scanned and analyzed artifacts.
5+
# The results will be written into the sub directory reports/anomaly-detection.
6+
7+
# Note that "scripts/prepareAnalysis.sh" is required to run prior to this script.
8+
9+
# Requires executeQueryFunctions.sh, projectionFunctions.sh, cleanupAfterReportGeneration.sh
10+
11+
# Fail on any error ("-e" = exit on first error, "-o pipefail" exist on errors within piped commands)
12+
set -o errexit -o pipefail
13+
14+
# Overrideable Constants (defaults also defined in sub scripts)
15+
REPORTS_DIRECTORY=${REPORTS_DIRECTORY:-"reports"}
16+
17+
## Get this "scripts/reports" directory if not already set
18+
# Even if $BASH_SOURCE is made for Bourne-like shells it is also supported by others and therefore here the preferred solution.
19+
# CDPATH reduces the scope of the cd command to potentially prevent unintended directory changes.
20+
# This way non-standard tools like readlink aren't needed.
21+
ANOMALY_DETECTION_SCRIPT_DIR=${ANOMALY_DETECTION_SCRIPT_DIR:-$(CDPATH=. cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)}
22+
echo "anomalyDetectionPipeline: ANOMALY_DETECTION_SCRIPT_DIR=${ANOMALY_DETECTION_SCRIPT_DIR}"
23+
# Get the "scripts" directory by taking the path of this script and going one directory up.
24+
SCRIPTS_DIR=${SCRIPTS_DIR:-"${ANOMALY_DETECTION_SCRIPT_DIR}/../../scripts"} # Repository directory containing the shell scripts
25+
# Get the "cypher" query directory for gathering features.
26+
ANOMALY_DETECTION_FEATURE_CYPHER_DIR=${ANOMALY_DETECTION_FEATURE_CYPHER_DIR:-"${ANOMALY_DETECTION_SCRIPT_DIR}/features"}
27+
ANOMALY_DETECTION_QUERY_CYPHER_DIR=${ANOMALY_DETECTION_QUERY_CYPHER_DIR:-"${ANOMALY_DETECTION_SCRIPT_DIR}/queries"}
28+
29+
# Function to display script usage
30+
usage() {
31+
echo -e "${COLOR_ERROR}" >&2
32+
echo "Usage: $0 [--verbose]" >&2
33+
echo -e "${COLOR_DEFAULT}" >&2
34+
exit 1
35+
}
36+
37+
# Default values
38+
verboseMode="" # either "" or "--verbose"
39+
40+
# Parse command line arguments
41+
while [[ $# -gt 0 ]]; do
42+
key="$1"
43+
value="${2}"
44+
45+
case ${key} in
46+
--verbose)
47+
verboseMode="--verbose"
48+
;;
49+
*)
50+
echo -e "${COLOR_ERROR}anomalyDetectionPipeline: Error: Unknown option: ${key}${COLOR_DEFAULT}" >&2
51+
usage
52+
;;
53+
esac
54+
shift || true # ignore error when there are no more arguments
55+
done
56+
57+
# Define functions to execute a cypher query from within a given file (first and only argument) like "execute_cypher"
58+
source "${SCRIPTS_DIR}/executeQueryFunctions.sh"
59+
60+
# Define functions to create and delete Graph Projections like "createUndirectedDependencyProjection"
61+
source "${SCRIPTS_DIR}/projectionFunctions.sh"
62+
63+
# Query or recalculate features.
64+
#
65+
# Required Parameters:
66+
# - projection_name=...
67+
# Name prefix for the in-memory projection name. Example: "package-anomaly-detection"
68+
# - projection_node_label=...
69+
# Label of the nodes that will be used for the projection. Example: "Package"
70+
# - projection_weight_property=...
71+
# Name of the node property that contains the dependency weight. Example: "weight"
72+
anomaly_detection_features() {
73+
# Determine the Betweenness centrality (with the directed graph projection) if not already done
74+
execute_cypher_queries_until_results "${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-Betweenness-Exists.cypher" \
75+
"${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-Betweenness-Write.cypher" "${@}"
76+
# Determine the local clustering coefficient if not already done
77+
execute_cypher_queries_until_results "${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-LocalClusteringCoefficient-Exists.cypher" \
78+
"${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-LocalClusteringCoefficient-Write.cypher" "${@}"
79+
# Determine the page rank if not already done
80+
execute_cypher_queries_until_results "${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-PageRank-Exists.cypher" \
81+
"${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-PageRank-Write.cypher" "${@}"
82+
# Determine the article rank if not already done
83+
execute_cypher_queries_until_results "${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-ArticleRank-Exists.cypher" \
84+
"${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-PageRank-Write.cypher" "${@}"
85+
}
86+
# Run queries to find anomalies in the graph.
87+
#
88+
# Required Parameters:
89+
# - projection_node_label=...
90+
# Label of the nodes that will be used for the projection. Example: "Package"
91+
anomaly_detection_queries() {
92+
local nodeLabel
93+
nodeLabel=$( extractQueryParameter "projection_node_label" "${@}" )
94+
95+
execute_cypher "${ANOMALY_DETECTION_QUERY_CYPHER_DIR}/AnomalyDetectionPotentialImbalancedRoles.cypher" "${@}" > "${FULL_REPORT_DIRECTORY}/${nodeLabel}AnomalyDetection_PotentialImbalancedRoles.csv"
96+
execute_cypher "${ANOMALY_DETECTION_QUERY_CYPHER_DIR}/AnomalyDetectionPotentialBoundarySpanningModules.cypher" "${@}" > "${FULL_REPORT_DIRECTORY}/${nodeLabel}AnomalyDetection_PotentialBoundarySpanningModules.csv"
97+
execute_cypher "${ANOMALY_DETECTION_QUERY_CYPHER_DIR}/AnomalyDetectionPotentialHiddenBottlenecksOrHubs.cypher" "${@}" > "${FULL_REPORT_DIRECTORY}/${nodeLabel}AnomalyDetection_PotentialHiddenBottlenecksOrHubs.csv"
98+
execute_cypher "${ANOMALY_DETECTION_QUERY_CYPHER_DIR}/AnomalyDetectionPotentialOverEngineerOrIsolated.cypher" "${@}" > "${FULL_REPORT_DIRECTORY}/${nodeLabel}AnomalyDetection_PotentialOverEngineerOrIsolated.csv"
99+
execute_cypher "${ANOMALY_DETECTION_QUERY_CYPHER_DIR}/AnomalyDetectionPotentialArchitectorSmells.cypher" "${@}" > "${FULL_REPORT_DIRECTORY}/${nodeLabel}AnomalyDetection_PotentialArchitectorSmells.csv"
100+
}
101+
102+
# TODO Remove notes:
103+
# High PageRank + high betweenness Critical infrastructure component
104+
# High ArticleRank + high betweenness Complex orchestrator or manager
105+
106+
# Run the anomaly detection pipeline.
107+
#
108+
# Required Parameters:
109+
# - projection_name=...
110+
# Name prefix for the in-memory projection name. Example: "package-anomaly-detection"
111+
# - projection_node_label=...
112+
# Label of the nodes that will be used for the projection. Example: "Package"
113+
# - projection_weight_property=...
114+
# Name of the node property that contains the dependency weight. Example: "weight"
115+
anomaly_detection_pipeline() {
116+
time anomaly_detection_features "${@}"
117+
time anomaly_detection_queries "${@}"
118+
# Get tuned Leiden communities as a reference to tune clustering
119+
time "${ANOMALY_DETECTION_SCRIPT_DIR}/tunedLeidenCommunityDetection.py" "${@}" ${verboseMode}
120+
# Tuned Fast Random Projection and tuned HDBSCAN clustering
121+
time "${ANOMALY_DETECTION_SCRIPT_DIR}/tunedNodeEmbeddingClustering.py" "${@}" ${verboseMode}
122+
# Reduce the dimensionality of the node embeddings down to 2D for visualization using UMAP
123+
time "${ANOMALY_DETECTION_SCRIPT_DIR}/umap2dNodeEmbeddings.py" "${@}" ${verboseMode}
124+
125+
# Query Results: Output all collected features into a CSV file.
126+
local nodeLabel
127+
nodeLabel=$( extractQueryParameter "projection_node_label" "${@}" )
128+
execute_cypher "${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeatures.cypher" "${@}" > "${FULL_REPORT_DIRECTORY}/${nodeLabel}AnomalyDetectionFeatures.csv"
129+
}
130+
131+
# Create report directory
132+
REPORT_NAME="anomaly-detection"
133+
FULL_REPORT_DIRECTORY="${REPORTS_DIRECTORY}/${REPORT_NAME}"
134+
mkdir -p "${FULL_REPORT_DIRECTORY}"
135+
136+
# Query Parameter key pairs for projection and algorithm side
137+
PROJECTION_NAME="dependencies_projection"
138+
ALGORITHM_PROJECTION="projection_name"
139+
140+
PROJECTION_NODE="dependencies_projection_node"
141+
ALGORITHM_NODE="projection_node_label"
142+
143+
PROJECTION_WEIGHT="dependencies_projection_weight_property"
144+
ALGORITHM_WEIGHT="projection_weight_property"
145+
146+
# Code independent algorithm parameters
147+
COMMUNITY_PROPERTY="community_property=communityLeidenIdTuned"
148+
149+
# Query (or recalculate) features.
150+
#
151+
# Required Parameters:
152+
# - projection_name=...
153+
# Name prefix for the in-memory projection name. Example: "package-anomaly-detection"
154+
# - projection_node_label=...
155+
# Label of the nodes that will be used for the projection. Example: "Package"
156+
# - projection_weight_property=...
157+
# Name of the node property that contains the dependency weight. Example: "weight"
158+
anomaly_detection_features() {
159+
# Query Feature: Determine the Betweenness centrality (with the directed graph projection) if not already done
160+
execute_cypher_queries_until_results "${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-Betweenness-Exists.cypher" \
161+
"${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-Betweenness-Write.cypher" "${@}"
162+
# Query Feature: Determine the local clustering coefficient if not already done
163+
execute_cypher_queries_until_results "${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-LocalClusteringCoefficient-Exists.cypher" \
164+
"${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-LocalClusteringCoefficient-Write.cypher" "${@}"
165+
# Query Feature: Determine the page rank if not already done
166+
execute_cypher_queries_until_results "${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-PageRank-Exists.cypher" \
167+
"${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-PageRank-Write.cypher" "${@}"
168+
# Query Feature: Determine the article rank if not already done
169+
execute_cypher_queries_until_results "${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-ArticleRank-Exists.cypher" \
170+
"${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeature-ArticleRank-Write.cypher" "${@}"
171+
}
172+
173+
# Run the anomaly detection pipeline.
174+
#
175+
# Required Parameters:
176+
# - projection_name=...
177+
# Name prefix for the in-memory projection name. Example: "package-anomaly-detection"
178+
# - projection_node_label=...
179+
# Label of the nodes that will be used for the projection. Example: "Package"
180+
# - projection_weight_property=...
181+
# Name of the node property that contains the dependency weight. Example: "weight"
182+
anomaly_detection_pipeline() {
183+
time anomaly_detection_features "${@}"
184+
# Run Python: Get tuned Leiden communities as a reference to tune clustering
185+
time "${ANOMALY_DETECTION_SCRIPT_DIR}/tunedLeidenCommunityDetection.py" "${@}" ${verboseMode}
186+
# Run Python: Tuned Fast Random Projection and tuned HDBSCAN clustering
187+
time "${ANOMALY_DETECTION_SCRIPT_DIR}/tunedNodeEmbeddingClustering.py" "${@}" ${verboseMode}
188+
189+
# Query Results: Output all collected features into a CSV file.
190+
local nodeLabel
191+
nodeLabel=$( extractQueryParameter "projection_node_label" "${@}" )
192+
execute_cypher "${ANOMALY_DETECTION_FEATURE_CYPHER_DIR}/AnomalyDetectionFeatures.cypher" "${@}" > "${FULL_REPORT_DIRECTORY}/${nodeLabel}AnomalyDetection.csv"
193+
}
194+
195+
# -- Java Artifact Node Embeddings -------------------------------
196+
197+
if createUndirectedDependencyProjection "${PROJECTION_NAME}=artifact-anomaly-detection" "${PROJECTION_NODE}=Artifact" "${PROJECTION_WEIGHT}=weight"; then
198+
createDirectedDependencyProjection "${PROJECTION_NAME}=artifact-anomaly-detection-directed" "${PROJECTION_NODE}=Artifact" "${PROJECTION_WEIGHT}=weight"
199+
anomaly_detection_pipeline "${ALGORITHM_PROJECTION}=artifact-anomaly-detection" "${ALGORITHM_NODE}=Artifact" "${ALGORITHM_WEIGHT}=weight" "${COMMUNITY_PROPERTY}"
200+
fi
201+
202+
# -- Java Package Node Embeddings --------------------------------
203+
204+
if createUndirectedDependencyProjection "${PROJECTION_NAME}=package-anomaly-detection" "${PROJECTION_NODE}=Package" "${PROJECTION_WEIGHT}=weight25PercentInterfaces"; then
205+
createDirectedDependencyProjection "${PROJECTION_NAME}=package-anomaly-detection-directed" "${PROJECTION_NODE}=Package" "${PROJECTION_WEIGHT}=weight25PercentInterfaces"
206+
anomaly_detection_pipeline "${ALGORITHM_PROJECTION}=package-anomaly-detection" "${ALGORITHM_NODE}=Package" "${ALGORITHM_WEIGHT}=weight25PercentInterfaces" "${COMMUNITY_PROPERTY}"
207+
fi
208+
209+
# -- Java Type Node Embeddings -----------------------------------
210+
211+
if createUndirectedJavaTypeDependencyProjection "${PROJECTION_NAME}=type-anomaly-detection"; then
212+
createDirectedJavaTypeDependencyProjection "${PROJECTION_NAME}=type-anomaly-detection-directed"
213+
anomaly_detection_pipeline "${ALGORITHM_PROJECTION}=type-anomaly-detection" "${ALGORITHM_NODE}=Type" "${ALGORITHM_WEIGHT}=weight" "${COMMUNITY_PROPERTY}" "${EMBEDDING_PROPERTY}"
214+
fi
215+
216+
# -- Typescript Module Node Embeddings ---------------------------
217+
218+
if createUndirectedDependencyProjection "${PROJECTION_NAME}=typescript-module-embedding" "${PROJECTION_NODE}=Module" "${PROJECTION_WEIGHT}=lowCouplingElement25PercentWeight"; then
219+
createDirectedDependencyProjection "${PROJECTION_NAME}=typescript-module-embedding-directed" "${PROJECTION_NODE}=Module" "${PROJECTION_WEIGHT}=lowCouplingElement25PercentWeight"
220+
anomaly_detection_pipeline "${ALGORITHM_PROJECTION}=typescript-module-embedding" "${ALGORITHM_NODE}=Module" "${ALGORITHM_WEIGHT}=lowCouplingElement25PercentWeight" "${COMMUNITY_PROPERTY}" "${EMBEDDING_PROPERTY}"
221+
fi
222+
223+
# ---------------------------------------------------------------
224+
225+
# Clean-up after report generation. Empty reports will be deleted.
226+
source "${SCRIPTS_DIR}/cleanupAfterReportGeneration.sh" "${FULL_REPORT_DIRECTORY}"
227+
228+
echo "anomalyDetectionPipeline: $(date +'%Y-%m-%dT%H:%M:%S%z') Successfully finished."
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Return the first node with a centralityArticleRank if it exists
2+
3+
MATCH (codeUnit)
4+
WHERE $projection_node_label IN labels(codeUnit)
5+
AND codeUnit.centralityArticleRank IS NOT NULL
6+
RETURN codeUnit.name AS shortCodeUnitName
7+
,elementId(codeUnit) AS nodeElementId
8+
,codeUnit.centralityArticleRank AS articleRank
9+
LIMIT 1
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Calculates and writes the Article Rank centrality score for anomaly detection
2+
3+
CALL gds.articleRank.write(
4+
$projection_name + '-directed-cleaned', {
5+
maxIterations: 50
6+
,relationshipWeightProperty: $projection_weight_property
7+
,writeProperty: 'centralityArticleRank'
8+
})
9+
YIELD nodePropertiesWritten, ranIterations, didConverge, preProcessingMillis, computeMillis, postProcessingMillis, writeMillis
10+
RETURN nodePropertiesWritten, ranIterations, didConverge, preProcessingMillis, computeMillis, postProcessingMillis, writeMillis
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Return the first node with a centralityBetweenness if it exists
2+
3+
MATCH (codeUnit)
4+
WHERE $projection_node_label IN labels(codeUnit)
5+
AND codeUnit.centralityBetweenness IS NOT NULL
6+
RETURN codeUnit.name AS shortCodeUnitName
7+
,elementId(codeUnit) AS nodeElementId
8+
,codeUnit.centralityBetweenness AS pageRank
9+
LIMIT 1
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Calculates and writes the Betweeness centrality score for anomaly detection
2+
3+
CALL gds.betweenness.write(
4+
$projection_name + '-directed-cleaned', {
5+
relationshipWeightProperty: $projection_weight_property
6+
,writeProperty: 'centralityBetweenness'
7+
})
8+
YIELD nodePropertiesWritten, preProcessingMillis, computeMillis, postProcessingMillis, writeMillis
9+
RETURN nodePropertiesWritten, preProcessingMillis, computeMillis, postProcessingMillis, writeMillis
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Return the first node with a clusteringCoefficient if it exists
2+
3+
MATCH (codeUnit)
4+
WHERE $projection_node_label IN labels(codeUnit)
5+
AND codeUnit.communityLocalClusteringCoefficient IS NOT NULL
6+
RETURN codeUnit.name AS shortCodeUnitName
7+
,elementId(codeUnit) AS nodeElementId
8+
,codeUnit.communityLocalClusteringCoefficient AS clusteringCoefficient
9+
LIMIT 1
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// Calculates and writes the local clustering coefficient for anomaly detection
2+
3+
CALL gds.localClusteringCoefficient.write(
4+
$projection_name + '-cleaned', {
5+
writeProperty: 'communityLocalClusteringCoefficient'
6+
})
7+
YIELD averageClusteringCoefficient, nodeCount, nodePropertiesWritten, preProcessingMillis, computeMillis, postProcessingMillis, writeMillis
8+
RETURN averageClusteringCoefficient, nodeCount, nodePropertiesWritten, preProcessingMillis, computeMillis, postProcessingMillis, writeMillis
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Return the first node with a centralityPageRank if it exists
2+
3+
MATCH (codeUnit)
4+
WHERE $projection_node_label IN labels(codeUnit)
5+
AND codeUnit.centralityPageRank IS NOT NULL
6+
RETURN codeUnit.name AS shortCodeUnitName
7+
,elementId(codeUnit) AS nodeElementId
8+
,codeUnit.centralityPageRank AS pageRank
9+
LIMIT 1
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Calculates and writes the Article Rank centrality score for anomaly detection
2+
3+
CALL gds.pageRank.write(
4+
$projection_name + '-directed-cleaned', {
5+
maxIterations: 50
6+
,relationshipWeightProperty: $projection_weight_property
7+
,writeProperty: 'centralityPageRank'
8+
})
9+
YIELD nodePropertiesWritten, ranIterations, didConverge, preProcessingMillis, computeMillis, postProcessingMillis, writeMillis
10+
RETURN nodePropertiesWritten, ranIterations, didConverge, preProcessingMillis, computeMillis, postProcessingMillis, writeMillis

0 commit comments

Comments
 (0)