Ejemplo n.º 1
0
def userfcn_reserves_ext2int(ppc, *args):
    """This is the 'ext2int' stage userfcn callback that prepares the input
    data for the formulation stage. It expects to find a 'reserves' field
    in ppc as described above. The optional args are not currently used.
    """
    ## initialize some things
    r = ppc['reserves']
    o = ppc['order']
    ng0 = o['ext']['gen'].shape[0]  ## number of original gens (+ disp loads)
    nrz = r['req'].shape[0]         ## number of reserve zones
    if nrz > 1:
        ppc['reserves']['rgens'] = any(r['zones'], 0)  ## mask of gens available to provide reserves
    else:
        ppc['reserves']['rgens'] = r['zones']

    igr = find(ppc['reserves']['rgens']) ## indices of gens available to provide reserves
    ngr = len(igr)              ## number of gens available to provide reserves

    ## check data for consistent dimensions
    if r['zones'].shape[0] != nrz:
        stderr.write('userfcn_reserves_ext2int: the number of rows in ppc[\'reserves\'][\'req\'] (%d) and ppc[\'reserves\'][\'zones\'] (%d) must match\n' % (nrz, r['zones'].shape[0]))

    if (r['cost'].shape[0] != ng0) & (r['cost'].shape[0] != ngr):
        stderr.write('userfcn_reserves_ext2int: the number of rows in ppc[\'reserves\'][\'cost\'] (%d) must equal the total number of generators (%d) or the number of generators able to provide reserves (%d)\n' % (r['cost'].shape[0], ng0, ngr))

    if 'qty' in r:
        if r['qty'].shape[0] != r['cost'].shape[0]:
            stderr.write('userfcn_reserves_ext2int: ppc[\'reserves\'][\'cost\'] (%d x 1) and ppc[\'reserves\'][\'qty\'] (%d x 1) must be the same dimension\n' % (r['cost'].shape[0], r['qty'].shape[0]))


    ## convert both cost and qty from ngr x 1 to full ng x 1 vectors if necessary
    if r['cost'].shape[0] < ng0:
        if 'original' not in ppc['reserves']:
            ppc['reserves']['original'] = {}
        ppc['reserves']['original']['cost'] = r['cost'].copy()    ## save original
        cost = zeros(ng0)
        cost[igr] = r['cost']
        ppc['reserves']['cost'] = cost
        if 'qty' in r:
            ppc['reserves']['original']['qty'] = r['qty'].copy()  ## save original
            qty = zeros(ng0)
            qty[igr] = r['qty']
            ppc['reserves']['qty'] = qty

    ##-----  convert stuff to internal indexing  -----
    ## convert all reserve parameters (zones, costs, qty, rgens)
    if 'qty' in r:
        ppc = e2i_field(ppc, ['reserves', 'qty'], 'gen')

    ppc = e2i_field(ppc, ['reserves', 'cost'], 'gen')
    ppc = e2i_field(ppc, ['reserves', 'zones'], 'gen', 1)
    ppc = e2i_field(ppc, ['reserves', 'rgens'], 'gen', 1)

    ## save indices of gens available to provide reserves
    ppc['order']['ext']['reserves']['igr'] = igr               ## external indexing
    ppc['reserves']['igr'] = find(ppc['reserves']['rgens'])    ## internal indexing

    return ppc
