/
populate_roi.py
1342 lines (1170 loc) · 50.6 KB
/
populate_roi.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
...
"""
#
# Copyright (C) 2009 University of Dundee. All rights reserved.
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
import tempfile
import logging
import time
import sys
import csv
import re
from threading import Thread
from getpass import getpass
from getopt import getopt, GetoptError
from Queue import Queue
from omero.rtypes import rdouble, rstring, rint, unwrap
from omero.model import OriginalFileI, PlateI, PlateAnnotationLinkI, ImageI, \
FileAnnotationI, RoiI, EllipseI, PointI
from omero.grid import ImageColumn, WellColumn, RoiColumn, LongColumn, \
DoubleColumn
from omero.sys import ParametersI
from omero.util.temp_files import create_path
from omero import client
from xml.etree.cElementTree import ElementTree, iterparse
log = logging.getLogger("omero.util.populate_roi")
def usage(error):
"""Prints usage so that we don't have to. :)"""
cmd = sys.argv[0]
print """%s
Usage: %s [-s hostname] [-u username | -k session_key] <-p port> [plate_id]
Runs measurement population code for a given plate.
Options:
-s OMERO hostname to use
-p OMERO port to use [defaults to 4064]
-u OMERO username to use
-k OMERO session key to use
-m Measurement index to populate
-i Dump measurement information and exit (no population)
-d Print debug statements
-t Number of threads to use when populating [defaults to 1]
Examples:
%s -s localhost -p 4063 -u bob 27
Report bugs to ome-devel@lists.openmicroscopy.org.uk""" % (error, cmd, cmd)
sys.exit(2)
###
# Worker and ThreadPool from...
# http://code.activestate.com/recipes/577187-python-thread-pool/
###
class Worker(Thread):
"""Thread executing tasks from a given tasks queue"""
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try:
func(*args, **kargs)
except Exception, e:
log.exception(e)
self.tasks.task_done()
class ThreadPool:
"""Pool of threads consuming tasks from a queue"""
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in range(num_threads):
Worker(self.tasks)
def add_task(self, func, *args, **kargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kargs))
def wait_completion(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()
# Global thread pool for use by ROI workers
thread_pool = None
def get_thread_pool():
global thread_pool
if thread_pool is None:
thread_pool = ThreadPool(1)
return thread_pool
class MeasurementError(Exception):
"""
Raised by the analysis or measurement context when an error condition
is reached.
"""
pass
class DownloadingOriginalFileProvider(object):
"""
Provides original file data by downloading it from an OMERO raw file store.
"""
# Default raw file store buffer size
BUFFER_SIZE = 1024 * 1024 # 1MB
def __init__(self, service_factory):
self.service_factory = service_factory
self.raw_file_store = self.service_factory.createRawFileStore()
self.dir = create_path("populate_roi", "dir", folder=True)
def get_original_file_data(self, original_file):
"""
Downloads an original file to a temporary file and returns an open
file handle to that temporary file seeked to zero. The caller is
responsible for closing the temporary file.
"""
log.info("Downloading original file: %d" % original_file.id.val)
self.raw_file_store.setFileId(original_file.id.val)
temporary_file = tempfile.TemporaryFile(mode='rU+', dir=str(self.dir))
size = original_file.size.val
for i in range((size / self.BUFFER_SIZE) + 1):
index = i * self.BUFFER_SIZE
data = self.raw_file_store.read(index, self.BUFFER_SIZE)
temporary_file.write(data)
temporary_file.seek(0L)
temporary_file.truncate(size)
return temporary_file
def __delete__(self):
self.raw_file_store.close()
class AbstractPlateAnalysisCtx(object):
"""
Abstract class which aggregates and represents all measurement runs made on
a given Plate.
"""
DEFAULT_ORIGINAL_FILE_PROVIDER = DownloadingOriginalFileProvider
def __init__(self, images, original_files, original_file_image_map,
plate_id, service_factory):
super(AbstractPlateAnalysisCtx, self).__init__()
self.images = images
self.numcols, self.numrows = self.guess_geometry(self.images)
self.original_files = original_files
self.original_file_image_map = original_file_image_map
self.plate_id = plate_id
self.service_factory = service_factory
self.log_files = dict()
self.detail_files = dict()
self.measurements = dict()
def guess_geometry(self, images):
max_col = 0
max_row = 0
for image in images:
# Using only first well sample link
ws = image.copyWellSamples()[0]
well = ws.well
max_col = max(max_col, well.column.val)
max_row = max(max_row, well.row.val)
return (max_col + 1, max_row + 1)
def colrow_from_wellnumber(self, width, wellnumber):
x = wellnumber - 1
col = x % width
row = x / width
return (col, row)
def image_from_wellnumber(self, wellnumber):
col, row = self.colrow_from_wellnumber(self.numcols, wellnumber)
log.debug("Finding image for %s (%s,%s)..." % (wellnumber, col, row))
for image in self.images:
well = image.copyWellSamples()[0].well
if well.column.val == col and well.row.val == row:
return image
raise Exception(
"Could not find image for (col,row)==(%s,%s)" % (col, row))
###
# Abstract methods
###
def is_this_type(klass):
"""
Concrete implementations are to return True if the class pertinent
for the original files associated with the plate.
"""
raise Exception("To be implemented by concrete implementations.")
is_this_type = classmethod(is_this_type)
def get_measurement_count(self):
"""Returns the number of recognized measurement runs."""
raise Exception("To be implemented by concrete implementations.")
def get_measurement_ctx(self, index):
"""Returns the measurement context for a given index."""
raise Exception("To be implemented by concrete implementations.")
def get_result_file_count(self, measurement_index):
"""
Return the number of result files associated with a measurement run.
"""
raise Exception("To be implemented by concrete implementations.")
class MIASPlateAnalysisCtx(AbstractPlateAnalysisCtx):
"""
MIAS dataset concrete class implementation of an analysis context. MIAS
measurements are aggregated based on a single "log" file. A result
file is present for each stitched (of multiple fields) mosaic and
contains the actual measured results and ROI.
"""
# Python datetime format string of the log filename completion date/time
datetime_format = '%Y-%m-%d-%Hh%Mm%Ss'
# Regular expression matching a log filename
log_regex = re.compile('.*log(\d+-\d+-\d+-\d+h\d+m\d+s).txt$')
# Regular expression matching a result filename
detail_regex = re.compile(
'^Well(\d+)_(.*)_detail_(\d+-\d+-\d+-\d+h\d+m\d+s).txt$')
# Companion file format
companion_format = 'Companion/MIAS'
def __init__(self, images, original_files, original_file_image_map,
plate_id, service_factory):
super(MIASPlateAnalysisCtx, self).__init__(
images, original_files, original_file_image_map, plate_id,
service_factory)
self._populate_log_and_detail_files()
self._populate_measurements()
def _populate_log_and_detail_files(self):
"""
Strips out erroneous files and collects the log and result original
files based on regular expression matching.
"""
for original_file in self.original_files:
if original_file.mimetype and \
original_file.mimetype.val != self.companion_format:
# In OMERO5, the mimetype will not be set.
continue
name = original_file.name.val
match = self.log_regex.match(name)
if match:
d = time.strptime(match.group(1), self.datetime_format)
self.log_files[d] = original_file
continue
match = self.detail_regex.match(name)
if match:
d = time.strptime(match.group(3), self.datetime_format)
self.detail_files[d] = original_file
continue
def _populate_measurements(self):
"""
Result original files are only recognizable as part of a given
measurement (declared by a log file) based upon their parsed
date/time of completion as encoded in the filename. This method
collects result original files and groups them by collective
parsed date/time of completion.
"""
log_timestamps = list(self.log_files.keys())
log_timestamps.sort()
detail_timestamps = list(self.detail_files.keys())
detail_timestamps.sort()
for log_timestamp in log_timestamps:
self.measurements[log_timestamp] = list()
for detail_timestamp in detail_timestamps:
for log_timestamp in log_timestamps:
if detail_timestamp < log_timestamp:
self.measurements[log_timestamp].append(
self.detail_files[detail_timestamp])
break
###
# Abstract method implementations
###
def is_this_type(klass, original_files):
for original_file in original_files:
format = unwrap(original_file.mimetype)
# In OMERO5, "Companion/*" is unused.
if (format is None or format == klass.companion_format) \
and klass.log_regex.match(original_file.name.val):
return True
is_this_type = classmethod(is_this_type)
def get_measurement_count(self):
return len(self.measurements.keys())
def get_measurement_ctx(self, index):
key = self.log_files.keys()[index]
sf = self.service_factory
original_file = self.log_files[key]
result_files = self.measurements[key]
provider = self.DEFAULT_ORIGINAL_FILE_PROVIDER(sf)
return MIASMeasurementCtx(self, sf, provider, original_file,
result_files)
def get_result_file_count(self, measurement_index):
key = self.log_files.keys()[measurement_index]
return len(self.measurements[key])
class FlexPlateAnalysisCtx(AbstractPlateAnalysisCtx):
"""
Flex dataset concrete class implementation of an analysis context. Flex
measurements are aggregated in a single ".res" XML file and contain no
ROI.
"""
# Companion file format
companion_format = 'Companion/Flex'
def __init__(self, images, original_files, original_file_image_map,
plate_id, service_factory):
super(FlexPlateAnalysisCtx, self).__init__(
images, original_files, original_file_image_map, plate_id,
service_factory)
path_original_file_map = dict()
for original_file in original_files:
path = original_file.path.val
name = original_file.name.val
format = original_file.mimetype.val
if format == self.companion_format and name.endswith('.res'):
path_original_file_map[path] = original_file
self.measurements = path_original_file_map.values()
###
# Abstract method implementations
###
def is_this_type(klass, original_files):
for original_file in original_files:
format = unwrap(original_file.mimetype)
name = original_file.name.val
if format == klass.companion_format and name.endswith('.res'):
return True
return False
is_this_type = classmethod(is_this_type)
def get_measurement_count(self):
return len(self.measurements)
def get_measurement_ctx(self, index):
sf = self.service_factory
original_file = self.measurements[index]
result_files = []
provider = self.DEFAULT_ORIGINAL_FILE_PROVIDER(sf)
return FlexMeasurementCtx(self, sf, provider, original_file,
result_files)
def get_result_file_count(self, measurement_index):
return 1
class InCellPlateAnalysisCtx(AbstractPlateAnalysisCtx):
"""
InCell dataset concrete class implementation of an analysis context.
InCell measurements are from InCell Analyzer and are aggregated in a
single gargantuan (often larger than 100MB per plate) XML file.
"""
# Companion file format
companion_format = 'Companion/InCell'
def __init__(self, images, original_files, original_file_image_map,
plate_id, service_factory):
super(InCellPlateAnalysisCtx, self).__init__(
images, original_files, original_file_image_map, plate_id,
service_factory)
path_original_file_map = dict()
for original_file in original_files:
path = original_file.path.val
name = original_file.name.val
format = original_file.mimetype.val
if format == self.companion_format and name.endswith('.xml'):
path_original_file_map[path] = original_file
self.measurements = path_original_file_map.values()
###
# Abstract method implementations
###
def is_this_type(klass, original_files):
for original_file in original_files:
format = unwrap(original_file.mimetype)
name = original_file.name.val
if format == klass.companion_format and name.endswith('.xml'):
return True
return False
is_this_type = classmethod(is_this_type)
def get_measurement_count(self):
return len(self.measurements)
def get_measurement_ctx(self, index):
sf = self.service_factory
original_file = self.measurements[index]
result_files = []
provider = self.DEFAULT_ORIGINAL_FILE_PROVIDER(sf)
return InCellMeasurementCtx(self, sf, provider, original_file,
result_files)
def get_result_file_count(self, measurement_index):
return 1
class PlateAnalysisCtxFactory(object):
"""
The plate analysis context factory is responsible for detecting and
returning a plate analysis context instance for a given plate.
"""
implementations = (FlexPlateAnalysisCtx, MIASPlateAnalysisCtx,
InCellPlateAnalysisCtx)
def __init__(self, service_factory):
self.service_factory = service_factory
self.query_service = self.service_factory.getQueryService()
def find_images_for_plate(self, plate_id):
"""
Retrieves all the images associated with a given plate. Fetched
are the Image's WellSample, the WellSample's Well, the annotation
stack associated with the Image and each annotation's linked
original file.
"""
# The query that follows is doublely linked:
# * Image --> WellSample --> Well
# * Well --> WellSample --> Image
# This is to facilitate later "ordered" access of fields/well
# samples required by certain measurement contexts (notably InCell).
log.debug("Loading image...")
images = self.query_service.findAllByQuery(
'select img from Image as img '
'join fetch img.wellSamples as ws '
'join fetch ws.well as w '
'join fetch w.wellSamples as ws2 '
'join w.plate as p '
'left outer join fetch img.annotationLinks as ia_links '
'left outer join fetch ia_links.child as ia '
'left outer join fetch ia.file as i_o_file '
'where p.id = %d' % plate_id, None)
log.debug("Loading plate...")
plate = self.query_service.findByQuery(
'select p from Plate p '
'left outer join fetch p.annotationLinks as pa_links '
'left outer join fetch pa_links.child as pa '
'left outer join fetch pa.file as p_o_file '
'where p.id = %d' % plate_id, None)
log.debug("Linking plate and images...")
for image in images:
for ws in image.copyWellSamples():
ws.well.plate = plate
return images, plate
def gather_original_files(self, obj, original_files,
original_file_obj_map):
for annotation_link in obj.copyAnnotationLinks():
annotation = annotation_link.child
if isinstance(annotation, FileAnnotationI):
f = annotation.file
original_files.add(f)
if original_file_obj_map is not None:
original_file_obj_map[f.id.val] = obj
# OMERO5 support
def find_filesets_for_plate(self, plateid):
"""
OMERO5 support. See #12235
"""
return self.query_service.findAllByQuery((
'select ofile from Fileset f '
'join f.usedFiles as fse '
'join fse.originalFile as ofile '
'join f.images as i '
'join i.wellSamples ws '
'join ws.well w '
'join w.plate p '
'where p.id = :id'),
ParametersI().addId(plateid))
def get_analysis_ctx(self, plate_id):
"""Retrieves a plate analysis context for a given plate."""
# Using a set since 1) no one was using the image.id key and 2)
# we are now also collecting original files from plates (MIAS)
# for which there's no clear key. Since all the files are loaded
# in a single shot, double linking should not cause a problem.
original_files = set()
original_file_image_map = dict()
images, plate = self.find_images_for_plate(plate_id)
fileset = self.find_filesets_for_plate(plate_id)
if fileset:
original_files.update(fileset)
self.gather_original_files(plate, original_files, None)
else:
plates = set()
for image in images:
for ws in image.copyWellSamples():
plate = ws.well.plate
if plate not in plates:
plates.add(plate)
self.gather_original_files(plate, original_files, None)
self.gather_original_files(
image, original_files, original_file_image_map)
for klass in self.implementations:
if klass.is_this_type(original_files):
return klass(images, original_files,
original_file_image_map,
plate_id, self.service_factory)
raise MeasurementError(
"Unable to find suitable analysis context for plate: %d" %
plate_id)
class MeasurementParsingResult(object):
"""
Holds the results of a measurement parsing event.
"""
def __init__(self, sets_of_columns=None):
if sets_of_columns is None:
self.sets_of_columns = list()
else:
self.sets_of_columns = sets_of_columns
def append_columns(self, columns):
"""Adds a set of columns to the parsing result."""
self.sets_of_columns.append(columns)
class AbstractMeasurementCtx(object):
"""
Abstract class which aggregates and represents all the results produced
from a given measurement run. It also provides a scaffold for interacting
with the OmeroTables infrastructure.
"""
# The number of ROI to have parsed before streaming them to the server
ROI_UPDATE_LIMIT = 1000
def __init__(self, analysis_ctx, service_factory, original_file_provider,
original_file, result_files):
super(AbstractMeasurementCtx, self).__init__()
self.thread_pool = get_thread_pool()
self.analysis_ctx = analysis_ctx
self.service_factory = service_factory
self.original_file_provider = original_file_provider
self.query_service = self.service_factory.getQueryService()
self.update_service = self.service_factory.getUpdateService()
self.original_file = original_file
self.result_files = result_files
# Establish the rest of our initial state
self.wellimages = dict()
for image in self.analysis_ctx.images:
for well_sample in image.copyWellSamples():
well = well_sample.well
idx = well.copyWellSamples().index(well_sample)
row = well.row.val
column = well.column.val
if row not in self.wellimages:
self.wellimages[row] = dict()
if column not in self.wellimages[row]:
self.wellimages[row][column] = []
# Now we save the image at it's proper index
l = self.wellimages[row][column]
for x in range(idx - len(l) + 1):
l.append(None)
l[idx] = image
def get_well_images(self, row, col):
"""
Takes a row and a col index and returns a tuple
of Well and image. Either might be None. Uses the
first image found to find the Well and therefore
must be loaded (image->wellSample->well)
"""
try:
images = self.wellimages[row][col]
if not images:
return (None, None)
image = images[0]
well = image.copyWellSamples()[0].well
return (well, images)
except KeyError:
# This has the potential to happen alot with the
# datasets we have given the split machine acquisition
# ".flex" file storage.
log.warn("WARNING: Missing data for row %d column %d" %
(row, col))
return (None, None)
def update_table(self, columns):
"""Updates the OmeroTables instance backing our results."""
# Create a new OMERO table to store our measurement results
sr = self.service_factory.sharedResources()
name = self.get_name()
self.table = sr.newTable(1, '/%s.r5' % name)
if self.table is None:
raise MeasurementError(
"Unable to create table: %s" % name)
# Retrieve the original file corresponding to the table for the
# measurement, link it to the file annotation representing the
# umbrella measurement run, link the annotation to the plate from
# which it belongs and save the file annotation.
table_original_file = self.table.getOriginalFile()
table_original_file_id = table_original_file.id.val
log.info("Created new table: %d" % table_original_file_id)
unloaded_o_file = OriginalFileI(table_original_file_id, False)
self.file_annotation.file = unloaded_o_file
unloaded_plate = PlateI(self.analysis_ctx.plate_id, False)
plate_annotation_link = PlateAnnotationLinkI()
plate_annotation_link.parent = unloaded_plate
plate_annotation_link.child = self.file_annotation
plate_annotation_link = \
self.update_service.saveAndReturnObject(plate_annotation_link)
self.file_annotation = plate_annotation_link.child
t0 = int(time.time() * 1000)
self.table.initialize(columns)
log.debug("Table init took %sms" % (int(time.time() * 1000) - t0))
t0 = int(time.time() * 1000)
column_report = dict()
for column in columns:
column_report[column.name] = len(column.values)
log.debug("Column report: %r" % column_report)
self.table.addData(columns)
self.table.close()
log.info("Table update took %sms" % (int(time.time() * 1000) - t0))
def create_file_annotation(self, set_of_columns):
"""
Creates a file annotation to represent a set of columns from our
measurment.
"""
self.file_annotation = FileAnnotationI()
self.file_annotation.ns = \
rstring('openmicroscopy.org/omero/measurement')
name = self.get_name(set_of_columns)
self.file_annotation.description = rstring(name)
def update_rois(self, rois, batches, batch_no):
"""
Updates a set of ROI for a given batch updating the batches
dictionary with the saved IDs.
"""
log.debug("Saving %d ROI for batch %d" % (len(rois), batch_no))
t0 = int(time.time() * 1000)
roi_ids = self.update_service.saveAndReturnIds(rois)
log.info("Batch %d ROI update took %sms" %
(batch_no, int(time.time() * 1000) - t0))
batches[batch_no] = roi_ids
def image_from_original_file(self, original_file):
"""Returns the image from which an original file has originated."""
m = self.analysis_ctx.original_file_image_map
return m[original_file.id.val]
def parse_and_populate(self):
"""
Calls parse and populate, updating the OmeroTables instance backing
our results and the OMERO database itself.
"""
result = self.parse()
if result is None:
return
for i, columns in enumerate(result.sets_of_columns):
self.create_file_annotation(i)
self.parse_and_populate_roi(columns)
self.populate(columns)
###
# Abstract methods
###
def get_name(self, set_of_columns=None):
"""Returns the name of the measurement, and a set of columns."""
raise Exception("To be implemented by concrete implementations.")
def parse(self):
"""Parses result files, returning a MeasurementParsingResult."""
raise Exception("To be implemented by concrete implementations.")
def parse_and_populate_roi(self, columns):
"""
Parses and populates ROI from column data in the OMERO database.
"""
raise Exception("To be implemented by concrete implementations.")
def populate(self, columns):
"""
Populates an OmeroTables instance backing our results and ROI
linkages.
"""
raise Exception("To be implemented by concrete implementations.")
class MIASMeasurementCtx(AbstractMeasurementCtx):
"""
MIAS measurements are a set of tab delimited text files per well. Each
TSV file's content is prefixed by the analysis parameters.
"""
# The OmeroTable ImageColumn index
IMAGE_COL = 0
# The OmeroTable RoiColumn index
ROI_COL = 1
# Expected columns in NEO datasets
NEO_EXPECTED = ('Image', 'ROI', 'Label', 'Row', 'Col', 'Nucleus Area',
'Cell Diam.', 'Cell Type', 'Mean Nucleus Intens.')
# Expected columns in MNU datasets
MNU_EXPECTED = ('Image', 'ROI', 'row', 'col', 'type')
def __init__(self, analysis_ctx, service_factory, original_file_provider,
original_file, result_files):
super(MIASMeasurementCtx, self).__init__(
analysis_ctx, service_factory, original_file_provider,
original_file, result_files)
def get_empty_columns(self, n_columns):
"""
Retrieves a set of empty OmeroTables columns for the analysis results
prefixed by an ImageColumn and RoiColumn to handle these linked
object indexes.
"""
columns = [ImageColumn('Image', '', list()),
RoiColumn('ROI', '', list())]
for i in range(n_columns):
columns.append(DoubleColumn('', '', list()))
return columns
###
# Overriding abstract implementation
###
def image_from_original_file(self, original_file):
"""
Overriding the abstract implementation since the companion
files are no longer attached to the images, but only to the plate
for MIAS. Instead, we use the filename itself to find the image.
"""
name = original_file.name.val
# Copy: '^Well(\d+)_(.*)_detail_(\d+-\d+-\d+-\d+h\d+m\d+s).txt$'
match = MIASPlateAnalysisCtx.detail_regex.match(name)
if match:
well_num = int(match.group(1))
return self.analysis_ctx.image_from_wellnumber(well_num)
else:
raise Exception("Not a detail file")
###
# Abstract method implementations
###
def get_name(self, set_of_columns=None):
return self.original_file.name.val[:-4]
def parse(self):
columns = None
for result_file in self.result_files:
log.info("Parsing: %s" % result_file.name.val)
image = self.image_from_original_file(result_file)
provider = self.original_file_provider
data = provider.get_original_file_data(result_file)
try:
rows = list(csv.reader(data, delimiter='\t'))
finally:
data.close()
rows.reverse()
if columns is None:
columns = self.get_empty_columns(len(rows[0]))
for row in rows:
try:
for i, value in enumerate(row):
value = float(value)
columns[i + 2].values.append(value)
columns[self.IMAGE_COL].values.append(image.id.val)
except ValueError:
for i, value in enumerate(row):
columns[i + 2].name = value
break
log.debug("Returning %d columns" % len(columns))
return MeasurementParsingResult([columns])
def _parse_neo_roi(self, columns):
"""Parses out ROI from OmeroTables columns for 'NEO' datasets."""
log.debug("Parsing %s NEO ROIs..." % (len(columns[0].values)))
image_ids = columns[self.IMAGE_COL].values
rois = list()
# Save our file annotation to the database so we can use an unloaded
# annotation for the saveAndReturnIds that will be triggered below.
self.file_annotation = \
self.update_service.saveAndReturnObject(self.file_annotation)
unloaded_file_annotation = \
FileAnnotationI(self.file_annotation.id.val, False)
batch_no = 1
batches = dict()
for i, image_id in enumerate(image_ids):
unloaded_image = ImageI(image_id, False)
roi = RoiI()
shape = EllipseI()
values = columns[6].values
diameter = rdouble(float(values[i]))
shape.theZ = rint(0)
shape.theT = rint(0)
values = columns[4].values
shape.x = rdouble(float(values[i]))
values = columns[3].values
shape.y = rdouble(float(values[i]))
shape.radiusX = diameter
shape.radiusY = diameter
roi.addShape(shape)
roi.image = unloaded_image
roi.linkAnnotation(unloaded_file_annotation)
rois.append(roi)
if len(rois) == self.ROI_UPDATE_LIMIT:
self.thread_pool.add_task(
self.update_rois, rois, batches, batch_no)
rois = list()
batch_no += 1
self.thread_pool.add_task(self.update_rois, rois, batches, batch_no)
self.thread_pool.wait_completion()
batch_keys = batches.keys()
batch_keys.sort()
for k in batch_keys:
columns[self.ROI_COL].values += batches[k]
def _parse_mnu_roi(self, columns):
"""Parses out ROI from OmeroTables columns for 'MNU' datasets."""
log.debug("Parsing %s MNU ROIs..." % (len(columns[0].values)))
image_ids = columns[self.IMAGE_COL].values
rois = list()
# Save our file annotation to the database so we can use an unloaded
# annotation for the saveAndReturnIds that will be triggered below.
self.file_annotation = \
self.update_service.saveAndReturnObject(self.file_annotation)
unloaded_file_annotation = \
FileAnnotationI(self.file_annotation.id.val, False)
batch_no = 1
batches = dict()
for i, image_id in enumerate(image_ids):
unloaded_image = ImageI(image_id, False)
roi = RoiI()
shape = PointI()
shape.theZ = rint(0)
shape.theT = rint(0)
values = columns[3].values
shape.x = rdouble(float(values[i]))
values = columns[2].values
shape.y = rdouble(float(values[i]))
roi.addShape(shape)
roi.image = unloaded_image
roi.linkAnnotation(unloaded_file_annotation)
rois.append(roi)
if len(rois) == self.ROI_UPDATE_LIMIT:
self.thread_pool.add_task(
self.update_rois, rois, batches, batch_no)
rois = list()
batch_no += 1
self.thread_pool.add_task(self.update_rois, rois, batches, batch_no)
self.thread_pool.wait_completion()
batch_keys = batches.keys()
batch_keys.sort()
for k in batch_keys:
columns[self.ROI_COL].values += batches[k]
def parse_and_populate_roi(self, columns):
names = [column.name for column in columns]
neo = [name in self.NEO_EXPECTED for name in names]
mnu = [name in self.MNU_EXPECTED for name in names]
for name in names:
log.debug("Column: %s" % name)
if len(columns) == 9 and False not in neo:
self._parse_neo_roi(columns)
elif len(columns) == 5 and False not in mnu:
self._parse_mnu_roi(columns)
else:
log.warn("Unknown ROI type for MIAS dataset: %r" % names)
def populate(self, columns):
"""
Query performed::
first_roi = columns[self.ROI_COL].values[0]
first_roi = self.query_service.findByQuery(
'select roi from Roi as roi ' \
'join fetch roi.annotationLinks as link ' \
'join fetch link.child ' \
'where roi.id = %d' % first_roi, None)
self.file_annotation = first_roi.copyAnnotationLinks()[0].child
"""
self.update_table(columns)
class FlexMeasurementCtx(AbstractMeasurementCtx):
"""
Flex measurements are located deep within a ".res" XML file container
and contain no ROI.
"""
# The XPath to the <Area> which aggregate an acquisition
AREA_XPATH = './/Areas/Area'
# The XPath to the an analysis <Parameter>; will become a column header
# and is below AREA_XPATH
PARAMETER_XPATH = './/Wells/ResultParameters/Parameter'
# The XPath to a <Well> which has had at least one acquisition event
# within and is below AREA_XPATH
WELL_XPATH = './/Wells/Well'
# The XPath to a <Result> for a given well and is below WELL_XPATH
RESULT_XPATH = './/Result'
def __init__(self, analysis_ctx, service_factory, original_file_provider,
original_file, result_files):
super(FlexMeasurementCtx, self).__init__(
analysis_ctx, service_factory, original_file_provider,
original_file, result_files)
def get_empty_columns(self, headers):
"""
Retrieves a set of empty OmeroTables columns for the analysis results
prefixed by a WellColumn to handle linked object indexes.
"""
columns = {'Well': WellColumn('Well', '', list())}
for header in headers:
columns[header] = DoubleColumn(header, '', list())
return columns
###
# Abstract method implementations
###
def get_name(self, set_of_columns=None):
return self.original_file.name.val[:-4]
def parse(self):