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.
- pidsmaker/__init__.py +1 -0
- pidsmaker/cli.py +81 -0
- pidsmaker/config/__init__.py +2 -0
- pidsmaker/config/config.py +2100 -0
- pidsmaker/config/pipeline.py +1824 -0
- pidsmaker/config/schemas.py +1032 -0
- pidsmaker/datasets.py +323 -0
- pidsmaker/debug_tests.py +30 -0
- pidsmaker/decoders/__init__.py +5 -0
- pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
- pidsmaker/decoders/custom_mlp_decoder.py +10 -0
- pidsmaker/decoders/edge_linear_decoder.py +16 -0
- pidsmaker/decoders/inner_product_decoder.py +18 -0
- pidsmaker/decoders/nodlink_decoder.py +56 -0
- pidsmaker/detection/__init__.py +0 -0
- pidsmaker/detection/evaluation_methods/__init__.py +9 -0
- pidsmaker/detection/evaluation_methods/edge_evaluation.py +255 -0
- pidsmaker/detection/evaluation_methods/evaluation_utils.py +1788 -0
- pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
- pidsmaker/detection/evaluation_methods/node_evaluation.py +459 -0
- pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
- pidsmaker/detection/evaluation_methods/plot.py +192 -0
- pidsmaker/detection/evaluation_methods/queue_evaluation.py +456 -0
- pidsmaker/detection/evaluation_methods/tw_evaluation.py +93 -0
- pidsmaker/detection/flash_detection.py +162 -0
- pidsmaker/detection/magic_knn.py +190 -0
- pidsmaker/detection/node_scoring.py +52 -0
- pidsmaker/detection/threatrace_detection.py +65 -0
- pidsmaker/detection/training_methods/__init__.py +1 -0
- pidsmaker/detection/training_methods/inference_loop.py +287 -0
- pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
- pidsmaker/detection/training_methods/threatrace_training.py +168 -0
- pidsmaker/detection/training_methods/training_loop.py +383 -0
- pidsmaker/encoders/__init__.py +22 -0
- pidsmaker/encoders/argus_encoder.py +69 -0
- pidsmaker/encoders/custom_mlp.py +75 -0
- pidsmaker/encoders/custom_mlp_encoder.py +10 -0
- pidsmaker/encoders/egraphsage_encoder.py +56 -0
- pidsmaker/encoders/gat.py +67 -0
- pidsmaker/encoders/gcn.py +27 -0
- pidsmaker/encoders/gin.py +48 -0
- pidsmaker/encoders/glstm.py +298 -0
- pidsmaker/encoders/graph_attention.py +63 -0
- pidsmaker/encoders/gru.py +29 -0
- pidsmaker/encoders/hetero/__init__.py +4 -0
- pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
- pidsmaker/encoders/hetero/entity_encoder.py +33 -0
- pidsmaker/encoders/hetero/event_encoder.py +81 -0
- pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
- pidsmaker/encoders/lares_encoder.py +68 -0
- pidsmaker/encoders/linear_encoder.py +16 -0
- pidsmaker/encoders/magic_encoder.py +161 -0
- pidsmaker/encoders/rcaid_encoder.py +81 -0
- pidsmaker/encoders/rgcn.py +75 -0
- pidsmaker/encoders/sage.py +51 -0
- pidsmaker/encoders/shadewatcher_encoder.py +149 -0
- pidsmaker/encoders/sum_aggregation.py +20 -0
- pidsmaker/encoders/temporal_wrappers.py +80 -0
- pidsmaker/encoders/textrcnn.py +82 -0
- pidsmaker/encoders/tgn_encoder.py +193 -0
- pidsmaker/experiments/tuning.py +102 -0
- pidsmaker/experiments/uncertainty.py +261 -0
- pidsmaker/factory.py +1456 -0
- pidsmaker/featurization/__init__.py +0 -0
- pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +30 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +65 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +14 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +53 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +37 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +69 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +84 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1728 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +55 -0
- pidsmaker/featurization/featurization_methods/__init__.py +0 -0
- pidsmaker/featurization/featurization_methods/build_trw.py +66 -0
- pidsmaker/featurization/featurization_methods/featurization_alacarte.py +747 -0
- pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +98 -0
- pidsmaker/featurization/featurization_methods/featurization_fasttext.py +74 -0
- pidsmaker/featurization/featurization_methods/featurization_flash.py +201 -0
- pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +242 -0
- pidsmaker/featurization/featurization_methods/featurization_trw.py +114 -0
- pidsmaker/featurization/featurization_methods/featurization_word2vec.py +89 -0
- pidsmaker/featurization/featurization_utils.py +275 -0
- pidsmaker/featurization/utils/build_random_walks.py +66 -0
- pidsmaker/featurization/utils/trw.py +203 -0
- pidsmaker/hetero.py +81 -0
- pidsmaker/losses.py +170 -0
- pidsmaker/main.py +478 -0
- pidsmaker/mimicry.py +284 -0
- pidsmaker/model.py +382 -0
- pidsmaker/objectives/__init__.py +16 -0
- pidsmaker/objectives/autoencode_edge_emb.py +43 -0
- pidsmaker/objectives/deep_graph_infomax.py +94 -0
- pidsmaker/objectives/detect_few_shot.py +21 -0
- pidsmaker/objectives/one_class.py +75 -0
- pidsmaker/objectives/predict_edge_contrastive.py +165 -0
- pidsmaker/objectives/predict_edge_supervised.py +77 -0
- pidsmaker/objectives/predict_edge_type.py +28 -0
- pidsmaker/objectives/predict_masked_struct.py +49 -0
- pidsmaker/objectives/predict_node_type.py +36 -0
- pidsmaker/objectives/predict_process_tag.py +169 -0
- pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
- pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
- pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
- pidsmaker/objectives/reconstruct_node_emb.py +13 -0
- pidsmaker/objectives/reconstruct_node_feat.py +13 -0
- pidsmaker/objectives/validation_wrapper.py +55 -0
- pidsmaker/preprocessing/__init__.py +0 -0
- pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
- pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +825 -0
- pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +216 -0
- pidsmaker/preprocessing/cleaning.py +258 -0
- pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
- pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
- pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
- pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
- pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
- pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
- pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
- pidsmaker/pretrained/__init__.py +5 -0
- pidsmaker/pretrained/data/__init__.py +4 -0
- pidsmaker/pretrained/data/behavior_signatures.py +548 -0
- pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
- pidsmaker/pretrained/data/edge_filter.py +381 -0
- pidsmaker/pretrained/data/entity_classes.py +476 -0
- pidsmaker/pretrained/data/sampler.py +926 -0
- pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
- pidsmaker/pretrained/detect.py +1427 -0
- pidsmaker/pretrained/embedding_generator.py +252 -0
- pidsmaker/pretrained/finetune.py +1434 -0
- pidsmaker/pretrained/models/__init__.py +20 -0
- pidsmaker/pretrained/models/behavior.py +348 -0
- pidsmaker/pretrained/models/bert.py +286 -0
- pidsmaker/pretrained/models/deepwalk.py +128 -0
- pidsmaker/pretrained/models/dgi.py +120 -0
- pidsmaker/pretrained/models/gae.py +114 -0
- pidsmaker/pretrained/models/gnn_distill.py +475 -0
- pidsmaker/pretrained/models/graphmae.py +373 -0
- pidsmaker/pretrained/models/hf_pretrained.py +213 -0
- pidsmaker/pretrained/models/llama.py +110 -0
- pidsmaker/pretrained/models/modernbert.py +567 -0
- pidsmaker/pretrained/models/roberta.py +147 -0
- pidsmaker/pretrained/models/rope_utils.py +99 -0
- pidsmaker/pretrained/models/ropebert.py +322 -0
- pidsmaker/pretrained/models/spider.py +204 -0
- pidsmaker/pretrained/models/tgn.py +770 -0
- pidsmaker/pretrained/pretrain/__init__.py +3 -0
- pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
- pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
- pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
- pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
- pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
- pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
- pidsmaker/pretrained/pretrain/pretrain_main.py +275 -0
- pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
- pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
- pidsmaker/pretrained/training_utils.py +157 -0
- pidsmaker/process_reapr_gt.py +101 -0
- pidsmaker/resources/config/anomal_e.yml +25 -0
- pidsmaker/resources/config/argus.yml +56 -0
- pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
- pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
- pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
- pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
- pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
- pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
- pidsmaker/resources/config/default.yml +315 -0
- pidsmaker/resources/config/egraphsage.yml +95 -0
- pidsmaker/resources/config/euler.yml +104 -0
- pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
- pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
- pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
- pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
- pidsmaker/resources/config/flash.yml +79 -0
- pidsmaker/resources/config/jbeil.yml +65 -0
- pidsmaker/resources/config/kairos.yml +121 -0
- pidsmaker/resources/config/lares.yml +115 -0
- pidsmaker/resources/config/magic.yml +86 -0
- pidsmaker/resources/config/nodlink.yml +79 -0
- pidsmaker/resources/config/ocrapt.yml +91 -0
- pidsmaker/resources/config/orthrus.yml +126 -0
- pidsmaker/resources/config/orthrus_fixed.yml +17 -0
- pidsmaker/resources/config/pretrained/README.md +101 -0
- pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
- pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
- pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
- pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
- pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
- pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
- pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
- pidsmaker/resources/config/prographer.yml +136 -0
- pidsmaker/resources/config/rcaid.yml +88 -0
- pidsmaker/resources/config/shadewatcher.yml +146 -0
- pidsmaker/resources/config/tests.yml +10 -0
- pidsmaker/resources/config/threatrace.yml +73 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
- pidsmaker/resources/config/velox.yml +10 -0
- pidsmaker/resources/config/viz_config.yml +10 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
- pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
- pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
- pidsmaker/resources/ground_truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
- pidsmaker/resources/ground_truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
- pidsmaker/resources/ground_truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
- pidsmaker/resources/ground_truth/orthrus/h051/node_h051_0925.csv +114 -0
- pidsmaker/resources/ground_truth/orthrus/h201/node_h201_0923.csv +2905 -0
- pidsmaker/resources/ground_truth/orthrus/h501/node_h501_0924.csv +749 -0
- pidsmaker/resources/ground_truth/orthrus/readme.md +98 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
- pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
- pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
- pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
- pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
- pidsmaker/resources/ground_truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
- pidsmaker/resources/ground_truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
- pidsmaker/resources/ground_truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
- pidsmaker/resources/ground_truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
- pidsmaker/resources/ground_truth/threatrace/README.md +123 -0
- pidsmaker/tasks/__init__.py +10 -0
- pidsmaker/tasks/batching.py +47 -0
- pidsmaker/tasks/construction.py +31 -0
- pidsmaker/tasks/evaluation.py +241 -0
- pidsmaker/tasks/feat_inference.py +413 -0
- pidsmaker/tasks/featurization.py +43 -0
- pidsmaker/tasks/training.py +17 -0
- pidsmaker/tasks/transformation.py +306 -0
- pidsmaker/tasks/triage.py +143 -0
- pidsmaker/tgn.py +635 -0
- pidsmaker/tokenization/__init__.py +112 -0
- pidsmaker/tokenization/base.py +58 -0
- pidsmaker/tokenization/bpe_tokenizer.py +83 -0
- pidsmaker/tokenization/hf_tokenizer.py +61 -0
- pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
- pidsmaker/tokenization/label_tokenizer.py +24 -0
- pidsmaker/tokenization/nltk_tokenizer.py +84 -0
- pidsmaker/tokenization/substitution.py +295 -0
- pidsmaker/triage/__init__.py +0 -0
- pidsmaker/triage/tracing_methods/__init__.py +1 -0
- pidsmaker/triage/tracing_methods/depimpact.py +213 -0
- pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
- pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
- pidsmaker/utils/__init__.py +0 -0
- pidsmaker/utils/cache_utils.py +256 -0
- pidsmaker/utils/console.py +282 -0
- pidsmaker/utils/data_utils.py +1742 -0
- pidsmaker/utils/database.py +150 -0
- pidsmaker/utils/dataset_utils.py +413 -0
- pidsmaker/utils/dataset_writer.py +570 -0
- pidsmaker/utils/graph_store.py +634 -0
- pidsmaker/utils/labelling.py +445 -0
- pidsmaker/utils/loss_files.py +193 -0
- pidsmaker/utils/process_tags.py +44 -0
- pidsmaker/utils/utils.py +712 -0
- pidsmaker/vizgen/__init__.py +1 -0
- pidsmaker/vizgen/backfill_manifests.py +100 -0
- pidsmaker/vizgen/dimensionality_reduction.py +249 -0
- pidsmaker/vizgen/embed_exporter.py +467 -0
- pidsmaker/vizgen/exporter.py +493 -0
- pidsmaker/vizgen/html_builder.py +936 -0
- pidsmaker/vizgen/web/__init__.py +1 -0
- pidsmaker/vizgen/web/export.py +62 -0
- pidsmaker/vizgen/web/static/css/app.css +250 -0
- pidsmaker/vizgen/web/static/index.html +182 -0
- pidsmaker/vizgen/web/static/js/app.js +627 -0
- pidsmaker/vizgen/web/static/js/campaign.js +123 -0
- pidsmaker/vizgen/web/static/js/data.js +119 -0
- pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
- pidsmaker/vizgen/web/static/js/jobs.js +75 -0
- pidsmaker/vizgen/web/static/js/scene.js +651 -0
- pidsmaker/vizgen/web/static/js/ui.js +370 -0
- pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
- pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
- pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
- pidsmaker/vizgen/web/viz_server.py +2176 -0
- pidsmaker-5.0.0.dist-info/METADATA +597 -0
- pidsmaker-5.0.0.dist-info/RECORD +339 -0
- pidsmaker-5.0.0.dist-info/WHEEL +5 -0
- pidsmaker-5.0.0.dist-info/entry_points.txt +2 -0
- pidsmaker-5.0.0.dist-info/licenses/LICENSE +201 -0
- pidsmaker-5.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,926 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Temporal random walk sampler for provenance graphs.
|
|
3
|
+
|
|
4
|
+
Generates walks on PIDSMaker's NetworkX MultiDiGraphs,
|
|
5
|
+
returning node IDs and edge types suitable for tokenization.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import bisect
|
|
9
|
+
import random
|
|
10
|
+
from collections import Counter
|
|
11
|
+
from typing import Dict, List, Optional, Tuple
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ProvenanceWalkSampler:
|
|
17
|
+
"""Temporal random walk sampler on provenance graphs (NetworkX MultiDiGraph).
|
|
18
|
+
|
|
19
|
+
Each walk produces:
|
|
20
|
+
- walk_nodes: [node_id_0, node_id_1, ..., node_id_k]
|
|
21
|
+
- walk_edge_types: [edge_type_01, edge_type_12, ..., edge_type_(k-1)k]
|
|
22
|
+
- walk_times: [t_01, t_12, ..., t_(k-1)k]
|
|
23
|
+
|
|
24
|
+
Walks are temporally constrained: timestamps must be monotonically increasing
|
|
25
|
+
(forward) or decreasing (backward).
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
graph,
|
|
31
|
+
walk_length: int = 30,
|
|
32
|
+
num_walks: int = 10,
|
|
33
|
+
time_weight: str = "uniform",
|
|
34
|
+
half_life: float = 1.0,
|
|
35
|
+
random_walk_start: bool = False,
|
|
36
|
+
diversity_weight: float = 0.0,
|
|
37
|
+
node2vec_p: float = 1.0,
|
|
38
|
+
node2vec_q: float = 1.0,
|
|
39
|
+
):
|
|
40
|
+
self.graph = graph
|
|
41
|
+
self.walk_length = walk_length
|
|
42
|
+
self.num_walks = num_walks
|
|
43
|
+
self.time_weight = time_weight
|
|
44
|
+
self.half_life = half_life
|
|
45
|
+
self.random_walk_start = random_walk_start
|
|
46
|
+
self.diversity_weight = diversity_weight
|
|
47
|
+
self.node2vec_p = node2vec_p
|
|
48
|
+
self.node2vec_q = node2vec_q
|
|
49
|
+
|
|
50
|
+
self.forward_adj = self._build_forward_adj()
|
|
51
|
+
self.backward_adj = self._build_backward_adj()
|
|
52
|
+
|
|
53
|
+
# Pre-compute neighbor sets for Node2Vec bias (O(1) lookup)
|
|
54
|
+
self._neighbor_sets: Optional[Dict] = None
|
|
55
|
+
if node2vec_p != 1.0 or node2vec_q != 1.0:
|
|
56
|
+
self._neighbor_sets = self._build_neighbor_sets()
|
|
57
|
+
|
|
58
|
+
# Pre-sort adjacency lists by timestamp for O(log n) temporal filtering
|
|
59
|
+
self.forward_times = self._sort_adj_and_extract_times(self.forward_adj)
|
|
60
|
+
self.backward_times = self._sort_adj_and_extract_times(self.backward_adj)
|
|
61
|
+
|
|
62
|
+
self.nodes = list(graph.nodes())
|
|
63
|
+
|
|
64
|
+
# Node labels for diverse neighbor deduplication
|
|
65
|
+
self.node_labels = {}
|
|
66
|
+
for nid, attrs in graph.nodes(data=True):
|
|
67
|
+
ntype = attrs.get("node_type", "unknown")
|
|
68
|
+
label = attrs.get("label", "unknown")
|
|
69
|
+
self.node_labels[nid] = (ntype, label)
|
|
70
|
+
|
|
71
|
+
def save_state(self) -> dict:
|
|
72
|
+
"""Serialize sampler state for disk caching (excludes the NetworkX graph).
|
|
73
|
+
|
|
74
|
+
Returns a dict suitable for torch.save / pickle.
|
|
75
|
+
"""
|
|
76
|
+
return {
|
|
77
|
+
"forward_adj": self.forward_adj,
|
|
78
|
+
"backward_adj": self.backward_adj,
|
|
79
|
+
"forward_times": self.forward_times,
|
|
80
|
+
"backward_times": self.backward_times,
|
|
81
|
+
"nodes": self.nodes,
|
|
82
|
+
"node_labels": self.node_labels,
|
|
83
|
+
"walk_length": self.walk_length,
|
|
84
|
+
"num_walks": self.num_walks,
|
|
85
|
+
"time_weight": self.time_weight,
|
|
86
|
+
"half_life": self.half_life,
|
|
87
|
+
"random_walk_start": self.random_walk_start,
|
|
88
|
+
"diversity_weight": self.diversity_weight,
|
|
89
|
+
"node2vec_p": self.node2vec_p,
|
|
90
|
+
"node2vec_q": self.node2vec_q,
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
@classmethod
|
|
94
|
+
def from_state(cls, state: dict) -> "ProvenanceWalkSampler":
|
|
95
|
+
"""Reconstruct a sampler from a saved state dict (no graph needed)."""
|
|
96
|
+
sampler = object.__new__(cls)
|
|
97
|
+
sampler.forward_adj = state["forward_adj"]
|
|
98
|
+
sampler.backward_adj = state["backward_adj"]
|
|
99
|
+
sampler.forward_times = state["forward_times"]
|
|
100
|
+
sampler.backward_times = state["backward_times"]
|
|
101
|
+
sampler.nodes = state["nodes"]
|
|
102
|
+
sampler.node_labels = state["node_labels"]
|
|
103
|
+
sampler.walk_length = state["walk_length"]
|
|
104
|
+
sampler.num_walks = state["num_walks"]
|
|
105
|
+
sampler.time_weight = state["time_weight"]
|
|
106
|
+
sampler.half_life = state["half_life"]
|
|
107
|
+
sampler.random_walk_start = state["random_walk_start"]
|
|
108
|
+
sampler.diversity_weight = state["diversity_weight"]
|
|
109
|
+
sampler.node2vec_p = state["node2vec_p"]
|
|
110
|
+
sampler.node2vec_q = state["node2vec_q"]
|
|
111
|
+
sampler.graph = None
|
|
112
|
+
sampler._neighbor_sets = None
|
|
113
|
+
if sampler.node2vec_p != 1.0 or sampler.node2vec_q != 1.0:
|
|
114
|
+
neighbors = {}
|
|
115
|
+
for src, edges in sampler.forward_adj.items():
|
|
116
|
+
for dst, _, _ in edges:
|
|
117
|
+
neighbors.setdefault(src, set()).add(dst)
|
|
118
|
+
neighbors.setdefault(dst, set()).add(src)
|
|
119
|
+
sampler._neighbor_sets = neighbors
|
|
120
|
+
return sampler
|
|
121
|
+
|
|
122
|
+
def _build_forward_adj(self) -> Dict:
|
|
123
|
+
"""Build forward adjacency: src -> [(dst, edge_type, time), ...]"""
|
|
124
|
+
adj = {}
|
|
125
|
+
for src, dst, _, attrs in self.graph.edges(data=True, keys=True):
|
|
126
|
+
if src not in adj:
|
|
127
|
+
adj[src] = []
|
|
128
|
+
adj[src].append((dst, attrs.get("label", ""), attrs.get("time", 0)))
|
|
129
|
+
return adj
|
|
130
|
+
|
|
131
|
+
def _build_backward_adj(self) -> Dict:
|
|
132
|
+
"""Build backward adjacency: dst -> [(src, edge_type, time), ...]"""
|
|
133
|
+
adj = {}
|
|
134
|
+
for src, dst, _, attrs in self.graph.edges(data=True, keys=True):
|
|
135
|
+
if dst not in adj:
|
|
136
|
+
adj[dst] = []
|
|
137
|
+
adj[dst].append((src, attrs.get("label", ""), attrs.get("time", 0)))
|
|
138
|
+
return adj
|
|
139
|
+
|
|
140
|
+
def _sort_adj_and_extract_times(self, adj: Dict) -> Dict:
|
|
141
|
+
"""Sort adjacency lists by timestamp and extract time arrays for binary search."""
|
|
142
|
+
times = {}
|
|
143
|
+
for node, edges in adj.items():
|
|
144
|
+
edges.sort(key=lambda x: x[2])
|
|
145
|
+
times[node] = [e[2] for e in edges]
|
|
146
|
+
return times
|
|
147
|
+
|
|
148
|
+
def _build_neighbor_sets(self) -> Dict:
|
|
149
|
+
"""Build undirected neighbor sets for Node2Vec bias computation."""
|
|
150
|
+
neighbors = {}
|
|
151
|
+
for src, dst, _, _ in self.graph.edges(data=True, keys=True):
|
|
152
|
+
neighbors.setdefault(src, set()).add(dst)
|
|
153
|
+
neighbors.setdefault(dst, set()).add(src)
|
|
154
|
+
return neighbors
|
|
155
|
+
|
|
156
|
+
def _pick_neighbor(
|
|
157
|
+
self, options: list, times_sorted: list, last_time: float, forward: bool,
|
|
158
|
+
walk_edge_types: Optional[List[str]] = None,
|
|
159
|
+
prev_node: Optional[str] = None,
|
|
160
|
+
) -> Optional[tuple]:
|
|
161
|
+
"""Pick a neighbor respecting temporal constraints using binary search.
|
|
162
|
+
|
|
163
|
+
Uses pre-sorted adjacency lists with bisect for O(log n) temporal
|
|
164
|
+
filtering instead of O(n) list comprehension.
|
|
165
|
+
|
|
166
|
+
When diversity_weight > 0 and walk_edge_types is provided, candidates
|
|
167
|
+
whose edge type is underrepresented in the walk so far receive higher
|
|
168
|
+
weight. The diversity bonus for each candidate is:
|
|
169
|
+
1 / (1 + count_of_this_edge_type_in_walk)
|
|
170
|
+
scaled by diversity_weight before combining with the base (time) weight.
|
|
171
|
+
|
|
172
|
+
When Node2Vec bias is active (p != 1 or q != 1) and prev_node is given,
|
|
173
|
+
candidates are weighted by their structural relationship to prev_node:
|
|
174
|
+
- candidate == prev_node (return): 1/p
|
|
175
|
+
- candidate is a neighbor of prev_node (BFS): 1
|
|
176
|
+
- otherwise (DFS): 1/q
|
|
177
|
+
"""
|
|
178
|
+
# Binary search on pre-sorted time array
|
|
179
|
+
if forward:
|
|
180
|
+
start = bisect.bisect_right(times_sorted, last_time)
|
|
181
|
+
end = len(options)
|
|
182
|
+
else:
|
|
183
|
+
start = 0
|
|
184
|
+
end = bisect.bisect_left(times_sorted, last_time)
|
|
185
|
+
|
|
186
|
+
if start >= end:
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
# Fast path: uniform weights + no diversity bias + no Node2Vec bias
|
|
190
|
+
has_node2vec = self._neighbor_sets is not None and prev_node is not None
|
|
191
|
+
if self.time_weight != "exponential" and self.diversity_weight <= 0 and not has_node2vec:
|
|
192
|
+
idx = random.randint(start, end - 1)
|
|
193
|
+
return options[idx]
|
|
194
|
+
|
|
195
|
+
# Slow path: need valid slice for weighted sampling
|
|
196
|
+
valid = options[start:end]
|
|
197
|
+
|
|
198
|
+
# Base weights from time weighting strategy
|
|
199
|
+
if self.time_weight == "exponential":
|
|
200
|
+
times = np.array([t for _, _, t in valid])
|
|
201
|
+
base_w = np.exp(np.abs(last_time - times) / (-self.half_life))
|
|
202
|
+
base_w = np.nan_to_num(base_w, nan=0.0)
|
|
203
|
+
if base_w.sum() == 0:
|
|
204
|
+
base_w = np.ones(len(valid))
|
|
205
|
+
else:
|
|
206
|
+
base_w = np.ones(len(valid))
|
|
207
|
+
|
|
208
|
+
# Apply edge-type diversity bias
|
|
209
|
+
if self.diversity_weight > 0 and walk_edge_types:
|
|
210
|
+
edge_counts = Counter(walk_edge_types)
|
|
211
|
+
diversity_w = np.array([
|
|
212
|
+
1.0 / (1 + edge_counts.get(etype, 0))
|
|
213
|
+
for _, etype, _ in valid
|
|
214
|
+
])
|
|
215
|
+
# Blend: base * (1 + diversity_weight * diversity_bonus)
|
|
216
|
+
weights = base_w * (1.0 + self.diversity_weight * diversity_w)
|
|
217
|
+
else:
|
|
218
|
+
weights = base_w
|
|
219
|
+
|
|
220
|
+
# Apply Node2Vec 2nd-order bias (p/q)
|
|
221
|
+
if has_node2vec:
|
|
222
|
+
prev_neighbors = self._neighbor_sets.get(prev_node, set())
|
|
223
|
+
inv_p = 1.0 / self.node2vec_p
|
|
224
|
+
inv_q = 1.0 / self.node2vec_q
|
|
225
|
+
n2v_w = np.array([
|
|
226
|
+
inv_p if dst == prev_node
|
|
227
|
+
else 1.0 if dst in prev_neighbors
|
|
228
|
+
else inv_q
|
|
229
|
+
for dst, _, _ in valid
|
|
230
|
+
])
|
|
231
|
+
weights = weights * n2v_w
|
|
232
|
+
|
|
233
|
+
total = weights.sum()
|
|
234
|
+
if total == 0:
|
|
235
|
+
idx = random.randint(0, len(valid) - 1)
|
|
236
|
+
return valid[idx]
|
|
237
|
+
weights /= total
|
|
238
|
+
idx = np.random.choice(len(valid), p=weights)
|
|
239
|
+
return valid[idx]
|
|
240
|
+
|
|
241
|
+
def _extend_forward(self, walk_nodes, walk_edge_types, walk_times, start_node):
|
|
242
|
+
"""Extend walk forward in time from start_node."""
|
|
243
|
+
if start_node not in self.forward_adj:
|
|
244
|
+
return
|
|
245
|
+
options = self.forward_adj[start_node]
|
|
246
|
+
|
|
247
|
+
if self.random_walk_start and options:
|
|
248
|
+
dst, etype, t = random.choice(options)
|
|
249
|
+
walk_nodes.append(dst)
|
|
250
|
+
walk_edge_types.append(etype)
|
|
251
|
+
walk_times.append(t)
|
|
252
|
+
last_time = t
|
|
253
|
+
else:
|
|
254
|
+
last_time = options[0][2] if options else -np.inf # sorted → min is first
|
|
255
|
+
|
|
256
|
+
while len(walk_nodes) < self.walk_length:
|
|
257
|
+
current = walk_nodes[-1]
|
|
258
|
+
if current not in self.forward_adj:
|
|
259
|
+
break
|
|
260
|
+
prev = walk_nodes[-2] if len(walk_nodes) >= 2 else None
|
|
261
|
+
picked = self._pick_neighbor(
|
|
262
|
+
self.forward_adj[current], self.forward_times[current],
|
|
263
|
+
last_time, forward=True,
|
|
264
|
+
walk_edge_types=walk_edge_types,
|
|
265
|
+
prev_node=prev,
|
|
266
|
+
)
|
|
267
|
+
if picked is None:
|
|
268
|
+
break
|
|
269
|
+
dst, etype, t = picked
|
|
270
|
+
walk_nodes.append(dst)
|
|
271
|
+
walk_edge_types.append(etype)
|
|
272
|
+
walk_times.append(t)
|
|
273
|
+
last_time = t
|
|
274
|
+
|
|
275
|
+
def _extend_backward(self, walk_nodes, walk_edge_types, walk_times, start_node):
|
|
276
|
+
"""Extend walk backward in time from start_node."""
|
|
277
|
+
if start_node not in self.backward_adj:
|
|
278
|
+
return
|
|
279
|
+
options = self.backward_adj[start_node]
|
|
280
|
+
|
|
281
|
+
# Build backward portion in reverse (append), then prepend once.
|
|
282
|
+
rev_nodes = []
|
|
283
|
+
rev_edges = []
|
|
284
|
+
rev_times = []
|
|
285
|
+
|
|
286
|
+
if self.random_walk_start and options:
|
|
287
|
+
src, etype, t = random.choice(options)
|
|
288
|
+
rev_nodes.append(src)
|
|
289
|
+
rev_edges.append(etype)
|
|
290
|
+
rev_times.append(t)
|
|
291
|
+
last_time = t
|
|
292
|
+
else:
|
|
293
|
+
last_time = options[-1][2] if options else np.inf # sorted → max is last
|
|
294
|
+
|
|
295
|
+
while len(walk_nodes) + len(rev_nodes) < self.walk_length:
|
|
296
|
+
current = rev_nodes[-1] if rev_nodes else start_node
|
|
297
|
+
if current not in self.backward_adj:
|
|
298
|
+
break
|
|
299
|
+
prev = rev_nodes[-2] if len(rev_nodes) >= 2 else (start_node if rev_nodes else None)
|
|
300
|
+
picked = self._pick_neighbor(
|
|
301
|
+
self.backward_adj[current], self.backward_times[current],
|
|
302
|
+
last_time, forward=False,
|
|
303
|
+
walk_edge_types=rev_edges,
|
|
304
|
+
prev_node=prev,
|
|
305
|
+
)
|
|
306
|
+
if picked is None:
|
|
307
|
+
break
|
|
308
|
+
src, etype, t = picked
|
|
309
|
+
rev_nodes.append(src)
|
|
310
|
+
rev_edges.append(etype)
|
|
311
|
+
rev_times.append(t)
|
|
312
|
+
last_time = t
|
|
313
|
+
|
|
314
|
+
if rev_nodes:
|
|
315
|
+
rev_nodes.reverse()
|
|
316
|
+
rev_edges.reverse()
|
|
317
|
+
rev_times.reverse()
|
|
318
|
+
walk_nodes[:0] = rev_nodes
|
|
319
|
+
walk_edge_types[:0] = rev_edges
|
|
320
|
+
walk_times[:0] = rev_times
|
|
321
|
+
|
|
322
|
+
def _single_walk(self, start_node: str) -> Tuple[List[str], List[str], List[float], int]:
|
|
323
|
+
"""Generate a single temporal random walk from start_node.
|
|
324
|
+
|
|
325
|
+
Randomly chooses whether to start forward or backward (50/50),
|
|
326
|
+
then extends in the other direction if the walk is too short.
|
|
327
|
+
This ensures balanced coverage of both causal history (backward)
|
|
328
|
+
and consequences (forward) during pretraining.
|
|
329
|
+
|
|
330
|
+
When random_walk_start is True, the first hop is a randomly selected
|
|
331
|
+
edge rather than always starting from the earliest/latest timestamp.
|
|
332
|
+
|
|
333
|
+
Returns:
|
|
334
|
+
walk_nodes: list of node IDs in the walk
|
|
335
|
+
walk_edge_types: list of edge types between consecutive nodes
|
|
336
|
+
walk_times: list of timestamps for each edge
|
|
337
|
+
entity_pos: index of start_node in walk_nodes after extension
|
|
338
|
+
"""
|
|
339
|
+
walk_nodes = [start_node]
|
|
340
|
+
walk_edge_types = []
|
|
341
|
+
walk_times = []
|
|
342
|
+
|
|
343
|
+
# Randomly pick primary direction
|
|
344
|
+
if random.random() < 0.5:
|
|
345
|
+
self._extend_forward(walk_nodes, walk_edge_types, walk_times, start_node)
|
|
346
|
+
n_before_bwd = len(walk_nodes)
|
|
347
|
+
if len(walk_nodes) < self.walk_length:
|
|
348
|
+
self._extend_backward(walk_nodes, walk_edge_types, walk_times, start_node)
|
|
349
|
+
# Backward prepends, so entity moved by (new_len - n_before_bwd) positions
|
|
350
|
+
entity_pos = len(walk_nodes) - n_before_bwd
|
|
351
|
+
else:
|
|
352
|
+
n_before_bwd = len(walk_nodes) # always 1
|
|
353
|
+
self._extend_backward(walk_nodes, walk_edge_types, walk_times, start_node)
|
|
354
|
+
# Compute entity_pos AFTER backward (prepend) but BEFORE forward (append)
|
|
355
|
+
entity_pos = len(walk_nodes) - n_before_bwd
|
|
356
|
+
if len(walk_nodes) < self.walk_length:
|
|
357
|
+
self._extend_forward(walk_nodes, walk_edge_types, walk_times, start_node)
|
|
358
|
+
return walk_nodes, walk_edge_types, walk_times, entity_pos
|
|
359
|
+
|
|
360
|
+
def sample_walks(
|
|
361
|
+
self,
|
|
362
|
+
batch_nodes: Optional[List[str]] = None,
|
|
363
|
+
) -> List[Tuple[List[str], List[str]]]:
|
|
364
|
+
"""Sample walks from a batch of start nodes.
|
|
365
|
+
|
|
366
|
+
Args:
|
|
367
|
+
batch_nodes: list of start node IDs. If None, sample from all nodes.
|
|
368
|
+
|
|
369
|
+
Returns:
|
|
370
|
+
List of (walk_nodes, walk_edge_types) tuples.
|
|
371
|
+
"""
|
|
372
|
+
if batch_nodes is None:
|
|
373
|
+
batch_nodes = self.nodes
|
|
374
|
+
|
|
375
|
+
walks = []
|
|
376
|
+
for node in batch_nodes:
|
|
377
|
+
for _ in range(self.num_walks):
|
|
378
|
+
walk_nodes, walk_edge_types, _, _ = self._single_walk(node)
|
|
379
|
+
if len(walk_nodes) > 1:
|
|
380
|
+
walks.append((walk_nodes, walk_edge_types))
|
|
381
|
+
|
|
382
|
+
return walks
|
|
383
|
+
|
|
384
|
+
def sample_bidirectional_walk(
|
|
385
|
+
self,
|
|
386
|
+
target_node: str,
|
|
387
|
+
max_ts: Optional[float] = None,
|
|
388
|
+
walk_length: Optional[int] = None,
|
|
389
|
+
) -> Tuple[List[str], List[str]]:
|
|
390
|
+
"""Sample a bidirectional walk centered on target_node.
|
|
391
|
+
|
|
392
|
+
Splits the walk budget evenly between two types of PAST context:
|
|
393
|
+
- Incoming-backward: follow incoming edges backward in time from
|
|
394
|
+
target_node (t < max_ts), capturing who/what caused target_node
|
|
395
|
+
to reach its current state (provenance).
|
|
396
|
+
- Outgoing-past: follow outgoing edges backward in time from
|
|
397
|
+
target_node (t < max_ts), capturing what target_node DID before
|
|
398
|
+
the scored edge (its own generated activity).
|
|
399
|
+
|
|
400
|
+
Both halves are strictly before max_ts — no future snooping.
|
|
401
|
+
|
|
402
|
+
The returned sequence is:
|
|
403
|
+
[...incoming_ancestors → target_node → ...past_outgoing_neighbors]
|
|
404
|
+
|
|
405
|
+
This gives the model both provenance (who caused this?) and effect
|
|
406
|
+
(what did this already trigger in the past?). For example, a malicious
|
|
407
|
+
nginx that has already written to /tmp or connected to a C2 server
|
|
408
|
+
before the scored edge will look different from a benign nginx that
|
|
409
|
+
only forwarded to PHP-FPM and wrote access logs.
|
|
410
|
+
|
|
411
|
+
Args:
|
|
412
|
+
target_node: the node to centre the walk on (typically the src node
|
|
413
|
+
of the scored edge).
|
|
414
|
+
max_ts: timestamp of the scored edge. Both walk halves are
|
|
415
|
+
constrained to edges with t < max_ts.
|
|
416
|
+
walk_length: hop budget per direction (backward and outgoing-past each get walk_length hops).
|
|
417
|
+
"""
|
|
418
|
+
wl = walk_length or self.walk_length
|
|
419
|
+
|
|
420
|
+
# ── Backward portion ─────────────────────────────────────────────
|
|
421
|
+
bwd_nodes_rev = [target_node]
|
|
422
|
+
bwd_edge_types_rev = []
|
|
423
|
+
last_time = max_ts if max_ts is not None else np.inf
|
|
424
|
+
|
|
425
|
+
while len(bwd_nodes_rev) <= wl:
|
|
426
|
+
current = bwd_nodes_rev[-1]
|
|
427
|
+
if current not in self.backward_adj:
|
|
428
|
+
break
|
|
429
|
+
picked = self._pick_neighbor(
|
|
430
|
+
self.backward_adj[current], self.backward_times[current],
|
|
431
|
+
last_time, forward=False,
|
|
432
|
+
)
|
|
433
|
+
if picked is None:
|
|
434
|
+
break
|
|
435
|
+
src, etype, t = picked
|
|
436
|
+
bwd_nodes_rev.append(src)
|
|
437
|
+
bwd_edge_types_rev.append(etype)
|
|
438
|
+
last_time = t
|
|
439
|
+
|
|
440
|
+
bwd_nodes_rev.reverse()
|
|
441
|
+
bwd_edge_types_rev.reverse()
|
|
442
|
+
# bwd_nodes_rev[-1] == target_node
|
|
443
|
+
|
|
444
|
+
# ── Outgoing-past portion ────────────────────────────────────────
|
|
445
|
+
# Follow OUTGOING edges from target_node in descending time order
|
|
446
|
+
# (t < max_ts), capturing what target_node DID before the scored edge.
|
|
447
|
+
# This is purely within the past — no future snooping.
|
|
448
|
+
fwd_nodes = []
|
|
449
|
+
fwd_edge_types = []
|
|
450
|
+
last_time = max_ts if max_ts is not None else np.inf
|
|
451
|
+
current = target_node
|
|
452
|
+
|
|
453
|
+
while len(fwd_nodes) < wl:
|
|
454
|
+
if current not in self.forward_adj:
|
|
455
|
+
break
|
|
456
|
+
picked = self._pick_neighbor(
|
|
457
|
+
self.forward_adj[current], self.forward_times[current],
|
|
458
|
+
last_time, forward=False,
|
|
459
|
+
)
|
|
460
|
+
if picked is None:
|
|
461
|
+
break
|
|
462
|
+
dst, etype, t = picked
|
|
463
|
+
fwd_nodes.append(dst)
|
|
464
|
+
fwd_edge_types.append(etype)
|
|
465
|
+
last_time = t
|
|
466
|
+
current = dst
|
|
467
|
+
|
|
468
|
+
# Combine: [...incoming_ancestors → target_node → ...past_outgoing]
|
|
469
|
+
return bwd_nodes_rev + fwd_nodes, bwd_edge_types_rev + fwd_edge_types
|
|
470
|
+
|
|
471
|
+
def sample_context_walk(
|
|
472
|
+
self,
|
|
473
|
+
target_node: str,
|
|
474
|
+
max_ts: Optional[float] = None,
|
|
475
|
+
walk_length: Optional[int] = None,
|
|
476
|
+
) -> Tuple[List[str], List[str]]:
|
|
477
|
+
"""Sample a backward walk ending at target_node (for fine-tuning context).
|
|
478
|
+
|
|
479
|
+
The walk goes backward in time from target_node, then is reversed
|
|
480
|
+
to produce a chronologically ordered sequence ending at target_node.
|
|
481
|
+
|
|
482
|
+
Args:
|
|
483
|
+
target_node: the node to end the walk at
|
|
484
|
+
max_ts: maximum timestamp (only use edges before this time)
|
|
485
|
+
walk_length: override default walk length
|
|
486
|
+
|
|
487
|
+
Returns:
|
|
488
|
+
(walk_nodes, walk_edge_types) ending at target_node
|
|
489
|
+
"""
|
|
490
|
+
wl = walk_length or self.walk_length
|
|
491
|
+
# Build walk backward, then reverse once at the end (avoids O(n²) inserts)
|
|
492
|
+
walk_nodes_rev = [target_node]
|
|
493
|
+
walk_edge_types_rev = []
|
|
494
|
+
last_time = max_ts if max_ts is not None else np.inf
|
|
495
|
+
|
|
496
|
+
while len(walk_nodes_rev) < wl:
|
|
497
|
+
current = walk_nodes_rev[-1]
|
|
498
|
+
if current not in self.backward_adj:
|
|
499
|
+
break
|
|
500
|
+
|
|
501
|
+
picked = self._pick_neighbor(
|
|
502
|
+
self.backward_adj[current], self.backward_times[current],
|
|
503
|
+
last_time, forward=False,
|
|
504
|
+
)
|
|
505
|
+
if picked is None:
|
|
506
|
+
break
|
|
507
|
+
|
|
508
|
+
src, etype, t = picked
|
|
509
|
+
walk_nodes_rev.append(src)
|
|
510
|
+
walk_edge_types_rev.append(etype)
|
|
511
|
+
last_time = t
|
|
512
|
+
|
|
513
|
+
walk_nodes_rev.reverse()
|
|
514
|
+
walk_edge_types_rev.reverse()
|
|
515
|
+
return walk_nodes_rev, walk_edge_types_rev
|
|
516
|
+
|
|
517
|
+
# ── T5 directional walk sampling ──────────────────────────────────
|
|
518
|
+
|
|
519
|
+
def _get_node_times(self, node: str) -> List[float]:
|
|
520
|
+
"""Get sorted unique edge timestamps for a node across both directions."""
|
|
521
|
+
times = set()
|
|
522
|
+
if node in self.forward_adj:
|
|
523
|
+
for _, _, t in self.forward_adj[node]:
|
|
524
|
+
times.add(t)
|
|
525
|
+
if node in self.backward_adj:
|
|
526
|
+
for _, _, t in self.backward_adj[node]:
|
|
527
|
+
times.add(t)
|
|
528
|
+
return sorted(times)
|
|
529
|
+
|
|
530
|
+
def _pick_neighbor_with_etype(
|
|
531
|
+
self, options: list, times_sorted: list, last_time: float,
|
|
532
|
+
forward: bool, preferred_etype: str,
|
|
533
|
+
) -> Optional[tuple]:
|
|
534
|
+
"""Pick a temporally valid neighbor with a preferred edge type.
|
|
535
|
+
|
|
536
|
+
Returns None if no neighbor with the preferred type satisfies
|
|
537
|
+
temporal constraints. The caller should fall back to _pick_neighbor.
|
|
538
|
+
"""
|
|
539
|
+
if forward:
|
|
540
|
+
start = bisect.bisect_right(times_sorted, last_time)
|
|
541
|
+
end = len(options)
|
|
542
|
+
else:
|
|
543
|
+
start = 0
|
|
544
|
+
end = bisect.bisect_left(times_sorted, last_time)
|
|
545
|
+
if start >= end:
|
|
546
|
+
return None
|
|
547
|
+
candidates = [options[i] for i in range(start, end) if options[i][1] == preferred_etype]
|
|
548
|
+
if candidates:
|
|
549
|
+
return random.choice(candidates)
|
|
550
|
+
return None
|
|
551
|
+
|
|
552
|
+
def _directed_walk(
|
|
553
|
+
self, start_node: str, entry_time: float, max_len: int,
|
|
554
|
+
forward: bool, preferred_etype: Optional[str] = None,
|
|
555
|
+
) -> Optional[Tuple[List[str], List[str]]]:
|
|
556
|
+
"""Sample a single directional walk from start_node at entry_time.
|
|
557
|
+
|
|
558
|
+
Args:
|
|
559
|
+
start_node: entity node to walk from.
|
|
560
|
+
entry_time: temporal entry point (first hop must be after/before).
|
|
561
|
+
max_len: maximum number of hops.
|
|
562
|
+
forward: True for forward walk, False for backward.
|
|
563
|
+
preferred_etype: if set, try this edge type for the first hop.
|
|
564
|
+
|
|
565
|
+
Returns:
|
|
566
|
+
(context_edge_types, context_nodes) or None if no valid walk.
|
|
567
|
+
"""
|
|
568
|
+
adj = self.forward_adj if forward else self.backward_adj
|
|
569
|
+
adj_times = self.forward_times if forward else self.backward_times
|
|
570
|
+
if start_node not in adj:
|
|
571
|
+
return None
|
|
572
|
+
|
|
573
|
+
edge_types: List[str] = []
|
|
574
|
+
context_nodes: List[str] = []
|
|
575
|
+
current = start_node
|
|
576
|
+
last_time = entry_time
|
|
577
|
+
|
|
578
|
+
while len(context_nodes) < max_len:
|
|
579
|
+
if current not in adj:
|
|
580
|
+
break
|
|
581
|
+
|
|
582
|
+
picked = None
|
|
583
|
+
# First hop: try preferred edge type for diversity
|
|
584
|
+
if not context_nodes and preferred_etype is not None:
|
|
585
|
+
picked = self._pick_neighbor_with_etype(
|
|
586
|
+
adj[current], adj_times[current], last_time, forward, preferred_etype
|
|
587
|
+
)
|
|
588
|
+
if picked is None:
|
|
589
|
+
picked = self._pick_neighbor(
|
|
590
|
+
adj[current], adj_times[current],
|
|
591
|
+
last_time, forward=forward,
|
|
592
|
+
walk_edge_types=edge_types,
|
|
593
|
+
)
|
|
594
|
+
if picked is None:
|
|
595
|
+
break
|
|
596
|
+
|
|
597
|
+
neighbor, etype, t = picked
|
|
598
|
+
context_nodes.append(neighbor)
|
|
599
|
+
edge_types.append(etype)
|
|
600
|
+
last_time = t
|
|
601
|
+
current = neighbor
|
|
602
|
+
|
|
603
|
+
if not context_nodes:
|
|
604
|
+
return None
|
|
605
|
+
return edge_types, context_nodes
|
|
606
|
+
|
|
607
|
+
def sample_directional_walks(
|
|
608
|
+
self, start_node: str, num_walks: int,
|
|
609
|
+
) -> List[Tuple[str, List[str], List[str]]]:
|
|
610
|
+
"""Sample diverse forward and backward walks for T5 pretraining.
|
|
611
|
+
|
|
612
|
+
For each node, produces separate forward and backward walks with:
|
|
613
|
+
- Random temporal entry points for different temporal views
|
|
614
|
+
- Round-robin first-hop edge types for edge-type diversity
|
|
615
|
+
- Random walk lengths between 1 and walk_length
|
|
616
|
+
- Local deduplication
|
|
617
|
+
|
|
618
|
+
Args:
|
|
619
|
+
start_node: entity node to build walks from.
|
|
620
|
+
num_walks: number of walk attempts per direction.
|
|
621
|
+
|
|
622
|
+
Returns:
|
|
623
|
+
List of (direction, context_edge_types, context_nodes).
|
|
624
|
+
direction is 'forward' or 'backward'.
|
|
625
|
+
"""
|
|
626
|
+
all_times = self._get_node_times(start_node)
|
|
627
|
+
if not all_times:
|
|
628
|
+
return []
|
|
629
|
+
|
|
630
|
+
# Available first-hop edge types per direction (for diversity round-robin)
|
|
631
|
+
fwd_etypes = sorted(set(e[1] for e in self.forward_adj.get(start_node, [])))
|
|
632
|
+
bwd_etypes = sorted(set(e[1] for e in self.backward_adj.get(start_node, [])))
|
|
633
|
+
|
|
634
|
+
results: List[Tuple[str, List[str], List[str]]] = []
|
|
635
|
+
seen: set = set()
|
|
636
|
+
|
|
637
|
+
for i in range(num_walks):
|
|
638
|
+
max_len = random.randint(1, self.walk_length)
|
|
639
|
+
entry_time = random.choice(all_times)
|
|
640
|
+
|
|
641
|
+
# Forward walk
|
|
642
|
+
if start_node in self.forward_adj:
|
|
643
|
+
preferred = fwd_etypes[i % len(fwd_etypes)] if fwd_etypes else None
|
|
644
|
+
result = self._directed_walk(
|
|
645
|
+
start_node, entry_time, max_len, forward=True,
|
|
646
|
+
preferred_etype=preferred,
|
|
647
|
+
)
|
|
648
|
+
if result is not None:
|
|
649
|
+
sig = ('f', tuple(result[0]), tuple(result[1]))
|
|
650
|
+
if sig not in seen:
|
|
651
|
+
seen.add(sig)
|
|
652
|
+
results.append(('forward', result[0], result[1]))
|
|
653
|
+
|
|
654
|
+
# Backward walk
|
|
655
|
+
if start_node in self.backward_adj:
|
|
656
|
+
preferred = bwd_etypes[i % len(bwd_etypes)] if bwd_etypes else None
|
|
657
|
+
result = self._directed_walk(
|
|
658
|
+
start_node, entry_time, max_len, forward=False,
|
|
659
|
+
preferred_etype=preferred,
|
|
660
|
+
)
|
|
661
|
+
if result is not None:
|
|
662
|
+
sig = ('b', tuple(result[0]), tuple(result[1]))
|
|
663
|
+
if sig not in seen:
|
|
664
|
+
seen.add(sig)
|
|
665
|
+
results.append(('backward', result[0], result[1]))
|
|
666
|
+
|
|
667
|
+
return results
|
|
668
|
+
|
|
669
|
+
# ── Temporal neighborhood sampling (for GNN-based / T5 pretraining) ─
|
|
670
|
+
|
|
671
|
+
def _get_neighbors_at_time(
|
|
672
|
+
self, node, ref_time: float, max_neighbors: int, forward: bool = False,
|
|
673
|
+
) -> List[Tuple]:
|
|
674
|
+
"""Get up to `max_neighbors` neighbors near `ref_time`.
|
|
675
|
+
|
|
676
|
+
For backward (default): returns the last N edges *before* ref_time,
|
|
677
|
+
sorted most-recent-first.
|
|
678
|
+
For forward: returns the first N edges *after* ref_time, sorted
|
|
679
|
+
earliest-first.
|
|
680
|
+
"""
|
|
681
|
+
adj = self.forward_adj if forward else self.backward_adj
|
|
682
|
+
adj_times = self.forward_times if forward else self.backward_times
|
|
683
|
+
|
|
684
|
+
if node not in adj:
|
|
685
|
+
return []
|
|
686
|
+
|
|
687
|
+
edges = adj[node]
|
|
688
|
+
times = adj_times[node]
|
|
689
|
+
|
|
690
|
+
if forward:
|
|
691
|
+
# First edge at or after ref_time
|
|
692
|
+
idx = bisect.bisect_left(times, ref_time)
|
|
693
|
+
if idx >= len(times):
|
|
694
|
+
return []
|
|
695
|
+
end = min(len(edges), idx + max_neighbors)
|
|
696
|
+
neighbors = edges[idx:end] # earliest first
|
|
697
|
+
else:
|
|
698
|
+
# Last edge strictly before ref_time
|
|
699
|
+
idx = bisect.bisect_left(times, ref_time)
|
|
700
|
+
if idx == 0:
|
|
701
|
+
return []
|
|
702
|
+
start = max(0, idx - max_neighbors)
|
|
703
|
+
neighbors = edges[start:idx]
|
|
704
|
+
neighbors.reverse() # most recent first
|
|
705
|
+
|
|
706
|
+
return neighbors
|
|
707
|
+
|
|
708
|
+
def _get_backward_neighbors_at_time(
|
|
709
|
+
self, node, ref_time: float, max_neighbors: int,
|
|
710
|
+
) -> List[Tuple]:
|
|
711
|
+
"""Get the last `max_neighbors` backward neighbors before `ref_time`.
|
|
712
|
+
|
|
713
|
+
Returns list of (neighbor_node, edge_type, timestamp) sorted by time descending
|
|
714
|
+
(most recent first).
|
|
715
|
+
"""
|
|
716
|
+
return self._get_neighbors_at_time(node, ref_time, max_neighbors, forward=False)
|
|
717
|
+
|
|
718
|
+
def sample_temporal_neighborhood(
|
|
719
|
+
self, node, n_min: int = 5, n_max: int = 20,
|
|
720
|
+
forward: bool = False,
|
|
721
|
+
) -> Optional[Tuple[str, float, List[Tuple]]]:
|
|
722
|
+
"""Sample a 1-hop temporal neighborhood for a node.
|
|
723
|
+
|
|
724
|
+
Picks a random timestamp where the node had activity, then extracts
|
|
725
|
+
up to N neighbors (N uniformly random in [n_min, n_max]).
|
|
726
|
+
|
|
727
|
+
Args:
|
|
728
|
+
node: target node ID
|
|
729
|
+
n_min: minimum neighborhood size
|
|
730
|
+
n_max: maximum neighborhood size
|
|
731
|
+
forward: if True, sample forward neighbors (after ref_time);
|
|
732
|
+
if False (default), sample backward neighbors (before ref_time).
|
|
733
|
+
|
|
734
|
+
Returns:
|
|
735
|
+
(node, ref_time, neighbors) where neighbors is a list of
|
|
736
|
+
(neighbor_node, edge_type, timestamp) tuples, or None if
|
|
737
|
+
the node has insufficient neighbors in the requested direction.
|
|
738
|
+
"""
|
|
739
|
+
all_times = self._get_node_times(node)
|
|
740
|
+
if not all_times:
|
|
741
|
+
return None
|
|
742
|
+
|
|
743
|
+
ref_time = random.choice(all_times)
|
|
744
|
+
n_neighbors = random.randint(n_min, n_max)
|
|
745
|
+
neighbors = self._get_neighbors_at_time(node, ref_time, n_neighbors, forward=forward)
|
|
746
|
+
|
|
747
|
+
if len(neighbors) < 2:
|
|
748
|
+
return None
|
|
749
|
+
|
|
750
|
+
return (node, ref_time, neighbors)
|
|
751
|
+
|
|
752
|
+
# ── N-hop neighborhood extraction (for GNN distillation) ──────────
|
|
753
|
+
|
|
754
|
+
def sample_nhop_neighborhood(
|
|
755
|
+
self,
|
|
756
|
+
node: str,
|
|
757
|
+
n_neighbors_min: int = 5,
|
|
758
|
+
n_neighbors_max: int = 20,
|
|
759
|
+
ref_time: Optional[float] = None,
|
|
760
|
+
diverse: bool = False,
|
|
761
|
+
) -> Optional[Tuple[str, List[str], List[Tuple[str, str, str]]]]:
|
|
762
|
+
"""Sample a 1-hop temporal neighborhood as a subgraph.
|
|
763
|
+
|
|
764
|
+
Samples a random number of direct neighbors (both backward and
|
|
765
|
+
forward) around a temporal reference point. The neighbor count
|
|
766
|
+
is drawn uniformly from [n_neighbors_min, n_neighbors_max] to
|
|
767
|
+
prevent the GNN from overfitting to a fixed neighborhood size.
|
|
768
|
+
|
|
769
|
+
Args:
|
|
770
|
+
node: center node ID.
|
|
771
|
+
n_neighbors_min: minimum neighbors to sample.
|
|
772
|
+
n_neighbors_max: maximum neighbors to sample.
|
|
773
|
+
ref_time: temporal reference point. If None, picked randomly
|
|
774
|
+
from the node's activity timestamps.
|
|
775
|
+
diverse: if True, dedup neighbors by (edge_type, neighbor_type,
|
|
776
|
+
neighbor_label) and prioritize edge type diversity.
|
|
777
|
+
|
|
778
|
+
Returns:
|
|
779
|
+
(center_node, unique_nodes, edges) where edges is a list of
|
|
780
|
+
(src, dst, edge_type) tuples, or None if the neighborhood is
|
|
781
|
+
too sparse (fewer than 1 edge).
|
|
782
|
+
"""
|
|
783
|
+
if ref_time is None:
|
|
784
|
+
all_times = self._get_node_times(node)
|
|
785
|
+
if not all_times:
|
|
786
|
+
return None
|
|
787
|
+
ref_time = random.choice(all_times)
|
|
788
|
+
|
|
789
|
+
n_neighbors = random.randint(n_neighbors_min, n_neighbors_max)
|
|
790
|
+
half_budget = max(1, n_neighbors // 2)
|
|
791
|
+
|
|
792
|
+
if diverse:
|
|
793
|
+
bwd_selected = self._diverse_neighbors(
|
|
794
|
+
node, ref_time, half_budget, forward=False,
|
|
795
|
+
)
|
|
796
|
+
fwd_selected = self._diverse_neighbors(
|
|
797
|
+
node, ref_time, half_budget, forward=True,
|
|
798
|
+
)
|
|
799
|
+
|
|
800
|
+
# Adaptive: if one direction empty, give full budget to the other
|
|
801
|
+
if not bwd_selected and fwd_selected and len(fwd_selected) < n_neighbors:
|
|
802
|
+
fwd_selected = self._diverse_neighbors(
|
|
803
|
+
node, ref_time, n_neighbors, forward=True,
|
|
804
|
+
)
|
|
805
|
+
elif not fwd_selected and bwd_selected and len(bwd_selected) < n_neighbors:
|
|
806
|
+
bwd_selected = self._diverse_neighbors(
|
|
807
|
+
node, ref_time, n_neighbors, forward=False,
|
|
808
|
+
)
|
|
809
|
+
|
|
810
|
+
all_edges: List[Tuple[str, str, str]] = []
|
|
811
|
+
visited = {node}
|
|
812
|
+
for neighbor, edge_type, _t in bwd_selected:
|
|
813
|
+
all_edges.append((neighbor, node, edge_type))
|
|
814
|
+
visited.add(neighbor)
|
|
815
|
+
for neighbor, edge_type, _t in fwd_selected:
|
|
816
|
+
all_edges.append((node, neighbor, edge_type))
|
|
817
|
+
visited.add(neighbor)
|
|
818
|
+
else:
|
|
819
|
+
all_edges = []
|
|
820
|
+
visited = {node}
|
|
821
|
+
|
|
822
|
+
bwd = self._get_neighbors_at_time(
|
|
823
|
+
node, ref_time + 1e-6, half_budget, forward=False,
|
|
824
|
+
)
|
|
825
|
+
for neighbor, edge_type, _t in bwd:
|
|
826
|
+
all_edges.append((neighbor, node, edge_type))
|
|
827
|
+
visited.add(neighbor)
|
|
828
|
+
|
|
829
|
+
fwd = self._get_neighbors_at_time(
|
|
830
|
+
node, ref_time, half_budget, forward=True,
|
|
831
|
+
)
|
|
832
|
+
for neighbor, edge_type, _t in fwd:
|
|
833
|
+
all_edges.append((node, neighbor, edge_type))
|
|
834
|
+
visited.add(neighbor)
|
|
835
|
+
|
|
836
|
+
if len(bwd) == 0 and len(fwd) > 0 and len(fwd) < n_neighbors:
|
|
837
|
+
extra_fwd = self._get_neighbors_at_time(
|
|
838
|
+
node, ref_time, n_neighbors, forward=True,
|
|
839
|
+
)
|
|
840
|
+
for neighbor, edge_type, _t in extra_fwd:
|
|
841
|
+
if neighbor not in visited:
|
|
842
|
+
all_edges.append((node, neighbor, edge_type))
|
|
843
|
+
visited.add(neighbor)
|
|
844
|
+
elif len(fwd) == 0 and len(bwd) > 0 and len(bwd) < n_neighbors:
|
|
845
|
+
extra_bwd = self._get_neighbors_at_time(
|
|
846
|
+
node, ref_time + 1e-6, n_neighbors, forward=False,
|
|
847
|
+
)
|
|
848
|
+
for neighbor, edge_type, _t in extra_bwd:
|
|
849
|
+
if neighbor not in visited:
|
|
850
|
+
all_edges.append((neighbor, node, edge_type))
|
|
851
|
+
visited.add(neighbor)
|
|
852
|
+
|
|
853
|
+
if len(all_edges) < 1:
|
|
854
|
+
return None
|
|
855
|
+
|
|
856
|
+
unique_nodes = [node] + [n for n in visited if n != node]
|
|
857
|
+
return (node, unique_nodes, all_edges)
|
|
858
|
+
|
|
859
|
+
def _diverse_neighbors(
|
|
860
|
+
self,
|
|
861
|
+
node: str,
|
|
862
|
+
ref_time: float,
|
|
863
|
+
budget: int,
|
|
864
|
+
forward: bool = True,
|
|
865
|
+
) -> List[Tuple]:
|
|
866
|
+
"""Select diverse neighbors: dedup by (edge_type, neighbor_type, label),
|
|
867
|
+
then prioritize edge type variety via round-robin.
|
|
868
|
+
|
|
869
|
+
Fetches a large pool of temporal neighbors, deduplicates by
|
|
870
|
+
(edge_type, neighbor_node_type, neighbor_label), then selects
|
|
871
|
+
up to `budget` neighbors with round-robin across edge types
|
|
872
|
+
to maximize action diversity.
|
|
873
|
+
|
|
874
|
+
Returns:
|
|
875
|
+
List of (neighbor, edge_type, time) tuples.
|
|
876
|
+
"""
|
|
877
|
+
# Fetch large pool (5x budget) for dedup headroom
|
|
878
|
+
pool_size = max(budget * 5, 100)
|
|
879
|
+
ref = ref_time if forward else ref_time + 1e-6
|
|
880
|
+
raw = self._get_neighbors_at_time(node, ref, pool_size, forward=forward)
|
|
881
|
+
|
|
882
|
+
if not raw:
|
|
883
|
+
return []
|
|
884
|
+
|
|
885
|
+
# Dedup by (edge_type, neighbor_type, neighbor_label)
|
|
886
|
+
seen_keys: set = set()
|
|
887
|
+
deduped: List[Tuple] = []
|
|
888
|
+
for neighbor, edge_type, t in raw:
|
|
889
|
+
nlbl = self.node_labels.get(neighbor, ("unknown", "unknown"))
|
|
890
|
+
key = (edge_type, nlbl[0], nlbl[1])
|
|
891
|
+
if key not in seen_keys:
|
|
892
|
+
seen_keys.add(key)
|
|
893
|
+
deduped.append((neighbor, edge_type, t))
|
|
894
|
+
|
|
895
|
+
if len(deduped) <= budget:
|
|
896
|
+
return deduped
|
|
897
|
+
|
|
898
|
+
# Group by edge type for round-robin selection
|
|
899
|
+
by_etype: Dict[str, List[Tuple]] = {}
|
|
900
|
+
for item in deduped:
|
|
901
|
+
etype = item[1]
|
|
902
|
+
if etype not in by_etype:
|
|
903
|
+
by_etype[etype] = []
|
|
904
|
+
by_etype[etype].append(item)
|
|
905
|
+
|
|
906
|
+
# Shuffle within each group for randomness
|
|
907
|
+
for items in by_etype.values():
|
|
908
|
+
random.shuffle(items)
|
|
909
|
+
|
|
910
|
+
# Round-robin: pick one per edge type, repeat until budget filled
|
|
911
|
+
selected: List[Tuple] = []
|
|
912
|
+
etypes = list(by_etype.keys())
|
|
913
|
+
random.shuffle(etypes)
|
|
914
|
+
|
|
915
|
+
while len(selected) < budget and etypes:
|
|
916
|
+
next_etypes = []
|
|
917
|
+
for etype in etypes:
|
|
918
|
+
if len(selected) >= budget:
|
|
919
|
+
break
|
|
920
|
+
if by_etype[etype]:
|
|
921
|
+
selected.append(by_etype[etype].pop())
|
|
922
|
+
if by_etype[etype]:
|
|
923
|
+
next_etypes.append(etype)
|
|
924
|
+
etypes = next_etypes
|
|
925
|
+
|
|
926
|
+
return selected
|