Skip to content

Commit

Permalink
Fix data loading & lint (#53)
Browse files Browse the repository at this point in the history
* fix plugin name

* Update pre-commit

* update plugin names

* fix pandas warning

* remove deprecated napari code

* Bump version: 0.2.14 → 0.2.15-rc0

* remove deprecated napari code

* Bump version: 0.2.15-rc0 → 0.2.16-rc0

* Bump version: 0.2.16-rc0 → 0.2.16
  • Loading branch information
adamltyson committed Jun 15, 2022
1 parent 22d3701 commit 1390077
Show file tree
Hide file tree
Showing 30 changed files with 180 additions and 261 deletions.
40 changes: 29 additions & 11 deletions .pre-commit-config.yaml
@@ -1,12 +1,30 @@
repos:
- repo: https://github.com/python/black
rev: 20.8b1
hooks:
- id: black
pass_filenames: true
- repo: https://gitlab.com/pycqa/flake8
rev: 3.7.9
hooks:
- id: flake8
pass_filenames: true
# exclude: __init__.py
- repo: https://github.com/pycqa/isort
rev: 5.10.1
hooks:
- id: isort
types: [text]
types_or: [python, cython]
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.1.0
hooks:
- id: check-docstring-first
- id: check-executables-have-shebangs
- id: check-merge-conflict
- id: check-toml
- id: end-of-file-fixer
- id: mixed-line-ending
args: [--fix=lf]
- id: requirements-txt-fixer
- id: trailing-whitespace
# bump2version produces whitespace in setup.cfg, so exclude to
# not inferfere with versioning
exclude: setup.cfg
- repo: https://gitlab.com/pycqa/flake8
rev: 3.9.2
hooks:
- id: flake8
- repo: https://github.com/psf/black
rev: 22.3.0
hooks:
- id: black
5 changes: 2 additions & 3 deletions README.md
Expand Up @@ -17,9 +17,9 @@ Segmentation of 1/2/3D brain structures in a common anatomical space

## Installation

brainreg-segment comes bundled with [`brainreg`](https://github.com/brainglobe/brainreg), so see the [brainreg installation instructions](https://docs.brainglobe.info/brainreg/installation).
brainreg-segment comes bundled with [`brainreg`](https://github.com/brainglobe/brainreg), so see the [brainreg installation instructions](https://docs.brainglobe.info/brainreg/installation).

brainreg-segment can be installed on it's own (`pip install brainreg-segment`), but you will need to register your data with brainreg first.
brainreg-segment can be installed on it's own (`pip install brainreg-segment`), but you will need to register your data with brainreg first.

## Usage

Expand All @@ -40,4 +40,3 @@ If you find brainreg-segment useful, and use it in your research, please let us
The BrainGlobe project is generously supported by the Sainsbury Wellcome Centre and the Institute of Neuroscience, Technical University of Munich, with funding from Wellcome, the Gatsby Charitable Foundation and the Munich Cluster for Systems Neurology - Synergy.

<img src='https://brainglobe.info/images/logos_combined.png' width="550">

2 changes: 1 addition & 1 deletion brainreg_segment/__init__.py
@@ -1,3 +1,3 @@
__author__ = "Adam Tyson"
__version__ = "0.2.14"
__version__ = "0.2.16"
from . import *
3 changes: 2 additions & 1 deletion brainreg_segment/atlas/utils.py
@@ -1,5 +1,6 @@
import re
from bg_atlasapi.list_atlases import utils, descriptors

from bg_atlasapi.list_atlases import descriptors, utils


def lateralise_atlas_image(
Expand Down
6 changes: 3 additions & 3 deletions brainreg_segment/layout/gui_elements.py
Expand Up @@ -2,12 +2,12 @@
# from napari.resources import build_icons # Contains .SVGPATH to all icons for napari

from qtpy.QtWidgets import (
QDoubleSpinBox,
QPushButton,
QCheckBox,
QComboBox,
QDoubleSpinBox,
QLabel,
QPushButton,
QSpinBox,
QComboBox,
)


Expand Down
72 changes: 0 additions & 72 deletions brainreg_segment/layout/utils.py
@@ -1,61 +1,6 @@
# Small layout utils
# import napari
from napari.viewer import Viewer

import bg_space as bg

# from brainreg_segment.layout.gui_constants import ORIENTATIONS

from qtpy.QtWidgets import QMessageBox


def disable_napari_btns(viewer):
"""
Disable some Napari functions to hide them from user interation
- Transpose TODO: Understand how to add this properly with space conventions
- Grid view
- Console
- New labels layer
- New points layer
- New shapes layer
"""
viewer.window.qt_viewer.viewerButtons.transposeDimsButton.setVisible(False)
viewer.window.qt_viewer.viewerButtons.gridViewButton.setVisible(False)
viewer.window.qt_viewer.viewerButtons.consoleButton.setVisible(False)
viewer.window.qt_viewer.layerButtons.newLabelsButton.setVisible(False)
viewer.window.qt_viewer.layerButtons.newPointsButton.setVisible(False)
viewer.window.qt_viewer.layerButtons.newShapesButton.setVisible(False)


def disable_napari_key_bindings():
"""
Disable some default key bingings that are unused
"""

@Viewer.bind_key("Control-G", overwrite=True)
def no_grid_mode_warning(self):
print("Grid mode is not supported")

@Viewer.bind_key("Control-T", overwrite=True)
def no_tranpose_warning(self):
print("Transposing is not supported")


def get_dims_from_origins(origins):
"""From a list of BG space abbreviations (e.g. ["asl","sla","lsa"]) get correct axes for display in Napari"""
all_dims = []
for o in range(len(origins)):
sc = bg.AnatomicalSpace(origins[0])
next_orientation = origins[(o + 1) % len(origins)]
dims, flips, _, _ = sc.map_to(next_orientation)
assert not any(
flips
), f"\nReceived orientations: {origins}\nThese require (orientation) flips. This is not currently supported"
all_dims.append(list(dims))
return all_dims


def display_warning(widget, title, message):
"""
Display a warning in a pop up that informs
Expand All @@ -71,20 +16,3 @@ def display_warning(widget, title, message):
return True
else:
return False


# def overwrite_napari_roll(viewer):
# """
# Overwrite Napari _roll() function with something that makes more sense for a (mouse) brain
# Goal: Cycle through views (e.g. asl -> lsa -> sal)
# """
# dims = get_dims_from_origins(ORIENTATIONS)
#
# def _roll(self):
# """Roll order of dimensions for display."""
# dims_idx = dims.index(self.order)
# next_dims = dims[(dims_idx + 1) % len(dims)]
# self.order = next_dims
#
# # Substitute Napari function
# napari.components.dims.Dims._roll = _roll
2 changes: 1 addition & 1 deletion brainreg_segment/measurement/measurement.py
Expand Up @@ -4,9 +4,9 @@
import pathlib
from typing import List, Tuple

from magicgui import magic_factory
import napari
import numpy as np
from magicgui import magic_factory


# For the axis This assumes the following (x,y,z) are each of the following
Expand Down
3 changes: 2 additions & 1 deletion brainreg_segment/plugins.py
@@ -1,10 +1,11 @@
from napari_plugin_engine import napari_hook_implementation
from brainreg_segment.segment import SegmentationWidget

from brainreg_segment.measurement import measurement
from brainreg_segment.measurement.random_layers import (
generate_random_points_2d_layer,
generate_random_points_3d_layer,
)
from brainreg_segment.segment import SegmentationWidget


@napari_hook_implementation
Expand Down
7 changes: 3 additions & 4 deletions brainreg_segment/regions/IO.py
@@ -1,10 +1,9 @@
import imio
import numpy as np

from pathlib import Path
from skimage import measure

import imio
import numpy as np
from imlib.general.pathlib import append_to_pathlib_stem
from skimage import measure


def convert_obj_to_br(verts, faces, voxel_size):
Expand Down
11 changes: 4 additions & 7 deletions brainreg_segment/regions/analysis.py
@@ -1,13 +1,10 @@
import numpy as np
import pandas as pd


from imlib.general.list import unique_elements_lists
from imlib.pandas.misc import initialise_df
from napari.qt.threading import thread_worker
from skimage.measure import regionprops_table

from imlib.pandas.misc import initialise_df
from imlib.general.list import unique_elements_lists

from brainreg_segment.atlas.utils import lateralise_atlas_image


Expand Down Expand Up @@ -66,7 +63,7 @@ def summarise_brain_regions(label_layers, filename, atlas_resolution):

result.columns = ["region"] + [volume_header] + length_columns

voxel_volume_in_mm = np.prod(atlas_resolution) / (1000 ** 3)
voxel_volume_in_mm = np.prod(atlas_resolution) / (1000**3)

result[volume_header] = result[volume_header] * voxel_volume_in_mm

Expand Down Expand Up @@ -140,7 +137,7 @@ def analyse_region_brain_areas(
unique_vals_right, counts_right = np.unique(
annotations_right, return_counts=True
)
voxel_volume_in_mm = np.prod(atlas.resolution) / (1000 ** 3)
voxel_volume_in_mm = np.prod(atlas.resolution) / (1000**3)

df = initialise_df(
"structure_name",
Expand Down
6 changes: 3 additions & 3 deletions brainreg_segment/regions/layers.py
@@ -1,9 +1,9 @@
import tifffile
import numpy as np

from glob import glob
from pathlib import Path

import numpy as np
import tifffile


def add_new_label_layer(
viewer,
Expand Down
78 changes: 20 additions & 58 deletions brainreg_segment/segment.py
@@ -1,60 +1,37 @@
from pathlib import Path

import napari
import numpy as np
from pathlib import Path
from bg_atlasapi import BrainGlobeAtlas
from napari.qt.threading import thread_worker
from qtpy import QtCore

from qtpy.QtWidgets import (
QLabel,
QFileDialog,
QGridLayout,
QGroupBox,
QWidget,
)

from bg_atlasapi import BrainGlobeAtlas

from brainreg_segment.paths import Paths

from brainreg_segment.regions.IO import (
save_label_layers,
export_label_layers,
)

from brainreg_segment.tracks.IO import save_track_layers, export_splines
from qtpy.QtWidgets import QFileDialog, QGridLayout, QGroupBox, QLabel, QWidget

from brainreg_segment.atlas.utils import (
get_available_atlases,
structure_from_viewer,
)
from brainreg_segment.layout.utils import display_warning

# LAYOUT HELPERS ################################################################################

# from brainreg_segment.layout.utils import (
# disable_napari_key_bindings,
# disable_napari_btns,
# overwrite_napari_roll,
# )
from brainreg_segment.layout.gui_constants import (
WINDOW_HEIGHT,
WINDOW_WIDTH,
BOUNDARIES_STRING,
COLUMN_WIDTH,
SEGM_METHODS_PANEL_ALIGN,
DISPLAY_REGION_INFO,
LOADING_PANEL_ALIGN,
BOUNDARIES_STRING,
SEGM_METHODS_PANEL_ALIGN,
TRACK_FILE_EXT,
DISPLAY_REGION_INFO,
)

from brainreg_segment.layout.gui_elements import (
add_button,
add_combobox,
WINDOW_HEIGHT,
WINDOW_WIDTH,
)
from brainreg_segment.layout.gui_elements import add_button, add_combobox
from brainreg_segment.layout.utils import display_warning
from brainreg_segment.paths import Paths
from brainreg_segment.regions.IO import export_label_layers, save_label_layers

# SEGMENTATION ################################################################################
from brainreg_segment.segmentation_panels.regions import RegionSeg
from brainreg_segment.segmentation_panels.tracks import TrackSeg
from brainreg_segment.tracks.IO import export_splines, save_track_layers

# LAYOUT HELPERS ################################################################################


class SegmentationWidget(QWidget):
Expand All @@ -68,13 +45,6 @@ def __init__(
# general variables
self.viewer = viewer

# Disable / overwrite napari viewer functions
# that either do not make sense or should be avoided by the user
# removed for now, to make sure plugin
# disable_napari_btns(self.viewer)
# disable_napari_key_bindings()
# overwrite_napari_roll(self.viewer)

# Main layers
self.base_layer = [] # Contains registered brain / reference brain
self.atlas_layer = [] # Contains annotations / region information
Expand Down Expand Up @@ -310,7 +280,6 @@ def initialise_atlas(self):

self.status_label.setText("Ready")
# Set window title
# self.viewer.title = f"Atlas: {self.current_atlas_name}"
self.initialise_segmentation_interface()
# Check / load previous regions and tracks
self.region_seg.check_saved_region()
Expand Down Expand Up @@ -365,10 +334,12 @@ def get_brainreg_directory(self, standard_space):
and sets global directory info
"""
if standard_space:
self.plugin = "brainreg-standard"
self.plugin = (
"brainglobe-napari-io.brainreg_read_dir_standard_space"
)
self.standard_space = True
else:
self.plugin = "brainglobe-io"
self.plugin = "brainglobe-napari-io.brainreg_read_dir"
self.standard_space = False

self.status_label.setText("Loading...")
Expand Down Expand Up @@ -440,11 +411,6 @@ def initialise_loaded_data(self):
self.hemispheres_data = self.viewer.layers["Hemispheres"].data

self.initialise_segmentation_interface()

# Set window title
# self.viewer.title = (
# f"Brainreg: {self.metadata['atlas']} ({self.plugin})"
# )
self.status_label.setText("Ready")

# MORE LAYOUT COMPONENTS ###########################################
Expand Down Expand Up @@ -511,10 +477,6 @@ def remove_layers(self):
except IndexError: # no idea why this happens
pass

# There seems to be a napari bug trying to access previously used slider
# values. Trying to circument for now
self.viewer.window.qt_viewer.dims._last_used = None

self.track_layers = []
self.label_layers = []
return True
Expand Down

0 comments on commit 1390077

Please sign in to comment.