GroupMultiNeSS 0.0.6__tar.gz → 0.0.8__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.
Files changed (23) hide show
  1. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/GroupMultiNeSS/base.py +72 -16
  2. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/GroupMultiNeSS/data_generation.py +11 -4
  3. groupmultiness-0.0.8/GroupMultiNeSS/group_multiness.py +683 -0
  4. groupmultiness-0.0.8/GroupMultiNeSS/multiness.py +1613 -0
  5. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/GroupMultiNeSS/shared_space_hunting.py +2 -2
  6. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/GroupMultiNeSS/utils.py +47 -6
  7. groupmultiness-0.0.8/GroupMultiNeSS.egg-info/PKG-INFO +221 -0
  8. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/GroupMultiNeSS.egg-info/requires.txt +1 -1
  9. groupmultiness-0.0.8/PKG-INFO +221 -0
  10. groupmultiness-0.0.8/README.md +187 -0
  11. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/setup.py +2 -2
  12. groupmultiness-0.0.6/GroupMultiNeSS/group_multiness.py +0 -661
  13. groupmultiness-0.0.6/GroupMultiNeSS/multiness.py +0 -1419
  14. groupmultiness-0.0.6/GroupMultiNeSS.egg-info/PKG-INFO +0 -102
  15. groupmultiness-0.0.6/PKG-INFO +0 -102
  16. groupmultiness-0.0.6/README.md +0 -68
  17. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/GroupMultiNeSS/MASE.py +0 -0
  18. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/GroupMultiNeSS/__init__.py +0 -0
  19. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/GroupMultiNeSS.egg-info/SOURCES.txt +0 -0
  20. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/GroupMultiNeSS.egg-info/dependency_links.txt +0 -0
  21. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/GroupMultiNeSS.egg-info/top_level.txt +0 -0
  22. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/LICENSE +0 -0
  23. {groupmultiness-0.0.6 → groupmultiness-0.0.8}/setup.cfg +0 -0
@@ -7,6 +7,7 @@ from warnings import warn
7
7
  from typing import Iterable
8
8
  from multiprocessing import shared_memory
9
9
  import statsmodels.api as sm
10
+ from sklearn.linear_model import LinearRegression, LogisticRegression, PoissonRegressor
10
11
 
11
12
  from .utils import sigmoid, leading_left_eigenvectors
12
13
 
@@ -43,11 +44,26 @@ class SharedMemoryMatrixFitter:
43
44
  elif vals is not None:
44
45
  warn("shape argument is not used as vals argument is provided!")
45
46
 
46
- shm = shared_memory.SharedMemory(create=True, size=np.prod(shape) * 8)
47
- self._param_matrices_shm = shared_memory.SharedMemory(name=shm.name)
47
+ shape = tuple(shape)
48
+ self.close()
49
+ self._param_matrices_shm = shared_memory.SharedMemory(create=True, size=int(np.prod(shape)) * 8)
48
50
  self.param_matrices = np.ndarray(shape, dtype=np.float64, buffer=self._param_matrices_shm.buf)
49
51
  if vals is not None:
50
52
  self.param_matrices[:] = vals
53
+ else:
54
+ self.param_matrices.fill(0.)
55
+
56
+ def close(self):
57
+ """Release the shared-memory allocation, including temporary CV fits."""
58
+ shm = getattr(self, "_param_matrices_shm", None)
59
+ if shm is not None:
60
+ self.param_matrices = None
61
+ shm.close()
62
+ try:
63
+ shm.unlink()
64
+ except FileNotFoundError:
65
+ pass
66
+ self._param_matrices_shm = None
51
67
 
52
68
  def _set_matrix(self, val, idx):
53
69
  """
@@ -89,6 +105,8 @@ class SharedMemoryMatrixFitter:
89
105
  np.ndarray
90
106
  Array backed by shared memory containing all parameter matrices.
91
107
  """
