core
¤
bioimageio.core --- core functionality for BioImage.IO resources
The main focus on this library is to provide functionality to run prediction with BioImage.IO models, including standardized pre- and postprocessing operations. The BioImage.IO models (and other resources) are described by---and can be loaded with---the bioimageio.spec package.
See predict and predict_many for straight-forward model inference
and create_prediction_pipeline for finer control of the inference process.
Other notable bioimageio.core functionalities include:
- Testing BioImage.IO resources beyond format validation, e.g. by generating model outputs from test inputs.
See test_model or for arbitrary resource types test_description.
- Extending available model weight formats by converting existing ones, see add_weights.
- Creating and manipulating Samples consisting of tensors with associated statistics.
- Computing statistics on datasets (represented as sequences of samples), see compute_dataset_measures.
Modules:
| Name | Description |
|---|---|
__main__ |
|
axis |
|
backends |
|
block |
|
block_meta |
|
cli |
bioimageio CLI |
commands |
These functions are used in the bioimageio command line interface |
common |
|
dataset |
|
digest_spec |
|
io |
|
prediction |
|
proc_ops |
|
proc_setup |
|
remote_backends |
|
sample |
|
stat_calculators |
|
stat_measures |
|
tensor |
|
utils |
|
weight_converters |
|
Classes:
| Name | Description |
|---|---|
Axis |
|
BlockMeta |
Block meta data of a sample member (a tensor in a sample) |
IntermediatePrediction |
Represents an intermediate prediction of a sample with blocking, including the predicted sample so far and the last predicted block. |
PredictionPipeline |
Represents model computation including preprocessing and postprocessing |
RemotePredictionPipeline |
Abstract base class for fully remote prediction pipelines. |
Sample |
A dataset sample. |
SampleBlock |
A block of a dataset sample |
SampleBlockMeta |
Meta data of a dataset sample block |
SampleSerializer |
|
Settings |
environment variables for bioimageio.spec and bioimageio.core |
Tensor |
A wrapper around an xr.DataArray for better integration with bioimageio.spec |
Functions:
| Name | Description |
|---|---|
add_weights |
Convert model weights to other formats and add them to the model description |
build_description |
build a bioimage.io resource description from an RDF's content. |
compute_dataset_measures |
compute all dataset |
compute_measures |
compute all |
compute_sample_measures |
compute all sample |
create_model_adapter |
Creates model adapter for |
create_prediction_pipeline |
Creates prediction pipeline which includes: |
create_remote_prediction_pipeline |
Create a |
dump_description |
Converts a resource to a dictionary containing only simple types that can directly be serialzed to YAML. |
enable_determinism |
Seed and configure ML frameworks for maximum reproducibility. |
load_dataset_description |
same as |
load_description |
load a bioimage.io resource description |
load_description_and_test |
Test a bioimage.io resource dynamically, |
load_description_and_validate_format_only |
same as |
load_model_description |
same as |
predict |
Run prediction for a single set of input(s) with a bioimage.io model |
predict_many |
Run prediction for a multiple sets of inputs with a bioimage.io model |
save_bioimageio_package |
Package a bioimageio resource as a zip file. |
save_bioimageio_package_as_folder |
Write the content of a bioimage.io resource package to a folder. |
save_bioimageio_yaml_only |
write the metadata of a resource description ( |
test_description |
Test a bioimage.io resource dynamically, |
test_model |
Test model inference |
validate_format |
Validate a dictionary holding a bioimageio description. |
Attributes:
| Name | Type | Description |
|---|---|---|
AxisId |
TypeAlias
|
An axis identifier, e.g. 'batch', 'channel', 'z', 'y', 'x' |
MemberId |
ID of a |
|
Stat |
TypeAlias
|
|
ValidationSummary |
|
|
__version__ |
|
|
load_model |
alias of |
|
load_resource |
alias of |
|
settings |
parsed environment variables for bioimageio.spec and bioimageio.core |
|
test_resource |
alias of |
AxisId
module-attribute
¤
An axis identifier, e.g. 'batch', 'channel', 'z', 'y', 'x'
MemberId
module-attribute
¤
ID of a Sample member, see bioimageio.core.sample.Sample
-
API Reference
digest_spec
Stat
module-attribute
¤
Stat: TypeAlias = Dict[Measure, MeasureValue]
-
API Reference
io
settings
module-attribute
¤
settings = Settings()
parsed environment variables for bioimageio.spec and bioimageio.core
Axis
dataclass
¤
Axis(id: AxisId, type: Literal['batch', 'channel', 'index', 'space', 'time'])
Methods:
| Name | Description |
|---|---|
__post_init__ |
|
create |
|
Attributes:
| Name | Type | Description |
|---|---|---|
id |
AxisId
|
|
type |
Literal['batch', 'channel', 'index', 'space', 'time']
|
|
__post_init__
¤
__post_init__()
Source code in src/bioimageio/core/axis.py
69 70 71 72 73 | |
create
classmethod
¤
Source code in src/bioimageio/core/axis.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | |
BlockMeta
¤
Block meta data of a sample member (a tensor in a sample)
Figure for illustration: The first 2d block (dashed) of a sample member (bold). The inner slice (thin) is expanded by a halo in both dimensions on both sides. The outer slice reaches from the sample member origin (0, 0) to the right halo point.
first block (at the sample origin)
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┐
╷ halo(left) ╷
╷ padding outside the sample ╷
╷ (0, 0)┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━┯━━━➔
╷ ┃ │ ╷ sample member
╷ ┃ inner │ outer ╷
╷ ┃ region │ region ╷
╷ ┃ /slice │ /slice ╷
╷ ┃ │ ╷
╷ ┣─────────────────┘ ╷
╷ ┃ outer region/slice ╷
╷ ┃ halo(right) ╷
└ ─ ─ ─ ─┃─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┘
⬇
Note: - Inner and outer slices are specified in sample member coordinates. - The outer_slice of a block at the sample edge may overlap by more than the halo with the neighboring block (the inner slices will not overlap though).
- API Reference
-
API Reference
sample
Methods:
| Name | Description |
|---|---|
__post_init__ |
|
get_transformed |
|
Attributes:
| Name | Type | Description |
|---|---|---|
block_index |
BlockIndex
|
the i-th block of the sample |
blocks_in_sample |
TotalNumberOfBlocks
|
total number of blocks in the sample |
dims |
Collection[AxisId]
|
|
halo |
PerAxisAnno[Halo]
|
halo enlarging the inner region to the block's sizes |
inner_shape |
PerAxis[int]
|
axis lengths of the inner region (without halo) |
inner_slice |
PerAxisAnno[SliceInfo]
|
inner region (without halo) wrt the sample |
inner_slice_wo_overlap |
PerAxis[SliceInfo]
|
subslice of the inner slice, such that all |
local_slice |
PerAxis[SliceInfo]
|
inner slice wrt the block, not the sample |
outer_slice |
PerAxis[SliceInfo]
|
slice of the outer block (without padding) wrt the sample |
padding |
PerAxis[PadWidth]
|
padding to realize the halo at the sample edge |
sample_shape |
PerAxisAnno[int]
|
the axis sizes of the whole (unblocked) sample |
shape |
PerAxis[int]
|
axis lengths of the block |
tagged_shape |
PerAxis[int]
|
alias for shape |
blocks_in_sample
instance-attribute
¤
blocks_in_sample: TotalNumberOfBlocks
total number of blocks in the sample
halo
instance-attribute
¤
halo: PerAxisAnno[Halo]
halo enlarging the inner region to the block's sizes
inner_shape
cached
property
¤
inner_shape: PerAxis[int]
axis lengths of the inner region (without halo)
inner_slice
instance-attribute
¤
inner_slice: PerAxisAnno[SliceInfo]
inner region (without halo) wrt the sample
inner_slice_wo_overlap
property
¤
subslice of the inner slice, such that all inner_slice_wo_overlap can be
stiched together trivially to form the original sample.
This can also be used to calculate statistics without overrepresenting block edge regions.
local_slice
cached
property
¤
inner slice wrt the block, not the sample
outer_slice
cached
property
¤
slice of the outer block (without padding) wrt the sample
padding
cached
property
¤
padding to realize the halo at the sample edge where we cannot simply enlarge the inner slice
sample_shape
instance-attribute
¤
sample_shape: PerAxisAnno[int]
the axis sizes of the whole (unblocked) sample
__post_init__
¤
__post_init__()
Source code in src/bioimageio/core/block_meta.py
199 200 201 202 203 204 205 206 207 208 209 210 211 | |
get_transformed
¤
get_transformed(new_axes: PerAxis[Union[LinearAxisTransform, int]]) -> Self
Source code in src/bioimageio/core/block_meta.py
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | |
IntermediatePrediction
¤
Bases: NamedTuple
flowchart TD
bioimageio.core.IntermediatePrediction[IntermediatePrediction]
click bioimageio.core.IntermediatePrediction href "" "bioimageio.core.IntermediatePrediction"
Represents an intermediate prediction of a sample with blocking, including the predicted sample so far and the last predicted block.
The final IntermediatePrediction in a sequence holds the complete predicted (and postprocessed if applicable) sample.
Attributes:
| Name | Type | Description |
|---|---|---|
last_block |
SampleBlock
|
|
sample |
Sample
|
|
PredictionPipeline
¤
PredictionPipeline(*, name: str, model_description: AnyModelDescr, preprocessing: List[Processing], postprocessing: List[Processing], model_adapter: ModelAdapter, default_blocksize_parameter: BlocksizeParameter = 10, default_batch_size: int = 1, preceding_prediction_pipelines: Optional[Sequence[Union[PredictionPipeline, RemotePredictionPipeline]]] = None)
Bases: _PredictionPipelineBase
flowchart TD
bioimageio.core.PredictionPipeline[PredictionPipeline]
bioimageio.core._prediction_pipeline._PredictionPipelineBase[_PredictionPipelineBase]
bioimageio.core._prediction_pipeline._PredictionPipelineBase --> bioimageio.core.PredictionPipeline
click bioimageio.core.PredictionPipeline href "" "bioimageio.core.PredictionPipeline"
click bioimageio.core._prediction_pipeline._PredictionPipelineBase href "" "bioimageio.core._prediction_pipeline._PredictionPipelineBase"
Represents model computation including preprocessing and postprocessing
Note: Ideally use the PredictionPipeline in a with statement
(as a context manager).
-
API Reference
corecreate_prediction_pipeline
Methods:
| Name | Description |
|---|---|
__enter__ |
|
__exit__ |
|
apply_postprocessing |
apply postprocessing in-place, also may updates samples stats |
apply_preprocessing |
Apply preprocessing in-place, also may updates sample stats |
close |
Permanently close the prediction pipeline and free any device memory in use. |
get_output_sample_id |
|
load |
Prepare prediction pipeline for use. |
predict_sample_block |
Predict a single sample block. |
predict_sample_with_blocking |
Predict a sample by predicting sample blocks. |
predict_sample_with_blocking_yield_intermediates |
Predict |
predict_sample_with_fixed_blocking |
Predict |
predict_sample_with_fixed_blocking_yield_intermediates |
Predict |
predict_sample_without_blocking |
Predict a whole sample at once. |
raise_for_non_blockwise_postprocessing |
Raises: |
raise_for_non_blockwise_preprocessing |
Raises: |
unload |
Free any device memory in use. |
Attributes:
| Name | Type | Description |
|---|---|---|
has_non_blockwise_postprocessing |
bool
|
|
has_non_blockwise_preprocessing |
bool
|
|
input_ids |
Sequence[MemberId]
|
|
model_descr |
AnyModelDescr
|
|
model_description |
AnyModelDescr
|
|
name |
|
|
output_ids |
Sequence[MemberId]
|
|
pad_mode |
|
Source code in src/bioimageio/core/_prediction_pipeline.py
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 | |
has_non_blockwise_postprocessing
property
¤
has_non_blockwise_postprocessing: bool
True if any postprocessing operators in the pipeline are not applicable blockwise.
has_non_blockwise_preprocessing
property
¤
has_non_blockwise_preprocessing: bool
True if any preprocessing operators in the pipeline are not applicable blockwise.
pad_mode
instance-attribute
¤
pad_mode = {} if isinstance(model_descr, v0_4.ModelDescr) else {(descr.id): (descr.pad or v0_5.SymmetricPadding()) for descr in (model_descr.inputs)}
__enter__
¤
__enter__()
Source code in src/bioimageio/core/_prediction_pipeline.py
496 497 498 | |
__exit__
¤
__exit__(exc_type, exc_val, exc_tb)
Source code in src/bioimageio/core/_prediction_pipeline.py
500 501 502 | |
apply_postprocessing
¤
apply_postprocessing(sample: Union[Sample, SampleBlock]) -> None
apply postprocessing in-place, also may updates samples stats
Source code in src/bioimageio/core/_prediction_pipeline.py
779 780 781 782 783 784 785 | |
apply_preprocessing
¤
apply_preprocessing(sample: Union[Sample, SampleBlock]) -> None
Apply preprocessing in-place, also may updates sample stats
Source code in src/bioimageio/core/_prediction_pipeline.py
748 749 750 751 752 753 754 755 756 | |
close
¤
close()
Permanently close the prediction pipeline and free any device memory in use. This makes the prediction pipeline unusable afterwards.
Source code in src/bioimageio/core/_prediction_pipeline.py
805 806 807 808 | |
get_output_sample_id
¤
get_output_sample_id(input_sample_id: SampleId)
Source code in src/bioimageio/core/_prediction_pipeline.py
613 614 615 616 617 618 619 | |
load
¤
load()
Prepare prediction pipeline for use.
Reusable model adapters may be loaded and unloaded multiple times, but currently not all model adapters cleanly unload and reload.
Note
For some model adapters loading is currently part of the constructor making them unusable after unloading.
Source code in src/bioimageio/core/_prediction_pipeline.py
787 788 789 790 791 792 793 794 795 796 | |
predict_sample_block
¤
predict_sample_block(sample_block: SampleBlock, skip_preprocessing: bool = False, skip_postprocessing: bool = False) -> SampleBlock
Predict a single sample block.
Note that this does not apply samplewise preprocessing or postprocessing steps, but only blockwise ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
SampleBlock
|
The sample block to predict on. |
required |
|
bool
|
If |
False
|
|
bool
|
If |
False
|
Source code in src/bioimageio/core/_prediction_pipeline.py
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 | |
predict_sample_with_blocking
¤
predict_sample_with_blocking(sample: Sample, skip_preprocessing: bool = False, skip_postprocessing: bool = False, ns: Optional[Union[v0_5.ParameterizedSize_N, Mapping[Tuple[MemberId, AxisId], v0_5.ParameterizedSize_N]]] = None, batch_size: Optional[int] = None) -> Sample
Predict a sample by predicting sample blocks.
Note: For fixed/known blocksizes use predict_sample_with_fixed_blocking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Sample
|
The sample to predict on. |
required |
|
bool
|
If |
False
|
|
bool
|
If |
False
|
|
Optional[Union[v0_5.ParameterizedSize_N, Mapping[Tuple[MemberId, AxisId], v0_5.ParameterizedSize_N]]]
|
Block size parameter(s) allows scaling the model's default input block size. Blocksize parameters are only applied to parameterized input axes, all other axis sizes are fixed/derived or (for output axes) data dependent. Unapplicable blocksize parameters are ignored. |
None
|
|
Optional[int]
|
Batch size to use for prediction. |
None
|
Source code in src/bioimageio/core/_prediction_pipeline.py
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 | |
predict_sample_with_blocking_yield_intermediates
¤
predict_sample_with_blocking_yield_intermediates(sample: Sample, skip_preprocessing: bool = False, skip_postprocessing: bool = False, ns: Optional[Union[v0_5.ParameterizedSize_N, Mapping[Tuple[MemberId, AxisId], v0_5.ParameterizedSize_N]]] = None, batch_size: Optional[int] = None) -> Tuple[int, Iterable[IntermediatePrediction]]
Predict sample by predicting sample blocks and yield intermediate predictions if no samplewise postprocessing is included.
Also yields intermediate predictions if there are preceding prediction pipelines (model inputs depend on another model's outputs).
For preceding prediction pipelines ns and batch_size are shared, but pre- and postprocessing are never skipped in preceding pipelines.
Returns:
| Type | Description |
|---|---|
Tuple[int, Iterable[IntermediatePrediction]]
|
Tuple of number of prediction steps and an iterator of predicted intermediate samples with the last predicted block, All samples, but the last one, are intermediate samples with more and more blocks predicted. In case samplewise postprocessing needs to be applied, no intermediate results are yielded, but only the final sample after all blocks are predicted and postprocessed. In case of preceding prediction pipelines (model inputs depend on another model's outputs), intermediate results initially do not include the final output tensors at all. |
Source code in src/bioimageio/core/_prediction_pipeline.py
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
predict_sample_with_fixed_blocking
¤
predict_sample_with_fixed_blocking(sample: Sample, input_block_shape: PerMember[PerAxis[int]], skip_preprocessing: bool = False, skip_postprocessing: bool = False) -> Sample
Predict sample with given input_block_shape.
Note
input_block_shapeis expected to be a valid input shape for the model.- Use
predict_sample_with_blockingif you want to control block sizes via generic block size parameters rather than fixed block shapes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Sample
|
The sample to predict on. |
required |
|
PerMember[PerAxis[int]]
|
Mapping of input member id to mapping of axis id to block size for that axis. |
required |
|
bool
|
If |
False
|
|
bool
|
If |
False
|
Source code in src/bioimageio/core/_prediction_pipeline.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
predict_sample_with_fixed_blocking_yield_intermediates
¤
predict_sample_with_fixed_blocking_yield_intermediates(sample: Sample, input_block_shape: PerMember[PerAxis[int]], *, skip_preprocessing: bool = False, skip_postprocessing: bool = False, fill_value: float = float('nan')) -> Tuple[int, Iterable[IntermediatePrediction]]
Predict sample by predicting sample blocks of input_block_shape and yield intermediate predictions if no samplewise postprocessing is included.
Also yields intermediate predictions if there are preceding prediction pipelines (model inputs depend on another model's outputs).
For preceding prediction pipelines input_block_shape and fill_value are shared, but pre- and postprocessing are never skipped in preceding pipelines.
Returns:
| Type | Description |
|---|---|
Tuple[int, Iterable[IntermediatePrediction]]
|
Tuple of number of prediction steps and an iterator of predicted intermediate samples with the last predicted block, All samples, but the last one, are intermediate samples with more and more blocks predicted. In case samplewise postprocessing needs to be applied, no intermediate results are yielded, but only the final sample after all blocks are predicted and postprocessed. In case of preceding prediction pipelines (model inputs depend on another model's outputs), intermediate results initially do not include the final output tensors at all. |
Source code in src/bioimageio/core/_prediction_pipeline.py
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 | |
predict_sample_without_blocking
¤
predict_sample_without_blocking(sample: Sample, skip_preprocessing: bool = False, skip_postprocessing: bool = False, skip_input_padding: bool = False, skip_output_cropping: bool = False) -> Sample
Predict a whole sample at once.
Note
The sample's tensor shapes have to match the model's input tensor description.
If that is not the case, consider predict_sample_with_blocking
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Sample
|
input sample |
required |
|
bool
|
if |
False
|
|
bool
|
if |
False
|
|
bool
|
if |
False
|
|
bool
|
if |
False
|
Source code in src/bioimageio/core/_prediction_pipeline.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | |
raise_for_non_blockwise_postprocessing
¤
raise_for_non_blockwise_postprocessing()
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
if there are any non-blockwise postprocessing operators in the pipeline |
Source code in src/bioimageio/core/_prediction_pipeline.py
537 538 539 540 541 542 | |
raise_for_non_blockwise_preprocessing
¤
raise_for_non_blockwise_preprocessing()
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
if there are any non-blockwise preprocessing operators in the pipeline |
Source code in src/bioimageio/core/_prediction_pipeline.py
530 531 532 533 534 535 | |
unload
¤
unload()
Free any device memory in use.
Note
Currently prediction pipeline becomes unusable after unloading.
Source code in src/bioimageio/core/_prediction_pipeline.py
798 799 800 801 802 803 | |
RemotePredictionPipeline
¤
RemotePredictionPipeline(model_descr: AnyModelDescr, *, server: str, default_blocksize_parameter: BlocksizeParameter, default_batch_size: int, preceding_prediction_pipelines: Optional[Sequence[Union[PredictionPipeline, RemotePredictionPipeline]]] = None)
Bases: _PredictionPipelineBase
flowchart TD
bioimageio.core.RemotePredictionPipeline[RemotePredictionPipeline]
bioimageio.core._prediction_pipeline._PredictionPipelineBase[_PredictionPipelineBase]
bioimageio.core._prediction_pipeline._PredictionPipelineBase --> bioimageio.core.RemotePredictionPipeline
click bioimageio.core.RemotePredictionPipeline href "" "bioimageio.core.RemotePredictionPipeline"
click bioimageio.core._prediction_pipeline._PredictionPipelineBase href "" "bioimageio.core._prediction_pipeline._PredictionPipelineBase"
Abstract base class for fully remote prediction pipelines.
A ("local") PredictionPipeline may also use a RemoteModelAdapter for remote model inference, but it may
still apply local preprocessing and postprocessing steps.
In contrast, a RemotePredictionPipeline is designed for the case where all steps including preprocessing and
postprocessing are performed remotely.
-
API Reference
corecreate_remote_prediction_pipeline
Methods:
| Name | Description |
|---|---|
predict_sample_block |
Predict a single sample block. |
predict_sample_with_blocking |
Predict a sample by predicting sample blocks. |
predict_sample_with_blocking_yield_intermediates |
Predict |
predict_sample_with_fixed_blocking |
Predict |
predict_sample_with_fixed_blocking_yield_intermediates |
Predict |
predict_sample_without_blocking |
Predict a whole sample at once. |
Attributes:
| Name | Type | Description |
|---|---|---|
input_ids |
Sequence[MemberId]
|
|
model_descr |
AnyModelDescr
|
|
model_description |
AnyModelDescr
|
|
output_ids |
Sequence[MemberId]
|
|
pad_mode |
|
|
server |
str
|
|
Source code in src/bioimageio/core/_prediction_pipeline.py
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 | |
pad_mode
instance-attribute
¤
pad_mode = {} if isinstance(model_descr, v0_4.ModelDescr) else {(descr.id): (descr.pad or v0_5.SymmetricPadding()) for descr in (model_descr.inputs)}
predict_sample_block
abstractmethod
¤
predict_sample_block(sample_block: SampleBlock, skip_preprocessing: bool = False, skip_postprocessing: bool = False) -> SampleBlock
Predict a single sample block.
Note that this does not apply samplewise preprocessing or postprocessing steps, but only blockwise ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
SampleBlock
|
The sample block to predict on. |
required |
|
bool
|
If |
False
|
|
bool
|
If |
False
|
Source code in src/bioimageio/core/_prediction_pipeline.py
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
predict_sample_with_blocking
¤
predict_sample_with_blocking(sample: Sample, skip_preprocessing: bool = False, skip_postprocessing: bool = False, ns: Optional[Union[v0_5.ParameterizedSize_N, Mapping[Tuple[MemberId, AxisId], v0_5.ParameterizedSize_N]]] = None, batch_size: Optional[int] = None) -> Sample
Predict a sample by predicting sample blocks.
Note: For fixed/known blocksizes use predict_sample_with_fixed_blocking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Sample
|
The sample to predict on. |
required |
|
bool
|
If |
False
|
|
bool
|
If |
False
|
|
Optional[Union[v0_5.ParameterizedSize_N, Mapping[Tuple[MemberId, AxisId], v0_5.ParameterizedSize_N]]]
|
Block size parameter(s) allows scaling the model's default input block size. Blocksize parameters are only applied to parameterized input axes, all other axis sizes are fixed/derived or (for output axes) data dependent. Unapplicable blocksize parameters are ignored. |
None
|
|
Optional[int]
|
Batch size to use for prediction. |
None
|
Source code in src/bioimageio/core/_prediction_pipeline.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | |
predict_sample_with_blocking_yield_intermediates
¤
predict_sample_with_blocking_yield_intermediates(sample: Sample, skip_preprocessing: bool = False, skip_postprocessing: bool = False, ns: Optional[Union[v0_5.ParameterizedSize_N, Mapping[Tuple[MemberId, AxisId], v0_5.ParameterizedSize_N]]] = None, batch_size: Optional[int] = None) -> Tuple[int, Iterable[IntermediatePrediction]]
Predict sample by predicting sample blocks and yield intermediate predictions if no samplewise postprocessing is included.
Also yields intermediate predictions if there are preceding prediction pipelines (model inputs depend on another model's outputs).
For preceding prediction pipelines ns and batch_size are shared, but pre- and postprocessing are never skipped in preceding pipelines.
Returns:
| Type | Description |
|---|---|
Tuple[int, Iterable[IntermediatePrediction]]
|
Tuple of number of prediction steps and an iterator of predicted intermediate samples with the last predicted block, All samples, but the last one, are intermediate samples with more and more blocks predicted. In case samplewise postprocessing needs to be applied, no intermediate results are yielded, but only the final sample after all blocks are predicted and postprocessed. In case of preceding prediction pipelines (model inputs depend on another model's outputs), intermediate results initially do not include the final output tensors at all. |
Source code in src/bioimageio/core/_prediction_pipeline.py
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
predict_sample_with_fixed_blocking
¤
predict_sample_with_fixed_blocking(sample: Sample, input_block_shape: PerMember[PerAxis[int]], skip_preprocessing: bool = False, skip_postprocessing: bool = False) -> Sample
Predict sample with given input_block_shape.
Note
input_block_shapeis expected to be a valid input shape for the model.- Use
predict_sample_with_blockingif you want to control block sizes via generic block size parameters rather than fixed block shapes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Sample
|
The sample to predict on. |
required |
|
PerMember[PerAxis[int]]
|
Mapping of input member id to mapping of axis id to block size for that axis. |
required |
|
bool
|
If |
False
|
|
bool
|
If |
False
|
Source code in src/bioimageio/core/_prediction_pipeline.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
predict_sample_with_fixed_blocking_yield_intermediates
¤
predict_sample_with_fixed_blocking_yield_intermediates(sample: Sample, input_block_shape: PerMember[PerAxis[int]], *, skip_preprocessing: bool = False, skip_postprocessing: bool = False, fill_value: float = float('nan')) -> Tuple[int, Iterable[IntermediatePrediction]]
Predict sample by predicting sample blocks of input_block_shape and yield intermediate predictions if no samplewise postprocessing is included.
Also yields intermediate predictions if there are preceding prediction pipelines (model inputs depend on another model's outputs).
For preceding prediction pipelines input_block_shape and fill_value are shared, but pre- and postprocessing are never skipped in preceding pipelines.
Returns:
| Type | Description |
|---|---|
Tuple[int, Iterable[IntermediatePrediction]]
|
Tuple of number of prediction steps and an iterator of predicted intermediate samples with the last predicted block, All samples, but the last one, are intermediate samples with more and more blocks predicted. In case samplewise postprocessing needs to be applied, no intermediate results are yielded, but only the final sample after all blocks are predicted and postprocessed. In case of preceding prediction pipelines (model inputs depend on another model's outputs), intermediate results initially do not include the final output tensors at all. |
Source code in src/bioimageio/core/_prediction_pipeline.py
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 | |
predict_sample_without_blocking
¤
predict_sample_without_blocking(sample: Sample, skip_preprocessing: bool = False, skip_postprocessing: bool = False, skip_input_padding: bool = False, skip_output_cropping: bool = False) -> Sample
Predict a whole sample at once.
Note
The sample's tensor shapes have to match the model's input tensor description.
If that is not the case, consider predict_sample_with_blocking
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Sample
|
input sample |
required |
|
bool
|
if |
False
|
|
bool
|
if |
False
|
|
bool
|
if |
False
|
|
bool
|
if |
False
|
Source code in src/bioimageio/core/_prediction_pipeline.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | |
Sample
dataclass
¤
A dataset sample.
A Sample has members, which allows to combine multiple tensors into a single
sample.
For example a Sample from a dataset with masked images may contain a
MemberId("raw") and MemberId("mask") image.
- API Reference
- API Reference
Methods:
| Name | Description |
|---|---|
__getitem__ |
|
as_arrays |
Return sample as dictionary of arrays. |
as_single_block |
|
assign_batch_multi_index |
Return a new sample with the batch multi-index assigned to all sample members. |
from_blocks |
Create a |
from_blocks_yield_intermediates |
Create a |
pad |
Convenience method to pad sample members. |
set_block |
Set values of |
split_into_blocks |
|
transpose |
Return a new sample with transposed sample members. |
unstack_batch_multi_index |
Unstack the batch multi-index of all sample members. |
Attributes:
| Name | Type | Description |
|---|---|---|
batch_multi_index |
Optional['pd.MultiIndex']
|
Return the batch multi-index of the sample, if it has one. |
id |
SampleId
|
Identifies the |
members |
Dict[MemberId, Tensor]
|
The sample's tensors |
shape |
PerMember[PerAxis[int]]
|
|
stat |
Stat
|
Sample and dataset statistics |
batch_multi_index
property
¤
batch_multi_index: Optional['pd.MultiIndex']
Return the batch multi-index of the sample, if it has one.
Returns:
| Type | Description |
|---|---|
Optional['pd.MultiIndex']
|
The batch multi-index of the sample, or |
id
instance-attribute
¤
id: SampleId
Identifies the Sample within the dataset -- typically a number or a string.
__getitem__
¤
__getitem__(key: PerMember[Union[SliceInfo, slice, int, PerAxis[Union[SliceInfo, slice, int]], Tensor, xr.DataArray]]) -> Self
Source code in src/bioimageio/core/sample.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
as_arrays
¤
as_arrays() -> Dict[MemberId, NDArray[Any]]
Return sample as dictionary of arrays.
Source code in src/bioimageio/core/sample.py
137 138 139 | |
as_single_block
¤
Source code in src/bioimageio/core/sample.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | |
assign_batch_multi_index
¤
assign_batch_multi_index(multi_index: 'pd.MultiIndex') -> Self
Return a new sample with the batch multi-index assigned to all sample members.
Raises:
| Type | Description |
|---|---|
ValueError
|
If not all sample members have a batch dimension. |
Source code in src/bioimageio/core/sample.py
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 | |
from_blocks
classmethod
¤
from_blocks(sample_blocks: Iterable[SampleBlock], *, fill_value: float = float('nan')) -> Self
Create a Sample from an iterable of SampleBlocks.
Note
All sample blocks must have the same sample_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Iterable[SampleBlock]
|
The blocks to create the sample from. |
required |
|
float
|
The value to fill missing values with (default: |
float('nan')
|
Source code in src/bioimageio/core/sample.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
from_blocks_yield_intermediates
classmethod
¤
from_blocks_yield_intermediates(sample_blocks: Iterable[SampleBlock], *, fill_value: float = float('nan'))
Create a Sample from an iterable of SampleBlocks, yielding the intermediate sample after each block.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Iterable[SampleBlock]
|
The blocks to create the sample from. |
required |
|
float
|
The value to fill missing values with (default: |
float('nan')
|
Source code in src/bioimageio/core/sample.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | |
pad
¤
pad(pad_width: PerMember[PerAxis[Union[int, PadWidthLike]]], mode: Union[PerMember[PadMode], PadMode]) -> Self
Convenience method to pad sample members.
Source code in src/bioimageio/core/sample.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | |
set_block
¤
set_block(block: SampleBlock) -> None
Set values of block.
Note
- Updates only existing sample members (extra block members are ignored)
- Ignores missing block members (i.e. members in the sample but not in the block are not modified)
Source code in src/bioimageio/core/sample.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | |
split_into_blocks
¤
split_into_blocks(block_shapes: PerMember[PerAxis[int]], halo: PerMember[PerAxis[HaloLike]], pad_mode: Union[PadMode, PerMember[PadMode]], broadcast: bool = False) -> Tuple[TotalNumberOfBlocks, Iterable[SampleBlockWithOrigin]]
Source code in src/bioimageio/core/sample.py
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
transpose
¤
transpose(axes: PerMember[Sequence[AxisId]], *, extra_dims: Literal['raise', 'squeeze', 'stack', 'squeeze_or_stack'] = 'raise', missing_dims: Literal['raise', 'expand', 'unstack', 'unstack_or_expand'] = 'raise') -> Self
Return a new sample with transposed sample members.
Raises:
| Type | Description |
|---|---|
ValueError
|
If not all batch dimensions have the same length after transposition (and possibly stacking/unstacking extra dimensions). |
Source code in src/bioimageio/core/sample.py
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | |
unstack_batch_multi_index
¤
unstack_batch_multi_index(*, errors: Literal['raise', 'ignore'] = 'raise') -> Self
Unstack the batch multi-index of all sample members.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Literal['raise', 'ignore']
|
Whether to raise an error if a member does not have a batch multi-index. Default is "raise". |
'raise'
|
Returns:
| Type | Description |
|---|---|
Self
|
A new |
Source code in src/bioimageio/core/sample.py
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | |
SampleBlock
dataclass
¤
Bases: SampleBlockBase[Block]
flowchart TD
bioimageio.core.SampleBlock[SampleBlock]
bioimageio.core.sample.SampleBlockBase[SampleBlockBase]
bioimageio.core.sample.SampleBlockBase --> bioimageio.core.SampleBlock
click bioimageio.core.SampleBlock href "" "bioimageio.core.SampleBlock"
click bioimageio.core.sample.SampleBlockBase href "" "bioimageio.core.sample.SampleBlockBase"
A block of a dataset sample
-
API Reference
sampleSampleBlockWithOrigin
Methods:
| Name | Description |
|---|---|
as_sample |
Convert this sample block to a |
from_meta |
|
get_meta |
|
get_transformed_meta |
|
Attributes:
| Name | Type | Description |
|---|---|---|
block_index |
BlockIndex
|
the n-th block of the sample |
blocks |
Dict[MemberId, Block]
|
Individual tensor blocks comprising this sample block |
blocks_in_sample |
TotalNumberOfBlocks
|
total number of blocks in the sample |
inner_shape |
PerMember[PerAxis[int]]
|
|
members |
PerMember[Tensor]
|
the sample block's tensors |
sample_id |
SampleId
|
identifier for the sample within its dataset |
sample_shape |
PerMemberAnno[PerAxis[int]]
|
the sample shape this block represents a part of |
shape |
PerMember[PerAxis[int]]
|
|
stat |
Stat
|
computed statistics |
blocks
instance-attribute
¤
Individual tensor blocks comprising this sample block
blocks_in_sample
instance-attribute
¤
blocks_in_sample: TotalNumberOfBlocks
total number of blocks in the sample
sample_shape
instance-attribute
¤
sample_shape: PerMemberAnno[PerAxis[int]]
the sample shape this block represents a part of
as_sample
¤
as_sample() -> Sample
Convert this sample block to a Sample with the shape of this block.
Note
If you want to convert one or more sample block to a sample with the shape of the original, whole sample,
use Sample.from_blocks() instead.
Source code in src/bioimageio/core/sample.py
591 592 593 594 595 596 597 598 599 600 601 602 | |
from_meta
classmethod
¤
from_meta(meta: SampleBlockMeta, data: PerMember[Tensor], stat: Stat) -> Self
Source code in src/bioimageio/core/sample.py
567 568 569 570 571 572 573 574 575 576 577 578 579 580 | |
get_meta
¤
get_meta() -> SampleBlockMeta
Source code in src/bioimageio/core/sample.py
582 583 584 585 586 587 588 589 | |
get_transformed_meta
¤
get_transformed_meta(new_axes: PerMember[PerAxis[Union[LinearSampleAxisTransform, int]]]) -> SampleBlockMeta
Source code in src/bioimageio/core/sample.py
556 557 558 559 560 561 562 563 564 565 | |
SampleBlockMeta
¤
Bases: SampleBlockBase[BlockMeta]
flowchart TD
bioimageio.core.SampleBlockMeta[SampleBlockMeta]
bioimageio.core.sample.SampleBlockBase[SampleBlockBase]
bioimageio.core.sample.SampleBlockBase --> bioimageio.core.SampleBlockMeta
click bioimageio.core.SampleBlockMeta href "" "bioimageio.core.SampleBlockMeta"
click bioimageio.core.sample.SampleBlockBase href "" "bioimageio.core.sample.SampleBlockBase"
Meta data of a dataset sample block
Methods:
| Name | Description |
|---|---|
get_transformed |
|
with_data |
|
Attributes:
| Name | Type | Description |
|---|---|---|
block_index |
BlockIndex
|
the n-th block of the sample |
blocks |
PerMemberAnno[BlockT]
|
Individual tensor blocks comprising this sample block |
blocks_in_sample |
TotalNumberOfBlocks
|
total number of blocks in the sample |
inner_shape |
PerMember[PerAxis[int]]
|
|
sample_id |
SampleId
|
identifier for the sample within its dataset |
sample_shape |
PerMemberAnno[PerAxis[int]]
|
the sample shape this block represents a part of |
shape |
PerMember[PerAxis[int]]
|
|
blocks
instance-attribute
¤
blocks: PerMemberAnno[BlockT]
Individual tensor blocks comprising this sample block
blocks_in_sample
instance-attribute
¤
blocks_in_sample: TotalNumberOfBlocks
total number of blocks in the sample
sample_shape
instance-attribute
¤
sample_shape: PerMemberAnno[PerAxis[int]]
the sample shape this block represents a part of
get_transformed
¤
get_transformed(new_axes: PerMember[PerAxis[Union[LinearSampleAxisTransform, int]]]) -> Self
Source code in src/bioimageio/core/sample.py
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 | |
with_data
¤
with_data(data: PerMember[Tensor], *, stat: Stat) -> SampleBlock
Source code in src/bioimageio/core/sample.py
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 | |
SampleSerializer
¤
Bases: ABC, Generic[SerializedSampleBlockType]
flowchart TD
bioimageio.core.SampleSerializer[SampleSerializer]
click bioimageio.core.SampleSerializer href "" "bioimageio.core.SampleSerializer"
Methods:
| Name | Description |
|---|---|
deserialize_sample |
|
deserialize_sample_block |
Deserialize a sample block into a new sample or merge it into |
serialize_sample |
Serialize a sample as a single block |
serialize_sample_block |
|
serialize_sample_blockwise |
Split a sample into blocks according to the model's input specifications and |
serialize_sample_with_fixed_blocking |
|
deserialize_sample
classmethod
¤
deserialize_sample(serialized: Iterable[SerializedSampleBlockType], fill_value: float = float('nan')) -> Sample
Source code in src/bioimageio/core/_sample_serializer.py
29 30 31 32 33 34 35 36 37 | |
deserialize_sample_block
abstractmethod
staticmethod
¤
deserialize_sample_block(serialized: SerializedSampleBlockType) -> SampleBlock
Deserialize a sample block into a new sample or merge it into output_sample if provided.
Source code in src/bioimageio/core/_sample_serializer.py
82 83 84 85 | |
serialize_sample
classmethod
¤
serialize_sample(sample: Sample) -> Tuple[SerializedSampleBlockType]
Serialize a sample as a single block
Source code in src/bioimageio/core/_sample_serializer.py
21 22 23 24 25 26 27 | |
serialize_sample_block
abstractmethod
staticmethod
¤
serialize_sample_block(sample_block: SampleBlock) -> SerializedSampleBlockType
Source code in src/bioimageio/core/_sample_serializer.py
76 77 78 79 80 | |
serialize_sample_blockwise
¤
serialize_sample_blockwise(sample: Sample, *, model: v0_5.ModelDescr, blocksize_parameter: int, batch_size: int = 1) -> Iterable[SerializedSampleBlockType]
Split a sample into blocks according to the model's input specifications and blocksize_parameter and serialize each block.
Source code in src/bioimageio/core/_sample_serializer.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | |
serialize_sample_with_fixed_blocking
classmethod
¤
serialize_sample_with_fixed_blocking(sample: Sample, *, block_shapes: PerMember[PerAxis[int]], halo: PerMember[PerAxis[HaloLike]], pad_mode: Union[PadMode, PerMember[PadMode]] = 'symmetric') -> Iterable[SerializedSampleBlockType]
Source code in src/bioimageio/core/_sample_serializer.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
Settings
¤
Bases: SpecSettings
flowchart TD
bioimageio.core.Settings[Settings]
bioimageio.spec._internal._settings.Settings[Settings]
bioimageio.spec._internal._settings.Settings --> bioimageio.core.Settings
click bioimageio.core.Settings href "" "bioimageio.core.Settings"
click bioimageio.spec._internal._settings.Settings href "" "bioimageio.spec._internal._settings.Settings"
environment variables for bioimageio.spec and bioimageio.core
Methods:
| Name | Description |
|---|---|
__setattr__ |
|
Attributes:
| Name | Type | Description |
|---|---|---|
CI |
Annotated[Union[bool, str], Field(alias=CI)]
|
Wether or not the execution happens in a continuous integration (CI) environment. |
allow_pickle |
bool
|
Sets the |
cache_path |
Path
|
bioimageio cache location |
collection_config_url |
str
|
URL to the bioimageio collection config |
collection_http_pattern |
str
|
A pattern to map bioimageio IDs to bioimageio.yaml URLs. |
collection_index_url |
str
|
URL to the bioimageio collection index |
disk_cache |
|
|
github_auth |
|
|
github_token |
Optional[str]
|
GitHub token for API requests |
github_username |
Optional[str]
|
GitHub username for API requests |
gradio_server |
Optional[str]
|
URL or Hugging Face space name to connect to with the remote gradio model adapter or remote gradio prediction pipeline. |
gradio_server_model_cache_max_memory |
str
|
Max memory to use for model caching in the gradio server for prediction pipelines using the gradio backend. |
gradio_server_model_cache_max_size |
int
|
Max number of models to cache in the gradio server for prediction pipelines using the gradio backend. |
http_timeout |
float
|
Timeout in seconds for http requests. |
huggingface_http_pattern |
str
|
A pattern to map huggingface repo IDs to bioimageio.yaml URLs. |
hypha_upload |
str
|
URL to the upload endpoint for bioimageio resources. |
hypha_upload_token |
Optional[str]
|
Hypha API token to use for uploads. |
id_map |
str
|
URL to bioimageio id_map.json to resolve resource IDs. |
id_map_draft |
str
|
URL to bioimageio id_map_draft.json to resolve draft IDs ending with '/draft'. |
keras_backend |
Annotated[Literal['torch', 'tensorflow', 'jax'], Field(alias=KERAS_BACKEND)]
|
|
log_warnings |
bool
|
Log validation warnings to console. |
model_config |
|
|
perform_io_checks |
bool
|
Wether or not to perform validation that requires file io, |
pytorch_enable_mps_fallback |
Annotated[Optional[bool], Field(alias=PYTORCH_ENABLE_MPS_FALLBACK)]
|
|
resolve_draft |
bool
|
Flag to resolve draft resource versions following the pattern |
user_agent |
Optional[str]
|
user agent for http requests |
CI
class-attribute
instance-attribute
¤
Wether or not the execution happens in a continuous integration (CI) environment.
allow_pickle
class-attribute
instance-attribute
¤
allow_pickle: bool = False
Sets the allow_pickle argument for numpy.load()
cache_path
class-attribute
instance-attribute
¤
cache_path: Path = Path(platformdirs.user_cache_dir('bioimageio'))
bioimageio cache location
collection_config_url
class-attribute
instance-attribute
¤
collection_config_url: str = 'https://bioimage-io.github.io/collection/bioimageio_collection_config.json'
URL to the bioimageio collection config
collection_http_pattern
class-attribute
instance-attribute
¤
collection_http_pattern: str = 'https://hypha.aicell.io/bioimage-io/artifacts/{bioimageio_id}/files/rdf.yaml'
A pattern to map bioimageio IDs to bioimageio.yaml URLs.
Notes:
- '{bioimageio_id}' is replaced with user query,
e.g. "affable-shark" when calling load_description("affable-shark").
- This method takes precedence over resolving via id_map.
- If this endpoints fails, we fall back to id_map.
collection_index_url
class-attribute
instance-attribute
¤
collection_index_url: str = 'https://bioimage-io.github.io/collection/index.json'
URL to the bioimageio collection index
github_token
class-attribute
instance-attribute
¤
github_token: Optional[str] = None
GitHub token for API requests
github_username
class-attribute
instance-attribute
¤
github_username: Optional[str] = None
GitHub username for API requests
gradio_server
class-attribute
instance-attribute
¤
gradio_server: Optional[str] = None
URL or Hugging Face space name to connect to with the remote gradio model adapter or remote gradio prediction pipeline.
Example: "bioimage-io/bioimage-io-gradio-server"
gradio_server_model_cache_max_memory
class-attribute
instance-attribute
¤
gradio_server_model_cache_max_memory: str = '40GB'
Max memory to use for model caching in the gradio server for prediction pipelines using the gradio backend.
gradio_server_model_cache_max_size
class-attribute
instance-attribute
¤
gradio_server_model_cache_max_size: int = 10
Max number of models to cache in the gradio server for prediction pipelines using the gradio backend.
http_timeout
class-attribute
instance-attribute
¤
http_timeout: float = 10.0
Timeout in seconds for http requests.
huggingface_http_pattern
class-attribute
instance-attribute
¤
huggingface_http_pattern: str = 'https://huggingface.co/{repo_id}/resolve/{branch}/package/bioimageio.yaml'
A pattern to map huggingface repo IDs to bioimageio.yaml URLs.
Notes:
- Used for loading source strings of the form "huggingface/{user_or_org}/{resource_id}[/{version}]"
- example use: load_description("huggingface/fynnbe/ambitious-sloth/1.3")
- A given version {version} is mapped to a branch name "v{version}", e.g. "v1.3".
- If no version is provided the "main" branch is used.
- This method takes precedence over resolving via id_map.
- If this endpoints fails, we fall back to id_map.
hypha_upload
class-attribute
instance-attribute
¤
hypha_upload: str = 'https://hypha.aicell.io/public/services/artifact-manager/create'
URL to the upload endpoint for bioimageio resources.
hypha_upload_token
class-attribute
instance-attribute
¤
hypha_upload_token: Optional[str] = None
Hypha API token to use for uploads.
By setting this token you agree to our terms of service at https://bioimage.io/#/toc.
How to obtain a token
- Login to https://bioimage.io
- Generate a new token at https://bioimage.io/#/api?tab=hypha-rpc
id_map
class-attribute
instance-attribute
¤
id_map: str = 'https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/id_map.json'
URL to bioimageio id_map.json to resolve resource IDs.
id_map_draft
class-attribute
instance-attribute
¤
id_map_draft: str = 'https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/id_map_draft.json'
URL to bioimageio id_map_draft.json to resolve draft IDs ending with '/draft'.
keras_backend
class-attribute
instance-attribute
¤
keras_backend: Annotated[Literal['torch', 'tensorflow', 'jax'], Field(alias=KERAS_BACKEND)] = 'torch'
log_warnings
class-attribute
instance-attribute
¤
log_warnings: bool = True
Log validation warnings to console.
model_config
class-attribute
instance-attribute
¤
model_config = SettingsConfigDict(env_prefix='BIOIMAGEIO_', env_file='.env', env_file_encoding='utf-8')
perform_io_checks
class-attribute
instance-attribute
¤
perform_io_checks: bool = True
Wether or not to perform validation that requires file io, e.g. downloading a remote files.
Existence of any local absolute file paths is still being checked.
pytorch_enable_mps_fallback
class-attribute
instance-attribute
¤
pytorch_enable_mps_fallback: Annotated[Optional[bool], Field(alias=PYTORCH_ENABLE_MPS_FALLBACK)] = None
resolve_draft
class-attribute
instance-attribute
¤
resolve_draft: bool = True
Flag to resolve draft resource versions following the pattern
Note that anyone may stage a new draft and that such a draft version may not have been reviewed yet. Set this flag to False to avoid this potential security risk and disallow loading draft versions.
user_agent
class-attribute
instance-attribute
¤
user_agent: Optional[str] = None
user agent for http requests
__setattr__
¤
__setattr__(name: str, value: Any)
Source code in bioimageio/spec/_internal/_settings.py
31 32 33 34 35 36 37 38 39 | |
Tensor
¤
Bases: MagicTensorOpsMixin
flowchart TD
bioimageio.core.Tensor[Tensor]
bioimageio.core._magic_tensor_ops.MagicTensorOpsMixin[MagicTensorOpsMixin]
bioimageio.core._magic_tensor_ops.MagicTensorOpsMixin --> bioimageio.core.Tensor
click bioimageio.core.Tensor href "" "bioimageio.core.Tensor"
click bioimageio.core._magic_tensor_ops.MagicTensorOpsMixin href "" "bioimageio.core._magic_tensor_ops.MagicTensorOpsMixin"
A wrapper around an xr.DataArray for better integration with bioimageio.spec and improved type annotations.
-
API Reference
ioload_tensor
Methods:
| Name | Description |
|---|---|
__abs__ |
|
__add__ |
|
__and__ |
|
__array__ |
|
__eq__ |
|
__floordiv__ |
|
__ge__ |
|
__getitem__ |
|
__gt__ |
|
__iadd__ |
|
__iand__ |
|
__ifloordiv__ |
|
__ilshift__ |
|
__imod__ |
|
__imul__ |
|
__invert__ |
|
__ior__ |
|
__ipow__ |
|
__irshift__ |
|
__isub__ |
|
__iter__ |
|
__itruediv__ |
|
__ixor__ |
|
__le__ |
|
__len__ |
|
__lshift__ |
|
__lt__ |
|
__mod__ |
|
__mul__ |
|
__ne__ |
|
__neg__ |
|
__or__ |
|
__pos__ |
|
__pow__ |
|
__radd__ |
|
__rand__ |
|
__repr__ |
|
__rfloordiv__ |
|
__rmod__ |
|
__rmul__ |
|
__ror__ |
|
__rpow__ |
|
__rshift__ |
|
__rsub__ |
|
__rtruediv__ |
|
__rxor__ |
|
__setitem__ |
|
__sub__ |
|
__truediv__ |
|
__xor__ |
|
argmax |
|
argsort |
|
assign_batch_multi_index |
Set the batch multi-index for this tensor. |
astype |
Return tensor cast to |
clip |
Return a tensor whose values are limited to [min, max]. |
conj |
|
conjugate |
|
crop_to |
crop to match |
expand_dims |
|
from_numpy |
create a |
from_xarray |
create a |
item |
Copy a tensor element to a standard Python scalar and return it. |
mean |
|
pad |
|
pad_to |
pad |
quantile |
|
resize_to |
return cropped/padded tensor with |
round |
|
std |
|
sum |
Reduce this Tensor's data by applying sum along some dimension(s). |
to_numpy |
Return the data of this tensor as a numpy array. |
transpose |
Return a transposed tensor, missing axes are expanded (if |
unstack_batch_multi_index |
Unstack the batch multi-index of this tensor. |
var |
|
Attributes:
| Name | Type | Description |
|---|---|---|
__hash__ |
None
|
|
__slots__ |
|
|
data |
|
|
dims |
Tuple of dimension names associated with this tensor. |
|
dtype |
DTypeStr
|
|
ndim |
Number of tensor dimensions. |
|
shape |
Tuple of tensor axes lengths |
|
shape_tuple |
Tuple of tensor axes lengths |
|
size |
Number of elements in the tensor. |
|
sizes |
Ordered, immutable mapping from axis ids to axis lengths. |
|
tagged_shape |
(alias for |
Source code in src/bioimageio/core/tensor.py
76 77 78 79 80 81 82 83 84 85 86 87 88 | |
size
property
¤
size
Number of elements in the tensor.
Equal to math.prod(tensor.shape), i.e., the product of the tensors’ dimensions.
tagged_shape
property
¤
tagged_shape
(alias for sizes) Ordered, immutable mapping from axis ids to lengths.
__abs__
¤
__abs__() -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
175 176 | |
__add__
¤
__add__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
31 32 | |
__and__
¤
__and__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
52 53 | |
__array__
¤
__array__(dtype: DTypeLike = None)
Source code in src/bioimageio/core/tensor.py
93 94 | |
__eq__
¤
__eq__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
79 80 81 82 83 | |
__floordiv__
¤
__floordiv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
46 47 | |
__ge__
¤
__ge__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
76 77 | |
__getitem__
¤
__getitem__(key: Union[SliceInfo, slice, int, PerAxis[Union[SliceInfo, slice, int]], Tensor, xr.DataArray]) -> Self
Source code in src/bioimageio/core/tensor.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | |
__gt__
¤
__gt__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
73 74 | |
__iadd__
¤
__iadd__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
130 131 | |
__iand__
¤
__iand__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
151 152 | |
__ifloordiv__
¤
__ifloordiv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
145 146 | |
__ilshift__
¤
__ilshift__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
160 161 | |
__imod__
¤
__imod__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
148 149 | |
__imul__
¤
__imul__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
136 137 | |
__invert__
¤
__invert__() -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
178 179 | |
__ior__
¤
__ior__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
157 158 | |
__ipow__
¤
__ipow__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
139 140 | |
__irshift__
¤
__irshift__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
163 164 | |
__isub__
¤
__isub__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
133 134 | |
__iter__
¤
__iter__() -> Iterator[Any]
Source code in src/bioimageio/core/tensor.py
143 144 145 146 | |
__itruediv__
¤
__itruediv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
142 143 | |
__ixor__
¤
__ixor__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
154 155 | |
__le__
¤
__le__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
70 71 | |
__len__
¤
__len__() -> int
Source code in src/bioimageio/core/tensor.py
136 137 | |
__lshift__
¤
__lshift__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
61 62 | |
__lt__
¤
__lt__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
67 68 | |
__mod__
¤
__mod__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
49 50 | |
__mul__
¤
__mul__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
37 38 | |
__ne__
¤
__ne__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
85 86 87 88 89 | |
__neg__
¤
__neg__() -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
169 170 | |
__or__
¤
__or__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
58 59 | |
__pos__
¤
__pos__() -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
172 173 | |
__pow__
¤
__pow__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
40 41 | |
__radd__
¤
__radd__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
95 96 | |
__rand__
¤
__rand__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
116 117 | |
__repr__
¤
__repr__() -> str
Source code in src/bioimageio/core/tensor.py
90 91 | |
__rfloordiv__
¤
__rfloordiv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
110 111 | |
__rmod__
¤
__rmod__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
113 114 | |
__rmul__
¤
__rmul__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
101 102 | |
__ror__
¤
__ror__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
122 123 | |
__rpow__
¤
__rpow__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
104 105 | |
__rshift__
¤
__rshift__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
64 65 | |
__rsub__
¤
__rsub__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
98 99 | |
__rtruediv__
¤
__rtruediv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
107 108 | |
__rxor__
¤
__rxor__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
119 120 | |
__setitem__
¤
__setitem__(key: Union[PerAxis[Union[SliceInfo, slice]], Tensor, xr.DataArray], value: Union[Tensor, xr.DataArray, float, int]) -> None
Source code in src/bioimageio/core/tensor.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
__sub__
¤
__sub__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
34 35 | |
__truediv__
¤
__truediv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
43 44 | |
__xor__
¤
__xor__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
55 56 | |
argmax
¤
argmax() -> Mapping[AxisId, int]
Source code in src/bioimageio/core/tensor.py
283 284 285 286 | |
argsort
¤
argsort(*args: Any, **kwargs: Any) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
188 189 190 191 192 193 | |
assign_batch_multi_index
¤
assign_batch_multi_index(multi_index: 'pd.MultiIndex') -> Self
Set the batch multi-index for this tensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
'pd.MultiIndex'
|
The multi-index to set. |
required |
Source code in src/bioimageio/core/tensor.py
492 493 494 495 496 497 498 499 500 501 502 503 504 505 | |
astype
¤
astype(dtype: DTypeStr, *, copy: bool = False)
Return tensor cast to dtype
note: if dtype is already satisfied copy if copy
Source code in src/bioimageio/core/tensor.py
288 289 290 291 292 | |
clip
¤
clip(min: Optional[float] = None, max: Optional[float] = None)
Return a tensor whose values are limited to [min, max]. At least one of max or min must be given.
Source code in src/bioimageio/core/tensor.py
294 295 296 297 | |
conj
¤
conj(*args: Any, **kwargs: Any) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
195 196 197 198 199 200 | |
conjugate
¤
conjugate(*args: Any, **kwargs: Any) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
202 203 204 205 206 207 | |
crop_to
¤
crop_to(sizes: PerAxis[int], crop_where: Union[CropWhere, PerAxis[CropWhere]] = 'left_and_right') -> Self
crop to match sizes
Source code in src/bioimageio/core/tensor.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |
expand_dims
¤
Source code in src/bioimageio/core/tensor.py
344 345 | |
from_numpy
classmethod
¤
create a Tensor from a numpy array
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
NDArray[Any]
|
the nd numpy array |
required |
|
Optional[Union[AxisLike, Sequence[AxisLike]]]
|
A description of the array's axes. If None axes are guessed (which might fail and raise a ValueError.) If dims do not match array shape, permutations and singleton dimensions are tried to find a match. |
required |
Raises:
ValueError: if dims is None and dims guessing fails.
Source code in src/bioimageio/core/tensor.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
from_xarray
classmethod
¤
from_xarray(data_array: xr.DataArray) -> Self
create a Tensor from an xarray data array
this factory method is round-trip save
for any Tensor's data property (an xarray.DataArray).
Source code in src/bioimageio/core/tensor.py
186 187 188 189 190 191 192 193 | |
item
¤
Copy a tensor element to a standard Python scalar and return it.
Source code in src/bioimageio/core/tensor.py
347 348 349 350 351 352 353 354 355 356 357 358 359 360 | |
mean
¤
Source code in src/bioimageio/core/tensor.py
362 363 | |
pad
¤
pad(pad_width: PerAxis[PadWidthLike], mode: PadMode = 'symmetric') -> Self
Source code in src/bioimageio/core/tensor.py
365 366 367 368 369 370 371 372 373 374 375 376 | |
pad_to
¤
pad_to(sizes: PerAxis[int], pad_where: Union[PadWhere, PerAxis[PadWhere]] = 'left_and_right', mode: PadMode = 'symmetric') -> Self
pad tensor to match sizes
Source code in src/bioimageio/core/tensor.py
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 | |
quantile
¤
quantile(q: Union[float, Sequence[float]], dim: Optional[Union[AxisId, Sequence[AxisId]]] = None, method: QuantileMethod = 'linear') -> Self
Source code in src/bioimageio/core/tensor.py
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 | |
resize_to
¤
resize_to(sizes: PerAxis[int], *, pad_where: Union[PadWhere, PerAxis[PadWhere]] = 'left_and_right', crop_where: Union[CropWhere, PerAxis[CropWhere]] = 'left_and_right', pad_mode: PadMode = 'symmetric')
return cropped/padded tensor with sizes
Source code in src/bioimageio/core/tensor.py
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 | |
round
¤
round(*args: Any, **kwargs: Any) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
181 182 183 184 185 186 | |
std
¤
Source code in src/bioimageio/core/tensor.py
485 486 | |
sum
¤
Reduce this Tensor's data by applying sum along some dimension(s).
Source code in src/bioimageio/core/tensor.py
488 489 490 | |
to_numpy
¤
to_numpy() -> NDArray[Any]
Return the data of this tensor as a numpy array.
Source code in src/bioimageio/core/tensor.py
279 280 281 | |
transpose
¤
transpose(axes: Sequence[AxisId], *, extra_dims: Literal['raise', 'squeeze', 'stack', 'squeeze_or_stack'] = 'squeeze', missing_dims: Literal['raise', 'expand', 'unstack', 'unstack_or_expand'] = 'unstack_or_expand') -> Self
Return a transposed tensor, missing axes are expanded (if unstack_missing_dims_from_batch is False) or unstacked from batch (if unstack_missing_dims_from_batch is True), extra axes are stacked to batch (if stack_extra_dims_to_batch is True). Additional axes raise (if stack_extra_dims_to_batch is True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Sequence[AxisId]
|
The desired tensor axes |
required |
|
Literal['raise', 'squeeze', 'stack', 'squeeze_or_stack']
|
Extra dimensions are any dimensions in the tensor that are not specified in |
'squeeze'
|
|
Literal['raise', 'expand', 'unstack', 'unstack_or_expand']
|
Missing dimensions are any dimensions specified in |
'unstack_or_expand'
|
Source code in src/bioimageio/core/tensor.py
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 | |
unstack_batch_multi_index
¤
unstack_batch_multi_index(*, errors: Literal['raise', 'ignore'] = 'raise') -> Self
Unstack the batch multi-index of this tensor.
Returns:
| Type | Description |
|---|---|
Self
|
A new tensor with the batch multi-index unstacked into separate axes. |
Source code in src/bioimageio/core/tensor.py
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 | |
add_weights
¤
add_weights(model_descr: ModelDescr, *, output_path: DirectoryPath, source_format: Optional[WeightsFormat] = None, target_format: Optional[WeightsFormat] = None, verbose: bool = False, allow_tracing: bool = True) -> Union[ModelDescr, InvalidDescr]
Convert model weights to other formats and add them to the model description
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
DirectoryPath
|
Path to save updated model package to. |
required |
|
Optional[WeightsFormat]
|
convert from a specific weights format. Default: choose automatically from any available. |
None
|
|
Optional[WeightsFormat]
|
convert to a specific weights format. Default: attempt to convert to any missing format. |
None
|
|
bool
|
log more (error) output |
False
|
|
bool
|
allow conversion to torchscript by tracing if scripting fails. |
True
|
Returns:
| Type | Description |
|---|---|
Union[ModelDescr, InvalidDescr]
|
A (potentially invalid) model copy stored at |
Source code in src/bioimageio/core/weight_converters/_add_weights.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
build_description
¤
build_description(content: BioimageioYamlContentView, /, *, context: Optional[ValidationContext] = None, format_version: Literal['latest']) -> Union[LatestResourceDescr, InvalidDescr]
build_description(content: BioimageioYamlContentView, /, *, context: Optional[ValidationContext] = None, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER) -> Union[ResourceDescr, InvalidDescr]
build_description(content: BioimageioYamlContentView, /, *, context: Optional[ValidationContext] = None, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER) -> Union[ResourceDescr, InvalidDescr]
build a bioimage.io resource description from an RDF's content.
Use load_description if you want to build a resource description from an rdf.yaml
or bioimage.io zip-package.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
BioimageioYamlContentView
|
loaded rdf.yaml file (loaded with YAML, not bioimageio.spec) |
required |
|
Optional[ValidationContext]
|
validation context to use during validation |
None
|
|
Union[FormatVersionPlaceholder, str]
|
(optional) use this argument to load the resource and convert its metadata to a higher format_version. Note: - Use "latest" to convert to the latest available format version. - Use "discover" to use the format version specified in the RDF. - Only considers major.minor format version, ignores patch version. - Conversion to lower format versions is not supported. |
DISCOVER
|
Returns:
| Type | Description |
|---|---|
Union[ResourceDescr, InvalidDescr]
|
An object holding all metadata of the bioimage.io resource |
Source code in bioimageio/spec/_description.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
compute_dataset_measures
¤
compute_dataset_measures(measures: Iterable[DatasetMeasure], dataset: Iterable[Sample]) -> Dict[DatasetMeasure, MeasureValue]
compute all dataset measures for the given dataset
Source code in src/bioimageio/core/stat_calculators.py
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 | |
compute_measures
¤
compute_measures(measures: Iterable[Measure], dataset: Iterable[Sample]) -> Dict[Measure, MeasureValue]
compute all measures for the given dataset
sample measures are computed for the last sample in dataset
Source code in src/bioimageio/core/stat_calculators.py
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 | |
compute_sample_measures
¤
compute_sample_measures(measures: Iterable[SampleMeasure], sample: Sample) -> Dict[SampleMeasure, MeasureValue]
compute all sample measures for the given sample
Source code in src/bioimageio/core/stat_calculators.py
596 597 598 599 600 601 602 603 604 605 606 607 | |
create_model_adapter
¤
create_model_adapter(model_description: Union[v0_4.ModelDescr, v0_5.ModelDescr], *, devices: Optional[Sequence[str]] = None, weight_format_priority_order: Optional[Sequence[SupportedWeightsFormat]] = None)
Creates model adapter for model_descritption
Source code in src/bioimageio/core/backends/__init__.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
create_prediction_pipeline
¤
create_prediction_pipeline(bioimageio_model: AnyModelDescr, *, devices: Optional[Sequence[str]] = None, weight_format: Optional[SupportedWeightsFormat] = None, weights_format: Optional[SupportedWeightsFormat] = None, dataset_for_initial_statistics: Iterable[Union[Sample, Sequence[Tensor]]] = tuple(), keep_updating_initial_dataset_statistics: bool = False, fixed_dataset_statistics: Mapping[Measure, MeasureValue] = MappingProxyType({}), model_adapter: Optional[ModelAdapter] = None, ns: Optional[BlocksizeParameter] = None, default_blocksize_parameter: BlocksizeParameter = 10, preceding_prediction_pipelines: Optional[Sequence[Union[PredictionPipeline, RemotePredictionPipeline]]] = None, **deprecated_kwargs: Any) -> PredictionPipeline
Creates prediction pipeline which includes: * computation of input statistics * preprocessing * model prediction * computation of output statistics * postprocessing
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
AnyModelDescr
|
A bioimageio model description. |
required |
|
Optional[Sequence[str]]
|
(optional) |
None
|
|
Optional[SupportedWeightsFormat]
|
deprecated in favor of weights_format |
None
|
|
Optional[SupportedWeightsFormat]
|
(optional) Use a specific weights_format rather than
choosing one automatically.
A corresponding |
None
|
|
Iterable[Union[Sample, Sequence[Tensor]]]
|
(optional) If preprocessing steps require input dataset statistics, dataset_for_initial_statistics allows you to specifcy a dataset from which these statistics are computed. |
tuple()
|
|
bool
|
(optional) Set to |
False
|
|
Mapping[Measure, MeasureValue]
|
(optional) Precomputed dataset (and optionally sample) statistics.
Any included sample statistics will not be calculated on the fly and it is the callers
responsibility to use samples with the corresponding statistics availble in |
MappingProxyType({})
|
|
Optional[ModelAdapter]
|
(optional) Allows you to use a custom model_adapter instead of creating one according to the present/selected weights_format. |
None
|
|
Optional[BlocksizeParameter]
|
deprecated in favor of default_blocksize_parameter |
None
|
|
BlocksizeParameter
|
Allows to control the default block size for
blockwise predictions, see |
10
|
|
Optional[Sequence[Union[PredictionPipeline, RemotePredictionPipeline]]]
|
(optional) If the model has inputs that are outputs of other models (input field 'output_of'), you can provide a sequence of preceding prediction pipelines. The prediction pipeline will then automatically use the outputs of those preceding pipelines as inputs for the current model. If no preceding prediction pipelines for a model are provided, prediction pipelines using the same devices and weight format as for the current model will be created for any required preceding models. |
None
|
Source code in src/bioimageio/core/_prediction_pipeline.py
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 | |
create_remote_prediction_pipeline
¤
create_remote_prediction_pipeline(model_description: AnyModelDescr, *, server: Optional[str] = None, server_type: Optional[Literal['gradio']] = 'gradio', precomputed_statistics: Mapping[Measure, MeasureValue] = MappingProxyType({}), default_blocksize_parameter: BlocksizeParameter = 10, default_batch_size: int = 1) -> RemotePredictionPipeline
Create a RemotePredictionPipeline for the given model_description.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
AnyModelDescr
|
The model to run inference with. |
required |
|
Optional[str]
|
The URL or Hugging Face space name of a running bioimageio server instance |
None
|
|
Optional[Literal['gradio']]
|
The type of the remote server to connect to. Currently only "gradio" is supported. |
'gradio'
|
|
Mapping[Measure, MeasureValue]
|
Precomputed dataset (and optionally sample) statistics.
Any included sample statistics will not be calculated on the fly and it is the callers
responsibility to use samples with the corresponding statistics availble in |
MappingProxyType({})
|
|
BlocksizeParameter
|
Allows to control the default block size with a single parameter for blockwise predictions. (not all models support this) |
10
|
|
int
|
Default batch size to use |
1
|
Source code in src/bioimageio/core/_prediction_pipeline.py
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 | |
dump_description
¤
dump_description(rd: Union[ResourceDescr, InvalidDescr], /, *, exclude_unset: bool = True, exclude_defaults: bool = False) -> BioimageioYamlContent
Converts a resource to a dictionary containing only simple types that can directly be serialzed to YAML.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Union[ResourceDescr, InvalidDescr]
|
bioimageio resource description |
required |
|
bool
|
Exclude fields that have not explicitly be set. |
True
|
|
bool
|
Exclude fields that have the default value (even if set explicitly). |
False
|
Source code in bioimageio/spec/_description.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
enable_determinism
¤
enable_determinism(mode: Literal['seed_only', 'full'] = 'full', weight_formats: Optional[Sequence[SupportedWeightsFormat]] = None)
Seed and configure ML frameworks for maximum reproducibility. May degrade performance. Only recommended for testing reproducibility!
Seed any random generators and (if mode=="full") request ML frameworks to use deterministic algorithms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Literal['seed_only', 'full']
|
determinism mode - 'seed_only' -- only set seeds, or - 'full' determinsm features (might degrade performance or throw exceptions) |
'full'
|
|
Optional[Sequence[SupportedWeightsFormat]]
|
Limit deep learning importing deep learning frameworks based on weight_formats. E.g. this allows to avoid importing tensorflow when testing with pytorch. |
None
|
Notes
Source code in src/bioimageio/core/_resource_tests.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | |
load_dataset_description
¤
load_dataset_description(source: Union[PermissiveFileSource, ZipFile], /, *, format_version: Literal['latest'], perform_io_checks: Optional[bool] = None, known_files: Optional[Dict[str, Optional[Sha256]]] = None, sha256: Optional[Sha256] = None) -> DatasetDescr
load_dataset_description(source: Union[PermissiveFileSource, ZipFile], /, *, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER, perform_io_checks: Optional[bool] = None, known_files: Optional[Dict[str, Optional[Sha256]]] = None, sha256: Optional[Sha256] = None) -> AnyDatasetDescr
load_dataset_description(source: Union[PermissiveFileSource, ZipFile], /, *, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER, perform_io_checks: Optional[bool] = None, known_files: Optional[Dict[str, Optional[Sha256]]] = None, sha256: Optional[Sha256] = None) -> AnyDatasetDescr
same as load_description, but addtionally ensures that the loaded
description is valid and of type 'dataset'.
Source code in bioimageio/spec/_io.py
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | |
load_description
¤
load_description(source: Union[PermissiveFileSource, ZipFile], /, *, format_version: Literal['latest'], perform_io_checks: Optional[bool] = None, known_files: Optional[Dict[str, Optional[Sha256]]] = None, sha256: Optional[Sha256] = None) -> Union[LatestResourceDescr, InvalidDescr]
load_description(source: Union[PermissiveFileSource, ZipFile], /, *, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER, perform_io_checks: Optional[bool] = None, known_files: Optional[Dict[str, Optional[Sha256]]] = None, sha256: Optional[Sha256] = None) -> Union[ResourceDescr, InvalidDescr]
load_description(source: Union[PermissiveFileSource, ZipFile], /, *, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER, perform_io_checks: Optional[bool] = None, known_files: Optional[Dict[str, Optional[Sha256]]] = None, sha256: Optional[Sha256] = None) -> Union[ResourceDescr, InvalidDescr]
load a bioimage.io resource description
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Union[PermissiveFileSource, ZipFile]
|
Path or URL to an rdf.yaml or a bioimage.io package (zip-file with rdf.yaml in it). |
required |
|
Union[FormatVersionPlaceholder, str]
|
(optional) Use this argument to load the resource and convert its metadata to a higher format_version. Note: - Use "latest" to convert to the latest available format version. - Use "discover" to use the format version specified in the RDF. - Only considers major.minor format version, ignores patch version. - Conversion to lower format versions is not supported. |
DISCOVER
|
|
Optional[bool]
|
Wether or not to perform validation that requires file io, e.g. downloading a remote files. The existence of local absolute file paths is still being checked. |
None
|
|
Optional[Dict[str, Optional[Sha256]]]
|
Allows to bypass download and hashing of referenced files (even if perform_io_checks is True). Keys should be file paths or URL strings as they appear in the bioimageio.yaml file. Values are Sha256 values compared to hash values in the description.
For If If |
None
|
|
Optional[Sha256]
|
Optional SHA-256 value of source |
None
|
Returns:
| Type | Description |
|---|---|
Union[ResourceDescr, InvalidDescr]
|
An object holding all metadata of the bioimage.io resource |
-
API Reference
coreload_resource
Source code in bioimageio/spec/_io.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
load_description_and_test
¤
load_description_and_test(source: Union[ResourceDescr, PermissiveFileSource, BioimageioYamlContent], *, format_version: Literal['latest'], weight_format: Optional[SupportedWeightsFormat] = None, devices: Optional[Sequence[str]] = None, determinism: Literal['seed_only', 'full'] = 'seed_only', expected_type: Literal['model'], sha256: Optional[Sha256] = None, stop_early: bool = False, working_dir: Optional[Union[os.PathLike[str], str]] = None, **deprecated: Unpack[DeprecatedKwargs]) -> Union[ModelDescr, InvalidDescr]
load_description_and_test(source: Union[ResourceDescr, PermissiveFileSource, BioimageioYamlContent], *, format_version: Literal['latest'], weight_format: Optional[SupportedWeightsFormat] = None, devices: Optional[Sequence[str]] = None, determinism: Literal['seed_only', 'full'] = 'seed_only', expected_type: Literal['dataset'], sha256: Optional[Sha256] = None, stop_early: bool = False, working_dir: Optional[Union[os.PathLike[str], str]] = None, **deprecated: Unpack[DeprecatedKwargs]) -> Union[DatasetDescr, InvalidDescr]
load_description_and_test(source: Union[ResourceDescr, PermissiveFileSource, BioimageioYamlContent], *, format_version: Literal['latest'], weight_format: Optional[SupportedWeightsFormat] = None, devices: Optional[Sequence[str]] = None, determinism: Literal['seed_only', 'full'] = 'seed_only', expected_type: Optional[str] = None, sha256: Optional[Sha256] = None, stop_early: bool = False, working_dir: Optional[Union[os.PathLike[str], str]] = None, **deprecated: Unpack[DeprecatedKwargs]) -> Union[LatestResourceDescr, InvalidDescr]
load_description_and_test(source: Union[ResourceDescr, PermissiveFileSource, BioimageioYamlContent], *, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER, weight_format: Optional[SupportedWeightsFormat] = None, devices: Optional[Sequence[str]] = None, determinism: Literal['seed_only', 'full'] = 'seed_only', expected_type: Literal['model'], sha256: Optional[Sha256] = None, stop_early: bool = False, working_dir: Optional[Union[os.PathLike[str], str]] = None, **deprecated: Unpack[DeprecatedKwargs]) -> Union[AnyModelDescr, InvalidDescr]
load_description_and_test(source: Union[ResourceDescr, PermissiveFileSource, BioimageioYamlContent], *, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER, weight_format: Optional[SupportedWeightsFormat] = None, devices: Optional[Sequence[str]] = None, determinism: Literal['seed_only', 'full'] = 'seed_only', expected_type: Literal['dataset'], sha256: Optional[Sha256] = None, stop_early: bool = False, working_dir: Optional[Union[os.PathLike[str], str]] = None, **deprecated: Unpack[DeprecatedKwargs]) -> Union[AnyDatasetDescr, InvalidDescr]
load_description_and_test(source: Union[ResourceDescr, PermissiveFileSource, BioimageioYamlContent], *, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER, weight_format: Optional[SupportedWeightsFormat] = None, devices: Optional[Sequence[str]] = None, determinism: Literal['seed_only', 'full'] = 'seed_only', expected_type: Optional[str] = None, sha256: Optional[Sha256] = None, stop_early: bool = False, working_dir: Optional[Union[os.PathLike[str], str]] = None, **deprecated: Unpack[DeprecatedKwargs]) -> Union[ResourceDescr, InvalidDescr]
load_description_and_test(source: Union[ResourceDescr, PermissiveFileSource, BioimageioYamlContent], *, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER, weight_format: Optional[SupportedWeightsFormat] = None, devices: Optional[Sequence[str]] = None, determinism: Literal['seed_only', 'full'] = 'seed_only', expected_type: Optional[str] = None, sha256: Optional[Sha256] = None, stop_early: bool = False, working_dir: Optional[Union[os.PathLike[str], str]] = None, **deprecated: Unpack[DeprecatedKwargs]) -> Union[ResourceDescr, InvalidDescr]
Test a bioimage.io resource dynamically, for example run prediction of test tensors for models.
See test_description for more details.
Returns:
| Type | Description |
|---|---|
Union[ResourceDescr, InvalidDescr]
|
A (possibly invalid) resource description object
with a populated |
Source code in src/bioimageio/core/_resource_tests.py
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 | |
load_description_and_validate_format_only
¤
load_description_and_validate_format_only(source: Union[PermissiveFileSource, ZipFile], /, *, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER, perform_io_checks: Optional[bool] = None, known_files: Optional[Dict[str, Optional[Sha256]]] = None, sha256: Optional[Sha256] = None) -> ValidationSummary
same as load_description, but only return the validation summary.
Returns:
| Type | Description |
|---|---|
ValidationSummary
|
Validation summary of the bioimage.io resource found at |
Source code in bioimageio/spec/_io.py
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | |
load_model_description
¤
load_model_description(source: Union[PermissiveFileSource, ZipFile], /, *, format_version: Literal['latest'], perform_io_checks: Optional[bool] = None, known_files: Optional[Dict[str, Optional[Sha256]]] = None, sha256: Optional[Sha256] = None) -> ModelDescr
load_model_description(source: Union[PermissiveFileSource, ZipFile], /, *, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER, perform_io_checks: Optional[bool] = None, known_files: Optional[Dict[str, Optional[Sha256]]] = None, sha256: Optional[Sha256] = None) -> AnyModelDescr
load_model_description(source: Union[PermissiveFileSource, ZipFile], /, *, format_version: Union[FormatVersionPlaceholder, str] = DISCOVER, perform_io_checks: Optional[bool] = None, known_files: Optional[Dict[str, Optional[Sha256]]] = None, sha256: Optional[Sha256] = None) -> AnyModelDescr
same as load_description, but addtionally ensures that the loaded
description is valid and of type 'model'.
Raises:
| Type | Description |
|---|---|
ValueError
|
for invalid or non-model resources |
-
API Reference
coreload_model
Source code in bioimageio/spec/_io.py
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
predict
¤
predict(*, model: Union[PermissiveFileSource, v0_4.ModelDescr, v0_5.ModelDescr, PredictionPipeline], inputs: Union[Sample, PerMember[TensorSource], TensorSource], sample_id: Hashable = 'sample', blocksize_parameter: Optional[BlocksizeParameter] = None, input_block_shape: Optional[Mapping[MemberId, Mapping[AxisId, int]]] = None, skip_preprocessing: bool = False, skip_postprocessing: bool = False, save_output_path: Optional[Union[Path, str]] = None) -> Sample
Run prediction for a single set of input(s) with a bioimage.io model
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Union[PermissiveFileSource, v0_4.ModelDescr, v0_5.ModelDescr, PredictionPipeline]
|
Model to predict with. May be given as RDF source, model description or prediction pipeline. |
required |
|
Union[Sample, PerMember[TensorSource], TensorSource]
|
the input sample or the named input(s) for this model as a dictionary |
required |
|
Hashable
|
the sample id. The sample_id is used to format save_output_path and to distinguish sample specific log messages. |
'sample'
|
|
Optional[BlocksizeParameter]
|
(optional) Tile the input into blocks parametrized by
blocksize_parameter according to any parametrized axis sizes defined
by the model.
See |
None
|
|
Optional[Mapping[MemberId, Mapping[AxisId, int]]]
|
(optional) Tile the input sample tensors into blocks. Note: Use blocksize_parameter for a parameterized block shape to run prediction independent of the exact block shape. |
None
|
|
bool
|
Flag to skip the model's preprocessing. |
False
|
|
bool
|
Flag to skip the model's postprocessing. |
False
|
|
Optional[Union[Path, str]]
|
A path with to save the output to. M
Must contain:
- |
None
|
Source code in src/bioimageio/core/prediction.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
predict_many
¤
predict_many(*, model: Union[PermissiveFileSource, v0_4.ModelDescr, v0_5.ModelDescr, PredictionPipeline], inputs: Union[Iterable[PerMember[TensorSource]], Iterable[TensorSource]], sample_id: str = 'sample{i:03}', blocksize_parameter: Optional[Union[v0_5.ParameterizedSize_N, Mapping[Tuple[MemberId, AxisId], v0_5.ParameterizedSize_N]]] = None, skip_preprocessing: bool = False, skip_postprocessing: bool = False, save_output_path: Optional[Union[Path, str]] = None) -> Iterator[Sample]
Run prediction for a multiple sets of inputs with a bioimage.io model
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Union[PermissiveFileSource, v0_4.ModelDescr, v0_5.ModelDescr, PredictionPipeline]
|
Model to predict with. May be given as RDF source, model description or prediction pipeline. |
required |
|
Union[Iterable[PerMember[TensorSource]], Iterable[TensorSource]]
|
An iterable of the named input(s) for this model as a dictionary. |
required |
|
str
|
The sample id.
note: |
'sample{i:03}'
|
|
Optional[Union[v0_5.ParameterizedSize_N, Mapping[Tuple[MemberId, AxisId], v0_5.ParameterizedSize_N]]]
|
(optional) Tile the input into blocks parametrized by blocksize according to any parametrized axis sizes defined in the model RDF. |
None
|
|
bool
|
Flag to skip the model's preprocessing. |
False
|
|
bool
|
Flag to skip the model's postprocessing. |
False
|
|
Optional[Union[Path, str]]
|
A path to save the output to.
Must contain:
- |
None
|
Source code in src/bioimageio/core/prediction.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | |
save_bioimageio_package
¤
save_bioimageio_package(source: Union[BioimageioYamlSource, ResourceDescr], /, *, compression: int = ZIP_DEFLATED, compression_level: int = 1, output_path: Union[NewPath, FilePath, None] = None, weights_priority_order: Optional[Sequence[Literal['keras_hdf5', 'onnx', 'pytorch_state_dict', 'tensorflow_js', 'tensorflow_saved_model_bundle', 'torchscript']]] = None, allow_invalid: bool = False, local_files_only: bool = False) -> FilePath
Package a bioimageio resource as a zip file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Union[BioimageioYamlSource, ResourceDescr]
|
bioimageio resource description |
required |
|
int
|
The numeric constant of compression method. |
ZIP_DEFLATED
|
|
int
|
Compression level to use when writing files to the archive. See https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile |
1
|
|
Union[NewPath, FilePath, None]
|
file path to write package to |
None
|
|
Optional[Sequence[Literal['keras_hdf5', 'onnx', 'pytorch_state_dict', 'tensorflow_js', 'tensorflow_saved_model_bundle', 'torchscript']]]
|
If given only the first weights format present in the model is included. If none of the prioritized weights formats is found all are included. |
None
|
|
bool
|
If True, do not raise an error if the exported package is invalid, but log an error instead. |
False
|
|
bool
|
If True, only local files are included in the package. If False, remote files are also included. |
False
|
Returns:
| Type | Description |
|---|---|
FilePath
|
path to zipped bioimageio package |
Source code in bioimageio/spec/_package.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
save_bioimageio_package_as_folder
¤
save_bioimageio_package_as_folder(source: Union[BioimageioYamlSource, ResourceDescr], /, *, output_path: Union[NewPath, DirectoryPath, None] = None, weights_priority_order: Optional[Sequence[Literal['keras_hdf5', 'onnx', 'pytorch_state_dict', 'tensorflow_js', 'tensorflow_saved_model_bundle', 'torchscript']]] = None, local_files_only: bool = False) -> DirectoryPath
Write the content of a bioimage.io resource package to a folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Union[BioimageioYamlSource, ResourceDescr]
|
bioimageio resource description |
required |
|
Union[NewPath, DirectoryPath, None]
|
file path to write package to |
None
|
|
Optional[Sequence[Literal['keras_hdf5', 'onnx', 'pytorch_state_dict', 'tensorflow_js', 'tensorflow_saved_model_bundle', 'torchscript']]]
|
If given only the first weights format present in the model is included. If none of the prioritized weights formats is found all are included. |
None
|
|
bool
|
If True, only local files are included in the package. If False, remote files are also included. |
False
|
Returns:
| Type | Description |
|---|---|
DirectoryPath
|
directory path to bioimageio package folder |
Source code in bioimageio/spec/_package.py
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | |
save_bioimageio_yaml_only
¤
save_bioimageio_yaml_only(rd: Union[ResourceDescr, BioimageioYamlContent, InvalidDescr], /, file: Union[NewPath, FilePath, TextIO], *, exclude_unset: bool = True, exclude_defaults: bool = False)
write the metadata of a resource description (rd) to file
without writing any of the referenced files in it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Union[ResourceDescr, BioimageioYamlContent, InvalidDescr]
|
bioimageio resource description |
required |
|
Union[NewPath, FilePath, TextIO]
|
file or stream to save to |
required |
|
bool
|
Exclude fields that have not explicitly be set. |
True
|
|
bool
|
Exclude fields that have the default value (even if set explicitly). |
False
|
Note: To save a resource description with its associated files as a package,
use save_bioimageio_package or save_bioimageio_package_as_folder.
Source code in bioimageio/spec/_io.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | |
test_description
¤
test_description(source: Union[ResourceDescr, PermissiveFileSource, BioimageioYamlContent], *, format_version: Union[FormatVersionPlaceholder, str] = 'discover', weight_format: Optional[SupportedWeightsFormat] = None, devices: Optional[Sequence[str]] = None, determinism: Literal['seed_only', 'full'] = 'seed_only', expected_type: Optional[str] = None, sha256: Optional[Sha256] = None, stop_early: bool = False, runtime_env: Union[Literal['currently-active', 'as-described'], Path, BioimageioCondaEnv] = 'currently-active', run_command: Callable[[Sequence[str]], None] = default_run_command, working_dir: Optional[Union[os.PathLike[str], str]] = None, **deprecated: Unpack[DeprecatedKwargs]) -> ValidationSummary
Test a bioimage.io resource dynamically, for example run prediction of test tensors for models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Union[ResourceDescr, PermissiveFileSource, BioimageioYamlContent]
|
model description source. |
required |
|
Optional[SupportedWeightsFormat]
|
Weight format to test. Default: All weight formats present in source. |
None
|
|
Optional[Sequence[str]]
|
Devices to test with, e.g. 'cpu', 'cuda'. Default (may be weight format dependent): ['cuda'] if available, ['cpu'] otherwise. |
None
|
|
Literal['seed_only', 'full']
|
Modes to improve reproducibility of test outputs. |
'seed_only'
|
|
Optional[str]
|
Assert an expected resource description |
None
|
|
Optional[Sha256]
|
Expected SHA256 value of source.
(Ignored if source already is a loaded |
None
|
|
bool
|
Do not run further subtests after a failed one. |
False
|
|
Union[Literal['currently-active', 'as-described'], Path, BioimageioCondaEnv]
|
(Experimental feature!) The Python environment to run the tests in
- |
'currently-active'
|
|
Callable[[Sequence[str]], None]
|
(Experimental feature!) Function to execute (conda) terminal commands in a subprocess.
The function should raise an exception if the command fails.
run_command is ignored if runtime_env is |
default_run_command
|
|
Optional[Union[os.PathLike[str], str]]
|
(for debugging) directory to save any temporary files (model packages, conda environments, test summaries). Defaults to a temporary directory. |
None
|
-
API Reference
coretest_resource
Source code in src/bioimageio/core/_resource_tests.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | |
test_model
¤
test_model(source: Union[v0_4.ModelDescr, v0_5.ModelDescr, PermissiveFileSource], weight_format: Optional[SupportedWeightsFormat] = None, devices: Optional[List[str]] = None, *, determinism: Literal['seed_only', 'full'] = 'seed_only', sha256: Optional[Sha256] = None, stop_early: bool = False, working_dir: Optional[Union[os.PathLike[str], str]] = None, **deprecated: Unpack[DeprecatedKwargs]) -> ValidationSummary
Test model inference
Source code in src/bioimageio/core/_resource_tests.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
validate_format
¤
validate_format(data: BioimageioYamlContent, /, *, format_version: Union[Literal['discover', 'latest'], str] = DISCOVER, context: Optional[ValidationContext] = None) -> ValidationSummary
Validate a dictionary holding a bioimageio description.
See bioimagieo.spec.load_description_and_validate_format_only
to validate a file source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
BioimageioYamlContent
|
Dictionary holding the raw bioimageio.yaml content. |
required |
|
Union[Literal['discover', 'latest'], str]
|
Format version to (update to and) use for validation. Note: - Use "latest" to convert to the latest available format version. - Use "discover" to use the format version specified in the RDF. - Only considers major.minor format version, ignores patch version. - Conversion to lower format versions is not supported. |
DISCOVER
|
|
Optional[ValidationContext]
|
Validation context, see |
None
|
Note
Use bioimagieo.spec.load_description_and_validate_format_only to validate a
file source instead of loading the YAML content and creating the appropriate
ValidationContext.
Alternatively you can use bioimagieo.spec.load_description and access the
validation_summary attribute of the returned object.
Source code in bioimageio/spec/_description.py
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |