File size: 41,409 Bytes
e32e74d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
# 先尝试导入 CuPy。
# 如果成功,部分矩阵运算可以走 GPU;失败则自动退回 NumPy。
try:
    import cupy as cp
    CUPY_AVAILABLE = True
except ImportError:
    cp = None
    CUPY_AVAILABLE = False

# NumPy 是 CPU 版矩阵运算基础。
import numpy as np
# rbf_kernel 用来计算 GIP 所需的高斯核相似度。
from sklearn.metrics.pairwise import rbf_kernel
# os 主要用于检查 mat 文件路径是否存在。
import os

# scipy.io 用来读取 .mat 文件。
try:
    import scipy.io as sio
    SCIPY_IO_AVAILABLE = True
except ImportError:
    sio = None
    SCIPY_IO_AVAILABLE = False

def AMVL(Wrd, Wrr_list, Wdd_list, params, use_cupy=False):
    """
    Training framework that combines BMC (Bi-relational Matrix Completion) and multi-view learning.

    Args:
    - Wrd (np.ndarray): Drug-disease interaction matrix.
    - Wrr_list (list of np.ndarray): List of drug similarity matrices.
    - Wdd_list (list of np.ndarray): List of disease similarity matrices.
    - params (dict): Dictionary of parameters for the algorithm.
    - use_cupy (bool): Whether to use CuPy for GPU acceleration (default: False).

    Returns:
    - F_final (np.ndarray): Final prediction matrix.
    """
    # 如果用户要求用 CuPy 但当前环境没有装,就打印警告并退回 CPU。
    if use_cupy and not CUPY_AVAILABLE:
        print("Warning: CuPy requested but not available. Falling back to NumPy.")
        use_cupy = False

    # 从参数字典中取出算法超参数;没给时使用默认值。
    alpha = params.get('alpha', 10)
    beta = params.get('beta', 10)
    lamdaR = params.get('lamdaR', 0.1)
    lamdaD = params.get('lamdaD', 0.1)
    threshold = params.get('threshold', 0.8)
    max_iter = params.get('max_iter', 300)
    tol1 = params.get('tol1', 2e-3)
    tol2 = params.get('tol2', 1e-5)
    gip_w = params.get('gip_w', 0.2)

    # T 是当前要被恢复 / 更新的药物-疾病关联矩阵。
    T = Wrd.copy()
    
    # 第 1 步:先做 BMC 矩阵补全,尽量把稀疏的已知关联补得更平滑一些。
    print(">>> Step 1: Starting BMC matrix completion...")
    T_mc, _ = BMC_F(alpha, beta, T, tol1, tol2, max_iter, use_cupy=use_cupy)

    # 用补全后的矩阵再计算一遍 GIP 相似度。
    # 这里会分别得到:
    # 1. 药物-药物 GIP 相似度 Grr
    # 2. 疾病-疾病 GIP 相似度 Gdd
    print(">>> Calculating GIP similarity matrices for disease-disease and drug-drug interactions...")
    Grr, Gdd = gip_similarity(T_mc * (T_mc > threshold))

    # 把 GIP 相似度和原始多视图相似度做加权融合。
    # gip_w 越大,表示越依赖 GIP。
    Grr_list = [gip_w * Grr + (1 - gip_w) * Wrr for Wrr in Wrr_list]
    Gdd_list = [gip_w * Gdd + (1 - gip_w) * Wdd for Wdd in Wdd_list]

    # 后续多视图学习时不希望自环干扰,所以先把对角线清零。
    print(">>> Removing diagonal elements to eliminate self-interactions...")
    Wrr_ML = [w.copy() for w in Grr_list]
    Wdd_ML = [w.copy() for w in Gdd_list]

    for i in range(len(Wrr_ML)):
        np.fill_diagonal(Wrr_ML[i], 0)
    for i in range(len(Wdd_ML)):
        np.fill_diagonal(Wdd_ML[i], 0)

    # 第 2 步:做 MSBMF 多相似性双线性矩阵分解。
    # 这一部分会给出一个低秩恢复结果。
    print(">>> Step 2: Performing Matrix Factorization with similarity regularization...")
    U, V, iter_count = MSBMF_F(T.T, Wdd_list, Wrr_list, lamdaD, lamdaR, min(T.shape), tol1, tol2, max_iter, use_cupy=use_cupy)
    print(f">>> Matrix factorization completed in {iter_count} iterations.")

    # 用 U 和 V 重构一个分解版关联矩阵。
    T_msbmf = np.dot(U, V.T).T
    # 再和 BMC 输出逐元素取最大,组合成更稳健的恢复结果。
    T_recovery = np.maximum(T_msbmf, T_mc)

    # 只保留大于阈值的关联,较弱关联先压掉。
    print(">>> Thresholding the recovered matrix based on the threshold value...")
    T_update_mc = T_recovery * (T_recovery > threshold)

    # 第 3 步:做多视图学习,让药物视图和疾病视图共同约束最终预测矩阵。
    print(">>> Step 3: Starting multi-view learning...")
    _, _, F_mv = MVL_F(Wrr_ML, Wdd_ML, T_update_mc, lamdaR, lamdaD, use_cupy=use_cupy)

    # 第 4 步:把多视图学习结果和前面恢复矩阵再融合一次。
    # 最终再把分数截断到 [0, 1] 区间。
    print(">>> Step 4: Combining results and ensuring values are in [0, 1] range...")
    F_final = np.maximum(T_update_mc, F_mv)
    F_final = np.clip(F_final, 0, 1)

    # 返回最终预测矩阵。
    print(">>> AdaMVL training complete. Returning final prediction matrix.")
    return F_final