Ejemplo n.º 2
0
def ext2int(ppc, val_or_field=None, ordering=None, dim=0):
    """Converts external to internal indexing.

    This function has two forms, the old form that operates on
    and returns individual matrices and the new form that operates
    on and returns an entire PYPOWER case dict.

    1.  C{ppc = ext2int(ppc)}

    If the input is a single PYPOWER case dict, then all isolated
    buses, off-line generators and branches are removed along with any
    generators, branches or areas connected to isolated buses. Then the
    buses are renumbered consecutively, beginning at 0, and the
    generators are sorted by increasing bus number. Any 'ext2int'
    callback routines registered in the case are also invoked
    automatically. All of the related
    indexing information and the original data matrices are stored under
    the 'order' key of the dict to be used by C{int2ext} to perform
    the reverse conversions. If the case is already using internal
    numbering it is returned unchanged.

    Example::
        ppc = ext2int(ppc)

    @see: L{int2ext}, L{e2i_field}, L{e2i_data}

    @author: Ray Zimmerman (PSERC Cornell)
    @author: Richard Lincoln
    """
    ppc = deepcopy(ppc)
    if val_or_field is None:  # nargin == 1
        first = 'order' not in ppc
        if first or ppc["order"]["state"] == 'e':
            ## initialize order
            if first:
                o = {
                        'ext':      {
                                'bus':      None,
                                'branch':   None,
                                'gen':      None
                            },
                        'bus':      { 'e2i':      None,
                                      'i2e':      None,
                                      'status':   {} },
                        'gen':      { 'e2i':      None,
                                      'i2e':      None,
                                      'status':   {} },
                        'branch':   { 'status': {} }
                    }
            else:
                o = ppc["order"]

            ## sizes
            nb = ppc["bus"].shape[0]
            ng = ppc["gen"].shape[0]
            ng0 = ng
            if 'A' in ppc:
                dc = True if ppc["A"].shape[1] < (2 * nb + 2 * ng) else False
            elif 'N' in ppc:
                dc = True if ppc["N"].shape[1] < (2 * nb + 2 * ng) else False
            else:
                dc = False

            ## save data matrices with external ordering
            if 'ext' not in o: o['ext'] = {}
            o["ext"]["bus"]    = ppc["bus"].copy()
            o["ext"]["branch"] = ppc["branch"].copy()
            o["ext"]["gen"]    = ppc["gen"].copy()
            if 'areas' in ppc:
                if len(ppc["areas"]) == 0: ## if areas field is empty
                    del ppc['areas']       ## delete it (so it's ignored)
                else:                      ## otherwise
                    o["ext"]["areas"] = ppc["areas"].copy()  ## save it

            ## check that all buses have a valid BUS_TYPE
            bt = ppc["bus"][:, BUS_TYPE]
            err = find(~((bt == PQ) | (bt == PV) | (bt == REF) | (bt == NONE)))
            if len(err) > 0:
                sys.stderr.write('ext2int: bus %d has an invalid BUS_TYPE\n' % err)

            ## determine which buses, branches, gens are connected and
            ## in-service
            n2i = sparse((range(nb), (ppc["bus"][:, BUS_I], zeros(nb))),
                         shape=(max(ppc["bus"][:, BUS_I]) + 1, 1))
            n2i = array( n2i.todense().flatten() )[0, :] # as 1D array
            bs = (bt != NONE)                               ## bus status
            o["bus"]["status"]["on"]  = find(  bs )         ## connected
            o["bus"]["status"]["off"] = find( ~bs )         ## isolated
            gs = ( (ppc["gen"][:, GEN_STATUS] > 0) &          ## gen status
                    bs[ n2i[ppc["gen"][:, GEN_BUS].astype(int)] ] )
            o["gen"]["status"]["on"]  = find(  gs )    ## on and connected
            o["gen"]["status"]["off"] = find( ~gs )    ## off or isolated
            brs = ( ppc["branch"][:, BR_STATUS].astype(int) &  ## branch status
                    bs[n2i[ppc["branch"][:, F_BUS].astype(int)]] &
                    bs[n2i[ppc["branch"][:, T_BUS].astype(int)]] ).astype(bool)
            o["branch"]["status"]["on"]  = find(  brs ) ## on and conn
            o["branch"]["status"]["off"] = find( ~brs )
            if 'areas' in ppc:
                ar = bs[ n2i[ppc["areas"][:, PRICE_REF_BUS].astype(int)] ]
                o["areas"] = {"status": {}}
                o["areas"]["status"]["on"]  = find(  ar )
                o["areas"]["status"]["off"] = find( ~ar )

            ## delete stuff that is "out"
            if len(o["bus"]["status"]["off"]) > 0:
#                ppc["bus"][o["bus"]["status"]["off"], :] = array([])
                ppc["bus"] = ppc["bus"][o["bus"]["status"]["on"], :]
            if len(o["branch"]["status"]["off"]) > 0:
#                ppc["branch"][o["branch"]["status"]["off"], :] = array([])
                ppc["branch"] = ppc["branch"][o["branch"]["status"]["on"], :]
            if len(o["gen"]["status"]["off"]) > 0:
#                ppc["gen"][o["gen"]["status"]["off"], :] = array([])
                ppc["gen"] = ppc["gen"][o["gen"]["status"]["on"], :]
            if 'areas' in ppc and (len(o["areas"]["status"]["off"]) > 0):
#                ppc["areas"][o["areas"]["status"]["off"], :] = array([])
                ppc["areas"] = ppc["areas"][o["areas"]["status"]["on"], :]

            ## update size
            nb = ppc["bus"].shape[0]

            ## apply consecutive bus numbering
            o["bus"]["i2e"] = ppc["bus"][:, BUS_I].copy()
            o["bus"]["e2i"] = zeros(int(max(o["bus"]["i2e"])) + 1)
            o["bus"]["e2i"][o["bus"]["i2e"].astype(int)] = arange(nb)
            ppc["bus"][:, BUS_I] = \
                o["bus"]["e2i"][ ppc["bus"][:, BUS_I].astype(int) ].copy()
            ppc["gen"][:, GEN_BUS] = \
                o["bus"]["e2i"][ ppc["gen"][:, GEN_BUS].astype(int) ].copy()
            ppc["branch"][:, F_BUS] = \
                o["bus"]["e2i"][ ppc["branch"][:, F_BUS].astype(int) ].copy()
            ppc["branch"][:, T_BUS] = \
                o["bus"]["e2i"][ ppc["branch"][:, T_BUS].astype(int) ].copy()
            if 'areas' in ppc:
                ppc["areas"][:, PRICE_REF_BUS] = \
                    o["bus"]["e2i"][ ppc["areas"][:,
                        PRICE_REF_BUS].astype(int) ].copy()

            ## reorder gens in order of increasing bus number
            o["gen"]["e2i"] = argsort(ppc["gen"][:, GEN_BUS])
            o["gen"]["i2e"] = argsort(o["gen"]["e2i"])

            ppc["gen"] = ppc["gen"][o["gen"]["e2i"].astype(int), :]

            if 'int' in o:
                del o['int']
            o["state"] = 'i'
            ppc["order"] = o

            ## update gencost, A and N
            if 'gencost' in ppc:
                ordering = ['gen']            ## Pg cost only
                if ppc["gencost"].shape[0] == (2 * ng0):
                    ordering.append('gen')    ## include Qg cost
                ppc = e2i_field(ppc, 'gencost', ordering)
            if 'A' in ppc or 'N' in ppc:
                if dc:
                    ordering = ['bus', 'gen']
                else:
                    ordering = ['bus', 'bus', 'gen', 'gen']
            if 'A' in ppc:
                ppc = e2i_field(ppc, 'A', ordering, 1)
            if 'N' in ppc:
                ppc = e2i_field(ppc, 'N', ordering, 1)

            ## execute userfcn callbacks for 'ext2int' stage
            if 'userfcn' in ppc:
                ppc = run_userfcn(ppc['userfcn'], 'ext2int', ppc)
    else:                    ## convert extra data
        if isinstance(val_or_field, str) or isinstance(val_or_field, list):
            ## field
            warn('Calls of the form ppc = ext2int(ppc, '
                '\'field_name\', ...) have been deprecated. Please '
                'replace ext2int with e2i_field.', DeprecationWarning)
            gen, branch = val_or_field, ordering
            ppc = e2i_field(ppc, gen, branch, dim)

        else:
            ## value
            warn('Calls of the form val = ext2int(ppc, val, ...) have been '
                 'deprecated. Please replace ext2int with e2i_data.',
                 DeprecationWarning)
            gen, branch = val_or_field, ordering
            ppc = e2i_data(ppc, gen, branch, dim)

    return ppc