108
+ if self.param_matrices is None or self._param_matrices_shm is None:
109
+ raise RuntimeError("Parameter storage is closed; fit the model again before accessing it")
92
110
  return np.ndarray(self.param_matrices.shape, dtype=np.float64, buffer=self._param_matrices_shm.buf)
93
111
 
94
112
 
@@ -107,7 +125,7 @@ class BaseMultiplexNetworksModel(ABC):
107
125
  Parameters
108
126
  ----------
109
127
  edge_distrib : str, default='normal'
110
- Type of edge distribution ('normal' or 'bernoulli').
128
+ Type of edge distribution ('normal', 'bernoulli', or 'poisson').
111
129
  loops_allowed : bool, default=True
112
130
  Whether self-loops are allowed in adjacency matrices.
113
131
  """
@@ -117,10 +135,12 @@ class BaseMultiplexNetworksModel(ABC):
117
135
  self.link_ = lambda x: x
118
136
  elif edge_distrib == "bernoulli":
119
137
  self.link_ = sigmoid
138
+ elif edge_distrib == "poisson":
139
+ self.link_ = np.exp
120
140
  else:
121
- raise NotImplementedError("Edge distribution should be either normal or bernoulli!")
141
+ raise NotImplementedError("Edge distribution should be normal, bernoulli, or poisson!")
122
142
 
123
- def _validate_input(self, As: List[np.ndarray]) -> np.ndarray:
143
+ def _validate_input(self, As: Union[List[np.ndarray], np.ndarray]) -> np.ndarray:
124
144
  """
125
145
  Validate input adjacency matrices.
126
146
 
@@ -147,7 +167,12 @@ class BaseMultiplexNetworksModel(ABC):
147
167
  self.n_nodes_ = As[0].shape[0]
148
168
  self.n_layers_ = len(As)
149
169
  self._param_participance_masks = self._get_param_participance_masks()
150
- return np.stack(As)
170
+ As = np.stack(list(As))
171
+ if self.edge_distrib == 'poisson':
172
+ observed = As[~np.isnan(As)]
173
+ if np.any(~np.isfinite(observed)) or np.any(observed < 0) or np.any(observed != np.floor(observed)):
174
+ raise ValueError('Poisson edges must be nonnegative integer counts (or NaN for missing edges)')
175
+ return As
151
176
 
152
177
  @abstractmethod
153
178
  def _get_param_participance_masks(self) -> np.ndarray:
@@ -177,7 +202,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
177
202
  Parameters
178
203
  ----------
179
204
  edge_distrib : str, default="normal"
180
- Type of edge distribution ('normal' or 'bernoulli').
205
+ Type of edge distribution ('normal', 'bernoulli', or 'poisson').
181
206
  max_rank : int, optional
182
207
  Maximum rank for eigenvector-based refitting.
183
208
  loops_allowed : bool, default=True
@@ -227,7 +252,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
227
252
  def _construct_refit_design_response_and_offset(self, As: np.ndarray, refit_matrix_indices: np.ndarray,
228
253
  refit_matrix_eigvecs: List[np.ndarray]):
229
254
  """
230
- Construct the design matrix, response vector, and offset for GLM refitting.
255
+ Construct the design matrix, response vector, and offset for refitting.
231
256
 
232
257
  Parameters
233
258
  ----------
@@ -241,7 +266,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
241
266
  Returns
242
267
  -------
243
268
  tuple of np.ndarray
244
- Design matrix, response vector, and offset vector for GLM fitting.
269
+ Design matrix, response vector, and offset vector for regression.
245
270
  """
246
271
  triu_indices = np.triu_indices(self.n_nodes_, k=0 if self.loops_allowed else 1)
247
272
  obs_mask = self._param_participance_masks[refit_matrix_indices].any(0)
@@ -270,7 +295,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
270
295
  refit_matrix_eigvecs : list of np.ndarray
271
296
  Eigenvectors for each refit matrix.
272
297
  refit_matrix_eigvals : np.ndarray
