Skip to content

Instantly share code, notes, and snippets.

@bramalingam
Last active March 14, 2020 10:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bramalingam/1d36f827add8f5342068 to your computer and use it in GitHub Desktop.
Save bramalingam/1d36f827add8f5342068 to your computer and use it in GitHub Desktop.
Integration : Micromanager+Matlab+OMERO
function [img_grid] = grid_calculator(x,y,fs,nf,nwx,nwy,xwd,ywd)
%ex usage for a 96 well plate,9 fields being imaged with a interfield
%distance of 200 microns.
% img_grid = grid_calculator(0,0,200,9,12,8,9000,9000);
% x: Stage x position
% y: Stage y position
% fs: Intra-well field spacing
% nf: Number of fields per well
% nwx: number of wells in the x direction or number of columns in your plate (12 in the case of 96 wells).
% nwx: number of wells in the y direction or number of rows in your
% plate (12 in the case of 96 wells).
% xwd: Centroid to centroid distance between adjacent wells in the x
% direction (Inter column spacing).
% ywd: Centroid to centroid distance between adjacent wells in the y
% direction (Inter row spacing).
xgrid=(x-fs*nf):fs:(x+fs*nf);
ygrid=(y-fs*nf):fs:(y+fs*nf);
resvec=[];
for i=1:length(xgrid)
xval=xgrid(i);
for j=1:length(ygrid)
yval=ygrid(j);
resvec=[resvec ; xval yval x y ((x-xval)^2+(y-yval)^2)^0.5];
end
end
[aa ii]=sort(resvec(:,5)); %#ok<*ASGLU>
img_grid=resvec(ii(1:nf),1:2);
xvec=repmat([0:xwd:(nwx-1)*xwd]',1,size(img_grid,1))';
xa1=repmat(img_grid(:,1),1,size(xvec,2));
xvec=xvec+xa1;
yvec=repmat(img_grid(:,2),1,size(xvec,2));
xvec=reshape(xvec,[],1);yvec=yvec(:);
yval=repmat([0:ywd:(nwy-1)*ywd]',1,size(yvec,1))';yval=yval(:);
rowvec=[xvec yvec];rowvec=repmat(rowvec,nwy,1);
img_grid=[rowvec(:,1) rowvec(:,2)+yval];
%Multiple sites imaging
%and image analysis(identifying cells with a circularity index>0.8)
%feedback, based on number of cells, change objective to check assay qc
%Author : Balaji.R
%Init
clear all;close all;
%Import packages
import mmcorej.*;
import org.micromanager.acquisition.AcquisitionWrapperEngine;
import org.micromanager.utils.ImageUtils;
import ij.IJ;
import ij.io.FileSaver;
import java.lang.StringBuffer;
import ij.ImagePlus;
import java.lang.StringBuffer;
import loci.formats.codec.CompressionType;
%OMERO Session
%Params
host= ''; %Host address
username = ''; %Username for OMERO
password = ''; %Password for OMERO
folder_depth_bioformats=10;
ProjectName = '';
DatasetName = '';
%Load Omero
client = loadOmero(host);
session = client.createSession(username, password);
client.enableKeepAlive(60);
%Import type for Omero (1 for Symlink Transfer/inplace-import,2 for UploadRmFileTransfer, any other numeric value for
%regular upload)
importopt = 2;
%file locations
acqName = 'test-acq';
rootDirName = '/Applications/Micro-Manager1.4/test/';
mkdir(rootDirName)
%parameters
exposures = [10, 1000];
fields = 6;
%Create objects (Acquisition engine and core object)
mmc = CMMCore;
%load config
mmc.loadSystemConfiguration ('/Applications/Micro-Manager1.4/MMConfig_demo.cfg');
%Get config's of devices
stage=mmc.getXYStageDevice();
zdrive=mmc.getFocusDevice();
%Get position of X,Y and Z
X1= mmc.getXPosition(stage);
Y1= mmc.getYPosition(stage);
Z1=mmc.getPosition(zdrive); %Manually focus on the first field
%load camera properties
config_groups=mmc.getAvailableConfigGroups();
% read_rate=config_groups.get(5);
objective_turr=mmc.getAvailableConfigs(config_groups.get(4));
light_path=mmc.getAvailableConfigs(config_groups.get(3));
Gain_multipler=config_groups.get(2);
channels=mmc.getAvailableConfigs(config_groups.get(1));
camera_gain=config_groups.get(0);
%Set light path (To camera view)
mmc.setConfig(config_groups.get(3), light_path.get(1));
%stage movement in microns (Field spacing)
rval1=100;rval=X1;
%Image Output Directory and Suffix for Image Name
acqRoot = [pwd '/'];
BrightAcqName = 'Test.ome.tiff';
%Temporary Params
Wells={'A' 'B' 'C' 'D'};
Fields = {'F'};
cntr1=1;resvec=[];cellcntr=0;
for l=1:2
%Move Stage
mmc.setXYPosition(stage, rval, Y1);
mmc.waitForDevice(stage);
for k=1:3
if k>1
rval=rval1+mmc.getXPosition(stage);
else
rval=mmc.getXPosition(stage);
end
cntr=1;rvec=[];
%Set Device/Config Group properties
mmc.setPosition(zdrive,(Z1));
mmc.setExposure(exposures(1));
mmc.setConfig(config_groups.get(1), channels.get(0));
mmc.setXYPosition(stage, rval, Y1);
mmc.waitForDevice(stage);
%Snap Image
mmc.snapImage();
img = mmc.getImage();
width = mmc.getImageWidth();
height = mmc.getImageHeight();
%Saving image
proc0 = ImageUtils.makeProcessor(mmc, img);
imgp0 = ImagePlus('',proc0);
%Extract Micro-Manager Device Properties
devices = mmc.getLoadedDevices();
cvec =[];
for i=0:devices.size-1
properties = mmc.getDevicePropertyNames(devices.get(i));
cvec = [cvec ; {char(devices.get(i))} {'#'}];
for j = 0:properties.size-1
s = properties.get(j);
v = mmc.getProperty(devices.get(i),s);
cvec = [cvec ; {char(s)} {char(v)}];
imgp0.setProperty(char(s), char(v));
end
end
imgp0.show;
cvec= [ cvec ; {'StageXPosition'} {num2str(mmc.getXPosition)}; {'StageYPosition'} {num2str(mmc.getYPosition)}; {'Z Position'} {num2str(mmc.getCurrentFocusScore)}];
imgp0.setProperty('StageXPosition',char(mmc.getXPosition));
imgp0.setProperty('StageYPosition',char(mmc.getYPosition));
imgp0.setProperty('Z Position',char(mmc.getCurrentFocusScore));
%Export Path
path=[acqRoot Wells{1} '00' num2str(l) Fields{1} '00' num2str(k) '_' BrightAcqName];
%Bio-Formats Exporter
buffer = StringBuffer();
buffer.append(['outfile=' path]);
buffer.append(' splitz=false');
buffer.append(' splitc=false');
buffer.append(' splitt=false');
buffer.append([' compression=' char(CompressionType.UNCOMPRESSED.getCompression())]);
buffer.append(' saveroi=true');
IJ.runPlugIn('loci.plugins.LociExporter', buffer.toString);
%Upload Image to the OMERO Server
imageId = upload_image(path,session,username,password,ProjectName,DatasetName,host,importopt);
%Upload Micro-Manager Device Properties as OMERO Key-Value pair Annotations
map = writeMapAnnotation(session, cvec(:,1)',cvec(:,2)');
link1 = linkAnnotation(session, map, 'image', imageId(1));
session.getUpdateService().saveAndReturnObject(link1);
imgp0.close;
cntr1=cntr1+1;
disp([mmc.getXPosition(),mmc.getYPosition()]);
% [seg_img clustidx]=kmeans(double(img(:)),3,'emptyaction','drop');
% idx1=find(clustidx==min(clustidx));
%
% [aa numcells]=bwlabel(bwareaopen(reshape(seg_img==idx1,512,512),15));
% props = regionprops(aa, 'Area', 'Perimeter');
% areas = [props.Area];
% perims = [props.Perimeter];
% circularities = 4 * pi * areas ./ perims .^ 2; % formula for circularity index
%
% remidx=find(circularities<=0.80);
% [finimg numcells]=bwlabel(~ismember(aa,[0 remidx]));
%
% stagevec(k,:)=[rval Y1 Z1 numcells];
% cellcntr=cellcntr+numcells;
% imwrite(img,[rootDirName acqName '_field_' num2str(k) '.tiff'],'Compression','none')
% if cellcntr>=70
% break
% end
end
end
%Stitch all images together (QC View)
% montage(img1);imcontrast;
% figure;imagesc(stagevec(:,4));caxis([0 100])
% %Move stage to field with minimum cells and change objectives and snap an
% %image
% idx1=find(stagevec(:,4)==min(stagevec(:,4)));
% mmc.setXYPosition(stage, stagevec(idx1,1), Y1);
% mmc.waitForDevice(stage);
% %change objectives line
% curr_obj=objective_turr.get(0);
% mmc.setConfig(config_groups.get(4), curr_obj);
% mmc.snapImage();
% img = mmc.getImage(); % returned as a 1D array of signed integers in row-major order
% width = mmc.getImageWidth();
% height = mmc.getImageHeight();
%
% if mmc.getBytesPerPixel == 2
% pixelType = 'uint16';
% else
% pixelType = 'uint8';
% end
%
% img = typecast(img, pixelType); % pixels must be interpreted as unsigned integers
% img = transpose(reshape(img, [width, height])); % image should be interpreted as a 2D array
% imshow(imadjust(img));title('10x image');
clear all;close all;
java.lang.System.clearProperty('java.util.prefs.PreferencesFactory')
javaaddpath('/Applications/Micro-Manager1.4/ij.jar')
javaaddpath('/Applications/Micro-Manager1.4/plugins/Micro-Manager/MMCoreJ.jar')
javaaddpath('/Applications/Micro-Manager1.4/plugins/Micro-Manager/MMJ_.jar')
javaaddpath('/Applications/Micro-Manager1.4/plugins/Micro-Manager/bsh-2.0b4.jar')
javaaddpath('/Applications/Micro-Manager1.4/plugins/Micro-Manager/swingx-0.9.5.jar')
javaaddpath('/Applications/Micro-Manager1.4/plugins/Micro-Manager/swing-layout-1.0.4.jar')
javaaddpath('/Applications/Micro-Manager1.4/plugins/Micro-Manager/ome-xml.jar')
javaaddpath('/Applications/Micro-Manager1.4/plugins/Micro-Manager/loci-common.jar')
javaaddpath('/Applications/Micro-Manager1.4/plugins/Micro-Manager/scifio.jar')
javaaddpath('/Applications/Micro-Manager1.4/plugins/Micro-Manager/slf4j-api-1.7.1.jar')
javaaddpath('/Applications/Micro-Manager1.4/plugins/bioformats_package.jar');
inputdir=['/Users/bramalingam/OME/matlab/OMERO.matlab-5.1.0-ice35-b40'];
addpath(genpath(inputdir));
javaaddpath('/Users/bramalingam/OME/matlab/OMERO.matlab-5.1.0-ice35-b40/libs/omero_client.jar')
javaaddpath('/Users/bramalingam/OME/matlab/OMERO.matlab-5.1.0-ice35-b40/libs/ini4j.jar')
javaaddpath('/Users/bramalingam/OME/matlab/OMERO.matlab-5.1.0-ice35-b40/libs/bioformats_package.jar')
% Remove the occurances of string s2 from string s1
% Input:
% s1 - big string
% s2 - forbidded string to be removed
%
% Output:
% s - string containing s1 without s2
%
function s = strdiff(s1, s2)
n = length(s2);
f = strfind(s1, s2); % find all occurances of 2nd string in 1st string
if(~isempty(f))
bad_inds = f;
for i=1:n-1
bad_inds = union(bad_inds, f+i);
end
good_inds = setdiff(1:length(s1), bad_inds);
s = s1(good_inds);
else % don't change the string
s = s1;
end
function imageId = upload_image(path,session,username,password,ProjectName,DatasetName,host,importopt)
%Import Packages
import loci.formats.in.DefaultMetadataOptions;
import loci.formats.in.MetadataLevel;
import loci.common.*;
import omero.model.Dataset;
import omero.model.DatasetI;
import ome.services.blitz.repo.*;
import ome.formats.OMEROMetadataStoreClient;
import ome.formats.importer.*;
import ome.formats.importer.ImportConfig;
import ome.formats.importer.cli.ErrorHandler;
import ome.formats.importer.cli.LoggingImportMonitor;
import ome.formats.importer.transfers.*;
import ome.formats.importer.transfers.SymlinkFileTransfer;
import ome.formats.importer.transfers.UploadRmFileTransfer;
import java.util.prefs.*;
%Choose a dataset name, will be assigned to your imported dataset under the root user.
DataForImport = path;%Source Directory
%Logging (switch on)
loci.common.DebugTools.enableLogging('DEBUG');
%Configuration Object
config = ImportConfig();
%Set Config params
config.email.set('');
config.sendFiles.set(true);
config.sendReport.set(false);
config.contOnError.set(false);
config.debug.set(false);
config.hostname.set(host);
port = javaObject('java.lang.Integer',4064);
config.port.set(port);
config.username.set(username);
config.password.set(password);
config.targetClass.set('omero.model.Dataset');
%Check a project named ProjectName
projects = getProjects(session);
project = [];
for j=1:numel(projects)
pjname=char(projects(j).getName.getValue());
if ~isempty(strmatch(pjname,ProjectName,'exact'))
project=projects(j);
break
end
end
if isempty(project)
project = handle(createProject(session, ProjectName));
end
%Check datasetList under the Project to see if there are datasets with
%similar name
datasetsList = project.linkedDatasetList;
for i = 0:datasetsList.size()-1,
d = datasetsList.get(i);
dname = char(d.getName.getValue());
if ~isempty(strmatch(dname,DatasetName,'exact'))
dataset=d;
break
end
end
if (datasetsList.size()==0)
dataset = createDataset(session, DatasetName, project.getId.getValue());
end
dataID = javaObject('java.lang.Long',dataset.getId().getValue());
config.targetId.set(dataID);
%Metadatastore Object
store = config.createStore();
store.logVersionInfo(config.getIniVersionNumber());
reader = OMEROWrapper(config);
%Library Object
if importopt == 1
library = handle(ImportLibrary(store, reader, SymlinkFileTransfer));
elseif importopt == 2
uploadRm = UploadRmFileTransfer;
library = handle(ImportLibrary(store, reader, uploadRm));
else
library = handle(ImportLibrary(store, reader));
end
handler = ErrorHandler(config);
library.addObserver(LoggingImportMonitor());
%Import
paths = DataForImport;
candidates = ImportCandidates(reader, paths, handler);
reader.setMetadataOptions(DefaultMetadataOptions(MetadataLevel.ALL));
% success = library.importCandidates(config, candidates);
containers = candidates.getContainers();
n = containers.size();
imageId = [];
for index=0:n-1
ic = containers.get(index);
ic.setTarget(dataset);
pixels = library.importImage(ic,index,0,n);
imageId = [imageId ; pixels.get(0).getImage.getId.getValue];
end
if importopt == 2
uploadRm.afterTransfer(handler.errorCount,toJavaList(paths));
end
%Logout and close session
store.logout();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment