Skip to content

sample ¤

Classes:

Name Description
LinearSampleAxisTransform
Sample

A dataset sample.

SampleBlock

A block of a dataset sample

SampleBlockBase

base class for SampleBlockMeta and SampleBlock

SampleBlockMeta

Meta data of a dataset sample block

SampleBlockWithOrigin

A SampleBlock with a reference (origin) to the whole Sample

Functions:

Name Description
sample_block_generator
sample_block_meta_generator

Attributes:

Name Type Description
BlockT

BlockT module-attribute ¤

BlockT = TypeVar('BlockT', bound=BlockMeta)

LinearSampleAxisTransform dataclass ¤

LinearSampleAxisTransform(axis: AxisId, scale: float, offset: int, member: MemberId)

Bases: LinearAxisTransform


              flowchart TD
              bioimageio.core.sample.LinearSampleAxisTransform[LinearSampleAxisTransform]
              bioimageio.core.block_meta.LinearAxisTransform[LinearAxisTransform]

                              bioimageio.core.block_meta.LinearAxisTransform --> bioimageio.core.sample.LinearSampleAxisTransform
                


              click bioimageio.core.sample.LinearSampleAxisTransform href "" "bioimageio.core.sample.LinearSampleAxisTransform"
              click bioimageio.core.block_meta.LinearAxisTransform href "" "bioimageio.core.block_meta.LinearAxisTransform"
            

Methods:

Name Description
compute

Attributes:

Name Type Description
axis AxisId
member MemberId
offset int
scale float

axis instance-attribute ¤

axis: AxisId

member instance-attribute ¤

member: MemberId

offset instance-attribute ¤

offset: int

scale instance-attribute ¤

scale: float

compute ¤

compute(s: int, round: Callable[[float], int] = floor) -> int
Source code in src/bioimageio/core/block_meta.py
43
44
def compute(self, s: int, round: Callable[[float], int] = floor) -> int:
    return round(s * self.scale) + self.offset

Sample dataclass ¤

Sample(members: Dict[MemberId, Tensor], stat: Stat, id: SampleId)

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.

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 Sample from an iterable of SampleBlocks.

from_blocks_yield_intermediates

Create a Sample from an iterable of SampleBlocks, yielding the intermediate sample after each block.

pad

Convenience method to pad sample members.

set_block

Set values of block.

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 Sample within the dataset -- typically a number or a string.

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 None if the sample does not have a batch dimension.

id instance-attribute ¤

Identifies the Sample within the dataset -- typically a number or a string.

members instance-attribute ¤

members: Dict[MemberId, Tensor]

The sample's tensors

shape property ¤

shape: PerMember[PerAxis[int]]

stat instance-attribute ¤

stat: Stat

Sample and dataset statistics

__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
def __getitem__(
    self,
    key: PerMember[
        Union[
            SliceInfo,
            slice,
            int,
            PerAxis[Union[SliceInfo, slice, int]],
            Tensor,
            xr.DataArray,
        ]
    ],
) -> Self:
    return self.__class__(
        members={m: t[key[m]] for m, t in self.members.items() if m in key},
        stat=self.stat,
        id=self.id,
    )

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
def as_arrays(self) -> Dict[MemberId, NDArray[Any]]:
    """Return sample as dictionary of arrays."""
    return {m: t.to_numpy() for m, t in self.members.items()}

as_single_block ¤

as_single_block(halo: Optional[PerMember[PerAxis[Halo]]] = None)
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
def as_single_block(self, halo: Optional[PerMember[PerAxis[Halo]]] = None):
    if halo is None:
        halo = {}
    return SampleBlockWithOrigin(
        sample_shape=self.shape,
        sample_id=self.id,
        blocks={
            m: Block(
                sample_shape=self.shape[m],
                data=data,
                inner_slice={
                    a: SliceInfo(0, s) for a, s in data.tagged_shape.items()
                },
                halo=halo.get(m, {}),
                block_index=0,
                blocks_in_sample=1,
            )
            for m, data in self.members.items()
        },
        stat=self.stat,
        origin=self,
        block_index=0,
        blocks_in_sample=1,
    )

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
def assign_batch_multi_index(self, multi_index: "pd.MultiIndex") -> Self:
    """Return a new sample with the batch multi-index assigned to all sample members.

    Raises:
        ValueError: If not all sample members have a batch dimension.
    """
    if len(
        no_batch := [
            m for m, t in self.members.items() if AxisId("batch") not in t.dims
        ]
    ) == len(self.members):
        raise ValueError(f"No member has a batch dimension: {no_batch}")

    return self.__class__(
        members={
            m: t
            if AxisId("batch") not in t.dims
            else t.assign_batch_multi_index(multi_index)
            for m, t in self.members.items()
        },
        stat=dict(self.stat),
        id=self.id,
    )

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