def _require_scipy_io():
    # *_from_mat 系列接口必须用 scipy.io 读取 .mat。
    if not SCIPY_IO_AVAILABLE:
        raise ImportError(
            "scipy is required for MAT-file I/O. "
            "Install scipy before using *_from_mat helpers."
        )


def _unwrap_matlab_strings(values):
    # 把 MATLAB 中常见的 object/cell 字符串结构展开成普通 numpy 字符串数组。
    if values is None:
        return None

    flattened = values.flatten()
    normalized = []
    for value in flattened:
        item = value
        # MATLAB 保存字符串时常常会出现多层 ndarray 嵌套,这里逐层拆开。
        while isinstance(item, np.ndarray):
            if item.size == 0:
                item = ""
                break
            item = item.flat[0]
        normalized.append(str(item))
    return np.array(normalized)


def _load_prediction_inputs_from_mat(mat_file_path, drug_sim_names=None, disease_sim_names=None):
    # 先确认 scipy 可用。
    _require_scipy_io()

    # mat 文件不存在时直接报错。
    if not os.path.exists(mat_file_path):
        raise FileNotFoundError(f"Mat file not found: {mat_file_path}")

    # 读取 mat 文件中的全部变量。
    print(f">>> Loading data from: {mat_file_path}")
    mat_data = sio.loadmat(mat_file_path)

    # 如果调用方没有手工指定视图,就按默认优先级自动挑选 mat 中存在的键。
    default_drug_sim_names = ['drug_AtcS', 'drug_ChemS', 'drug_DDIS', 'drug_GepS',
                               'drug_KgS', 'drug_LlmS', 'drug_SideS', 'drug_TargetS']
    default_disease_sim_names = ['disease_DoS', 'disease_KgS', 'disease_LlmS', 'disease_PhS']

    if drug_sim_names is None:
        drug_sim_names = [name for name in default_drug_sim_names if name in mat_data]
    if disease_sim_names is None:
        disease_sim_names = [name for name in default_disease_sim_names if name in mat_data]

    print(f">>> Using {len(drug_sim_names)} drug similarity matrices: {drug_sim_names}")
    print(f">>> Using {len(disease_sim_names)} disease similarity matrices: {disease_sim_names}")

    # 取出实际用于预测的药物侧和疾病侧矩阵列表。
    Wrr_list_extended = [mat_data[name] for name in drug_sim_names]
    Wdd_list = [mat_data[name] for name in disease_sim_names]

    # didr 是 mat 文件里疾病 × 药物的已知关联矩阵。
    if 'didr' not in mat_data:
        raise ValueError("Association matrix 'didr' not found in mat file")
    didr = mat_data['didr']
    # 模型内部统一使用药物 × 疾病,所以这里要转置。
    Wrd_known = didr.T

    # Wrname / Wdname 分别是药物名和疾病名。
    drug_names = _unwrap_matlab_strings(mat_data.get('Wrname'))
    disease_names = _unwrap_matlab_strings(mat_data.get('Wdname'))

    # 返回预测所需的核心输入。
    return Wrd_known, Wrr_list_extended, Wdd_list, drug_names, disease_names

###### GIP ######
def gip_similarity(mat_wrd, gamma_d=0.5, gamma_m=0.5):
    """
    Compute the Gaussian interaction profile similarity for diseases and drugs using the RBF kernel.

    Parameters
    ----------
    mat_dv : ndarray of shape (nd, nm)
        Disease-drug interaction matrix where rows represent diseases and columns represent drugs.
    gamma_d : float
        RBF kernel parameter controlling the width of the similarity distribution for diseases.
    gamma_m : float
        RBF kernel parameter controlling the width of the similarity distribution for drugs.

    Returns
    -------
    gdd : ndarray of shape (nd, nd)
        Disease-disease similarity matrix.
    gvv : ndarray of shape (nm, nm)
        Drug-drug similarity matrix.
    """
    # 根据药物的交互轮廓计算药物-药物高斯核相似度。
    grr = rbf_kernel(mat_wrd, mat_wrd, gamma=gamma_d)

    # 根据疾病的交互轮廓计算疾病-疾病高斯核相似度。
    gdd = rbf_kernel(mat_wrd.T, mat_wrd.T, gamma=gamma_m)

    return grr, gdd

