Example #1
0
    def test_12(self):
        inlets = dict(KNS_0=vrtxs.HE2_Source_Vertex('P', 200, 'water', 20))
        outlets = dict(well_0=vrtxs.HE2_Boundary_Vertex('Q', 10))
        outlets.update(well_1=vrtxs.HE2_Boundary_Vertex('Q', 10))
        juncs = dict(junc_0=vrtxs.HE2_ABC_GraphVertex())
        juncs.update(junc_1=vrtxs.HE2_ABC_GraphVertex())

        G = nx.DiGraph()  # Di = directed
        for k, v in {**inlets, **outlets, **juncs}.items():
            G.add_node(k, obj=v)

        G.add_edge('junc_0',
                   'KNS_0',
                   obj=HE2_WaterPipe([300], [-10], [0.1], [1e-5]))
        G.add_edge('junc_1',
                   'KNS_0',
                   obj=HE2_WaterPipe([300], [-10], [0.1], [1e-5]))
        G.add_edge('junc_0',
                   'junc_1',
                   obj=HE2_WaterPipe([300], [0], [0.1], [1e-5]))
        G.add_edge('well_0',
                   'junc_0',
                   obj=HE2_WaterPipe([200], [-10], [0.1], [1e-5]))
        G.add_edge('well_1',
                   'junc_1',
                   obj=HE2_WaterPipe([200], [-10], [0.1], [1e-5]))

        solver = HE2_Solver(G)
        solver.solve()
Example #2
0
    def test_10(self):
        inlets = dict(KNS_0=vrtxs.HE2_Source_Vertex('P', 200, 'water', 20))
        outlets = dict(well_0=vrtxs.HE2_Boundary_Vertex('Q', 10))
        outlets.update(well_1=vrtxs.HE2_Boundary_Vertex('Q', 10))
        juncs = dict(junc_0=vrtxs.HE2_ABC_GraphVertex())

        G = nx.DiGraph()  # Di = directed
        for k, v in {**inlets, **outlets, **juncs}.items():
            G.add_node(k, obj=v)

        G.add_edge('KNS_0',
                   'junc_0',
                   obj=HE2_WaterPipe([300], [10], [0.1], [1e-5]))
        G.add_edge('junc_0',
                   'well_0',
                   obj=HE2_WaterPipe([200], [10], [0.1], [1e-5]))
        G.add_edge('junc_0',
                   'well_1',
                   obj=HE2_WaterPipe([200], [10], [0.1], [1e-5]))

        solver = HE2_Solver(G)
        solver.solve()

        p0_bar, t0_C = 200, 20
        pipe = HE2_WaterPipeSegment()
        pipe.inner_diam_m = 0.1
        pipe.roughness_m = 1e-5
        pipe.L_m = (300 * 300 + 10 * 10)**0.5
        pipe.uphill_m = 10
        x_kgs = 20
        p_junc, t_junc = pipe.calc_segment_pressure_drop(
            p0_bar, t0_C, x_kgs, 1)
        pipe = HE2_WaterPipeSegment()
        pipe.inner_diam_m = 0.1
        pipe.roughness_m = 1e-5
        pipe.L_m = (200 * 200 + 10 * 10)**0.5
        pipe.uphill_m = 10
        x_kgs = 10
        p_well, t_well = pipe.calc_segment_pressure_drop(
            p_junc, t_junc, x_kgs, 1)

        self.assertAlmostEqual(G.nodes['KNS_0']['obj'].result['P_bar'], p0_bar)
        self.assertAlmostEqual(G.nodes['KNS_0']['obj'].result['T_C'], t0_C)

        self.assertAlmostEqual(G.nodes['junc_0']['obj'].result['P_bar'],
                               p_junc)
        self.assertAlmostEqual(G.nodes['junc_0']['obj'].result['T_C'], t_junc)

        self.assertAlmostEqual(G.nodes['well_0']['obj'].result['P_bar'],
                               p_well)
        self.assertAlmostEqual(G.nodes['well_0']['obj'].result['T_C'], t_well)

        self.assertAlmostEqual(G.nodes['well_1']['obj'].result['P_bar'],
                               p_well)
        self.assertAlmostEqual(G.nodes['well_1']['obj'].result['T_C'], t_well)
