-
Notifications
You must be signed in to change notification settings - Fork 377
/
pipeline.py
executable file
·2296 lines (2051 loc) · 101 KB
/
pipeline.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
"""Pipeline.py - an ordered set of modules to be executed
CellProfiler is distributed under the GNU General Public License.
See the accompanying file LICENSE for details.
Copyright (c) 2003-2009 Massachusetts Institute of Technology
Copyright (c) 2009-2012 Broad Institute
All rights reserved.
Please see the AUTHORS file for credits.
Website: http://www.cellprofiler.org
"""
from __future__ import with_statement
__version__ = "$Revision$"
import hashlib
import logging
import gc
import numpy as np
import scipy.io.matlab
import scipy
try:
#implemented in scipy.io.matlab.miobase.py@5582
from scipy.io.matlab.miobase import MatReadError
has_mat_read_error = True
except:
has_mat_read_error = False
import os
import StringIO
import sys
import tempfile
import traceback
import datetime
import traceback
import threading
import urlparse
import urllib2
import re
logger = logging.getLogger(__name__)
pipeline_stats_logger = logging.getLogger("PipelineStatistics")
import cellprofiler.cpmodule
import cellprofiler.preferences as cpprefs
import cellprofiler.cpimage as cpi
import cellprofiler.measurements as cpmeas
import cellprofiler.objects as cpo
import cellprofiler.workspace as cpw
import cellprofiler.settings as cps
from cellprofiler.utilities.utf16encode import utf16encode, utf16decode
from cellprofiler.matlab.cputils import make_cell_struct_dtype, new_string_cell_array, encapsulate_strings_in_arrays
'''The measurement name of the image number'''
IMAGE_NUMBER = cpmeas.IMAGE_NUMBER
GROUP_NUMBER = cpmeas.GROUP_NUMBER
GROUP_INDEX = cpmeas.GROUP_INDEX
CURRENT = 'Current'
NUMBER_OF_IMAGE_SETS = 'NumberOfImageSets'
NUMBER_OF_MODULES = 'NumberOfModules'
SET_BEING_ANALYZED = 'SetBeingAnalyzed'
SAVE_OUTPUT_HOW_OFTEN = 'SaveOutputHowOften'
TIME_STARTED = 'TimeStarted'
STARTING_IMAGE_SET = 'StartingImageSet'
STARTUP_DIRECTORY = 'StartupDirectory'
DEFAULT_MODULE_DIRECTORY = 'DefaultModuleDirectory'
DEFAULT_IMAGE_DIRECTORY = 'DefaultImageDirectory'
DEFAULT_OUTPUT_DIRECTORY = 'DefaultOutputDirectory'
IMAGE_TOOLS_FILENAMES = 'ImageToolsFilenames'
IMAGE_TOOL_HELP = 'ImageToolHelp'
PREFERENCES = 'Preferences'
PIXEL_SIZE = 'PixelSize'
SKIP_ERRORS = 'SkipErrors'
INTENSITY_COLOR_MAP = 'IntensityColorMap'
LABEL_COLOR_MAP = 'LabelColorMap'
STRIP_PIPELINE = 'StripPipeline'
DISPLAY_MODE_VALUE = 'DisplayModeValue'
DISPLAY_WINDOWS = 'DisplayWindows'
FONT_SIZE = 'FontSize'
IMAGES = 'Images'
MEASUREMENTS = 'Measurements'
PIPELINE = 'Pipeline'
SETTINGS = 'Settings'
VARIABLE_VALUES = 'VariableValues'
VARIABLE_INFO_TYPES = 'VariableInfoTypes'
MODULE_NAMES = 'ModuleNames'
PIXEL_SIZE = 'PixelSize'
NUMBERS_OF_VARIABLES = 'NumbersOfVariables'
VARIABLE_REVISION_NUMBERS = 'VariableRevisionNumbers'
MODULE_REVISION_NUMBERS = 'ModuleRevisionNumbers'
MODULE_NOTES = 'ModuleNotes'
CURRENT_MODULE_NUMBER = 'CurrentModuleNumber'
SHOW_WINDOW = 'ShowFrame'
BATCH_STATE = 'BatchState'
EXIT_STATUS = 'Exit_Status'
SETTINGS_DTYPE = np.dtype([(VARIABLE_VALUES, '|O4'),
(VARIABLE_INFO_TYPES, '|O4'),
(MODULE_NAMES, '|O4'),
(NUMBERS_OF_VARIABLES, '|O4'),
(PIXEL_SIZE, '|O4'),
(VARIABLE_REVISION_NUMBERS, '|O4'),
(MODULE_REVISION_NUMBERS, '|O4'),
(MODULE_NOTES, '|O4'),
(SHOW_WINDOW, '|O4'),
(BATCH_STATE, '|O4')])
CURRENT_DTYPE = make_cell_struct_dtype([ NUMBER_OF_IMAGE_SETS,
SET_BEING_ANALYZED, NUMBER_OF_MODULES,
SAVE_OUTPUT_HOW_OFTEN,TIME_STARTED,
STARTING_IMAGE_SET,
STARTUP_DIRECTORY,
DEFAULT_OUTPUT_DIRECTORY,
DEFAULT_IMAGE_DIRECTORY,
IMAGE_TOOLS_FILENAMES,
IMAGE_TOOL_HELP])
PREFERENCES_DTYPE = make_cell_struct_dtype([PIXEL_SIZE,
DEFAULT_MODULE_DIRECTORY,
DEFAULT_OUTPUT_DIRECTORY,
DEFAULT_IMAGE_DIRECTORY,
INTENSITY_COLOR_MAP,
LABEL_COLOR_MAP,
STRIP_PIPELINE, SKIP_ERRORS,
DISPLAY_MODE_VALUE, FONT_SIZE,
DISPLAY_WINDOWS])
'''Save pipeline in Matlab format'''
FMT_MATLAB = "Matlab"
'''Save pipeline in native format'''
FMT_NATIVE = "Native"
'''The current pipeline file format version'''
NATIVE_VERSION = 2
H_VERSION = 'Version'
H_SVN_REVISION = 'SVNRevision'
H_DATE_REVISION = 'DateRevision'
'''A pipeline file header variable for faking a matlab pipeline file'''
H_FROM_MATLAB = 'FromMatlab'
'''The cookie that identifies a file as a CellProfiler pipeline'''
COOKIE = "CellProfiler Pipeline: http://www.cellprofiler.org"
'''HDF5 file header according to the specification
see http://www.hdfgroup.org/HDF5/doc/H5.format.html#FileMetaData
'''
HDF5_HEADER = (chr(137) + chr(72) + chr(68) + chr(70) + chr(13) + chr(10) +
chr (26) + chr(10))
C_PIPELINE = "Pipeline"
F_PIPELINE = "Pipeline"
M_PIPELINE = "_".join((C_PIPELINE,F_PIPELINE))
def add_all_images(handles,image_set, object_set):
""" Add all images to the handles structure passed
Add images to the handles structure, for example in the Python sandwich.
"""
images = {}
for provider in image_set.providers:
name = provider.name()
image = image_set.get_image(name)
images[name] = image.image
if image.has_mask:
images['CropMask'+name] = image.mask
for object_name in object_set.object_names:
objects = object_set.get_objects(object_name)
images['Segmented'+object_name] = objects.segmented
if objects.has_unedited_segmented():
images['UneditedSegmented'+object_name] = objects.unedited_segmented
if objects.has_small_removed_segmented():
images['SmallRemovedSegmented'+object_name] = objects.small_removed_segmented
npy_images = np.ndarray((1,1),dtype=make_cell_struct_dtype(images.keys()))
for key,image in images.iteritems():
npy_images[key][0,0] = image
handles[PIPELINE]=npy_images
def map_feature_names(feature_names, max_size=63):
'''Map feature names to legal Matlab field names
returns a dictionary where the key is the field name and
the value is the feature name.
'''
mapping = {}
seeded = False
def shortest_first(a,b):
return -1 if len(a) < len(b) else 1 if len(b) < len(a) else cmp(a,b)
for feature_name in sorted(feature_names,shortest_first):
if len(feature_name) > max_size:
name = feature_name
to_remove = len(feature_name) - max_size
remove_count = 0
for to_drop in (('a','e','i','o','u'),
('b','c','d','f','g','h','j','k','l','m','n',
'p','q','r','s','t','v','w','x','y','z'),
('A','B','C','D','E','F','G','H','I','J','K',
'L','M','N','O','P','Q','R','S','T','U','V',
'W','X','Y','Z')):
for index in range(len(name)-1,-1,-1):
if name[index] in to_drop:
name = name[:index]+name[index+1:]
remove_count += 1
if remove_count == to_remove:
break
if remove_count == to_remove:
break
if name in mapping.keys() or len(name) > max_size:
# Panic mode - a duplication
if not seeded:
np.random.seed(0)
seeded = True
while True:
npname = np.fromstring(feature_name, '|S1')
indices = np.random.permutation(len(name))[:max_size]
indices.sort()
name = npname[indices]
name = name.tostring()
if not name in mapping.keys():
break
else:
name = feature_name
mapping[name] = feature_name
return mapping
def add_all_measurements(handles, measurements):
"""Add all measurements from our measurements object into the numpy structure passed
"""
object_names = [name for name in measurements.get_object_names()
if len(measurements.get_feature_names(name)) > 0]
measurements_dtype = make_cell_struct_dtype(object_names)
npy_measurements = np.ndarray((1,1),dtype=measurements_dtype)
handles[MEASUREMENTS]=npy_measurements
image_numbers = measurements.get_image_numbers()
max_image_number = np.max(image_numbers)
has_image_number = np.zeros(max_image_number + 1, bool)
has_image_number[image_numbers] = True
for object_name in object_names:
if object_name == cpmeas.EXPERIMENT:
continue
mapping = map_feature_names(measurements.get_feature_names(object_name))
object_dtype = make_cell_struct_dtype(mapping.keys())
object_measurements = np.ndarray((1,1),dtype=object_dtype)
npy_measurements[object_name][0,0] = object_measurements
for field, feature_name in mapping.iteritems():
feature_measurements = np.ndarray((1, max_image_number),
dtype='object')
object_measurements[field][0,0] = feature_measurements
for i in np.argwhere(~ has_image_number[1:]).flatten():
feature_measurements[0, i] = np.zeros(0)
for i in measurements.get_image_numbers():
ddata = measurements.get_measurement(object_name, feature_name, i)
if np.isscalar(ddata) and np.isreal(ddata):
feature_measurements[0, i-1] = np.array([ddata])
elif ddata is not None:
feature_measurements[0,i-1] = ddata
else:
feature_measurements[0, i-1] = np.zeros(0)
if cpmeas.EXPERIMENT in measurements.object_names:
mapping = map_feature_names(measurements.get_feature_names(cpmeas.EXPERIMENT))
object_dtype = make_cell_struct_dtype(mapping.keys())
experiment_measurements = np.ndarray((1,1), dtype=object_dtype)
npy_measurements[cpmeas.EXPERIMENT][0,0] = experiment_measurements
for field, feature_name in mapping.iteritems():
feature_measurements = np.ndarray((1,1),dtype='object')
feature_measurements[0,0] = measurements.get_experiment_measurement(feature_name)
experiment_measurements[field][0,0] = feature_measurements
_evt_modulerunner_done_id = None
_evt_modulerunner_eventtype = None
def evt_modulerunner_done_id():
"""Initialize _evt_modulerunner_done_id inside this function
instead of at the top level so that the module will not require wx
when the GUI stuff is not being used."""
import wx
global _evt_modulerunner_done_id
if _evt_modulerunner_done_id is None:
_evt_modulerunner_done_id = wx.NewId()
return _evt_modulerunner_done_id
def evt_modulerunner_event_type():
"""Initialize the module runner event type"""
import wx
global _evt_modulerunner_eventtype
if _evt_modulerunner_eventtype is None:
_evt_modulerunner_eventtype = wx.NewEventType()
return _evt_modulerunner_eventtype
def evt_modulerunner_done(win, func):
done_id = evt_modulerunner_done_id()
event_type = evt_modulerunner_event_type()
win.Connect(done_id, done_id, event_type, func)
class ModuleRunner(threading.Thread):
"""Worker thread that executes the run() method of a module."""
def __init__(self, module, workspace, notify_window):
super(ModuleRunner, self).__init__()
self.module = module
self.workspace = workspace
self.notify_window = notify_window
self.paused = False
self.exited_run = False
self.exception = None
self.tb = None
workspace.add_disposition_listener(self.on_disposition_changed)
def on_disposition_changed(self, event):
'''Callback to listen for changes in the workspace disposition
This gets called when a module decides to pause, continue,
or cancel running the pipeline. We want to postpone posting done
during pause and post done if we've finished running and
we're switching from paused to not paused
'''
if event.disposition == cpw.DISPOSITION_PAUSE:
self.paused = True
elif self.paused:
self.paused = False
if self.exited_run:
self.post_done()
def run(self):
try:
self.module.run(self.workspace)
except Exception, instance:
self.exception = instance
self.tb = sys.exc_info()[2]
logger.warning("Intercepted exception while running module",
exc_info=True)
if os.getenv('CELLPROFILER_RERAISE') is not None:
raise
if not self.paused:
self.post_done()
self.exited_run = True
def post_done(self):
post_module_runner_done_event(self.notify_window)
def post_module_runner_done_event(window):
import wx
# Defined here because the module should not depend on wx.
class ModuleRunnerDoneEvent(wx.PyEvent):
"""In spite of its name, this event is posted both when a module
runner is done (i.e., when the module's run() method is finished)
and then again when run_with_yield has displayed the module's
results and collected its measurements."""
def __init__(self):
wx.PyEvent.__init__(self)
self.SetEventType(evt_modulerunner_event_type())
self.SetId(evt_modulerunner_done_id())
def RequestMore(self):
"For now, make this work with code written for IdleEvent."
pass
wx.PostEvent(window, ModuleRunnerDoneEvent())
class Pipeline(object):
"""A pipeline represents the modules that a user has put together
to analyze their images.
"""
def __init__(self):
self.__modules = [];
self.__listeners = [];
self.__measurement_columns = {}
self.__measurement_column_hash = None
self.__test_mode = False
self.__settings = []
self.__undo_stack = []
self.__undo_start = None
def copy(self):
'''Create a copy of the pipeline modules and settings'''
fd = StringIO.StringIO()
self.save(fd)
pipeline = Pipeline()
fd.seek(0)
pipeline.load(fd)
return pipeline
def settings_hash(self):
'''Return a hash of the module settings
This function can be used to invalidate a cached calculation
that's based on pipeline settings - if the settings change, the
hash changes and the calculation must be performed again.
We use secure hashing functions which are really good at avoiding
collisions for small changes in data.
'''
h = hashlib.md5()
for module in self.modules():
h.update(module.module_name)
for setting in module.settings():
h.update(setting.unicode_value.encode('utf-8'))
return h.digest()
def create_from_handles(self,handles):
"""Read a pipeline's modules out of the handles structure
"""
self.__modules = [];
try:
settings = handles[SETTINGS][0,0]
module_names = settings[MODULE_NAMES]
except Exception,instance:
logger.error("Failed to load pipeline", exc_info=True)
e = LoadExceptionEvent(instance, None)
self.notify_listeners(e)
return
module_count = module_names.shape[1]
real_module_num = 1
for module_num in range(1,module_count+1):
idx = module_num-1
module_name = module_names[0,idx][0]
module = None
try:
module = self.instantiate_module(module_name)
module.create_from_handles(handles, module_num)
module.module_num = real_module_num
except Exception,instance:
logger.error("Failed to load pipeline", exc_info=True)
number_of_variables = settings[NUMBERS_OF_VARIABLES][0,idx]
module_settings = [settings[VARIABLE_VALUES][idx, i]
for i in range(number_of_variables)]
module_settings = [('' if np.product(x.shape) == 0
else str(x[0])) if isinstance(x, np.ndarray)
else str(x)
for x in module_settings]
event = LoadExceptionEvent(instance,module, module_name,
module_settings)
self.notify_listeners(event)
if event.cancel_run:
# The pipeline is somewhat loaded at this point
# so we break the loop and clean up as well as we can
break
if module is not None:
self.__modules.append(module)
real_module_num += 1
for module in self.__modules:
module.post_pipeline_load(self)
self.notify_listeners(PipelineLoadedEvent())
def instantiate_module(self,module_name):
import cellprofiler.modules
return cellprofiler.modules.instantiate_module(module_name)
def reload_modules(self):
"""Reload modules from source, and attempt to update pipeline to new versions.
Returns True if pipeline was successfully updated.
"""
# clear previously seen errors on reload
import cellprofiler.gui.errordialog
cellprofiler.gui.errordialog.clear_old_errors()
import cellprofiler.modules
reload(cellprofiler.modules)
cellprofiler.modules.reload_modules()
# attempt to reinstantiate pipeline with new modules
try:
self.copy() # if this fails, we probably can't reload
fd = StringIO.StringIO()
self.save(fd)
fd.seek(0)
self.loadtxt(fd, raise_on_error=True)
return True
except Exception, e:
logging.warning("Modules reloaded, but could not reinstantiate pipeline with new versions.", exc_info=True)
return False
def save_to_handles(self):
"""Create a numpy array representing this pipeline
"""
settings = np.ndarray(shape=[1,1],dtype=SETTINGS_DTYPE)
handles = {SETTINGS:settings }
setting = settings[0,0]
# The variables are a (modules,max # of variables) array of cells (objects)
# where an empty cell is a (1,0) array of float64
try:
variable_count = max([len(module.settings()) for module in self.modules()])
except:
for module in self.modules():
if not isinstance(module.settings(), list):
raise ValueError('Module %s.settings() did not return a list\n value: %s'%(module.module_name, module.settings()))
raise
module_count = len(self.modules())
setting[VARIABLE_VALUES] = new_string_cell_array((module_count,variable_count))
# The variable info types are similarly shaped
setting[VARIABLE_INFO_TYPES] = new_string_cell_array((module_count,variable_count))
setting[MODULE_NAMES] = new_string_cell_array((1,module_count))
setting[NUMBERS_OF_VARIABLES] = np.ndarray((1,module_count),
dtype=np.dtype('uint8'))
setting[PIXEL_SIZE] = cpprefs.get_pixel_size()
setting[VARIABLE_REVISION_NUMBERS] =np.ndarray((1,module_count),
dtype=np.dtype('uint8'))
setting[MODULE_REVISION_NUMBERS] = np.ndarray((1,module_count),
dtype=np.dtype('uint16'))
setting[MODULE_NOTES] = new_string_cell_array((1,module_count))
setting[SHOW_WINDOW] = np.ndarray((1,module_count),
dtype=np.dtype('uint8'))
setting[BATCH_STATE] = np.ndarray((1,module_count),
dtype=np.dtype('object'))
for i in range(module_count):
setting[BATCH_STATE][0,i] = np.zeros((0,),np.uint8)
for module in self.modules():
module.save_to_handles(handles)
return handles
def load(self, fd_or_filename):
"""Load the pipeline from a file
fd_or_filename - either the name of a file or a file-like object
"""
filename = None
if hasattr(fd_or_filename,'seek') and hasattr(fd_or_filename,'read'):
fd = fd_or_filename
needs_close = False
elif hasattr(fd_or_filename, 'read') and hasattr(fd_or_filename, 'url'):
# This is a URL file descriptor. Read into a StringIO so that
# seek is available.
fd = StringIO.StringIO()
while True:
text = fd_or_filename.read()
if len(text) == 0:
break
fd.write(text)
fd.seek(0)
elif os.path.exists(fd_or_filename):
fd = open(fd_or_filename,'rb')
needs_close = True
filename = fd_or_filename
else:
# Assume is string URL
parsed_path = urlparse.urlparse(fd_or_filename)
if len(parsed_path.scheme) < 2:
raise IOError("Could not find file, " + fd_or_filename)
fd = urllib2.urlopen(fd_or_filename)
return self.load(fd)
header = fd.read(len(COOKIE))
if header == COOKIE:
fd.seek(0)
self.loadtxt(fd)
return
if needs_close:
fd.close()
else:
fd.seek(0)
if header[:8] == HDF5_HEADER:
if filename is None:
fid, filename = tempfile.mkstemp(".h5")
fd_out = os.fdopen(fid, "wb")
fd_out.write(fd.read())
fd_out.close()
self.load(filename)
os.unlink(filename)
return
else:
m = cpmeas.load_measurements(filename)
pipeline_text = m.get_experiment_measurement(M_PIPELINE)
pipeline_text = pipeline_text.encode('us-ascii')
self.load(StringIO.StringIO(pipeline_text))
return
if has_mat_read_error:
try:
handles=scipy.io.matlab.mio.loadmat(fd_or_filename,
struct_as_record=True)
except MatReadError:
logging.error("Caught exception in Matlab reader\n", exc_info=True)
e = MatReadError(
"%s is an unsupported .MAT file, most likely a measurements file.\nYou can load this as a pipeline if you load it as a pipeline using CellProfiler 1.0 and then save it to a different file.\n" %
fd_or_filename)
self.notify_listeners(LoadExceptionEvent(e, None))
return
except Exception, e:
logging.error("Tried to load corrupted .MAT file: %s\n" % fd_or_filename,
exc_info = True)
self.notify_listeners(LoadExceptionEvent(e, None))
return
else:
handles=scipy.io.matlab.mio.loadmat(fd_or_filename,
struct_as_record=True)
if handles.has_key("handles"):
#
# From measurements...
#
handles=handles["handles"][0,0]
self.create_from_handles(handles)
self.__settings = [[str(setting) for setting in module.settings()]
for module in self.modules()]
self.__undo_stack = []
def loadtxt(self, fd_or_filename, raise_on_error=False):
'''Load a pipeline from a text file
fd_or_filename - either a path to a file or a file-descriptor-like
object.
raise_on_error - if there is an error loading the pipeline, raise an
exception rather than generating a LoadException event.
See savetxt for more comprehensive documentation.
'''
from cellprofiler.utilities.version import version_number as cp_version_number
if hasattr(fd_or_filename,'seek') and hasattr(fd_or_filename,'read'):
fd = fd_or_filename
else:
fd = open(fd_or_filename,'r')
def rl():
'''Read a line from fd'''
try:
line = fd.next()
if line is None:
return None
line = line.strip("\r\n")
return line
except StopIteration:
return None
header = rl()
if header != COOKIE:
raise NotImplementedError('Invalid header: "%s"'%header)
version = NATIVE_VERSION
from_matlab = False
do_utf16_decode = False
while True:
line = rl()
if line is None:
raise ValueError("Pipeline file unexpectedly truncated before module section")
elif len(line.strip()) == 0:
break
kwd, value = line.split(':')
if kwd == H_VERSION:
version = int(value)
if version > NATIVE_VERSION:
raise ValueError("Pipeline file version is %d.\nCellProfiler can only read version %d or less.\nPlease upgrade to the latest version of CellProfiler." %
(version, NATIVE_VERSION))
elif version > 1:
do_utf16_decode = True
elif kwd in (H_SVN_REVISION, H_DATE_REVISION):
pipeline_version = int(value)
CURRENT_VERSION = cp_version_number
if pipeline_version > CURRENT_VERSION:
if cpprefs.get_headless():
logging.warning(
('Your pipeline version is %d but you are '
'running CellProfiler version %d. '
'Loading this pipeline may fail or have '
'unpredictable results.')
% (pipeline_version, CURRENT_VERSION))
else:
try:
import wx
if wx.GetApp():
dlg = wx.MessageDialog(
parent = None,
message = 'Your pipeline version is %d but you are running CellProfiler version %d. \nLoading this pipeline may fail or have unpredictable results. Continue?' % (pipeline_version, CURRENT_VERSION),
caption = 'Pipeline version mismatch',
style = wx.OK | wx.CANCEL | wx.ICON_QUESTION)
if dlg.ShowModal() != wx.ID_OK:
dlg.Destroy()
return None
dlg.Destroy()
else:
raise Exception # fall through to sys.stderr.write
except:
logger.error('Your pipeline version is %d but you are running CellProfiler version %d. \nLoading this pipeline may fail or have unpredictable results.\n' %(pipeline_version, CURRENT_VERSION))
else:
if ((not cpprefs.get_headless()) and
pipeline_version < CURRENT_VERSION):
from cellprofiler.gui.errordialog import show_warning
show_warning(
"Pipeline saved with old version of CellProfiler",
"Your pipeline was saved using an old version\n"
"of CellProfiler (version %d). The current version\n"
"of CellProfiler can load and run this pipeline, but\n"
"if you make changes to it and save, the older version\n"
"of CellProfiler (perhaps the version your collaborator\n"
"has?) may not be able to load it.\n\n"
"You can ignore this warning if you do not plan to save\n"
"this pipeline or if you will only use it with this or\n"
"later versions of CellProfiler." % pipeline_version,
cpprefs.get_warn_about_old_pipeline,
cpprefs.set_warn_about_old_pipeline)
pipeline_stats_logger.info("Pipeline saved with CellProfiler version %d", pipeline_version)
elif kwd == H_FROM_MATLAB:
from_matlab = bool(value)
else:
print line
#
# The module section
#
new_modules = []
module_number = 1
skip_attributes = ['svn_version','module_num']
while True:
line = rl()
if line is None:
break
settings = []
try:
module = None
module_name = None
split_loc = line.find(':')
if split_loc == -1:
raise ValueError("Invalid format for module header: %s" % line)
module_name = line[:split_loc].strip()
attribute_string = line[(split_loc+1):]
#
# Decode the settings
#
last_module = False
while True:
line = rl()
if line is None:
last_module = True
break
if len(line.strip()) == 0:
break
if len(line.split(':')) != 2:
raise ValueError("Invalid format for setting: %s" % line)
text, setting = line.split(':')
setting = setting.decode('string_escape')
if do_utf16_decode:
setting = utf16decode(setting)
settings.append(setting)
#
# Set up the module
#
module_name = module_name.decode('string_escape')
module = self.instantiate_module(module_name)
module.module_num = module_number
#
# Decode the attributes. These are turned into strings using
# repr, so True -> 'True', etc. They are then encoded using
# Pipeline.encode_txt.
#
if (len(attribute_string) < 2 or attribute_string[0] != '[' or
attribute_string[-1] != ']'):
raise ValueError("Invalid format for attributes: %s" %
attribute_string)
attribute_strings = attribute_string[1:-1].split('|')
variable_revision_number = None
# make batch_state decodable from text pipelines
array = np.array
uint8 = np.uint8
for a in attribute_strings:
if len(a.split(':')) != 2:
raise ValueError("Invalid attribute string: %s" % a)
attribute, value = a.split(':')
value = value.decode('string_escape')
value = eval(value)
if attribute == 'variable_revision_number':
variable_revision_number = value
elif attribute in skip_attributes:
pass
else:
setattr(module, attribute, value)
if variable_revision_number is None:
raise ValueError("Module %s did not have a variable revision # attribute" % module_name)
module.set_settings_from_values(settings,
variable_revision_number,
module_name, from_matlab)
except Exception, instance:
if raise_on_error:
raise
logging.error("Failed to load pipeline", exc_info=True)
event = LoadExceptionEvent(instance, module, module_name,
settings)
self.notify_listeners(event)
if event.cancel_run:
break
if module is not None:
new_modules.append(module)
module_number += 1
self.__modules = new_modules
self.__settings = [[str(setting) for setting in module.settings()]
for module in self.modules()]
for module in self.modules():
module.post_pipeline_load(self)
self.notify_listeners(PipelineLoadedEvent())
self.__undo_stack = []
def save(self, fd_or_filename, format=FMT_NATIVE):
"""Save the pipeline to a file
fd_or_filename - either a file descriptor or the name of the file
"""
if format == FMT_MATLAB:
handles = self.save_to_handles()
self.savemat(fd_or_filename,handles)
elif format == FMT_NATIVE:
self.savetxt(fd_or_filename)
else:
raise NotImplementedError("Unknown pipeline file format: %s" %
format)
def encode_txt(self, s):
'''Encode a string for saving in the text format
s - input string
Encode for automatic decoding using the 'string_escape' decoder.
We encode the special characters, '[', ':', '|' and ']' using the '\\x'
syntax.
'''
s = s.encode('string_escape')
s = s.replace(':','\\x3A')
s = s.replace('|','\\x7C')
s = s.replace('[','\\x5B').replace(']','\\x5D')
return s
def savetxt(self, fd_or_filename, modules_to_save = None):
'''Save the pipeline in a text format
fd_or_filename - can be either a "file descriptor" with a "write"
attribute or the path to the file to write.
modules_to_save - if present, the module numbers of the modules to save
The format of the file is the following:
Strings are encoded using a backslash escape sequence. The colon
character is encoded as \\x3A if it should happen to appear in a string
and any non-printing character is encoded using the \\x## convention.
Line 1: The cookie, identifying this as a CellProfiler pipeline file.
The header, i
Line 2: "Version:#" the file format version #
Line 3: "DateRevision:#" the version # of the CellProfiler
that wrote this file (date encoded as int, see cp.utitlities.version)
Line 4: blank
The module list follows. Each module has a header composed of
the module name, followed by attributes to be set on the module
using setattr (the string following the attribute is first evaluated
using eval()). For instance:
Align:[show_window:True|notes='Align my image']
The settings follow. Each setting has text and a value. For instance,
Enter object name:Nuclei
'''
from cellprofiler.utilities.version import version_number
if hasattr(fd_or_filename,"write"):
fd = fd_or_filename
needs_close = False
else:
fd = open(fd_or_filename,"wt")
needs_close = True
fd.write("%s\n"%COOKIE)
fd.write("%s:%d\n" % (H_VERSION, NATIVE_VERSION))
fd.write("%s:%d\n" % (H_DATE_REVISION, version_number))
attributes = ('module_num','svn_version','variable_revision_number',
'show_window','notes','batch_state')
notes_idx = 4
for module in self.modules():
if ((modules_to_save is not None) and
module.module_num not in modules_to_save):
continue
fd.write("\n")
attribute_values = [repr(getattr(module, attribute))
for attribute in attributes]
attribute_values = [self.encode_txt(v) for v in attribute_values]
attribute_strings = [attribute+':'+value
for attribute, value
in zip(attributes, attribute_values)]
attribute_string = '[%s]' % ('|'.join(attribute_strings))
fd.write('%s:%s\n' % (self.encode_txt(module.module_name),
attribute_string))
for setting in module.settings():
setting_text = setting.text
if isinstance(setting_text, unicode):
setting_text = setting_text.encode('utf-8')
else:
setting_text = str(setting_text)
fd.write(' %s:%s\n' % (
self.encode_txt(setting_text),
self.encode_txt(utf16encode(setting.unicode_value))))
if needs_close:
fd.close()
def save_measurements(self, filename, measurements):
"""Save the measurements and the pipeline settings in a Matlab file
filename - name of file to create, or a file-like object
measurements - measurements structure that is the result of running the pipeline
"""
handles = self.build_matlab_handles()
add_all_measurements(handles, measurements)
handles[CURRENT][NUMBER_OF_IMAGE_SETS][0,0] = float(measurements.image_set_number+1)
handles[CURRENT][SET_BEING_ANALYZED][0,0] = float(measurements.image_set_number+1)
#
# For the output file, you have to bury it a little deeper - the root has to have
# a single field named "handles"
#
root = {'handles':np.ndarray((1,1),dtype=make_cell_struct_dtype(handles.keys()))}
for key,value in handles.iteritems():
root['handles'][key][0,0]=value
self.savemat(filename, root)
def write_pipeline_measurement(self, m):
'''Write the pipeline experiment measurement to the measurements'''
assert(isinstance(m, cpmeas.Measurements))
fd = StringIO.StringIO()
self.savetxt(fd)
m.add_measurement(cpmeas.EXPERIMENT, M_PIPELINE, fd.getvalue(),
can_overwrite = True)
def savemat(self, filename, root):
'''Save a handles structure accounting for scipy version compatibility to a filename or file-like object'''
sver = scipy.__version__.split('.')
if (len(sver) >= 2 and sver[0].isdigit() and int(sver[0]) == 0 and
sver[1].isdigit() and int(sver[1]) < 8):
#
# 1-d -> 2-d not done
#
scipy.io.matlab.mio.savemat(filename, root, format='5',
long_field_names=True)
else:
scipy.io.matlab.mio.savemat(filename, root, format='5',
long_field_names = True,
oned_as = 'column')
def build_matlab_handles(self, image_set = None, object_set = None, measurements=None):
handles = self.save_to_handles()
image_tools_dir = os.path.join(cpprefs.cell_profiler_root_directory(),'ImageTools')
if os.access(image_tools_dir, os.R_OK):
image_tools = [str(os.path.split(os.path.splitext(filename)[0])[1])
for filename in os.listdir(image_tools_dir)
if os.path.splitext(filename)[1] == '.m']
else:
image_tools = []
image_tools.insert(0,'Image tools')
npy_image_tools = np.ndarray((1,len(image_tools)),dtype=np.dtype('object'))
for tool,idx in zip(image_tools,range(0,len(image_tools))):
npy_image_tools[0,idx] = tool
current = np.ndarray(shape=[1,1],dtype=CURRENT_DTYPE)
handles[CURRENT]=current
current[NUMBER_OF_IMAGE_SETS][0,0] = [(image_set != None and image_set.legacy_fields.has_key(NUMBER_OF_IMAGE_SETS) and image_set.legacy_fields[NUMBER_OF_IMAGE_SETS]) or 1]
current[SET_BEING_ANALYZED][0,0] = [(measurements and measurements.image_set_number) or 1]
current[NUMBER_OF_MODULES][0,0] = [len(self.__modules)]
current[SAVE_OUTPUT_HOW_OFTEN][0,0] = [1]
current[TIME_STARTED][0,0] = str(datetime.datetime.now())
current[STARTING_IMAGE_SET][0,0] = [1]
current[STARTUP_DIRECTORY][0,0] = cpprefs.cell_profiler_root_directory()
current[DEFAULT_OUTPUT_DIRECTORY][0,0] = cpprefs.get_default_output_directory()
current[DEFAULT_IMAGE_DIRECTORY][0,0] = cpprefs.get_default_image_directory()
current[IMAGE_TOOLS_FILENAMES][0,0] = npy_image_tools
current[IMAGE_TOOL_HELP][0,0] = []
preferences = np.ndarray(shape=(1,1),dtype=PREFERENCES_DTYPE)
handles[PREFERENCES] = preferences
preferences[PIXEL_SIZE][0,0] = cpprefs.get_pixel_size()
preferences[DEFAULT_MODULE_DIRECTORY][0,0] = cpprefs.module_directory()
preferences[DEFAULT_OUTPUT_DIRECTORY][0,0] = cpprefs.get_default_output_directory()
preferences[DEFAULT_IMAGE_DIRECTORY][0,0] = cpprefs.get_default_image_directory()
preferences[INTENSITY_COLOR_MAP][0,0] = 'gray'
preferences[LABEL_COLOR_MAP][0,0] = 'jet'
preferences[STRIP_PIPELINE][0,0] = 'Yes' # TODO - get from preferences
preferences[SKIP_ERRORS][0,0] = 'No' # TODO - get from preferences
preferences[DISPLAY_MODE_VALUE][0,0] = [1] # TODO - get from preferences
preferences[FONT_SIZE][0,0] = [10] # TODO - get from preferences
preferences[DISPLAY_WINDOWS][0,0] = [1 for module in self.__modules] # TODO - UI allowing user to choose whether to display a window
images = {}
if image_set:
for provider in image_set.providers:
image = image_set.get_image(provider.name)
if image.image != None:
images[provider.name]=image.image
if image.mask != None:
images['CropMask'+provider.name]=image.mask
for key,value in image_set.legacy_fields.iteritems():
if key != NUMBER_OF_IMAGE_SETS:
images[key]=value
if object_set:
for name,objects in object_set.all_objects:
images['Segmented'+name]=objects.segmented
if objects.has_unedited_segmented():
images['UneditedSegmented'+name] = objects.unedited_segmented
if objects.has_small_removed_segmented():
images['SmallRemovedSegmented'+name] = objects.small_removed_segmented