sample_blocks ¤

Iterable[SampleBlock]

The blocks to create the sample from.

required

fill_value ¤

float

The value to fill missing values with (default: nan).

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
@classmethod
def from_blocks(
    cls,
    sample_blocks: Iterable[SampleBlock],
    *,
    fill_value: float = float("nan"),
) -> Self:
    """Create a `Sample` from an iterable of `SampleBlock`s.

    Note:
        All sample blocks must have the same `sample_id`.

    Args:
        sample_blocks: The blocks to create the sample from.
        fill_value: The value to fill missing values with (default: `nan`).
    """
    output = None
    for output in cls.from_blocks_yield_intermediates(
        sample_blocks, fill_value=fill_value
    ):
        pass

    if output is None:
        raise ValueError("no sample blocks provided")

    return output

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

sample_blocks ¤

Iterable[SampleBlock]

The blocks to create the sample from.

required

fill_value ¤

float

The value to fill missing values with (default: nan).

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
@classmethod
def from_blocks_yield_intermediates(
    cls,
    sample_blocks: Iterable[SampleBlock],
    *,
    fill_value: float = float("nan"),
):
    """Create a `Sample` from an iterable of `SampleBlock`s, yielding the intermediate sample after each block.

    Args:
        sample_blocks: The blocks to create the sample from.
        fill_value: The value to fill missing values with (default: `nan`).
    """
    output = cls(members={}, stat={}, id=None)
    for sample_block in sample_blocks:
        if output.id is None:
            output.id = sample_block.sample_id
        else:
            assert output.id == sample_block.sample_id, (
                "sample id changed between sample blocks"
            )

        output.stat = sample_block.stat

        for m, block in sample_block.blocks.items():
            if m not in output.members:
                if -1 in block.sample_shape.values():
                    raise NotImplementedError(
                        "merging blocks with data dependent axis not yet implemented"
                    )

                output.members[m] = Tensor(
                    np.full(
                        tuple(block.sample_shape[a] for a in block.data.dims),
                        fill_value,
                        dtype=block.data.dtype,
                    ),
                    dims=block.data.dims,
                )

            output.members[m][block.inner_slice] = block.inner_data
        yield output

    yield output

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
def pad(
    self,
    pad_width: PerMember[PerAxis[Union[int, PadWidthLike]]],
    mode: Union[PerMember[PadMode], PadMode],
) -> Self:
    """Convenience method to pad sample members."""
    default_mode = "symmetric"
    if isinstance(mode, collections.abc.Mapping):
        mode_per_member = mode
    else:
        mode_per_member: Mapping[MemberId, PadMode] = {}
        default_mode = mode

    return self.__class__(
        members={
            m: t.pad(
                pad_width=pad_width.get(m, {}),
                mode=mode_per_member.get(m, default_mode),
            )
            for m, t in self.members.items()
        },
        stat=self.stat,
        id=self.id,
    )

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
def set_block(self, 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)

    Raises:
        ValueError if block and sample members do not overlap at all.
    """
    no_overlap = True
    for m in self.members:
        if m not in block.blocks:
            continue
        b = block.blocks[m]
        self.members[m][b.inner_slice] = b.inner_data
        no_overlap = False

    if no_overlap:
        raise ValueError(
            f"block with members {list(block.blocks)} does not overlap with sample members {list(self.members)}"
        )

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
def split_into_blocks(
    self,
    block_shapes: PerMember[PerAxis[int]],
    halo: PerMember[PerAxis[HaloLike]],
    pad_mode: Union[PadMode, PerMember[PadMode]],
    broadcast: bool = False,
) -> Tuple[TotalNumberOfBlocks, Iterable[SampleBlockWithOrigin]]:
    assert not (missing := [m for m in block_shapes if m not in self.members]), (
        f"`block_shapes` specified for unknown members: {missing}"
    )
    assert not (missing := [m for m in halo if m not in block_shapes]), (
        f"`halo` specified for members without `block_shape`: {missing}"
    )

    n_blocks, blocks = split_multiple_shapes_into_blocks(
        shapes=self.shape,
        block_shapes=block_shapes,
        halo=halo,
        broadcast=broadcast,
    )
    return n_blocks, sample_block_generator(blocks, origin=self, pad_mode=pad_mode)

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
def transpose(
    self,
    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:
        ValueError: If not all batch dimensions have the same length after transposition (and possibly stacking/unstacking extra dimensions).

    """
    if any((unknown := [m not in self.members for m in axes])):
        raise ValueError(f"Axes specified for unknown members: {unknown}")

    members = {
        m: t
        if m not in axes
        else t.transpose(
            axes=axes[m],
            extra_dims=extra_dims,
            missing_dims=missing_dims,
        )
        for m, t in self.members.items()
    }

    if (
        len(
            (
                batch_lengths := {
                    t.sizes[AxisId("batch")]
                    for t in members.values()
                    if AxisId("batch") in t.dims
                }
            )
        )
        > 1
    ):
        raise ValueError(
            f"Transposed sample members have incompatible batch lengths: {batch_lengths}."
        )

    return self.__class__(members=members, stat=dict(self.stat), id=self.id)

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