Ejemplo n.º 3
0
def ext2int(ppc, val_or_field=None, ordering=None, dim=0):
    """Converts external to internal indexing.

    This function has two forms, the old form that operates on
    and returns individual matrices and the new form that operates
    on and returns an entire PYPOWER case dict.

    1.  C{ppc = ext2int(ppc)}

    If the input is a single PYPOWER case dict, then all isolated
    buses, off-line generators and branches are removed along with any
    generators, branches or areas connected to isolated buses. Then the
    buses are renumbered consecutively, beginning at 0, and the
    generators are sorted by increasing bus number. Any 'ext2int'
    callback routines registered in the case are also invoked
    automatically. All of the related
    indexing information and the original data matrices are stored under
    the 'order' key of the dict to be used by C{int2ext} to perform
    the reverse conversions. If the case is already using internal
    numbering it is returned unchanged.

    Example::
        ppc = ext2int(ppc)

    @see: L{int2ext}, L{e2i_field}, L{e2i_data}

    @author: Ray Zimmerman (PSERC Cornell)
    @author: Richard Lincoln
    """
    ppc = deepcopy(ppc)
    if val_or_field is None:  # nargin == 1
        first = 'order' not in ppc
        if first or ppc["order"]["state"] == 'e':
            ## initialize order
            if first:
                o = {
                        'ext':      {
                                'bus':      None,
                                'branch':   None,
                                'gen':      None
                            },
                        'bus':      { 'e2i':      None,
                                      'i2e':      None,
                                      'status':   {} },
                        'gen':      { 'e2i':      None,
                                      'i2e':      None,
                                      'status':   {} },
                        'branch':   { 'status': {} }
                    }
            else:
                o = ppc["order"]

            ## sizes
            nb = ppc["bus"].shape[0]
            ng = ppc["gen"].shape[0]
            ng0 = ng
            if 'A' in ppc:
                dc = True if ppc["A"].shape[1] < (2 * nb + 2 * ng) else False
            elif 'N' in ppc:
                dc = True if ppc["N"].shape[1] < (2 * nb + 2 * ng) else False
            else:
                dc = False

            ## save data matrices with external ordering
            if 'ext' not in o: o['ext'] = {}
            o["ext"]["bus"]    = ppc["bus"].copy()
            o["ext"]["branch"] = ppc["branch"].copy()
            o["ext"]["gen"]    = ppc["gen"].copy()
            if 'areas' in ppc:
                if len(ppc["areas"]) == 0: ## if areas field is empty
                    del ppc['areas']       ## delete it (so it's ignored)
                else:                      ## otherwise
                    o["ext"]["areas"] = ppc["areas"].copy()  ## save it

            ## check that all buses have a valid BUS_TYPE
            bt = ppc["bus"][:, BUS_TYPE]
            err = find(~((bt == PQ) | (bt == PV) | (bt == REF) | (bt == NONE)))
            if len(err) > 0:
                sys.stderr.write('ext2int: bus %d has an invalid BUS_TYPE\n' % err)

            ## determine which buses, branches, gens are connected and
            ## in-service
            n2i = sparse((range(nb), (ppc["bus"][:, BUS_I], zeros(nb))),
                         shape=(max(ppc["bus"][:, BUS_I]) + 1, 1))
            n2i = array( n2i.todense().flatten() )[0, :] # as 1D array
            bs = (bt != NONE)                               ## bus status
            o["bus"]["status"]["on"]  = find(  bs )         ## connected
            o["bus"]["status"]["off"] = find( ~bs )         ## isolated
            gs = ( (ppc["gen"][:, GEN_STATUS] > 0) &          ## gen status
                    bs[ n2i[ppc["gen"][:, GEN_BUS].astype(int)] ] )
            o["gen"]["status"]["on"]  = find(  gs )    ## on and connected
            o["gen"]["status"]["off"] = find( ~gs )    ## off or isolated
            brs = ( ppc["branch"][:, BR_STATUS].astype(int) &  ## branch status
                    bs[n2i[ppc["branch"][:, F_BUS].astype(int)]] &
                    bs[n2i[ppc["branch"][:, T_BUS].astype(int)]] ).astype(bool)
            o["branch"]["status"]["on"]  = find(  brs ) ## on and conn
            o["branch"]["status"]["off"] = find( ~brs )
            if 'areas' in ppc:
                ar = bs[ n2i[ppc["areas"][:, PRICE_REF_BUS].astype(int)] ]
                o["areas"] = {"status": {}}
                o["areas"]["status"]["on"]  = find(  ar )
                o["areas"]["status"]["off"] = find( ~ar )

            ## delete stuff that is "out"
            if len(o["bus"]["status"]["off"]) > 0:
