File: _unbalanced.py

package info (click to toggle)
python-pot 0.9.5%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,884 kB
  • sloc: python: 56,498; cpp: 2,310; makefile: 265; sh: 19
file content (1282 lines) | stat: -rw-r--r-- 53,581 bytes parent folder | download
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
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
# -*- coding: utf-8 -*-
"""
Unbalanced Co-Optimal Transport and Fused Unbalanced Gromov-Wasserstein solvers
"""

# Author: Quang Huy Tran <quang-huy.tran@univ-ubs.fr>
#         Alexis Thual <alexis.thual@cea.fr>
#
# License: MIT License

import warnings
from functools import partial
import ot
from ot.backend import get_backend
from ot.utils import list_to_array, get_parameter_pair
from ._utils import (
    fused_unbalanced_across_spaces_cost,
    uot_cost_matrix,
    uot_parameters_and_measures,
)


def fused_unbalanced_across_spaces_divergence(
    X,
    Y,
    wx_samp=None,
    wx_feat=None,
    wy_samp=None,
    wy_feat=None,
    reg_marginals=10,
    epsilon=0,
    reg_type="joint",
    divergence="kl",
    unbalanced_solver="sinkhorn",
    alpha=0,
    M_samp=None,
    M_feat=None,
    rescale_plan=True,
    init_pi=None,
    init_duals=None,
    max_iter=100,
    tol=1e-7,
    max_iter_ot=500,
    tol_ot=1e-7,
    log=False,
    verbose=False,
    **kwargs_solver,
):
    r"""Compute the fused unbalanced cross-spaces divergence between two matrices equipped
    with the distributions on rows and columns. We consider two cases of matrix:

    - (Squared) similarity matrix in Gromov-Wasserstein setting,
    whose rows and columns represent the samples.

    - Arbitrary-size matrix in Co-Optimal Transport setting,
    whose rows represent samples, and columns represent corresponding features/dimensions.

    More precisely, this function returns the sample and feature transport plans between
    :math:`(\mathbf{X}, \mathbf{w}_{xs}, \mathbf{w}_{xf})` and
    :math:`(\mathbf{Y}, \mathbf{w}_{ys}, \mathbf{w}_{yf})`,
    by solving the following problem using Block Coordinate Descent algorithm:

    .. math::

        \mathop{\arg \min}_{\mathbf{P}, \mathbf{Q}}
        &\quad \sum_{i,j,k,l}
        (\mathbf{X}_{i,k} - \mathbf{Y}_{j,l})^2 \mathbf{P}_{i,j} \mathbf{Q}_{k,l} \\
        &+ \rho_s \mathbf{Div}(\mathbf{P}_{\# 1} \mathbf{Q}_{\# 1}^T | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
        + \rho_f \mathbf{Div}(\mathbf{P}_{\# 2} \mathbf{Q}_{\# 2}^T | \mathbf{w}_{xf} \mathbf{w}_{yf}^T) \\
        &+ \alpha_s \sum_{i,j} \mathbf{P}_{i,j} \mathbf{M^{(s)}}_{i, j}
        + \alpha_f \sum_{k, l} \mathbf{Q}_{k,l} \mathbf{M^{(f)}}_{k, l}
        + \mathbf{Reg}(\mathbf{P}, \mathbf{Q})

    Where:

    - :math:`\mathbf{X}`: Source input (arbitrary-size) matrix
    - :math:`\mathbf{Y}`: Target input (arbitrary-size) matrix
    - :math:`\mathbf{M^{(s)}}`: Additional sample matrix
    - :math:`\mathbf{M^{(f)}}`: Additional feature matrix
    - :math:`\mathbf{w}_{xs}`: Distribution of the samples in the source space
    - :math:`\mathbf{w}_{xf}`: Distribution of the features in the source space
    - :math:`\mathbf{w}_{ys}`: Distribution of the samples in the target space
    - :math:`\mathbf{w}_{yf}`: Distribution of the features in the target space
    - :math:`\mathbf{Div}`: Either Kullback-Leibler divergence or half-squared L2 norm.
    - :math:`\mathbf{Reg}`: Regularizer for sample and feature couplings.

    We consider two types of regularizer:
        + Independent regularization used in unbalanced Co-Optimal Transport

        .. math::
            \mathbf{Reg}(\mathbf{P}, \mathbf{Q}) =
            \varepsilon_s \mathbf{Div}(\mathbf{P} | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
            + \varepsilon_f \mathbf{Div}(\mathbf{Q} | \mathbf{w}_{xf} \mathbf{w}_{yf}^T)

        + Joint regularization used in fused unbalanced Gromov-Wasserstein

        .. math::
            \mathbf{Reg}(\mathbf{P}, \mathbf{Q}) =
            \varepsilon \mathbf{Div}(\mathbf{P} \otimes \mathbf{Q} | (\mathbf{w}_{xs} \mathbf{w}_{ys}^T) \otimes (\mathbf{w}_{xf} \mathbf{w}_{yf}^T) )

    .. note:: This function allows epsilon to be zero. In that case, `unbalanced_method` must be either "mm" or "lbfgsb".

    Parameters
    ----------
    X : (n_sample_x, n_feature_x) array-like, float
        Source input matrix.
    Y : (n_sample_y, n_feature_y) array-like, float
        Target input matrix.
    wx_samp : (n_sample_x, ) array-like, float, optional (default = None)
        Histogram assigned on rows (samples) of matrix X.
        Uniform distribution by default.
    wx_feat : (n_feature_x, ) array-like, float, optional (default = None)
        Histogram assigned on columns (features) of matrix X.
        Uniform distribution by default.
    wy_samp : (n_sample_y, ) array-like, float, optional (default = None)
        Histogram assigned on rows (samples) of matrix Y.
        Uniform distribution by default.
    wy_feat : (n_feature_y, ) array-like, float, optional (default = None)
        Histogram assigned on columns (features) of matrix Y.
        Uniform distribution by default.
    reg_marginals: float or indexable object of length 1 or 2
        Marginal relaxation terms for sample and feature couplings.
        If `reg_marginals` is a scalar or an indexable object of length 1,
        then the same value is applied to both marginal relaxations.
    epsilon : scalar or indexable object of length 2, float or int, optional (default = 0)
        Regularization parameters for entropic approximation of sample and feature couplings.
        Allow the case where `epsilon` contains 0. In that case, the MM solver is used by default
        instead of Sinkhorn solver. If `epsilon` is scalar, then the same value is applied to
        both regularization of sample and feature couplings.
    reg_type: string, optional

        - If `reg_type` = "joint": then use joint regularization for couplings.

        - If `reg_type` = "independent": then use independent regularization for couplings.
    divergence : string, optional (default = "kl")

        - If `divergence` = "kl", then Div is the Kullback-Leibler divergence.

        - If `divergence` = "l2", then Div is the half squared Euclidean norm.
    unbalanced_solver : string, optional (default = "sinkhorn")
        Solver for the unbalanced OT subroutine.

        - If `divergence` = "kl", then `unbalanced_solver` can be: "sinkhorn", "sinkhorn_log", "mm", "lbfgsb"

        - If `divergence` = "l2", then `unbalanced_solver` can be "mm", "lbfgsb"
    alpha : scalar or indexable object of length 2, float or int, optional (default = 0)
        Coeffficient parameter of linear terms with respect to the sample and feature couplings.
        If alpha is scalar, then the same alpha is applied to both linear terms.
    M_samp : (n_sample_x, n_sample_y), float, optional (default = None)
        Sample matrix associated to the Wasserstein linear term on sample coupling.
    M_feat : (n_feature_x, n_feature_y), float, optional (default = None)
        Feature matrix associated to the Wasserstein linear term on feature coupling.
    rescale_plan : boolean, optional (default = True)
        If True, then rescale the sample and feature transport plans within each BCD iteration,
        so that they always have equal mass.
    init_pi : tuple of two matrices of size (n_sample_x, n_sample_y) and
        (n_feature_x, n_feature_y), optional (default = None).
        Initialization of sample and feature couplings.
        Uniform distributions by default.
    init_duals : tuple of two tuples ((n_sample_x, ), (n_sample_y, )) and ((n_feature_x, ), (n_feature_y, )), optional (default = None).
        Initialization of sample and feature dual vectors
        if using Sinkhorn algorithm. Zero vectors by default.
    max_iter : int, optional (default = 100)
        Number of Block Coordinate Descent (BCD) iterations.
    tol : float, optional (default = 1e-7)
        Tolerance of BCD scheme. If the L1-norm between the current and previous
        sample couplings is under this threshold, then stop BCD scheme.
    max_iter_ot : int, optional (default = 100)
        Number of iterations to solve each of the
        two unbalanced optimal transport problems in each BCD iteration.
    tol_ot : float, optional (default = 1e-7)
        Tolerance of unbalanced solver for each of the
        two unbalanced optimal transport problems in each BCD iteration.
    log : bool, optional (default = False)
        If True then the cost and four dual vectors, including
        two from sample and two from feature couplings, are recorded.
    verbose : bool, optional (default = False)
        If True then print the COOT cost at every multiplier of `eval_bcd`-th iteration.

    Returns
    -------
    pi_samp : (n_sample_x, n_sample_y) array-like, float
        Sample coupling matrix.
    pi_feat : (n_feature_x, n_feature_y) array-like, float
        Feature coupling matrix.
    log : dictionary, optional
        Returned if `log` is True. The keys are:

            error : array-like, float
                list of L1 norms between the current and previous sample coupling.
            duals_sample : (n_sample_x, n_sample_y) tuple, float
                Pair of dual vectors when solving OT problem w.r.t the sample coupling.
            duals_feature : (n_feature_x, n_feature_y) tuple, float
                Pair of dual vectors when solving OT problem w.r.t the feature coupling.
            linear : float
                Linear part of the cost.
            ucoot : float
                Total cost.
            backend
                The proper backend for all input arrays
    """

    # MAIN FUNCTION

    if reg_type not in ["joint", "independent"]:
        raise (NotImplementedError('Unknown reg_type="{}"'.format(reg_type)))
    if divergence not in ["kl", "l2"]:
        raise (NotImplementedError('Unknown divergence="{}"'.format(divergence)))
    if unbalanced_solver not in ["sinkhorn", "sinkhorn_log", "mm", "lbfgsb"]:
        raise (NotImplementedError('Unknown method="{}"'.format(unbalanced_solver)))

    # hyperparameters
    alpha_samp, alpha_feat = get_parameter_pair(alpha)
    rho_x, rho_y = get_parameter_pair(reg_marginals)
    eps_samp, eps_feat = get_parameter_pair(epsilon)

    if reg_type == "joint":  # same regularization
        eps_feat = eps_samp
    if unbalanced_solver in ["sinkhorn", "sinkhorn_log"] and divergence == "l2":
        warnings.warn(
            "Sinkhorn algorithm does not support L2 norm. \
                      Divergence is set to 'kl'."
        )
        divergence = "kl"
    if unbalanced_solver in ["sinkhorn", "sinkhorn_log"] and (
        eps_samp == 0 or eps_feat == 0
    ):
        warnings.warn(
            "Sinkhorn algorithm does not support unregularized problem. \
                      Solver is set to 'mm'."
        )
        unbalanced_solver = "mm"

    if init_pi is None:
        pi_samp, pi_feat = None, None
    else:
        pi_samp, pi_feat = init_pi

    if init_duals is None:
        init_duals = (None, None)
    duals_samp, duals_feat = init_duals

    arr = [X, Y]

    for tuple in [duals_samp, duals_feat]:
        if tuple is not None:
            d1, d2 = duals_feat
            if d1 is not None:
                arr.append(list_to_array(d1))
            if d2 is not None:
                arr.append(list_to_array(d2))

    nx = get_backend(
        *arr, wx_samp, wx_feat, wy_samp, wy_feat, M_samp, M_feat, pi_samp, pi_feat
    )

    # constant input variables
    if M_samp is None:
        if alpha_samp > 0:
            warnings.warn(
                "M_samp is None but alpha_samp = {} > 0. \
                          The algo will treat as if alpha_samp = 0.".format(alpha_samp)
            )
    else:
        M_samp = alpha_samp * M_samp

    if M_feat is None:
        if alpha_feat > 0:
            warnings.warn(
                "M_feat is None but alpha_feat = {} > 0. \
                          The algo will treat as if alpha_feat = 0.".format(alpha_feat)
            )
    else:
        M_feat = alpha_feat * M_feat

    nx_samp, nx_feat = X.shape
    ny_samp, ny_feat = Y.shape

    # measures on rows and columns
    if wx_samp is None:
        wx_samp = nx.ones(nx_samp, type_as=X) / nx_samp
    if wx_feat is None:
        wx_feat = nx.ones(nx_feat, type_as=X) / nx_feat
    if wy_samp is None:
        wy_samp = nx.ones(ny_samp, type_as=Y) / ny_samp
    if wy_feat is None:
        wy_feat = nx.ones(ny_feat, type_as=Y) / ny_feat
    wxy_samp = wx_samp[:, None] * wy_samp[None, :]
    wxy_feat = wx_feat[:, None] * wy_feat[None, :]

    # initialize coupling and dual vectors
    pi_samp = wxy_samp if pi_samp is None else pi_samp
    pi_feat = wxy_feat if pi_feat is None else pi_feat

    if unbalanced_solver in ["sinkhorn", "sinkhorn_log"]:
        if duals_samp is None:
            duals_samp = (nx.zeros(nx_samp, type_as=X), nx.zeros(ny_samp, type_as=Y))
        if duals_feat is None:
            duals_feat = (nx.zeros(nx_feat, type_as=X), nx.zeros(ny_feat, type_as=Y))

    # shortcut functions
    X_sqr, Y_sqr = X**2, Y**2
    local_cost_samp = partial(
        uot_cost_matrix,
        data=(X_sqr, Y_sqr, X, Y, M_samp),
        tuple_p=(wx_feat, wy_feat),
        hyperparams=(rho_x, rho_y, eps_feat),
        divergence=divergence,
        reg_type=reg_type,
        nx=nx,
    )

    local_cost_feat = partial(
        uot_cost_matrix,
        data=(X_sqr.T, Y_sqr.T, X.T, Y.T, M_feat),
        tuple_p=(wx_samp, wy_samp),
        hyperparams=(rho_x, rho_y, eps_samp),
        divergence=divergence,
        reg_type=reg_type,
        nx=nx,
    )

    parameters_uot_l2_samp = partial(
        uot_parameters_and_measures,
        tuple_weights=(wx_samp, wy_samp, wxy_samp),
        hyperparams=(rho_x, rho_y, eps_samp),
        reg_type=reg_type,
        divergence=divergence,
        nx=nx,
    )

    parameters_uot_l2_feat = partial(
        uot_parameters_and_measures,
        tuple_weights=(wx_feat, wy_feat, wxy_feat),
        hyperparams=(rho_x, rho_y, eps_feat),
        reg_type=reg_type,
        divergence=divergence,
        nx=nx,
    )

    solver = partial(
        ot.solve,
        reg_type=divergence,
        unbalanced_type=divergence,
        method=unbalanced_solver,
        max_iter=max_iter_ot,
        tol=tol_ot,
        verbose=False,
    )

    # initialize log
    if log:
        dict_log = {"backend": nx, "error": []}

    for idx in range(max_iter):
        pi_samp_prev = nx.copy(pi_samp)

        # Update feature coupling
        mass = nx.sum(pi_samp)
        uot_cost = local_cost_feat(pi=pi_samp)

        if divergence == "kl":
            new_rho = (rho_x * mass, rho_y * mass)
            new_eps = mass * eps_feat if reg_type == "joint" else eps_feat
            new_wx, new_wy, new_wxy = wx_feat, wy_feat, wxy_feat
        else:  # divergence == "l2"
            new_w, new_rho, new_eps = parameters_uot_l2_feat(pi_feat)
            new_wx, new_wy, new_wxy = new_w

        res = solver(
            M=uot_cost,
            a=new_wx,
            b=new_wy,
            reg=new_eps,
            c=new_wxy,
            unbalanced=new_rho,
            plan_init=pi_feat,
            potentials_init=duals_feat,
        )
        pi_feat, duals_feat = res.plan, res.potentials

        if rescale_plan:
            pi_feat = nx.sqrt(mass / nx.sum(pi_feat)) * pi_feat

        # Update sample coupling
        mass = nx.sum(pi_feat)
        uot_cost = local_cost_samp(pi=pi_feat)

        if divergence == "kl":
            new_rho = (rho_x * mass, rho_y * mass)
            new_eps = mass * eps_feat if reg_type == "joint" else eps_feat
            new_wx, new_wy, new_wxy = wx_samp, wy_samp, wxy_samp
        else:  # divergence == "l2"
            new_w, new_rho, new_eps = parameters_uot_l2_samp(pi_samp)
            new_wx, new_wy, new_wxy = new_w

        res = solver(
            M=uot_cost,
            a=new_wx,
            b=new_wy,
            reg=new_eps,
            c=new_wxy,
            unbalanced=new_rho,
            plan_init=pi_samp,
            potentials_init=duals_samp,
        )
        pi_samp, duals_samp = res.plan, res.potentials

        if rescale_plan:
            pi_samp = nx.sqrt(mass / nx.sum(pi_samp)) * pi_samp  # shape nx x ny

        # get L1 error
        err = nx.sum(nx.abs(pi_samp - pi_samp_prev))
        if log:
            dict_log["error"].append(err)
        if verbose:
            print("{:5d}|{:8e}|".format(idx + 1, err))
        if err < tol:
            break

    # sanity check
    if nx.sum(nx.isnan(pi_samp)) > 0 or nx.sum(nx.isnan(pi_feat)) > 0:
        raise (
            ValueError(
                "There is NaN in coupling. \
                          Adjust the relaxation or regularization parameters."
            )
        )

    if log:
        linear_cost, ucoot_cost = fused_unbalanced_across_spaces_cost(
            M_linear=(M_samp, M_feat),
            data=(X_sqr, Y_sqr, X, Y),
            tuple_pxy_samp=(wx_samp, wy_samp, wxy_samp),
            tuple_pxy_feat=(wx_feat, wy_feat, wxy_feat),
            pi_samp=pi_samp,
            pi_feat=pi_feat,
            hyperparams=(rho_x, rho_y, eps_samp, eps_feat),
            divergence=divergence,
            reg_type=reg_type,
            nx=nx,
        )

        dict_log["duals_sample"] = duals_samp
        dict_log["duals_feature"] = duals_feat
        dict_log["linear_cost"] = linear_cost
        dict_log["ucoot_cost"] = ucoot_cost

        return pi_samp, pi_feat, dict_log

    else:
        return pi_samp, pi_feat