errors ¤

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 Sample with unstacked batch multi-index for all members.

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
def unstack_batch_multi_index(
    self, *, errors: Literal["raise", "ignore"] = "raise"
) -> Self:
    """Unstack the batch multi-index of all sample members.

    Args:
        errors: Whether to raise an error if a member does not have a batch multi-index. Default is "raise".

    Returns:
        A new `Sample` with unstacked batch multi-index for all members.
    """
    if (
        len(
            no_batch := [
                m for m, t in self.members.items() if AxisId("batch") not in t.dims
            ]
        )
        == len(self.members)
        and errors == "raise"
    ):
        raise ValueError(f"No member has a batch dimension: {no_batch}")

    members = {
        m: t
        if AxisId("batch") not in t.dims
        else t.unstack_batch_multi_index(errors=errors)
        for m, t in self.members.items()
    }
    if (
        len(
            batch_lengths := {
                t.sizes.get(AxisId("batch"))
                for t in members.values()
                if AxisId("batch") in t.dims
            }
        )
        > 1
    ):
        raise ValueError(
            f"Different batch lengths after unstacking: {batch_lengths}"
        )

    stat: Stat = {
        k: v.unstack_batch_multi_index(errors="ignore")
        if isinstance(v, Tensor)
        else float(v)
        for k, v in self.stat.items()
    }
    return self.__class__(
        members=members,
        stat=stat,
        id=self.id,
    )

SampleBlock dataclass ¤

SampleBlock(blocks: Dict[MemberId, Block], stat: Stat)

Bases: SampleBlockBase[Block]


              flowchart TD
              bioimageio.core.sample.SampleBlock[SampleBlock]
              bioimageio.core.sample.SampleBlockBase[SampleBlockBase]

                              bioimageio.core.sample.SampleBlockBase --> bioimageio.core.sample.SampleBlock
                


              click bioimageio.core.sample.SampleBlock href "" "bioimageio.core.sample.SampleBlock"
              click bioimageio.core.sample.SampleBlockBase href "" "bioimageio.core.sample.SampleBlockBase"
            

A block of a dataset sample

Methods:

Name Description
as_sample

Convert this sample block to a Sample with the shape of this block.

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

block_index instance-attribute ¤

block_index: BlockIndex

the n-th block of the sample

blocks instance-attribute ¤

blocks: Dict[MemberId, Block]