###### MSBMF #######
def MSBMF_F(M, D_list, R_list, lambda1, lambda2, k, tol1, tol2, maxiter, use_cupy=False, seed=42):
    """
    MSBMF: Drug repositioning based on multi-similarity bilinear matrix factorization.
    Usage: X, Y, iter = MSBMF(M, D_list, R_list, lambda1, lambda2, lambda3, k, tol1, tol2, maxiter)

    Inputs:
        M         - the target matrix with only known entries and the unobserved entries are 0.
        D_list    - list of disease similarity matrices.
        R_list    - list of drug similarity matrices.
        lambda1   - regularization parameter.
        lambda2   - regularization parameter.
        k         - the latent dimension of matrix factorization.
        tol1, tol2- tolerance of termination conditions.
        maxiter   - maximum number of iterations.

    Outputs:
        X, Y      - two latent low-rank matrices of the completed matrix.
        iter      - the number of iterations.
    """
    # xp 统一抽象成“当前使用的数值后端”,可能是 CuPy 也可能是 NumPy。
    xp = cp if (use_cupy and CUPY_AVAILABLE) else np

    # 把输入矩阵全部转成当前后端支持的数组类型。
    M = xp.array(M)
    # D_list / R_list 先横向拼接成一个大矩阵,便于一起做正则约束。
    D = xp.hstack([xp.array(d) for d in D_list])
    R = xp.hstack([xp.array(r) for r in R_list])
    
    # 固定随机种子,便于复现。
    xp.random.seed(seed)
    # omega 标记已知位置,omega_ 标记未知位置。
    omega = (M != 0).astype(float)
    omega_ = xp.ones_like(omega) - omega

    # 初始化低秩分解和相似性辅助变量。
    U = xp.random.rand(M.shape[0], k)
    V = xp.random.rand(M.shape[1], k)
    P = xp.random.rand(D.shape[1], k)
    Q = xp.random.rand(R.shape[1], k)
    
    X = U
    Y = V
    Z = M.copy()
    W1 = xp.zeros_like(U)
    W2 = xp.zeros_like(V)
    XY = M.copy()

    rho = 1.05
    mu = 1e-4
    max_mu = 1e20

    stop1 = 1
    stop2 = 1

    for i in range(maxiter):
        # 迭代更新 U。
        U = xp.dot(Z, V) + lambda2 * xp.dot(D, P) - W1 + mu * X
        U = xp.dot(U, xp.linalg.inv(xp.dot(V.T, V) + lambda2 * xp.dot(P.T, P) + (lambda1 + mu) * xp.eye(k)))

        # 迭代更新 V。
        V = xp.dot(Z.T, U) + lambda2 * xp.dot(R, Q) - W2 + mu * Y
        V = xp.dot(V, xp.linalg.inv(xp.dot(U.T, U) + lambda2 * xp.dot(Q.T, Q) + (lambda1 + mu) * xp.eye(k)))

        # 更新疾病侧辅助变量 P。
        P = xp.dot(lambda2 * D.T, U)
        P = xp.dot(P, xp.linalg.inv(lambda2 * xp.dot(U.T, U) + lambda2 * xp.eye(k)))

        # 更新药物侧辅助变量 Q。
        Q = xp.dot(lambda2 * R.T, V)
        Q = xp.dot(Q, xp.linalg.inv(lambda2 * xp.dot(V.T, V) + lambda2 * xp.eye(k)))

        # 更新 X,并强制非负。
        X = U + (1 / mu) * W1
        X[X < 0] = 0

        # 更新 Y,并强制非负。
        Y = V + (1 / mu) * W2
        Y[Y < 0] = 0

        # 只在未知位置用 U @ V.T 填补,已知位置仍保留原始观测值。
        Z = M * omega + xp.dot(U, V.T) * omega_

        # 更新拉格朗日乘子。
        W1 = W1 + mu * (U - X)
        W2 = W2 + mu * (V - Y)

        # 计算停止条件:
        # stop1 衡量本轮重构矩阵与上一轮的相对变化,
        # stop2 衡量 stop1 自身是否趋于稳定。
        stop1_0 = stop1
        stop1 = xp.linalg.norm(xp.dot(X, Y.T) - XY, 'fro') / xp.linalg.norm(XY, 'fro')
        stop2 = abs(stop1 - stop1_0) / max(1, abs(stop1_0))

        # 更新上一轮的重构矩阵缓存。
        XY = xp.dot(X, Y.T)

        # 满足双重阈值时停止,否则继续并逐步增大 mu。
        if stop1 < tol1 and stop2 < tol2:
            iter = i + 1
            break
        else:
            iter = i + 1
            mu = min(mu * rho, max_mu)

    if use_cupy and CUPY_AVAILABLE:
        # 如果前面走的是 GPU,这里在返回前转回 NumPy。
        X = xp.asnumpy(X)
        Y = xp.asnumpy(Y)

    return X, Y, iter

###### Multi-View Learning ######
def l2_distance(a, b):
    """
    Compute the squared Euclidean distance between column vectors.

    Args:
    - a (np.ndarray): First input matrix.
    - b (np.ndarray): Second input matrix.

    Returns:
    - d (np.ndarray): Matrix of pairwise squared distances.
    """
    # aa / bb 分别是每个列向量的平方范数。
    aa = np.sum(a * a, axis=0)
    bb = np.sum(b * b, axis=0)
    # ab 是列向量之间的内积矩阵。
    ab = np.dot(a.T, b)
    # 利用 ||x-y||^2 = ||x||^2 + ||y||^2 - 2x^Ty 批量计算距离。
    d = np.add.outer(aa, bb) - 2 * ab
    # 数值误差可能让结果略小于 0,这里裁回非负。
    d = np.maximum(d, 0)
    return d

def e_proj_simplex(v, k=1):
    """
    Project the vector v onto the simplex defined by sum(x) = k and x >= 0.
    Optimized using a sorting algorithm with time complexity O(n log n).

    Args:
    - v (np.ndarray): Input vector.
    - k (float): Value of the sum constraint.

    Returns:
    - w (np.ndarray): The projected vector.
    """
    # 空向量直接返回空。
    n = len(v)
    if n == 0:
        return np.array([])
    # 先按降序排序,这是 simplex 投影经典做法的一步。
    u = np.sort(v)[::-1]
    # cssv 是累计和减去总和约束 k 后的中间量。
    cssv = np.cumsum(u) - k
    # ind 从 1 开始计数。
    ind = np.arange(n) + 1
    # 找到满足条件的可行位置。
    cond = u - cssv / ind > 0
    if np.any(cond):
        # rho 是最后一个满足条件的位置。
        rho = ind[cond][-1]
        # theta 是阈值,用来把原向量平移到 simplex 上。
        theta = cssv[cond][-1] / rho
        w = np.maximum(v - theta, 0)
    else:
        # 如果没有满足条件的元素,就退化成全零向量。
        w = np.zeros_like(v)
    return w

