Пример #1
0
def create_power_transformer_end(network: NetworkService, pt: PowerTransformer, t: Terminal, end_number: int = 0, **kwargs) -> PowerTransformerEnd:
    en = end_number if end_number > 0 else t.sequence_number
    te = PowerTransformerEnd(mrid=f"{pt.mrid}_e{en}", power_transformer=pt, terminal=t, end_number=en,
                             **kwargs)
    pt.add_end(te)
    network.add(te)
    return te
Пример #2
0
def create_power_transformer_for_connecting(network: NetworkService, mrid: str = "", num_terms: int = 0, phases: PhaseCode = PhaseCode.ABCN,
                                            num_usagepoints: int = 0, num_meters: int = 0, end_args: List[Dict] = None) -> PowerTransformer:
    """
    `end_args` A list of dictionaries, each of which is passed to `create_power_transformer_end` for every terminal created. Possible kwargs are anything that
               can be passed to the `PowerTransformerEnd` constructor. Keep in mind CIM recommends the HV end is first in the list.
    """
    if not mrid:
        mrid = CopyableUUID()

    pt = PowerTransformer(mrid, name="test powertransformer")
    terminals = create_terminals(network, pt, num_terms, phases)

    for eargs, t in zip(end_args, terminals):
        create_power_transformer_end(network, pt, t, **eargs)

    for i in range(num_usagepoints):
        up = UsagePoint(f"{mrid}-up{i}")
        pt.add_usage_point(up)
        up.add_equipment(pt)
        for j in range(num_meters):
            meter = create_meter(network, f"{mrid}-up{i}-m{j}")
            up.add_end_device(meter)
            meter.add_usage_point(up)
        network.add(up)

    network.add(pt)
    return pt
Пример #3
0
async def feeder_network():
    network_service = NetworkService()

    source = create_source_for_connecting(network_service, "source", 1, PhaseCode.AB)
    fcb = create_switch_for_connecting(network_service, "fcb", 2, PhaseCode.AB)
    fsp = create_junction_for_connecting(network_service, "fsp", 2, PhaseCode.AB)
    tx = create_power_transformer_for_connecting(network_service, "tx", 2, PhaseCode.AB, end_args=[{"rated_u": 22000}, {"rated_u": 415}])

    c1 = create_acls_for_connecting(network_service, "c1", PhaseCode.AB)
    c2 = create_acls_for_connecting(network_service, "c2", PhaseCode.AB)

    sub = create_substation(network_service, "f", "f")
    create_feeder(network_service, "f001", "f001", sub, fsp.get_terminal_by_sn(2))

    add_location(network_service, source, 1.0, 1.0)
    add_location(network_service, fcb, 1.0, 1.0)
    add_location(network_service, fsp, 5.0, 1.0)
    add_location(network_service, tx, 10.0, 2.0)
    add_location(network_service, c1, 1.0, 1.0, 5.0, 1.0)
    add_location(network_service, c2, 5.0, 1.0, 10.0, 2.0)

    network_service.connect_terminals(source.get_terminal_by_sn(1), fcb.get_terminal_by_sn(1))
    network_service.connect_terminals(fcb.get_terminal_by_sn(2), c1.get_terminal_by_sn(1))
    network_service.connect_terminals(c1.get_terminal_by_sn(2), fsp.get_terminal_by_sn(1))
    network_service.connect_terminals(fsp.get_terminal_by_sn(2), c2.get_terminal_by_sn(1))
    network_service.connect_terminals(c2.get_terminal_by_sn(2), tx.get_terminal_by_sn(1))

    await SetPhases().run(network_service)
    await AssignToFeeders().run(network_service)
    return network_service
Пример #4
0
def create_geographical_region(network: NetworkService, mrid: str = "", name: str = "") -> GeographicalRegion:
    if not mrid:
        mrid = CopyableUUID()

    gr = GeographicalRegion(mrid, name=name)
    network.add(gr)
    return gr
