GroupMultiNeSS 0.0.4__tar.gz → 0.0.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -78,7 +78,7 @@ def ASE(A: np.array, d: int, check_if_symmetric: bool = True,
78
78
  if indef_inner_prod:
79
79
  sort_idx = np.argsort(eigvals)[::-1]
80
80
  eigvals = eigvals[sort_idx]
81
- eigvecs = eigvecs[:, :sort_idx]
81
+ eigvecs = eigvecs[:, sort_idx]
82
82
  signature = np.where(eigvals > 0, 1., -1)
83
83
  ase = eigvecs @ np.diag(np.sqrt(np.abs(eigvals)))
84
84
  return (ase, signature) if return_signature else ase
@@ -1,11 +1,12 @@
1
+ from abc import ABC, abstractmethod
2
+
1
3
  import numpy as np
2
4
  from numpy.linalg import norm
3
- from typing import List, Union
5
+ from typing import List, Optional, Union
4
6
  from warnings import warn
5
7
  from typing import Iterable
6
8
  from multiprocessing import shared_memory
7
9
  import statsmodels.api as sm
8
- from more_itertools import zip_equal
9
10
 
10
11
  from .utils import sigmoid, leading_left_eigenvectors
11
12
 
@@ -18,8 +19,8 @@ class SharedMemoryMatrixFitter:
18
19
  which can be used for parallel computations without duplicating data.
19
20
  """
20
21
 
21
- def _init_param_matrices(self, vals: Union[List[np.ndarray], np.ndarray] = None,
22
- shape: Iterable[int] = None) -> None:
22
+ def _init_param_matrices(self, vals: Optional[Union[List[np.ndarray], np.ndarray]] = None,
23
+ shape: Optional[Iterable[int]] = None) -> None:
23
24
  """
24
25
  Initialize shared memory for parameter matrices.
25
26
 
@@ -36,7 +37,7 @@ class SharedMemoryMatrixFitter:
36
37
  - Allocates shared memory of type float64 for storing matrices.
37
38
  """
38
39
  if shape is None:
39
- assert vals is not None, "One of vals or shape arguments should berandom_seed provided!"
40
+ assert vals is not None, "One of vals or shape arguments should be provided!"
40
41
  vals = np.array(vals)
41
42
  shape = vals.shape
42
43
  elif vals is not None:
@@ -62,7 +63,7 @@ class SharedMemoryMatrixFitter:
62
63
  param_matrices = self.get_all_fitted_matrices()
63
64
  param_matrices[idx] = val
64
65
 
65
- def _set_matrices(self, vals, indices: Union[List[int], np.ndarray] = None):
66
+ def _set_matrices(self, vals, indices: Optional[Union[List[int], np.ndarray]] = None):
66
67
  """
67
68
  Set multiple matrices in shared memory.
68
69
 
@@ -76,7 +77,7 @@ class SharedMemoryMatrixFitter:
76
77
  if indices is None:
77
78
  indices = list(range(len(self.get_all_fitted_matrices())))
78
79
  assert len(vals) == len(indices)
79
- for idx, val in zip_equal(indices, vals):
80
+ for idx, val in zip(indices, vals, strict=True):
80
81
  self._set_matrix(val, idx)
81
82
 
82
83
  def get_all_fitted_matrices(self):
@@ -91,7 +92,8 @@ class SharedMemoryMatrixFitter:
91
92
  return np.ndarray(self.param_matrices.shape, dtype=np.float64, buffer=self._param_matrices_shm.buf)
92
93
 
93
94
 
94
- class BaseMultiplexNetworksModel:
95
+
96
+ class BaseMultiplexNetworksModel(ABC):
95
97
  """
96
98
  Base class for multiplex network models.
97
99
 
@@ -118,7 +120,7 @@ class BaseMultiplexNetworksModel:
118
120
  else:
119
121
  raise NotImplementedError("Edge distribution should be either normal or bernoulli!")
120
122
 
121
- def _validate_input(self, As: List[np.array]) -> np.ndarray:
123
+ def _validate_input(self, As: List[np.ndarray]) -> np.ndarray:
122
124
  """
123
125
  Validate input adjacency matrices.
124
126
 
@@ -147,6 +149,7 @@ class BaseMultiplexNetworksModel:
147
149
  self._param_participance_masks = self._get_param_participance_masks()
148
150
  return np.stack(As)
149
151
 
152
+ @abstractmethod
150
153
  def _get_param_participance_masks(self) -> np.ndarray:
151
154
  """
152
155
  Return masks indicating which parameters participate in each layer.
@@ -166,7 +169,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
166
169
  Base class for refitting latent matrices in multiplex network models.
167
170
  """
168
171
 
169
- def __init__(self, edge_distrib="normal", max_rank: int = None, loops_allowed: bool = True,
172
+ def __init__(self, edge_distrib="normal", max_rank: Optional[int] = None, loops_allowed: bool = True,
170
173
  refit_threshold: float = 1e-8):
171
174
  """
172
175
  Initialize the BaseRefitting object.
@@ -250,7 +253,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
250
253
  refit_matrix_participance_masks = self._param_participance_masks[refit_matrix_indices][:, obs_mask]
251
254
 
252
255
  design_mat = []
253
- for param_design, participance_mask in zip_equal(param_designs, refit_matrix_participance_masks):
256
+ for param_design, participance_mask in zip(param_designs, refit_matrix_participance_masks, strict=True):
254
257
  design_mat.append(np.vstack([param_design if participate else np.zeros_like(param_design)
255
258
  for participate in participance_mask]))
256
259
 
@@ -306,7 +309,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
306
309
  refit_matrix_indices)) # don't refit rank zero matrices after hard-threshold
307
310
  return np.array(refit_matrix_indices, dtype=int)
308
311
 
309
- def refit(self, As: Union[List[np.array], np.array], refit_matrix_indices=None):
312
+ def refit(self, As: Union[List[np.ndarray], np.ndarray], refit_matrix_indices=None):
310
313
  """
311
314
  Refit parameter matrices using GLM based on current adjacency matrices.
312
315
 
@@ -1,5 +1,5 @@
1
1
  import numpy as np
2
- from typing import Union, List
2
+ from typing import Optional, Union, List
3
3
  from warnings import warn
4
4
 
5
5
  from .utils import sigmoid, generate_matrices_given_pairwise_max_cosines
@@ -47,7 +47,7 @@ class LatentPositionGenerator:
47
47
  d_individs: Union[List, int] = 2,
48
48
  s_vu: float = 0.,
49
49
  s_uu: float = 0.,
50
- comps_max_cosine_mat: np.array = None,
50
+ comps_max_cosine_mat: Optional[np.ndarray] = None,
51
51
  min_V_max_U_eigval_ratio=None):
52
52
 
53
53
  self.n_nodes = n_nodes
@@ -1,14 +1,16 @@
1
1
  import numpy as np
2
- from typing import List, Dict, Union, Tuple
2
+ import matplotlib.pyplot as plt
3
+ from typing import List, Dict, Optional, Union, Tuple
3
4
  from collections import Counter
4
5
  from functools import partial
5
6
  from joblib import Parallel, delayed
6
7
  from warnings import warn
8
+ from multiprocessing import Manager
7
9
 
8
10
  from .multiness import BaseMultiNeSS, BaseMultiNeSSRefined, BaseMultiNeSSRefinedCV, BaseOracleMultiNeSS
9
11
  from .base import BaseRefitting
10
12
  from .utils import if_scalar_or_given_length_array, fill_diagonals, \
11
- soft_thresholding_operator
13
+ soft_thresholding_operator, mean_frobenius_error
12
14
 
13
15
 
14
16
  class BaseGroupMultiNeSS(BaseMultiNeSS):
@@ -107,7 +109,7 @@ class BaseGroupMultiNeSS(BaseMultiNeSS):
107
109
  """
108
110
  return ["Shared component", "Group components", "Individual components"]
109
111
 
110
- def _validate_input(self, As: List[np.array]):
112
+ def _validate_input(self, As: List[np.ndarray]):
111
113
  """
112
114
  Validate input data and group assignments.
113
115
 
@@ -160,10 +162,10 @@ class BaseGroupMultiNeSSRefined(BaseGroupMultiNeSS, BaseMultiNeSSRefined):
160
162
 
161
163
  def __init__(self, group_indices: List[int],
162
164
  edge_distrib: str = "normal",
163
- max_rank: int = None, init_rank: int = None,
164
- sigmas: Union[float, List, np.ndarray] = None,
165
+ max_rank: Optional[int] = None, init_rank: Optional[int] = None,
166
+ sigmas: Optional[Union[float, List, np.ndarray]] = None,
165
167
  loops_allowed: bool = True,
166
- n_jobs: int = None):
168
+ n_jobs: Optional[int] = None):
167
169
  """
168
170
  Initialize BaseGroupMultiNeSSRefined.
169
171
  """