def mini_job(mv_matrix, F, lambda_):
    """
    Update similarity matrix for multi-view learning by minimizing distance with respect to lambda.

    Args:
    - mv_matrix (list of np.ndarray): List of similarity matrices from different views.
    - F (np.ndarray): Feature matrix.
    - lambda_ (float): Regularization parameter.

    Returns:
    - S (np.ndarray): Updated similarity matrix.
    """
    # 根据当前特征矩阵 F 计算样本间欧氏距离。
    distd = l2_distance(F.T, F.T)
    # 先把多个视图相似矩阵做平均,形成一个公共先验。
    a0 = np.mean(mv_matrix, axis=0)
    # 距离越大,更新后的相似度就会被压低。
    ad = a0 - 0.5 * lambda_ * distd
    # 对每一行做 simplex 投影,使每行是非负且和为 1 的权重分布。
    S = np.apply_along_axis(e_proj_simplex, 1, ad)
    return S

def mini_job_gpu(AR, F, lamda, use_cupy=False):
    # mini_job 的加速版:
    # 如果开启 use_cupy 且安装了 CuPy,就尽量在 GPU 上完成计算;
    # 否则直接退回 NumPy 版。
    if use_cupy and CUPY_AVAILABLE:
        xp = cp
        # 确保 F 是当前后端的数组类型。
        F_xp = xp.asarray(F) if not isinstance(F, xp.ndarray) else F
        # l2_distance 目前是 NumPy 实现,这里先转回 CPU 计算后再送回 GPU。
        distd_xp = xp.asarray(l2_distance(xp.asnumpy(F_xp.T), xp.asnumpy(F_xp.T)))
        # 对多个视图求平均。
        a0_xp = sum([xp.asarray(ar) for ar in AR]) / len(AR)
        ad_xp = a0_xp - 0.5 * lamda * distd_xp
        # 对每一行做 simplex 投影,投影函数本身仍在 CPU 上执行。
        S_xp = xp.apply_along_axis(lambda v: xp.asarray(e_proj_simplex(xp.asnumpy(v), k=1)), 1, ad_xp)
        return S_xp
    else:
        # 没有 GPU 时直接用 NumPy 版本。
        return mini_job(AR, F, lamda)

def solve_sylvester_admm(A, B, C, rho=1e-1, max_iter=100, tol=1e-6, use_cupy=False):
    """
    Solve the Sylvester equation using ADMM with increased precision.

    Args:
    - A (np.ndarray): Coefficient matrix A.
    - B (np.ndarray): Coefficient matrix B.
    - C (np.ndarray): Constant matrix C.
    - rho (float): Augmented Lagrangian parameter.
    - max_iter (int): Maximum number of iterations.
    - tol (float): Tolerance for convergence.
    - use_cupy (bool): Whether to use CuPy for GPU acceleration (default: False).

    Returns:
    - X (np.ndarray): Solution matrix X.
    """
    # 统一选择当前数值后端。
    xp = cp if (use_cupy and CUPY_AVAILABLE) else np

    # 把输入矩阵转成当前后端数组。
    A_xp = xp.asarray(A)
    B_xp = xp.asarray(B)
    C_xp = xp.asarray(C)

    # C 的形状就是要求解的 X 的形状。
    m, n = C_xp.shape
    # X 是待求解变量,Z/U 是 ADMM 的辅助变量。
    X_xp = xp.zeros((m, n))
    Z_xp = xp.zeros((m, n))
    U_xp = xp.zeros((m, n))

    # 构造单位阵。
    I_m = xp.eye(m)
    I_n = xp.eye(n)

    # 预先算好逆矩阵,减少循环内重复计算。
    A_inv_xp = xp.linalg.inv(A_xp + rho * I_m)
    B_inv_xp = xp.linalg.inv(B_xp + rho * I_n)

    # 进行 ADMM 迭代。
    for _ in range(max_iter):
        # 先更新 X。
        V_xp = C_xp - Z_xp + U_xp
        X_xp = A_inv_xp @ V_xp @ B_inv_xp

        # 保存旧 Z,用于计算对偶残差。
        Z_old_xp = Z_xp.copy()
        # 这里的 Z 更新是一个简单拷贝步骤。
        Z_xp = (X_xp + U_xp)

        # 更新对偶变量 U。
        U_xp = U_xp + (X_xp - Z_xp)

        # r_norm 是原始残差,s_norm 是对偶残差。
        r_norm = xp.linalg.norm(X_xp - Z_xp, ord='fro')
        s_norm = xp.linalg.norm(-rho * (Z_xp - Z_old_xp), ord='fro')

        # 两个残差都足够小时停止。
        if r_norm < tol and s_norm < tol:
            break

    if use_cupy and CUPY_AVAILABLE:
        # GPU 跑完后转回 NumPy。
        return xp.asnumpy(X_xp)
    else:
        return X_xp

