Exemplo n.º 1
0
def loadPlasmaParams(filename=None, gui=True):
    """
    Load plasma parameters.

    Returns :class:`blowout.plasma.PlasmaParams`.
    """
    if filename is None and gui:
        import scisalt.qt as _ssqt
        filename = _ssqt.getOpenFileName()

    with _h5.File(name=filename, mode='r') as f:
        _checkversion(f)

        # ======================================
        # Load metadata
        # ======================================
        mattrs = f['metadata'].attrs
        xi_start  = mattrs['xi_start']
        xi_end    = mattrs['xi_end']
        dxi       = mattrs['dxi']
        np        = mattrs['np']

    # ======================================
    # Create class
    # ======================================
    plasmaparams = PlasmaParams(
        xi_start = xi_start,
        xi_end   = xi_end,
        dxi      = dxi,
        np       = np
        )

    return plasmaparams
Exemplo n.º 2
0
def loadDrive(filename=None, gui=True):
    if filename is None and gui:
        import scisalt.qt as _ssqt
        filename = _ssqt.getOpenFileName()

    with _h5.File(name=filename, mode='r') as f:
        _checkversion(f)

        # ======================================
        # Load metadata
        # ======================================
        mattrs = f['metadata'].attrs
        sx     = mattrs['sx']
        sy     = mattrs['sy']
        sz     = mattrs['sz']
        charge = mattrs['charge']
        gamma  = mattrs['gamma']

    return Drive(
        sx     = sx,
        sy     = sy,
        sz     = sz,
        charge = charge,
        gamma  = gamma
        )
Exemplo n.º 3
0
def loadPlasmaIons(plasmaparams=None, filename=None, gui=True):
    """
    Load plasma ions.

    Returns :class:`blowout.ions.PlasmaIons`.
    """
    if filename is None and gui:
        import scisalt.qt as _ssqt
        filename = _ssqt.getOpenFileName()

    with _h5.File(name=filename, mode='r') as f:
        _checkversion(f)

        # ======================================
        # Load metadata
        # ======================================
        mattrs = f['metadata'].attrs

        # ======================================
        # Load data
        # ======================================
        data = f['data']

        img            = _read_arrays(data, 'img')
        bounds         = _read_arrays(data, 'bounds')
        closed_ellipse = _read_arrays(data, 'closed_ellipse')
        xind           = data['xind'].value
        yind           = data['yind'].value
        results_flat = _read_dict(data, 'results_flat')

    # ======================================
    # Create class
    # ======================================
    plas = PlasmaIons(
        PlasmaParams = plasmaparams,
        )

    # ======================================
    # Put data into class
    # ======================================
    plas._img            = img
    plas._bounds         = bounds
    plas._closed_ellipse = closed_ellipse
    plas._xind           = xind
    plas._yind           = yind
    plas._results_flat   = results_flat

    # # ======================================
    # # Load coordinate data
    # # ======================================
    # plas.x_coords  = x_coords
    # plas.y_coords  = y_coords
    # plas.bx_coords = bx_coords
    # plas.by_coords = by_coords

    return plas
Exemplo n.º 4
0
def loadPlasmaE(plasmaparams=None, filename=None, gui=True):
    """
    Load plasma particles.

    Returns :class:`blowout.electrons.PlasmaE`.
    """
    if filename is None and gui:
        import scisalt.qt as _ssqt
        filename = _ssqt.getOpenFileName()

    with _h5.File(name=filename, mode='r') as f:
        _checkversion(f)

        # ======================================
        # Load metadata
        # ======================================
        mattrs = f['metadata'].attrs
        num_parts = mattrs['num_parts']

        # ======================================
        # Load data
        # ======================================
        data = f['data']

        x_coords  = data['x_coords'].value
        y_coords  = data['y_coords'].value
        bx_coords = data['bx_coords'].value
        by_coords = data['by_coords'].value

    # ======================================
    # Create class
    # ======================================
    plas = PlasmaE(
        PlasmaParams = plasmaparams,
        num_parts    = num_parts,
        )

    # ======================================
    # Load coordinate data
    # ======================================
    plas.x_coords  = x_coords
    plas.y_coords  = y_coords
    plas.bx_coords = bx_coords
    plas.by_coords = by_coords

    return plas
