Git Product home page Git Product logo

gala's Introduction

gala: segmentation of nD images Picture

Gala is a Python library for performing and evaluating image segmentation, distributed under the open-source, BSD-like Janelia Farm license. It implements the algorithm described in Nunez-Iglesias et al., PLOS ONE, 2013.

If you use this library in your research, please cite:

Nunez-Iglesias J, Kennedy R, Plaza SM, Chakraborty A and Katz WT (2014) Graph-based active learning of agglomeration (GALA): a Python library to segment 2D and 3D neuroimages. Front. Neuroinform. 8:34. doi:10.3389/fninf.2014.00034

If you use or compare to the GALA algorithm in your research, please cite:

Nunez-Iglesias J, Kennedy R, Parag T, Shi J, Chklovskii DB (2013) Machine Learning of Hierarchical Clustering to Segment 2D and 3D Images. PLoS ONE 8(8): e71715. doi:10.1371/journal.pone.0071715

Gala supports n-dimensional images (images, volumes, videos, videos of volumes...) and multiple channels per image. It is compatible with Python 3.5.

Build Status Coverage Status

Requirements

After version 0.3, Gala requires Python 3.5 to run. For a full list of dependencies, see the requirements.txt file.

Optional dependencies

In its original incarnation, this project used Vigra for the random forest classifier. Installation is less simple than scikit-learn, which has emerged in recent years as a truly excellent implementation and is now recommended. Tests in the test suite expect scikit-learn rather than Vigra. You can also use any of the scikit-learn classifiers, including their world-class random forest implementation.

Installation

Installing gala

Gala is a Python library with limited Cython extensions and can be installed in three ways:

  • Use pip: pip install gala.
  • Add the gala directory to your PYTHONPATH environment variable, or
  • Use distutils to install it into your preferred python environment:
$ python setup.py install

Installing requirements

Though you can install all the requirements yourself, as most are available in the Python Package Index (PyPI) and can be installed with simple commands, the easiest way to get up and running is to use miniconda. Once you have the conda command, you can create a fully-functional gala environment with conda env create -f environment.yml (inside the gala directory).

Installing with Buildem

Alternatively, you can use Janelia's own buildem system to automatically download, compile, test, and install requirements into a specified buildem prefix directory. (You will need CMake.)

$ cmake -D BUILDEM_DIR=/path/to/platform-specific/build/dir <gala directory>
$ make

You might have to run the above steps twice if this is the first time you are using the buildem system.

On Mac, you might have to install compilers (such as gcc, g++, and gfortran).

Testing

The test coverage is rather small, but it is still a nice way to check you haven't completely screwed up your installation. After installing gala, go to the code directory and type:

$ py.test

You need to have pytest and pytest-cov installed, both of which are available through PyPI.

Usage

An example script, example.py, exists in the tests/example-data directory. We step through it here for a quick rundown of gala's capabilities.

First, import gala's submodules:

from gala import imio, classify, features, agglo, evaluate as ev

Next, read in the training data: a ground truth volume (gt_train), a probability map (pr_train) and a superpixel or watershed map (ws_train).

gt_train, pr_train, ws_train = (map(imio.read_h5_stack,
                                ['train-gt.lzf.h5', 'train-p1.lzf.h5',
                                 'train-ws.lzf.h5']))

A feature manager is a callable object that computes feature vectors from graph edges. The object has the following responsibilities, which it can inherit from classify.base.Null:

  • create a (possibly empty) feature cache on each edge and node, precomputing some of the calculations needed for feature computation;
  • maintain the feature cache throughout node merges during agglomeration; and,
  • compute the feature vector from the feature caches when called with the inputs of a graph and two nodes.

Feature managers can be chained through the features.Composite class.

fm = features.moments.Manager()
fh = features.histogram.Manager()
fc = features.base.Composite(children=[fm, fh])

With the feature manager, and the above data, we can create a region adjacency graph or RAG, and use it to train the agglomeration process:

g_train = agglo.Rag(ws_train, pr_train, feature_manager=fc)
(X, y, w, merges) = g_train.learn_agglomerate(gt_train, fc)[0]
y = y[:, 0] # gala has 3 truth labeling schemes, pick the first one

X and y above have the now-standard scikit-learn supervised dataset format. This means we can use any classifier that satisfies the scikit-learn API. Below, we use a simple wrapper around the scikit-learn RandomForestClassifier.

rf = classify.DefaultRandomForest().fit(X, y)

