load an ASCII SFR output file into a dictionary of kper: dataframes.  aggregates
    flow to aquifer for segments and returns and flow out at downstream end of segment.

    Parameters
    ----------
    sfr_out_file : str
        SFR ASCII output file

    Returns
    -------
        sfr_dict : dict
            dictionary of {kper:dataframe}

def load_sfr_out(sfr_out_file, selection=None):
    """load an ASCII SFR output file into a dictionary of kper: dataframes.  aggregates
    flow to aquifer for segments and returns and flow out at downstream end of segment.

    Parameters
    ----------
    sfr_out_file : str
        SFR ASCII output file

    Returns
    -------
        sfr_dict : dict
            dictionary of {kper:dataframe}

    """
    assert os.path.exists(sfr_out_file),"couldn't find sfr out file {0}".\
        format(sfr_out_file)
    tag = " stream listing"
    lcount = 0
    sfr_dict = {}
    if selection is None:
        pass
    elif isinstance(selection, str):
        assert selection == 'all', "If string passed as selection only 'all' allowed: {}".format(selection)
    else:
        assert isinstance(
            selection, pd.DataFrame), "'selection needs to be pandas Dataframe. Type {} passed.".format(type(selection))
        assert np.all([sr in selection.columns for sr in ['segment', 'reach']]
                      ), "Either 'segment' or 'reach' not in selection columns"
    with open(sfr_out_file) as f:
        while True:
            line = f.readline().lower()
            lcount += 1
            if line == '':
                break
            if line.startswith(tag):
                raw = line.strip().split()
                kper = int(raw[3]) - 1
                kstp = int(raw[5]) - 1
                [f.readline() for _ in range(4)] #skip to where the data starts
                lcount += 4
                dlines = []
                while True:
                    dline = f.readline()
                    lcount += 1
                    if dline.strip() == '':
                        break
                    draw = dline.strip().split()
                    dlines.append(draw)
                df = pd.DataFrame(data=np.array(dlines)).iloc[:, [3, 4, 6, 7]]
                df.columns = ["segment", "reach", "flaqx", "flout"]
                df.loc[:, "segment"] = df.segment.apply(np.int)
                df.loc[:, "reach"] = df.reach.apply(np.int)
                df.loc[:, "flaqx"] = df.flaqx.apply(np.float)
                df.loc[:, "flout"] = df.flout.apply(np.float)
                df.index = df.apply(lambda x: "{0:03d}_{1:03d}".format(int(x.segment), int(x.reach)), axis=1)
                if selection is None:  # setup for all segs, aggregate
                    gp = df.groupby(df.segment)
                    bot_reaches = gp[['reach']].max().apply(
                        lambda x: "{0:03d}_{1:03d}".format(int(x.name), int(x.reach)), axis=1)
                    df2 = pd.DataFrame(index=gp.groups.keys(), columns=['flaqx', 'flout'])
                    df2['flaqx'] = gp.flaqx.sum()  # only sum distributed output
                    df2['flout'] = df.loc[bot_reaches, 'flout'].values  # take flow out of seg
                    # df = df.groupby(df.segment).sum()
                    df2.loc[:,"segment"] = df2.index
                elif isinstance(selection, str) and selection == 'all':
                    df2 = df
                else:
                    seg_reach_id = selection.apply(lambda x: "{0:03d}_{1:03d}".
                                                   format(int(x.segment), int(x.reach)), axis=1).values
                    for sr in seg_reach_id:
                        if sr not in df.index:
                            s, r = [x.lstrip('0') for x in sr.split('_')]
                            warnings.warn("Requested segment reach pair ({0},{1}) is not in sfr output. Dropping...".
                                          format(int(r), int(s)), PyemuWarning)
                            seg_reach_id = np.delete(seg_reach_id, np.where(seg_reach_id == sr), axis=0)
                    df2 = df.loc[seg_reach_id].copy()
                if kper in sfr_dict.keys():
                    print("multiple entries found for kper {0}, replacing...".format(kper))
                sfr_dict[kper] = df2
    return sfr_dict