Exemplo n.º 5
0
def get_valid_filename(pathstr, experiment, verbose=False, local=False):
    # File doesn't exist
    # This case must terminate in us trying again.
    logger.log(level=loggerlevel, msg='Input is: pathstr={}'.format(pathstr))

    # ======================================
    # Return info if the file is local
    # ======================================
    if local:
        if not _path.exists(pathstr):
            _warnings.warn('File not found: {}'.format(pathstr))
            #  raise IOError('File not found: {}'.format(pathstr))
        pathstr = _path.abspath(pathstr)
        dir_beg = ''
        dir_mid = _path.dirname(pathstr)
        filename = _path.basename(pathstr)
        data_source_type = '2014'
        output = (dir_beg, dir_mid, filename, data_source_type)
        return output

    # ======================================
    # Return info if the file is a nas file
    # ======================================
    if not _path.exists(pathstr):

        logger.log(level=loggerlevel,
                   msg='Path does not exist: {}'.format(pathstr))
        # If file didn't exist, maybe it needs a prefix
        # Append prefix
        prefix = get_remoteprefix()
        pathstr = _path.join(prefix, pathstr)
        # print(prefix)

        # If it didn't work, we need to find the file somehow
        # The prefix may be wrong, the file may not be where we thought,
        # or the drive might not have been mounted and we can mount and
        # try again.
        if not _path.exists(pathstr):
            logger.log(level=loggerlevel,
                       msg='Adding prefix didn'
                       't help, new pathstr={}'.format(pathstr))

            title = 'File not found!'
            maintext = 'File doesn' 't exist:\n\n{}'.format(pathstr)
            subtext = '(External drive may not be mounted.)'
            buttons = _np.array([
                _mtqt.Button('Try again', _QtGui.QMessageBox.AcceptRole),
                _mtqt.Button('Change prefix',
                             _QtGui.QMessageBox.ActionRole,
                             default=True),
                _mtqt.Button('Locate file', _QtGui.QMessageBox.ActionRole),
                _QtGui.QMessageBox.Abort
            ])

            buttonbox = _mtqt.ButtonMsg(maintext,
                                        title=title,
                                        infotext=subtext,
                                        buttons=buttons)
            clicked = buttonbox.clickedArray

            # Change prefix
            if clicked[0]:
                logger.log(level=loggerlevel, msg='Trying again')
            elif clicked[1]:
                logger.log(level=loggerlevel, msg='Changing prefix')

                prefix = choose_remoteprefix(pathstart=prefix)
            # Locate file
            elif clicked[2]:
                logger.log(level=loggerlevel, msg='Locating file')

                # Try to open the path by chopping of the end
                while not _path.isdir(pathstr):
                    lastpath = pathstr
                    pathstr = _path.dirname(pathstr)
                    # If you've chopped all you can chop, look in the base data folder
                    if lastpath == pathstr:
                        pathstr = _get_datapath()
                        break
                pathstr = _mtqt.getOpenFileName(directory=pathstr,
                                                caption='Locate file',
                                                filter='Matlab Files (*.mat)')
            elif clicked[3]:
                logger.log(level=loggerlevel, msg='Aborting')

                raise IOError('Aborting')
            else:
                print('Thar be dragons!')
        logger.log(level=loggerlevel,
                   msg='Trying new pathstr={}'.format(pathstr))

        return get_valid_filename(pathstr)
    elif _path.isdir(pathstr):
        logger.log(level=loggerlevel, msg='Path is a directory')

        patterns = [
            '*scan_info.mat', '*filenames.mat', '{}_*.mat'.format(experiment)
        ]
        files = _np.array([])
        for i, val in enumerate(patterns):
            gfiles = _glob(_path.join(pathstr, val))
            files = _np.append(files, gfiles)
        logger.log(level=loggerlevel,
                   msg='Files match patterns\npatterns: {}\nfiles: {}'.format(
                       patterns, files))

        if files.size == 1:
            logger.log(level=loggerlevel, msg='Found one file.')

            pathstr = files[0]
        elif files.size == 0:
            logger.log(level=loggerlevel, msg='Found no files.')

            title = 'File Not Found'
            maintext = 'No valid file found in folder.'
            subtext = 'Locate manually?'
            buttons = _np.array(
                [_QtGui.QMessageBox.Ok, _QtGui.QMessageBox.Abort],
                dtype=object)

            buttonbox = _mtqt.ButtonMsg(maintext,
                                        title=title,
                                        infotext=subtext,
                                        buttons=buttons)
            clicked = buttonbox.clickedArray

            if clicked[0]:
                logger.log(level=loggerlevel, msg='Trying to locate manually.')

                pathstr = _mtqt.getOpenFileName(directory=pathstr,
                                                caption='Locate file',
                                                filter='Matlab Files (*.mat)')
            elif clicked[1]:
                logger.log(level=loggerlevel, msg='Aborting.')

                raise IOError('Aborting')
        logger.log(level=loggerlevel,
                   msg='Trying new pathstr={}'.format(pathstr))

        return get_valid_filename(pathstr)

    elif _path.isfile(pathstr):
        logger.log(level=loggerlevel, msg='Path is a file.')

        # Check for string endings
        strends = _np.array([
            'scan_info.mat$', 'filenames.mat$',
            '{}_[0-9]*\.mat'.format(experiment)
        ])
        strmatch = _np.empty(strends.size, dtype=object)
        for i, val in enumerate(strends):
            strmatch[i] = _re.search(val, pathstr)

        # True for matches
        strmatch_bool = _np.not_equal(strmatch, None)

        # Warn if there are no matches
        if not _np.any(strmatch_bool):
            logger.log(level=loggerlevel,
                       msg='File doesn'
                       't match patterns={}'.format(strends))

            _warnings.warn(
                'Neither a 2014+ data file, scan_info.mat file, nor a filenames.mat file: {}'
                .format(pathstr))

        if strmatch_bool[2]:
            data_source_type = '2014'
        else:
            data_source_type = '2013'

        logger.log(level=loggerlevel,
                   msg='data_source_type is {}'.format(data_source_type))

        # Check that this is a data file
        # Must have /nas/nas-li20-pm01
        match = _re.search('/nas/nas-li20-pm0', pathstr)
        if match is None:
            raise IOError(
                'Does not point to a file with /nas/nas-li20-pm01 or /nas/nas-li20-pm00 in its path.'
            )

        # Get the directories
        dirstr = _path.dirname(pathstr)
        filename = _path.basename(pathstr)

        dir_beg = dirstr[:match.start()]
        dir_mid = dirstr[match.start() + 1:]

        output = (dir_beg, dir_mid, filename, data_source_type)
        logger.log(level=loggerlevel, msg='Output is: {}'.format(output))

        return output
