Example #1
0
 def get_related_families(self, families=[]):
     rows = self.cursor.select(table='family_parent')
     graph = kjGraph([(r.family, r.parent) for r in rows])
     dfamilies = Set()
     for fam in families:
         dfamilies |= Set([fam]) | Set(graph.reachable(fam).items())
     return dfamilies
Example #2
0
    def _find( me, g, cut =kj.kjGraph(), cost4cut =0 ):
        mincost = me.cost
        #me.n_cycles +=1
        cycles = g & ~g.tclosure()      #get core-cycle(s)
#        print mincost
#        prngraph( cycles)
        if not cycles:
            if cut:
                if not mincost or mincost > cost4cut:
                    mincost = me.cost = cost4cut
                    me.cut = cut.items()  #copy
                #else: print 'ignoring',
                #print 'cut:', cost4cut,':',
                #prngraph(cut)
        else:
            for edge in cycles.items():
                #XXX is it cheaper to cut 1 single links than 1 double-link? if not, then multiplicity doesnot matter; cost=1
                #XXX and, is it same to cut 2 single links than 1 double-link???
                c = me.edge_cost[ edge]

                cost = cost4cut+c
                if mincost and cost >= mincost:
                    #print 'abandon', cut
                    continue
                #me.n_del_edges + =1
                cut.add( *edge)
                g = cycles - cut        #delete edge
                mincost = me._find( g, cut, cost)   #update mincost
                cut.delete_arc( *edge)  #restore
        return mincost
Example #3
0
def get_recipients(obj, roles, users):
    recipients = set(users)
    if hasattr(obj, "users"):
        manager = obj.users.now().order_by()
        roles_filter = Q()

        for role in roles:
            if role == ROLE_SIGN:
                roles_filter |= Q(role__startswith=role)
            else:
                roles_filter |= Q(role=role)
        users = list(manager.filter(roles_filter).values_list("user", flat=True).distinct())
        recipients.update(users)
        links = tuple(DelegationLink.current_objects.filter(roles_filter).order_by("role")\
                .values_list("role", "delegator", "delegatee"))
        for role, group in groupby(links, itemgetter(0)):
            gr = kjbuckets.kjGraph(tuple((x[1], x[2]) for x in group))
            for u in users:
                recipients.update(gr.reachable(u).items())
    elif roles == [ROLE_OWNER]:
        if hasattr(obj, "owner"):
            recipients.add(obj.owner_id)
        elif isinstance(obj, User):
            recipients.add(obj.id)
    return recipients
Example #4
0
 def __init__( me, pairs):
     me.graph = kjGraph( pairs)
     me.links = DictAttr()
     me.tag_has = me.links.setdefault( HAS, {})
     me.tag_is = me.links.setdefault( IS, {})
     me.tag_in = me.links.setdefault( IN, {})
     me.recalc()
Example #5
0
 def get_delegators(cls, user, role):
     """
     Returns the list of user's id of the delegators of *user* for the role
     *role*.
     """
     links = cls.objects.filter(role=role).values_list("delegatee", "delegator")
     gr = kjbuckets.kjGraph(tuple(links))
     return gr.reachable(user.id).items()
Example #6
0
def test():
    from kjbuckets import kjGraph
    G = kjGraph( map(None, "pumpernickle", "nicklepumppp") )
    print G
    (iG, l) = factor(G)
    print iG, l
    G2 = unfactor(iG, l)
    print G2
    if G!=G2: print "OOPS"
Example #7
0
def unfactor(indexpairs, allnodelist):
    from kjbuckets import kjGraph
    from time import time
    now = time()
    (left, right) = indexpairs
    size = len(left)
    result = kjGraph(size)
    for i in xrange(size):
        result[allnodelist[left[i]]] = allnodelist[right[i]]
    #print time() - now
    return result