def MVL_F(AR, AD, A, lamdaR, lamdaD, use_cupy=False):
    """
    Python implementation of Multi-View Prediction with ADMM to solve Sylvester equation.

    Args:
    - AR (list of np.ndarray): List of drug similarity matrices from multiple views.
    - AD (list of np.ndarray): List of disease similarity matrices from multiple views.
    - A (np.ndarray): Drug-disease association matrix.
    - lamdaR (float): Regularization parameter for drug similarity.
    - lamdaD (float): Regularization parameter for disease similarity.
    - use_cupy (bool): Whether to use CuPy for GPU acceleration (default: False).

    Returns:
    - SR (np.ndarray): Updated drug similarity matrix.
    - SD (np.ndarray): Updated disease similarity matrix.
    - F (np.ndarray): Multi-view prediction result.
    """
    # 输出当前使用了多少个药物视图和疾病视图。
    print(f">>> Performing multi-view learning with {len(AR)} drug views and {len(AD)} disease views...")

    # NITER 是最大迭代次数。
    NITER = 100
    # thresh 是收敛判据阈值。
    thresh = 1e-10
    # epsilon 用来避免度矩阵分母为 0。
    epsilon = 1e-5

    # F_old 保存上一轮的预测矩阵。
    F_old = A.copy()
    # F 是当前轮预测矩阵,初始直接取 A。
    F = A.copy()
    # 记录药物和疾病数量。
    num_drugs = A.shape[0]
    num_diseases = A.shape[1]
    # SR / SD 分别是更新后的统一药物图和统一疾病图。
    SR = np.zeros_like(AR[0])
    SD = np.zeros_like(AD[0])

    # 单位阵用于构造归一化拉普拉斯。
    idR = np.eye(num_drugs)
    idD = np.eye(num_diseases)

    for iter in range(NITER):
        # 第一步:根据当前 F 更新统一药物图 SR 和统一疾病图 SD。
        if use_cupy and CUPY_AVAILABLE:
            F_xp = cp.asarray(F)
            SR_xp = mini_job_gpu([cp.asarray(ar) for ar in AR], F_xp, lamdaR, use_cupy=use_cupy)
            SR = cp.asnumpy(SR_xp)
            # GPU 分支下同步更新疾病图。
            SD_xp = mini_job_gpu([cp.asarray(ad) for ad in AD], F_xp.T, lamdaD, use_cupy=use_cupy)
            SD = cp.asnumpy(SD_xp)
        else:
            SR = mini_job_gpu(AR, F, lamdaR, use_cupy=use_cupy)
            SD = mini_job_gpu(AD, F.T, lamdaD, use_cupy=use_cupy)

        # 第二步:对 SR 做对称化,并构造药物图拉普拉斯矩阵。
        SR0 = SR - np.diag(np.diag(SR))
        SR1 = (SR0 + SR0.T) / 2
        DR_diag = np.sum(SR1, axis=1) + epsilon
        DR_sqrt_inv = np.diag(1 / np.sqrt(DR_diag))
        LSR = idR - DR_sqrt_inv @ SR1 @ DR_sqrt_inv

        # 第三步:对 SD 做对称化,并构造疾病图拉普拉斯矩阵。
        SD0 = SD - np.diag(np.diag(SD))
        SD1 = (SD0 + SD0.T) / 2
        DD_diag = np.sum(SD1, axis=1) + epsilon
        DD_sqrt_inv = np.diag(1 / np.sqrt(DD_diag))
        LSD = idD - DD_sqrt_inv @ SD1 @ DD_sqrt_inv

        # 第四步:解 Sylvester 方程,得到新的 F。
        F = solve_sylvester_admm(2 * lamdaR * LSR + idR, 2 * lamdaD * LSD + idD, A, use_cupy=use_cupy)

        # 用 Frobenius 范数衡量新旧 F 的变化程度。
        diff = np.linalg.norm(F - F_old, 'fro')
        if diff < thresh:
            print(f'>>> Iteration stops at {iter + 1} step.')
            break

        # 没收敛就更新 F_old 进入下一轮。
        F_old = F.copy()

    return SR, SD, F

###### Bounded Matrix Completion ######
def BMC_F(alpha, beta, T, tol1, tol2, max_iter, use_cupy=False):
    """
    BMC: Bounded Matrix Completion (BMC) Algorithm that can use CuPy for GPU acceleration or NumPy for CPU.
    This algorithm completes the input matrix T by optimizing it while ensuring that the values are within the specified bounds [0, 1].

    Args:
    - alpha, beta (float): Parameters for the algorithm controlling the influence of different terms.
    - T (np.ndarray): Target matrix with observed entries, while unobserved entries are set to 0.
    - tol1, tol2 (float): Tolerance values for convergence criteria.
    - max_iter (int): Maximum number of iterations allowed.
    - use_cupy (bool): Whether to use CuPy for GPU acceleration (default: False).

    Returns:
    - T_recovery (np.ndarray): Completed matrix after BMC.
    - iter_count (int): Number of iterations performed by the algorithm.
    """
    # 统一当前数值后端。
    xp = cp if (use_cupy and CUPY_AVAILABLE) else np

    # tr_index 标记原矩阵中哪些位置是已知观测值。
    tr_index = (T != 0).astype(float)

    # 把输入矩阵转成当前后端数组。
    T = xp.array(T)
    tr_index = xp.array(tr_index)

    # 初始化 ADMM 变量:
    # X 是当前估计矩阵,
    # W 是施加边界约束后的矩阵,
    # Y 是对偶变量。
    X = T.copy()
    W = X.copy()
    Y = xp.zeros_like(X)

    # i 是迭代计数器。
    i = 1
    # stop1 / stop2 是收敛判据。
    stop1 = 1
    stop2 = 1

    # 进入 BMC 主循环。
    while (stop1 > tol1 or stop2 > tol2) and i <= max_iter:
        # 第一步:根据当前 X、Y 和观测项更新 W。
        tran = (1 / beta) * (Y + alpha * (T * tr_index)) + X
        W = tran - (alpha / (alpha + beta)) * (tran * tr_index)
        # 把 W 裁到 [0, 1] 范围内。
        W = xp.clip(W, 0, 1)

        # 第二步:对 W - Y/beta 做 SVT,更新 X。
        X_new = svt(W - (1 / beta) * Y, 1 / beta, use_cupy=use_cupy)

        # 第三步:更新对偶变量 Y。
        Y = Y + beta * (X_new - W)

        # 第四步:更新停止条件。
        stop1_0 = stop1
        stop1 = xp.linalg.norm(X_new - X, 'fro') / (xp.linalg.norm(X, 'fro') + 1e-8)
        stop2 = abs(stop1 - stop1_0) / max(1, abs(stop1_0))

        # 把当前轮结果作为下一轮的旧值。
        X = X_new.copy()
        i += 1

    # 循环结束后打印收敛信息。
    if i > max_iter:
        print('>>> Warning: Reached maximum iteration without convergence!')
    else:
        print(f'>>> BMC converged in {i - 1} iterations.')

    # 返回补全后的矩阵以及真实迭代次数。
    if use_cupy and CUPY_AVAILABLE:
        T_recovery = xp.asnumpy(W)
    else:
        T_recovery = W
    iter_count = i - 1
    return T_recovery, iter_count

