-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtransaction_graph_generator.py
More file actions
1891 lines (1573 loc) · 83.7 KB
/
transaction_graph_generator.py
File metadata and controls
1891 lines (1573 loc) · 83.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Generate a base transaction graph used in the simulator
"""
import networkx as nx
import numpy as np
import itertools
import random
import csv
import yaml
import os
import sys
import logging
import pickle
from scipy import stats
from collections import Counter, defaultdict
from .utils.nominator import Nominator
from .utils.normal_model import NormalModel
from .utils.random_amount import RandomAmount
from .utils.rounded_amount import RoundedAmount
from .ml_account_selector import MoneyLaunderingAccountSelector
from .demographics_assigner import assign_kyc_from_demographics
logger = logging.getLogger(__name__)
# Attribute keys
MAIN_ACCT_KEY = "main_acct" # Main account ID (SAR typology subgraph attribute)
IS_SAR_KEY = "is_sar" # SAR flag (account vertex attribute)
DEFAULT_MARGIN_RATIO = 0.1 # Each member will keep this ratio of the received amount
# Utility functions parsing values
def parse_int(value):
""" Convert string to int
:param value: string value
:return: int value if the parameter can be converted to str, otherwise None
"""
try:
return int(value)
except (ValueError, TypeError):
return None
def parse_float(value):
""" Convert string to amount (float)
:param value: string value
:return: float value if the parameter can be converted to float, otherwise None
"""
try:
return float(value)
except (ValueError, TypeError):
return None
def parse_flag(value):
""" Convert string to boolean (True or false)
:param value: string value
:return: True if the value is equal to "true" (case-insensitive), otherwise False
"""
return type(value) == str and value.lower() == "true"
def get_positive_or_none(value):
""" Get positive value or None (used to parse simulation step parameters)
:param value: Numerical value or None
:return: If the value is positive, return this value. Otherwise, return None.
"""
if value is None:
return None
else:
return value if value > 0 else None
def directed_configuration_model(_in_deg, _out_deg, seed=0):
"""Generate a directed random graph with the given degree sequences without self loop.
Based on nx.generators.degree_seq.directed_configuration_model
:param _in_deg: Each list entry corresponds to the in-degree of a node.
:param _out_deg: Each list entry corresponds to the out-degree of a node.
:param seed: Seed for random number generator
:return: MultiDiGraph without self loop
"""
if not sum(_in_deg) == sum(_out_deg):
raise nx.NetworkXError('Invalid degree sequences. Sequences must have equal sums.')
random.seed(seed)
n_in = len(_in_deg)
n_out = len(_out_deg)
if n_in < n_out:
_in_deg.extend((n_out - n_in) * [0])
else:
_out_deg.extend((n_in - n_out) * [0])
num_nodes = len(_in_deg)
_g = nx.empty_graph(num_nodes, nx.MultiDiGraph())
if num_nodes == 0 or max(_in_deg) == 0:
return _g # No edges exist
in_tmp_list = list()
out_tmp_list = list()
for n in _g.nodes():
in_tmp_list.extend(_in_deg[n] * [n])
out_tmp_list.extend(_out_deg[n] * [n])
random.shuffle(in_tmp_list)
random.shuffle(out_tmp_list)
added_edges = set() # To prevent duplicate edges
for i in range(len(in_tmp_list)):
_src = out_tmp_list[i]
_dst = in_tmp_list[i]
# Ensure no self-loops or duplicates
if _src != _dst and (_src, _dst) not in added_edges:
_g.add_edge(_src, _dst)
added_edges.add((_src, _dst))
else:
# Find a new pair to avoid self-loop or duplicate
for j in range(i + 1, len(in_tmp_list)):
potential_dst = in_tmp_list[j]
if _src != potential_dst and (_src, potential_dst) not in added_edges:
# Swap to avoid the self-loop or duplicate and break the inner loop
in_tmp_list[i], in_tmp_list[j] = in_tmp_list[j], in_tmp_list[i]
_g.add_edge(_src, in_tmp_list[i])
added_edges.add((_src, in_tmp_list[i]))
break
return _g
def get_degrees(deg_csv, num_v):
"""
:param deg_csv: Degree distribution parameter CSV file
:param num_v: Number of total account vertices
:return: In-degree and out-degree sequence list
"""
with open(deg_csv, "r") as rf: # Load in/out-degree sequences from parameter CSV file for each account
reader = csv.reader(rf)
next(reader)
return get_in_and_out_degrees(reader, num_v)
def get_in_and_out_degrees(iterable, num_v):
_in_deg = list() # In-degree sequence
_out_deg = list() # Out-degree sequence
for row in iterable:
if row[0].startswith("#"):
continue
count = int(row[0])
_in_deg.extend([int(row[1])] * count)
_out_deg.extend([int(row[2])] * count)
in_len, out_len = len(_in_deg), len(_out_deg)
if in_len != out_len:
raise ValueError("The length of in-degree (%d) and out-degree (%d) sequences must be same."
% (in_len, out_len))
total_in_deg, total_out_deg = sum(_in_deg), sum(_out_deg)
if total_in_deg != total_out_deg:
raise ValueError("The sum of in-degree (%d) and out-degree (%d) must be same."
% (total_in_deg, total_out_deg))
if num_v % in_len != 0:
raise ValueError("The number of total accounts (%d) "
"must be a multiple of the degree sequence length (%d)."
% (num_v, in_len))
repeats = num_v // in_len
_in_deg = _in_deg * repeats
_out_deg = _out_deg * repeats
# shuffle in and out degrees
_in_out_deg = list(zip(_in_deg, _out_deg))
random.shuffle(_in_out_deg)
_in_deg, _out_deg = zip(*_in_out_deg)
_in_deg, _out_deg = list(_in_deg), list(_out_deg)
return _in_deg, _out_deg
class TransactionGenerator:
def __init__(self, conf, sim_name=None):
"""Initialize transaction network from parameter files.
:param conf_file: JSON file as configurations
:param sim_name: Simulation name (overrides the content in the `conf_json`)
"""
self.g = nx.DiGraph() # Transaction graph object
self.num_accounts = 0 # Number of total accounts
self.hubs = set() # Hub account vertices (main account candidates of AML typology subgraphs)
self.attr_names = list() # Additional account attribute names
self.bank_to_accts = defaultdict(set) # Bank ID -> account set
self.acct_to_bank = dict() # Account ID -> bank ID
self.normal_model_counts = dict()
self.normal_models = list()
self.normal_model_id = 1
self.conf = conf
general_conf = self.conf["general"]
# Set random seed
seed = general_conf.get("random_seed")
env_seed = os.getenv("RANDOM_SEED")
if env_seed is not None:
seed = env_seed # Overwrite random seed if specified as an environment variable
self.seed = seed if seed is None else int(seed)
np.random.seed(self.seed)
random.seed(self.seed)
logger.info("Random seed: " + str(self.seed))
# Get simulation name
if sim_name is None:
sim_name = general_conf["simulation_name"]
logger.info("Simulation name: " + sim_name)
self.total_steps = parse_int(general_conf["total_steps"])
# Set default amounts, steps and model ID
default_conf = self.conf["default"]
self.default_min_amount = parse_float(default_conf.get("min_amount"))
self.default_max_amount = parse_float(default_conf.get("max_amount"))
self.default_min_balance = parse_float(default_conf.get("min_balance"))
self.default_max_balance = parse_float(default_conf.get("max_balance"))
self.default_start_step = parse_int(default_conf.get("start_step"))
self.default_end_step = parse_int(default_conf.get("end_step"))
self.default_start_range = parse_int(default_conf.get("start_range"))
self.default_end_range = parse_int(default_conf.get("end_range"))
self.default_model = parse_int(default_conf.get("transaction_model"))
# The ratio of amount intermediate accounts receive
self.margin_ratio = parse_float(default_conf.get("margin_ratio", DEFAULT_MARGIN_RATIO))
if not 0.0 <= self.margin_ratio <= 1.0:
raise ValueError("Margin ratio in AML typologies (%f) must be within [0.0, 1.0]" % self.margin_ratio)
# Probability of adding random edges in bipartite pattern
self.bipartite_edge_prob = parse_float(default_conf.get("bipartite_edge_prob", 0.8))
if not 0.0 <= self.bipartite_edge_prob <= 1.0:
raise ValueError("Bipartite edge probability (%f) must be within [0.0, 1.0]" % self.bipartite_edge_prob)
self.default_bank_id = default_conf.get("bank_id") # Default bank ID if not specified at parameter files
# Get input file names and properties
input_conf = self.conf["input"]
self.input_dir = input_conf["directory"] # The directory name of input files
self.account_file = input_conf["accounts"] # Account list file
self.alert_file = input_conf["alert_patterns"] # AML typology definition file
self.normal_models_file = input_conf["normal_models"] # Normal models definition file
self.degree_file = input_conf["degree"] # Degree distribution file
self.type_file = input_conf["transaction_type"] # Transaction type
self.is_aggregated = input_conf["is_aggregated_accounts"] # Flag whether the account list is aggregated
# Get output file names (spatial simulation outputs)
output_conf = self.conf["spatial"]
self.output_dir = os.path.join(output_conf["directory"]) # Spatial output directory
self.out_tx_file = output_conf["transactions"] # All transaction list CSV file
self.out_account_file = output_conf["accounts"] # All account list CSV file
self.out_alert_member_file = output_conf["alert_members"] # Account list of AML typology members CSV file
self.out_normal_models_file = output_conf["normal_models"] # List of normal models CSV file
# High risk settings (optional)
other_conf = self.conf.get("graph_generator", {})
high_risk_countries_str = other_conf.get("high_risk_countries", "")
high_risk_business_str = other_conf.get("high_risk_business", "")
self.high_risk_countries = set(high_risk_countries_str.split(",")) if high_risk_countries_str else set()
self.high_risk_business = set(high_risk_business_str.split(",")) if high_risk_business_str else set()
self.edge_id = 0 # Edge ID. Formerly Transaction ID
self.alert_id = 0 # Alert ID from the alert parameter file
self.alert_groups = dict() # Alert ID and alert transaction subgraph
# TODO: Move the mapping of AML pattern to configuration JSON file
self.alert_types = {"fan_out": 1, "fan_in": 2, "cycle": 3, "bipartite": 4, "stack": 5,
"random": 6, "scatter_gather": 7, "gather_scatter": 8} # Pattern name and model ID
# Money laundering account selector (initialized later after graph is built)
# Always uses weighted selection based on structure/KYC when prepared
self.ml_selector = None
# Demographics-based KYC assignment (required)
self.demographics_csv = self.conf.get('demographics', {}).get('csv_path')
self.acct_file = os.path.join(self.input_dir, self.account_file)
def get_types(type_csv):
"""Read out the transaction types
Args:
type_csv (string): Transaction types csv file
Returns:
list: transaction types
"""
tx_types = list()
with open(type_csv, "r") as _rf:
reader = csv.reader(_rf)
next(reader)
for row in reader:
if row[0].startswith("#"):
continue
ttype = row[0]
tx_types.extend([ttype] * int(row[1]))
return tx_types
self.tx_types = get_types(os.path.join(self.input_dir, self.type_file))
def check_hub_exists(self):
"""Validate whether one or more hub accounts exist as main accounts of AML typologies
"""
if not self.hubs:
raise ValueError("No main account candidates found in the transaction graph.")
def set_main_acct_candidates(self):
""" Set self.hubs to be a set of all nodes as main account candidates
Throw an error if not done successfully.
"""
self.hubs = set(self.g.nodes())
self.check_hub_exists()
def check_account_exist(self, aid):
"""Validate an existence of a specified account. If absent, it raises KeyError.
:param aid: Account ID
"""
if not self.g.has_node(aid):
raise KeyError("Account %s does not exist" % str(aid))
def check_account_absent(self, aid):
"""Validate an absence of a specified account
:param aid: Account ID
:return: True if an account of the specified ID is not yet added
"""
if self.g.has_node(aid):
logger.warning("Account %s already exists" % str(aid))
return False
else:
return True
def get_all_bank_ids(self):
"""Get a list of all bank IDs
:return: Bank ID list
"""
return list(self.bank_to_accts.keys())
def get_typology_members(self, num, bank_id=""):
"""Choose accounts as members of AML typologies using weighted selection.
The ML selector applies participation decay after each selection, naturally
spreading participation across accounts without explicit bin tracking.
:param num: Number of total account vertices (including the main account)
:param bank_id: If specified, chooses members from a single bank with the ID.
If empty (default), chooses members from all banks.
:return: Main account and list of member account IDs
"""
if num <= 1:
raise ValueError("The number of members must be more than 1")
if bank_id in self.bank_to_accts:
# Choose members from the specified bank
available_accts = list(self.bank_to_accts[bank_id])
elif bank_id == "":
# Choose members from all accounts
available_accts = list(self.g.nodes())
else:
raise KeyError("No such bank ID: %s" % bank_id)
members = []
for _ in range(num):
# Get candidates not already selected for this typology
candidates = [a for a in available_accts if a not in members]
if not candidates:
break # No more available accounts
# Select using ML selector (applies decay automatically)
if self.ml_selector is not None:
if bank_id:
candidate = self.ml_selector.weighted_choice_bank(candidates, bank_id)
else:
candidate = self.ml_selector.weighted_choice(candidates)
else:
candidate = random.choice(candidates)
members.append(candidate)
# Select main account from members (highest weight among selected)
if self.ml_selector is not None:
main_acct = self.ml_selector.weighted_choice(members)
else:
main_acct = random.choice(members)
return main_acct, members
def load_account_list(self):
"""Load and add account vertices from a CSV file
"""
if self.is_aggregated:
self.load_account_list_param()
else:
self.load_account_list_raw()
def load_account_list_raw(self):
"""Load and add account vertices from a CSV file with raw account info
header: uuid,seq,first_name,last_name,street_addr,city,state,zip,gender,phone_number,birth_date,ssn
:param acct_file: Raw account list file path
"""
# Balance will be set by demographics assignment
start_day = get_positive_or_none(self.default_start_step)
end_day = get_positive_or_none(self.default_end_step)
start_range = get_positive_or_none(self.default_start_range)
end_range = get_positive_or_none(self.default_end_range)
default_model = self.default_model if self.default_model is not None else 1
self.attr_names.extend(["first_name", "last_name", "street_addr", "city", "state", "zip",
"gender", "phone_number", "birth_date", "ssn", "lon", "lat"])
with open(self.acct_file, "r") as rf:
reader = csv.reader(rf)
header = next(reader)
name2idx = {n: i for i, n in enumerate(header)}
idx_aid = name2idx["uuid"]
idx_first_name = name2idx["first_name"]
idx_last_name = name2idx["last_name"]
idx_street_addr = name2idx["street_addr"]
idx_city = name2idx["city"]
idx_state = name2idx["state"]
idx_zip = name2idx["zip"]
idx_gender = name2idx["gender"]
idx_phone_number = name2idx["phone_number"]
idx_birth_date = name2idx["birth_date"]
idx_ssn = name2idx["ssn"]
idx_lon = name2idx["lon"]
idx_lat = name2idx["lat"]
count = 0
for row in reader:
if row[0].startswith("#"): # Comment line
continue
aid = row[idx_aid]
first_name = row[idx_first_name]
last_name = row[idx_last_name]
street_addr = row[idx_street_addr]
city = row[idx_city]
state = row[idx_state]
zip_code = row[idx_zip]
gender = row[idx_gender]
phone_number = row[idx_phone_number]
birth_date = row[idx_birth_date]
ssn = row[idx_ssn]
lon = row[idx_lon]
lat = row[idx_lat]
model = default_model
if start_day is not None and start_range is not None:
start = start_day + random.randrange(start_range)
else:
start = -1
if end_day is not None and end_range is not None:
end = end_day - random.randrange(end_range)
else:
end = -1
attr = {"first_name": first_name, "last_name": last_name, "street_addr": street_addr,
"city": city, "state": state, "zip": zip_code, "gender": gender,
"phone_number": phone_number, "birth_date": birth_date, "ssn": ssn, "lon": lon, "lat": lat}
# Balance will be set by demographics assignment
self.add_account(aid, init_balance=0.0, is_sar=False, **attr)
count += 1
def set_num_accounts(self):
"""Read the number of accounts from the account list file
"""
with open(self.acct_file, "r") as rf:
reader = csv.reader(rf)
# Parse header
header = next(reader)
count = 0
for row in reader:
if row[0].startswith("#"):
continue
num = int(row[header.index('count')])
count += num
self.num_accounts = count
def load_account_list_param(self):
"""Load and add account vertices from a CSV file with aggregated parameters
Each row may represent two or more accounts
:param acct_file: Account parameter file path
"""
with open(self.acct_file, "r") as rf:
reader = csv.reader(rf)
# Parse header
header = next(reader)
acct_id = 0
for row in reader:
if row[0].startswith("#"):
continue
num = int(row[header.index('count')])
bank_id = row[header.index('bank_id')]
if bank_id is None:
bank_id = self.default_bank_id
# Generate accounts (balance will be set by demographics assignment)
for i in range(num):
self.add_account(acct_id, init_balance=0.0, bank_id=bank_id, is_sar=False, normal_models=list())
acct_id += 1
logger.info("Generated %d accounts." % self.num_accounts)
def generate_normal_transactions(self):
"""Generate a base directed graph from degree sequences
TODO: Add options to call scale-free generator functions directly instead of loading degree CSV files
:return: Directed graph as the base transaction graph (not complete transaction graph)
"""
deg_file = os.path.join(self.output_dir, self.degree_file) # degree.csv is in spatial output
in_deg, out_deg = get_degrees(deg_file, self.num_accounts) # read out the in and out degree distributions
G = directed_configuration_model(in_deg, out_deg, self.seed)
G = nx.DiGraph(G)
self.g = G
logger.info("Add %d base transactions" % self.g.number_of_edges())
nodes = list(self.g.nodes())
for src_i, dst_i in self.g.edges():
src = nodes[src_i]
dst = nodes[dst_i]
self.add_edge_info(src, dst) # Add edge info.
def add_account(self, acct_id, **attr):
"""Add an account vertex
:param acct_id: Account ID
:param init_balance: Initial amount
:param start: The day when the account opened
:param end: The day when the account closed
:param bank_id: Bank ID
:param attr: Optional attributes
:return:
"""
if attr['bank_id'] is None:
attr['bank_id'] = self.default_bank_id
self.g.nodes[acct_id].update(attr)
self.bank_to_accts[attr['bank_id']].add(acct_id)
self.acct_to_bank[acct_id] = attr['bank_id']
def remove_typology_candidate(self, acct):
"""Remove an account vertex from AML typology member candidates
:param acct: Account ID
"""
self.hubs.discard(acct) # remove from hubs
bank_id = self.acct_to_bank[acct]
del self.acct_to_bank[acct] # remove from bank mapping
self.bank_to_accts[bank_id].discard(acct)
def add_edge_info(self, orig, bene):
"""Adds info to edge. Based on add_transaction.
Add transaction will go away eventually.
:param orig: Originator account ID
:param bene: Beneficiary account ID
:return:
"""
self.check_account_exist(orig) # Ensure the originator and beneficiary accounts exist
self.check_account_exist(bene)
if orig == bene:
raise ValueError("Self loop from/to %s is not allowed for transaction networks" % str(orig))
self.g.edges[orig, bene]['edge_id'] = self.edge_id
self.edge_id += 1
# Load Custom Topology Files
def add_subgraph(self, members, topology):
"""Add subgraph from existing account vertices and given graph topology
:param members: Account vertex list
:param topology: Topology graph
:return:
"""
if len(members) != topology.number_of_nodes():
raise nx.NetworkXError("The number of account vertices does not match")
node_map = dict(zip(members, topology.nodes()))
for e in topology.edges():
src = node_map[e[0]]
dst = node_map[e[1]]
self.g.add_edge(src, dst)
self.add_edge_info(src, dst)
def load_edgelist(self, members, csv_name):
"""Load edgelist and add edges with existing account vertices
:param members: Account vertex list
:param csv_name: Edgelist file name
:return:
"""
topology = nx.DiGraph()
topology = nx.read_edgelist(csv_name, delimiter=",", create_using=topology)
self.add_subgraph(members, topology)
def mark_active_edges(self):
nx.set_edge_attributes(self.g, False, 'active')
for normal_model in self.normal_models:
subgraph = self.g.subgraph(normal_model.node_ids)
nx.set_edge_attributes(subgraph, True, 'active')
def load_normal_models(self):
"""Load a Normal Model parameter file
"""
normal_models_file = os.path.join(self.input_dir, self.normal_models_file)
with open(normal_models_file, "r") as csvfile:
reader = csv.reader(csvfile)
self.read_normal_models(reader)
def read_normal_models(self, reader):
"""Parse the Normal Model parameter file
"""
header = next(reader)
# Get participation decay from config (default 1.0 = no decay for backward compatibility)
normal_patterns_conf = self.conf.get('normal_patterns', {})
participation_decay = normal_patterns_conf.get('participation_decay', 1.0)
self.nominator = Nominator(self.g, participation_decay=participation_decay)
for row in reader:
count = int(row[header.index('count')])
type = row[header.index('type')]
# schedule_id, min_period, max_period removed - timing now generated in temporal simulation
schedule_id = 2 # Default: unordered (not used in temporal sim anymore)
min_accounts = int(row[header.index('min_accounts')])
max_accounts = int(row[header.index('max_accounts')])
min_period = 1 # Default: not used in temporal sim anymore
max_period = 100 # Default: not used in temporal sim anymore
bank_id = row[header.index('bank_id')]
if bank_id == "":
bank_id = None
self.nominator.initialize_count(type, count, schedule_id, min_accounts, max_accounts, min_period, max_period, bank_id)
self.nominator.initialize_candidates() # create candidate lists for the types considered
def build_normal_models(self):
""" Go through the accounts and attach normal models to them
"""
while(self.nominator.has_more()):
for type in self.nominator.types():
count = self.nominator.count(type)
if count > 0:
success = self.choose_normal_model(type)
self.normal_model_id += success
logger.info(f"Generated {len(self.normal_models)} normal models.")
logger.info("Normal model counts %s", self.nominator.used_count_dict)
return self.normal_models # just to get access in unit test, probably not a good solution
def choose_normal_model(self, type):
"""Choose a normal model based on the type
Args:
type (string): Type of normal model
"""
if type == 'fan_in':
success = self.fan_in_model(type)
elif type == 'fan_out':
success = self.fan_out_model(type)
elif type == 'forward':
success = self.forward_model(type)
elif type == 'single':
success = self.single_model(type)
elif type == 'mutual':
success = self.mutual_model(type)
elif type == 'periodical':
success = self.periodical_model(type)
return success
def fan_in_model(self, type):
node_id = self.nominator.next(type) # get the next node_id for this type
if node_id is None:
return False
candidates = self.nominator.find_available_candidate_neighbors(type, node_id)
if not candidates:
raise ValueError('should always be candidates')
# Create the normal pattern
schedule_id, min_accounts, max_accounts, start_step, end_step, _ = self.nominator.model_params_dict[type][self.nominator.current_candidate_index[type]]
result_ids = candidates | { node_id }
normal_model = NormalModel(self.normal_model_id, type, result_ids, node_id)
normal_model.set_params(schedule_id, start_step, end_step)
for result_id in result_ids:
self.g.nodes[result_id]['normal_models'].append(normal_model)
self.normal_models.append(normal_model)
self.nominator.post_update(node_id, type)
return True
def fan_out_model(self, type):
node_id = self.nominator.next(type) # get the next node_id for this type
if node_id is None:
return False
candidates = self.nominator.find_available_candidate_neighbors(type, node_id) # get the neighboring nodes that are in a potential fan-out relationship
if not candidates:
raise ValueError('should always be candidates')
schedule_id, _, _, start_step, end_step, _ = self.nominator.model_params_dict[type][self.nominator.current_candidate_index[type]]
result_ids = candidates | { node_id }
normal_model = NormalModel(self.normal_model_id, type, result_ids, node_id)
normal_model.set_params(schedule_id, start_step, end_step)
for id in result_ids:
self.g.nodes[id]['normal_models'].append(normal_model)
self.normal_models.append(normal_model)
self.nominator.post_update(node_id, type)
return True
def forward_model(self, type):
node_id = self.nominator.next(type) # get the next node_id for this type
# min and max accounts are not used in forward
schedule_id, _, _, start_step, end_step, bank_id = self.nominator.model_params_dict[type][self.nominator.current_candidate_index[type]]
if node_id is None:
return False
succ_ids = list(self.g.successors(node_id))
pred_ids = list(self.g.predecessors(node_id))
# if bank_id is not None:
# succ_ids = [succ_id for succ_id in succ_ids if self.acct_to_bank[succ_id] == bank_id]
# pred_ids = [pred_id for pred_id in pred_ids if self.acct_to_bank[pred_id] == bank_id]
# find all input-node_id-output sets avialable where input and output are different
sets = [[node_id, pred_id, succ_id] for pred_id in pred_ids for succ_id in succ_ids if pred_id != succ_id]
random.shuffle(sets)
# find the first set of nodes that is not in a forward relationship with this node_id
chosen_nodes = next((nodes for nodes in sets if not self.nominator.is_in_type_relationship_ordered(type, nodes[1], nodes)), None)
if chosen_nodes is None:
raise ValueError('should always be candidates')
main_node = chosen_nodes[1]
# Create normal models
normal_model = NormalModel(self.normal_model_id, type, chosen_nodes, main_node)
normal_model.set_params(schedule_id, start_step, end_step)
for id in chosen_nodes:
self.g.nodes[id]['normal_models'].append(normal_model)
self.normal_models.append(normal_model)
self.nominator.post_update(node_id, type)
return True
def single_model(self, type):
node_id = self.nominator.next(type) # get the next node_id for this type
if node_id is None:
return False
succ_ids = list(self.g.successors(node_id)) # find the accounts connected to this node_id
# find the first account that is not in a single relationship with this node_id
succ_id = next(succ_id for succ_id in succ_ids if not self.nominator.is_in_type_relationship(type, node_id, {node_id, succ_id})) # TODO: this takes a lot of time...
result_ids = { node_id, succ_id }
normal_model = NormalModel(self.normal_model_id, type, result_ids, node_id) # create a normal model with the node_id and the connected account
schedule_id, min_accounts, max_accounts, start_step, end_step, bank_id = self.nominator.model_params_dict[type][self.nominator.current_candidate_index[type]]
normal_model.set_params(schedule_id, start_step, end_step)
for id in result_ids:
self.g.nodes[id]['normal_models'].append(normal_model) # add the normal model to the nodes
self.normal_models.append(normal_model)
self.nominator.post_update(node_id, type)
return True
def periodical_model(self, type):
node_id = self.nominator.next(type)
if node_id is None:
return False
succ_ids = list(self.g.successors(node_id))
succ_id = next(succ_id for succ_id in succ_ids if not self.nominator.is_in_type_relationship(type, node_id, {node_id, succ_id}))
result_ids = { node_id, succ_id }
normal_model = NormalModel(self.normal_model_id, type, result_ids, node_id)
schedule_id, min_accounts, max_accounts, start_step, end_step, _ = self.nominator.model_params_dict[type][self.nominator.current_candidate_index[type]]
normal_model.set_params(schedule_id, start_step, end_step)
for id in result_ids:
self.g.nodes[id]['normal_models'].append(normal_model)
self.normal_models.append(normal_model)
self.nominator.post_update(node_id, type)
return True
def mutual_model(self, type):
node_id = self.nominator.next(type)
if node_id is None:
return False
succ_ids = list(self.g.successors(node_id))
succ_id = next(succ_id for succ_id in succ_ids if not self.nominator.is_in_type_relationship(type, node_id, {node_id, succ_id}))
result_ids = { node_id, succ_id }
normal_model = NormalModel(self.normal_model_id, type, result_ids, node_id)
schedule_id, min_accounts, max_accounts, start_step, end_step, _ = self.nominator.model_params_dict[type][self.nominator.current_candidate_index[type]]
normal_model.set_params(schedule_id, start_step, end_step)
for id in result_ids:
self.g.nodes[id]['normal_models'].append(normal_model)
self.normal_models.append(normal_model)
self.nominator.post_update(node_id, type)
return True
def assign_demographics(self):
"""
Assign demographics-based KYC attributes (age, salary, balance) to accounts.
Uses demographic statistics to create realistic, correlated KYC.
Call after normal models are built, before ML selector preparation.
Balance is derived from: salary + structural position + noise.
"""
demographics_config = self.conf.get('demographics', {})
csv_path = demographics_config.get('csv_path')
if not csv_path:
raise ValueError("demographics.csv_path is required in config")
# Resolve path relative to input directory if not absolute
if not os.path.isabs(csv_path):
csv_path = os.path.join(self.input_dir, csv_path)
logger.info(f"Assigning demographics-based KYC from {csv_path}...")
balance_params = demographics_config.get('balance_params', None)
assign_kyc_from_demographics(
graph=self.g,
demographics_csv=csv_path,
seed=self.seed,
balance_params=balance_params
)
logger.info("Demographics assignment complete")
def prepare_money_laundering_selector(self):
"""
Initialize and prepare the money laundering account selector.
This should be called after the baseline graph and normal models are built,
but before alert patterns are injected.
The selector biases alert member selection based on:
- Graph structure (degree, betweenness, pagerank)
- KYC attributes (balance, salary, age)
- Locality propagation via Personalized PageRank
"""
logger.info("Preparing money laundering account selector...")
self.ml_selector = MoneyLaunderingAccountSelector(
graph=self.g,
config=self.conf,
acct_to_bank=self.acct_to_bank,
seed=self.seed
)
self.ml_selector.prepare()
logger.info("ML account selector ready")
def plot_ml_selection_analysis(self, verbose: bool = False):
"""
Generate plots analyzing ML account selection vs structural/KYC components.
Should be called after load_alert_patterns() so SAR flags are set on accounts.
Args:
verbose: If True, generate plots. If False, skip plotting.
"""
if not verbose:
return
if self.ml_selector is None:
logger.info("ML selector not configured, skipping selection analysis plots")
return
# Output to spatial output directory (alongside accounts.csv, transactions.csv, etc.)
self.ml_selector.plot_ml_selection_analysis(self.output_dir)
def save_baseline_checkpoint(self, checkpoint_path: str = None):
"""
Save the baseline graph state after demographics assignment.
This checkpoint captures the state before alert pattern injection,
allowing the tuner to re-inject alerts with different configurations
without regenerating the entire graph.
The checkpoint includes:
- Transaction graph (nodes, edges, attributes)
- Bank mappings
- Normal models
- Hub accounts
- Edge/alert counters
Args:
checkpoint_path: Path to save checkpoint. If None, saves to
{output_dir}/baseline_checkpoint.pkl
"""
if checkpoint_path is None:
checkpoint_path = os.path.join(self.output_dir, 'baseline_checkpoint.pkl')
checkpoint = {
'graph': self.g,
'bank_to_accts': dict(self.bank_to_accts), # Convert defaultdict
'acct_to_bank': self.acct_to_bank.copy(),
'normal_models': self.normal_models,
'normal_model_id': self.normal_model_id,
'hubs': self.hubs.copy(),
'edge_id': self.edge_id,
'alert_id': self.alert_id,
'num_accounts': self.num_accounts,
'attr_names': self.attr_names.copy(),
}
os.makedirs(os.path.dirname(checkpoint_path), exist_ok=True)
with open(checkpoint_path, 'wb') as f:
pickle.dump(checkpoint, f)
logger.info(f"Saved baseline checkpoint to {checkpoint_path}")
return checkpoint_path
def load_baseline_checkpoint(self, checkpoint_path: str = None):
"""
Load a baseline graph state from checkpoint.
Restores the graph to the state after demographics assignment,
before alert pattern injection. This allows re-injecting alerts
with different ML selector configurations.
Args:
checkpoint_path: Path to checkpoint file. If None, loads from
{output_dir}/baseline_checkpoint.pkl
"""
if checkpoint_path is None:
checkpoint_path = os.path.join(self.output_dir, 'baseline_checkpoint.pkl')
with open(checkpoint_path, 'rb') as f:
checkpoint = pickle.load(f)
# Restore graph state
self.g = checkpoint['graph'].copy() # Deep copy to avoid modifying original
self.bank_to_accts = defaultdict(set, checkpoint['bank_to_accts'])
self.acct_to_bank = checkpoint['acct_to_bank'].copy()
self.normal_models = checkpoint['normal_models']
self.normal_model_id = checkpoint['normal_model_id']
self.hubs = checkpoint['hubs'].copy()
self.edge_id = checkpoint['edge_id']
self.alert_id = checkpoint['alert_id']
self.num_accounts = checkpoint['num_accounts']
self.attr_names = checkpoint['attr_names'].copy()
# Reset alert groups (will be repopulated by load_alert_patterns)
self.alert_groups = dict()
# Reset ML selector (will be re-prepared with new config)
self.ml_selector = None
logger.info(f"Loaded baseline checkpoint from {checkpoint_path}")
def load_alert_patterns(self):
"""Load an AML typology parameter file