Exemplo n.º 6
0
def get_valid_filename(pathstr, experiment, verbose=False, local=False):
    # File doesn't exist
    # This case must terminate in us trying again.
    logger.log(level=loggerlevel, msg='Input is: pathstr={}'.format(pathstr))

    # ======================================
    # Return info if the file is local
    # ======================================
    if local:
        if not _path.exists(pathstr):
            _warnings.warn('File not found: {}'.format(pathstr))
            #  raise IOError('File not found: {}'.format(pathstr))
        pathstr = _path.abspath(pathstr)
        dir_beg = ''
        dir_mid = _path.dirname(pathstr)
        filename = _path.basename(pathstr)
        data_source_type = '2014'
        output = (dir_beg, dir_mid, filename, data_source_type)
        return output

    # ======================================
    # Return info if the file is a nas file
    # ======================================
    if not _path.exists(pathstr):

        logger.log(level=loggerlevel, msg='Path does not exist: {}'.format(pathstr))
        # If file didn't exist, maybe it needs a prefix
        # Append prefix
        prefix = get_remoteprefix()
        pathstr = _path.join(prefix, pathstr)
        # print(prefix)

        # If it didn't work, we need to find the file somehow
        # The prefix may be wrong, the file may not be where we thought,
        # or the drive might not have been mounted and we can mount and
        # try again.
        if not _path.exists(pathstr):
            logger.log(level=loggerlevel, msg='Adding prefix didn''t help, new pathstr={}'.format(pathstr))

            title    = 'File not found!'
            maintext = 'File doesn''t exist:\n\n{}'.format(pathstr)
            subtext  = '(External drive may not be mounted.)'
            buttons  = _np.array([
                _mtqt.Button('Try again', _QtGui.QMessageBox.AcceptRole),
                _mtqt.Button('Change prefix', _QtGui.QMessageBox.ActionRole, default=True),
                _mtqt.Button('Locate file', _QtGui.QMessageBox.ActionRole),
                _QtGui.QMessageBox.Abort
                ])

            buttonbox = _mtqt.ButtonMsg(maintext, title=title, infotext=subtext, buttons=buttons)
            clicked   = buttonbox.clickedArray

            # Change prefix
            if clicked[0]:
                logger.log(level=loggerlevel, msg='Trying again')
            elif clicked[1]:
                logger.log(level=loggerlevel, msg='Changing prefix')

                prefix = choose_remoteprefix(pathstart=prefix)
            # Locate file
            elif clicked[2]:
                logger.log(level=loggerlevel, msg='Locating file')

                # Try to open the path by chopping of the end
                while not _path.isdir(pathstr):
                    lastpath = pathstr
                    pathstr  = _path.dirname(pathstr)
                    # If you've chopped all you can chop, look in the base data folder
                    if lastpath == pathstr:
                        pathstr = _get_datapath()
                        break
                pathstr = _mtqt.getOpenFileName(directory=pathstr, caption='Locate file', filter='Matlab Files (*.mat)')
            elif clicked[3]:
                logger.log(level=loggerlevel, msg='Aborting')

                raise IOError('Aborting')
            else:
                print('Thar be dragons!')
        logger.log(level=loggerlevel, msg='Trying new pathstr={}'.format(pathstr))

        return get_valid_filename(pathstr)
    elif _path.isdir(pathstr):
        logger.log(level=loggerlevel, msg='Path is a directory')

        patterns = ['*scan_info.mat', '*filenames.mat', '{}_*.mat'.format(experiment)]
        files    = _np.array([])
        for i, val in enumerate(patterns):
            gfiles = _glob(_path.join(pathstr, val))
            files = _np.append(files, gfiles)
        logger.log(level=loggerlevel, msg='Files match patterns\npatterns: {}\nfiles: {}'.format(patterns, files))

        if files.size == 1:
            logger.log(level=loggerlevel, msg='Found one file.')

            pathstr = files[0]
        elif files.size == 0:
            logger.log(level=loggerlevel, msg='Found no files.')

            title    = 'File Not Found'
            maintext = 'No valid file found in folder.'
            subtext  = 'Locate manually?'
            buttons  = _np.array([
                _QtGui.QMessageBox.Ok,
                _QtGui.QMessageBox.Abort
                ], dtype=object)

            buttonbox = _mtqt.ButtonMsg(maintext, title=title, infotext=subtext, buttons=buttons)
            clicked   = buttonbox.clickedArray

            if clicked[0]:
                logger.log(level=loggerlevel, msg='Trying to locate manually.')

                pathstr = _mtqt.getOpenFileName(directory=pathstr, caption='Locate file', filter='Matlab Files (*.mat)')
            elif clicked[1]:
                logger.log(level=loggerlevel, msg='Aborting.')

                raise IOError('Aborting')
        logger.log(level=loggerlevel, msg='Trying new pathstr={}'.format(pathstr))

        return get_valid_filename(pathstr)

    elif _path.isfile(pathstr):
        logger.log(level=loggerlevel, msg='Path is a file.')

        # Check for string endings
        strends = _np.array(['scan_info.mat$', 'filenames.mat$', '{}_[0-9]*\.mat'.format(experiment)])
        strmatch = _np.empty(strends.size, dtype=object)
        for i, val in enumerate(strends):
            strmatch[i] = _re.search(val, pathstr)

        # True for matches
        strmatch_bool = _np.not_equal(strmatch, None)

        # Warn if there are no matches
        if not _np.any(strmatch_bool):
            logger.log(level=loggerlevel, msg='File doesn''t match patterns={}'.format(strends))

            _warnings.warn('Neither a 2014+ data file, scan_info.mat file, nor a filenames.mat file: {}'.format(pathstr))

        if strmatch_bool[2]:
            data_source_type = '2014'
        else:
            data_source_type = '2013'

        logger.log(level=loggerlevel, msg='data_source_type is {}'.format(data_source_type))

        # Check that this is a data file
        # Must have /nas/nas-li20-pm01
        match = _re.search('/nas/nas-li20-pm0', pathstr)
        if match is None:
            raise IOError('Does not point to a file with /nas/nas-li20-pm01 or /nas/nas-li20-pm00 in its path.')

        # Get the directories
        dirstr   = _path.dirname(pathstr)
        filename = _path.basename(pathstr)
        
        dir_beg = dirstr[:match.start()]
        dir_mid = dirstr[match.start()+1:]

        output = (dir_beg, dir_mid, filename, data_source_type)
        logger.log(level=loggerlevel, msg='Output is: {}'.format(output))

        return output