Individual tensor blocks comprising this sample block

blocks_in_sample instance-attribute ¤

blocks_in_sample: TotalNumberOfBlocks

total number of blocks in the sample

inner_shape property ¤

inner_shape: PerMember[PerAxis[int]]

members property ¤

members: PerMember[Tensor]

the sample block's tensors

sample_id instance-attribute ¤

sample_id: SampleId

identifier for the sample within its dataset

sample_shape instance-attribute ¤

sample_shape: PerMemberAnno[PerAxis[int]]

the sample shape this block represents a part of

shape property ¤

shape: PerMember[PerAxis[int]]

stat instance-attribute ¤

stat: Stat

computed statistics

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
def as_sample(self) -> 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.
    """
    return Sample(
        members=dict(self.members),
        stat=dict(self.stat),
        id=self.sample_id,
    )

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
@classmethod
def from_meta(
    cls, meta: SampleBlockMeta, data: PerMember[Tensor], stat: Stat
) -> Self:
    return cls(
        sample_shape=meta.sample_shape,
        sample_id=meta.sample_id,
        blocks={
            m: Block.from_meta(b, data=data[m]) for m, b in meta.blocks.items()
        },
        stat=stat,
        block_index=meta.block_index,
        blocks_in_sample=meta.blocks_in_sample,
    )

get_meta ¤

get_meta() -> SampleBlockMeta
Source code in src/bioimageio/core/sample.py
582
583
584
585
586
587
588
589
def get_meta(self) -> SampleBlockMeta:
    return SampleBlockMeta(
        sample_id=self.sample_id,
        blocks={m: b.get_meta() for m, b in self.blocks.items()},
        sample_shape=self.sample_shape,
        block_index=self.block_index,
        blocks_in_sample=self.blocks_in_sample,
    )

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
def get_transformed_meta(
    self, new_axes: PerMember[PerAxis[Union[LinearSampleAxisTransform, int]]]
) -> SampleBlockMeta:
    return SampleBlockMeta(
        sample_id=self.sample_id,
        blocks=dict(self.blocks),
        sample_shape=self.sample_shape,
        block_index=self.block_index,
        blocks_in_sample=self.blocks_in_sample,
    ).get_transformed(new_axes)

SampleBlockBase ¤

Bases: Generic[BlockT]


              flowchart TD
              bioimageio.core.sample.SampleBlockBase[SampleBlockBase]

              

              click bioimageio.core.sample.SampleBlockBase href "" "bioimageio.core.sample.SampleBlockBase"
            

base class for SampleBlockMeta and SampleBlock

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]]

block_index instance-attribute ¤

block_index: BlockIndex

the n-th block of the sample

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

inner_shape property ¤

inner_shape: PerMember[PerAxis[int]]

sample_id instance-attribute ¤

sample_id: SampleId

identifier for the sample within its dataset

sample_shape instance-attribute ¤

sample_shape: PerMemberAnno[PerAxis[int]]

the sample shape this block represents a part of

shape property ¤

shape: PerMember[PerAxis[int]]

SampleBlockMeta ¤

Bases: SampleBlockBase[BlockMeta]


              flowchart TD
              bioimageio.core.sample.SampleBlockMeta[SampleBlockMeta]
              bioimageio.core.sample.SampleBlockBase[SampleBlockBase]

                              bioimageio.core.sample.SampleBlockBase --> bioimageio.core.sample.SampleBlockMeta
                


              click bioimageio.core.sample.SampleBlockMeta href "" "bioimageio.core.sample.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]]

block_index instance-attribute ¤

block_index: BlockIndex

the n-th block of the sample

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

inner_shape property ¤

inner_shape: PerMember[PerAxis[int]]

sample_id instance-attribute ¤

sample_id: SampleId

identifier for the sample within its dataset

sample_shape instance-attribute ¤

sample_shape: PerMemberAnno[PerAxis[int]]

the sample shape this block represents a part of

shape property ¤

shape: PerMember[PerAxis[int]]

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
def get_transformed(
    self, new_axes: PerMember[PerAxis[Union[LinearSampleAxisTransform, int]]]
) -> Self:
    sample_shape = {
        m: {
            a: (
                trf
                if isinstance(trf, int)
                else trf.compute(self.sample_shape[trf.member][trf.axis])
            )
            for a, trf in new_axes[m].items()
        }
        for m in new_axes
    }

    def get_member_halo(m: MemberId, round: Callable[[float], int]):
        return {
            a: (
                Halo(0, 0)
                if isinstance(trf, int)
                or trf.axis not in self.blocks[trf.member].halo
                else Halo(
                    round(self.blocks[trf.member].halo[trf.axis].left * trf.scale),
                    round(self.blocks[trf.member].halo[trf.axis].right * trf.scale),
                )
            )
            for a, trf in new_axes[m].items()
        }

    halo: Dict[MemberId, Dict[AxisId, Halo]] = {}
    for m in new_axes:
        halo[m] = get_member_halo(m, floor)
        if halo[m] != get_member_halo(m, ceil):
            raise ValueError(
                f"failed to unambiguously scale halo {halo[m]} with {new_axes[m]}"
                + f" for {m}."
            )

    inner_slice = {
        m: {
            a: (
                SliceInfo(0, trf)
                if isinstance(trf, int)
                else SliceInfo(
                    trf.compute(
                        self.blocks[trf.member].inner_slice[trf.axis].start
                    ),
                    trf.compute(self.blocks[trf.member].inner_slice[trf.axis].stop),
                )
            )
            for a, trf in new_axes[m].items()
        }
        for m in new_axes
    }
    return self.__class__(
        blocks={
            m: BlockMeta(
                sample_shape=sample_shape[m],
                inner_slice=inner_slice[m],
                halo=halo[m],
                block_index=self.block_index,
                blocks_in_sample=self.blocks_in_sample,
            )
            for m in new_axes
        },
        sample_shape=sample_shape,
        sample_id=self.sample_id,
        block_index=self.block_index,
        blocks_in_sample=self.blocks_in_sample,
    )

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
def with_data(self, data: PerMember[Tensor], *, stat: Stat) -> SampleBlock:
    return SampleBlock(
        sample_shape={
            m: {
                a: data[m].tagged_shape[a] if s == -1 else s
                for a, s in member_shape.items()
            }
            for m, member_shape in self.sample_shape.items()
        },
        sample_id=self.sample_id,
        blocks={
            m: Block.from_meta(b, data=data[m]) for m, b in self.blocks.items()
        },
        stat=stat,
        block_index=self.block_index,
        blocks_in_sample=self.blocks_in_sample,
    )

SampleBlockWithOrigin dataclass ¤

SampleBlockWithOrigin(blocks: Dict[MemberId, Block], stat: Stat, origin: Sample)

Bases: SampleBlock


              flowchart TD
              bioimageio.core.sample.SampleBlockWithOrigin[SampleBlockWithOrigin]
              bioimageio.core.sample.SampleBlock[SampleBlock]
              bioimageio.core.sample.SampleBlockBase[SampleBlockBase]

                              bioimageio.core.sample.SampleBlock --> bioimageio.core.sample.SampleBlockWithOrigin
                                bioimageio.core.sample.SampleBlockBase --> bioimageio.core.sample.SampleBlock
                



              click bioimageio.core.sample.SampleBlockWithOrigin href "" "bioimageio.core.sample.SampleBlockWithOrigin"
              click bioimageio.core.sample.SampleBlock href "" "bioimageio.core.sample.SampleBlock"
              click bioimageio.core.sample.SampleBlockBase href "" "bioimageio.core.sample.SampleBlockBase"
            

A SampleBlock with a reference (origin) to the whole Sample

Methods:

Name Description
as_sample

Convert this sample block to a Sample with the shape of this block.

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

origin Sample

the sample this sample block was taken from

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

block_index instance-attribute ¤

block_index: BlockIndex

the n-th block of the sample

blocks instance-attribute ¤

blocks: Dict[MemberId, Block]

Individual tensor blocks comprising this sample block

blocks_in_sample instance-attribute ¤

blocks_in_sample: TotalNumberOfBlocks

total number of blocks in the sample

inner_shape property ¤

inner_shape: PerMember[PerAxis[int]]

members property ¤

members: PerMember[Tensor]

the sample block's tensors

origin instance-attribute ¤

origin: Sample

the sample this sample block was taken from

sample_id instance-attribute ¤

sample_id: SampleId

identifier for the sample within its dataset

sample_shape instance-attribute ¤

sample_shape: PerMemberAnno[PerAxis[int]]

the sample shape this block represents a part of

shape property ¤

shape: PerMember[PerAxis[int]]

stat instance-attribute ¤

stat: Stat

computed statistics

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
def as_sample(self) -> 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.
    """
    return Sample(
        members=dict(self.members),
        stat=dict(self.stat),
        id=self.sample_id,
    )

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
@classmethod
def from_meta(
    cls, meta: SampleBlockMeta, data: PerMember[Tensor], stat: Stat
) -> Self:
    return cls(
        sample_shape=meta.sample_shape,
        sample_id=meta.sample_id,
        blocks={
            m: Block.from_meta(b, data=data[m]) for m, b in meta.blocks.items()
        },
        stat=stat,
        block_index=meta.block_index,
        blocks_in_sample=meta.blocks_in_sample,
    )

