### Install pynrrd from GitHub (Bash) Source: https://pynrrd.readthedocs.io/en/stable/_sources/index Installs the pynrrd library directly from its GitHub repository using pip. This is useful for installing the latest development version. ```bash pip install git+https://github.com/mhe/pynrrd.git ``` -------------------------------- ### Install pynrrd via Pip (Bash) Source: https://pynrrd.readthedocs.io/en/stable/_sources/index Installs the pynrrd library using pip from the Python Package Index (PyPI). This is the recommended installation method. ```bash pip install pynrrd ``` -------------------------------- ### Write and Read NRRD with Custom Fields using pynrrd Source: https://pynrrd.readthedocs.io/en/stable/_sources/examples Demonstrates writing and reading NRRD files that include custom header fields. This example shows how to define custom fields and their types for both writing and reading. Requires the numpy and nrrd libraries. ```python import numpy as np import nrrd data = np.linspace(1, 60, 60).reshape((3, 10, 2)) header = {'kinds': ['domain', 'domain', 'domain'], 'units': ['mm', 'mm', 'mm'], 'spacings': [1.0458, 1.0458, 2.5], 'space': 'right-anterior-superior', 'space directions': np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), 'encoding': 'ASCII', 'custom_field_here1': 24.34, 'custom_field_here2': np.array([1, 2, 3, 4])} custom_field_map = {'custom_field_here1': 'double', 'custom_field_here2': 'int list'} nrrd.write('output.nrrd', data, header, custom_field_map=custom_field_map) data2, header2 = nrrd.read('output.nrrd', custom_field_map) print(np.all(data == data2)) >>> True print(header) >>> {'units': ['mm', 'mm', 'mm'], 'spacings': [1.0458, 1.0458, 2.5], 'custom_field_here1': 24.34, 'space': 'right-anterior-superior', 'space directions': array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), 'type': 'double', 'encoding': 'ASCII', 'kinds': ['domain', 'domain', 'domain'], 'dimension': 3, 'custom_field_here2': array([1, 2, 3, 4]), 'sizes': [3, 10, 2]} print(header2) >>> OrderedDict([('type', 'double'), ('dimension', 3), ('space', 'right-anterior-superior'), ('sizes', array([ 3, 10, 2])), ('space directions', array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])), ('kinds', ['domain', 'domain', 'domain']), ('encoding', 'ASCII'), ('spacings', array([1.0458, 1.0458, 2.5 ])), ('units', ['mm', 'mm', 'mm']), ('custom_field_here1', 24.34), ('custom_field_here2', array([1, 2, 3, 4]))]) ``` -------------------------------- ### Read NRRD Header Only with pynrrd Source: https://pynrrd.readthedocs.io/en/stable/_sources/examples Shows how to read only the header information from an NRRD file without loading the actual data. This is useful when you only need metadata. Requires the numpy and nrrd libraries. ```python import numpy as np import nrrd data = np.linspace(1, 50, 50) nrrd.write('output.nrrd', data) header = nrrd.read_header('output.nrrd') print(header) >>> OrderedDict([('type', 'double'), ('dimension', 1), ('sizes', array([50])), ('endian', 'little'), ('encoding', 'gzip')]) ``` -------------------------------- ### Read and Write NRRD with C-order Indexing using pynrrd Source: https://pynrrd.readthedocs.io/en/stable/examples Explains and demonstrates how to handle C-order (row-major) indexing when writing and reading NRRD files with pynrrd. It shows how to specify the index order during writing and how to interpret the 'sizes' field in the header which will always be in Fortran-order. Requires numpy and nrrd. ```python import numpy as np import nrrd # Treat this data array as a 3D volume using C-order indexing # This means we have a volume with a shape of 600x800x70 (x by y by z) data = np.zeros((70, 800, 600)) # Shape is (z, y, x) for C-order # Save the NRRD object with the correct index order nrrd.write('output.nrrd', data, index_order='C') # Read the NRRD file with C-order indexing # Note: We can specify either index order here, this is just a preference unlike in nrrd.write where # it MUST be set based on the data setup data, header = nrrd.read('output.nrrd', index_order='C') # The data shape is exactly the same shape as what we wrote print(data.shape) >>> (70, 800, 600) # But the shape saved in the header is in Fortran-order print(header['sizes']) >>> [600 800 70] # Read the NRRD file with Fortran-order indexing now data, header = nrrd.read('output.nrrd', index_order='F') # The data shape is now in Fortran order, or transposed from what we wrote print(data.shape) >>> (600, 800, 70) print(header['sizes']) >>> [600 800 70] ``` -------------------------------- ### Read and Write NRRD from Memory with pynrrd Source: https://pynrrd.readthedocs.io/en/stable/_sources/examples Illustrates how to write NRRD data to an in-memory byte stream (io.BytesIO) and read it back. This avoids creating temporary files on disk. Requires the io, numpy, and nrrd libraries. ```python import io import numpy as np import nrrd memory_nrrd = io.BytesIO() data = np.linspace(1, 50, 50) nrrd.write(memory_nrrd, data) memory_nrrd.seek(0) header = nrrd.read_header(memory_nrrd) print(header) >>> OrderedDict([('type', 'double'), ('dimension', 1), ('sizes', array([50])), ('endian', 'little'), ('encoding', 'gzip')]) data2 = nrrd.read_data(header, memory_nrrd) print(np.all(data == data2)) >>> True ``` -------------------------------- ### Quick Start: Read and Write NRRD Files (Python) Source: https://pynrrd.readthedocs.io/en/stable/_sources/index Demonstrates the basic usage of the pynrrd library to write a numpy array to an NRRD file and then read it back. It shows how to import the library, create sample data, and use the `write` and `read` functions. ```python import numpy as np import nrrd # Some sample numpy data data = np.zeros((5, 4, 3, 2)) filename = 'testdata.nrrd' # Write to a NRRD file nrrd.write(filename, data) # Read the data back from file readdata, header = nrrd.read(filename) print(readdata.shape) print(header) ``` -------------------------------- ### Write and Read NRRD Data with pynrrd Source: https://pynrrd.readthedocs.io/en/stable/examples Demonstrates the basic workflow of writing a NumPy array to an NRRD file and then reading it back. It verifies that the read data matches the original data and prints the header information. Dependencies include numpy and nrrd. ```python import numpy as np import nrrd data = np.linspace(1, 50, 50) nrrd.write('output.nrrd', data) data2, header = nrrd.read('output.nrrd') print(np.all(data == data2)) >>> True print(header) >>> OrderedDict([('type', 'double'), ('dimension', 1), ('sizes', array([50])), ('endian', 'little'), ('encoding', 'gzip')]) ``` -------------------------------- ### Write and Read NRRD File with pynrrd Source: https://pynrrd.readthedocs.io/en/stable/_sources/examples Demonstrates the basic workflow of writing a NumPy array to an NRRD file and then reading it back. It verifies that the data read matches the original data and prints the header information. Requires the numpy and nrrd libraries. ```python import numpy as np import nrrd data = np.linspace(1, 50, 50) nrrd.write('output.nrrd', data) data2, header = nrrd.read('output.nrrd') print(np.all(data == data2)) >>> True print(header) >>> OrderedDict([('type', 'double'), ('dimension', 1), ('sizes', array([50])), ('endian', 'little'), ('encoding', 'gzip')]) ``` -------------------------------- ### NRRD Read/Write with C-order Indexing using pynrrd Source: https://pynrrd.readthedocs.io/en/stable/_sources/examples Explains and demonstrates how to specify C-order indexing when writing NRRD files with pynrrd. It also shows how to read the file specifying either C-order or Fortran-order indexing, highlighting the effect on data shape and header sizes. Requires the numpy and nrrd libraries. ```python import numpy as np import nrrd # Treat this data array as a 3D volume using C-order indexing # This means we have a volume with a shape of 600x800x70 (x by y by z) data = np.zeros((70, 800, 600)) # Save the NRRD object with the correct index order nrrd.write('output.nrrd', data, index_order='C') # Read the NRRD file with C-order indexing # Note: We can specify either index order here, this is just a preference unlike in nrrd.write where # it MUST be set based on the data setup data, header = nrrd.read('output.nrrd', index_order='C') # The data shape is exactly the same shape as what we wrote print(data.shape) >>> (70, 800, 600) # But the shape saved in the header is in Fortran-order print(header['sizes']) >>> [600 800 70] # Read the NRRD file with Fortran-order indexing now data, header = nrrd.read('output.nrrd', index_order='F') # The data shape is exactly the same shape as what we wrote # The data shape is now in Fortran order, or transposed from what we wrote print(data.shape) >>> (600, 800, 70) ``` -------------------------------- ### Access NRRD Header Sizes in Python Source: https://pynrrd.readthedocs.io/en/stable/_sources/examples Demonstrates how to access the 'sizes' field from a NRRD header dictionary in Python. This typically represents the dimensions of the NRRD data. No external dependencies are required beyond the pynrrd library. ```python print(header['sizes']) >>> [600 800 70] ``` -------------------------------- ### Write and Read NRRD with Custom Fields using pynrrd Source: https://pynrrd.readthedocs.io/en/stable/examples Demonstrates how to write NRRD files with custom header fields and associated type mappings, and then read them back, preserving the custom data. This allows for extended metadata storage. Dependencies include numpy and nrrd. ```python import numpy as np import nrrd data = np.linspace(1, 60, 60).reshape((3, 10, 2)) header = {'kinds': ['domain', 'domain', 'domain'], 'units': ['mm', 'mm', 'mm'], 'spacings': [1.0458, 1.0458, 2.5], 'space': 'right-anterior-superior', 'space directions': np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), 'encoding': 'ASCII', 'custom_field_here1': 24.34, 'custom_field_here2': np.array([1, 2, 3, 4])} custom_field_map = {'custom_field_here1': 'double', 'custom_field_here2': 'int list'} nrrd.write('output.nrrd', data, header, custom_field_map=custom_field_map) data2, header2 = nrrd.read('output.nrrd', custom_field_map) print(np.all(data == data2)) >>> True print(header) >>> {'units': ['mm', 'mm', 'mm'], 'spacings': [1.0458, 1.0458, 2.5], 'custom_field_here1': 24.34, 'space': 'right-anterior-superior', 'space directions': array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), 'type': 'double', 'encoding': 'ASCII', 'kinds': ['domain', 'domain', 'domain'], 'dimension': 3, 'custom_field_here2': array([1, 2, 3, 4]), 'sizes': [3, 10, 2]} print(header2) >>> OrderedDict([('type', 'double'), ('dimension', 3), ('space', 'right-anterior-superior'), ('sizes', array([ 3, 10, 2])), ('space directions', array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])), ('kinds', ['domain', 'domain', 'domain']), ('encoding', 'ASCII'), ('spacings', array([1.0458, 1.0458, 2.5 ])), ('units', ['mm', 'mm', 'mm']), ('custom_field_here1', 24.34), ('custom_field_here2', array([1, 2, 3, 4]))]) ``` -------------------------------- ### Handle Duplicated Header Fields in NRRD with pynrrd Source: https://pynrrd.readthedocs.io/en/stable/_sources/examples Shows how to configure pynrrd to allow reading NRRD files that contain duplicated header fields. By setting `nrrd.reader.ALLOW_DUPLICATE_FIELD = True`, warnings are issued instead of errors. Requires the nrrd library. ```python import nrrd # Set this field to True to enable the reading of files with duplicated header fields nrrd.reader.ALLOW_DUPLICATE_FIELD = True # Name of the file you want to read with a duplicated header field filename = "filename.nrrd" # Read the file # filedata = numpy array # fileheader = header of the NRRD file # A warning is now received about duplicate headers rather than an error being thrown filedata, fileheader = nrrd.read(filename) >>> UserWarning: Duplicate header field: 'space' warnings.warn(dup_message) ``` -------------------------------- ### Read NRRD Header Only with pynrrd Source: https://pynrrd.readthedocs.io/en/stable/examples Shows how to read only the header information from an NRRD file without loading the actual data. This is useful for inspecting metadata or checking file structure. Requires numpy and nrrd libraries. ```python import numpy as np import nrrd data = np.linspace(1, 50, 50) nrrd.write('output.nrrd', data) header = nrrd.read_header('output.nrrd') print(header) >>> OrderedDict([('type', 'double'), ('dimension', 1), ('sizes', array([50])), ('endian', 'little'), ('encoding', 'gzip')]) ``` -------------------------------- ### Quick Start: Reading and Writing NRRD Files with pynrrd Source: https://pynrrd.readthedocs.io/en/stable/index This Python code snippet demonstrates the basic usage of the pynrrd library. It shows how to create sample numpy data, write it to a NRRD file, and then read it back, printing the shape of the data and the header information. Dependencies include numpy. ```python import numpy as np import nrrd # Some sample numpy data data = np.zeros((5, 4, 3, 2)) filename = 'testdata.nrrd' # Write to a NRRD file nrrd.write(filename, data) # Read the data back from file readdata, header = nrrd.read(filename) print(readdata.shape) print(header) ``` -------------------------------- ### Write and Read NRRD Data from Memory with pynrrd Source: https://pynrrd.readthedocs.io/en/stable/examples Illustrates writing NRRD data to an in-memory byte stream (io.BytesIO) and then reading it back. This is useful for scenarios where temporary NRRD data does not need to be persisted to disk. It requires the io, numpy, and nrrd libraries. ```python import io import numpy as np import nrrd memory_nrrd = io.BytesIO() data = np.linspace(1, 50, 50) nrrd.write(memory_nrrd, data) memory_nrrd.seek(0) header = nrrd.read_header(memory_nrrd) print(header) >>> OrderedDict([('type', 'double'), ('dimension', 1), ('sizes', array([50])), ('endian', 'little'), ('encoding', 'gzip')]) data2 = nrrd.read_data(header, memory_nrrd) print(np.all(data == data2)) >>> True ``` -------------------------------- ### Handle Duplicate Header Fields when Reading NRRD with pynrrd Source: https://pynrrd.readthedocs.io/en/stable/examples Shows how to enable the reading of NRRD files that contain duplicate header fields, which would normally raise an error. By setting `nrrd.reader.ALLOW_DUPLICATE_FIELD = True`, a UserWarning is issued instead of an error, allowing processing to continue. Requires the nrrd library. ```python import nrrd # Set this field to True to enable the reading of files with duplicated header fields nrrd.reader.ALLOW_DUPLICATE_FIELD = True # Name of the file you want to read with a duplicated header field filename = "filename.nrrd" # Read the file # filedata = numpy array # fileheader = header of the NRRD file # A warning is now received about duplicate headers rather than an error being thrown filedata, fileheader = nrrd.read(filename) >>> UserWarning: Duplicate header field: 'space' warnings.warn(dup_message) ``` -------------------------------- ### Validate NRRD Magic Line Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/reader Validates the initial 'NRRD' magic line of an NRRD file and extracts the version number. It ensures the file starts with 'NRRD' and handles version checks, raising errors for unsupported versions or invalid formats. This function is crucial for identifying NRRD files and their compatibility. ```python def _validate_magic_line(line: str) -> int: """For NRRD files, the first four characters are always "NRRD", and remaining characters give information about the file format version >>> _validate_magic_line('NRRD0005') 8 >>> _validate_magic_line('NRRD0006') Traceback (most recent call last): ... NrrdError: NRRD file version too new for this library. >>> _validate_magic_line('NRRD') Traceback (most recent call last): ... NrrdError: Invalid NRRD magic line: NRRD """ if not line.startswith('NRRD'): raise NRRDError('Invalid NRRD magic line. Is this an NRRD file?') try: version = int(line[4:]) if version > 5: raise NRRDError(f'Unsupported NRRD file version (version: {version}). This library only supports v5 ' 'and below.') except ValueError: raise NRRDError(f'Invalid NRRD magic line: {line}') return len(line) ``` -------------------------------- ### Import necessary modules for nrrd.reader Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/reader Imports required modules for reading NRRD files, including compression libraries, I/O utilities, regular expressions, command-line parsing, warnings, and typing hints. It also imports specific components from the 'nrrd' package for parsing and data types. ```python import bz2 import io import os import re import shlex import warnings import zlib from collections import OrderedDict from typing import IO, Any, AnyStr, Iterable, Tuple import nrrd from nrrd.parsers import * from nrrd.types import IndexOrder, NRRDFieldMap, NRRDFieldType, NRRDHeader ``` -------------------------------- ### Write NRRD Header and Data (Python) Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/writer This snippet demonstrates writing NRRD header and data. It handles file objects and automatically generates header fields. It supports custom fields and compression levels. ```python header = _handle_header(data, header, index_order) # If the file is a file handle, then write to the file. if isinstance(file, io.IOBase): _write_header(file, header, custom_field_map) _write_data(data, file, header, compression_level=compression_level, index_order=index_order) return ``` -------------------------------- ### NRRD File Format Structure Source: https://pynrrd.readthedocs.io/en/stable/background/about This code snippet illustrates the general structure of an NRRD file, including the magic line, header fields, custom fields, comments, and data placement. It serves as a template for understanding how NRRD files are organized. ```plaintext NRRD # Complete NRRD file format specification at: # http://teem.sourceforge.net/nrrd/format.html : : ... : := := ... := # Comments are identified with a # symbol ``` -------------------------------- ### Representing String Lists in NRRD and Python Source: https://pynrrd.readthedocs.io/en/stable/background/datatypes Shows the NRRD syntax for space-separated strings ('s s ... s') and its parsing into a Python list of strings. This is for handling multiple text entries. ```python [‘this’, ‘is’, ‘space’, ‘separated’] ``` -------------------------------- ### Import Statements and Data Handling Notes for nrrd.writer Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/writer This snippet shows the import statements for the nrrd.writer module and a comment discussing a historical Python limitation regarding large uncompressed data. It highlights the use of libraries like bz2, io, os, zlib, and numpy, along with nrrd-specific components. The comment explains a workaround for handling data exceeding 4GB by reading in smaller chunks, with a default chunk size of 1MB. ```python import bz2 import io import os import zlib from collections import OrderedDict from datetime import datetime from typing import IO, Any, Dict import numpy.typing as npt from nrrd.errors import NRRDError from nrrd.formatters import * from nrrd.reader import _get_field_type from nrrd.types import IndexOrder, NRRDFieldMap, NRRDFieldType, NRRDHeader # Older versions of Python had issues when uncompressed data was larger than 4GB (2^32). This should be fixed in latest # version of Python 2.7 and all versions of Python 3. The fix for this issue is to read the data in smaller chunks. The # chunk size is set to be small here at 1MB since performance did not vary much based on the chunk size. A smaller chunk ``` -------------------------------- ### Main NRRD Write Function Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/writer Orchestrates the writing of NumPy arrays to NRRD files. It handles file paths, header information, compression settings, and detached header creation. It validates input parameters and calls appropriate internal functions based on the specified encoding. ```python def write(file: Union[str, IO], data: npt.NDArray, header: Optional[NRRDHeader] = None, detached_header: bool = False, relative_data_path: bool = True, custom_field_map: Optional[NRRDFieldMap] = None, compression_level: int = 9, index_order: IndexOrder = 'F'): """Write :class:`numpy.ndarray` to NRRD file The :obj:`file` parameter specifies the absolute or relative filename to write the NRRD file to or an io.BytesIO object. If :obj:`file` is a filename and the extension is .nhdr, then the :obj:`detached_header` parameter is set to true automatically. If the :obj:`detached_header` parameter is set to :obj:`True` and the :obj:`filename` ends in .nrrd, then the header file will have the same path and base name as the :obj:`file` but with an extension of .nhdr. In all other cases, the header and data are saved in the same file. :obj:`header` is an optional parameter containing the fields and values to be added to the NRRD header. .. note:: :obj:`detached_header` is ignored if :obj:`file` is io.BytesIO and not a str filename .. note:: ``` -------------------------------- ### nrrd.read() - Read Entire NRRD File Source: https://pynrrd.readthedocs.io/en/stable/reference/reading Reads an entire NRRD file, returning both the header information and the data as a NumPy array. It supports custom field mapping and index order specification. ```APIDOC ## nrrd.read() ### Description Read a NRRD file and return the header and data. ### Method `nrrd.read` ### Endpoint Not applicable (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **filename** (str) - Required - Filename of the NRRD file. - **custom_field_map** (dict[str, Literal['int', 'double', 'string', 'int list', 'double list', 'string list', 'quoted string list', 'int vector', 'double vector', 'int matrix', 'double matrix']]) - Optional - Dictionary used for parsing custom field types where the key is the custom field name and the value is a string identifying datatype for the custom field. - **index_order** (Literal['F', 'C']) - Optional - Specifies the index order of the resulting data array. Either ‘C’ (C-order) or ‘F’ (Fortran-order). ### Returns - **data** (numpy.ndarray) - Data read from NRRD file. - **header** (dict[str, Any]) - Dictionary containing the header fields and their corresponding parsed value. ### Request Example ```python import nrrd data, header = nrrd.read('my_file.nrrd') ``` ### Response #### Success Response (Tuple[ndarray, dict]) - **data** (numpy.ndarray) - The data content of the NRRD file. - **header** (dict) - A dictionary containing all parsed header fields. #### Response Example ```json { "data": "", "header": { "type": "int8", "dimension": 3, "sizes": [100, 100, 100], "space": "left-posterior-superior", "space directions": [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ], "kinds": [ "domain", "domain", "domain" ] } } ``` ``` -------------------------------- ### Representing Integer Matrices in NRRD and Python Source: https://pynrrd.readthedocs.io/en/stable/background/datatypes Details the NRRD syntax for integer matrices ('(i,i,...) (i,i,...) ...') and their conversion into a 2D NumPy array of integers in Python. All rows must be specified. ```python np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) ``` -------------------------------- ### Write Compressed Data (gzip/bzip2) in Chunks Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/writer Writes NRRD data using gzip or bzip2 compression. It initializes the appropriate compressor object and writes the data in chunks, compressing each chunk before writing to the file object. The process includes flushing the compressor to ensure all data is written. ```python # Convert the data into a string raw_data = data.tobytes(order=index_order) # Construct the compressor object based on encoding if header['encoding'] in ['gzip', 'gz']: compressobj = zlib.compressobj(compression_level, zlib.DEFLATED, zlib.MAX_WBITS | 16) elif header['encoding'] in ['bzip2', 'bz2']: compressobj = bz2.BZ2Compressor(compression_level) else: raise NRRDError(f'Unsupported encoding: {header["encoding"]}') # Write the data in chunks (see _WRITE_CHUNKSIZE declaration for more information why) # Obtain the length of the data since we will be using it repeatedly, more efficient start_index = 0 raw_data_len = len(raw_data) # Loop through the data and write it by chunk while start_index < raw_data_len: # End index is start index plus the chunk size # Set to the string length to read the remaining chunk at the end end_index = min(start_index + _WRITE_CHUNKSIZE, raw_data_len) # Write the compressed data fh.write(compressobj.compress(raw_data[start_index:end_index])) start_index = end_index # Finish writing the data fh.write(compressobj.flush()) fh.flush() ``` -------------------------------- ### Basic Datatypes in pynrrd Source: https://pynrrd.readthedocs.io/en/stable/_sources/background/datatypes Demonstrates the mapping of simple NRRD datatypes (int, double, string) to their Python equivalents. These are fundamental types used for single values within NRRD headers. ```python import numpy as np # NRRD Syntax: # Python Datatype: :class:`int` python_int = 12 # NRRD Syntax: # Python Datatype: :class:`float` python_float = 3.14 # NRRD Syntax: # Python Datatype: :class:`str` python_string = 'test' ``` -------------------------------- ### Representing Strings in NRRD and Python Source: https://pynrrd.readthedocs.io/en/stable/background/datatypes Illustrates the NRRD syntax for strings ('s') and their mapping to Python strings. This is used for textual data within headers. ```python ‘test’ ``` -------------------------------- ### Representing Integers in NRRD and Python Source: https://pynrrd.readthedocs.io/en/stable/background/datatypes Demonstrates the NRRD syntax for single integers ('i') and their representation as Python integers. This is a fundamental datatype for numerical data. ```python 12 ``` -------------------------------- ### Representing Integer Vector Lists in NRRD and Python Source: https://pynrrd.readthedocs.io/en/stable/background/datatypes Explains the NRRD syntax for lists of integer vectors ('(i,i,...) (i,i,...) ...') and their parsing into a Python list of NumPy integer arrays. Optional rows are represented as None. ```python [np.array([1, 0, 0]), np.array([0, 1, 0]), None, np.array([0, 0, 1])] ``` -------------------------------- ### nrrd.format_vector_list Source: https://pynrrd.readthedocs.io/en/stable/reference/formatting Formats a list of (N,) NumPy arrays into a NRRD vector list string. ```APIDOC ## nrrd.format_vector_list ### Description Formats a list of (N,) NumPy arrays into a NRRD vector list string. ### Method `nrrd.format_vector_list(x)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **x** (list of ndarray) - Required - The list of (N,) NumPy arrays to convert. ### Request Example ```json { "x": [[1.0, 2.0], [3.0, 4.0]] } ``` ### Response #### Success Response (200) - **vector_list** (str) - The formatted vector list as a string. #### Response Example ```json { "vector_list": "(1.0,2.0);(3.0,4.0)" } ``` ``` -------------------------------- ### Write NRRD Header and Data (Python) Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/writer This code snippet demonstrates how to write NRRD file headers and associated data using the pynrrd library. It handles both cases where the header and data are written to a single file or to separate header (.nhdr) and data (.nrrd) files. It utilizes internal functions like `_write_header` and `_write_data`. ```python elif file.endswith('.nrrd') and detached_header: data_filename = file file = f'{os.path.splitext(file)[0]}.nhdr' header['data file'] = os.path.basename(data_filename) if relative_data_path else os.path.abspath(data_filename) else: # Write header & data as one file data_filename = file detached_header = False with open(file, 'wb') as fh: _write_header(fh, header, custom_field_map) # If header & data in the same file is desired, write data in the file if not detached_header: _write_data(data, fh, header, compression_level=compression_level, index_order=index_order) # If detached header desired, write data to different file if detached_header: with open(data_filename, 'wb') as data_fh: _write_data(data, data_fh, header, compression_level=compression_level, index_order=index_order) ``` -------------------------------- ### nrrd.write API Source: https://pynrrd.readthedocs.io/en/stable/reference/writing This section details the `nrrd.write` function for saving numpy arrays to NRRD files. It covers parameters for file handling, data input, header customization, and compression options. ```APIDOC ## POST /nrrd/write ### Description Writes a `numpy.ndarray` to an NRRD file. Supports various options for header customization, detached file storage, and compression. ### Method POST ### Endpoint /nrrd/write ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (str or io.IOBase) - Required - Filename or file object for the NRRD file. - **data** (numpy.ndarray) - Required - The numpy array data to be saved. - **header** (dict, optional) - Optional - Dictionary containing NRRD header fields and values. - **detached_header** (bool or str, optional) - Optional - If True, saves header and data in separate files. If a string is provided, it specifies the path to the data file when the main file ends with '.nhdr'. Defaults to False. - **relative_data_path** (bool, optional) - Optional - Determines if the data filename in a detached header is relative or absolute. Ignored if not using detached headers. Defaults to True. - **custom_field_map** (dict, optional) - Optional - Maps custom field names to their data types for parsing. - **compression_level** (int, optional) - Optional - Compression level (1-9) for compressed encodings (gzip, bzip). Defaults to 9. - **index_order** (str, optional) - Optional - Specifies the index order for writing ('C' for C-order, 'F' for Fortran-order). Must be consistent with reading order. Defaults to 'F'. ### Request Example ```json { "file": "output.nrrd", "data": [[1, 2], [3, 4]], "header": { "comment": "Example NRRD file" }, "detached_header": false, "compression_level": 6 } ``` ### Response #### Success Response (200) - **message** (str) - Confirmation message indicating the file was written successfully. #### Response Example ```json { "message": "File output.nrrd written successfully." } ``` ``` -------------------------------- ### Handle Unsupported Encodings Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/reader Raises an NRRDError if the specified encoding in the NRRD header is not supported (e.g., not 'raw', 'ASCII', 'gzip', or 'bzip2'). It also ensures the file handle is closed if it was opened internally. ```python else: # Must close the file because if the file was opened above from detached filename, there is no "with" block # to close it for us if data_filename is not None: fh.close() raise NRRDError(f'Unsupported encoding: {header["encoding"]}') ``` -------------------------------- ### nrrd.format_optional_vector_list Source: https://pynrrd.readthedocs.io/en/stable/reference/formatting Formats a list containing (N,) NumPy arrays or None into a NRRD optional vector list string. ```APIDOC ## nrrd.format_optional_vector_list ### Description Formats a list of (N,) NumPy arrays or None into a NRRD optional vector list string. ### Method `nrrd.format_optional_vector_list(x)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **x** (list of ndarray or None) - Required - The list of (N,) NumPy arrays or None to convert. ### Request Example ```json { "x": [[1.0, 2.0], null, [3.0, 4.0]] } ``` ### Response #### Success Response (200) - **vector_list** (str) - The formatted optional vector list as a string. #### Response Example ```json { "vector_list": "(1.0,2.0);none;(3.0,4.0)" } ``` ``` -------------------------------- ### Write NRRD File Header Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/writer Writes the NRRD file header to a given file object. Includes magic number, generation timestamp, and comments. It also formats and writes header fields, including custom fields, in a defined order. ```python def _write_header(file: IO, header: Dict[str, Any], custom_field_map: Optional[NRRDFieldMap] = None): file.write(b'NRRD0005\n') file.write(b'# This NRRD file was generated by pynrrd\n') file.write(b'# on ' + datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S').encode('ascii') + b'(GMT).\n') file.write(b'# Complete NRRD file format specification at:\n') file.write(b'# http://teem.sourceforge.net/nrrd/format.html\n') # Copy the options since dictionaries are mutable when passed as an argument # Thus, to prevent changes to the actual options, a copy is made # Empty ordered_options list is made (will be converted into dictionary) local_options = header.copy() ordered_options = [] # Loop through field order and add the key/value if present # Remove the key/value from the local options so that we know not to add it again for field in _NRRD_FIELD_ORDER: if field in local_options: ordered_options.append((field, local_options[field])) del local_options[field] # Leftover items are assumed to be the custom field/value options ``` -------------------------------- ### Decompress and Parse Bzip2 Encoded Data Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/reader Manages the decompression of bzip2-encoded NRRD data. It reads compressed data in chunks, decompresses it using bz2.BZ2Decompressor, and then parses the decompressed bytes into a NumPy array, applying any byte skip. ```python elif header['encoding'] in ['bzip2', 'bz2']: decompobj = bz2.BZ2Decompressor() # ... (rest of the decompression loop and parsing) data = np.frombuffer(decompressed_data[byte_skip:], dtype) ``` -------------------------------- ### Representing Double Matrices in NRRD and Python Source: https://pynrrd.readthedocs.io/en/stable/background/datatypes Shows the NRRD syntax for double matrices ('(d,d,...) (d,d,...) ...') and their representation as 2D NumPy arrays of floats in Python. Supports 'none' for empty rows, mapped to NaN. ```python np.array([[2.54, 1.3, 0.0], [3.14, 0.3, 3.3], [np.nan, np.nan, np.nan], [0.0, -12.3, -3.3]]) ``` -------------------------------- ### Representing Integer Lists in NRRD and Python Source: https://pynrrd.readthedocs.io/en/stable/background/datatypes Details the NRRD syntax for a sequence of integers ('i i ... i') and its conversion into a 1D NumPy array with integer dtype in Python. Useful for collections of integer values. ```python np.array([1, 2, 3, 4]) ``` -------------------------------- ### nrrd.format_matrix Source: https://pynrrd.readthedocs.io/en/stable/reference/formatting Formats a NumPy array of shape (M,N) into a NRRD matrix string. ```APIDOC ## nrrd.format_matrix ### Description Formats a (M,N) NumPy array into a NRRD matrix string. ### Method `nrrd.format_matrix(x)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **x** (ndarray) - Required - The (M,N) NumPy array to convert. ### Request Example ```json { "x": [[1, 2], [3, 4]] } ``` ### Response #### Success Response (200) - **matrix** (str) - The formatted matrix as a string. #### Response Example ```json { "matrix": "(1,2;3,4)" } ``` ``` -------------------------------- ### Write Custom Fields to NRRD Header Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/writer Appends custom fields to the NRRD header, differentiating between standard and custom fields using a ':=' delimiter for custom entries. It iterates through ordered options, formats field values, and writes them to the file, followed by a closing newline. ```python # So get current size and any items past this index will be a custom value custom_field_start_index = len(ordered_options) # Add the leftover items to the end of the list and convert the options into a dictionary ordered_options.extend(local_options.items()) ordered_options = OrderedDict(ordered_options) for x, (field, value) in enumerate(ordered_options.items()): # Get the field_type based on field and then get corresponding # value as a str using _format_field_value field_type = _get_field_type(field, custom_field_map) value_str = _format_field_value(value, field_type) # Custom fields are written as key/value pairs with a := instead of : delimiter if x >= custom_field_start_index: file.write((f'{field}:={value_str}\n').encode('ascii')) else: file.write((f'{field}: {value_str}\n').encode('ascii')) # Write the closing extra newline file.write(b'\n') ``` -------------------------------- ### Decompress and Parse Gzip Encoded Data Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/reader Handles decompression of gzip-encoded NRRD data. It reads compressed data in chunks, decompresses it, and then parses the resulting bytes into a NumPy array according to the specified dtype and byte skip. ```python if header['encoding'] in ['gzip', 'gz']: decompobj = zlib.decompressobj(zlib.MAX_WBITS | 16) # ... (rest of the decompression loop and parsing) data = np.frombuffer(decompressed_data[byte_skip:], dtype) ``` -------------------------------- ### Representing Double Vector Lists in NRRD and Python Source: https://pynrrd.readthedocs.io/en/stable/background/datatypes Details the NRRD syntax for lists of double vectors ('(d,d,...) (d,d,...) ...') and their conversion into a Python list of NumPy float arrays. Optional rows are handled as None. ```python [np.array([2.54, 1.3, 0.0]), np.array([3.14, 0.3, 3.3]), None, np.array([0.0, -12.3, -3.3])] ``` -------------------------------- ### Representing Quoted String Lists in NRRD and Python Source: https://pynrrd.readthedocs.io/en/stable/background/datatypes Details the NRRD syntax for quoted strings ('“” “” ... “”') and their conversion into a Python list of strings. This handles strings that may contain spaces. ```python [‘one item’, ‘two items’, ‘three’, ‘four’] ``` -------------------------------- ### Read NRRD File Data and Header with pynrrd Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/reader Reads data and header information from an NRRD file. It handles custom field parsing and allows specification of the data array's index order (C-order or Fortran-order). Returns a NumPy array for the data and a dictionary for the header. ```python with open(filename, 'rb') as fh: header = read_header(fh, custom_field_map) data = read_data(header, fh, filename, index_order) return data, header ``` -------------------------------- ### Parse ASCII Data from BytesIO Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/reader Reads data encoded as ASCII text from a BytesIO object, splitting values by spaces and converting them to a specified NumPy dtype. This is for in-memory text-based NRRD data. ```python if isinstance(fh, io.BytesIO): data = np.fromstring(fh.read(), dtype, sep=' ') else: data = np.fromfile(fh, dtype, sep=' ') ``` -------------------------------- ### Handle large uncompressed data in nrrd.reader Source: https://pynrrd.readthedocs.io/en/stable/_modules/nrrd/reader Addresses a historical Python issue where uncompressed data larger than 4GB could cause problems. The code comments explain that this is fixed in newer Python versions and suggests reading data in smaller chunks if issues arise, with a default chunk size of 1GB for performance. ```python # Older versions of Python had issues when uncompressed data was larger than 4GB (2^32). This should be fixed in latest # version of Python 2.7 and all versions of Python 3. The fix for this issue is to read the data in smaller chunks. # Chunk size is set to be large at 1GB to improve performance. If issues arise decompressing larger files, try to reduce ```