@@ -230,25 +232,8 @@ class BaseGroupMultiNeSSRefined(BaseGroupMultiNeSS, BaseMultiNeSSRefined):
230
232
  for group in self.unique_groups_},
231
233
  **{(1, 0): list(range(1 + self.n_groups_))}}
232
234
 
233
- def _update_latent_history(self, key: Tuple[int, int]) -> None:
234
- """
235
- Update stored latent history for a given key.
236
-
237
- Parameters
238
- ----------
239
- key : tuple
240
- Optimization stage and group key.
241
- """
242
- stage, group = key
243
- history_key = self._key_2_history_key[key]
244
- if stage == 0:
245
- self.latent_history_[history_key].append(
246
- (self.get_group_latent_spaces()[group].copy(),
247
- self.get_individual_latent_spaces()[self.group_indices == group].copy()))
248
- else:
249
- self.latent_history_[history_key].append((self.get_shared_latent_space(), self.get_group_latent_spaces()))
250
-
251
- def _fit(self, As, lr: Union[float, Tuple[float, float]] = 1., **optim_kwargs):
235
+ def _fit(self, As, lr: Union[float, Tuple[float, float]] = 1., n_epochs: int = 1, reinit: bool = True,
236
+ **optim_kwargs):
252
237
  """
253
238
  Fit the model using two-stage optimization for groups and shared components.
254
239
 
@@ -258,16 +243,160 @@ class BaseGroupMultiNeSSRefined(BaseGroupMultiNeSS, BaseMultiNeSSRefined):
258
243
  Input adjacency matrices.
259
244
  lr : float or tuple of float, default=1.
260
245
  Learning rates for stage 1 and 2.
261
- """
262
- self._pre_fit()
263
- lr = if_scalar_or_given_length_array(lr, length=2, name="lr")
264
- Parallel(n_jobs=self.n_jobs)(
265
- [delayed(self._optimize_params)(key=(0, group),
266
- As=As, lr=lr[0],
267
- **optim_kwargs)
268
- for group in self.unique_groups_])
269
- self._optimize_params(key=(1, 0), As=As, lr=lr[1], **optim_kwargs)
246
+ n_epochs : int, default=1
247
+ Number of epochs to run the optimization.
248
+ reinit : bool, default=True
249
+ Whether to reinitialize the parameters before each epoch.
250
+ """
251
+ self._pre_fit(n_epochs=n_epochs)
252
+ lrs = if_scalar_or_given_length_array(lr, length=2, name="lr")
253
+ for epoch in range(n_epochs):
254
+ # self._set_matrix(val=np.zeros((self.n_nodes_, self.n_nodes_)), idx=0)
255
+ Parallel(n_jobs=self.n_jobs)(
256
+ [delayed(self._optimize_params)(key=(0, group),
257
+ As=As, lr=lrs[0],
258
+ epoch=epoch,
259
+ reinit=(reinit and epoch == 0),
260
+ **optim_kwargs)
261
+ for group in self.unique_groups_])
262
+ # self._set_matrices(vals=np.zeros((self.n_groups_, self.n_nodes_, self.n_nodes_)), indices=np.arange(1, 1 + self.n_groups_))
263
+ self._optimize_params(key=(1, 0), As=As, lr=lrs[1],
264
+ epoch=epoch,
265
+ reinit=(reinit and epoch == 0),
266
+ **optim_kwargs)
267
+
268
+ def get_error_history(self, *true_params, relative_errors=True):
269
+ """
270
+ Compute convergence error curves for S, Q_k, R_kl, concatenated across epochs.
271
+
272
+ Parameters
273
+ ----------
274
+ true_params : tuple (S_true, Q_true, R_true)
275
+ S_true : np.ndarray, shape (n_nodes, n_nodes)
276
+ Q_true : array-like, shape (n_groups, n_nodes, n_nodes) -- Q_true[k]
277
+ R_true : array-like, shape (n_layers, n_nodes, n_nodes) -- R_true[l]
278
+ relative_errors : bool, default=True
279
+ Whether to compute relative Frobenius errors.
270
280
 
281
+ Returns
282
+ -------
283
+ dict
284
+ Maps each key (stage, group) to a dict with:
285
+ - "series": dict of series_name -> 1d np.ndarray of errors, one value
286
+ per iteration, concatenated across all epochs in fit order.
287
+ Stage 0, group k: "$S+Q_k$" and "$R_{k\\ell}$".
288
+ Stage 1: "$S$", "$Q_k$" for every group k, and "$\\bar{Q}$" (average
289
+ error across groups).
290
+ - "epoch_ends": cumulative iteration counts at which each epoch stopped.
291
+ """
292
+ assert self.latent_history_, "Set save_latent_history == True during fit to access latent_history!"
293
+ S_true, Q_true, R_true = true_params
294
+ Q_true, R_true = np.asarray(Q_true), np.asarray(R_true)
295
+
296
+ err_hist = {}
297
+ for key, history_key in self._key_2_history_key.items():
298
+ stage, group = key
299
+ series, epoch_ends, cum_iter = {}, [], 0
300
+
301
+ for epoch_history in self.latent_history_:
302
+ snapshots = epoch_history[history_key] # list over iterations of [S_hat, Q_hat, R_hat]
303
+ for S_hat, Q_hat, R_hat in snapshots:
304
+ if stage == 0:
305
+ layers_in_group = np.where(np.asarray(self.group_indices) == group)[0]
306
+ err_SQ = mean_frobenius_error(S_true + Q_true[group], S_hat + Q_hat[group],
307
+ relative=relative_errors, include_offdiag=self.loops_allowed)
308
+ err_R = np.mean([mean_frobenius_error(R_true[l], R_hat[l], relative=relative_errors,
309
+ include_offdiag=self.loops_allowed)
310
+ for l in layers_in_group])
311
+ series.setdefault(rf"$S+Q_{{{group}}}$", []).append(err_SQ)
312
+ series.setdefault(rf"$R_{{{group}\ell}}$", []).append(err_R)
313
+ else:
314
+ err_S = mean_frobenius_error(S_true, S_hat, relative=relative_errors,
315
+ include_offdiag=self.loops_allowed)
316
+ series.setdefault("$S$", []).append(err_S)
317
+ series.setdefault(r"$Q$", []).append(
318
+ mean_frobenius_error(Q_true, Q_hat, relative=relative_errors, include_offdiag=self.loops_allowed)
319
+ )
320
+ cum_iter += len(snapshots)
321
+ epoch_ends.append(cum_iter)
322
+
323
+ err_hist[key] = {"series": {name: np.array(vals) for name, vals in series.items()},
324
+ "epoch_ends": epoch_ends}
325
+ return err_hist
326
+
327
+
328
+ def plot_error_history(self, *true_params, relative_errors=True, n_cols: int = 4,
329
+ fontsize=14, figsize=(12, 20), print_final_errors=True):
330
+ """
331
+ Plot convergence of S+Q_k / R_kl (stage 1, per group) and S / Q_k / mean Q
332
+ (stage 2), with all epochs drawn on the same continuous x-axis. Epoch
333
+ boundaries are marked with bracket-shaped underlines labeled "Epoch {n}"
334
+ below the plot, rather than a numeric tick axis.
335
+
336
+ Parameters
337
+ ----------
338
+ true_params : tuple (S_true, Q_true, R_true)
339
+ Ground-truth components, see `get_error_history`.
340
+ relative_errors : bool, default=True
341
+ Whether to plot relative Frobenius errors.
342
+ n_cols : int, default=4
343
+ Number of subplot columns.
344
+ fontsize : int, default=14
345
+ Font size for labels/titles.
346
+ figsize : tuple, default=(12, 20)
347
+ Figure size.
348
+ print_final_errors : bool, default=True
349
+ Whether to print the final-iteration errors for each subplot.
350
+ """
351
+ from matplotlib.transforms import blended_transform_factory
352
+
353
+ err_hist = self.get_error_history(*true_params, relative_errors=relative_errors)
354
+ keys = sorted(err_hist.keys()) # (0, 0) ... (0, K-1), (1, 0)
355
+
356
+ n_cols = min(n_cols, len(keys))
357
+ n_rows = int(np.ceil(len(keys) / n_cols))
358
+ fig, axs = plt.subplots(ncols=n_cols, nrows=n_rows, figsize=figsize)
359
+ axs = np.array(axs).flatten()
360
+
361
+ bracket_y = -0.10
362
+ tick_height = 0.025
363
+ label_y = bracket_y - 0.02
364
+
365
+ for ax, key in zip(axs, keys):
366
+ hist = err_hist[key]
367
+ for name, errs in hist["series"].items():
368
+ ax.plot(np.arange(1, len(errs) + 1), errs, label=name)
369
+
370
+ epoch_ends = hist["epoch_ends"]
371
+ epoch_starts = [0] + list(epoch_ends[:-1])
372
+ trans = blended_transform_factory(ax.transData, ax.transAxes)
373
+
374
+ for epoch_num, (start, end) in enumerate(zip(epoch_starts, epoch_ends), start=1):
375
+ ax.plot([start, end], [bracket_y, bracket_y], transform=trans,
376
+ color='black', linewidth=1.5, clip_on=False)
377
+ ax.plot([start, start], [bracket_y, bracket_y + tick_height], transform=trans,
378
+ color='black', linewidth=1.5, clip_on=False)
379
+ ax.plot([end, end], [bracket_y, bracket_y + tick_height], transform=trans,
380
+ color='black', linewidth=1.5, clip_on=False)
381
+ ax.text((start + end) / 2, label_y, f"Epoch {epoch_num}", transform=trans,
382
+ ha='center', va='top', fontsize=max(fontsize - 4, 8), clip_on=False)
383
+
384
+ ax.set_ylabel("Error", fontsize=fontsize)
385
+ ax.set_title(self._key_2_history_key[key], fontsize=fontsize)
386
+ ax.tick_params(axis='both', which='major', labelsize=fontsize)
387
+ ax.legend(fontsize=fontsize)
388
+
389
+ for idx in range(len(keys), n_cols * n_rows):
390
+ fig.delaxes(axs[idx])
391
+ plt.tight_layout()
392
+
393
+ if print_final_errors:
394
+ final_errs = {self._key_2_history_key[key]: {name: round(float(errs[-1]), 3)
395
+ for name, errs in hist["series"].items()}
396
+ for key, hist in err_hist.items()}
397
+ print("Final errors:", final_errs)
398
+ plt.show()
399
+
271
400
 
272
401
  class GroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseRefitting):
273
402
  """