273
- Refitted eigenvalues from GLM.
298
+ Refitted eigenvalues from regression.
274
299
 
275
300
  Returns
276
301
  -------
@@ -309,9 +334,36 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
309
334
  refit_matrix_indices)) # don't refit rank zero matrices after hard-threshold
310
335
  return np.array(refit_matrix_indices, dtype=int)
311
336
 
337
+ def _fit_refit_coefficients(self, design_mat, response, offset, sample_weight=None):
338
+ """Unpenalized regression with no intercept, preserving optional offsets."""
339
+ if self.edge_distrib == 'normal':
340
+ # Subtracting the offset is exact for the identity link.
341
+ model = LinearRegression(fit_intercept=False)
342
+ return model.fit(design_mat, response - offset, sample_weight=sample_weight).coef_
343
+
344
+ # Scaling columns improves conditioning without changing the model space
345
+ # or the unpenalized likelihood; undo it on the fitted eigenvalues.
346
+ scale = np.sqrt(np.mean(design_mat ** 2, axis=0))
347
+ scale[scale == 0] = 1.
348
+ design = design_mat / scale
349
+ # LogisticRegression requires both response classes. A binomial GLM
350
+ # also accepts an all-zero/all-one response (e.g. a sparse CV fold).
351
+ if np.any(offset != 0) or (self.edge_distrib == 'bernoulli' and np.unique(response).size < 2):
352
+ family = sm.families.Poisson() if self.edge_distrib == 'poisson' else sm.families.Binomial()
353
+ return sm.GLM(response, design, family=family, offset=offset).fit().params / scale
354
+ if self.edge_distrib == 'poisson':
355
+ model = PoissonRegressor(alpha=0., fit_intercept=False, solver='lbfgs',
356
+ tol=1e-9, max_iter=1000)
357
+ else:
358
+ # Infinite C disables regularization without version-specific penalty
359
+ # spellings ('none', None, or the newer deprecated default).
360
+ model = LogisticRegression(C=np.inf, fit_intercept=False, solver='lbfgs',
361
+ tol=1e-9, max_iter=1000)
362
+ return model.fit(design, response).coef_.reshape(-1) / scale
363
+
312
364
  def refit(self, As: Union[List[np.ndarray], np.ndarray], refit_matrix_indices=None):
