pidsmaker 5.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (339) hide show
  1. pidsmaker/__init__.py +1 -0
  2. pidsmaker/cli.py +81 -0
  3. pidsmaker/config/__init__.py +2 -0
  4. pidsmaker/config/config.py +2100 -0
  5. pidsmaker/config/pipeline.py +1824 -0
  6. pidsmaker/config/schemas.py +1032 -0
  7. pidsmaker/datasets.py +323 -0
  8. pidsmaker/debug_tests.py +30 -0
  9. pidsmaker/decoders/__init__.py +5 -0
  10. pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
  11. pidsmaker/decoders/custom_mlp_decoder.py +10 -0
  12. pidsmaker/decoders/edge_linear_decoder.py +16 -0
  13. pidsmaker/decoders/inner_product_decoder.py +18 -0
  14. pidsmaker/decoders/nodlink_decoder.py +56 -0
  15. pidsmaker/detection/__init__.py +0 -0
  16. pidsmaker/detection/evaluation_methods/__init__.py +9 -0
  17. pidsmaker/detection/evaluation_methods/edge_evaluation.py +255 -0
  18. pidsmaker/detection/evaluation_methods/evaluation_utils.py +1788 -0
  19. pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
  20. pidsmaker/detection/evaluation_methods/node_evaluation.py +459 -0
  21. pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
  22. pidsmaker/detection/evaluation_methods/plot.py +192 -0
  23. pidsmaker/detection/evaluation_methods/queue_evaluation.py +456 -0
  24. pidsmaker/detection/evaluation_methods/tw_evaluation.py +93 -0
  25. pidsmaker/detection/flash_detection.py +162 -0
  26. pidsmaker/detection/magic_knn.py +190 -0
  27. pidsmaker/detection/node_scoring.py +52 -0
  28. pidsmaker/detection/threatrace_detection.py +65 -0
  29. pidsmaker/detection/training_methods/__init__.py +1 -0
  30. pidsmaker/detection/training_methods/inference_loop.py +287 -0
  31. pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
  32. pidsmaker/detection/training_methods/threatrace_training.py +168 -0
  33. pidsmaker/detection/training_methods/training_loop.py +383 -0
  34. pidsmaker/encoders/__init__.py +22 -0
  35. pidsmaker/encoders/argus_encoder.py +69 -0
  36. pidsmaker/encoders/custom_mlp.py +75 -0
  37. pidsmaker/encoders/custom_mlp_encoder.py +10 -0
  38. pidsmaker/encoders/egraphsage_encoder.py +56 -0
  39. pidsmaker/encoders/gat.py +67 -0
  40. pidsmaker/encoders/gcn.py +27 -0
  41. pidsmaker/encoders/gin.py +48 -0
  42. pidsmaker/encoders/glstm.py +298 -0
  43. pidsmaker/encoders/graph_attention.py +63 -0
  44. pidsmaker/encoders/gru.py +29 -0
  45. pidsmaker/encoders/hetero/__init__.py +4 -0
  46. pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
  47. pidsmaker/encoders/hetero/entity_encoder.py +33 -0
  48. pidsmaker/encoders/hetero/event_encoder.py +81 -0
  49. pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
  50. pidsmaker/encoders/lares_encoder.py +68 -0
  51. pidsmaker/encoders/linear_encoder.py +16 -0
  52. pidsmaker/encoders/magic_encoder.py +161 -0
  53. pidsmaker/encoders/rcaid_encoder.py +81 -0
  54. pidsmaker/encoders/rgcn.py +75 -0
  55. pidsmaker/encoders/sage.py +51 -0
  56. pidsmaker/encoders/shadewatcher_encoder.py +149 -0
  57. pidsmaker/encoders/sum_aggregation.py +20 -0
  58. pidsmaker/encoders/temporal_wrappers.py +80 -0
  59. pidsmaker/encoders/textrcnn.py +82 -0
  60. pidsmaker/encoders/tgn_encoder.py +193 -0
  61. pidsmaker/experiments/tuning.py +102 -0
  62. pidsmaker/experiments/uncertainty.py +261 -0
  63. pidsmaker/factory.py +1456 -0
  64. pidsmaker/featurization/__init__.py +0 -0
  65. pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
  66. pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +30 -0
  67. pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +65 -0
  68. pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +14 -0
  69. pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +53 -0
  70. pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +37 -0
  71. pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +69 -0
  72. pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +84 -0
  73. pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
  74. pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1728 -0
  75. pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +55 -0
  76. pidsmaker/featurization/featurization_methods/__init__.py +0 -0
  77. pidsmaker/featurization/featurization_methods/build_trw.py +66 -0
  78. pidsmaker/featurization/featurization_methods/featurization_alacarte.py +747 -0
  79. pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +98 -0
  80. pidsmaker/featurization/featurization_methods/featurization_fasttext.py +74 -0
  81. pidsmaker/featurization/featurization_methods/featurization_flash.py +201 -0
  82. pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +242 -0
  83. pidsmaker/featurization/featurization_methods/featurization_trw.py +114 -0
  84. pidsmaker/featurization/featurization_methods/featurization_word2vec.py +89 -0
  85. pidsmaker/featurization/featurization_utils.py +275 -0
  86. pidsmaker/featurization/utils/build_random_walks.py +66 -0
  87. pidsmaker/featurization/utils/trw.py +203 -0
  88. pidsmaker/hetero.py +81 -0
  89. pidsmaker/losses.py +170 -0
  90. pidsmaker/main.py +478 -0
  91. pidsmaker/mimicry.py +284 -0
  92. pidsmaker/model.py +382 -0
  93. pidsmaker/objectives/__init__.py +16 -0
  94. pidsmaker/objectives/autoencode_edge_emb.py +43 -0
  95. pidsmaker/objectives/deep_graph_infomax.py +94 -0
  96. pidsmaker/objectives/detect_few_shot.py +21 -0
  97. pidsmaker/objectives/one_class.py +75 -0
  98. pidsmaker/objectives/predict_edge_contrastive.py +165 -0
  99. pidsmaker/objectives/predict_edge_supervised.py +77 -0
  100. pidsmaker/objectives/predict_edge_type.py +28 -0
  101. pidsmaker/objectives/predict_masked_struct.py +49 -0
  102. pidsmaker/objectives/predict_node_type.py +36 -0
  103. pidsmaker/objectives/predict_process_tag.py +169 -0
  104. pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
  105. pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
  106. pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
  107. pidsmaker/objectives/reconstruct_node_emb.py +13 -0
  108. pidsmaker/objectives/reconstruct_node_feat.py +13 -0
  109. pidsmaker/objectives/validation_wrapper.py +55 -0
  110. pidsmaker/preprocessing/__init__.py +0 -0
  111. pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
  112. pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +825 -0
  113. pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +216 -0
  114. pidsmaker/preprocessing/cleaning.py +258 -0
  115. pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
  116. pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
  117. pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
  118. pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
  119. pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
  120. pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
  121. pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
  122. pidsmaker/pretrained/__init__.py +5 -0
  123. pidsmaker/pretrained/data/__init__.py +4 -0
  124. pidsmaker/pretrained/data/behavior_signatures.py +548 -0
  125. pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
  126. pidsmaker/pretrained/data/edge_filter.py +381 -0
  127. pidsmaker/pretrained/data/entity_classes.py +476 -0
  128. pidsmaker/pretrained/data/sampler.py +926 -0
  129. pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
  130. pidsmaker/pretrained/detect.py +1427 -0
  131. pidsmaker/pretrained/embedding_generator.py +252 -0
  132. pidsmaker/pretrained/finetune.py +1434 -0
  133. pidsmaker/pretrained/models/__init__.py +20 -0
  134. pidsmaker/pretrained/models/behavior.py +348 -0
  135. pidsmaker/pretrained/models/bert.py +286 -0
  136. pidsmaker/pretrained/models/deepwalk.py +128 -0
  137. pidsmaker/pretrained/models/dgi.py +120 -0
  138. pidsmaker/pretrained/models/gae.py +114 -0
  139. pidsmaker/pretrained/models/gnn_distill.py +475 -0
  140. pidsmaker/pretrained/models/graphmae.py +373 -0
  141. pidsmaker/pretrained/models/hf_pretrained.py +213 -0
  142. pidsmaker/pretrained/models/llama.py +110 -0
  143. pidsmaker/pretrained/models/modernbert.py +567 -0
  144. pidsmaker/pretrained/models/roberta.py +147 -0
  145. pidsmaker/pretrained/models/rope_utils.py +99 -0
  146. pidsmaker/pretrained/models/ropebert.py +322 -0
  147. pidsmaker/pretrained/models/spider.py +204 -0
  148. pidsmaker/pretrained/models/tgn.py +770 -0
  149. pidsmaker/pretrained/pretrain/__init__.py +3 -0
  150. pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
  151. pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
  152. pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
  153. pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
  154. pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
  155. pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
  156. pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
  157. pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
  158. pidsmaker/pretrained/pretrain/pretrain_main.py +275 -0
  159. pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
  160. pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
  161. pidsmaker/pretrained/training_utils.py +157 -0
  162. pidsmaker/process_reapr_gt.py +101 -0
  163. pidsmaker/resources/config/anomal_e.yml +25 -0
  164. pidsmaker/resources/config/argus.yml +56 -0
  165. pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
  166. pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
  167. pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
  168. pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
  169. pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
  170. pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
  171. pidsmaker/resources/config/default.yml +315 -0
  172. pidsmaker/resources/config/egraphsage.yml +95 -0
  173. pidsmaker/resources/config/euler.yml +104 -0
  174. pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
  175. pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
  176. pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
  177. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
  178. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
  179. pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
  180. pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
  181. pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
  182. pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
  183. pidsmaker/resources/config/flash.yml +79 -0
  184. pidsmaker/resources/config/jbeil.yml +65 -0
  185. pidsmaker/resources/config/kairos.yml +121 -0
  186. pidsmaker/resources/config/lares.yml +115 -0
  187. pidsmaker/resources/config/magic.yml +86 -0
  188. pidsmaker/resources/config/nodlink.yml +79 -0
  189. pidsmaker/resources/config/ocrapt.yml +91 -0
  190. pidsmaker/resources/config/orthrus.yml +126 -0
  191. pidsmaker/resources/config/orthrus_fixed.yml +17 -0
  192. pidsmaker/resources/config/pretrained/README.md +101 -0
  193. pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
  194. pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
  195. pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
  196. pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
  197. pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
  198. pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
  199. pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
  200. pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
  201. pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
  202. pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
  203. pidsmaker/resources/config/prographer.yml +136 -0
  204. pidsmaker/resources/config/rcaid.yml +88 -0
  205. pidsmaker/resources/config/shadewatcher.yml +146 -0
  206. pidsmaker/resources/config/tests.yml +10 -0
  207. pidsmaker/resources/config/threatrace.yml +73 -0
  208. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
  209. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
  210. pidsmaker/resources/config/velox.yml +10 -0
  211. pidsmaker/resources/config/viz_config.yml +10 -0
  212. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
  213. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
  214. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
  215. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
  216. pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
  217. pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
  218. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
  219. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
  220. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
  221. pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
  222. pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
  223. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
  224. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
  225. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
  226. pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
  227. pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
  228. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
  229. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
  230. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
  231. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
  232. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
  233. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
  234. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
  235. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
  236. pidsmaker/resources/ground_truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
  237. pidsmaker/resources/ground_truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
  238. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
  239. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
  240. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
  241. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
  242. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
  243. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
  244. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
  245. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
  246. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
  247. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
  248. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
  249. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
  250. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
  251. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
  252. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
  253. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
  254. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
  255. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
  256. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
  257. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
  258. pidsmaker/resources/ground_truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
  259. pidsmaker/resources/ground_truth/orthrus/h051/node_h051_0925.csv +114 -0
  260. pidsmaker/resources/ground_truth/orthrus/h201/node_h201_0923.csv +2905 -0
  261. pidsmaker/resources/ground_truth/orthrus/h501/node_h501_0924.csv +749 -0
  262. pidsmaker/resources/ground_truth/orthrus/readme.md +98 -0
  263. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
  264. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
  265. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
  266. pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
  267. pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
  268. pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
  269. pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
  270. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
  271. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
  272. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
  273. pidsmaker/resources/ground_truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
  274. pidsmaker/resources/ground_truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
  275. pidsmaker/resources/ground_truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
  276. pidsmaker/resources/ground_truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
  277. pidsmaker/resources/ground_truth/threatrace/README.md +123 -0
  278. pidsmaker/tasks/__init__.py +10 -0
  279. pidsmaker/tasks/batching.py +47 -0
  280. pidsmaker/tasks/construction.py +31 -0
  281. pidsmaker/tasks/evaluation.py +241 -0
  282. pidsmaker/tasks/feat_inference.py +413 -0
  283. pidsmaker/tasks/featurization.py +43 -0
  284. pidsmaker/tasks/training.py +17 -0
  285. pidsmaker/tasks/transformation.py +306 -0
  286. pidsmaker/tasks/triage.py +143 -0
  287. pidsmaker/tgn.py +635 -0
  288. pidsmaker/tokenization/__init__.py +112 -0
  289. pidsmaker/tokenization/base.py +58 -0
  290. pidsmaker/tokenization/bpe_tokenizer.py +83 -0
  291. pidsmaker/tokenization/hf_tokenizer.py +61 -0
  292. pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
  293. pidsmaker/tokenization/label_tokenizer.py +24 -0
  294. pidsmaker/tokenization/nltk_tokenizer.py +84 -0
  295. pidsmaker/tokenization/substitution.py +295 -0
  296. pidsmaker/triage/__init__.py +0 -0
  297. pidsmaker/triage/tracing_methods/__init__.py +1 -0
  298. pidsmaker/triage/tracing_methods/depimpact.py +213 -0
  299. pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
  300. pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
  301. pidsmaker/utils/__init__.py +0 -0
  302. pidsmaker/utils/cache_utils.py +256 -0
  303. pidsmaker/utils/console.py +282 -0
  304. pidsmaker/utils/data_utils.py +1742 -0
  305. pidsmaker/utils/database.py +150 -0
  306. pidsmaker/utils/dataset_utils.py +413 -0
  307. pidsmaker/utils/dataset_writer.py +570 -0
  308. pidsmaker/utils/graph_store.py +634 -0
  309. pidsmaker/utils/labelling.py +445 -0
  310. pidsmaker/utils/loss_files.py +193 -0
  311. pidsmaker/utils/process_tags.py +44 -0
  312. pidsmaker/utils/utils.py +712 -0
  313. pidsmaker/vizgen/__init__.py +1 -0
  314. pidsmaker/vizgen/backfill_manifests.py +100 -0
  315. pidsmaker/vizgen/dimensionality_reduction.py +249 -0
  316. pidsmaker/vizgen/embed_exporter.py +467 -0
  317. pidsmaker/vizgen/exporter.py +493 -0
  318. pidsmaker/vizgen/html_builder.py +936 -0
  319. pidsmaker/vizgen/web/__init__.py +1 -0
  320. pidsmaker/vizgen/web/export.py +62 -0
  321. pidsmaker/vizgen/web/static/css/app.css +250 -0
  322. pidsmaker/vizgen/web/static/index.html +182 -0
  323. pidsmaker/vizgen/web/static/js/app.js +627 -0
  324. pidsmaker/vizgen/web/static/js/campaign.js +123 -0
  325. pidsmaker/vizgen/web/static/js/data.js +119 -0
  326. pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
  327. pidsmaker/vizgen/web/static/js/jobs.js +75 -0
  328. pidsmaker/vizgen/web/static/js/scene.js +651 -0
  329. pidsmaker/vizgen/web/static/js/ui.js +370 -0
  330. pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
  331. pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
  332. pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
  333. pidsmaker/vizgen/web/viz_server.py +2176 -0
  334. pidsmaker-5.0.0.dist-info/METADATA +597 -0
  335. pidsmaker-5.0.0.dist-info/RECORD +339 -0
  336. pidsmaker-5.0.0.dist-info/WHEEL +5 -0
  337. pidsmaker-5.0.0.dist-info/entry_points.txt +2 -0
  338. pidsmaker-5.0.0.dist-info/licenses/LICENSE +201 -0
  339. pidsmaker-5.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,28 @@
