Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • swain-lab/aliby/aliby-mirror
  • swain-lab/aliby/alibylite
2 results
Show changes
Commits on Source (1222)
[flake8]
ignore = E203, E266, E501, W503, F403, F401
max-line-length = 79
select = B,C,E,F,W,T4,B9
exclude =
# No need to traverse our git directory
.git,
# There's no value in checking cache directories
__pycache__,
# Ignore virtual environment contents
.venv
# The conf file is mostly autogenerated, ignore it
docs/source/conf.py,
# The old directory contains Flake8 2.0
old,
# This contains our built documentation
build,
# This contains builds of flake8 that we don't want to check
dist,
# Any data produced inside the folder during development
data/,
# Temporarily ignore tests
tests/
max-complexity = 18
......@@ -110,7 +110,6 @@ venv.bak/
omero_py/omeroweb/
omero_py/pipeline/
**.ipynb
data/
notebooks/
*.pdf
*.h5
......
image: python:3.7
image: python:3.8
cache:
key: "project-${CI_JOB_NAME}"
......@@ -12,9 +12,9 @@ variables:
TRIGGER_PYPI_NAME: ""
stages:
- test
- check
- release
- tests
- checks
# - release
before_script:
- test -e $HOME/.poetry/bin/ || curl -sSL https://install.python-poetry.org | python3 -
......@@ -22,48 +22,68 @@ before_script:
- poetry --version
- poetry config virtualenvs.in-project true
- pip install --upgrade pip
- git remote rm origin && git remote add origin https://${ACCESS_TOKEN_NAME}:${ACCESS_TOKEN}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git
- git config pull.rebase false
- git pull origin HEAD:master
- rm -rf ~/.cache/pypoetry
- if [ ${var+TRIGGER_PYPI_NAME} ]; then echo "Pipeline triggered by ${TRIGGER_PYPI_NAME}"; poetry add ${TRIGGER_PYPI_NAME}@latest; fi
- poetry install -vv
# - git remote rm origin && git remote add origin https://${ACCESS_TOKEN_NAME}:${ACCESS_TOKEN}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git
# - git config pull.rebase false
# - git pull origin HEAD:master
# - rm -rf ~/.cache/pypoetry
# - if [ ${var+TRIGGER_PYPI_NAME} ]; then echo "Pipeline triggered by ${TRIGGER_PYPI_NAME}"; poetry add ${TRIGGER_PYPI_NAME}@latest; fi
# - export WITHOUT="docs,network";
- export ARGS="--with test,dev";
- if [[ "$CI_STAGE_NAME" == "tests" ]]; then echo "Installing system dependencies for ${CI_STAGE_NAME}"; apt update && apt install -y ffmpeg libsm6 libxext6; fi
- if [[ "$CI_JOB_NAME" == "Static Type" ]]; then echo "Activating development group"; export ARGS="${ARGS},dev"; fi
- if [[ "$CI_JOB_NAME" == "Network Tools Tests" ]]; then echo "Setting flag to compile zeroc-ice"; export ARGS="${ARGS} --all-extras"; fi
- poetry install -vv $ARGS
Unit test:
stage: test
Local Tests:
stage: tests
script:
- apt update && apt install ffmpeg libsm6 libxext6 -y
- poetry run pytest ./tests/
# - poetry install -vv
- poetry run coverage run -m --branch pytest ./tests --ignore ./tests/aliby/network --ignore ./tests/aliby/pipeline
- poetry run coverage report -m
- poetry run coverage xml
coverage: '/(?i)total.*? (100(?:\.0+)?\%|[1-9]?\d(?:\.\d+)?\%)$/'
artifacts:
reports:
coverage_report:
coverage_format: cobertura
path: coverage.xml
Python Code Lint:
stage: check
Network Tools Tests:
stage: tests
script:
- poetry run black .
- poetry run pytest ./tests/aliby/network
- DIRNAME="test_datasets"
- curl https://zenodo.org/record/7513194/files/test_datasets.tar.gz\?download\=1 -o "test_datasets.tar.gz"
- mkdir -p $DIRNAME
- tar xvf test_datasets.tar.gz -C $DIRNAME
- poetry run pytest -s tests/aliby/pipeline --file $DIRNAME/560_2022_11_30_pypipeline_unit_test_reconstituted_00
Static Type:
stage: check
stage: checks
allow_failure: true
script:
- poetry run black .
- poetry run isort .
- poetry run mypy . --exclude 'setup\.py$'
# We can remove the flag once this is resolved https://github.com/pypa/setuptools/issues/2345
Bump_release:
stage: release
script:
- git config --global user.email ${GITLAB_USER_EMAIL}
- git config --global user.name ${GITLAB_USER_NAME}
- git pull origin HEAD:MASTER && poetry version ${BUMP_RULE} && git add poetry.lock add pyproject.toml poetry.lock && git commit -m "Bump version" && git push -o ci.skip origin HEAD:master && poetry publish --build --username ${PYPI_USER} --password ${PYPI_PASSWORD}
- echo "TRIGGER_PYPI_NAME=$(cat pyproject.toml | grep '^name =' | head -n 1 | cut -f3 -d' ' | tr -d \")" >> build.env
- echo "Exporting TRIGGER_PYPI_NAME as ${TRIGGER_PYPI_NAME}"
only:
- master
except:
changes:
- tests/
- .*
# TODO add more tests before activating auto-release
# Bump_release:
# stage: release
# script:
# - git config --global user.email ${GITLAB_USER_EMAIL}
# - git config --global user.name ${GITLAB_USER_NAME}
# # - git pull origin HEAD:MASTER && poetry version ${BUMP_RULE} && git add poetry.lock add pyproject.toml poetry.lock && git commit -m "Bump version" && git push -o ci.skip origin HEAD:master && poetry publish --build --username ${PYPI_USER} --password ${PYPI_PASSWORD}
# - echo "TRIGGER_PYPI_NAME=$(cat pyproject.toml | grep '^name =' | head -n 1 | cut -f3 -d' ' | tr -d \")" >> build.env
# - echo "Exporting TRIGGER_PYPI_NAME as ${TRIGGER_PYPI_NAME}"
# only:
# - master
# except:
# changes:
# - tests/
# - .*
needs:
job: Unit test
# needs:
# job: Unit test
## Custom stages ##
## Summary
(Summarize the bug encountered concisely)
{Summarize the bug encountered concisely}
I confirm that I have (if relevant):
- [ ] Read the troubleshooting guide: https://gitlab.com/aliby/aliby/-/wikis/Troubleshooting-(basic)
- [ ] Updated aliby and aliby-baby.
- [ ] Tried the unit test.
- [ ] Tried a scaled-down version of my experiment (distributed=0, filter=0, tps=10)
- [ ] Tried re-postprocessing.
## Steps to reproduce
(How one can reproduce the issue - this is very important)
{How one can reproduce the issue - this is very important}
- aliby version: 0.1.{...}, or if development/unreleased version, commit SHA: {...}
- platform(s):
- [ ] Jura
- [ ] Other Linux, please specify distribution and version: {...}
- [ ] MacOS, please specify version: {...}
- [ ] Windows, please specify version: {...}
- experiment ID: {...}
- Any special things you need to know about this experiment: {...}
## What is the current bug behavior?
......@@ -19,7 +35,12 @@
(Paste any relevant logs - please use code blocks (```) to format console output, logs, and code, as
it's very hard to read otherwise.)
```
{PASTE YOUR ERROR MESSAGE HERE!!}
```
## Possible fixes
(If you can, link to the line of code that might be responsible for the problem)
exclude: '^examples/'
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.3.0
hooks:
# - id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
args: [--markdown-linebreak-ext=md]
- id: check-added-large-files
- id: check-docstring-first
- id: name-tests-test
args: [--pytest-test-first]
- repo: https://github.com/psf/black
rev: 22.6.0
hooks:
- id: black
- repo: https://github.com/PyCQA/isort
rev: 5.10.1
hooks:
- id: isort
- repo: https://github.com/PyCQA/flake8
rev: 4.0.1
hooks:
- id: flake8
exclude: ^tests/ # Temporarily exclude tests
# .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Set the version of Python and other tools you might need
build:
os: ubuntu-20.04
tools:
python: "3.8"
# Build documentation in the docs/ directory with Sphinx
sphinx:
configuration: docs/source/conf.py
# If using Sphinx, optionally build your docs in additional formats such as PDF
# formats:
# - pdf
# Optionally declare the Python requirements required to build your docs
python:
install:
- requirements: docs/requirements.txt
# Contributing
We focus our work on python 3.8 due to the current neural network being developed on tensorflow 1. In the near future we will migrate the network to pytorch to support more recent versions of all packages.
## Issues
All issues are managed within the gitlab [ repository ](https://gitlab.com/aliby/aliby/-/issues), if you don't have an account on the University of Edinburgh's gitlab instance and would like to submit issues please get in touch with [Prof. Peter Swain](mailto:peter.swain@ed.ac.uk ).
## Data aggregation
ALIBY has been tested by a few research groups, but we welcome new data sources for the models and pipeline to be as general as possible. Please get in touch with [ us ](mailto:peter.swain@ed.ac.uk ) if you are interested in testing it on your data.
# Installation
Tested on: Mac OSX Mojave
## Requirements
We strongly recommend installing within a python environment as there are many dependencies that you may not want polluting your regular python environment.
Make sure you are using python 3.
An environment can be created with using the conda package manager:
$ conda create --name <env>
$ conda activate <env>
Which you can deactivate with:
$ conda deactivate
Or using virtualenv:
$ python -m virtualenv /path/to/venv/
$ source /path/to/venv/bin/activate
This will download all of your packages under `/path/to/venv` and then activate it.
Deactivate using
$ deactivate
You will also need to make sure you have a recent version of pip.
In your local environment, run:
$ pip install --upgrade pip
## Pipeline installation
Once you have created your local environment, run:
$ cd pipeline-core
$ pip install -e ./
You will be asked to put in your GitLab credentials for a couple of the packages installed as dependencies.
The `-e` option will install in 'editable' mode: all of the changes that are made to the code in the repository will immediately be reflected in the installation.
This is very useful to keep up with any changes and branching that we make.
That way, if you want to keep up with the most recent updates, just run:
$ git pull
If you would rather be more in charge of which updates you install and which you don't, remove `-e` from your installation command.
In this case (or if you run into a dependency error) in order to update your installed version you will have to run:
$ cd pipeline-core
$ git pull
$ pip install ./
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.
# Pipeline core
# ALIBY (Analyser of Live-cell Imaging for Budding Yeast)
The core classes and methods for the python microfluidics, microscopy, and
analysis pipeline.
### Installation
See [INSTALL.md](./INSTALL.md) for installation instructions.
[![docs](https://readthedocs.org/projects/aliby/badge/?version=master)](https://aliby.readthedocs.io/en/latest)
[![PyPI version](https://badge.fury.io/py/aliby.svg)](https://badge.fury.io/py/aliby)
[![pipeline](https://gitlab.com/aliby/aliby/badges/master/pipeline.svg?key_text=master)](https://gitlab.com/aliby/aliby/-/pipelines)
[![dev pipeline](https://gitlab.com/aliby/aliby/badges/dev/pipeline.svg?key_text=dev)](https://gitlab.com/aliby/aliby/-/commits/dev)
[![coverage](https://gitlab.com/aliby/aliby/badges/dev/coverage.svg)](https://gitlab.com/aliby/aliby/-/commits/dev)
End-to-end processing of cell microscopy time-lapses. ALIBY automates segmentation, tracking, lineage predictions, post-processing and report production. It leverages the existing Python ecosystem and open-source scientific software available to produce seamless and standardised pipelines.
## Quickstart Documentation
### Setting up a server
For testing and development, the easiest way to set up an OMERO server is by
using Docker images.
[The software carpentry](https://software-carpentry.org/) and the [Open
Microscopy Environment](https://www.openmicroscopy.org), have provided
[instructions](https://ome.github.io/training-docker/) to do this.
The `docker-compose.yml` file can be used to create an OMERO server with an
accompanying PostgreSQL database, and an OMERO web server.
It is described in detail
[here](https://ome.github.io/training-docker/12-dockercompose/).
Our version of the `docker-compose.yml` has been adapted from the above to
use version 5.6 of OMERO.
To start these containers (in background):
```shell script
cd pipeline-core
docker-compose up -d
```
Omit the `-d` to run in foreground.
Installation of [VS Studio](https://visualstudio.microsoft.com/downloads/#microsoft-visual-c-redistributable-for-visual-studio-2022) Native MacOS support for is under work, but you can use containers (e.g., Docker, Podman) in the meantime.
To stop them, in the same directory, run:
```shell script
docker-compose stop
```
To analyse local data
```bash
pip install aliby
```
Add any of the optional flags `omero` and `utils` (e.g., `pip install aliby[omero, utils]`). `omero` provides tools to connect with an OMERO server and `utils` provides visualisation, user interface and additional deep learning tools.
See our [installation instructions]( https://aliby.readthedocs.io/en/latest/INSTALL.html ) for more details.
### CLI
If installed via poetry, you have access to a Command Line Interface (CLI)
```bash
aliby-run --expt_id EXPT_PATH --distributed 4 --tps None
```
And to run Omero servers, the basic arguments are shown:
```bash
aliby-run --expt_id XXX --host SERVER.ADDRESS --user USER --password PASSWORD
```
The output is a folder with the original logfiles and a set of hdf5 files, one with the results of each multidimensional inside.
For more information, including available options, see the page on [running the analysis pipeline](https://aliby.readthedocs.io/en/latest/PIPELINE.html)
### Raw data access
## Using specific components
### Access raw data
ALIBY's tooling can also be used as an interface to OMERO servers, for example, to fetch a brightfield channel.
```python
from aliby.io.omero import Dataset, Image
......@@ -56,129 +60,53 @@ with Image(list(image_ids.values())[0], **server_info) as image:
imgs = dimg[tps, image.metadata["channels"].index("Brightfield"), 2, ...].compute()
# tps timepoints, Brightfield channel, z=2, all x,y
```
### Tiling the raw data
A `Tiler` object performs trap registration. It is built in different ways, the easiest one is using an image and a the default parameters set.
A `Tiler` object performs trap registration. It may be built in different ways but the simplest one is using an image and a the default parameters set.
```python
from aliby.tile.tiler import Tiler, TilerParameters
with Image(list(image_ids.values())[0], **server_info) as image:
tiler = Tiler.from_image(image, TilerParameters.default())
tiler.run_tp(0)
```
The initialisation should take a few seconds, as it needs to align the images
in time.
in time.
It fetches the metadata from the Image object, and uses the TilerParameters values (all Processes in aliby depend on an associated Parameters class, which is in essence a dictionary turned into a class.)
#### Get a timelapse for a given trap
TODO: Update this
#### Get a timelapse for a given tile (remote connection)
```python
channels = [0] #Get only the first channel, this is also the default
z = [0, 1, 2, 3, 4] #Get all z-positions
trap_id = 0
tile_size = 117
# Get a timelapse of the trap
# The default trap size is 96 by 96
# The trap is in the center of the image, except for edge cases
# The output has shape (C, T, X, Y, Z), so in this example: (1, T, 96, 96, 5)
timelapse = seg_expt.get_trap_timelapse(trap_id, tile_size=tile_size,
channels=channels, z=z)
```
fpath = "h5/location"
This can take several seconds at the moment.
For a speed-up: take fewer z-positions if you can.
tile_id = 9
trange = range(0, 10)
ncols = 8
If you're not sure what indices to use:
```python
seg_expt.channels # Get a list of channels
channel = 'Brightfield'
ch_id = seg_expt.get_channel_index(channel)
riv = remoteImageViewer(fpath)
trap_tps = [riv.tiler.get_tiles_timepoint(tile_id, t) for t in trange]
n_traps = seg_expt.n_traps # Get the number of traps
```
#### Get the traps for a given time point
Alternatively, if you want to get all the traps at a given timepoint:
# You can also access labelled traps
m_ts = riv.get_labelled_trap(tile_id=0, tps=[0])
```python
timepoint = 0
seg_expt.get_traps_timepoints(timepoint, tile_size=96, channels=None,
z=[0,1,2,3,4])
```
## Reading MATLAB files
*Disclaimer: this is very much still in development so it may not always
work for you case. If you run into any problems please let me know, or even
better start an Issue on the project describing your problem.*
At the moment the best/only way to read matlab files is through a `matObject`:
```python
from aliby.io.matlab import matObject
cTimelapse = matObject('/path/to/cTimelapse.mat')
```
You can see an overview of what's in the object:
```python
cTimelapse.describe()
# And plot them directly
riv.plot_labelled_trap(trap_id=0, channels=[0, 1, 2, 3], trange=range(10))
```
The `matObject` has some dictionary-like features although it is *not* a
dictionary (yet). You can access different parts of the object using keys
, though, and can use the `keys()` function to do so. This will usually
work at the first few levels, but if it doesn't you may have run into an
object that's actually a list or a numpy array.
```python
cTimelapse.keys()
```
Depending on the network speed can take several seconds at the moment.
For a speed-up: take fewer z-positions if you can.
This should return an iterable of the upper level keys. For example, a
timelapse object will usually have a `timelapseTrapsOmero` key which you
can look deeper into in the same manner. Once you've found what you want
you can usually access it as you would a nested dictionary, for instance:
#### Get the tiles for a given time point
Alternatively, if you want to get all the traps at a given timepoint:
```python
cTimelapse['timelapseTrapsOmero']['cTimepoint']['trapLocations']
```
For more information about using MATLAB files in python objects, please see
[this page](docs/matlab.md).
## Development guidelines
In order to separate the python2, python3, and "currently working" versions
(\#socialdistancing) of the pipeline, please use the branches:
* python2.7: for any development on the 2 version
* python3.6-dev: for any added features for the python3 version
* master: very sparingly and only for changes that need to be made in both
versions as I will be merging changes from master into the development
branches frequently
* Ideally for adding features into any branch, espeically master, create
a new branch first, then create a pull request (from within Gitlab) before
merging it back so we can check each others' code. This is just to make
sure that we can always use the code that is in the master branch without
any issues.
Branching cheat-sheet:
```git
git branch my_branch # Create a new branch called branch_name from master
git branch my_branch another_branch #Branch from another_branch, not master
git checkout -b my_branch # Create my_branch and switch to it
# Merge changes from master into your branch
git pull #get any remote changes in master
git checkout my_branch
git merge master
# Merge changes from your branch into another branch
git checkout another_branch
git merge my_branch #check the doc for --no-ff option, you might want to use it
timepoint = (4,6)
tiler.get_tiles_timepoint(timepoint, channels=None,
z=[0,1,2,3,4])
```
## TODO
### Tests
* test full pipeline with OMERO experiment (no download.)
### Contributing
See [CONTRIBUTING](https://aliby.readthedocs.io/en/latest/INSTALL.html) on how to help out or get involved.
"""Core classes for the pipeline"""
import atexit
import itertools
import os
import abc
import glob
import json
import warnings
from getpass import getpass
from pathlib import Path
import re
import logging
from typing import Union
import h5py
from tqdm import tqdm
import pandas as pd
import omero
from omero.gateway import BlitzGateway
from logfile_parser import Parser
from agora.io.utils import accumulate
from aliby.timelapse import TimelapseOMERO, TimelapseLocal
from agora.io.metadata_parser import parse_logfiles
from agora.io.writer import Writer
logger = logging.getLogger(__name__)
########################### Dask objects ###################################
##################### ENVIRONMENT INITIALISATION ################
import omero
from omero.gateway import BlitzGateway, PixelsWrapper
from omero.model import enums as omero_enums
import numpy as np
# Set up the pixels so that we can reuse them across sessions (?)
PIXEL_TYPES = {
omero_enums.PixelsTypeint8: np.int8,
omero_enums.PixelsTypeuint8: np.uint8,
omero_enums.PixelsTypeint16: np.int16,
omero_enums.PixelsTypeuint16: np.uint16,
omero_enums.PixelsTypeint32: np.int32,
omero_enums.PixelsTypeuint32: np.uint32,
omero_enums.PixelsTypefloat: np.float32,
omero_enums.PixelsTypedouble: np.float64,
}
class NonCachedPixelsWrapper(PixelsWrapper):
"""Extend gateway.PixelWrapper to override _prepareRawPixelsStore."""
def _prepareRawPixelsStore(self):
"""
Creates RawPixelsStore and sets the id etc
This overrides the superclass behaviour to make sure that
we don't re-use RawPixelStore in multiple processes since
the Store may be closed in 1 process while still needed elsewhere.
This is needed when napari requests may planes simultaneously,
e.g. when switching to 3D view.
"""
ps = self._conn.c.sf.createRawPixelsStore()
ps.setPixelsId(self._obj.id.val, True, self._conn.SERVICE_OPTS)
return ps
omero.gateway.PixelsWrapper = NonCachedPixelsWrapper
# Update the BlitzGateway to use our NonCachedPixelsWrapper
omero.gateway.refreshWrappers()
###################### DATA ACCESS ###################
import dask.array as da
from dask import delayed
def get_data_lazy(image) -> da.Array:
"""Get 5D dask array, with delayed reading from OMERO image."""
nt, nc, nz, ny, nx = [getattr(image, f"getSize{x}")() for x in "TCZYX"]
pixels = image.getPrimaryPixels()
dtype = PIXEL_TYPES.get(pixels.getPixelsType().value, None)
get_plane = delayed(lambda idx: pixels.getPlane(*idx))
def get_lazy_plane(zct):
return da.from_delayed(get_plane(zct), shape=(ny, nx), dtype=dtype)
# 5D stack: TCZXY
t_stacks = []
for t in range(nt):
c_stacks = []
for c in range(nc):
z_stack = []
for z in range(nz):
z_stack.append(get_lazy_plane((z, c, t)))
c_stacks.append(da.stack(z_stack))
t_stacks.append(da.stack(c_stacks))
return da.stack(t_stacks)
class MetaData:
"""Small metadata Process that loads log."""
def __init__(self, log_dir, store):
self.log_dir = log_dir
self.store = store
self.metadata_writer = Writer(self.store)
def load_logs(self):
parsed_flattened = parse_logfiles(self.log_dir)
return parsed_flattened
def run(self):
metadata_dict = self.load_logs()
self.metadata_writer.write(path="/", meta=metadata_dict, overwrite=False)
def add_field(self, field_name, field_value):
self.metadata_writer.write(
path="/", meta={field_name: field_value}, overwrite=False
)
def add_fields(self, fields_values: dict):
for field, value in fields_values.items():
self.add_field(field, value)
########################### Old Objects ####################################
class Experiment(abc.ABC):
"""
Abstract base class for experiments.
Gives all the functions that need to be implemented in both the local
version and the Omero version of the Experiment class.
As this is an abstract class, experiments can not be directly instantiated
through the usual `__init__` function, but must be instantiated from a
source.
>>> expt = Experiment.from_source(root_directory)
Data from the current timelapse can be obtained from the experiment using
colon and comma separated slicing.
The order of data is C, T, X, Y, Z
C, T and Z can have any slice
X and Y will only consider the beginning and end as we want the images
to be continuous
>>> bf_1 = expt[0, 0, :, :, :] # First channel, first timepoint, all x,y,z
"""
__metaclass__ = abc.ABCMeta
# metadata_parser = AcqMetadataParser()
def __init__(self):
self.exptID = ""
self._current_position = None
self.position_to_process = 0
def __getitem__(self, item):
return self.current_position[item]
@property
def shape(self):
return self.current_position.shape
@staticmethod
def from_source(*args, **kwargs):
"""
Factory method to construct an instance of an Experiment subclass (
either ExperimentOMERO or ExperimentLocal).
:param source: Where the data is stored (OMERO server or directory
name)
:param kwargs: If OMERO server, `user` and `password` keyword
arguments are required. If the data is stored locally keyword
arguments are ignored.
"""
if len(args) > 1:
logger.debug("ExperimentOMERO: {}".format(args, kwargs))
return ExperimentOMERO(*args, **kwargs)
else:
logger.debug("ExperimentLocal: {}".format(args, kwargs))
return ExperimentLocal(*args, **kwargs)
@property
@abc.abstractmethod
def positions(self):
"""Returns list of available position names"""
return
@abc.abstractmethod
def get_position(self, position):
return
@property
def current_position(self):
return self._current_position
@property
def channels(self):
return self._current_position.channels
@current_position.setter
def current_position(self, position):
self._current_position = self.get_position(position)
def get_hypercube(self, x, y, z_positions, channels, timepoints):
return self.current_position.get_hypercube(
x, y, z_positions, channels, timepoints
)
# Todo: cache images like in ExperimentLocal
class ExperimentOMERO(Experiment):
"""
Experiment class to organise different timelapses.
Connected to a Dataset object which handles database I/O.
"""
def __init__(self, omero_id, host, port=4064, **kwargs):
super(ExperimentOMERO, self).__init__()
self.exptID = omero_id
# Get annotations
self.use_annotations = kwargs.get("use_annotations", True)
self._files = None
self._tags = None
# Create a connection
self.connection = BlitzGateway(
kwargs.get("username") or input("Username: "),
kwargs.get("password") or getpass("Password: "),
host=host,
port=port,
)
connected = self.connection.connect()
try:
assert connected is True, "Could not connect to server."
except AssertionError as e:
self.connection.close()
raise (e)
try: # Run everything that could cause the initialisation to fail
self.dataset = self.connection.getObject("Dataset", self.exptID)
self.name = self.dataset.getName()
# Create positions objects
self._positions = {
img.getName(): img.getId()
for img in sorted(
self.dataset.listChildren(), key=lambda x: x.getName()
)
}
# Set up local cache
self.root_dir = Path(kwargs.get("save_dir", "./")) / self.name
if not self.root_dir.exists():
self.root_dir.mkdir(parents=True)
self.compression = kwargs.get("compression", None)
self.image_cache = h5py.File(self.root_dir / "images.h5", "a")
# Set up the current position as the first in the list
self._current_position = self.get_position(self.positions[0])
self.running_tp = 0
except Exception as e:
# Close the connection!
print("Error in initialisation, closing connection.")
self.connection.close()
print(self.connection.isConnected())
raise e
atexit.register(self.close) # Close everything if program ends
def close(self):
print("Clean-up on exit.")
self.image_cache.close()
self.connection.close()
@property
def files(self):
if self._files is None:
self._files = {
x.getFileName(): x
for x in self.dataset.listAnnotations()
if isinstance(x, omero.gateway.FileAnnotationWrapper)
}
return self._files
@property
def tags(self):
if self._tags is None:
self._tags = {
x.getName(): x
for x in self.dataset.listAnnotations()
if isinstance(x, omero.gateway.TagAnnotationWrapper)
}
return self._tags
@property
def positions(self):
return list(self._positions.keys())
def _get_position_annotation(self, position):
# Get file annotations filtered by position name and ordered by
# creation date
r = re.compile(position)
wrappers = sorted(
[self.files[key] for key in filter(r.match, self.files)],
key=lambda x: x.creationEventDate(),
reverse=True,
)
# Choose newest file
if len(wrappers) < 1:
return None
else:
# Choose the newest annotation and cache it
annotation = wrappers[0]
filepath = self.root_dir / annotation.getFileName().replace("/", "_")
if not filepath.exists():
with open(str(filepath), "wb") as fd:
for chunk in annotation.getFileInChunks():
fd.write(chunk)
return filepath
def get_position(self, position):
"""Get a Timelapse object for a given position by name"""
# assert position in self.positions, "Position not available."
img = self.connection.getObject("Image", self._positions[position])
if self.use_annotations:
annotation = self._get_position_annotation(position)
else:
annotation = None
return TimelapseOMERO(img, annotation, self.image_cache)
def cache_locally(
self,
root_dir="./",
positions=None,
channels=None,
timepoints=None,
z_positions=None,
):
"""
Save the experiment locally.
:param root_dir: The directory in which the experiment will be
saved. The experiment will be a subdirectory of "root_directory"
and will be named by its id.
"""
logger.warning("Saving experiment {}; may take some time.".format(self.name))
if positions is None:
positions = self.positions
if channels is None:
channels = self.current_position.channels
if timepoints is None:
timepoints = range(self.current_position.size_t)
if z_positions is None:
z_positions = range(self.current_position.size_z)
save_dir = Path(root_dir) / self.name
if not save_dir.exists():
save_dir.mkdir()
# Save the images
for pos_name in tqdm(positions):
pos = self.get_position(pos_name)
pos_dir = save_dir / pos_name
if not pos_dir.exists():
pos_dir.mkdir()
self.cache_set(pos, range(pos.size_t))
self.cache_logs(save_dir)
# Save the file annotations
cache_config = dict(
positions=positions,
channels=channels,
timepoints=timepoints,
z_positions=z_positions,
)
with open(str(save_dir / "cache.config"), "w") as fd:
json.dump(cache_config, fd)
logger.info("Downloaded experiment {}".format(self.exptID))
def cache_logs(self, **kwargs):
# Save the file annotations
tags = dict() # and the tag annotations
for annotation in self.dataset.listAnnotations():
if isinstance(annotation, omero.gateway.FileAnnotationWrapper):
filepath = self.root_dir / annotation.getFileName().replace("/", "_")
if str(filepath).endswith("txt") and not filepath.exists():
# Save only the text files
with open(str(filepath), "wb") as fd:
for chunk in annotation.getFileInChunks():
fd.write(chunk)
if isinstance(annotation, omero.gateway.TagAnnotationWrapper):
key = annotation.getDescription()
if key == "":
key = "misc. tags"
if key in tags:
if not isinstance(tags[key], list):
tags[key] = [tags[key]]
tags[key].append(annotation.getValue())
else:
tags[key] = annotation.getValue()
with open(str(self.root_dir / "omero_tags.json"), "w") as fd:
json.dump(tags, fd)
return
def run(self, keys: Union[list, int], store, **kwargs):
if self.running_tp == 0:
self.cache_logs(**kwargs)
self.running_tp = 1 # Todo rename based on annotations
run_tps = dict()
for pos, tps in accumulate(keys):
position = self.get_position(pos)
run_tps[pos] = position.run(tps, store, save_dir=self.root_dir)
# Update the keys to match what was actually run
keys = [(pos, tp) for pos in run_tps for tp in run_tps[pos]]
return keys
class ExperimentLocal(Experiment):
def __init__(self, root_dir, finished=True):
super(ExperimentLocal, self).__init__()
self.root_dir = Path(root_dir)
self.exptID = self.root_dir.name
self._pos_mapper = dict()
# Fixme: Made the assumption that the Acq file gets saved before the
# experiment is run and that the information in that file is
# trustworthy.
acq_file = self._find_acq_file()
acq_parser = Parser("multiDGUI_acq_format")
with open(acq_file, "r") as fd:
metadata = acq_parser.parse(fd)
self.metadata = metadata
self.metadata["finished"] = finished
self.files = [f for f in self.root_dir.iterdir() if f.is_file()]
self.image_cache = h5py.File(self.root_dir / "images.h5", "a")
if self.finished:
cache = self._find_cache()
# log = self._find_log() # Todo: add log metadata
if cache is not None:
with open(cache, "r") as fd:
cache_config = json.load(fd)
self.metadata.update(**cache_config)
self._current_position = self.get_position(self.positions[0])
def _find_file(self, regex):
file = glob.glob(os.path.join(str(self.root_dir), regex))
if len(file) != 1:
return None
else:
return file[0]
def _find_acq_file(self):
file = self._find_file("*[Aa]cq.txt")
if file is None:
raise ValueError(
"Cannot load this experiment. There are either "
"too many or too few acq files."
)
return file
def _find_cache(self):
return self._find_file("cache.config")
@property
def finished(self):
return self.metadata["finished"]
@property
def running(self):
return not self.metadata["finished"]
@property
def positions(self):
return self.metadata["positions"]["posname"]
def _get_position_annotation(self, position):
r = re.compile(position)
files = list(filter(lambda x: r.match(x.stem), self.files))
if len(files) == 0:
return None
files = sorted(files, key=lambda x: x.lstat().st_ctime, reverse=True)
# Get the newest and return as string
return files[0]
def get_position(self, position):
if position not in self._pos_mapper:
annotation = self._get_position_annotation(position)
self._pos_mapper[position] = TimelapseLocal(
position,
self.root_dir,
finished=self.finished,
annotation=annotation,
cache=self.image_cache,
)
return self._pos_mapper[position]
def run(self, keys, store, **kwargs):
"""
:param keys: List of (position, time point) tuples to process.
:return:
"""
run_tps = dict()
for pos, tps in accumulate(keys):
run_tps[pos] = self.get_position(pos).run(tps, store)
# Update the keys to match what was actually run
keys = [(pos, tp) for pos in run_tps for tp in run_tps[pos]]
return keys
"""
A module to extract data from a processed experiment.
"""
import h5py
import numpy as np
from tqdm import tqdm
from core.io.matlab import matObject
from growth_rate.estimate_gr import estimate_gr
class Extracted:
# TODO write the filtering functions.
def __init__(self):
self.volume = None
self._keep = None
def filter(self, filename=None, **kwargs):
"""
1. Filter out small non-growing tracks. This means:
a. the cell size never reaches beyond a certain size-threshold
volume_thresh or
b. the cell's volume doesn't increase by at least a minimum
amount over its lifetime
2. Join daughter tracks that are contiguous and within a volume
threshold of each other
3. Discard tracks that are shorter than a threshold number of
timepoints
This function is used to fix tracking/bud errors in post-processing.
The parameters define the thresholds used to determine which cells are
discarded.
FIXME Ideally we get to a point where this is no longer needed.
:return:
"""
#self.join_tracks()
filter_out = self.filter_size(**kwargs)
filter_out += self.filter_lifespan(**kwargs)
# TODO save data or just filtering parameters?
#self.to_hdf(filename)
self.keep = ~filter_out
def filter_size(self, volume_thresh=7, growth_thresh=10, **kwargs):
"""Filter out small and non-growing cells.
:param volume_thresh: Size threshold for small cells
:param growth_thresh: Size difference threshold for non-growing cells
"""
filter_out = np.where(np.max(self.volume, axis=1) < volume_thresh,
True, False)
growth = [v[v > 0] for v in self.volume]
growth = np.array([v[-1] - v[0] if len(v) > 0 else 0 for v in growth])
filter_out += np.where(growth < growth_thresh, True, False)
return filter_out
def filter_lifespan(self, min_time=5, **kwargs):
"""Remove daughter cells that have a small life span.
:param min_time: The minimum life span, under which cells are removed.
"""
# TODO What if there are nan values?
filter_out = np.where(np.count_nonzero(self.volume, axis=1) <
min_time, True, False)
return filter_out
def join_tracks(self, threshold=7):
""" Join contiguous tracks that are within a certain volume
threshold of each other.
:param threshold: Maximum volume difference to join contiguous tracks.
:return:
"""
# For all pairs of cells
#
pass
class ExtractedHDF(Extracted):
# TODO pull all the data out of the HFile and filter!
def __init__(self, file):
# We consider the data to be read-only
self.hfile = h5py.File(file, 'r')
class ExtractedMat(Extracted):
""" Pulls the extracted data out of the MATLAB cTimelapse file.
This is mostly a convenience function in order to run the
gaussian-processes growth-rate estimation
"""
def __init__(self, file, debug=False):
ct = matObject(file)
self.debug = debug
# Pre-computed data
# TODO what if there is no timelapseTrapsOmero?
self.metadata = ct['timelapseTrapsOmero']['metadata']
self.extracted_data = ct['timelapseTrapsOmero']['extractedData']
self.channels = ct['timelapseTrapsOmero']['extractionParameters'][
'functionParameters']['channels'].tolist()
self.time_settings = ct['timelapseTrapsOmero']['metadata']['acq'][
'times']
# Get filtering information
n_cells = self.extracted_data['cellNum'][0].shape
self.keep = np.full(n_cells, True)
# Not yet computed data
self._growth_rate = None
self._daughter_index = None
def get_channel_index(self, channel):
"""Get index of channel based on name. This only considers
fluorescence channels."""
return self.channels.index(channel)
@property
def trap_num(self):
return self.extracted_data['trapNum'][0][self.keep]
@property
def cell_num(self):
return self.extracted_data['cellNum'][0][self.keep]
def identity(self, cell_idx):
"""Get the (position), trap, and cell label given a cell's global
index."""
# Todo include position when using full strain
trap = self.trap_num[cell_idx]
cell = self.cell_num[cell_idx]
return trap, cell
def global_index(self, trap_id, cell_label):
"""Get the global index of a cell given it's trap/cellNum
combination."""
candidates = np.where(np.logical_and(
(self.trap_num == trap_id), # +1?
(self.cell_num == cell_label)
))[0]
# TODO raise error if number of candidates != 1
if len(candidates) == 1:
return candidates[0]
elif len(candidates) == 0:
return -1
else:
raise(IndexError("No such cell/trap combination"))
@property
def daughter_label(self):
"""Returns the cell label of the daughters of each cell over the
timelapse.
0 corresponds to no daughter. This *not* the index of the daughter
cell within the data. To get this, use daughter_index.
"""
return self.extracted_data['daughterLabel'][0][self.keep]
def _single_daughter_idx(self, mother_idx, daughter_labels):
trap_id, _ = self.identity(mother_idx)
daughter_index = [self.global_index(trap_id, cell_label) for
cell_label
in daughter_labels]
return daughter_index
@property
def daughter_index(self):
"""Returns the global index of the daughters of each cell.
This is different from the daughter label because it corresponds to
the index of the daughter when counting all of the cells. This can
be used to index within the data arrays.
"""
if self._daughter_index is None:
daughter_index = [self._single_daughter_idx(i, daughter_labels)
for i, daughter_labels in enumerate(
self.daughter_label)]
self._daughter_index = np.array(daughter_index)
return self._daughter_index
@property
def births(self):
return np.array(self.extracted_data['births'][0].todense())[self.keep]
@property
def volume(self):
"""Get the volume of all of the cells"""
return np.array(self.extracted_data['volume'][0].todense())[self.keep]
def _gr_estimation(self):
dt = self.time_settings['interval'] / 360 # s to h conversion
results = []
for v in tqdm(self.volume):
results.append(estimate_gr(v, dt))
merged = {k: np.stack([x[k] for x in results]) for k in results[0]}
self._gr_results = merged
return
@property
def growth_rate(self):
"""Get the growth rate for all cells.
Note that this uses the gaussian processes method of estimating
growth rate by default. If there is no growth rate in the given file
(usually the case for MATLAB), it needs to run estimation first.
This can take a while.
"""
# TODO cache the results of growth rate estimation.
if self._gr_results is None:
dt = self.time_settings['interval'] / 360 # s to h conversion
self._growth_rate = [estimate_gr(v, dt) for v in self.volume]
return self._gr_results['growth_rate']
def _fluo_attribute(self, channel, attribute):
channel_id = self.get_channel_index(channel)
res = np.array(self.extracted_data[attribute][channel_id].todense())
return res[self.keep]
def protein_localisation(self, channel, method='nucEstConv'):
"""Returns protein localisation data for a given channel.
Uses the 'nucEstConv' by default. Alternatives are 'smallPeakConv',
'max5px', 'max2p5pc'
"""
return self._fluo_attribute(channel, method)
def background_fluo(self, channel):
return self._fluo_attribute(channel, 'imBackground')
def mean(self, channel):
return self._fluo_attribute(channel, 'mean')
def median(self, channel):
return self._fluo_attribute(channel, 'median')
def filter(self, filename=None):
"""Filters and saves results to and HDF5 file.
This is necessary because we cannot write to the MATLAB file,
so the results of the filter cannot be saved in the object.
"""
super().filter(filename=filename)
self._growth_rate = None # reset growth rate so it is recomputed
def to_hdf(self, filename):
"""Store the current results, including any filtering done, to a file.
TODO Should we save filtered results or just re-do?
:param filename:
:return:
"""
store = h5py.File(filename, 'w')
try:
# Store (some of the) metadata
for meta in ['experiment', 'username', 'microscope',
'comments', 'project', 'date', 'posname',
'exptid']:
store.attrs[meta] = self.metadata[meta]
# TODO store timing information?
store.attrs['time_interval'] = self.time_settings['interval']
store.attrs['timepoints'] = self.time_settings['ntimepoints']
store.attrs['total_duration'] = self.time_settings['totalduration']
# Store volume, births, daughterLabel, trapNum, cellNum
for key in ['volume', 'births', 'daughter_label', 'trap_num',
'cell_num']:
store[key] = getattr(self, key)
# Store growth rate results
if self._gr_results:
grp = store.create_group('gaussian_process')
for key, val in self._gr_results.items():
grp[key] = val
for channel in self.channels:
# Create a group for each channel
grp = store.create_group(channel)
# Store protein_localisation, background fluorescence, mean, median
# for each channel
grp['protein_localisation'] = self.protein_localisation(channel)
grp['background_fluo'] = self.background_fluo(channel)
grp['mean'] = self.mean(channel)
grp['median'] = self.median(channel)
finally:
store.close()
"""Read and convert MATLAB files from Swain Lab platform.
TODO: Information that I need from lab members esp J and A
* Lots of examples to try
* Any ideas on what these Map objects are?
TODO: Update Swain Lab wiki
All credit to Matt Bauman for
the reverse engineering at https://nbviewer.jupyter.org/gist/mbauman/9121961
"""
import re
import struct
import sys
from collections import Iterable
from io import BytesIO
import h5py
import numpy as np
import pandas as pd
import scipy
from numpy.compat import asstr
# TODO only use this if scipy>=1.6 or so
from scipy.io import matlab
from scipy.io.matlab.mio5 import MatFile5Reader
from scipy.io.matlab.mio5_params import mat_struct
from aliby.io.utils import read_int, read_string, read_delim
def read_minimat_vars(rdr):
rdr.initialize_read()
mdict = {"__globals__": []}
i = 0
while not rdr.end_of_stream():
hdr, next_position = rdr.read_var_header()
name = asstr(hdr.name)
if name == "":
name = "var_%d" % i
i += 1
res = rdr.read_var_array(hdr, process=False)
rdr.mat_stream.seek(next_position)
mdict[name] = res
if hdr.is_global:
mdict["__globals__"].append(name)
return mdict
def read_workspace_vars(fname):
fp = open(fname, "rb")
rdr = MatFile5Reader(fp, struct_as_record=True, squeeze_me=True)
vars = rdr.get_variables()
fws = vars["__function_workspace__"]
ws_bs = BytesIO(fws.tostring())
ws_bs.seek(2)
rdr.mat_stream = ws_bs
# Guess byte order.
mi = rdr.mat_stream.read(2)
rdr.byte_order = mi == b"IM" and "<" or ">"
rdr.mat_stream.read(4) # presumably byte padding
mdict = read_minimat_vars(rdr)
fp.close()
return mdict
class matObject:
"""A python read-out of MATLAB objects
The objects pulled out of the
"""
def __init__(self, filepath):
self.filepath = filepath # For record
self.classname = None
self.object_name = None
self.buffer = None
self.version = None
self.names = None
self.segments = None
self.heap = None
self.attrs = dict()
self._init_buffer()
self._init_heap()
self._read_header()
self.parse_file()
def __getitem__(self, item):
return self.attrs[item]
def keys(self):
"""Returns the names of the available properties"""
return self.attrs.keys()
def get(self, item, default=None):
return self.attrs.get(item, default)
def _init_buffer(self):
fp = open(self.filepath, "rb")
rdr = MatFile5Reader(fp, struct_as_record=True, squeeze_me=True)
vars = rdr.get_variables()
self.classname = vars["None"]["s2"][0].decode("utf-8")
self.object_name = vars["None"]["s0"][0].decode("utf-8")
fws = vars["__function_workspace__"]
self.buffer = BytesIO(fws.tostring())
fp.close()
def _init_heap(self):
super_data = read_workspace_vars(self.filepath)
elem = super_data["var_0"][0, 0]
if isinstance(elem, mat_struct):
self.heap = elem.MCOS[0]["arr"]
else:
self.heap = elem["MCOS"][0]["arr"]
def _read_header(self):
self.buffer.seek(248) # the start of the header
version = read_int(self.buffer)
n_str = read_int(self.buffer)
offsets = read_int(self.buffer, n=6)
# check that the next two are zeros
reserved = read_int(self.buffer, n=2)
assert all(
[x == 0 for x in reserved]
), "Non-zero reserved header fields: {}".format(reserved)
# check that we are at the right place
assert self.buffer.tell() == 288, "String elemnts begin at 288"
hdrs = []
for i in range(n_str):
hdrs.append(read_string(self.buffer))
self.names = hdrs
self.version = version
# The offsets are actually STARTING FROM 248 as well
self.segments = [x + 248 for x in offsets] # list(offsets)
return
def parse_file(self):
# Get class attributes from segment 1
self.buffer.seek(self.segments[0])
classes = self._parse_class_attributes(self.segments[1])
# Get first set of properties from segment 2
self.buffer.seek(self.segments[1])
props1 = self._parse_properties(self.segments[2])
# Get the property description from segment 3
self.buffer.seek(self.segments[2])
object_info = self._parse_prop_description(classes, self.segments[3])
# Get more properties from segment 4
self.buffer.seek(self.segments[3])
props2 = self._parse_properties(self.segments[4])
# Check that the last segment is empty
self.buffer.seek(self.segments[4])
seg5_length = (self.segments[5] - self.segments[4]) // 8
read_delim(self.buffer, seg5_length)
props = (props1, props2)
self._to_attrs(object_info, props)
def _to_attrs(self, object_info, props):
"""Re-organise the various classes and subclasses into a nested
dictionary.
:return:
"""
for pkg_clss, indices, idx in object_info:
pkg, clss = pkg_clss
idx = max(indices)
which = indices.index(idx)
obj = flatten_obj(props[which][idx])
subdict = self.attrs
if pkg != "":
subdict = self.attrs.setdefault(pkg, {})
if clss in subdict:
if isinstance(subdict[clss], list):
subdict[clss].append(obj)
else:
subdict[clss] = [subdict[clss]]
subdict[clss].append(obj)
else:
subdict[clss] = obj
def describe(self):
describe(self.attrs)
def _parse_class_attributes(self, section_end):
"""Read the Class attributes = the first segment"""
read_delim(self.buffer, 4)
classes = []
while self.buffer.tell() < section_end:
package_index = read_int(self.buffer) - 1
package = self.names[package_index] if package_index > 0 else ""
name_idx = read_int(self.buffer) - 1
name = self.names[name_idx] if name_idx > 0 else ""
classes.append((package, name))
read_delim(self.buffer, 2)
return classes
def _parse_prop_description(self, classes, section_end):
"""Parse the description of each property = the third segment"""
read_delim(self.buffer, 6)
object_info = []
while self.buffer.tell() < section_end:
class_idx = read_int(self.buffer) - 1
class_type = classes[class_idx]
read_delim(self.buffer, 2)
indices = [x - 1 for x in read_int(self.buffer, 2)]
obj_id = read_int(self.buffer)
object_info.append((class_type, indices, obj_id))
return object_info
def _parse_properties(self, section_end):
"""
Parse the actual values of the attributes == segments 2 and 4
"""
read_delim(self.buffer, 2)
props = []
while self.buffer.tell() < section_end:
n_props = read_int(self.buffer)
d = parse_prop(n_props, self.buffer, self.names, self.heap)
if not d: # Empty dictionary
break
props.append(d)
# Move to next 8-byte aligned offset
self.buffer.seek(self.buffer.tell() + self.buffer.tell() % 8)
return props
def to_hdf(self, filename):
f = h5py.File(filename, mode="w")
save_to_hdf(f, "/", self.attrs)
def describe(d, indent=0, width=4, out=None):
for key, value in d.items():
print(f'{"": <{width * indent}}' + str(key), file=out)
if isinstance(value, dict):
describe(value, indent + 1, out=out)
elif isinstance(value, np.ndarray):
print(
f'{"": <{width * (indent + 1)}} {value.shape} array '
f"of type {value.dtype}",
file=out,
)
elif isinstance(value, scipy.sparse.csc.csc_matrix):
print(
f'{"": <{width * (indent + 1)}} {value.shape} '
f"sparse matrix of type {value.dtype}",
file=out,
)
elif isinstance(value, Iterable) and not isinstance(value, str):
print(
f'{"": <{width * (indent + 1)}} {type(value)} of len ' f"{len(value)}",
file=out,
)
else:
print(f'{"": <{width * (indent + 1)}} {value}', file=out)
def parse_prop(n_props, buff, names, heap):
d = dict()
for i in range(n_props):
name_idx, flag, heap_idx = read_int(buff, 3)
if flag not in [0, 1, 2] and name_idx == 0:
n_props = flag
buff.seek(buff.tell() - 1) # go back on one byte
d = parse_prop(n_props, buff, names, heap)
else:
item_name = names[name_idx - 1]
if flag == 0:
d[item_name] = names[heap_idx]
elif flag == 1:
d[item_name] = heap[heap_idx + 2] # Todo: what is the heap?
elif flag == 2:
assert 0 <= heap_idx <= 1, (
"Boolean flag has a value other " "than 0 or 1 "
)
d[item_name] = bool(heap_idx)
else:
raise ValueError(
"unknown flag {} for property {} with heap "
"index {}".format(flag, item_name, heap_idx)
)
return d
def is_object(x):
"""Checking object dtype for structured numpy arrays"""
if x.dtype.names is not None and len(x.dtype.names) > 1: # Complex obj
return all(x.dtype[ix] == np.object for ix in range(len(x.dtype)))
else: # simple object
return x.dtype == np.object
def flatten_obj(arr):
# TODO turn structured arrays into nested dicts of lists rather that
# lists of dicts
if isinstance(arr, np.ndarray):
if arr.dtype.names:
arrdict = dict()
for fieldname in arr.dtype.names:
arrdict[fieldname] = flatten_obj(arr[fieldname])
arr = arrdict
elif arr.dtype == np.object and arr.ndim == 0:
arr = flatten_obj(arr[()])
elif arr.dtype == np.object and arr.ndim > 0:
try:
arr = np.stack(arr)
if arr.dtype.names:
d = {k: flatten_obj(arr[k]) for k in arr.dtype.names}
arr = d
except:
arr = [flatten_obj(x) for x in arr.tolist()]
elif isinstance(arr, dict):
arr = {k: flatten_obj(v) for k, v in arr.items()}
elif isinstance(arr, list):
try:
arr = flatten_obj(np.stack(arr))
except:
arr = [flatten_obj(x) for x in arr]
return arr
def save_to_hdf(h5file, path, dic):
"""
Saving a MATLAB object to HDF5
"""
if isinstance(dic, list):
dic = {str(i): v for i, v in enumerate(dic)}
for key, item in dic.items():
if isinstance(item, (int, float, str)):
h5file[path].attrs.create(key, item)
elif isinstance(item, list):
if len(item) == 0 and path + key not in h5file: # empty list empty group
h5file.create_group(path + key)
if all(isinstance(x, (int, float, str)) for x in item):
if path not in h5file:
h5file.create_group(path)
h5file[path].attrs.create(key, item)
else:
if path + key not in h5file:
h5file.create_group(path + key)
save_to_hdf(
h5file, path + key + "/", {str(i): x for i, x in enumerate(item)}
)
elif isinstance(item, scipy.sparse.csc.csc_matrix):
try:
h5file.create_dataset(
path + key, data=item.todense(), compression="gzip"
)
except Exception as e:
print(path + key)
raise e
elif isinstance(item, (np.ndarray, np.int64, np.float64)):
if item.dtype == np.dtype("<U1"): # Strings to 'S' type for HDF5
item = item.astype("S")
try:
h5file.create_dataset(path + key, data=item, compression="gzip")
except Exception as e:
print(path + key)
raise e
elif isinstance(item, dict):
if path + key not in h5file:
h5file.create_group(path + key)
save_to_hdf(h5file, path + key + "/", item)
elif item is None:
continue
else:
raise ValueError(f"Cannot save {type(item)} type at key {path + key}")
## NOT YET FULLY IMPLEMENTED!
class _Info:
def __init__(self, info):
self.info = info
self._identity = None
def __getitem__(self, item):
val = self.info[item]
if val.shape[0] == 1:
val = val[0]
if 0 in val[1].shape:
val = val[0]
if isinstance(val, scipy.sparse.csc.csc_matrix):
return np.asarray(val.todense())
if val.dtype == np.dtype("O"):
# 3d "sparse matrix"
if all(isinstance(x, scipy.sparse.csc.csc_matrix) for x in val):
val = np.array([x.todense() for x in val])
# TODO: The actual object data
equality = val[0] == val[1]
if isinstance(equality, scipy.sparse.csc.csc_matrix):
equality = equality.todense()
if equality.all():
val = val[0]
return np.squeeze(val)
@property
def categories(self):
return self.info.dtype.names
class TrapInfo(_Info):
def __init__(self, info):
"""
The information on all of the traps in a given position.
:param info: The TrapInfo structure, can be found in the heap of
the CTimelapse at index 7
"""
super().__init__(info)
class CellInfo(_Info):
def __init__(self, info):
"""
The extracted information of all cells in a given position.
:param info: The CellInfo structure, can be found in the heap
of the CTimelapse at index 15.
"""
super().__init__(info)
@property
def identity(self):
if self._identity is None:
self._identity = pd.DataFrame(
zip(self["trapNum"], self["cellNum"]), columns=["trapNum", "cellNum"]
)
return self._identity
def index(self, trapNum, cellNum):
query = "trapNum=={} and cellNum=={}".format(trapNum, cellNum)
try:
result = self.identity.query(query).index[0]
except Exception as e:
print(query)
raise e
return result
@property
def nucEstConv1(self):
return np.asarray(self.info["nuc_est_conv"][0][0].todense())
@property
def nucEstConv2(self):
return np.asarray(self.info["nuc_est_conv"][0][1].todense())
@property
def mothers(self):
return np.where((self["births"] != 0).any(axis=1))[0]
def daughters(self, mother_index):
"""
Get daughters of cell with index `mother_index`.
:param mother_index: the index of the mother within the data. This is
different from the mother's cell/trap identity.
"""
daughter_ids = np.unique(self["daughterLabel"][mother_index]).tolist()
daughter_ids.remove(0)
mother_trap = self.identity["trapNum"].loc[mother_index]
daughters = [self.index(mother_trap, cellNum) for cellNum in daughter_ids]
return daughters
def _todict(matobj):
"""
A recursive function which constructs from matobjects nested dictionaries
"""
if not hasattr(matobj, "_fieldnames"):
return matobj
d = {}
for strg in matobj._fieldnames:
elem = matobj.__dict__[strg]
if isinstance(elem, matlab.mio5_params.mat_struct):
d[strg] = _todict(elem)
elif isinstance(elem, np.ndarray):
d[strg] = _toarray(elem)
else:
d[strg] = elem
return d
def _toarray(ndarray):
"""
A recursive function which constructs ndarray from cellarrays
(which are loaded as numpy ndarrays), recursing into the elements
if they contain matobjects.
"""
if ndarray.dtype != "float64":
elem_list = []
for sub_elem in ndarray:
if isinstance(sub_elem, matlab.mio5_params.mat_struct):
elem_list.append(_todict(sub_elem))
elif isinstance(sub_elem, np.ndarray):
elem_list.append(_toarray(sub_elem))
else:
elem_list.append(sub_elem)
return np.array(elem_list)
else:
return ndarray
from pathlib import Path
class Strain:
"""The cell info for all the positions of a strain."""
def __init__(self, origin, strain):
self.origin = Path(origin)
self.files = [x for x in origin.iterdir() if strain in str(x)]
self.cts = [matObject(x) for x in self.files]
self.cinfos = [CellInfo(x.heap[15]) for x in self.cts]
self._identity = None
def __getitem__(self, item):
try:
return np.concatenate([c[item] for c in self.cinfos])
except ValueError: # If first axis is the channel
return np.concatenate([c[item] for c in self.cinfos], axis=1)
@property
def categories(self):
return set.union(*[set(c.categories) for c in self.cinfos])
@property
def identity(self):
if self._identity is None:
identities = []
for pos_id, cinfo in enumerate(self.cinfos):
identity = cinfo.identity
identity["position"] = pos_id
identities.append(identity)
self._identity = pd.concat(identities, ignore_index=True)
return self._identity
def index(self, posNum, trapNum, cellNum):
query = "position=={} and trapNum=={} and cellNum=={}".format(
posNum, trapNum, cellNum
)
try:
result = self.identity.query(query).index[0]
except Exception as e:
raise e
return result
@property
def mothers(self):
# At least two births are needed to be considered a mother cell
return np.where(np.count_nonzero(self["births"], axis=1) > 3)[0]
def daughters(self, mother_index):
"""
Get daughters of cell with index `mother_index`.
:param mother_index: the index of the mother within the data. This is
different from the mother's pos/trap/cell identity.
"""
daughter_ids = np.unique(self["daughterLabel"][mother_index]).tolist()
if 0 in daughter_ids:
daughter_ids.remove(0)
mother_pos_trap = self.identity[["position", "trapNum"]].loc[mother_index]
daughters = []
for cellNum in daughter_ids:
try:
daughters.append(self.index(*mother_pos_trap, cellNum))
except IndexError:
continue
return daughters
import h5py
import omero
from omero.gateway import BlitzGateway
from aliby.experiment import get_data_lazy
from agora.io.cells import CellsHDF
class Argo:
# TODO use the one in extraction?
def __init__(
self, host="islay.bio.ed.ac.uk", username="upload", password="***REMOVED***"
):
self.conn = None
self.host = host
self.username = username
self.password = password
def get_meta(self):
pass
def __enter__(self):
self.conn = BlitzGateway(
host=self.host, username=self.username, passwd=self.password
)
self.conn.connect()
return self
def __exit__(self, *exc):
self.conn.close()
return False
class Dataset(Argo):
def __init__(self, expt_id, **server_info):
super().__init__(**server_info)
self.expt_id = expt_id
self._files = None
@property
def dataset(self):
return self.conn.getObject("Dataset", self.expt_id)
@property
def name(self):
return self.dataset.getName()
@property
def date(self):
return self.dataset.getDate()
@property
def unique_name(self):
return "_".join((self.date.strftime("%Y_%m_%d").replace("/", "_"), self.name))
def get_images(self):
return {im.getName(): im.getId() for im in self.dataset.listChildren()}
@property
def files(self):
if self._files is None:
self._files = {
x.getFileName(): x
for x in self.dataset.listAnnotations()
if isinstance(x, omero.gateway.FileAnnotationWrapper)
}
if not len(self._files):
raise Exception("Exception:Metadata: Experiment has no annotation files.")
return self._files
@property
def tags(self):
if self._tags is None:
self._tags = {
x.getName(): x
for x in self.dataset.listAnnotations()
if isinstance(x, omero.gateway.TagAnnotationWrapper)
}
return self._tags
def cache_logs(self, root_dir):
for name, annotation in self.files.items():
filepath = root_dir / annotation.getFileName().replace("/", "_")
if str(filepath).endswith("txt") and not filepath.exists():
# Save only the text files
with open(str(filepath), "wb") as fd:
for chunk in annotation.getFileInChunks():
fd.write(chunk)
return True
class Image(Argo):
def __init__(self, image_id, **server_info):
super().__init__(**server_info)
self.image_id = image_id
self._image_wrap = None
@property
def image_wrap(self):
# TODO check that it is alive/ connected
if self._image_wrap is None:
self._image_wrap = self.conn.getObject("Image", self.image_id)
return self._image_wrap
@property
def name(self):
return self.image_wrap.getName()
@property
def data(self):
return get_data_lazy(self.image_wrap)
@property
def metadata(self):
meta = dict()
meta["size_x"] = self.image_wrap.getSizeX()
meta["size_y"] = self.image_wrap.getSizeY()
meta["size_z"] = self.image_wrap.getSizeZ()
meta["size_c"] = self.image_wrap.getSizeC()
meta["size_t"] = self.image_wrap.getSizeT()
meta["channels"] = self.image_wrap.getChannelLabels()
meta["name"] = self.image_wrap.getName()
return meta
class Cells(CellsHDF):
def __init__(self, filename):
file = h5py.File(filename, "r")
super().__init__(file)
def __enter__(self):
return self
def __exit__(self, *exc):
self.close
return False
import re
import struct
def clean_ascii(text):
return re.sub(r'[^\x20-\x7F]', '.', text)
def xxd(x, start=0, stop=None):
if stop is None:
stop = len(x)
for i in range(start, stop, 8):
# Row number
print("%04d" % i, end=" ")
# Hexadecimal bytes
for r in range(i, i + 8):
print("%02x" % x[r], end="")
if (r + 1) % 4 == 0:
print(" ", end="")
# ASCII
print(" ", clean_ascii(x[i:i + 8].decode('utf-8', errors='ignore')),
" ", end="")
# Int32
print('{:>10} {:>10}'.format(*struct.unpack('II', x[i: i + 8])),
end=" ")
print("") # Newline
return
# Buffer reading functions
def read_int(buffer, n=1):
res = struct.unpack('I' * n, buffer.read(4 * n))
if n == 1:
res = res[0]
return res
def read_string(buffer):
return ''.join([x.decode() for x in iter(lambda: buffer.read(1), b'\x00')])
def read_delim(buffer, n):
delim = read_int(buffer, n)
assert all([x == 0 for x in delim]), "Unknown nonzero value in delimiter"
from pathos.multiprocessing import Pool
from aliby.pipeline import PipelineParameters, Pipeline
class MultiExp:
"""
Manages cases when you need to segment several different experiments with a single
position (e.g. pH calibration).
"""
def __init__(self, expt_ids, npools=8, *args, **kwargs):
self.expt_ids = expt_ids
def run(self):
run_expt = lambda expt: Pipeline(
PipelineParameters.default(general={"expt_id": expt, "distributed": 0})
).run()
with Pool(npools) as p:
results = p.map(lambda x: self.create_pipeline(x), self.exp_ids)
@classmethod
def default(self):
return cls(expt_ids=list(range(20448, 20467 + 1)))
"""
Pipeline and chaining elements.
"""
import logging
import os
from abc import ABC, abstractmethod
from typing import List
from pathlib import Path
import traceback
from itertools import groupby
import re
import h5py
import yaml
from tqdm import tqdm
from time import perf_counter
from pathos.multiprocessing import Pool
import numpy as np
import pandas as pd
from scipy import ndimage
from aliby.experiment import MetaData
from aliby.haystack import initialise_tf
from aliby.baby_client import BabyRunner, BabyParameters
from aliby.tile.tiler import Tiler, TilerParameters
from aliby.io.omero import Dataset, Image
from agora.abc import ParametersABC, ProcessABC
from agora.io.writer import TilerWriter, BabyWriter, StateWriter
from agora.io.reader import StateReader
from agora.io.signal import Signal
from extraction.core.extractor import Extractor, ExtractorParameters
from extraction.core.functions.defaults import exparams_from_meta
from postprocessor.core.processor import PostProcessor, PostProcessorParameters
from postprocessor.compiler import ExperimentCompiler, PageOrganiser
logging.basicConfig(
filename="aliby.log",
filemode="w",
format="%(name)s - %(levelname)s - %(message)s",
level=logging.DEBUG,
)
class PipelineParameters(ParametersABC):
def __init__(
self, general, tiler, baby, extraction, postprocessing, reporting=None
):
self.general = general
self.tiler = tiler
self.baby = baby
self.extraction = extraction
self.postprocessing = postprocessing
self.reporting = reporting
@classmethod
def default(
cls,
general={},
tiler={},
baby={},
extraction={},
postprocessing={},
reporting={},
):
"""
Load unit test experiment
:expt_id: Experiment id
:directory: Output directory
Provides default parameters for the entire pipeline. This downloads the logfiles and sets the default
timepoints and extraction parameters from there.
"""
expt_id = general.get("expt_id", 19993)
directory = Path(general.get("directory", "../data"))
with Dataset(int(expt_id), **general.get("server_info")) as conn:
directory = directory / conn.unique_name
if not directory.exists():
directory.mkdir(parents=True)
# Download logs to use for metadata
conn.cache_logs(directory)
meta = MetaData(directory, None).load_logs()
tps = meta["time_settings/ntimepoints"][0]
defaults = {
"general": dict(
id=expt_id,
distributed=0,
tps=tps,
directory=str(directory),
filter="",
earlystop=dict(
min_tp=100,
thresh_pos_clogged=0.3,
thresh_trap_clogged=7,
ntps_to_eval=5,
),
)
}
defaults["tiler"] = TilerParameters.default().to_dict()
defaults["baby"] = BabyParameters.default().to_dict()
defaults["extraction"] = exparams_from_meta(meta)
defaults["postprocessing"] = PostProcessorParameters.default().to_dict()
for k in defaults.keys():
exec("defaults[k].update(" + k + ")")
return cls(**{k: v for k, v in defaults.items()})
def load_logs(self):
parsed_flattened = parse_logfiles(self.log_dir)
return parsed_flattened
class Pipeline(ProcessABC):
"""
A chained set of Pipeline elements connected through pipes.
Tiling, Segmentation,Extraction and Postprocessing should use their own default parameters.
These can be overriden passing the key:value of parameters to override to a PipelineParameters class
"""
def __init__(self, parameters: PipelineParameters, store=None):
super().__init__(parameters)
if store is None:
store = self.parameters.general["directory"]
self.store = store
@classmethod
def from_yaml(cls, fpath):
# This is just a convenience function, think before implementing
# for other processes
return cls(parameters=PipelineParameters.from_yaml(fpath))
@classmethod
def from_existing_h5(cls, fpath):
with h5py.File(fpath, "r") as f:
pipeline_parameters = PipelineParameters.from_yaml(f.attrs["parameters"])
return cls(pipeline_parameters)
def run(self):
# Config holds the general information, use in main
# Steps holds the description of tasks with their parameters
# Steps: all holds general tasks
# steps: strain_name holds task for a given strain
config = self.parameters.to_dict()
expt_id = config["general"]["id"]
distributed = config["general"]["distributed"]
pos_filter = config["general"]["filter"]
root_dir = config["general"]["directory"]
root_dir = Path(root_dir)
print("Searching OMERO")
# Do all initialis
with Dataset(int(expt_id), **self.general["server_info"]) as conn:
image_ids = conn.get_images()
directory = root_dir / conn.unique_name
if not directory.exists():
directory.mkdir(parents=True)
# Download logs to use for metadata
conn.cache_logs(directory)
# Modify to the configuration
self.parameters.general["directory"] = directory
config["general"]["directory"] = directory
# Filter TODO integrate filter onto class and add regex
filt_int = lambda d, filt: {
k: v for i, (k, v) in enumerate(d.items()) if i == filt
}
filt_str = lambda d, filt: {
k: v for k, v in image_ids.items() if re.search(filt, k)
}
def pick_filter(image_ids, filt):
if isinstance(filt, str):
image_ids = filt_str(image_ids, filt)
elif isinstance(filt, int):
image_ids = filt_int(image_ids, filt)
return image_ids
if isinstance(pos_filter, list):
image_ids = {
k: v
for filt in pos_filter
for k, v in pick_filter(image_ids, filt).items()
}
else:
image_ids = pick_filter(image_ids, pos_filter)
assert len(image_ids), "No images to segment"
if distributed != 0: # Gives the number of simultaneous processes
with Pool(distributed) as p:
results = p.map(lambda x: self.create_pipeline(x), image_ids.items())
return results
else: # Sequential
results = []
for k, v in image_ids.items():
r = self.create_pipeline((k, v))
results.append(r)
def create_pipeline(self, image_id):
config = self.parameters.to_dict()
name, image_id = image_id
general_config = config["general"]
session = None
earlystop = general_config["earlystop"]
try:
directory = general_config["directory"]
with Image(image_id, **self.general["server_info"]) as image:
filename = f"{directory}/{image.name}.h5"
meta = MetaData(directory, filename)
from_start = True
trackers_state = None
if (
not general_config.get("overwrite", False)
and Path(filename).exists()
):
try:
print(f"Existing file {filename} will be used.")
with h5py.File(filename, "r") as f:
tiler = Tiler.from_hdf5(image, filename)
s = Signal(filename)
process_from = (
f.attrs["last_processed"]
or s.get_raw("/general/None/extraction/volume").columns[
-1
]
or 0
)
# get state array
trackers_state = StateReader(
filename
).get_formatted_states()
tiler.n_processed = process_from
process_from += 1
from_start = False
except:
pass
if from_start: # New experiment or overwriting
try:
os.remove(filename)
except:
pass
process_from = 0
meta.run()
meta.add_fields(
{"omero_id,": config["general"]["id"], "image_id": image_id}
)
try:
tiler = Tiler.from_image(
image, TilerParameters.from_dict(config["tiler"])
)
except:
# Remove and try to run again?
meta.add_fields({"end_status": "Untiled"})
writer = TilerWriter(filename)
session = initialise_tf(2)
runner = BabyRunner.from_tiler(
BabyParameters.from_dict(config["baby"]), tiler
)
if trackers_state:
runner.crawler.trackers_state = trackers_state
bwriter = BabyWriter(filename)
swriter = StateWriter(filename)
# Limit extraction parameters during run using the available channels in tiler
av_channels = set((*tiler.channels, "general"))
config["extraction"]["tree"] = {
k: v
for k, v in config["extraction"]["tree"].items()
if k in av_channels
}
config["extraction"]["sub_bg"] = av_channels.intersection(
config["extraction"]["sub_bg"]
)
av_channels_wsub = av_channels.union(
[c + "_bgsub" for c in config["extraction"]["sub_bg"]]
)
for op in config["extraction"]["multichannel_ops"]:
config["extraction"]["multichannel_ops"][op] = [
x
for x in config["extraction"]["multichannel_ops"]
if len(x[0]) == len(av_channels_wsub.intersection(x[0]))
]
config["extraction"]["multichannel_ops"] = {
k: v
for k, v in config["extraction"]["multichannel_ops"].items()
if len(v)
}
exparams = ExtractorParameters.from_dict(config["extraction"])
ext = Extractor.from_tiler(exparams, store=filename, tiler=tiler)
# RUN
# Adjust tps based on how many tps are available on the server
tps = min(general_config["tps"], image.data.shape[0])
frac_clogged_traps = 0
for i in tqdm(
range(process_from, tps), desc=image.name, initial=process_from
):
if (
frac_clogged_traps < earlystop["thresh_pos_clogged"]
or i < earlystop["min_tp"]
):
t = perf_counter()
trap_info = tiler.run_tp(i)
logging.debug(f"Timing:Trap:{perf_counter() - t}s")
t = perf_counter()
writer.write(trap_info, overwrite=[], tp=i)
logging.debug(f"Timing:Writing-trap:{perf_counter() - t}s")
t = perf_counter()
seg = runner.run_tp(i)
logging.debug(f"Timing:Segmentation:{perf_counter() - t}s")
# logging.debug(
# f"Segmentation failed:Segmentation:{perf_counter() - t}s"
# )
t = perf_counter()
bwriter.write(seg, overwrite=["mother_assign"], tp=i)
logging.debug(f"Timing:Writing-baby:{perf_counter() - t}s")
# TODO add time-skipping for cases when the
# an interruption happens after writing segmentation but before extraction
t = perf_counter()
labels, masks = groupby_traps(
seg["trap"],
seg["cell_label"],
seg["edgemasks"],
tiler.n_traps,
)
tmp = ext.run(tps=[i], masks=masks, labels=labels)
logging.debug(f"Timing:Extraction:{perf_counter() - t}s")
else: # Stop if more than X% traps are clogged
logging.debug(
f"EarlyStop:{earlystop['thresh_pos_clogged']*100}% traps clogged at time point {i}"
)
print(
f"Stopping analysis at time {i} with {frac_clogged_traps} clogged traps"
)
meta.add_fields({"end_status": "Clogged"})
break
if (
i > earlystop["min_tp"]
): # Calculate the fraction of clogged traps
frac_clogged_traps = self.check_earlystop(filename, earlystop)
logging.debug(f"Quality:Clogged_traps:{frac_clogged_traps}")
print("Frac clogged traps: ", frac_clogged_traps)
# State Writer to recover interrupted experiments
swriter.write(
data=runner.crawler.tracker_states,
overwrite=swriter.datatypes.keys(),
)
meta.add_fields({"last_processed": i})
import pickle as pkl
with open(
Path(bwriter.file).parent / f"{i}_live_state.pkl", "wb"
) as f:
pkl.dump(runner.crawler.tracker_states, f)
with open(
Path(bwriter.file).parent / f"{i}_read_state.pkl", "wb"
) as f:
pkl.dump(StateReader(bwriter.file).get_formatted_states(), f)
# Run post processing
meta.add_fields({"end_status": "Success"})
post_proc_params = PostProcessorParameters.from_dict(
self.parameters.postprocessing
).to_dict()
PostProcessor(filename, post_proc_params).run()
return 1
except Exception as e: # bug in the trap getting
logging.exception(
f"Caught exception in worker thread (x = {name}):", exc_info=True
)
print(f"Caught exception in worker thread (x = {name}):")
# This prints the type, value, and stack trace of the
# current exception being handled.
traceback.print_exc()
print()
raise e
finally:
if session:
session.close()
try:
compiler = ExperimentCompiler(None, filepath)
tmp = compiler.run()
po = PageOrganiser(tmp, grid_spec=(3, 2))
po.plot()
po.save(fullpath / f"{directory}report.pdf")
except Exception as e:
print(e)
def check_earlystop(self, filename, es_parameters):
s = Signal(filename)
df = s["/extraction/general/None/area"]
frac_clogged_traps = (
df[df.columns[-1 - es_parameters["ntps_to_eval"] : -1]]
.dropna(how="all")
.notna()
.groupby("trap")
.apply(sum)
.apply(np.mean, axis=1)
> es_parameters["thresh_trap_clogged"]
).mean()
return frac_clogged_traps
def groupby_traps(traps, labels, edgemasks, ntraps):
# Group data by traps to pass onto extractor without re-reading hdf5
iterators = [
groupby(zip(traps, dset), lambda x: x[0]) for dset in (labels, edgemasks)
]
label_d = {key: [x[1] for x in group] for key, group in iterators[0]}
mask_d = {
key: np.dstack([ndimage.morphology.binary_fill_holes(x[1]) for x in group])
for key, group in iterators[1]
}
labels = {i: label_d.get(i, []) for i in range(ntraps)}
masks = {i: mask_d.get(i, []) for i in range(ntraps)}
return labels, masks
"""
Post-processing utilities
Notes: I don't have statistics on ranges of radii for each of the knots in
the radial spline representation, but we regularly extract the average of
these radii for each cell. So, depending on camera/lens, we get:
* 60x evolve: mean radii of 2-14 pixels (and measured areas of 30-750
pixels^2)
* 60x prime95b: mean radii of 3-24 pixels (and measured areas of 60-2000
pixels^2)
And I presume that for a 100x lens we would get an ~5/3 increase over those
values.
In terms of the current volume estimation method, it's currently only
implemented in the AnalysisToolbox repository, but it's super simple:
mVol = 4/3*pi*sqrt(mArea/pi).^3
where mArea is simply the sum of pixels for that cell.
"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from scipy import ndimage
from skimage.morphology import erosion, ball
from skimage import measure, draw
def my_ball(radius):
"""Generates a ball-shaped structuring element.
This is the 3D equivalent of a disk.
A pixel is within the neighborhood if the Euclidean distance between
it and the origin is no greater than radius.
Parameters
----------
radius : int
The radius of the ball-shaped structuring element.
Other Parameters
----------------
dtype : data-type
The data type of the structuring element.
Returns
-------
selem : ndarray
The structuring element where elements of the neighborhood
are 1 and 0 otherwise.
"""
n = 2 * radius + 1
Z, Y, X = np.mgrid[-radius:radius:n * 1j,
-radius:radius:n * 1j,
-radius:radius:n * 1j]
X **= 2
Y **= 2
Z **= 2
X += Y
X += Z
# s = X ** 2 + Y ** 2 + Z ** 2
return X <= radius * radius
def circle_outline(r):
return ellipse_perimeter(r, r)
def ellipse_perimeter(x, y):
im_shape = int(2*max(x, y) + 1)
img = np.zeros((im_shape, im_shape), dtype=np.uint8)
rr, cc = draw.ellipse_perimeter(int(im_shape//2), int(im_shape//2),
int(x), int(y))
img[rr, cc] = 1
return np.pad(img, 1)
def capped_cylinder(x, y):
max_size = (y + 2*x + 2)
pixels = np.zeros((max_size, max_size))
rect_start = ((max_size-x)//2, x + 1)
rr, cc = draw.rectangle_perimeter(rect_start, extent=(x, y),
shape=(max_size, max_size))
pixels[rr, cc] = 1
circle_centres = [(max_size//2 - 1, x),
(max_size//2 - 1, max_size - x - 1 )]
for r, c in circle_centres:
rr, cc = draw.circle_perimeter(r, c, (x + 1)//2,
shape=(max_size, max_size))
pixels[rr, cc] = 1
pixels = ndimage.morphology.binary_fill_holes(pixels)
pixels ^= erosion(pixels)
return pixels
def volume_of_sphere(radius):
return 4 / 3 * np.pi * radius**3
def plot_voxels(voxels):
verts, faces, normals, values = measure.marching_cubes_lewiner(
voxels, 0)
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
mesh = Poly3DCollection(verts[faces])
mesh.set_edgecolor('k')
ax.add_collection3d(mesh)
ax.set_xlim(0, voxels.shape[0])
ax.set_ylim(0, voxels.shape[1])
ax.set_zlim(0, voxels.shape[2])
plt.tight_layout()
plt.show()
# Volume estimation
def union_of_spheres(outline, shape='my_ball', debug=False):
filled = ndimage.binary_fill_holes(outline)
nearest_neighbor = ndimage.morphology.distance_transform_edt(
outline == 0) * filled
voxels = np.zeros((filled.shape[0], filled.shape[1], max(filled.shape)))
c_z = voxels.shape[2] // 2
for x,y in zip(*np.where(filled)):
radius = nearest_neighbor[(x,y)]
if radius > 0:
if shape == 'ball':
b = ball(radius)
elif shape == 'my_ball':
b = my_ball(radius)
else:
raise ValueError(f"{shape} is not an accepted value for "
f"shape.")
centre_b = ndimage.measurements.center_of_mass(b)
I,J,K = np.ogrid[:b.shape[0], :b.shape[1], :b.shape[2]]
voxels[I + int(x - centre_b[0]), J + int(y - centre_b[1]),
K + int(c_z - centre_b[2])] += b
if debug:
plot_voxels(voxels)
return voxels.astype(bool).sum()
def improved_uos(outline, shape='my_ball', debug=False):
filled = ndimage.binary_fill_holes(outline)
nearest_neighbor = ndimage.morphology.distance_transform_edt(
outline == 0) * filled
voxels = np.zeros((filled.shape[0], filled.shape[1], max(filled.shape)))
c_z = voxels.shape[2] // 2
while np.any(nearest_neighbor != 0):
radius = np.max(nearest_neighbor)
x, y = np.argwhere(nearest_neighbor == radius)[0]
if shape == 'ball':
b = ball(np.ceil(radius))
elif shape == 'my_ball':
b = my_ball(np.ceil(radius))
else:
raise ValueError(f"{shape} is not an accepted value for shape")
centre_b = ndimage.measurements.center_of_mass(b)
I, J, K = np.ogrid[:b.shape[0], :b.shape[1], :b.shape[2]]
voxels[I + int(x - centre_b[0]), J + int(y - centre_b[1]),
K + int(c_z - centre_b[2])] += b
# Use the central disk of the ball from voxels to get the circle
# = 0 if nn[x,y] < r else nn[x,y]
rr, cc = draw.circle(x, y, np.ceil(radius), nearest_neighbor.shape)
nearest_neighbor[rr, cc] = 0
if debug:
plot_voxels(voxels)
return voxels.astype(bool).sum()
def conical(outline, debug=False):
nearest_neighbor = ndimage.morphology.distance_transform_edt(
outline == 0) * ndimage.binary_fill_holes(outline)
if debug:
hf = plt.figure()
ha = hf.add_subplot(111, projection='3d')
X, Y = np.meshgrid(np.arange(nearest_neighbor.shape[0]),
np.arange(nearest_neighbor.shape[1]))
ha.plot_surface(X, Y, nearest_neighbor)
plt.show()
return 4 * nearest_neighbor.sum()
def volume(outline, method='spheres'):
if method=='conical':
return conical(outline)
elif method=='spheres':
return union_of_spheres(outline)
else:
raise ValueError(f"Method {method} not implemented.")
def circularity(outline):
pass
\ No newline at end of file
"""Pipeline results classes and utilities"""
class SegmentationResults:
"""
Object storing the data from the Segmentation pipeline.
Everything is stored as an `AttributeDict`, which is a `defaultdict` where
you can get elements as attributes.
In addition, it implements:
- IO functionality (read from file, write to file)
"""
def __init__(self, raw_expt):
pass
class CellResults:
"""
Results on a set of cells TODO: what set of cells, how?
Contains:
* cellInf describing which cells are taken into account
* annotations on the cell
* segmentation maps of the cell TODO: how to define and save this?
* trapLocations TODO: why is this not part of cellInf?
"""
def __init__(self, cellInf=None, annotations=None, segmentation=None,
trapLocations=None):
self._cellInf = cellInf
self._annotations = annotations
self._segmentation = segmentation
self._trapLocations = trapLocations
"""Segment/segmented pipelines.
Includes splitting the image into traps/parts,
cell segmentation, nucleus segmentation."""
import warnings
from functools import lru_cache
import h5py
import numpy as np
from pathlib import Path, PosixPath
from skimage.registration import phase_cross_correlation
from agora.abc import ParametersABC, ProcessABC
from aliby.tile.traps import segment_traps
from agora.io.writer import load_attributes
trap_template_directory = Path(__file__).parent / "trap_templates"
# TODO do we need multiple templates, one for each setup?
trap_template = np.array([]) # np.load(trap_template_directory / "trap_prime.npy")
def get_tile_shapes(x, tile_size, max_shape):
half_size = tile_size // 2
xmin = int(x[0] - half_size)
ymin = max(0, int(x[1] - half_size))
if xmin + tile_size > max_shape[0]:
xmin = max_shape[0] - tile_size
if ymin + tile_size > max_shape[1]:
ymin = max_shape[1] - tile_size
return xmin, xmin + tile_size, ymin, ymin + tile_size
###################### Dask versions ########################
class Trap:
def __init__(self, centre, parent, size, max_size):
self.centre = centre
self.parent = parent # Used to access drifts
self.size = size
self.half_size = size // 2
self.max_size = max_size
def padding_required(self, tp):
"""Check if we need to pad the trap image for this time point."""
try:
assert all(self.at_time(tp) - self.half_size >= 0)
assert all(self.at_time(tp) + self.half_size <= self.max_size)
except AssertionError:
return True
return False
def at_time(self, tp):
"""Return trap centre at time tp"""
drifts = self.parent.drifts
return self.centre - np.sum(drifts[: tp + 1], axis=0)
def as_tile(self, tp):
"""Return trap in the OMERO tile format of x, y, w, h
Also returns the padding necessary for this tile.
"""
x, y = self.at_time(tp)
# tile bottom corner
x = int(x - self.half_size)
y = int(y - self.half_size)
return x, y, self.size, self.size
def as_range(self, tp):
"""Return trap in a range format, two slice objects that can be used in Arrays"""
x, y, w, h = self.as_tile(tp)
return slice(x, x + w), slice(y, y + h)
class TrapLocations:
def __init__(self, initial_location, tile_size, max_size=1200, drifts=[]):
self.tile_size = tile_size
self.max_size = max_size
self.initial_location = initial_location
self.traps = [
Trap(centre, self, tile_size, max_size) for centre in initial_location
]
self.drifts = drifts
# @classmethod
# def from_source(cls, fpath: str):
# with h5py.File(fpath, "r") as f:
# # TODO read tile size from file metadata
# drifts = f["trap_info/drifts"][()].tolist()
# tlocs = cls(f["trap_info/trap_locations"][()], tile_size=96, drifts=drifts)
# return tlocs
@property
def shape(self):
return len(self.traps), len(self.drifts)
def __len__(self):
return len(self.traps)
def __iter__(self):
yield from self.traps
def padding_required(self, tp):
return any([trap.padding_required(tp) for trap in self.traps])
def to_dict(self, tp):
res = dict()
if tp == 0:
res["trap_locations"] = self.initial_location
res["attrs/tile_size"] = self.tile_size
res["attrs/max_size"] = self.max_size
res["drifts"] = np.expand_dims(self.drifts[tp], axis=0)
# res["processed_timepoints"] = tp
return res
@classmethod
def read_hdf5(cls, file):
with h5py.File(file, "r") as hfile:
trap_info = hfile["trap_info"]
initial_locations = trap_info["trap_locations"][()]
drifts = trap_info["drifts"][()].tolist()
max_size = trap_info.attrs["max_size"]
tile_size = trap_info.attrs["tile_size"]
trap_locs = cls(initial_locations, tile_size, max_size=max_size)
trap_locs.drifts = drifts
return trap_locs
class TilerParameters(ParametersABC):
def __init__(
self, tile_size: int, ref_channel: str, ref_z: int, template_name: str = None
):
self.tile_size = tile_size
self.ref_channel = ref_channel
self.ref_z = ref_z
self.template_name = template_name
@classmethod
def from_template(cls, template_name: str, ref_channel: str, ref_z: int):
return cls(template.shape[0], ref_channel, ref_z, template_path=template_name)
@classmethod
def default(cls):
return cls(117, "Brightfield", 0)
class Tiler(ProcessABC):
"""A dummy TimelapseTiler object fora Dask Demo.
Does trap finding and image registration."""
def __init__(
self,
image,
metadata,
parameters: TilerParameters,
trap_locs=None,
):
super().__init__(parameters)
self.image = image
self.channels = metadata["channels"]
self.ref_channel = self.get_channel_index(parameters.ref_channel)
self.trap_locs = trap_locs
@classmethod
def from_image(cls, image, parameters: TilerParameters):
return cls(image.data, image.metadata, parameters)
@classmethod
def from_hdf5(cls, image, filepath):
trap_locs = TrapLocations.read_hdf5(filepath)
metadata = load_attributes(filepath)
metadata["channels"] = metadata["channels/channel"].tolist()
return cls(
image.data,
metadata,
TilerParameters.default(),
trap_locs=trap_locs,
)
@lru_cache(maxsize=2)
def get_tc(self, t, c):
# Get image
full = self.image[t, c].compute() # FORCE THE CACHE
return full
@property
def shape(self):
c, t, z, y, x = self.image.shape
return (c, t, x, y, z)
@property
def n_processed(self):
if not hasattr(self, "_n_processed"):
self._n_processed = 0
return self._n_processed
@n_processed.setter
def n_processed(self, value):
self._n_processed = value
@property
def n_traps(self):
return len(self.trap_locs)
@property
def finished(self):
return self.n_processed == self.image.shape[0]
def _initialise_traps(self, tile_size):
"""Find initial trap positions.
Removes all those that are too close to the edge so no padding is necessary.
"""
half_tile = tile_size // 2
max_size = min(self.image.shape[-2:])
initial_image = self.image[
0, self.ref_channel, self.ref_z
] # First time point, first channel, first z-position
trap_locs = segment_traps(initial_image, tile_size)
trap_locs = [
[x, y]
for x, y in trap_locs
if half_tile < x < max_size - half_tile
and half_tile < y < max_size - half_tile
]
self.trap_locs = TrapLocations(trap_locs, tile_size)
def find_drift(self, tp):
# TODO check that the drift doesn't move any tiles out of the image, remove them from list if so
prev_tp = max(0, tp - 1)
drift, error, _ = phase_cross_correlation(
self.image[prev_tp, self.ref_channel, self.ref_z],
self.image[tp, self.ref_channel, self.ref_z],
)
if 0 < tp < len(self.trap_locs.drifts):
self.trap_locs.drifts[tp] = drift.tolist()
else:
self.trap_locs.drifts.append(drift.tolist())
def get_tp_data(self, tp, c):
traps = []
full = self.get_tc(tp, c)
# if self.trap_locs.padding_required(tp):
for trap in self.trap_locs:
ndtrap = self.ifoob_pad(full, trap.as_range(tp))
traps.append(ndtrap)
return np.stack(traps)
def get_trap_data(self, trap_id, tp, c):
full = self.get_tc(tp, c)
trap = self.trap_locs.traps[trap_id]
ndtrap = self.ifoob_pad(full, trap.as_range(tp))
return ndtrap
@staticmethod
def ifoob_pad(full, slices):
"""
Returns the slices padded if it is out of bounds
Parameters:
----------
full: (zstacks, max_size, max_size) ndarray
Entire position with zstacks as first axis
slices: tuple of two slices
Each slice indicates an axis to index
Returns
Trap for given slices, padded with median if needed, or np.nan if the padding is too much
"""
max_size = full.shape[-1]
y, x = [slice(max(0, s.start), min(max_size, s.stop)) for s in slices]
trap = full[:, y, x]
padding = np.array(
[(-min(0, s.start), -min(0, max_size - s.stop)) for s in slices]
)
if padding.any():
tile_size = slices[0].stop - slices[0].start
if (padding > tile_size / 4).any():
trap = np.full((full.shape[0], tile_size, tile_size), np.nan)
else:
trap = np.pad(trap, [[0, 0]] + padding.tolist(), "median")
return trap
def run_tp(self, tp):
# assert tp >= self.n_processed, "Time point already processed"
# TODO check contiguity?
if self.n_processed == 0:
self._initialise_traps(self.tile_size)
self.find_drift(tp) # Get drift
# update n_processed
self.n_processed = tp + 1
# Return result for writer
return self.trap_locs.to_dict(tp)
def run(self, tp):
if self.n_processed == 0:
self._initialise_traps(self.tile_size)
self.find_drift(tp) # Get drift
# update n_processed
self.n_processed += 1
# Return result for writer
return self.trap_locs.to_dict(tp)
# The next set of functions are necessary for the extraction object
def get_traps_timepoint(self, tp, tile_size=None, channels=None, z=None):
# FIXME we currently ignore the tile size
# FIXME can we ignore z(always give)
res = []
for c in channels:
val = self.get_tp_data(tp, c)[:, z] # Only return requested z
# positions
# Starts at traps, z, y, x
# Turn to Trap, C, T, X, Y, Z order
val = val.swapaxes(1, 3).swapaxes(1, 2)
val = np.expand_dims(val, axis=1)
res.append(val)
return np.stack(res, axis=1)
def get_channel_index(self, item):
for i, ch in enumerate(self.channels):
if item in ch:
return i
def get_position_annotation(self):
# TODO required for matlab support
return None