Example #3
0
    def test_10(self):
        for x_kgs in [-1, 0, 1]:
            for dy in [-10, 0, 10]:
                p0_bar, t0_C = 50, 20
                pipe = HE2_WaterPipeSegment()
                pipe.inner_diam_m = 0.05
                pipe.roughness_m = 1e-5
                pipe.set_pipe_geometry(dx=100, dy=dy)
                p1, t1 = pipe.calc_segment_pressure_drop(
                    p0_bar, t0_C, x_kgs, 1)
                p2, t2 = pipe.calc_segment_pressure_drop(p1, t1, x_kgs, -1)
                self.assertAlmostEqual(p0_bar, p2)
                self.assertAlmostEqual(t0_C, t2)

                data = dict(dxs=[pipe.dx_m / 2] * 2,
                            dys=[pipe.uphill_m / 2] * 2,
                            diams=[pipe.inner_diam_m] * 2,
                            rghs=[pipe.roughness_m] * 2)
                pipeline = HE2_WaterPipe(**data)
                p3, t3 = pipeline.perform_calc_forward(p0_bar, t0_C, x_kgs)
                p4, t4 = pipeline.perform_calc_backward(p3, t3, x_kgs)

                self.assertAlmostEqual(p3, p1)
                self.assertAlmostEqual(t3, t1)
                self.assertAlmostEqual(p4, p2)
                self.assertAlmostEqual(t4, t2)
Example #4
0
 def test_7(self):
     data = dict(dxs=[], dys=[], diams=[], rghs=[])
     pipeline = HE2_WaterPipe(**data)
     p0_bar, t0_C, x_kgs = 50, 20, 10
     p, t = pipeline.perform_calc_forward(p0_bar, t0_C, x_kgs)
     self.assertEqual(p0_bar, p)
     self.assertEqual(t0_C, t)
Example #5
0
def build_dual_schema_from_solved(schema, p_nodes, sources, sinks, juncs):
    G = nx.MultiDiGraph(schema, data=True)
    nodes_P, nodes_Q = {}, {}

    X_sum_dict = dict(zip(G.nodes, [0] * len(G.nodes)))
    for u, v, k in G.edges:
        x = G[u][v][k]['obj'].result['x']
        X_sum_dict[u] -= x
        X_sum_dict[v] += x

    for n in p_nodes:
        nodes_P[n] = G.nodes[n]['obj'].P
        nodes_Q[n] = -X_sum_dict[n]

    for n in juncs:
        nodes_Q[n] = 0
    for n in sources:
        nodes_Q[n] = G.nodes[n]['obj'].Q
    for n in sinks:
        nodes_Q[n] = -G.nodes[n]['obj'].Q

    for n in {**sources, **sinks, **juncs}:
        obj = G.nodes[n]['obj']
        nodes_P[n] = obj.result['P_bar']

    newschema = nx.MultiDiGraph()
    p_n = np.random.choice(G.nodes)
    for n in G.nodes:
        kind = np.random.choice(['P', 'Q'], p=[0.2, 0.8])
        if n == p_n:
            kind = 'P'
        P = nodes_P[n]
        Q = nodes_Q[n]
        value = abs(Q) if kind == 'Q' else P
        obj = None

        if (Q < 0) or (Q == 0 and kind == 'P'):
            obj = vrtxs.HE2_Boundary_Vertex(kind, value)
        elif Q == 0 and kind == 'Q':
            obj = vrtxs.HE2_ABC_GraphVertex()
        elif Q > 0:
            obj = vrtxs.HE2_Source_Vertex(kind, value, 'water', 20)

        newschema.add_node(n, obj=obj)

    for u, v, k in G.edges:
        obj = G[u][v][k]['obj']
        dxs, dys, diams, rghs = [], [], [], []
        for seg in obj.segments:
            dxs += [seg.dx_m]
            dys += [seg.uphill_m]
            diams += [seg.inner_diam_m]
            rghs += [seg.roughness_m]

        newobj = HE2_WaterPipe(dxs, dys, diams, rghs)
        newschema.add_edge(u, v, obj=newobj)

    return newschema