1
+ """DAG transformation for provenance graphs.
2
+
3
+ Converts provenance graphs to Directed Acyclic Graphs (DAGs) by removing cycles
4
+ and self-loops. Some PIDS systems assume acyclic structure for efficiency or
5
+ simplicity in backward/forward tracing algorithms.
6
+ """
7
+
8
+ import networkx as nx
9
+
10
+
11
+ def main(G: nx.Graph) -> nx.Graph:
12
+ """
13
+ Removes edges that make cycles in the graph, including self-loops.
14
+ Also removes duplicate edges.
15
+ Basically makes graph G a DAG.
16
+ """
17
+ G = nx.DiGraph(G)
18
+ G.remove_edges_from(nx.selfloop_edges(G))
19
+ while True:
20
+ try:
21
+ cycles = nx.find_cycle(G)
22
+ for cycle in cycles: # fast approximation, the optimal would be to remove 1 by 1
23
+ G.remove_edge(*cycle)
24
+
25
+ except nx.NetworkXNoCycle:
26
+ break
27
+ G = nx.MultiDiGraph(G)
28
+ return G
@@ -0,0 +1,136 @@
1
+ """Merges the repeated edges of each graph, as done by network IDSs (Euler, Argus, LARES).
2
+
3
+ All the edges between a same source and destination (and optionally of a same edge type) in a
4
+ graph become a single edge, with the attributes of the first event, the label of the most
5
+ malicious event (`y` is the max of the merged labels), and two new attributes:
6
+
7
+ - `count`: the number of merged events;
8
+ - `weight`: the count standardized over the edges of the graph and squashed by a sigmoid,
9
+ sigmoid((count - mean) / std), used as edge weight by weighted encoders (e.g. `gcn`).
10
+
11
+ With `aggregate_attributes`, merged edges also aggregate the edge attributes of all their events
12
+ (see `aggregated_edge_attribute_columns`): the number of events with each value of each
13
+ categorical attribute, and the number, mean and std of the values of numeric attributes. These
14
+ are the edge features of the models instead of the attributes of the first event.
15
+
16
+ Merged edges are ordered by the time of their first event.
17
+ """
18
+
19
+ import networkx as nx
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ from pidsmaker.utils.dataset_utils import aggregated_edge_attribute_columns, get_input_edge_attributes
24
+ from pidsmaker.utils.graph_store import graph_columns
25
+
26
+
27
+ def main(G: nx.MultiDiGraph, cfg) -> nx.MultiDiGraph:
28
+ """Merges the edges of a networkx graph (see `merge_columns`)."""
29
+ return merge_columns(graph_columns(G), cfg)
30
+
31
+
32
+ def _factorize(cols_attrs, name, m):
33
+ """(codes, uniques) of an edge attribute column (all None if the column is missing)."""
34
+ if name in cols_attrs:
35
+ return cols_attrs.factorize(name)
36
+ return np.zeros(m, dtype=np.int64), [None]
37
+
38
+
39
+ def merge_columns(cols, cfg) -> nx.MultiDiGraph:
40
+ """Merged graph of the graph whose columns are `cols` (`graph_store.GraphColumns`, e.g. from
41
+ `load_graph_columns`), computed with vectorized operations on the columns: graphs of network
42
+ datasets have millions of edges."""
43
+ per_edge_type = bool(cfg.transformation.merge_edges.per_edge_type)
44
+ aggregate = bool(getattr(cfg.transformation.merge_edges, "aggregate_attributes", False))
45
+ attributes = get_input_edge_attributes(cfg, selected=False) if aggregate else []
46
+ columns = aggregated_edge_attribute_columns(cfg, selected=False) if aggregate else {}
47
+
48
+ H = nx.MultiDiGraph()
49
+ node_keys = list(cols.node_attrs)
50
+ H.add_nodes_from(
51
+ (n, dict(zip(node_keys, values)))
52
+ for n, *values in zip(cols.node_ids, *(cols.node_attrs[k] for k in node_keys))
53
+ )
54
+ m = len(cols.src)
55
+ if m == 0:
56
+ return H
57
+
58
+ attrs = cols.edge_attrs
59
+ src, dst = np.asarray(cols.src, dtype=np.int64), np.asarray(cols.dst, dtype=np.int64)
60
+ # Groups numbered in order of first appearance, as the dict of `main`
61
+ gid = pd.factorize(src * len(cols.node_ids) + dst)[0]
62
+ if per_edge_type:
63
+ label_codes, labels = _factorize(attrs, "label", m)
64
+ gid = pd.factorize(gid.astype(np.int64) * len(labels) + label_codes)[0]
65
+ gid = gid.astype(np.int64)
66
+ num_groups = int(gid.max()) + 1
67
+ time = attrs.array("time", np.int64)
68
+
69
+ # First event of each group: earliest time, then earliest in edge order (stable sort)
70
+ order = np.lexsort((time, gid))
71
+ sorted_gid = gid[order]
72
+ starts = np.flatnonzero(np.r_[True, sorted_gid[1:] != sorted_gid[:-1]])
73
+ first_idx = order[starts] # indexed by group
74
+
75
+ counts = np.bincount(gid, minlength=num_groups)
76
+ if "y" in attrs:
77
+ y_max = np.maximum.reduceat(attrs.array("y", np.int64)[order], starts)
78
+ else:
79
+ y_max = np.zeros(num_groups, dtype=np.int64)
80
+
81
+ extra = {} # aggregated column -> per-group values
82
+ for attr in attributes:
83
+ codes, uniques = _factorize(attrs, attr.name, m)
84
+ if attr.kind == "categorical":
85
+ known = set(attr.values)
86
+ index = {value: i for i, (_, value) in enumerate(columns[attr.name])}
87
+ lut = np.array(
88
+ [index.get(v if v in known else attr.OTHER, -1) for v in map(str, uniques)],
89
+ dtype=np.int64,
90
+ )
91
+ value_idx = lut[codes]
92
+ kept = value_idx >= 0
93
+ k = len(index)
94
+ table = np.bincount(
95
+ gid[kept] * k + value_idx[kept], minlength=num_groups * k
96
+ ).reshape(num_groups, k)
97
+ for i, (column, _) in enumerate(columns[attr.name]):
98
+ extra[column] = table[:, i]
99
+ else:
100
+ lut = np.array([np.nan if v is None else float(v) for v in uniques], dtype=np.float64)
101
+ xs = lut[codes]
102
+ valid = ~np.isnan(xs)
103
+ x = np.where(valid, xs, 0.0)
104
+ n = np.bincount(gid, weights=valid, minlength=num_groups)
105
+ with np.errstate(invalid="ignore", divide="ignore"):
106
+ mean = np.where(n > 0, np.bincount(gid, weights=x, minlength=num_groups) / n, 0.0)
107
+ sq = np.where(valid, (x - mean[gid]) ** 2, 0.0)
108
+ var = np.bincount(gid, weights=sq, minlength=num_groups) / n
109
+ std = np.where(n > 0, np.sqrt(var), 0.0)
110
+ stats = {"n": n.astype(np.int64), "mean": mean, "std": std}
111
+ for column, stat in columns[attr.name]:
112
+ extra[column] = stats[stat]
113
+
114
+ c = counts.astype(np.float64)
115
+ mean, std = c.mean(), c.std()
116
+ z = (c - mean) / std if std > 0 else np.zeros(num_groups)
117
+ weight = 1.0 / (1.0 + np.exp(-z))
118
+
119
+ # Merged edges ordered by the time of their first event (ties: group order)
120
+ group_order = np.lexsort((np.arange(num_groups), time[first_idx]))
121
+ edge_idx = first_idx[group_order]
122
+ keys = list(attrs) + [k for k in ("y", "count") if k not in attrs] + list(extra) + ["weight"]
123
+ values = {k: attrs.take(k, edge_idx) for k in attrs}
124
+ values["y"] = y_max[group_order].tolist()
125
+ values["count"] = counts[group_order].tolist()
126
+ for column, col_values in extra.items():
127
+ values[column] = col_values[group_order].tolist()
128
+ values["weight"] = weight[group_order].tolist()
129
+
130
+ node_ids = cols.node_ids
131
+ us = [node_ids[i] for i in src[edge_idx].tolist()]
132
+ vs = [node_ids[i] for i in dst[edge_idx].tolist()]
133
+ H.add_edges_from(
134
+ (u, v, dict(zip(keys, row))) for u, v, *row in zip(us, vs, *(values[k] for k in keys))
135
+ )
136
+ return H
@@ -0,0 +1,510 @@
1
+ """R-Caid pseudo-graph transformation.
2
+
3
+ Each root node (whose earliest outgoing edge precedes its earliest incoming edge) gets an edge
4
+ to each of its descendants. With pruning, roots reaching more than half of the nodes get none.
5
+ Only these root -> descendant edges are kept, with random timestamps drawn in the range of the
6
+ original timestamps.
7
+
8
+ The options of `transformation.rcaid_pseudo_graph` (see `Options`) follow the paper (Section
9
+ 4.2): roots are files and sockets (`root_node_types`), and the GNN passes messages over the
10
+ provenance graph and over the pseudo edges, whose sources keep their initial features
11
+ (`keep_original_edges`: the original edges are kept, and the pseudo edges have no edge type).
12
+ They also bound the pseudo-graph, which the paper only prunes with `prune_threshold`: a process
13
+ reading thousands of files gives as many roots to each of its descendants (902M pseudo edges in
14
+ a window of THEIA_E5 with 146K nodes). Roots with the same label bring the same features and are
15
+ merged (`merge_same_label_roots`), and each node keeps its `max_roots_per_node` most specific
16
+ roots, those with the fewest descendants (as the paper prunes the roots reaching many nodes).
17
+ Unset, the options give the original transformation described below.
18
+
19
+ The result is identical to the original implementation (kept in
20
+ `tests/test_rcaid_transformation.py`), which built a pseudo-graph with one pseudo-root per root
21
+ connected to `nx.descendants(G, root)`, pruned it, merged the pseudo-roots into their roots with
22
+ `nx.relabel_nodes`, added the timestamps and converted the result to a MultiDiGraph. Its output
23
+ is fully determined by:
24
+
25
+ - the nodes of G, in order, with copies of their attributes;
26
+ - for each kept root in node order, its descendants in the iteration order of the set returned
27
+ by `nx.descendants`, i.e. a set built by inserting the descendants in breadth-first order
28
+ (the iteration order of a set depends on its insertion order, so the set is rebuilt the same
29
+ way);
30
+ - `np.random.randint(min_t, max_t, size=num_edges)` assigned to the edges in that order.
31
+
32
+ It is computed here without building the pseudo-graph and without exploring the descendants of
33
+ pruned roots:
34
+
35
+ - roots are found with numpy from the edge timestamps;
36
+ - the breadth-first order from a root r only depends on its successors S (the BFS starts with
37
+ r's successors, in adjacency order), and is the same for all roots with the same S, except
38
+ that r itself is skipped when it is reachable from S (r is then in the same strongly
39
+ connected component as one of its successors). Roots with the same successors (e.g. files
40
+ read by the same process) thus share one BFS;
41
+ - with pruning, a BFS stops as soon as it has seen enough nodes for the root to be pruned. Nodes
42
+ known to reach too many nodes ("big") are marked with all their ancestors, so that the BFS of
43
+ later roots stop when they meet one.
44
+ """
45
+
46
+ import gc
47
+
48
+ import networkx as nx
49
+ import numpy as np
50
+ import scipy.sparse as sp
51
+ from scipy.sparse.csgraph import connected_components
52
+
53
+ from pidsmaker.utils import graph_store
54
+
55
+ from .transformation_utils import randint_timestamps
56
+
57
+ PRUNE_THRESHOLD = 0.5
58
+
59
+
60
+ class _Structure:
61
+ """What the transformation reads from a graph: `nodes` (in order), `succ` (the unique
62
+ successors of each node, as positions in `nodes`, in adjacency order: the order in which
63
+ `nx.bfs_edges` visits them), and the ends (node positions) and times of all the edges, in
64
+ `G.edges(data=True)` order."""
65
+
66
+ def __init__(self, nodes, succ, src, dst, times, node_attr=None):
67
+ self.nodes, self.succ, self.src, self.dst, self.times = nodes, succ, src, dst, times
68
+ self.pos = {n: i for i, n in enumerate(nodes)}
69
+ # node_attr(key): the values of a node attribute, in node order
70
+ self.node_attr = node_attr
71
+
72
+ @classmethod
73
+ def from_graph(cls, G):
74
+ nodes = list(G._node)
75
+ pos = {n: i for i, n in enumerate(nodes)}
76
+ succ = [[pos[v] for v in G._succ[n]] for n in nodes]
77
+ src, dst, times = [], [], []
78
+ multi = G.is_multigraph()
79
+ for u, nbrs in G._succ.items():
80
+ ui = pos[u]
81
+ for v, inner in nbrs.items():
82
+ vi = pos[v]
83
+ if multi:
84
+ for d in inner.values():
85
+ src.append(ui)
86
+ dst.append(vi)
87
+ times.append(d["time"])
88
+ else:
89
+ src.append(ui)
90
+ dst.append(vi)
91
+ times.append(inner["time"])
92
+ node_store = G._node
93
+ return cls(
94
+ nodes, succ, np.asarray(src, dtype=np.int64), np.asarray(dst, dtype=np.int64), times,
95
+ node_attr=lambda key: [node_store[n].get(key) for n in nodes],
96
+ )
97
+
98
+ @classmethod
99
+ def from_columns(cls, cols):
100
+ """From the `GraphColumns` of a stored graph (edges in `G.edges` order, so grouped by
101
+ source node in node order, and by (source, destination) pair)."""
102
+ nodes = cols.node_ids
103
+ src = cols.src.astype(np.int64)
104
+ dst = cols.dst.astype(np.int64)
105
+ n, m = len(nodes), len(src)
106
+ if m:
107
+ starts = np.flatnonzero(np.r_[True, (src[1:] != src[:-1]) | (dst[1:] != dst[:-1])])
108
+ else:
109
+ starts = np.zeros(0, dtype=np.int64)
110
+ pair_src, pair_dst = src[starts], dst[starts]
111
+ bounds = np.searchsorted(pair_src, np.arange(n + 1)).tolist()
112
+ pair_dst = pair_dst.tolist()
113
+ succ = [pair_dst[bounds[i] : bounds[i + 1]] for i in range(n)]
114
+ times = cols.edge_attrs["time"] if m else []
115
+ return cls(nodes, succ, src, dst, times, node_attr=lambda key: cols.node_attrs[key])
116
+
117
+
118
+ def _numeric_times(times):
119
+ """The times as a numpy array if they can be compared exactly with numpy, else None."""
120
+ types = set(map(type, times))
121
+ try:
122
+ if types <= {int, np.int64}:
123
+ return np.array(times, dtype=np.int64)
124
+ if types == {float}:
125
+ arr = np.array(times, dtype=np.float64)
126
+ return None if np.isnan(arr).any() else arr
127
+ except OverflowError:
128
+ pass
129
+ return None
130
+
131
+
132
+ def _root_mask(num_nodes, src, dst, times):
133
+ """Boolean mask of the root nodes (same rule as `identify_root_nodes` of the original)."""
134
+ arr = _numeric_times(times)
135
+ if arr is None:
136
+ # Exact Python comparison of arbitrary values
137
+ out_min, in_min = {}, {}
138
+ for u, v, t in zip(src.tolist(), dst.tolist(), times):
139
+ if u not in out_min or t < out_min[u]:
140
+ out_min[u] = t
141
+ if v not in in_min or t < in_min[v]:
142
+ in_min[v] = t
143
+ mask = np.zeros(num_nodes, dtype=bool)
144
+ for u, t in out_min.items():
145
+ if u not in in_min or t < in_min[u]:
146
+ mask[u] = True
147
+ return mask
148
+
149
+ src_a, dst_a = src, dst
150
+ has_out = np.bincount(src_a, minlength=num_nodes) > 0
151
+ has_in = np.bincount(dst_a, minlength=num_nodes) > 0
152
+ out_min = np.zeros(num_nodes, dtype=arr.dtype)
153
+ in_min = np.zeros(num_nodes, dtype=arr.dtype)
154
+ # Min per node: sort by (node, time) and take the first time of each node
155
+ order = np.lexsort((arr, src_a))
156
+ first = np.r_[True, src_a[order][1:] != src_a[order][:-1]] if len(order) else order.astype(bool)
157
+ out_min[src_a[order][first]] = arr[order][first]
158
+ order = np.lexsort((arr, dst_a))
159
+ first = np.r_[True, dst_a[order][1:] != dst_a[order][:-1]] if len(order) else order.astype(bool)
160
+ in_min[dst_a[order][first]] = arr[order][first]
161
+ return has_out & (~has_in | (out_min < in_min))
162
+
163
+
164
+ class _Descendants:
165
+ """Descendants of the roots in the order of the original implementation."""
166
+
167
+ def __init__(self, structure, use_pruning, prune_threshold=PRUNE_THRESHOLD):
168
+ self.nodes = structure.nodes
169
+ self.pos = structure.pos
170
+ self.succ = structure.succ
171
+ n = len(self.nodes)
172
+ self.pred = None # built on first use
173
+ # Original rule: pruned if the number of descendants is > prune_threshold * |V|
174
+ self.max_desc = prune_threshold * n if use_pruning else None
175
+ # A BFS from a successor set S stops once |reach(S)| > max_desc + 1: then every root
176
+ # with these successors has > max_desc descendants
177
+ self.big = bytearray(n) # nodes v with |reach(v) including v| > max_desc + 1
178
+ self.seen = bytearray(n)
179
+ self.cache = {}
180
+
181
+ indptr = np.zeros(n + 1, dtype=np.int64)
182
+ np.cumsum([len(s) for s in self.succ], out=indptr[1:])
183
+ indices = np.fromiter((v for s in self.succ for v in s), dtype=np.int64, count=indptr[-1])
184
+ adj = sp.csr_matrix((np.ones(len(indices), dtype=np.int8), indices, indptr), shape=(n, n))
185
+ _, self.scc = connected_components(adj, directed=True, connection="strong")
186
+ self.scc = self.scc.tolist()
187
+
188
+ def _mark_big(self, v):
189
+ """Marks v and all its ancestors as big."""
190
+ if self.big[v]:
191
+ return
192
+ if self.pred is None:
193
+ self.pred = [[] for _ in range(len(self.succ))]
194
+ for u, s in enumerate(self.succ):
195
+ for w in s:
196
+ self.pred[w].append(u)
197
+ big, pred = self.big, self.pred
198
+ big[v] = 1
199
+ stack = [v]
200
+ while stack:
201
+ for u in pred[stack.pop()]:
202
+ if not big[u]:
203
+ big[u] = 1
204
+ stack.append(u)
205
+
206
+ def _bfs(self, start):
207
+ """Nodes reachable from `start` (included) in BFS order, or None if too many (or if a
208
+ big node is reachable)."""
209
+ seen, succ, big = self.seen, self.succ, self.big
210
+ limit = None if self.max_desc is None else self.max_desc + 1
211
+ order = list(start)
212
+ for v in order:
213
+ seen[v] = 1
214
+ too_many = False
215
+ i = 0
216
+ while i < len(order):
217
+ for v in succ[order[i]]:
218
+ if not seen[v]:
219
+ if big[v]:
220
+ too_many = True
221
+ break
222
+ seen[v] = 1
223
+ order.append(v)
224
+ if too_many or (limit is not None and len(order) > limit):
225
+ too_many = True
226
+ break
227
+ i += 1
228
+ for v in order:
229
+ seen[v] = 0
230
+ return None if too_many else order
231
+
232
+ def _set_order(self, order):
233
+ """Positions of the nodes `order` in the iteration order of a set of their IDs filled in
234
+ this order (as `nx.descendants` returns them)."""
235
+ ids = set(map(self.nodes.__getitem__, order))
236
+ return np.fromiter(map(self.pos.__getitem__, ids), dtype=np.int64, count=len(ids))
237
+
238
+ def of_root(self, r):
239
+ """Positions of the descendants of root r in output order, or None if pruned."""
240
+ start = tuple(v for v in self.succ[r] if v != r)
241
+ if not start:
242
+ return np.zeros(0, dtype=np.int64)
243
+ scc = self.scc
244
+ in_cycle = any(scc[v] == scc[r] for v in start)
245
+ if not in_cycle and start in self.cache:
246
+ return self.cache[start]
247
+
248
+ if self.max_desc is not None and any(self.big[v] for v in start):
249
+ result = None
250
+ else:
251
+ order = self._bfs(start)
252
+ if order is None:
253
+ result = None
254
+ if len(start) == 1:
255
+ self._mark_big(start[0])
256
+ else:
257
+ if in_cycle:
258
+ # r is reached again from its successors, but nx.descendants skips it.
259
+ # As r only leads to nodes already seen, the order is otherwise the same
260
+ order = [v for v in order if v != r]
261
+ if self.max_desc is not None and len(order) > self.max_desc:
262
+ result = None
263
+ else:
264
+ result = self._set_order(order)
265
+ if result is None and self.max_desc is not None:
266
+ # More than max_desc descendants: reach(r) has more than max_desc + 1 nodes
267
+ self._mark_big(r)
268
+ if not in_cycle:
269
+ self.cache[start] = result
270
+ return result
271
+
272
+
273
+
274
+
275
+ class Options:
276
+ """Options of the transformation (`transformation.rcaid_pseudo_graph`). Unset options keep
277
+ the behavior of the original implementation."""
278
+
279
+ def __init__(self, cfg):
280
+ c = cfg.transformation.rcaid_pseudo_graph
281
+ self.use_pruning = bool(c.use_pruning)
282
+ threshold = getattr(c, "prune_threshold", None)
283
+ self.prune_threshold = PRUNE_THRESHOLD if threshold is None else float(threshold)
284
+ types = (getattr(c, "root_node_types", None) or "all").strip()
285
+ self.root_node_types = (
286
+ None if types == "all" else {t.strip() for t in types.split(",") if t.strip()}
287
+ )
288
+ self.keep_original_edges = bool(getattr(c, "keep_original_edges", None) or False)
289
+ self.merge_same_label_roots = bool(getattr(c, "merge_same_label_roots", None) or False)
290
+ max_roots = getattr(c, "max_roots_per_node", None)
291
+ self.max_roots_per_node = int(max_roots) if max_roots else None # 0 or unset: no limit
292
+
293
+
294
+ def _factorize(values):
295
+ """Integer codes of hashable values (equal values have equal codes)."""
296
+ index = {}
297
+ return np.fromiter((index.setdefault(v, len(index)) for v in values), np.int64, count=len(values))
298
+
299
+
300
+ def pseudo_graph_edges(structure, use_pruning, options=None):
301
+ """Pseudo edges (root -> descendant) of the transformed graph, in order, as arrays of node
302
+ positions (src, dst).
303
+
304
+ Without options, as in the original implementation: every root gets an edge to each of its
305
+ descendants (in the order of `nx.descendants`), roots in node order. With options:
306
+
307
+ - `root_node_types`: only the roots of these types get edges;
308
+ - `merge_same_label_roots`: a node gets a single pseudo edge from all its roots with the same
309
+ (node type, label), which bring the same features;
310
+ - `max_roots_per_node`: a node gets pseudo edges from at most this number of roots, the most
311
+ specific ones: those with the fewest descendants (then in node order). This bounds the
312
+ number of pseudo edges by `max_roots_per_node` times the number of nodes.
313
+
314
+ Edges are ordered by root (in node order), then as without options. Merged roots are
315
+ represented by the first of them processed: in node order without `max_roots_per_node`, by
316
+ specificity otherwise.
317
+ """
318
+ st = structure
319
+ prune_threshold = PRUNE_THRESHOLD if options is None else options.prune_threshold
320
+ mask = _root_mask(len(st.nodes), st.src, st.dst, st.times)
321
+ if options is not None and options.root_node_types is not None:
322
+ types = st.node_attr("node_type")
323
+ mask &= np.fromiter((t in options.root_node_types for t in types), bool, count=len(types))
324
+ roots = np.flatnonzero(mask).tolist()
325
+ empty = np.zeros(0, dtype=np.int64)
326
+ if not roots:
327
+ return empty, empty
328
+
329
+ merge = options is not None and options.merge_same_label_roots
330
+ if merge:
331
+ key = _factorize(list(zip(st.node_attr("node_type"), st.node_attr("label"))))
332
+ max_roots = None if options is None else options.max_roots_per_node
333
+
334
+ desc = _Descendants(st, use_pruning, prune_threshold)
335
+ # Roots with a single successor first: they are the most likely to identify big nodes
336
+ results = {}
337
+ for r in sorted(roots, key=lambda r: len(st.succ[r]) != 1):
338
+ results[r] = desc.of_root(r)
339
+ roots = [r for r in roots if results[r] is not None and len(results[r])]
340
+ if not roots:
341
+ return empty, empty
342
+
343
+ if max_roots is not None:
344
+ return _capped_pseudo_edges(len(st.nodes), roots, results, max_roots, key if merge else None)
345
+
346
+ out_src, out_dst = [], []
347
+ # With merging, the roots with the same successors have the same descendants: only the first
348
+ # root of each key gets edges there. The (key, descendant) pairs of the roots with different
349
+ # successors are deduplicated afterwards
350
+ seen_keys = {}
351
+ for r in roots:
352
+ d = results[r]
353
+ if merge:
354
+ group = seen_keys.setdefault(tuple(st.succ[r]), set())
355
+ if key[r] in group:
356
+ continue
357
+ group.add(key[r])
358
+ out_src.append(np.full(len(d), r, dtype=np.int64))
359
+ out_dst.append(d)
360
+ if not out_src:
361
+ return empty, empty
362
+ src, dst = np.concatenate(out_src), np.concatenate(out_dst)
363
+ if merge:
364
+ _, first = np.unique(key[src] * len(st.nodes) + dst, return_index=True)
365
+ first.sort()
366
+ src, dst = src[first], dst[first]
367
+ return src, dst
368
+
369
+
370
+ def _capped_pseudo_edges(num_nodes, roots, results, max_roots, key=None):
371
+ """Pseudo edges when each node keeps at most `max_roots` roots, the ones with the fewest
372
+ descendants first (then in node order); with `key`, at most one root per key and node."""
373
+ count = np.zeros(num_nodes, dtype=np.int64)
374
+ # Keys of the roots of each node (-1: none), to merge the roots with the same key
375
+ node_keys = np.full((num_nodes, max_roots), -1, dtype=np.int64) if key is not None else None
376
+ selected = {}
377
+ for r in sorted(roots, key=lambda r: len(results[r])):
378
+ d = results[r]
379
+ d = d[count[d] < max_roots]
380
+ if key is not None and len(d):
381
+ d = d[~(node_keys[d] == key[r]).any(axis=1)]
382
+ node_keys[d, count[d]] = key[r]
383
+ if len(d):
384
+ count[d] += 1
385
+ selected[r] = d
386
+ empty = np.zeros(0, dtype=np.int64)
387
+ if not selected:
388
+ return empty, empty
389
+ order = sorted(selected)
390
+ src = np.concatenate([np.full(len(selected[r]), r, dtype=np.int64) for r in order])
391
+ dst = np.concatenate([selected[r] for r in order])
392
+ return src, dst
393
+
394
+
395
+ def _transform(structure, cfg):
396
+ """(src, dst, times) of the pseudo edges of the transformed graph."""
397
+ options = Options(cfg)
398
+ src, dst = pseudo_graph_edges(structure, options.use_pruning, options)
399
+ times = structure.times
400
+ # Raises ValueError on graphs without edges, as the original
401
+ min_t, max_t = min(times), max(times)
402
+ return src, dst, randint_timestamps(min_t, max_t, len(src))
403
+
404
+
405
+ def _build_multidigraph(G, nodes, src, dst, edge_times):
406
+ """MultiDiGraph with the nodes of G (copied attributes) and the edges (key 0, {"time": t})
407
+ added in order, as `nx.MultiDiGraph(DiGraph)` builds it."""
408
+ gc_enabled = gc.isenabled()
409
+ gc.disable() # building many containers triggers costly GC passes that free nothing
410
+ try:
411
+ H = nx.MultiDiGraph()
412
+ node_store, succ, pred = H._node, H._succ, H._pred
413
+ for n, d in G._node.items():
414
+ node_store[n] = d.copy()
415
+ succ[n] = {}
416
+ pred[n] = {}
417
+ node_arr = np.empty(len(nodes), dtype=object)
418
+ node_arr[:] = nodes
419
+ for u, v, t in zip(node_arr[src].tolist(), node_arr[dst].tolist(), edge_times):
420
+ inner = {0: {"time": t}}
421
+ succ[u][v] = inner
422
+ pred[v][u] = inner
423
+ finally:
424
+ if gc_enabled:
425
+ gc.enable()
426
+ return H
427
+
428
+
429
+ def _pseudo_edge_attr(key, num_pseudo, pseudo_times):
430
+ """Values of the edge attribute `key` for the pseudo edges: a random time, a `y` of 0, and
431
+ None otherwise (in particular no edge type `label`)."""
432
+ if key == "time":
433
+ return [int(t) for t in pseudo_times]
434
+ if key == "y":
435
+ return [0] * num_pseudo
436
+ return [None] * num_pseudo
437
+
438
+
439
+ def _all_edge_attrs(edge_keys, orig_attr, pseudo_times):
440
+ """{key: values} of the original edges (`orig_attr(key)`) followed by the pseudo edges."""
441
+ out = {}
442
+ for k in edge_keys:
443
+ values = list(orig_attr(k))
444
+ if k == "time":
445
+ values = [int(t) for t in values]
446
+ out[k] = values + _pseudo_edge_attr(k, len(pseudo_times), pseudo_times)
447
+ return out
448
+
449
+
450
+ def _with_original_edges(G, nodes, src, dst, rand_t):
451
+ """MultiDiGraph with the nodes and edges of G (copied attributes), followed by the pseudo
452
+ edges."""
453
+ H = nx.MultiDiGraph()
454
+ H.add_nodes_from((n, d.copy()) for n, d in G._node.items())
455
+ edge_dicts = [d for _, _, d in G.edges(data=True)]
456
+ H.add_edges_from((u, v, d.copy()) for u, v, d in G.edges(data=True))
457
+ edge_keys = list(edge_dicts[0]) if edge_dicts else ["time"]
458
+ columns = {k: _pseudo_edge_attr(k, len(src), rand_t) for k in edge_keys}
459
+ for i, (u, v) in enumerate(zip(np.asarray(src).tolist(), np.asarray(dst).tolist())):
460
+ H.add_edge(nodes[u], nodes[v], **{k: columns[k][i] for k in edge_keys})
461
+ return H
462
+
463
+
464
+ def main(graph: nx.Graph, cfg) -> nx.Graph:
465
+ structure = _Structure.from_graph(graph)
466
+ src, dst, rand_t = _transform(structure, cfg)
467
+ if Options(cfg).keep_original_edges:
468
+ return _with_original_edges(graph, structure.nodes, src, dst, rand_t)
469
+ return _build_multidigraph(graph, structure.nodes, src, dst, rand_t)
470
+
471
+
472
+ def transform_and_save(graph, cfg, path):
473
+ """Saves `main(graph, cfg)` to `path` as `save_graph` would, without building it."""
474
+ structure = _Structure.from_graph(graph)
475
+ src, dst, rand_t = _transform(structure, cfg)
476
+ node_cols = graph_store.encode_attr_dicts(list(graph._node.values()))
477
+ keep_original = Options(cfg).keep_original_edges
478
+ if node_cols is None: # not storable as columns: saved as a pickle
479
+ if keep_original:
480
+ graph = _with_original_edges(graph, structure.nodes, src, dst, rand_t)
481
+ else:
482
+ graph = _build_multidigraph(graph, structure.nodes, src, dst, rand_t)
483
+ graph_store.save_graph(graph, path)
484
+ return
485
+ if keep_original:
486
+ edge_dicts = [d for _, _, d in graph.edges(data=True)]
487
+ edge_keys = list(edge_dicts[0]) if edge_dicts else ["time"]
488
+ attrs = _all_edge_attrs(edge_keys, lambda k: [d.get(k) for d in edge_dicts], rand_t)
489
+ graph_store.save_multi_edge_positions(
490
+ path, structure.nodes, node_cols, np.concatenate([structure.src, src]),
491
+ np.concatenate([structure.dst, dst]), attrs,
492
+ )
493
+ return
494
+ graph_store.save_edge_positions(path, structure.nodes, node_cols, src, dst, {"time": rand_t})
495
+
496
+
497
+ def transform_columns_and_save(cols, cfg, path):
498
+ """Same as `transform_and_save` on the graph stored with the `GraphColumns` cols."""
499
+ structure = _Structure.from_columns(cols)
500
+ src, dst, rand_t = _transform(structure, cfg)
501
+ node_cols = cols.node_attrs.encoded()
502
+ if Options(cfg).keep_original_edges:
503
+ edge_keys = list(cols.edge_attrs) or ["time"]
504
+ attrs = _all_edge_attrs(edge_keys, lambda k: cols.edge_attrs[k], rand_t)
505
+ graph_store.save_multi_edge_positions(
506
+ path, structure.nodes, node_cols, np.concatenate([structure.src, src]),
507
+ np.concatenate([structure.dst, dst]), attrs,
508
+ )
509
+ return
510
+ graph_store.save_edge_positions(path, structure.nodes, node_cols, src, dst, {"time": rand_t})