import itertools


def is_weakly_connected_matrix(path_matrix, nodedict, source_nodes, target_nodes):
    """
    Function to check whether nodes in the source_nodes are not weakly connected to
    nodes in the target_nodes.

    Input
    -----
    path_matrix - 1/0 matrix where entry P[i,j] = 1 if nodes with indices i,j are weakly connected
    nodedict - dictionary where keys are node names and values are their corresponding indices in the path matrix
    source_nodes - list of nodes
    target_nodes - list of nodes

    Return
    ------
    True - if nodes in source_nodes and target_nodes form a weakly_connected subgraph
    False - if not
    """
    source_nodes_id, target_nodes_id = [nodedict[s] for s in source_nodes], [
        nodedict[t] for t in target_nodes
    ]

    for s, t in itertools.product(source_nodes_id, target_nodes_id):
        if path_matrix[s, t] == 1 or path_matrix[t, s] == 1:
            return True
    return False