Example #6
0
    def test_11(self):
        inlets = dict(KNS_0=vrtxs.HE2_Source_Vertex('P', 200, 'water', 20))
        outlets = dict(well_0=vrtxs.HE2_Boundary_Vertex('Q', 10))
        outlets.update(well_1=vrtxs.HE2_Boundary_Vertex('Q', 10))
        juncs = dict(junc_0=vrtxs.HE2_ABC_GraphVertex())

        G = nx.DiGraph()  # Di = directed
        for k, v in {**inlets, **outlets, **juncs}.items():
            G.add_node(k, obj=v)

        G.add_edge('junc_0',
                   'KNS_0',
                   obj=HE2_WaterPipe([300], [-10], [0.1], [1e-5]))
        G.add_edge('well_0',
                   'junc_0',
                   obj=HE2_WaterPipe([200], [-10], [0.1], [1e-5]))
        G.add_edge('well_1',
                   'junc_0',
                   obj=HE2_WaterPipe([200], [-10], [0.1], [1e-5]))

        solver = HE2_Solver(G)
        solver.solve()

        inlets = dict(KNS_0=vrtxs.HE2_Source_Vertex('P', 200, 'water', 20))
        outlets = dict(well_0=vrtxs.HE2_Boundary_Vertex('Q', 10))
        outlets.update(well_1=vrtxs.HE2_Boundary_Vertex('Q', 10))
        juncs = dict(junc_0=vrtxs.HE2_ABC_GraphVertex())

        G2 = nx.DiGraph()  # Di = directed
        for k, v in {**inlets, **outlets, **juncs}.items():
            G2.add_node(k, obj=v)

        G2.add_edge('KNS_0',
                    'junc_0',
                    obj=HE2_WaterPipe([300], [10], [0.1], [1e-5]))
        G2.add_edge('junc_0',
                    'well_0',
                    obj=HE2_WaterPipe([200], [10], [0.1], [1e-5]))
        G2.add_edge('junc_0',
                    'well_1',
                    obj=HE2_WaterPipe([200], [10], [0.1], [1e-5]))

        solver = HE2_Solver(G2)
        solver.solve()

        for n in G.nodes:
            res1 = G.nodes[n]['obj'].result
            res2 = G2.nodes[n]['obj'].result
            self.assertAlmostEqual(res1['P_bar'], res2['P_bar'])
            self.assertAlmostEqual(res1['T_C'], res2['T_C'])

        for u, v in G.edges:
            res1 = G[u][v]['obj'].result
            res2 = G2[v][u]['obj'].result
            self.assertAlmostEqual(res1['x'], -res2['x'])
Example #7
0
    def test_9(self):
        p0_bar, t0_C, x_kgs = 50, 20, 10
        pipe = HE2_WaterPipeSegment()
        pipe.inner_diam_m = 0.05
        pipe.roughness_m = 1e-5
        pipe.set_pipe_geometry(dx=100, dy=10)
        p1, t1 = pipe.calc_segment_pressure_drop(p0_bar, t0_C, x_kgs, 1)

        data = dict(dxs=[pipe.dx_m / 2] * 2,
                    dys=[pipe.uphill_m / 2] * 2,
                    diams=[pipe.inner_diam_m] * 2,
                    rghs=[pipe.roughness_m] * 2)
        pipeline = HE2_WaterPipe(**data)
        p2, t2 = pipeline.perform_calc_forward(p0_bar, t0_C, x_kgs)
        self.assertEqual(p1, p2)
        self.assertEqual(t1, t2)