def svt(M, tau, use_cupy=False):
    """
    Singular Value Thresholding (SVT) function that can use CuPy or NumPy.
    Performs Singular Value Decomposition (SVD) on the input matrix M and applies soft-thresholding to singular values.

    Args:
    - M (np.ndarray or cp.ndarray): Input matrix.
    - tau (float): Threshold parameter.
    - use_cupy (bool): Whether to use CuPy for GPU acceleration (default: False).

    Returns:
    - X (np.ndarray or cp.ndarray): Matrix after thresholding.
    """
    # 统一当前数值后端。
    xp = cp if (use_cupy and CUPY_AVAILABLE) else np

    # 先做奇异值分解。
    U, S, VT = xp.linalg.svd(M, full_matrices=False)
    # 对奇异值做软阈值化。
    S_threshold = xp.maximum(S - tau, 0)
    # 用阈值化后的奇异值重新构造矩阵。
    X = xp.dot(U, xp.dot(xp.diag(S_threshold), VT))
    return X


def predict_new_drug(Wrd_known, Wrr_list_extended, Wdd_list, params=None, use_cupy=False):
    """
    Predict associations between a new drug and all diseases.

    Scenario:
    - Training set: x drugs and y diseases with known associations (Wrd_known: x×y)
    - New drug: 1 additional drug (row x+1) with unknown disease associations
    - Drug similarity matrices are extended from x×x to (x+1)×(x+1)
    - Disease similarity matrices remain y×y

    Args:
    - Wrd_known (np.ndarray): Known drug-disease association matrix (x×y), complete training set.
    - Wrr_list_extended (list of np.ndarray): List of extended drug similarity matrices ((x+1)×(x+1)).
                                               The last row/column represents the new drug's similarity to known drugs.
    - Wdd_list (list of np.ndarray): List of disease similarity matrices (y×y), unchanged.
    - params (dict, optional): Dictionary of parameters for the AMVL algorithm. If None, uses default parameters.
    - use_cupy (bool): Whether to use CuPy for GPU acceleration (default: False).

    Returns:
    - predictions (np.ndarray): Predicted association probabilities for the new drug with all diseases (shape: y,).
    - ranked_results (list of tuples): List of (disease_index, probability) tuples, sorted by probability in descending order.

    Example:
    >>> # Suppose we have 593 drugs and 313 diseases in training set
    >>> Wrd_known = np.random.rand(593, 313)  # Known associations
    >>> Wrr_extended = [np.random.rand(594, 594) for _ in range(5)]  # Extended drug similarities
    >>> Wdd = [np.random.rand(313, 313) for _ in range(2)]  # Disease similarities
    >>> predictions, ranked = predict_new_drug(Wrd_known, Wrr_extended, Wdd)
    >>> print(f"Top 10 predicted diseases: {ranked[:10]}")
    """
    # 这个函数本质上是单药兼容封装:
    # 内部其实直接调用 predict_new_drugs,
    # 然后只返回最后 1 个新药的结果。
    predictions_all, ranked_all = predict_new_drugs(
        Wrd_known=Wrd_known,
        Wrr_list_extended=Wrr_list_extended,
        Wdd_list=Wdd_list,
        params=params,
        use_cupy=use_cupy,
    )

    # 如果实际上追加了多个新药,这里会给出警告,但仍只保留最后一个。
    if predictions_all.shape[0] > 1:
        print(
            f"Warning: Found {predictions_all.shape[0]} appended new drugs. "
            "predict_new_drug() keeps backward compatibility and only returns the last one."
        )

    # 单药接口只取最后一行预测分数。
    predictions = predictions_all[-1, :]
    # 单药接口只取最后一个新药对应的排序结果。
    ranked_results = ranked_all[-1]

    # 额外打印 top10,方便快速查看。
    print(f">>> Top 10 predicted disease associations:")
    for rank, (disease_idx, prob) in enumerate(ranked_results[:10], 1):
        print(f"    {rank}. Disease {disease_idx}: {prob:.6f}")

    return predictions, ranked_results