313
365
  """
314
- Refit parameter matrices using GLM based on current adjacency matrices.
366
+ Jointly refit eigenvalues by unpenalized linear, logistic, or Poisson regression.
315
367
 
316
368
  Parameters
317
369
  ----------
@@ -324,17 +376,21 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
324
376
  refit_matrix_indices = self._preprocess_refit_matrix_indices(refit_matrix_indices)
325
377
  if len(refit_matrix_indices) != 0:
326
378
 
327
- refit_matrix_eigvecs = [leading_left_eigenvectors(mat, k=self.max_rank,
379
+ refit_matrix_eigvecs = [leading_left_eigenvectors(mat, k=self.n_nodes_ if self.max_rank is None else self.max_rank,
328
380
  eigval_threshold=self.refit_threshold)
329
381
  for mat in self.get_all_fitted_matrices()[refit_matrix_indices]]
330
382
 
331
383
  design_mat, response, offset = self._construct_refit_design_response_and_offset(
332
384
  As=As, refit_matrix_indices=refit_matrix_indices, refit_matrix_eigvecs=refit_matrix_eigvecs)
333
385
 
334
- family = sm.families.Gaussian() if self.edge_distrib == "normal" else sm.families.Binomial()
335
- refit_model = sm.GLM(response, design_mat, family=family, offset=offset)
336
- result = refit_model.fit()
337
- refit_matrix_eigvals = result.params
386
+ sample_weight = None
387
+ sigmas = getattr(self, 'sigmas_', None)
388
+ if self.edge_distrib == 'normal' and sigmas is not None:
389
+ obs_mask = self._param_participance_masks[refit_matrix_indices].any(0)
390
+ rows, cols = np.triu_indices(self.n_nodes_, k=0 if self.loops_allowed else 1)
391
+ observed = ~np.isnan(As[obs_mask][:, rows, cols].ravel())
392
+ sample_weight = (1. / sigmas[obs_mask][:, rows, cols].ravel() ** 2)[observed]
393
+ refit_matrix_eigvals = self._fit_refit_coefficients(design_mat, response, offset, sample_weight)
338
394
 
339
395
  refitted_matrices = self._construct_refitted_matrices(refit_matrix_eigvecs, refit_matrix_eigvals)
340
396
  self._set_matrices(refitted_matrices, indices=refit_matrix_indices)
@@ -10,7 +10,7 @@ class LatentPositionGenerator:
10
10
  Generator of latent positions for MultiNeSS model.
11
11
 
12
12
  This class simulates multiple network layers that share a common latent component and
13
- layer-specific deviations. It supports normal and Bernoulli edge generation models
13
+ layer-specific deviations. It supports normal, Bernoulli, and Poisson edge models
14
14
  and can impose angle constraints between latent spaces.
15
15
 
16
16
  Parameters
@@ -19,9 +19,10 @@ class LatentPositionGenerator:
19
19
  Number of nodes in each network layer.
20
20
  n_layers : int
21
21
  Number of network layers to generate.
22
- edge_distrib : {'normal', 'bernoulli'}, default='normal'
22
+ edge_distrib : {'normal', 'bernoulli', 'poisson'}, default='normal'
23
23
  Type of edge distribution. If 'normal', edges are generated with Gaussian noise.
24
24
  If 'bernoulli', edges are drawn as Bernoulli random variables.
25
+ If 'poisson', counts are drawn with mean exp(latent parameter).
25
26
  noise_sigma : float, default=1.0
26
27
  Standard deviation of the Gaussian noise for normal-distributed edges.
27
28
  loops_allowed : bool, default=True
@@ -67,8 +68,10 @@ class LatentPositionGenerator:
67
68
  self.link_fun = lambda x: x
68
69
  elif self.edge_distrib == "bernoulli":
69
70
  self.link_fun = sigmoid
71
+ elif self.edge_distrib == 'poisson':
72
+ self.link_fun = np.exp
70
73
  else:
71
- raise NotImplementedError("Link function should be normal or bernoulli")
74
+ raise NotImplementedError("Edge distribution should be normal, bernoulli, or poisson")
72
75
 
73
76
  if isinstance(self.d_individs, (list, np.ndarray)):
74
77
  assert len(self.d_individs) == self.n_layers, \
@@ -133,11 +136,15 @@ class LatentPositionGenerator:
133
136
  elif self.edge_distrib == "bernoulli":
134
137
  A = (np.random.rand(self.n_nodes, self.n_nodes) <= P).astype(float)
135
138
  A[triu_x, triu_y] = A[triu_y, triu_x]
139
+ elif self.edge_distrib == 'poisson':
140
+ A = np.random.poisson(P)
141
+ A[triu_x, triu_y] = A[triu_y, triu_x]
136
142
  else:
137
143
  raise NotImplementedError()
138
144
 
139
145
  if not self.loops_allowed:
140
146
  np.fill_diagonal(A, 0.)
147
+ np.fill_diagonal(P, 0.)
141
148
  As.append(A)
142
149
  self.As = np.stack(As)
143
150
 
@@ -154,7 +161,7 @@ class GroupLatentPositionGenerator(LatentPositionGenerator):
154
161
  Number of network layers to generate.
155
162
  group_indices : list of int
156
163
  Group index for each layer, specifying which group latent component applies.
157
- edge_distrib : {'normal', 'bernoulli'}, default='normal'
164
+ edge_distrib : {'normal', 'bernoulli', 'poisson'}, default='normal'
158
165
  Type of edge distribution for generated networks.
159
166
  noise_sigma : float, default=1.0
160
167
  Standard deviation of Gaussian noise for normal-distributed edges.