def unbalanced_co_optimal_transport(
    X,
    Y,
    wx_samp=None,
    wx_feat=None,
    wy_samp=None,
    wy_feat=None,
    reg_marginals=10,
    epsilon=0,
    divergence="kl",
    unbalanced_solver="mm",
    alpha=0,
    M_samp=None,
    M_feat=None,
    rescale_plan=True,
    init_pi=None,
    init_duals=None,
    max_iter=100,
    tol=1e-7,
    max_iter_ot=500,
    tol_ot=1e-7,
    log=False,
    verbose=False,
    **kwargs_solve,
):
    r"""Compute the unbalanced Co-Optimal Transport between two Euclidean point clouds
    (represented as matrices whose rows are samples and columns are the features/dimensions).

    More precisely, this function returns the sample and feature transport plans between
    :math:`(\mathbf{X}, \mathbf{w}_{xs}, \mathbf{w}_{xf})` and
    :math:`(\mathbf{Y}, \mathbf{w}_{ys}, \mathbf{w}_{yf})`,
    by solving the following problem using Block Coordinate Descent algorithm:

    .. math::
        \mathop{\arg \min}_{\mathbf{P}, \mathbf{Q}} &\quad \sum_{i,j,k,l}
        (\mathbf{X}_{i,k} - \mathbf{Y}_{j,l})^2 \mathbf{P}_{i,j} \mathbf{Q}_{k,l} \\
        &+ \rho_s \mathbf{Div}(\mathbf{P}_{\# 1} \mathbf{Q}_{\# 1}^T | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
        + \rho_f \mathbf{Div}(\mathbf{P}_{\# 2} \mathbf{Q}_{\# 2}^T | \mathbf{w}_{xf} \mathbf{w}_{yf}^T) \\
        &+ \alpha_s \sum_{i,j} \mathbf{P}_{i,j} \mathbf{M^{(s)}}_{i, j}
        + \alpha_f \sum_{k, l} \mathbf{Q}_{k,l} \mathbf{M^{(f)}}_{k, l} \\
        &+ \varepsilon_s \mathbf{Div}(\mathbf{P} | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
        + \varepsilon_f \mathbf{Div}(\mathbf{Q} | \mathbf{w}_{xf} \mathbf{w}_{yf}^T)

    Where:

    - :math:`\mathbf{X}`: Source input (arbitrary-size) matrix
    - :math:`\mathbf{Y}`: Target input (arbitrary-size) matrix
    - :math:`\mathbf{M^{(s)}}`: Additional sample matrix
    - :math:`\mathbf{M^{(f)}}`: Additional feature matrix
    - :math:`\mathbf{w}_{xs}`: Distribution of the samples in the source space
    - :math:`\mathbf{w}_{xf}`: Distribution of the features in the source space
    - :math:`\mathbf{w}_{ys}`: Distribution of the samples in the target space
    - :math:`\mathbf{w}_{yf}`: Distribution of the features in the target space
    - :math:`\mathbf{Div}`: Either Kullback-Leibler divergence or half-squared L2 norm.

    .. note:: This function allows `epsilon` to be zero. In that case, `unbalanced_method` must be either "mm" or "lbfgsb".

    Parameters
    ----------
    X : (n_sample_x, n_feature_x) array-like, float
        Source input matrix.
    Y : (n_sample_y, n_feature_y) array-like, float
        Target input matrix.
    wx_samp : (n_sample_x, ) array-like, float, optional (default = None)
        Histogram assigned on rows (samples) of matrix X.
        Uniform distribution by default.
    wx_feat : (n_feature_x, ) array-like, float, optional (default = None)
        Histogram assigned on columns (features) of matrix X.
        Uniform distribution by default.
    wy_samp : (n_sample_y, ) array-like, float, optional (default = None)
        Histogram assigned on rows (samples) of matrix Y.
        Uniform distribution by default.
    wy_feat : (n_feature_y, ) array-like, float, optional (default = None)
        Histogram assigned on columns (features) of matrix Y.
        Uniform distribution by default.
    reg_marginals: float or indexable object of length 1 or 2
        Marginal relaxation terms for sample and feature couplings.
        If `reg_marginals is a scalar` or an indexable object of length 1,
        then the same value is applied to both marginal relaxations.
    epsilon : scalar or indexable object of length 2, float or int, optional (default = 0)
        Regularization parameters for entropic approximation of sample and feature couplings.
        Allow the case where `epsilon` contains 0. In that case, the MM solver is used by default
        instead of Sinkhorn solver. If `epsilon` is scalar, then the same value is applied to
        both regularization of sample and feature couplings.
    divergence : string, optional (default = "kl")

        - If `divergence` = "kl", then Div is the Kullback-Leibler divergence.

        - If `divergence` = "l2", then Div is the half squared Euclidean norm.
    unbalanced_solver : string, optional (default = "sinkhorn")
        Solver for the unbalanced OT subroutine.

        - If `divergence` = "kl", then `unbalanced_solver` can be: "sinkhorn", "sinkhorn_log", "mm", "lbfgsb"

        - If `divergence` = "l2", then `unbalanced_solver` can be "mm", "lbfgsb"
    alpha : scalar or indexable object of length 2, float or int, optional (default = 0)
        Coeffficient parameter of linear terms with respect to the sample and feature couplings.
        If alpha is scalar, then the same alpha is applied to both linear terms.
    M_samp : (n_sample_x, n_sample_y), float, optional (default = None)
        Sample matrix associated to the Wasserstein linear term on sample coupling.
    M_feat : (n_feature_x, n_feature_y), float, optional (default = None)
        Feature matrix associated to the Wasserstein linear term on feature coupling.
    rescale_plan : boolean, optional (default = True)
        If True, then rescale the sample and feature transport plans within each BCD iteration,
        so that they always have equal mass.
    init_pi : tuple of two matrices of size (n_sample_x, n_sample_y) and
        (n_feature_x, n_feature_y), optional (default = None).
        Initialization of sample and feature couplings.
        Uniform distributions by default.
    init_duals : tuple of two tuples ((n_sample_x, ), (n_sample_y, )) and ((n_feature_x, ), (n_feature_y, )), optional (default = None).
        Initialization of sample and feature dual vectors
        if using Sinkhorn algorithm. Zero vectors by default.
    max_iter : int, optional (default = 100)
        Number of Block Coordinate Descent (BCD) iterations.
    tol : float, optional (default = 1e-7)
        Tolerance of BCD scheme. If the L1-norm between the current and previous
        sample couplings is under this threshold, then stop BCD scheme.
    max_iter_ot : int, optional (default = 100)
        Number of iterations to solve each of the
        two unbalanced optimal transport problems in each BCD iteration.
    tol_ot : float, optional (default = 1e-7)
        Tolerance of unbalanced solver for each of the
        two unbalanced optimal transport problems in each BCD iteration.
    log : bool, optional (default = False)
        If True then the cost and four dual vectors, including
        two from sample and two from feature couplings, are recorded.
    verbose : bool, optional (default = False)
        If True then print the COOT cost at every multiplier of `eval_bcd`-th iteration.

    Returns
    -------
    pi_samp : (n_sample_x, n_sample_y) array-like, float
        Sample coupling matrix.
    pi_feat : (n_feature_x, n_feature_y) array-like, float
        Feature coupling matrix.
    log : dictionary, optional
        Returned if `log` is True. The keys are:

            error : array-like, float
                list of L1 norms between the current and previous sample coupling.
            duals_sample : (n_sample_x, n_sample_y)-tuple, float
                Pair of dual vectors when solving OT problem w.r.t the sample coupling.
            duals_feature : (n_feature_x, n_feature_y)-tuple, float
                Pair of dual vectors when solving OT problem w.r.t the feature coupling.
            linear : float
                Linear part of the cost.
            ucoot : float
                Total cost.

    References
    ----------
    .. [71] Tran, H., Janati, H., Courty, N., Flamary, R., Redko, I., Demetci, P., & Singh, R.
            Unbalanced Co-Optimal Transport. AAAI Conference on Artificial Intelligence, 2023.
    """

    return fused_unbalanced_across_spaces_divergence(
        X=X,
        Y=Y,
        wx_samp=wx_samp,
        wx_feat=wx_feat,
        wy_samp=wy_samp,
        wy_feat=wy_feat,
        reg_marginals=reg_marginals,
        epsilon=epsilon,
        reg_type="independent",
        divergence=divergence,
        unbalanced_solver=unbalanced_solver,
        alpha=alpha,
        M_samp=M_samp,
        M_feat=M_feat,
        rescale_plan=rescale_plan,
        init_pi=init_pi,
        init_duals=init_duals,
        max_iter=max_iter,
        tol=tol,
        max_iter_ot=max_iter_ot,
        tol_ot=tol_ot,
        log=log,
        verbose=verbose,
        **kwargs_solve,
    )


