|
| 1 | +# Copilot Instructions for czitools |
| 2 | + |
| 3 | +This document provides guidelines for GitHub Copilot when working with the czitools repository. |
| 4 | + |
| 5 | +## Project Overview |
| 6 | + |
| 7 | +**czitools** is a Python package for reading CZI (Carl Zeiss Image) pixel and metadata. It simplifies working with CZI microscopy image files by providing tools for metadata extraction and pixel data reading. |
| 8 | + |
| 9 | +### Key Dependencies |
| 10 | +- `pylibCZIrw` - Core library for reading/writing CZI files |
| 11 | +- `aicspylibczi` - Additional CZI functionality |
| 12 | +- `numpy` - Array operations |
| 13 | +- `dask` - Lazy/delayed array operations |
| 14 | +- `xarray` - Labeled multi-dimensional arrays |
| 15 | +- `pandas` - Data manipulation (planetables) |
| 16 | +- `python-box` - Dictionary access via attributes |
| 17 | +- `pydantic` - Data validation |
| 18 | +- `loguru` / `colorlog` - Logging |
| 19 | + |
| 20 | +### Supported Python Versions |
| 21 | +- Python 3.10, 3.11, 3.12, 3.13 |
| 22 | + |
| 23 | +### Supported Operating Systems |
| 24 | +- Windows |
| 25 | +- Linux |
| 26 | +- macOS (with manual pylibCZIrw wheel installation) |
| 27 | + |
| 28 | +## Project Structure |
| 29 | + |
| 30 | +``` |
| 31 | +src/czitools/ |
| 32 | +├── metadata_tools/ # Classes for extracting CZI metadata |
| 33 | +│ ├── czi_metadata.py # Main CziMetadata class |
| 34 | +│ ├── dimension.py # CziDimensions |
| 35 | +│ ├── scaling.py # CziScaling |
| 36 | +│ ├── channel.py # CziChannelInfo |
| 37 | +│ ├── boundingbox.py # CziBoundingBox |
| 38 | +│ ├── objective.py # CziObjectives |
| 39 | +│ ├── detector.py # CziDetector |
| 40 | +│ ├── microscope.py # CziMicroscope |
| 41 | +│ ├── sample.py # CziSampleInfo |
| 42 | +│ └── add_metadata.py # CziAddMetaData |
| 43 | +├── read_tools/ # Functions for reading pixel data |
| 44 | +│ └── read_tools.py # read_6darray, read_mdarray, etc. |
| 45 | +├── utils/ # Utility modules |
| 46 | +│ ├── logging_tools.py # Logging configuration |
| 47 | +│ ├── box.py # Box utilities for metadata |
| 48 | +│ ├── misc.py # Miscellaneous helpers |
| 49 | +│ ├── pixels.py # Pixel type utilities |
| 50 | +│ └── planetable.py # Planetable generation |
| 51 | +├── visu_tools/ # Visualization utilities |
| 52 | +└── _tests/ # Test suite |
| 53 | +``` |
| 54 | + |
| 55 | +## Coding Conventions |
| 56 | + |
| 57 | +### Python Style |
| 58 | +- Use Python 3.10+ syntax and type hints |
| 59 | +- Follow PEP 8 style guidelines |
| 60 | +- Use `dataclass` for metadata classes with `@dataclass` decorator |
| 61 | +- Use `field(init=False, default=None)` for computed fields in dataclasses |
| 62 | +- Prefer `Optional[Type]` for nullable types |
| 63 | +- Use `Union[str, os.PathLike[str]]` for file paths |
| 64 | + |
| 65 | +### Type Annotations |
| 66 | +```python |
| 67 | +from typing import List, Dict, Tuple, Optional, Any, Union |
| 68 | +from dataclasses import dataclass, field |
| 69 | + |
| 70 | +@dataclass |
| 71 | +class ExampleMetadata: |
| 72 | + filepath: Union[str, os.PathLike[str]] |
| 73 | + value: Optional[float] = field(init=False, default=None) |
| 74 | + items: Optional[List[str]] = field(init=False, default_factory=lambda: []) |
| 75 | +``` |
| 76 | + |
| 77 | +### Imports Organization |
| 78 | +1. Standard library imports |
| 79 | +2. Third-party imports (numpy, pandas, etc.) |
| 80 | +3. Local imports from czitools |
| 81 | + |
| 82 | +```python |
| 83 | +# Standard library |
| 84 | +from typing import Dict, Tuple, Optional, Union |
| 85 | +import os |
| 86 | +from pathlib import Path |
| 87 | +from dataclasses import dataclass, field |
| 88 | + |
| 89 | +# Third-party |
| 90 | +import numpy as np |
| 91 | +from box import Box |
| 92 | +from pylibCZIrw import czi as pyczi |
| 93 | + |
| 94 | +# Local |
| 95 | +from czitools.utils import logging_tools |
| 96 | +from czitools.metadata_tools.helper import ValueRange |
| 97 | +``` |
| 98 | + |
| 99 | +### Logging |
| 100 | +- Use the custom logging setup from `czitools.utils.logging_tools` |
| 101 | +- Initialize logger at module level: `logger = logging_tools.set_logging()` |
| 102 | +- Use `logger.info()`, `logger.warning()`, `logger.error()` for messages |
| 103 | +- Use `verbose` parameter in classes to control logging output |
| 104 | + |
| 105 | +```python |
| 106 | +from czitools.utils import logging_tools |
| 107 | +logger = logging_tools.set_logging() |
| 108 | + |
| 109 | +if self.verbose: |
| 110 | + logger.info("Processing completed successfully") |
| 111 | +``` |
| 112 | + |
| 113 | +### File Path Handling |
| 114 | +- Accept both `str` and `os.PathLike[str]` (Path objects) |
| 115 | +- Convert Path to string when needed: `str(filepath)` |
| 116 | +- Use `pathlib.Path` for path manipulations |
| 117 | +- Support URL paths using `validators.url()` check |
| 118 | + |
| 119 | +```python |
| 120 | +from pathlib import Path |
| 121 | + |
| 122 | +if isinstance(self.filepath, Path): |
| 123 | + self.filepath = str(self.filepath) |
| 124 | +``` |
| 125 | + |
| 126 | +### Error Handling |
| 127 | +- Use defensive programming with fallback values |
| 128 | +- Guard against None values and division by zero |
| 129 | +- Use `try/except` blocks for external library calls |
| 130 | +- Return None or sensible defaults instead of raising exceptions when appropriate |
| 131 | + |
| 132 | +```python |
| 133 | +# Safe value extraction with fallback |
| 134 | +try: |
| 135 | + value = float(data.Value) * 1000000 |
| 136 | + if value == 0.0: |
| 137 | + value = 1.0 # fallback |
| 138 | +except (AttributeError, TypeError): |
| 139 | + value = None |
| 140 | +``` |
| 141 | + |
| 142 | +### Docstrings |
| 143 | +- Use Google-style docstrings |
| 144 | +- Include Args, Returns, and Raises sections |
| 145 | +- Document class attributes in class docstring |
| 146 | + |
| 147 | +```python |
| 148 | +def read_6darray( |
| 149 | + filepath: Union[str, os.PathLike[str]], |
| 150 | + use_dask: Optional[bool] = False, |
| 151 | + zoom: Optional[float] = 1.0, |
| 152 | +) -> Tuple[Optional[np.ndarray], CziMetadata]: |
| 153 | + """Read a CZI image file as 6D array. |
| 154 | +
|
| 155 | + Args: |
| 156 | + filepath: Path to the CZI image file. |
| 157 | + use_dask: Option to use dask for delayed reading. |
| 158 | + zoom: Downscale factor [0.01 - 1.0]. |
| 159 | +
|
| 160 | + Returns: |
| 161 | + Tuple of (array6d, metadata) where array6d may be None on error. |
| 162 | + """ |
| 163 | +``` |
| 164 | + |
| 165 | +## Testing Guidelines |
| 166 | + |
| 167 | +### Test Location |
| 168 | +- Tests are in `src/czitools/_tests/` |
| 169 | +- Test files follow pattern: `test_*.py` |
| 170 | +- Use pytest as the test framework |
| 171 | + |
| 172 | +### Test Structure |
| 173 | +```python |
| 174 | +from czitools.metadata_tools import czi_metadata as czimd |
| 175 | +from pathlib import Path |
| 176 | +import pytest |
| 177 | +from typing import List, Any |
| 178 | + |
| 179 | +basedir = Path(__file__).resolve().parents[3] |
| 180 | + |
| 181 | +@pytest.mark.parametrize( |
| 182 | + "czifile, expected_value", |
| 183 | + [ |
| 184 | + ("CellDivision_T3_Z5_CH2_X240_Y170.czi", [None, 3, 5, 2, 170, 240]) |
| 185 | + ] |
| 186 | +) |
| 187 | +def test_example(czifile: str, expected_value: List[Any]) -> None: |
| 188 | + filepath = basedir / "data" / czifile |
| 189 | + # Test implementation |
| 190 | + assert result == expected_value |
| 191 | +``` |
| 192 | + |
| 193 | +### Test Data |
| 194 | +- Test CZI files are in `data/` directory |
| 195 | +- Use parametrized tests for multiple test cases |
| 196 | +- Reference test files relative to `basedir` |
| 197 | + |
| 198 | +### Running Tests |
| 199 | +```bash |
| 200 | +pytest src/czitools/_tests/ |
| 201 | +pytest -m "not network" # Skip network tests |
| 202 | +``` |
| 203 | + |
| 204 | +## Common Patterns |
| 205 | + |
| 206 | +### Reading Metadata |
| 207 | +```python |
| 208 | +from czitools.metadata_tools.czi_metadata import CziMetadata |
| 209 | +from czitools.metadata_tools.scaling import CziScaling |
| 210 | +from czitools.metadata_tools.dimension import CziDimensions |
| 211 | + |
| 212 | +# Get all metadata at once |
| 213 | +mdata = CziMetadata(filepath) |
| 214 | + |
| 215 | +# Or get specific metadata |
| 216 | +scaling = CziScaling(filepath) |
| 217 | +dimensions = CziDimensions(filepath) |
| 218 | +``` |
| 219 | + |
| 220 | +### Reading Pixel Data |
| 221 | +```python |
| 222 | +from czitools.read_tools import read_tools |
| 223 | + |
| 224 | +# Read as 6D array (STCZYX order) |
| 225 | +array6d, mdata = read_tools.read_6darray( |
| 226 | + filepath, |
| 227 | + use_dask=True, # For large files |
| 228 | + use_xarray=True, # For labeled dimensions |
| 229 | + zoom=0.5 # Downscale |
| 230 | +) |
| 231 | +``` |
| 232 | + |
| 233 | +### Using Box for Metadata |
| 234 | +```python |
| 235 | +from czitools.utils.box import get_czimd_box |
| 236 | + |
| 237 | +# Get metadata as Box object for attribute-style access |
| 238 | +czi_box = get_czimd_box(filepath) |
| 239 | +scaling = czi_box.ImageDocument.Metadata.Scaling.Items.Distance |
| 240 | +``` |
| 241 | + |
| 242 | +## Array Dimension Order |
| 243 | + |
| 244 | +CZI arrays use the dimension order: **STCZYX(A)** |
| 245 | +- S = Scene |
| 246 | +- T = Time |
| 247 | +- C = Channel |
| 248 | +- Z = Z-slice |
| 249 | +- Y = Y dimension |
| 250 | +- X = X dimension |
| 251 | +- A = Alpha/RGB component (optional) |
| 252 | + |
| 253 | +## Additional Notes |
| 254 | + |
| 255 | +### Metadata Classes Pattern |
| 256 | +All metadata classes follow a similar pattern: |
| 257 | +1. Accept `czisource` as filepath, Path, or Box object |
| 258 | +2. Use `@dataclass` with `field(init=False)` for computed attributes |
| 259 | +3. Implement `__post_init__` for initialization logic |
| 260 | +4. Support `verbose` parameter for logging control |
| 261 | + |
| 262 | +### Scaling Units |
| 263 | +- Internal scaling values are in **microns** |
| 264 | +- Conversion from CZI values: `value * 1000000` (meters to microns) |
| 265 | + |
| 266 | +### RGB Support |
| 267 | +- Check `isRGB` dictionary for RGB status per channel |
| 268 | +- RGB images have an additional 'A' dimension |
| 269 | + |
| 270 | +### Scene Handling |
| 271 | +- CZI files may have multiple scenes |
| 272 | +- Check `has_scenes` and `SizeS` for scene information |
| 273 | +- Use `bbox.total_bounding_box` for combined bounds |
0 commit comments