async def main(argv):
    feeder_mrid = ''
    rpc_port = 50052
    host = "localhost"
    try:
        opts, args = getopt.getopt(argv, "h:i:p:u:",
                                   ["mrid=", "port=", "host="])
    except getopt.GetoptError:
        print('get_feeder.py -i <feeder_mrid> -p <rpc_port> -u <host>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('get_feeder.py -p <rpc_port> -i <feeder_mrid>')
            sys.exit()
        elif opt in ("-i", "--mrid"):
            feeder_mrid = arg
        elif opt in ("-p", "--port"):
            rpc_port = arg
        elif opt in ("-u", "--host"):
            host = arg
    async with connect_async(host=host, rpc_port=rpc_port) as channel:
        service = NetworkService()
        client = NetworkConsumerClient(channel)
        result = (await client.get_feeder(service,
                                          feeder_mrid)).throw_on_error()
        print(feeder_mrid)
        print(service.get(feeder_mrid))
        print_feeder_eq(service)
Пример #6
0
def create_junction_for_connecting(network: NetworkService, mrid: str = "", num_terms: int = 0, phases: PhaseCode = PhaseCode.ABCN) -> Junction:
    if not mrid:
        mrid = CopyableUUID()

    junction = Junction(mrid, name="test junction")
    create_terminals(network, junction, num_terms, phases)
    network.add(junction)
    return junction
Пример #7
0
def create_energy_consumer_for_connecting(network: NetworkService, mrid: str = "", num_terms: int = 0, phases: PhaseCode = PhaseCode.ABCN) -> EnergyConsumer:
    if not mrid:
        mrid = CopyableUUID()

    ec = EnergyConsumer(mrid, name=f"{mrid}-name")
    create_terminals(network, ec, num_terms, phases)
    network.add(ec)
    return ec
Пример #8
0
def create_meter(network: NetworkService, id: str = "") -> Meter:
    if not id:
        id = CopyableUUID()

    meter = Meter(id, name=f"companyMeterId{id}")
    meter.add_organisation_role(create_asset_owner(network, f"company{id}"))
    network.add(meter)
    return meter
def run_feeder():
    with connect(rpc_port=50052) as channel:
        service = NetworkService()
        client = SyncNetworkConsumerClient(channel=channel)
        result = client.get_feeder(service, "PBH3A")
        network = result.result
        print(len(service._unresolved_references))
        print(service.len_of())
Пример #10
0
def add_location(network: NetworkService, psr: PowerSystemResource, *coords: float):
    """
    `coords` XY/longlats to use for the PositionPoint for this location. Must be an even number of coords.
    :return:
    """
    loc = Location()
    for i in range(0, len(coords), 2):
        loc.add_point(PositionPoint(coords[i], coords[i+1]))
    psr.location = loc
    network.add(loc)
Пример #11
0
def create_substation(network: NetworkService, mrid: str = "", name: str = "", sgr: SubGeographicalRegion = None) -> Substation:
    if not mrid:
        mrid = CopyableUUID()

    sub = Substation(mrid, name=name, sub_geographical_region=sgr)
    if sgr is not None:
        sgr.add_substation(sub)

    network.add(sub)
    return sub
async def main():
    async with connect_async(host="localhost", rpc_port=50052) as channel:
        service = NetworkService()
        client = NetworkConsumerClient(channel)
        result = (await client.get_feeder(
            service, '55832b20-0dd2-404e-bce6-61734a025d77')).throw_on_error()
        print(service.get('55832b20-0dd2-404e-bce6-61734a025d77'))

        for equip in service.objects(Equipment):
            print(equip.mrid, equip.name)
Пример #13
0
def create_asset_owner(network: NetworkService, company: str, customer_service: Optional[CustomerService] = None) -> AssetOwner:
    ao = AssetOwner(mrid=f"{company}-owner-role")
    org = Organisation(mrid=company, name=company)
    ao.organisation = org
    network.add(org)
    network.add(ao)

    if customer_service is not None:
        customer_service.add(org)

    return ao
Пример #14
0
def create_subgeographical_region(network: NetworkService, mrid: str = "", name: str = "", gr: GeographicalRegion = None) -> SubGeographicalRegion:
    if not mrid:
        mrid = CopyableUUID()

    sgr = SubGeographicalRegion(mrid, name=name)
    if gr is not None:
        sgr.geographical_region = gr
        gr.add_sub_geographical_region(sgr)

    network.add(sgr)
    return sgr
Пример #15
0
def create_switch_for_connecting(network: NetworkService, mrid: str = "", num_terms: int = 0, phases: PhaseCode = PhaseCode.ABC, *phase_states: bool) -> Breaker:
    if not mrid:
        mrid = CopyableUUID()

    cb = Breaker(mrid, name="test breaker")
    create_terminals(network, cb, num_terms, phases)

    for i, state in enumerate(phase_states):
        cb.set_normally_open(state, phases.single_phases[i])
        cb.set_open(state, phases.single_phases[i])

    network.add(cb)
    return cb
Пример #16
0
def create_feeder(network: NetworkService, mrid: str = "", name: str = "", sub: Substation = None, head_terminal: Terminal = None, *equipment_mrids: str) -> Feeder:
    """
    `equipment_mrids` Equipment to fetch from the network and add to this feeder.
    """
    feeder = Feeder(mrid, name=name, normal_head_terminal=head_terminal, normal_energizing_substation=sub)
    sub.add_feeder(feeder)
    network.add(feeder)

    for mrid in equipment_mrids:
        ce = network.get(mrid, ConductingEquipment)
        ce.add_container(feeder)
        feeder.add_equipment(ce)

    return feeder
Пример #17
0
def create_source_for_connecting(network: NetworkService, mrid: str = "", num_terms: int = 0, phases: PhaseCode = PhaseCode.ABCN) -> EnergySource:
    if not mrid:
        mrid = CopyableUUID()

    source = EnergySource(mrid)
    for phase in phases.single_phases:
        esp = EnergySourcePhase(energy_source=source, phase=phase)

        source.add_phase(esp)
        network.add(esp)

    create_terminals(network, source, num_terms, phases)
    network.add(source)
    return source
Пример #18
0
def feeder_start_point_between_conductors_network():
    network_service = NetworkService()

    sub = create_substation(network_service)

    c1 = create_acls_for_connecting(network_service, "c1", PhaseCode.A)
    fsp = create_junction_for_connecting(network_service, "fsp", 2)
    c2 = create_acls_for_connecting(network_service, "c2", PhaseCode.A)

    network_service.connect_terminals(c1.get_terminal_by_sn(2), fsp.get_terminal_by_sn(1))
    network_service.connect_terminals(c2.get_terminal_by_sn(1), fsp.get_terminal_by_sn(2))

    create_feeder(network_service, "f", "f", sub, fsp.get_terminal_by_sn(2))
    return network_service
def test_resolves_pole_streetlight():
    ns = NetworkService()
    pole = Pole()
    streetlight = Streetlight(pole=pole)
    pole.add_streetlight(streetlight)
    br = resolver.streetlights(pole)
    ns.resolve_or_defer_reference(br, streetlight.mrid)
    assert streetlight.mrid in ns.get_unresolved_reference_mrids(br)
    ns.add(streetlight)
    assert len(list(ns.get_unresolved_reference_mrids(br))) == 0
    streetlight_fetched = ns.get(streetlight.mrid)
    assert streetlight == streetlight_fetched
    async def _retrieve_network(
            self) -> GrpcResult[Union[NetworkResult, Exception]]:
        service = NetworkService()
        result = (await self._get_network_hierarchy()).throw_on_error()

        hierarchy: NetworkHierarchy = result.result
        for mrid in hierarchy.geographical_regions.keys():
            gr_result = await self._get_identified_object(service, mrid)
            if gr_result.was_failure:
                return gr_result

        for mrid in hierarchy.sub_geographical_regions.keys():
            sgr_result = await self._get_identified_object(service, mrid)
            if sgr_result.was_failure:
                return sgr_result

        for mrid in hierarchy.substations.keys():
            substation_result = await self._get_identified_object(
                service, mrid)
            if substation_result.was_failure:
                return substation_result

        for mrid in hierarchy.feeders.keys():
            feeder_result = await self._get_identified_object(service, mrid)
            if feeder_result.was_failure:
                return feeder_result

        failed = set()
        while service.has_unresolved_references():
            # we only want to break out if we've been trying to resolve the same set of references as we did in the last iteration.
            # so if we didn't resolve anything in the last iteration (i.e, the number of unresolved refs didn't change) we keep a
            # record of those mRIDs and break out of the loop if they don't change after another fetch.

            failed = set()
            for mrid in service.unresolved_mrids():
                result = (await
                          self._get_identified_object(service,
                                                      mrid)).throw_on_error()
                if result.was_failure or result.result is None:
                    failed.add(mrid)

            if failed:
                if failed == set(service.unresolved_mrids()):
                    return GrpcResult(NetworkResult(service, failed))

        return GrpcResult(NetworkResult(service, failed))
Пример #21
0
def create_terminals(network: NetworkService, ce: ConductingEquipment, num_terms: int, phases: PhaseCode = PhaseCode.ABCN) -> List[Terminal]:
    terms = []
    for i in range(1, num_terms + 1):
        term = Terminal(mrid=f"{ce.mrid}_t{i}", conducting_equipment=ce, phases=phases, sequence_number=i)
        ce.add_terminal(term)
        assert network.add(term)
        terms.append(term)

    return terms
Пример #22
0
 async def test_retrieve_supported_types(self, networkidentifiedobjects):
     network_service = NetworkService()
     for nio in networkidentifiedobjects:
         response = GetIdentifiedObjectsResponse(
             objectGroup=IdentifiedObjectGroup(identifiedObject=nio))
         stub = MagicMock(
             **{"getIdentifiedObjects.return_value": [response]})
         client = NetworkConsumerClient(stub=stub)
         pbio = getattr(nio, nio.WhichOneof("identifiedObject"), None)
         result = await client.get_identified_objects(
             network_service, [pbio.mrid()])
         assert result.was_successful
         if pbio.mrid():
             assert result.result.value[pbio.mrid(
             )] is not None, f"type: {nio.WhichOneof('identifiedObject')} mrid: {pbio.mrid()}"
             assert network_service.get(
                 pbio.mrid()) is result.result.value[pbio.mrid()]
         else:
             assert pbio.mrid() in result.result.failed
    async def _get_feeder(self, service: NetworkService,
                          mrid: str) -> GrpcResult[MultiObjectResult]:
        feeder_response = await self._get_identified_object(service, mrid)
        if feeder_response.was_failure:
            return feeder_response
        feeder: Feeder = feeder_response.result

        if not feeder:
            return GrpcResult(result=None)

        equipment_objects = await self._get_identified_objects(
            service,
            service.get_unresolved_reference_mrids(
                resolver.ec_equipment(feeder)))
        if equipment_objects.was_failure:
            return equipment_objects

        resolvers = list()
        resolvers.append(resolver.normal_energizing_substation(feeder))
        for equip in feeder.equipment:
            try:
                for terminal in equip.terminals:
                    resolvers.append(resolver.connectivity_node(terminal))
                if isinstance(equip, Conductor):
                    resolvers.append(
                        resolver.per_length_sequence_impedance(equip))
                    resolvers.append(resolver.asset_info(equip))
            except AttributeError:
                pass  # Not ConductingEquipment.
            resolvers.append(resolver.psr_location(equip))

        mrids = service.get_unresolved_reference_mrids(resolvers)
        objects = await self._get_identified_objects(service, mrids)
        if objects.was_failure:
            return objects
        objects.result.value.update(
            equipment_objects.result.value)  # Combine with previous results
        objects.result.value[feeder.mrid] = feeder  # Add feeder to result
        return GrpcResult(result=MultiObjectResult(
            objects.result.value,
            objects.result.failed.union(equipment_objects.result.failed)))
Пример #24
0
def test_associated_terminal_tracker():
    ns = NetworkService()
    tracker = AssociatedTerminalTracker()

    assert tracker.has_visited(None)
    assert tracker.has_visited(Terminal())
    assert not tracker.visit(None)
    assert not tracker.visit(Terminal())

    acls1 = create_acls_for_connecting(ns, "acls1")
    t1 = acls1.get_terminal_by_sn(1)
    assert not tracker.has_visited(t1)
    assert tracker.visit(t1)
    assert tracker.has_visited(t1)
    async def _process_identified_objects(
            self, service: NetworkService,
            mrids: Iterable[str]) -> AsyncGenerator[IdentifiedObject, None]:
        to_fetch = set()
        existing = set()
        for mrid in mrids:
            try:
                fetched = service.get(mrid)
                existing.add((fetched, fetched.mrid))
            except KeyError:
                to_fetch.add(mrid)

        responses = self._stub.getIdentifiedObjects(
            GetIdentifiedObjectsRequest(mrids=to_fetch))
        for response in responses:
            og = response.objectGroup
            yield extract_identified_object(service, og.identifiedObject)
            for owned_obj in og.ownedIdentifiedObject:
                yield extract_identified_object(service, owned_obj)
Пример #26
0
def create_acls_for_connecting(network: NetworkService, mrid: str = "", phases: PhaseCode = PhaseCode.ABCN, length: float = 0.0,
                               plsi_mrid: str = "perLengthSequenceImepedance",
                               wi_mrid: str = "wireInfo") -> AcLineSegment:
    if not mrid:
        mrid = CopyableUUID()

    try:
        plsi = network.get(plsi_mrid, PerLengthSequenceImpedance)
    except KeyError:
        plsi = PerLengthSequenceImpedance(plsi_mrid)
        network.add(plsi)

    try:
        wi = network.get(wi_mrid, WireInfo)
    except:
        wi = WireInfo(wi_mrid)
        network.add(wi)

    acls = AcLineSegment(mrid, name=f"{mrid} name", per_length_sequence_impedance=plsi, asset_info=wi, length=length)
    create_terminals(network, acls, 2, phases)
    network.add(acls)
    return acls
Пример #27
0
    async def test_get_identifiedobject(self, aclinesegment):
        network_service = NetworkService()
        nio = NetworkIdentifiedObject(acLineSegment=aclinesegment)
        response = GetIdentifiedObjectsResponse(
            objectGroup=IdentifiedObjectGroup(identifiedObject=nio))
        stub = MagicMock(**{"getIdentifiedObjects.return_value": [response]})
        client = NetworkConsumerClient(stub=stub)
        pbio = getattr(nio, nio.WhichOneof("identifiedObject"), None)
        result = await client.get_identified_object(network_service,
                                                    pbio.mrid())
        assert result.was_successful
        assert result.result is not None
        assert result.result.mrid == pbio.mrid()

        stub = MagicMock(**{"getIdentifiedObjects.return_value": []})
        client = NetworkConsumerClient(stub=stub)
        pbio = getattr(nio, nio.WhichOneof("identifiedObject"), None)
        result = await client.get_identified_object(network_service,
                                                    "fakemrid")
        assert result.was_successful
        assert result.result is None
Пример #28
0
def feeder_start_point_to_open_point_network(request):
    normally_open = request.param[0]
    currently_open = request.param[1]
    network_service = NetworkService()
    sub = create_substation(network_service)
    fsp = create_junction_for_connecting(network_service, "fsp", 1)
    c1 = create_acls_for_connecting(network_service, "c1", PhaseCode.A)
    op = create_switch_for_connecting(network_service, "op", 2, PhaseCode.A)
    c2 = create_acls_for_connecting(network_service, "c2", PhaseCode.A)

    op.set_normally_open(normally_open)
    op.set_open(currently_open)

    network_service.connect_terminals(c1.get_terminal_by_sn(1), fsp.get_terminal_by_sn(1))
    network_service.connect_terminals(c1.get_terminal_by_sn(2), op.get_terminal_by_sn(1))
    network_service.connect_terminals(c2.get_terminal_by_sn(1), op.get_terminal_by_sn(2))

    create_feeder(network_service, "f", "f", sub, fsp.get_terminal_by_sn(1))
    return network_service
Пример #29
0
def create_feeder():
    """
    Creates a small feeder based on https://bitbucket.org/zepben/cimdemo/src/master/lv_simple_net.png.
    :return: A NetworkService representing the feeder.
    """
    # Create the network. This will be used for sending all components of the feeder.
    network = NetworkService()

    # A network has multiple BaseVoltage's, each used to represent the intended nominal voltage of equipment operating
    # on a segment of the network.
    bv_11kv = BaseVoltage(mrid='11kv', nominal_voltage=11000, name='11kV')

    # We must add the BaseVoltage to the network directly if any ConductingEquipment relies on it.
    network.add(bv_11kv)

    # There is no required order for adding equipment to the network, as long as its dependencies are satisfied.
    # In this example, we will start with the main EnergySource, working towards the leaf nodes in the network
    # in a depth-first traversal.

    # Geographic coordinates and location details are stored as a Location against any type extending
    # PowerSystemResource.
    energy_source_loc = Location(mrid='es-loc')
    energy_source_loc.add_point(PositionPoint(152.9100276,-31.43952262))
    network.add(energy_source_loc)

    # Create the EnergySource, specifying any desired parameters plus passing in our BaseVoltage, EnergySourcePhase's,
    # Location, and Terminals. Note that terminals accepts a list of Terminals, however an EnergySource only has one.
    energy_source = EnergySource(mrid='EnergySource',
                                 name='Source',
                                 base_voltage=bv_11kv,
                                 voltage_magnitude=11000,
                                 voltage_angle=0.0,
                                 location=energy_source_loc)

    # Note that all types extending IdentifiedObject take an mrid. If it is not provided, a UUID will be generated
    # for you. We create a Terminal specifying its phase and connectivity_node. The ConnectivityNode will also
    # receive a reference to the Terminal as part of the constructor.
    es_t1 = Terminal(mrid='es-t1', phases=PhaseCode.ABC, conducting_equipment=energy_source)

    # This is the starting ConnectivityNode in our network
    # At a bare minimum, at least one connectivity node and one Terminal is required for an EnergySource to be
    # connected to the network. Note however that the network will allow you to add disconnected equipment if that
    # suits your use case.
    # NetworkService.connect_by_mrid is a helper method that will create a ConnectivityNode in the NetworkService for
    # the given mRID (in this case, SourceNode), and connect the passed in Terminal to it (es_t1).
    # You should ensure you always call connect_by_mrid or connect_by_terminal, as this keeps the references between
    # the ConnectivityNode and Terminal in sync.
    network.connect_by_mrid(es_t1, "SourceNode")

    # Any ConductingEquipment must have its terminals added to it before being utilised. This can be performed through
    # the constructor via the terminals_ parameter, or added after initialisation like below. The Terminal must also
    # have its conducting_equipment specified for add_terminal() to succeed.
    energy_source.add_terminal(es_t1)
    network.add(es_t1)

    # An EnergySource has an EnergySourcePhase representing each phase it supplies. This is primarily used for tracing,
    # however more attributes will be added at a later date.
    es_phases = [EnergySourcePhase(mrid="esp1", energy_source=energy_source, phase=SinglePhaseKind.A),
                 EnergySourcePhase(mrid="esp2", energy_source=energy_source, phase=SinglePhaseKind.B),
                 EnergySourcePhase(mrid="esp3", energy_source=energy_source, phase=SinglePhaseKind.C)]

    for phase in es_phases:
        energy_source.add_phase(phase)
        network.add(phase)

    network.add(energy_source)

    # Create the PowerTransformer
    # Note BaseVoltage is not used for the PowerTransformer as it has two separate voltages. rated_u must be populated
    # on both ends.
    power_transformer = PowerTransformer(mrid="PowerTransformer", vector_group=VectorGroup.DYN11)
    delta_pt_end = PowerTransformerEnd(mrid="delta-pt-end", rated_s=800000, rated_u=11000, connection_kind=WindingConnection.D, power_transformer=power_transformer)
    delta_tap_changer = RatioTapChanger(mrid="rtc1", high_step=4, low_step=1, step=2.0, neutral_step=2, normal_step=2, step_voltage_increment=0.25, transformer_end=delta_pt_end)
    delta_pt_end.ratio_tap_changer = delta_tap_changer

    network.add(delta_tap_changer)
    network.add(delta_pt_end)

    wye_pt_end = PowerTransformerEnd(mrid="wye-pt-end", rated_s=800000, rated_u=416, connection_kind=WindingConnection.Yn, power_transformer=power_transformer)
    wye_tap_changer = RatioTapChanger(mrid="rtc2", high_step=2, low_step=1, step=2.0, neutral_step=2, normal_step=2, step_voltage_increment=0.5, transformer_end=wye_pt_end)
    wye_pt_end.ratio_tap_changer = wye_tap_changer

    network.add(wye_tap_changer)
    network.add(wye_pt_end)

    # Terminals are required on the PowerTransformer, corresponding to each PowerTransformerEnd
    # Note that ordering of the Terminals is significant, and must correspond with the ordering of the ends.
    delta_terminal = Terminal(mrid='pt-t1', phases=PhaseCode.ABC, conducting_equipment=power_transformer)
    # Connect the terminal to the source ConnectivityNode
    network.connect_by_mrid(delta_terminal, 'SourceNode')
    power_transformer.add_terminal(delta_terminal)
    network.add(delta_terminal)

    # Set the terminal on the Delta PowerTransformerEnd (This allows us to correlate the Terminal with the voltage)
    delta_pt_end.terminal = delta_terminal

    # The wye Terminal is connected to the Bus 0 ConnectivityNode
    wye_terminal = Terminal(mrid='pt-t2', phases=PhaseCode.ABCN, conducting_equipment=power_transformer)
    # Connect the terminal to the ConnectivityNode
    network.connect_by_mrid(wye_terminal, 'Bus 0')
    power_transformer.add_terminal(wye_terminal)
    network.add(wye_terminal)

    # Set the terminal on the WYE PowerTransformerEnd (This allows us to correlate the Terminal with the voltage)
    wye_pt_end.terminal = wye_terminal

    # Location
    pt_loc = Location(mrid='pt-loc')
    pt_loc.add_point(PositionPoint(152.9100276,-31.43952262))
    power_transformer.location = pt_loc
    network.add(pt_loc)

    # Add the ends to the network
    power_transformer.add_end(delta_pt_end)
    power_transformer.add_end(wye_pt_end)

    # Add the PowerTransformer to the network
    network.add(power_transformer)

    # Create the Breaker. It requires a new BaseVoltage of 416V
    # Note Breaker constructor defaults all switch states to CLOSED.
    bv_416v = BaseVoltage(mrid="416v", nominal_voltage=416, name="0.416kV")
    network.add(bv_416v)

    # Create a location for the Breaker
    breaker_loc = Location(mrid='breaker-loc')
    breaker_loc.add_point(PositionPoint(152.9100276,-31.43952262))
    network.add(breaker_loc)

    breaker = Breaker(mrid="Breaker", base_voltage=bv_416v, location=breaker_loc)

    t1 = Terminal(mrid='br-t1', phases=PhaseCode.ABCN, conducting_equipment=breaker)
    network.connect_by_mrid(t1, 'Bus 0')
    breaker.add_terminal(t1)
    network.add(t1)

    t2 = Terminal(mrid='br-t2', phases=PhaseCode.ABCN, conducting_equipment=breaker)
    network.connect_by_mrid(t2, 'Bus 1')
    breaker.add_terminal(t2)
    network.add(t2)

    # Add the Breaker to the network
    network.add(breaker)

    # Create first AcLineSegment with a PerLengthSequenceImpedance and Location with two position_points
    # The properties of the conductor are contained in a PerLengthSequenceImpedance. All amounts are per metre.
    plsi_1 = PerLengthSequenceImpedance(mrid="4c_70", r=466.0, x=71.0, r0=1505.0, x0=83.0)
    network.add(plsi_1)

    # A line typically has two longlats representing each terminal point. Note these must be added in order and
    # correspond to the matching Terminal.
    acls1_loc = Location(mrid="acls1-loc")
    acls1_loc.add_point(PositionPoint(152.9144265,-31.43913816))
    acls1_loc.add_point(PositionPoint(152.910199,-31.439523))
    network.add(acls1_loc)

    acls1 = AcLineSegment(mrid="acls1",name="acls1",
                          base_voltage=bv_416v,
                          length=31.71938,
                          per_length_sequence_impedance=plsi_1,
                          location=acls1_loc)

    # Create and add the Terminal's for this ACLS
    acls1_t1 = Terminal(mrid='acls1-t1', phases=PhaseCode.ABCN, conducting_equipment=acls1)
    network.connect_by_mrid(acls1_t1, "Bus 1")
    acls1.add_terminal(acls1_t1)
    network.add(acls1_t1)

    acls1_t2 = Terminal(mrid='acls1-t2', phases=PhaseCode.ABCN, conducting_equipment=acls1)
    network.connect_by_mrid(acls1_t2, "Bus 25")
    acls1.add_terminal(acls1_t2)
    network.add(acls1_t2)

    # Add the ACLS to the network after adding all its dependencies
    network.add(acls1)

    # Create the rest of the lines. These are all quite similar to above.
    create_lines(network, bv_416v, "Bus 25", plsi_1)

    # Create first EnergyConsumer on 230V with a single phase
    bv_230v = BaseVoltage(mrid="230v", nominal_voltage=230, name="0.23kV")
    network.add(bv_230v)

    # Each EnergyConsumer has a list of phases it is connected on. These are optional and only used to
    # specify additional properties per phase when they are known.
    ecp = [EnergyConsumerPhase(mrid='ecp1', phase=SinglePhaseKind.A, p_fixed=800.0, q_fixed=200.0)]
    network.add(ecp[0])

    # Creaote the EnergyConsumer's Location
    ec1_loc = Location(mrid="ec1-loc")
    ec1_loc.add_point(PositionPoint(152.9172589,-31.44307421))
    network.add(ec1_loc)

    energy_consumer1 = EnergyConsumer(mrid="EnergyConsumer1",
                                      p=1000,
                                      q=334.27413609633844,
                                      name="Load 1",
                                      phase_connection=PhaseShuntConnectionKind.Y,
                                      energy_consumer_phases=ecp,
                                      base_voltage=bv_230v,
                                      location=ec1_loc)

    # Create and add the Terminal, Note that the ConnectivityNode will be retrieved from the network (Bus 34 was created in create_lines())
    ec1_t1 = Terminal(mrid='ec1-t1', phases=PhaseCode.A, conducting_equipment=energy_consumer1)
    network.connect_by_mrid(ec1_t1, "Bus 34")
    energy_consumer1.add_terminal(ec1_t1)
    network.add(ec1_t1)

    # Add the energy consumer to the network
    network.add(energy_consumer1)

    # Create PV EnergySource with a single phase and a location
    esp = [EnergySourcePhase(mrid='esp4', phase=SinglePhaseKind.A)]
    network.add(esp[0])

    es2_loc = Location(mrid="es2-loc")
    es2_loc.add_point(PositionPoint(152.9172589,-31.44307421))
    network.add(es2_loc)

    energy_source_pv = EnergySource(mrid="PV-DG",
                                    name='PV Distributed Generator',
                                    base_voltage=bv_230v,
                                    voltage_magnitude=416,
                                    voltage_angle=9.0,
                                    energy_source_phases=esp,
                                    location=es2_loc)
    es2_t1 = Terminal(mrid='es2-t1', phases=PhaseCode.A, conducting_equipment=energy_source_pv)
    network.connect_by_mrid(es2_t1, "Bus 34")
    energy_source_pv.add_terminal(es2_t1)
    network.add(es2_t1)

    # Add the EnergySource to the network.
    network.add(energy_source_pv)

    # Create second EnergyConsumer with a single phase of B and a Location.
    ecp = [EnergyConsumerPhase(mrid="ecp2", phase=SinglePhaseKind.B, p_fixed=800.0, q_fixed=200.0)]
    network.add(ecp[0])

    ec2_loc = Location(mrid="ec2-loc")
    ec2_loc.add_point(PositionPoint(152.9121734,-31.44320236))
    network.add(ec2_loc)

    energy_consumer2 = EnergyConsumer(mrid="EnergyConsumer2",
                                      p=1000,
                                      q=334.27413609633844,
                                      name="Load 2",
                                      phase_connection=PhaseShuntConnectionKind.Y,
                                      energy_consumer_phases=ecp,
                                      base_voltage=bv_230v,
                                      location=ec2_loc)

    # Create and connect the Terminal.
    ec2_t1 = Terminal(mrid='ec2-t1', phases=PhaseCode.B, conducting_equipment=energy_consumer2)
    network.connect_by_mrid(ec2_t1, "Bus 47")
    energy_consumer2.add_terminal(ec2_t1)
    network.add(ec2_t1)

    # Add the EnergyConsumer to the network
    network.add(energy_consumer2)

    # Create third EnergyConsumer with a single phase A and a Location.
    ecp = [EnergyConsumerPhase(mrid="ecp3", phase=SinglePhaseKind.A, p_fixed=800.0, q_fixed=200.0)]
    network.add(ecp[0])

    ec3_loc = Location(mrid="ec3-loc", position_points=[PositionPoint(152.9151775,-31.43624552)])
    network.add(ec3_loc)

    energy_consumer3 = EnergyConsumer(mrid="EnergyConsumer3",
                                      p=1000,
                                      q=334.27413609633844,
                                      name="Load 3",
                                      phase_connection=PhaseShuntConnectionKind.Y,
                                      energy_consumer_phases=ecp,
                                      base_voltage=bv_230v,
                                      location=ec3_loc)
    ec3_t1 = Terminal(mrid='ec3-t1', phases=PhaseCode.A, conducting_equipment=energy_consumer3)
    network.connect_by_mrid(ec3_t1, "Bus 70")
    energy_consumer3.add_terminal(ec3_t1)
    network.add(ec3_t1)

    # Add the last energy consumer to the network
    network.add(energy_consumer3)

    # Our network is complete and connected. Next we must send it.
    return network
Пример #30
0
def basic_network_hierarchy():
    service = NetworkService()
    feeder = Feeder(name="basic-feeder")
    create_switch_for_connecting(service, "test_breaker", 2, PhaseCode.ABCN, True, True, True, True)