Example #8
0
def factor(G):
    from kjbuckets import kjSet, kjGraph
    allnodes = kjSet(G.keys()) + kjSet(G.values())
    allnodelist = allnodes.items()
    allnodemap = map(None, allnodelist, range(len(allnodelist)))
    nodetoindex = kjGraph(allnodemap)
    pairs = G.items()
    left = pairs[:]
    right = left[:]
    for i in xrange(len(left)):
        (l, r) = pairs[i]
        left[i], right[i] = nodetoindex[l], nodetoindex[r]
    return (left, right), allnodelist
Example #9
0
 def __init__(self):
     self.trans   = {}
     self.acts = {}
     for key, transitions in groupby(self.workflow, attrgetter('role')):
         if not self.trans.has_key(key):
             self.trans[key] = kjGraph()
         for t in transitions:
             arch = (t.a, t.b)
             self.trans[key].add(arch)
             try:
                 self.acts[arch+(t.role,)] += t
             except KeyError:
                 self.acts[arch+(t.role,)] = t
Example #10
0
def tsort(list_of_pairs):
    result = []
    Graph = kjGraph(list_of_pairs)
    notsource = (kjSet(Graph.values()) - kjSet(Graph.keys())).items()
    while Graph:
       sources = kjSet(Graph.keys())
       dests = kjSet(Graph.values())
       startingpoints = sources - dests
       if not startingpoints:
          raise LOOPERROR, "loop detected in Graph"
       for node in startingpoints.items():
           result.append(node)
           del Graph[node]
    return result + notsource
Example #11
0
    def __init__(me, items, relation_attr, key_func=None):
        from kjbuckets import kjGraph
        me.key_func = key_func or (lambda o: o)
        d = {}
        for item in items:
            p = getattr(item, relation_attr)
            d.setdefault(p, []).append(item)
        lst = []
        for k, v in d.iteritems():
            lst.extend([(k, item) for item in v])

        me.kjdict = {}
        kjlist = []
        for i, j in lst:
            keys = [me.key_func(o) for o in (i, j)]
            me.kjdict.update(zip(keys, (i, j)))
            kjlist.append(keys)
        me.graph = kjGraph(kjlist)
Example #12
0
    def calc_mincut( me, g, uncutables =(), exclude_selfrefs =True, count_multiples =True):
        edge_cost = me.edge_cost = {}
        for edge in g:
            if edge in uncutables: cost = len(g)
            else:
                cost = count_multiples and g.count(edge) or 1
            edge_cost[ edge] = cost

        g = kj.kjGraph( g)

        #prngraph( g & ~g.tclosure() ) #- core-cycle

        if exclude_selfrefs:
    #        self_refs = kj.kjSet(g).ident() & g
    #        g = g - self_refs
             g = g - kj.kjSet(g).ident()

        me._find( g)
Example #13
0
def get_recipients(obj, roles, users):
    recipients = set(users)
    if hasattr(obj, "plmobjectuserlink_plmobject"):
        manager = obj.plmobjectuserlink_plmobject.order_by()
        roles_filter = Q()

        for role in roles:
            if role == ROLE_SIGN:
                roles_filter |= Q(role__startswith=role)
            else:
                roles_filter |= Q(role=role)
        users = manager.filter(roles_filter).values_list("user", flat=True)
        recipients.update(users)
        links = DelegationLink.objects.filter(roles_filter)\
                        .values_list("delegator", "delegatee")
        gr = kjbuckets.kjGraph(tuple(links))
        for u in users:
            recipients.update(gr.reachable(u).items())
    elif roles == [ROLE_OWNER]:
        if hasattr(obj, "owner"):
            recipients.add(obj.owner_id)
        elif isinstance(obj, User):
            recipients.add(obj.id)
    return recipients
Example #14
0
 def __init__(self, conn, suite):
     table = ujoin(suite, 'trait', 'parent')
     _TraitRelation.__init__(self, conn, suite, table, name='TraitParent')
     self.graph = kjGraph([(r.trait, r.parent) for r in self.cmd.select()])
Example #15
0
 def clear(self):
     self.G = kjbuckets.kjGraph()
     self.W = {}
Example #16
0
 def __init__(self):
     self.G = kjbuckets.kjGraph()
     self.W = {}