def unbalanced_co_optimal_transport2(
    X,
    Y,
    wx_samp=None,
    wx_feat=None,
    wy_samp=None,
    wy_feat=None,
    reg_marginals=10,
    epsilon=0,
    divergence="kl",
    unbalanced_solver="sinkhorn",
    alpha=0,
    M_samp=None,
    M_feat=None,
    rescale_plan=True,
    init_pi=None,
    init_duals=None,
    max_iter=100,
    tol=1e-7,
    max_iter_ot=500,
    tol_ot=1e-7,
    log=False,
    verbose=False,
    **kwargs_solve,
):
    r"""Compute the unbalanced Co-Optimal Transport between two Euclidean point clouds
    (represented as matrices whose rows are samples and columns are the features/dimensions).

    More precisely, this function returns the unbalanced Co-Optimal Transport cost between
    :math:`(\mathbf{X}, \mathbf{w}_{xs}, \mathbf{w}_{xf})` and
    :math:`(\mathbf{Y}, \mathbf{w}_{ys}, \mathbf{w}_{yf})`,
    by solving the following problem using Block Coordinate Descent algorithm:

    .. math::
        \mathop{\min}_{\mathbf{P}, \mathbf{Q}} &\quad \sum_{i,j,k,l}
        (\mathbf{X}_{i,k} - \mathbf{Y}_{j,l})^2 \mathbf{P}_{i,j} \mathbf{Q}_{k,l} \\
        &+ \rho_s \mathbf{Div}(\mathbf{P}_{\# 1} \mathbf{Q}_{\# 1}^T | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
        + \rho_f \mathbf{Div}(\mathbf{P}_{\# 2} \mathbf{Q}_{\# 2}^T | \mathbf{w}_{xf} \mathbf{w}_{yf}^T) \\
        &+ \alpha_s \sum_{i,j} \mathbf{P}_{i,j} \mathbf{M^{(s)}}_{i, j}
        + \alpha_f \sum_{k, l} \mathbf{Q}_{k,l} \mathbf{M^{(f)}}_{k, l} \\
        &+ \varepsilon_s \mathbf{Div}(\mathbf{P} | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
        + \varepsilon_f \mathbf{Div}(\mathbf{Q} | \mathbf{w}_{xf} \mathbf{w}_{yf}^T)

    Where:

    - :math:`\mathbf{X}`: Source input (arbitrary-size) matrix
    - :math:`\mathbf{Y}`: Target input (arbitrary-size) matrix
    - :math:`\mathbf{M^{(s)}}`: Additional sample matrix
    - :math:`\mathbf{M^{(f)}}`: Additional feature matrix
    - :math:`\mathbf{w}_{xs}`: Distribution of the samples in the source space
    - :math:`\mathbf{w}_{xf}`: Distribution of the features in the source space
    - :math:`\mathbf{w}_{ys}`: Distribution of the samples in the target space
    - :math:`\mathbf{w}_{yf}`: Distribution of the features in the target space
    - :math:`\mathbf{Div}`: Either Kullback-Leibler divergence or half-squared L2 norm.

    .. note:: This function allows `epsilon` to be zero. In that case, `unbalanced_method` must be either "mm" or "lbfgsb".
            Also the computation of gradients is only supported for KL divergence. The case of half squared-L2 norm uses those of KL divergence.

    Parameters
    ----------
    X : (n_sample_x, n_feature_x) array-like, float
        Source input matrix.
    Y : (n_sample_y, n_feature_y) array-like, float
        Target input matrix.
    wx_samp : (n_sample_x, ) array-like, float, optional (default = None)
        Histogram assigned on rows (samples) of matrix X.
        Uniform distribution by default.
    wx_feat : (n_feature_x, ) array-like, float, optional (default = None)
        Histogram assigned on columns (features) of matrix X.
        Uniform distribution by default.
    wy_samp : (n_sample_y, ) array-like, float, optional (default = None)
        Histogram assigned on rows (samples) of matrix Y.
        Uniform distribution by default.
    wy_feat : (n_feature_y, ) array-like, float, optional (default = None)
        Histogram assigned on columns (features) of matrix Y.
        Uniform distribution by default.
    reg_marginals: float or indexable object of length 1 or 2
        Marginal relaxation terms for sample and feature couplings.
        If `reg_marginals` is a scalar or an indexable object of length 1,
        then the same value is applied to both marginal relaxations.
    epsilon : scalar or indexable object of length 2, float or int, optional (default = 0)
        Regularization parameters for entropic approximation of sample and feature couplings.
        Allow the case where `epsilon` contains 0. In that case, the MM solver is used by default
        instead of Sinkhorn solver. If `epsilon` is scalar, then the same value is applied to
        both regularization of sample and feature couplings.
    divergence : string, optional (default = "kl")

        - If `divergence` = "kl", then Div is the Kullback-Leibler divergence.

        - If `divergence` = "l2", then Div is the half squared Euclidean norm.
    unbalanced_solver : string, optional (default = "sinkhorn")
        Solver for the unbalanced OT subroutine.

        - If `divergence` = "kl", then `unbalanced_solver` can be: "sinkhorn", "sinkhorn_log", "mm", "lbfgsb"

        - If `divergence` = "l2", then `unbalanced_solver` can be "mm", "lbfgsb"
    alpha : scalar or indexable object of length 2, float or int, optional (default = 0)
        Coeffficient parameter of linear terms with respect to the sample and feature couplings.
        If alpha is scalar, then the same alpha is applied to both linear terms.
    M_samp : (n_sample_x, n_sample_y), float, optional (default = None)
        Sample matrix associated to the Wasserstein linear term on sample coupling.
    M_feat : (n_feature_x, n_feature_y), float, optional (default = None)
        Feature matrix associated to the Wasserstein linear term on feature coupling.
    rescale_plan : boolean, optional (default = True)
        If True, then rescale the transport plans in each BCD iteration,
        so that they always have equal mass.
    init_pi : tuple of two matrices of size (n_sample_x, n_sample_y) and
        (n_feature_x, n_feature_y), optional (default = None).
        Initialization of sample and feature couplings.
        Uniform distributions by default.
    init_duals : tuple of two tuples ((n_sample_x, ), (n_sample_y, )) and ((n_feature_x, ), (n_feature_y, )), optional (default = None).
        Initialization of sample and feature dual vectors
        if using Sinkhorn algorithm. Zero vectors by default.
    max_iter : int, optional (default = 100)
        Number of Block Coordinate Descent (BCD) iterations.
    tol : float, optional (default = 1e-7)
        Tolerance of BCD scheme. If the L1-norm between the current and previous
        sample couplings is under this threshold, then stop BCD scheme.
    max_iter_ot : int, optional (default = 100)
        Number of iterations to solve each of the
        two unbalanced optimal transport problems in each BCD iteration.
    tol_ot : float, optional (default = 1e-7)
        Tolerance of unbalanced solver for each of the
        two unbalanced optimal transport problems in each BCD iteration.
    log : bool, optional (default = False)
        If True then the cost and four dual vectors, including
        two from sample and two from feature couplings, are recorded.
    verbose : bool, optional (default = False)
        If True then print the COOT cost at every multiplier of `eval_bcd`-th iteration.

    Returns
    -------
    ucoot : float
        UCOOT cost.
    log : dictionary, optional
        Returned if `log` is True. The keys are:

            error : array-like, float
                list of L1 norms between the current and previous sample coupling.
            duals_sample : (n_sample_x, n_sample_y)-tuple, float
                Pair of dual vectors when solving OT problem w.r.t the sample coupling.
            duals_feature : (n_feature_x, n_feature_y)-tuple, float
                Pair of dual vectors when solving OT problem w.r.t the feature coupling.
            linear : float
                Linear part of UCOOT cost.
            ucoot : float
                UCOOT cost.
            backend
                The proper backend for all input arrays

    References
    ----------
    .. [71] Tran, H., Janati, H., Courty, N., Flamary, R., Redko, I., Demetci, P., & Singh, R.
            Unbalanced Co-Optimal Transport. AAAI Conference on Artificial Intelligence, 2023.
    """

    if divergence != "kl":
        warnings.warn(
            "The computation of gradients is only supported for KL divergence, not \
                      for {} divergence".format(divergence)
        )

    pi_samp, pi_feat, log_ucoot = unbalanced_co_optimal_transport(
        X=X,
        Y=Y,
        wx_samp=wx_samp,
        wx_feat=wx_feat,
        wy_samp=wy_samp,
        wy_feat=wy_feat,
        reg_marginals=reg_marginals,
        epsilon=epsilon,
        divergence=divergence,
        unbalanced_solver=unbalanced_solver,
        alpha=alpha,
        M_samp=M_samp,
        M_feat=M_feat,
        rescale_plan=rescale_plan,
        init_pi=init_pi,
        init_duals=init_duals,
        max_iter=max_iter,
        tol=tol,
        max_iter_ot=max_iter_ot,
        tol_ot=tol_ot,
        log=True,
        verbose=verbose,
        **kwargs_solve,
    )

    nx = log_ucoot["backend"]

    nx_samp, nx_feat = X.shape
    ny_samp, ny_feat = Y.shape

    # measures on rows and columns
    if wx_samp is None:
        wx_samp = nx.ones(nx_samp, type_as=X) / nx_samp
    if wx_feat is None:
        wx_feat = nx.ones(nx_feat, type_as=X) / nx_feat
    if wy_samp is None:
        wy_samp = nx.ones(ny_samp, type_as=Y) / ny_samp
    if wy_feat is None:
        wy_feat = nx.ones(ny_feat, type_as=Y) / ny_feat

    # extract parameters
    rho_x, rho_y = get_parameter_pair(reg_marginals)
    eps_samp, eps_feat = get_parameter_pair(epsilon)

    # calculate marginals
    pi1_samp, pi2_samp = nx.sum(pi_samp, 1), nx.sum(pi_samp, 0)
    pi1_feat, pi2_feat = nx.sum(pi_feat, 1), nx.sum(pi_feat, 0)
    m_samp, m_feat = nx.sum(pi1_samp), nx.sum(pi1_feat)
    m_wx_feat, m_wx_samp = nx.sum(wx_feat), nx.sum(wx_samp)
    m_wy_feat, m_wy_samp = nx.sum(wy_feat), nx.sum(wy_samp)

    # calculate subgradients
    gradX = 2 * X * (pi1_samp[:, None] * pi1_feat[None, :]) - 2 * nx.dot(
        nx.dot(pi_samp, Y), pi_feat.T
    )  # shape (nx_samp, nx_feat)
    gradY = 2 * Y * (pi2_samp[:, None] * pi2_feat[None, :]) - 2 * nx.dot(
        nx.dot(pi_samp.T, X), pi_feat
    )  # shape (ny_samp, ny_feat)

    grad_wx_samp = rho_x * (m_wx_feat - m_feat * pi1_samp / wx_samp) + eps_samp * (
        m_wy_samp - pi1_samp / wx_samp
    )
    grad_wx_feat = rho_x * (m_wx_samp - m_samp * pi1_feat / wx_feat) + eps_feat * (
        m_wy_feat - pi1_feat / wx_feat
    )
    grad_wy_samp = rho_y * (m_wy_feat - m_feat * pi2_samp / wy_samp) + eps_samp * (
        m_wx_samp - pi2_samp / wy_samp
    )
    grad_wy_feat = rho_y * (m_wy_samp - m_samp * pi2_feat / wy_feat) + eps_feat * (
        m_wx_feat - pi2_feat / wy_feat
    )

    # set gradients
    ucoot = log_ucoot["ucoot_cost"]
    ucoot = nx.set_gradients(
        ucoot,
        (X, Y, wx_samp, wx_feat, wy_samp, wy_feat),
        (gradX, gradY, grad_wx_samp, grad_wx_feat, grad_wy_samp, grad_wy_feat),
    )

    if log:
        return ucoot, log_ucoot

    else:
        return ucoot


