def renumber_segments(self):

        # get renumbering info from per=0
        nseg = self.segment_data[0].nseg
        outseg = self.segment_data[0].outseg

        def reassign_upsegs(r, nexts, upsegs):
            nextupsegs = []
            for u in upsegs:
                r[u] = nexts if u > 0 else u # handle lakes
                nexts -= 1
                nextupsegs += list(nseg[outseg == u])
            return r, nexts, nextupsegs

        ns = len(nseg)

        nexts = ns
        r = {0: 0}
        nextupsegs = nseg[outseg == 0]
        for i in range(ns):
            r, nexts, nextupsegs = reassign_upsegs(r, nexts, nextupsegs)
            if len(nextupsegs) == 0:
                break

        # renumber segments in all stress period data
        for per in self.segment_data.keys():
            self.segment_data[per]['nseg'] = [r[s] for s in nseg]
            self.segment_data[per]['outseg'] = [r[s] for s in outseg]
            self.segment_data[per].sort(order='nseg')
            inds = (outseg > 0) & (nseg > outseg)
            assert not np.any(inds)
            assert len(self.segment_data[per]['nseg']) == self.segment_data[per]['nseg'].max()

        # renumber segments in reach_data
        self.reach_data['iseg'] = [r[s] for s in self.reach_data.iseg]
Renumber segments so that segment numbering is continuous and always increases
dataset/ETHPy150Open modflowpy/flopy/flopy/modflow/mfsfr2.py/ModflowSfr2.renumber_segments