pedemonte96 / causaleffect

Python package to compute conditional and non-conditional causal effects.
MIT License
31 stars 3 forks source link

handling arbitrary strings as variable names #6

Open matthewvowels1 opened 2 years ago

matthewvowels1 commented 2 years ago

Thanks again for releasing this code.

I was wondering if there are any plans to enable it to accept arbitrary strings as node names?

If I have not misunderstood, the following won't work for s in ce.createGraph(s)

s = ['Ab->Qb']
s = ['A_->Q_D']
s = ['0->1']
s = ['_A->Q_']

but it will work with s = ['A_->Q_'] so the behaviour is a little unpredictable.

It would be fantastic if this could handle arbitrary node names. Any plans for this?

Thanks! M

matthewvowels1 commented 2 years ago

I modified the causaleffect.create_graph function, and it seems to work with more arbitrary strings, although I haven't tested it much. Pasting the function here in case it's useful to anyone.


def createGraph(list_edges_string, verbose=False):
    '''Creates a graph from a list of edges in string-format.'''

    vertices = []
    edges = []
    confounding = []
    for e in list_edges_string:
        conf = 0
        e = e.replace(" ", "")
        endpoints = re.split('<->|->|<-', e)
        vertex1, vertex2 = endpoints[0], endpoints[1]

        e = e.replace(vertex1, "").replace(vertex2, "")
        index1, index2 = -1, -1
        if vertex1 in vertices:
            index1 = vertices.index(vertex1)
        else:
            index1 = len(vertices)
            vertices.append(vertex1)
        if vertex2 in vertices:
            index2 = vertices.index(vertex2)
        else:
            index2 = len(vertices)
            vertices.append(vertex2)
        if (e[0] == '<'):
            conf += 1
            edges.append((index2, index1))
        if (e[-1] == '>'):
            conf += 1
            edges.append((index1, index2))
        # confounding edge
        if (conf == 2):
            confounding.append(1)
            confounding.append(-1)
        else:
            confounding.append(0)

    if verbose: print(vertices)
    if verbose: print(edges)
    if verbose: print(confounding)
    g = Graph(vertex_attrs={"name": vertices}, edges=edges, directed=True)

    g.es["confounding"] = confounding
    return g```