#                ppc["bus"][o["bus"]["status"]["off"], :] = array([])
                ppc["bus"] = ppc["bus"][o["bus"]["status"]["on"], :]
            if len(o["branch"]["status"]["off"]) > 0:
#                ppc["branch"][o["branch"]["status"]["off"], :] = array([])
                ppc["branch"] = ppc["branch"][o["branch"]["status"]["on"], :]
            if len(o["gen"]["status"]["off"]) > 0:
#                ppc["gen"][o["gen"]["status"]["off"], :] = array([])
                ppc["gen"] = ppc["gen"][o["gen"]["status"]["on"], :]
            if 'areas' in ppc and (len(o["areas"]["status"]["off"]) > 0):
#                ppc["areas"][o["areas"]["status"]["off"], :] = array([])
                ppc["areas"] = ppc["areas"][o["areas"]["status"]["on"], :]

            ## update size
            nb = ppc["bus"].shape[0]

            ## apply consecutive bus numbering
            o["bus"]["i2e"] = ppc["bus"][:, BUS_I].copy()
            o["bus"]["e2i"] = zeros(max(o["bus"]["i2e"]) + 1)
            o["bus"]["e2i"][o["bus"]["i2e"].astype(int)] = arange(nb)

            ppc["bus"][:, BUS_I] = \
                o["bus"]["e2i"][ ppc["bus"][:, BUS_I].astype(int) ].copy()


            ppc["gen"][:, GEN_BUS] = \
                o["bus"]["e2i"][ ppc["gen"][:, GEN_BUS].astype(int) ].copy()
            ppc["branch"][:, F_BUS] = \
                o["bus"]["e2i"][ ppc["branch"][:, F_BUS].astype(int) ].copy()
            ppc["branch"][:, T_BUS] = \
                o["bus"]["e2i"][ ppc["branch"][:, T_BUS].astype(int) ].copy()
            if 'areas' in ppc:
                ppc["areas"][:, PRICE_REF_BUS] = \
                    o["bus"]["e2i"][ ppc["areas"][:,
                        PRICE_REF_BUS].astype(int) ].copy()

            ## reorder gens in order of increasing bus number
            o["gen"]["e2i"] = argsort(ppc["gen"][:, GEN_BUS])
            o["gen"]["i2e"] = argsort(o["gen"]["e2i"])

            ppc["gen"] = ppc["gen"][o["gen"]["e2i"].astype(int), :]

            if 'int' in o:
                del o['int']
            o["state"] = 'i'
            ppc["order"] = o

            ## update gencost, A and N
            if 'gencost' in ppc:
                ordering = ['gen']            ## Pg cost only
                if ppc["gencost"].shape[0] == (2 * ng0):
                    ordering.append('gen')    ## include Qg cost
                ppc = e2i_field(ppc, 'gencost', ordering)
            if 'A' in ppc or 'N' in ppc:
                if dc:
                    ordering = ['bus', 'gen']
                else:
                    ordering = ['bus', 'bus', 'gen', 'gen']
            if 'A' in ppc:
                ppc = e2i_field(ppc, 'A', ordering, 1)
            if 'N' in ppc:
                ppc = e2i_field(ppc, 'N', ordering, 1)

            ## execute userfcn callbacks for 'ext2int' stage
            if 'userfcn' in ppc:
                ppc = run_userfcn(ppc['userfcn'], 'ext2int', ppc)
    else:                    ## convert extra data
        if isinstance(val_or_field, str) or isinstance(val_or_field, list):
            ## field
            warn('Calls of the form ppc = ext2int(ppc, '
                '\'field_name\', ...) have been deprecated. Please '
                'replace ext2int with e2i_field.', DeprecationWarning)
            gen, branch = val_or_field, ordering
            ppc = e2i_field(ppc, gen, branch, dim)

        else:
            ## value
            warn('Calls of the form val = ext2int(ppc, val, ...) have been '
                 'deprecated. Please replace ext2int with e2i_data.',
                 DeprecationWarning)
            gen, branch = val_or_field, ordering
            ppc = e2i_data(ppc, gen, branch, dim)

    return ppc
