isac 0.1.0__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.
- isac-0.1.0/LICENSE +7 -0
- isac-0.1.0/PKG-INFO +27 -0
- isac-0.1.0/README.md +11 -0
- isac-0.1.0/pyproject.toml +25 -0
- isac-0.1.0/setup.cfg +4 -0
- isac-0.1.0/src/isac/__init__.py +1 -0
- isac-0.1.0/src/isac/core.py +270 -0
- isac-0.1.0/src/isac/helpers.py +514 -0
- isac-0.1.0/src/isac.egg-info/PKG-INFO +27 -0
- isac-0.1.0/src/isac.egg-info/SOURCES.txt +11 -0
- isac-0.1.0/src/isac.egg-info/dependency_links.txt +1 -0
- isac-0.1.0/src/isac.egg-info/requires.txt +2 -0
- isac-0.1.0/src/isac.egg-info/top_level.txt +1 -0
isac-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
Copyright © 2026 by Pietro Bozzo
|
|
3
|
+
|
|
4
|
+
This program is free software: you can redistribute it and/or modify
|
|
5
|
+
it under the terms of the GNU General Public License as published by
|
|
6
|
+
the Free Software Foundation, either version 3 of the License, or
|
|
7
|
+
(at your option) any later version.
|
isac-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: isac
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python port of ISAC
|
|
5
|
+
Author: Pietro Bozzo
|
|
6
|
+
License-Expression: GPL-3.0-or-later
|
|
7
|
+
Project-URL: Homepage, https://github.com/mnpompili/ISAC
|
|
8
|
+
Project-URL: Repository, https://github.com/mnpompili/ISAC
|
|
9
|
+
Project-URL: Issues, https://github.com/mnpompili/ISAC/issues
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: numba
|
|
14
|
+
Requires-Dist: numpy
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# ISAC (Python Port)
|
|
18
|
+
|
|
19
|
+
This is a Python port of ISAC.
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
This package is distributed via PyPI and can be installed, for example, with pip:
|
|
24
|
+
```
|
|
25
|
+
# e.g., on Linux
|
|
26
|
+
$ pip install isac # install isac in currently active python environment
|
|
27
|
+
```
|
isac-0.1.0/README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# ISAC (Python Port)
|
|
2
|
+
|
|
3
|
+
This is a Python port of ISAC.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
This package is distributed via PyPI and can be installed, for example, with pip:
|
|
8
|
+
```
|
|
9
|
+
# e.g., on Linux
|
|
10
|
+
$ pip install isac # install isac in currently active python environment
|
|
11
|
+
```
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "isac"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python port of ISAC"
|
|
9
|
+
authors = [{name = "Pietro Bozzo"}]
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
license = "GPL-3.0-or-later"
|
|
12
|
+
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
dependencies = [
|
|
15
|
+
"numba",
|
|
16
|
+
"numpy",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Homepage = "https://github.com/mnpompili/ISAC"
|
|
21
|
+
Repository = "https://github.com/mnpompili/ISAC"
|
|
22
|
+
Issues = "https://github.com/mnpompili/ISAC/issues"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.packages.find]
|
|
25
|
+
where = ["src"]
|
isac-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .core import *
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import scipy.stats
|
|
2
|
+
from .helpers import *
|
|
3
|
+
__all__ = ["isac","compile_numba"]
|
|
4
|
+
|
|
5
|
+
def isac(spikes, window:float, threshold=None, n_min:int=None, max_size:int=None, min_size:int=None,
|
|
6
|
+
constraints=None, chunk_size:int=None, verbose:bool=True):
|
|
7
|
+
"""Find groups of neurons that tend to fire together, assemblies
|
|
8
|
+
|
|
9
|
+
Every triplet of neurons is tested first, valid groups are then extended one unit
|
|
10
|
+
at a time, and each extended group is re-confirmed for all of its members
|
|
11
|
+
|
|
12
|
+
Parameters
|
|
13
|
+
----------
|
|
14
|
+
spikes : array_like, shape (n_spikes, 2)
|
|
15
|
+
Columns are [timestamp, unit_id]. Unit ids are positive integers
|
|
16
|
+
(1-based). Ids with no spikes are kept as silent units.
|
|
17
|
+
window : float
|
|
18
|
+
Assembly timescale: the largest time span allowed between the
|
|
19
|
+
spikes of an assembly for them to count as one activation.
|
|
20
|
+
threshold : float or (float, float), optional
|
|
21
|
+
Z-score cutoff(s). Default: 2.5758 (two-sided 1%, equal to
|
|
22
|
+
sqrt(2) * erfcinv(0.01) in MATLAB). A scalar is used for both
|
|
23
|
+
criteria. With two values, the first is the "affinity" criterion
|
|
24
|
+
(the unit fires more within the assembly's activations than the
|
|
25
|
+
non-member population does) and the second is the "unity" criterion
|
|
26
|
+
(the unit fires more within complete activations than within
|
|
27
|
+
activations missing one member).
|
|
28
|
+
n_min : int, optional
|
|
29
|
+
Minimum number of activations a group needs to be tested for extension. Default: 1.
|
|
30
|
+
max_size : int, optional
|
|
31
|
+
Largest number of units allowed in an assembly. Default: the number of units.
|
|
32
|
+
min_size : int, optional
|
|
33
|
+
Smallest number of units an assembly must have to be returned. Default: 3.
|
|
34
|
+
group_id : array_like of int, shape (n_units,), optional
|
|
35
|
+
Group label for each unit (e.g., cell type or region). Default: all units in group 1. IMPLEMENT
|
|
36
|
+
constraints : list of array_like, optional
|
|
37
|
+
Group constraints for the assemblies to look for. `[[2]]` means
|
|
38
|
+
at least one member from group 2, `[[1, 2, 3]]` means members from
|
|
39
|
+
groups 1, 2 and 3 together, and `[[1, 2], [4]]` combines both
|
|
40
|
+
requirements. Default: none. IMPLEMENT
|
|
41
|
+
verbose : bool, optional
|
|
42
|
+
Print progress messages. Default: False.
|
|
43
|
+
|
|
44
|
+
Returns
|
|
45
|
+
-------
|
|
46
|
+
assemblies : ndarray of bool, shape (n_assemblies, n_units)
|
|
47
|
+
One row per assembly, one column per unit. Column k corresponds to
|
|
48
|
+
unit id k + 1. Rows are sorted lexicographically. Assemblies
|
|
49
|
+
contained in a larger assembly are removed.
|
|
50
|
+
|
|
51
|
+
Notes
|
|
52
|
+
-----
|
|
53
|
+
The z-values are scores from a pooled two-proportion test on clustered and paired spike counts.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
spikes = np.asarray(spikes, dtype=float).copy()
|
|
57
|
+
spikes = spikes[np.lexsort((spikes[:,1], spikes[:,0]))] # sort by time, then by id
|
|
58
|
+
times = np.ascontiguousarray(spikes[:,0])
|
|
59
|
+
units = spikes[:,1].astype(int) - 1 # 0-based ids from here on
|
|
60
|
+
n_units = units.max() + 1
|
|
61
|
+
order = np.argsort(units, kind="stable") # group by unit, keep time order
|
|
62
|
+
flat_times = times[order] # each unit's spikes back to back, sorted
|
|
63
|
+
n_spikes = np.bincount(units, minlength=n_units) # n spikes per unit
|
|
64
|
+
offsets = np.zeros(n_units + 1, dtype=np.int64)
|
|
65
|
+
np.cumsum(n_spikes, out=offsets[1:]) # unit u's spike times: flat_times[offsets[u]:offsets[u+1]]
|
|
66
|
+
|
|
67
|
+
# defaults
|
|
68
|
+
if threshold is None: threshold = (scipy.stats.norm.isf(0.005),) * 2
|
|
69
|
+
threshold = np.array(threshold, ndmin=1, dtype=float)
|
|
70
|
+
if threshold.size == 1: threshold = np.full(2, threshold[0])
|
|
71
|
+
if n_min is None: n_min = 1
|
|
72
|
+
if max_size is None: max_size = n_units
|
|
73
|
+
if min_size is None: min_size = 3
|
|
74
|
+
if chunk_size is None: chunk_size = 10000
|
|
75
|
+
n_min = int(n_min); max_size = int(max_size); min_size = int(min_size); chunk_size = int(chunk_size)
|
|
76
|
+
|
|
77
|
+
# start with all pairs
|
|
78
|
+
pairs = np.array(list(itertools.combinations(range(n_units), 2)), dtype=int).reshape(-1, 2)
|
|
79
|
+
l_array = np.zeros((len(pairs), n_units), dtype=bool)
|
|
80
|
+
rows = np.arange(len(pairs))
|
|
81
|
+
l_array[rows, pairs[:,0]] = True
|
|
82
|
+
l_array[rows, pairs[:,1]] = True
|
|
83
|
+
|
|
84
|
+
final = []
|
|
85
|
+
for cycle in range(1, max_size - 1):
|
|
86
|
+
if l_array.shape[0] == 0:
|
|
87
|
+
break
|
|
88
|
+
verbose and print(f"Cycle {cycle}...")
|
|
89
|
+
|
|
90
|
+
l_array0 = l_array
|
|
91
|
+
n_previous = l_array0.shape[0]
|
|
92
|
+
|
|
93
|
+
# 1. find units to skip for each parent assembly
|
|
94
|
+
if cycle == 1:
|
|
95
|
+
#if constraints is not None and len(constraints) > 0:
|
|
96
|
+
# skip_list = [np.array([], dtype=int)] * n_previous
|
|
97
|
+
#else:
|
|
98
|
+
# # only test units with index > max(members) THIS LIST MAYBE CONTAINS MEMBERS AS WELL FOR NO REASON
|
|
99
|
+
skip_list = [np.arange(np.flatnonzero(r).max() + 1) for r in l_array0]
|
|
100
|
+
else:
|
|
101
|
+
skip_list = skip_duplicate_extensions(l_array0)
|
|
102
|
+
|
|
103
|
+
# 2. candidate assemblies to be extended
|
|
104
|
+
verbose and print(f" testing {n_previous} candidates for extension")
|
|
105
|
+
members = np.nonzero(l_array0)[1].reshape(-1, cycle + 1)
|
|
106
|
+
assembly_id, neuron_id = extend_assemblies(members, skip_list, times, units, flat_times,
|
|
107
|
+
offsets, n_spikes, window, threshold, n_min, chunk_size)
|
|
108
|
+
n_candidates = assembly_id.size
|
|
109
|
+
|
|
110
|
+
# 3. confirm extensions
|
|
111
|
+
verbose and print(f" confirming {n_previous} assemblies")
|
|
112
|
+
if n_candidates > 0:
|
|
113
|
+
l_array = l_array0[assembly_id].copy()
|
|
114
|
+
l_array[np.arange(n_candidates), neuron_id] = True
|
|
115
|
+
passes = confirm_assemblies(members, assembly_id, neuron_id, times, units, flat_times,
|
|
116
|
+
offsets, n_spikes, window, threshold)
|
|
117
|
+
l_array = l_array[passes]
|
|
118
|
+
no_branches = np.bincount(assembly_id, weights=passes, minlength=n_previous) == 0
|
|
119
|
+
else:
|
|
120
|
+
l_array = np.zeros((0, n_units), dtype=bool)
|
|
121
|
+
no_branches = np.ones(n_previous, dtype=bool)
|
|
122
|
+
|
|
123
|
+
# store confirmed assemblies
|
|
124
|
+
final.append(l_array0[no_branches].copy())
|
|
125
|
+
l_array = unique_rows_stable(l_array)
|
|
126
|
+
if cycle == max_size - 2:
|
|
127
|
+
final.append(l_array.copy())
|
|
128
|
+
|
|
129
|
+
# filter by 'min_size', unique and sorted
|
|
130
|
+
assemblies = np.vstack(final)
|
|
131
|
+
assemblies = assemblies[assemblies.sum(axis=1) >= min_size]
|
|
132
|
+
if assemblies.shape[0] == 0:
|
|
133
|
+
return assemblies
|
|
134
|
+
assemblies = np.unique(assemblies.astype(np.uint8), axis=0).astype(bool)
|
|
135
|
+
|
|
136
|
+
# drop assemblies fully contained in a bigger one
|
|
137
|
+
a = assemblies.astype(np.float32)
|
|
138
|
+
commons = a @ a.T # pairwise overlap counts
|
|
139
|
+
np.fill_diagonal(commons, 0)
|
|
140
|
+
num_neurons = assemblies.sum(axis=1)
|
|
141
|
+
is_included = commons == num_neurons[:,None] # row i contained in col j
|
|
142
|
+
assemblies = assemblies[~is_included.any(axis=1)]
|
|
143
|
+
|
|
144
|
+
return assemblies
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def defragment(orig_assemblies, spikes, window, threshold=np.inf, n_min=0, verbose=False, tolerance=0.0):
|
|
148
|
+
"""Merge overlapping assemblies into larger ones (port of DefragmentSAC).
|
|
149
|
+
|
|
150
|
+
orig_assemblies : bool (n_assemblies, n_units)
|
|
151
|
+
threshold : -inf skips the RateSSA test; default inf as in MATLAB
|
|
152
|
+
tolerance : fraction of missing 3-member sub-assemblies allowed
|
|
153
|
+
Returns (assemblies, triplets), both bool matrices.
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
from_prepare = prepare_inputs(spikes, window) # spike layout for rate_ssa
|
|
157
|
+
A = np.asarray(orig_assemblies, dtype=bool)
|
|
158
|
+
if A.shape[0] == 0:
|
|
159
|
+
return A, np.zeros((0, A.shape[1]), dtype=bool)
|
|
160
|
+
n_units = A.shape[1]
|
|
161
|
+
if from_prepare.n_units != n_units:
|
|
162
|
+
raise ValueError("orig_assemblies columns must equal the number of units")
|
|
163
|
+
if n_units ** 3 >= 2 ** 63:
|
|
164
|
+
raise ValueError("too many units for int64 triplet keys")
|
|
165
|
+
P, tol = from_prepare, float(tolerance)
|
|
166
|
+
|
|
167
|
+
# t0 = time.perf_counter()
|
|
168
|
+
# def log(msg):
|
|
169
|
+
# if verbose:
|
|
170
|
+
# print(f"[{time.perf_counter() - t0:7.1f}s] {msg}")
|
|
171
|
+
|
|
172
|
+
# ---- split every assembly into its smallest-size constituents
|
|
173
|
+
sizes = A.sum(axis=1)
|
|
174
|
+
cs0, max_size = int(sizes.min()), int(sizes.max())
|
|
175
|
+
pieces = []
|
|
176
|
+
for s in range(cs0, max_size + 1):
|
|
177
|
+
rows = A[sizes == s]
|
|
178
|
+
if rows.shape[0] == 0:
|
|
179
|
+
continue
|
|
180
|
+
mem = np.nonzero(rows)[1].reshape(-1, s).astype(np.int64)
|
|
181
|
+
if s > cs0:
|
|
182
|
+
ci = np.array(list(itertools.combinations(range(s), cs0)),
|
|
183
|
+
dtype=np.int64)
|
|
184
|
+
mem = unique_rows(mem[:, ci].reshape(-1, cs0))
|
|
185
|
+
pieces.append(mem)
|
|
186
|
+
cur = unique_rows(np.concatenate(pieces))
|
|
187
|
+
triplets = to_bool(cur, n_units)
|
|
188
|
+
# log(f"{cur.shape[0]} {cs0}-member fragments after splitting")
|
|
189
|
+
|
|
190
|
+
if cs0 == 3:
|
|
191
|
+
N = np.int64(n_units)
|
|
192
|
+
tri_keys = np.sort((cur[:, 0] * N + cur[:, 1]) * N + cur[:, 2])
|
|
193
|
+
else:
|
|
194
|
+
tri_keys = np.empty(0, dtype=np.int64) # MATLAB can never match here
|
|
195
|
+
print(f"WARNING: smallest assemblies have {cs0} members, not 3; the "
|
|
196
|
+
"3-member clique test cannot match (as in the MATLAB)")
|
|
197
|
+
|
|
198
|
+
set_aside = {}
|
|
199
|
+
for cs in range(cs0, 101):
|
|
200
|
+
assemblies = cur
|
|
201
|
+
set_aside[cs] = assemblies
|
|
202
|
+
# log(f"{cs}-member: {assemblies.shape[0]} assemblies")
|
|
203
|
+
if assemblies.shape[0] < 2: # one assembly left, done
|
|
204
|
+
break
|
|
205
|
+
|
|
206
|
+
cand, nonext = prune(assemblies, n_units, cs, tol > 0)
|
|
207
|
+
if cand.shape[0] == 0:
|
|
208
|
+
break
|
|
209
|
+
|
|
210
|
+
combos, hits = find_cliques(cand, n_units, cs, tri_keys, tol)
|
|
211
|
+
if tol > 0 and combos.shape[0]:
|
|
212
|
+
combos, idx = unique_rows(combos, return_index=True)
|
|
213
|
+
hits = [hits[i] for i in idx]
|
|
214
|
+
# log(f"{combos.shape[0]} candidate {cs + 1}-member cliques")
|
|
215
|
+
|
|
216
|
+
if threshold == -np.inf:
|
|
217
|
+
passed = np.ones(combos.shape[0], dtype=bool)
|
|
218
|
+
elif combos.shape[0] == 0:
|
|
219
|
+
passed = np.zeros(0, dtype=bool)
|
|
220
|
+
else:
|
|
221
|
+
uc, inv = unique_rows(combos, return_inverse=True) # test each row once
|
|
222
|
+
pass_u = np.fromiter(
|
|
223
|
+
(rate_ssa(r, P, window, threshold, n_min) for r in uc),
|
|
224
|
+
dtype=bool, count=uc.shape[0])
|
|
225
|
+
passed = pass_u[inv]
|
|
226
|
+
|
|
227
|
+
keep = np.ones(cand.shape[0], dtype=bool)
|
|
228
|
+
if passed.any():
|
|
229
|
+
keep[np.concatenate([h for h, p in zip(hits, passed) if p])] = False
|
|
230
|
+
new = combos[passed]
|
|
231
|
+
set_aside[cs] = np.concatenate([cand[keep], *nonext])
|
|
232
|
+
# log(f"{new.shape[0]} cliques passed; {set_aside[cs].shape[0]} set aside")
|
|
233
|
+
if new.shape[0] == 0:
|
|
234
|
+
break
|
|
235
|
+
cur = new
|
|
236
|
+
|
|
237
|
+
blocks = [to_bool(set_aside[c], n_units)
|
|
238
|
+
for c in sorted(set_aside) if set_aside[c].shape[0]]
|
|
239
|
+
return merge_assemblies(np.concatenate(blocks)), triplets
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def compile_numba():
|
|
243
|
+
|
|
244
|
+
# tiny dataset: 3 units, a few spikes each (sorted by time, then id)
|
|
245
|
+
times = np.array([0.10, 0.11, 0.12, 0.50, 0.51, 0.52], dtype=np.float64)
|
|
246
|
+
units = np.array([0, 1, 2, 0, 1, 2], dtype=np.int64)
|
|
247
|
+
n_units = 3; window = 0.05; threshold = np.array([2.0, 2.0]); n_min = 3
|
|
248
|
+
|
|
249
|
+
order = np.argsort(units, kind="stable")
|
|
250
|
+
flat_times = times[order]
|
|
251
|
+
n_spikes = np.bincount(units, minlength=n_units)
|
|
252
|
+
offsets = np.zeros(n_units + 1, dtype=np.int64)
|
|
253
|
+
np.cumsum(n_spikes, out=offsets[1:])
|
|
254
|
+
|
|
255
|
+
# 1. extension
|
|
256
|
+
members_2d = np.arange(2, dtype=np.int64)[None,:]
|
|
257
|
+
skip_ptr = np.zeros(2, dtype=np.int64)
|
|
258
|
+
skip_idx = np.zeros(0, dtype=np.int64)
|
|
259
|
+
z = np.empty((1, n_units))
|
|
260
|
+
extend_parallel(times, units, flat_times, offsets, n_spikes, members_2d,
|
|
261
|
+
skip_ptr, skip_idx, window, threshold[0], n_min, z)
|
|
262
|
+
|
|
263
|
+
# 2. confirmation
|
|
264
|
+
assembly_id = [0]; neuron_id = np.array([2])
|
|
265
|
+
cand = np.ascontiguousarray(np.concatenate([members_2d[assembly_id], neuron_id[:,None]], axis=1))
|
|
266
|
+
passes = np.empty(cand.shape[0], dtype=np.bool_)
|
|
267
|
+
confirm_parallel(times, units, flat_times, offsets, n_spikes, cand,
|
|
268
|
+
neuron_id.astype(np.int64), window, threshold[0], threshold[1], False, passes)
|
|
269
|
+
|
|
270
|
+
return
|
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import itertools
|
|
3
|
+
from numba import njit, prange
|
|
4
|
+
|
|
5
|
+
def skip_duplicate_extensions(l_array0):
|
|
6
|
+
"""for each parent assembly, find units whose addition would create the same candidate as an earlier parent"""
|
|
7
|
+
n_units = l_array0.shape[1]
|
|
8
|
+
seen = set()
|
|
9
|
+
skip = []
|
|
10
|
+
for row in l_array0:
|
|
11
|
+
# encode members as logical array
|
|
12
|
+
base = 0
|
|
13
|
+
for m in np.flatnonzero(row):
|
|
14
|
+
base |= 1 << int(m)
|
|
15
|
+
# encode all possible extensions (addition of 1 member), store duplicates in skip
|
|
16
|
+
dup = []
|
|
17
|
+
for n in range(n_units):
|
|
18
|
+
if row[n]:
|
|
19
|
+
continue
|
|
20
|
+
key = base | (1 << n)
|
|
21
|
+
if key in seen:
|
|
22
|
+
dup.append(n)
|
|
23
|
+
else:
|
|
24
|
+
seen.add(key)
|
|
25
|
+
skip.append(np.array(dup, dtype=int))
|
|
26
|
+
return skip
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def unique_rows_stable(a):
|
|
30
|
+
"""equivalent of MATLAB unique(a, 'rows', 'stable')."""
|
|
31
|
+
if a.shape[0] == 0:
|
|
32
|
+
return a
|
|
33
|
+
_, idx = np.unique(a.astype(np.uint8), axis=0, return_index=True)
|
|
34
|
+
return a[np.sort(idx)]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def unique_rows(a, return_index=False, return_inverse=False):
|
|
38
|
+
"""unique(a,'rows') for equal-size sorted index rows, in the order MATLAB
|
|
39
|
+
gives for the equivalent logical matrix (= descending tuple order)."""
|
|
40
|
+
res = np.unique(a, axis=0, return_index=True, return_inverse=return_inverse)
|
|
41
|
+
u, idx = res[0][::-1], res[1][::-1]
|
|
42
|
+
if return_inverse:
|
|
43
|
+
inv = np.asarray(res[2]).reshape(-1)
|
|
44
|
+
inv = (u.shape[0] - 1) - inv # position after reversal
|
|
45
|
+
return (u, idx, inv) if return_index else (u, inv)
|
|
46
|
+
return (u, idx) if return_index else u
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def to_bool(members, n_units):
|
|
50
|
+
out = np.zeros((members.shape[0], n_units), dtype=bool)
|
|
51
|
+
out[np.arange(members.shape[0])[:,None], members] = True
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
# --- extension ---
|
|
55
|
+
|
|
56
|
+
def extend_assemblies(mem, skip, t, u, flat, offsets, n_spikes, w, thr, n_min, chunk):
|
|
57
|
+
"""thr = (thr0, thr1). Returns parent_ids, unit_ids with z >= thr1."""
|
|
58
|
+
n_units = len(n_spikes); n_prev = mem.shape[0]
|
|
59
|
+
mem = np.ascontiguousarray(mem, dtype=np.int64)
|
|
60
|
+
parents = []; units_out = []
|
|
61
|
+
for a in range(0, n_prev, chunk):
|
|
62
|
+
b = min(a + chunk, n_prev)
|
|
63
|
+
lens = np.fromiter((len(skip[i]) for i in range(a, b)), np.int64, b - a)
|
|
64
|
+
ptr = np.zeros(b - a + 1, dtype=np.int64)
|
|
65
|
+
np.cumsum(lens, out=ptr[1:])
|
|
66
|
+
idx = np.concatenate([skip[i] for i in range(a, b)]).astype(np.int64)
|
|
67
|
+
z = np.empty((b - a, n_units))
|
|
68
|
+
extend_parallel(t, u, flat, offsets, n_spikes, mem[a:b], ptr, idx, w, float(thr[0]), n_min, z)
|
|
69
|
+
with np.errstate(invalid="ignore"):
|
|
70
|
+
r, c = np.nonzero(z >= thr[1])
|
|
71
|
+
parents.append(r + a)
|
|
72
|
+
units_out.append(c)
|
|
73
|
+
parents = np.concatenate(parents)
|
|
74
|
+
units_out = np.concatenate(units_out)
|
|
75
|
+
order = np.lexsort((parents, units_out)) # reproduce MATLAB's column-major order
|
|
76
|
+
return parents[order], units_out[order]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@njit(cache=True, parallel=True, error_model="numpy")
|
|
80
|
+
def extend_parallel(times, units, flat_times, offsets, n_spikes, members_2d,
|
|
81
|
+
skip_ptr, skip_idx, w, thr0, n_min, z_out):
|
|
82
|
+
"""members_2d: (n, k) sorted rows. z_out: (n, n_units) float64."""
|
|
83
|
+
"""
|
|
84
|
+
times: all spike times, sorted. units: 0-based unit id per spike.
|
|
85
|
+
n_spikes: n spikes per unit. members, skip: 0-based unit indices.
|
|
86
|
+
Returns z (n_units,), NaN where not tested or criterion 1 failed.
|
|
87
|
+
"""
|
|
88
|
+
for i in prange(members_2d.shape[0]):
|
|
89
|
+
_extend_one(times, units, flat_times, offsets, n_spikes,
|
|
90
|
+
members_2d[i], skip_idx[skip_ptr[i]:skip_ptr[i + 1]],
|
|
91
|
+
w, thr0, n_min, z_out[i])
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@njit(cache=True, nogil=True, error_model="numpy")
|
|
95
|
+
def _extend_one(times, units, flat_times, offsets, n_spikes, members,
|
|
96
|
+
skip, w, thr0, n_min, out):
|
|
97
|
+
n_units = n_spikes.shape[0]
|
|
98
|
+
n_members = members.shape[0]
|
|
99
|
+
out[:] = np.nan
|
|
100
|
+
|
|
101
|
+
# assembly activations
|
|
102
|
+
stimes, scodes = _stream(flat_times, offsets, members, -1, -1)
|
|
103
|
+
starts, ends, duration = _profile(stimes, scodes, n_members, w, False)
|
|
104
|
+
if starts.shape[0] < n_min: # min number of assembly activations
|
|
105
|
+
return
|
|
106
|
+
counts = _grouped_coverage(times, units, starts, ends, n_units) # n spikes in activations per unit
|
|
107
|
+
|
|
108
|
+
# define candidates
|
|
109
|
+
is_member = np.zeros(n_units, np.bool_)
|
|
110
|
+
for m in members:
|
|
111
|
+
is_member[m] = True
|
|
112
|
+
n_nonmember = 0.0 # total n nonmember spikes
|
|
113
|
+
count_nonmember = 0.0 # n nonmember spikes inside act
|
|
114
|
+
can = np.zeros(n_units, np.bool_)
|
|
115
|
+
for u in range(n_units):
|
|
116
|
+
if not is_member[u]:
|
|
117
|
+
n_nonmember += n_spikes[u]
|
|
118
|
+
count_nonmember += counts[u]
|
|
119
|
+
can[u] = n_spikes[u] > 0
|
|
120
|
+
for u in skip:
|
|
121
|
+
can[u] = False
|
|
122
|
+
|
|
123
|
+
# criterion 1: p spike_i > p spikes_nonmembers inside activity windows
|
|
124
|
+
candidates = np.empty(n_units, np.int64)
|
|
125
|
+
n_candidates = 0
|
|
126
|
+
for u in range(n_units):
|
|
127
|
+
if can[u]:
|
|
128
|
+
z0 = _z_test(float(counts[u]), float(n_spikes[u]), count_nonmember, n_nonmember)
|
|
129
|
+
if z0 > thr0: # NaN -> False
|
|
130
|
+
candidates[n_candidates] = u
|
|
131
|
+
n_candidates += 1
|
|
132
|
+
if n_candidates == 0:
|
|
133
|
+
return
|
|
134
|
+
|
|
135
|
+
# criterion 2: p spike_i in activity > than in incomplete activities (sub-assemblies)
|
|
136
|
+
z1 = np.full((n_candidates, n_members), np.nan)
|
|
137
|
+
for without in range(n_members):
|
|
138
|
+
# incomplete activations (one member removed at a time)
|
|
139
|
+
stimes_inc, scodes_inc = _stream(flat_times, offsets, members, without, -1)
|
|
140
|
+
s, e, d = _profile(stimes_inc, scodes_inc, n_members - 1, w, True)
|
|
141
|
+
counts_inc = _grouped_coverage(times, units, s, e, n_units)
|
|
142
|
+
for ci in range(n_candidates):
|
|
143
|
+
u = candidates[ci]
|
|
144
|
+
c_inc = counts_inc[u] / d * duration # normalize for duration: make incomplete and complete counts comparable
|
|
145
|
+
z1[ci, without] = _z_test(float(counts[u]), float(n_spikes[u]), c_inc, float(n_spikes[u])) # chi-square test
|
|
146
|
+
|
|
147
|
+
for ci in range(n_candidates): # NaN-ignoring min, NaN if all NaN
|
|
148
|
+
best = np.nan
|
|
149
|
+
for without in range(n_members):
|
|
150
|
+
v = z1[ci, without]
|
|
151
|
+
if v == v and (best != best or v < best):
|
|
152
|
+
best = v
|
|
153
|
+
out[candidates[ci]] = best
|
|
154
|
+
|
|
155
|
+
# --- confirmation ---
|
|
156
|
+
|
|
157
|
+
def confirm_assemblies(members, assembly_id, neuron_id, t, u, flat_t, offsets, n_spikes, w, thr):
|
|
158
|
+
cand = np.concatenate([members[assembly_id], neuron_id[:,None]], axis=1) # rows: assemblies to confirm
|
|
159
|
+
passes = np.empty(cand.shape[0], dtype=np.bool_)
|
|
160
|
+
confirm_parallel(t, u, flat_t, offsets, n_spikes, np.ascontiguousarray(cand, dtype=np.int64),
|
|
161
|
+
neuron_id.astype(np.int64), w, float(thr[0]), float(thr[1]), False, passes)
|
|
162
|
+
return passes
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@njit(cache=True, parallel=True, error_model="numpy")
|
|
166
|
+
def confirm_parallel(times, units, flat_times, offsets, n_spikes, cand_members,
|
|
167
|
+
new_units, w, thr0, thr1, nan_fails, passes):
|
|
168
|
+
"""cand_members: (n, k+1) sorted rows. new_units: (n,) unit ids.
|
|
169
|
+
passes: (n,) bool output."""
|
|
170
|
+
for i in prange(cand_members.shape[0]):
|
|
171
|
+
passes[i] = _confirm_one(times, units, flat_times, offsets, n_spikes,
|
|
172
|
+
cand_members[i], new_units[i], w,
|
|
173
|
+
thr0, thr1, nan_fails)
|
|
174
|
+
|
|
175
|
+
@njit(cache=True, nogil=True, error_model="numpy")
|
|
176
|
+
def _confirm_one(times, units, flat_times, offsets, n_spikes, members,
|
|
177
|
+
new_unit, w, thr0, thr1, nan_fails):
|
|
178
|
+
"""members: sorted unit ids (size >= 3). new_unit: unit id to skip."""
|
|
179
|
+
n_units = n_spikes.shape[0]
|
|
180
|
+
n_members = members.shape[0]
|
|
181
|
+
n_others = n_members - 1
|
|
182
|
+
for jp in range(n_members):
|
|
183
|
+
j = members[jp]
|
|
184
|
+
if j == new_unit:
|
|
185
|
+
continue
|
|
186
|
+
|
|
187
|
+
# complete activations of the other members (no zero patch, as in MATLAB)
|
|
188
|
+
st, sc = _stream(flat_times, offsets, members, jp, -1)
|
|
189
|
+
starts, ends, dur = _profile(st, sc, n_others, w, False)
|
|
190
|
+
counts = _grouped_coverage(times, units, starts, ends, n_units)
|
|
191
|
+
|
|
192
|
+
g = 0.0
|
|
193
|
+
for u in range(n_units):
|
|
194
|
+
g += counts[u]
|
|
195
|
+
n_non = float(times.shape[0])
|
|
196
|
+
for t in range(n_members):
|
|
197
|
+
if t != jp:
|
|
198
|
+
g -= counts[members[t]]
|
|
199
|
+
n_non -= n_spikes[members[t]]
|
|
200
|
+
count = float(counts[j])
|
|
201
|
+
nj = float(n_spikes[j])
|
|
202
|
+
|
|
203
|
+
# criterion 1 (non-members include j itself, as in MATLAB)
|
|
204
|
+
z1 = _z_test(count, nj, g, n_non)
|
|
205
|
+
if z1 < thr0 or (nan_fails and z1 != z1):
|
|
206
|
+
return False
|
|
207
|
+
|
|
208
|
+
# criterion 2: remove one more member at a time
|
|
209
|
+
for wo in range(n_others):
|
|
210
|
+
pos = wo if wo < jp else wo + 1 # position in `members`
|
|
211
|
+
st2, sc2 = _stream(flat_times, offsets, members, jp, pos)
|
|
212
|
+
s2, e2, d2 = _profile(st2, sc2, n_others - 1, w, True)
|
|
213
|
+
c = _count_unit(flat_times, offsets[j], offsets[j + 1], s2, e2)
|
|
214
|
+
c_inc = c / d2 * dur
|
|
215
|
+
z2 = _z_test(count, nj, c_inc, nj)
|
|
216
|
+
if z2 < thr1 or (nan_fails and z2 != z2):
|
|
217
|
+
return False
|
|
218
|
+
return True
|
|
219
|
+
|
|
220
|
+
# --- defragmentation ---
|
|
221
|
+
|
|
222
|
+
def prune(assemblies, n_units, cs, relaxed):
|
|
223
|
+
"""Repeat the two 'non-extendable' removals until nothing changes.
|
|
224
|
+
Returns (candidates, list of removed blocks in MATLAB's append order)."""
|
|
225
|
+
cand, nonext = assemblies, []
|
|
226
|
+
while True:
|
|
227
|
+
n0 = cand.shape[0]
|
|
228
|
+
if n0 > 1: # MATLAB: NaN max for a lone row
|
|
229
|
+
drop = ~_has_partner(cand, n_units)
|
|
230
|
+
nonext.append(cand[drop])
|
|
231
|
+
cand = cand[~drop]
|
|
232
|
+
cnt = np.bincount(cand.ravel(), minlength=n_units)
|
|
233
|
+
possible = cnt >= cs - int(relaxed)
|
|
234
|
+
bad = ~possible[cand].all(axis=1)
|
|
235
|
+
nonext.append(cand[bad])
|
|
236
|
+
cand = cand[~bad]
|
|
237
|
+
if cand.shape[0] == n0 or cand.shape[0] == 0:
|
|
238
|
+
return cand, nonext
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def find_cliques(cand, n_units, cs, tri_keys, tol):
|
|
242
|
+
"""Port of the `for j` loop. Returns (combos (n, cs+1), hits list)."""
|
|
243
|
+
m = cand.shape[0]
|
|
244
|
+
flat = cand.ravel()
|
|
245
|
+
order = np.argsort(flat, kind="stable")
|
|
246
|
+
inv_rows = order // cs # rows per unit, ascending
|
|
247
|
+
inv_ptr = np.zeros(n_units + 1, dtype=np.int64)
|
|
248
|
+
np.cumsum(np.bincount(flat, minlength=n_units), out=inv_ptr[1:])
|
|
249
|
+
tri_idx = np.array(list(itertools.combinations(range(cs + 1), 3)),
|
|
250
|
+
dtype=np.int64)
|
|
251
|
+
|
|
252
|
+
out_c, out_h = [], []
|
|
253
|
+
for j in range(m):
|
|
254
|
+
row = cand[j]
|
|
255
|
+
parts = []
|
|
256
|
+
for u in row:
|
|
257
|
+
l = inv_rows[inv_ptr[u]:inv_ptr[u + 1]]
|
|
258
|
+
parts.append(l[np.searchsorted(l, j, side="right"):]) # rows after j
|
|
259
|
+
r = np.concatenate(parts)
|
|
260
|
+
if r.size == 0:
|
|
261
|
+
continue
|
|
262
|
+
ids, cnt = np.unique(r, return_counts=True)
|
|
263
|
+
ext = ids[cnt == cs - 1] # share exactly cs-1 members
|
|
264
|
+
if ext.size == 0:
|
|
265
|
+
continue
|
|
266
|
+
ext_rows = cand[ext]
|
|
267
|
+
y = ext_rows[~np.isin(ext_rows, row)] # the one new unit per ext
|
|
268
|
+
uy, inv, ycnt = np.unique(y, return_inverse=True, return_counts=True)
|
|
269
|
+
keep = ycnt[np.asarray(inv).reshape(-1)] >= 2 # MATLAB's possibleNeurons filter
|
|
270
|
+
if not keep.any():
|
|
271
|
+
continue
|
|
272
|
+
ext, y = ext[keep], y[keep]
|
|
273
|
+
uy = np.unique(y)[::-1] # MATLAB unique-rows order
|
|
274
|
+
combos = np.sort(np.concatenate(
|
|
275
|
+
[np.broadcast_to(row, (uy.size, cs)), uy[:, None]], axis=1), axis=1)
|
|
276
|
+
ok = _missing_fraction(combos, tri_keys, n_units, tri_idx) <= tol
|
|
277
|
+
for yy, c in zip(uy[ok], combos[ok]):
|
|
278
|
+
out_c.append(c)
|
|
279
|
+
out_h.append(np.concatenate(([j], ext[y == yy])))
|
|
280
|
+
if not out_c:
|
|
281
|
+
return np.empty((0, cs + 1), dtype=np.int64), []
|
|
282
|
+
return np.stack(out_c), out_h
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def rate_ssa_assemblies(members, t, u, flat_t, offsets, n_spikes, w, thr, n_min):
|
|
286
|
+
"""members: (n, k) sorted unit ids, one candidate per row. Returns bool (n,)."""
|
|
287
|
+
passes = np.empty(members.shape[0], dtype=np.bool_)
|
|
288
|
+
rate_ssa_parallel(t, u, flat_t, offsets, n_spikes,
|
|
289
|
+
np.ascontiguousarray(members, dtype=np.int64),
|
|
290
|
+
w, float(thr), int(n_min), False, passes)
|
|
291
|
+
return passes
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
@njit(cache=True, parallel=True, error_model="numpy")
|
|
295
|
+
def rate_ssa_parallel(times, units, flat_times, offsets, n_spikes, cand_members,
|
|
296
|
+
w, thr, n_min, nan_fails, passes):
|
|
297
|
+
"""cand_members: (n, k) sorted rows. passes: (n,) bool output."""
|
|
298
|
+
for i in prange(cand_members.shape[0]):
|
|
299
|
+
passes[i] = _rate_ssa_one(times, units, flat_times, offsets, n_spikes,
|
|
300
|
+
cand_members[i], w, thr, n_min, nan_fails)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
@njit(cache=True, nogil=True, error_model="numpy")
|
|
304
|
+
def _rate_ssa_one(times, units, flat_times, offsets, n_spikes, members,
|
|
305
|
+
w, thr, n_min, nan_fails):
|
|
306
|
+
"""Affinity criterion only, for every member. members: sorted, size >= 3."""
|
|
307
|
+
n_units = n_spikes.shape[0]
|
|
308
|
+
n_members = members.shape[0]
|
|
309
|
+
n_others = n_members - 1
|
|
310
|
+
for jp in range(n_members):
|
|
311
|
+
j = members[jp]
|
|
312
|
+
nj = float(n_spikes[j])
|
|
313
|
+
if nj == 0.0:
|
|
314
|
+
return False
|
|
315
|
+
|
|
316
|
+
# complete activations of the other members (no zero patch, as in MATLAB)
|
|
317
|
+
st, sc = _stream(flat_times, offsets, members, jp, -1)
|
|
318
|
+
starts, ends, dur = _profile(st, sc, n_others, w, True)
|
|
319
|
+
counts = _grouped_coverage(times, units, starts, ends, n_units)
|
|
320
|
+
if starts.shape[0] < n_min: # min number of assembly activations
|
|
321
|
+
return False
|
|
322
|
+
|
|
323
|
+
g = 0.0
|
|
324
|
+
for q in range(n_units):
|
|
325
|
+
g += counts[q]
|
|
326
|
+
n_non = float(times.shape[0])
|
|
327
|
+
for t in range(n_members):
|
|
328
|
+
if t != jp:
|
|
329
|
+
g -= counts[members[t]] # non-members include j itself
|
|
330
|
+
n_non -= n_spikes[members[t]]
|
|
331
|
+
|
|
332
|
+
z = _z_test(float(counts[j]), nj, g, n_non)
|
|
333
|
+
if z < thr or (nan_fails and z != z): # NaN passes, as in MATLAB
|
|
334
|
+
return False
|
|
335
|
+
return True
|
|
336
|
+
|
|
337
|
+
# --- low-level helpers ---
|
|
338
|
+
|
|
339
|
+
@njit(cache=True, nogil=True)
|
|
340
|
+
def _stream(flat_times, offsets, members, skip_a, skip_b):
|
|
341
|
+
"""Merged spikes of `members` (sorted ascending) leaving out the member
|
|
342
|
+
at positions skip_a / skip_b (-1 = none). Codes = rank among kept members.
|
|
343
|
+
Stable sort keeps (time, id) order, as sortrows did."""
|
|
344
|
+
total = 0
|
|
345
|
+
for t in range(members.shape[0]):
|
|
346
|
+
if t != skip_a and t != skip_b:
|
|
347
|
+
u = members[t]
|
|
348
|
+
total += offsets[u + 1] - offsets[u]
|
|
349
|
+
tt = np.empty(total)
|
|
350
|
+
cc = np.empty(total, np.int64)
|
|
351
|
+
p = 0
|
|
352
|
+
c = 0
|
|
353
|
+
for t in range(members.shape[0]):
|
|
354
|
+
if t == skip_a or t == skip_b:
|
|
355
|
+
continue
|
|
356
|
+
u = members[t]
|
|
357
|
+
for q in range(offsets[u], offsets[u + 1]):
|
|
358
|
+
tt[p] = flat_times[q]
|
|
359
|
+
cc[p] = c
|
|
360
|
+
p += 1
|
|
361
|
+
c += 1
|
|
362
|
+
order = np.argsort(tt, kind="mergesort") # stable
|
|
363
|
+
return tt[order], cc[order]
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
@njit(cache=True, nogil=True)
|
|
367
|
+
def _profile(st, sc, k, w, patch_zero):
|
|
368
|
+
"""Window starts/ends and overlap-corrected duration for the activations
|
|
369
|
+
of k cells. k == 1: windows around the single unit's spikes (the MATLAB
|
|
370
|
+
'pair' branch). patch_zero: apply the ==0 -> NaN patch (incomplete case)."""
|
|
371
|
+
if k == 1:
|
|
372
|
+
starts = st - w / 2
|
|
373
|
+
ends = st + w / 2
|
|
374
|
+
else:
|
|
375
|
+
act = _common_intervals(st, sc, w, k, k - 1, 0)
|
|
376
|
+
m = act.shape[0]
|
|
377
|
+
if m == 0: # MEX returns a 1x2 zero matrix
|
|
378
|
+
act = np.zeros((1, 2))
|
|
379
|
+
m = 1
|
|
380
|
+
starts = np.empty(m)
|
|
381
|
+
ends = np.empty(m)
|
|
382
|
+
for r in range(m):
|
|
383
|
+
a = act[r, 0]
|
|
384
|
+
b = act[r, 1]
|
|
385
|
+
if patch_zero and (a == 0.0 or b == 0.0):
|
|
386
|
+
c = np.nan
|
|
387
|
+
else:
|
|
388
|
+
c = (a + b) / 2
|
|
389
|
+
starts[r] = c - w / 2
|
|
390
|
+
ends[r] = c + w / 2
|
|
391
|
+
acc = 0.0
|
|
392
|
+
for r in range(starts.shape[0] - 1):
|
|
393
|
+
d = starts[r + 1] - starts[r]
|
|
394
|
+
if not (d > w): # NaN falls through, like MATLAB
|
|
395
|
+
acc += d - w
|
|
396
|
+
return starts, ends, w * starts.shape[0] + acc
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
@njit(cache=True, nogil=True)
|
|
400
|
+
def _common_intervals(times, codes, window, n_cells, anchor, old_end0):
|
|
401
|
+
"""times: float64, sorted by (time, id)
|
|
402
|
+
codes: int64, 0-based, in {0, n_cells-1} (NOT bounds-checked)
|
|
403
|
+
anchor: 0-based anchor code"""
|
|
404
|
+
L = times.shape[0]
|
|
405
|
+
n_anchor = 0 # count anchor spikes
|
|
406
|
+
for i in range(L):
|
|
407
|
+
if codes[i] == anchor:
|
|
408
|
+
n_anchor += 1
|
|
409
|
+
out = np.empty((n_anchor, 2)) # at most one interval per anchor spike
|
|
410
|
+
occ = np.full(n_cells, np.nan) # found spike times per cell, NaN: unset (WAS 0!)
|
|
411
|
+
row = 0
|
|
412
|
+
old_end = old_end0 # index of last found spike, old_end0 is used to reproduce MEX bug
|
|
413
|
+
|
|
414
|
+
for i in range(L):
|
|
415
|
+
if codes[i] != anchor:
|
|
416
|
+
continue
|
|
417
|
+
occ[:] = np.nan # reset found spikes
|
|
418
|
+
occ[anchor] = times[i]
|
|
419
|
+
counter = 1 # number of cells found for this anchor spike
|
|
420
|
+
|
|
421
|
+
# backwards search: nearest occurrence per cell
|
|
422
|
+
j = i - 1
|
|
423
|
+
while j > old_end and (times[i] - times[j]) < window:
|
|
424
|
+
c = codes[j]
|
|
425
|
+
if np.isnan(occ[c]):
|
|
426
|
+
occ[c] = times[j]
|
|
427
|
+
counter += 1
|
|
428
|
+
if counter == n_cells:
|
|
429
|
+
out[row, 0] = times[j]
|
|
430
|
+
out[row, 1] = times[i]
|
|
431
|
+
old_end = i
|
|
432
|
+
row += 1
|
|
433
|
+
break
|
|
434
|
+
j -= 1
|
|
435
|
+
|
|
436
|
+
# forwards search: latest occurrence per cell (if not yet complete)
|
|
437
|
+
if counter != n_cells:
|
|
438
|
+
j = i + 1
|
|
439
|
+
while j < L and (times[j] - times[i]) < window and codes[j] != anchor:
|
|
440
|
+
c = codes[j]
|
|
441
|
+
if np.isnan(occ[c]):
|
|
442
|
+
counter += 1
|
|
443
|
+
occ[c] = times[j] # this could be inside if to keep first occurrence per cell
|
|
444
|
+
if counter == n_cells:
|
|
445
|
+
cur_min = times[j] # first spike in this window
|
|
446
|
+
for k in range(n_cells):
|
|
447
|
+
if occ[k] < cur_min:
|
|
448
|
+
cur_min = occ[k]
|
|
449
|
+
if times[j] - occ[k] > window: # drop earliest found spike if this window is too wide
|
|
450
|
+
counter -= 1
|
|
451
|
+
occ[k] = np.nan
|
|
452
|
+
if counter == n_cells:
|
|
453
|
+
out[row, 0] = cur_min
|
|
454
|
+
out[row, 1] = times[j]
|
|
455
|
+
old_end = j
|
|
456
|
+
row += 1
|
|
457
|
+
break
|
|
458
|
+
j += 1
|
|
459
|
+
return out[:row]
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
@njit(cache=True, nogil=True)
|
|
463
|
+
def _grouped_coverage(times, units, starts, ends, n_units):
|
|
464
|
+
"""Per-unit counts of spikes inside the intervals, each spike counted
|
|
465
|
+
at most once (same semantics as ExclusiveCountInIntervals, summed per
|
|
466
|
+
unit). times sorted; units: 0-based id per spike; closed intervals."""
|
|
467
|
+
counts = np.zeros(n_units, dtype=np.int64)
|
|
468
|
+
n = times.shape[0]
|
|
469
|
+
j = 0
|
|
470
|
+
for i in range(starts.shape[0]):
|
|
471
|
+
s = starts[i]
|
|
472
|
+
e = ends[i]
|
|
473
|
+
if s != s or e != e: # NaN interval: counts nothing
|
|
474
|
+
continue
|
|
475
|
+
if j >= n:
|
|
476
|
+
break
|
|
477
|
+
if times[j] < s: # jump to first x >= s
|
|
478
|
+
j += np.searchsorted(times[j:], s)
|
|
479
|
+
while j < n and times[j] <= e:
|
|
480
|
+
counts[units[j]] += 1
|
|
481
|
+
j += 1
|
|
482
|
+
return counts
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
@njit(cache=True, nogil=True, error_model="numpy")
|
|
486
|
+
def _z_test(s1, n1, s2, n2):
|
|
487
|
+
p1 = s1 / n1
|
|
488
|
+
p2 = s2 / n2
|
|
489
|
+
P = (p1 * n1 + p2 * n2) / (n1 + n2)
|
|
490
|
+
v = P * (1.0 - P) * (1.0 / n1 + 1.0 / n2)
|
|
491
|
+
if v < 0.0:
|
|
492
|
+
return np.nan
|
|
493
|
+
return (p1 - p2) / np.sqrt(v) # 0/0 -> nan, x/0 -> +-inf
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
@njit(cache=True, nogil=True)
|
|
497
|
+
def _count_unit(flat_times, lo, hi, starts, ends):
|
|
498
|
+
"""Spikes of one unit (flat_times[lo:hi], sorted) inside the closed
|
|
499
|
+
intervals, each counted once. Same semantics as ExclusiveCountInIntervals."""
|
|
500
|
+
j = lo
|
|
501
|
+
total = 0
|
|
502
|
+
for i in range(starts.shape[0]):
|
|
503
|
+
s = starts[i]
|
|
504
|
+
e = ends[i]
|
|
505
|
+
if s != s or e != e:
|
|
506
|
+
continue
|
|
507
|
+
if j >= hi:
|
|
508
|
+
break
|
|
509
|
+
if flat_times[j] < s:
|
|
510
|
+
j += np.searchsorted(flat_times[j:hi], s)
|
|
511
|
+
while j < hi and flat_times[j] <= e:
|
|
512
|
+
total += 1
|
|
513
|
+
j += 1
|
|
514
|
+
return total
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: isac
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python port of ISAC
|
|
5
|
+
Author: Pietro Bozzo
|
|
6
|
+
License-Expression: GPL-3.0-or-later
|
|
7
|
+
Project-URL: Homepage, https://github.com/mnpompili/ISAC
|
|
8
|
+
Project-URL: Repository, https://github.com/mnpompili/ISAC
|
|
9
|
+
Project-URL: Issues, https://github.com/mnpompili/ISAC/issues
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: numba
|
|
14
|
+
Requires-Dist: numpy
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# ISAC (Python Port)
|
|
18
|
+
|
|
19
|
+
This is a Python port of ISAC.
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
This package is distributed via PyPI and can be installed, for example, with pip:
|
|
24
|
+
```
|
|
25
|
+
# e.g., on Linux
|
|
26
|
+
$ pip install isac # install isac in currently active python environment
|
|
27
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/isac/__init__.py
|
|
5
|
+
src/isac/core.py
|
|
6
|
+
src/isac/helpers.py
|
|
7
|
+
src/isac.egg-info/PKG-INFO
|
|
8
|
+
src/isac.egg-info/SOURCES.txt
|
|
9
|
+
src/isac.egg-info/dependency_links.txt
|
|
10
|
+
src/isac.egg-info/requires.txt
|
|
11
|
+
src/isac.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
isac
|