def fused_unbalanced_gromov_wasserstein(
    Cx,
    Cy,
    wx=None,
    wy=None,
    reg_marginals=10,
    epsilon=0,
    divergence="kl",
    unbalanced_solver="mm",
    alpha=0,
    M=None,
    init_duals=None,
    init_pi=None,
    max_iter=100,
    tol=1e-7,
    max_iter_ot=500,
    tol_ot=1e-7,
    log=False,
    verbose=False,
    **kwargs_solve,
):
    r"""Compute the lower bound of the fused unbalanced Gromov-Wasserstein (FUGW) between two similarity matrices.
    In practice, this lower bound is used interchangeably with the true FUGW.

    More precisely, this function returns the transport plan between
    :math:`(\mathbf{C^X}, \mathbf{w_X})` and :math:`(\mathbf{C^Y}, \mathbf{w_Y})`,
    by solving the following problem using Block Coordinate Descent algorithm:

    .. math::
        \mathop{\arg \min}_{\substack{\mathbf{P}, \mathbf{Q}: \\ mass(P) = mass(Q)}}
        &\quad \sum_{i,j,k,l} (\mathbf{C^X}_{i,k} - \mathbf{C^Y}_{j,l})^2 \mathbf{P}_{i,j} \mathbf{Q}_{k,l}
        + \frac{\alpha}{2} \sum_{i,j} (\mathbf{P}_{i,j} + \mathbf{Q}_{i,j}) \mathbf{M}_{i, j} \\
        &+ \rho_1 \mathbf{Div}(\mathbf{P}_{\# 1} \mathbf{Q}_{\# 1}^T | \mathbf{w_X} \mathbf{w_X}^T)
        + \rho_2 \mathbf{Div}(\mathbf{P}_{\# 2} \mathbf{Q}_{\# 2}^T | \mathbf{w_Y} \mathbf{w_Y}^T) \\
        &+ \varepsilon \mathbf{Div}(\mathbf{P} \otimes \mathbf{Q} | (\mathbf{w_X} \mathbf{w_Y}^T) \otimes (\mathbf{w_X} \mathbf{w_Y}^T))

    Where:

    - :math:`\mathbf{C^X}`: Source similarity matrix
    - :math:`\mathbf{C^Y}`: Target similarity matrix
    - :math:`\mathbf{M}`: Sample matrix corresponding to the Wasserstein term
    - :math:`\mathbf{w_X}`: Distribution of the samples in the source space
    - :math:`\mathbf{w_Y}`: Distribution of the samples in the target space
    - :math:`\mathbf{Div}`: Either Kullback-Leibler divergence or half-squared L2 norm.

    .. note:: This function allows epsilon to be zero. In that case, `unbalanced_method` must be either "mm" or "lbfgsb".

    Parameters
    ----------
    Cx : (n_sample_x, n_feature_x) array-like, float
        Source similarity matrix.
    Cy : (n_sample_y, n_feature_y) array-like, float
        Target similarity matrix.
    wx : (n_sample_x, ) array-like, float, optional (default = None)
        Histogram assigned on rows (samples) of matrix Cx.
        Uniform distribution by default.
    wy : (n_sample_y, ) array-like, float, optional (default = None)
        Histogram assigned on rows (samples) of matrix Cy.
        Uniform distribution by default.
    reg_marginals: float or indexable object of length 1 or 2
        Marginal relaxation terms for sample and feature couplings.
        If `reg_marginals` is a scalar or an indexable object of length 1,
        then the same value is applied to both marginal relaxations.
    epsilon : scalar, float or int, optional (default = 0)
        Regularization parameters for entropic approximation of sample and feature couplings.
        Allow the case where `epsilon` contains 0. In that case, the MM solver is used by default
        instead of Sinkhorn solver. If `epsilon` is scalar, then the same value is applied to
        both regularization of sample and feature couplings.
    divergence : string, optional (default = "kl")

        - If `divergence` = "kl", then Div is the Kullback-Leibler divergence.

        - If `divergence` = "l2", then Div is the half squared Euclidean norm.
    unbalanced_solver : string, optional (default = "sinkhorn")
        Solver for the unbalanced OT subroutine.

        - If `divergence` = "kl", then `unbalanced_solver` can be: "sinkhorn", "sinkhorn_log", "mm", "lbfgsb"

        - If `divergence` = "l2", then `unbalanced_solver` can be "mm", "lbfgsb"
    alpha : scalar, float or int, optional (default = 0)
        Coeffficient parameter of linear terms with respect to the sample and feature couplings.
        If alpha is scalar, then the same alpha is applied to both linear terms.
    M : (n_sample_x, n_sample_y), float, optional (default = None)
        Sample matrix associated to the Wasserstein linear term on sample coupling.
    init_pi :(n_sample_x, n_sample_y) array-like, optional (default = None)
        Initialization of sample coupling. By default = :math:`w_X w_Y^T`.
    init_duals : tuple of vectors ((n_sample_x, ), (n_sample_y, )), optional (default = None).
        Initialization of sample and feature dual vectors
        if using Sinkhorn algorithm. Zero vectors by default.
    max_iter : int, optional (default = 100)
        Number of Block Coordinate Descent (BCD) iterations.
    tol : float, optional (default = 1e-7)
        Tolerance of BCD scheme. If the L1-norm between the current and previous
        sample couplings is under this threshold, then stop BCD scheme.
    max_iter_ot : int, optional (default = 100)
        Number of iterations to solve each of the
        two unbalanced optimal transport problems in each BCD iteration.
    tol_ot : float, optional (default = 1e-7)
        Tolerance of unbalanced solver for each of the
        two unbalanced optimal transport problems in each BCD iteration.
    log : bool, optional (default = False)
        If True then the cost and four dual vectors, including
        two from sample and two from feature couplings, are recorded.
    verbose : bool, optional (default = False)
        If True then print the COOT cost at every multiplier of `eval_bcd`-th iteration.

    Returns
    -------
    pi_samp : (n_sample_x, n_sample_y) array-like, float
        Sample coupling matrix.
        In practice, we use this matrix as solution of FUGW.
    pi_samp2 : (n_sample_x, n_sample_y) array-like, float
        Second sample coupling matrix.
        In practice, we usually ignore this output.
    log : dictionary, optional
        Returned if `log` is True. The keys are:

            error : array-like, float
                list of L1 norms between the current and previous sample couplings.
            duals : (n_sample_x, n_sample_y)-tuple, float
                Pair of dual vectors when solving OT problem w.r.t the sample coupling.
            linear : float
                Linear part of FUGW cost.
            fugw_cost : float
                Total FUGW cost.
            backend
                The proper backend for all input arrays

    References
    ----------
    .. [70] Thual, A., Tran, H., Zemskova, T., Courty, N., Flamary, R., Dehaene, S., & Thirion, B.
            Aligning individual brains with Fused Unbalanced Gromov-Wasserstein.
            Advances in Neural Information Systems, 35 (2022).

    .. [72] Thibault Séjourné, François-Xavier Vialard, & Gabriel Peyré.
            The Unbalanced Gromov Wasserstein Distance: Conic Formulation and Relaxation.
            Neural Information Processing Systems, 34 (2021).
    """

    alpha = (alpha / 2, alpha / 2)

    pi_samp, pi_feat, dict_log = fused_unbalanced_across_spaces_divergence(
        X=Cx,
        Y=Cy,
        wx_samp=wx,
        wx_feat=wx,
        wy_samp=wy,
        wy_feat=wy,
        reg_marginals=reg_marginals,
        epsilon=epsilon,
        reg_type="joint",
        divergence=divergence,
        unbalanced_solver=unbalanced_solver,
        alpha=alpha,
        M_samp=M,
        M_feat=M,
        rescale_plan=True,
        init_pi=(init_pi, init_pi),
        init_duals=(init_duals, init_duals),
        max_iter=max_iter,
        tol=tol,
        max_iter_ot=max_iter_ot,
        tol_ot=tol_ot,
        log=True,
        verbose=verbose,
        **kwargs_solve,
    )

    if log:
        log_fugw = {
            "error": dict_log["error"],
            "duals": dict_log["duals_sample"],
            "linear_cost": dict_log["linear_cost"],
            "fugw_cost": dict_log["ucoot_cost"],
            "backend": dict_log["backend"],
        }

        return pi_samp, pi_feat, log_fugw

    else:
        return pi_samp, pi_feat