def predict_new_drugs(Wrd_known, Wrr_list_extended, Wdd_list, params=None, use_cupy=False):
    """
    Predict associations between one or more appended new drugs and all diseases.

    Scenario:
    - Training set: x drugs and y diseases with known associations (Wrd_known: x×y)
    - Test set: k additional drugs with unknown disease associations
    - Drug similarity matrices are extended from x×x to (x+k)×(x+k)
    - Disease similarity matrices remain y×y

    Args:
    - Wrd_known (np.ndarray): Known drug-disease association matrix (x×y), complete training set.
    - Wrr_list_extended (list of np.ndarray): List of extended drug similarity matrices ((x+k)×(x+k)).
    - Wdd_list (list of np.ndarray): List of disease similarity matrices (y×y), unchanged.
    - params (dict, optional): Dictionary of parameters for the AMVL algorithm. If None, uses default parameters.
    - use_cupy (bool): Whether to use CuPy for GPU acceleration (default: False).

    Returns:
    - predictions_all (np.ndarray): Predicted association probabilities for all appended new drugs
      with all diseases (shape: k×y).
    - ranked_results_all (list of list[tuple[int, float]]): Ranked disease predictions for each
      appended new drug, sorted by probability in descending order.
    """
    # 如果请求 GPU 但当前环境没有 CuPy,就退回 CPU。
    if use_cupy and not CUPY_AVAILABLE:
        print("Warning: CuPy requested but not available. Falling back to NumPy.")
        use_cupy = False

    # 读取老药数、疾病数和扩展后总药物数。
    num_known_drugs, num_diseases = Wrd_known.shape
    num_total_drugs = Wrr_list_extended[0].shape[0]
    # 新药数量 = 扩展后总药物数 - 老药数量。
    num_new_drugs = num_total_drugs - num_known_drugs

    # 如果没多出任何新药,说明输入矩阵不是扩展版。
    if num_new_drugs <= 0:
        raise ValueError(
            f"No new drugs found. Drug similarity matrices have {num_total_drugs} drugs, "
            f"but association matrix has {num_known_drugs} drugs."
        )

    # 检查所有药物相似矩阵是否尺寸一致。
    for i, Wrr in enumerate(Wrr_list_extended):
        if Wrr.shape != (num_total_drugs, num_total_drugs):
            raise ValueError(
                f"Wrr_list_extended[{i}] has shape {Wrr.shape}, expected {(num_total_drugs, num_total_drugs)}"
            )

    # 检查所有疾病相似矩阵是否尺寸一致。
    for i, Wdd in enumerate(Wdd_list):
        if Wdd.shape != (num_diseases, num_diseases):
            raise ValueError(
                f"Wdd_list[{i}] has shape {Wdd.shape}, expected {(num_diseases, num_diseases)}"
            )

    # 打印当前预测任务的基本规模。
    print(f">>> Predicting associations for {num_new_drugs} new drug(s) with {num_diseases} diseases...")
    print(f">>> Training set: {num_known_drugs} drugs × {num_diseases} diseases")
    print(f">>> Extended drug similarity matrices: {num_total_drugs} × {num_total_drugs}")

    # 给 Wrd_known 下面补 num_new_drugs 行全 0,
    # 这些 0 行表示“新药对疾病的未知标签”。
    Wrd_extended = np.vstack([Wrd_known, np.zeros((num_new_drugs, num_diseases))])
    print(f">>> Extended association matrix shape: {Wrd_extended.shape}")

    # 如果调用方没传参数,就使用内置默认参数。
    if params is None:
        params = {
            'alpha': 10,
            'beta': 10,
            'lamdaR': 0.1,
            'lamdaD': 0.1,
            'threshold': 0.8,
            'max_iter': 300,
            'tol1': 2e-3,
            'tol2': 1e-5,
            'gip_w': 0.2
        }

    # 调用 AMVL 主体,得到完整药物集合上的最终预测矩阵。
    print(">>> Running AMVL algorithm for batch new-drug prediction...")
    F_final = AMVL(Wrd_extended, Wrr_list_extended, Wdd_list, params, use_cupy=use_cupy)

    # 只取最后 num_new_drugs 行,作为新药预测结果。
    predictions_all = F_final[-num_new_drugs:, :]
    print(f">>> Prediction complete. Shape of predictions: {predictions_all.shape}")
    print(
        f">>> Prediction statistics - Min: {predictions_all.min():.4f}, "
        f"Max: {predictions_all.max():.4f}, Mean: {predictions_all.mean():.4f}"
    )

    # 把每个新药对所有疾病的分数展开成排序列表。
    ranked_results_all = []
    for row in predictions_all:
        ranked_results = [(i, prob) for i, prob in enumerate(row)]
        ranked_results.sort(key=lambda x: x[1], reverse=True)
        ranked_results_all.append(ranked_results)

    # 多药模式下不逐个打印 top10,避免终端输出过长。
    if num_new_drugs > 1:
        print(">>> Batch mode detected. Skipping verbose per-drug top-10 dump.")

    return predictions_all, ranked_results_all