The composition of a feature map and a classifier defines a policy or merge priority function, which will determine the agglomeration of a volume of hereby unseen data (the test volume).

learned_policy = agglo.classifier_probability(fc, rf)

pr_test, ws_test = (map(imio.read_h5_stack,
                        ['test-p1.lzf.h5', 'test-ws.lzf.h5']))
g_test = agglo.Rag(ws_test, pr_test, learned_policy, feature_manager=fc)

The best expected segmentation is obtained at a threshold of 0.5, when a merge has even odds of being correct or incorrect, according to the trained classifier.

g_test.agglomerate(0.5)

The RAG is a model for the segmentation. To extract the segmentation itself, use the get_segmentation function. This is a map of labels of the same shape as the original image.

seg_test1 = g_test.get_segmentation()

Gala transparently supports multi-channel probability maps. In the case of EM images, for example, one channel may be the probability that a given pixel is part of a cell boundary, while the next channel may be the probability that it is part of a mitochondrion. The feature managers work identically with single and multi-channel features.

# p4_train and p4_test have 4 channels
p4_train = imio.read_h5_stack('train-p4.lzf.h5')
# the existing feature manager works transparently with multiple channels!
g_train4 = agglo.Rag(ws_train, p4_train, feature_manager=fc)
(X4, y4, w4, merges4) = g_train4.learn_agglomerate(gt_train, fc)[0]
y4 = y4[:, 0]
rf4 = classify.DefaultRandomForest().fit(X4, y4)
learned_policy4 = agglo.classifier_probability(fc, rf4)
p4_test = imio.read_h5_stack('test-p4.lzf.h5')
g_test4 = agglo.Rag(ws_test, p4_test, learned_policy4, feature_manager=fc)
g_test4.agglomerate(0.5)
seg_test4 = g_test4.get_segmentation()

For comparison, gala allows the implementation of many agglomerative algorithms, including mean agglomeration (below) and LASH.

g_testm = agglo.Rag(ws_test, pr_test,
                    merge_priority_function=agglo.boundary_mean)
g_testm.agglomerate(0.5)
seg_testm = g_testm.get_segmentation()

Evaluation

The gala library contains numerous evaluation functions, including edit distance, Rand index and adjusted Rand index, and our personal favorite, the variation of information (VI):

gt_test = imio.read_h5_stack('test-gt.lzf.h5')
import numpy as np
results = np.vstack((
    ev.split_vi(ws_test, gt_test),
    ev.split_vi(seg_testm, gt_test),
    ev.split_vi(seg_test1, gt_test),
    ev.split_vi(seg_test4, gt_test)
    ))
print(results)

This should print something like:

[[ 0.1845286   1.64774412]
 [ 0.18719817  1.16091003]
 [ 0.38978567  0.28277887]
 [ 0.39504714  0.2341758 ]]

Each row is an evaluation, with the first number representing the undersegmentation error or false merges, and the second representing the oversegmentation error or false splits, both measured in bits.

(Results may vary since there is some randomness involved in training a random forest, and the datasets are small.)

As mentioned earlier, many other evaluation functions are available. See the documentation for the evaluate package for more information.

# rand index and adjusted rand index
ri = ev.rand_index(seg_test1, gt_test)
ari = ev.adj_rand_index(seg_test1, gt_test)
# Fowlkes-Mallows index
fm = ev.fm_index(seg_test1, gt_test)

Other options

Gala supports a wide array of merge priority functions to explore your data. We can specify the median boundary probability with the merge_priority_function argument to the RAG constructor:

g_testM = agglo.Rag(ws_test, pr_test,
                    merge_priority_function=agglo.boundary_median)

A user can specify their own merge priority function. A valid merge priority function is a callable Python object that takes as input a graph and two nodes, and returns a real number.

To be continued...

That's a quick summary of the capabilities of Gala. There are of course many options under the hood, many of which are undocumented... Feel free to push me to update the documentation of your favorite function!

gala's People

Contributors

anirbanchakraborty avatar apiszcz avatar docsavage avatar jakirkham avatar jefferis avatar jni avatar johnnyteutonic avatar nealjmd avatar pmbuko avatar stephenplaza avatar stuarteberg avatar tobiasmaier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gala's Issues

`_learn_agglomerate` doesn't use learning mode

The line:

if learning_mode != 'strict' or label < 0:

assumes two learning_mode values exist, "strict" and "loose", but instead the labeling_mode ("assignment") is being passed. This results in implicitly using the "loose" mode, and some downstream indexing errors.

