def filternodes(pseq, R, trim=True):
    """
    This function trims a collection of paths to those that start or end with nodes in R.
    There is a parameter to prevent trimming self loops (set trim==False).

    When trimmed, nodes with only loops do not appear in the path dictionary at all.
    """

    if isinstance(pseq, dict):

        pd = pseq
        pd2 = {}

        for s in pd:
            if s in R:
                for d in pd[s]:
                    if (not trim or s != d) and d in R:
                        pd2.setdefault(s, dict())[d] = pd[s][d]

        return pd2

    elif isinstance(pseq, list):

        pl2 = []
        for path in pseq:
            s = path[0]
            d = path[-1]
            if s in R and d in R and (s != d or not trim):
                pl2.append(path)

        return pl2

    else:

        raise TypeError