GroupMultiNeSS 0.0.5__tar.gz → 0.0.7__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.
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/GroupMultiNeSS/base.py +87 -28
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/GroupMultiNeSS/data_generation.py +13 -6
- groupmultiness-0.0.7/GroupMultiNeSS/group_multiness.py +479 -0
- groupmultiness-0.0.7/GroupMultiNeSS/multiness.py +919 -0
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/GroupMultiNeSS/shared_space_hunting.py +2 -2
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/GroupMultiNeSS/utils.py +55 -14
- groupmultiness-0.0.7/GroupMultiNeSS.egg-info/PKG-INFO +206 -0
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/GroupMultiNeSS.egg-info/requires.txt +1 -2
- groupmultiness-0.0.7/PKG-INFO +206 -0
- groupmultiness-0.0.7/README.md +172 -0
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/setup.py +3 -4
- groupmultiness-0.0.5/GroupMultiNeSS/group_multiness.py +0 -523
- groupmultiness-0.0.5/GroupMultiNeSS/multiness.py +0 -1307
- groupmultiness-0.0.5/GroupMultiNeSS.egg-info/PKG-INFO +0 -102
- groupmultiness-0.0.5/PKG-INFO +0 -102
- groupmultiness-0.0.5/README.md +0 -68
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/GroupMultiNeSS/MASE.py +0 -0
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/GroupMultiNeSS/__init__.py +0 -0
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/GroupMultiNeSS.egg-info/SOURCES.txt +0 -0
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/GroupMultiNeSS.egg-info/dependency_links.txt +0 -0
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/GroupMultiNeSS.egg-info/top_level.txt +0 -0
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/LICENSE +0 -0
- {groupmultiness-0.0.5 → groupmultiness-0.0.7}/setup.cfg +0 -0
|
@@ -1,11 +1,13 @@
|
|
|
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
|
|
10
|
+
from sklearn.linear_model import LinearRegression, LogisticRegression, PoissonRegressor
|
|
9
11
|
|
|
10
12
|
from .utils import sigmoid, leading_left_eigenvectors
|
|
11
13
|
|
|
@@ -18,8 +20,8 @@ class SharedMemoryMatrixFitter:
|
|
|
18
20
|
which can be used for parallel computations without duplicating data.
|
|
19
21
|
"""
|
|
20
22
|
|
|
21
|
-
def _init_param_matrices(self, vals: Union[List[np.ndarray], np.ndarray] = None,
|
|
22
|
-
shape: Iterable[int] = None) -> None:
|
|
23
|
+
def _init_param_matrices(self, vals: Optional[Union[List[np.ndarray], np.ndarray]] = None,
|
|
24
|
+
shape: Optional[Iterable[int]] = None) -> None:
|
|
23
25
|
"""
|
|
24
26
|
Initialize shared memory for parameter matrices.
|
|
25
27
|
|
|
@@ -36,17 +38,32 @@ class SharedMemoryMatrixFitter:
|
|
|
36
38
|
- Allocates shared memory of type float64 for storing matrices.
|
|
37
39
|
"""
|
|
38
40
|
if shape is None:
|
|
39
|
-
assert vals is not None, "One of vals or shape arguments should
|
|
41
|
+
assert vals is not None, "One of vals or shape arguments should be provided!"
|
|
40
42
|
vals = np.array(vals)
|
|
41
43
|
shape = vals.shape
|
|
42
44
|
elif vals is not None:
|
|
43
45
|
warn("shape argument is not used as vals argument is provided!")
|
|
44
46
|
|
|
45
|
-
|
|
46
|
-
self.
|
|
47
|
+
shape = tuple(shape)
|
|
48
|
+
self.close()
|
|
49
|
+
self._param_matrices_shm = shared_memory.SharedMemory(create=True, size=int(np.prod(shape)) * 8)
|
|
47
50
|
self.param_matrices = np.ndarray(shape, dtype=np.float64, buffer=self._param_matrices_shm.buf)
|
|
48
51
|
if vals is not None:
|
|
49
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
|
|
50
67
|
|
|
51
68
|
def _set_matrix(self, val, idx):
|
|
52
69
|
"""
|
|
@@ -62,7 +79,7 @@ class SharedMemoryMatrixFitter:
|
|
|
62
79
|
param_matrices = self.get_all_fitted_matrices()
|
|
63
80
|
param_matrices[idx] = val
|
|
64
81
|
|
|
65
|
-
def _set_matrices(self, vals, indices: Union[List[int], np.ndarray] = None):
|
|
82
|
+
def _set_matrices(self, vals, indices: Optional[Union[List[int], np.ndarray]] = None):
|
|
66
83
|
"""
|
|
67
84
|
Set multiple matrices in shared memory.
|
|
68
85
|
|
|
@@ -76,7 +93,7 @@ class SharedMemoryMatrixFitter:
|
|
|
76
93
|
if indices is None:
|
|
77
94
|
indices = list(range(len(self.get_all_fitted_matrices())))
|
|
78
95
|
assert len(vals) == len(indices)
|
|
79
|
-
for idx, val in
|
|
96
|
+
for idx, val in zip(indices, vals, strict=True):
|
|
80
97
|
self._set_matrix(val, idx)
|
|
81
98
|
|
|
82
99
|
def get_all_fitted_matrices(self):
|
|
@@ -88,10 +105,13 @@ class SharedMemoryMatrixFitter:
|
|
|
88
105
|
np.ndarray
|
|
89
106
|
Array backed by shared memory containing all parameter matrices.
|
|
90
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")
|
|
91
110
|
return np.ndarray(self.param_matrices.shape, dtype=np.float64, buffer=self._param_matrices_shm.buf)
|
|
92
111
|
|
|
93
112
|
|
|
94
|
-
|
|
113
|
+
|
|
114
|
+
class BaseMultiplexNetworksModel(ABC):
|
|
95
115
|
"""
|
|
96
116
|
Base class for multiplex network models.
|
|
97
117
|
|
|
@@ -105,7 +125,7 @@ class BaseMultiplexNetworksModel:
|
|
|
105
125
|
Parameters
|
|
106
126
|
----------
|
|
107
127
|
edge_distrib : str, default='normal'
|
|
108
|
-
Type of edge distribution ('normal' or '
|
|
128
|
+
Type of edge distribution ('normal', 'bernoulli', or 'poisson').
|
|
109
129
|
loops_allowed : bool, default=True
|
|
110
130
|
Whether self-loops are allowed in adjacency matrices.
|
|
111
131
|
"""
|
|
@@ -115,10 +135,12 @@ class BaseMultiplexNetworksModel:
|
|
|
115
135
|
self.link_ = lambda x: x
|
|
116
136
|
elif edge_distrib == "bernoulli":
|
|
117
137
|
self.link_ = sigmoid
|
|
138
|
+
elif edge_distrib == "poisson":
|
|
139
|
+
self.link_ = np.exp
|
|
118
140
|
else:
|
|
119
|
-
raise NotImplementedError("Edge distribution should be
|
|
141
|
+
raise NotImplementedError("Edge distribution should be normal, bernoulli, or poisson!")
|
|
120
142
|
|
|
121
|
-
def _validate_input(self, As: List[np.
|
|
143
|
+
def _validate_input(self, As: Union[List[np.ndarray], np.ndarray]) -> np.ndarray:
|
|
122
144
|
"""
|
|
123
145
|
Validate input adjacency matrices.
|
|
124
146
|
|
|
@@ -145,8 +167,14 @@ class BaseMultiplexNetworksModel:
|
|
|
145
167
|
self.n_nodes_ = As[0].shape[0]
|
|
146
168
|
self.n_layers_ = len(As)
|
|
147
169
|
self._param_participance_masks = self._get_param_participance_masks()
|
|
148
|
-
|
|
149
|
-
|
|
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
|
|
176
|
+
|
|
177
|
+
@abstractmethod
|
|
150
178
|
def _get_param_participance_masks(self) -> np.ndarray:
|
|
151
179
|
"""
|
|
152
180
|
Return masks indicating which parameters participate in each layer.
|
|
@@ -166,7 +194,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
|
|
|
166
194
|
Base class for refitting latent matrices in multiplex network models.
|
|
167
195
|
"""
|
|
168
196
|
|
|
169
|
-
def __init__(self, edge_distrib="normal", max_rank: int = None, loops_allowed: bool = True,
|
|
197
|
+
def __init__(self, edge_distrib="normal", max_rank: Optional[int] = None, loops_allowed: bool = True,
|
|
170
198
|
refit_threshold: float = 1e-8):
|
|
171
199
|
"""
|
|
172
200
|
Initialize the BaseRefitting object.
|
|
@@ -174,7 +202,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
|
|
|
174
202
|
Parameters
|
|
175
203
|
----------
|
|
176
204
|
edge_distrib : str, default="normal"
|
|
177
|
-
Type of edge distribution ('normal' or '
|
|
205
|
+
Type of edge distribution ('normal', 'bernoulli', or 'poisson').
|
|
178
206
|
max_rank : int, optional
|
|
179
207
|
Maximum rank for eigenvector-based refitting.
|
|
180
208
|
loops_allowed : bool, default=True
|
|
@@ -224,7 +252,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
|
|
|
224
252
|
def _construct_refit_design_response_and_offset(self, As: np.ndarray, refit_matrix_indices: np.ndarray,
|
|
225
253
|
refit_matrix_eigvecs: List[np.ndarray]):
|
|
226
254
|
"""
|
|
227
|
-
Construct the design matrix, response vector, and offset for
|
|
255
|
+
Construct the design matrix, response vector, and offset for refitting.
|
|
228
256
|
|
|
229
257
|
Parameters
|
|
230
258
|
----------
|
|
@@ -238,7 +266,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
|
|
|
238
266
|
Returns
|
|
239
267
|
-------
|
|
240
268
|
tuple of np.ndarray
|
|
241
|
-
Design matrix, response vector, and offset vector for
|
|
269
|
+
Design matrix, response vector, and offset vector for regression.
|
|
242
270
|
"""
|
|
243
271
|
triu_indices = np.triu_indices(self.n_nodes_, k=0 if self.loops_allowed else 1)
|
|
244
272
|
obs_mask = self._param_participance_masks[refit_matrix_indices].any(0)
|
|
@@ -250,7 +278,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
|
|
|
250
278
|
refit_matrix_participance_masks = self._param_participance_masks[refit_matrix_indices][:, obs_mask]
|
|
251
279
|
|
|
252
280
|
design_mat = []
|
|
253
|
-
for param_design, participance_mask in
|
|
281
|
+
for param_design, participance_mask in zip(param_designs, refit_matrix_participance_masks, strict=True):
|
|
254
282
|
design_mat.append(np.vstack([param_design if participate else np.zeros_like(param_design)
|
|
255
283
|
for participate in participance_mask]))
|
|
256
284
|
|
|
@@ -267,7 +295,7 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
|
|
|
267
295
|
refit_matrix_eigvecs : list of np.ndarray
|
|
268
296
|
Eigenvectors for each refit matrix.
|
|
269
297
|
refit_matrix_eigvals : np.ndarray
|
|
270
|
-
Refitted eigenvalues from
|
|
298
|
+
Refitted eigenvalues from regression.
|
|
271
299
|
|
|
272
300
|
Returns
|
|
273
301
|
-------
|
|
@@ -306,9 +334,36 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
|
|
|
306
334
|
refit_matrix_indices)) # don't refit rank zero matrices after hard-threshold
|
|
307
335
|
return np.array(refit_matrix_indices, dtype=int)
|
|
308
336
|
|
|
309
|
-
def
|
|
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
|
+
|
|
364
|
+
def refit(self, As: Union[List[np.ndarray], np.ndarray], refit_matrix_indices=None):
|
|
310
365
|
"""
|
|
311
|
-
|
|
366
|
+
Jointly refit eigenvalues by unpenalized linear, logistic, or Poisson regression.
|
|
312
367
|
|
|
313
368
|
Parameters
|
|
314
369
|
----------
|
|
@@ -321,17 +376,21 @@ class BaseRefitting(BaseMultiplexNetworksModel, SharedMemoryMatrixFitter):
|
|
|
321
376
|
refit_matrix_indices = self._preprocess_refit_matrix_indices(refit_matrix_indices)
|
|
322
377
|
if len(refit_matrix_indices) != 0:
|
|
323
378
|
|
|
324
|
-
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,
|
|
325
380
|
eigval_threshold=self.refit_threshold)
|
|
326
381
|
for mat in self.get_all_fitted_matrices()[refit_matrix_indices]]
|
|
327
382
|
|
|
328
383
|
design_mat, response, offset = self._construct_refit_design_response_and_offset(
|
|
329
384
|
As=As, refit_matrix_indices=refit_matrix_indices, refit_matrix_eigvecs=refit_matrix_eigvecs)
|
|
330
385
|
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
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)
|
|
335
394
|
|
|
336
395
|
refitted_matrices = self._construct_refitted_matrices(refit_matrix_eigvecs, refit_matrix_eigvals)
|
|
337
396
|
self._set_matrices(refitted_matrices, indices=refit_matrix_indices)
|
|
@@ -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
|
|
@@ -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
|
|
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
|
|
@@ -47,7 +48,7 @@ class LatentPositionGenerator:
|
|
|
47
48
|
d_individs: Union[List, int] = 2,
|
|
48
49
|
s_vu: float = 0.,
|
|
49
50
|
s_uu: float = 0.,
|
|
50
|
-
comps_max_cosine_mat: np.
|
|
51
|
+
comps_max_cosine_mat: Optional[np.ndarray] = None,
|
|
51
52
|
min_V_max_U_eigval_ratio=None):
|
|
52
53
|
|
|
53
54
|
self.n_nodes = n_nodes
|
|
@@ -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("
|
|
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.
|