Example #8
0
def generate_random_net_v0(N=15,
                           E=20,
                           SRC=3,
                           SNK=3,
                           Q=20,
                           P=200,
                           D=0.5,
                           H=50,
                           L=1000,
                           RGH=1e-4,
                           SEGS=10,
                           randseed=None):
    '''
    :param N: total nodes count
    :param E: total edges count, cannot be less than N-1
    :param SRC: sources count
    :param SNK: sinks count
    :param Q: maximum boundary flow on source (not sink!)  node
    :param P: maximum boundary pressure on one of source/sink node
    :param D: maximum pipe segment inner diameter on graph edge
    :param H: maximum pipe segment slope
    :param L: maximum pipe segment length
    :param SEGS: maximum pipe segments count
    :return: DiGraph (not Multi)
    This method produce water pipelines network with one pressure constrained node, with constant temperature
    and with some sources/sinks. Network graph can contains cycles
    '''
    np.random.seed(randseed)
    E = max(E, N - 1)
    J = N - SRC - SNK
    juncs = {f'junc_{i}': vrtxs.HE2_ABC_GraphVertex() for i in range(J)}
    coin = np.random.randint(0, 2)
    pressure = np.random.randint(-P, P)
    if coin == 1:
        p_nodes = {
            'p_node_0': vrtxs.HE2_Source_Vertex('P', pressure, 'water', 20)
        }
    else:
        p_nodes = {'p_node_0': vrtxs.HE2_Boundary_Vertex('P', pressure)}

    src_q = np.random.uniform(0, Q, SRC)
    total_q = sum(src_q)
    sink_q = np.random.uniform(0, 1, SNK)
    sink_q = total_q * sink_q / sum(sink_q)
    np.testing.assert_almost_equal(total_q, sum(sink_q))

    SRC = SRC - coin
    SNK = SNK - (1 - coin)
    sources = {
        f'src_{i}': vrtxs.HE2_Source_Vertex('Q', src_q[i], 'water', 20)
        for i in range(SRC)
    }
    sinks = {
        f'sink_{i}': vrtxs.HE2_Boundary_Vertex('Q', -sink_q[i])
        for i in range(SNK)
    }

    nodes = {**p_nodes, **sources, **sinks, **juncs}
    mapping = dict(zip(range(len(nodes)), nodes.keys()))
    UDRG = nx.generators.random_graphs.gnm_random_graph(N,
                                                        E,
                                                        directed=False,
                                                        seed=randseed)
    while nx.algorithms.components.number_connected_components(
            nx.Graph(UDRG)) != 1:
        UDRG = nx.generators.random_graphs.gnm_random_graph(N,
                                                            E,
                                                            directed=False)
    edgelist = []
    for u, v in UDRG.edges:
        if np.random.randint(0, 2):
            edgelist += [(u, v)]
        else:
            edgelist += [(v, u)]
    DRG = nx.DiGraph(edgelist)
    G = nx.relabel.relabel_nodes(DRG, mapping)
    nx.set_node_attributes(G, name='obj', values=nodes)

    # for n in G.nodes():
    #     print(n)

    pipes = dict()
    for u, v in G.edges():
        segs = np.random.randint(SEGS) + 1
        Ls = np.random.uniform(1e-5, L, segs)
        Hs = np.random.uniform(-H, H, segs)
        Ds = np.random.uniform(1e-5, D, segs)
        Rs = np.random.uniform(0, RGH, segs)
        # print(u, v, Ls, Hs, Ds, Rs)
        pipe = HE2_WaterPipe(Ls, Hs, Ds, Rs)
        pipes[(u, v)] = pipe
    nx.set_edge_attributes(G, name='obj', values=pipes)

    return G, dict(p_nodes=p_nodes, juncs=juncs, sources=sources, sinks=sinks)
