This notebook loads the polygons which are linked to the images of idr0001-graml-sysgro and compares the length of cells labelled with a particular gene e.g. ASH2 versus the wild type.
The cell below will install dependencies if you choose to run the notebook in Google Colab.
%pip install idr-py
from idr import connection
from pandas import DataFrame
import omero
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import ttest_ind
import skimage.measure as skmes
import skimage.transform as sktrans
screenId = 3 # sysgro
def getBulkAnnotationAsDf(screenID, conn):
"""
Download the annotation file from a screen as a Pandas DataFrame
"""
screen = conn.getObject('Screen', screenID)
for ann in screen.listAnnotations():
if isinstance(ann, omero.gateway.FileAnnotationWrapper):
if (ann.getFile().getName() == 'bulk_annotations'):
if (ann.getFile().getSize() > 147625090):
print("that's a big file...")
return None
ofId = ann.getFile().getId()
break
original_file = omero.model.OriginalFileI(ofId, False)
table = conn.c.sf.sharedResources().openTable(original_file)
try:
rowCount = table.getNumberOfRows()
column_names = [col.name for col in table.getHeaders()]
black_list = []
column_indices = []
for column_name in column_names:
if column_name in black_list:
continue
column_indices.append(column_names.index(column_name))
table_data = table.slice(column_indices, None)
finally:
table.close()
data = []
for index in range(rowCount):
row_values = [column.values[index] for column in table_data.columns]
data.append(row_values)
dfAnn = DataFrame(data)
dfAnn.columns = column_names
return dfAnn
def getLengthsFromStrain(astrain, lenlen=100, verbose=False):
lengths = []
params = omero.sys.ParametersI()
key = sysgroba["Characteristics [Strain]"]
wellids = sysgroba[key == astrain].Well.values
params.addIds(wellids)
# Wells and images that contain a ROI
imageswithrois = queryService.projection(
'SELECT w.id, i.id FROM Image i JOIN i.wellSamples s JOIN s.well w '
'WHERE w.id in (:ids) AND EXISTS '
'(SELECT 1 FROM Roi AS r WHERE r.image = i) ORDER BY i.id', params)
wellswithrois = {}
for wid, iid in omero.rtypes.unwrap(imageswithrois):
try:
wellswithrois[wid].append(iid)
except KeyError:
wellswithrois[wid] = [iid]
for wid in sorted(wellswithrois.keys()):
for imId in wellswithrois[wid]:
result = roiService.findByImage(imId, None)
if verbose:
v = 'Well-id:%d Image-id:%d rois:[%d]'
print(v % (wid, imId, len(result.rois)))
for ii in range(len(result.rois)):
# get the coordinates of the outline of the ROI
s = result.rois[ii].copyShapes()[0]
pts = s.getPoints().getValue()
pts = [int(xx) for x in pts.split(' ') for xx in x.split(',')]
pts = np.reshape(pts, (len(pts) // 2, 2))
# from coordinates to mask image
M0, m0 = pts[:, 0].max(), pts[:, 0].min()
M1, m1 = pts[:, 1].max(), pts[:, 1].min()
imroi = np.zeros((M0 - m0 + 1, M1 - m1 + 1))
for i in range(pts.shape[0]):
imroi[pts[i, 0] - m0, pts[i, 1] - m1] = 1
iml = skmes.label(1-imroi, connectivity=1)
imroi = 1 * (iml == iml[iml.shape[0] // 2,
iml.shape[1] // 2])
# length of cell as length of bounding box of rotated image
# (thanks to the particular shape of yeast cells)
# default orientation is changing in 0.16 so -pi/2 to
# make relative to x-axis
regions = skmes.regionprops(1 * imroi, coordinates='rc')[0]
ori = regions.orientation - np.pi // 2
imroi = sktrans.rotate(1. * imroi, - ori // np.pi * 180,
resize=True, order=0)
regions = skmes.regionprops(skmes.label(imroi),
coordinates='rc')[0]
bbox = regions.bbox
lengths.append(bbox[3] - bbox[1])
# to speed things up when there are a lot of images...
if len(lengths) > lenlen:
break
return lengths
conn = connection('idr.openmicroscopy.org')
Connected to IDR ...
roiService = conn.getRoiService()
queryService = conn.getQueryService()
sysgroba = getBulkAnnotationAsDf(screenId, conn)
WTls = getLengthsFromStrain('MS1404', lenlen=1000)
ash2ls = getLengthsFromStrain('ash2', lenlen=1000)
pixsize = .11 # could be taken from IDR metadata
ash2ls = [x * pixsize for x in ash2ls]
WTls = [x * pixsize for x in WTls]
conn.close()
plt.figure()
h1 = plt.hist(ash2ls, bins=50, alpha=.5)
h2 = plt.hist(WTls, bins=50, alpha=.5)
ttest_ind(WTls, ash2ls)
Ttest_indResult(statistic=-13.398273380158818, pvalue=2.5160251562338347e-39)
Copyright (C) 2017-2021 University of Dundee. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.