@@ -296,15 +425,15 @@ class GroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseRefitting):
296
425
  """
297
426
 
298
427
  def __init__(self, group_indices: List[int],
299
- lmbda1: Union[float, np.ndarray, list] = None,
300
- lmbda2: float = None,
301
- alpha1: Union[float, np.ndarray, list] = None,
302
- alpha2: Union[float, np.ndarray, list] = None,
428
+ lmbda1: Optional[Union[float, np.ndarray, list]] = None,
429
+ lmbda2: Optional[float] = None,
430
+ alpha1: Optional[Union[float, np.ndarray, list]] = None,
431
+ alpha2: Optional[Union[float, np.ndarray, list]] = None,
303
432
  edge_distrib: str = "normal",
304
- max_rank: int = None, init_rank: int = None,
305
- sigmas: Union[float, List, np.ndarray] = None,
433
+ max_rank: Optional[int] = None, init_rank: Optional[int] = None,
434
+ sigmas: Optional[Union[float, List[float], np.ndarray]] = None,
306
435
  loops_allowed: bool = True,
307
- n_jobs: int = None,
436
+ n_jobs: Optional[int] = None,
308
437
  refit_threshold: float = 1e-8):
309
438
  """
310
439
  Initialize GroupMultiNeSS model.
@@ -392,10 +521,12 @@ class GroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseRefitting):
392
521
  for group in self.unique_groups_},
393
522
  **{(1, 0): {"lmbda2": lmbda2, "alpha2": alpha2}}}
394
523
 
395
- def fit(self, As: List[np.array],
524
+ def fit(self, As: List[np.ndarray],
396
525
  lr: Union[float, Tuple[float, float]] = 1e-1,
397
526
  max_iter: int = 100, tol=1e-5, patience=10,
398
- refit=True, verbose: bool = False, verbose_interval=1,
527
+ refit=True, reinit=True,
528
+ n_epochs: int = 1,
529
+ verbose: bool = False, verbose_interval=1,
399
530
  save_latent_history=False, save_nll_history=True):
400
531
  """
401
532
  Fit the GroupMultiNeSS model.
@@ -414,6 +545,10 @@ class GroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseRefitting):
414
545
  Early stopping patience.
415
546
  refit : bool, default=True
416
547
  Whether to refit components.
548
+ n_epochs : int, default=1
549
+ Number of epochs to run the optimization.
550
+ reinit : bool, default=True
551
+ Whether to reinitialize the parameters
417
552
  verbose : bool, default=False
418
553
  Verbosity flag.
419
554
  verbose_interval : int, default=1
@@ -429,31 +564,34 @@ class GroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseRefitting):
429
564
  Fitted model instance.
430
565
  """
431
566
  As = self._validate_input(As=As)
432
- self._fit(As, lr=lr,
567
+ self._fit(As, lr=lr, n_epochs=n_epochs,
433
568
  max_iter=max_iter, tol=tol, patience=patience,
434
- refit=refit,
569
+ reinit=reinit, refit=False,
435
570
  verbose=verbose, verbose_interval=verbose_interval,
436
571
  save_latent_history=save_latent_history, save_nll_history=save_nll_history)
572
+
573
+ if refit:
574
+ self.refit(As, refit_matrix_indices=np.arange(self.n_fitted_matrices))
437
575
  return self
438
576
 
439
577
 
440
578
  class GroupMultiNeSSCV(GroupMultiNeSS, BaseMultiNeSSRefinedCV):
441
579
  def __init__(self, group_indices: List[int],
442
- param_grid: Dict[str, List] = None,
580
+ param_grid: Optional[Dict[str, List[float]]] = None,
443
581
  edge_distrib: str = "normal",
444
- lmbda1: Union[float, np.ndarray, list] = None,
445
- lmbda2: float = None,
446
- alpha1: Union[float, np.ndarray, list] = None,
447
- alpha2: Union[float, np.ndarray, list] = None,
582
+ lmbda1: Optional[Union[float, np.ndarray, list]] = None,
583
+ lmbda2: Optional[float] = None,
584
+ alpha1: Optional[Union[float, np.ndarray, list]] = None,
585
+ alpha2: Optional[Union[float, np.ndarray, list]] = None,
448
586
  loops_allowed: bool = True,
449
- cv_folds=3, test_prop=0.1,
450
- max_rank: int = None, init_rank: int = None,
451
- sigmas: Union[float, List, np.ndarray] = None,
452
- n_jobs: int = None,
587
+ cv_folds: int = 3, test_prop: float = 0.1,
588
+ max_rank: Optional[int] = None, init_rank: Optional[int] = None,
589
+ sigmas: Optional[Union[float, List[float], np.ndarray]] = None,
590
+ n_jobs: Optional[int] = None,
453
591
  refit_threshold=1e-8,
454
592
  fix_layer_split: bool = False,
455
593
  use_1se_rule: bool = False,
456
- random_seed: int = None):
594
+ random_seed: Optional[int] = None):
457
595
 
458
596
  BaseMultiNeSSRefinedCV.__init__(self, param_grid=param_grid, cv_folds=cv_folds, test_prop=test_prop,
459
597
  loops_allowed=loops_allowed,
@@ -486,9 +624,9 @@ class OracleGroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseOracleMultiNeSS):
486
624
  def __init__(self, group_indices: List[int],
487
625
  d_shared: int, d_groups: List[int], d_individs: List[int],
488
626
  edge_distrib: str = "normal",
489
- sigmas: Union[float, List, np.ndarray] = None,
627
+ sigmas: Optional[Union[float, List[float], np.ndarray]] = None,
490
628
  loops_allowed: bool = True,
491
- n_jobs: int = None):
629
+ n_jobs: Optional[int] = None):
492
630
 