get_meta ¤

get_meta() -> SampleBlockMeta
Source code in src/bioimageio/core/sample.py
582
583
584
585
586
587
588
589
def get_meta(self) -> SampleBlockMeta:
    return SampleBlockMeta(
        sample_id=self.sample_id,
        blocks={m: b.get_meta() for m, b in self.blocks.items()},
        sample_shape=self.sample_shape,
        block_index=self.block_index,
        blocks_in_sample=self.blocks_in_sample,
    )

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
def get_transformed_meta(
    self, new_axes: PerMember[PerAxis[Union[LinearSampleAxisTransform, int]]]
) -> SampleBlockMeta:
    return SampleBlockMeta(
        sample_id=self.sample_id,
        blocks=dict(self.blocks),
        sample_shape=self.sample_shape,
        block_index=self.block_index,
        blocks_in_sample=self.blocks_in_sample,
    ).get_transformed(new_axes)

sample_block_generator ¤

sample_block_generator(blocks: Iterable[PerMember[BlockMeta]], *, origin: Sample, pad_mode: Union[PadMode, PerMember[PadMode]]) -> Iterable[SampleBlockWithOrigin]
Source code in src/bioimageio/core/sample.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
def sample_block_generator(
    blocks: Iterable[PerMember[BlockMeta]],
    *,
    origin: Sample,
    pad_mode: Union[PadMode, PerMember[PadMode]],
) -> Iterable[SampleBlockWithOrigin]:
    for member_blocks in blocks:
        cons = _ConsolidatedMemberBlocks(member_blocks)
        yield SampleBlockWithOrigin(
            blocks={
                m: Block.from_sample_member(
                    origin.members[m],
                    block=member_blocks[m],
                    pad_mode=pad_mode.get(m, "symmetric")
                    if isinstance(pad_mode, collections.abc.Mapping)
                    else pad_mode,
                )
                for m in origin.members
            },
            sample_shape=origin.shape,
            origin=origin,
            stat=origin.stat,
            sample_id=origin.id,
            block_index=cons.block_index,
            blocks_in_sample=cons.blocks_in_sample,
        )

sample_block_meta_generator ¤

sample_block_meta_generator(blocks: Iterable[PerMember[BlockMeta]], *, sample_shape: PerMember[PerAxis[int]], sample_id: SampleId)
Source code in src/bioimageio/core/sample.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
def sample_block_meta_generator(
    blocks: Iterable[PerMember[BlockMeta]],
    *,
    sample_shape: PerMember[PerAxis[int]],
    sample_id: SampleId,
):
    for member_blocks in blocks:
        cons = _ConsolidatedMemberBlocks(member_blocks)
        yield SampleBlockMeta(
            blocks=dict(member_blocks),
            sample_shape=sample_shape,
            sample_id=sample_id,
            block_index=cons.block_index,
            blocks_in_sample=cons.blocks_in_sample,
        )