query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
sequencelengths
20
553
Returns bounds on the optimisation variables .
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
700
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L152-L164
[ "def", "url_to_resource", "(", "url", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "request", "=", "get_current_request", "(", ")", "# cnv = request.registry.getAdapter(request, IResourceUrlConverter)", "reg", "=", "get_current_registry", "(", ")", "cnv", "=", "reg", ".", "getAdapter", "(", "request", ",", "IResourceUrlConverter", ")", "return", "cnv", ".", "url_to_resource", "(", "url", ")" ]
Selects an interior initial point for interior point solver .
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 ] # Angles set to first reference angle. if ny > 0 : yvar = self . om . get_var ( "y" ) # Largest y-value in CCV data 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
701
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L167-L190
[ "def", "find", "(", "self", ",", "path", ")", ":", "if", "isinstance", "(", "path", ",", "Device", ")", ":", "return", "path", "for", "device", "in", "self", ":", "if", "device", ".", "is_file", "(", "path", ")", ":", "self", ".", "_log", ".", "debug", "(", "_", "(", "'found device owning \"{0}\": \"{1}\"'", ",", "path", ",", "device", ")", ")", "return", "device", "raise", "FileNotFoundError", "(", "_", "(", "'no device found owning \"{0}\"'", ",", "path", ")", ")" ]
Solves DC optimal power flow and returns a results dict .
def solve ( self ) : base_mva = self . om . case . base_mva Bf = self . om . _Bf Pfinj = self . om . _Pfinj # Unpack the OPF model. bs , ln , gn , cp = self . _unpack_model ( self . om ) # Compute problem dimensions. ipol , ipwl , nb , nl , nw , ny , nxyz = self . _dimension_data ( bs , ln , gn ) # Split the constraints in equality and inequality. AA , ll , uu = self . _linear_constraints ( self . om ) # Piece-wise linear components of the objective function. Npwl , Hpwl , Cpwl , fparm_pwl , any_pwl = self . _pwl_costs ( ny , nxyz , ipwl ) # Quadratic components of the objective function. Npol , Hpol , Cpol , fparm_pol , polycf , npol = self . _quadratic_costs ( gn , ipol , nxyz , base_mva ) # Combine pwl, poly and user costs. NN , HHw , CCw , ffparm = self . _combine_costs ( Npwl , Hpwl , Cpwl , fparm_pwl , any_pwl , Npol , Hpol , Cpol , fparm_pol , npol , nw ) # Transform quadratic coefficients for w into coefficients for X. HH , CC , C0 = self . _transform_coefficients ( NN , HHw , CCw , ffparm , polycf , any_pwl , npol , nw ) # Bounds on the optimisation variables. _ , xmin , xmax = self . _var_bounds ( ) # Select an interior initial point for interior point solver. x0 = self . _initial_interior_point ( bs , gn , xmin , xmax , ny ) # Call the quadratic/linear solver. s = self . _run_opf ( HH , CC , AA , ll , uu , xmin , xmax , x0 , self . opt ) # Compute the objective function value. Va , Pg = self . _update_solution_data ( s , HH , CC , C0 ) # Set case result attributes. self . _update_case ( bs , ln , gn , base_mva , Bf , Pfinj , Va , Pg , s [ "lmbda" ] ) return s
702
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L218-L257
[ "def", "concatenate_not_none", "(", "l", ",", "axis", "=", "0", ")", ":", "# Get the indexes of the arrays in the list", "mask", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "l", ")", ")", ":", "if", "l", "[", "i", "]", "is", "not", "None", ":", "mask", ".", "append", "(", "i", ")", "# Concatenate them", "l_stacked", "=", "np", ".", "concatenate", "(", "[", "l", "[", "i", "]", "for", "i", "in", "mask", "]", ",", "axis", "=", "axis", ")", "return", "l_stacked" ]
Returns the piece - wise linear components of the objective function .
def _pwl_costs ( self , ny , nxyz , ipwl ) : any_pwl = int ( ny > 0 ) if any_pwl : y = self . om . get_var ( "y" ) # Sum of y vars. 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 #zeros((0, nxyz)) Hpwl = None #array([]) Cpwl = array ( [ ] ) fparm_pwl = zeros ( ( 0 , 4 ) ) return Npwl , Hpwl , Cpwl , fparm_pwl , any_pwl
703
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L260-L277
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "XFSCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'xfs'", "}", ")", "return", "config" ]
Returns the quadratic cost components of the objective function .
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 ] ) #[iqdr, :].T if len ( ilin ) > 0 : polycf [ ilin , 1 : ] = array ( [ list ( g . p_cost [ : 2 ] ) for g in generators ] ) #[ilin, :].T # Convert to per-unit. 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
704
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L280-L316
[ "def", "decode_pet", "(", "self", ",", "specifictrap", ",", "petdata", ")", ":", "self", ".", "oem_init", "(", ")", "return", "sel", ".", "EventHandler", "(", "self", ".", "init_sdr", "(", ")", ",", "self", ")", ".", "decode_pet", "(", "specifictrap", ",", "petdata", ")" ]
Combines pwl polynomial and user - defined costs .
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 ] ) # if H is not None: # H = hstack([csr_matrix((nw, any_pwl+npol)), H]) 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
705
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L319-L337
[ "def", "restore_droplet", "(", "self", ",", "droplet_id", ",", "image_id", ")", ":", "if", "not", "droplet_id", ":", "raise", "DOPException", "(", "'droplet_id is required to restore a droplet!'", ")", "if", "not", "image_id", ":", "raise", "DOPException", "(", "'image_id is required to rebuild a droplet!'", ")", "params", "=", "{", "'image_id'", ":", "image_id", "}", "json", "=", "self", ".", "request", "(", "'/droplets/%s/restore'", "%", "droplet_id", ",", "method", "=", "'GET'", ",", "params", "=", "params", ")", "status", "=", "json", ".", "get", "(", "'status'", ")", "if", "status", "==", "'OK'", ":", "return", "json", ".", "get", "(", "'event_id'", ")", "else", ":", "message", "=", "json", ".", "get", "(", "'message'", ")", "raise", "DOPException", "(", "'[%s]: %s'", "%", "(", "status", ",", "message", ")", ")" ]
Transforms quadratic coefficients for w into coefficients for x .
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 ] # FIXME: Possibly column 1. HMR = HHw * MR MN = M * NN HH = MN . T * HHw * MN CC = MN . T * ( CCw - HMR ) # Constant term of cost. C0 = 1. / 2. * MR . T * HMR + sum ( polycf [ : , 2 ] ) return HH , CC , C0 [ 0 ]
706
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L340-L354
[ "def", "poll", "(", ")", ":", "event_ptr", "=", "ffi", ".", "new", "(", "'SDL_Event *'", ")", "while", "lib", ".", "SDL_PollEvent", "(", "event_ptr", ")", ":", "yield", "Event", ".", "_from_ptr", "(", "event_ptr", ")", "event_ptr", "=", "ffi", ".", "new", "(", "'SDL_Event *'", ")" ]
Adds a constraint on the reference bus angles .
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
707
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L444-L453
[ "def", "download_storyitem", "(", "self", ",", "item", ":", "StoryItem", ",", "target", ":", "str", ")", "->", "bool", ":", "date_local", "=", "item", ".", "date_local", "dirname", "=", "_PostPathFormatter", "(", "item", ")", ".", "format", "(", "self", ".", "dirname_pattern", ",", "target", "=", "target", ")", "filename", "=", "dirname", "+", "'/'", "+", "self", ".", "format_filename", "(", "item", ",", "target", "=", "target", ")", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ",", "exist_ok", "=", "True", ")", "downloaded", "=", "False", "if", "not", "item", ".", "is_video", "or", "self", ".", "download_video_thumbnails", "is", "True", ":", "url", "=", "item", ".", "url", "downloaded", "=", "self", ".", "download_pic", "(", "filename", "=", "filename", ",", "url", "=", "url", ",", "mtime", "=", "date_local", ")", "if", "item", ".", "is_video", "and", "self", ".", "download_videos", "is", "True", ":", "downloaded", "|=", "self", ".", "download_pic", "(", "filename", "=", "filename", ",", "url", "=", "item", ".", "video_url", ",", "mtime", "=", "date_local", ")", "# Save caption if desired", "metadata_string", "=", "_ArbitraryItemFormatter", "(", "item", ")", ".", "format", "(", "self", ".", "storyitem_metadata_txt_pattern", ")", ".", "strip", "(", ")", "if", "metadata_string", ":", "self", ".", "save_caption", "(", "filename", "=", "filename", ",", "mtime", "=", "item", ".", "date_local", ",", "caption", "=", "metadata_string", ")", "# Save metadata as JSON if desired.", "if", "self", ".", "save_metadata", "is", "not", "False", ":", "self", ".", "save_metadata_json", "(", "filename", ",", "item", ")", "self", ".", "context", ".", "log", "(", ")", "return", "downloaded" ]
Evaluates the objective function .
def _f ( self , x , user_data = None ) : p_gen = x [ self . _Pg . i1 : self . _Pg . iN + 1 ] # Active generation in p.u. q_gen = x [ self . _Qg . i1 : self . _Qg . iN + 1 ] # Reactive generation in p.u. # Polynomial cost of P and Q. 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 # Piecewise linear cost of P and Q. 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 ) ) # TODO: Generalised cost term. return f
708
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L515-L539
[ "def", "convert_timestamps", "(", "files", ")", ":", "sentences", "=", "[", "]", "for", "f", "in", "files", ":", "if", "not", "f", ".", "endswith", "(", "'.transcription.txt'", ")", ":", "f", "=", "f", "+", "'.transcription.txt'", "if", "os", ".", "path", ".", "exists", "(", "f", ")", "is", "False", ":", "continue", "with", "open", "(", "f", ",", "'r'", ")", "as", "infile", ":", "lines", "=", "infile", ".", "readlines", "(", ")", "lines", "=", "[", "re", ".", "sub", "(", "r'\\(.*?\\)'", ",", "''", ",", "l", ")", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", "for", "l", "in", "lines", "]", "lines", "=", "[", "l", "for", "l", "in", "lines", "if", "len", "(", "l", ")", "==", "4", "]", "seg_start", "=", "-", "1", "seg_end", "=", "-", "1", "for", "index", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "word", ",", "start", ",", "end", ",", "conf", "=", "line", "if", "word", "==", "'<s>'", "or", "word", "==", "'<sil>'", "or", "word", "==", "'</s>'", ":", "if", "seg_start", "==", "-", "1", ":", "seg_start", "=", "index", "seg_end", "=", "-", "1", "else", ":", "seg_end", "=", "index", "if", "seg_start", ">", "-", "1", "and", "seg_end", ">", "-", "1", ":", "words", "=", "lines", "[", "seg_start", "+", "1", ":", "seg_end", "]", "start", "=", "float", "(", "lines", "[", "seg_start", "]", "[", "1", "]", ")", "end", "=", "float", "(", "lines", "[", "seg_end", "]", "[", "1", "]", ")", "if", "words", ":", "sentences", ".", "append", "(", "{", "'start'", ":", "start", ",", "'end'", ":", "end", ",", "'words'", ":", "words", ",", "'file'", ":", "f", "}", ")", "if", "word", "==", "'</s>'", ":", "seg_start", "=", "-", "1", "else", ":", "seg_start", "=", "seg_end", "seg_end", "=", "-", "1", "return", "sentences" ]
Evaluates the cost gradient .
def _df ( self , x , user_data = None ) : p_gen = x [ self . _Pg . i1 : self . _Pg . iN + 1 ] # Active generation in p.u. q_gen = x [ self . _Qg . i1 : self . _Qg . iN + 1 ] # Reactive generation in p.u. # Polynomial cost of P and Q. 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 ) # Polynomial cost of P and Q. df_dPgQg = zeros ( ( 2 * self . _ng , 1 ) ) # w.r.t p.u. Pg and Qg # df_dPgQg[ipol] = matrix([g.poly_cost(xx[i], 1) for g in gpol]) # for i, g in enumerate(gn): # der = polyder(list(g.p_cost)) # df_dPgQg[i] = polyval(der, xx[i]) * base_mva 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 ] # Piecewise linear cost of P and Q. df = df + self . _ccost . T # TODO: Generalised cost term. return asarray ( df ) . flatten ( )
709
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L542-L573
[ "def", "drop", "(", "self", ",", "labels", ",", "errors", "=", "'raise'", ")", ":", "arr_dtype", "=", "'object'", "if", "self", ".", "dtype", "==", "'object'", "else", "None", "labels", "=", "com", ".", "index_labels_to_array", "(", "labels", ",", "dtype", "=", "arr_dtype", ")", "indexer", "=", "self", ".", "get_indexer", "(", "labels", ")", "mask", "=", "indexer", "==", "-", "1", "if", "mask", ".", "any", "(", ")", ":", "if", "errors", "!=", "'ignore'", ":", "raise", "KeyError", "(", "'{} not found in axis'", ".", "format", "(", "labels", "[", "mask", "]", ")", ")", "indexer", "=", "indexer", "[", "~", "mask", "]", "return", "self", ".", "delete", "(", "indexer", ")" ]
Evaluates the cost Hessian .
def _d2f ( self , x ) : d2f_dPg2 = lil_matrix ( ( self . _ng , 1 ) ) # w.r.t p.u. Pg d2f_dQg2 = lil_matrix ( ( self . _ng , 1 ) ) # w.r.t p.u. Qg] 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 # for i in ipol: # d2f_dQg2[i] = polyval(polyder(list(gn[i].p_cost), 2), # Qg.v0[i] * base_mva) * 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
710
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L576-L595
[ "def", "sample", "(", "self", ",", "event", "=", "None", ",", "record_keepalive", "=", "False", ")", ":", "url", "=", "'https://stream.twitter.com/1.1/statuses/sample.json'", "params", "=", "{", "\"stall_warning\"", ":", "True", "}", "headers", "=", "{", "'accept-encoding'", ":", "'deflate, gzip'", "}", "errors", "=", "0", "while", "True", ":", "try", ":", "log", ".", "info", "(", "\"connecting to sample stream\"", ")", "resp", "=", "self", ".", "post", "(", "url", ",", "params", ",", "headers", "=", "headers", ",", "stream", "=", "True", ")", "errors", "=", "0", "for", "line", "in", "resp", ".", "iter_lines", "(", "chunk_size", "=", "512", ")", ":", "if", "event", "and", "event", ".", "is_set", "(", ")", ":", "log", ".", "info", "(", "\"stopping sample\"", ")", "# Explicitly close response", "resp", ".", "close", "(", ")", "return", "if", "line", "==", "\"\"", ":", "log", ".", "info", "(", "\"keep-alive\"", ")", "if", "record_keepalive", ":", "yield", "\"keep-alive\"", "continue", "try", ":", "yield", "json", ".", "loads", "(", "line", ".", "decode", "(", ")", ")", "except", "Exception", "as", "e", ":", "log", ".", "error", "(", "\"json parse error: %s - %s\"", ",", "e", ",", "line", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "e", ":", "errors", "+=", "1", "log", ".", "error", "(", "\"caught http error %s on %s try\"", ",", "e", ",", "errors", ")", "if", "self", ".", "http_errors", "and", "errors", "==", "self", ".", "http_errors", ":", "log", ".", "warning", "(", "\"too many errors\"", ")", "raise", "e", "if", "e", ".", "response", ".", "status_code", "==", "420", ":", "if", "interruptible_sleep", "(", "errors", "*", "60", ",", "event", ")", ":", "log", ".", "info", "(", "\"stopping filter\"", ")", "return", "else", ":", "if", "interruptible_sleep", "(", "errors", "*", "5", ",", "event", ")", ":", "log", ".", "info", "(", "\"stopping filter\"", ")", "return", "except", "Exception", "as", "e", ":", "errors", "+=", "1", "log", ".", "error", "(", "\"caught exception %s on %s try\"", ",", "e", ",", "errors", ")", "if", "self", ".", "http_errors", "and", "errors", "==", "self", ".", "http_errors", ":", "log", ".", "warning", "(", "\"too many errors\"", ")", "raise", "e", "if", "interruptible_sleep", "(", "errors", ",", "event", ")", ":", "log", ".", "info", "(", "\"stopping filter\"", ")", "return" ]
Evaluates the constraint function values .
def _gh ( self , x ) : Pgen = x [ self . _Pg . i1 : self . _Pg . iN + 1 ] # Active generation in p.u. Qgen = x [ self . _Qg . i1 : self . _Qg . iN + 1 ] # Reactive generation in p.u. for i , gen in enumerate ( self . _gn ) : gen . p = Pgen [ i ] * self . _base_mva # active generation in MW gen . q = Qgen [ i ] * self . _base_mva # reactive generation in MVAr # Rebuild the net complex bus power injection vector in p.u. 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 ) # Evaluate the power flow equations. mis = V * conj ( self . _Ybus * V ) - Sbus # Equality constraints (power flow). g = r_ [ mis . real , # active power mismatch for all buses mis . imag ] # reactive power mismatch for all buses # Inequality constraints (branch flow limits). # (line constraint is actually on square of limit) flow_max = array ( [ ( l . rate_a / self . _base_mva ) ** 2 for l in self . _ln ] ) # FIXME: There must be a more elegant method for this. 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 # Branch current limits. 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 ] # Complex power injected at "from" bus (p.u.). Sf = V [ i_fbus ] * conj ( self . _Yf * V ) # Complex power injected at "to" bus (p.u.). St = V [ i_tbus ] * conj ( self . _Yt * V ) if self . flow_lim == PFLOW : # active power limit, P (Pan Wei) # Branch real power limits. h = r_ [ Sf . real ( ) ** 2 - flow_max , St . real ( ) ** 2 - flow_max ] elif self . flow_lim == SFLOW : # apparent power limit, |S| # Branch apparent power limits. h = r_ [ ( Sf * conj ( Sf ) ) - flow_max , ( St * conj ( St ) ) - flow_max ] . real else : raise ValueError return h , g
711
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L598-L654
[ "def", "parse_message", "(", "message", ",", "nodata", "=", "False", ")", ":", "header", "=", "read_machine_header", "(", "message", ")", "h_len", "=", "__get_machine_header_length", "(", "header", ")", "meta_raw", "=", "message", "[", "h_len", ":", "h_len", "+", "header", "[", "'meta_len'", "]", "]", "meta", "=", "__parse_meta", "(", "meta_raw", ",", "header", ")", "data_start", "=", "h_len", "+", "header", "[", "'meta_len'", "]", "data", "=", "b''", "if", "not", "nodata", ":", "data", "=", "__decompress", "(", "meta", ",", "message", "[", "data_start", ":", "data_start", "+", "header", "[", "'data_len'", "]", "]", ")", "return", "header", ",", "meta", ",", "data" ]
Evaluates the objective function gradient and Hessian for OPF .
def _costfcn ( self , x ) : f = self . _f ( x ) df = self . _df ( x ) d2f = self . _d2f ( x ) return f , df , d2f
712
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L716-L723
[ "def", "_clean_message", "(", "message", ")", ":", "message", "=", "message", ".", "replace", "(", "'zonecfg: '", ",", "''", ")", "message", "=", "message", ".", "splitlines", "(", ")", "for", "line", "in", "message", ":", "if", "line", ".", "startswith", "(", "'On line'", ")", ":", "message", ".", "remove", "(", "line", ")", "return", "\"\\n\"", ".", "join", "(", "message", ")" ]
Evaluates nonlinear constraints and their Jacobian for OPF .
def _consfcn ( self , x ) : h , g = self . _gh ( x ) dh , dg = self . _dgh ( x ) return h , g , dh , dg
713
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L726-L732
[ "def", "write_result_stream", "(", "result_stream", ",", "filename_prefix", "=", "None", ",", "results_per_file", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "result_stream", ",", "types", ".", "GeneratorType", ")", ":", "stream", "=", "result_stream", "else", ":", "stream", "=", "result_stream", ".", "stream", "(", ")", "file_time_formatter", "=", "\"%Y-%m-%dT%H_%M_%S\"", "if", "filename_prefix", "is", "None", ":", "filename_prefix", "=", "\"twitter_search_results\"", "if", "results_per_file", ":", "logger", ".", "info", "(", "\"chunking result stream to files with {} tweets per file\"", ".", "format", "(", "results_per_file", ")", ")", "chunked_stream", "=", "partition", "(", "stream", ",", "results_per_file", ",", "pad_none", "=", "True", ")", "for", "chunk", "in", "chunked_stream", ":", "chunk", "=", "filter", "(", "lambda", "x", ":", "x", "is", "not", "None", ",", "chunk", ")", "curr_datetime", "=", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "file_time_formatter", ")", ")", "_filename", "=", "\"{}_{}.json\"", ".", "format", "(", "filename_prefix", ",", "curr_datetime", ")", "yield", "from", "write_ndjson", "(", "_filename", ",", "chunk", ")", "else", ":", "curr_datetime", "=", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "file_time_formatter", ")", ")", "_filename", "=", "\"{}.json\"", ".", "format", "(", "filename_prefix", ")", "yield", "from", "write_ndjson", "(", "_filename", ",", "stream", ")" ]
Loads a pickled case .
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
714
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/pickle.py#L45-L66
[ "def", "download_next_song", "(", "self", ",", "song", ")", ":", "dl_ydl_opts", "=", "dict", "(", "ydl_opts", ")", "dl_ydl_opts", "[", "\"progress_hooks\"", "]", "=", "[", "self", ".", "ytdl_progress_hook", "]", "dl_ydl_opts", "[", "\"outtmpl\"", "]", "=", "self", ".", "output_format", "# Move the songs from the next cache to the current cache", "self", ".", "move_next_cache", "(", ")", "self", ".", "state", "=", "'ready'", "self", ".", "play_empty", "(", ")", "# Download the file and create the stream", "with", "youtube_dl", ".", "YoutubeDL", "(", "dl_ydl_opts", ")", "as", "ydl", ":", "try", ":", "ydl", ".", "download", "(", "[", "song", "]", ")", "except", "DownloadStreamException", ":", "# This is a livestream, use the appropriate player", "future", "=", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "create_stream_player", "(", "song", ",", "dl_ydl_opts", ")", ",", "client", ".", "loop", ")", "try", ":", "future", ".", "result", "(", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "e", ")", "self", ".", "vafter_ts", "(", ")", "return", "except", "PermissionError", ":", "# File is still in use, it'll get cleared next time", "pass", "except", "youtube_dl", ".", "utils", ".", "DownloadError", "as", "e", ":", "self", ".", "logger", ".", "exception", "(", "e", ")", "self", ".", "statuslog", ".", "error", "(", "e", ")", "self", ".", "vafter_ts", "(", ")", "return", "except", "Exception", "as", "e", ":", "self", ".", "logger", ".", "exception", "(", "e", ")", "self", ".", "vafter_ts", "(", ")", "return" ]
Writes the case to file using pickle .
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
715
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/pickle.py#L76-L97
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]
count comments and non - empty lines that contain code
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' ) ) : # start new line self . contains_code = False self . sloc += 1 # for c style includes elif ( tok [ 0 ] . __str__ ( ) == 'Token.Comment.Preproc' and tok [ 1 ] . count ( u'\n' ) ) : # start new line self . contains_code = False self . sloc += 1 elif ( tok [ 0 ] [ 0 ] in token_types ) : self . contains_code = True
716
https://github.com/finklabs/metrics/blob/fd9974af498831664b9ae8e8f3834e1ec2e8a699/metrics/sloc.py#L34-L53
[ "def", "catalogFactory", "(", "name", ",", "*", "*", "kwargs", ")", ":", "fn", "=", "lambda", "member", ":", "inspect", ".", "isclass", "(", "member", ")", "and", "member", ".", "__module__", "==", "__name__", "catalogs", "=", "odict", "(", "inspect", ".", "getmembers", "(", "sys", ".", "modules", "[", "__name__", "]", ",", "fn", ")", ")", "if", "name", "not", "in", "list", "(", "catalogs", ".", "keys", "(", ")", ")", ":", "msg", "=", "\"%s not found in catalogs:\\n %s\"", "%", "(", "name", ",", "list", "(", "kernels", ".", "keys", "(", ")", ")", ")", "logger", ".", "error", "(", "msg", ")", "msg", "=", "\"Unrecognized catalog: %s\"", "%", "name", "raise", "Exception", "(", "msg", ")", "return", "catalogs", "[", "name", "]", "(", "*", "*", "kwargs", ")" ]
Calculate ratio_comment_to_code and return with the other values
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
717
https://github.com/finklabs/metrics/blob/fd9974af498831664b9ae8e8f3834e1ec2e8a699/metrics/sloc.py#L68-L79
[ "def", "_check_missing_manifests", "(", "self", ",", "segids", ")", ":", "manifest_paths", "=", "[", "self", ".", "_manifest_path", "(", "segid", ")", "for", "segid", "in", "segids", "]", "with", "Storage", "(", "self", ".", "vol", ".", "layer_cloudpath", ",", "progress", "=", "self", ".", "vol", ".", "progress", ")", "as", "stor", ":", "exists", "=", "stor", ".", "files_exist", "(", "manifest_paths", ")", "dne", "=", "[", "]", "for", "path", ",", "there", "in", "exists", ".", "items", "(", ")", ":", "if", "not", "there", ":", "(", "segid", ",", ")", "=", "re", ".", "search", "(", "r'(\\d+):0$'", ",", "path", ")", ".", "groups", "(", ")", "dne", ".", "append", "(", "segid", ")", "return", "dne" ]
Perform an action on the world that changes it s internal state .
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 ) ) # Set the output of each (non-reference) generator. for i , g in enumerate ( gs ) : g . p = action [ i ] # Compute power flows and slack generator set-point. NewtonPF ( self . case , verbose = False ) . solve ( ) #FastDecoupledPF(self.case, verbose=False).solve() # Store all generator set-points (only used for plotting). self . _Pg [ : , self . _step ] = [ g . p for g in self . case . online_generators ] # Apply the next load profile value to the original demand at each bus. 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 )
718
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/rlopf.py#L109-L137
[ "def", "Process", "(", "self", ",", "parser_mediator", ",", "registry_key", ",", "*", "*", "kwargs", ")", ":", "if", "registry_key", "is", "None", ":", "raise", "ValueError", "(", "'Windows Registry key is not set.'", ")", "# This will raise if unhandled keyword arguments are passed.", "super", "(", "WindowsRegistryPlugin", ",", "self", ")", ".", "Process", "(", "parser_mediator", ",", "*", "*", "kwargs", ")", "self", ".", "ExtractEvents", "(", "parser_mediator", ",", "registry_key", ",", "*", "*", "kwargs", ")" ]
Re - initialises the environment .
def reset ( self ) : logger . info ( "Reseting environment." ) self . _step = 0 # Reset the set-point of each generator to its original value. 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 ] # Apply load profile to the original demand at each bus. 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 ] # Initialise the record of generator set-points. self . _Pg = zeros ( ( len ( self . case . online_generators ) , len ( self . profile ) ) ) # Apply the first load profile value. # self.step() self . case . reset ( )
719
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/rlopf.py#L140-L162
[ "def", "getVATAmount", "(", "self", ")", ":", "price", ",", "vat", "=", "self", ".", "getPrice", "(", ")", ",", "self", ".", "getVAT", "(", ")", "return", "float", "(", "price", ")", "*", "(", "float", "(", "vat", ")", "/", "100", ")" ]
Is the current episode over?
def isFinished ( self ) : finished = ( self . env . _step == len ( self . env . profile ) ) if finished : logger . info ( "Finished episode." ) return finished
720
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/rlopf.py#L216-L222
[ "def", "_init_itemid2name", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ".", "args", ",", "'id2sym'", ")", ":", "return", "None", "fin_id2sym", "=", "self", ".", "args", ".", "id2sym", "if", "fin_id2sym", "is", "not", "None", "and", "os", ".", "path", ".", "exists", "(", "fin_id2sym", ")", ":", "id2sym", "=", "{", "}", "cmpl", "=", "re", ".", "compile", "(", "r'^\\s*(\\S+)[\\s,;]+(\\S+)'", ")", "with", "open", "(", "fin_id2sym", ")", "as", "ifstrm", ":", "for", "line", "in", "ifstrm", ":", "mtch", "=", "cmpl", ".", "search", "(", "line", ")", "if", "mtch", ":", "id2sym", "[", "mtch", ".", "group", "(", "1", ")", "]", "=", "mtch", ".", "group", "(", "2", ")", "return", "id2sym" ]
Does one interaction between the task and the agent .
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 ( ) ) # Save the cumulative sum of set-points for each period. 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
721
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/rlopf.py#L272-L288
[ "def", "calc_regenerated", "(", "self", ",", "lastvotetime", ")", ":", "delta", "=", "datetime", ".", "utcnow", "(", ")", "-", "datetime", ".", "strptime", "(", "lastvotetime", ",", "'%Y-%m-%dT%H:%M:%S'", ")", "td", "=", "delta", ".", "days", "ts", "=", "delta", ".", "seconds", "tt", "=", "(", "td", "*", "86400", ")", "+", "ts", "return", "tt", "*", "10000", "/", "86400", "/", "5" ]
Does the the given number of episodes .
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 ) # Average the set-points for each period. self . Pg = self . Pg / number return rewards
722
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/rlopf.py#L291-L302
[ "def", "compare_root_path", "(", "path_cost1", ",", "path_cost2", ",", "bridge_id1", ",", "bridge_id2", ",", "port_id1", ",", "port_id2", ")", ":", "result", "=", "Stp", ".", "_cmp_value", "(", "path_cost1", ",", "path_cost2", ")", "if", "not", "result", ":", "result", "=", "Stp", ".", "_cmp_value", "(", "bridge_id1", ",", "bridge_id2", ")", "if", "not", "result", ":", "result", "=", "Stp", ".", "_cmp_value", "(", "port_id1", ",", "port_id2", ")", "return", "result" ]
searches for an object with the name given inside the object given . obj . child . meth will return the meth obj .
def getMethodByName ( obj , name ) : try : #to get a method by asking the service obj = obj . _getMethodByName ( name ) except : #assumed a childObject is ment #split the name from objName.childObjName... -> [objName, childObjName, ...] #and get all objects up to the last in list with name checking from the service object names = name . split ( "." ) for name in names : if nameAllowed ( name ) : obj = getattr ( obj , name ) else : raise MethodNameNotAllowed ( ) return obj
723
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/contrib/public/services/jsonrpc/__init__.py#L168-L186
[ "def", "update_feature_type_rates", "(", "sender", ",", "instance", ",", "created", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "created", ":", "for", "role", "in", "ContributorRole", ".", "objects", ".", "all", "(", ")", ":", "FeatureTypeRate", ".", "objects", ".", "create", "(", "role", "=", "role", ",", "feature_type", "=", "instance", ",", "rate", "=", "0", ")" ]
blocks until the response arrived or timeout is reached .
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" ]
724
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/contrib/public/services/jsonrpc/__init__.py#L51-L60
[ "def", "_load", "(", "self", ")", ":", "indexfilename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__dir", ",", "\"index.dat\"", ")", "if", "os", ".", "path", ".", "exists", "(", "indexfilename", ")", ":", "data", "=", "self", ".", "_read_file", "(", "indexfilename", ")", "self", ".", "__index", "=", "data", "[", "0", "]", "self", ".", "__filename_rep", "=", "data", "[", "1", "]", "if", "self", ".", "__filename_rep", ".", "_sha1_sigs", "!=", "self", ".", "__sha1_sigs", ":", "print", "(", "(", "\"CACHE: Warning: sha1_sigs stored in the cache is set \"", "+", "\"to %s.\"", ")", "%", "self", ".", "__filename_rep", ".", "_sha1_sigs", ")", "print", "(", "\"Please remove the cache to change this setting.\"", ")", "self", ".", "__sha1_sigs", "=", "self", ".", "__filename_rep", ".", "_sha1_sigs", "else", ":", "self", ".", "__index", "=", "{", "}", "self", ".", "__filename_rep", "=", "filename_repository_t", "(", "self", ".", "__sha1_sigs", ")", "self", ".", "__modified_flag", "=", "False" ]
sends a request to the peer
def sendRequest ( self , name , args ) : ( respEvt , id ) = self . newResponseEvent ( ) self . sendMessage ( { "id" : id , "method" : name , "params" : args } ) return respEvt
725
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/contrib/public/services/jsonrpc/__init__.py#L108-L112
[ "def", "enum", "(", "option", ",", "*", "options", ")", ":", "options", "=", "(", "option", ",", ")", "+", "options", "rangeob", "=", "range", "(", "len", "(", "options", ")", ")", "try", ":", "inttype", "=", "_inttypes", "[", "int", "(", "np", ".", "log2", "(", "len", "(", "options", ")", "-", "1", ")", ")", "//", "8", "]", "except", "IndexError", ":", "raise", "OverflowError", "(", "'Cannot store enums with more than sys.maxsize elements, got %d'", "%", "len", "(", "options", ")", ",", ")", "class", "_enum", "(", "Structure", ")", ":", "_fields_", "=", "[", "(", "o", ",", "inttype", ")", "for", "o", "in", "options", "]", "def", "__iter__", "(", "self", ")", ":", "return", "iter", "(", "rangeob", ")", "def", "__contains__", "(", "self", ",", "value", ")", ":", "return", "0", "<=", "value", "<", "len", "(", "options", ")", "def", "__repr__", "(", "self", ")", ":", "return", "'<enum: %s>'", "%", "(", "(", "'%d fields'", "%", "len", "(", "options", ")", ")", "if", "len", "(", "options", ")", ">", "10", "else", "repr", "(", "options", ")", ")", "return", "_enum", "(", "*", "rangeob", ")" ]
sends a response to the peer
def sendResponse ( self , id , result , error ) : self . sendMessage ( { "result" : result , "error" : error , "id" : id } )
726
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/contrib/public/services/jsonrpc/__init__.py#L114-L116
[ "def", "beacon", "(", "config", ")", ":", "parts", "=", "psutil", ".", "disk_partitions", "(", "all", "=", "True", ")", "ret", "=", "[", "]", "for", "mounts", "in", "config", ":", "mount", "=", "next", "(", "iter", "(", "mounts", ")", ")", "# Because we're using regular expressions", "# if our mount doesn't end with a $, insert one.", "mount_re", "=", "mount", "if", "not", "mount", ".", "endswith", "(", "'$'", ")", ":", "mount_re", "=", "'{0}$'", ".", "format", "(", "mount", ")", "if", "salt", ".", "utils", ".", "platform", ".", "is_windows", "(", ")", ":", "# mount_re comes in formatted with a $ at the end", "# can be `C:\\\\$` or `C:\\\\\\\\$`", "# re string must be like `C:\\\\\\\\` regardless of \\\\ or \\\\\\\\", "# also, psutil returns uppercase", "mount_re", "=", "re", ".", "sub", "(", "r':\\\\\\$'", ",", "r':\\\\\\\\'", ",", "mount_re", ")", "mount_re", "=", "re", ".", "sub", "(", "r':\\\\\\\\\\$'", ",", "r':\\\\\\\\'", ",", "mount_re", ")", "mount_re", "=", "mount_re", ".", "upper", "(", ")", "for", "part", "in", "parts", ":", "if", "re", ".", "match", "(", "mount_re", ",", "part", ".", "mountpoint", ")", ":", "_mount", "=", "part", ".", "mountpoint", "try", ":", "_current_usage", "=", "psutil", ".", "disk_usage", "(", "_mount", ")", "except", "OSError", ":", "log", ".", "warning", "(", "'%s is not a valid mount point.'", ",", "_mount", ")", "continue", "current_usage", "=", "_current_usage", ".", "percent", "monitor_usage", "=", "mounts", "[", "mount", "]", "if", "'%'", "in", "monitor_usage", ":", "monitor_usage", "=", "re", ".", "sub", "(", "'%'", ",", "''", ",", "monitor_usage", ")", "monitor_usage", "=", "float", "(", "monitor_usage", ")", "if", "current_usage", ">=", "monitor_usage", ":", "ret", ".", "append", "(", "{", "'diskusage'", ":", "current_usage", ",", "'mount'", ":", "_mount", "}", ")", "return", "ret" ]
creates a response event and adds it to a waiting list When the reponse arrives it will be removed from the list .
def newResponseEvent ( self ) : respEvt = ResponseEvent ( ) self . respLock . acquire ( ) eid = id ( respEvt ) self . respEvents [ eid ] = respEvt self . respLock . release ( ) return ( respEvt , eid )
727
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/contrib/public/services/jsonrpc/__init__.py#L118-L127
[ "def", "_local_update", "(", "self", ",", "rdict", ")", ":", "sanitized", "=", "self", ".", "_check_keys", "(", "rdict", ")", "temp_meta", "=", "self", ".", "_meta_data", "self", ".", "__dict__", "=", "sanitized", "self", ".", "_meta_data", "=", "temp_meta" ]
handles a response by fireing the response event for the response coming in
def handleResponse ( self , resp ) : id = resp [ "id" ] evt = self . respEvents [ id ] del ( self . respEvents [ id ] ) evt . handleResponse ( resp )
728
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/contrib/public/services/jsonrpc/__init__.py#L145-L150
[ "def", "replace", "(", "self", ",", "key", ",", "value", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be None\"", ")", "check_not_none", "(", "value", ",", "\"value can't be None\"", ")", "key_data", "=", "self", ".", "_to_data", "(", "key", ")", "value_data", "=", "self", ".", "_to_data", "(", "value", ")", "return", "self", ".", "_replace_internal", "(", "key_data", ",", "value_data", ")" ]
handles a request by calling the appropriete method the service exposes
def handleRequest ( self , req ) : name = req [ "method" ] params = req [ "params" ] id = req [ "id" ] obj = None try : #to get a callable obj obj = getMethodByName ( self . service , name ) except MethodNameNotAllowed , e : self . sendResponse ( id , None , e ) except : self . sendResponse ( id , None , MethodNotFound ( ) ) if obj : try : #to call the object with parameters rslt = obj ( * params ) self . sendResponse ( id , rslt , None ) except TypeError : # wrong arguments #todo what if the TypeError was not thrown directly by the callable obj s = getTracebackStr ( ) self . sendResponse ( id , None , InvalidMethodParameters ( ) ) except : #error inside the callable object s = getTracebackStr ( ) self . sendResponse ( id , None , s )
729
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/contrib/public/services/jsonrpc/__init__.py#L205-L227
[ "def", "write_lines_to_file", "(", "cls_name", ",", "filename", ",", "lines", ",", "metadata_dict", ")", ":", "metadata_dict", "=", "metadata_dict", "or", "{", "}", "header_line", "=", "\"%s%s\"", "%", "(", "_HEADER_PREFIX", ",", "cls_name", ")", "metadata_line", "=", "\"%s%s\"", "%", "(", "_METADATA_PREFIX", ",", "json", ".", "dumps", "(", "metadata_dict", ",", "sort_keys", "=", "True", ")", ")", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "filename", ",", "\"wb\"", ")", "as", "f", ":", "for", "line", "in", "[", "header_line", ",", "metadata_line", "]", ":", "f", ".", "write", "(", "tf", ".", "compat", ".", "as_bytes", "(", "line", ")", ")", "f", ".", "write", "(", "tf", ".", "compat", ".", "as_bytes", "(", "\"\\n\"", ")", ")", "if", "lines", ":", "f", ".", "write", "(", "tf", ".", "compat", ".", "as_bytes", "(", "\"\\n\"", ".", "join", "(", "lines", ")", ")", ")", "f", ".", "write", "(", "tf", ".", "compat", ".", "as_bytes", "(", "\"\\n\"", ")", ")" ]
handles a notification request by calling the appropriete method the service exposes
def handleNotification ( self , req ) : name = req [ "method" ] params = req [ "params" ] try : #to get a callable obj obj = getMethodByName ( self . service , name ) rslt = obj ( * params ) except : pass
730
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/contrib/public/services/jsonrpc/__init__.py#L229-L237
[ "def", "write_lines_to_file", "(", "cls_name", ",", "filename", ",", "lines", ",", "metadata_dict", ")", ":", "metadata_dict", "=", "metadata_dict", "or", "{", "}", "header_line", "=", "\"%s%s\"", "%", "(", "_HEADER_PREFIX", ",", "cls_name", ")", "metadata_line", "=", "\"%s%s\"", "%", "(", "_METADATA_PREFIX", ",", "json", ".", "dumps", "(", "metadata_dict", ",", "sort_keys", "=", "True", ")", ")", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "filename", ",", "\"wb\"", ")", "as", "f", ":", "for", "line", "in", "[", "header_line", ",", "metadata_line", "]", ":", "f", ".", "write", "(", "tf", ".", "compat", ".", "as_bytes", "(", "line", ")", ")", "f", ".", "write", "(", "tf", ".", "compat", ".", "as_bytes", "(", "\"\\n\"", ")", ")", "if", "lines", ":", "f", ".", "write", "(", "tf", ".", "compat", ".", "as_bytes", "(", "\"\\n\"", ".", "join", "(", "lines", ")", ")", ")", "f", ".", "write", "(", "tf", ".", "compat", ".", "as_bytes", "(", "\"\\n\"", ")", ")" ]
Parses a PSAT data file and returns a case object
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 ( ) # Name the 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 ( ) # TODO: Lines.con - Alternative line data format 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 ( ) # TODO: Varname.bus (Bus names) # Pyparsing case: 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
731
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L54-L101
[ "def", "_sync", "(", "self", ")", ":", "if", "(", "self", ".", "_opcount", ">", "self", ".", "checkpoint_operations", "or", "datetime", ".", "now", "(", ")", ">", "self", ".", "_last_sync", "+", "self", ".", "checkpoint_timeout", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Synchronizing queue metadata.\"", ")", "self", ".", "queue_metadata", ".", "sync", "(", ")", "self", ".", "_last_sync", "=", "datetime", ".", "now", "(", ")", "self", ".", "_opcount", "=", "0", "else", ":", "self", ".", "log", ".", "debug", "(", "\"NOT synchronizing queue metadata.\"", ")" ]
Returns a construct for an array of bus data .
def _get_bus_array_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) v_base = real . setResultsName ( "v_base" ) # kV v_magnitude = Optional ( real ) . setResultsName ( "v_magnitude" ) v_angle = Optional ( real ) . setResultsName ( "v_angle" ) # radians area = Optional ( integer ) . setResultsName ( "area" ) # not used yet region = Optional ( integer ) . setResultsName ( "region" ) # not used yet 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 ) ) # Sort buses according to their name (bus_no) bus_array . setParseAction ( self . sort_buses ) return bus_array
732
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L107-L128
[ "async", "def", "update_lease_async", "(", "self", ",", "lease", ")", ":", "if", "lease", "is", "None", ":", "return", "False", "if", "not", "lease", ".", "token", ":", "return", "False", "_logger", ".", "debug", "(", "\"Updating lease %r %r\"", ",", "self", ".", "host", ".", "guid", ",", "lease", ".", "partition_id", ")", "# First, renew the lease to make sure the update will go through.", "if", "await", "self", ".", "renew_lease_async", "(", "lease", ")", ":", "try", ":", "await", "self", ".", "host", ".", "loop", ".", "run_in_executor", "(", "self", ".", "executor", ",", "functools", ".", "partial", "(", "self", ".", "storage_client", ".", "create_blob_from_text", ",", "self", ".", "lease_container_name", ",", "lease", ".", "partition_id", ",", "json", ".", "dumps", "(", "lease", ".", "serializable", "(", ")", ")", ",", "lease_id", "=", "lease", ".", "token", ")", ")", "except", "Exception", "as", "err", ":", "# pylint: disable=broad-except", "_logger", ".", "error", "(", "\"Failed to update lease %r %r %r\"", ",", "self", ".", "host", ".", "guid", ",", "lease", ".", "partition_id", ",", "err", ")", "raise", "err", "else", ":", "return", "False", "return", "True" ]
Returns a construct for an array of line data .
def _get_line_array_construct ( self ) : from_bus = integer . setResultsName ( "fbus" ) to_bus = integer . setResultsName ( "tbus" ) s_rating = real . setResultsName ( "s_rating" ) # MVA v_rating = real . setResultsName ( "v_rating" ) # kV f_rating = real . setResultsName ( "f_rating" ) # Hz length = real . setResultsName ( "length" ) # km (Line only) v_ratio = real . setResultsName ( "v_ratio" ) # kV/kV (Transformer only) r = real . setResultsName ( "r" ) # p.u. or Ohms/km x = real . setResultsName ( "x" ) # p.u. or Henrys/km b = real . setResultsName ( "b" ) # p.u. or Farads/km (Line only) tap_ratio = real . setResultsName ( "tap" ) # p.u./p.u. (Transformer only) phase_shift = real . setResultsName ( "shift" ) # degrees (Transformer only) i_limit = Optional ( real ) . setResultsName ( "i_limit" ) # p.u. p_limit = Optional ( real ) . setResultsName ( "p_limit" ) # p.u. s_limit = Optional ( real ) . setResultsName ( "s_limit" ) # p.u. 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
733
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L131-L160
[ "def", "need_rejoin", "(", "self", ")", ":", "if", "not", "self", ".", "_subscription", ".", "partitions_auto_assigned", "(", ")", ":", "return", "False", "if", "self", ".", "_auto_assign_all_partitions", "(", ")", ":", "return", "False", "# we need to rejoin if we performed the assignment and metadata has changed", "if", "(", "self", ".", "_assignment_snapshot", "is", "not", "None", "and", "self", ".", "_assignment_snapshot", "!=", "self", ".", "_metadata_snapshot", ")", ":", "return", "True", "# we need to join if our subscription has changed since the last join", "if", "(", "self", ".", "_joined_subscription", "is", "not", "None", "and", "self", ".", "_joined_subscription", "!=", "self", ".", "_subscription", ".", "subscription", ")", ":", "return", "True", "return", "super", "(", "ConsumerCoordinator", ",", "self", ")", ".", "need_rejoin", "(", ")" ]
Returns a construct for an array of slack bus data .
def _get_slack_array_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) s_rating = real . setResultsName ( "s_rating" ) # MVA v_rating = real . setResultsName ( "v_rating" ) # kV v_magnitude = real . setResultsName ( "v_magnitude" ) # p.u. ref_angle = real . setResultsName ( "ref_angle" ) # p.u. q_max = Optional ( real ) . setResultsName ( "q_max" ) # p.u. q_min = Optional ( real ) . setResultsName ( "q_min" ) # p.u. v_max = Optional ( real ) . setResultsName ( "v_max" ) # p.u. v_min = Optional ( real ) . setResultsName ( "v_min" ) # p.u. p_guess = Optional ( real ) . setResultsName ( "p_guess" ) # p.u. # Loss participation coefficient 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
734
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L163-L190
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "try", ":", "modified", "=", "request", ".", "session", ".", "modified", "except", "AttributeError", ":", "pass", "else", ":", "if", "modified", "or", "settings", ".", "SESSION_SAVE_EVERY_REQUEST", ":", "if", "request", ".", "session", ".", "get_expire_at_browser_close", "(", ")", ":", "max_age", "=", "None", "expires", "=", "None", "else", ":", "max_age", "=", "request", ".", "session", ".", "get_expiry_age", "(", ")", "expires_time", "=", "time", ".", "time", "(", ")", "+", "max_age", "expires", "=", "cookie_date", "(", "expires_time", ")", "# Save the session data and refresh the client cookie.", "request", ".", "session", ".", "save", "(", ")", "response", ".", "set_cookie", "(", "settings", ".", "SESSION_COOKIE_NAME", ",", "request", ".", "session", ".", "session_key", ",", "max_age", "=", "max_age", ",", "expires", "=", "expires", ",", "domain", "=", "settings", ".", "SESSION_COOKIE_DOMAIN", ",", "path", "=", "settings", ".", "SESSION_COOKIE_PATH", ",", "secure", "=", "settings", ".", "SESSION_COOKIE_SECURE", "or", "None", ")", "return", "response" ]
Returns a construct for an array of PV generator data .
def _get_pv_array_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) s_rating = real . setResultsName ( "s_rating" ) # MVA v_rating = real . setResultsName ( "v_rating" ) # kV p = real . setResultsName ( "p" ) # p.u. v = real . setResultsName ( "v" ) # p.u. q_max = Optional ( real ) . setResultsName ( "q_max" ) # p.u. q_min = Optional ( real ) . setResultsName ( "q_min" ) # p.u. v_max = Optional ( real ) . setResultsName ( "v_max" ) # p.u. v_min = Optional ( real ) . setResultsName ( "v_min" ) # p.u. # Loss participation coefficient 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
735
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L193-L217
[ "def", "_do_lumping", "(", "self", ")", ":", "c", "=", "copy", ".", "deepcopy", "(", "self", ".", "countsmat_", ")", "if", "self", ".", "sliding_window", ":", "c", "*=", "self", ".", "lag_time", "c", ",", "macro_map", ",", "statesKeep", "=", "self", ".", "_filterFunc", "(", "c", ")", "w", "=", "np", ".", "array", "(", "c", ".", "sum", "(", "axis", "=", "1", ")", ")", ".", "flatten", "(", ")", "w", "[", "statesKeep", "]", "+=", "1", "unmerged", "=", "np", ".", "zeros", "(", "w", ".", "shape", "[", "0", "]", ",", "dtype", "=", "np", ".", "int8", ")", "unmerged", "[", "statesKeep", "]", "=", "1", "# get nonzero indices in upper triangle", "indRecalc", "=", "self", ".", "_getInds", "(", "c", ",", "statesKeep", ")", "dMat", "=", "np", ".", "zeros", "(", "c", ".", "shape", ",", "dtype", "=", "np", ".", "float32", ")", "i", "=", "0", "nCurrentStates", "=", "statesKeep", ".", "shape", "[", "0", "]", "self", ".", "bayesFactors", "=", "{", "}", "dMat", ",", "minX", ",", "minY", "=", "self", ".", "_calcDMat", "(", "c", ",", "w", ",", "indRecalc", ",", "dMat", ",", "statesKeep", ",", "unmerged", ")", "while", "nCurrentStates", ">", "self", ".", "n_macrostates", ":", "c", ",", "w", ",", "indRecalc", ",", "dMat", ",", "macro_map", ",", "statesKeep", ",", "unmerged", ",", "minX", ",", "minY", "=", "self", ".", "_mergeTwoClosestStates", "(", "c", ",", "w", ",", "indRecalc", ",", "dMat", ",", "macro_map", ",", "statesKeep", ",", "minX", ",", "minY", ",", "unmerged", ")", "nCurrentStates", "-=", "1", "if", "self", ".", "save_all_maps", ":", "saved_map", "=", "copy", ".", "deepcopy", "(", "macro_map", ")", "self", ".", "map_dict", "[", "nCurrentStates", "]", "=", "saved_map", "if", "nCurrentStates", "-", "1", "==", "self", ".", "n_macrostates", ":", "self", ".", "microstate_mapping_", "=", "macro_map" ]
Returns a construct for an array of PQ load data .
def _get_pq_array_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) s_rating = real . setResultsName ( "s_rating" ) # MVA v_rating = real . setResultsName ( "v_rating" ) # kV p = real . setResultsName ( "p" ) # p.u. q = real . setResultsName ( "q" ) # p.u. v_max = Optional ( real ) . setResultsName ( "v_max" ) # p.u. v_min = Optional ( real ) . setResultsName ( "v_min" ) # p.u. # Allow conversion to impedance 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
736
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L220-L242
[ "def", "preprocess_cell", "(", "self", ",", "cell", ":", "\"NotebookNode\"", ",", "resources", ":", "dict", ",", "index", ":", "int", ")", "->", "Tuple", "[", "\"NotebookNode\"", ",", "dict", "]", ":", "if", "cell", ".", "cell_type", "==", "\"markdown\"", ":", "variables", "=", "cell", "[", "\"metadata\"", "]", ".", "get", "(", "\"variables\"", ",", "{", "}", ")", "if", "len", "(", "variables", ")", ">", "0", ":", "cell", ".", "source", "=", "self", ".", "replace_variables", "(", "cell", ".", "source", ",", "variables", ")", "if", "resources", ".", "get", "(", "\"delete_pymarkdown\"", ",", "False", ")", ":", "del", "cell", ".", "metadata", "[", "\"variables\"", "]", "return", "cell", ",", "resources" ]
Returns a construct for an array of power demand data .
def _get_demand_array_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) s_rating = real . setResultsName ( "s_rating" ) # MVA p_direction = real . setResultsName ( "p_direction" ) # p.u. q_direction = real . setResultsName ( "q_direction" ) # p.u. p_bid_max = real . setResultsName ( "p_bid_max" ) # p.u. p_bid_min = real . setResultsName ( "p_bid_min" ) # p.u. p_optimal_bid = Optional ( real ) . setResultsName ( "p_optimal_bid" ) p_fixed = real . setResultsName ( "p_fixed" ) # $/hr p_proportional = real . setResultsName ( "p_proportional" ) # $/MWh p_quadratic = real . setResultsName ( "p_quadratic" ) # $/MW^2h q_fixed = real . setResultsName ( "q_fixed" ) # $/hr q_proportional = real . setResultsName ( "q_proportional" ) # $/MVArh q_quadratic = real . setResultsName ( "q_quadratic" ) # $/MVAr^2h commitment = boolean . setResultsName ( "commitment" ) cost_tie_break = real . setResultsName ( "cost_tie_break" ) # $/MWh cost_cong_up = real . setResultsName ( "cost_cong_up" ) # $/h cost_cong_down = real . setResultsName ( "cost_cong_down" ) # $/h 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
737
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L245-L278
[ "def", "update_if_client", "(", "fctn", ")", ":", "@", "functools", ".", "wraps", "(", "fctn", ")", "def", "_update_if_client", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "b", "=", "self", ".", "_bundle", "if", "b", "is", "None", "or", "not", "hasattr", "(", "b", ",", "'is_client'", ")", ":", "return", "fctn", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "elif", "b", ".", "is_client", "and", "(", "b", ".", "_last_client_update", "is", "None", "or", "(", "datetime", ".", "now", "(", ")", "-", "b", ".", "_last_client_update", ")", ".", "seconds", ">", "1", ")", ":", "b", ".", "client_update", "(", ")", "return", "fctn", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_update_if_client" ]
Returns a construct for an array of power supply data .
def _get_supply_array_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) s_rating = real . setResultsName ( "s_rating" ) # MVA p_direction = real . setResultsName ( "p_direction" ) # CPF p_bid_max = real . setResultsName ( "p_bid_max" ) # p.u. p_bid_min = real . setResultsName ( "p_bid_min" ) # p.u. p_bid_actual = real . setResultsName ( "p_bid_actual" ) # p.u. p_fixed = real . setResultsName ( "p_fixed" ) # $/hr p_proportional = real . setResultsName ( "p_proportional" ) # $/MWh p_quadratic = real . setResultsName ( "p_quadratic" ) # $/MW^2h q_fixed = real . setResultsName ( "q_fixed" ) # $/hr q_proportional = real . setResultsName ( "q_proportional" ) # $/MVArh q_quadratic = real . setResultsName ( "q_quadratic" ) # $/MVAr^2h commitment = boolean . setResultsName ( "commitment" ) cost_tie_break = real . setResultsName ( "cost_tie_break" ) # $/MWh lp_factor = real . setResultsName ( "lp_factor" ) # Loss participation factor q_max = real . setResultsName ( "q_max" ) # p.u. q_min = real . setResultsName ( "q_min" ) # p.u. cost_cong_up = real . setResultsName ( "cost_cong_up" ) # $/h cost_cong_down = real . setResultsName ( "cost_cong_down" ) # $/h 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
738
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L281-L316
[ "def", "patch", "(", "save", "=", "True", ",", "tensorboardX", "=", "tensorboardX_loaded", ")", ":", "global", "Summary", ",", "Event", "if", "tensorboardX", ":", "tensorboard_module", "=", "\"tensorboardX.writer\"", "if", "tensorflow_loaded", ":", "wandb", ".", "termlog", "(", "\"Found TensorboardX and tensorflow, pass tensorboardX=False to patch regular tensorboard.\"", ")", "from", "tensorboardX", ".", "proto", ".", "summary_pb2", "import", "Summary", "from", "tensorboardX", ".", "proto", ".", "event_pb2", "import", "Event", "else", ":", "tensorboard_module", "=", "\"tensorflow.python.summary.writer.writer\"", "from", "tensorflow", ".", "summary", "import", "Summary", ",", "Event", "writers", "=", "set", "(", ")", "def", "_add_event", "(", "self", ",", "event", ",", "step", ",", "walltime", "=", "None", ")", ":", "event", ".", "wall_time", "=", "time", ".", "time", "(", ")", "if", "walltime", "is", "None", "else", "walltime", "if", "step", "is", "not", "None", ":", "event", ".", "step", "=", "int", "(", "step", ")", "try", ":", "# TensorboardX uses _file_name", "if", "hasattr", "(", "self", ".", "event_writer", ".", "_ev_writer", ",", "\"_file_name\"", ")", ":", "name", "=", "self", ".", "event_writer", ".", "_ev_writer", ".", "_file_name", "else", ":", "name", "=", "self", ".", "event_writer", ".", "_ev_writer", ".", "FileName", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", "writers", ".", "add", "(", "name", ")", "# This is a little hacky, there is a case where the log_dir changes.", "# Because the events files will have the same names in sub directories", "# we simply overwrite the previous symlink in wandb.save if the log_dir", "# changes.", "log_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "commonprefix", "(", "list", "(", "writers", ")", ")", ")", "filename", "=", "os", ".", "path", ".", "basename", "(", "name", ")", "# Tensorboard loads all tfevents files in a directory and prepends", "# their values with the path. Passing namespace to log allows us", "# to nest the values in wandb", "namespace", "=", "name", ".", "replace", "(", "filename", ",", "\"\"", ")", ".", "replace", "(", "log_dir", ",", "\"\"", ")", ".", "strip", "(", "os", ".", "sep", ")", "if", "save", ":", "wandb", ".", "save", "(", "name", ",", "base_path", "=", "log_dir", ")", "wandb", ".", "save", "(", "os", ".", "path", ".", "join", "(", "log_dir", ",", "\"*.pbtxt\"", ")", ",", "base_path", "=", "log_dir", ")", "log", "(", "event", ",", "namespace", "=", "namespace", ",", "step", "=", "event", ".", "step", ")", "except", "Exception", "as", "e", ":", "wandb", ".", "termerror", "(", "\"Unable to log event %s\"", "%", "e", ")", "# six.reraise(type(e), e, sys.exc_info()[2])", "self", ".", "event_writer", ".", "add_event", "(", "event", ")", "writer", "=", "wandb", ".", "util", ".", "get_module", "(", "tensorboard_module", ")", "writer", ".", "SummaryToEventTransformer", ".", "_add_event", "=", "_add_event" ]
Returns a construct for an array of generator ramping data .
def _get_generator_ramping_construct ( self ) : supply_no = integer . setResultsName ( "supply_no" ) s_rating = real . setResultsName ( "s_rating" ) # MVA up_rate = real . setResultsName ( "up_rate" ) # p.u./h down_rate = real . setResultsName ( "down_rate" ) # p.u./h min_period_up = real . setResultsName ( "min_period_up" ) # h min_period_down = real . setResultsName ( "min_period_down" ) # h 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
739
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L319-L340
[ "def", "get_hostname", "(", "cls", ",", "container_name", ",", "client_name", "=", "None", ")", ":", "base_name", "=", "container_name", "for", "old", ",", "new", "in", "cls", ".", "hostname_replace", ":", "base_name", "=", "base_name", ".", "replace", "(", "old", ",", "new", ")", "if", "not", "client_name", "or", "client_name", "==", "cls", ".", "default_client_name", ":", "return", "base_name", "client_suffix", "=", "client_name", "for", "old", ",", "new", "in", "cls", ".", "hostname_replace", ":", "client_suffix", "=", "client_suffix", ".", "replace", "(", "old", ",", "new", ")", "return", "'{0}-{1}'", ".", "format", "(", "base_name", ",", "client_suffix", ")" ]
Returns a construct for an array of load ramping data .
def _get_load_ramping_construct ( self ) : bus_no = integer . setResultsName ( "bus_no" ) s_rating = real . setResultsName ( "s_rating" ) # MVA up_rate = real . setResultsName ( "up_rate" ) # p.u./h down_rate = real . setResultsName ( "down_rate" ) # p.u./h min_up_time = real . setResultsName ( "min_up_time" ) # min min_down_time = real . setResultsName ( "min_down_time" ) # min 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
740
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L343-L363
[ "def", "get_hostname", "(", "cls", ",", "container_name", ",", "client_name", "=", "None", ")", ":", "base_name", "=", "container_name", "for", "old", ",", "new", "in", "cls", ".", "hostname_replace", ":", "base_name", "=", "base_name", ".", "replace", "(", "old", ",", "new", ")", "if", "not", "client_name", "or", "client_name", "==", "cls", ".", "default_client_name", ":", "return", "base_name", "client_suffix", "=", "client_name", "for", "old", ",", "new", "in", "cls", ".", "hostname_replace", ":", "client_suffix", "=", "client_suffix", ".", "replace", "(", "old", ",", "new", ")", "return", "'{0}-{1}'", ".", "format", "(", "base_name", ",", "client_suffix", ")" ]
Adds a Bus object to the case .
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 )
741
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L369-L381
[ "def", "download_next_song", "(", "self", ",", "song", ")", ":", "dl_ydl_opts", "=", "dict", "(", "ydl_opts", ")", "dl_ydl_opts", "[", "\"progress_hooks\"", "]", "=", "[", "self", ".", "ytdl_progress_hook", "]", "dl_ydl_opts", "[", "\"outtmpl\"", "]", "=", "self", ".", "output_format", "# Move the songs from the next cache to the current cache", "self", ".", "move_next_cache", "(", ")", "self", ".", "state", "=", "'ready'", "self", ".", "play_empty", "(", ")", "# Download the file and create the stream", "with", "youtube_dl", ".", "YoutubeDL", "(", "dl_ydl_opts", ")", "as", "ydl", ":", "try", ":", "ydl", ".", "download", "(", "[", "song", "]", ")", "except", "DownloadStreamException", ":", "# This is a livestream, use the appropriate player", "future", "=", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "create_stream_player", "(", "song", ",", "dl_ydl_opts", ")", ",", "client", ".", "loop", ")", "try", ":", "future", ".", "result", "(", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "e", ")", "self", ".", "vafter_ts", "(", ")", "return", "except", "PermissionError", ":", "# File is still in use, it'll get cleared next time", "pass", "except", "youtube_dl", ".", "utils", ".", "DownloadError", "as", "e", ":", "self", ".", "logger", ".", "exception", "(", "e", ")", "self", ".", "statuslog", ".", "error", "(", "e", ")", "self", ".", "vafter_ts", "(", ")", "return", "except", "Exception", "as", "e", ":", "self", ".", "logger", ".", "exception", "(", "e", ")", "self", ".", "vafter_ts", "(", ")", "return" ]
Adds a Branch object to the case .
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" ] # Optional parameter if tokens [ "tap" ] == 0 : #Transmission line e . ratio = 1.0 else : # Transformer e . ratio = tokens [ "tap" ] e . phase_shift = tokens [ "shift" ] # Optional parameter # if "status" in tokens.keys: # e.online = tokens["status"] self . case . branches . append ( e )
742
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L390-L415
[ "def", "add_item", "(", "self", ",", "item_url", ",", "item_metadata", ")", ":", "c", "=", "self", ".", "conn", ".", "cursor", "(", ")", "c", ".", "execute", "(", "\"DELETE FROM items WHERE url=?\"", ",", "(", "str", "(", "item_url", ")", ",", ")", ")", "self", ".", "conn", ".", "commit", "(", ")", "c", ".", "execute", "(", "\"INSERT INTO items VALUES (?, ?, ?)\"", ",", "(", "str", "(", "item_url", ")", ",", "item_metadata", ",", "self", ".", "__now_iso_8601", "(", ")", ")", ")", "self", ".", "conn", ".", "commit", "(", ")", "c", ".", "close", "(", ")" ]
Finds the slack bus adds a Generator with the appropriate data and sets the bus type to slack .
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" ] # Optional parameter # if tokens.has_key("status"): # g.online = tokens["status"] self . case . generators . append ( g ) bus . type = "ref"
743
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L418-L435
[ "def", "__expire_files", "(", "self", ")", ":", "self", ".", "__files", "=", "OrderedDict", "(", "item", "for", "item", "in", "self", ".", "__files", ".", "items", "(", ")", "if", "not", "item", "[", "1", "]", ".", "expired", ")" ]
Creates and Generator object populates it with data finds its Bus and adds it .
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" ] # Optional parameter # if tokens.has_key("status"): # g.online = tokens["status"] self . case . generators . append ( g )
744
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L438-L454
[ "def", "get_minimum_score_metadata", "(", "self", ")", ":", "# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template", "metadata", "=", "dict", "(", "self", ".", "_mdata", "[", "'minimum_score'", "]", ")", "metadata", ".", "update", "(", "{", "'existing_cardinal_values'", ":", "self", ".", "_my_map", "[", "'minimumScore'", "]", "}", ")", "return", "Metadata", "(", "*", "*", "metadata", ")" ]
Creates and Load object populates it with data finds its Bus and adds it .
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" ]
745
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L457-L465
[ "def", "get_minimum_score_metadata", "(", "self", ")", ":", "# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template", "metadata", "=", "dict", "(", "self", ".", "_mdata", "[", "'minimum_score'", "]", ")", "metadata", ".", "update", "(", "{", "'existing_cardinal_values'", ":", "self", ".", "_my_map", "[", "'minimumScore'", "]", "}", ")", "return", "Metadata", "(", "*", "*", "metadata", ")" ]
Adds OPF and CPF data to a Generator .
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" ] )
746
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L493-L518
[ "def", "unbind", "(", "self", ",", "devices_to_unbind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/subscribe/unbind\"", "headers", "=", "{", "\"apikey\"", ":", "self", ".", "entity_api_key", "}", "data", "=", "{", "\"exchange\"", ":", "\"amq.topic\"", ",", "\"keys\"", ":", "devices_to_unbind", ",", "\"queue\"", ":", "self", ".", "entity_id", "}", "with", "self", ".", "no_ssl_verification", "(", ")", ":", "r", "=", "requests", ".", "delete", "(", "url", ",", "json", "=", "data", ",", "headers", "=", "headers", ")", "print", "(", "r", ")", "response", "=", "dict", "(", ")", "if", "\"No API key\"", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "json", ".", "loads", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "[", "'message'", "]", "elif", "'unbind'", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"success\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "response", "[", "\"response\"", "]", "=", "str", "(", "r", ")", "return", "response" ]
Parses the given file - like object .
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
747
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/matpower.py#L95-L125
[ "def", "unbind", "(", "self", ",", "devices_to_unbind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/subscribe/unbind\"", "headers", "=", "{", "\"apikey\"", ":", "self", ".", "entity_api_key", "}", "data", "=", "{", "\"exchange\"", ":", "\"amq.topic\"", ",", "\"keys\"", ":", "devices_to_unbind", ",", "\"queue\"", ":", "self", ".", "entity_id", "}", "with", "self", ".", "no_ssl_verification", "(", ")", ":", "r", "=", "requests", ".", "delete", "(", "url", ",", "json", "=", "data", ",", "headers", "=", "headers", ")", "print", "(", "r", ")", "response", "=", "dict", "(", ")", "if", "\"No API key\"", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "json", ".", "loads", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "[", "'message'", "]", "elif", "'unbind'", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"success\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "response", "[", "\"response\"", "]", "=", "str", "(", "r", ")", "return", "response" ]
Writes case data to file in MATPOWER format .
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 )
748
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/matpower.py#L748-L758
[ "async", "def", "async_delete_api_key", "(", "session", ",", "host", ",", "port", ",", "api_key", ")", ":", "url", "=", "'http://{host}:{port}/api/{api_key}/config/whitelist/{api_key}'", ".", "format", "(", "host", "=", "host", ",", "port", "=", "str", "(", "port", ")", ",", "api_key", "=", "api_key", ")", "response", "=", "await", "async_request", "(", "session", ".", "delete", ",", "url", ")", "_LOGGER", ".", "info", "(", "response", ")" ]
Writes the case data in MATPOWER format .
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 ) )
749
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/matpower.py#L767-L776
[ "def", "clear_key_before", "(", "self", ",", "key", ",", "namespace", "=", "None", ",", "timestamp", "=", "None", ")", ":", "block_size", "=", "self", ".", "config", ".", "block_size", "if", "namespace", "is", "None", ":", "namespace", "=", "self", ".", "config", ".", "namespace", "if", "timestamp", "is", "not", "None", ":", "offset", ",", "remainder", "=", "divmod", "(", "timestamp", ",", "block_size", ")", "if", "remainder", ":", "raise", "ValueError", "(", "'timestamp must be on a block boundary'", ")", "if", "offset", "==", "0", ":", "raise", "ValueError", "(", "'cannot delete before offset zero'", ")", "offset", "-=", "1", "self", ".", "driver", ".", "clear_key_before", "(", "key", ",", "namespace", ",", "offset", ",", "timestamp", ")", "else", ":", "self", ".", "driver", ".", "clear_key_before", "(", "key", ",", "namespace", ")" ]
Writes generator cost data to file .
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 # cp = [p for p, q in generator.p_cost] # cq = [q for p, q in generator.p_cost] # c = zip(cp, cq) 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" )
750
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/matpower.py#L858-L888
[ "def", "remove_async_sns_topic", "(", "self", ",", "lambda_name", ")", ":", "topic_name", "=", "get_topic_name", "(", "lambda_name", ")", "removed_arns", "=", "[", "]", "for", "sub", "in", "self", ".", "sns_client", ".", "list_subscriptions", "(", ")", "[", "'Subscriptions'", "]", ":", "if", "topic_name", "in", "sub", "[", "'TopicArn'", "]", ":", "self", ".", "sns_client", ".", "delete_topic", "(", "TopicArn", "=", "sub", "[", "'TopicArn'", "]", ")", "removed_arns", ".", "append", "(", "sub", "[", "'TopicArn'", "]", ")", "return", "removed_arns" ]
Writes area data to file .
def write_area_data ( self , file ) : file . write ( "%% area data" + "\n" ) file . write ( "%\tno.\tprice_ref_bus" + "\n" ) file . write ( "areas = [" + "\n" ) # TODO: Implement areas file . write ( "\t1\t1;" + "\n" ) file . write ( "];" + "\n" )
751
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/matpower.py#L906-L915
[ "def", "ConsultarProvincias", "(", "self", ",", "sep", "=", "\"||\"", ")", ":", "ret", "=", "self", ".", "client", ".", "provinciasConsultar", "(", "auth", "=", "{", "'token'", ":", "self", ".", "Token", ",", "'sign'", ":", "self", ".", "Sign", ",", "'cuit'", ":", "self", ".", "Cuit", ",", "}", ",", ")", "[", "'provinciasReturn'", "]", "self", ".", "__analizar_errores", "(", "ret", ")", "array", "=", "ret", ".", "get", "(", "'provincias'", ",", "[", "]", ")", "if", "sep", "is", "None", ":", "return", "dict", "(", "[", "(", "int", "(", "it", "[", "'codigoDescripcion'", "]", "[", "'codigo'", "]", ")", ",", "it", "[", "'codigoDescripcion'", "]", "[", "'descripcion'", "]", ")", "for", "it", "in", "array", "]", ")", "else", ":", "return", "[", "(", "\"%s %%s %s %%s %s\"", "%", "(", "sep", ",", "sep", ",", "sep", ")", ")", "%", "(", "it", "[", "'codigoDescripcion'", "]", "[", "'codigo'", "]", ",", "it", "[", "'codigoDescripcion'", "]", "[", "'descripcion'", "]", ")", "for", "it", "in", "array", "]" ]
Initiate processing for each token .
def process_file ( self , language , key , token_list ) : self . language = language for tok in token_list : self . process_token ( tok )
752
https://github.com/finklabs/metrics/blob/fd9974af498831664b9ae8e8f3834e1ec2e8a699/metrics/metricbase.py#L26-L34
[ "def", "arcball_constrain_to_axis", "(", "point", ",", "axis", ")", ":", "v", "=", "np", ".", "array", "(", "point", ",", "dtype", "=", "np", ".", "float64", ",", "copy", "=", "True", ")", "a", "=", "np", ".", "array", "(", "axis", ",", "dtype", "=", "np", ".", "float64", ",", "copy", "=", "True", ")", "v", "-=", "a", "*", "np", ".", "dot", "(", "a", ",", "v", ")", "# on plane", "n", "=", "vector_norm", "(", "v", ")", "if", "n", ">", "_EPS", ":", "if", "v", "[", "2", "]", "<", "0.0", ":", "np", ".", "negative", "(", "v", ",", "v", ")", "v", "/=", "n", "return", "v", "if", "a", "[", "2", "]", "==", "1.0", ":", "return", "np", ".", "array", "(", "[", "1.0", ",", "0.0", ",", "0.0", "]", ")", "return", "unit_vector", "(", "[", "-", "a", "[", "1", "]", ",", "a", "[", "0", "]", ",", "0.0", "]", ")" ]
Initialises plots of the environment .
def draw_plot ( self ) : pylab . ion ( ) fig = pylab . figure ( 1 ) # State plot. # state_axis = fig.add_subplot(3, 1, 1) # numrows, numcols, fignum # state_axis.title = 'State' # state_axis.xlabel = 'Time (hours)' # state_axis.grid = True # for i in range(self.state_data.shape[0]): # lines = state_axis.plot(self.state_data[i, 0], "g+-") # self.state_lines.append(lines[0]) # Action plot. # action_axis = fig.add_subplot(3, 1, 2) # action_axis.title = 'Action' # action_axis.xlabel = 'Time (hours)' # action_axis.ylabel = 'Price ($/MWh)' # action_axis.grid = True # for i in range(self.action_data.shape[0]): # lines = action_axis.plot(self.action_data[i, 0], "ro-") # self.action_lines.append(lines[0]) # Reward plot. reward_axis = fig . add_subplot ( 3 , 1 , 3 ) # reward_axis.title = 'Reward' # reward_axis.xlabel = 'Time (hours)' # reward_axis.ylabel = 'Earnings ($)' # reward_axis.grid(True) reward_lines = reward_axis . plot ( self . reward_data [ 0 , 0 ] , [ 0 ] , "mx-" ) self . reward_line = reward_lines [ 0 ] pylab . draw ( )
753
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/renderer.py#L177-L211
[ "def", "cudnnSetPooling2dDescriptor", "(", "poolingDesc", ",", "mode", ",", "windowHeight", ",", "windowWidth", ",", "verticalPadding", ",", "horizontalPadding", ",", "verticalStride", ",", "horizontalStride", ")", ":", "status", "=", "_libcudnn", ".", "cudnnSetPooling2dDescriptor", "(", "poolingDesc", ",", "mode", ",", "windowHeight", ",", "windowWidth", ",", "verticalPadding", ",", "horizontalPadding", ",", "verticalStride", ",", "horizontalStride", ")", "cudnnCheckStatus", "(", "status", ")" ]
Writes case data to file .
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 ) ) )
754
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psse.py#L387-L397
[ "def", "get_new_connection", "(", "self", ",", "conn_params", ")", ":", "connection", "=", "ldap", ".", "ldapobject", ".", "ReconnectLDAPObject", "(", "uri", "=", "conn_params", "[", "'uri'", "]", ",", "retry_max", "=", "conn_params", "[", "'retry_max'", "]", ",", "retry_delay", "=", "conn_params", "[", "'retry_delay'", "]", ",", "bytes_mode", "=", "False", ")", "options", "=", "conn_params", "[", "'options'", "]", "for", "opt", ",", "value", "in", "options", ".", "items", "(", ")", ":", "if", "opt", "==", "'query_timeout'", ":", "connection", ".", "timeout", "=", "int", "(", "value", ")", "elif", "opt", "==", "'page_size'", ":", "self", ".", "page_size", "=", "int", "(", "value", ")", "else", ":", "connection", ".", "set_option", "(", "opt", ",", "value", ")", "if", "conn_params", "[", "'tls'", "]", ":", "connection", ".", "start_tls_s", "(", ")", "connection", ".", "simple_bind_s", "(", "conn_params", "[", "'bind_dn'", "]", ",", "conn_params", "[", "'bind_pw'", "]", ",", ")", "return", "connection" ]
Plots the costs of the given generators .
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 ( )
755
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/util.py#L129-L147
[ "def", "_stream_annotation", "(", "file_name", ",", "pb_dir", ")", ":", "# Full url of annotation file", "url", "=", "posixpath", ".", "join", "(", "config", ".", "db_index_url", ",", "pb_dir", ",", "file_name", ")", "# Get the content", "response", "=", "requests", ".", "get", "(", "url", ")", "# Raise HTTPError if invalid url", "response", ".", "raise_for_status", "(", ")", "# Convert to numpy array", "ann_data", "=", "np", ".", "fromstring", "(", "response", ".", "content", ",", "dtype", "=", "np", ".", "dtype", "(", "'<u1'", ")", ")", "return", "ann_data" ]
Writes market experiment data to file in ReStructuredText format .
def write ( self , file ) : # Write environment state data. file . write ( "State\n" ) file . write ( ( "-" * 5 ) + "\n" ) self . writeDataTable ( file , type = "state" ) # Write action data. file . write ( "Action\n" ) file . write ( ( "-" * 6 ) + "\n" ) self . writeDataTable ( file , type = "action" ) # Write reward data. file . write ( "Reward\n" ) file . write ( ( "-" * 6 ) + "\n" ) self . writeDataTable ( file , type = "reward" )
756
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/util.py#L210-L226
[ "def", "_put_options", "(", "self", ",", "options_list", ")", ":", "new_options", "=", "self", ".", "_options", ".", "copy", "(", ")", "# make a full copy of the dict not to only link it and update dict in place", "new_options", ".", "update", "(", "{", "\"value_choices\"", ":", "options_list", "}", ")", "validate", "(", "new_options", ",", "options_json_schema", ")", "url", "=", "self", ".", "_client", ".", "_build_url", "(", "'property'", ",", "property_id", "=", "self", ".", "id", ")", "response", "=", "self", ".", "_client", ".", "_request", "(", "'PUT'", ",", "url", ",", "json", "=", "{", "'options'", ":", "new_options", "}", ")", "if", "response", ".", "status_code", "!=", "200", ":", "# pragma: no cover", "raise", "APIError", "(", "\"Could not update property value. Response: {}\"", ".", "format", "(", "str", "(", "response", ")", ")", ")", "else", ":", "self", ".", "_options", "=", "new_options" ]
Writes agent data to an ReST table . The type argument may be state action or reward .
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 ) # Table column headers. file . write ( ".." . rjust ( idxColWidth ) + " " ) for agent in agents : # The end of the name is typically the unique part. file . write ( agent . name [ - colWidth : ] . center ( colWidth ) + " " ) file . write ( "\n" ) file . write ( sep ) # Table values. 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 ) # FIXME: Handle multiple state values. file . write ( "%8.3f " % field [ sequence , 0 ] ) file . write ( "\n" ) file . write ( sep )
757
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/util.py#L229-L269
[ "def", "_sync_with_file", "(", "self", ")", ":", "self", ".", "_records", "=", "[", "]", "i", "=", "-", "1", "for", "i", ",", "line", "in", "self", ".", "_enum_lines", "(", ")", ":", "self", ".", "_records", ".", "append", "(", "None", ")", "self", ".", "_last_synced_index", "=", "i" ]
Execute one action .
def performAction ( self , action ) : # print "ACTION:", action self . t += 1 Task . performAction ( self , action ) # self.addReward() self . samples += 1
758
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/continuous/task.py#L74-L81
[ "def", "volumes_delete", "(", "storage_pool", ",", "logger", ")", ":", "try", ":", "for", "vol_name", "in", "storage_pool", ".", "listVolumes", "(", ")", ":", "try", ":", "vol", "=", "storage_pool", ".", "storageVolLookupByName", "(", "vol_name", ")", "vol", ".", "delete", "(", "0", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volume %s.\"", ",", "vol_name", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volumes.\"", ")" ]
Split equations into differential algebraic and algebraic only
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 ) }
759
https://github.com/pymoca/pymoca/blob/14b5eb7425e96689de6cc5c10f400895d586a978/src/pymoca/backends/xml/model.py#L174-L186
[ "def", "logEndTime", "(", ")", ":", "logger", ".", "info", "(", "'\\n'", "+", "'#'", "*", "70", ")", "logger", ".", "info", "(", "'Complete'", ")", "logger", ".", "info", "(", "datetime", ".", "today", "(", ")", ".", "strftime", "(", "\"%A, %d %B %Y %I:%M%p\"", ")", ")", "logger", ".", "info", "(", "'#'", "*", "70", "+", "'\\n'", ")" ]
Perumute a vector
def permute ( x : SYM , perm : List [ int ] ) -> SYM : x_s = [ ] for i in perm : x_s . append ( x [ i ] ) return ca . vertcat ( * x_s )
760
https://github.com/pymoca/pymoca/blob/14b5eb7425e96689de6cc5c10f400895d586a978/src/pymoca/backends/xml/model.py#L189-L194
[ "def", "handle_simulation_end", "(", "self", ",", "data_portal", ")", ":", "log", ".", "info", "(", "'Simulated {} trading days\\n'", "'first open: {}\\n'", "'last close: {}'", ",", "self", ".", "_session_count", ",", "self", ".", "_trading_calendar", ".", "session_open", "(", "self", ".", "_first_session", ")", ",", "self", ".", "_trading_calendar", ".", "session_close", "(", "self", ".", "_last_session", ")", ",", ")", "packet", "=", "{", "}", "self", ".", "end_of_simulation", "(", "packet", ",", "self", ".", "_ledger", ",", "self", ".", "_trading_calendar", ",", "self", ".", "_sessions", ",", "data_portal", ",", "self", ".", "_benchmark_source", ",", ")", "return", "packet" ]
Sort equations by dependence
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 }
761
https://github.com/pymoca/pymoca/blob/14b5eb7425e96689de6cc5c10f400895d586a978/src/pymoca/backends/xml/model.py#L198-L213
[ "def", "json_parse", "(", "self", ",", "response", ")", ":", "try", ":", "data", "=", "response", ".", "json", "(", ")", "except", "ValueError", ":", "data", "=", "{", "'meta'", ":", "{", "'status'", ":", "500", ",", "'msg'", ":", "'Server Error'", "}", ",", "'response'", ":", "{", "\"error\"", ":", "\"Malformed JSON or HTML was returned.\"", "}", "}", "# We only really care about the response if we succeed", "# and the error if we fail", "if", "200", "<=", "data", "[", "'meta'", "]", "[", "'status'", "]", "<=", "399", ":", "return", "data", "[", "'response'", "]", "else", ":", "return", "data" ]
Discrete state dynamics
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 )
762
https://github.com/pymoca/pymoca/blob/14b5eb7425e96689de6cc5c10f400895d586a978/src/pymoca/backends/xml/model.py#L94-L100
[ "def", "center_cell_text", "(", "cell", ")", ":", "lines", "=", "cell", ".", "text", ".", "split", "(", "'\\n'", ")", "cell_width", "=", "len", "(", "lines", "[", "0", "]", ")", "-", "2", "truncated_lines", "=", "[", "''", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "lines", ")", "-", "1", ")", ":", "truncated", "=", "lines", "[", "i", "]", "[", "2", ":", "len", "(", "lines", "[", "i", "]", ")", "-", "2", "]", ".", "rstrip", "(", ")", "truncated_lines", ".", "append", "(", "truncated", ")", "truncated_lines", ".", "append", "(", "''", ")", "max_line_length", "=", "get_longest_line_length", "(", "'\\n'", ".", "join", "(", "truncated_lines", ")", ")", "remainder", "=", "cell_width", "-", "max_line_length", "left_width", "=", "math", ".", "floor", "(", "remainder", "/", "2", ")", "left_space", "=", "left_width", "*", "' '", "for", "i", "in", "range", "(", "len", "(", "truncated_lines", ")", ")", ":", "truncated_lines", "[", "i", "]", "=", "left_space", "+", "truncated_lines", "[", "i", "]", "right_width", "=", "cell_width", "-", "len", "(", "truncated_lines", "[", "i", "]", ")", "truncated_lines", "[", "i", "]", "+=", "right_width", "*", "' '", "for", "i", "in", "range", "(", "1", ",", "len", "(", "lines", ")", "-", "1", ")", ":", "lines", "[", "i", "]", "=", "''", ".", "join", "(", "[", "lines", "[", "i", "]", "[", "0", "]", ",", "truncated_lines", "[", "i", "]", ",", "lines", "[", "i", "]", "[", "-", "1", "]", "]", ")", "cell", ".", "text", "=", "'\\n'", ".", "join", "(", "lines", ")", "return", "cell" ]
Jacobian for state integration
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 )
763
https://github.com/pymoca/pymoca/blob/14b5eb7425e96689de6cc5c10f400895d586a978/src/pymoca/backends/xml/model.py#L102-L108
[ "def", "getFileCategory", "(", "self", ",", "fileInfo", ")", ":", "category", "=", "fileInfo", "[", "fileInfo", ".", "find", "(", "\"Category\"", ")", ":", "]", "category", "=", "category", "[", "category", ".", "find", "(", "\"<FONT \"", ")", "+", "47", ":", "]", "category", "=", "category", "[", "category", ".", "find", "(", "'\">'", ")", "+", "2", ":", "]", "category", "=", "category", "[", ":", "category", ".", "find", "(", "\"</A></B>\"", ")", "-", "0", "]", "return", "category" ]
Convert to a HybridOde
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 , )
764
https://github.com/pymoca/pymoca/blob/14b5eb7425e96689de6cc5c10f400895d586a978/src/pymoca/backends/xml/model.py#L143-L171
[ "def", "get_bundle", "(", "self", ",", "bundle_name", ",", "extensions", "=", "None", ")", ":", "if", "self", ".", "stats", ".", "get", "(", "'status'", ")", "==", "'done'", ":", "bundle", "=", "self", ".", "stats", ".", "get", "(", "'chunks'", ",", "{", "}", ")", ".", "get", "(", "bundle_name", ",", "None", ")", "if", "bundle", "is", "None", ":", "raise", "KeyError", "(", "'No such bundle {0!r}.'", ".", "format", "(", "bundle_name", ")", ")", "test", "=", "self", ".", "_chunk_filter", "(", "extensions", ")", "return", "[", "self", ".", "_add_url", "(", "c", ")", "for", "c", "in", "bundle", "if", "test", "(", "c", ")", "]", "elif", "self", ".", "stats", ".", "get", "(", "'status'", ")", "==", "'error'", ":", "raise", "RuntimeError", "(", "\"{error}: {message}\"", ".", "format", "(", "*", "*", "self", ".", "stats", ")", ")", "else", ":", "raise", "RuntimeError", "(", "\"Bad webpack stats file {0} status: {1!r}\"", ".", "format", "(", "self", ".", "state", ".", "stats_file", ",", "self", ".", "stats", ".", "get", "(", "'status'", ")", ")", ")" ]
Tries to infer a protocol from the file extension .
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
765
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/util.py#L159-L168
[ "def", "sync_hooks", "(", "user_id", ",", "repositories", ")", ":", "from", ".", "api", "import", "GitHubAPI", "try", ":", "# Sync hooks", "gh", "=", "GitHubAPI", "(", "user_id", "=", "user_id", ")", "for", "repo_id", "in", "repositories", ":", "try", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "gh", ".", "sync_repo_hook", "(", "repo_id", ")", "# We commit per repository, because while the task is running", "# the user might enable/disable a hook.", "db", ".", "session", ".", "commit", "(", ")", "except", "RepositoryAccessError", "as", "e", ":", "current_app", ".", "logger", ".", "warning", "(", "e", ".", "message", ",", "exc_info", "=", "True", ")", "except", "NoResultFound", ":", "pass", "# Repository not in DB yet", "except", "Exception", "as", "exc", ":", "sync_hooks", ".", "retry", "(", "exc", "=", "exc", ")" ]
Parses the MATPOWER case files at the given paths and pickles the resulting Case objects to the same directory .
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 : # Read the MATPOWER case file. case = pylon . io . MATPOWERReader ( case_format ) . read ( case_path ) # Give the new file the same name, but with a different extension. 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' ) # Pickle the resulting Pylon Case object. pylon . io . PickleWriter ( case ) . write ( pickled_case_path )
766
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/util.py#L174-L194
[ "def", "update_cluster", "(", "cluster_ref", ",", "cluster_spec", ")", ":", "cluster_name", "=", "get_managed_object_name", "(", "cluster_ref", ")", "log", ".", "trace", "(", "'Updating cluster \\'%s\\''", ",", "cluster_name", ")", "try", ":", "task", "=", "cluster_ref", ".", "ReconfigureComputeResource_Task", "(", "cluster_spec", ",", "modify", "=", "True", ")", "except", "vim", ".", "fault", ".", "NoPermission", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "salt", ".", "exceptions", ".", "VMwareApiError", "(", "'Not enough permissions. Required privilege: '", "'{}'", ".", "format", "(", "exc", ".", "privilegeId", ")", ")", "except", "vim", ".", "fault", ".", "VimFault", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "salt", ".", "exceptions", ".", "VMwareApiError", "(", "exc", ".", "msg", ")", "except", "vmodl", ".", "RuntimeFault", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "salt", ".", "exceptions", ".", "VMwareRuntimeError", "(", "exc", ".", "msg", ")", "wait_for_task", "(", "task", ",", "cluster_name", ",", "'ClusterUpdateTask'", ")" ]
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 .
def fair_max ( x ) : value = max ( x ) # List indexes of max value. i = [ x . index ( v ) for v in x if v == value ] # Select index randomly among occurances. idx = random . choice ( i ) return idx , value
767
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/util.py#L243-L256
[ "def", "reset_local_buffers", "(", "self", ")", ":", "agent_ids", "=", "list", "(", "self", ".", "keys", "(", ")", ")", "for", "k", "in", "agent_ids", ":", "self", "[", "k", "]", ".", "reset_agent", "(", ")" ]
Returns the factorial of n .
def factorial ( n ) : f = 1 while ( n > 0 ) : f = f * n n = n - 1 return f
768
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/util.py#L262-L269
[ "def", "to_javascript_data", "(", "plugins", ")", ":", "def", "escape", "(", "v", ")", ":", "return", "re", ".", "sub", "(", "r'\"'", ",", "r'\\\\\"'", ",", "v", ")", "def", "dom_matchers", "(", "p", ")", ":", "dom_matchers", "=", "p", ".", "get_matchers", "(", "'dom'", ")", "escaped_dom_matchers", "=", "[", "]", "for", "dm", "in", "dom_matchers", ":", "check_statement", ",", "version_statement", "=", "dm", "escaped_dom_matchers", ".", "append", "(", "{", "'check_statement'", ":", "escape", "(", "check_statement", ")", ",", "# Escape '' and not None", "'version_statement'", ":", "escape", "(", "version_statement", "or", "''", ")", ",", "}", ")", "return", "escaped_dom_matchers", "return", "[", "{", "'name'", ":", "p", ".", "name", ",", "'matchers'", ":", "dom_matchers", "(", "p", ")", "}", "for", "p", "in", "plugins", ".", "with_dom_matchers", "(", ")", "]" ]
Returns the name which is generated if it has not been already .
def _get_name ( self ) : if self . _name is None : self . _name = self . _generate_name ( ) return self . _name
769
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/util.py#L61-L66
[ "def", "set_soup", "(", "self", ")", ":", "self", ".", "soup", "=", "BeautifulSoup", "(", "self", ".", "feed_content", ",", "\"html.parser\"", ")", "for", "item", "in", "self", ".", "soup", ".", "findAll", "(", "'item'", ")", ":", "item", ".", "decompose", "(", ")", "for", "image", "in", "self", ".", "soup", ".", "findAll", "(", "'image'", ")", ":", "image", ".", "decompose", "(", ")" ]
Save the object to a given file like object in the given format .
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 )
770
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/util.py#L98-L105
[ "def", "_clean_workers", "(", "self", ")", ":", "while", "self", ".", "_bag_collector", ":", "self", ".", "_bag_collector", ".", "popleft", "(", ")", "self", ".", "_timer_worker_delete", ".", "stop", "(", ")" ]
Load the object from a given file like object in the given format .
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 )
771
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/util.py#L109-L116
[ "def", "_clean_workers", "(", "self", ")", ":", "while", "self", ".", "_bag_collector", ":", "self", ".", "_bag_collector", ".", "popleft", "(", ")", "self", ".", "_timer_worker_delete", ".", "stop", "(", ")" ]
Save the object to file given by filename .
def save ( self , filename , format = None , * * kwargs ) : if format is None : # try to derive protocol from file extension format = format_from_extension ( filename ) with file ( filename , 'wb' ) as fp : self . save_to_file_object ( fp , format , * * kwargs )
772
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/util.py#L119-L126
[ "def", "delete_topic_groups", "(", "self", ",", "group_id", ",", "topic_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - group_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"group_id\"", "]", "=", "group_id", "# REQUIRED - PATH - topic_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"topic_id\"", "]", "=", "topic_id", "self", ".", "logger", ".", "debug", "(", "\"DELETE /api/v1/groups/{group_id}/discussion_topics/{topic_id} with query params: {params} and form data: {data}\"", ".", "format", "(", "params", "=", "params", ",", "data", "=", "data", ",", "*", "*", "path", ")", ")", "return", "self", ".", "generic_request", "(", "\"DELETE\"", ",", "\"/api/v1/groups/{group_id}/discussion_topics/{topic_id}\"", ".", "format", "(", "*", "*", "path", ")", ",", "data", "=", "data", ",", "params", "=", "params", ",", "no_data", "=", "True", ")" ]
Return an instance of the class that is saved in the file with the given filename in the specified format .
def load ( cls , filename , format = None ) : if format is None : # try to derive protocol from file extension format = format_from_extension ( filename ) with file ( filename , 'rbU' ) as fp : obj = cls . load_from_file_object ( fp , format ) obj . filename = filename return obj
773
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/util.py#L130-L140
[ "def", "StartAndWait", "(", "self", ")", ":", "self", ".", "StartTask", "(", ")", "self", ".", "WaitUntilTaskDone", "(", "pydaq", ".", "DAQmx_Val_WaitInfinitely", ")", "self", ".", "ClearTask", "(", ")" ]
Solves a DC power flow .
def solve ( self ) : case = self . case logger . info ( "Starting DC power flow [%s]." % case . name ) t0 = time . time ( ) # Update bus indexes. self . case . index_buses ( ) # Find the index of the refence bus. ref_idx = self . _get_reference_index ( case ) if ref_idx < 0 : return False # Build the susceptance matrices. B , Bsrc , p_businj , p_srcinj = case . Bdc # Get the vector of initial voltage angles. v_angle_guess = self . _get_v_angle_guess ( case ) # Calculate the new voltage phase angles. 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 # Push the results to the case. 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
774
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/dc_pf.py#L66-L95
[ "def", "DeleteNotifications", "(", "self", ",", "session_ids", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "not", "session_ids", ":", "return", "for", "session_id", "in", "session_ids", ":", "if", "not", "isinstance", "(", "session_id", ",", "rdfvalue", ".", "SessionID", ")", ":", "raise", "RuntimeError", "(", "\"Can only delete notifications for rdfvalue.SessionIDs.\"", ")", "if", "start", "is", "None", ":", "start", "=", "0", "else", ":", "start", "=", "int", "(", "start", ")", "if", "end", "is", "None", ":", "end", "=", "self", ".", "frozen_timestamp", "or", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")", "for", "queue", ",", "ids", "in", "iteritems", "(", "collection", ".", "Group", "(", "session_ids", ",", "lambda", "session_id", ":", "session_id", ".", "Queue", "(", ")", ")", ")", ":", "queue_shards", "=", "self", ".", "GetAllNotificationShards", "(", "queue", ")", "self", ".", "data_store", ".", "DeleteNotifications", "(", "queue_shards", ",", "ids", ",", "start", ",", "end", ")" ]
Returns the index of the reference bus .
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
775
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/dc_pf.py#L101-L109
[ "def", "preview", "(", "request", ")", ":", "if", "settings", ".", "MARKDOWN_PROTECT_PREVIEW", ":", "user", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "if", "not", "user", "or", "not", "user", ".", "is_staff", ":", "from", "django", ".", "contrib", ".", "auth", ".", "views", "import", "redirect_to_login", "return", "redirect_to_login", "(", "request", ".", "get_full_path", "(", ")", ")", "return", "render", "(", "request", ",", "settings", ".", "MARKDOWN_PREVIEW_TEMPLATE", ",", "dict", "(", "content", "=", "request", ".", "POST", ".", "get", "(", "'data'", ",", "'No content posted'", ")", ",", "css", "=", "settings", ".", "MARKDOWN_STYLE", ")", ")" ]
Make the vector of voltage phase guesses .
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
776
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/dc_pf.py#L115-L120
[ "def", "Copy_to_Clipboard", "(", "self", ",", "event", "=", "None", ")", ":", "bmp_obj", "=", "wx", ".", "BitmapDataObject", "(", ")", "bmp_obj", ".", "SetBitmap", "(", "self", ".", "bitmap", ")", "if", "not", "wx", ".", "TheClipboard", ".", "IsOpened", "(", ")", ":", "open_success", "=", "wx", ".", "TheClipboard", ".", "Open", "(", ")", "if", "open_success", ":", "wx", ".", "TheClipboard", ".", "SetData", "(", "bmp_obj", ")", "wx", ".", "TheClipboard", ".", "Close", "(", ")", "wx", ".", "TheClipboard", ".", "Flush", "(", ")" ]
Calculates the voltage phase angles .
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 ] # Get the susceptance matrix with the column and row corresponding to # the reference bus removed. Bpvpq = B [ pvpq_rows , pvpq_idxs ] Bref = B [ pvpq_rows , [ iref ] ] # Bus active power injections (generation - load) adjusted for phase # shifters and real shunts. 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, res, rank, s = linalg.lstsq(A.todense(), b) x = spsolve ( A , b ) # Insert the reference voltage angle of the slack bus. v_angle = r_ [ x [ : iref ] , v_angle_guess [ iref ] , x [ iref : ] ] return v_angle , Pbus [ iref ]
777
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/dc_pf.py#L126-L159
[ "def", "run", "(", "self", ",", "handler", ")", ":", "import", "eventlet", ".", "patcher", "if", "not", "eventlet", ".", "patcher", ".", "is_monkey_patched", "(", "os", ")", ":", "msg", "=", "(", "\"%s requires eventlet.monkey_patch() (before \"", "\"import)\"", "%", "self", ".", "__class__", ".", "__name__", ")", "raise", "RuntimeError", "(", "msg", ")", "# Separate out wsgi.server arguments", "wsgi_args", "=", "{", "}", "for", "arg", "in", "(", "'log'", ",", "'environ'", ",", "'max_size'", ",", "'max_http_version'", ",", "'protocol'", ",", "'server_event'", ",", "'minimum_chunk_size'", ",", "'log_x_forwarded_for'", ",", "'custom_pool'", ",", "'keepalive'", ",", "'log_output'", ",", "'log_format'", ",", "'url_length_limit'", ",", "'debug'", ",", "'socket_timeout'", ",", "'capitalize_response_headers'", ")", ":", "try", ":", "wsgi_args", "[", "arg", "]", "=", "self", ".", "options", ".", "pop", "(", "arg", ")", "except", "KeyError", ":", "pass", "if", "'log_output'", "not", "in", "wsgi_args", ":", "wsgi_args", "[", "'log_output'", "]", "=", "not", "self", ".", "quiet", "import", "eventlet", ".", "wsgi", "sock", "=", "self", ".", "options", ".", "pop", "(", "'shared_socket'", ",", "None", ")", "or", "self", ".", "get_socket", "(", ")", "eventlet", ".", "wsgi", ".", "server", "(", "sock", ",", "handler", ",", "*", "*", "wsgi_args", ")" ]
Updates the case with values computed from the voltage phase angle solution .
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 # Update Pg for swing generator. g_ref = [ g for g in case . generators if g . bus == buses [ iref ] ] [ 0 ] # Pg = Pinj + Pload + Gs # newPg = oldPg + newPinj - oldPinj p_inj = ( B [ iref , : ] * v_angle - p_ref ) * base_mva g_ref . p += p_inj [ 0 ]
778
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/dc_pf.py#L165-L192
[ "def", "friend", "(", "self", ",", "note", "=", "None", ",", "_unfriend", "=", "False", ")", ":", "self", ".", "reddit_session", ".", "evict", "(", "self", ".", "reddit_session", ".", "config", "[", "'friends'", "]", ")", "# Requests through password auth use /api/friend", "# Requests through oauth use /api/v1/me/friends/{username}", "if", "not", "self", ".", "reddit_session", ".", "is_oauth_session", "(", ")", ":", "modifier", "=", "_modify_relationship", "(", "'friend'", ",", "unlink", "=", "_unfriend", ")", "data", "=", "{", "'note'", ":", "note", "}", "if", "note", "else", "{", "}", "return", "modifier", "(", "self", ".", "reddit_session", ".", "user", ",", "self", ",", "*", "*", "data", ")", "url", "=", "self", ".", "reddit_session", ".", "config", "[", "'friend_v1'", "]", ".", "format", "(", "user", "=", "self", ".", "name", ")", "# This endpoint wants the data to be a string instead of an actual", "# dictionary, although it is not required to have any content for adds.", "# Unfriending does require the 'id' key.", "if", "_unfriend", ":", "data", "=", "{", "'id'", ":", "self", ".", "name", "}", "else", ":", "# We cannot send a null or empty note string.", "data", "=", "{", "'note'", ":", "note", "}", "if", "note", "else", "{", "}", "data", "=", "dumps", "(", "data", ")", "method", "=", "'DELETE'", "if", "_unfriend", "else", "'PUT'", "return", "self", ".", "reddit_session", ".", "request_json", "(", "url", ",", "data", "=", "data", ",", "method", "=", "method", ")" ]
Returns the net complex bus power injection vector in p . u .
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
779
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L270-L275
[ "def", "DeleteNotifications", "(", "self", ",", "session_ids", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "not", "session_ids", ":", "return", "for", "session_id", "in", "session_ids", ":", "if", "not", "isinstance", "(", "session_id", ",", "rdfvalue", ".", "SessionID", ")", ":", "raise", "RuntimeError", "(", "\"Can only delete notifications for rdfvalue.SessionIDs.\"", ")", "if", "start", "is", "None", ":", "start", "=", "0", "else", ":", "start", "=", "int", "(", "start", ")", "if", "end", "is", "None", ":", "end", "=", "self", ".", "frozen_timestamp", "or", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")", "for", "queue", ",", "ids", "in", "iteritems", "(", "collection", ".", "Group", "(", "session_ids", ",", "lambda", "session_id", ":", "session_id", ".", "Queue", "(", ")", ")", ")", ":", "queue_shards", "=", "self", ".", "GetAllNotificationShards", "(", "queue", ")", "self", ".", "data_store", ".", "DeleteNotifications", "(", "queue_shards", ",", "ids", ",", "start", ",", "end", ")" ]
Reorders the list of generators according to bus index .
def sort_generators ( self ) : self . generators . sort ( key = lambda gn : gn . bus . _i )
780
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L280-L283
[ "def", "display", "(", "self", ",", "image", ")", ":", "assert", "(", "image", ".", "size", "==", "self", ".", "size", ")", "self", ".", "_last_image", "=", "image", "image", "=", "self", ".", "preprocess", "(", "image", ")", "surface", "=", "self", ".", "to_surface", "(", "image", ",", "alpha", "=", "self", ".", "_contrast", ")", "rawbytes", "=", "self", ".", "_pygame", ".", "image", ".", "tostring", "(", "surface", ",", "\"RGB\"", ",", "False", ")", "im", "=", "Image", ".", "frombytes", "(", "\"RGB\"", ",", "surface", ".", "get_size", "(", ")", ",", "rawbytes", ")", "self", ".", "_images", ".", "append", "(", "im", ")", "self", ".", "_count", "+=", "1", "logger", ".", "debug", "(", "\"Recording frame: {0}\"", ".", "format", "(", "self", ".", "_count", ")", ")", "if", "self", ".", "_max_frames", "and", "self", ".", "_count", ">=", "self", ".", "_max_frames", ":", "sys", ".", "exit", "(", "0", ")" ]
Updates the indices of all buses .
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
781
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L289-L297
[ "def", "rmarkdown_draft", "(", "filename", ",", "template", ",", "package", ")", ":", "if", "file_exists", "(", "filename", ")", ":", "return", "filename", "draft_template", "=", "Template", "(", "'rmarkdown::draft(\"$filename\", template=\"$template\", package=\"$package\", edit=FALSE)'", ")", "draft_string", "=", "draft_template", ".", "substitute", "(", "filename", "=", "filename", ",", "template", "=", "template", ",", "package", "=", "package", ")", "report_dir", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "rcmd", "=", "Rscript_cmd", "(", ")", "with", "chdir", "(", "report_dir", ")", ":", "do", ".", "run", "(", "[", "rcmd", ",", "\"--no-environ\"", ",", "\"-e\"", ",", "draft_string", "]", ",", "\"Creating bcbioRNASeq quality control template.\"", ")", "do", ".", "run", "(", "[", "\"sed\"", ",", "\"-i\"", ",", "\"s/YYYY-MM-DD\\///g\"", ",", "filename", "]", ",", "\"Editing bcbioRNAseq quality control template.\"", ")", "return", "filename" ]
Updates the indices of all branches .
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
782
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L300-L308
[ "def", "read_avro", "(", "file_path_or_buffer", ",", "schema", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "file_path_or_buffer", ",", "six", ".", "string_types", ")", ":", "with", "open", "(", "file_path_or_buffer", ",", "'rb'", ")", "as", "f", ":", "return", "__file_to_dataframe", "(", "f", ",", "schema", ",", "*", "*", "kwargs", ")", "else", ":", "return", "__file_to_dataframe", "(", "file_path_or_buffer", ",", "schema", ",", "*", "*", "kwargs", ")" ]
Returns the total complex power generation capacity .
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
783
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L314-L323
[ "def", "DeleteNotifications", "(", "self", ",", "session_ids", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "not", "session_ids", ":", "return", "for", "session_id", "in", "session_ids", ":", "if", "not", "isinstance", "(", "session_id", ",", "rdfvalue", ".", "SessionID", ")", ":", "raise", "RuntimeError", "(", "\"Can only delete notifications for rdfvalue.SessionIDs.\"", ")", "if", "start", "is", "None", ":", "start", "=", "0", "else", ":", "start", "=", "int", "(", "start", ")", "if", "end", "is", "None", ":", "end", "=", "self", ".", "frozen_timestamp", "or", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")", "for", "queue", ",", "ids", "in", "iteritems", "(", "collection", ".", "Group", "(", "session_ids", ",", "lambda", "session_id", ":", "session_id", ".", "Queue", "(", ")", ")", ")", ":", "queue_shards", "=", "self", ".", "GetAllNotificationShards", "(", "queue", ")", "self", ".", "data_store", ".", "DeleteNotifications", "(", "queue_shards", ",", "ids", ",", "start", ",", "end", ")" ]
Returns the total complex power demand .
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
784
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L326-L334
[ "def", "filename", "(", "self", ")", ":", "client_id", ",", "__", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "video", ".", "client_video_id", ")", "file_name", "=", "u'{name}-{language}.{format}'", ".", "format", "(", "name", "=", "client_id", ",", "language", "=", "self", ".", "language_code", ",", "format", "=", "self", ".", "file_format", ")", ".", "replace", "(", "'\\n'", ",", "' '", ")", "return", "file_name" ]
Resets the readonly variables for all of the case components .
def reset ( self ) : for bus in self . buses : bus . reset ( ) for branch in self . branches : branch . reset ( ) for generator in self . generators : generator . reset ( )
785
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L911-L919
[ "def", "register", "(", "cls", ",", "interface_type", ",", "resource_class", ")", ":", "def", "_internal", "(", "python_class", ")", ":", "if", "(", "interface_type", ",", "resource_class", ")", "in", "cls", ".", "_session_classes", ":", "logger", ".", "warning", "(", "'%s is already registered in the ResourceManager. '", "'Overwriting with %s'", "%", "(", "(", "interface_type", ",", "resource_class", ")", ",", "python_class", ")", ")", "python_class", ".", "session_type", "=", "(", "interface_type", ",", "resource_class", ")", "cls", ".", "_session_classes", "[", "(", "interface_type", ",", "resource_class", ")", "]", "=", "python_class", "return", "python_class", "return", "_internal" ]
Serialize the case as a MATPOWER data file .
def save_matpower ( self , fd ) : from pylon . io import MATPOWERWriter MATPOWERWriter ( self ) . write ( fd )
786
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L925-L929
[ "async", "def", "async_delete_all_keys", "(", "session", ",", "host", ",", "port", ",", "api_key", ",", "api_keys", "=", "[", "]", ")", ":", "url", "=", "'http://{}:{}/api/{}/config'", ".", "format", "(", "host", ",", "str", "(", "port", ")", ",", "api_key", ")", "response", "=", "await", "async_request", "(", "session", ".", "get", ",", "url", ")", "api_keys", ".", "append", "(", "api_key", ")", "for", "key", "in", "response", "[", "'whitelist'", "]", ".", "keys", "(", ")", ":", "if", "key", "not", "in", "api_keys", ":", "await", "async_delete_api_key", "(", "session", ",", "host", ",", "port", ",", "key", ")" ]
Returns a case object from the given PSAT data file .
def load_psat ( cls , fd ) : from pylon . io . psat import PSATReader return PSATReader ( ) . read ( fd )
787
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L960-L964
[ "def", "validate", "(", "self", ")", ":", "if", "not", "self", ".", "start", ":", "raise", "ValueError", "(", "\"Event has no start date\"", ")", "if", "not", "self", ".", "end", ":", "raise", "ValueError", "(", "\"Event has no end date\"", ")", "if", "self", ".", "end", "<", "self", ".", "start", ":", "raise", "ValueError", "(", "\"Start date is after end date\"", ")", "if", "self", ".", "reminder_minutes_before_start", "and", "not", "isinstance", "(", "self", ".", "reminder_minutes_before_start", ",", "int", ")", ":", "raise", "TypeError", "(", "\"reminder_minutes_before_start must be of type int\"", ")", "if", "self", ".", "is_all_day", "and", "not", "isinstance", "(", "self", ".", "is_all_day", ",", "bool", ")", ":", "raise", "TypeError", "(", "\"is_all_day must be of type bool\"", ")" ]
Save a reStructuredText representation of the case .
def save_rst ( self , fd ) : from pylon . io import ReSTWriter ReSTWriter ( self ) . write ( fd )
788
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L967-L971
[ "def", "bootstrap_from_webapi", "(", "self", ",", "cellid", "=", "0", ")", ":", "self", ".", "_LOG", ".", "debug", "(", "\"Attempting bootstrap via WebAPI\"", ")", "from", "steam", "import", "webapi", "try", ":", "resp", "=", "webapi", ".", "get", "(", "'ISteamDirectory'", ",", "'GetCMList'", ",", "1", ",", "params", "=", "{", "'cellid'", ":", "cellid", "}", ")", "except", "Exception", "as", "exp", ":", "self", ".", "_LOG", ".", "error", "(", "\"WebAPI boostrap failed: %s\"", "%", "str", "(", "exp", ")", ")", "return", "False", "result", "=", "EResult", "(", "resp", "[", "'response'", "]", "[", "'result'", "]", ")", "if", "result", "!=", "EResult", ".", "OK", ":", "self", ".", "_LOG", ".", "error", "(", "\"GetCMList failed with %s\"", "%", "repr", "(", "result", ")", ")", "return", "False", "serverlist", "=", "resp", "[", "'response'", "]", "[", "'serverlist'", "]", "self", ".", "_LOG", ".", "debug", "(", "\"Recieved %d servers from WebAPI\"", "%", "len", "(", "serverlist", ")", ")", "def", "str_to_tuple", "(", "serveraddr", ")", ":", "ip", ",", "port", "=", "serveraddr", ".", "split", "(", "':'", ")", "return", "str", "(", "ip", ")", ",", "int", "(", "port", ")", "self", ".", "clear", "(", ")", "self", ".", "merge_list", "(", "map", "(", "str_to_tuple", ",", "serverlist", ")", ")", "return", "True" ]
Saves the case as a series of Comma - Separated Values .
def save_csv ( self , fd ) : from pylon . io . excel import CSVWriter CSVWriter ( self ) . write ( fd )
789
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L974-L978
[ "def", "GetIndex", "(", "self", ")", ":", "if", "self", ".", "index", "is", "None", ":", "return", "None", "if", "self", ".", "index", ":", "res", ",", "ui", "=", "chmlib", ".", "chm_resolve_object", "(", "self", ".", "file", ",", "self", ".", "index", ")", "if", "(", "res", "!=", "chmlib", ".", "CHM_RESOLVE_SUCCESS", ")", ":", "return", "None", "size", ",", "text", "=", "chmlib", ".", "chm_retrieve_object", "(", "self", ".", "file", ",", "ui", ",", "0l", ",", "ui", ".", "length", ")", "if", "(", "size", "==", "0", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'GetIndex: file size = 0\\n'", ")", "return", "None", "return", "text" ]
Saves the case as an Excel spreadsheet .
def save_excel ( self , fd ) : from pylon . io . excel import ExcelWriter ExcelWriter ( self ) . write ( fd )
790
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L981-L985
[ "def", "_strip_ctype", "(", "name", ",", "ctype", ",", "protocol", "=", "2", ")", ":", "# parse channel type from name (e.g. 'L1:GDS-CALIB_STRAIN,reduced')", "try", ":", "name", ",", "ctypestr", "=", "name", ".", "rsplit", "(", "','", ",", "1", ")", "except", "ValueError", ":", "pass", "else", ":", "ctype", "=", "Nds2ChannelType", ".", "find", "(", "ctypestr", ")", ".", "value", "# NDS1 stores channels with trend suffix, so we put it back:", "if", "protocol", "==", "1", "and", "ctype", "in", "(", "Nds2ChannelType", ".", "STREND", ".", "value", ",", "Nds2ChannelType", ".", "MTREND", ".", "value", ")", ":", "name", "+=", "',{0}'", ".", "format", "(", "ctypestr", ")", "return", "name", ",", "ctype" ]
Saves a representation of the case in the Graphviz DOT language .
def save_dot ( self , fd ) : from pylon . io import DotWriter DotWriter ( self ) . write ( fd )
791
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L988-L992
[ "def", "_sync", "(", "self", ")", ":", "if", "(", "self", ".", "_opcount", ">", "self", ".", "checkpoint_operations", "or", "datetime", ".", "now", "(", ")", ">", "self", ".", "_last_sync", "+", "self", ".", "checkpoint_timeout", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Synchronizing queue metadata.\"", ")", "self", ".", "queue_metadata", ".", "sync", "(", ")", "self", ".", "_last_sync", "=", "datetime", ".", "now", "(", ")", "self", ".", "_opcount", "=", "0", "else", ":", "self", ".", "log", ".", "debug", "(", "\"NOT synchronizing queue metadata.\"", ")" ]
Runs a power flow
def solve ( self ) : # Zero result attributes. self . case . reset ( ) # Retrieve the contents of the case. b , l , g , _ , _ , _ , _ = self . _unpack_case ( self . case ) # Update bus indexes. self . case . index_buses ( b ) # Index buses accoding to type. # try: # _, pq, pv, pvpq = self._index_buses(b) # except SlackBusError: # logger.error("Swing bus required for DCPF.") # return {"converged": False} refs , pq , pv , pvpq = self . _index_buses ( b ) if len ( refs ) != 1 : logger . error ( "Swing bus required for DCPF." ) return { "converged" : False } # Start the clock. t0 = time ( ) # Build the vector of initial complex bus voltages. V0 = self . _initial_voltage ( b , g ) # Save index and angle of original reference bus. # if self.qlimit: # ref0 = ref # Varef0 = b[ref0].Va # # List of buses at Q limits. # limits = [] # # Qg of generators at Q limits. # fixedQg = matrix(0.0, (g.size[0], 1)) repeat = True while repeat : # Build admittance matrices. Ybus , Yf , Yt = self . case . getYbus ( b , l ) # Compute complex bus power injections (generation - load). Sbus = self . case . getSbus ( b ) # Run the power flow. V , converged , i = self . _run_power_flow ( Ybus , Sbus , V0 , pv , pq , pvpq ) # Update case with solution. self . case . pf_solution ( Ybus , Yf , Yt , V ) # Enforce generator Q limits. 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 }
792
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/ac_pf.py#L94-L166
[ "def", "_index_audio_cmu", "(", "self", ",", "basename", "=", "None", ",", "replace_already_indexed", "=", "False", ")", ":", "self", ".", "_prepare_audio", "(", "basename", "=", "basename", ",", "replace_already_indexed", "=", "replace_already_indexed", ")", "for", "staging_audio_basename", "in", "self", ".", "_list_audio_files", "(", "sub_dir", "=", "\"staging\"", ")", ":", "original_audio_name", "=", "''", ".", "join", "(", "staging_audio_basename", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "[", ":", "-", "3", "]", "pocketsphinx_command", "=", "''", ".", "join", "(", "[", "\"pocketsphinx_continuous\"", ",", "\"-infile\"", ",", "str", "(", "\"{}/staging/{}\"", ".", "format", "(", "self", ".", "src_dir", ",", "staging_audio_basename", ")", ")", ",", "\"-time\"", ",", "\"yes\"", ",", "\"-logfn\"", ",", "\"/dev/null\"", "]", ")", "try", ":", "if", "self", ".", "get_verbosity", "(", ")", ":", "print", "(", "\"Now indexing {}\"", ".", "format", "(", "staging_audio_basename", ")", ")", "output", "=", "subprocess", ".", "check_output", "(", "[", "\"pocketsphinx_continuous\"", ",", "\"-infile\"", ",", "str", "(", "\"{}/staging/{}\"", ".", "format", "(", "self", ".", "src_dir", ",", "staging_audio_basename", ")", ")", ",", "\"-time\"", ",", "\"yes\"", ",", "\"-logfn\"", ",", "\"/dev/null\"", "]", ",", "universal_newlines", "=", "True", ")", ".", "split", "(", "'\\n'", ")", "str_timestamps_with_sil_conf", "=", "list", "(", "map", "(", "lambda", "x", ":", "x", ".", "split", "(", "\" \"", ")", ",", "filter", "(", "None", ",", "output", "[", "1", ":", "]", ")", ")", ")", "# Timestamps are putted in a list of a single element. To match", "# Watson's output.", "self", ".", "__timestamps_unregulated", "[", "original_audio_name", "+", "\".wav\"", "]", "=", "[", "(", "self", ".", "_timestamp_extractor_cmu", "(", "staging_audio_basename", ",", "str_timestamps_with_sil_conf", ")", ")", "]", "if", "self", ".", "get_verbosity", "(", ")", ":", "print", "(", "\"Done indexing {}\"", ".", "format", "(", "staging_audio_basename", ")", ")", "except", "OSError", "as", "e", ":", "if", "self", ".", "get_verbosity", "(", ")", ":", "print", "(", "e", ",", "\"The command was: {}\"", ".", "format", "(", "pocketsphinx_command", ")", ")", "self", ".", "__errors", "[", "(", "time", "(", ")", ",", "staging_audio_basename", ")", "]", "=", "e", "self", ".", "_timestamp_regulator", "(", ")", "if", "self", ".", "get_verbosity", "(", ")", ":", "print", "(", "\"Finished indexing procedure\"", ")" ]
Returns the contents of the case to be used in the OPF .
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
793
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/ac_pf.py#L169-L180
[ "def", "clear_key_before", "(", "self", ",", "key", ",", "namespace", "=", "None", ",", "timestamp", "=", "None", ")", ":", "block_size", "=", "self", ".", "config", ".", "block_size", "if", "namespace", "is", "None", ":", "namespace", "=", "self", ".", "config", ".", "namespace", "if", "timestamp", "is", "not", "None", ":", "offset", ",", "remainder", "=", "divmod", "(", "timestamp", ",", "block_size", ")", "if", "remainder", ":", "raise", "ValueError", "(", "'timestamp must be on a block boundary'", ")", "if", "offset", "==", "0", ":", "raise", "ValueError", "(", "'cannot delete before offset zero'", ")", "offset", "-=", "1", "self", ".", "driver", ".", "clear_key_before", "(", "key", ",", "namespace", ",", "offset", ",", "timestamp", ")", "else", ":", "self", ".", "driver", ".", "clear_key_before", "(", "key", ",", "namespace", ")" ]
Set up indexing for updating v .
def _index_buses ( self , buses ) : refs = [ bus . _i for bus in buses if bus . type == REFERENCE ] # if len(refs) != 1: # raise SlackBusError 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
794
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/ac_pf.py#L183-L193
[ "def", "get_welcome_response", "(", ")", ":", "session_attributes", "=", "{", "}", "card_title", "=", "\"Welcome\"", "speech_output", "=", "\"Welcome to the Alexa Skills Kit sample. \"", "\"Please tell me your favorite color by saying, \"", "\"my favorite color is red\"", "# If the user either does not reply to the welcome message or says something", "# that is not understood, they will be prompted again with this text.", "reprompt_text", "=", "\"Please tell me your favorite color by saying, \"", "\"my favorite color is red.\"", "should_end_session", "=", "False", "return", "build_response", "(", "session_attributes", ",", "build_speechlet_response", "(", "card_title", ",", "speech_output", ",", "reprompt_text", ",", "should_end_session", ")", ")" ]
Returns the initial vector of complex bus voltages .
def _initial_voltage ( self , buses , generators ) : Vm = array ( [ bus . v_magnitude for bus in buses ] ) # Initial bus voltage angles in radians. Va = array ( [ bus . v_angle * ( pi / 180.0 ) for bus in buses ] ) V = Vm * exp ( 1j * Va ) # Get generator set points. for g in generators : i = g . bus . _i V [ i ] = g . v_magnitude / abs ( V [ i ] ) * V [ i ] return V
795
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/ac_pf.py#L196-L216
[ "def", "__expire_files", "(", "self", ")", ":", "self", ".", "__files", "=", "OrderedDict", "(", "item", "for", "item", "in", "self", ".", "__files", ".", "items", "(", ")", "if", "not", "item", "[", "1", "]", ".", "expired", ")" ]
Performs one Newton iteration .
def _one_iteration ( self , F , Ybus , V , Vm , Va , pv , pq , pvpq ) : J = self . _build_jacobian ( Ybus , V , pv , pq , pvpq ) # Update step. dx = - 1 * spsolve ( J , F ) # dx = -1 * linalg.lstsq(J.todense(), F)[0] # Update voltage vector. 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 ) # Avoid wrapped round negative Vm. Va = angle ( V ) return V , Vm , Va
796
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/ac_pf.py#L265-L287
[ "def", "_MakeTimestamp", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "mysql_unsigned_bigint_max", "=", "18446744073709551615", "ts_start", "=", "int", "(", "start", "or", "0", ")", "if", "end", "is", "None", ":", "ts_end", "=", "mysql_unsigned_bigint_max", "else", ":", "ts_end", "=", "int", "(", "end", ")", "if", "ts_start", "==", "0", "and", "ts_end", "==", "mysql_unsigned_bigint_max", ":", "return", "None", "else", ":", "return", "(", "ts_start", ",", "ts_end", ")" ]
Returns the Jacobian matrix .
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
797
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/ac_pf.py#L325-L344
[ "def", "_sim_texture", "(", "r1", ",", "r2", ")", ":", "return", "sum", "(", "[", "min", "(", "a", ",", "b", ")", "for", "a", ",", "b", "in", "zip", "(", "r1", "[", "\"hist_t\"", "]", ",", "r2", "[", "\"hist_t\"", "]", ")", "]", ")" ]
Evaluates the mismatch .
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
798
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/ac_pf.py#L444-L452
[ "def", "download_supplementary_files", "(", "self", ",", "directory", "=", "'series'", ",", "download_sra", "=", "True", ",", "email", "=", "None", ",", "sra_kwargs", "=", "None", ",", "nproc", "=", "1", ")", ":", "if", "sra_kwargs", "is", "None", ":", "sra_kwargs", "=", "dict", "(", ")", "if", "directory", "==", "'series'", ":", "dirpath", "=", "os", ".", "path", ".", "abspath", "(", "self", ".", "get_accession", "(", ")", "+", "\"_Supp\"", ")", "utils", ".", "mkdir_p", "(", "dirpath", ")", "else", ":", "dirpath", "=", "os", ".", "path", ".", "abspath", "(", "directory", ")", "utils", ".", "mkdir_p", "(", "dirpath", ")", "downloaded_paths", "=", "dict", "(", ")", "if", "nproc", "==", "1", ":", "# No need to parallelize, running ordinary download in loop", "downloaded_paths", "=", "dict", "(", ")", "for", "gsm", "in", "itervalues", "(", "self", ".", "gsms", ")", ":", "logger", ".", "info", "(", "\"Downloading SRA files for %s series\\n\"", "%", "gsm", ".", "name", ")", "paths", "=", "gsm", ".", "download_supplementary_files", "(", "email", "=", "email", ",", "download_sra", "=", "download_sra", ",", "directory", "=", "dirpath", ",", "sra_kwargs", "=", "sra_kwargs", ")", "downloaded_paths", "[", "gsm", ".", "name", "]", "=", "paths", "elif", "nproc", ">", "1", ":", "# Parallelization enabled", "downloaders", "=", "list", "(", ")", "# Collecting params for Pool.map in a loop", "for", "gsm", "in", "itervalues", "(", "self", ".", "gsms", ")", ":", "downloaders", ".", "append", "(", "[", "gsm", ",", "download_sra", ",", "email", ",", "dirpath", ",", "sra_kwargs", "]", ")", "p", "=", "Pool", "(", "nproc", ")", "results", "=", "p", ".", "map", "(", "_supplementary_files_download_worker", ",", "downloaders", ")", "downloaded_paths", "=", "dict", "(", "results", ")", "else", ":", "raise", "ValueError", "(", "\"Nproc should be non-negative: %s\"", "%", "str", "(", "nproc", ")", ")", "return", "downloaded_paths" ]
Performs a P iteration updates Va .
def _p_iteration ( self , P , Bp_solver , Vm , Va , pvpq ) : dVa = - Bp_solver . solve ( P ) # Update voltage. Va [ pvpq ] = Va [ pvpq ] + dVa V = Vm * exp ( 1j * Va ) return V , Vm , Va
799
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/ac_pf.py#L479-L488
[ "def", "read", "(", "self", ",", "timeout", "=", "READ_TIMEOUT", ",", "raw", "=", "False", ")", ":", "time", ".", "sleep", "(", "READ_SLEEP_TIME", ")", "raw_out", "=", "self", ".", "ser", ".", "read", "(", "self", ".", "ser", ".", "in_waiting", ")", "out", "=", "raw_out", ".", "decode", "(", "OUTPUT_ENCODING", ")", "time_waiting", "=", "0", "while", "len", "(", "out", ")", "==", "0", "or", "ending_in", "(", "out", ".", "strip", "(", "OUTPUT_STRIP_CHARS", ")", ",", "RESPONSE_END_WORDS", ")", "is", "None", ":", "time", ".", "sleep", "(", "READ_SLEEP_TIME", ")", "time_waiting", "+=", "READ_SLEEP_TIME", "raw_out", "+=", "self", ".", "ser", ".", "read", "(", "self", ".", "ser", ".", "in_waiting", ")", "out", "=", "raw_out", ".", "decode", "(", "OUTPUT_ENCODING", ")", "# TODO how to handle timeouts, if they're now unexpected?", "if", "time_waiting", ">=", "timeout", ":", "break", "if", "raw", ":", "return", "raw_out", "return", "out" ]