493
631
  BaseGroupMultiNeSSRefined.__init__(self, group_indices=group_indices,
494
632
  edge_distrib=edge_distrib, sigmas=sigmas,
@@ -1,12 +1,13 @@
1
+ from abc import abstractmethod
2
+
1
3
  import numpy as np
2
- from typing import List, Dict, Callable, Union, Tuple
4
+ from typing import List, Dict, Callable, Optional, Union, Tuple
3
5
  import matplotlib.pyplot as plt
4
6
  from functools import partial
5
7
  import seaborn as sns
6
8
  from multiprocessing import Manager
7
- from copy import deepcopy
9
+ from copy import copy
8
10
  from itertools import product
9
- from more_itertools import zip_equal
10
11
 
11
12
  from .utils import soft_thresholding_operator, hard_thresholding_operator, make_error_report, \
12
13
  mean_frobenius_error, EarlyStopper, if_scalar_or_given_length_array, fill_diagonals, \
@@ -40,7 +41,7 @@ class BaseMultiNeSS(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
40
41
  """
41
42
  return [self.get_shared_latent_space(), self.get_individual_latent_spaces()]
42
43
 
43
- def get_all_matrix_latent_positions(self, ds: List[int] = None, check_if_symmetric=True):
44
+ def get_all_matrix_latent_positions(self, ds: Optional[List[int]] = None, check_if_symmetric=True):
44
45
  """
45
46
  Compute latent positions for all fitted matrices using adjacency spectral embedding (ASE).
46
47
 
@@ -60,7 +61,7 @@ class BaseMultiNeSS(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
60
61
  if ds is None:
61
62
  ds = [np.linalg.matrix_rank(matrix) for matrix in matrices]
62
63
  return [ASE(matrix, d, check_if_symmetric=check_if_symmetric) if d != 0 else np.empty((self.n_nodes_, 0))
63
- for matrix, d in zip_equal(matrices, ds)]
64
+ for matrix, d in zip(matrices, ds, strict=True)]
64
65
 
65
66
  def get_node_latent_positions_across_layers(self):
66
67
  """
@@ -168,8 +169,8 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
168
169
  """
169
170
 
170
171
  def __init__(self, edge_distrib: str = "normal", loops_allowed: bool = True,
171
- max_rank: int = None, init_rank: int = None,
172
- sigmas: Union[float, List, np.ndarray] = None):
172
+ max_rank: Optional[int] = None, init_rank: Optional[int] = None,
173
+ sigmas: Optional[Union[float, List, np.ndarray]] = None):
173
174
  """
174
175
  Initialize a refined MultiNeSS model with specified configuration.
175
176
 
@@ -203,14 +204,16 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
203
204
  Key identifying optimization stage.
204
205
  """
205
206
  param_indices = self._key_2_param_indices[key]
206
- param_inits = []
207
- for idx in param_indices:
208
- mask = self._param_participance_masks[idx]
209
- param_init = hard_thresholding_operator(np.nansum(As[mask], axis=0) / mask.sum(), max_rank=self.init_rank)
210
- param_inits.append(param_init)
211
- self._set_matrices(param_inits, indices=param_indices)
212
-
213
- def _update_history(self, nll: float, key: Tuple[int, int],
207
+ for idx in sorted(param_indices):
208
+ layers_mask = self._param_participance_masks[idx]
209
+ offset_params_mask = self._param_participance_masks.copy()
210
+ offset_params_mask[idx] = False
211
+ As_resids = As - np.einsum('pm,pij->mij', offset_params_mask, self.get_all_fitted_matrices())
212
+ param_init = hard_thresholding_operator(np.nansum(As_resids[layers_mask], axis=0) / layers_mask.sum(),
213
+ max_rank=self.init_rank)
214
+ self._set_matrix(param_init, idx)
215
+
216
+ def _update_history(self, nll: float, key: Tuple[int, int], epoch: int = 0,
214
217
  save_nll_history: bool = True,
215
218
  save_latent_history: bool = False) -> None:
216
219
  """
@@ -226,25 +229,15 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
226
229
  Whether to save NLL history.
227
230
  save_latent_history : bool, default=False
228
231
  Whether to save latent variable history.
232
+ epoch : int, default=0
233
+ Current epoch number.
229
234
  """
230
235
  if save_nll_history:
231
- self._update_nll_history(nll=nll, key=key)
236
+ self._update_nll_history(nll=nll, key=key, epoch=epoch)
232
237
  if save_latent_history:
233
- self._update_latent_history(key)
234
-
235
- def _reset_history(self, key: Tuple[int, int]):
236
- """
237
- Reset optimization history for a given key.
238
-
239
- Parameters
240
- ----------
241
- key : tuple of int
242
- Identifier for optimization stage.
243
- """
244
- hist_key = self._key_2_history_key[key]
245
- self.nll_history_[hist_key][:] = []
238
+ self._update_latent_history(key, epoch=epoch)
246
239
 
247
- def _update_nll_history(self, nll: float, key: Tuple[int, int]):
240
+ def _update_nll_history(self, nll: float, key: Tuple[int, int], epoch: int = 0):
248
241
  """
249
242
  Append new negative log-likelihood value to history.
250
243
 
@@ -254,11 +247,13 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
254
247
  Negative log-likelihood value.
255
248
  key : tuple of int
256
249
  Identifier for optimization stage.
250
+ epoch : int, default=0
251
+ Current epoch number.
257
252
  """
258
253
  history_key = self._key_2_history_key[key]
259
- self.nll_history_[history_key].append(nll)
254
+ self.nll_history_[epoch][history_key].append(nll)
260
255
 
261
- def _update_latent_history(self, key: Tuple[int, int]):
256
+ def _update_latent_history(self, key: Tuple[int, int], epoch: int = 0):
262
257
  """
263
258
  Append current latent space matrices to history.
264
259
 
@@ -266,9 +261,11 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
266
261
  ----------
267
262
  key : tuple of int
268
263
  Identifier for optimization stage.
264
+ epoch : int, default=0
265
+ Current epoch number.
269
266
  """
270
267
  history_key = self._key_2_history_key[key]
271
- self.latent_history_[history_key].append(deepcopy(self.get_all_fitted_matrices_by_type()))
268
+ self.latent_history_[epoch][history_key].append(copy(self.get_all_fitted_matrices_by_type()))
272
269
 
273
270
  def _make_key_2_history_key_dict(self) -> None:
274
271
  """Create mapping from optimization keys to history keys."""
@@ -304,7 +301,7 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
304
301
  param_val = param_val if np.isscalar(old_val) else param_val * np.ones_like(old_val)
305
302
  self._key_2_hyperparams_dict[key][param_name] = param_val
306
303
 
307
- def _init_history(self, manager: Manager):
304
+ def _init_history(self, manager: Manager, n_epochs: int = 1):
308
305
  """
309
306
  Initialize shared memory-based history tracking structures.
310
307
 
@@ -312,11 +309,15 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
312
309
  ----------
313
310
  manager : multiprocessing.Manager
314
311
  Shared memory manager for inter-process synchronization.
312
+ n_epochs : int, default=1
313
+ Number of epochs to initialize history for.
315
314
  """
316
315
  self._shm_lock = manager.Lock()
317
316
  self.optim_info = manager.dict({'n_svd_calls': 0})
318
- self.nll_history_ = manager.dict({hist_key: manager.list() for hist_key in self._key_2_history_key.values()})
319
- self.latent_history_ = manager.dict({hist_key: manager.list() for hist_key in self._key_2_history_key.values()})
317
+ self.nll_history_ = manager.list([manager.dict({hist_key: manager.list() for hist_key in self._key_2_history_key.values()})
318
+ for _ in range(n_epochs)])
319
+ self.latent_history_ = manager.list([manager.dict({hist_key: manager.list() for hist_key in self._key_2_history_key.values()})
320
+ for _ in range(n_epochs)])
320
321
 
321
322
  def _validate_hyperparams(self):
322
323
  """
@@ -355,11 +356,12 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
355
356
  else:
356
357
  raise NotImplementedError("sigmas should be a scalar, 1d, 2d, or 3d array.")
357
358
 
359
+ @abstractmethod
358
360
  def _compute_projected_map(self, idx: int, lr: float, key: Tuple[int, int]) -> Callable:
359
361
  """Placeholder for projected map computation (to be implemented in subclass)."""
360
362
  pass
361
363
 
362
- def _update_matrix(self, idx, lr: float, sample_grads: np.array, key: Tuple[int, int]):
364
+ def _update_matrix(self, idx, lr: float, sample_grads: np.ndarray, key: Tuple[int, int]):
363
365
  """
364
366
  Update a single parameter matrix via gradient step and projection.
365
367
 
@@ -386,14 +388,14 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
386
388
  """int: Total number of fitted matrices (shared + individual)."""
387
389
  return 1 + self.n_layers_
388
390
 
389
- def _pre_fit(self):
391
+ def _pre_fit(self, n_epochs: int = 1):
390
392
  """Perform pre-fitting initialization including parameters, keys, and history."""
391
393
  self._init_param_matrices(np.zeros((self.n_fitted_matrices, self.n_nodes_, self.n_nodes_)))
392
394
  self._validate_hyperparams()
393
395
  self._init_keys()
394
- self._init_history(manager=Manager())
396
+ self._init_history(manager=Manager(), n_epochs=n_epochs)
395
397
 
396
- def _optimization_step(self, param_indices, key: Tuple[int, int], As, lr: float, iteration: int,
398
+ def _optimization_step(self, param_indices, key: Tuple[int, int], As, lr: float, iteration: int, epoch: int,
397
399
  verbose: bool, tol: float,
398
400
  save_latent_history: bool, save_nll_history: bool) -> float:
399
401
  """
@@ -411,6 +413,8 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
411
413
  Learning rate.
412
414
  iteration : int
413
415
  Current iteration number.
416
+ epoch : int
417
+ Current epoch number.
414
418
  verbose : bool
415
419
  Whether to print progress.
416
420
  tol : float
@@ -433,7 +437,7 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
433
437
  nll = self._compute_nll(As, obs_mask=obs_mask)
434
438
 
435
439
  with self._shm_lock:
436
- self._update_history(nll, key=key,
440
+ self._update_history(nll, key=key, epoch=epoch,
437
441
  save_latent_history=save_latent_history, save_nll_history=save_nll_history)
438
442
 
439
443
  if verbose:
@@ -445,7 +449,9 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
445
449
  max_iter: int, tol: float, patience,
446
450
  verbose: bool, verbose_interval: int,
447
451
  save_latent_history: bool, save_nll_history: bool,
448
- refit: bool):
452
+ refit: bool = True, reinit: bool = True,
453
+ epoch: int = 0
454
+ ):
449
455
  """
450
456
  Optimize model parameters via iterative updates and early stopping.
451
457
 
@@ -473,14 +479,19 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
473
479
  Whether to save NLL values.
474
480
  refit : bool
475
481
  Whether to refit parameters after optimization.
482
+ reinit : bool, default=True
483
+ Whether to reinitialize parameters before optimization.
484
+ epoch : int, default=0
485
+ Current epoch number.
476
486
  """
477
- self._reset_history(key=key)
478
487
  param_indices = self._key_2_param_indices[key]
479
- self._optimized_params_init(As, key=key)
488
+ if reinit:
489
+ self._optimized_params_init(As, key=key)
490
+
480
491
  early_stopper = EarlyStopper(patience=patience, higher_better=False, rtol=tol)
481
492
  for iteration in range(max_iter):
482
- nll = self._optimization_step(param_indices, key=key, As=As, lr=lr, iteration=iteration, tol=tol,
483
- verbose=verbose and iteration % verbose_interval == 0,
493
+ nll = self._optimization_step(param_indices, key=key, As=As, lr=lr, iteration=iteration, epoch=epoch, tol=tol,
494
+ verbose=verbose and iteration % verbose_interval == 0,
484
495
  save_latent_history=save_latent_history, save_nll_history=save_nll_history)
485
496
 
486
497
  if early_stopper.stop_check(nll):
@@ -493,7 +504,7 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
493
504
  if refit:
494
505
  self.refit(As, refit_matrix_indices=param_indices)
495
506
 
496
- def _fit(self, As, **optim_kwargs):
507
+ def _fit(self, As, n_epochs: int = 1, **optim_kwargs):
497
508
  """
498
509
  Full model fitting routine combining initialization and optimization.
499
510
 
@@ -504,7 +515,7 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
504
515
  **optim_kwargs
505
516
  Optimization keyword arguments passed to `_optimize_params`.
506
517
  """
507
- self._pre_fit()
518
+ self._pre_fit(n_epochs=n_epochs)
508
519
  self._optimize_params(As=As, key=(0, 0), **optim_kwargs)
509
520
 
510
521
  def _nll_sample_grads(self, As):
@@ -602,16 +613,79 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
602
613
  Returns
603
614
  -------
604
615
  list of dict
605
- Error values for each iteration.
616
+ For each epoch, a dict mapping optimization-stage name to the list of
617
+ per-iteration error reports for that stage (mirrors the structure of
618
+ `nll_history_` / `latent_history_`).
606
619
  """
607
620
  assert self.latent_history_, "Set save_latent_history == True during fit to access latent_history!"
608
621
  assert len(true_params) == len(self._get_all_fitted_parameter_names()), \
609
622
  f"Length of true_params should be equal to {len(self._get_all_fitted_parameter_names())}"
610
- err_hist = []
611
- for estimate_params in self.latent_history_:
612
- iteration_errs = make_error_report(true_params, estimate_params, relative_errors=relative_errors)
613
- err_hist.append(iteration_errs)
614
- return err_hist
623
+ err_hist_over_epochs = []
624
+ for epoch_history in self.latent_history_:
625
+ err_hist = {}
626
+ for stage, param_estimates_over_iter in epoch_history.items():
627
+ iteration_errs = [make_error_report(true_params, param_estimates, relative_errors=relative_errors)
628
+ for param_estimates in param_estimates_over_iter]
629
+ err_hist[stage] = iteration_errs
630
+ err_hist_over_epochs.append(err_hist)
631
+ return err_hist_over_epochs
632
+
633
+ def plot_error_history(self, *true_params, relative_errors=True, labels=None, n_cols: int = 4,
634
+ fontsize=14, figsize=(12, 20), print_final_errors=True):
635
+ """
636
+ Plot evolution of parameter estimation errors over iterations, one subplot
637
+ per optimization stage within each epoch (analogous to `plot_nll_history`).
638
+
639
+ Parameters
640
+ ----------
641
+ *true_params : list of np.ndarray
642
+ Ground truth parameters.
643
+ relative_errors : bool, default=True
644
+ Whether to plot relative errors.
645
+ labels : list of str, optional
646
+ Custom labels for parameters.
647
+ n_cols : int, default=4
648
+ Number of subplot columns.
649
+ fontsize : int, default=14
650
+ Font size for plot.
651
+ figsize : tuple, default=(12, 20)
652
+ Figure size.
653
+ print_final_errors : bool, default=True
654
+ Whether to print final iteration errors.
655
+ """
656
+ if labels is None:
657
+ labels = self._get_all_fitted_parameter_names()
658
+ else:
659
+ assert len(true_params) == len(labels), \
660
+ "labels should be of the same length as the length of true_params"
661
+
662
+ err_hist_over_epochs = self.get_error_history(*true_params, relative_errors=relative_errors)
663
+ for epoch, epoch_err_hist in enumerate(err_hist_over_epochs):
664
+ epoch_n_cols = min(n_cols, len(epoch_err_hist))
665
+ n_rows = int(np.ceil(len(epoch_err_hist) / epoch_n_cols))
666
+ fig, axs = plt.subplots(ncols=epoch_n_cols, nrows=n_rows, figsize=figsize)
667
+ axs = np.array(axs).flatten()
668
+
669
+ for ax, (stage, iteration_errs) in zip(axs, epoch_err_hist.items()):
670
+ stage_errs = np.stack(iteration_errs) # shape (n_iterations, n_params)
671
+ ax.plot(stage_errs, label=labels)
672
+ ax.set_xlabel("Iteration", fontsize=fontsize)
673
+ ax.set_ylabel("Error", fontsize=fontsize)
674
+ ax.set_title(f"{stage}", fontsize=fontsize)
675
+ ax.tick_params(axis='both', labelsize=fontsize)
676
+ axs[0].legend(fontsize=fontsize)
677
+
678
+ for idx in range(len(epoch_err_hist), epoch_n_cols * n_rows):
679
+ fig.delaxes(axs[idx]) # Remove extra axes
680
+ plt.tight_layout()
681
+ if len(epoch_err_hist) > 1:
682
+ plt.suptitle(f"Epoch {epoch}", fontsize=fontsize + 2)
683
+
684
+ if print_final_errors:
685
+ final_errs = {stage: np.round(iteration_errs[-1], 2)
686
+ for stage, iteration_errs in epoch_err_hist.items()}
687
+ print(f"Final errors after epoch {epoch}:", final_errs)
688
+ plt.show()
615
689
 
616
690
  def plot_nll_history(self, n_cols: int = 4, fontsize: int = 14, figsize=(12, 20)):
617
691
  """
@@ -626,54 +700,89 @@ class BaseMultiNeSSRefined(BaseMultiNeSS, BaseRefitting):
626
700
  figsize : tuple, default=(12, 20)
627
701
  Figure size.
628
702
  """
629
- n_cols = min(n_cols, len(self.nll_history_))
630
- n_rows = int(np.ceil(len(self.nll_history_) / n_cols))
631
- fig, axs = plt.subplots(ncols=n_cols, nrows=n_rows, figsize=figsize)
632
- axs = np.array(axs).flatten()
633
- for ax, (stage, nll_hist) in zip(axs, self.nll_history_.items()):
634
- ax.plot(nll_hist)
635
- ax.set_xlabel("Iteration", fontsize=fontsize)
636
- ax.set_ylabel("Negative Loglikelihood", fontsize=fontsize)
637
- ax.set_title(f"{stage}", fontsize=fontsize)
638
- ax.tick_params(axis='both', labelsize=fontsize)
639
- for idx in range(len(self.nll_history_), n_cols * n_rows):
640
- fig.delaxes(axs[idx]) # Remove extra axes
641
- plt.tight_layout()
642
- plt.show()
703
+ for epoch, epoch_nll_hist in enumerate(self.nll_history_):
704
+ n_cols = min(n_cols, len(epoch_nll_hist))
705
+ n_rows = int(np.ceil(len(epoch_nll_hist) / n_cols))
706
+ fig, axs = plt.subplots(ncols=n_cols, nrows=n_rows, figsize=figsize)
707
+ axs = np.array(axs).flatten()
708
+ for ax, (stage, nll_hist) in zip(axs, epoch_nll_hist.items()):
709
+ ax.plot(nll_hist)
710
+ ax.set_xlabel("Iteration", fontsize=fontsize)
711
+ ax.set_ylabel("Negative Loglikelihood", fontsize=fontsize)
712
+ ax.set_title(f"{stage}", fontsize=fontsize)
713
+ ax.tick_params(axis='both', labelsize=fontsize)
714
+ for idx in range(len(epoch_nll_hist), n_cols * n_rows):
715
+ fig.delaxes(axs[idx]) # Remove extra axes
716
+ plt.tight_layout()
717
+ if len(epoch_nll_hist) > 1:
718
+ plt.title(f"Epoch {epoch}", fontsize=fontsize + 2)
719
+ plt.show()
643
720
 
644
- def plot_error_history(self, *true_params, relative_errors=True, labels=None, fontsize=14,
645
- print_final_errors=True):
721
+ def plot_nll_history(self, n_cols: int = 4, fontsize: int = 14, figsize=(12, 20)):
646
722
  """
647
- Plot evolution of parameter estimation errors over iterations.
723
+ Plot negative log-likelihood convergence per stage/group, with all epochs
724
+ drawn on the same continuous x-axis. Epoch boundaries are marked with
725
+ bracket-shaped underlines labeled "Epoch {n}" below each plot.
648
726
 
649
727
  Parameters
650
728
  ----------
651
- *true_params : list of np.ndarray
652
- Ground truth parameters.
653
- relative_errors : bool, default=True
654
- Whether to plot relative errors.
655
- labels : list of str, optional
656
- Custom labels for parameters.
729
+ n_cols : int, default=4
730
+ Number of subplot columns.
657
731
  fontsize : int, default=14
658
- Font size for plot.
659
- print_final_errors : bool, default=True
660
- Whether to print final iteration errors.
732
+ Font size for labels and titles.
733
+ figsize : tuple, default=(12, 20)
734
+ Figure size.
661
735
  """
662
- if labels is None:
663
- labels = self._get_all_fitted_parameter_names()
664
- else:
665
- assert len(true_params) == len(labels), \
666
- "labels should be of the same length as the length of true_params"
736
+ from matplotlib.transforms import blended_transform_factory
737
+
738
+ keys = sorted(self._key_2_history_key.keys()) # (0, 0) ... (0, K-1), (1, 0)
739
+
740
+ nll_hist = {}
741
+ for key in keys:
742
+ history_key = self._key_2_history_key[key]
743
+ vals, epoch_ends, cum_iter = [], [], 0
744
+ for epoch_nll_hist in self.nll_history_:
745
+ epoch_vals = list(epoch_nll_hist[history_key])
746
+ vals.extend(epoch_vals)
747
+ cum_iter += len(epoch_vals)
748
+ epoch_ends.append(cum_iter)
749
+ nll_hist[key] = {"nll": np.array(vals), "epoch_ends": epoch_ends}
667
750
 
668
- err_hist = self.get_error_history(*true_params, relative_errors=relative_errors)
669
- if print_final_errors:
670
- print("Final errors:", np.round(err_hist[-1], 2))
671
- plt.figure(figsize=(12, 8))
672
- plt.plot(err_hist, label=labels)
673
- plt.legend(fontsize=fontsize)
674
- plt.xlabel("Iteration", fontsize=fontsize)
675
- plt.ylabel("Error", fontsize=fontsize)
676
- plt.title("Relative Frobenius Errors", fontsize=fontsize)
751
+ n_cols = min(n_cols, len(keys))
752
+ n_rows = int(np.ceil(len(keys) / n_cols))
753
+ fig, axs = plt.subplots(ncols=n_cols, nrows=n_rows, figsize=figsize)
754
+ axs = np.array(axs).flatten()
755
+
756
+ bracket_y = -0.10
757
+ tick_height = 0.025
758
+ label_y = bracket_y - 0.02
759
+
760
+ for ax, key in zip(axs, keys):
761
+ hist = nll_hist[key]
762
+ ax.plot(np.arange(1, len(hist["nll"]) + 1), hist["nll"])
763
+
764
+ epoch_ends = hist["epoch_ends"]
765
+ epoch_starts = [0] + list(epoch_ends[:-1])
766
+ trans = blended_transform_factory(ax.transData, ax.transAxes)
767
+
768
+ for epoch_num, (start, end) in enumerate(zip(epoch_starts, epoch_ends), start=1):
769
+ ax.plot([start, end], [bracket_y, bracket_y], transform=trans,
770
+ color='black', linewidth=1.5, clip_on=False)
771
+ ax.plot([start, start], [bracket_y, bracket_y + tick_height], transform=trans,
772
+ color='black', linewidth=1.5, clip_on=False)
773
+ ax.plot([end, end], [bracket_y, bracket_y + tick_height], transform=trans,
774
+ color='black', linewidth=1.5, clip_on=False)
775
+ ax.text((start + end) / 2, label_y, f"Epoch {epoch_num}", transform=trans,
776
+ ha='center', va='top', fontsize=max(fontsize - 4, 8), clip_on=False)
777
+
778
+ ax.set_ylabel("Negative Loglikelihood", fontsize=fontsize)
779
+ ax.set_title(self._key_2_history_key[key], fontsize=fontsize)
780
+ ax.tick_params(axis='both', which='major', labelsize=fontsize)
781
+
782
+ for idx in range(len(keys), n_cols * n_rows):
783
+ fig.delaxes(axs[idx])
784
+ plt.tight_layout()
785
+ plt.show()
677
786
 
678
787
 
679
788
  class BaseMultiNeSSRefinedCV(BaseMultiNeSSRefined):
@@ -700,8 +809,8 @@ class BaseMultiNeSSRefinedCV(BaseMultiNeSSRefined):
700
809
  Random seed for reproducibility.
701
810
  """
702
811
 
703
- def __init__(self, param_grid: Dict[str, List] = None, cv_folds=None, test_prop=0.1,
704
- fix_layer_split: bool = False, use_1se_rule=False, random_seed: int = None, **kwargs):
812
+ def __init__(self, param_grid: Optional[Dict[str, List]] = None, cv_folds=3, test_prop=0.1,
813
+ fix_layer_split: bool = False, use_1se_rule=False, random_seed: Optional[int] = None, **kwargs):
705
814
  super().__init__(**kwargs)
706
815
  self.cv_folds = cv_folds
707
816
  self.test_prop = test_prop
@@ -730,7 +839,7 @@ class BaseMultiNeSSRefinedCV(BaseMultiNeSSRefined):
730
839
  super()._init_keys()
731
840
  self._make_key_2_hyperparams_grid_dict()
732
841
 
733
- def _init_history(self, manager: Manager):
842
+ def _init_history(self, manager: Manager, n_epochs: int = 1):
734
843
  """
735
844
  Initialize multiprocessing-safe containers for cross-validation results.
736
845
 
@@ -738,8 +847,10 @@ class BaseMultiNeSSRefinedCV(BaseMultiNeSSRefined):
738
847
  ----------
739
848
  manager : multiprocessing.Manager
740
849
  Shared-memory manager used to create thread-safe dictionaries and lists.
850
+ n_epochs : int, default=1
851
+ Number of epochs for which to initialize the history.
741
852
  """
742
- super()._init_history(manager)
853
+ super()._init_history(manager, n_epochs=n_epochs)
743
854
  self._cv_results = manager.dict(
744
855
  {key: manager.dict({params: manager.list() for params in product(*param_grid_dict.values())})
745
856
  for key, param_grid_dict in self._key_2_hyperparams_grid.items()}
@@ -937,11 +1048,11 @@ class MultiNeSS(BaseMultiNeSSRefined, BaseRefitting):
937
1048
  """
938
1049
 
939
1050
  def __init__(self,
940
- lmbda: float = None,
941
- alpha: Union[float, List, np.ndarray] = None,
942
- max_rank: int = None, init_rank: int = None,
1051
+ lmbda: Optional[float] = None,
1052
+ alpha: Optional[Union[float, List, np.ndarray]] = None,
1053
+ max_rank: Optional[int] = None, init_rank: Optional[int] = None,
943
1054
  edge_distrib: str = "normal",
944
- sigmas: Union[float, List, np.ndarray] = None,
1055
+ sigmas: Optional[Union[float, List, np.ndarray]] = None,
945
1056
  loops_allowed: bool = True,
946
1057
  refit_threshold=1e-8):
947
1058
 
@@ -1007,7 +1118,7 @@ class MultiNeSS(BaseMultiNeSSRefined, BaseRefitting):
1007
1118
  alpha = if_scalar_or_given_length_array(self.alpha, length=self.n_layers_, name="alpha")
1008
1119
  self._key_2_hyperparams_dict = {(0, 0): {"lmbda": lmbda, "alpha": alpha}}
1009
1120
 
1010
- def fit(self, As: List[np.array],
1121
+ def fit(self, As: List[np.ndarray],
1011
1122
  lr: float = 1.,
1012
1123
  max_iter: int = 100, tol=1e-5, patience=10,
1013
1124
  refit=True,
@@ -1060,17 +1171,17 @@ class MultiNeSSCV(MultiNeSS, BaseMultiNeSSRefinedCV):
1060
1171
  Extends `MultiNeSS` with hyperparameter selection via cross-validation.
1061
1172
  """
1062
1173
 
1063
- def __init__(self, param_grid: Dict[str, List[float]] = None, cv_folds=3, test_prop=0.1,
1064
- lmbda: float = None,
1065
- alpha: Union[float, np.ndarray, list] = None,
1174
+ def __init__(self, param_grid: Optional[Dict[str, List[float]]] = None, cv_folds=3, test_prop=0.1,
1175
+ lmbda: Optional[float] = None,
1176
+ alpha: Optional[Union[float, np.ndarray, list]] = None,
1066
1177
  edge_distrib: str = "normal",
1067
- max_rank: int = None, init_rank: int = None,
1068
- sigmas: Union[float, List, np.ndarray] = None,
1178
+ max_rank: Optional[int] = None, init_rank: Optional[int] = None,
1179
+ sigmas: Optional[Union[float, List[float], np.ndarray]] = None,
1069
1180
  loops_allowed: bool = True,
1070
1181
  refit_threshold: float = 1e-8,
1071
1182
  fix_layer_split: bool = False,
1072
1183
  use_1se_rule: bool = False,
1073
- random_seed: int = None):
1184
+ random_seed: Optional[int] = None):
1074
1185
  """
1075
1186
  Initialize a MultiNeSS model with cross-validation.
1076
1187
 
@@ -1137,6 +1248,7 @@ class BaseOracleMultiNeSS(BaseMultiNeSSRefined):
1137
1248
  Inherits all parameters from BaseMultiNeSSRefined.
1138
1249
  """
1139
1250
 
1251
+ @abstractmethod
1140
1252
  def _compute_threshold_rank(self, idx: int, key: Tuple[int, int]) -> int:
1141
1253
  """
1142
1254
  Compute the threshold rank for hard-thresholding operator.
@@ -1196,7 +1308,7 @@ class BaseOracleMultiNeSS(BaseMultiNeSSRefined):
1196
1308
  param_inits.append(param_init)
1197
1309
  self._set_matrices(param_inits, indices=param_indices)
1198
1310
 
1199
- def fit(self, As: List[np.array],
1311
+ def fit(self, As: List[np.ndarray],
1200
1312
  lr: float = 1.,
1201
1313
  max_iter: int = 100, tol=1e-5, patience=10,
1202
1314
  verbose=True, verbose_interval=1,
@@ -1,6 +1,6 @@
1
1
  import numpy as np
2
2
  from scipy.sparse.linalg import svds, eigsh
3
- from typing import List, Union, Tuple
3
+ from typing import List, Optional, Union, Tuple
4
4
  from copy import copy
5
5
  from scipy.linalg import sqrtm
6
6
  from sklearn.model_selection import KFold
@@ -37,14 +37,14 @@ class MultipleNetworkTrainTestSplitter:
37
37
  self.random_seed = random_seed
38
38
  self.check_if_sym_input = check_if_sym_input
39
39
 
40
- def _validate_input(self, As: np.array):
40
+ def _validate_input(self, As: np.ndarray):
41
41
  assert As.ndim == 3
42
42
  assert As.shape[1] == As.shape[2]
43
43
  if self.check_if_sym_input:
44
44
  assert np.all([np.allclose(A, A.T) for A in As])
45
45
  self.n_layers_, self.n_nodes_, _ = As.shape
46
46
 
47
- def _make_train_test_layers(self, As, triu_test_masks: np.array):
47
+ def _make_train_test_layers(self, As, triu_test_masks: np.ndarray):
48
48
  triu_x, triu_y = np.triu_indices(self.n_nodes_, k=0 if self.loops_allowed else 1)
49
49
  triu_train_masks = ~triu_test_masks
50
50
  As_test = As.copy()
@@ -218,8 +218,8 @@ def mean_frobenius_error(As_true, As_pred, relative=True, include_offdiag=True):
218
218
  for A_true, A in zip(As_true, As_pred)])
219
219
 
220
220
 
221
- def make_error_report(params_true: Union[List[np.array], Tuple[np.array]],
222
- params_pred: Union[List[np.array], Tuple[np.array]],
221
+ def make_error_report(params_true: Union[List[np.ndarray], Tuple[np.ndarray]],
222
+ params_pred: Union[List[np.ndarray], Tuple[np.ndarray]],
223
223
  relative_errors: bool = True):
224
224
  assert len(params_true) == len(params_pred)
225
225
  errs = []
@@ -229,7 +229,7 @@ def make_error_report(params_true: Union[List[np.array], Tuple[np.array]],
229
229
  return errs
230
230
 
231
231
 
232
- def make_group_averages(As, group_indices, groups=None) -> np.array:
232
+ def make_group_averages(As, group_indices, groups=None) -> np.ndarray:
233
233
  A_bars = []
234
234
  if groups is not None:
235
235
  assert set(groups).issubset(set(group_indices))
@@ -329,7 +329,7 @@ def estimate_sigma_mad(M):
329
329
  return sigma
330
330
 
331
331
 
332
- def if_scalar_or_given_length_array(val, length: int, name: str = None) -> np.array:
332
+ def if_scalar_or_given_length_array(val, length: int, name: Optional[str] = None) -> np.ndarray:
333
333
  name = f'{val=}'.split('=')[0] if name is None else name
334
334
  if isinstance(val, (np.ndarray, list)):
335
335
  assert len(val) == length, \
@@ -342,7 +342,7 @@ def if_scalar_or_given_length_array(val, length: int, name: str = None) -> np.ar
342
342
  return val
343
343
 
344
344
 
345
- def fill_diagonals(As: Union[np.array, List[np.array]], val: float = 0, inplace: bool = True):
345
+ def fill_diagonals(As: Union[np.ndarray, List[np.ndarray]], val: float = 0, inplace: bool = True):
346
346
  if not inplace:
347
347
  As = copy(As)
348
348
  for idx in range(len(As)):
@@ -1,16 +1,16 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: GroupMultiNeSS
3
- Version: 0.0.4
3
+ Version: 0.0.6
4
4
  Summary: GroupMultiNeSS package
5
5
  Author: Alexander Kagan
6
6
  Author-email: <amkagan@umich.edu>
7
7
  Keywords: python,multiplex networks,multiness,latent space models
8
8
  Classifier: Development Status :: 3 - Alpha
9
9
  Classifier: Intended Audience :: Education
10
- Classifier: Programming Language :: Python :: 2
11
10
  Classifier: Programming Language :: Python :: 3
12
11
  Classifier: Operating System :: MacOS :: MacOS X
13
12
  Classifier: Operating System :: Microsoft :: Windows
13
+ Requires-Python: <3.12
14
14
  Description-Content-Type: text/markdown
15
15
  License-File: LICENSE
16
16
  Requires-Dist: numpy<2
@@ -21,7 +21,6 @@ Requires-Dist: matplotlib
21
21
  Requires-Dist: seaborn
22
22
  Requires-Dist: statsmodels
23
23
  Requires-Dist: scikit-learn
24
- Requires-Dist: more_itertools
25
24
  Dynamic: author
26
25
  Dynamic: author-email
27
26
  Dynamic: classifier
@@ -30,12 +29,13 @@ Dynamic: description-content-type
30
29
  Dynamic: keywords
31
30
  Dynamic: license-file
32
31
  Dynamic: requires-dist
32
+ Dynamic: requires-python
33
33
  Dynamic: summary
34
34
 
35
35
  # GroupMultiNeSS
36
36
 
37
37
  GroupMultiNeSS is a package for statistical modeling of multilayer networks. It implements multiple approaches allowing to extract shared, group, and individual latent structures from a collection of networks on a shared set of nodes. Specifically, it contains the implementation of fitting and sampling procedures for the following models:
38
- - GroupMultiNeSS [Kagan et al. (2025)] - likelihood based approach with nuclear norm penalization, accounts for the additional group latent structure
38
+ - GroupMultiNeSS [[Kagan et al. (2025)](https://arxiv.org/abs/2511.11086)] - likelihood based approach with nuclear norm penalization, accounts for the additional group latent structure
39
39
  - MultiNeSS [[MacDonald et al. (2021)](https://arxiv.org/abs/2012.14409)] - likelihood based approach with nuclear norm penalization
40
40
  - MultiNeSS [[Tian et al. (2024)](https://arxiv.org/abs/2412.02151)] - likelihood based approach with pre-estimation of latent ranks via Shared Space Hunting algorithm
41
41
  - COSIE [[Arroyo et al. (2020)](https://arxiv.org/abs/1906.10026)] - spectral-based Multiple Adjacency Spectral Embedding algorithm
@@ -6,4 +6,3 @@ matplotlib
6
6
  seaborn
7
7
  statsmodels
8
8
  scikit-learn
9
- more_itertools
@@ -1,16 +1,16 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: GroupMultiNeSS
3
- Version: 0.0.4
3
+ Version: 0.0.6
4
4
  Summary: GroupMultiNeSS package
5
5
  Author: Alexander Kagan
6
6
  Author-email: <amkagan@umich.edu>
7
7
  Keywords: python,multiplex networks,multiness,latent space models
8
8
  Classifier: Development Status :: 3 - Alpha
9
9
  Classifier: Intended Audience :: Education
10
- Classifier: Programming Language :: Python :: 2
11
10
  Classifier: Programming Language :: Python :: 3
12
11
  Classifier: Operating System :: MacOS :: MacOS X
13
12
  Classifier: Operating System :: Microsoft :: Windows
13
+ Requires-Python: <3.12
14
14
  Description-Content-Type: text/markdown
15
15
  License-File: LICENSE
16
16
  Requires-Dist: numpy<2
@@ -21,7 +21,6 @@ Requires-Dist: matplotlib
21
21
  Requires-Dist: seaborn
22
22
  Requires-Dist: statsmodels
23
23
  Requires-Dist: scikit-learn
24
- Requires-Dist: more_itertools
25
24
  Dynamic: author
26
25
  Dynamic: author-email
27
26
  Dynamic: classifier
@@ -30,12 +29,13 @@ Dynamic: description-content-type
30
29
  Dynamic: keywords
31
30
  Dynamic: license-file
32
31
  Dynamic: requires-dist
32
+ Dynamic: requires-python
33
33
  Dynamic: summary
34
34
 
35
35
  # GroupMultiNeSS
36
36
 
37
37
  GroupMultiNeSS is a package for statistical modeling of multilayer networks. It implements multiple approaches allowing to extract shared, group, and individual latent structures from a collection of networks on a shared set of nodes. Specifically, it contains the implementation of fitting and sampling procedures for the following models:
38
- - GroupMultiNeSS [Kagan et al. (2025)] - likelihood based approach with nuclear norm penalization, accounts for the additional group latent structure
38
+ - GroupMultiNeSS [[Kagan et al. (2025)](https://arxiv.org/abs/2511.11086)] - likelihood based approach with nuclear norm penalization, accounts for the additional group latent structure
39
39
  - MultiNeSS [[MacDonald et al. (2021)](https://arxiv.org/abs/2012.14409)] - likelihood based approach with nuclear norm penalization
40
40
  - MultiNeSS [[Tian et al. (2024)](https://arxiv.org/abs/2412.02151)] - likelihood based approach with pre-estimation of latent ranks via Shared Space Hunting algorithm
41
41
  - COSIE [[Arroyo et al. (2020)](https://arxiv.org/abs/1906.10026)] - spectral-based Multiple Adjacency Spectral Embedding algorithm
@@ -1,7 +1,7 @@
1
1
  # GroupMultiNeSS
2
2
 
3
3
  GroupMultiNeSS is a package for statistical modeling of multilayer networks. It implements multiple approaches allowing to extract shared, group, and individual latent structures from a collection of networks on a shared set of nodes. Specifically, it contains the implementation of fitting and sampling procedures for the following models:
4
- - GroupMultiNeSS [Kagan et al. (2025)] - likelihood based approach with nuclear norm penalization, accounts for the additional group latent structure
4
+ - GroupMultiNeSS [[Kagan et al. (2025)](https://arxiv.org/abs/2511.11086)] - likelihood based approach with nuclear norm penalization, accounts for the additional group latent structure
5
5
  - MultiNeSS [[MacDonald et al. (2021)](https://arxiv.org/abs/2012.14409)] - likelihood based approach with nuclear norm penalization
6
6
  - MultiNeSS [[Tian et al. (2024)](https://arxiv.org/abs/2412.02151)] - likelihood based approach with pre-estimation of latent ranks via Shared Space Hunting algorithm
7
7
  - COSIE [[Arroyo et al. (2020)](https://arxiv.org/abs/1906.10026)] - spectral-based Multiple Adjacency Spectral Embedding algorithm
@@ -3,7 +3,7 @@ from pathlib import Path
3
3
  this_directory = Path(__file__).parent
4
4
  LONG_DESCRIPTION = (this_directory / "README.md").read_text()
5
5
 
6
- VERSION = '0.0.4'
6
+ VERSION = '0.0.6'
7
7
  DESCRIPTION = 'GroupMultiNeSS package'
8
8
 
9
9
  setup(
@@ -15,6 +15,7 @@ setup(
15
15
  long_description_content_type="text/markdown",
16
16
  long_description=LONG_DESCRIPTION,
17
17
  packages=find_packages(),
18
+ python_requires='<3.12',
18
19
  install_requires=["numpy<2",
19
20
  "scipy",
20
21
  "typing",
@@ -22,15 +23,13 @@ setup(
22
23
  "matplotlib",
23
24
  "seaborn",
24
25
  "statsmodels",
25
- "scikit-learn",
26
- "more_itertools"],
26
+ "scikit-learn"],
27
27
 
28
28
  keywords=['python', 'multiplex networks', 'multiness', 'latent space models'],
29
29
 
30
30
  classifiers=[
31
31
  "Development Status :: 3 - Alpha",
32
32
  "Intended Audience :: Education",
33
- "Programming Language :: Python :: 2",
34
33
  "Programming Language :: Python :: 3",
35
34
  "Operating System :: MacOS :: MacOS X",
36
35
  "Operating System :: Microsoft :: Windows",
File without changes
File without changes