def fused_unbalanced_gromov_wasserstein2(
    Cx,
    Cy,
    wx=None,
    wy=None,
    reg_marginals=10,
    epsilon=0,
    divergence="kl",
    unbalanced_solver="mm",
    alpha=0,
    M=None,
    init_duals=None,
    init_pi=None,
    max_iter=100,
    tol=1e-7,
    max_iter_ot=500,
    tol_ot=1e-7,
    log=False,
    verbose=False,
    **kwargs_solve,
):
    r"""Compute the lower bound of the fused unbalanced Gromov-Wasserstein (FUGW) between two similarity matrices.
    In practice, this lower bound is used interchangeably with the true FUGW.

    More precisely, this function returns the lower bound of the fused unbalanced Gromov-Wasserstein cost between
    :math:`(\mathbf{C^X}, \mathbf{w_X})` and :math:`(\mathbf{C^Y}, \mathbf{w_Y})`,
    by solving the following problem using Block Coordinate Descent algorithm:

    .. math::
        \mathop{\min}_{\substack{\mathbf{P}, \mathbf{Q}: \\ mass(P) = mass(Q)}}
        &\quad \sum_{i,j,k,l} (\mathbf{C^X}_{i,k} - \mathbf{C^Y}_{j,l})^2 \mathbf{P}_{i,j} \mathbf{Q}_{k,l}
        + \frac{\alpha}{2} \sum_{i,j} (\mathbf{P}_{i,j} + \mathbf{Q}_{i,j}) \mathbf{M}_{i, j} \\
        &+ \rho_1 \mathbf{Div}(\mathbf{P}_{\# 1} \mathbf{Q}_{\# 1}^T | \mathbf{w_X} \mathbf{w_X}^T)
        + \rho_2 \mathbf{Div}(\mathbf{P}_{\# 2} \mathbf{Q}_{\# 2}^T | \mathbf{w_Y} \mathbf{w_Y}^T) \\
        &+ \varepsilon \mathbf{Div}(\mathbf{P} \otimes \mathbf{Q} | (\mathbf{w_X} \mathbf{w_Y}^T) \otimes (\mathbf{w_X} \mathbf{w_Y}^T))

    Where:

    - :math:`\mathbf{C^X}`: Source similarity matrix
    - :math:`\mathbf{C^Y}`: Target similarity matrix
    - :math:`\mathbf{M}`: Sample matrix corresponding to the Wasserstein term
    - :math:`\mathbf{w_X}`: Distribution of the samples in the source space
    - :math:`\mathbf{w_Y}`: Distribution of the samples in the target space
    - :math:`\mathbf{Div}`: Either Kullback-Leibler divergence or half-squared L2 norm.

    .. note:: This function allows `epsilon` to be zero. In that case, unbalanced_method must be either "mm" or "lbfgsb".
            Also the computation of gradients is only supported for KL divergence, but not for half squared-L2 norm. In case of half squared-L2 norm, the calculation of KL divergence will be used.

    Parameters
    ----------
    Cx : (n_sample_x, n_feature_x) array-like, float
        Source similarity matrix.
    Cy : (n_sample_y, n_feature_y) array-like, float
        Target similarity matrix.
    wx : (n_sample_x, ) array-like, float, optional (default = None)
        Histogram assigned on rows (samples) of matrix Cx.
        Uniform distribution by default.
    wy : (n_sample_y, ) array-like, float, optional (default = None)
        Histogram assigned on rows (samples) of matrix Cy.
        Uniform distribution by default.
    reg_marginals: float or indexable object of length 1 or 2
        Marginal relaxation terms for sample and feature couplings.
        If `reg_marginals` is a scalar or an indexable object of length 1,
        then the same value is applied to both marginal relaxations.
    epsilon : scalar, float or int, optional (default = 0)
        Regularization parameters for entropic approximation of sample and feature couplings.
        Allow the case where `epsilon` contains 0. In that case, the MM solver is used by default
        instead of Sinkhorn solver. If `epsilon` is scalar, then the same value is applied to
        both regularization of sample and feature couplings.
    divergence : string, optional (default = "kl")

        - If `divergence` = "kl", then Div is the Kullback-Leibler divergence.

        - If `divergence` = "l2", then Div is the half squared Euclidean norm.
    unbalanced_solver : string, optional (default = "sinkhorn")
        Solver for the unbalanced OT subroutine.

        - If `divergence` = "kl", then `unbalanced_solver` can be: "sinkhorn", "sinkhorn_log", "mm", "lbfgsb"

        - If `divergence` = "l2", then `unbalanced_solver` can be "mm", "lbfgsb"
    alpha : scalar, float or int, optional (default = 0)
        Coeffficient parameter of linear terms with respect to the sample and feature couplings.
        If alpha is scalar, then the same alpha is applied to both linear terms.
    M : (n_sample_x, n_sample_y), float, optional (default = None)
        Sample matrix associated to the Wasserstein linear term on sample coupling.
    init_pi :(n_sample_x, n_sample_y) array-like, optional (default = None)
        Initialization of sample coupling. By default = :math:`w_X w_Y^T`.
    init_duals : tuple of vectors ((n_sample_x, ), (n_sample_y, )), optional (default = None).
        Initialization of sample and feature dual vectors
        if using Sinkhorn algorithm. Zero vectors by default.
    max_iter : int, optional (default = 100)
        Number of Block Coordinate Descent (BCD) iterations.
    tol : float, optional (default = 1e-7)
        Tolerance of BCD scheme. If the L1-norm between the current and previous
        sample couplings is under this threshold, then stop BCD scheme.
    max_iter_ot : int, optional (default = 100)
        Number of iterations to solve each of the
        two unbalanced optimal transport problems in each BCD iteration.
    tol_ot : float, optional (default = 1e-7)
        Tolerance of unbalanced solver for each of the
        two unbalanced optimal transport problems in each BCD iteration.
    log : bool, optional (default = False)
        If True then the cost and four dual vectors, including
        two from sample and two from feature couplings, are recorded.
    verbose : bool, optional (default = False)
        If True then print the COOT cost at every multiplier of `eval_bcd`-th iteration.

    Returns
    -------
    fugw : float
        Total FUGW cost
    log : dictionary, optional
        Returned if `log` is True. The keys are:

            error : array-like, float
                list of L1 norms between the current and previous sample couplings.
            duals : (n_sample_x, n_sample_y)-tuple, float
                Pair of dual vectors when solving OT problem w.r.t the sample coupling.
            linear : float
                Linear part of FUGW cost.
            fugw_cost : float
                Total FUGW cost.
            backend
                The proper backend for all input arrays

    References
    ----------
    .. [70] Thual, A., Tran, H., Zemskova, T., Courty, N., Flamary, R., Dehaene, S., & Thirion, B.
            Aligning individual brains with Fused Unbalanced Gromov-Wasserstein.
            Advances in Neural Information Systems, 35 (2022).

    .. [72] Thibault Séjourné, François-Xavier Vialard, & Gabriel Peyré.
            The Unbalanced Gromov Wasserstein Distance: Conic Formulation and Relaxation.
            Neural Information Processing Systems, 34 (2021).
    """

    if divergence != "kl":
        warnings.warn(
            "The computation of gradients is only supported for KL divergence, \
                      but not for {} divergence. The gradient of the KL case will be used.".format(
                divergence
            )
        )

    pi_samp, pi_feat, log_fugw = fused_unbalanced_gromov_wasserstein(
        Cx=Cx,
        Cy=Cy,
        wx=wx,
        wy=wy,
        reg_marginals=reg_marginals,
        epsilon=epsilon,
        divergence=divergence,
        unbalanced_solver=unbalanced_solver,
        alpha=alpha,
        M=M,
        init_duals=init_duals,
        init_pi=init_pi,
        max_iter=max_iter,
        tol=tol,
        max_iter_ot=max_iter_ot,
        tol_ot=tol_ot,
        log=True,
        verbose=verbose,
        **kwargs_solve,
    )

    nx = log_fugw["backend"]
    sx, sy = Cx.shape[0], Cy.shape[0]

    # measures on rows and columns
    if wx is None:
        wx = nx.ones(sx, type_as=Cx) / sx
    if wy is None:
        wy = nx.ones(sy, type_as=Cy) / sy

    # calculate marginals
    pi1_samp, pi2_samp = nx.sum(pi_samp, 1), nx.sum(pi_samp, 0)
    pi1_feat, pi2_feat = nx.sum(pi_feat, 1), nx.sum(pi_feat, 0)
    m_samp, m_feat = nx.sum(pi1_samp), nx.sum(pi1_feat)
    m_wx, m_wy = nx.sum(wx), nx.sum(wy)

    # calculate subgradients
    gradX = 2 * Cx * (pi1_samp[:, None] * pi1_feat[None, :]) - 2 * nx.dot(
        nx.dot(pi_samp, Cy), pi_feat.T
    )  # shape (nx_samp, nx_feat)
    gradY = 2 * Cy * (pi2_samp[:, None] * pi2_feat[None, :]) - 2 * nx.dot(
        nx.dot(pi_samp.T, Cx), pi_feat
    )  # shape (ny_samp, ny_feat)

    gradM = alpha / 2 * (pi_samp + pi_feat)

    rho_x, rho_y = get_parameter_pair(reg_marginals)
    grad_wx = (
        2 * m_wx * (rho_x + epsilon * m_wy**2)
        - (rho_x + epsilon) * (m_feat * pi1_samp + m_samp * pi1_feat) / wx
    )
    grad_wy = (
        2 * m_wy * (rho_y + epsilon * m_wx**2)
        - (rho_y + epsilon) * (m_feat * pi2_samp + m_samp * pi2_feat) / wy
    )

    # set gradients
    fugw = log_fugw["fugw_cost"]
    fugw = nx.set_gradients(
        fugw, (Cx, Cy, M, wx, wy), (gradX, gradY, gradM, grad_wx, grad_wy)
    )

    if log:
        return fugw, log_fugw

    else:
        return fugw