idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
700
def _var_bounds ( self ) : x0 = array ( [ ] ) xmin = array ( [ ] ) xmax = array ( [ ] ) for var in self . om . vars : x0 = r_ [ x0 , var . v0 ] xmin = r_ [ xmin , var . vl ] xmax = r_ [ xmax , var . vu ] return x0 , xmin , xmax
Returns bounds on the optimisation variables .
701
def _initial_interior_point ( self , buses , generators , xmin , xmax , ny ) : Va = self . om . get_var ( "Va" ) va_refs = [ b . v_angle * pi / 180.0 for b in buses if b . type == REFERENCE ] x0 = ( xmin + xmax ) / 2.0 x0 [ Va . i1 : Va . iN + 1 ] = va_refs [ 0 ] if ny > 0 : yvar = self . om . get_var ( "y" ) c = [ ] for g in generators : if g . pcost_model == PW_LINEAR : for _ , y in g . p_cost : c . append ( y ) x0 [ yvar . i1 : yvar . iN + 1 ] = max ( c ) * 1.1 return x0
Selects an interior initial point for interior point solver .
702
def solve ( self ) : base_mva = self . om . case . base_mva Bf = self . om . _Bf Pfinj = self . om . _Pfinj bs , ln , gn , cp = self . _unpack_model ( self . om ) ipol , ipwl , nb , nl , nw , ny , nxyz = self . _dimension_data ( bs , ln , gn ) AA , ll , uu = self . _linear_constraints ( self . om ) Npwl , Hpwl , Cpwl , fparm_pwl , any_pwl = self . _pwl_costs ( ny , nxyz , ipwl ) Npol , Hpol , Cpol , fparm_pol , polycf , npol = self . _quadratic_costs ( gn , ipol , nxyz , base_mva ) NN , HHw , CCw , ffparm = self . _combine_costs ( Npwl , Hpwl , Cpwl , fparm_pwl , any_pwl , Npol , Hpol , Cpol , fparm_pol , npol , nw ) HH , CC , C0 = self . _transform_coefficients ( NN , HHw , CCw , ffparm , polycf , any_pwl , npol , nw ) _ , xmin , xmax = self . _var_bounds ( ) x0 = self . _initial_interior_point ( bs , gn , xmin , xmax , ny ) s = self . _run_opf ( HH , CC , AA , ll , uu , xmin , xmax , x0 , self . opt ) Va , Pg = self . _update_solution_data ( s , HH , CC , C0 ) self . _update_case ( bs , ln , gn , base_mva , Bf , Pfinj , Va , Pg , s [ "lmbda" ] ) return s
Solves DC optimal power flow and returns a results dict .
703
def _pwl_costs ( self , ny , nxyz , ipwl ) : any_pwl = int ( ny > 0 ) if any_pwl : y = self . om . get_var ( "y" ) Npwl = csr_matrix ( ( ones ( ny ) , ( zeros ( ny ) , array ( ipwl ) + y . i1 ) ) ) Hpwl = csr_matrix ( ( 1 , 1 ) ) Cpwl = array ( [ 1 ] ) fparm_pwl = array ( [ [ 1. , 0. , 0. , 1. ] ] ) else : Npwl = None Hpwl = None Cpwl = array ( [ ] ) fparm_pwl = zeros ( ( 0 , 4 ) ) return Npwl , Hpwl , Cpwl , fparm_pwl , any_pwl
Returns the piece - wise linear components of the objective function .
704
def _quadratic_costs ( self , generators , ipol , nxyz , base_mva ) : npol = len ( ipol ) rnpol = range ( npol ) gpol = [ g for g in generators if g . pcost_model == POLYNOMIAL ] if [ g for g in gpol if len ( g . p_cost ) > 3 ] : logger . error ( "Order of polynomial cost greater than quadratic." ) iqdr = [ i for i , g in enumerate ( generators ) if g . pcost_model == POLYNOMIAL and len ( g . p_cost ) == 3 ] ilin = [ i for i , g in enumerate ( generators ) if g . pcost_model == POLYNOMIAL and len ( g . p_cost ) == 2 ] polycf = zeros ( ( npol , 3 ) ) if npol > 0 : if len ( iqdr ) > 0 : polycf [ iqdr , : ] = array ( [ list ( g . p_cost ) for g in generators ] ) if len ( ilin ) > 0 : polycf [ ilin , 1 : ] = array ( [ list ( g . p_cost [ : 2 ] ) for g in generators ] ) polycf = polycf * array ( [ base_mva ** 2 , base_mva , 1 ] ) Pg = self . om . get_var ( "Pg" ) Npol = csr_matrix ( ( ones ( npol ) , ( rnpol , Pg . i1 + array ( ipol ) ) ) , ( npol , nxyz ) ) Hpol = csr_matrix ( ( 2 * polycf [ : , 0 ] , ( rnpol , rnpol ) ) , ( npol , npol ) ) Cpol = polycf [ : , 1 ] fparm_pol = ( ones ( npol ) * array ( [ [ 1 ] , [ 0 ] , [ 0 ] , [ 1 ] ] ) ) . T else : Npol = Hpol = None Cpol = array ( [ ] ) fparm_pol = zeros ( ( 0 , 4 ) ) return Npol , Hpol , Cpol , fparm_pol , polycf , npol
Returns the quadratic cost components of the objective function .
705
def _combine_costs ( self , Npwl , Hpwl , Cpwl , fparm_pwl , any_pwl , Npol , Hpol , Cpol , fparm_pol , npol , nw ) : NN = vstack ( [ n for n in [ Npwl , Npol ] if n is not None ] , "csr" ) if ( Hpwl is not None ) and ( Hpol is not None ) : Hpwl = hstack ( [ Hpwl , csr_matrix ( ( any_pwl , npol ) ) ] ) Hpol = hstack ( [ csr_matrix ( ( npol , any_pwl ) ) , Hpol ] ) HHw = vstack ( [ h for h in [ Hpwl , Hpol ] if h is not None ] , "csr" ) CCw = r_ [ Cpwl , Cpol ] ffparm = r_ [ fparm_pwl , fparm_pol ] return NN , HHw , CCw , ffparm
Combines pwl polynomial and user - defined costs .
706
def _transform_coefficients ( self , NN , HHw , CCw , ffparm , polycf , any_pwl , npol , nw ) : nnw = any_pwl + npol + nw M = csr_matrix ( ( ffparm [ : , 3 ] , ( range ( nnw ) , range ( nnw ) ) ) ) MR = M * ffparm [ : , 2 ] HMR = HHw * MR MN = M * NN HH = MN . T * HHw * MN CC = MN . T * ( CCw - HMR ) C0 = 1. / 2. * MR . T * HMR + sum ( polycf [ : , 2 ] ) return HH , CC , C0 [ 0 ]
Transforms quadratic coefficients for w into coefficients for x .
707
def _ref_bus_angle_constraint ( self , buses , Va , xmin , xmax ) : refs = [ bus . _i for bus in buses if bus . type == REFERENCE ] Varefs = array ( [ b . v_angle for b in buses if b . type == REFERENCE ] ) xmin [ Va . i1 - 1 + refs ] = Varefs xmax [ Va . iN - 1 + refs ] = Varefs return xmin , xmax
Adds a constraint on the reference bus angles .
708
def _f ( self , x , user_data = None ) : p_gen = x [ self . _Pg . i1 : self . _Pg . iN + 1 ] q_gen = x [ self . _Qg . i1 : self . _Qg . iN + 1 ] xx = r_ [ p_gen , q_gen ] * self . _base_mva if len ( self . _ipol ) > 0 : f = sum ( [ g . total_cost ( xx [ i ] ) for i , g in enumerate ( self . _gn ) ] ) else : f = 0 if self . _ny : y = self . om . get_var ( "y" ) self . _ccost = csr_matrix ( ( ones ( self . _ny ) , ( range ( y . i1 , y . iN + 1 ) , zeros ( self . _ny ) ) ) , shape = ( self . _nxyz , 1 ) ) . T f = f + self . _ccost * x else : self . _ccost = zeros ( ( 1 , self . _nxyz ) ) return f
Evaluates the objective function .
709
def _df ( self , x , user_data = None ) : p_gen = x [ self . _Pg . i1 : self . _Pg . iN + 1 ] q_gen = x [ self . _Qg . i1 : self . _Qg . iN + 1 ] xx = r_ [ p_gen , q_gen ] * self . _base_mva iPg = range ( self . _Pg . i1 , self . _Pg . iN + 1 ) iQg = range ( self . _Qg . i1 , self . _Qg . iN + 1 ) df_dPgQg = zeros ( ( 2 * self . _ng , 1 ) ) for i in self . _ipol : p_cost = list ( self . _gn [ i ] . p_cost ) df_dPgQg [ i ] = self . _base_mva * polyval ( polyder ( p_cost ) , xx [ i ] ) df = zeros ( ( self . _nxyz , 1 ) ) df [ iPg ] = df_dPgQg [ : self . _ng ] df [ iQg ] = df_dPgQg [ self . _ng : self . _ng + self . _ng ] df = df + self . _ccost . T return asarray ( df ) . flatten ( )
Evaluates the cost gradient .
710
def _d2f ( self , x ) : d2f_dPg2 = lil_matrix ( ( self . _ng , 1 ) ) d2f_dQg2 = lil_matrix ( ( self . _ng , 1 ) ) for i in self . _ipol : p_cost = list ( self . _gn [ i ] . p_cost ) d2f_dPg2 [ i , 0 ] = polyval ( polyder ( p_cost , 2 ) , self . _Pg . v0 [ i ] * self . _base_mva ) * self . _base_mva ** 2 i = r_ [ range ( self . _Pg . i1 , self . _Pg . iN + 1 ) , range ( self . _Qg . i1 , self . _Qg . iN + 1 ) ] d2f = csr_matrix ( ( vstack ( [ d2f_dPg2 , d2f_dQg2 ] ) . toarray ( ) . flatten ( ) , ( i , i ) ) , shape = ( self . _nxyz , self . _nxyz ) ) return d2f
Evaluates the cost Hessian .
711
def _gh ( self , x ) : Pgen = x [ self . _Pg . i1 : self . _Pg . iN + 1 ] Qgen = x [ self . _Qg . i1 : self . _Qg . iN + 1 ] for i , gen in enumerate ( self . _gn ) : gen . p = Pgen [ i ] * self . _base_mva gen . q = Qgen [ i ] * self . _base_mva Sbus = self . om . case . getSbus ( self . _bs ) Vang = x [ self . _Va . i1 : self . _Va . iN + 1 ] Vmag = x [ self . _Vm . i1 : self . _Vm . iN + 1 ] V = Vmag * exp ( 1j * Vang ) mis = V * conj ( self . _Ybus * V ) - Sbus g = r_ [ mis . real , mis . imag ] flow_max = array ( [ ( l . rate_a / self . _base_mva ) ** 2 for l in self . _ln ] ) for i , v in enumerate ( flow_max ) : if v == 0.0 : flow_max [ i ] = Inf if self . flow_lim == IFLOW : If = self . _Yf * V It = self . _Yt * V h = r_ [ ( If * conj ( If ) ) - flow_max , ( It * conj ( It ) ) - flow_max ] else : i_fbus = [ e . from_bus . _i for e in self . _ln ] i_tbus = [ e . to_bus . _i for e in self . _ln ] Sf = V [ i_fbus ] * conj ( self . _Yf * V ) St = V [ i_tbus ] * conj ( self . _Yt * V ) if self . flow_lim == PFLOW : h = r_ [ Sf . real ( ) ** 2 - flow_max , St . real ( ) ** 2 - flow_max ] elif self . flow_lim == SFLOW : h = r_ [ ( Sf * conj ( Sf ) ) - flow_max , ( St * conj ( St ) ) - flow_max ] . real else : raise ValueError return h , g
Evaluates the constraint function values .
712
def _costfcn ( self , x ) : f = self . _f ( x ) df = self . _df ( x ) d2f = self . _d2f ( x ) return f , df , d2f
Evaluates the objective function gradient and Hessian for OPF .
713
def _consfcn ( self , x ) : h , g = self . _gh ( x ) dh , dg = self . _dgh ( x ) return h , g , dh , dg
Evaluates nonlinear constraints and their Jacobian for OPF .
714
def read ( self , file_or_filename ) : if isinstance ( file_or_filename , basestring ) : fname = os . path . basename ( file_or_filename ) logger . info ( "Unpickling case file [%s]." % fname ) file = None try : file = open ( file_or_filename , "rb" ) except : logger . error ( "Error opening %s." % fname ) return None finally : if file is not None : case = pickle . load ( file ) file . close ( ) else : file = file_or_filename case = pickle . load ( file ) return case
Loads a pickled case .
715
def write ( self , file_or_filename ) : if isinstance ( file_or_filename , basestring ) : fname = os . path . basename ( file_or_filename ) logger . info ( "Pickling case [%s]." % fname ) file = None try : file = open ( file_or_filename , "wb" ) except : logger . error ( "Error opening '%s'." % ( fname ) ) return False finally : if file is not None : pickle . dump ( self . case , file ) file . close ( ) else : file = file_or_filename pickle . dump ( file , self . case ) return True
Writes the case to file using pickle .
716
def process_token ( self , tok ) : if ( tok [ 0 ] . __str__ ( ) in ( 'Token.Comment.Multiline' , 'Token.Comment' , 'Token.Literal.String.Doc' ) ) : self . comments += tok [ 1 ] . count ( '\n' ) + 1 elif ( tok [ 0 ] . __str__ ( ) in ( 'Token.Comment.Single' ) ) : self . comments += 1 elif ( self . contains_code and tok [ 0 ] . __str__ ( ) . startswith ( 'Token.Text' ) and tok [ 1 ] . count ( u'\n' ) ) : self . contains_code = False self . sloc += 1 elif ( tok [ 0 ] . __str__ ( ) == 'Token.Comment.Preproc' and tok [ 1 ] . count ( u'\n' ) ) : self . contains_code = False self . sloc += 1 elif ( tok [ 0 ] [ 0 ] in token_types ) : self . contains_code = True
count comments and non - empty lines that contain code
717
def get_metrics ( self ) : if ( self . sloc == 0 ) : if ( self . comments == 0 ) : ratio_comment_to_code = 0.00 else : ratio_comment_to_code = 1.00 else : ratio_comment_to_code = float ( self . comments ) / self . sloc metrics = OrderedDict ( [ ( 'sloc' , self . sloc ) , ( 'comments' , self . comments ) , ( 'ratio_comment_to_code' , round ( ratio_comment_to_code , 2 ) ) ] ) return metrics
Calculate ratio_comment_to_code and return with the other values
718
def performAction ( self , action ) : gs = [ g for g in self . case . online_generators if g . bus . type != REFERENCE ] assert len ( action ) == len ( gs ) logger . info ( "Action: %s" % list ( action ) ) for i , g in enumerate ( gs ) : g . p = action [ i ] NewtonPF ( self . case , verbose = False ) . solve ( ) self . _Pg [ : , self . _step ] = [ g . p for g in self . case . online_generators ] if self . _step != len ( self . profile ) - 1 : pq_buses = [ b for b in self . case . buses if b . type == PQ ] for i , b in enumerate ( pq_buses ) : b . p_demand = self . _Pd0 [ i ] * self . profile [ self . _step + 1 ] self . _step += 1 logger . info ( "Entering step %d." % self . _step )
Perform an action on the world that changes it s internal state .
719
def reset ( self ) : logger . info ( "Reseting environment." ) self . _step = 0 gs = [ g for g in self . case . online_generators if g . bus . type != REFERENCE ] for i , g in enumerate ( gs ) : g . p = self . _Pg0 [ i ] for i , b in enumerate ( [ b for b in self . case . buses if b . type == PQ ] ) : b . p_demand = self . _Pd0 [ i ] * self . profile [ self . _step ] self . _Pg = zeros ( ( len ( self . case . online_generators ) , len ( self . profile ) ) ) self . case . reset ( )
Re - initialises the environment .
720
def isFinished ( self ) : finished = ( self . env . _step == len ( self . env . profile ) ) if finished : logger . info ( "Finished episode." ) return finished
Is the current episode over?
721
def _oneInteraction ( self ) : if self . doOptimization : raise Exception ( 'When using a black-box learning algorithm, only full episodes can be done.' ) else : self . stepid += 1 self . agent . integrateObservation ( self . task . getObservation ( ) ) self . task . performAction ( self . agent . getAction ( ) ) for i , g in enumerate ( self . task . env . case . online_generators ) : self . Pg [ i , self . stepid - 1 ] = self . Pg [ i , self . stepid - 1 ] + g . p reward = self . task . getReward ( ) self . agent . giveReward ( reward ) return reward
Does one interaction between the task and the agent .
722
def doEpisodes ( self , number = 1 ) : env = self . task . env self . Pg = zeros ( ( len ( env . case . online_generators ) , len ( env . profile ) ) ) rewards = super ( OPFExperiment , self ) . doEpisodes ( number ) self . Pg = self . Pg / number return rewards
Does the the given number of episodes .
723
def getMethodByName ( obj , name ) : try : obj = obj . _getMethodByName ( name ) except : names = name . split ( "." ) for name in names : if nameAllowed ( name ) : obj = getattr ( obj , name ) else : raise MethodNameNotAllowed ( ) return obj
searches for an object with the name given inside the object given . obj . child . meth will return the meth obj .
724
def waitForResponse ( self , timeOut = None ) : self . __evt . wait ( timeOut ) if self . waiting ( ) : raise Timeout ( ) else : if self . response [ "error" ] : raise Exception ( self . response [ "error" ] ) else : return self . response [ "result" ]
blocks until the response arrived or timeout is reached .
725
def sendRequest ( self , name , args ) : ( respEvt , id ) = self . newResponseEvent ( ) self . sendMessage ( { "id" : id , "method" : name , "params" : args } ) return respEvt
sends a request to the peer
726
def sendResponse ( self , id , result , error ) : self . sendMessage ( { "result" : result , "error" : error , "id" : id } )
sends a response to the peer
727
def newResponseEvent ( self ) : respEvt = ResponseEvent ( ) self . respLock . acquire ( ) eid = id ( respEvt ) self . respEvents [ eid ] = respEvt self . respLock . release ( ) return ( respEvt , eid )
creates a response event and adds it to a waiting list When the reponse arrives it will be removed from the list .
728
def handleResponse ( self , resp ) : id = resp [ "id" ] evt = self . respEvents [ id ] del ( self . respEvents [ id ] ) evt . handleResponse ( resp )
handles a response by fireing the response event for the response coming in
729
def handleRequest ( self , req ) : name = req [ "method" ] params = req [ "params" ] id = req [ "id" ] obj = None try : obj = getMethodByName ( self . service , name ) except MethodNameNotAllowed , e : self . sendResponse ( id , None , e ) except : self . sendResponse ( id , None , MethodNotFound ( ) ) if obj : try : rslt = obj ( * params ) self . sendResponse ( id , rslt , None ) except TypeError : s = getTracebackStr ( ) self . sendResponse ( id , None , InvalidMethodParameters ( ) ) except : s = getTracebackStr ( ) self . sendResponse ( id , None , s )
handles a request by calling the appropriete method the service exposes
730
def handleNotification ( self , req ) : name = req [ "method" ] params = req [ "params" ] try : obj = getMethodByName ( self . service , name ) rslt = obj ( * params ) except : pass
handles a notification request by calling the appropriete method the service exposes
731
def read ( self , file_or_filename ) : self . file_or_filename = file_or_filename logger . info ( "Parsing PSAT case file [%s]." % file_or_filename ) t0 = time . time ( ) self . case = Case ( ) if isinstance ( file_or_filename , basestring ) : name , _ = splitext ( basename ( file_or_filename ) ) else : name , _ = splitext ( file_or_filename . name ) self . case . name = name bus_array = self . _get_bus_array_construct ( ) line_array = self . _get_line_array_construct ( ) slack_array = self . _get_slack_array_construct ( ) pv_array = self . _get_pv_array_construct ( ) pq_array = self . _get_pq_array_construct ( ) demand_array = self . _get_demand_array_construct ( ) supply_array = self . _get_supply_array_construct ( ) case = ZeroOrMore ( matlab_comment ) + bus_array + ZeroOrMore ( matlab_comment ) + line_array + ZeroOrMore ( matlab_comment ) + slack_array + ZeroOrMore ( matlab_comment ) + pv_array + ZeroOrMore ( matlab_comment ) + pq_array + ZeroOrMore ( matlab_comment ) + demand_array + ZeroOrMore ( matlab_comment ) + supply_array case . parseFile ( file_or_filename ) elapsed = time . time ( ) - t0 logger . info ( "PSAT case file parsed in %.3fs." % elapsed ) return self . case
Parses a PSAT data file and returns a case object
732
def _get_bus_array_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) v_base = real . setResultsName ( "v_base" ) v_magnitude = Optional ( real ) . setResultsName ( "v_magnitude" ) v_angle = Optional ( real ) . setResultsName ( "v_angle" ) area = Optional ( integer ) . setResultsName ( "area" ) region = Optional ( integer ) . setResultsName ( "region" ) bus_data = bus_no + v_base + v_magnitude + v_angle + area + region + scolon bus_data . setParseAction ( self . push_bus ) bus_array = Literal ( "Bus.con" ) + "=" + "[" + "..." + ZeroOrMore ( bus_data + Optional ( "]" + scolon ) ) bus_array . setParseAction ( self . sort_buses ) return bus_array
Returns a construct for an array of bus data .
733
def _get_line_array_construct ( self ) : from_bus = integer . setResultsName ( "fbus" ) to_bus = integer . setResultsName ( "tbus" ) s_rating = real . setResultsName ( "s_rating" ) v_rating = real . setResultsName ( "v_rating" ) f_rating = real . setResultsName ( "f_rating" ) length = real . setResultsName ( "length" ) v_ratio = real . setResultsName ( "v_ratio" ) r = real . setResultsName ( "r" ) x = real . setResultsName ( "x" ) b = real . setResultsName ( "b" ) tap_ratio = real . setResultsName ( "tap" ) phase_shift = real . setResultsName ( "shift" ) i_limit = Optional ( real ) . setResultsName ( "i_limit" ) p_limit = Optional ( real ) . setResultsName ( "p_limit" ) s_limit = Optional ( real ) . setResultsName ( "s_limit" ) status = Optional ( boolean ) . setResultsName ( "status" ) line_data = from_bus + to_bus + s_rating + v_rating + f_rating + length + v_ratio + r + x + b + tap_ratio + phase_shift + i_limit + p_limit + s_limit + status + scolon line_data . setParseAction ( self . push_line ) line_array = Literal ( "Line.con" ) + "=" + "[" + "..." + ZeroOrMore ( line_data + Optional ( "]" + scolon ) ) return line_array
Returns a construct for an array of line data .
734
def _get_slack_array_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) s_rating = real . setResultsName ( "s_rating" ) v_rating = real . setResultsName ( "v_rating" ) v_magnitude = real . setResultsName ( "v_magnitude" ) ref_angle = real . setResultsName ( "ref_angle" ) q_max = Optional ( real ) . setResultsName ( "q_max" ) q_min = Optional ( real ) . setResultsName ( "q_min" ) v_max = Optional ( real ) . setResultsName ( "v_max" ) v_min = Optional ( real ) . setResultsName ( "v_min" ) p_guess = Optional ( real ) . setResultsName ( "p_guess" ) lp_coeff = Optional ( real ) . setResultsName ( "lp_coeff" ) ref_bus = Optional ( boolean ) . setResultsName ( "ref_bus" ) status = Optional ( boolean ) . setResultsName ( "status" ) slack_data = bus_no + s_rating + v_rating + v_magnitude + ref_angle + q_max + q_min + v_max + v_min + p_guess + lp_coeff + ref_bus + status + scolon slack_data . setParseAction ( self . push_slack ) slack_array = Literal ( "SW.con" ) + "=" + "[" + "..." + ZeroOrMore ( slack_data + Optional ( "]" + scolon ) ) return slack_array
Returns a construct for an array of slack bus data .
735
def _get_pv_array_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) s_rating = real . setResultsName ( "s_rating" ) v_rating = real . setResultsName ( "v_rating" ) p = real . setResultsName ( "p" ) v = real . setResultsName ( "v" ) q_max = Optional ( real ) . setResultsName ( "q_max" ) q_min = Optional ( real ) . setResultsName ( "q_min" ) v_max = Optional ( real ) . setResultsName ( "v_max" ) v_min = Optional ( real ) . setResultsName ( "v_min" ) lp_coeff = Optional ( real ) . setResultsName ( "lp_coeff" ) status = Optional ( boolean ) . setResultsName ( "status" ) pv_data = bus_no + s_rating + v_rating + p + v + q_max + q_min + v_max + v_min + lp_coeff + status + scolon pv_data . setParseAction ( self . push_pv ) pv_array = Literal ( "PV.con" ) + "=" + "[" + "..." + ZeroOrMore ( pv_data + Optional ( "]" + scolon ) ) return pv_array
Returns a construct for an array of PV generator data .
736
def _get_pq_array_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) s_rating = real . setResultsName ( "s_rating" ) v_rating = real . setResultsName ( "v_rating" ) p = real . setResultsName ( "p" ) q = real . setResultsName ( "q" ) v_max = Optional ( real ) . setResultsName ( "v_max" ) v_min = Optional ( real ) . setResultsName ( "v_min" ) z_conv = Optional ( boolean ) . setResultsName ( "z_conv" ) status = Optional ( boolean ) . setResultsName ( "status" ) pq_data = bus_no + s_rating + v_rating + p + q + v_max + v_min + z_conv + status + scolon pq_data . setParseAction ( self . push_pq ) pq_array = Literal ( "PQ.con" ) + "=" + "[" + "..." + ZeroOrMore ( pq_data + Optional ( "]" + scolon ) ) return pq_array
Returns a construct for an array of PQ load data .
737
def _get_demand_array_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) s_rating = real . setResultsName ( "s_rating" ) p_direction = real . setResultsName ( "p_direction" ) q_direction = real . setResultsName ( "q_direction" ) p_bid_max = real . setResultsName ( "p_bid_max" ) p_bid_min = real . setResultsName ( "p_bid_min" ) p_optimal_bid = Optional ( real ) . setResultsName ( "p_optimal_bid" ) p_fixed = real . setResultsName ( "p_fixed" ) p_proportional = real . setResultsName ( "p_proportional" ) p_quadratic = real . setResultsName ( "p_quadratic" ) q_fixed = real . setResultsName ( "q_fixed" ) q_proportional = real . setResultsName ( "q_proportional" ) q_quadratic = real . setResultsName ( "q_quadratic" ) commitment = boolean . setResultsName ( "commitment" ) cost_tie_break = real . setResultsName ( "cost_tie_break" ) cost_cong_up = real . setResultsName ( "cost_cong_up" ) cost_cong_down = real . setResultsName ( "cost_cong_down" ) status = Optional ( boolean ) . setResultsName ( "status" ) demand_data = bus_no + s_rating + p_direction + q_direction + p_bid_max + p_bid_min + p_optimal_bid + p_fixed + p_proportional + p_quadratic + q_fixed + q_proportional + q_quadratic + commitment + cost_tie_break + cost_cong_up + cost_cong_down + status + scolon demand_data . setParseAction ( self . push_demand ) demand_array = Literal ( "Demand.con" ) + "=" + "[" + "..." + ZeroOrMore ( demand_data + Optional ( "]" + scolon ) ) return demand_array
Returns a construct for an array of power demand data .
738
def _get_supply_array_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) s_rating = real . setResultsName ( "s_rating" ) p_direction = real . setResultsName ( "p_direction" ) p_bid_max = real . setResultsName ( "p_bid_max" ) p_bid_min = real . setResultsName ( "p_bid_min" ) p_bid_actual = real . setResultsName ( "p_bid_actual" ) p_fixed = real . setResultsName ( "p_fixed" ) p_proportional = real . setResultsName ( "p_proportional" ) p_quadratic = real . setResultsName ( "p_quadratic" ) q_fixed = real . setResultsName ( "q_fixed" ) q_proportional = real . setResultsName ( "q_proportional" ) q_quadratic = real . setResultsName ( "q_quadratic" ) commitment = boolean . setResultsName ( "commitment" ) cost_tie_break = real . setResultsName ( "cost_tie_break" ) lp_factor = real . setResultsName ( "lp_factor" ) q_max = real . setResultsName ( "q_max" ) q_min = real . setResultsName ( "q_min" ) cost_cong_up = real . setResultsName ( "cost_cong_up" ) cost_cong_down = real . setResultsName ( "cost_cong_down" ) status = Optional ( boolean ) . setResultsName ( "status" ) supply_data = bus_no + s_rating + p_direction + p_bid_max + p_bid_min + p_bid_actual + p_fixed + p_proportional + p_quadratic + q_fixed + q_proportional + q_quadratic + commitment + cost_tie_break + lp_factor + q_max + q_min + cost_cong_up + cost_cong_down + status + scolon supply_data . setParseAction ( self . push_supply ) supply_array = Literal ( "Supply.con" ) + "=" + "[" + "..." + ZeroOrMore ( supply_data + Optional ( "]" + scolon ) ) return supply_array
Returns a construct for an array of power supply data .
739
def _get_generator_ramping_construct ( self ) : supply_no = integer . setResultsName ( "supply_no" ) s_rating = real . setResultsName ( "s_rating" ) up_rate = real . setResultsName ( "up_rate" ) down_rate = real . setResultsName ( "down_rate" ) min_period_up = real . setResultsName ( "min_period_up" ) min_period_down = real . setResultsName ( "min_period_down" ) initial_period_up = integer . setResultsName ( "initial_period_up" ) initial_period_down = integer . setResultsName ( "initial_period_down" ) c_startup = real . setResultsName ( "c_startup" ) status = boolean . setResultsName ( "status" ) g_ramp_data = supply_no + s_rating + up_rate + down_rate + min_period_up + min_period_down + initial_period_up + initial_period_down + c_startup + status + scolon g_ramp_array = Literal ( "Rmpg.con" ) + "=" + "[" + ZeroOrMore ( g_ramp_data + Optional ( "]" + scolon ) ) return g_ramp_array
Returns a construct for an array of generator ramping data .
740
def _get_load_ramping_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) s_rating = real . setResultsName ( "s_rating" ) up_rate = real . setResultsName ( "up_rate" ) down_rate = real . setResultsName ( "down_rate" ) min_up_time = real . setResultsName ( "min_up_time" ) min_down_time = real . setResultsName ( "min_down_time" ) n_period_up = integer . setResultsName ( "n_period_up" ) n_period_down = integer . setResultsName ( "n_period_down" ) status = boolean . setResultsName ( "status" ) l_ramp_data = bus_no + s_rating + up_rate + down_rate + min_up_time + min_down_time + n_period_up + n_period_down + status + scolon l_ramp_array = Literal ( "Rmpl.con" ) + "=" + "[" + ZeroOrMore ( l_ramp_data + Optional ( "]" + scolon ) ) return l_ramp_array
Returns a construct for an array of load ramping data .
741
def push_bus ( self , tokens ) : logger . debug ( "Pushing bus data: %s" % tokens ) bus = Bus ( ) bus . name = tokens [ "bus_no" ] bus . v_magnitude = tokens [ "v_magnitude" ] bus . v_angle = tokens [ "v_angle" ] bus . v_magnitude = tokens [ "v_magnitude" ] bus . v_angle = tokens [ "v_angle" ] self . case . buses . append ( bus )
Adds a Bus object to the case .
742
def push_line ( self , tokens ) : logger . debug ( "Pushing line data: %s" % tokens ) from_bus = self . case . buses [ tokens [ "fbus" ] - 1 ] to_bus = self . case . buses [ tokens [ "tbus" ] - 1 ] e = Branch ( from_bus = from_bus , to_bus = to_bus ) e . r = tokens [ "r" ] e . x = tokens [ "x" ] e . b = tokens [ "b" ] e . rate_a = tokens [ "s_limit" ] e . rate_b = tokens [ "p_limit" ] e . rate_c = tokens [ "i_limit" ] if tokens [ "tap" ] == 0 : e . ratio = 1.0 else : e . ratio = tokens [ "tap" ] e . phase_shift = tokens [ "shift" ] self . case . branches . append ( e )
Adds a Branch object to the case .
743
def push_slack ( self , tokens ) : logger . debug ( "Pushing slack data: %s" % tokens ) bus = self . case . buses [ tokens [ "bus_no" ] - 1 ] g = Generator ( bus ) g . q_max = tokens [ "q_max" ] g . q_min = tokens [ "q_min" ] self . case . generators . append ( g ) bus . type = "ref"
Finds the slack bus adds a Generator with the appropriate data and sets the bus type to slack .
744
def push_pv ( self , tokens ) : logger . debug ( "Pushing PV data: %s" % tokens ) bus = self . case . buses [ tokens [ "bus_no" ] - 1 ] g = Generator ( bus ) g . p = tokens [ "p" ] g . q_max = tokens [ "q_max" ] g . q_min = tokens [ "q_min" ] self . case . generators . append ( g )
Creates and Generator object populates it with data finds its Bus and adds it .
745
def push_pq ( self , tokens ) : logger . debug ( "Pushing PQ data: %s" % tokens ) bus = self . case . buses [ tokens [ "bus_no" ] - 1 ] bus . p_demand = tokens [ "p" ] bus . q_demand = tokens [ "q" ]
Creates and Load object populates it with data finds its Bus and adds it .
746
def push_supply ( self , tokens ) : logger . debug ( "Pushing supply data: %s" % tokens ) bus = self . case . buses [ tokens [ "bus_no" ] - 1 ] n_generators = len ( [ g for g in self . case . generators if g . bus == bus ] ) if n_generators == 0 : logger . error ( "No generator at bus [%s] for matching supply" % bus ) return elif n_generators > 1 : g = [ g for g in self . case . generators if g . bus == bus ] [ 0 ] logger . warning ( "More than one generator at bus [%s] for demand. Using the " "first one [%s]." % ( bus , g ) ) else : g = [ g for g in self . case . generators if g . bus == bus ] [ 0 ] g . pcost_model = "poly" g . poly_coeffs = ( tokens [ "p_fixed" ] , tokens [ "p_proportional" ] , tokens [ "p_quadratic" ] )
Adds OPF and CPF data to a Generator .
747
def _parse_file ( self , file ) : case = Case ( ) file . seek ( 0 ) line = file . readline ( ) . split ( ) if line [ 0 ] != "function" : logger . error ( "Invalid data file header." ) return case if line [ 1 ] != "mpc" : self . _is_struct = False base = "" else : base = "mpc." case . name = line [ - 1 ] for line in file : if line . startswith ( "%sbaseMVA" % base ) : case_data = line . rstrip ( ";\n" ) . split ( ) case . base_mva = float ( case_data [ - 1 ] ) elif line . startswith ( "%sbus" % base ) : self . _parse_buses ( case , file ) elif line . startswith ( "%sgencost" % base ) : self . _parse_gencost ( case , file ) elif line . startswith ( "%sgen" % base ) : self . _parse_generators ( case , file ) elif line . startswith ( "%sbranch" % base ) : self . _parse_branches ( case , file ) return case
Parses the given file - like object .
748
def write ( self , file_or_filename ) : if isinstance ( file_or_filename , basestring ) : self . _fcn_name , _ = splitext ( basename ( file_or_filename ) ) else : self . _fcn_name = self . case . name self . _fcn_name = self . _fcn_name . replace ( "," , "" ) . replace ( " " , "_" ) super ( MATPOWERWriter , self ) . write ( file_or_filename )
Writes case data to file in MATPOWER format .
749
def write_case_data ( self , file ) : file . write ( "function mpc = %s\n" % self . _fcn_name ) file . write ( '\n%%%% MATPOWER Case Format : Version %d\n' % 2 ) file . write ( "mpc.version = '%d';\n" % 2 ) file . write ( "\n%%%%----- Power Flow Data -----%%%%\n" ) file . write ( "%%%% system MVA base\n" ) file . write ( "%sbaseMVA = %g;\n" % ( self . _prefix , self . case . base_mva ) )
Writes the case data in MATPOWER format .
750
def write_generator_cost_data ( self , file ) : file . write ( "\n%%%% generator cost data\n" ) file . write ( "%%\t1\tstartup\tshutdown\tn\tx1\ty1\t...\txn\tyn\n" ) file . write ( "%%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\n" ) file . write ( "%sgencost = [\n" % self . _prefix ) for generator in self . case . generators : n = len ( generator . p_cost ) template = '\t%d\t%g\t%g\t%d' for _ in range ( n ) : template = '%s\t%%g' % template template = '%s;\n' % template if generator . pcost_model == PW_LINEAR : t = 2 c = [ v for pc in generator . p_cost for v in pc ] elif generator . pcost_model == POLYNOMIAL : t = 1 c = list ( generator . p_cost ) else : raise vals = [ t , generator . c_startup , generator . c_shutdown , n ] + c file . write ( template % tuple ( vals ) ) file . write ( "];\n" )
Writes generator cost data to file .
751
def write_area_data ( self , file ) : file . write ( "%% area data" + "\n" ) file . write ( "%\tno.\tprice_ref_bus" + "\n" ) file . write ( "areas = [" + "\n" ) file . write ( "\t1\t1;" + "\n" ) file . write ( "];" + "\n" )
Writes area data to file .
752
def process_file ( self , language , key , token_list ) : self . language = language for tok in token_list : self . process_token ( tok )
Initiate processing for each token .
753
def draw_plot ( self ) : pylab . ion ( ) fig = pylab . figure ( 1 ) reward_axis = fig . add_subplot ( 3 , 1 , 3 ) reward_lines = reward_axis . plot ( self . reward_data [ 0 , 0 ] , [ 0 ] , "mx-" ) self . reward_line = reward_lines [ 0 ] pylab . draw ( )
Initialises plots of the environment .
754
def write_case_data ( self , file ) : change_code = 0 s_base = self . case . base_mva timestr = time . strftime ( "%Y%m%d%H%M" , time . gmtime ( ) ) file . write ( "%d, %8.2f, 30 / PSS(tm)E-30 RAW created by Pylon (%s).\n" % ( change_code , s_base , timestr ) ) file . write ( "Modified by Hantao Cui, CURENT, UTK\n " ) file . write ( "%s, %d BUSES, %d BRANCHES\n" % ( self . case . name , len ( self . case . buses ) , len ( self . case . branches ) ) )
Writes case data to file .
755
def plotGenCost ( generators ) : figure ( ) plots = [ ] for generator in generators : if generator . pcost_model == PW_LINEAR : x = [ x for x , _ in generator . p_cost ] y = [ y for _ , y in generator . p_cost ] elif generator . pcost_model == POLYNOMIAL : x = scipy . arange ( generator . p_min , generator . p_max , 5 ) y = scipy . polyval ( scipy . array ( generator . p_cost ) , x ) else : raise plots . append ( plot ( x , y ) ) xlabel ( "P (MW)" ) ylabel ( "Cost ($)" ) legend ( plots , [ g . name for g in generators ] ) show ( )
Plots the costs of the given generators .
756
def write ( self , file ) : file . write ( "State\n" ) file . write ( ( "-" * 5 ) + "\n" ) self . writeDataTable ( file , type = "state" ) file . write ( "Action\n" ) file . write ( ( "-" * 6 ) + "\n" ) self . writeDataTable ( file , type = "action" ) file . write ( "Reward\n" ) file . write ( ( "-" * 6 ) + "\n" ) self . writeDataTable ( file , type = "reward" )
Writes market experiment data to file in ReStructuredText format .
757
def writeDataTable ( self , file , type ) : agents = self . experiment . agents numAgents = len ( self . experiment . agents ) colWidth = 8 idxColWidth = 3 sep = ( "=" * idxColWidth ) + " " + ( "=" * colWidth + " " ) * numAgents + "\n" file . write ( sep ) file . write ( ".." . rjust ( idxColWidth ) + " " ) for agent in agents : file . write ( agent . name [ - colWidth : ] . center ( colWidth ) + " " ) file . write ( "\n" ) file . write ( sep ) if agents : rows , _ = agents [ 0 ] . history . getField ( type ) . shape else : rows , _ = ( 0 , 0 ) for sequence in range ( min ( rows , 999 ) ) : file . write ( str ( sequence + 1 ) . rjust ( idxColWidth ) + " " ) for agent in agents : field = agent . history . getField ( type ) file . write ( "%8.3f " % field [ sequence , 0 ] ) file . write ( "\n" ) file . write ( sep )
Writes agent data to an ReST table . The type argument may be state action or reward .
758
def performAction ( self , action ) : self . t += 1 Task . performAction ( self , action ) self . samples += 1
Execute one action .
759
def split_dae_alg ( eqs : SYM , dx : SYM ) -> Dict [ str , SYM ] : dae = [ ] alg = [ ] for eq in ca . vertsplit ( eqs ) : if ca . depends_on ( eq , dx ) : dae . append ( eq ) else : alg . append ( eq ) return { 'dae' : ca . vertcat ( * dae ) , 'alg' : ca . vertcat ( * alg ) }
Split equations into differential algebraic and algebraic only
760
def permute ( x : SYM , perm : List [ int ] ) -> SYM : x_s = [ ] for i in perm : x_s . append ( x [ i ] ) return ca . vertcat ( * x_s )
Perumute a vector
761
def blt ( f : List [ SYM ] , x : List [ SYM ] ) -> Dict [ str , Any ] : J = ca . jacobian ( f , x ) nblock , rowperm , colperm , rowblock , colblock , coarserow , coarsecol = J . sparsity ( ) . btf ( ) return { 'J' : J , 'nblock' : nblock , 'rowperm' : rowperm , 'colperm' : colperm , 'rowblock' : rowblock , 'colblock' : colblock , 'coarserow' : coarserow , 'coarsecol' : coarsecol }
Sort equations by dependence
762
def create_function_f_m ( self ) : return ca . Function ( 'f_m' , [ self . t , self . x , self . y , self . m , self . p , self . c , self . pre_c , self . ng , self . nu ] , [ self . f_m ] , [ 't' , 'x' , 'y' , 'm' , 'p' , 'c' , 'pre_c' , 'ng' , 'nu' ] , [ 'm' ] , self . func_opt )
Discrete state dynamics
763
def create_function_f_J ( self ) : return ca . Function ( 'J' , [ self . t , self . x , self . y , self . m , self . p , self . c , self . ng , self . nu ] , [ ca . jacobian ( self . f_x_rhs , self . x ) ] , [ 't' , 'x' , 'y' , 'm' , 'p' , 'c' , 'ng' , 'nu' ] , [ 'J' ] , self . func_opt )
Jacobian for state integration
764
def to_ode ( self ) -> HybridOde : res_split = split_dae_alg ( self . f_x , self . dx ) alg = res_split [ 'alg' ] dae = res_split [ 'dae' ] x_rhs = tangent_approx ( dae , self . dx , assert_linear = True ) y_rhs = tangent_approx ( alg , self . y , assert_linear = True ) return HybridOde ( c = self . c , dx = self . dx , f_c = self . f_c , f_i = self . f_i , f_m = self . f_m , f_x_rhs = x_rhs , y_rhs = y_rhs , m = self . m , ng = self . ng , nu = self . nu , p = self . p , pre_m = self . pre_m , pre_c = self . pre_c , prop = self . prop , sym = self . sym , t = self . t , x = self . x , y = self . y , )
Convert to a HybridOde
765
def format_from_extension ( fname ) : _base , ext = os . path . splitext ( fname ) if not ext : return None try : format = known_extensions [ ext . replace ( '.' , '' ) ] except KeyError : format = None return format
Tries to infer a protocol from the file extension .
766
def pickle_matpower_cases ( case_paths , case_format = 2 ) : import pylon . io if isinstance ( case_paths , basestring ) : case_paths = [ case_paths ] for case_path in case_paths : case = pylon . io . MATPOWERReader ( case_format ) . read ( case_path ) dir_path = os . path . dirname ( case_path ) case_basename = os . path . basename ( case_path ) root , _ = os . path . splitext ( case_basename ) pickled_case_path = os . path . join ( dir_path , root + '.pkl' ) pylon . io . PickleWriter ( case ) . write ( pickled_case_path )
Parses the MATPOWER case files at the given paths and pickles the resulting Case objects to the same directory .
767
def fair_max ( x ) : value = max ( x ) i = [ x . index ( v ) for v in x if v == value ] idx = random . choice ( i ) return idx , value
Takes a single iterable as an argument and returns the same output as the built - in function max with two output parameters except that where the maximum value occurs at more than one position in the vector the index is chosen randomly from these positions as opposed to just choosing the first occurance .
768
def factorial ( n ) : f = 1 while ( n > 0 ) : f = f * n n = n - 1 return f
Returns the factorial of n .
769
def _get_name ( self ) : if self . _name is None : self . _name = self . _generate_name ( ) return self . _name
Returns the name which is generated if it has not been already .
770
def save_to_file_object ( self , fd , format = None , ** kwargs ) : format = 'pickle' if format is None else format save = getattr ( self , "save_%s" % format , None ) if save is None : raise ValueError ( "Unknown format '%s'." % format ) save ( fd , ** kwargs )
Save the object to a given file like object in the given format .
771
def load_from_file_object ( cls , fd , format = None ) : format = 'pickle' if format is None else format load = getattr ( cls , "load_%s" % format , None ) if load is None : raise ValueError ( "Unknown format '%s'." % format ) return load ( fd )
Load the object from a given file like object in the given format .
772
def save ( self , filename , format = None , ** kwargs ) : if format is None : format = format_from_extension ( filename ) with file ( filename , 'wb' ) as fp : self . save_to_file_object ( fp , format , ** kwargs )
Save the object to file given by filename .
773
def load ( cls , filename , format = None ) : if format is None : format = format_from_extension ( filename ) with file ( filename , 'rbU' ) as fp : obj = cls . load_from_file_object ( fp , format ) obj . filename = filename return obj
Return an instance of the class that is saved in the file with the given filename in the specified format .
774
def solve ( self ) : case = self . case logger . info ( "Starting DC power flow [%s]." % case . name ) t0 = time . time ( ) self . case . index_buses ( ) ref_idx = self . _get_reference_index ( case ) if ref_idx < 0 : return False B , Bsrc , p_businj , p_srcinj = case . Bdc v_angle_guess = self . _get_v_angle_guess ( case ) v_angle , p_ref = self . _get_v_angle ( case , B , v_angle_guess , p_businj , ref_idx ) logger . debug ( "Bus voltage phase angles: \n%s" % v_angle ) self . v_angle = v_angle self . _update_model ( case , B , Bsrc , v_angle , p_srcinj , p_ref , ref_idx ) logger . info ( "DC power flow completed in %.3fs." % ( time . time ( ) - t0 ) ) return True
Solves a DC power flow .
775
def _get_reference_index ( self , case ) : refs = [ bus . _i for bus in case . connected_buses if bus . type == REFERENCE ] if len ( refs ) == 1 : return refs [ 0 ] else : logger . error ( "Single swing bus required for DCPF." ) return - 1
Returns the index of the reference bus .
776
def _get_v_angle_guess ( self , case ) : v_angle = array ( [ bus . v_angle * ( pi / 180.0 ) for bus in case . connected_buses ] ) return v_angle
Make the vector of voltage phase guesses .
777
def _get_v_angle ( self , case , B , v_angle_guess , p_businj , iref ) : buses = case . connected_buses pv_idxs = [ bus . _i for bus in buses if bus . type == PV ] pq_idxs = [ bus . _i for bus in buses if bus . type == PQ ] pvpq_idxs = pv_idxs + pq_idxs pvpq_rows = [ [ i ] for i in pvpq_idxs ] Bpvpq = B [ pvpq_rows , pvpq_idxs ] Bref = B [ pvpq_rows , [ iref ] ] p_surplus = array ( [ case . s_surplus ( v ) . real for v in buses ] ) g_shunt = array ( [ bus . g_shunt for bus in buses ] ) Pbus = ( p_surplus - p_businj - g_shunt ) / case . base_mva Pbus . shape = len ( Pbus ) , 1 A = Bpvpq b = Pbus [ pvpq_idxs ] - Bref * v_angle_guess [ iref ] x = spsolve ( A , b ) v_angle = r_ [ x [ : iref ] , v_angle_guess [ iref ] , x [ iref : ] ] return v_angle , Pbus [ iref ]
Calculates the voltage phase angles .
778
def _update_model ( self , case , B , Bsrc , v_angle , p_srcinj , p_ref , ref_idx ) : iref = ref_idx base_mva = case . base_mva buses = case . connected_buses branches = case . online_branches p_from = ( Bsrc * v_angle + p_srcinj ) * base_mva p_to = - p_from for i , branch in enumerate ( branches ) : branch . p_from = p_from [ i ] branch . p_to = p_to [ i ] branch . q_from = 0.0 branch . q_to = 0.0 for j , bus in enumerate ( buses ) : bus . v_angle = v_angle [ j ] * ( 180 / pi ) bus . v_magnitude = 1.0 g_ref = [ g for g in case . generators if g . bus == buses [ iref ] ] [ 0 ] p_inj = ( B [ iref , : ] * v_angle - p_ref ) * base_mva g_ref . p += p_inj [ 0 ]
Updates the case with values computed from the voltage phase angle solution .
779
def getSbus ( self , buses = None ) : bs = self . buses if buses is None else buses s = array ( [ self . s_surplus ( v ) / self . base_mva for v in bs ] ) return s
Returns the net complex bus power injection vector in p . u .
780
def sort_generators ( self ) : self . generators . sort ( key = lambda gn : gn . bus . _i )
Reorders the list of generators according to bus index .
781
def index_buses ( self , buses = None , start = 0 ) : bs = self . connected_buses if buses is None else buses for i , b in enumerate ( bs ) : b . _i = start + i
Updates the indices of all buses .
782
def index_branches ( self , branches = None , start = 0 ) : ln = self . online_branches if branches is None else branches for i , l in enumerate ( ln ) : l . _i = start + i
Updates the indices of all branches .
783
def s_supply ( self , bus ) : Sg = array ( [ complex ( g . p , g . q ) for g in self . generators if ( g . bus == bus ) and not g . is_load ] , dtype = complex64 ) if len ( Sg ) : return sum ( Sg ) else : return 0 + 0j
Returns the total complex power generation capacity .
784
def s_demand ( self , bus ) : Svl = array ( [ complex ( g . p , g . q ) for g in self . generators if ( g . bus == bus ) and g . is_load ] , dtype = complex64 ) Sd = complex ( bus . p_demand , bus . q_demand ) return - sum ( Svl ) + Sd
Returns the total complex power demand .
785
def reset ( self ) : for bus in self . buses : bus . reset ( ) for branch in self . branches : branch . reset ( ) for generator in self . generators : generator . reset ( )
Resets the readonly variables for all of the case components .
786
def save_matpower ( self , fd ) : from pylon . io import MATPOWERWriter MATPOWERWriter ( self ) . write ( fd )
Serialize the case as a MATPOWER data file .
787
def load_psat ( cls , fd ) : from pylon . io . psat import PSATReader return PSATReader ( ) . read ( fd )
Returns a case object from the given PSAT data file .
788
def save_rst ( self , fd ) : from pylon . io import ReSTWriter ReSTWriter ( self ) . write ( fd )
Save a reStructuredText representation of the case .
789
def save_csv ( self , fd ) : from pylon . io . excel import CSVWriter CSVWriter ( self ) . write ( fd )
Saves the case as a series of Comma - Separated Values .
790
def save_excel ( self , fd ) : from pylon . io . excel import ExcelWriter ExcelWriter ( self ) . write ( fd )
Saves the case as an Excel spreadsheet .
791
def save_dot ( self , fd ) : from pylon . io import DotWriter DotWriter ( self ) . write ( fd )
Saves a representation of the case in the Graphviz DOT language .
792
def solve ( self ) : self . case . reset ( ) b , l , g , _ , _ , _ , _ = self . _unpack_case ( self . case ) self . case . index_buses ( b ) refs , pq , pv , pvpq = self . _index_buses ( b ) if len ( refs ) != 1 : logger . error ( "Swing bus required for DCPF." ) return { "converged" : False } t0 = time ( ) V0 = self . _initial_voltage ( b , g ) repeat = True while repeat : Ybus , Yf , Yt = self . case . getYbus ( b , l ) Sbus = self . case . getSbus ( b ) V , converged , i = self . _run_power_flow ( Ybus , Sbus , V0 , pv , pq , pvpq ) self . case . pf_solution ( Ybus , Yf , Yt , V ) if self . qlimit : raise NotImplementedError else : repeat = False elapsed = time ( ) - t0 if converged and self . verbose : logger . info ( "AC power flow converged in %.3fs" % elapsed ) return { "converged" : converged , "elapsed" : elapsed , "iterations" : i , "V" : V }
Runs a power flow
793
def _unpack_case ( self , case ) : base_mva = case . base_mva b = case . connected_buses l = case . online_branches g = case . online_generators nb = len ( b ) nl = len ( l ) ng = len ( g ) return b , l , g , nb , nl , ng , base_mva
Returns the contents of the case to be used in the OPF .
794
def _index_buses ( self , buses ) : refs = [ bus . _i for bus in buses if bus . type == REFERENCE ] pv = [ bus . _i for bus in buses if bus . type == PV ] pq = [ bus . _i for bus in buses if bus . type == PQ ] pvpq = pv + pq return refs , pq , pv , pvpq
Set up indexing for updating v .
795
def _initial_voltage ( self , buses , generators ) : Vm = array ( [ bus . v_magnitude for bus in buses ] ) Va = array ( [ bus . v_angle * ( pi / 180.0 ) for bus in buses ] ) V = Vm * exp ( 1j * Va ) for g in generators : i = g . bus . _i V [ i ] = g . v_magnitude / abs ( V [ i ] ) * V [ i ] return V
Returns the initial vector of complex bus voltages .
796
def _one_iteration ( self , F , Ybus , V , Vm , Va , pv , pq , pvpq ) : J = self . _build_jacobian ( Ybus , V , pv , pq , pvpq ) dx = - 1 * spsolve ( J , F ) npv = len ( pv ) npq = len ( pq ) if npv > 0 : Va [ pv ] = Va [ pv ] + dx [ range ( npv ) ] if npq > 0 : Va [ pq ] = Va [ pq ] + dx [ range ( npv , npv + npq ) ] Vm [ pq ] = Vm [ pq ] + dx [ range ( npv + npq , npv + npq + npq ) ] V = Vm * exp ( 1j * Va ) Vm = abs ( V ) Va = angle ( V ) return V , Vm , Va
Performs one Newton iteration .
797
def _build_jacobian ( self , Ybus , V , pv , pq , pvpq ) : pq_col = [ [ i ] for i in pq ] pvpq_col = [ [ i ] for i in pvpq ] dS_dVm , dS_dVa = self . case . dSbus_dV ( Ybus , V ) J11 = dS_dVa [ pvpq_col , pvpq ] . real J12 = dS_dVm [ pvpq_col , pq ] . real J21 = dS_dVa [ pq_col , pvpq ] . imag J22 = dS_dVm [ pq_col , pq ] . imag J = vstack ( [ hstack ( [ J11 , J12 ] ) , hstack ( [ J21 , J22 ] ) ] , format = "csr" ) return J
Returns the Jacobian matrix .
798
def _evaluate_mismatch ( self , Ybus , V , Sbus , pq , pvpq ) : mis = ( multiply ( V , conj ( Ybus * V ) ) - Sbus ) / abs ( V ) P = mis [ pvpq ] . real Q = mis [ pq ] . imag return P , Q
Evaluates the mismatch .
799
def _p_iteration ( self , P , Bp_solver , Vm , Va , pvpq ) : dVa = - Bp_solver . solve ( P ) Va [ pvpq ] = Va [ pvpq ] + dVa V = Vm * exp ( 1j * Va ) return V , Vm , Va
Performs a P iteration updates Va .