-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
523 additions
and
47 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
0.5.0 | ||
0.5.1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
# Copyright (c) 2020, CRS4 | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy of | ||
# this software and associated documentation files (the "Software"), to deal in | ||
# the Software without restriction, including without limitation the rights to | ||
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of | ||
# the Software, and to permit persons to whom the Software is furnished to do so, | ||
# subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in all | ||
# copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS | ||
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | ||
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER | ||
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN | ||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
|
||
from django.core.management.base import BaseCommand, CommandError | ||
from rois_manager.models import Slice, Core, FocusRegion | ||
from rois_manager.serializers import SliceSerializer, CoreSerializer, FocusRegionSerializer | ||
|
||
import csv, os, copy | ||
try: | ||
import simplejson as json | ||
except ImportError: | ||
import json | ||
|
||
import logging | ||
|
||
logger = logging.getLogger('promort_commands') | ||
|
||
|
||
class Command(BaseCommand): | ||
help = """ | ||
""" | ||
|
||
def add_arguments(self, parser): | ||
parser.add_argument('--rois-list', dest='rois_list', type=str, required=True, | ||
help='A file containing the list of ROIs that will be extracted') | ||
parser.add_argument('--out-folder', dest='out_folder', type=str, required=True, | ||
help='The output folder for the extracted data') | ||
|
||
def _load_rois_map(self, rois_file): | ||
logger.info('Loading data from CSV file') | ||
with open(rois_file) as f: | ||
rois_map = dict() | ||
reader = csv.DictReader(f) | ||
for row in reader: | ||
rois_map.setdefault(row['slide_id'], dict()).setdefault(row['roi_type'], set()).add(int(row['roi_id'])) | ||
return rois_map | ||
|
||
def _get_related(self, rois): | ||
related_rois = copy.copy(rois) | ||
related_rois.setdefault('slice', set()) | ||
related_rois.setdefault('core', set()) | ||
related_rois.setdefault('focus_region', set()) | ||
# step 1: process slices | ||
logger.info('Processing %d slices', len(related_rois['slice'])) | ||
for s in related_rois['slice']: | ||
s_obj = Slice.objects.get(pk=s) | ||
# get cores related to given slice | ||
for c_obj in s_obj.cores.all(): | ||
related_rois['core'].add(c_obj.id) | ||
# step 2: process focus regions | ||
logger.info('Processing %d focus regions', len(related_rois['focus_region'])) | ||
for fr in related_rois['focus_region']: | ||
fr_obj = FocusRegion.objects.get(pk=fr) | ||
# get core related to given focus region | ||
related_rois['core'].add(fr_obj.core.id) | ||
# step 3: process cores | ||
logger.info('Processing %d cores', len(related_rois['core'])) | ||
for c in related_rois['core']: | ||
c_obj = Core.objects.get(pk=c) | ||
# get slice related to given core | ||
related_rois['slice'].add(c_obj.slice.id) | ||
# get focus regions related to given core | ||
for fr_obj in c_obj.focus_regions.all(): | ||
related_rois['focus_region'].add(fr_obj.id) | ||
logger.info('Retrived %d slices, %d cores, %d focus regions', | ||
len(related_rois['slice']), len(related_rois['core']), | ||
len(related_rois['focus_region'])) | ||
return related_rois | ||
|
||
def _dump_slide_rois(self, slide_id, rois, output_folder): | ||
logger.info('Dumping ROIs for slide %s', slide_id) | ||
rois = self._get_related(rois) | ||
labels_map = { | ||
'slice': dict(), | ||
'core': dict() | ||
} | ||
to_be_saved = { | ||
'slice': list(), | ||
'core': list(), | ||
'focus_region': list() | ||
} | ||
for s in rois['slice']: | ||
ser_obj = SliceSerializer(Slice.objects.get(pk=s)).data | ||
labels_map['slice'][ser_obj.get('id')] = ser_obj['label'] | ||
slice_obj = { | ||
'label': ser_obj['label'], | ||
'roi_json': ser_obj['roi_json'], | ||
'total_cores': ser_obj['total_cores'] | ||
} | ||
to_be_saved['slice'].append(slice_obj) | ||
for c in rois['core']: | ||
ser_obj = CoreSerializer(Core.objects.get(pk=c)).data | ||
labels_map['core'][ser_obj.get('id')] = ser_obj['label'] | ||
core_obj = { | ||
'label': ser_obj['label'], | ||
'slice': labels_map['slice'].get(ser_obj['slice']), | ||
'roi_json': ser_obj['roi_json'], | ||
'length': ser_obj['length'], | ||
'area': ser_obj['area'], | ||
'tumor_length': ser_obj['tumor_length'] | ||
} | ||
to_be_saved['core'].append(core_obj) | ||
for fr in rois['focus_region']: | ||
ser_obj = FocusRegionSerializer(FocusRegion.objects.get(pk=fr)).data | ||
focus_region_obj = { | ||
'label': ser_obj['label'], | ||
'core': labels_map['core'].get(ser_obj['core']), | ||
'roi_json': ser_obj['roi_json'], | ||
'length': ser_obj['length'], | ||
'area': ser_obj['area'], | ||
'tissue_status': ser_obj['tissue_status'] | ||
} | ||
to_be_saved['focus_region'].append(focus_region_obj) | ||
with open(os.path.join(output_folder, '%s.json' % slide_id), 'w') as out_file: | ||
json.dump(to_be_saved, out_file) | ||
|
||
def _dump_rois(self, rois_map, output_folder): | ||
logger.debug('Checking if folder %s exists' % output_folder) | ||
if not os.path.isdir(output_folder): | ||
raise CommandError('Output folder %s does not exist, exit' % output_folder) | ||
for slide, rois in rois_map.iteritems(): | ||
self._dump_slide_rois(slide, rois, output_folder) | ||
|
||
def handle(self, *args, **opts): | ||
logger.info('== Starting job ==') | ||
rois = self._load_rois_map(opts['rois_list']) | ||
self._dump_rois(rois, opts['out_folder']) | ||
logger.info('== Job completed ==') |
147 changes: 147 additions & 0 deletions
147
promort/rois_manager/management/commands/extract_cores.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
# Copyright (c) 2019, CRS4 | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy of | ||
# this software and associated documentation files (the "Software"), to deal in | ||
# the Software without restriction, including without limitation the rights to | ||
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of | ||
# the Software, and to permit persons to whom the Software is furnished to do so, | ||
# subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in all | ||
# copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS | ||
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | ||
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER | ||
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN | ||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
|
||
from django.core.management.base import BaseCommand, CommandError | ||
from reviews_manager.models import ROIsAnnotationStep | ||
from promort.settings import OME_SEADRAGON_BASE_URL | ||
|
||
from csv import DictWriter | ||
try: | ||
import simplejson as json | ||
except ImportError: | ||
import json | ||
|
||
import logging, sys, os, requests | ||
from urlparse import urljoin | ||
from shapely.geometry import Polygon | ||
|
||
logger = logging.getLogger('promort_commands') | ||
|
||
|
||
class Command(BaseCommand): | ||
help = """ | ||
Extract focus regions as JSON objects | ||
""" | ||
|
||
def add_arguments(self, parser): | ||
parser.add_argument('--output_folder', dest='out_folder', type=str, required=True, | ||
help='path of the output folder for the extracted JSON objects') | ||
parser.add_argument('--exclude_empty_cores', dest='exclude_empty', action='store_true', | ||
help='exclude cores with 0 focus regions') | ||
parser.add_argument('--exclude_rejected', dest='exclude_rejected', action='store_true', | ||
help='exclude cores from review steps rejected by the user') | ||
parser.add_argument('--limit-bounds', dest='limit_bounds', action='store_true', | ||
help='extract ROIs considering only the non-empty slide region') | ||
|
||
def _load_rois_annotation_steps(self, exclude_rejected): | ||
steps = ROIsAnnotationStep.objects.filter(completion_date__isnull=False) | ||
if exclude_rejected: | ||
steps = [s for s in steps if s.slide_evaluation.adequate_slide] | ||
return steps | ||
|
||
def _get_slide_bounds(self, slide): | ||
if slide.image_type == 'OMERO_IMG': | ||
url = urljoin(OME_SEADRAGON_BASE_URL, 'deepzoom/slide_bounds/%d.dzi' % slide.omero_id) | ||
elif slide.image_type == 'MIRAX': | ||
url = urljoin(OME_SEADRAGON_BASE_URL, 'mirax/deepzoom/slide_bounds/%s.dzi' % slide.id) | ||
else: | ||
logger.error('Unknown image type %s for slide %s', slide.image_type, slide.id) | ||
return None | ||
response = requests.get(url) | ||
if response.status_code == requests.codes.OK: | ||
return response.json() | ||
else: | ||
logger.error('Error while loading slide bounds %s', slide.id) | ||
return None | ||
|
||
def _extract_points(self, roi_json, slide_bounds): | ||
points = list() | ||
shape = json.loads(roi_json) | ||
segments = shape['segments'] | ||
for x in segments: | ||
points.append( | ||
( | ||
x['point']['x'] + int(slide_bounds['bounds_x']), | ||
x['point']['y'] + int(slide_bounds['bounds_y']) | ||
) | ||
) | ||
return points | ||
|
||
def _extract_bounding_box(self, roi_points): | ||
polygon = Polygon(roi_points) | ||
bounds = polygon.bounds | ||
return [(bounds[0], bounds[1]), (bounds[2], bounds[3])] | ||
|
||
def _dump_core(self, core, slide_id, slide_bounds, out_folder): | ||
file_path = os.path.join(out_folder, 'c_%d.json' % core.id) | ||
points = self._extract_points(core.roi_json, slide_bounds) | ||
bbox = self._extract_bounding_box(points) | ||
with open(file_path, 'w') as ofile: | ||
json.dump(points, ofile) | ||
return { | ||
'slide_id': slide_id, | ||
'core_id': core.id, | ||
'core_label': core.label, | ||
'file_name': 'c_%d.json' % core.id, | ||
'bbox': bbox, | ||
'focus_regions_count': core.focus_regions.count() | ||
} | ||
|
||
def _dump_details(self, details, out_folder): | ||
with open(os.path.join(out_folder, 'cores.csv'), 'w') as ofile: | ||
writer = DictWriter(ofile, ['slide_id', 'core_id', 'core_label', 'focus_regions_count', | ||
'bbox', 'file_name']) | ||
writer.writeheader() | ||
writer.writerows(details) | ||
|
||
def _dump_cores(self, step, out_folder, exclude_empty, limit_bounds): | ||
cores = step.cores | ||
if exclude_empty: | ||
cores = [c for c in cores if c.focus_regions.count() > 0] | ||
slide = step.slide | ||
logger.info('Loading info for slide %s', slide.id) | ||
if not limit_bounds: | ||
slide_bounds = self._get_slide_bounds(slide) | ||
else: | ||
slide_bounds = {'bounds_x': 0, 'bounds_y': 0} | ||
if slide_bounds: | ||
logger.info('Dumping %d cores for step %s', len(cores), step.label) | ||
if len(cores) > 0: | ||
out_path = os.path.join(out_folder, step.slide.id, step.label) | ||
try: | ||
os.makedirs(out_path) | ||
except OSError: | ||
pass | ||
cores_details = list() | ||
for c in cores: | ||
cores_details.append( | ||
self._dump_core(c, step.slide.id, slide_bounds, out_path) | ||
) | ||
self._dump_details(cores_details, out_path) | ||
|
||
def _export_data(self, out_folder, exclude_empty=False, exclude_rejected=False, limit_bounds=False): | ||
steps = self._load_rois_annotation_steps(exclude_rejected) | ||
logger.info('Loaded %d ROIs Annotation Steps', len(steps)) | ||
for s in steps: | ||
self._dump_cores(s, out_folder, exclude_empty, limit_bounds) | ||
|
||
def handle(self, *args, **opts): | ||
logger.info('=== Starting export job ===') | ||
self._export_data(opts['out_folder'], opts['exclude_empty'], opts['exclude_rejected'], opts['limit_bounds']) | ||
logger.info('=== Export completed ===') |
Oops, something went wrong.