/
myutils.py
3136 lines (2753 loc) · 106 KB
/
myutils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import pathlib
import difflib
import sys
import platform
import tempfile
import shutil
import traceback
import logging
import datetime
import time
import subprocess
import importlib
from uuid import uuid4
from importlib import import_module
from math import pow, ceil, floor
from functools import wraps, partial
from collections import namedtuple, Counter
from tqdm import tqdm
import requests
import zipfile
import numpy as np
import pandas as pd
import skimage
import inspect
import typing
from natsort import natsorted
import tifffile
import skimage.io
import skimage.measure
from . import GUI_INSTALLED, KNOWN_EXTENSIONS
if GUI_INSTALLED:
from qtpy.QtWidgets import QMessageBox
from qtpy.QtCore import Signal, QObject, QCoreApplication
from . import widgets, apps
from . import config
from . import core, load
from . import html_utils, is_linux, is_win, is_mac, issues_url, is_mac_arm64
from . import cellacdc_path, printl, settings_folderpath, logs_path
from . import user_profile_path, recentPaths_path
from . import models_list_file_path
from . import github_home_url
from . import try_input_install_package
from . import _warnings
from . import urls
ArgSpec = namedtuple('ArgSpec', ['name', 'default', 'type', 'desc', 'docstring'])
def get_module_name(script_file_path):
parts = pathlib.Path(script_file_path).parts
parts = list(parts[parts.index('cellacdc')+1:])
parts[-1] = os.path.splitext(parts[-1])[0]
module = '.'.join(parts)
return module
def get_pos_status(pos_path):
images_path = os.path.join(pos_path, 'Images')
ls = listdir(images_path)
for file in ls:
if file.endswith('acdc_output.csv'):
acdc_df_path = os.path.join(images_path, file)
break
else:
return ''
acdc_df = pd.read_csv(acdc_df_path)
last_tracked_i = acdc_df['frame_i'].max()
last_cca_i = 0
if 'cell_cycle_stage' in acdc_df.columns:
cca_df = acdc_df[['frame_i', 'cell_cycle_stage']].dropna()
last_cca_i = cca_df['frame_i'].max()
if last_cca_i > 0:
return (
f' (last tracked frame = {last_tracked_i+1}, '
f'last annotated frame = {last_cca_i+1})'
)
else:
return f' (last tracked frame = {last_tracked_i+1})'
def get_gdrive_path():
if is_win:
return os.path.join(f'G:{os.sep}', 'My Drive')
elif is_mac:
return os.path.join(
'/Users/francesco.padovani/Library/CloudStorage/'
'GoogleDrive-padovaf@tcd.ie/My Drive'
)
def get_acdc_data_path():
Cell_ACDC_path = os.path.dirname(cellacdc_path)
return os.path.join(Cell_ACDC_path, 'data')
def get_open_filemaneger_os_string():
if is_win:
return 'Show in Explorer...'
elif is_mac:
return 'Reveal in Finder...'
elif is_linux:
return 'Show in File Manager...'
def filterCommonStart(images_path):
startNameLen = 6
ls = listdir(images_path)
if not ls:
return []
allFilesStartNames = [f[:startNameLen] for f in ls]
mostCommonStart = Counter(allFilesStartNames).most_common(1)[0][0]
commonStartFilenames = [f for f in ls if f.startswith(mostCommonStart)]
return commonStartFilenames
def get_salute_string():
time_now = datetime.datetime.now().time()
time_end_morning = datetime.time(12,00,00)
time_end_lunch = datetime.time(13,00,00)
time_end_afternoon = datetime.time(15,00,00)
time_end_evening = datetime.time(20,00,00)
time_end_night = datetime.time(4,00,00)
if time_now >= time_end_night and time_now < time_end_morning:
return 'Have a good day!'
elif time_now >= time_end_morning and time_now < time_end_lunch:
return 'Enjoy your lunch!'
elif time_now >= time_end_lunch and time_now < time_end_afternoon:
return 'Have a good afternoon!'
elif time_now >= time_end_afternoon and time_now < time_end_evening:
return 'Have a good evening!'
else:
return 'Have a good night!'
def remove_known_extension(name):
for ext in KNOWN_EXTENSIONS:
if name.endswith(ext):
return name[:-len(ext)], ext
return name, ''
def getCustomAnnotTooltip(annotState):
toolTip = (
f'Name: {annotState["name"]}\n\n'
f'Type: {annotState["type"]}\n\n'
f'Usage: activate the button and RIGHT-CLICK on cell to annotate\n\n'
f'Description: {annotState["description"]}\n\n'
f'SHORTCUT: "{annotState["shortcut"]}"'
)
return toolTip
def trim_path(path, depth=3, start_with_dots=True):
path_li = os.path.abspath(path).split(os.sep)
rel_path = f'{f"{os.sep}".join(path_li[-depth:])}'
if start_with_dots:
return f'...{os.sep}{rel_path}'
else:
return rel_path
def get_add_custom_model_instructions():
url = 'https://github.com/SchmollerLab/Cell_ACDC/issues'
user_manual_url = 'https://github.com/SchmollerLab/Cell_ACDC/blob/main/UserManual/Cell-ACDC_User_Manual.pdf'
href_user_manual = f'<a href="{user_manual_url}">user manual</a>'
href = f'<a href="{url}">here</a>'
models_path = os.path.join(cellacdc_path, 'models')
func_color = (111/255,66/255,205/255) # purplish
kwargs_color = (208/255,88/255,9/255) # reddish/orange
class_color = (215/255,58/255,73/255) # reddish
blue_color = (0/255,92/255,197/255) # blueish
class_sh = html_utils.class_sh
def_sh = html_utils.def_sh
kwargs_sh = html_utils.kwargs_sh
Model_sh = html_utils.Model_sh
segment_sh = html_utils.segment_sh
predict_sh = html_utils.predict_sh
init_sh = html_utils.init_sh
myModel_sh = html_utils.myModel_sh
return_sh = html_utils.return_sh
equal_sh = html_utils.equal_sh
open_par_sh = html_utils.open_par_sh
close_par_sh = html_utils.close_par_sh
image_sh = html_utils.image_sh
from_sh = html_utils.from_sh
import_sh = html_utils.import_sh
s = html_utils.paragraph(f"""
To use a custom model first <b>create a folder</b> with the same name of your model.<br><br>
Inside this new folder create a file named <code>acdcSegment.py</code>.<br><br>
In the <code>acdcSegment.py</code> file you will <b>implement the model class</b>.<br><br>
Have a look at the other existing models, but essentially you have to create
a class called <code>Model</code> with at least<br>
the <code>{init_sh}</code> and the <code>{segment_sh}</code> method.<br><br>
The <code>{segment_sh}</code> method takes the image (2D or 3D) as an input and return the segmentation mask.<br><br>
You can find more details in the {href_user_manual} at the section
called <code>Adding segmentation models to the pipeline</code>.<br><br>
Pseudo-code for the <code>acdcSegment.py</code> file:
<pre><code>
{from_sh} myModel {import_sh} {myModel_sh}
{class_sh} {Model_sh}:
{def_sh} {init_sh}(self, {kwargs_sh}):
self.model {equal_sh} {myModel_sh}{open_par_sh}{close_par_sh}
{def_sh} {segment_sh}(self, {image_sh}, {kwargs_sh}):
labels {equal_sh} self.model.{predict_sh}{open_par_sh}{image_sh}{close_par_sh}
{return_sh} labels
</code></pre>
If it doesn't work, please report the issue {href} with the
code you wrote. Thanks.
""")
return s, models_path
def is_iterable(item):
try:
iter(item)
return True
except TypeError as e:
return False
class utilClass:
pass
def get_trimmed_list(li: list, max_num_digits=10):
li_str = li.copy()
tom_num_digits = sum([len(str(val)) for val in li])
avg_num_digits = tom_num_digits/len(li)
max_num_vals = int(round(max_num_digits/avg_num_digits))
if tom_num_digits>max_num_digits:
del li_str[max_num_vals:-max_num_vals]
li_str.insert(max_num_vals, "...")
li_str = f"[{', '.join(map(str, li_str))}]"
return li_str
def _bytes_to_MB(size_bytes):
factor = pow(2, -20)
size_MB = round(size_bytes*factor)
return size_MB
def _bytes_to_GB(size_bytes):
factor = pow(2, -30)
size_GB = round(size_bytes*factor, 2)
return size_GB
def getMemoryFootprint(files_list):
required_memory = sum([
48 if file.endswith('.h5') else os.path.getsize(file)
for file in files_list
])
return required_memory
def get_logs_path():
return logs_path
class Logger(logging.Logger):
def __init__(
self,
module='base',
name='cellacdc-logger',
level=logging.DEBUG
):
super().__init__(f'{name}-{module}', level=level)
self._stdout = sys.stdout
def write(self, text, log_to_file=True):
"""Capture print statements, print to terminal and log text to
the open log file
Parameters
----------
text : str
Text to log
log_to_file : bool, optional
If True, call `info` method with `text`. Default is True
"""
self._stdout.write(text)
if not log_to_file:
return
if text == '\n':
return
if not text:
return
self.debug(text)
def close(self):
for handler in self.handlers:
handler.close()
self.removeHandler(handler)
sys.stdout = self._stdout
def __del__(self):
sys.stdout = self._stdout
def info(self, text, *args, **kwargs):
super().info(text, *args, **kwargs)
self.write(f'{text}\n', log_to_file=False)
def warning(self, text, *args, **kwargs):
super().warning(text, *args, **kwargs)
self.write(f'[WARNING]: {text}\n', log_to_file=False)
def error(self, text, *args, **kwargs):
super().error(text, *args, **kwargs)
self.write(f'[ERROR]: {text}\n', log_to_file=False)
def critical(self, text, *args, **kwargs):
super().critical(text, *args, **kwargs)
self.write(f'[CRITICAL]: {text}\n', log_to_file=False)
def exception(self, text, *args, **kwargs):
super().exception(text, *args, **kwargs)
self.write(f'[ERROR]: {text}\n', log_to_file=False)
def log(self, level, text):
super().log(level, text)
levelName = logging.getLevelName(level)
getattr(self, levelName.lower())(text)
# self.write(f'[{levelName}]: {text}\n', log_to_file=False)
def flush(self):
self._stdout.flush()
def delete_older_log_files(logs_path):
if not os.path.exists(logs_path):
return
log_files = os.listdir(logs_path)
for log_file in log_files:
if not log_file.endswith('.log'):
continue
log_filepath = os.path.join(logs_path, log_file)
try:
mtime = os.path.getmtime(log_filepath)
except Exception as err:
continue
mdatetime = datetime.datetime.fromtimestamp(mtime)
days = (datetime.datetime.now() - mdatetime).days
if days < 7:
continue
try:
os.remove(log_filepath)
except Exception as err:
continue
def setupLogger(module='base', logs_path=None):
if logs_path is None:
logs_path = get_logs_path()
logger = Logger(module=module)
sys.stdout = logger
delete_older_log_files(logs_path)
if not os.path.exists(logs_path):
os.mkdir(logs_path)
date_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
id = uuid4()
log_filename = f'.{date_time}_{module}_{id}_stdout.log'
log_path = os.path.join(logs_path, log_filename)
output_file_handler = logging.FileHandler(log_path, mode='w')
# Format your logs (optional)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s:\n'
'------------------------\n'
'%(message)s\n'
'------------------------\n',
datefmt='%d-%m-%Y, %H:%M:%S'
)
output_file_handler.setFormatter(formatter)
logger.addHandler(output_file_handler)
logger.info(f'Initialized log file "{log_path}"')
py_ver = sys.version_info
python_version = f'{py_ver.major}.{py_ver.minor}.{py_ver.micro}'
logger.info(f'Running Python v{python_version} from "{sys.exec_prefix}"')
if GUI_INSTALLED:
from qtpy import QtCore
logger.info(f'Using Qt version {QtCore.__version__}')
logger.info(f'Cell-ACDC installation directory: "{cellacdc_path}"')
logger.info(f'System version: {sys.version}')
logger.info(f'Platform: {platform.platform()}')
# if module == 'gui' and GUI_INSTALLED:
# qt_handler = widgets.QtHandler()
# qt_handler.setFormatter(logging.Formatter("%(message)s"))
# logger.addHandler(qt_handler)
return logger, logs_path, log_path, log_filename
def get_pos_foldernames(exp_path):
ls = listdir(exp_path)
pos_foldernames = [
pos for pos in ls if pos.find('Position_')!=-1
and os.path.isdir(os.path.join(exp_path, pos))
and os.path.exists(os.path.join(exp_path, pos, 'Images'))
]
return pos_foldernames
def getMostRecentPath():
if os.path.exists(recentPaths_path):
df = pd.read_csv(recentPaths_path, index_col='index')
if 'opened_last_on' in df.columns:
df = df.sort_values('opened_last_on', ascending=False)
MostRecentPath = ''
for path in df['path']:
if os.path.exists(path):
MostRecentPath = path
break
else:
MostRecentPath = ''
return MostRecentPath
def addToRecentPaths(exp_path, logger=None):
if not os.path.exists(exp_path):
return
exp_path = exp_path.replace('\\', '/')
if os.path.exists(recentPaths_path):
try:
df = pd.read_csv(recentPaths_path, index_col='index')
recentPaths = df['path'].to_list()
if 'opened_last_on' in df.columns:
openedOn = df['opened_last_on'].to_list()
else:
openedOn = [np.nan]*len(recentPaths)
if exp_path in recentPaths:
pop_idx = recentPaths.index(exp_path)
recentPaths.pop(pop_idx)
openedOn.pop(pop_idx)
recentPaths.insert(0, exp_path)
openedOn.insert(0, datetime.datetime.now())
# Keep max 40 recent paths
if len(recentPaths) > 40:
recentPaths.pop(-1)
openedOn.pop(-1)
except Exception as e:
recentPaths = [exp_path]
openedOn = [datetime.datetime.now()]
else:
recentPaths = [exp_path]
openedOn = [datetime.datetime.now()]
df = pd.DataFrame({
'path': recentPaths,
'opened_last_on': pd.Series(openedOn, dtype='datetime64[ns]')}
)
df.index.name = 'index'
df.to_csv(recentPaths_path)
def checkDataIntegrity(filenames, parent_path, parentQWidget=None):
char = filenames[0][:2]
startWithSameChar = all([f.startswith(char) for f in filenames])
if not startWithSameChar:
msg = widgets.myMessageBox()
txt = html_utils.paragraph(
'Cell-ACDC detected files inside the folder '
'that <b>do not start with the same, common basename</b>.<br><br>'
'To ensure correct loading of the data, the folder where '
'the file(s) is/are should either contain a single image file or'
'only files that start with the same, common basename.<br><br>'
'For example the following filenames:<br><br>'
'<code>F014_s01_phase_contr.tif</code><br>'
'<code>F014_s01_mCitrine.tif</code><br><br>'
'are named correctly since they all start with the '
'the common basename "F014_s01_". After the common basename you '
'can write whatever text you want. In the example above, "phase_contr" '
'and "mCitrine" are the channel names.<br><br>'
'Data loading may still be successfull, so Cell-ACDC will '
'still try to load data now.<br>'
)
filesFormat = [f' - {file}' for file in filenames]
filesFormat = "\n".join(filesFormat)
detailsText = (
f'Files present in the folder {parent_path}:\n\n'
f'{filesFormat}'
)
msg.addShowInFileManagerButton(parent_path, txt='Open folder...')
msg.warning(
parentQWidget, 'Data structure compromised', txt,
detailsText=detailsText, buttonsTexts=('Cancel', 'Ok')
)
if msg.cancel:
raise TypeError(
'Process aborted by the user.'
)
return False
return True
def get_cca_colname_desc():
desc = {
'Cell ID': (
'ID of the segmented cell. All of the other columns '
'are properties of this ID.'
),
'Cell cycle stage': (
'G1 if the cell does NOT have a bud. S/G2/M if it does.'
),
'Relative ID': (
'ID of the bud related to the Cell ID (row). For cells in G1 write the '
'bud ID it had in the previous cycle.'
),
'Generation number': (
'Number of times the cell divided from a bud. For cells in the first '
'frame write any number greater than 1.'
),
'Relationship': (
'Relationship of the current Cell ID (row). '
'Either <b>mother</b> or <b>bud</b>. An object is a bud if '
'it didn\'t divide from the mother yet. All other instances '
'(e.g., cell in G1) are still labelled as mother.'
),
'Emerging frame num.': (
'Frame number at which the object emerged/appeared in the scene.'
),
'Division frame num.': (
'Frame number at which the bud separated from the mother.'
),
'Is history known?': (
'Cells that are already present in the first frame or appears '
'from outside of the field of view, have some information missing. '
'For example, for cells in the first frame we do not know how many '
'times it budded and divided in the past. '
'In these cases Is history known? is True.'
)
}
return desc
def testQcoreApp():
print(QCoreApplication.instance())
def store_custom_model_path(model_file_path):
model_file_path = model_file_path.replace('\\', '/')
model_name = os.path.basename(os.path.dirname(model_file_path))
cp = config.ConfigParser()
if os.path.exists(models_list_file_path):
cp.read(models_list_file_path)
if model_name not in cp:
cp[model_name] = {}
cp[model_name]['path'] = model_file_path
with open(models_list_file_path, 'w') as configFile:
cp.write(configFile)
def check_git_installed(parent=None):
try:
subprocess.check_call(['git', '--version'], shell=True)
return True
except Exception as e:
print('='*20)
traceback.print_exc()
print('='*20)
git_url = 'https://git-scm.com/book/en/v2/Getting-Started-Installing-Git'
msg = widgets.myMessageBox()
txt = html_utils.paragraph(f"""
In order to install <code>javabridge</code> you first need to <b>install
Git</b> (it was not found).<br><br>
<b>Close Cell-ACDC</b> and follow the instructions
{html_utils.tag('here', f'a href="{git_url}"')}.<br><br>
<i><b>NOTE</b>: After installing Git you might need to <b>restart the
terminal</b></i>.
""")
msg.warning(
parent, 'Git not installed', txt
)
return False
def browse_url(url):
import webbrowser
webbrowser.open(url)
def browse_docs():
browse_url(urls.docs_homepage)
def install_java():
try:
subprocess.check_call(['javac', '-version'], shell=True)
return False
except Exception as e:
from . import widgets
win = widgets.installJavaDialog()
win.exec_()
return win.clickedButton == win.cancelButton
def install_javabridge(force_compile=False, attempt_uninstall_first=False):
if attempt_uninstall_first:
try:
subprocess.check_call(
[sys.executable, '-m', 'pip', 'uninstall', '-y', 'javabridge']
)
except Exception as e:
pass
if sys.platform.startswith('win'):
if force_compile:
subprocess.check_call(
[sys.executable, '-m', 'pip', 'install', '-U',
'git+https://github.com/SchmollerLab/python-javabridge-acdc']
)
else:
subprocess.check_call(
[sys.executable, '-m', 'pip', 'install', '-U',
'git+https://github.com/SchmollerLab/python-javabridge-windows']
)
elif is_mac:
subprocess.check_call(
[sys.executable, '-m', 'pip', 'install', '-U',
'git+https://github.com/SchmollerLab/python-javabridge-acdc']
)
elif is_linux:
subprocess.check_call(
[sys.executable, '-m', 'pip', 'install', '-U',
'git+https://github.com/LeeKamentsky/python-javabridge.git@master']
)
def is_in_bounds(x,y,X,Y):
in_bounds = x >= 0 and x < X and y >= 0 and y < Y
return in_bounds
def read_version(logger=None, return_success=False):
cellacdc_parent_path = os.path.dirname(cellacdc_path)
cellacdc_parent_folder = os.path.basename(cellacdc_parent_path)
if cellacdc_parent_folder == 'site-packages':
from . import __version__
version = __version__
success = True
else:
try:
from setuptools_scm import get_version
version = get_version(root='..', relative_to=__file__)
success = True
except Exception as e:
if logger is None:
logger = print
logger('*'*40)
logger(traceback.format_exc())
logger('-'*40)
logger(
'[WARNING]: Cell-ACDC could not determine the current version. '
'See details above.'
)
logger('='*40)
try:
from . import _version
version = _version.version
success = False
except Exception as e:
version = 'ND'
success = False
if return_success:
return version, success
else:
return version
def showInExplorer(path):
if is_mac:
os.system(f'open "{path}"')
elif is_linux:
os.system(f'xdg-open "{path}"')
else:
os.startfile(path)
def exec_time(func):
@wraps(func)
def inner_function(self, *args, **kwargs):
t0 = time.perf_counter()
if func.__code__.co_argcount==1 and func.__defaults__ is None:
result = func(self)
elif func.__code__.co_argcount>1 and func.__defaults__ is None:
result = func(self, *args)
else:
result = func(self, *args, **kwargs)
t1 = time.perf_counter()
s = f'{func.__name__} execution time = {(t1-t0)*1000:.3f} ms'
printl(s, is_decorator=True)
return result
return inner_function
def setRetainSizePolicy(widget, retain=True):
sp = widget.sizePolicy()
sp.setRetainSizeWhenHidden(retain)
widget.setSizePolicy(sp)
def getAcdcDfSegmPaths(images_path):
ls = listdir(images_path)
basename = getBasename(ls)
paths = {}
for file in ls:
filePath = os.path.join(images_path, file)
fileName, ext = os.path.splitext(file)
endName = fileName[len(basename):]
if endName.find('acdc_output') != -1 and ext=='.csv':
info_name = endName.replace('acdc_output', '')
paths.setdefault(info_name, {})
paths[info_name]['acdc_df_path'] = filePath
paths[info_name]['acdc_df_filename'] = fileName
elif endName.find('segm') != -1 and ext=='.npz':
info_name = endName.replace('segm', '')
paths.setdefault(info_name, {})
paths[info_name]['segm_path'] = filePath
paths[info_name]['segm_filename'] = fileName
return paths
def getChannelFilePath(images_path, chName):
file = ''
alignedFilePath = ''
tifFilePath = ''
h5FilePath = ''
for file in listdir(images_path):
filePath = os.path.join(images_path, file)
if file.endswith(f'{chName}_aligned.npz'):
alignedFilePath = filePath
elif file.endswith(f'{chName}.tif'):
tifFilePath = filePath
elif file.endswith(f'{chName}.h5'):
h5FilePath = filePath
if alignedFilePath:
return alignedFilePath
elif h5FilePath:
return h5FilePath
elif tifFilePath:
return tifFilePath
else:
return ''
def get_number_fstring_formatter(dtype, precision=4):
if np.issubdtype(dtype, np.integer):
return 'd'
else:
return f'.{precision}f'
def get_chname_from_basename(filename, basename, remove_ext=True):
if remove_ext:
filename, ext = os.path.splitext(filename)
chName = filename[len(basename):]
aligned_idx = chName.find('_aligned')
if aligned_idx != -1:
chName = chName[:aligned_idx]
return chName
def getBaseAcdcDf(rp):
zeros_list = [0]*len(rp)
nones_list = [None]*len(rp)
minus1_list = [-1]*len(rp)
IDs = []
xx_centroid = []
yy_centroid = []
for obj in rp:
xc, yc = obj.centroid[-2:]
IDs.append(obj.label)
xx_centroid.append(xc)
yy_centroid.append(yc)
df = pd.DataFrame(
{
'Cell_ID': IDs,
'is_cell_dead': zeros_list,
'is_cell_excluded': zeros_list,
'x_centroid': xx_centroid,
'y_centroid': yy_centroid,
'was_manually_edited': minus1_list
}
).set_index('Cell_ID')
return df
def getBasenameAndChNames(images_path, useExt=None):
_tempPosData = utilClass()
_tempPosData.images_path = images_path
load.loadData.getBasenameAndChNames(_tempPosData, useExt=useExt)
return _tempPosData.basename, _tempPosData.chNames
def getBasename(files):
basename = files[0]
for file in files:
# Determine the basename based on intersection of all files
_, ext = os.path.splitext(file)
sm = difflib.SequenceMatcher(None, file, basename)
i, j, k = sm.find_longest_match(
0, len(file), 0, len(basename)
)
basename = file[i:i+k]
return basename
def findalliter(patter, string):
"""Function used to return all re.findall objects in string"""
m_test = re.findall(r'(\d+)_(.+)', string)
m_iter = [m_test]
while m_test:
m_test = re.findall(r'(\d+)_(.+)', m_test[0][1])
m_iter.append(m_test)
return m_iter
def clipSelemMask(mask, shape, Yc, Xc, copy=True):
if copy:
mask = mask.copy()
Y, X = shape
h, w = mask.shape
# Bottom, Left, Top, Right global coordinates of mask
Y0, X0, Y1, X1 = Yc-(h/2), Xc-(w/2), Yc+(h/2), Xc+(w/2)
mask_limits = [floor(Y0)+1, floor(X0)+1, floor(Y1)+1, floor(X1)+1]
if Y0>=0 and X0>=0 and Y1<=Y and X1<=X:
# Mask is withing shape boundaries, no need to clip
ystart, xstart, yend, xend = mask_limits
mask_slice = slice(ystart, yend), slice(xstart, xend)
return mask, mask_slice
if Y0<0:
# Mask is exceeding at the bottom
ystart = floor(abs(Y0))
mask_limits[0] = 0
mask = mask[ystart:]
if X0<0:
# Mask is exceeding at the left
xstart = floor(abs(X0))
mask_limits[1] = 0
mask = mask[:, xstart:]
if Y1>Y:
# Mask is exceeding at the top
yend = ceil(abs(Y1)) - Y
mask_limits[2] = Y
mask = mask[:-yend]
if X1>X:
# Mask is exceeding at the right
xend = ceil(abs(X1)) - X
mask_limits[3] = X
mask = mask[:, :-xend]
ystart, xstart, yend, xend = mask_limits
mask_slice = slice(ystart, yend), slice(xstart, xend)
return mask, mask_slice
def listdir(path):
return natsorted([
f for f in os.listdir(path)
if not f.startswith('.')
and not f == 'desktop.ini'
and not f == 'recovery'
])
def insertModelArgSpect(
params, param_name, param_value, param_type=None, desc='',
docstring=''
):
updated_params = []
for param in params:
if param.name == param_name:
if param_type is None:
param_type = param.type
new_param = ArgSpec(
name=param_name, default=param_value, type=param_type,
desc=desc, docstring=docstring
)
updated_params.append(new_param)
else:
updated_params.append(param)
return updated_params
def getModelArgSpec(acdcSegment):
init_ArgSpec = inspect.getfullargspec(acdcSegment.Model.__init__)
init_kwargs_type_hints = typing.get_type_hints(acdcSegment.Model.__init__)
init_doc = acdcSegment.Model.__init__.__doc__
init_params = params_to_ArgSpec(
init_ArgSpec, init_kwargs_type_hints, init_doc
)
init_params = add_segm_data_param(init_params, init_ArgSpec)
segment_ArgSpec = inspect.getfullargspec(acdcSegment.Model.segment)
segment_kwargs_type_hints = typing.get_type_hints(acdcSegment.Model.segment)
try:
segment_ArgSpec.args.remove('frame_i')
except Exception as e:
pass
segment_doc = acdcSegment.Model.segment.__doc__
segment_params = params_to_ArgSpec(
segment_ArgSpec, segment_kwargs_type_hints, segment_doc,
)
return init_params, segment_params
def _get_doc_stop_idx(docstring, start_idx, next_param_name=None, debug=False):
if debug:
import pdb; pdb.set_trace()
if next_param_name is not None:
doc_stop_idx = docstring.find(f'{next_param_name} : ')
if doc_stop_idx > 1:
return doc_stop_idx
docstring_from_start = docstring[start_idx:]
next_param_searched = re.search(r'\w+ : ', docstring_from_start)
if next_param_searched is not None:
return next_param_searched.start(0) + start_idx
doc_stop_idx = docstring.find('Returns')
if doc_stop_idx > 1:
return doc_stop_idx
doc_stop_idx = docstring.find('Notes')
if doc_stop_idx > 1:
return doc_stop_idx
return -1
def parse_model_param_doc(name, next_param_name=None, docstring=None):
if not docstring:
return ''
try:
# Extract parameter description from 'param : ...'
start_text = f'{name} : '
if docstring.find(start_text) == -1:
# Parameter not present in docstring
return ''
doc_start_idx = docstring.find(start_text) + len(start_text)
doc_stop_idx = _get_doc_stop_idx(
docstring, doc_start_idx, next_param_name=next_param_name
)
if doc_stop_idx == -1:
doc_stop_idx = len(docstring)
param_doc = docstring[doc_start_idx:doc_stop_idx]
# Start at first end of line
param_doc = param_doc[param_doc.find('\n')+1:]
# Replace multiples spaces with single space
param_doc = re.sub(' +', ' ', param_doc)
# Remove trailing spaces
param_doc = param_doc.strip()
except Exception as err:
param_doc = ''
param_doc = param_doc.replace(', optional', '')
return param_doc
def add_segm_data_param(init_params, init_argspecs):
if init_argspecs.defaults is None:
num_kwargs = 0
else:
num_kwargs = len(init_argspecs.defaults)
# Segm model requires segm data --> add it to params
num_args = len(init_argspecs.args) - num_kwargs
if num_args == 1:
# Args is only self --> segm data not needed
return init_params
desc = (
'This model requires an additional segmentation file as input.\n\n'
'Please, select which segmentation file to provide to the model.'
)
segm_data_argspec = ArgSpec(
name='Auxiliary segmentation file',
default='',
type=str,
desc=desc,
docstring=None
)
init_params.insert(0, segm_data_argspec)
return init_params
def params_to_ArgSpec(
fullargspecs, type_hints, docstring, args_to_skip=None
):
params = []
if fullargspecs.defaults is None:
return params
if args_to_skip is None:
args_to_skip = set()
num_params = len(fullargspecs.args)
ip = num_params - len(fullargspecs.defaults)
if ip < 0:
return params
for arg, default in zip(fullargspecs.args[ip:], fullargspecs.defaults):
if arg in args_to_skip:
continue