Ejemplo n.º 4
0
def t_ext2int2ext(quiet=False):
    """Tests C{ext2int} and C{int2ext}.

    @author: Ray Zimmerman (PSERC Cornell)
    @author: Richard Lincoln
    """
    t_begin(85, quiet)

    ##-----  ppc = e2i_data/i2e_data(ppc)  -----
    t = 'ppc = e2i_data(ppc) : '
    ppce = loadcase(t_case_ext())
    ppci = loadcase(t_case_int())
    ppc = e2i_data(ppce)
    t_is(ppc['bus'], ppci['bus'], 12, [t, 'bus'])
    t_is(ppc['branch'], ppci['branch'], 12, [t, 'branch'])
    t_is(ppc['gen'], ppci['gen'], 12, [t, 'gen'])
    t_is(ppc['gencost'], ppci['gencost'], 12, [t, 'gencost'])
    t_is(ppc['areas'], ppci['areas'], 12, [t, 'areas'])
    t_is(ppc['A'], ppci['A'], 12, [t, 'A'])
    t_is(ppc['N'], ppci['N'], 12, [t, 'N'])
    t = 'ppc = e2i_data(ppc) - repeat : '
    ppc = e2i_data(ppc)
    t_is(ppc['bus'], ppci['bus'], 12, [t, 'bus'])
    t_is(ppc['branch'], ppci['branch'], 12, [t, 'branch'])
    t_is(ppc['gen'], ppci['gen'], 12, [t, 'gen'])
    t_is(ppc['gencost'], ppci['gencost'], 12, [t, 'gencost'])
    t_is(ppc['areas'], ppci['areas'], 12, [t, 'areas'])
    t_is(ppc['A'], ppci['A'], 12, [t, 'A'])
    t_is(ppc['N'], ppci['N'], 12, [t, 'N'])
    t = 'ppc = i2e_data(ppc) : '
    ppc = i2e_data(ppc)
    t_is(ppc['bus'], ppce['bus'], 12, [t, 'bus'])
    t_is(ppc['branch'], ppce['branch'], 12, [t, 'branch'])
    t_is(ppc['gen'], ppce['gen'], 12, [t, 'gen'])
    t_is(ppc['gencost'], ppce['gencost'], 12, [t, 'gencost'])
    t_is(ppc['areas'], ppce['areas'], 12, [t, 'areas'])
    t_is(ppc['A'], ppce['A'], 12, [t, 'A'])
    t_is(ppc['N'], ppce['N'], 12, [t, 'N'])

    ##-----  val = e2i_data/i2e_data(ppc, val, ...)  -----
    t = 'val = e2i_data(ppc, val, \'bus\')'
    ppc = e2i_data(ppce)
    got = e2i_data(ppc, ppce['xbus'], 'bus')
    ex = ppce['xbus']
    ex = delete(ex, 5, 0)
    t_is(got, ex, 12, t)
    t = 'val = i2e_data(ppc, val, oldval, \'bus\')'
    tmp = ones(ppce['xbus'].shape)
    tmp[5, :] = ppce['xbus'][5, :]
    got = i2e_data(ppc, ex, tmp, 'bus')
    t_is(got, ppce['xbus'], 12, t)

    t = 'val = e2i_data(ppc, val, \'bus\', 1)'
    got = e2i_data(ppc, ppce['xbus'], 'bus', 1)
    ex = ppce['xbus']
    ex = delete(ex, 5, 1)
    t_is(got, ex, 12, t)
    t = 'val = i2e_data(ppc, val, oldval, \'bus\', 1)'
    tmp = ones(ppce['xbus'].shape)
    tmp[:, 5] = ppce['xbus'][:, 5]
    got = i2e_data(ppc, ex, tmp, 'bus', 1)
    t_is(got, ppce['xbus'], 12, t)

    t = 'val = e2i_data(ppc, val, \'gen\')'
    got = e2i_data(ppc, ppce['xgen'], 'gen')
    ex = ppce['xgen'][[3, 1, 0], :]
    t_is(got, ex, 12, t)
    t = 'val = i2e_data(ppc, val, oldval, \'gen\')'
    tmp = ones(ppce['xgen'].shape)
    tmp[2, :] = ppce['xgen'][2, :]
    got = i2e_data(ppc, ex, tmp, 'gen')
    t_is(got, ppce['xgen'], 12, t)

    t = 'val = e2i_data(ppc, val, \'gen\', 1)'
    got = e2i_data(ppc, ppce['xgen'], 'gen', 1)
    ex = ppce['xgen'][:, [3, 1, 0]]
    t_is(got, ex, 12, t)
    t = 'val = i2e_data(ppc, val, oldval, \'gen\', 1)'
    tmp = ones(ppce['xgen'].shape)
    tmp[:, 2] = ppce['xgen'][:, 2]
    got = i2e_data(ppc, ex, tmp, 'gen', 1)
    t_is(got, ppce['xgen'], 12, t)

    t = 'val = e2i_data(ppc, val, \'branch\')'
    got = e2i_data(ppc, ppce['xbranch'], 'branch')
    ex = ppce['xbranch']
    ex = delete(ex, 6, 0)
    t_is(got, ex, 12, t)
    t = 'val = i2e_data(ppc, val, oldval, \'branch\')'
    tmp = ones(ppce['xbranch'].shape)
    tmp[6, :] = ppce['xbranch'][6, :]
    got = i2e_data(ppc, ex, tmp, 'branch')
    t_is(got, ppce['xbranch'], 12, t)

    t = 'val = e2i_data(ppc, val, \'branch\', 1)'
    got = e2i_data(ppc, ppce['xbranch'], 'branch', 1)
    ex = ppce['xbranch']
    ex = delete(ex, 6, 1)
    t_is(got, ex, 12, t)
    t = 'val = i2e_data(ppc, val, oldval, \'branch\', 1)'
    tmp = ones(ppce['xbranch'].shape)
    tmp[:, 6] = ppce['xbranch'][:, 6]
    got = i2e_data(ppc, ex, tmp, 'branch', 1)
    t_is(got, ppce['xbranch'], 12, t)

    t = 'val = e2i_data(ppc, val, {\'branch\', \'gen\', \'bus\'})'
    got = e2i_data(ppc, ppce['xrows'], ['branch', 'gen', 'bus'])
    ex = r_[ppce['xbranch'][list(range(6)) + list(range(7, 10)), :4],
            ppce['xgen'][[3, 1, 0], :],
            ppce['xbus'][list(range(5)) + list(range(6, 10)), :4],
            -1 * ones((2, 4))]
    t_is(got, ex, 12, t)
    t = 'val = i2e_data(ppc, val, oldval, {\'branch\', \'gen\', \'bus\'})'
    tmp1 = ones(ppce['xbranch'][:, :4].shape)
    tmp1[6, :4] = ppce['xbranch'][6, :4]
    tmp2 = ones(ppce['xgen'].shape)
    tmp2[2, :] = ppce['xgen'][2, :]
    tmp3 = ones(ppce['xbus'][:, :4].shape)
    tmp3[5, :4] = ppce['xbus'][5, :4]
    tmp = r_[tmp1, tmp2, tmp3]
    got = i2e_data(ppc, ex, tmp, ['branch', 'gen', 'bus'])
    t_is(got, ppce['xrows'], 12, t)

    t = 'val = e2i_data(ppc, val, {\'branch\', \'gen\', \'bus\'}, 1)'
    got = e2i_data(ppc, ppce['xcols'], ['branch', 'gen', 'bus'], 1)
    ex = r_[ppce['xbranch'][list(range(6)) + list(range(7, 10)), :4],
            ppce['xgen'][[3, 1, 0], :],
            ppce['xbus'][list(range(5)) + list(range(6, 10)), :4],
            -1 * ones((2, 4))].T
    t_is(got, ex, 12, t)
    t = 'val = i2e_data(ppc, val, oldval, {\'branch\', \'gen\', \'bus\'}, 1)'
    tmp1 = ones(ppce['xbranch'][:, :4].shape)
    tmp1[6, :4] = ppce['xbranch'][6, :4]
    tmp2 = ones(ppce['xgen'].shape)
    tmp2[2, :] = ppce['xgen'][2, :]
    tmp3 = ones(ppce['xbus'][:, :4].shape)
    tmp3[5, :4] = ppce['xbus'][5, :4]
    tmp = r_[tmp1, tmp2, tmp3].T
    got = i2e_data(ppc, ex, tmp, ['branch', 'gen', 'bus'], 1)
    t_is(got, ppce['xcols'], 12, t)

    ##-----  ppc = e2i_field/i2e_field(ppc, field, ...)  -----
    t = 'ppc = e2i_field(ppc, field, \'bus\')'
    ppc = e2i_field(ppce)
    ex = ppce['xbus']
    ex = delete(ex, 5, 0)
    got = e2i_field(ppc, 'xbus', 'bus')
    t_is(got['xbus'], ex, 12, t)
    t = 'ppc = i2e_field(ppc, field, \'bus\')'
    got = i2e_field(got, 'xbus', ordering='bus')
    t_is(got['xbus'], ppce['xbus'], 12, t)

    t = 'ppc = e2i_field(ppc, field, \'bus\', 1)'
    ex = ppce['xbus']
    ex = delete(ex, 5, 1)
    got = e2i_field(ppc, 'xbus', 'bus', 1)
    t_is(got['xbus'], ex, 12, t)
    t = 'ppc = i2e_field(ppc, field, \'bus\', 1)'
    got = i2e_field(got, 'xbus', ordering='bus', dim=1)
    t_is(got['xbus'], ppce['xbus'], 12, t)

    t = 'ppc = e2i_field(ppc, field, \'gen\')'
    ex = ppce['xgen'][[3, 1, 0], :]
    got = e2i_field(ppc, 'xgen', 'gen')
    t_is(got['xgen'], ex, 12, t)
    t = 'ppc = i2e_field(ppc, field, \'gen\')'
    got = i2e_field(got, 'xgen', ordering='gen')
    t_is(got['xgen'], ppce['xgen'], 12, t)

    t = 'ppc = e2i_field(ppc, field, \'gen\', 1)'
    ex = ppce['xgen'][:, [3, 1, 0]]
    got = e2i_field(ppc, 'xgen', 'gen', 1)
    t_is(got['xgen'], ex, 12, t)
    t = 'ppc = i2e_field(ppc, field, \'gen\', 1)'
    got = i2e_field(got, 'xgen', ordering='gen', dim=1)
    t_is(got['xgen'], ppce['xgen'], 12, t)

    t = 'ppc = e2i_field(ppc, field, \'branch\')'
    ex = ppce['xbranch']
    ex = delete(ex, 6, 0)
    got = e2i_field(ppc, 'xbranch', 'branch')
    t_is(got['xbranch'], ex, 12, t)
    t = 'ppc = i2e_field(ppc, field, \'branch\')'
    got = i2e_field(got, 'xbranch', ordering='branch')
    t_is(got['xbranch'], ppce['xbranch'], 12, t)

    t = 'ppc = e2i_field(ppc, field, \'branch\', 1)'
    ex = ppce['xbranch']
    ex = delete(ex, 6, 1)
    got = e2i_field(ppc, 'xbranch', 'branch', 1)
    t_is(got['xbranch'], ex, 12, t)
    t = 'ppc = i2e_field(ppc, field, \'branch\', 1)'
    got = i2e_field(got, 'xbranch', ordering='branch', dim=1)
    t_is(got['xbranch'], ppce['xbranch'], 12, t)

    t = 'ppc = e2i_field(ppc, field, {\'branch\', \'gen\', \'bus\'})'
    ex = r_[ppce['xbranch'][list(range(6)) + list(range(7, 10)), :4],
            ppce['xgen'][[3, 1, 0], :],
            ppce['xbus'][list(range(5)) + list(range(6, 10)), :4],
            -1 * ones((2, 4))]
    got = e2i_field(ppc, 'xrows', ['branch', 'gen', 'bus'])
    t_is(got['xrows'], ex, 12, t)
    t = 'ppc = i2e_field(ppc, field, {\'branch\', \'gen\', \'bus\'})'
    got = i2e_field(got, 'xrows', ordering=['branch', 'gen', 'bus'])
    t_is(got['xrows'], ppce['xrows'], 12, t)

    t = 'ppc = e2i_field(ppc, field, {\'branch\', \'gen\', \'bus\'}, 1)'
    ex = r_[ppce['xbranch'][list(range(6)) + list(range(7, 10)), :4],
            ppce['xgen'][[3, 1, 0], :],
            ppce['xbus'][list(range(5)) + list(range(6, 10)), :4],
            -1 * ones((2, 4))].T
    got = e2i_field(ppc, 'xcols', ['branch', 'gen', 'bus'], 1)
    t_is(got['xcols'], ex, 12, t)
    t = 'ppc = i2e_field(ppc, field, {\'branch\', \'gen\', \'bus\'})'
    got = i2e_field(got, 'xcols', ordering=['branch', 'gen', 'bus'], dim=1)
    t_is(got['xcols'], ppce['xcols'], 12, t)

    t = 'ppc = e2i_field(ppc, {\'field1\', \'field2\'}, ordering)'
    ex = ppce['x']['more'][[3, 1, 0], :]
    got = e2i_field(ppc, ['x', 'more'], 'gen')
    t_is(got['x']['more'], ex, 12, t)
    t = 'ppc = i2e_field(ppc, {\'field1\', \'field2\'}, ordering)'
    got = i2e_field(got, ['x', 'more'], ordering='gen')
    t_is(got['x']['more'], ppce['x']['more'], 12, t)

    t = 'ppc = e2i_field(ppc, {\'field1\', \'field2\'}, ordering, 1)'
    ex = ppce['x']['more'][:, [3, 1, 0]]
    got = e2i_field(ppc, ['x', 'more'], 'gen', 1)
    t_is(got['x']['more'], ex, 12, t)
    t = 'ppc = i2e_field(ppc, {\'field1\', \'field2\'}, ordering, 1)'
    got = i2e_field(got, ['x', 'more'], ordering='gen', dim=1)
    t_is(got['x']['more'], ppce['x']['more'], 12, t)

    ##-----  more ppc = ext2int/int2ext(ppc)  -----
    t = 'ppc = ext2int(ppc) - bus/gen/branch only : '
    ppce = loadcase(t_case_ext())
    ppci = loadcase(t_case_int())
    del ppce['gencost']
    del ppce['areas']
    del ppce['A']
    del ppce['N']
    del ppci['gencost']
    del ppci['areas']
    del ppci['A']
    del ppci['N']
    ppc = ext2int(ppce)
    t_is(ppc['bus'], ppci['bus'], 12, [t, 'bus'])
    t_is(ppc['branch'], ppci['branch'], 12, [t, 'branch'])
    t_is(ppc['gen'], ppci['gen'], 12, [t, 'gen'])

    t = 'ppc = ext2int(ppc) - no areas/A : '
    ppce = loadcase(t_case_ext())
    ppci = loadcase(t_case_int())
    del ppce['areas']
    del ppce['A']
    del ppci['areas']
    del ppci['A']
    ppc = ext2int(ppce)
    t_is(ppc['bus'], ppci['bus'], 12, [t, 'bus'])
    t_is(ppc['branch'], ppci['branch'], 12, [t, 'branch'])
    t_is(ppc['gen'], ppci['gen'], 12, [t, 'gen'])
    t_is(ppc['gencost'], ppci['gencost'], 12, [t, 'gencost'])
    t_is(ppc['N'], ppci['N'], 12, [t, 'N'])

    t = 'ppc = ext2int(ppc) - Qg cost, no N : '
    ppce = loadcase(t_case_ext())
    ppci = loadcase(t_case_int())
    del ppce['N']
    del ppci['N']
    ppce['gencost'] = c_[ppce['gencost'], ppce['gencost']]
    ppci['gencost'] = c_[ppci['gencost'], ppci['gencost']]
    ppc = ext2int(ppce)
    t_is(ppc['bus'], ppci['bus'], 12, [t, 'bus'])
    t_is(ppc['branch'], ppci['branch'], 12, [t, 'branch'])
    t_is(ppc['gen'], ppci['gen'], 12, [t, 'gen'])
    t_is(ppc['gencost'], ppci['gencost'], 12, [t, 'gencost'])
    t_is(ppc['areas'], ppci['areas'], 12, [t, 'areas'])
    t_is(ppc['A'], ppci['A'], 12, [t, 'A'])

    t = 'ppc = ext2int(ppc) - A, N are DC sized : '
    ppce = loadcase(t_case_ext())
    ppci = loadcase(t_case_int())
    eVmQgcols = list(range(10, 20)) + list(range(24, 28))
    iVmQgcols = list(range(9, 18)) + list(range(21, 24))
    ppce['A'] = delete(ppce['A'], eVmQgcols, 1)
    ppce['N'] = delete(ppce['N'], eVmQgcols, 1)
    ppci['A'] = delete(ppci['A'], iVmQgcols, 1)
    ppci['N'] = delete(ppci['N'], iVmQgcols, 1)
    ppc = ext2int(ppce)
    t_is(ppc['bus'], ppci['bus'], 12, [t, 'bus'])
    t_is(ppc['branch'], ppci['branch'], 12, [t, 'branch'])
    t_is(ppc['gen'], ppci['gen'], 12, [t, 'gen'])
    t_is(ppc['gencost'], ppci['gencost'], 12, [t, 'gencost'])
    t_is(ppc['areas'], ppci['areas'], 12, [t, 'areas'])
    t_is(ppc['A'], ppci['A'], 12, [t, 'A'])
    t_is(ppc['N'], ppci['N'], 12, [t, 'N'])
    t = 'ppc = int2ext(ppc) - A, N are DC sized : '
    ppc = int2ext(ppc)
    t_is(ppc['bus'], ppce['bus'], 12, [t, 'bus'])
    t_is(ppc['branch'], ppce['branch'], 12, [t, 'branch'])
    t_is(ppc['gen'], ppce['gen'], 12, [t, 'gen'])
    t_is(ppc['gencost'], ppce['gencost'], 12, [t, 'gencost'])
    t_is(ppc['areas'], ppce['areas'], 12, [t, 'areas'])
    t_is(ppc['A'], ppce['A'], 12, [t, 'A'])
    t_is(ppc['N'], ppce['N'], 12, [t, 'N'])

    t_end()