See this mailing list post for more information.

errors while running py.test

Hello,

I am trying to use GALA. When I run py.test, I got the following output. This might be some stupid installation problem of mine but I am not able to figure what's going wrong. I tried building NeruoProof and tried copying the libraries (for example, "libNeuroProofPriority ") to the gala-master folder and ran py.test but the output persisted.

Any help is very appreciated!

Following is the error:
`==================================== ERRORS ====================================
___________ ERROR collecting build/lib.linux-x86_64-3.5/gala/auto.py ___________
build/lib.linux-x86_64-3.5/gala/auto.py:2: in
import libNeuroProofPriority as neuroproof
E ImportError: No module named 'libNeuroProofPriority'
___ ERROR collecting build/lib.linux-x86_64-3.5/gala/segmentation_stitch.py ____
build/lib.linux-x86_64-3.5/gala/segmentation_stitch.py:20: in
from . import imio, morpho, classify, evaluate, app_logger, session_manager, pixel, features, stack_np
build/lib.linux-x86_64-3.5/gala/stack_np.py:2: in
import libNeuroProofRag as neuroproof
E ImportError: No module named 'libNeuroProofRag'
_________ ERROR collecting build/lib.linux-x86_64-3.5/gala/stack_np.py _________
build/lib.linux-x86_64-3.5/gala/stack_np.py:2: in
import libNeuroProofRag as neuroproof
E ImportError: No module named 'libNeuroProofRag'
__________ ERROR collecting build/lib.linux-x86_64-3.5/gala/stitch.py __________
build/lib.linux-x86_64-3.5/gala/stitch.py:11: in
from gala import single_arg_read_image_stack
E ImportError: cannot import name 'single_arg_read_image_stack'
_______ ERROR collecting build/lib.linux-x86_64-3.5/gala/test_package.py _______
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:650: in pyimport
import(modname)
E File "/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/test_package.py", line 147
E os.makedirs(writedir)
E ^
E TabError: inconsistent use of tabs and spaces in indentation
_______ ERROR collecting build/lib.linux-x86_64-3.5/gala/test_package.py _______
../../../miniconda3/envs/gala/lib/python3.5/site-packages/_pytest/python.py:610: in _importtestmodule
mod = self.fspath.pyimport(ensuresyspath=importmode)
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:650: in pyimport
import(modname)
E File "/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/test_package.py", line 147
E os.makedirs(writedir)
E ^
E TabError: inconsistent use of tabs and spaces in indentation
_________ ERROR collecting build/lib.linux-x86_64-3.5/gala/valprob.py __________
build/lib.linux-x86_64-3.5/gala/valprob.py:2: in
import libNeuroProofPriority as neuroproof
E ImportError: No module named 'libNeuroProofPriority'
________________________ ERROR collecting gala/agglo.py ________________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.agglo', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/agglo.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/agglo.py'))
_______________________ ERROR collecting gala/agglo2.py ________________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.agglo2', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/agglo2.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/agglo2.py'))
____________________ ERROR collecting gala/annotefinder.py _____________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.annotefinder', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/annotefinder.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/annotefinder.py'))
_____________________ ERROR collecting gala/app_logger.py ______________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.app_logger', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/app_logger.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/app_logger.py'))
______________________ ERROR collecting gala/classify.py _______________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.classify', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/classify.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/classify.py'))
_______________________ ERROR collecting gala/dtypes.py ________________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.dtypes', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/dtypes.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/dtypes.py'))
______________________ ERROR collecting gala/evaluate.py _______________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.evaluate', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/evaluate.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/evaluate.py'))
_______________________ ERROR collecting gala/filters.py _______________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.filters', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/filters.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/filters.py'))
________________________ ERROR collecting gala/imio.py _________________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.imio', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/imio.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/imio.py'))
____________________ ERROR collecting gala/iterprogress.py _____________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.iterprogress', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/iterprogress.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/iterprogress.py'))
_____________________ ERROR collecting gala/mergequeue.py ______________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.mergequeue', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/mergequeue.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/mergequeue.py'))
_______________________ ERROR collecting gala/morpho.py ________________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.morpho', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/morpho.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/morpho.py'))
________________________ ERROR collecting gala/ncut.py _________________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.ncut', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/ncut.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/ncut.py'))
___________________ ERROR collecting gala/option_manager.py ____________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.option_manager', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/option_manager.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/option_manager.py'))
________________________ ERROR collecting gala/pixel.py ________________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.pixel', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/pixel.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/pixel.py'))
________________ ERROR collecting gala/segmentation_pipeline.py ________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.segmentation_pipeline', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/segmentation_pipeline.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/segmentation_pipeline.py'))
________________________ ERROR collecting gala/serve.py ________________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.serve', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/serve.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/serve.py'))
___________________ ERROR collecting gala/session_manager.py ___________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.session_manager', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/session_manager.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/session_manager.py'))
______________________ ERROR collecting gala/sparselol.py ______________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.sparselol', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/sparselol.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/sparselol.py'))
________________________ ERROR collecting gala/util.py _________________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.util', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/util.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/util.py'))
_________________________ ERROR collecting gala/viz.py _________________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.viz', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/viz.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/viz.py'))
____________________ ERROR collecting gala/features/base.py ____________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.features.base', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/features/base.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/features/base.py'))
________________ ERROR collecting gala/features/convex_hull.py _________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.features.convex_hull', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/features/convex_hull.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/features/convex_hull.py'))
__________________ ERROR collecting gala/features/default.py ___________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.features.default', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/features/default.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/features/default.py'))
___________________ ERROR collecting gala/features/graph.py ____________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.features.graph', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/features/graph.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/features/graph.py'))
_________________ ERROR collecting gala/features/inclusion.py __________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.features.inclusion', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/features/inclusion.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/features/inclusion.py'))
_____________________ ERROR collecting gala/features/io.py _____________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.features.io', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/features/io.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/features/io.py'))
________________ ERROR collecting gala/features/orientation.py _________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.features.orientation', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/features/orientation.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/features/orientation.py'))
________________ ERROR collecting gala/features/squiggliness.py ________________
../../../miniconda3/envs/gala/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
raise self.ImportMismatchError(modname, modfile, self)
E py._path.local.LocalPath.ImportMismatchError: ('gala.features.squiggliness', '/home/kalyan/Desktop/GalaDirIn/gala-master/build/lib.linux-x86_64-3.5/gala/features/squiggliness.py', local('/home/kalyan/Desktop/GalaDirIn/gala-master/gala/features/squiggliness.py'))

Make graph backends more easily swappable

Rather than having agglo.Rag, stack_np.Stack, and any future additions to the backends, it would be simpler for users to have syntax:

g = gala.Graph(backend='NeuroProof')

This offers the advantages of a simpler codebase, and the ability to easily switch default backends based on evolving needs of the FlyEM project, while maintaining all backends for specific user needs.

Related to this issue is my recent discovery of the graph-tools and zen libraries, both of which could make excellent substitutes for NetworkX.

Support non-sequential labels in input data

Non-sequential data in supervoxels during training can result in errors during learning, as well as log(0) errors (due to non-existing segments). See this thread on the mailing list for details.

The simplest fix is to run skimage.relabel_sequential on both the superpixel and ground truth volumes, but I'm not sure whether other things would break at that point (and we might need to maintain the inverse maps if specific labels need to be reported back to the user). Ideally, we would have a test case to ensure this doesn't regress.

Enable progress bar during learning

The progress bar is currently turned off during training because the total number of queue pops is unknown (since a pop can be valid but not result in a merge), and exceeding 100% of merges results in a crash.

Possible options:

  • find an upper bound for the total number of examined edges and use that as the total. Downside is that this might be much higher than necessary, resulting in over-inflated ETAs and never reaching 100%.
  • find an average case for the total number of examined cases, and modify the progress bar behaviour to prevent crashes upon reaching 100%.
  • find a way to update the total during execution.
  • find a way to update the current number of merges during execution.

Request Docker image or updated version of GALA

Dear Gala team,

thank you for creating GALA .
Currently, the library has a dependency problem.

I tried to solve it by changing the source code to fit with the current library like scikit-image, etc.
However, I still cannot fix it.

Do you have any plans to maintained it?
or do you have the docker image for GALA?

help me new to python

import gala.coordinates as gc import gala.dynamics as gd import gala.potential as gp


ImportError Traceback (most recent call last)
in
13
14 #gala imports
---> 15 import gala.coordinates as gc
16 import gala.dynamics as gd
17 import gala.potential as gp

~/opt/anaconda3/lib/python3.7/site-packages/gala/init.py in
24 if not ASTROPY_SETUP:
25 from . import coordinates
---> 26 from . import dynamics
27 from . import integrate
28 from . import potential

~/opt/anaconda3/lib/python3.7/site-packages/gala/dynamics/init.py in
1 from .core import PhaseSpacePosition, CartesianPhaseSpacePosition
2 from .orbit import Orbit, CartesianOrbit
----> 3 from .analyticactionangle import *
4 from .actionangle import *
5 from .nonlinear import *

~/opt/anaconda3/lib/python3.7/site-packages/gala/dynamics/analyticactionangle.py in
11
12 # Project
---> 13 from ..potential import (Hamiltonian, PotentialBase,
14 IsochronePotential, HarmonicOscillatorPotential)
15 from ..util import atleast_2d

~/opt/anaconda3/lib/python3.7/site-packages/gala/potential/init.py in
----> 1 from .potential import *
2 from .hamiltonian import *
3 from .frame import *
4 from .scf import SCFPotential

~/opt/anaconda3/lib/python3.7/site-packages/gala/potential/potential/init.py in
2 from .cpotential import *
3 from .ccompositepotential import *
----> 4 from .builtin import *
5 from .io import *
6 from .util import *

~/opt/anaconda3/lib/python3.7/site-packages/gala/potential/potential/builtin/init.py in
1 from .cybuiltin import *
2 from .pybuiltin import *
----> 3 from .special import *

~/opt/anaconda3/lib/python3.7/site-packages/gala/potential/potential/builtin/special.py in
6 # from .cpotential import CCompositePotential
7 # from ..core import CompositePotential
----> 8 from .cybuiltin import (HernquistPotential,
9 MiyamotoNagaiPotential,
10 LogarithmicPotential,

ImportError: cannot import name 'HernquistPotential' from 'gala.potential.potential.builtin.cybuiltin' (unknown location)``

Image library import needs updating for Fedora 19+

Line 12 of gala/imio.py does not work correctly on Fedora 19 and later. The Python Imaging Library package included in the Fedora repository, python-imaging, has been replaced by python-pillow. This is a drop-in replacement with one exception:

You can no longer use

import Image

but must instead use

from PIL import Image

Where and why to ignore 0 in VI?

Thank you for sharing your code.
And I found that the codes in skimage and cremi are also based on your code.
*skimage: https://github.com/scikit-image/scikit-image/blob/master/skimage/metrics/_variation_of_information.py
*cremi: https://github.com/cremi/cremi_python/blob/master/cremi/evaluation/voi.py
But there is a tiny question: Where and why to ignore 0 in VI?
For your code, gala, you ignore 0 both in gt and pred (Default)
For cremi code, they only ignore 0 in gt, not in pred (Deafult)
For skimage, they did not ignore 0 in gt and pred (Default)
I made a simple comparison below, and i found that different setting will draw out different result. Can you tell what should i do in the task of neuron segmentation? Do i need to ignore 0 label in both gt and pred?
image

No module named gala

Hi,
I installed gala into two machines (win8 & ubuntu). Apparently it was correctly installed.
But when I try to run the examples into test folder, it sends this message:

python test_agglo.py
ImportError: No module named gala

I included gala folder into PATH (win8) and .profile file (ubuntu), but this happens on both systems.
so what I did wrong? what I have to do to run it?

thanks, jaime

Add CONTRIBUTING.md file

This gets automatically displayed by github any time someone opens an issue or submits a pull request.

Find way to activate long testing in Travis easily

Some tests were taking too long, so I replaced them with corresponding tests with tiny data. Nevertheless, the long tests are still there with a skipif decorator (see here) and they are useful to run occasionally because they use real data. It would be great to enable them easily on Travis e.g. with a flag in the commit message, e.g. for refactors that alter large chunks of code. I haven't yet explored how this can be done realistically.

Include pre-built segmentation models

Training gala is cumbersome, especially for newcomers and especially especially for natural images (ie many training examples). It would be nice to include some pre-trained RFs and feature transforms that would allow someone to immediately get a segmentation of a natural image with gala.

Benchmark building ijv triplets from CSR

We have two options:

  • directly from CSR:
        edges_iter = ((i, j, {'boundary-ids': {edge_map[i, j]}})
                      for i in range(edge_map.shape[0])
                      for j in edge_map.indices[edge_map.indptr[i]:
                                                edge_map.indptr[i+1]])
  • or via COO:
        coo = edge_map.tocoo()
        edges_iter = ((i, j, {'boundary-ids': {k}}) for i, j, k in
                      zip(coo.row, coo.col, coo.data))

They are unlikely to be equal in performance, but performance might be data-dependent.

agglo.best_possible_segmentation()

agglo.best_possible_segmentation() returns wrong result if fragments are not continuous starting at 1

ws = np.array([[2,3],[4,5]], np.int32)
gt = np.array([[1,2],[1,2]], np.int32)
agglo.best_possible_segmentation(ws, gt)
array([[1, 7], [3, 7]])

the expected result is array([[a, b], [a, b]])

KeyError in rag.learn_agglomerate(...)

Hi,

I am trying to run Gala (current master) on 2D images of neural tissue, but I keep getting a KeyError in learn_agglomerate(). I am using the following python script:

#!/usr/bin/python

from gala import imio, classify, features, agglo, evaluate as ev
from skimage.segmentation import relabel_sequential

print "Reading groundtruth..."
gt = imio.read_image_stack("./gt/neuron_ids0000.png")
print "Reading probability maps..."
pr = imio.read_image_stack("./prob/membrane0000.png")
print "Reading superpixels..."
sp = imio.read_image_stack("./superpixels/membrane0000.tif")

gt = relabel_sequential(gt)[0]
sp = relabel_sequential(sp)[0]

print "Creating feature managers..."
fm = features.moments.Manager()
fh = features.histogram.Manager()
fc = features.base.Composite(children=[fm, fh])

print "Creating RAG..."
rag = agglo.Rag(sp, pr, feature_manager=fc)
(X, y, w, merges) = rag.learn_agglomerate(gt, fc)[0]
y = y[:,0]
print((X.shape, y.shape))

print "Training..."
rf = classify.DefaultRandomForest().fit(X, y)

classify.save_classifier(rf, "rf.dat")

on this data: http://lego.slyip.net/gala_mwe.tar.gz. This is the traceback of the error I get:

Traceback (most recent call last):
  File "./train.py", line 23, in <module>
    (X, y, w, merges) = rag.learn_agglomerate(gt, fc)[0]
  File "/usr/local/lib/python2.7/dist-packages/gala-0.3dev-py2.7-linux-x86_64.egg/gala/agglo.py", line 1264, in learn_agglomerate
    learning_mode, labeling_mode))
  File "/usr/local/lib/python2.7/dist-packages/gala-0.3dev-py2.7-linux-x86_64.egg/gala/agglo.py", line 1411, in _learn_agglomerate
    node_id = g.merge_nodes(n1, n2, merge_priority)
  File "/usr/local/lib/python2.7/dist-packages/gala-0.3dev-py2.7-linux-x86_64.egg/gala/agglo.py", line 1582, in merge_nodes
    self.refine_post_merge_boundaries(n1, n2, sp2segment)
  File "/usr/local/lib/python2.7/dist-packages/gala-0.3dev-py2.7-linux-x86_64.egg/gala/agglo.py", line 1636, in refine_post_merge_boundaries
    self.update_merge_queue(u, v)
  File "/usr/local/lib/python2.7/dist-packages/gala-0.3dev-py2.7-linux-x86_64.egg/gala/agglo.py", line 1742, in update_merge_queue
    w = self.merge_priority_function(self,u,v)
  File "/usr/local/lib/python2.7/dist-packages/gala-0.3dev-py2.7-linux-x86_64.egg/gala/agglo.py", line 207, in predict
    features = feature_extractor(g, n1, n2)
  File "/usr/local/lib/python2.7/dist-packages/gala-0.3dev-py2.7-linux-x86_64.egg/gala/features/base.py", line 9, in __call__
    return self.compute_features(g, n1, n2)
  File "/usr/local/lib/python2.7/dist-packages/gala-0.3dev-py2.7-linux-x86_64.egg/gala/features/base.py", line 19, in compute_features
    if g.node[n1]['size'] > g.node[n2]['size']:
KeyError: 'size'
Exception TypeError: TypeError("'NoneType' object is not callable",) in <bound method UmfpackContext.new_del of <scipy.sparse.linalg.dsolve.umfpack.umfpack.UmfpackContext object at 0x7f1a02408610>> ignored

Any help would be greatly appreciated!

Cheers,
Jan

unexpected keyword argument 'random_state'

Hello,
I was trying to run an adapted version of example.py as shown in the appendix below, with the example data provided with the source code.

However, I get the following error:

python example_1.py 
pylibtiff not available: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pylibtiff
~/miniconda2/envs/gala/lib/python3.5/site-packages/gala/agglo.py:265: RuntimeWarning: invalid value encountered in double_scalars
  return p3*log2(p3) - p1*log2(p1) - p2*log2(p2) - \
Traceback (most recent call last):
  File "galaTest1.py", line 47, in <module>
    (X, y, w, merges) = g_train.learn_agglomerate(gt_train, fc)[0]
  File "~/miniconda2/envs/gala/lib/python3.5/site-packages/gala/agglo.py", line 1091, in learn_agglomerate
    cl = get_classifier(classifier, random_state=random_state)
  File "~/miniconda2/envs/gala/lib/python3.5/site-packages/gala/classify.py", line 168, in get_classifier
    return VigraRandomForest(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'random_state'

Any idea of what's gone wrong?

Thanks
Thanuja


Appendix: code

from gala import imio, classify, features, agglo, evaluate as ev
import numpy as np
#import scipy.misc.imsave
import os
from PIL import Image

'''
Inputs
'''

h5File_train_gt = 'train-gt.lzf.h5'
h5File_train_ws = 'train-ws.lzf.h5'
h5File_train_probMap = 'train-p1.lzf.h5'

h5File_test_ws = 'test-ws.lzf.h5'
h5File_test_probMap = 'test-p1.lzf.h5'

'''
Outputs
'''
outputRoot = '20160627_gala_sstem'

# read in training data
# groundtruth volume, probability maps, superpixe/watershed map
gt_train, pr_train, ws_train = (map(imio.read_h5_stack,
                                [h5File_train_gt, h5File_train_probMap,
                                 h5File_train_ws]))

# create a feature manager
fm = features.moments.Manager()
fh = features.histogram.Manager()
fc = features.base.Composite(children=[fm, fh])

# create Region Adjacency Graph (RAG) and obtain a training dataset
g_train = agglo.Rag(ws_train, pr_train, feature_manager=fc)
(X, y, w, merges) = g_train.learn_agglomerate(gt_train, fc)[0]
y = y[:, 0] # gala has 3 truth labeling schemes, pick the first one ????
print((X.shape, y.shape)) # standard scikit-learn input format

# train a classifier, scikit-learn syntax
rf = classify.DefaultRandomForest().fit(X, y)
# a policy is the composition of a feature map and a classifier
# policy = merge priority function
learned_policy = agglo.classifier_probability(fc, rf)

# get the test data and make a RAG with the trained policy
pr_test, ws_test = (map(imio.read_h5_stack,
                        [h5File_test_probMap, h5File_test_ws]))
g_test = agglo.Rag(ws_test, pr_test, learned_policy, feature_manager=fc)
g_test.agglomerate(0.5) # best expected segmentation obtained with a threshold of 0.5
seg_test1 = g_test.get_segmentation()

# convert hdf into png and save 
np_data = np.array(seg_test1)
sizeZ,sizeY,sizeX = np_data.shape
for i in range(0,sizeZ):
    im1 = np_data[i,:,:]
    im = Image.fromarray(im1.astype('uint8'))
    imFileName = str(i).zfill(3) + ".png"
    imFileName = os.path.join(outputRoot,imFileName)
    #scipy.misc.toimage(im, cmin=0.0, cmax=...).save(imFileName)
    im.save(imFileName)

gala.sparselol_cy

It goes like
ERROR gala/agglo.py - ModuleNotFoundError: No module named 'gala.sparselol_cy'

It coinutes whit 23 more error, how can i fix it?

Ensure `agglo.Rag.separate_fragments` leaves a consistent graph

Currently, the separate_fragments methods splits up the merge tree, but it doesn't touch the graph. This means that the merge tree and the graph are inconsistent with each other and results in later errors.

Two things need to happen:

  • when splitting off two branches of the tree, the implied RAG nodes need to be built.
  • one of the two branches needs to be merged to the parent of the deleted node, if applicable.

KeyError when adding boundary with label 0 in oversegmentation

I'm trying to add a region with label 0 in the oversegmentation to represent boundary.
But whenever there's a 0 in the oversegmentation (even only one at a random position) gala raises a KeyError during the training.
Some debugging revealed that node includes an entry that does not contain any properties.
However, the index of that node changes from run to run.

Traceback (most recent call last):
File "/home/lheinric/PycharmProjects/GALA_test/own_test.py", line 128, in
test()
File "/home/lheinric/PycharmProjects/GALA_test/own_test.py", line 60, in test
(X, y, w, merges) = g_train.learn_agglomerate(gt_train, fc)[0]
File "/home/lheinric/.local/lib/python2.7/site-packages/gala/agglo.py", line 1261, in learn_agglomerate
learning_mode, labeling_mode))
File "/home/lheinric/.local/lib/python2.7/site-packages/gala/agglo.py", line 1408, in _learn_agglomerate
node_id = g.merge_nodes(n1, n2, merge_priority)
File "/home/lheinric/.local/lib/python2.7/site-packages/gala/agglo.py", line 1579, in merge_nodes
self.refine_post_merge_boundaries(n1, n2, sp2segment)
File "/home/lheinric/.local/lib/python2.7/site-packages/gala/agglo.py", line 1633, in refine_post_merge_boundaries
self.update_merge_queue(u, v)
File "/home/lheinric/.local/lib/python2.7/site-packages/gala/agglo.py", line 1739, in update_merge_queue
w = self.merge_priority_function(self,u,v)
File "/home/lheinric/.local/lib/python2.7/site-packages/gala/agglo.py", line 207, in predict
features = feature_extractor(g, n1, n2)
File "/home/lheinric/.local/lib/python2.7/site-packages/gala/features/base.py", line 9, in call
return self.compute_features(g, n1, n2)
File "/home/lheinric/.local/lib/python2.7/site-packages/gala/features/base.py", line 19, in compute_features
if g.node[n1]['size'] > g.node[n2]['size']:
KeyError: 'size'

agglo.py runtime warning and and unmerged output

Hi
From my tif dataset I created hdf5 files with an identical structure to the ones used in example.py and ran the following code (Appendix 1) similar to example.py with the addition of converting the output into png files. I get the following warning:

/miniconda2/envs/gala/lib/python3.5/site-packages/gala/agglo.py:265: RuntimeWarning: invalid value encountered in double_scalars
  return p3*log2(p3) - p1*log2(p1) - p2*log2(p2) - \

Also, the final segmentation seems to be the same as the initial superpixel map:
000

The probability map for this image is:
00_probmap

with superpixel map obtained by Watershed transform (labeled with integers):
00_ws

What do you think is the problem?

Thanks in advance!


Appendix 1 (Code)

from gala import imio, classify, features, agglo, evaluate as ev
import numpy as np
import os
from PIL import Image
'''
Inputs
'''
h5File_train_gt = 'train_gt.h5'
h5File_train_ws = 'train_ws.h5'
h5File_train_probMap = 'train_probMaps.h5'

h5File_test_ws = 'test_ws.h5'
h5File_test_probMap = 'test_probMaps.h5'

'''
Outputs
'''
outputRoot = 'outputs'

# read in training data
# groundtruth volume, probability maps, superpixe/watershed map
gt_train, pr_train, ws_train = (map(imio.read_h5_stack,
                                [h5File_train_gt, h5File_train_probMap,
                                 h5File_train_ws]))

# create a feature manager
fm = features.moments.Manager()
fh = features.histogram.Manager()
fc = features.base.Composite(children=[fm, fh])

# create Region Adjacency Graph (RAG) and obtain a training dataset
g_train = agglo.Rag(ws_train, pr_train, feature_manager=fc)
(X, y, w, merges) = g_train.learn_agglomerate(gt_train, fc)[0]
y = y[:, 0] # gala has 3 truth labeling schemes, pick the first one ????
print((X.shape, y.shape)) # standard scikit-learn input format

# train a classifier, scikit-learn syntax
rf = classify.DefaultRandomForest().fit(X, y)
# a policy is the composition of a feature map and a classifier
# policy = merge priority function
learned_policy = agglo.classifier_probability(fc, rf)

# get the test data and make a RAG with the trained policy
pr_test, ws_test = (map(imio.read_h5_stack,
                        [h5File_test_probMap, h5File_test_ws]))
g_test = agglo.Rag(ws_test, pr_test, learned_policy, feature_manager=fc)
g_test.agglomerate(0.5) # best expected segmentation obtained with a threshold of 0.5
seg_test1 = g_test.get_segmentation()

# convert hdf into png and save 
np_data = np.array(seg_test1)
sizeZ,sizeY,sizeX = np_data.shape
for i in range(0,sizeZ):
    im1 = np_data[i,:,:]
    im = Image.fromarray(im1.astype('uint8'))
    imFileName = str(i).zfill(3) + ".png"
    imFileName = os.path.join(outputRoot,imFileName)
    im.save(imFileName)

pip install not working with newer cython

Upgrade to cython 0.22 and then install via pip.
First error says no *.pyx files found (line 59). Edited setup.py to change to *.py and then build continues and files with compile error in agglo.py

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.