def main(args):
    # ----- Load and validate file ---------------------------------------------
    if (args.config_local):
        if not os.path.exists(args.config_local):
            logging.error("Could not find local config file %s",
                          args.config_local)
            return

    dset = h5py.File(args.filename, 'r')
    if not dset:
        logging.error("Not a valid dataset: %s" % args.filename)
        return

    dsetNames = dset.keys()
    logging.info("File %s contains %d groups:", args.filename,
                 len(dset.keys()))
    print(" ", "\n  ".join(dsetNames))

    if not args.in_group:
        if len(dset.keys()) is 1:
            args.in_group = list(dset.keys())[0]
        else:
            logging.error(
                "Input group not specified and multiple groups are present")
            return

    if args.in_group not in dset:
        logging.error("Could not find group %s", args.in_group)
        return

    group = dset.get(args.in_group)

    logging.info("Reading data from group '%s' in file '%s'", args.in_group,
                 args.filename)

    # ----- Determine type of data stored --------------------------------------
    # Raw data is stored as:
    #   /group/config      text of recon config parameters (optional)
    #   /group/xml         text of ISMRMRD flexible data header
    #   /group/data        array of IsmsmrdAcquisition data + header
    #   /group/waveforms   array of waveform (e.g. PMU) data

    # Image data is stored as:
    #   /group/config              text of recon config parameters (optional)
    #   /group/xml                 text of ISMRMRD flexible data header (optional)
    #   /group/image_0/data        array of IsmrmrdImage data
    #   /group/image_0/header      array of ImageHeader
    #   /group/image_0/attributes  text of image MetaAttributes
    isRaw = False
    isImage = False

    if (('data' in group) and ('xml' in group)):
        isRaw = True
    else:
        isImage = True
        imageNames = group.keys()
        logging.info("Found %d image sub-groups: %s", len(imageNames),
                     ", ".join(imageNames))
        # print(" ", "\n  ".join(imageNames))

        for imageName in imageNames:
            image = group[imageName]
            if not (('data' in image) and ('header' in image) and
                    ('attributes' in image)):
                isImage = False

    dset.close()

    if ((isRaw is False) and (isImage is False)):
        logging.error(
            "File does not contain properly formatted MRD raw or image data")
        return

    # ----- Open connection to server ------------------------------------------
    # Spawn a thread to connect and handle incoming data
    logging.info("Connecting to MRD server at %s:%d" %
                 (args.address, args.port))
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((args.address, args.port))

    process = multiprocessing.Process(
        target=connection_receive_loop,
        args=[sock, args.outfile, args.out_group])
    process.daemon = True
    process.start()

    # This connection is only used for outgoing data.  It should not be used for
    # writing to the HDF5 file as multi-threading issues can occur
    connection = Connection(sock, False)

    if (args.config_local):
        fid = open(args.config_local, "r")
        config_text = fid.read()
        fid.close()
        logging.info("Sending local config file '%s' with text:",
                     args.config_local)
        logging.info(config_text)
        connection.send_config_text(config_text)
    else:
        logging.info("Sending remote config file name '%s'", args.config)
        connection.send_config_file(args.config)

    # --------------- Send raw data ----------------------
    if isRaw:
        logging.info("Starting raw data session")
        dset = ismrmrd.Dataset(args.filename, args.in_group, False)

        xml_header = dset.read_xml_header()
        connection.send_metadata(xml_header)

        logging.info("Found %d raw data readouts",
                     dset.number_of_acquisitions())

        for idx in range(dset.number_of_acquisitions()):
            acq = dset.read_acquisition(idx)
            try:
                connection.send_acquisition(acq)
            except:
                logging.error('Failed to send acquisition %d' % idx)

        dset.close()

    # --------------- Send image data ----------------------
    else:
        logging.info("Starting image data session")
        dset = ismrmrd.Dataset(args.filename, args.in_group, False)

        groups = dset.list()
        if ('xml' in groups):
            xml_header = dset.read_xml_header()
        else:
            xml_header = "Dummy XML header"
        connection.send_metadata(xml_header)

        for group in groups:
            if ((group is 'config') or (group is 'xml')):
                logging.info("Skipping group %s", group)

            logging.info("Reading images from '/" + args.in_group + "/" +
                         group + "'")

            for imgNum in range(0, dset.number_of_images(group)):
                image = dset.read_image(group, imgNum)
                image.attribute_string = image.attribute_string.decode('utf-8')

                logging.debug("Sending image %d of %d", imgNum,
                              dset.number_of_images(group) - 1)
                connection.send_image(image)

        dset.close()

    connection.send_close()

    # Wait for incoming data and cleanup
    logging.debug("Waiting for threads to finish")
    process.join()
    logging.info("Session complete")

    return
示例#2
0
# coding: utf-8

import os
import ismrmrd
import ismrmrd.xsd
import numpy as np

from ismrmrdtools import show, transform

# Load file
filename = '/media/george/storge/DeepMRI_data/knee1.h5'
if not os.path.isfile(filename):
    print("%s is not a valid file" % filename)
    raise SystemExit
dset = ismrmrd.Dataset(filename, 'dataset', create_if_needed=False)

header = ismrmrd.xsd.CreateFromDocument(dset.read_xml_header())
enc = header.encoding[0]

# Matrix size
eNx = enc.encodedSpace.matrixSize.x
eNy = enc.encodedSpace.matrixSize.y
eNz = enc.encodedSpace.matrixSize.z
# rNx = enc.reconSpace.matrixSize.x
# rNy = enc.reconSpace.matrixSize.y
# rNz = enc.reconSpace.matrixSize.z

# Field of View
eFOVx = enc.encodedSpace.fieldOfView_mm.x
eFOVy = enc.encodedSpace.fieldOfView_mm.y
eFOVz = enc.encodedSpace.fieldOfView_mm.z
               dwell=1e-6 * dwelltime_us,
               delay=gx.rise_time,
               system=system)

# RF spoiling
rf_spoiling_inc = 117
rf_phase = 0
rf_inc = 0

#%% Set up metadata

meta_folder = '../../dependency/metadata/'
meta_filename = meta_folder + seq_name + '.h5'
if os.path.isfile(meta_filename):
    os.remove(meta_filename)
meta_file = ismrmrd.Dataset(meta_filename)
hdr = ismrmrd.xsd.ismrmrdHeader()
params_hdr = {
    "trajtype": "cartesian",
    "fov": fov * 1e3,
    "res": res * 1e3,
    "slices": slices,
    "slice_res": slice_res,
    "nintl": Ny,
    "ncontrast": len(TE)
}
create_hdr(hdr, params_hdr)

#%% Set up sequence

seq.set_definition(