def sort_stream_by_station(st):
    """
    Sort the traces in stream. Group the traces from same network,
    station, location, and channel code together
    """
    ntotal = len(st)
    sta_dict = {}
    n_added = 0
    for tr in st:
        nw = tr.stats.network
        station = tr.stats.station
        loc = tr.stats.location
        chan = tr.stats.channel[0:2]
        station_id = '%s.%s.%s.%s' % (nw, station, loc, chan)
        if station_id not in sta_dict:
            sta_dict[station_id] = st.select(network=nw, station=station,
                location=loc, channel='%s*' % chan)
            n_added += len(sta_dict[station_id])
    if n_added != ntotal:
        raise ValueError(
            'Sort stream by station errors: number of traces is inconsistent')
    return sta_dict
