sarc-asm 0.2.2__py2.py3-none-any.whl
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.
Potentially problematic release.
This version of sarc-asm might be problematic. Click here for more details.
- contraction_net/__init__.py +4 -0
- contraction_net/annotation.py +148 -0
- contraction_net/contraction_net.py +81 -0
- contraction_net/data.py +158 -0
- contraction_net/losses.py +97 -0
- contraction_net/prediction.py +41 -0
- contraction_net/training.py +171 -0
- contraction_net/utils.py +248 -0
- sarc_asm-0.2.2.dist-info/LICENSE +27 -0
- sarc_asm-0.2.2.dist-info/METADATA +18 -0
- sarc_asm-0.2.2.dist-info/RECORD +64 -0
- sarc_asm-0.2.2.dist-info/WHEEL +4 -0
- sarcasm/.DS_Store +0 -0
- sarcasm/__init__.py +25 -0
- sarcasm/_version.py +20 -0
- sarcasm/core.py +624 -0
- sarcasm/core_omezarr.py +801 -0
- sarcasm/exceptions.py +17 -0
- sarcasm/export.py +464 -0
- sarcasm/feature_dict.py +743 -0
- sarcasm/ioutils.py +112 -0
- sarcasm/meta_data_handler.py +120 -0
- sarcasm/meta_data_handler_omezarr.py +243 -0
- sarcasm/models/model_ContractionNet.pt +0 -0
- sarcasm/models/model_sarcomeres_generalist.pt +0 -0
- sarcasm/models/model_z_bands_unet3d.pt +0 -0
- sarcasm/motion.py +938 -0
- sarcasm/plot_utils.py +302 -0
- sarcasm/plots.py +1615 -0
- sarcasm/py.typed +0 -0
- sarcasm/structure.py +2668 -0
- sarcasm/structure_xarray.py +2899 -0
- sarcasm/training_data_generation.py +1041 -0
- sarcasm/type_utils.py +34 -0
- sarcasm/utils.py +1276 -0
- sarcasm_app/__init__.py +256 -0
- sarcasm_app/__main__.py +24 -0
- sarcasm_app/control/__init__.py +17 -0
- sarcasm_app/control/application_control.py +579 -0
- sarcasm_app/control/batch_processing_control.py +495 -0
- sarcasm_app/control/chain_execution.py +89 -0
- sarcasm_app/control/file_selection_control.py +322 -0
- sarcasm_app/control/loi_analysis_control.py +202 -0
- sarcasm_app/control/motion_analysis_control.py +320 -0
- sarcasm_app/control/popup_export.py +295 -0
- sarcasm_app/control/structure_analysis_control.py +505 -0
- sarcasm_app/icons/sarcasm.icns +0 -0
- sarcasm_app/icons/sarcasm.ico +0 -0
- sarcasm_app/model/__init__.py +356 -0
- sarcasm_app/model/parameter.py +148 -0
- sarcasm_app/model/parameters.py +60 -0
- sarcasm_app/py.typed +0 -0
- sarcasm_app/ui-files/file_selection.ui +212 -0
- sarcasm_app/ui-files/parameters_batch_processing.ui +276 -0
- sarcasm_app/ui-files/parameters_loi_analysis.ui +680 -0
- sarcasm_app/ui-files/parameters_motion_analysis.ui +740 -0
- sarcasm_app/ui-files/parameters_structure_analysis.ui +1199 -0
- sarcasm_app/ui-files/update_py_files.bat +5 -0
- sarcasm_app/view/__init__.py +0 -0
- sarcasm_app/view/file_selection.py +146 -0
- sarcasm_app/view/parameters_batch_processing.py +174 -0
- sarcasm_app/view/parameters_loi_analysis.py +371 -0
- sarcasm_app/view/parameters_motion_analysis.py +404 -0
- sarcasm_app/view/parameters_structure_analysis.py +643 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
import torch.optim as optim
|
|
5
|
+
from torch.utils.data import DataLoader, random_split
|
|
6
|
+
from tqdm import tqdm
|
|
7
|
+
|
|
8
|
+
from .losses import BCEDiceLoss, SmoothnessLoss
|
|
9
|
+
from .contraction_net import ContractionNet
|
|
10
|
+
from .utils import get_device
|
|
11
|
+
|
|
12
|
+
# select device
|
|
13
|
+
device = get_device()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Trainer:
|
|
17
|
+
"""
|
|
18
|
+
Class for training of ContractionNet. Creates Trainer object.
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
Parameters
|
|
22
|
+
----------
|
|
23
|
+
dataset
|
|
24
|
+
Training data, object of PyTorch Dataset class
|
|
25
|
+
num_epochs : int
|
|
26
|
+
Number of training epochs
|
|
27
|
+
network
|
|
28
|
+
Network class (Default Unet)
|
|
29
|
+
in_channels : int
|
|
30
|
+
Number of input channels
|
|
31
|
+
out_channels : int
|
|
32
|
+
Number of output channels
|
|
33
|
+
batch_size : int
|
|
34
|
+
Batch size for training
|
|
35
|
+
lr : float
|
|
36
|
+
Learning rate
|
|
37
|
+
n_filter : int
|
|
38
|
+
Number of convolutional filters in first layer
|
|
39
|
+
val_split : float
|
|
40
|
+
Validation split
|
|
41
|
+
save_dir : str
|
|
42
|
+
Path of directory to save trained networks
|
|
43
|
+
save_name : str
|
|
44
|
+
Base name for saving trained networks
|
|
45
|
+
save_iter : bool
|
|
46
|
+
If True, network state is save after each epoch
|
|
47
|
+
load_weights : str, optional
|
|
48
|
+
If not None, network state is loaded before training
|
|
49
|
+
loss_function : str
|
|
50
|
+
Loss function ('BCEDice', 'Tversky' or 'logcoshTversky')
|
|
51
|
+
loss_params : Tuple[float, float]
|
|
52
|
+
Parameter of loss function, depends on chosen loss function
|
|
53
|
+
"""
|
|
54
|
+
def __init__(self, dataset, num_epochs, network=ContractionNet, in_channels=1, out_channels=2,
|
|
55
|
+
batch_size=16, lr=1e-3, n_filter=64, val_split=0.2,
|
|
56
|
+
save_dir='./', save_name='model.pt', save_iter=False, loss_function='BCEDice',
|
|
57
|
+
loss_params=(1, 1)):
|
|
58
|
+
|
|
59
|
+
self.network = network
|
|
60
|
+
self.model = network(n_filter=n_filter, in_channels=in_channels, out_channels=out_channels).to(device)
|
|
61
|
+
self.data = dataset
|
|
62
|
+
self.in_channels = in_channels
|
|
63
|
+
self.out_channels = out_channels
|
|
64
|
+
self.num_epochs = num_epochs
|
|
65
|
+
self.batch_size = batch_size
|
|
66
|
+
self.lr = lr
|
|
67
|
+
self.best_loss = torch.tensor(float('inf'))
|
|
68
|
+
self.save_iter = save_iter
|
|
69
|
+
self.loss_function = loss_function
|
|
70
|
+
self.loss_params = loss_params
|
|
71
|
+
self.n_filter = n_filter
|
|
72
|
+
# split training and validation data
|
|
73
|
+
num_val = int(len(dataset) * val_split)
|
|
74
|
+
num_train = len(dataset) - num_val
|
|
75
|
+
self.dim = dataset.input_len
|
|
76
|
+
self.train_data, self.val_data = random_split(dataset, [num_train, num_val])
|
|
77
|
+
self.train_loader = DataLoader(self.train_data, batch_size=self.batch_size, pin_memory=True, drop_last=True)
|
|
78
|
+
self.val_loader = DataLoader(self.val_data, batch_size=self.batch_size, pin_memory=True, drop_last=True)
|
|
79
|
+
if loss_function == 'BCEDice':
|
|
80
|
+
self.criterion = BCEDiceLoss(loss_params)
|
|
81
|
+
else:
|
|
82
|
+
raise ValueError(f'Loss "{loss_function}" not defined!')
|
|
83
|
+
self.smooth_loss = SmoothnessLoss(alpha=0.01)
|
|
84
|
+
self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr)
|
|
85
|
+
self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, 'min', patience=4, factor=0.1)
|
|
86
|
+
self.save_dir = save_dir
|
|
87
|
+
os.makedirs(self.save_dir, exist_ok=True)
|
|
88
|
+
self.save_name = save_name
|
|
89
|
+
|
|
90
|
+
def __iterate(self, epoch, mode):
|
|
91
|
+
if mode == 'train':
|
|
92
|
+
print('\nStarting training epoch %s ...' % epoch)
|
|
93
|
+
for i, batch_i in tqdm(enumerate(self.train_loader), total=len(self.train_loader), unit='batch'):
|
|
94
|
+
x_i = batch_i['input'].view(self.batch_size, self.in_channels, self.dim).to(device)
|
|
95
|
+
y_i = batch_i['target'].view(self.batch_size, 1, self.dim).to(device)
|
|
96
|
+
d_i = batch_i['distance'].view(self.batch_size, 1, self.dim).to(device)
|
|
97
|
+
# Forward pass: Compute predicted y by passing x to the model
|
|
98
|
+
y_pred, y_logits = self.model(x_i)
|
|
99
|
+
# Split the tensor into 2 chunks along the second dimension
|
|
100
|
+
y_1, y_2 = torch.chunk(y_logits, chunks=2, dim=1)
|
|
101
|
+
# Compute loss
|
|
102
|
+
contr_loss = self.criterion(y_1, y_i)
|
|
103
|
+
dist_loss = self.criterion(y_2, d_i)
|
|
104
|
+
smooth_loss = self.smooth_loss(y_2)
|
|
105
|
+
loss = contr_loss + dist_loss
|
|
106
|
+
# Zero gradients, perform a backward pass, and update the weights.
|
|
107
|
+
self.optimizer.zero_grad()
|
|
108
|
+
loss.backward()
|
|
109
|
+
self.optimizer.step()
|
|
110
|
+
return loss
|
|
111
|
+
|
|
112
|
+
elif mode == 'val':
|
|
113
|
+
loss_list = []
|
|
114
|
+
print('\nStarting validation epoch %s ...' % epoch)
|
|
115
|
+
with torch.no_grad():
|
|
116
|
+
for i, batch_i in enumerate(self.val_loader):
|
|
117
|
+
x_i = batch_i['input'].view(self.batch_size, self.in_channels, self.dim).to(device)
|
|
118
|
+
y_i = batch_i['target'].view(self.batch_size, 1, self.dim).to(device)
|
|
119
|
+
d_i = batch_i['distance'].view(self.batch_size, 1, self.dim).to(device)
|
|
120
|
+
# Forward pass: Compute predicted y by passing x to the model
|
|
121
|
+
y_pred, y_logits = self.model(x_i)
|
|
122
|
+
|
|
123
|
+
# Compute loss
|
|
124
|
+
loss = self.criterion(y_logits[:, 0], y_i[:, 0]) + self.criterion(y_logits[:, 1], d_i[:, 0])
|
|
125
|
+
loss_list.append(loss.detach())
|
|
126
|
+
val_loss = torch.stack(loss_list).mean()
|
|
127
|
+
return val_loss
|
|
128
|
+
|
|
129
|
+
def start(self):
|
|
130
|
+
"""
|
|
131
|
+
Start network training.
|
|
132
|
+
"""
|
|
133
|
+
train_loss = []
|
|
134
|
+
val_loss = []
|
|
135
|
+
for epoch in range(self.num_epochs):
|
|
136
|
+
train_loss_i = self.__iterate(epoch, 'train')
|
|
137
|
+
train_loss.append(train_loss_i)
|
|
138
|
+
self.state = {
|
|
139
|
+
'epoch': epoch,
|
|
140
|
+
'train_loss': train_loss,
|
|
141
|
+
'val_loss': val_loss,
|
|
142
|
+
'best_loss': self.best_loss,
|
|
143
|
+
'state_dict': self.model.state_dict(),
|
|
144
|
+
'optimizer': self.optimizer.state_dict(),
|
|
145
|
+
'lr': self.lr,
|
|
146
|
+
'loss_function': self.loss_function,
|
|
147
|
+
'loss_params': self.loss_params,
|
|
148
|
+
'in_channels': self.in_channels,
|
|
149
|
+
'out_channels': self.out_channels,
|
|
150
|
+
'n_filter': self.n_filter,
|
|
151
|
+
'batch_size': self.batch_size,
|
|
152
|
+
'augmentation': self.data.aug_factor,
|
|
153
|
+
'noise_amp': self.data.noise_amp,
|
|
154
|
+
'random_offset': self.data.random_offset,
|
|
155
|
+
'random_drift': self.data.random_drift,
|
|
156
|
+
'random_outlier': self.data.random_outlier,
|
|
157
|
+
'random_subsampling': self.data.random_subsampling,
|
|
158
|
+
'random_swap': self.data.random_swap,
|
|
159
|
+
}
|
|
160
|
+
with torch.no_grad():
|
|
161
|
+
val_loss_i = self.__iterate(epoch, 'val')
|
|
162
|
+
val_loss.append(val_loss_i)
|
|
163
|
+
self.scheduler.step(val_loss_i)
|
|
164
|
+
if val_loss_i < self.best_loss:
|
|
165
|
+
print('\nValidation loss improved from %s to %s - saving model state' % (
|
|
166
|
+
round(self.best_loss.item(), 5), round(val_loss_i.item(), 5)))
|
|
167
|
+
self.state['best_loss'] = self.best_loss = val_loss_i
|
|
168
|
+
torch.save(self.state, self.save_dir + '/' + self.save_name)
|
|
169
|
+
if self.save_iter:
|
|
170
|
+
torch.save(self.state, self.save_dir + '/' + f'model_epoch_{epoch}.pt')
|
|
171
|
+
|
contraction_net/utils.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import torch
|
|
5
|
+
from matplotlib import pyplot as plt
|
|
6
|
+
from scipy.ndimage import label, distance_transform_edt
|
|
7
|
+
from skimage.morphology import binary_dilation, remove_small_holes, binary_closing
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def simulate_training_data(folder, input_len=512, n=100, freq_range=(0.04, 0.25), prob_zeros=0.5,
|
|
11
|
+
clip_thrs=(-0.75, 0.75), random_drift_amp_range=(0.005, 0.02),
|
|
12
|
+
random_drift_freq_range=(0, 0.05), noise_amp_range=(0, 0.25), plot=False):
|
|
13
|
+
"""
|
|
14
|
+
Simulate training data for ContractionNet with sinusoidal patterns, random drift, and noise.
|
|
15
|
+
|
|
16
|
+
Parameters
|
|
17
|
+
----------
|
|
18
|
+
folder : str
|
|
19
|
+
Path to the folder where the simulated data will be saved.
|
|
20
|
+
input_len : int, optional
|
|
21
|
+
Length of each simulated sequence, by default 512.
|
|
22
|
+
n : int, optional
|
|
23
|
+
Number of sequences to simulate, by default 100.
|
|
24
|
+
freq_range : tuple of float, optional
|
|
25
|
+
Range of frequencies for the sinusoidal patterns, by default (0.04, 0.25).
|
|
26
|
+
prob_zeros : float, optional
|
|
27
|
+
Probability of zero frequency (flat line), by default 0.5.
|
|
28
|
+
clip_thrs : tuple of float, optional
|
|
29
|
+
Clipping thresholds for the sinusoidal values, by default (-0.75, 0.75).
|
|
30
|
+
random_drift_amp_range : tuple of float, optional
|
|
31
|
+
Amplitude range for the random drift, by default (0.005, 0.02).
|
|
32
|
+
random_drift_freq_range : tuple of float, optional
|
|
33
|
+
Frequency range for the random drift, by default (0, 0.05).
|
|
34
|
+
noise_amp_range : tuple of float, optional
|
|
35
|
+
Amplitude range for the added noise, by default (0, 0.25).
|
|
36
|
+
plot : bool, optional
|
|
37
|
+
Whether to plot the simulated data, by default False.
|
|
38
|
+
"""
|
|
39
|
+
# Ensure the folder exists
|
|
40
|
+
os.makedirs(folder, exist_ok=True)
|
|
41
|
+
|
|
42
|
+
for i in range(n):
|
|
43
|
+
# Randomly select a frequency within the specified range
|
|
44
|
+
freq = np.random.uniform(freq_range[0], freq_range[1])
|
|
45
|
+
x_range = np.arange(input_len)
|
|
46
|
+
|
|
47
|
+
# Amplitude modulation with a slow cosine function
|
|
48
|
+
amp_mod = 1 + np.abs(np.cos(x_range * np.random.uniform(0.01, 0.02)))
|
|
49
|
+
|
|
50
|
+
# Set frequency to zero with a certain probability
|
|
51
|
+
if np.random.binomial(1, prob_zeros):
|
|
52
|
+
freq = 0
|
|
53
|
+
|
|
54
|
+
# Generate a cosine wave and clip its values
|
|
55
|
+
y_sim = np.clip(np.cos(x_range * freq), None, np.random.uniform(clip_thrs[0], clip_thrs[1]))
|
|
56
|
+
y_sim -= np.max(y_sim) # Normalize to zero baseline
|
|
57
|
+
y_sim = amp_mod * y_sim
|
|
58
|
+
|
|
59
|
+
# Calculate systole as a binary mask where the signal is non-zero
|
|
60
|
+
y_contr = np.zeros_like(y_sim)
|
|
61
|
+
y_contr[y_sim != 0] = 1
|
|
62
|
+
|
|
63
|
+
# Add random drift to the signal
|
|
64
|
+
random_drift = (np.random.uniform(random_drift_amp_range[0], random_drift_amp_range[1]),
|
|
65
|
+
np.random.uniform(random_drift_freq_range[0], random_drift_freq_range[1]))
|
|
66
|
+
y_sim += random_drift[0] * np.cos(random_drift[1] * x_range)
|
|
67
|
+
|
|
68
|
+
# Add normal noise to the signal
|
|
69
|
+
y_sim += np.random.normal(0, np.random.uniform(noise_amp_range[0], noise_amp_range[1]), size=input_len)
|
|
70
|
+
|
|
71
|
+
# Plot the simulated data
|
|
72
|
+
if plot:
|
|
73
|
+
plt.figure()
|
|
74
|
+
plt.plot(x_range, y_sim)
|
|
75
|
+
plt.plot(x_range, y_contr)
|
|
76
|
+
plt.show()
|
|
77
|
+
|
|
78
|
+
# Save the simulated signal and its contraction mask to text files
|
|
79
|
+
np.savetxt(os.path.join(folder, f'simulated_{i}.txt'), y_sim)
|
|
80
|
+
np.savetxt(os.path.join(folder, f'simulated_{i}_contr.txt'), y_contr)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def plot_selection_training_data(dataset, n_sample):
|
|
84
|
+
"""
|
|
85
|
+
Plot a random selection of training data sequences.
|
|
86
|
+
|
|
87
|
+
Parameters
|
|
88
|
+
----------
|
|
89
|
+
dataset : object
|
|
90
|
+
Dataset object containing the training data.
|
|
91
|
+
n_sample : int
|
|
92
|
+
Number of samples to plot.
|
|
93
|
+
"""
|
|
94
|
+
# Randomly select n_sample sequences from the dataset
|
|
95
|
+
selection = dataset.data[np.random.choice(dataset.data.shape[0], n_sample)]
|
|
96
|
+
|
|
97
|
+
# Create subplots
|
|
98
|
+
fig, axs = plt.subplots(figsize=(5, 2 * n_sample), nrows=n_sample)
|
|
99
|
+
|
|
100
|
+
for i, d_i in enumerate(selection):
|
|
101
|
+
# Plot the data sequences
|
|
102
|
+
axs[i].plot(d_i[0], c='k') # Plot the first sequence in black
|
|
103
|
+
axs[i].plot(d_i[1], c='r') # Plot the second sequence in red
|
|
104
|
+
|
|
105
|
+
plt.show()
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def find_txt_files(root_dir):
|
|
109
|
+
"""
|
|
110
|
+
Find all .txt files in a directory and its subdirectories.
|
|
111
|
+
|
|
112
|
+
Parameters
|
|
113
|
+
----------
|
|
114
|
+
root_dir : str
|
|
115
|
+
Root directory to search for text files.
|
|
116
|
+
|
|
117
|
+
Returns
|
|
118
|
+
-------
|
|
119
|
+
list of str
|
|
120
|
+
List of paths to the found text files.
|
|
121
|
+
"""
|
|
122
|
+
txt_files = []
|
|
123
|
+
# Walk through the directory tree
|
|
124
|
+
for dirpath, dirnames, filenames in os.walk(root_dir):
|
|
125
|
+
for filename in filenames:
|
|
126
|
+
if filename.endswith('.txt'):
|
|
127
|
+
# Append the full path of text files to the list
|
|
128
|
+
txt_files.append(os.path.join(dirpath, filename))
|
|
129
|
+
return txt_files
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def get_device(print_device=False):
|
|
133
|
+
"""
|
|
134
|
+
Determines the most suitable device (CUDA, MPS, or CPU) for PyTorch operations.
|
|
135
|
+
|
|
136
|
+
Returns:
|
|
137
|
+
- A torch.device object representing the selected device.
|
|
138
|
+
"""
|
|
139
|
+
if torch.backends.cuda.is_built():
|
|
140
|
+
device = torch.device('cuda:0')
|
|
141
|
+
elif torch.backends.mps.is_built(): # only for Apple M1/M2/...
|
|
142
|
+
device = torch.device('mps')
|
|
143
|
+
else:
|
|
144
|
+
device = torch.device('cpu')
|
|
145
|
+
print("Warning: No CUDA or MPS device found. Calculations will run on the CPU, "
|
|
146
|
+
"which might be slower.")
|
|
147
|
+
if print_device:
|
|
148
|
+
print(f"Using device: {device}")
|
|
149
|
+
return device
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def distance_transform(input, target):
|
|
153
|
+
"""
|
|
154
|
+
Compute a normalized distance transform for each labeled region in the target.
|
|
155
|
+
|
|
156
|
+
The function calculates the Euclidean distance transform for each unique label
|
|
157
|
+
in the target array. Each distance transform is then normalized by its maximum
|
|
158
|
+
value to ensure distances are scaled between 0 and 1. These normalized distance
|
|
159
|
+
transforms are summed to produce a composite distance map.
|
|
160
|
+
|
|
161
|
+
Parameters
|
|
162
|
+
----------
|
|
163
|
+
input : ndarray
|
|
164
|
+
The input image array. This parameter is currently not used in the function,
|
|
165
|
+
but included for future extensions or modifications.
|
|
166
|
+
target : ndarray
|
|
167
|
+
The target image array containing labeled regions. The regions should be
|
|
168
|
+
labeled as distinct integers, with background typically labeled as 0.
|
|
169
|
+
|
|
170
|
+
Returns
|
|
171
|
+
-------
|
|
172
|
+
distances : ndarray
|
|
173
|
+
An array of the same shape as `target`, containing the normalized distance
|
|
174
|
+
transform values for each labeled region in `target`.
|
|
175
|
+
|
|
176
|
+
Notes
|
|
177
|
+
-----
|
|
178
|
+
This implementation assumes that the target contains non-overlapping labeled
|
|
179
|
+
regions. Overlapping regions will result in undefined behavior.
|
|
180
|
+
"""
|
|
181
|
+
# Initialize an array to store the distance transforms
|
|
182
|
+
distances = np.zeros_like(input, dtype=float)
|
|
183
|
+
# Label the connected components in the target
|
|
184
|
+
labels, n_labels = label(target)
|
|
185
|
+
# Iterate over each label to compute its distance transform
|
|
186
|
+
for label_i in range(1, n_labels + 1):
|
|
187
|
+
# Create a binary mask for the current label
|
|
188
|
+
labels_i = labels == label_i
|
|
189
|
+
# Compute the Euclidean distance transform for the current label
|
|
190
|
+
distance_i = distance_transform_edt(labels_i)
|
|
191
|
+
# Normalize and accumulate the distance transform
|
|
192
|
+
distances += distance_i / distance_i.max()
|
|
193
|
+
return distances
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def process_contractions(contractions, signal=None, threshold=0.05, area_min=3, dilate_surrounding=2, len_min=4,
|
|
197
|
+
merge_max=3):
|
|
198
|
+
"""
|
|
199
|
+
Process contraction time series to filter based on specified criteria.
|
|
200
|
+
|
|
201
|
+
Parameters
|
|
202
|
+
----------
|
|
203
|
+
contractions : ndarray
|
|
204
|
+
Array indicating intervals of potential contractions (output of ContractionNet).
|
|
205
|
+
signal : ndarray
|
|
206
|
+
Array of the original signal values corresponding to contractions. If None, no signal will be processed.
|
|
207
|
+
threshold : float, optional
|
|
208
|
+
Threshold value to binarize contractions, by default 0.05.
|
|
209
|
+
area_min : int, optional
|
|
210
|
+
Minimum area under the signal curve for contraction interval to consider, by default 3 frames.
|
|
211
|
+
dilate_surrounding : int, optional
|
|
212
|
+
Number of frames to dilate around each contraction for offset calculation, by default 2 frames.
|
|
213
|
+
len_min : int, optional
|
|
214
|
+
Minimum length of a contraction to consider, by default 4 frames.
|
|
215
|
+
merge_max : int, optional
|
|
216
|
+
Maximum gap to merge subsequent filtered contractions, by default 3 frames.
|
|
217
|
+
|
|
218
|
+
Returns
|
|
219
|
+
-------
|
|
220
|
+
ndarray
|
|
221
|
+
Binary array with filtered contractions based on the specified criteria.
|
|
222
|
+
"""
|
|
223
|
+
contr_labels, n_labels = label(contractions > threshold)
|
|
224
|
+
|
|
225
|
+
contr_labels_filtered = np.zeros_like(contr_labels)
|
|
226
|
+
|
|
227
|
+
for i, contr_i in enumerate(np.unique(contr_labels)[1:]):
|
|
228
|
+
contr_labels_i = contr_labels == contr_i
|
|
229
|
+
len_i = np.count_nonzero(contr_labels_i)
|
|
230
|
+
if signal is not None:
|
|
231
|
+
signal_i = signal[contr_labels_i]
|
|
232
|
+
# Dilate contraction labels and calculate offset
|
|
233
|
+
contr_labels_i_dilated = binary_dilation(contr_labels_i, np.ones((dilate_surrounding * 2 + 1)))
|
|
234
|
+
surrounding_i = contr_labels_i_dilated ^ contr_labels_i
|
|
235
|
+
offset_i = np.mean(signal[surrounding_i])
|
|
236
|
+
signal_i -= offset_i
|
|
237
|
+
# Calculate area under peak and length
|
|
238
|
+
area_i = np.abs(np.sum(signal_i))
|
|
239
|
+
else:
|
|
240
|
+
area_i = np.inf
|
|
241
|
+
|
|
242
|
+
if area_i >= area_min and len_i >= len_min:
|
|
243
|
+
contr_labels_filtered += contr_labels_i
|
|
244
|
+
|
|
245
|
+
# Remove small holes
|
|
246
|
+
contr_labels_filtered = binary_closing(contr_labels_filtered, np.ones(merge_max))
|
|
247
|
+
|
|
248
|
+
return contr_labels_filtered
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
License
|
|
2
|
+
=======
|
|
3
|
+
|
|
4
|
+
This software is patent pending (Patent Application No. DE 10 2024 112 939.5, Priority Date: 8.5.2024).
|
|
5
|
+
|
|
6
|
+
Academic and Non-Commercial Use
|
|
7
|
+
-------------------------------
|
|
8
|
+
|
|
9
|
+
This software is free for academic and non-commercial use. Users are granted a non-exclusive, non-transferable license to use the software for research, educational, and other non-commercial purposes.
|
|
10
|
+
|
|
11
|
+
Commercial Use Restrictions
|
|
12
|
+
---------------------------
|
|
13
|
+
|
|
14
|
+
Commercial use of this software is strictly prohibited without obtaining a separate license agreement. This includes but is not limited to:
|
|
15
|
+
- Using the software in a commercial product or service
|
|
16
|
+
- Using the software to provide services to third parties
|
|
17
|
+
- Reselling or redistributing the software
|
|
18
|
+
|
|
19
|
+
For commercial licensing inquiries, please contact:
|
|
20
|
+
|
|
21
|
+
**MBM ScienceBridge GmbH**
|
|
22
|
+
Hans-Adolf-Krebs-Weg 1
|
|
23
|
+
37077 Göttingen
|
|
24
|
+
Germany
|
|
25
|
+
https://sciencebridge.de/en/
|
|
26
|
+
|
|
27
|
+
All rights not expressly granted are reserved. Unauthorized use may result in legal action.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: sarc-asm
|
|
3
|
+
Version: 0.2.2
|
|
4
|
+
Summary: Sarcomere Analysis Multitool for structural and functional analysis of sarcomeres in microscopy images and movies
|
|
5
|
+
Author: Daniel Haertter
|
|
6
|
+
Author-email: dani.hae@posteo.de
|
|
7
|
+
Classifier: Programming Language :: Python :: 2
|
|
8
|
+
Classifier: Programming Language :: Python :: 2.7
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.4
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.5
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.6
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
contraction_net/__init__.py,sha256=rP4JKgOpG-_NLG3xieGUadoCwt_4n70tter4344dBA0,148
|
|
2
|
+
contraction_net/annotation.py,sha256=scck5zvCigQIp6zrQUAVvpaeWCPyEmKVixqJ7XU9N6g,6017
|
|
3
|
+
contraction_net/contraction_net.py,sha256=aqfdbTSXB1Qq1BJx6lq3O8qosIvOyDbarbHMXmJErWs,3683
|
|
4
|
+
contraction_net/data.py,sha256=Vr5EIDXZjWmMVTFPG7sxpsiOXcwBMGDZ1NI_gKJGHlk,6737
|
|
5
|
+
contraction_net/losses.py,sha256=C7CUhNExLnExCJLilSDRvSGWDqaCcqZBMXbL8XcwBOw,3030
|
|
6
|
+
contraction_net/prediction.py,sha256=NiXR7Nau9fJUOD4W0SgdiyJ_d9kQ86lp-5gFFfr2pWM,1487
|
|
7
|
+
contraction_net/training.py,sha256=vvi-3t0Oag9xeUbxeLkk2o-xRT10rFatQaZwTFhayzg,7425
|
|
8
|
+
contraction_net/utils.py,sha256=NIleUuqJo0xNE0EYMC9YNqZbiLmfEPvIS9Y81sxZssg,9683
|
|
9
|
+
sarcasm/.DS_Store,sha256=yV4UrPwIOBjajRBgl065FPpmMcziXjRfvHncP22Zia4,6148
|
|
10
|
+
sarcasm/__init__.py,sha256=TJyovGNKxSV0SdpewuVqDkdu3DFZUuqgkbjv3QSYvXQ,868
|
|
11
|
+
sarcasm/_version.py,sha256=Lmqu0RVl6U3AGAbw6R_gvWfsu0LURNR6B8At2WqdDBQ,635
|
|
12
|
+
sarcasm/core.py,sha256=7BNCMhhiGzhD7hjfYWhV72M00kHdCX-AhwBJkFvF-IA,23491
|
|
13
|
+
sarcasm/core_omezarr.py,sha256=-aoV2aAEa9k3sDP5-FpX1s70Fx0A2ADubizPH3hvWzc,30194
|
|
14
|
+
sarcasm/exceptions.py,sha256=LGi6YYLbteUvPtgE6x05-CI1lDHsUpL5Qa2dCpVhP7Q,580
|
|
15
|
+
sarcasm/export.py,sha256=KdkdPNLVcS7LvT6b2H28hhi1VPxVjrVuxRq8LYVEqMM,16523
|
|
16
|
+
sarcasm/feature_dict.py,sha256=ZtVPk0VCW-ru5Nbcco0wctdhCynPZiT-ZdbdBBrAcXs,33082
|
|
17
|
+
sarcasm/ioutils.py,sha256=Wxl1shU4vGjJtMfRUMzkZS5FxGVWQp6AaHhkfZssOpY,4113
|
|
18
|
+
sarcasm/meta_data_handler.py,sha256=-V6W377XlWQ3ex_xhDJOQXaMZfncmxwXPgWlnm-hRcc,4502
|
|
19
|
+
sarcasm/meta_data_handler_omezarr.py,sha256=kG6XLPMz8gh0hiZIJZrf8-dwBPnT3z5vojVkgk1gdPk,9433
|
|
20
|
+
sarcasm/models/model_ContractionNet.pt,sha256=oVoEk34i2lU47UMD9vG8nfMhUUkBB7DY6WH1X_o49x4,7644187
|
|
21
|
+
sarcasm/models/model_sarcomeres_generalist.pt,sha256=d6ymXOFl6882QB44UiCQzpzVGdfMrg3qdKISjQFGc40,35813640
|
|
22
|
+
sarcasm/models/model_z_bands_unet3d.pt,sha256=bKsW2lc9_3jgSAt9LvpLN6B3Nj1i3vkppkdfOApq7SA,6441892
|
|
23
|
+
sarcasm/motion.py,sha256=IxaDPmWKyEiTkeF47yVBEwnJrPr-Auh1EgOeaMm6BFI,47686
|
|
24
|
+
sarcasm/plot_utils.py,sha256=VN2dbFg8BzCQMy_rHAQ4FHoOL9LrUZNPLYEk_lIWbNc,11275
|
|
25
|
+
sarcasm/plots.py,sha256=8feYp3KxzWzMNE-yytRMrJg8xcWEP-oR1sk8_Hy37No,77928
|
|
26
|
+
sarcasm/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
27
|
+
sarcasm/structure.py,sha256=w-Q0W7jVtVpWUYgbiLB6QWhw3gWZ9tsDZImDMyBrcQI,136192
|
|
28
|
+
sarcasm/structure_xarray.py,sha256=28CZo2q_23aJwT2LgqwScGvOm_mk7r4LJF-DVP2c4Jg,144873
|
|
29
|
+
sarcasm/training_data_generation.py,sha256=i9_yznWeUtXsu97pMSPYVeaTBoNSaFRdQNuORU48Btg,49394
|
|
30
|
+
sarcasm/type_utils.py,sha256=NkSoLcfegWxThFSRPAnqfjr-sErCx0jljbjSrd2lTxE,1056
|
|
31
|
+
sarcasm/utils.py,sha256=R1M9tCQt7B6mqAdw2w9aRpnXNiTH4EMVzhd9AzY3lIk,46946
|
|
32
|
+
sarcasm_app/__init__.py,sha256=ste6OgWcvctUmc-6kuGckkvI9bk8LEEknGJNSjLZPJY,11251
|
|
33
|
+
sarcasm_app/__main__.py,sha256=Yd8NpOywuMkm6UlJ-RtLskyls0d5sbZPWxeM7lptSTs,630
|
|
34
|
+
sarcasm_app/control/__init__.py,sha256=tL_aT3Kj_m5aH89Z2rvXZF0nzJGNVw4ZbbloxmugDk8,582
|
|
35
|
+
sarcasm_app/control/application_control.py,sha256=EkxMUTJ54vm8buj_2lmpI_mspxVKZgxO2cZx57_aM2E,28146
|
|
36
|
+
sarcasm_app/control/batch_processing_control.py,sha256=CeNuXcbAiUUt8hUqHo7WzwfZAFr-BIws7OCgKbJyjzA,27825
|
|
37
|
+
sarcasm_app/control/chain_execution.py,sha256=KaZSiv9cS21mv3xYXVB0OdJBK6yjfmATDB4HlcW2lOY,3997
|
|
38
|
+
sarcasm_app/control/file_selection_control.py,sha256=zlfxdyGgKunhZzuaa-IXiXzyUcXj4rvzgah1hneHtu4,14820
|
|
39
|
+
sarcasm_app/control/loi_analysis_control.py,sha256=LE6_pYmWZ6_yBbo-2gzZMW_Pics4adknwFZ68KinOk4,12091
|
|
40
|
+
sarcasm_app/control/motion_analysis_control.py,sha256=MtXRgX1-4vDd-JVpUGfwEsh8xhuKtYOGcTA_LdANzHs,17930
|
|
41
|
+
sarcasm_app/control/popup_export.py,sha256=DlBQvCwlseb2Dczy_dyWIQqnavZbCp8XlwAmCcEYuuU,12103
|
|
42
|
+
sarcasm_app/control/structure_analysis_control.py,sha256=43pf_DIxbXclAdhVPbLmT03rtKWYbih6tSOqbINCtIQ,27899
|
|
43
|
+
sarcasm_app/icons/sarcasm.icns,sha256=hCJ3SSc_MxZmppPga6eVkiDCkogJ5SrHVpYAE1gQllA,60519
|
|
44
|
+
sarcasm_app/icons/sarcasm.ico,sha256=YaHRzv0FJoqoZH55OBv77id-iwF5JDnu8tQF6FEyH0s,410598
|
|
45
|
+
sarcasm_app/model/__init__.py,sha256=9mZNT2MsDj0qf1GaSYcx1KJQJ_rk3WeQ32_9BFI4up8,21558
|
|
46
|
+
sarcasm_app/model/parameter.py,sha256=yIFqSoPuULfXnnZ3FGJB_yEQi2pADr9Rs5LAP50nfE4,5929
|
|
47
|
+
sarcasm_app/model/parameters.py,sha256=g4zBSJ6d8SAq-3cASO_1aYnT37ZJtbAiRLaCy7UdgLY,1975
|
|
48
|
+
sarcasm_app/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
49
|
+
sarcasm_app/ui-files/file_selection.ui,sha256=NYtgyQ7aTBKD0Vl7jbkMVaTiqlrAlpNs4uC2D677gXc,6337
|
|
50
|
+
sarcasm_app/ui-files/parameters_batch_processing.ui,sha256=pjKgfmL-p2qcHs8IETIxCEn43ah85E00LSsHX5m6z40,9301
|
|
51
|
+
sarcasm_app/ui-files/parameters_loi_analysis.ui,sha256=4z4tkDE8o2jPMYm5yXUayQo4bQbBkobF2zTqOWRLz3o,23146
|
|
52
|
+
sarcasm_app/ui-files/parameters_motion_analysis.ui,sha256=rYliTjnnJzLB7o2k3fHPqSjxc6G5mwTHMb193AoOf78,25388
|
|
53
|
+
sarcasm_app/ui-files/parameters_structure_analysis.ui,sha256=DW_K968uT6jLz-PPXsGJ_Am1SPKJcves94uZa3z8ZUc,41700
|
|
54
|
+
sarcasm_app/ui-files/update_py_files.bat,sha256=IgG6iK1HXe2iewrH5x8hbHxP5UoloplEjYeqIVIwnS4,645
|
|
55
|
+
sarcasm_app/view/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
56
|
+
sarcasm_app/view/file_selection.py,sha256=nh5ASFwkL8_pKT20bU_xYWoY4E4Xq0yeRLXfYei5OoY,8374
|
|
57
|
+
sarcasm_app/view/parameters_batch_processing.py,sha256=1QVMUV5v01Omb0VQfO4oMd9PhdexaI0nmHbCjh6rrrw,11443
|
|
58
|
+
sarcasm_app/view/parameters_loi_analysis.py,sha256=oLA_HFUQEHLQGW18uR3FZCuhMBsUXOcEva2TAQhunUE,26748
|
|
59
|
+
sarcasm_app/view/parameters_motion_analysis.py,sha256=lF-xK2oDQSEEKxNCmsomfKm_XEXtSMJ6XJMpF5zlRlI,29638
|
|
60
|
+
sarcasm_app/view/parameters_structure_analysis.py,sha256=-KutSd1Kzx-PkIvUCLBB8wiFgqCUaEK-7uDQ57SP1_k,47218
|
|
61
|
+
sarc_asm-0.2.2.dist-info/LICENSE,sha256=47k1veu2SxFs3mPuojVPsrJIWFuTY-BPKH-fKaZm9-w,1001
|
|
62
|
+
sarc_asm-0.2.2.dist-info/METADATA,sha256=LgmdSizNLt5GuTvoz1XYaGbjmGZPtqWqVpfkoPXGPlo,831
|
|
63
|
+
sarc_asm-0.2.2.dist-info/WHEEL,sha256=IrRNNNJ-uuL1ggO5qMvT1GGhQVdQU54d6ZpYqEZfEWo,92
|
|
64
|
+
sarc_asm-0.2.2.dist-info/RECORD,,
|
sarcasm/.DS_Store
ADDED
|
Binary file
|
sarcasm/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright (c) 2025 University Medical Center Göttingen, Germany.
|
|
3
|
+
# All rights reserved.
|
|
4
|
+
#
|
|
5
|
+
# Patent Pending: DE 10 2024 112 939.5
|
|
6
|
+
# SPDX-License-Identifier: LicenseRef-Proprietary-See-LICENSE
|
|
7
|
+
#
|
|
8
|
+
# This software is licensed under a custom license. See the LICENSE file
|
|
9
|
+
# in the root directory for full details.
|
|
10
|
+
#
|
|
11
|
+
# **Commercial use is prohibited without a separate license.**
|
|
12
|
+
# Contact MBM ScienceBridge GmbH (https://sciencebridge.de/en/) for licensing.
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
from ._version import __version__
|
|
16
|
+
from .core import SarcAsM
|
|
17
|
+
from .structure import Structure
|
|
18
|
+
from .motion import Motion
|
|
19
|
+
from .utils import Utils
|
|
20
|
+
from .ioutils import IOUtils
|
|
21
|
+
from .plots import Plots
|
|
22
|
+
from .plot_utils import PlotUtils
|
|
23
|
+
from .export import MultiStructureAnalysis, MultiLOIAnalysis
|
|
24
|
+
from .type_utils import TypeUtils
|
|
25
|
+
from .training_data_generation import TrainingDataGenerator
|
sarcasm/_version.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright (c) 2025 University Medical Center Göttingen, Germany.
|
|
3
|
+
# All rights reserved.
|
|
4
|
+
#
|
|
5
|
+
# Patent Pending: DE 10 2024 112 939.5
|
|
6
|
+
# SPDX-License-Identifier: LicenseRef-Proprietary-See-LICENSE
|
|
7
|
+
#
|
|
8
|
+
# This software is licensed under a custom license. See the LICENSE file
|
|
9
|
+
# in the root directory for full details.
|
|
10
|
+
#
|
|
11
|
+
# **Commercial use is prohibited without a separate license.**
|
|
12
|
+
# Contact MBM ScienceBridge GmbH (https://sciencebridge.de/en/) for licensing.
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
import importlib.metadata
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
__version__ = importlib.metadata.version("sarc-asm")
|
|
19
|
+
except:
|
|
20
|
+
__version__ = "0.0.0-dev" # Fallback for development
|