Example #9
0
def generate_random_net_v1(N=15,
                           E=20,
                           SRC=3,
                           SNK=3,
                           P_CNT=1,
                           Q=20,
                           P=200,
                           D=0.5,
                           H=50,
                           L=1000,
                           RGH=1e-4,
                           SEGS=1,
                           randseed=None):
    '''
    :param N: total nodes count
    :param E: total edges count, cannot be less than N-1
    :param SRC: sources count
    :param SNK: sinks count
    :param P_CNT: count of nodes with fixed pressure
    :param Q: maximum boundary flow on source (not sink!)  node
    :param P: maximum boundary pressure on one of source/sink node
    :param D: maximum pipe segment inner diameter on graph edge
    :param H: maximum pipe segment slope
    :param L: maximum pipe segment length
    :param SEGS: maximum pipe segments count
    :return: MultiDiGraph
    This method produce water pipelines network with some pressure constrained node, with constant temperature
    and with some sources/sinks. Result will be a non-tree, linked multigraph with objects attached to nodes and edges
    '''
    np.random.seed(randseed)
    E = max(E, N - 1)
    B = SRC + SNK
    J = N - B
    juncs = {f'junc_{i}': vrtxs.HE2_ABC_GraphVertex() for i in range(J)}

    kinds = ['P'] * P_CNT + ['Q'] * (B - P_CNT)
    srcs = [True] * SRC + [False] * SNK
    np.random.shuffle(kinds)
    total_q = np.random.uniform(Q * B)
    src_q = np.random.uniform(0, 1, SRC)
    src_q = total_q * src_q / sum(src_q)
    snk_q = np.random.uniform(0, 1, SNK)
    snk_q = total_q * snk_q / sum(snk_q)
    qs = list(src_q) + list(snk_q)

    p_nodes, sources, sinks = dict(), dict(), dict()
    for kind, src, q in zip(kinds, srcs, qs):
        if src and kind == 'P':
            node = vrtxs.HE2_Source_Vertex(kind, np.random.randint(-P, P),
                                           'water', 20)
            name = f'p_node_{len(p_nodes)}'
            p_nodes[name] = node
        elif src and kind == 'Q':
            node = vrtxs.HE2_Source_Vertex(kind, q, 'water', 20)
            name = f'src_{len(sources)}'
            sources[name] = node
        elif not src and kind == 'P':
            node = vrtxs.HE2_Boundary_Vertex(kind, np.random.randint(-P, P))
            name = f'p_node_{len(p_nodes)}'
            p_nodes[name] = node
        elif not src and kind == 'Q':
            node = vrtxs.HE2_Boundary_Vertex(kind, q)
            name = f'snk_{len(sinks)}'
            sinks[name] = node

    nodes = {**p_nodes, **sources, **sinks, **juncs}
    assert len(nodes) == N
    mapping = dict(zip(range(N), nodes.keys()))
    RT = nx.generators.trees.random_tree(N, seed=randseed)
    edgelist = [
        tuple(np.random.choice([u, v], 2, replace=False)) for u, v in RT.edges
    ]
    edgelist += [
        tuple(np.random.choice(range(N), 2, replace=False))
        for i in range(E - (N - 1))
    ]

    MDRG = nx.MultiDiGraph(edgelist)
    G = nx.relabel.relabel_nodes(MDRG, mapping)
    nx.set_node_attributes(G, name='obj', values=nodes)

    pipes = dict()
    for u, v, k in G.edges:
        segs = np.random.randint(SEGS) + 1
        Ls = np.random.uniform(1e-5, L, segs)
        Hs = np.random.uniform(-H, H, segs)
        Ds = np.random.uniform(1e-5, D, segs)
        Rs = np.random.uniform(0, RGH, segs)
        # print(u, v, Ls, Hs, Ds, Rs)
        pipe = HE2_WaterPipe(Ls, Hs, Ds, Rs)
        pipes[(u, v, k)] = pipe
    nx.set_edge_attributes(G, name='obj', values=pipes)

    assert nx.algorithms.components.number_connected_components(
        nx.Graph(G)) == 1

    return G, dict(p_nodes=p_nodes, juncs=juncs, sources=sources, sinks=sinks)
Example #10
0
def make_multigraph_schema_from_OISPipe_dataframes(df_pipes, df_boundaries):
    df = df_pipes[["node_id_start", "node_id_end"]]
    df.columns = ["source", "target"]
    G = nx.from_pandas_edgelist(df, create_using=nx.MultiDiGraph)

    cmpnts = nx.algorithms.components.number_connected_components(nx.Graph(G))
    if cmpnts != 1:
        print('Not single component graph!')
        assert False

    pipes = dict()
    for u, v, k in G.edges:
        df = df_pipes
        df = df[(df.node_id_start == u) & (df.node_id_end == v)]
        d = df.iloc[k].to_dict()

        Ls = [d['L']]
        Hs = [d['altitude_end'] - d['altitude_start']]
        Ds = [d['D'] - 2 * d['S']]
        Rs = [1e-5]

        pipe = HE2_WaterPipe(Ls, Hs, Ds, Rs)
        pipes[(u, v, k)] = pipe
    nx.set_edge_attributes(G, name='obj', values=pipes)

    df = df_boundaries[['Q', 'P']].fillna(-1e9)
    df_boundaries['value'] = df.max(axis=1)

    nodes = dict()
    id_list = list(df_boundaries.id.values)
    for n in G.nodes():
        df = df_boundaries
        if n in id_list:
            df = df[df.id == n]
            d = df.iloc[0].to_dict()
        else:
            obj = vrtxs.HE2_ABC_GraphVertex()
            nodes[n] = obj
            continue
        # if d['kind']=='P':
        #     print(d)

        if d['is_source']:
            obj = vrtxs.HE2_Source_Vertex(d['kind'], d['value'], 'water', 20)
        elif d['kind'] == 'Q' and ((d['Q'] is None) or d['Q'] == 0):
            obj = vrtxs.HE2_ABC_GraphVertex()
        else:
            obj = vrtxs.HE2_Boundary_Vertex(d['kind'], d['value'])
        nodes[n] = obj

    nx.set_node_attributes(G, name='obj', values=nodes)

    for n in G.nodes():
        o = G.nodes[n]['obj']
        assert o is not None

    for u, v, k in G.edges:
        o = G[u][v][k]['obj']
        assert o is not None

    return G