def predict_new_drug_from_mat(mat_file_path, drug_sim_names=None, disease_sim_names=None,
                                params=None, use_cupy=False, return_names=True):
    """
    Predict associations between a new drug and all diseases directly from a .mat file.

    This is a simplified interface that only requires a .mat file path. The .mat file should contain:
    - Extended drug similarity matrices (e.g., 594×594 for 593 known + 1 new drug)
    - Disease similarity matrices (e.g., 313×313)
    - Known drug-disease associations for the training drugs
    - Drug and disease names

    Args:
    - mat_file_path (str): Path to the .mat file containing the dataset.
    - drug_sim_names (list of str, optional): Names of drug similarity matrices to use.
                                               If None, uses all drug similarity matrices found.
                                               Default order: ['drug_AtcS', 'drug_ChemS', 'drug_DDIS',
                                                              'drug_GepS', 'drug_KgS', 'drug_LlmS',
                                                              'drug_SideS', 'drug_TargetS']
    - disease_sim_names (list of str, optional): Names of disease similarity matrices to use.
                                                  If None, uses all disease similarity matrices found.
                                                  Default order: ['disease_DoS', 'disease_KgS',
                                                                 'disease_LlmS', 'disease_PhS']
    - params (dict, optional): Dictionary of parameters for the AMVL algorithm. If None, uses default.
    - use_cupy (bool): Whether to use CuPy for GPU acceleration (default: False).
    - return_names (bool): Whether to return drug and disease names (default: True).

    Returns:
    - predictions (np.ndarray): Predicted association probabilities for the new drug with all diseases.
    - ranked_results (list of tuples): List of (disease_index, probability, disease_name) tuples
                                       if return_names=True, otherwise (disease_index, probability).
    - drug_names (np.ndarray, optional): Array of drug names (returned if return_names=True).
    - disease_names (np.ndarray, optional): Array of disease names (returned if return_names=True).

    Example:
    >>> # With extended dataset (594 drugs, 313 diseases)
    >>> predictions, ranked, drug_names, disease_names = predict_new_drug_from_mat(
    ...     'data/Fdataset/Fdataset_new_drug.mat'
    ... )
    >>> print(f"Top 10 predicted diseases for new drug {drug_names[-1]}:")
    >>> for rank, (idx, prob, disease) in enumerate(ranked[:10], 1):
    ...     print(f"{rank}. {disease}: {prob:.4f}")
    """
    # 这是单药兼容接口:
    # 从 .mat 中加载输入,再调用批量接口,最后只返回最后一个新药。
    Wrd_known, Wrr_list_extended, Wdd_list, drug_names, disease_names = _load_prediction_inputs_from_mat(
        mat_file_path=mat_file_path,
        drug_sim_names=drug_sim_names,
        disease_sim_names=disease_sim_names,
    )

    # 读取维度信息。
    num_drugs_extended = Wrr_list_extended[0].shape[0]
    num_known_drugs = Wrd_known.shape[0]
    num_diseases = Wrd_known.shape[1]

    # 打印读取到的数据规模,便于核查。
    print(f">>> Dataset dimensions:")
    print(f"    Total drugs (with new drug): {num_drugs_extended}")
    print(f"    Known drugs (training): {num_known_drugs}")
    print(f"    Diseases: {num_diseases}")
    print(f"    Drug similarity matrices: {[W.shape for W in Wrr_list_extended]}")
    print(f"    Disease similarity matrices: {[W.shape for W in Wdd_list]}")

    # 如果总药物数没有超过老药数,说明 .mat 并没有真正追加新药。
    if num_drugs_extended <= num_known_drugs:
        raise ValueError(
            f"No new drug found. Drug similarity matrices have {num_drugs_extended} drugs, "
            f"but association matrix has {num_known_drugs} drugs. Expected at least {num_known_drugs + 1}."
        )

    # 计算当前 .mat 里到底追加了多少个新药。
    num_new_drugs = num_drugs_extended - num_known_drugs
    # 如果不止 1 个,这个兼容接口仍会只返回最后一个。
    if num_new_drugs != 1:
        print(f"Warning: Found {num_new_drugs} new drugs, but only predicting for the last one.")

    # 实际预测仍然调用批量版本。
    predictions_all, ranked_results_all = predict_new_drugs(
        Wrd_known=Wrd_known,
        Wrr_list_extended=Wrr_list_extended,
        Wdd_list=Wdd_list,
        params=params,
        use_cupy=use_cupy,
    )

    # 单药兼容接口只取最后一个新药的结果。
    predictions = predictions_all[-1, :]
    ranked_results_basic = ranked_results_all[-1]

    # 如果要求返回疾病名称,就把 disease_names 也拼进去。
    if return_names and disease_names is not None:
        ranked_results = [(idx, prob, disease_names[idx]) for idx, prob in ranked_results_basic]
    else:
        ranked_results = ranked_results_basic

    # 根据 return_names 决定返回几项内容。
    if return_names:
        return predictions, ranked_results, drug_names, disease_names
    return predictions, ranked_results


def predict_new_drugs_from_mat(mat_file_path, drug_sim_names=None, disease_sim_names=None,
                                params=None, use_cupy=False, return_names=True):
    """
    Predict associations for all appended new drugs directly from a .mat file.

    Returns:
    - predictions_all (np.ndarray): Shape (k, num_diseases), one row per appended new drug.
    - ranked_results_all (list): Ranked disease predictions for each appended new drug.
    - new_drug_names (np.ndarray, optional): Names/IDs of the appended new drugs.
    - disease_names (np.ndarray, optional): Disease names/IDs.
    """
    # 这是当前真正推荐的多药 .mat 接口。
    Wrd_known, Wrr_list_extended, Wdd_list, drug_names, disease_names = _load_prediction_inputs_from_mat(
        mat_file_path=mat_file_path,
        drug_sim_names=drug_sim_names,
        disease_sim_names=disease_sim_names,
    )

    # 读取当前扩展数据集规模。
    num_drugs_extended = Wrr_list_extended[0].shape[0]
    num_known_drugs = Wrd_known.shape[0]
    num_diseases = Wrd_known.shape[1]
    num_new_drugs = num_drugs_extended - num_known_drugs

    # 打印维度信息,帮助确认 batch 新药数量是否正确。
    print(f">>> Dataset dimensions:")
    print(f"    Total drugs (with new drugs): {num_drugs_extended}")
    print(f"    Known drugs (training): {num_known_drugs}")
    print(f"    New drugs (batch): {num_new_drugs}")
    print(f"    Diseases: {num_diseases}")
    print(f"    Drug similarity matrices: {[W.shape for W in Wrr_list_extended]}")
    print(f"    Disease similarity matrices: {[W.shape for W in Wdd_list]}")

    # 调用真正的批量预测主体。
    predictions_all, ranked_results_basic = predict_new_drugs(
        Wrd_known=Wrd_known,
        Wrr_list_extended=Wrr_list_extended,
        Wdd_list=Wdd_list,
        params=params,
        use_cupy=use_cupy,
    )

    # 如果药物名存在,就取 Wrname 最后 num_new_drugs 个作为新药名称列表。
    new_drug_names = None
    if drug_names is not None:
        new_drug_names = drug_names[-num_new_drugs:]

    # 如果要求返回疾病名称,就为每个新药的排序结果补上疾病名。
    if return_names and disease_names is not None:
        ranked_results_all = [
            [(idx, prob, disease_names[idx]) for idx, prob in ranked_results]
            for ranked_results in ranked_results_basic
        ]
    else:
        ranked_results_all = ranked_results_basic

    # 根据 return_names 决定返回四元组还是二元组。
    if return_names:
        return predictions_all, ranked_results_all, new_drug_names, disease_names
    return predictions_all, ranked_results_all