Ejemplo n.º 5
0
def userfcn_reserves_ext2int(ppc, *args):
    """This is the 'ext2int' stage userfcn callback that prepares the input
    data for the formulation stage. It expects to find a 'reserves' field
    in ppc as described above. The optional args are not currently used.
    """
    ## initialize some things
    r = ppc['reserves']
    o = ppc['order']
    ng0 = o['ext']['gen'].shape[0]  ## number of original gens (+ disp loads)
    nrz = r['req'].shape[0]  ## number of reserve zones
    if nrz > 1:
        ppc['reserves']['rgens'] = any(
            r['zones'], 0)  ## mask of gens available to provide reserves
    else:
        ppc['reserves']['rgens'] = r['zones']

    igr = find(ppc['reserves']
               ['rgens'])  ## indices of gens available to provide reserves
    ngr = len(igr)  ## number of gens available to provide reserves

    ## check data for consistent dimensions
    if r['zones'].shape[0] != nrz:
        stderr.write(
            'userfcn_reserves_ext2int: the number of rows in ppc[\'reserves\'][\'req\'] (%d) and ppc[\'reserves\'][\'zones\'] (%d) must match\n'
            % (nrz, r['zones'].shape[0]))

    if (r['cost'].shape[0] != ng0) & (r['cost'].shape[0] != ngr):
        stderr.write(
            'userfcn_reserves_ext2int: the number of rows in ppc[\'reserves\'][\'cost\'] (%d) must equal the total number of generators (%d) or the number of generators able to provide reserves (%d)\n'
            % (r['cost'].shape[0], ng0, ngr))

    if 'qty' in r:
        if r['qty'].shape[0] != r['cost'].shape[0]:
            stderr.write(
                'userfcn_reserves_ext2int: ppc[\'reserves\'][\'cost\'] (%d x 1) and ppc[\'reserves\'][\'qty\'] (%d x 1) must be the same dimension\n'
                % (r['cost'].shape[0], r['qty'].shape[0]))

    ## convert both cost and qty from ngr x 1 to full ng x 1 vectors if necessary
    if r['cost'].shape[0] < ng0:
        if 'original' not in ppc['reserves']:
            ppc['reserves']['original'] = {}
        ppc['reserves']['original']['cost'] = r['cost'].copy(
        )  ## save original
        cost = zeros(ng0)
        cost[igr] = r['cost']
        ppc['reserves']['cost'] = cost
        if 'qty' in r:
            ppc['reserves']['original']['qty'] = r['qty'].copy(
            )  ## save original
            qty = zeros(ng0)
            qty[igr] = r['qty']
            ppc['reserves']['qty'] = qty

    ##-----  convert stuff to internal indexing  -----
    ## convert all reserve parameters (zones, costs, qty, rgens)
    if 'qty' in r:
        ppc = e2i_field(ppc, ['reserves', 'qty'], 'gen')

    ppc = e2i_field(ppc, ['reserves', 'cost'], 'gen')
    ppc = e2i_field(ppc, ['reserves', 'zones'], 'gen', 1)
    ppc = e2i_field(ppc, ['reserves', 'rgens'], 'gen', 1)

    ## save indices of gens available to provide reserves
    ppc['order']['ext']['reserves']['igr'] = igr  ## external indexing
    ppc['reserves']['igr'] = find(
        ppc['reserves']['rgens'])  ## internal indexing

    return ppc