sequence
stringlengths 546
16.2k
| code
stringlengths 108
19.3k
|
---|---|
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:greedy_max_inden_setcover; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:candidate_sets_dict; 5, identifier:items; 6, default_parameter; 6, 7; 6, 8; 7, identifier:max_covers; 8, None; 9, block; 9, 10; 9, 12; 9, 19; 9, 25; 9, 31; 9, 35; 9, 160; 9, 167; 9, 174; 10, expression_statement; 10, 11; 11, comment; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:uncovered_set; 15, call; 15, 16; 15, 17; 16, identifier:set; 17, argument_list; 17, 18; 18, identifier:items; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:rejected_keys; 22, call; 22, 23; 22, 24; 23, identifier:set; 24, argument_list; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:accepted_keys; 28, call; 28, 29; 28, 30; 29, identifier:set; 30, argument_list; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:covered_items_list; 34, list:[]; 35, while_statement; 35, 36; 35, 37; 35, 38; 36, True; 37, comment; 38, block; 38, 39; 38, 52; 38, 56; 38, 61; 38, 62; 38, 122; 38, 123; 38, 129; 38, 135; 38, 142; 38, 152; 38, 153; 39, if_statement; 39, 40; 39, 50; 40, boolean_operator:and; 40, 41; 40, 44; 41, comparison_operator:is; 41, 42; 41, 43; 42, identifier:max_covers; 43, None; 44, comparison_operator:>=; 44, 45; 44, 49; 45, call; 45, 46; 45, 47; 46, identifier:len; 47, argument_list; 47, 48; 48, identifier:covered_items_list; 49, identifier:max_covers; 50, block; 50, 51; 51, break_statement; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:maxkey; 55, None; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:maxlen; 59, unary_operator:-; 59, 60; 60, integer:1; 61, comment; 62, for_statement; 62, 63; 62, 66; 62, 72; 63, pattern_list; 63, 64; 63, 65; 64, identifier:key; 65, identifier:candidate_items; 66, call; 66, 67; 66, 70; 67, attribute; 67, 68; 67, 69; 68, identifier:six; 69, identifier:iteritems; 70, argument_list; 70, 71; 71, identifier:candidate_sets_dict; 72, block; 72, 73; 72, 83; 72, 84; 72, 91; 72, 92; 73, if_statement; 73, 74; 73, 81; 74, boolean_operator:or; 74, 75; 74, 78; 75, comparison_operator:in; 75, 76; 75, 77; 76, identifier:key; 77, identifier:rejected_keys; 78, comparison_operator:in; 78, 79; 78, 80; 79, identifier:key; 80, identifier:accepted_keys; 81, block; 81, 82; 82, continue_statement; 83, comment; 84, expression_statement; 84, 85; 85, assignment; 85, 86; 85, 87; 86, identifier:lenval; 87, call; 87, 88; 87, 89; 88, identifier:len; 89, argument_list; 89, 90; 90, identifier:candidate_items; 91, comment; 92, if_statement; 92, 93; 92, 99; 92, 113; 93, call; 93, 94; 93, 97; 94, attribute; 94, 95; 94, 96; 95, identifier:uncovered_set; 96, identifier:issuperset; 97, argument_list; 97, 98; 98, identifier:candidate_items; 99, block; 99, 100; 100, if_statement; 100, 101; 100, 104; 101, comparison_operator:>; 101, 102; 101, 103; 102, identifier:lenval; 103, identifier:maxlen; 104, block; 104, 105; 104, 109; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 108; 107, identifier:maxkey; 108, identifier:key; 109, expression_statement; 109, 110; 110, assignment; 110, 111; 110, 112; 111, identifier:maxlen; 112, identifier:lenval; 113, else_clause; 113, 114; 114, block; 114, 115; 115, expression_statement; 115, 116; 116, call; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:rejected_keys; 119, identifier:add; 120, argument_list; 120, 121; 121, identifier:key; 122, comment; 123, if_statement; 123, 124; 123, 127; 124, comparison_operator:is; 124, 125; 124, 126; 125, identifier:maxkey; 126, None; 127, block; 127, 128; 128, break_statement; 129, expression_statement; 129, 130; 130, assignment; 130, 131; 130, 132; 131, identifier:maxval; 132, subscript; 132, 133; 132, 134; 133, identifier:candidate_sets_dict; 134, identifier:maxkey; 135, expression_statement; 135, 136; 136, call; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:accepted_keys; 139, identifier:add; 140, argument_list; 140, 141; 141, identifier:maxkey; 142, expression_statement; 142, 143; 143, call; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:covered_items_list; 146, identifier:append; 147, argument_list; 147, 148; 148, call; 148, 149; 148, 150; 149, identifier:list; 150, argument_list; 150, 151; 151, identifier:maxval; 152, comment; 153, expression_statement; 153, 154; 154, call; 154, 155; 154, 158; 155, attribute; 155, 156; 155, 157; 156, identifier:uncovered_set; 157, identifier:difference_update; 158, argument_list; 158, 159; 159, identifier:maxval; 160, expression_statement; 160, 161; 161, assignment; 161, 162; 161, 163; 162, identifier:uncovered_items; 163, call; 163, 164; 163, 165; 164, identifier:list; 165, argument_list; 165, 166; 166, identifier:uncovered_set; 167, expression_statement; 167, 168; 168, assignment; 168, 169; 168, 170; 169, identifier:covertup; 170, expression_list; 170, 171; 170, 172; 170, 173; 171, identifier:uncovered_items; 172, identifier:covered_items_list; 173, identifier:accepted_keys; 174, return_statement; 174, 175; 175, identifier:covertup | def greedy_max_inden_setcover(candidate_sets_dict, items, max_covers=None):
"""
greedy algorithm for maximum independent set cover
Covers items with sets from candidate sets. Could be made faster.
CommandLine:
python -m utool.util_alg --test-greedy_max_inden_setcover
Example0:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> candidate_sets_dict = {'a': [5, 3], 'b': [2, 3, 5],
... 'c': [4, 8], 'd': [7, 6, 2, 1]}
>>> items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> max_covers = None
>>> tup = greedy_max_inden_setcover(candidate_sets_dict, items, max_covers)
>>> (uncovered_items, covered_items_list, accepted_keys) = tup
>>> result = ut.repr4((uncovered_items, sorted(list(accepted_keys))), nl=False)
>>> print(result)
([0, 9], ['a', 'c', 'd'])
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> candidate_sets_dict = {'a': [5, 3], 'b': [2, 3, 5],
... 'c': [4, 8], 'd': [7, 6, 2, 1]}
>>> items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> max_covers = 1
>>> tup = greedy_max_inden_setcover(candidate_sets_dict, items, max_covers)
>>> (uncovered_items, covered_items_list, accepted_keys) = tup
>>> result = ut.repr4((uncovered_items, sorted(list(accepted_keys))), nl=False)
>>> print(result)
([0, 3, 4, 5, 8, 9], ['d'])
"""
uncovered_set = set(items)
rejected_keys = set()
accepted_keys = set()
covered_items_list = []
while True:
# Break if we have enough covers
if max_covers is not None and len(covered_items_list) >= max_covers:
break
maxkey = None
maxlen = -1
# Loop over candidates to find the biggested unadded cover set
for key, candidate_items in six.iteritems(candidate_sets_dict):
if key in rejected_keys or key in accepted_keys:
continue
#print('Checking %r' % (key,))
lenval = len(candidate_items)
# len(uncovered_set.intersection(candidate_items)) == lenval:
if uncovered_set.issuperset(candidate_items):
if lenval > maxlen:
maxkey = key
maxlen = lenval
else:
rejected_keys.add(key)
# Add the set to the cover
if maxkey is None:
break
maxval = candidate_sets_dict[maxkey]
accepted_keys.add(maxkey)
covered_items_list.append(list(maxval))
# Add values in this key to the cover
uncovered_set.difference_update(maxval)
uncovered_items = list(uncovered_set)
covertup = uncovered_items, covered_items_list, accepted_keys
return covertup |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 17; 2, function_name:setcover_greedy; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 4, identifier:candidate_sets_dict; 5, default_parameter; 5, 6; 5, 7; 6, identifier:items; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:set_weights; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:item_values; 13, None; 14, default_parameter; 14, 15; 14, 16; 15, identifier:max_weight; 16, None; 17, block; 17, 18; 17, 20; 17, 25; 17, 29; 17, 30; 17, 48; 17, 79; 17, 106; 17, 118; 17, 137; 17, 138; 17, 242; 18, expression_statement; 18, 19; 19, comment; 20, import_statement; 20, 21; 21, aliased_import; 21, 22; 21, 24; 22, dotted_name; 22, 23; 23, identifier:utool; 24, identifier:ut; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:solution_cover; 28, dictionary; 29, comment; 30, if_statement; 30, 31; 30, 34; 31, comparison_operator:is; 31, 32; 31, 33; 32, identifier:items; 33, None; 34, block; 34, 35; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:items; 38, call; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:ut; 41, identifier:flatten; 42, argument_list; 42, 43; 43, call; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:candidate_sets_dict; 46, identifier:values; 47, argument_list; 48, if_statement; 48, 49; 48, 52; 48, 57; 49, comparison_operator:is; 49, 50; 49, 51; 50, identifier:set_weights; 51, None; 52, block; 52, 53; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:get_weight; 56, identifier:len; 57, else_clause; 57, 58; 58, block; 58, 59; 59, function_definition; 59, 60; 59, 61; 59, 63; 60, function_name:get_weight; 61, parameters; 61, 62; 62, identifier:solution_cover; 63, block; 63, 64; 64, expression_statement; 64, 65; 65, call; 65, 66; 65, 67; 66, identifier:sum; 67, argument_list; 67, 68; 68, list_comprehension; 68, 69; 68, 72; 69, subscript; 69, 70; 69, 71; 70, identifier:set_weights; 71, identifier:key; 72, for_in_clause; 72, 73; 72, 74; 73, identifier:key; 74, call; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, identifier:solution_cover; 77, identifier:keys; 78, argument_list; 79, if_statement; 79, 80; 79, 83; 79, 88; 80, comparison_operator:is; 80, 81; 80, 82; 81, identifier:item_values; 82, None; 83, block; 83, 84; 84, expression_statement; 84, 85; 85, assignment; 85, 86; 85, 87; 86, identifier:get_value; 87, identifier:len; 88, else_clause; 88, 89; 89, block; 89, 90; 90, function_definition; 90, 91; 90, 92; 90, 94; 91, function_name:get_value; 92, parameters; 92, 93; 93, identifier:vals; 94, block; 94, 95; 95, expression_statement; 95, 96; 96, call; 96, 97; 96, 98; 97, identifier:sum; 98, argument_list; 98, 99; 99, list_comprehension; 99, 100; 99, 103; 100, subscript; 100, 101; 100, 102; 101, identifier:item_values; 102, identifier:v; 103, for_in_clause; 103, 104; 103, 105; 104, identifier:v; 105, identifier:vals; 106, if_statement; 106, 107; 106, 110; 107, comparison_operator:is; 107, 108; 107, 109; 108, identifier:max_weight; 109, None; 110, block; 110, 111; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:max_weight; 114, call; 114, 115; 114, 116; 115, identifier:get_weight; 116, argument_list; 116, 117; 117, identifier:candidate_sets_dict; 118, expression_statement; 118, 119; 119, assignment; 119, 120; 119, 121; 120, identifier:avail_covers; 121, dictionary_comprehension; 121, 122; 121, 128; 122, pair; 122, 123; 122, 124; 123, identifier:key; 124, call; 124, 125; 124, 126; 125, identifier:set; 126, argument_list; 126, 127; 127, identifier:val; 128, for_in_clause; 128, 129; 128, 132; 129, pattern_list; 129, 130; 129, 131; 130, identifier:key; 131, identifier:val; 132, call; 132, 133; 132, 136; 133, attribute; 133, 134; 133, 135; 134, identifier:candidate_sets_dict; 135, identifier:items; 136, argument_list; 137, comment; 138, while_statement; 138, 139; 138, 152; 138, 153; 139, boolean_operator:and; 139, 140; 139, 146; 140, comparison_operator:<; 140, 141; 140, 145; 141, call; 141, 142; 141, 143; 142, identifier:get_weight; 143, argument_list; 143, 144; 144, identifier:solution_cover; 145, identifier:max_weight; 146, comparison_operator:>; 146, 147; 146, 151; 147, call; 147, 148; 147, 149; 148, identifier:len; 149, argument_list; 149, 150; 150, identifier:avail_covers; 151, integer:0; 152, comment; 153, block; 153, 154; 153, 160; 153, 175; 153, 184; 153, 193; 153, 206; 153, 207; 153, 213; 153, 221; 153, 222; 153, 223; 153, 227; 154, expression_statement; 154, 155; 155, call; 155, 156; 155, 159; 156, attribute; 156, 157; 156, 158; 157, identifier:avail_covers; 158, identifier:values; 159, argument_list; 160, expression_statement; 160, 161; 161, assignment; 161, 162; 161, 163; 162, identifier:uncovered_values; 163, call; 163, 164; 163, 165; 164, identifier:list; 165, argument_list; 165, 166; 166, call; 166, 167; 166, 168; 167, identifier:map; 168, argument_list; 168, 169; 168, 170; 169, identifier:get_value; 170, call; 170, 171; 170, 174; 171, attribute; 171, 172; 171, 173; 172, identifier:avail_covers; 173, identifier:values; 174, argument_list; 175, expression_statement; 175, 176; 176, assignment; 176, 177; 176, 178; 177, identifier:chosen_idx; 178, call; 178, 179; 178, 182; 179, attribute; 179, 180; 179, 181; 180, identifier:ut; 181, identifier:argmax; 182, argument_list; 182, 183; 183, identifier:uncovered_values; 184, if_statement; 184, 185; 184, 190; 184, 191; 185, comparison_operator:<=; 185, 186; 185, 189; 186, subscript; 186, 187; 186, 188; 187, identifier:uncovered_values; 188, identifier:chosen_idx; 189, integer:0; 190, comment; 191, block; 191, 192; 192, break_statement; 193, expression_statement; 193, 194; 194, assignment; 194, 195; 194, 196; 195, identifier:chosen_key; 196, subscript; 196, 197; 196, 205; 197, call; 197, 198; 197, 199; 198, identifier:list; 199, argument_list; 199, 200; 200, call; 200, 201; 200, 204; 201, attribute; 201, 202; 201, 203; 202, identifier:avail_covers; 203, identifier:keys; 204, argument_list; 205, identifier:chosen_idx; 206, comment; 207, expression_statement; 207, 208; 208, assignment; 208, 209; 208, 210; 209, identifier:chosen_set; 210, subscript; 210, 211; 210, 212; 211, identifier:avail_covers; 212, identifier:chosen_key; 213, expression_statement; 213, 214; 214, assignment; 214, 215; 214, 218; 215, subscript; 215, 216; 215, 217; 216, identifier:solution_cover; 217, identifier:chosen_key; 218, subscript; 218, 219; 218, 220; 219, identifier:candidate_sets_dict; 220, identifier:chosen_key; 221, comment; 222, comment; 223, delete_statement; 223, 224; 224, subscript; 224, 225; 224, 226; 225, identifier:avail_covers; 226, identifier:chosen_key; 227, for_statement; 227, 228; 227, 229; 227, 234; 228, identifier:vals; 229, call; 229, 230; 229, 233; 230, attribute; 230, 231; 230, 232; 231, identifier:avail_covers; 232, identifier:values; 233, argument_list; 234, block; 234, 235; 235, expression_statement; 235, 236; 236, call; 236, 237; 236, 240; 237, attribute; 237, 238; 237, 239; 238, identifier:vals; 239, identifier:difference_update; 240, argument_list; 240, 241; 241, identifier:chosen_set; 242, return_statement; 242, 243; 243, identifier:solution_cover | def setcover_greedy(candidate_sets_dict, items=None, set_weights=None, item_values=None, max_weight=None):
r"""
Greedy algorithm for various covering problems.
approximation gaurentees depending on specifications like set_weights and item values
Set Cover: log(len(items) + 1) approximation algorithm
Weighted Maximum Cover: 1 - 1/e == .632 approximation algorithm
Generalized maximum coverage is not implemented
References:
https://en.wikipedia.org/wiki/Maximum_coverage_problem
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> candidate_sets_dict = {
>>> 'a': [1, 2, 3, 8, 9, 0],
>>> 'b': [1, 2, 3, 4, 5],
>>> 'c': [4, 5, 7],
>>> 'd': [5, 6, 7],
>>> 'e': [6, 7, 8, 9, 0],
>>> }
>>> max_weight = None
>>> items = None
>>> set_weights = None
>>> item_values = None
>>> greedy_soln = ut.sort_dict(ut.setcover_greedy(candidate_sets_dict))
>>> exact_soln = ut.sort_dict(ut.setcover_ilp(candidate_sets_dict))
>>> print('greedy_soln = %r' % (greedy_soln,))
>>> print('exact_soln = %r' % (exact_soln,))
"""
import utool as ut
solution_cover = {}
# If candset_weights or item_values not given use the length as defaults
if items is None:
items = ut.flatten(candidate_sets_dict.values())
if set_weights is None:
get_weight = len
else:
def get_weight(solution_cover):
sum([set_weights[key] for key in solution_cover.keys()])
if item_values is None:
get_value = len
else:
def get_value(vals):
sum([item_values[v] for v in vals])
if max_weight is None:
max_weight = get_weight(candidate_sets_dict)
avail_covers = {key: set(val) for key, val in candidate_sets_dict.items()}
# While we still need covers
while get_weight(solution_cover) < max_weight and len(avail_covers) > 0:
# Find candiate set with the most uncovered items
avail_covers.values()
uncovered_values = list(map(get_value, avail_covers.values()))
chosen_idx = ut.argmax(uncovered_values)
if uncovered_values[chosen_idx] <= 0:
# needlessly adding value-less items
break
chosen_key = list(avail_covers.keys())[chosen_idx]
# Add values in this key to the cover
chosen_set = avail_covers[chosen_key]
solution_cover[chosen_key] = candidate_sets_dict[chosen_key]
# Remove chosen set from available options and covered items
# from remaining available sets
del avail_covers[chosen_key]
for vals in avail_covers.values():
vals.difference_update(chosen_set)
return solution_cover |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:get_nth_prime; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:n; 5, default_parameter; 5, 6; 5, 7; 6, identifier:max_prime; 7, integer:4100; 8, default_parameter; 8, 9; 8, 10; 9, identifier:safe; 10, True; 11, block; 11, 12; 11, 14; 11, 170; 12, expression_statement; 12, 13; 13, comment; 14, if_statement; 14, 15; 14, 18; 14, 132; 15, comparison_operator:<=; 15, 16; 15, 17; 16, identifier:n; 17, integer:100; 18, block; 18, 19; 18, 123; 18, 124; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:first_100_primes; 22, tuple; 22, 23; 22, 24; 22, 25; 22, 26; 22, 27; 22, 28; 22, 29; 22, 30; 22, 31; 22, 32; 22, 33; 22, 34; 22, 35; 22, 36; 22, 37; 22, 38; 22, 39; 22, 40; 22, 41; 22, 42; 22, 43; 22, 44; 22, 45; 22, 46; 22, 47; 22, 48; 22, 49; 22, 50; 22, 51; 22, 52; 22, 53; 22, 54; 22, 55; 22, 56; 22, 57; 22, 58; 22, 59; 22, 60; 22, 61; 22, 62; 22, 63; 22, 64; 22, 65; 22, 66; 22, 67; 22, 68; 22, 69; 22, 70; 22, 71; 22, 72; 22, 73; 22, 74; 22, 75; 22, 76; 22, 77; 22, 78; 22, 79; 22, 80; 22, 81; 22, 82; 22, 83; 22, 84; 22, 85; 22, 86; 22, 87; 22, 88; 22, 89; 22, 90; 22, 91; 22, 92; 22, 93; 22, 94; 22, 95; 22, 96; 22, 97; 22, 98; 22, 99; 22, 100; 22, 101; 22, 102; 22, 103; 22, 104; 22, 105; 22, 106; 22, 107; 22, 108; 22, 109; 22, 110; 22, 111; 22, 112; 22, 113; 22, 114; 22, 115; 22, 116; 22, 117; 22, 118; 22, 119; 22, 120; 22, 121; 22, 122; 23, integer:2; 24, integer:3; 25, integer:5; 26, integer:7; 27, integer:11; 28, integer:13; 29, integer:17; 30, integer:19; 31, integer:23; 32, integer:29; 33, integer:31; 34, integer:37; 35, integer:41; 36, integer:43; 37, integer:47; 38, integer:53; 39, integer:59; 40, integer:61; 41, integer:67; 42, integer:71; 43, integer:73; 44, integer:79; 45, integer:83; 46, integer:89; 47, integer:97; 48, integer:101; 49, integer:103; 50, integer:107; 51, integer:109; 52, integer:113; 53, integer:127; 54, integer:131; 55, integer:137; 56, integer:139; 57, integer:149; 58, integer:151; 59, integer:157; 60, integer:163; 61, integer:167; 62, integer:173; 63, integer:179; 64, integer:181; 65, integer:191; 66, integer:193; 67, integer:197; 68, integer:199; 69, integer:211; 70, integer:223; 71, integer:227; 72, integer:229; 73, integer:233; 74, integer:239; 75, integer:241; 76, integer:251; 77, integer:257; 78, integer:263; 79, integer:269; 80, integer:271; 81, integer:277; 82, integer:281; 83, integer:283; 84, integer:293; 85, integer:307; 86, integer:311; 87, integer:313; 88, integer:317; 89, integer:331; 90, integer:337; 91, integer:347; 92, integer:349; 93, integer:353; 94, integer:359; 95, integer:367; 96, integer:373; 97, integer:379; 98, integer:383; 99, integer:389; 100, integer:397; 101, integer:401; 102, integer:409; 103, integer:419; 104, integer:421; 105, integer:431; 106, integer:433; 107, integer:439; 108, integer:443; 109, integer:449; 110, integer:457; 111, integer:461; 112, integer:463; 113, integer:467; 114, integer:479; 115, integer:487; 116, integer:491; 117, integer:499; 118, integer:503; 119, integer:509; 120, integer:521; 121, integer:523; 122, integer:541; 123, comment; 124, expression_statement; 124, 125; 125, assignment; 125, 126; 125, 127; 126, identifier:nth_prime; 127, subscript; 127, 128; 127, 129; 128, identifier:first_100_primes; 129, binary_operator:-; 129, 130; 129, 131; 130, identifier:n; 131, integer:1; 132, else_clause; 132, 133; 133, block; 133, 134; 134, if_statement; 134, 135; 134, 136; 134, 160; 135, identifier:safe; 136, block; 136, 137; 136, 154; 137, expression_statement; 137, 138; 138, assignment; 138, 139; 138, 140; 139, identifier:primes; 140, list_comprehension; 140, 141; 140, 142; 140, 149; 141, identifier:num; 142, for_in_clause; 142, 143; 142, 144; 143, identifier:num; 144, call; 144, 145; 144, 146; 145, identifier:range; 146, argument_list; 146, 147; 146, 148; 147, integer:2; 148, identifier:max_prime; 149, if_clause; 149, 150; 150, call; 150, 151; 150, 152; 151, identifier:is_prime; 152, argument_list; 152, 153; 153, identifier:num; 154, expression_statement; 154, 155; 155, assignment; 155, 156; 155, 157; 156, identifier:nth_prime; 157, subscript; 157, 158; 157, 159; 158, identifier:primes; 159, identifier:n; 160, else_clause; 160, 161; 160, 162; 161, comment; 162, block; 162, 163; 163, expression_statement; 163, 164; 164, assignment; 164, 165; 164, 166; 165, identifier:nth_prime; 166, call; 166, 167; 166, 168; 167, identifier:get_nth_prime_bruteforce; 168, argument_list; 168, 169; 169, identifier:n; 170, return_statement; 170, 171; 171, identifier:nth_prime | def get_nth_prime(n, max_prime=4100, safe=True):
""" hacky but still brute force algorithm for finding nth prime for small tests """
if n <= 100:
first_100_primes = (
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,
139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277,
281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359,
367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439,
443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521,
523, 541, )
#print(len(first_100_primes))
nth_prime = first_100_primes[n - 1]
else:
if safe:
primes = [num for num in range(2, max_prime) if is_prime(num)]
nth_prime = primes[n]
else:
# This can run for a while... get it? while?
nth_prime = get_nth_prime_bruteforce(n)
return nth_prime |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:knapsack_ilp; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:items; 5, identifier:maxweight; 6, default_parameter; 6, 7; 6, 8; 7, identifier:verbose; 8, False; 9, block; 9, 10; 9, 12; 9, 15; 9, 16; 9, 26; 9, 36; 9, 46; 9, 47; 9, 59; 9, 60; 9, 87; 9, 88; 9, 110; 9, 111; 9, 136; 9, 137; 9, 138; 9, 149; 9, 150; 9, 162; 9, 181; 9, 197; 9, 198; 9, 245; 10, expression_statement; 10, 11; 11, comment; 12, import_statement; 12, 13; 13, dotted_name; 13, 14; 14, identifier:pulp; 15, comment; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:values; 19, list_comprehension; 19, 20; 19, 23; 20, subscript; 20, 21; 20, 22; 21, identifier:t; 22, integer:0; 23, for_in_clause; 23, 24; 23, 25; 24, identifier:t; 25, identifier:items; 26, expression_statement; 26, 27; 27, assignment; 27, 28; 27, 29; 28, identifier:weights; 29, list_comprehension; 29, 30; 29, 33; 30, subscript; 30, 31; 30, 32; 31, identifier:t; 32, integer:1; 33, for_in_clause; 33, 34; 33, 35; 34, identifier:t; 35, identifier:items; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:indices; 39, list_comprehension; 39, 40; 39, 43; 40, subscript; 40, 41; 40, 42; 41, identifier:t; 42, integer:2; 43, for_in_clause; 43, 44; 43, 45; 44, identifier:t; 45, identifier:items; 46, comment; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:prob; 50, call; 50, 51; 50, 54; 51, attribute; 51, 52; 51, 53; 52, identifier:pulp; 53, identifier:LpProblem; 54, argument_list; 54, 55; 54, 56; 55, string:"Knapsack"; 56, attribute; 56, 57; 56, 58; 57, identifier:pulp; 58, identifier:LpMaximize; 59, comment; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:x; 63, call; 63, 64; 63, 69; 64, attribute; 64, 65; 64, 68; 65, attribute; 65, 66; 65, 67; 66, identifier:pulp; 67, identifier:LpVariable; 68, identifier:dicts; 69, argument_list; 69, 70; 69, 73; 69, 76; 69, 79; 69, 82; 70, keyword_argument; 70, 71; 70, 72; 71, identifier:name; 72, string:'x'; 73, keyword_argument; 73, 74; 73, 75; 74, identifier:indexs; 75, identifier:indices; 76, keyword_argument; 76, 77; 76, 78; 77, identifier:lowBound; 78, integer:0; 79, keyword_argument; 79, 80; 79, 81; 80, identifier:upBound; 81, integer:1; 82, keyword_argument; 82, 83; 82, 84; 83, identifier:cat; 84, attribute; 84, 85; 84, 86; 85, identifier:pulp; 86, identifier:LpInteger; 87, comment; 88, expression_statement; 88, 89; 89, assignment; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:prob; 92, identifier:objective; 93, call; 93, 94; 93, 95; 94, identifier:sum; 95, generator_expression; 95, 96; 95, 101; 96, binary_operator:*; 96, 97; 96, 98; 97, identifier:v; 98, subscript; 98, 99; 98, 100; 99, identifier:x; 100, identifier:i; 101, for_in_clause; 101, 102; 101, 105; 102, pattern_list; 102, 103; 102, 104; 103, identifier:v; 104, identifier:i; 105, call; 105, 106; 105, 107; 106, identifier:zip; 107, argument_list; 107, 108; 107, 109; 108, identifier:values; 109, identifier:indices; 110, comment; 111, expression_statement; 111, 112; 112, call; 112, 113; 112, 116; 113, attribute; 113, 114; 113, 115; 114, identifier:prob; 115, identifier:add; 116, argument_list; 116, 117; 117, comparison_operator:<=; 117, 118; 117, 135; 118, call; 118, 119; 118, 120; 119, identifier:sum; 120, generator_expression; 120, 121; 120, 126; 121, binary_operator:*; 121, 122; 121, 123; 122, identifier:w; 123, subscript; 123, 124; 123, 125; 124, identifier:x; 125, identifier:i; 126, for_in_clause; 126, 127; 126, 130; 127, pattern_list; 127, 128; 127, 129; 128, identifier:w; 129, identifier:i; 130, call; 130, 131; 130, 132; 131, identifier:zip; 132, argument_list; 132, 133; 132, 134; 133, identifier:weights; 134, identifier:indices; 135, identifier:maxweight; 136, comment; 137, comment; 138, expression_statement; 138, 139; 139, call; 139, 140; 139, 147; 140, attribute; 140, 141; 140, 146; 141, call; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, identifier:pulp; 144, identifier:PULP_CBC_CMD; 145, argument_list; 146, identifier:solve; 147, argument_list; 147, 148; 148, identifier:prob; 149, comment; 150, expression_statement; 150, 151; 151, assignment; 151, 152; 151, 153; 152, identifier:flags; 153, list_comprehension; 153, 154; 153, 159; 154, attribute; 154, 155; 154, 158; 155, subscript; 155, 156; 155, 157; 156, identifier:x; 157, identifier:i; 158, identifier:varValue; 159, for_in_clause; 159, 160; 159, 161; 160, identifier:i; 161, identifier:indices; 162, expression_statement; 162, 163; 163, assignment; 163, 164; 163, 165; 164, identifier:total_value; 165, call; 165, 166; 165, 167; 166, identifier:sum; 167, argument_list; 167, 168; 168, list_comprehension; 168, 169; 168, 170; 168, 179; 169, identifier:val; 170, for_in_clause; 170, 171; 170, 174; 171, pattern_list; 171, 172; 171, 173; 172, identifier:val; 173, identifier:flag; 174, call; 174, 175; 174, 176; 175, identifier:zip; 176, argument_list; 176, 177; 176, 178; 177, identifier:values; 178, identifier:flags; 179, if_clause; 179, 180; 180, identifier:flag; 181, expression_statement; 181, 182; 182, assignment; 182, 183; 182, 184; 183, identifier:items_subset; 184, list_comprehension; 184, 185; 184, 186; 184, 195; 185, identifier:item; 186, for_in_clause; 186, 187; 186, 190; 187, pattern_list; 187, 188; 187, 189; 188, identifier:item; 189, identifier:flag; 190, call; 190, 191; 190, 192; 191, identifier:zip; 192, argument_list; 192, 193; 192, 194; 193, identifier:items; 194, identifier:flags; 195, if_clause; 195, 196; 196, identifier:flag; 197, comment; 198, if_statement; 198, 199; 198, 200; 199, identifier:verbose; 200, block; 200, 201; 200, 206; 200, 211; 200, 237; 201, expression_statement; 201, 202; 202, call; 202, 203; 202, 204; 203, identifier:print; 204, argument_list; 204, 205; 205, identifier:prob; 206, expression_statement; 206, 207; 207, call; 207, 208; 207, 209; 208, identifier:print; 209, argument_list; 209, 210; 210, string:'OPT:'; 211, expression_statement; 211, 212; 212, call; 212, 213; 212, 214; 213, identifier:print; 214, argument_list; 214, 215; 215, call; 215, 216; 215, 219; 216, attribute; 216, 217; 216, 218; 217, string:'\n'; 218, identifier:join; 219, argument_list; 219, 220; 220, list_comprehension; 220, 221; 220, 234; 221, binary_operator:%; 221, 222; 221, 223; 222, string:' %s = %s'; 223, tuple; 223, 224; 223, 229; 224, attribute; 224, 225; 224, 228; 225, subscript; 225, 226; 225, 227; 226, identifier:x; 227, identifier:i; 228, identifier:name; 229, attribute; 229, 230; 229, 233; 230, subscript; 230, 231; 230, 232; 231, identifier:x; 232, identifier:i; 233, identifier:varValue; 234, for_in_clause; 234, 235; 234, 236; 235, identifier:i; 236, identifier:indices; 237, expression_statement; 237, 238; 238, call; 238, 239; 238, 240; 239, identifier:print; 240, argument_list; 240, 241; 241, binary_operator:%; 241, 242; 241, 243; 242, string:'total_value = %r'; 243, tuple; 243, 244; 244, identifier:total_value; 245, return_statement; 245, 246; 246, expression_list; 246, 247; 246, 248; 247, identifier:total_value; 248, identifier:items_subset | def knapsack_ilp(items, maxweight, verbose=False):
"""
solves knapsack using an integer linear program
CommandLine:
python -m utool.util_alg knapsack_ilp
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> # Solve https://xkcd.com/287/
>>> weights = [2.15, 2.75, 3.35, 3.55, 4.2, 5.8, 6.55]
>>> values = [2.15, 2.75, 3.35, 3.55, 4.2, 5.8, 6.55]
>>> indices = ['mixed fruit', 'french fries', 'side salad',
>>> 'hot wings', 'mozzarella sticks', 'sampler plate',
>>> 'barbecue']
>>> items = [(v, w, i) for v, w, i in zip(values, weights, indices)]
>>> #items += [(3.95, 3.95, 'mystery plate')]
>>> maxweight = 15.05
>>> verbose = True
>>> total_value, items_subset = knapsack_ilp(items, maxweight, verbose)
>>> print('items_subset = %s' % (ut.repr3(items_subset, nl=1),))
"""
import pulp
# Given Input
values = [t[0] for t in items]
weights = [t[1] for t in items]
indices = [t[2] for t in items]
# Formulate integer program
prob = pulp.LpProblem("Knapsack", pulp.LpMaximize)
# Solution variables
x = pulp.LpVariable.dicts(name='x', indexs=indices,
lowBound=0, upBound=1, cat=pulp.LpInteger)
# maximize objective function
prob.objective = sum(v * x[i] for v, i in zip(values, indices))
# subject to
prob.add(sum(w * x[i] for w, i in zip(weights, indices)) <= maxweight)
# Solve using with solver like CPLEX, GLPK, or SCIP.
#pulp.CPLEX().solve(prob)
pulp.PULP_CBC_CMD().solve(prob)
# Read solution
flags = [x[i].varValue for i in indices]
total_value = sum([val for val, flag in zip(values, flags) if flag])
items_subset = [item for item, flag in zip(items, flags) if flag]
# Print summary
if verbose:
print(prob)
print('OPT:')
print('\n'.join([' %s = %s' % (x[i].name, x[i].varValue) for i in indices]))
print('total_value = %r' % (total_value,))
return total_value, items_subset |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:knapsack_iterative_int; 3, parameters; 3, 4; 3, 5; 4, identifier:items; 5, identifier:maxweight; 6, block; 6, 7; 6, 9; 6, 19; 6, 29; 6, 35; 6, 36; 6, 50; 6, 62; 6, 66; 6, 67; 6, 82; 6, 83; 6, 207; 6, 208; 6, 212; 6, 247; 6, 254; 6, 264; 6, 277; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:values; 12, list_comprehension; 12, 13; 12, 16; 13, subscript; 13, 14; 13, 15; 14, identifier:t; 15, integer:0; 16, for_in_clause; 16, 17; 16, 18; 17, identifier:t; 18, identifier:items; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:weights; 22, list_comprehension; 22, 23; 22, 26; 23, subscript; 23, 24; 23, 25; 24, identifier:t; 25, integer:1; 26, for_in_clause; 26, 27; 26, 28; 27, identifier:t; 28, identifier:items; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:maxsize; 32, binary_operator:+; 32, 33; 32, 34; 33, identifier:maxweight; 34, integer:1; 35, comment; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:dpmat; 39, call; 39, 40; 39, 41; 40, identifier:defaultdict; 41, argument_list; 41, 42; 42, lambda; 42, 43; 43, call; 43, 44; 43, 45; 44, identifier:defaultdict; 45, argument_list; 45, 46; 46, lambda; 46, 47; 47, attribute; 47, 48; 47, 49; 48, identifier:np; 49, identifier:inf; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:kmat; 53, call; 53, 54; 53, 55; 54, identifier:defaultdict; 55, argument_list; 55, 56; 56, lambda; 56, 57; 57, call; 57, 58; 57, 59; 58, identifier:defaultdict; 59, argument_list; 59, 60; 60, lambda; 60, 61; 61, False; 62, expression_statement; 62, 63; 63, assignment; 63, 64; 63, 65; 64, identifier:idx_subset; 65, list:[]; 66, comment; 67, for_statement; 67, 68; 67, 69; 67, 73; 68, identifier:w; 69, call; 69, 70; 69, 71; 70, identifier:range; 71, argument_list; 71, 72; 72, identifier:maxsize; 73, block; 73, 74; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 81; 76, subscript; 76, 77; 76, 80; 77, subscript; 77, 78; 77, 79; 78, identifier:dpmat; 79, integer:0; 80, identifier:w; 81, integer:0; 82, comment; 83, for_statement; 83, 84; 83, 85; 83, 92; 84, identifier:idx; 85, call; 85, 86; 85, 87; 86, identifier:range; 87, argument_list; 87, 88; 88, call; 88, 89; 88, 90; 89, identifier:len; 90, argument_list; 90, 91; 91, identifier:items; 92, block; 92, 93; 92, 99; 92, 105; 92, 106; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:item_val; 96, subscript; 96, 97; 96, 98; 97, identifier:values; 98, identifier:idx; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:item_weight; 102, subscript; 102, 103; 102, 104; 103, identifier:weights; 104, identifier:idx; 105, comment; 106, for_statement; 106, 107; 106, 108; 106, 112; 107, identifier:w; 108, call; 108, 109; 108, 110; 109, identifier:range; 110, argument_list; 110, 111; 111, identifier:maxsize; 112, block; 112, 113; 112, 119; 112, 156; 112, 162; 112, 168; 113, expression_statement; 113, 114; 114, assignment; 114, 115; 114, 116; 115, identifier:valid_item; 116, comparison_operator:<=; 116, 117; 116, 118; 117, identifier:item_weight; 118, identifier:w; 119, if_statement; 119, 120; 119, 123; 119, 146; 120, comparison_operator:>; 120, 121; 120, 122; 121, identifier:idx; 122, integer:0; 123, block; 123, 124; 123, 134; 124, expression_statement; 124, 125; 125, assignment; 125, 126; 125, 127; 126, identifier:prev_val; 127, subscript; 127, 128; 127, 133; 128, subscript; 128, 129; 128, 130; 129, identifier:dpmat; 130, binary_operator:-; 130, 131; 130, 132; 131, identifier:idx; 132, integer:1; 133, identifier:w; 134, expression_statement; 134, 135; 135, assignment; 135, 136; 135, 137; 136, identifier:prev_noitem_val; 137, subscript; 137, 138; 137, 143; 138, subscript; 138, 139; 138, 140; 139, identifier:dpmat; 140, binary_operator:-; 140, 141; 140, 142; 141, identifier:idx; 142, integer:1; 143, binary_operator:-; 143, 144; 143, 145; 144, identifier:w; 145, identifier:item_weight; 146, else_clause; 146, 147; 147, block; 147, 148; 147, 152; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 151; 150, identifier:prev_val; 151, integer:0; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:prev_noitem_val; 155, integer:0; 156, expression_statement; 156, 157; 157, assignment; 157, 158; 157, 159; 158, identifier:withitem_val; 159, binary_operator:+; 159, 160; 159, 161; 160, identifier:item_val; 161, identifier:prev_noitem_val; 162, expression_statement; 162, 163; 163, assignment; 163, 164; 163, 165; 164, identifier:more_valuable; 165, comparison_operator:>; 165, 166; 165, 167; 166, identifier:withitem_val; 167, identifier:prev_val; 168, if_statement; 168, 169; 168, 172; 168, 189; 169, boolean_operator:and; 169, 170; 169, 171; 170, identifier:valid_item; 171, identifier:more_valuable; 172, block; 172, 173; 172, 181; 173, expression_statement; 173, 174; 174, assignment; 174, 175; 174, 180; 175, subscript; 175, 176; 175, 179; 176, subscript; 176, 177; 176, 178; 177, identifier:dpmat; 178, identifier:idx; 179, identifier:w; 180, identifier:withitem_val; 181, expression_statement; 181, 182; 182, assignment; 182, 183; 182, 188; 183, subscript; 183, 184; 183, 187; 184, subscript; 184, 185; 184, 186; 185, identifier:kmat; 186, identifier:idx; 187, identifier:w; 188, True; 189, else_clause; 189, 190; 190, block; 190, 191; 190, 199; 191, expression_statement; 191, 192; 192, assignment; 192, 193; 192, 198; 193, subscript; 193, 194; 193, 197; 194, subscript; 194, 195; 194, 196; 195, identifier:dpmat; 196, identifier:idx; 197, identifier:w; 198, identifier:prev_val; 199, expression_statement; 199, 200; 200, assignment; 200, 201; 200, 206; 201, subscript; 201, 202; 201, 205; 202, subscript; 202, 203; 202, 204; 203, identifier:kmat; 204, identifier:idx; 205, identifier:w; 206, False; 207, comment; 208, expression_statement; 208, 209; 209, assignment; 209, 210; 209, 211; 210, identifier:K; 211, identifier:maxweight; 212, for_statement; 212, 213; 212, 214; 212, 224; 213, identifier:idx; 214, call; 214, 215; 214, 216; 215, identifier:reversed; 216, argument_list; 216, 217; 217, call; 217, 218; 217, 219; 218, identifier:range; 219, argument_list; 219, 220; 220, call; 220, 221; 220, 222; 221, identifier:len; 222, argument_list; 222, 223; 223, identifier:items; 224, block; 224, 225; 225, if_statement; 225, 226; 225, 231; 226, subscript; 226, 227; 226, 230; 227, subscript; 227, 228; 227, 229; 228, identifier:kmat; 229, identifier:idx; 230, identifier:K; 231, block; 231, 232; 231, 239; 232, expression_statement; 232, 233; 233, call; 233, 234; 233, 237; 234, attribute; 234, 235; 234, 236; 235, identifier:idx_subset; 236, identifier:append; 237, argument_list; 237, 238; 238, identifier:idx; 239, expression_statement; 239, 240; 240, assignment; 240, 241; 240, 242; 241, identifier:K; 242, binary_operator:-; 242, 243; 242, 244; 243, identifier:K; 244, subscript; 244, 245; 244, 246; 245, identifier:weights; 246, identifier:idx; 247, expression_statement; 247, 248; 248, assignment; 248, 249; 248, 250; 249, identifier:idx_subset; 250, call; 250, 251; 250, 252; 251, identifier:sorted; 252, argument_list; 252, 253; 253, identifier:idx_subset; 254, expression_statement; 254, 255; 255, assignment; 255, 256; 255, 257; 256, identifier:items_subset; 257, list_comprehension; 257, 258; 257, 261; 258, subscript; 258, 259; 258, 260; 259, identifier:items; 260, identifier:i; 261, for_in_clause; 261, 262; 261, 263; 262, identifier:i; 263, identifier:idx_subset; 264, expression_statement; 264, 265; 265, assignment; 265, 266; 265, 267; 266, identifier:total_value; 267, subscript; 267, 268; 267, 276; 268, subscript; 268, 269; 268, 270; 269, identifier:dpmat; 270, binary_operator:-; 270, 271; 270, 275; 271, call; 271, 272; 271, 273; 272, identifier:len; 273, argument_list; 273, 274; 274, identifier:items; 275, integer:1; 276, identifier:maxweight; 277, return_statement; 277, 278; 278, expression_list; 278, 279; 278, 280; 279, identifier:total_value; 280, identifier:items_subset | def knapsack_iterative_int(items, maxweight):
r"""
Iterative knapsack method
Math:
maximize \sum_{i \in T} v_i
subject to \sum_{i \in T} w_i \leq W
Notes:
dpmat is the dynamic programming memoization matrix.
dpmat[i, w] is the total value of the items with weight at most W
T is idx_subset, the set of indicies in the optimal solution
CommandLine:
python -m utool.util_alg --exec-knapsack_iterative_int --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> weights = [1, 3, 3, 5, 2, 1] * 2
>>> items = [(w, w, i) for i, w in enumerate(weights)]
>>> maxweight = 10
>>> items = [(.8, 700, 0)]
>>> maxweight = 2000
>>> print('maxweight = %r' % (maxweight,))
>>> print('items = %r' % (items,))
>>> total_value, items_subset = knapsack_iterative_int(items, maxweight)
>>> total_weight = sum([t[1] for t in items_subset])
>>> print('total_weight = %r' % (total_weight,))
>>> print('items_subset = %r' % (items_subset,))
>>> result = 'total_value = %.2f' % (total_value,)
>>> print(result)
total_value = 0.80
Ignore:
DPMAT = [[dpmat[r][c] for c in range(maxweight)] for r in range(len(items))]
KMAT = [[kmat[r][c] for c in range(maxweight)] for r in range(len(items))]
"""
values = [t[0] for t in items]
weights = [t[1] for t in items]
maxsize = maxweight + 1
# Sparse representation seems better
dpmat = defaultdict(lambda: defaultdict(lambda: np.inf))
kmat = defaultdict(lambda: defaultdict(lambda: False))
idx_subset = [] # NOQA
for w in range(maxsize):
dpmat[0][w] = 0
# For each item consider to include it or not
for idx in range(len(items)):
item_val = values[idx]
item_weight = weights[idx]
# consider at each possible bag size
for w in range(maxsize):
valid_item = item_weight <= w
if idx > 0:
prev_val = dpmat[idx - 1][w]
prev_noitem_val = dpmat[idx - 1][w - item_weight]
else:
prev_val = 0
prev_noitem_val = 0
withitem_val = item_val + prev_noitem_val
more_valuable = withitem_val > prev_val
if valid_item and more_valuable:
dpmat[idx][w] = withitem_val
kmat[idx][w] = True
else:
dpmat[idx][w] = prev_val
kmat[idx][w] = False
# Trace backwards to get the items used in the solution
K = maxweight
for idx in reversed(range(len(items))):
if kmat[idx][K]:
idx_subset.append(idx)
K = K - weights[idx]
idx_subset = sorted(idx_subset)
items_subset = [items[i] for i in idx_subset]
total_value = dpmat[len(items) - 1][maxweight]
return total_value, items_subset |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:knapsack_iterative_numpy; 3, parameters; 3, 4; 3, 5; 4, identifier:items; 5, identifier:maxweight; 6, block; 6, 7; 6, 9; 6, 10; 6, 19; 6, 27; 6, 28; 6, 42; 6, 48; 6, 49; 6, 63; 6, 71; 6, 80; 6, 86; 6, 103; 6, 123; 6, 127; 6, 142; 6, 240; 6, 244; 6, 279; 6, 286; 6, 296; 6, 309; 7, expression_statement; 7, 8; 8, comment; 9, comment; 10, expression_statement; 10, 11; 11, assignment; 11, 12; 11, 13; 12, identifier:items; 13, call; 13, 14; 13, 17; 14, attribute; 14, 15; 14, 16; 15, identifier:np; 16, identifier:array; 17, argument_list; 17, 18; 18, identifier:items; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:weights; 22, subscript; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:items; 25, identifier:T; 26, integer:1; 27, comment; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:max_exp; 31, call; 31, 32; 31, 33; 32, identifier:max; 33, argument_list; 33, 34; 34, list_comprehension; 34, 35; 34, 39; 35, call; 35, 36; 35, 37; 36, identifier:number_of_decimals; 37, argument_list; 37, 38; 38, identifier:w_; 39, for_in_clause; 39, 40; 39, 41; 40, identifier:w_; 41, identifier:weights; 42, expression_statement; 42, 43; 43, assignment; 43, 44; 43, 45; 44, identifier:coeff; 45, binary_operator:**; 45, 46; 45, 47; 46, integer:10; 47, identifier:max_exp; 48, comment; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:weights; 52, call; 52, 53; 52, 59; 53, attribute; 53, 54; 53, 58; 54, parenthesized_expression; 54, 55; 55, binary_operator:*; 55, 56; 55, 57; 56, identifier:weights; 57, identifier:coeff; 58, identifier:astype; 59, argument_list; 59, 60; 60, attribute; 60, 61; 60, 62; 61, identifier:np; 62, identifier:int; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:values; 66, subscript; 66, 67; 66, 70; 67, attribute; 67, 68; 67, 69; 68, identifier:items; 69, identifier:T; 70, integer:0; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:MAXWEIGHT; 74, call; 74, 75; 74, 76; 75, identifier:int; 76, argument_list; 76, 77; 77, binary_operator:*; 77, 78; 77, 79; 78, identifier:maxweight; 79, identifier:coeff; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:W_SIZE; 83, binary_operator:+; 83, 84; 83, 85; 84, identifier:MAXWEIGHT; 85, integer:1; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:dpmat; 89, call; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:np; 92, identifier:full; 93, argument_list; 93, 94; 93, 100; 94, tuple; 94, 95; 94, 99; 95, call; 95, 96; 95, 97; 96, identifier:len; 97, argument_list; 97, 98; 98, identifier:items; 99, identifier:W_SIZE; 100, attribute; 100, 101; 100, 102; 101, identifier:np; 102, identifier:inf; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:kmat; 106, call; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, identifier:np; 109, identifier:full; 110, argument_list; 110, 111; 110, 117; 110, 118; 111, tuple; 111, 112; 111, 116; 112, call; 112, 113; 112, 114; 113, identifier:len; 114, argument_list; 114, 115; 115, identifier:items; 116, identifier:W_SIZE; 117, integer:0; 118, keyword_argument; 118, 119; 118, 120; 119, identifier:dtype; 120, attribute; 120, 121; 120, 122; 121, identifier:np; 122, identifier:bool; 123, expression_statement; 123, 124; 124, assignment; 124, 125; 124, 126; 125, identifier:idx_subset; 126, list:[]; 127, for_statement; 127, 128; 127, 129; 127, 133; 128, identifier:w; 129, call; 129, 130; 129, 131; 130, identifier:range; 131, argument_list; 131, 132; 132, identifier:W_SIZE; 133, block; 133, 134; 134, expression_statement; 134, 135; 135, assignment; 135, 136; 135, 141; 136, subscript; 136, 137; 136, 140; 137, subscript; 137, 138; 137, 139; 138, identifier:dpmat; 139, integer:0; 140, identifier:w; 141, integer:0; 142, for_statement; 142, 143; 142, 144; 142, 152; 143, identifier:idx; 144, call; 144, 145; 144, 146; 145, identifier:range; 146, argument_list; 146, 147; 146, 148; 147, integer:1; 148, call; 148, 149; 148, 150; 149, identifier:len; 150, argument_list; 150, 151; 151, identifier:items; 152, block; 152, 153; 152, 159; 152, 165; 153, expression_statement; 153, 154; 154, assignment; 154, 155; 154, 156; 155, identifier:item_val; 156, subscript; 156, 157; 156, 158; 157, identifier:values; 158, identifier:idx; 159, expression_statement; 159, 160; 160, assignment; 160, 161; 160, 162; 161, identifier:item_weight; 162, subscript; 162, 163; 162, 164; 163, identifier:weights; 164, identifier:idx; 165, for_statement; 165, 166; 165, 167; 165, 171; 166, identifier:w; 167, call; 167, 168; 167, 169; 168, identifier:range; 169, argument_list; 169, 170; 170, identifier:W_SIZE; 171, block; 171, 172; 171, 178; 171, 188; 171, 221; 171, 232; 172, expression_statement; 172, 173; 173, assignment; 173, 174; 173, 175; 174, identifier:valid_item; 175, comparison_operator:<=; 175, 176; 175, 177; 176, identifier:item_weight; 177, identifier:w; 178, expression_statement; 178, 179; 179, assignment; 179, 180; 179, 181; 180, identifier:prev_val; 181, subscript; 181, 182; 181, 187; 182, subscript; 182, 183; 182, 184; 183, identifier:dpmat; 184, binary_operator:-; 184, 185; 184, 186; 185, identifier:idx; 186, integer:1; 187, identifier:w; 188, if_statement; 188, 189; 188, 190; 188, 215; 189, identifier:valid_item; 190, block; 190, 191; 190, 203; 190, 209; 191, expression_statement; 191, 192; 192, assignment; 192, 193; 192, 194; 193, identifier:prev_noitem_val; 194, subscript; 194, 195; 194, 200; 195, subscript; 195, 196; 195, 197; 196, identifier:dpmat; 197, binary_operator:-; 197, 198; 197, 199; 198, identifier:idx; 199, integer:1; 200, binary_operator:-; 200, 201; 200, 202; 201, identifier:w; 202, identifier:item_weight; 203, expression_statement; 203, 204; 204, assignment; 204, 205; 204, 206; 205, identifier:withitem_val; 206, binary_operator:+; 206, 207; 206, 208; 207, identifier:item_val; 208, identifier:prev_noitem_val; 209, expression_statement; 209, 210; 210, assignment; 210, 211; 210, 212; 211, identifier:more_valuable; 212, comparison_operator:>; 212, 213; 212, 214; 213, identifier:withitem_val; 214, identifier:prev_val; 215, else_clause; 215, 216; 216, block; 216, 217; 217, expression_statement; 217, 218; 218, assignment; 218, 219; 218, 220; 219, identifier:more_valuable; 220, False; 221, expression_statement; 221, 222; 222, assignment; 222, 223; 222, 228; 223, subscript; 223, 224; 223, 227; 224, subscript; 224, 225; 224, 226; 225, identifier:dpmat; 226, identifier:idx; 227, identifier:w; 228, conditional_expression:if; 228, 229; 228, 230; 228, 231; 229, identifier:withitem_val; 230, identifier:more_valuable; 231, identifier:prev_val; 232, expression_statement; 232, 233; 233, assignment; 233, 234; 233, 239; 234, subscript; 234, 235; 234, 238; 235, subscript; 235, 236; 235, 237; 236, identifier:kmat; 237, identifier:idx; 238, identifier:w; 239, identifier:more_valuable; 240, expression_statement; 240, 241; 241, assignment; 241, 242; 241, 243; 242, identifier:K; 243, identifier:MAXWEIGHT; 244, for_statement; 244, 245; 244, 246; 244, 257; 245, identifier:idx; 246, call; 246, 247; 246, 248; 247, identifier:reversed; 248, argument_list; 248, 249; 249, call; 249, 250; 249, 251; 250, identifier:range; 251, argument_list; 251, 252; 251, 253; 252, integer:1; 253, call; 253, 254; 253, 255; 254, identifier:len; 255, argument_list; 255, 256; 256, identifier:items; 257, block; 257, 258; 258, if_statement; 258, 259; 258, 263; 259, subscript; 259, 260; 259, 261; 259, 262; 260, identifier:kmat; 261, identifier:idx; 262, identifier:K; 263, block; 263, 264; 263, 271; 264, expression_statement; 264, 265; 265, call; 265, 266; 265, 269; 266, attribute; 266, 267; 266, 268; 267, identifier:idx_subset; 268, identifier:append; 269, argument_list; 269, 270; 270, identifier:idx; 271, expression_statement; 271, 272; 272, assignment; 272, 273; 272, 274; 273, identifier:K; 274, binary_operator:-; 274, 275; 274, 276; 275, identifier:K; 276, subscript; 276, 277; 276, 278; 277, identifier:weights; 278, identifier:idx; 279, expression_statement; 279, 280; 280, assignment; 280, 281; 280, 282; 281, identifier:idx_subset; 282, call; 282, 283; 282, 284; 283, identifier:sorted; 284, argument_list; 284, 285; 285, identifier:idx_subset; 286, expression_statement; 286, 287; 287, assignment; 287, 288; 287, 289; 288, identifier:items_subset; 289, list_comprehension; 289, 290; 289, 293; 290, subscript; 290, 291; 290, 292; 291, identifier:items; 292, identifier:i; 293, for_in_clause; 293, 294; 293, 295; 294, identifier:i; 295, identifier:idx_subset; 296, expression_statement; 296, 297; 297, assignment; 297, 298; 297, 299; 298, identifier:total_value; 299, subscript; 299, 300; 299, 308; 300, subscript; 300, 301; 300, 302; 301, identifier:dpmat; 302, binary_operator:-; 302, 303; 302, 307; 303, call; 303, 304; 303, 305; 304, identifier:len; 305, argument_list; 305, 306; 306, identifier:items; 307, integer:1; 308, identifier:MAXWEIGHT; 309, return_statement; 309, 310; 310, expression_list; 310, 311; 310, 312; 311, identifier:total_value; 312, identifier:items_subset | def knapsack_iterative_numpy(items, maxweight):
"""
Iterative knapsack method
maximize \sum_{i \in T} v_i
subject to \sum_{i \in T} w_i \leq W
Notes:
dpmat is the dynamic programming memoization matrix.
dpmat[i, w] is the total value of the items with weight at most W
T is the set of indicies in the optimal solution
"""
#import numpy as np
items = np.array(items)
weights = items.T[1]
# Find maximum decimal place (this problem is in NP)
max_exp = max([number_of_decimals(w_) for w_ in weights])
coeff = 10 ** max_exp
# Adjust weights to be integral
weights = (weights * coeff).astype(np.int)
values = items.T[0]
MAXWEIGHT = int(maxweight * coeff)
W_SIZE = MAXWEIGHT + 1
dpmat = np.full((len(items), W_SIZE), np.inf)
kmat = np.full((len(items), W_SIZE), 0, dtype=np.bool)
idx_subset = []
for w in range(W_SIZE):
dpmat[0][w] = 0
for idx in range(1, len(items)):
item_val = values[idx]
item_weight = weights[idx]
for w in range(W_SIZE):
valid_item = item_weight <= w
prev_val = dpmat[idx - 1][w]
if valid_item:
prev_noitem_val = dpmat[idx - 1][w - item_weight]
withitem_val = item_val + prev_noitem_val
more_valuable = withitem_val > prev_val
else:
more_valuable = False
dpmat[idx][w] = withitem_val if more_valuable else prev_val
kmat[idx][w] = more_valuable
K = MAXWEIGHT
for idx in reversed(range(1, len(items))):
if kmat[idx, K]:
idx_subset.append(idx)
K = K - weights[idx]
idx_subset = sorted(idx_subset)
items_subset = [items[i] for i in idx_subset]
total_value = dpmat[len(items) - 1][MAXWEIGHT]
return total_value, items_subset |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:knapsack_greedy; 3, parameters; 3, 4; 3, 5; 4, identifier:items; 5, identifier:maxweight; 6, block; 6, 7; 6, 9; 6, 13; 6, 17; 6, 21; 6, 61; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:items_subset; 12, list:[]; 13, expression_statement; 13, 14; 14, assignment; 14, 15; 14, 16; 15, identifier:total_weight; 16, integer:0; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:total_value; 20, integer:0; 21, for_statement; 21, 22; 21, 23; 21, 24; 22, identifier:item; 23, identifier:items; 24, block; 24, 25; 24, 36; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 30; 27, pattern_list; 27, 28; 27, 29; 28, identifier:value; 29, identifier:weight; 30, subscript; 30, 31; 30, 32; 31, identifier:item; 32, slice; 32, 33; 32, 34; 32, 35; 33, integer:0; 34, colon; 35, integer:2; 36, if_statement; 36, 37; 36, 42; 36, 44; 37, comparison_operator:>; 37, 38; 37, 41; 38, binary_operator:+; 38, 39; 38, 40; 39, identifier:total_weight; 40, identifier:weight; 41, identifier:maxweight; 42, block; 42, 43; 43, continue_statement; 44, else_clause; 44, 45; 45, block; 45, 46; 45, 53; 45, 57; 46, expression_statement; 46, 47; 47, call; 47, 48; 47, 51; 48, attribute; 48, 49; 48, 50; 49, identifier:items_subset; 50, identifier:append; 51, argument_list; 51, 52; 52, identifier:item; 53, expression_statement; 53, 54; 54, augmented_assignment:+=; 54, 55; 54, 56; 55, identifier:total_weight; 56, identifier:weight; 57, expression_statement; 57, 58; 58, augmented_assignment:+=; 58, 59; 58, 60; 59, identifier:total_value; 60, identifier:value; 61, return_statement; 61, 62; 62, expression_list; 62, 63; 62, 64; 63, identifier:total_value; 64, identifier:items_subset | def knapsack_greedy(items, maxweight):
r"""
non-optimal greedy version of knapsack algorithm
does not sort input. Sort the input by largest value
first if desired.
Args:
`items` (tuple): is a sequence of tuples `(value, weight, id_)`, where `value`
is a scalar and `weight` is a non-negative integer, and `id_` is an
item identifier.
`maxweight` (scalar): is a non-negative integer.
CommandLine:
python -m utool.util_alg --exec-knapsack_greedy
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> items = [(4, 12, 0), (2, 1, 1), (6, 4, 2), (1, 1, 3), (2, 2, 4)]
>>> maxweight = 15
>>> total_value, items_subset = knapsack_greedy(items, maxweight)
>>> result = 'total_value = %r\n' % (total_value,)
>>> result += 'items_subset = %r' % (items_subset,)
>>> print(result)
total_value = 7
items_subset = [(4, 12, 0), (2, 1, 1), (1, 1, 3)]
"""
items_subset = []
total_weight = 0
total_value = 0
for item in items:
value, weight = item[0:2]
if total_weight + weight > maxweight:
continue
else:
items_subset.append(item)
total_weight += weight
total_value += value
return total_value, items_subset |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:ungroup_gen; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:grouped_items; 5, identifier:groupxs; 6, default_parameter; 6, 7; 6, 8; 7, identifier:fill; 8, None; 9, block; 9, 10; 9, 12; 9, 17; 9, 18; 9, 19; 9, 20; 9, 37; 9, 50; 9, 59; 9, 68; 9, 69; 9, 79; 9, 88; 9, 89; 9, 93; 9, 97; 9, 98; 9, 102; 9, 103; 9, 125; 9, 126; 9, 132; 9, 151; 9, 152; 10, expression_statement; 10, 11; 11, comment; 12, import_statement; 12, 13; 13, aliased_import; 13, 14; 13, 16; 14, dotted_name; 14, 15; 15, identifier:utool; 16, identifier:ut; 17, comment; 18, comment; 19, comment; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:minpergroup; 23, list_comprehension; 23, 24; 23, 34; 24, conditional_expression:if; 24, 25; 24, 29; 24, 33; 25, call; 25, 26; 25, 27; 26, identifier:min; 27, argument_list; 27, 28; 28, identifier:xs; 29, call; 29, 30; 29, 31; 30, identifier:len; 31, argument_list; 31, 32; 32, identifier:xs; 33, integer:0; 34, for_in_clause; 34, 35; 34, 36; 35, identifier:xs; 36, identifier:groupxs; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 40; 39, identifier:minval; 40, conditional_expression:if; 40, 41; 40, 45; 40, 49; 41, call; 41, 42; 41, 43; 42, identifier:min; 43, argument_list; 43, 44; 44, identifier:minpergroup; 45, call; 45, 46; 45, 47; 46, identifier:len; 47, argument_list; 47, 48; 48, identifier:minpergroup; 49, integer:0; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:flat_groupx; 53, call; 53, 54; 53, 57; 54, attribute; 54, 55; 54, 56; 55, identifier:ut; 56, identifier:flatten; 57, argument_list; 57, 58; 58, identifier:groupxs; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:sortx; 62, call; 62, 63; 62, 66; 63, attribute; 63, 64; 63, 65; 64, identifier:ut; 65, identifier:argsort; 66, argument_list; 66, 67; 67, identifier:flat_groupx; 68, comment; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:groupx_sorted; 72, call; 72, 73; 72, 76; 73, attribute; 73, 74; 73, 75; 74, identifier:ut; 75, identifier:take; 76, argument_list; 76, 77; 76, 78; 77, identifier:flat_groupx; 78, identifier:sortx; 79, expression_statement; 79, 80; 80, assignment; 80, 81; 80, 82; 81, identifier:flat_items; 82, call; 82, 83; 82, 86; 83, attribute; 83, 84; 83, 85; 84, identifier:ut; 85, identifier:iflatten; 86, argument_list; 86, 87; 87, identifier:grouped_items; 88, comment; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:toyeild; 92, dictionary; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:items_yeilded; 96, integer:0; 97, comment; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:current_index; 101, integer:0; 102, comment; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:num_fills_before; 106, binary_operator:+; 106, 107; 106, 123; 107, binary_operator:+; 107, 108; 107, 110; 108, list:[minval]; 108, 109; 109, identifier:minval; 110, call; 110, 111; 110, 122; 111, attribute; 111, 112; 111, 121; 112, parenthesized_expression; 112, 113; 113, binary_operator:-; 113, 114; 113, 120; 114, call; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, identifier:np; 117, identifier:diff; 118, argument_list; 118, 119; 119, identifier:groupx_sorted; 120, integer:1; 121, identifier:tolist; 122, argument_list; 123, list:[0]; 123, 124; 124, integer:0; 125, comment; 126, expression_statement; 126, 127; 127, assignment; 127, 128; 127, 129; 128, identifier:fills; 129, subscript; 129, 130; 129, 131; 130, identifier:num_fills_before; 131, identifier:items_yeilded; 132, if_statement; 132, 133; 132, 136; 133, comparison_operator:>; 133, 134; 133, 135; 134, identifier:fills; 135, integer:0; 136, block; 136, 137; 137, for_statement; 137, 138; 137, 139; 137, 143; 138, identifier:_; 139, call; 139, 140; 139, 141; 140, identifier:range; 141, argument_list; 141, 142; 142, identifier:fills; 143, block; 143, 144; 143, 147; 144, expression_statement; 144, 145; 145, yield; 145, 146; 146, None; 147, expression_statement; 147, 148; 148, augmented_assignment:+=; 148, 149; 148, 150; 149, identifier:current_index; 150, integer:1; 151, comment; 152, for_statement; 152, 153; 152, 156; 152, 161; 153, pattern_list; 153, 154; 153, 155; 154, identifier:yeild_at; 155, identifier:item; 156, call; 156, 157; 156, 158; 157, identifier:zip; 158, argument_list; 158, 159; 158, 160; 159, identifier:flat_groupx; 160, identifier:flat_items; 161, block; 161, 162; 162, if_statement; 162, 163; 162, 166; 162, 173; 163, comparison_operator:>; 163, 164; 163, 165; 164, identifier:yeild_at; 165, identifier:current_index; 166, block; 166, 167; 167, expression_statement; 167, 168; 168, assignment; 168, 169; 168, 172; 169, subscript; 169, 170; 169, 171; 170, identifier:toyeild; 171, identifier:yeild_at; 172, identifier:item; 173, elif_clause; 173, 174; 173, 177; 173, 178; 174, comparison_operator:==; 174, 175; 174, 176; 175, identifier:yeild_at; 176, identifier:current_index; 177, comment; 178, block; 178, 179; 178, 182; 178, 186; 178, 190; 178, 191; 178, 197; 178, 216; 178, 217; 179, expression_statement; 179, 180; 180, yield; 180, 181; 181, identifier:item; 182, expression_statement; 182, 183; 183, augmented_assignment:+=; 183, 184; 183, 185; 184, identifier:current_index; 185, integer:1; 186, expression_statement; 186, 187; 187, augmented_assignment:+=; 187, 188; 187, 189; 188, identifier:items_yeilded; 189, integer:1; 190, comment; 191, expression_statement; 191, 192; 192, assignment; 192, 193; 192, 194; 193, identifier:fills; 194, subscript; 194, 195; 194, 196; 195, identifier:num_fills_before; 196, identifier:items_yeilded; 197, if_statement; 197, 198; 197, 201; 198, comparison_operator:>; 198, 199; 198, 200; 199, identifier:fills; 200, integer:0; 201, block; 201, 202; 202, for_statement; 202, 203; 202, 204; 202, 208; 203, identifier:_; 204, call; 204, 205; 204, 206; 205, identifier:range; 206, argument_list; 206, 207; 207, identifier:fills; 208, block; 208, 209; 208, 212; 209, expression_statement; 209, 210; 210, yield; 210, 211; 211, None; 212, expression_statement; 212, 213; 213, augmented_assignment:+=; 213, 214; 213, 215; 214, identifier:current_index; 215, integer:1; 216, comment; 217, while_statement; 217, 218; 217, 221; 218, comparison_operator:in; 218, 219; 218, 220; 219, identifier:current_index; 220, identifier:toyeild; 221, block; 221, 222; 221, 231; 221, 234; 221, 238; 221, 242; 221, 243; 221, 249; 222, expression_statement; 222, 223; 223, assignment; 223, 224; 223, 225; 224, identifier:item; 225, call; 225, 226; 225, 229; 226, attribute; 226, 227; 226, 228; 227, identifier:toyeild; 228, identifier:pop; 229, argument_list; 229, 230; 230, identifier:current_index; 231, expression_statement; 231, 232; 232, yield; 232, 233; 233, identifier:item; 234, expression_statement; 234, 235; 235, augmented_assignment:+=; 235, 236; 235, 237; 236, identifier:current_index; 237, integer:1; 238, expression_statement; 238, 239; 239, augmented_assignment:+=; 239, 240; 239, 241; 240, identifier:items_yeilded; 241, integer:1; 242, comment; 243, expression_statement; 243, 244; 244, assignment; 244, 245; 244, 246; 245, identifier:fills; 246, subscript; 246, 247; 246, 248; 247, identifier:num_fills_before; 248, identifier:items_yeilded; 249, if_statement; 249, 250; 249, 253; 250, comparison_operator:>; 250, 251; 250, 252; 251, identifier:fills; 252, integer:0; 253, block; 253, 254; 254, for_statement; 254, 255; 254, 256; 254, 260; 255, identifier:_; 256, call; 256, 257; 256, 258; 257, identifier:range; 258, argument_list; 258, 259; 259, identifier:fills; 260, block; 260, 261; 260, 264; 261, expression_statement; 261, 262; 262, yield; 262, 263; 263, None; 264, expression_statement; 264, 265; 265, augmented_assignment:+=; 265, 266; 265, 267; 266, identifier:current_index; 267, integer:1 | def ungroup_gen(grouped_items, groupxs, fill=None):
"""
Ungroups items returning a generator.
Note that this is much slower than the list version and is not gaurenteed
to have better memory usage.
Args:
grouped_items (list):
groupxs (list):
maxval (int): (default = None)
Returns:
list: ungrouped_items
SeeAlso:
vt.invert_apply_grouping
CommandLine:
python -m utool.util_alg ungroup_unique
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> grouped_items = [[1.1, 1.2], [2.1, 2.2], [3.1, 3.2]]
>>> groupxs = [[1, 2], [5, 6], [9, 3]]
>>> ungrouped_items1 = list(ungroup_gen(grouped_items, groupxs))
>>> ungrouped_items2 = ungroup(grouped_items, groupxs)
>>> assert ungrouped_items1 == ungrouped_items2
>>> grouped_items = [[1.1, 1.2], [2.1, 2.2], [3.1, 3.2]]
>>> groupxs = [[0, 2], [1, 5], [4, 3]]
>>> ungrouped_items1 = list(ungroup_gen(grouped_items, groupxs))
>>> ungrouped_items2 = ungroup(grouped_items, groupxs)
>>> assert ungrouped_items1 == ungrouped_items2
Ignore:
labels = np.random.randint(0, 64, 10000)
unique_labels, groupxs = ut.group_indices(labels)
grouped_items = ut.apply_grouping(np.arange(len(labels)), groupxs)
ungrouped_items1 = list(ungroup_gen(grouped_items, groupxs))
ungrouped_items2 = ungroup(grouped_items, groupxs)
assert ungrouped_items2 == ungrouped_items1
%timeit list(ungroup_gen(grouped_items, groupxs))
%timeit ungroup(grouped_items, groupxs)
"""
import utool as ut
# Determine the number of items if unknown
#maxpergroup = [max(xs) if len(xs) else 0 for xs in groupxs]
#maxval = max(maxpergroup) if len(maxpergroup) else 0
minpergroup = [min(xs) if len(xs) else 0 for xs in groupxs]
minval = min(minpergroup) if len(minpergroup) else 0
flat_groupx = ut.flatten(groupxs)
sortx = ut.argsort(flat_groupx)
# Indicates the index being yeilded
groupx_sorted = ut.take(flat_groupx, sortx)
flat_items = ut.iflatten(grouped_items)
# Storage for data weiting to be yeilded
toyeild = {}
items_yeilded = 0
# Indicates the index we are curently yeilding
current_index = 0
# Determine where fills need to happen
num_fills_before = [minval] + (np.diff(groupx_sorted) - 1).tolist() + [0]
# Check if there are fills before the first item
fills = num_fills_before[items_yeilded]
if fills > 0:
for _ in range(fills):
yield None
current_index += 1
# Yield items as possible
for yeild_at, item in zip(flat_groupx, flat_items):
if yeild_at > current_index:
toyeild[yeild_at] = item
elif yeild_at == current_index:
# When we find the next element to yeild
yield item
current_index += 1
items_yeilded += 1
# Check if there are fills before the next item
fills = num_fills_before[items_yeilded]
if fills > 0:
for _ in range(fills):
yield None
current_index += 1
# Now yield everything that came before this
while current_index in toyeild:
item = toyeild.pop(current_index)
yield item
current_index += 1
items_yeilded += 1
# Check if there are fills before the next item
fills = num_fills_before[items_yeilded]
if fills > 0:
for _ in range(fills):
yield None
current_index += 1 |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:standardize_boolexpr; 3, parameters; 3, 4; 3, 5; 4, identifier:boolexpr_; 5, default_parameter; 5, 6; 5, 7; 6, identifier:parens; 7, False; 8, block; 8, 9; 8, 11; 8, 16; 8, 19; 8, 23; 8, 34; 8, 45; 8, 56; 8, 67; 8, 78; 8, 96; 8, 108; 8, 117; 8, 138; 8, 148; 8, 158; 8, 184; 8, 185; 8, 197; 8, 198; 8, 204; 8, 210; 8, 227; 8, 228; 8, 245; 8, 286; 8, 399; 8, 413; 8, 431; 8, 440; 9, expression_statement; 9, 10; 10, comment; 11, import_statement; 11, 12; 12, aliased_import; 12, 13; 12, 15; 13, dotted_name; 13, 14; 14, identifier:utool; 15, identifier:ut; 16, import_statement; 16, 17; 17, dotted_name; 17, 18; 18, identifier:re; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:onlyvars; 22, identifier:boolexpr_; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:onlyvars; 26, call; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, identifier:re; 29, identifier:sub; 30, argument_list; 30, 31; 30, 32; 30, 33; 31, string:'\\bnot\\b'; 32, string:''; 33, identifier:onlyvars; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:onlyvars; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:re; 40, identifier:sub; 41, argument_list; 41, 42; 41, 43; 41, 44; 42, string:'\\band\\b'; 43, string:''; 44, identifier:onlyvars; 45, expression_statement; 45, 46; 46, assignment; 46, 47; 46, 48; 47, identifier:onlyvars; 48, call; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:re; 51, identifier:sub; 52, argument_list; 52, 53; 52, 54; 52, 55; 53, string:'\\bor\\b'; 54, string:''; 55, identifier:onlyvars; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:onlyvars; 59, call; 59, 60; 59, 63; 60, attribute; 60, 61; 60, 62; 61, identifier:re; 62, identifier:sub; 63, argument_list; 63, 64; 63, 65; 63, 66; 64, string:'\\('; 65, string:''; 66, identifier:onlyvars; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:onlyvars; 70, call; 70, 71; 70, 74; 71, attribute; 71, 72; 71, 73; 72, identifier:re; 73, identifier:sub; 74, argument_list; 74, 75; 74, 76; 74, 77; 75, string:'\\)'; 76, string:''; 77, identifier:onlyvars; 78, expression_statement; 78, 79; 79, assignment; 79, 80; 79, 81; 80, identifier:varnames; 81, call; 81, 82; 81, 94; 82, attribute; 82, 83; 82, 93; 83, call; 83, 84; 83, 92; 84, attribute; 84, 85; 84, 91; 85, call; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, identifier:ut; 88, identifier:remove_doublspaces; 89, argument_list; 89, 90; 90, identifier:onlyvars; 91, identifier:strip; 92, argument_list; 93, identifier:split; 94, argument_list; 94, 95; 95, string:' '; 96, expression_statement; 96, 97; 97, assignment; 97, 98; 97, 99; 98, identifier:varied_dict; 99, dictionary_comprehension; 99, 100; 99, 105; 100, pair; 100, 101; 100, 102; 101, identifier:var; 102, list:[True, False]; 102, 103; 102, 104; 103, True; 104, False; 105, for_in_clause; 105, 106; 105, 107; 106, identifier:var; 107, identifier:varnames; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:bool_states; 111, call; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:ut; 114, identifier:all_dict_combinations; 115, argument_list; 115, 116; 116, identifier:varied_dict; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 120; 119, identifier:outputs; 120, list_comprehension; 120, 121; 120, 135; 121, call; 121, 122; 121, 123; 122, identifier:eval; 123, argument_list; 123, 124; 123, 125; 123, 130; 124, identifier:boolexpr_; 125, call; 125, 126; 125, 129; 126, attribute; 126, 127; 126, 128; 127, identifier:state; 128, identifier:copy; 129, argument_list; 130, call; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:state; 133, identifier:copy; 134, argument_list; 135, for_in_clause; 135, 136; 135, 137; 136, identifier:state; 137, identifier:bool_states; 138, expression_statement; 138, 139; 139, assignment; 139, 140; 139, 141; 140, identifier:true_states; 141, call; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, identifier:ut; 144, identifier:compress; 145, argument_list; 145, 146; 145, 147; 146, identifier:bool_states; 147, identifier:outputs; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 151; 150, identifier:true_tuples; 151, call; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:ut; 154, identifier:take_column; 155, argument_list; 155, 156; 155, 157; 156, identifier:true_states; 157, identifier:varnames; 158, expression_statement; 158, 159; 159, assignment; 159, 160; 159, 161; 160, identifier:true_cases; 161, list_comprehension; 161, 162; 161, 181; 162, call; 162, 163; 162, 164; 163, identifier:str; 164, argument_list; 164, 165; 165, call; 165, 166; 165, 169; 166, attribute; 166, 167; 166, 168; 167, string:''; 168, identifier:join; 169, argument_list; 169, 170; 170, list_comprehension; 170, 171; 170, 178; 171, call; 171, 172; 171, 173; 172, identifier:str; 173, argument_list; 173, 174; 174, call; 174, 175; 174, 176; 175, identifier:int; 176, argument_list; 176, 177; 177, identifier:t; 178, for_in_clause; 178, 179; 178, 180; 179, identifier:t; 180, identifier:tup; 181, for_in_clause; 181, 182; 181, 183; 182, identifier:tup; 183, identifier:true_tuples; 184, comment; 185, expression_statement; 185, 186; 186, assignment; 186, 187; 186, 188; 187, identifier:ones_bin; 188, list_comprehension; 188, 189; 188, 194; 189, call; 189, 190; 189, 191; 190, identifier:int; 191, argument_list; 191, 192; 191, 193; 192, identifier:x; 193, integer:2; 194, for_in_clause; 194, 195; 194, 196; 195, identifier:x; 196, identifier:true_cases; 197, comment; 198, import_from_statement; 198, 199; 198, 202; 199, dotted_name; 199, 200; 199, 201; 200, identifier:quine_mccluskey; 201, identifier:qm; 202, dotted_name; 202, 203; 203, identifier:QuineMcCluskey; 204, expression_statement; 204, 205; 205, assignment; 205, 206; 205, 207; 206, identifier:qm; 207, call; 207, 208; 207, 209; 208, identifier:QuineMcCluskey; 209, argument_list; 210, expression_statement; 210, 211; 211, assignment; 211, 212; 211, 213; 212, identifier:result; 213, call; 213, 214; 213, 217; 214, attribute; 214, 215; 214, 216; 215, identifier:qm; 216, identifier:simplify; 217, argument_list; 217, 218; 217, 221; 218, keyword_argument; 218, 219; 218, 220; 219, identifier:ones; 220, identifier:ones_bin; 221, keyword_argument; 221, 222; 221, 223; 222, identifier:num_bits; 223, call; 223, 224; 223, 225; 224, identifier:len; 225, argument_list; 225, 226; 226, identifier:varnames; 227, comment; 228, expression_statement; 228, 229; 229, assignment; 229, 230; 229, 231; 230, identifier:grouped_terms; 231, list_comprehension; 231, 232; 231, 242; 232, call; 232, 233; 232, 234; 233, identifier:dict; 234, argument_list; 234, 235; 235, call; 235, 236; 235, 239; 236, attribute; 236, 237; 236, 238; 237, identifier:ut; 238, identifier:group_items; 239, argument_list; 239, 240; 239, 241; 240, identifier:varnames; 241, identifier:rs; 242, for_in_clause; 242, 243; 242, 244; 243, identifier:rs; 244, identifier:result; 245, function_definition; 245, 246; 245, 247; 245, 250; 246, function_name:parenjoin; 247, parameters; 247, 248; 247, 249; 248, identifier:char; 249, identifier:list_; 250, block; 250, 251; 251, if_statement; 251, 252; 251, 258; 251, 261; 252, comparison_operator:==; 252, 253; 252, 257; 253, call; 253, 254; 253, 255; 254, identifier:len; 255, argument_list; 255, 256; 256, identifier:list_; 257, integer:0; 258, block; 258, 259; 259, return_statement; 259, 260; 260, string:''; 261, else_clause; 261, 262; 262, block; 262, 263; 263, if_statement; 263, 264; 263, 265; 263, 277; 264, identifier:parens; 265, block; 265, 266; 266, return_statement; 266, 267; 267, binary_operator:+; 267, 268; 267, 276; 268, binary_operator:+; 268, 269; 268, 270; 269, string:'('; 270, call; 270, 271; 270, 274; 271, attribute; 271, 272; 271, 273; 272, identifier:char; 273, identifier:join; 274, argument_list; 274, 275; 275, identifier:list_; 276, string:')'; 277, else_clause; 277, 278; 278, block; 278, 279; 279, return_statement; 279, 280; 280, call; 280, 281; 280, 284; 281, attribute; 281, 282; 281, 283; 282, identifier:char; 283, identifier:join; 284, argument_list; 284, 285; 285, identifier:list_; 286, if_statement; 286, 287; 286, 288; 286, 344; 287, identifier:parens; 288, block; 288, 289; 289, expression_statement; 289, 290; 290, assignment; 290, 291; 290, 292; 291, identifier:expanded_terms; 292, list_comprehension; 292, 293; 292, 341; 293, parenthesized_expression; 293, 294; 294, binary_operator:+; 294, 295; 294, 318; 295, binary_operator:+; 295, 296; 295, 303; 296, call; 296, 297; 296, 300; 297, attribute; 297, 298; 297, 299; 298, identifier:term; 299, identifier:get; 300, argument_list; 300, 301; 300, 302; 301, string:'1'; 302, list:[]; 303, list_comprehension; 303, 304; 303, 309; 304, binary_operator:+; 304, 305; 304, 308; 305, binary_operator:+; 305, 306; 305, 307; 306, string:'(not '; 307, identifier:b; 308, string:')'; 309, for_in_clause; 309, 310; 309, 311; 310, identifier:b; 311, call; 311, 312; 311, 315; 312, attribute; 312, 313; 312, 314; 313, identifier:term; 314, identifier:get; 315, argument_list; 315, 316; 315, 317; 316, string:'0'; 317, list:[]; 318, list:[
parenjoin(' ^ ', term.get('^', [])),
parenjoin(' ~ ', term.get('~', [])),
]; 318, 319; 318, 330; 319, call; 319, 320; 319, 321; 320, identifier:parenjoin; 321, argument_list; 321, 322; 321, 323; 322, string:' ^ '; 323, call; 323, 324; 323, 327; 324, attribute; 324, 325; 324, 326; 325, identifier:term; 326, identifier:get; 327, argument_list; 327, 328; 327, 329; 328, string:'^'; 329, list:[]; 330, call; 330, 331; 330, 332; 331, identifier:parenjoin; 332, argument_list; 332, 333; 332, 334; 333, string:' ~ '; 334, call; 334, 335; 334, 338; 335, attribute; 335, 336; 335, 337; 336, identifier:term; 337, identifier:get; 338, argument_list; 338, 339; 338, 340; 339, string:'~'; 340, list:[]; 341, for_in_clause; 341, 342; 341, 343; 342, identifier:term; 343, identifier:grouped_terms; 344, else_clause; 344, 345; 345, block; 345, 346; 346, expression_statement; 346, 347; 347, assignment; 347, 348; 347, 349; 348, identifier:expanded_terms; 349, list_comprehension; 349, 350; 349, 396; 350, parenthesized_expression; 350, 351; 351, binary_operator:+; 351, 352; 351, 373; 352, binary_operator:+; 352, 353; 352, 360; 353, call; 353, 354; 353, 357; 354, attribute; 354, 355; 354, 356; 355, identifier:term; 356, identifier:get; 357, argument_list; 357, 358; 357, 359; 358, string:'1'; 359, list:[]; 360, list_comprehension; 360, 361; 360, 364; 361, binary_operator:+; 361, 362; 361, 363; 362, string:'not '; 363, identifier:b; 364, for_in_clause; 364, 365; 364, 366; 365, identifier:b; 366, call; 366, 367; 366, 370; 367, attribute; 367, 368; 367, 369; 368, identifier:term; 369, identifier:get; 370, argument_list; 370, 371; 370, 372; 371, string:'0'; 372, list:[]; 373, list:[
parenjoin(' ^ ', term.get('^', [])),
parenjoin(' ~ ', term.get('~', [])),
]; 373, 374; 373, 385; 374, call; 374, 375; 374, 376; 375, identifier:parenjoin; 376, argument_list; 376, 377; 376, 378; 377, string:' ^ '; 378, call; 378, 379; 378, 382; 379, attribute; 379, 380; 379, 381; 380, identifier:term; 381, identifier:get; 382, argument_list; 382, 383; 382, 384; 383, string:'^'; 384, list:[]; 385, call; 385, 386; 385, 387; 386, identifier:parenjoin; 387, argument_list; 387, 388; 387, 389; 388, string:' ~ '; 389, call; 389, 390; 389, 393; 390, attribute; 390, 391; 390, 392; 391, identifier:term; 392, identifier:get; 393, argument_list; 393, 394; 393, 395; 394, string:'~'; 395, list:[]; 396, for_in_clause; 396, 397; 396, 398; 397, identifier:term; 398, identifier:grouped_terms; 399, expression_statement; 399, 400; 400, assignment; 400, 401; 400, 402; 401, identifier:final_terms; 402, list_comprehension; 402, 403; 402, 410; 403, list_comprehension; 403, 404; 403, 405; 403, 408; 404, identifier:t; 405, for_in_clause; 405, 406; 405, 407; 406, identifier:t; 407, identifier:term; 408, if_clause; 408, 409; 409, identifier:t; 410, for_in_clause; 410, 411; 410, 412; 411, identifier:term; 412, identifier:expanded_terms; 413, expression_statement; 413, 414; 414, assignment; 414, 415; 414, 416; 415, identifier:products; 416, list_comprehension; 416, 417; 416, 428; 417, call; 417, 418; 417, 419; 418, identifier:parenjoin; 419, argument_list; 419, 420; 419, 421; 420, string:' and '; 421, list_comprehension; 421, 422; 421, 423; 421, 426; 422, identifier:f; 423, for_in_clause; 423, 424; 423, 425; 424, identifier:f; 425, identifier:form; 426, if_clause; 426, 427; 427, identifier:f; 428, for_in_clause; 428, 429; 428, 430; 429, identifier:form; 430, identifier:final_terms; 431, expression_statement; 431, 432; 432, assignment; 432, 433; 432, 434; 433, identifier:final_expr; 434, call; 434, 435; 434, 438; 435, attribute; 435, 436; 435, 437; 436, string:' or '; 437, identifier:join; 438, argument_list; 438, 439; 439, identifier:products; 440, return_statement; 440, 441; 441, identifier:final_expr | def standardize_boolexpr(boolexpr_, parens=False):
r"""
Standardizes a boolean expression into an or-ing of and-ed variables
Args:
boolexpr_ (str):
Returns:
str: final_expr
CommandLine:
sudo pip install git+https://github.com/tpircher/quine-mccluskey.git
python -m utool.util_alg standardize_boolexpr --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> boolexpr_ = 'not force_opencv and (orient_ or is_gif)'
>>> result = standardize_boolexpr(boolexpr_, parens=True)
>>> print(result)
(orient_ and (not force_opencv)) or (is_gif and (not force_opencv))
"""
import utool as ut
import re
onlyvars = boolexpr_
onlyvars = re.sub('\\bnot\\b', '', onlyvars)
onlyvars = re.sub('\\band\\b', '', onlyvars)
onlyvars = re.sub('\\bor\\b', '', onlyvars)
onlyvars = re.sub('\\(', '', onlyvars)
onlyvars = re.sub('\\)', '', onlyvars)
varnames = ut.remove_doublspaces(onlyvars).strip().split(' ')
varied_dict = {var: [True, False] for var in varnames}
bool_states = ut.all_dict_combinations(varied_dict)
outputs = [eval(boolexpr_, state.copy(), state.copy()) for state in bool_states]
true_states = ut.compress(bool_states, outputs)
true_tuples = ut.take_column(true_states, varnames)
true_cases = [str(''.join([str(int(t)) for t in tup])) for tup in true_tuples]
# Convert to binary
ones_bin = [int(x, 2) for x in true_cases]
#ones_str = [str(x) for x in true_cases]
from quine_mccluskey.qm import QuineMcCluskey
qm = QuineMcCluskey()
result = qm.simplify(ones=ones_bin, num_bits=len(varnames))
#result = qm.simplify_los(ones=ones_str, num_bits=len(varnames))
grouped_terms = [dict(ut.group_items(varnames, rs)) for rs in result]
def parenjoin(char, list_):
if len(list_) == 0:
return ''
else:
if parens:
return '(' + char.join(list_) + ')'
else:
return char.join(list_)
if parens:
expanded_terms = [
(
term.get('1', []) +
['(not ' + b + ')' for b in term.get('0', [])] +
[
parenjoin(' ^ ', term.get('^', [])),
parenjoin(' ~ ', term.get('~', [])),
]
) for term in grouped_terms
]
else:
expanded_terms = [
(
term.get('1', []) +
['not ' + b for b in term.get('0', [])] +
[
parenjoin(' ^ ', term.get('^', [])),
parenjoin(' ~ ', term.get('~', [])),
]
) for term in grouped_terms
]
final_terms = [[t for t in term if t] for term in expanded_terms]
products = [parenjoin(' and ', [f for f in form if f]) for form in final_terms]
final_expr = ' or '.join(products)
return final_expr |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:factors; 3, parameters; 3, 4; 4, identifier:n; 5, block; 5, 6; 5, 8; 6, expression_statement; 6, 7; 7, comment; 8, return_statement; 8, 9; 9, call; 9, 10; 9, 11; 10, identifier:set; 11, argument_list; 11, 12; 12, call; 12, 13; 12, 14; 13, identifier:reduce; 14, argument_list; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:list; 17, identifier:__add__; 18, generator_expression; 18, 19; 18, 24; 18, 38; 19, list:[i, n // i]; 19, 20; 19, 21; 20, identifier:i; 21, binary_operator://; 21, 22; 21, 23; 22, identifier:n; 23, identifier:i; 24, for_in_clause; 24, 25; 24, 26; 25, identifier:i; 26, call; 26, 27; 26, 28; 27, identifier:range; 28, argument_list; 28, 29; 28, 30; 29, integer:1; 30, binary_operator:+; 30, 31; 30, 37; 31, call; 31, 32; 31, 33; 32, identifier:int; 33, argument_list; 33, 34; 34, binary_operator:**; 34, 35; 34, 36; 35, identifier:n; 36, float:0.5; 37, integer:1; 38, if_clause; 38, 39; 39, comparison_operator:==; 39, 40; 39, 43; 40, binary_operator:%; 40, 41; 40, 42; 41, identifier:n; 42, identifier:i; 43, integer:0 | def factors(n):
"""
Computes all the integer factors of the number `n`
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> result = sorted(ut.factors(10))
>>> print(result)
[1, 2, 5, 10]
References:
http://stackoverflow.com/questions/6800193/finding-all-the-factors
"""
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:dict_stack; 3, parameters; 3, 4; 3, 5; 4, identifier:dict_list; 5, default_parameter; 5, 6; 5, 7; 6, identifier:key_prefix; 7, string:''; 8, block; 8, 9; 8, 11; 8, 18; 8, 44; 8, 51; 9, expression_statement; 9, 10; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:dict_stacked_; 14, call; 14, 15; 14, 16; 15, identifier:defaultdict; 16, argument_list; 16, 17; 17, identifier:list; 18, for_statement; 18, 19; 18, 20; 18, 21; 19, identifier:dict_; 20, identifier:dict_list; 21, block; 21, 22; 22, for_statement; 22, 23; 22, 26; 22, 32; 23, pattern_list; 23, 24; 23, 25; 24, identifier:key; 25, identifier:val; 26, call; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, identifier:six; 29, identifier:iteritems; 30, argument_list; 30, 31; 31, identifier:dict_; 32, block; 32, 33; 33, expression_statement; 33, 34; 34, call; 34, 35; 34, 42; 35, attribute; 35, 36; 35, 41; 36, subscript; 36, 37; 36, 38; 37, identifier:dict_stacked_; 38, binary_operator:+; 38, 39; 38, 40; 39, identifier:key_prefix; 40, identifier:key; 41, identifier:append; 42, argument_list; 42, 43; 43, identifier:val; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:dict_stacked; 47, call; 47, 48; 47, 49; 48, identifier:dict; 49, argument_list; 49, 50; 50, identifier:dict_stacked_; 51, return_statement; 51, 52; 52, identifier:dict_stacked | def dict_stack(dict_list, key_prefix=''):
r"""
stacks values from two dicts into a new dict where the values are list of
the input values. the keys are the same.
DEPRICATE in favor of dict_stack2
Args:
dict_list (list): list of dicts with similar keys
Returns:
dict dict_stacked
CommandLine:
python -m utool.util_dict --test-dict_stack
python -m utool.util_dict --test-dict_stack:1
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': 1, 'b': 2}
>>> dict2_ = {'a': 2, 'b': 3, 'c': 4}
>>> dict_stacked = dict_stack([dict1_, dict2_])
>>> result = ut.repr2(dict_stacked, sorted_=True)
>>> print(result)
{'a': [1, 2], 'b': [2, 3], 'c': [4]}
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> # Get equivalent behavior with dict_stack2?
>>> # Almost, as long as None is not part of the list
>>> dict1_ = {'a': 1, 'b': 2}
>>> dict2_ = {'a': 2, 'b': 3, 'c': 4}
>>> dict_stacked_ = dict_stack2([dict1_, dict2_])
>>> dict_stacked = {key: ut.filter_Nones(val) for key, val in dict_stacked_.items()}
>>> result = ut.repr2(dict_stacked, sorted_=True)
>>> print(result)
{'a': [1, 2], 'b': [2, 3], 'c': [4]}
"""
dict_stacked_ = defaultdict(list)
for dict_ in dict_list:
for key, val in six.iteritems(dict_):
dict_stacked_[key_prefix + key].append(val)
dict_stacked = dict(dict_stacked_)
return dict_stacked |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:invert_dict; 3, parameters; 3, 4; 3, 5; 4, identifier:dict_; 5, default_parameter; 5, 6; 5, 7; 6, identifier:unique_vals; 7, True; 8, block; 8, 9; 8, 11; 8, 59; 9, expression_statement; 9, 10; 10, comment; 11, if_statement; 11, 12; 11, 13; 11, 41; 12, identifier:unique_vals; 13, block; 13, 14; 13, 31; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:inverted_items; 17, list_comprehension; 17, 18; 17, 21; 18, tuple; 18, 19; 18, 20; 19, identifier:val; 20, identifier:key; 21, for_in_clause; 21, 22; 21, 25; 22, pattern_list; 22, 23; 22, 24; 23, identifier:key; 24, identifier:val; 25, call; 25, 26; 25, 29; 26, attribute; 26, 27; 26, 28; 27, identifier:six; 28, identifier:iteritems; 29, argument_list; 29, 30; 30, identifier:dict_; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:inverted_dict; 34, call; 34, 35; 34, 39; 35, call; 35, 36; 35, 37; 36, identifier:type; 37, argument_list; 37, 38; 38, identifier:dict_; 39, argument_list; 39, 40; 40, identifier:inverted_items; 41, else_clause; 41, 42; 42, block; 42, 43; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 46; 45, identifier:inverted_dict; 46, call; 46, 47; 46, 48; 47, identifier:group_items; 48, argument_list; 48, 49; 48, 54; 49, call; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:dict_; 52, identifier:keys; 53, argument_list; 54, call; 54, 55; 54, 58; 55, attribute; 55, 56; 55, 57; 56, identifier:dict_; 57, identifier:values; 58, argument_list; 59, return_statement; 59, 60; 60, identifier:inverted_dict | def invert_dict(dict_, unique_vals=True):
"""
Reverses the keys and values in a dictionary. Set unique_vals to False if
the values in the dict are not unique.
Args:
dict_ (dict_): dictionary
unique_vals (bool): if False, inverted keys are returned in a list.
Returns:
dict: inverted_dict
CommandLine:
python -m utool.util_dict --test-invert_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'a': 1, 'b': 2}
>>> inverted_dict = invert_dict(dict_)
>>> result = ut.repr4(inverted_dict, nl=False)
>>> print(result)
{1: 'a', 2: 'b'}
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = OrderedDict([(2, 'good',), (1, 'ok',), (0, 'junk',), (None, 'UNKNOWN',)])
>>> inverted_dict = invert_dict(dict_)
>>> result = ut.repr4(inverted_dict, nl=False)
>>> print(result)
{'good': 2, 'ok': 1, 'junk': 0, 'UNKNOWN': None}
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'a': 1, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 2}
>>> inverted_dict = invert_dict(dict_, unique_vals=False)
>>> inverted_dict = ut.map_dict_vals(sorted, inverted_dict)
>>> result = ut.repr4(inverted_dict, nl=False)
>>> print(result)
{0: ['b', 'c', 'd', 'e'], 1: ['a'], 2: ['f']}
"""
if unique_vals:
inverted_items = [(val, key) for key, val in six.iteritems(dict_)]
inverted_dict = type(dict_)(inverted_items)
else:
inverted_dict = group_items(dict_.keys(), dict_.values())
return inverted_dict |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:all_dict_combinations_lbls; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:varied_dict; 5, default_parameter; 5, 6; 5, 7; 6, identifier:remove_singles; 7, True; 8, default_parameter; 8, 9; 8, 10; 9, identifier:allow_lone_singles; 10, False; 11, block; 11, 12; 11, 14; 11, 43; 11, 108; 11, 121; 11, 151; 11, 174; 11, 175; 12, expression_statement; 12, 13; 13, comment; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:is_lone_single; 17, call; 17, 18; 17, 19; 18, identifier:all; 19, argument_list; 19, 20; 20, list_comprehension; 20, 21; 20, 35; 21, boolean_operator:and; 21, 22; 21, 29; 22, call; 22, 23; 22, 24; 23, identifier:isinstance; 24, argument_list; 24, 25; 24, 26; 25, identifier:val_list; 26, tuple; 26, 27; 26, 28; 27, identifier:list; 28, identifier:tuple; 29, comparison_operator:==; 29, 30; 29, 34; 30, call; 30, 31; 30, 32; 31, identifier:len; 32, argument_list; 32, 33; 33, identifier:val_list; 34, integer:1; 35, for_in_clause; 35, 36; 35, 39; 36, pattern_list; 36, 37; 36, 38; 37, identifier:key; 38, identifier:val_list; 39, call; 39, 40; 39, 41; 40, identifier:iteritems_sorted; 41, argument_list; 41, 42; 42, identifier:varied_dict; 43, if_statement; 43, 44; 43, 51; 43, 52; 43, 72; 44, boolean_operator:or; 44, 45; 44, 47; 45, not_operator; 45, 46; 46, identifier:remove_singles; 47, parenthesized_expression; 47, 48; 48, boolean_operator:and; 48, 49; 48, 50; 49, identifier:allow_lone_singles; 50, identifier:is_lone_single; 51, comment; 52, block; 52, 53; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:multitups_list; 56, list_comprehension; 56, 57; 56, 64; 57, list_comprehension; 57, 58; 57, 61; 58, tuple; 58, 59; 58, 60; 59, identifier:key; 60, identifier:val; 61, for_in_clause; 61, 62; 61, 63; 62, identifier:val; 63, identifier:val_list; 64, for_in_clause; 64, 65; 64, 68; 65, pattern_list; 65, 66; 65, 67; 66, identifier:key; 67, identifier:val_list; 68, call; 68, 69; 68, 70; 69, identifier:iteritems_sorted; 70, argument_list; 70, 71; 71, identifier:varied_dict; 72, else_clause; 72, 73; 73, block; 73, 74; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 77; 76, identifier:multitups_list; 77, list_comprehension; 77, 78; 77, 85; 77, 93; 78, list_comprehension; 78, 79; 78, 82; 79, tuple; 79, 80; 79, 81; 80, identifier:key; 81, identifier:val; 82, for_in_clause; 82, 83; 82, 84; 83, identifier:val; 84, identifier:val_list; 85, for_in_clause; 85, 86; 85, 89; 86, pattern_list; 86, 87; 86, 88; 87, identifier:key; 88, identifier:val_list; 89, call; 89, 90; 89, 91; 90, identifier:iteritems_sorted; 91, argument_list; 91, 92; 92, identifier:varied_dict; 93, if_clause; 93, 94; 94, boolean_operator:and; 94, 95; 94, 102; 95, call; 95, 96; 95, 97; 96, identifier:isinstance; 97, argument_list; 97, 98; 97, 99; 98, identifier:val_list; 99, tuple; 99, 100; 99, 101; 100, identifier:list; 101, identifier:tuple; 102, comparison_operator:>; 102, 103; 102, 107; 103, call; 103, 104; 103, 105; 104, identifier:len; 105, argument_list; 105, 106; 106, identifier:val_list; 107, integer:1; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:combtup_list; 111, call; 111, 112; 111, 113; 112, identifier:list; 113, argument_list; 113, 114; 114, call; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, identifier:it; 117, identifier:product; 118, argument_list; 118, 119; 119, list_splat; 119, 120; 120, identifier:multitups_list; 121, expression_statement; 121, 122; 122, assignment; 122, 123; 122, 124; 123, identifier:combtup_list2; 124, list_comprehension; 124, 125; 124, 148; 125, list_comprehension; 125, 126; 125, 143; 126, conditional_expression:if; 126, 127; 126, 130; 126, 137; 127, tuple; 127, 128; 127, 129; 128, identifier:key; 129, identifier:val; 130, call; 130, 131; 130, 132; 131, identifier:isinstance; 132, argument_list; 132, 133; 132, 134; 133, identifier:val; 134, attribute; 134, 135; 134, 136; 135, identifier:six; 136, identifier:string_types; 137, tuple; 137, 138; 137, 139; 138, identifier:key; 139, call; 139, 140; 139, 141; 140, identifier:repr; 141, argument_list; 141, 142; 142, identifier:val; 143, for_in_clause; 143, 144; 143, 147; 144, tuple_pattern; 144, 145; 144, 146; 145, identifier:key; 146, identifier:val; 147, identifier:combtup; 148, for_in_clause; 148, 149; 148, 150; 149, identifier:combtup; 150, identifier:combtup_list; 151, expression_statement; 151, 152; 152, assignment; 152, 153; 152, 154; 153, identifier:comb_lbls; 154, list_comprehension; 154, 155; 154, 171; 155, call; 155, 156; 155, 159; 156, attribute; 156, 157; 156, 158; 157, string:','; 158, identifier:join; 159, argument_list; 159, 160; 160, list_comprehension; 160, 161; 160, 166; 161, binary_operator:%; 161, 162; 161, 163; 162, string:'%s=%s'; 163, tuple; 163, 164; 163, 165; 164, identifier:key; 165, identifier:val; 166, for_in_clause; 166, 167; 166, 170; 167, tuple_pattern; 167, 168; 167, 169; 168, identifier:key; 169, identifier:val; 170, identifier:combtup; 171, for_in_clause; 171, 172; 171, 173; 172, identifier:combtup; 173, identifier:combtup_list2; 174, comment; 175, return_statement; 175, 176; 176, identifier:comb_lbls | def all_dict_combinations_lbls(varied_dict, remove_singles=True, allow_lone_singles=False):
"""
returns a label for each variation in a varydict.
It tries to not be oververbose and returns only what parameters are varied
in each label.
CommandLine:
python -m utool.util_dict --test-all_dict_combinations_lbls
python -m utool.util_dict --exec-all_dict_combinations_lbls:1
Example:
>>> # ENABLE_DOCTEST
>>> import utool
>>> from utool.util_dict import * # NOQA
>>> varied_dict = {'logdist_weight': [0.0, 1.0], 'pipeline_root': ['vsmany'], 'sv_on': [True, False, None]}
>>> comb_lbls = utool.all_dict_combinations_lbls(varied_dict)
>>> result = (utool.repr4(comb_lbls))
>>> print(result)
[
'logdist_weight=0.0,sv_on=True',
'logdist_weight=0.0,sv_on=False',
'logdist_weight=0.0,sv_on=None',
'logdist_weight=1.0,sv_on=True',
'logdist_weight=1.0,sv_on=False',
'logdist_weight=1.0,sv_on=None',
]
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> from utool.util_dict import * # NOQA
>>> varied_dict = {'logdist_weight': [0.0], 'pipeline_root': ['vsmany'], 'sv_on': [True]}
>>> allow_lone_singles = True
>>> comb_lbls = ut.all_dict_combinations_lbls(varied_dict, allow_lone_singles=allow_lone_singles)
>>> result = (ut.repr4(comb_lbls))
>>> print(result)
[
'logdist_weight=0.0,pipeline_root=vsmany,sv_on=True',
]
"""
is_lone_single = all([
isinstance(val_list, (list, tuple)) and len(val_list) == 1
for key, val_list in iteritems_sorted(varied_dict)
])
if not remove_singles or (allow_lone_singles and is_lone_single):
# all entries have one length
multitups_list = [
[(key, val) for val in val_list]
for key, val_list in iteritems_sorted(varied_dict)
]
else:
multitups_list = [
[(key, val) for val in val_list]
for key, val_list in iteritems_sorted(varied_dict)
if isinstance(val_list, (list, tuple)) and len(val_list) > 1]
combtup_list = list(it.product(*multitups_list))
combtup_list2 = [
[(key, val) if isinstance(val, six.string_types) else (key, repr(val))
for (key, val) in combtup]
for combtup in combtup_list]
comb_lbls = [','.join(['%s=%s' % (key, val) for (key, val) in combtup])
for combtup in combtup_list2]
#comb_lbls = list(map(str, comb_pairs))
return comb_lbls |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 18; 2, function_name:update_existing; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 4, identifier:dict1; 5, identifier:dict2; 6, default_parameter; 6, 7; 6, 8; 7, identifier:copy; 8, False; 9, default_parameter; 9, 10; 9, 11; 10, identifier:assert_exists; 11, False; 12, default_parameter; 12, 13; 12, 14; 13, identifier:iswarning; 14, False; 15, default_parameter; 15, 16; 15, 17; 16, identifier:alias_dict; 17, None; 18, block; 18, 19; 18, 21; 18, 61; 18, 71; 18, 80; 18, 112; 19, expression_statement; 19, 20; 20, comment; 21, if_statement; 21, 22; 21, 23; 22, identifier:assert_exists; 23, block; 23, 24; 24, try_statement; 24, 25; 24, 32; 25, block; 25, 26; 26, expression_statement; 26, 27; 27, call; 27, 28; 27, 29; 28, identifier:assert_keys_are_subset; 29, argument_list; 29, 30; 29, 31; 30, identifier:dict1; 31, identifier:dict2; 32, except_clause; 32, 33; 32, 37; 33, as_pattern; 33, 34; 33, 35; 34, identifier:AssertionError; 35, as_pattern_target; 35, 36; 36, identifier:ex; 37, block; 37, 38; 37, 43; 37, 56; 38, import_from_statement; 38, 39; 38, 41; 39, dotted_name; 39, 40; 40, identifier:utool; 41, dotted_name; 41, 42; 42, identifier:util_dbg; 43, expression_statement; 43, 44; 44, call; 44, 45; 44, 48; 45, attribute; 45, 46; 45, 47; 46, identifier:util_dbg; 47, identifier:printex; 48, argument_list; 48, 49; 48, 50; 48, 53; 49, identifier:ex; 50, keyword_argument; 50, 51; 50, 52; 51, identifier:iswarning; 52, identifier:iswarning; 53, keyword_argument; 53, 54; 53, 55; 54, identifier:N; 55, integer:1; 56, if_statement; 56, 57; 56, 59; 57, not_operator; 57, 58; 58, identifier:iswarning; 59, block; 59, 60; 60, raise_statement; 61, if_statement; 61, 62; 61, 63; 62, identifier:copy; 63, block; 63, 64; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:dict1; 67, call; 67, 68; 67, 69; 68, identifier:dict; 69, argument_list; 69, 70; 70, identifier:dict1; 71, if_statement; 71, 72; 71, 75; 72, comparison_operator:is; 72, 73; 72, 74; 73, identifier:alias_dict; 74, None; 75, block; 75, 76; 76, expression_statement; 76, 77; 77, assignment; 77, 78; 77, 79; 78, identifier:alias_dict; 79, dictionary; 80, for_statement; 80, 81; 80, 84; 80, 90; 81, pattern_list; 81, 82; 81, 83; 82, identifier:key; 83, identifier:val; 84, call; 84, 85; 84, 88; 85, attribute; 85, 86; 85, 87; 86, identifier:six; 87, identifier:iteritems; 88, argument_list; 88, 89; 89, identifier:dict2; 90, block; 90, 91; 90, 101; 91, expression_statement; 91, 92; 92, assignment; 92, 93; 92, 94; 93, identifier:key; 94, call; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:alias_dict; 97, identifier:get; 98, argument_list; 98, 99; 98, 100; 99, identifier:key; 100, identifier:key; 101, if_statement; 101, 102; 101, 105; 102, comparison_operator:in; 102, 103; 102, 104; 103, identifier:key; 104, identifier:dict1; 105, block; 105, 106; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 111; 108, subscript; 108, 109; 108, 110; 109, identifier:dict1; 110, identifier:key; 111, identifier:val; 112, return_statement; 112, 113; 113, identifier:dict1 | def update_existing(dict1, dict2, copy=False, assert_exists=False,
iswarning=False, alias_dict=None):
r"""
updates vals in dict1 using vals from dict2 only if the
key is already in dict1.
Args:
dict1 (dict):
dict2 (dict):
copy (bool): if true modifies dictionary in place (default = False)
assert_exists (bool): if True throws error if new key specified (default = False)
alias_dict (dict): dictionary of alias keys for dict2 (default = None)
Returns:
dict - updated dictionary
CommandLine:
python -m utool.util_dict --test-update_existing
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> dict1 = {'a': 1, 'b': 2, 'c': 3}
>>> dict2 = {'a': 2, 'd': 3}
>>> dict1_ = update_existing(dict1, dict2)
>>> assert 'd' not in dict1
>>> assert dict1['a'] == 2
>>> assert dict1_ is dict1
"""
if assert_exists:
try:
assert_keys_are_subset(dict1, dict2)
except AssertionError as ex:
from utool import util_dbg
util_dbg.printex(ex, iswarning=iswarning, N=1)
if not iswarning:
raise
if copy:
dict1 = dict(dict1)
if alias_dict is None:
alias_dict = {}
for key, val in six.iteritems(dict2):
key = alias_dict.get(key, key)
if key in dict1:
dict1[key] = val
return dict1 |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:groupby_tags; 3, parameters; 3, 4; 3, 5; 4, identifier:item_list; 5, identifier:tags_list; 6, block; 6, 7; 6, 9; 6, 16; 6, 39; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:groupid_to_items; 12, call; 12, 13; 12, 14; 13, identifier:defaultdict; 14, argument_list; 14, 15; 15, identifier:list; 16, for_statement; 16, 17; 16, 20; 16, 25; 17, pattern_list; 17, 18; 17, 19; 18, identifier:tags; 19, identifier:item; 20, call; 20, 21; 20, 22; 21, identifier:zip; 22, argument_list; 22, 23; 22, 24; 23, identifier:tags_list; 24, identifier:item_list; 25, block; 25, 26; 26, for_statement; 26, 27; 26, 28; 26, 29; 27, identifier:tag; 28, identifier:tags; 29, block; 29, 30; 30, expression_statement; 30, 31; 31, call; 31, 32; 31, 37; 32, attribute; 32, 33; 32, 36; 33, subscript; 33, 34; 33, 35; 34, identifier:groupid_to_items; 35, identifier:tag; 36, identifier:append; 37, argument_list; 37, 38; 38, identifier:item; 39, return_statement; 39, 40; 40, identifier:groupid_to_items | def groupby_tags(item_list, tags_list):
r"""
case where an item can belong to multiple groups
Args:
item_list (list):
tags_list (list):
Returns:
dict: groupid_to_items
CommandLine:
python -m utool.util_dict --test-groupby_tags
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> tagged_item_list = {
>>> 'spam': ['meat', 'protein', 'food'],
>>> 'eggs': ['protein', 'food'],
>>> 'cheese': ['dairy', 'protein', 'food'],
>>> 'jam': ['fruit', 'food'],
>>> 'banana': ['weapon', 'fruit', 'food'],
>>> }
>>> item_list = list(tagged_item_list.keys())
>>> tags_list = list(tagged_item_list.values())
>>> groupid_to_items = groupby_tags(item_list, tags_list)
>>> groupid_to_items = ut.map_vals(sorted, groupid_to_items)
>>> result = ('groupid_to_items = %s' % (ut.repr4(groupid_to_items),))
>>> print(result)
groupid_to_items = {
'dairy': ['cheese'],
'food': ['banana', 'cheese', 'eggs', 'jam', 'spam'],
'fruit': ['banana', 'jam'],
'meat': ['spam'],
'protein': ['cheese', 'eggs', 'spam'],
'weapon': ['banana'],
}
"""
groupid_to_items = defaultdict(list)
for tags, item in zip(tags_list, item_list):
for tag in tags:
groupid_to_items[tag].append(item)
return groupid_to_items |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:group_items; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:items; 5, default_parameter; 5, 6; 5, 7; 6, identifier:by; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:sorted_; 10, True; 11, block; 11, 12; 11, 14; 11, 80; 11, 81; 11, 88; 11, 89; 11, 104; 12, expression_statement; 12, 13; 13, comment; 14, if_statement; 14, 15; 14, 18; 14, 74; 15, comparison_operator:is; 15, 16; 15, 17; 16, identifier:by; 17, None; 18, block; 18, 19; 18, 30; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:pairs; 22, call; 22, 23; 22, 24; 23, identifier:list; 24, argument_list; 24, 25; 25, call; 25, 26; 25, 27; 26, identifier:zip; 27, argument_list; 27, 28; 27, 29; 28, identifier:by; 29, identifier:items; 30, if_statement; 30, 31; 30, 32; 30, 33; 30, 34; 31, identifier:sorted_; 32, comment; 33, comment; 34, block; 34, 35; 35, try_statement; 35, 36; 35, 52; 36, block; 36, 37; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 40; 39, identifier:pairs; 40, call; 40, 41; 40, 42; 41, identifier:sorted; 42, argument_list; 42, 43; 42, 44; 43, identifier:pairs; 44, keyword_argument; 44, 45; 44, 46; 45, identifier:key; 46, call; 46, 47; 46, 50; 47, attribute; 47, 48; 47, 49; 48, identifier:op; 49, identifier:itemgetter; 50, argument_list; 50, 51; 51, integer:0; 52, except_clause; 52, 53; 52, 54; 52, 55; 53, identifier:TypeError; 54, comment; 55, block; 55, 56; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:pairs; 59, call; 59, 60; 59, 61; 60, identifier:sorted; 61, argument_list; 61, 62; 61, 63; 62, identifier:pairs; 63, keyword_argument; 63, 64; 63, 65; 64, identifier:key; 65, lambda; 65, 66; 65, 68; 66, lambda_parameters; 66, 67; 67, identifier:tup; 68, call; 68, 69; 68, 70; 69, identifier:str; 70, argument_list; 70, 71; 71, subscript; 71, 72; 71, 73; 72, identifier:tup; 73, integer:0; 74, else_clause; 74, 75; 75, block; 75, 76; 76, expression_statement; 76, 77; 77, assignment; 77, 78; 77, 79; 78, identifier:pairs; 79, identifier:items; 80, comment; 81, expression_statement; 81, 82; 82, assignment; 82, 83; 82, 84; 83, identifier:groupid_to_items; 84, call; 84, 85; 84, 86; 85, identifier:defaultdict; 86, argument_list; 86, 87; 87, identifier:list; 88, comment; 89, for_statement; 89, 90; 89, 93; 89, 94; 90, pattern_list; 90, 91; 90, 92; 91, identifier:groupid; 92, identifier:item; 93, identifier:pairs; 94, block; 94, 95; 95, expression_statement; 95, 96; 96, call; 96, 97; 96, 102; 97, attribute; 97, 98; 97, 101; 98, subscript; 98, 99; 98, 100; 99, identifier:groupid_to_items; 100, identifier:groupid; 101, identifier:append; 102, argument_list; 102, 103; 103, identifier:item; 104, return_statement; 104, 105; 105, identifier:groupid_to_items | def group_items(items, by=None, sorted_=True):
"""
Groups a list of items by group id.
Args:
items (list): a list of the values to be grouped.
if `by` is None, then each item is assumed to be a
(groupid, value) pair.
by (list): a corresponding list to group items by.
if specified, these are used as the keys to group values
in `items`
sorted_ (bool): if True preserves the ordering of items within groups
(default = True) FIXME. the opposite is true
Returns:
dict: groupid_to_items: maps a groupid to a list of items
SeeAlso:
group_indices - first part of a a more fine grained grouping algorithm
apply_gropuing - second part of a more fine grained grouping algorithm
CommandLine:
python -m utool.util_dict --test-group_items
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> items = ['ham', 'jam', 'spam', 'eggs', 'cheese', 'bannana']
>>> by = ['protein', 'fruit', 'protein', 'protein', 'dairy', 'fruit']
>>> groupid_to_items = ut.group_items(items, iter(by))
>>> result = ut.repr2(groupid_to_items)
>>> print(result)
{'dairy': ['cheese'], 'fruit': ['jam', 'bannana'], 'protein': ['ham', 'spam', 'eggs']}
"""
if by is not None:
pairs = list(zip(by, items))
if sorted_:
# Sort by groupid for cache efficiency (does this even do anything?)
# I forgot why this is needed? Determenism?
try:
pairs = sorted(pairs, key=op.itemgetter(0))
except TypeError:
# Python 3 does not allow sorting mixed types
pairs = sorted(pairs, key=lambda tup: str(tup[0]))
else:
pairs = items
# Initialize a dict of lists
groupid_to_items = defaultdict(list)
# Insert each item into the correct group
for groupid, item in pairs:
groupid_to_items[groupid].append(item)
return groupid_to_items |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 12; 2, function_name:hierarchical_map_vals; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 4, identifier:func; 5, identifier:node; 6, default_parameter; 6, 7; 6, 8; 7, identifier:max_depth; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:depth; 11, integer:0; 12, block; 12, 13; 12, 15; 12, 16; 13, expression_statement; 13, 14; 14, comment; 15, comment; 16, if_statement; 16, 17; 16, 23; 16, 29; 16, 46; 17, not_operator; 17, 18; 18, call; 18, 19; 18, 20; 19, identifier:hasattr; 20, argument_list; 20, 21; 20, 22; 21, identifier:node; 22, string:'items'; 23, block; 23, 24; 24, return_statement; 24, 25; 25, call; 25, 26; 25, 27; 26, identifier:func; 27, argument_list; 27, 28; 28, identifier:node; 29, elif_clause; 29, 30; 29, 37; 29, 38; 30, boolean_operator:and; 30, 31; 30, 34; 31, comparison_operator:is; 31, 32; 31, 33; 32, identifier:max_depth; 33, None; 34, comparison_operator:>=; 34, 35; 34, 36; 35, identifier:depth; 36, identifier:max_depth; 37, comment; 38, block; 38, 39; 38, 45; 39, return_statement; 39, 40; 40, call; 40, 41; 40, 42; 41, identifier:map_dict_vals; 42, argument_list; 42, 43; 42, 44; 43, identifier:func; 44, identifier:node; 45, comment; 46, else_clause; 46, 47; 46, 48; 46, 49; 46, 50; 47, comment; 48, comment; 49, comment; 50, block; 50, 51; 50, 75; 51, expression_statement; 51, 52; 52, assignment; 52, 53; 52, 54; 53, identifier:keyval_list; 54, list_comprehension; 54, 55; 54, 66; 55, tuple; 55, 56; 55, 57; 56, identifier:key; 57, call; 57, 58; 57, 59; 58, identifier:hierarchical_map_vals; 59, argument_list; 59, 60; 59, 61; 59, 62; 59, 63; 60, identifier:func; 61, identifier:val; 62, identifier:max_depth; 63, binary_operator:+; 63, 64; 63, 65; 64, identifier:depth; 65, integer:1; 66, for_in_clause; 66, 67; 66, 70; 67, pattern_list; 67, 68; 67, 69; 68, identifier:key; 69, identifier:val; 70, call; 70, 71; 70, 74; 71, attribute; 71, 72; 71, 73; 72, identifier:node; 73, identifier:items; 74, argument_list; 75, if_statement; 75, 76; 75, 81; 75, 87; 76, call; 76, 77; 76, 78; 77, identifier:isinstance; 78, argument_list; 78, 79; 78, 80; 79, identifier:node; 80, identifier:OrderedDict; 81, block; 81, 82; 82, return_statement; 82, 83; 83, call; 83, 84; 83, 85; 84, identifier:OrderedDict; 85, argument_list; 85, 86; 86, identifier:keyval_list; 87, else_clause; 87, 88; 88, block; 88, 89; 89, return_statement; 89, 90; 90, call; 90, 91; 90, 92; 91, identifier:dict; 92, argument_list; 92, 93; 93, identifier:keyval_list | def hierarchical_map_vals(func, node, max_depth=None, depth=0):
"""
node is a dict tree like structure with leaves of type list
TODO: move to util_dict
CommandLine:
python -m utool.util_dict --exec-hierarchical_map_vals
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 3, 4, 5, 6, 7, 8]
>>> groupids_list = [[1, 2, 1, 2, 1, 2, 1, 2], [3, 2, 2, 2, 3, 1, 1, 1]]
>>> tree = ut.hierarchical_group_items(item_list, groupids_list)
>>> len_tree = ut.hierarchical_map_vals(len, tree)
>>> result = ('len_tree = ' + ut.repr4(len_tree, nl=1))
>>> print(result)
len_tree = {
1: {1: 1, 2: 1, 3: 2},
2: {1: 2, 2: 2},
}
Example1:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> depth = 4
>>> item_list = list(range(2 ** (depth + 1)))
>>> num = len(item_list) // 2
>>> groupids_list = []
>>> total = 0
>>> for level in range(depth):
... num2 = len(item_list) // int((num * 2))
... #nonflat_levelids = [([total + 2 * x + 1] * num + [total + 2 * x + 2] * num) for x in range(num2)]
... nonflat_levelids = [([1] * num + [2] * num) for x in range(num2)]
... levelids = ut.flatten(nonflat_levelids)
... groupids_list.append(levelids)
... total += num2 * 2
... num //= 2
>>> print('groupids_list = %s' % (ut.repr4(groupids_list, nl=1),))
>>> print('depth = %r' % (len(groupids_list),))
>>> tree = ut.hierarchical_group_items(item_list, groupids_list)
>>> print('tree = ' + ut.repr4(tree, nl=None))
>>> flat_tree_values = list(ut.iflatten_dict_values(tree))
>>> assert sorted(flat_tree_values) == sorted(item_list)
>>> print('flat_tree_values = ' + str(flat_tree_values))
>>> #print('flat_tree_keys = ' + str(list(ut.iflatten_dict_keys(tree))))
>>> #print('iflatten_dict_items = ' + str(list(ut.iflatten_dict_items(tree))))
>>> len_tree = ut.hierarchical_map_vals(len, tree, max_depth=4)
>>> result = ('len_tree = ' + ut.repr4(len_tree, nl=None))
>>> print(result)
"""
#if not isinstance(node, dict):
if not hasattr(node, 'items'):
return func(node)
elif max_depth is not None and depth >= max_depth:
#return func(node)
return map_dict_vals(func, node)
#return {key: func(val) for key, val in six.iteritems(node)}
else:
# recursion
#return {key: hierarchical_map_vals(func, val, max_depth, depth + 1) for key, val in six.iteritems(node)}
#keyval_list = [(key, hierarchical_map_vals(func, val, max_depth, depth + 1)) for key, val in six.iteritems(node)]
keyval_list = [(key, hierarchical_map_vals(func, val, max_depth, depth + 1)) for key, val in node.items()]
if isinstance(node, OrderedDict):
return OrderedDict(keyval_list)
else:
return dict(keyval_list) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 14; 2, function_name:sort_dict; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 4, identifier:dict_; 5, default_parameter; 5, 6; 5, 7; 6, identifier:part; 7, string:'keys'; 8, default_parameter; 8, 9; 8, 10; 9, identifier:key; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:reverse; 13, False; 14, block; 14, 15; 14, 17; 14, 47; 14, 75; 14, 93; 14, 100; 15, expression_statement; 15, 16; 16, comment; 17, if_statement; 17, 18; 17, 21; 17, 26; 17, 37; 18, comparison_operator:==; 18, 19; 18, 20; 19, identifier:part; 20, string:'keys'; 21, block; 21, 22; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:index; 25, integer:0; 26, elif_clause; 26, 27; 26, 32; 27, comparison_operator:in; 27, 28; 27, 29; 28, identifier:part; 29, set; 29, 30; 29, 31; 30, string:'vals'; 31, string:'values'; 32, block; 32, 33; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:index; 36, integer:1; 37, else_clause; 37, 38; 38, block; 38, 39; 39, raise_statement; 39, 40; 40, call; 40, 41; 40, 42; 41, identifier:ValueError; 42, argument_list; 42, 43; 43, binary_operator:%; 43, 44; 43, 45; 44, string:'Unknown method part=%r'; 45, tuple; 45, 46; 46, identifier:part; 47, if_statement; 47, 48; 47, 51; 47, 61; 48, comparison_operator:is; 48, 49; 48, 50; 49, identifier:key; 50, None; 51, block; 51, 52; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:_key; 55, call; 55, 56; 55, 59; 56, attribute; 56, 57; 56, 58; 57, identifier:op; 58, identifier:itemgetter; 59, argument_list; 59, 60; 60, identifier:index; 61, else_clause; 61, 62; 62, block; 62, 63; 63, function_definition; 63, 64; 63, 65; 63, 67; 64, function_name:_key; 65, parameters; 65, 66; 66, identifier:item; 67, block; 67, 68; 68, return_statement; 68, 69; 69, call; 69, 70; 69, 71; 70, identifier:key; 71, argument_list; 71, 72; 72, subscript; 72, 73; 72, 74; 73, identifier:item; 74, identifier:index; 75, expression_statement; 75, 76; 76, assignment; 76, 77; 76, 78; 77, identifier:sorted_items; 78, call; 78, 79; 78, 80; 79, identifier:sorted; 80, argument_list; 80, 81; 80, 87; 80, 90; 81, call; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:six; 84, identifier:iteritems; 85, argument_list; 85, 86; 86, identifier:dict_; 87, keyword_argument; 87, 88; 87, 89; 88, identifier:key; 89, identifier:_key; 90, keyword_argument; 90, 91; 90, 92; 91, identifier:reverse; 92, identifier:reverse; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:sorted_dict; 96, call; 96, 97; 96, 98; 97, identifier:OrderedDict; 98, argument_list; 98, 99; 99, identifier:sorted_items; 100, return_statement; 100, 101; 101, identifier:sorted_dict | def sort_dict(dict_, part='keys', key=None, reverse=False):
"""
sorts a dictionary by its values or its keys
Args:
dict_ (dict_): a dictionary
part (str): specifies to sort by keys or values
key (Optional[func]): a function that takes specified part
and returns a sortable value
reverse (bool): (Defaults to False) - True for descinding order. False
for ascending order.
Returns:
OrderedDict: sorted dictionary
CommandLine:
python -m utool.util_dict sort_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'a': 3, 'c': 2, 'b': 1}
>>> results = []
>>> results.append(sort_dict(dict_, 'keys'))
>>> results.append(sort_dict(dict_, 'vals'))
>>> results.append(sort_dict(dict_, 'vals', lambda x: -x))
>>> result = ut.repr4(results)
>>> print(result)
[
{'a': 3, 'b': 1, 'c': 2},
{'b': 1, 'c': 2, 'a': 3},
{'a': 3, 'c': 2, 'b': 1},
]
"""
if part == 'keys':
index = 0
elif part in {'vals', 'values'}:
index = 1
else:
raise ValueError('Unknown method part=%r' % (part,))
if key is None:
_key = op.itemgetter(index)
else:
def _key(item):
return key(item[index])
sorted_items = sorted(six.iteritems(dict_), key=_key, reverse=reverse)
sorted_dict = OrderedDict(sorted_items)
return sorted_dict |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:order_dict_by; 3, parameters; 3, 4; 3, 5; 4, identifier:dict_; 5, identifier:key_order; 6, block; 6, 7; 6, 9; 6, 20; 6, 29; 6, 39; 6, 57; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:dict_keys; 12, call; 12, 13; 12, 14; 13, identifier:set; 14, argument_list; 14, 15; 15, call; 15, 16; 15, 19; 16, attribute; 16, 17; 16, 18; 17, identifier:dict_; 18, identifier:keys; 19, argument_list; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:other_keys; 23, binary_operator:-; 23, 24; 23, 25; 24, identifier:dict_keys; 25, call; 25, 26; 25, 27; 26, identifier:set; 27, argument_list; 27, 28; 28, identifier:key_order; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:key_order; 32, call; 32, 33; 32, 36; 33, attribute; 33, 34; 33, 35; 34, identifier:it; 35, identifier:chain; 36, argument_list; 36, 37; 36, 38; 37, identifier:key_order; 38, identifier:other_keys; 39, expression_statement; 39, 40; 40, assignment; 40, 41; 40, 42; 41, identifier:sorted_dict; 42, call; 42, 43; 42, 44; 43, identifier:OrderedDict; 44, generator_expression; 44, 45; 44, 50; 44, 53; 45, tuple; 45, 46; 45, 47; 46, identifier:key; 47, subscript; 47, 48; 47, 49; 48, identifier:dict_; 49, identifier:key; 50, for_in_clause; 50, 51; 50, 52; 51, identifier:key; 52, identifier:key_order; 53, if_clause; 53, 54; 54, comparison_operator:in; 54, 55; 54, 56; 55, identifier:key; 56, identifier:dict_keys; 57, return_statement; 57, 58; 58, identifier:sorted_dict | def order_dict_by(dict_, key_order):
r"""
Reorders items in a dictionary according to a custom key order
Args:
dict_ (dict_): a dictionary
key_order (list): custom key order
Returns:
OrderedDict: sorted_dict
CommandLine:
python -m utool.util_dict --exec-order_dict_by
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: 1, 2: 2, 3: 3, 4: 4}
>>> key_order = [4, 2, 3, 1]
>>> sorted_dict = order_dict_by(dict_, key_order)
>>> result = ('sorted_dict = %s' % (ut.repr4(sorted_dict, nl=False),))
>>> print(result)
>>> assert result == 'sorted_dict = {4: 4, 2: 2, 3: 3, 1: 1}'
"""
dict_keys = set(dict_.keys())
other_keys = dict_keys - set(key_order)
key_order = it.chain(key_order, other_keys)
sorted_dict = OrderedDict(
(key, dict_[key]) for key in key_order if key in dict_keys
)
return sorted_dict |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:iteritems_sorted; 3, parameters; 3, 4; 4, identifier:dict_; 5, block; 5, 6; 5, 8; 6, expression_statement; 6, 7; 7, comment; 8, if_statement; 8, 9; 8, 14; 8, 22; 9, call; 9, 10; 9, 11; 10, identifier:isinstance; 11, argument_list; 11, 12; 11, 13; 12, identifier:dict_; 13, identifier:OrderedDict; 14, block; 14, 15; 15, return_statement; 15, 16; 16, call; 16, 17; 16, 20; 17, attribute; 17, 18; 17, 19; 18, identifier:six; 19, identifier:iteritems; 20, argument_list; 20, 21; 21, identifier:dict_; 22, else_clause; 22, 23; 23, block; 23, 24; 24, return_statement; 24, 25; 25, call; 25, 26; 25, 27; 26, identifier:iter; 27, argument_list; 27, 28; 28, call; 28, 29; 28, 30; 29, identifier:sorted; 30, argument_list; 30, 31; 31, call; 31, 32; 31, 35; 32, attribute; 32, 33; 32, 34; 33, identifier:six; 34, identifier:iteritems; 35, argument_list; 35, 36; 36, identifier:dict_ | def iteritems_sorted(dict_):
""" change to iteritems ordered """
if isinstance(dict_, OrderedDict):
return six.iteritems(dict_)
else:
return iter(sorted(six.iteritems(dict_))) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:num_fmt; 3, parameters; 3, 4; 3, 5; 4, identifier:num; 5, default_parameter; 5, 6; 5, 7; 6, identifier:max_digits; 7, None; 8, block; 8, 9; 8, 11; 8, 18; 8, 36; 8, 72; 9, expression_statement; 9, 10; 10, comment; 11, if_statement; 11, 12; 11, 15; 12, comparison_operator:is; 12, 13; 12, 14; 13, identifier:num; 14, None; 15, block; 15, 16; 16, return_statement; 16, 17; 17, string:'None'; 18, function_definition; 18, 19; 18, 20; 18, 23; 19, function_name:num_in_mag; 20, parameters; 20, 21; 20, 22; 21, identifier:num; 22, identifier:mag; 23, block; 23, 24; 24, return_statement; 24, 25; 25, boolean_operator:and; 25, 26; 25, 29; 26, comparison_operator:>; 26, 27; 26, 28; 27, identifier:mag; 28, identifier:num; 29, comparison_operator:>; 29, 30; 29, 31; 30, identifier:num; 31, parenthesized_expression; 31, 32; 32, binary_operator:*; 32, 33; 32, 35; 33, unary_operator:-; 33, 34; 34, integer:1; 35, identifier:mag; 36, if_statement; 36, 37; 36, 40; 36, 41; 37, comparison_operator:is; 37, 38; 37, 39; 38, identifier:max_digits; 39, None; 40, comment; 41, block; 41, 42; 42, if_statement; 42, 43; 42, 48; 42, 66; 43, call; 43, 44; 43, 45; 44, identifier:num_in_mag; 45, argument_list; 45, 46; 45, 47; 46, identifier:num; 47, integer:1; 48, block; 48, 49; 49, if_statement; 49, 50; 49, 55; 49, 60; 50, call; 50, 51; 50, 52; 51, identifier:num_in_mag; 52, argument_list; 52, 53; 52, 54; 53, identifier:num; 54, float:.1; 55, block; 55, 56; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:max_digits; 59, integer:4; 60, else_clause; 60, 61; 61, block; 61, 62; 62, expression_statement; 62, 63; 63, assignment; 63, 64; 63, 65; 64, identifier:max_digits; 65, integer:3; 66, else_clause; 66, 67; 67, block; 67, 68; 68, expression_statement; 68, 69; 69, assignment; 69, 70; 69, 71; 70, identifier:max_digits; 71, integer:1; 72, if_statement; 72, 73; 72, 79; 72, 139; 72, 152; 73, call; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:util_type; 76, identifier:is_float; 77, argument_list; 77, 78; 78, identifier:num; 79, block; 79, 80; 79, 94; 79, 95; 79, 109; 79, 123; 79, 137; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:num_str; 83, binary_operator:%; 83, 84; 83, 93; 84, parenthesized_expression; 84, 85; 85, binary_operator:+; 85, 86; 85, 92; 86, binary_operator:+; 86, 87; 86, 88; 87, string:'%.'; 88, call; 88, 89; 88, 90; 89, identifier:str; 90, argument_list; 90, 91; 91, identifier:max_digits; 92, string:'f'; 93, identifier:num; 94, comment; 95, expression_statement; 95, 96; 96, assignment; 96, 97; 96, 98; 97, identifier:num_str; 98, call; 98, 99; 98, 107; 99, attribute; 99, 100; 99, 106; 100, call; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:num_str; 103, identifier:rstrip; 104, argument_list; 104, 105; 105, string:'0'; 106, identifier:lstrip; 107, argument_list; 107, 108; 108, string:'0'; 109, if_statement; 109, 110; 109, 116; 110, call; 110, 111; 110, 114; 111, attribute; 111, 112; 111, 113; 112, identifier:num_str; 113, identifier:startswith; 114, argument_list; 114, 115; 115, string:'.'; 116, block; 116, 117; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 120; 119, identifier:num_str; 120, binary_operator:+; 120, 121; 120, 122; 121, string:'0'; 122, identifier:num_str; 123, if_statement; 123, 124; 123, 130; 124, call; 124, 125; 124, 128; 125, attribute; 125, 126; 125, 127; 126, identifier:num_str; 127, identifier:endswith; 128, argument_list; 128, 129; 129, string:'.'; 130, block; 130, 131; 131, expression_statement; 131, 132; 132, assignment; 132, 133; 132, 134; 133, identifier:num_str; 134, binary_operator:+; 134, 135; 134, 136; 135, identifier:num_str; 136, string:'0'; 137, return_statement; 137, 138; 138, identifier:num_str; 139, elif_clause; 139, 140; 139, 146; 140, call; 140, 141; 140, 144; 141, attribute; 141, 142; 141, 143; 142, identifier:util_type; 143, identifier:is_int; 144, argument_list; 144, 145; 145, identifier:num; 146, block; 146, 147; 147, return_statement; 147, 148; 148, call; 148, 149; 148, 150; 149, identifier:int_comma_str; 150, argument_list; 150, 151; 151, identifier:num; 152, else_clause; 152, 153; 153, block; 153, 154; 154, return_statement; 154, 155; 155, string:'%r' | def num_fmt(num, max_digits=None):
r"""
Weird function. Not very well written. Very special case-y
Args:
num (int or float):
max_digits (int):
Returns:
str:
CommandLine:
python -m utool.util_num --test-num_fmt
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_num import * # NOQA
>>> # build test data
>>> num_list = [0, 0.0, 1.2, 1003232, 41431232., .0000000343, -.443243]
>>> max_digits = None
>>> # execute function
>>> result = [num_fmt(num, max_digits) for num in num_list]
>>> # verify results
>>> print(result)
['0', '0.0', '1.2', '1,003,232', '41431232.0', '0.0', '-0.443']
"""
if num is None:
return 'None'
def num_in_mag(num, mag):
return mag > num and num > (-1 * mag)
if max_digits is None:
# TODO: generalize
if num_in_mag(num, 1):
if num_in_mag(num, .1):
max_digits = 4
else:
max_digits = 3
else:
max_digits = 1
if util_type.is_float(num):
num_str = ('%.' + str(max_digits) + 'f') % num
# Handle trailing and leading zeros
num_str = num_str.rstrip('0').lstrip('0')
if num_str.startswith('.'):
num_str = '0' + num_str
if num_str.endswith('.'):
num_str = num_str + '0'
return num_str
elif util_type.is_int(num):
return int_comma_str(num)
else:
return '%r' |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 16; 2, function_name:inject_print_functions; 3, parameters; 3, 4; 3, 7; 3, 10; 3, 13; 4, default_parameter; 4, 5; 4, 6; 5, identifier:module_name; 6, None; 7, default_parameter; 7, 8; 7, 9; 8, identifier:module_prefix; 9, string:'[???]'; 10, default_parameter; 10, 11; 10, 12; 11, identifier:DEBUG; 12, False; 13, default_parameter; 13, 14; 13, 15; 14, identifier:module; 15, None; 16, block; 16, 17; 16, 19; 16, 27; 16, 345; 16, 346; 16, 353; 17, expression_statement; 17, 18; 18, comment; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:module; 22, call; 22, 23; 22, 24; 23, identifier:_get_module; 24, argument_list; 24, 25; 24, 26; 25, identifier:module_name; 26, identifier:module; 27, if_statement; 27, 28; 27, 29; 27, 57; 28, identifier:SILENT; 29, block; 29, 30; 29, 39; 29, 48; 30, function_definition; 30, 31; 30, 32; 30, 35; 31, function_name:print; 32, parameters; 32, 33; 33, list_splat_pattern; 33, 34; 34, identifier:args; 35, block; 35, 36; 35, 38; 36, expression_statement; 36, 37; 37, comment; 38, pass_statement; 39, function_definition; 39, 40; 39, 41; 39, 44; 40, function_name:printDBG; 41, parameters; 41, 42; 42, list_splat_pattern; 42, 43; 43, identifier:args; 44, block; 44, 45; 44, 47; 45, expression_statement; 45, 46; 46, comment; 47, pass_statement; 48, function_definition; 48, 49; 48, 50; 48, 53; 49, function_name:print_; 50, parameters; 50, 51; 51, list_splat_pattern; 51, 52; 52, identifier:args; 53, block; 53, 54; 53, 56; 54, expression_statement; 54, 55; 55, comment; 56, pass_statement; 57, else_clause; 57, 58; 58, block; 58, 59; 58, 126; 58, 175; 58, 176; 58, 187; 58, 213; 58, 238; 58, 247; 58, 256; 58, 273; 58, 286; 59, if_statement; 59, 60; 59, 61; 59, 62; 59, 106; 60, identifier:DEBUG_PRINT; 61, comment; 62, block; 62, 63; 63, function_definition; 63, 64; 63, 65; 63, 68; 64, function_name:print; 65, parameters; 65, 66; 66, list_splat_pattern; 66, 67; 67, identifier:args; 68, block; 68, 69; 68, 71; 68, 78; 68, 95; 69, expression_statement; 69, 70; 70, comment; 71, import_from_statement; 71, 72; 71, 76; 72, dotted_name; 72, 73; 72, 74; 72, 75; 73, identifier:utool; 74, identifier:_internal; 75, identifier:meta_util_dbg; 76, dotted_name; 76, 77; 77, identifier:get_caller_name; 78, expression_statement; 78, 79; 79, assignment; 79, 80; 79, 81; 80, identifier:calltag; 81, call; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, string:''; 84, identifier:join; 85, argument_list; 85, 86; 86, tuple; 86, 87; 86, 88; 86, 94; 87, string:'[caller:'; 88, call; 88, 89; 88, 90; 89, identifier:get_caller_name; 90, argument_list; 90, 91; 91, keyword_argument; 91, 92; 91, 93; 92, identifier:N; 93, identifier:DEBUG_PRINT_N; 94, string:']'; 95, expression_statement; 95, 96; 96, call; 96, 97; 96, 102; 97, call; 97, 98; 97, 101; 98, attribute; 98, 99; 98, 100; 99, identifier:util_logging; 100, identifier:_utool_print; 101, argument_list; 102, argument_list; 102, 103; 102, 104; 103, identifier:calltag; 104, list_splat; 104, 105; 105, identifier:args; 106, else_clause; 106, 107; 107, block; 107, 108; 108, function_definition; 108, 109; 108, 110; 108, 113; 109, function_name:print; 110, parameters; 110, 111; 111, list_splat_pattern; 111, 112; 112, identifier:args; 113, block; 113, 114; 113, 116; 114, expression_statement; 114, 115; 115, comment; 116, expression_statement; 116, 117; 117, call; 117, 118; 117, 123; 118, call; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:util_logging; 121, identifier:_utool_print; 122, argument_list; 123, argument_list; 123, 124; 124, list_splat; 124, 125; 125, identifier:args; 126, if_statement; 126, 127; 126, 128; 126, 155; 127, identifier:__AGGROFLUSH__; 128, block; 128, 129; 129, function_definition; 129, 130; 129, 131; 129, 134; 130, function_name:print_; 131, parameters; 131, 132; 132, list_splat_pattern; 132, 133; 133, identifier:args; 134, block; 134, 135; 134, 137; 134, 147; 135, expression_statement; 135, 136; 136, comment; 137, expression_statement; 137, 138; 138, call; 138, 139; 138, 144; 139, call; 139, 140; 139, 143; 140, attribute; 140, 141; 140, 142; 141, identifier:util_logging; 142, identifier:_utool_write; 143, argument_list; 144, argument_list; 144, 145; 145, list_splat; 145, 146; 146, identifier:args; 147, expression_statement; 147, 148; 148, call; 148, 149; 148, 154; 149, call; 149, 150; 149, 153; 150, attribute; 150, 151; 150, 152; 151, identifier:util_logging; 152, identifier:_utool_flush; 153, argument_list; 154, argument_list; 155, else_clause; 155, 156; 156, block; 156, 157; 157, function_definition; 157, 158; 157, 159; 157, 162; 158, function_name:print_; 159, parameters; 159, 160; 160, list_splat_pattern; 160, 161; 161, identifier:args; 162, block; 162, 163; 162, 165; 163, expression_statement; 163, 164; 164, comment; 165, expression_statement; 165, 166; 166, call; 166, 167; 166, 172; 167, call; 167, 168; 167, 171; 168, attribute; 168, 169; 168, 170; 169, identifier:util_logging; 170, identifier:_utool_write; 171, argument_list; 172, argument_list; 172, 173; 173, list_splat; 173, 174; 174, identifier:args; 175, comment; 176, expression_statement; 176, 177; 177, assignment; 177, 178; 177, 179; 178, identifier:dotpos; 179, call; 179, 180; 179, 185; 180, attribute; 180, 181; 180, 184; 181, attribute; 181, 182; 181, 183; 182, identifier:module; 183, identifier:__name__; 184, identifier:rfind; 185, argument_list; 185, 186; 186, string:'.'; 187, if_statement; 187, 188; 187, 192; 187, 199; 188, comparison_operator:==; 188, 189; 188, 190; 189, identifier:dotpos; 190, unary_operator:-; 190, 191; 191, integer:1; 192, block; 192, 193; 193, expression_statement; 193, 194; 194, assignment; 194, 195; 194, 196; 195, identifier:module_name; 196, attribute; 196, 197; 196, 198; 197, identifier:module; 198, identifier:__name__; 199, else_clause; 199, 200; 200, block; 200, 201; 201, expression_statement; 201, 202; 202, assignment; 202, 203; 202, 204; 203, identifier:module_name; 204, subscript; 204, 205; 204, 208; 205, attribute; 205, 206; 205, 207; 206, identifier:module; 207, identifier:__name__; 208, slice; 208, 209; 208, 212; 209, binary_operator:+; 209, 210; 209, 211; 210, identifier:dotpos; 211, integer:1; 212, colon; 213, function_definition; 213, 214; 213, 215; 213, 217; 214, function_name:_replchars; 215, parameters; 215, 216; 216, identifier:str_; 217, block; 217, 218; 218, return_statement; 218, 219; 219, call; 219, 220; 219, 235; 220, attribute; 220, 221; 220, 234; 221, call; 221, 222; 221, 231; 222, attribute; 222, 223; 222, 230; 223, call; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:str_; 226, identifier:replace; 227, argument_list; 227, 228; 227, 229; 228, string:'_'; 229, string:'-'; 230, identifier:replace; 231, argument_list; 231, 232; 231, 233; 232, string:']'; 233, string:''; 234, identifier:replace; 235, argument_list; 235, 236; 235, 237; 236, string:'['; 237, string:''; 238, expression_statement; 238, 239; 239, assignment; 239, 240; 239, 241; 240, identifier:flag1; 241, binary_operator:%; 241, 242; 241, 243; 242, string:'--debug-%s'; 243, call; 243, 244; 243, 245; 244, identifier:_replchars; 245, argument_list; 245, 246; 246, identifier:module_name; 247, expression_statement; 247, 248; 248, assignment; 248, 249; 248, 250; 249, identifier:flag2; 250, binary_operator:%; 250, 251; 250, 252; 251, string:'--debug-%s'; 252, call; 252, 253; 252, 254; 253, identifier:_replchars; 254, argument_list; 254, 255; 255, identifier:module_prefix; 256, expression_statement; 256, 257; 257, assignment; 257, 258; 257, 259; 258, identifier:DEBUG_FLAG; 259, call; 259, 260; 259, 261; 260, identifier:any; 261, argument_list; 261, 262; 262, list_comprehension; 262, 263; 262, 268; 263, comparison_operator:in; 263, 264; 263, 265; 264, identifier:flag; 265, attribute; 265, 266; 265, 267; 266, identifier:sys; 267, identifier:argv; 268, for_in_clause; 268, 269; 268, 270; 269, identifier:flag; 270, list:[flag1, flag2]; 270, 271; 270, 272; 271, identifier:flag1; 272, identifier:flag2; 273, for_statement; 273, 274; 273, 275; 273, 276; 274, identifier:curflag; 275, identifier:ARGV_DEBUG_FLAGS; 276, block; 276, 277; 277, if_statement; 277, 278; 277, 281; 278, comparison_operator:in; 278, 279; 278, 280; 279, identifier:curflag; 280, identifier:module_prefix; 281, block; 281, 282; 282, expression_statement; 282, 283; 283, assignment; 283, 284; 283, 285; 284, identifier:DEBUG_FLAG; 285, True; 286, if_statement; 286, 287; 286, 292; 286, 334; 287, boolean_operator:or; 287, 288; 287, 291; 288, boolean_operator:or; 288, 289; 288, 290; 289, identifier:__DEBUG_ALL__; 290, identifier:DEBUG; 291, identifier:DEBUG_FLAG; 292, block; 292, 293; 292, 302; 293, expression_statement; 293, 294; 294, call; 294, 295; 294, 296; 295, identifier:print; 296, argument_list; 296, 297; 297, binary_operator:%; 297, 298; 297, 299; 298, string:'INJECT_PRINT: %r == %r'; 299, tuple; 299, 300; 299, 301; 300, identifier:module_name; 301, identifier:module_prefix; 302, function_definition; 302, 303; 302, 304; 302, 307; 303, function_name:printDBG; 304, parameters; 304, 305; 305, list_splat_pattern; 305, 306; 306, identifier:args; 307, block; 307, 308; 307, 310; 307, 323; 308, expression_statement; 308, 309; 309, comment; 310, expression_statement; 310, 311; 311, assignment; 311, 312; 311, 313; 312, identifier:msg; 313, call; 313, 314; 313, 317; 314, attribute; 314, 315; 314, 316; 315, string:', '; 316, identifier:join; 317, argument_list; 317, 318; 318, call; 318, 319; 318, 320; 319, identifier:map; 320, argument_list; 320, 321; 320, 322; 321, identifier:str; 322, identifier:args; 323, expression_statement; 323, 324; 324, call; 324, 325; 324, 328; 325, attribute; 325, 326; 325, 327; 326, identifier:util_logging; 327, identifier:__UTOOL_PRINTDBG__; 328, argument_list; 328, 329; 329, binary_operator:+; 329, 330; 329, 333; 330, binary_operator:+; 330, 331; 330, 332; 331, identifier:module_prefix; 332, string:' DEBUG '; 333, identifier:msg; 334, else_clause; 334, 335; 335, block; 335, 336; 336, function_definition; 336, 337; 336, 338; 336, 341; 337, function_name:printDBG; 338, parameters; 338, 339; 339, list_splat_pattern; 339, 340; 340, identifier:args; 341, block; 341, 342; 341, 344; 342, expression_statement; 342, 343; 343, comment; 344, pass_statement; 345, comment; 346, expression_statement; 346, 347; 347, assignment; 347, 348; 347, 349; 348, identifier:print_funcs; 349, tuple; 349, 350; 349, 351; 349, 352; 350, identifier:print; 351, identifier:print_; 352, identifier:printDBG; 353, return_statement; 353, 354; 354, identifier:print_funcs | def inject_print_functions(module_name=None, module_prefix='[???]',
DEBUG=False, module=None):
"""
makes print functions to be injected into the module
"""
module = _get_module(module_name, module)
if SILENT:
def print(*args):
""" silent builtins.print """
pass
def printDBG(*args):
""" silent debug print """
pass
def print_(*args):
""" silent stdout.write """
pass
else:
if DEBUG_PRINT:
# Turns on printing where a message came from
def print(*args):
""" debugging logging builtins.print """
from utool._internal.meta_util_dbg import get_caller_name
calltag = ''.join(('[caller:', get_caller_name(N=DEBUG_PRINT_N), ']' ))
util_logging._utool_print()(calltag, *args)
else:
def print(*args):
""" logging builtins.print """
util_logging._utool_print()(*args)
if __AGGROFLUSH__:
def print_(*args):
""" aggressive logging stdout.write """
util_logging._utool_write()(*args)
util_logging._utool_flush()()
else:
def print_(*args):
""" logging stdout.write """
util_logging._utool_write()(*args)
# turn on module debugging with command line flags
dotpos = module.__name__.rfind('.')
if dotpos == -1:
module_name = module.__name__
else:
module_name = module.__name__[dotpos + 1:]
def _replchars(str_):
return str_.replace('_', '-').replace(']', '').replace('[', '')
flag1 = '--debug-%s' % _replchars(module_name)
flag2 = '--debug-%s' % _replchars(module_prefix)
DEBUG_FLAG = any([flag in sys.argv for flag in [flag1, flag2]])
for curflag in ARGV_DEBUG_FLAGS:
if curflag in module_prefix:
DEBUG_FLAG = True
if __DEBUG_ALL__ or DEBUG or DEBUG_FLAG:
print('INJECT_PRINT: %r == %r' % (module_name, module_prefix))
def printDBG(*args):
""" debug logging print """
msg = ', '.join(map(str, args))
util_logging.__UTOOL_PRINTDBG__(module_prefix + ' DEBUG ' + msg)
else:
def printDBG(*args):
""" silent debug logging print """
pass
#_inject_funcs(module, print, print_, printDBG)
print_funcs = (print, print_, printDBG)
return print_funcs |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 13; 2, function_name:get_isobaric_ratios; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 4, identifier:psmfn; 5, identifier:psmheader; 6, identifier:channels; 7, identifier:denom_channels; 8, identifier:min_int; 9, identifier:targetfn; 10, identifier:accessioncol; 11, identifier:normalize; 12, identifier:normratiofn; 13, block; 13, 14; 13, 16; 13, 28; 13, 114; 13, 115; 13, 116; 14, expression_statement; 14, 15; 15, comment; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:psm_or_feat_ratios; 19, call; 19, 20; 19, 21; 20, identifier:get_psmratios; 21, argument_list; 21, 22; 21, 23; 21, 24; 21, 25; 21, 26; 21, 27; 22, identifier:psmfn; 23, identifier:psmheader; 24, identifier:channels; 25, identifier:denom_channels; 26, identifier:min_int; 27, identifier:accessioncol; 28, if_statement; 28, 29; 28, 32; 28, 71; 28, 108; 29, boolean_operator:and; 29, 30; 29, 31; 30, identifier:normalize; 31, identifier:normratiofn; 32, block; 32, 33; 32, 42; 32, 51; 32, 62; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:normheader; 36, call; 36, 37; 36, 40; 37, attribute; 37, 38; 37, 39; 38, identifier:reader; 39, identifier:get_tsv_header; 40, argument_list; 40, 41; 41, identifier:normratiofn; 42, expression_statement; 42, 43; 43, assignment; 43, 44; 43, 45; 44, identifier:normratios; 45, call; 45, 46; 45, 47; 46, identifier:get_ratios_from_fn; 47, argument_list; 47, 48; 47, 49; 47, 50; 48, identifier:normratiofn; 49, identifier:normheader; 50, identifier:channels; 51, expression_statement; 51, 52; 52, assignment; 52, 53; 52, 54; 53, identifier:ch_medians; 54, call; 54, 55; 54, 56; 55, identifier:get_medians; 56, argument_list; 56, 57; 56, 58; 56, 59; 57, identifier:channels; 58, identifier:normratios; 59, keyword_argument; 59, 60; 59, 61; 60, identifier:report; 61, True; 62, expression_statement; 62, 63; 63, assignment; 63, 64; 63, 65; 64, identifier:outratios; 65, call; 65, 66; 65, 67; 66, identifier:calculate_normalized_ratios; 67, argument_list; 67, 68; 67, 69; 67, 70; 68, identifier:psm_or_feat_ratios; 69, identifier:ch_medians; 70, identifier:channels; 71, elif_clause; 71, 72; 71, 73; 72, identifier:normalize; 73, block; 73, 74; 73, 88; 73, 99; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 77; 76, identifier:flatratios; 77, list_comprehension; 77, 78; 77, 85; 78, list_comprehension; 78, 79; 78, 82; 79, subscript; 79, 80; 79, 81; 80, identifier:feat; 81, identifier:ch; 82, for_in_clause; 82, 83; 82, 84; 83, identifier:ch; 84, identifier:channels; 85, for_in_clause; 85, 86; 85, 87; 86, identifier:feat; 87, identifier:psm_or_feat_ratios; 88, expression_statement; 88, 89; 89, assignment; 89, 90; 89, 91; 90, identifier:ch_medians; 91, call; 91, 92; 91, 93; 92, identifier:get_medians; 93, argument_list; 93, 94; 93, 95; 93, 96; 94, identifier:channels; 95, identifier:flatratios; 96, keyword_argument; 96, 97; 96, 98; 97, identifier:report; 98, True; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:outratios; 102, call; 102, 103; 102, 104; 103, identifier:calculate_normalized_ratios; 104, argument_list; 104, 105; 104, 106; 104, 107; 105, identifier:psm_or_feat_ratios; 106, identifier:ch_medians; 107, identifier:channels; 108, else_clause; 108, 109; 109, block; 109, 110; 110, expression_statement; 110, 111; 111, assignment; 111, 112; 111, 113; 112, identifier:outratios; 113, identifier:psm_or_feat_ratios; 114, comment; 115, comment; 116, if_statement; 116, 117; 116, 120; 116, 140; 116, 154; 117, boolean_operator:and; 117, 118; 117, 119; 118, identifier:accessioncol; 119, identifier:targetfn; 120, block; 120, 121; 120, 133; 121, expression_statement; 121, 122; 122, assignment; 122, 123; 122, 124; 123, identifier:outratios; 124, dictionary_comprehension; 124, 125; 124, 130; 125, pair; 125, 126; 125, 129; 126, subscript; 126, 127; 126, 128; 127, identifier:x; 128, identifier:ISOQUANTRATIO_FEAT_ACC; 129, identifier:x; 130, for_in_clause; 130, 131; 130, 132; 131, identifier:x; 132, identifier:outratios; 133, return_statement; 133, 134; 134, call; 134, 135; 134, 136; 135, identifier:output_to_target_accession_table; 136, argument_list; 136, 137; 136, 138; 136, 139; 137, identifier:targetfn; 138, identifier:outratios; 139, identifier:channels; 140, elif_clause; 140, 141; 140, 146; 141, boolean_operator:and; 141, 142; 141, 144; 142, not_operator; 142, 143; 143, identifier:accessioncol; 144, not_operator; 144, 145; 145, identifier:targetfn; 146, block; 146, 147; 147, return_statement; 147, 148; 148, call; 148, 149; 148, 150; 149, identifier:paste_to_psmtable; 150, argument_list; 150, 151; 150, 152; 150, 153; 151, identifier:psmfn; 152, identifier:psmheader; 153, identifier:outratios; 154, elif_clause; 154, 155; 154, 159; 154, 160; 155, boolean_operator:and; 155, 156; 155, 157; 156, identifier:accessioncol; 157, not_operator; 157, 158; 158, identifier:targetfn; 159, comment; 160, block; 160, 161; 161, return_statement; 161, 162; 162, generator_expression; 162, 163; 162, 185; 163, dictionary_comprehension; 163, 164; 163, 176; 164, pair; 164, 165; 164, 175; 165, parenthesized_expression; 165, 166; 166, conditional_expression:if; 166, 167; 166, 168; 166, 172; 167, identifier:k; 168, not_operator; 168, 169; 169, comparison_operator:==; 169, 170; 169, 171; 170, identifier:k; 171, identifier:ISOQUANTRATIO_FEAT_ACC; 172, attribute; 172, 173; 172, 174; 173, identifier:prottabledata; 174, identifier:HEADER_ACCESSION; 175, identifier:v; 176, for_in_clause; 176, 177; 176, 180; 177, pattern_list; 177, 178; 177, 179; 178, identifier:k; 179, identifier:v; 180, call; 180, 181; 180, 184; 181, attribute; 181, 182; 181, 183; 182, identifier:ratio; 183, identifier:items; 184, argument_list; 185, for_in_clause; 185, 186; 185, 187; 186, identifier:ratio; 187, identifier:outratios | def get_isobaric_ratios(psmfn, psmheader, channels, denom_channels, min_int,
targetfn, accessioncol, normalize, normratiofn):
"""Main function to calculate ratios for PSMs, peptides, proteins, genes.
Can do simple ratios, median-of-ratios and median-centering
normalization."""
psm_or_feat_ratios = get_psmratios(psmfn, psmheader, channels,
denom_channels, min_int, accessioncol)
if normalize and normratiofn:
normheader = reader.get_tsv_header(normratiofn)
normratios = get_ratios_from_fn(normratiofn, normheader, channels)
ch_medians = get_medians(channels, normratios, report=True)
outratios = calculate_normalized_ratios(psm_or_feat_ratios, ch_medians,
channels)
elif normalize:
flatratios = [[feat[ch] for ch in channels]
for feat in psm_or_feat_ratios]
ch_medians = get_medians(channels, flatratios, report=True)
outratios = calculate_normalized_ratios(psm_or_feat_ratios, ch_medians,
channels)
else:
outratios = psm_or_feat_ratios
# at this point, outratios look like:
# [{ch1: 123, ch2: 456, ISOQUANTRATIO_FEAT_ACC: ENSG1244}, ]
if accessioncol and targetfn:
outratios = {x[ISOQUANTRATIO_FEAT_ACC]: x for x in outratios}
return output_to_target_accession_table(targetfn, outratios, channels)
elif not accessioncol and not targetfn:
return paste_to_psmtable(psmfn, psmheader, outratios)
elif accessioncol and not targetfn:
# generate new table with accessions
return ({(k if not k == ISOQUANTRATIO_FEAT_ACC
else prottabledata.HEADER_ACCESSION): v
for k, v in ratio.items()} for ratio in outratios) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:clean_line_profile_text; 3, parameters; 3, 4; 4, identifier:text; 5, block; 5, 6; 5, 8; 5, 9; 5, 16; 5, 17; 5, 18; 5, 19; 5, 28; 5, 29; 5, 49; 5, 56; 5, 69; 5, 70; 5, 79; 5, 80; 5, 81; 5, 88; 5, 92; 6, expression_statement; 6, 7; 7, comment; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:profile_block_list; 12, call; 12, 13; 12, 14; 13, identifier:parse_rawprofile_blocks; 14, argument_list; 14, 15; 15, identifier:text; 16, comment; 17, comment; 18, comment; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 24; 21, pattern_list; 21, 22; 21, 23; 22, identifier:prefix_list; 23, identifier:timemap; 24, call; 24, 25; 24, 26; 25, identifier:parse_timemap_from_blocks; 26, argument_list; 26, 27; 27, identifier:profile_block_list; 28, comment; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:sorted_lists; 32, call; 32, 33; 32, 34; 33, identifier:sorted; 34, argument_list; 34, 35; 34, 41; 35, call; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:six; 38, identifier:iteritems; 39, argument_list; 39, 40; 40, identifier:timemap; 41, keyword_argument; 41, 42; 41, 43; 42, identifier:key; 43, call; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:operator; 46, identifier:itemgetter; 47, argument_list; 47, 48; 48, integer:0; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:newlist; 52, subscript; 52, 53; 52, 54; 53, identifier:prefix_list; 54, slice; 54, 55; 55, colon; 56, for_statement; 56, 57; 56, 60; 56, 61; 57, pattern_list; 57, 58; 57, 59; 58, identifier:key; 59, identifier:val; 60, identifier:sorted_lists; 61, block; 61, 62; 62, expression_statement; 62, 63; 63, call; 63, 64; 63, 67; 64, attribute; 64, 65; 64, 66; 65, identifier:newlist; 66, identifier:extend; 67, argument_list; 67, 68; 68, identifier:val; 69, comment; 70, expression_statement; 70, 71; 71, assignment; 71, 72; 71, 73; 72, identifier:output_text; 73, call; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, string:'\n'; 76, identifier:join; 77, argument_list; 77, 78; 78, identifier:newlist; 79, comment; 80, comment; 81, expression_statement; 81, 82; 82, assignment; 82, 83; 82, 84; 83, identifier:summary_text; 84, call; 84, 85; 84, 86; 85, identifier:get_summary; 86, argument_list; 86, 87; 87, identifier:profile_block_list; 88, expression_statement; 88, 89; 89, assignment; 89, 90; 89, 91; 90, identifier:output_text; 91, identifier:output_text; 92, return_statement; 92, 93; 93, expression_list; 93, 94; 93, 95; 94, identifier:output_text; 95, identifier:summary_text | def clean_line_profile_text(text):
"""
Sorts the output from line profile by execution time
Removes entries which were not run
"""
#
profile_block_list = parse_rawprofile_blocks(text)
#profile_block_list = fix_rawprofile_blocks(profile_block_list)
#---
# FIXME can be written much nicer
prefix_list, timemap = parse_timemap_from_blocks(profile_block_list)
# Sort the blocks by time
sorted_lists = sorted(six.iteritems(timemap), key=operator.itemgetter(0))
newlist = prefix_list[:]
for key, val in sorted_lists:
newlist.extend(val)
# Rejoin output text
output_text = '\n'.join(newlist)
#---
# Hack in a profile summary
summary_text = get_summary(profile_block_list)
output_text = output_text
return output_text, summary_text |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:random_product; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:items; 5, default_parameter; 5, 6; 5, 7; 6, identifier:num; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:rng; 10, None; 11, block; 11, 12; 11, 14; 11, 19; 11, 29; 11, 35; 11, 46; 11, 59; 11, 68; 11, 78; 11, 79; 12, expression_statement; 12, 13; 13, comment; 14, import_statement; 14, 15; 15, aliased_import; 15, 16; 15, 18; 16, dotted_name; 16, 17; 17, identifier:utool; 18, identifier:ut; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:rng; 22, call; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:ut; 25, identifier:ensure_rng; 26, argument_list; 26, 27; 26, 28; 27, identifier:rng; 28, string:'python'; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:seen; 32, call; 32, 33; 32, 34; 33, identifier:set; 34, argument_list; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:items; 38, list_comprehension; 38, 39; 38, 43; 39, call; 39, 40; 39, 41; 40, identifier:list; 41, argument_list; 41, 42; 42, identifier:g; 43, for_in_clause; 43, 44; 43, 45; 44, identifier:g; 45, identifier:items; 46, expression_statement; 46, 47; 47, assignment; 47, 48; 47, 49; 48, identifier:max_num; 49, call; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:ut; 52, identifier:prod; 53, argument_list; 53, 54; 54, call; 54, 55; 54, 56; 55, identifier:map; 56, argument_list; 56, 57; 56, 58; 57, identifier:len; 58, identifier:items; 59, if_statement; 59, 60; 59, 63; 60, comparison_operator:is; 60, 61; 60, 62; 61, identifier:num; 62, None; 63, block; 63, 64; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:num; 67, identifier:max_num; 68, if_statement; 68, 69; 68, 72; 69, comparison_operator:>; 69, 70; 69, 71; 70, identifier:num; 71, identifier:max_num; 72, block; 72, 73; 73, raise_statement; 73, 74; 74, call; 74, 75; 74, 76; 75, identifier:ValueError; 76, argument_list; 76, 77; 77, string:'num exceedes maximum number of products'; 78, comment; 79, if_statement; 79, 80; 79, 85; 79, 110; 80, comparison_operator:>; 80, 81; 80, 82; 81, identifier:num; 82, binary_operator://; 82, 83; 82, 84; 83, identifier:max_num; 84, integer:2; 85, block; 85, 86; 86, for_statement; 86, 87; 86, 88; 86, 106; 87, identifier:prod; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:ut; 91, identifier:shuffle; 92, argument_list; 92, 93; 92, 103; 93, call; 93, 94; 93, 95; 94, identifier:list; 95, argument_list; 95, 96; 96, call; 96, 97; 96, 100; 97, attribute; 97, 98; 97, 99; 98, identifier:it; 99, identifier:product; 100, argument_list; 100, 101; 101, list_splat; 101, 102; 102, identifier:items; 103, keyword_argument; 103, 104; 103, 105; 104, identifier:rng; 105, identifier:rng; 106, block; 106, 107; 107, expression_statement; 107, 108; 108, yield; 108, 109; 109, identifier:prod; 110, else_clause; 110, 111; 111, block; 111, 112; 112, while_statement; 112, 113; 112, 119; 112, 120; 113, comparison_operator:<; 113, 114; 113, 118; 114, call; 114, 115; 114, 116; 115, identifier:len; 116, argument_list; 116, 117; 117, identifier:seen; 118, identifier:num; 119, comment; 120, block; 120, 121; 120, 142; 121, expression_statement; 121, 122; 122, assignment; 122, 123; 122, 124; 123, identifier:idxs; 124, call; 124, 125; 124, 126; 125, identifier:tuple; 126, generator_expression; 126, 127; 126, 139; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:rng; 130, identifier:randint; 131, argument_list; 131, 132; 131, 133; 132, integer:0; 133, binary_operator:-; 133, 134; 133, 138; 134, call; 134, 135; 134, 136; 135, identifier:len; 136, argument_list; 136, 137; 137, identifier:g; 138, integer:1; 139, for_in_clause; 139, 140; 139, 141; 140, identifier:g; 141, identifier:items; 142, if_statement; 142, 143; 142, 146; 143, comparison_operator:not; 143, 144; 143, 145; 144, identifier:idxs; 145, identifier:seen; 146, block; 146, 147; 146, 154; 146, 172; 147, expression_statement; 147, 148; 148, call; 148, 149; 148, 152; 149, attribute; 149, 150; 149, 151; 150, identifier:seen; 151, identifier:add; 152, argument_list; 152, 153; 153, identifier:idxs; 154, expression_statement; 154, 155; 155, assignment; 155, 156; 155, 157; 156, identifier:prod; 157, call; 157, 158; 157, 159; 158, identifier:tuple; 159, generator_expression; 159, 160; 159, 163; 160, subscript; 160, 161; 160, 162; 161, identifier:g; 162, identifier:x; 163, for_in_clause; 163, 164; 163, 167; 164, pattern_list; 164, 165; 164, 166; 165, identifier:g; 166, identifier:x; 167, call; 167, 168; 167, 169; 168, identifier:zip; 169, argument_list; 169, 170; 169, 171; 170, identifier:items; 171, identifier:idxs; 172, expression_statement; 172, 173; 173, yield; 173, 174; 174, identifier:prod | def random_product(items, num=None, rng=None):
"""
Yields `num` items from the cartesian product of items in a random order.
Args:
items (list of sequences): items to get caresian product of
packed in a list or tuple.
(note this deviates from api of it.product)
Example:
import utool as ut
items = [(1, 2, 3), (4, 5, 6, 7)]
rng = 0
list(ut.random_product(items, rng=0))
list(ut.random_product(items, num=3, rng=0))
"""
import utool as ut
rng = ut.ensure_rng(rng, 'python')
seen = set()
items = [list(g) for g in items]
max_num = ut.prod(map(len, items))
if num is None:
num = max_num
if num > max_num:
raise ValueError('num exceedes maximum number of products')
# TODO: make this more efficient when num is large
if num > max_num // 2:
for prod in ut.shuffle(list(it.product(*items)), rng=rng):
yield prod
else:
while len(seen) < num:
# combo = tuple(sorted(rng.choice(items, size, replace=False)))
idxs = tuple(rng.randint(0, len(g) - 1) for g in items)
if idxs not in seen:
seen.add(idxs)
prod = tuple(g[x] for g, x in zip(items, idxs))
yield prod |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:parse_dsn; 3, parameters; 3, 4; 4, identifier:dsn_string; 5, block; 5, 6; 5, 8; 5, 15; 5, 28; 5, 38; 5, 44; 5, 90; 5, 113; 5, 130; 5, 152; 5, 163; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:dsn; 11, call; 11, 12; 11, 13; 12, identifier:urlparse; 13, argument_list; 13, 14; 14, identifier:dsn_string; 15, expression_statement; 15, 16; 16, assignment; 16, 17; 16, 18; 17, identifier:scheme; 18, subscript; 18, 19; 18, 27; 19, call; 19, 20; 19, 25; 20, attribute; 20, 21; 20, 24; 21, attribute; 21, 22; 21, 23; 22, identifier:dsn; 23, identifier:scheme; 24, identifier:split; 25, argument_list; 25, 26; 26, string:'+'; 27, integer:0; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:username; 31, assignment; 31, 32; 31, 33; 32, identifier:password; 33, assignment; 33, 34; 33, 35; 34, identifier:host; 35, assignment; 35, 36; 35, 37; 36, identifier:port; 37, None; 38, expression_statement; 38, 39; 39, assignment; 39, 40; 39, 41; 40, identifier:host; 41, attribute; 41, 42; 41, 43; 42, identifier:dsn; 43, identifier:netloc; 44, if_statement; 44, 45; 44, 48; 45, comparison_operator:in; 45, 46; 45, 47; 46, string:'@'; 47, identifier:host; 48, block; 48, 49; 48, 60; 48, 83; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 54; 51, pattern_list; 51, 52; 51, 53; 52, identifier:username; 53, identifier:host; 54, call; 54, 55; 54, 58; 55, attribute; 55, 56; 55, 57; 56, identifier:host; 57, identifier:split; 58, argument_list; 58, 59; 59, string:'@'; 60, if_statement; 60, 61; 60, 64; 61, comparison_operator:in; 61, 62; 61, 63; 62, string:':'; 63, identifier:username; 64, block; 64, 65; 64, 76; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 70; 67, pattern_list; 67, 68; 67, 69; 68, identifier:username; 69, identifier:password; 70, call; 70, 71; 70, 74; 71, attribute; 71, 72; 71, 73; 72, identifier:username; 73, identifier:split; 74, argument_list; 74, 75; 75, string:':'; 76, expression_statement; 76, 77; 77, assignment; 77, 78; 77, 79; 78, identifier:password; 79, call; 79, 80; 79, 81; 80, identifier:unquote; 81, argument_list; 81, 82; 82, identifier:password; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:username; 86, call; 86, 87; 86, 88; 87, identifier:unquote; 88, argument_list; 88, 89; 89, identifier:username; 90, if_statement; 90, 91; 90, 94; 91, comparison_operator:in; 91, 92; 91, 93; 92, string:':'; 93, identifier:host; 94, block; 94, 95; 94, 106; 95, expression_statement; 95, 96; 96, assignment; 96, 97; 96, 100; 97, pattern_list; 97, 98; 97, 99; 98, identifier:host; 99, identifier:port; 100, call; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:host; 103, identifier:split; 104, argument_list; 104, 105; 105, string:':'; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:port; 109, call; 109, 110; 109, 111; 110, identifier:int; 111, argument_list; 111, 112; 112, identifier:port; 113, expression_statement; 113, 114; 114, assignment; 114, 115; 114, 116; 115, identifier:database; 116, subscript; 116, 117; 116, 127; 117, subscript; 117, 118; 117, 126; 118, call; 118, 119; 118, 124; 119, attribute; 119, 120; 119, 123; 120, attribute; 120, 121; 120, 122; 121, identifier:dsn; 122, identifier:path; 123, identifier:split; 124, argument_list; 124, 125; 125, string:'?'; 126, integer:0; 127, slice; 127, 128; 127, 129; 128, integer:1; 129, colon; 130, expression_statement; 130, 131; 131, assignment; 131, 132; 131, 133; 132, identifier:query; 133, conditional_expression:if; 133, 134; 133, 144; 133, 149; 134, subscript; 134, 135; 134, 143; 135, call; 135, 136; 135, 141; 136, attribute; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:dsn; 139, identifier:path; 140, identifier:split; 141, argument_list; 141, 142; 142, string:'?'; 143, integer:1; 144, comparison_operator:in; 144, 145; 144, 146; 145, string:'?'; 146, attribute; 146, 147; 146, 148; 147, identifier:dsn; 148, identifier:path; 149, attribute; 149, 150; 149, 151; 150, identifier:dsn; 151, identifier:query; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:kwargs; 155, call; 155, 156; 155, 157; 156, identifier:dict; 157, argument_list; 157, 158; 158, call; 158, 159; 158, 160; 159, identifier:parse_qsl; 160, argument_list; 160, 161; 160, 162; 161, identifier:query; 162, True; 163, if_statement; 163, 164; 163, 167; 163, 176; 163, 227; 163, 294; 164, comparison_operator:==; 164, 165; 164, 166; 165, identifier:scheme; 166, string:'sqlite'; 167, block; 167, 168; 168, return_statement; 168, 169; 169, expression_list; 169, 170; 169, 171; 169, 175; 170, identifier:SQLiteDriver; 171, list:[dsn.path]; 171, 172; 172, attribute; 172, 173; 172, 174; 173, identifier:dsn; 174, identifier:path; 175, dictionary; 176, elif_clause; 176, 177; 176, 180; 177, comparison_operator:==; 177, 178; 177, 179; 178, identifier:scheme; 179, string:'mysql'; 180, block; 180, 181; 180, 189; 180, 195; 180, 204; 180, 213; 180, 222; 181, expression_statement; 181, 182; 182, assignment; 182, 183; 182, 186; 183, subscript; 183, 184; 183, 185; 184, identifier:kwargs; 185, string:'user'; 186, boolean_operator:or; 186, 187; 186, 188; 187, identifier:username; 188, string:'root'; 189, expression_statement; 189, 190; 190, assignment; 190, 191; 190, 194; 191, subscript; 191, 192; 191, 193; 192, identifier:kwargs; 193, string:'db'; 194, identifier:database; 195, if_statement; 195, 196; 195, 197; 196, identifier:port; 197, block; 197, 198; 198, expression_statement; 198, 199; 199, assignment; 199, 200; 199, 203; 200, subscript; 200, 201; 200, 202; 201, identifier:kwargs; 202, string:'port'; 203, identifier:port; 204, if_statement; 204, 205; 204, 206; 205, identifier:host; 206, block; 206, 207; 207, expression_statement; 207, 208; 208, assignment; 208, 209; 208, 212; 209, subscript; 209, 210; 209, 211; 210, identifier:kwargs; 211, string:'host'; 212, identifier:host; 213, if_statement; 213, 214; 213, 215; 214, identifier:password; 215, block; 215, 216; 216, expression_statement; 216, 217; 217, assignment; 217, 218; 217, 221; 218, subscript; 218, 219; 218, 220; 219, identifier:kwargs; 220, string:'passwd'; 221, identifier:password; 222, return_statement; 222, 223; 223, expression_list; 223, 224; 223, 225; 223, 226; 224, identifier:MySQLDriver; 225, list:[]; 226, identifier:kwargs; 227, elif_clause; 227, 228; 227, 231; 228, comparison_operator:==; 228, 229; 228, 230; 229, identifier:scheme; 230, string:'postgresql'; 231, block; 231, 232; 231, 240; 231, 246; 231, 255; 231, 280; 231, 289; 232, expression_statement; 232, 233; 233, assignment; 233, 234; 233, 237; 234, subscript; 234, 235; 234, 236; 235, identifier:kwargs; 236, string:'user'; 237, boolean_operator:or; 237, 238; 237, 239; 238, identifier:username; 239, string:'postgres'; 240, expression_statement; 240, 241; 241, assignment; 241, 242; 241, 245; 242, subscript; 242, 243; 242, 244; 243, identifier:kwargs; 244, string:'database'; 245, identifier:database; 246, if_statement; 246, 247; 246, 248; 247, identifier:port; 248, block; 248, 249; 249, expression_statement; 249, 250; 250, assignment; 250, 251; 250, 254; 251, subscript; 251, 252; 251, 253; 252, identifier:kwargs; 253, string:'port'; 254, identifier:port; 255, if_statement; 255, 256; 255, 259; 255, 271; 256, comparison_operator:in; 256, 257; 256, 258; 257, string:'unix_socket'; 258, identifier:kwargs; 259, block; 259, 260; 260, expression_statement; 260, 261; 261, assignment; 261, 262; 261, 265; 262, subscript; 262, 263; 262, 264; 263, identifier:kwargs; 264, string:'host'; 265, call; 265, 266; 265, 269; 266, attribute; 266, 267; 266, 268; 267, identifier:kwargs; 268, identifier:pop; 269, argument_list; 269, 270; 270, string:'unix_socket'; 271, elif_clause; 271, 272; 271, 273; 272, identifier:host; 273, block; 273, 274; 274, expression_statement; 274, 275; 275, assignment; 275, 276; 275, 279; 276, subscript; 276, 277; 276, 278; 277, identifier:kwargs; 278, string:'host'; 279, identifier:host; 280, if_statement; 280, 281; 280, 282; 281, identifier:password; 282, block; 282, 283; 283, expression_statement; 283, 284; 284, assignment; 284, 285; 284, 288; 285, subscript; 285, 286; 285, 287; 286, identifier:kwargs; 287, string:'password'; 288, identifier:password; 289, return_statement; 289, 290; 290, expression_list; 290, 291; 290, 292; 290, 293; 291, identifier:PostgreSQLDriver; 292, list:[]; 293, identifier:kwargs; 294, else_clause; 294, 295; 295, block; 295, 296; 296, raise_statement; 296, 297; 297, call; 297, 298; 297, 299; 298, identifier:ValueError; 299, argument_list; 299, 300; 300, binary_operator:%; 300, 301; 300, 302; 301, string:'Unknown driver %s'; 302, identifier:dsn_string | def parse_dsn(dsn_string):
"""Parse a connection string and return the associated driver"""
dsn = urlparse(dsn_string)
scheme = dsn.scheme.split('+')[0]
username = password = host = port = None
host = dsn.netloc
if '@' in host:
username, host = host.split('@')
if ':' in username:
username, password = username.split(':')
password = unquote(password)
username = unquote(username)
if ':' in host:
host, port = host.split(':')
port = int(port)
database = dsn.path.split('?')[0][1:]
query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query
kwargs = dict(parse_qsl(query, True))
if scheme == 'sqlite':
return SQLiteDriver, [dsn.path], {}
elif scheme == 'mysql':
kwargs['user'] = username or 'root'
kwargs['db'] = database
if port:
kwargs['port'] = port
if host:
kwargs['host'] = host
if password:
kwargs['passwd'] = password
return MySQLDriver, [], kwargs
elif scheme == 'postgresql':
kwargs['user'] = username or 'postgres'
kwargs['database'] = database
if port:
kwargs['port'] = port
if 'unix_socket' in kwargs:
kwargs['host'] = kwargs.pop('unix_socket')
elif host:
kwargs['host'] = host
if password:
kwargs['password'] = password
return PostgreSQLDriver, [], kwargs
else:
raise ValueError('Unknown driver %s' % dsn_string) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 31; 2, function_name:numpy_str; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 3, 23; 3, 26; 3, 29; 4, identifier:arr; 5, default_parameter; 5, 6; 5, 7; 6, identifier:strvals; 7, False; 8, default_parameter; 8, 9; 8, 10; 9, identifier:precision; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:pr; 13, None; 14, default_parameter; 14, 15; 14, 16; 15, identifier:force_dtype; 16, False; 17, default_parameter; 17, 18; 17, 19; 18, identifier:with_dtype; 19, None; 20, default_parameter; 20, 21; 20, 22; 21, identifier:suppress_small; 22, None; 23, default_parameter; 23, 24; 23, 25; 24, identifier:max_line_width; 25, None; 26, default_parameter; 26, 27; 26, 28; 27, identifier:threshold; 28, None; 29, dictionary_splat_pattern; 29, 30; 30, identifier:kwargs; 31, block; 31, 32; 31, 34; 31, 35; 31, 45; 31, 46; 31, 47; 31, 48; 31, 49; 31, 65; 31, 69; 31, 70; 31, 71; 31, 77; 31, 183; 31, 249; 31, 265; 31, 273; 32, expression_statement; 32, 33; 33, comment; 34, comment; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:itemsep; 38, call; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:kwargs; 41, identifier:get; 42, argument_list; 42, 43; 42, 44; 43, string:'itemsep'; 44, string:' '; 45, comment; 46, comment; 47, comment; 48, comment; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:newlines; 52, call; 52, 53; 52, 56; 53, attribute; 53, 54; 53, 55; 54, identifier:kwargs; 55, identifier:pop; 56, argument_list; 56, 57; 56, 58; 57, string:'nl'; 58, call; 58, 59; 58, 62; 59, attribute; 59, 60; 59, 61; 60, identifier:kwargs; 61, identifier:pop; 62, argument_list; 62, 63; 62, 64; 63, string:'newlines'; 64, integer:1; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:data; 68, identifier:arr; 69, comment; 70, comment; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:separator; 74, binary_operator:+; 74, 75; 74, 76; 75, string:','; 76, identifier:itemsep; 77, if_statement; 77, 78; 77, 79; 77, 88; 78, identifier:strvals; 79, block; 79, 80; 79, 84; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:prefix; 83, string:''; 84, expression_statement; 84, 85; 85, assignment; 85, 86; 85, 87; 86, identifier:suffix; 87, string:''; 88, else_clause; 88, 89; 89, block; 89, 90; 89, 99; 89, 100; 89, 104; 89, 115; 89, 126; 89, 135; 89, 144; 89, 154; 90, expression_statement; 90, 91; 91, assignment; 91, 92; 91, 93; 92, identifier:modname; 93, attribute; 93, 94; 93, 98; 94, call; 94, 95; 94, 96; 95, identifier:type; 96, argument_list; 96, 97; 97, identifier:data; 98, identifier:__module__; 99, comment; 100, expression_statement; 100, 101; 101, assignment; 101, 102; 101, 103; 102, identifier:np_nice; 103, string:'np'; 104, expression_statement; 104, 105; 105, assignment; 105, 106; 105, 107; 106, identifier:modname; 107, call; 107, 108; 107, 111; 108, attribute; 108, 109; 108, 110; 109, identifier:re; 110, identifier:sub; 111, argument_list; 111, 112; 111, 113; 111, 114; 112, string:'\\bnumpy\\b'; 113, identifier:np_nice; 114, identifier:modname; 115, expression_statement; 115, 116; 116, assignment; 116, 117; 116, 118; 117, identifier:modname; 118, call; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:re; 121, identifier:sub; 122, argument_list; 122, 123; 122, 124; 122, 125; 123, string:'\\bma.core\\b'; 124, string:'ma'; 125, identifier:modname; 126, expression_statement; 126, 127; 127, assignment; 127, 128; 127, 129; 128, identifier:class_name; 129, attribute; 129, 130; 129, 134; 130, call; 130, 131; 130, 132; 131, identifier:type; 132, argument_list; 132, 133; 133, identifier:data; 134, identifier:__name__; 135, if_statement; 135, 136; 135, 139; 136, comparison_operator:==; 136, 137; 136, 138; 137, identifier:class_name; 138, string:'ndarray'; 139, block; 139, 140; 140, expression_statement; 140, 141; 141, assignment; 141, 142; 141, 143; 142, identifier:class_name; 143, string:'array'; 144, expression_statement; 144, 145; 145, assignment; 145, 146; 145, 147; 146, identifier:prefix; 147, binary_operator:+; 147, 148; 147, 153; 148, binary_operator:+; 148, 149; 148, 152; 149, binary_operator:+; 149, 150; 149, 151; 150, identifier:modname; 151, string:'.'; 152, identifier:class_name; 153, string:'('; 154, if_statement; 154, 155; 154, 156; 154, 177; 155, identifier:with_dtype; 156, block; 156, 157; 156, 165; 156, 166; 157, expression_statement; 157, 158; 158, assignment; 158, 159; 158, 160; 159, identifier:dtype_repr; 160, attribute; 160, 161; 160, 164; 161, attribute; 161, 162; 161, 163; 162, identifier:data; 163, identifier:dtype; 164, identifier:name; 165, comment; 166, expression_statement; 166, 167; 167, assignment; 167, 168; 167, 169; 168, identifier:suffix; 169, call; 169, 170; 169, 173; 170, attribute; 170, 171; 170, 172; 171, string:',{}dtype={}.{})'; 172, identifier:format; 173, argument_list; 173, 174; 173, 175; 173, 176; 174, identifier:itemsep; 175, identifier:np_nice; 176, identifier:dtype_repr; 177, else_clause; 177, 178; 178, block; 178, 179; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 182; 181, identifier:suffix; 182, string:')'; 183, if_statement; 183, 184; 183, 199; 183, 200; 183, 223; 184, boolean_operator:and; 184, 185; 184, 193; 185, boolean_operator:and; 185, 186; 185, 188; 186, not_operator; 186, 187; 187, identifier:strvals; 188, comparison_operator:==; 188, 189; 188, 192; 189, attribute; 189, 190; 189, 191; 190, identifier:data; 191, identifier:size; 192, integer:0; 193, comparison_operator:!=; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:data; 196, identifier:shape; 197, tuple; 197, 198; 198, integer:0; 199, comment; 200, block; 200, 201; 200, 207; 201, expression_statement; 201, 202; 202, assignment; 202, 203; 202, 204; 203, identifier:prefix; 204, binary_operator:+; 204, 205; 204, 206; 205, identifier:modname; 206, string:'.empty('; 207, expression_statement; 207, 208; 208, assignment; 208, 209; 208, 210; 209, identifier:body; 210, call; 210, 211; 210, 212; 211, identifier:repr; 212, argument_list; 212, 213; 213, call; 213, 214; 213, 215; 214, identifier:tuple; 215, argument_list; 215, 216; 216, call; 216, 217; 216, 218; 217, identifier:map; 218, argument_list; 218, 219; 218, 220; 219, identifier:int; 220, attribute; 220, 221; 220, 222; 221, identifier:data; 222, identifier:shape; 223, else_clause; 223, 224; 224, block; 224, 225; 225, expression_statement; 225, 226; 226, assignment; 226, 227; 226, 228; 227, identifier:body; 228, call; 228, 229; 228, 232; 229, attribute; 229, 230; 229, 231; 230, identifier:np; 231, identifier:array2string; 232, argument_list; 232, 233; 232, 234; 232, 237; 232, 240; 232, 243; 232, 246; 233, identifier:data; 234, keyword_argument; 234, 235; 234, 236; 235, identifier:precision; 236, identifier:precision; 237, keyword_argument; 237, 238; 237, 239; 238, identifier:separator; 239, identifier:separator; 240, keyword_argument; 240, 241; 240, 242; 241, identifier:suppress_small; 242, identifier:suppress_small; 243, keyword_argument; 243, 244; 243, 245; 244, identifier:prefix; 245, identifier:prefix; 246, keyword_argument; 246, 247; 246, 248; 247, identifier:max_line_width; 248, identifier:max_line_width; 249, if_statement; 249, 250; 249, 252; 249, 253; 250, not_operator; 250, 251; 251, identifier:newlines; 252, comment; 253, block; 253, 254; 254, expression_statement; 254, 255; 255, assignment; 255, 256; 255, 257; 256, identifier:body; 257, call; 257, 258; 257, 261; 258, attribute; 258, 259; 258, 260; 259, identifier:re; 260, identifier:sub; 261, argument_list; 261, 262; 261, 263; 261, 264; 262, string:'\n *'; 263, string:''; 264, identifier:body; 265, expression_statement; 265, 266; 266, assignment; 266, 267; 266, 268; 267, identifier:formatted; 268, binary_operator:+; 268, 269; 268, 272; 269, binary_operator:+; 269, 270; 269, 271; 270, identifier:prefix; 271, identifier:body; 272, identifier:suffix; 273, return_statement; 273, 274; 274, identifier:formatted | def numpy_str(arr, strvals=False, precision=None, pr=None,
force_dtype=False,
with_dtype=None, suppress_small=None, max_line_width=None,
threshold=None, **kwargs):
"""
suppress_small = False turns off scientific representation
"""
# strvals = kwargs.get('strvals', False)
itemsep = kwargs.get('itemsep', ' ')
# precision = kwargs.get('precision', None)
# suppress_small = kwargs.get('supress_small', None)
# max_line_width = kwargs.get('max_line_width', None)
# with_dtype = kwargs.get('with_dtype', False)
newlines = kwargs.pop('nl', kwargs.pop('newlines', 1))
data = arr
# if with_dtype and strvals:
# raise ValueError('cannot format with strvals and dtype')
separator = ',' + itemsep
if strvals:
prefix = ''
suffix = ''
else:
modname = type(data).__module__
# substitute shorthand for numpy module names
np_nice = 'np'
modname = re.sub('\\bnumpy\\b', np_nice, modname)
modname = re.sub('\\bma.core\\b', 'ma', modname)
class_name = type(data).__name__
if class_name == 'ndarray':
class_name = 'array'
prefix = modname + '.' + class_name + '('
if with_dtype:
dtype_repr = data.dtype.name
# dtype_repr = np.core.arrayprint.dtype_short_repr(data.dtype)
suffix = ',{}dtype={}.{})'.format(itemsep, np_nice, dtype_repr)
else:
suffix = ')'
if not strvals and data.size == 0 and data.shape != (0,):
# Special case for displaying empty data
prefix = modname + '.empty('
body = repr(tuple(map(int, data.shape)))
else:
body = np.array2string(data, precision=precision,
separator=separator,
suppress_small=suppress_small,
prefix=prefix,
max_line_width=max_line_width)
if not newlines:
# remove newlines if we need to
body = re.sub('\n *', '', body)
formatted = prefix + body + suffix
return formatted |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:list_str; 3, parameters; 3, 4; 3, 5; 4, identifier:list_; 5, dictionary_splat_pattern; 5, 6; 6, identifier:listkw; 7, block; 7, 8; 7, 10; 7, 15; 7, 31; 7, 41; 7, 51; 7, 60; 7, 69; 7, 78; 7, 94; 7, 104; 7, 105; 7, 115; 7, 119; 7, 128; 7, 136; 7, 149; 7, 165; 7, 208; 7, 220; 7, 394; 7, 395; 7, 410; 7, 432; 8, expression_statement; 8, 9; 9, comment; 10, import_statement; 10, 11; 11, aliased_import; 11, 12; 11, 14; 12, dotted_name; 12, 13; 13, identifier:utool; 14, identifier:ut; 15, expression_statement; 15, 16; 16, assignment; 16, 17; 16, 18; 17, identifier:newlines; 18, call; 18, 19; 18, 22; 19, attribute; 19, 20; 19, 21; 20, identifier:listkw; 21, identifier:pop; 22, argument_list; 22, 23; 22, 24; 23, string:'nl'; 24, call; 24, 25; 24, 28; 25, attribute; 25, 26; 25, 27; 26, identifier:listkw; 27, identifier:pop; 28, argument_list; 28, 29; 28, 30; 29, string:'newlines'; 30, integer:1; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:packed; 34, call; 34, 35; 34, 38; 35, attribute; 35, 36; 35, 37; 36, identifier:listkw; 37, identifier:pop; 38, argument_list; 38, 39; 38, 40; 39, string:'packed'; 40, False; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:truncate; 44, call; 44, 45; 44, 48; 45, attribute; 45, 46; 45, 47; 46, identifier:listkw; 47, identifier:pop; 48, argument_list; 48, 49; 48, 50; 49, string:'truncate'; 50, False; 51, expression_statement; 51, 52; 52, assignment; 52, 53; 52, 56; 53, subscript; 53, 54; 53, 55; 54, identifier:listkw; 55, string:'nl'; 56, call; 56, 57; 56, 58; 57, identifier:_rectify_countdown_or_bool; 58, argument_list; 58, 59; 59, identifier:newlines; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 65; 62, subscript; 62, 63; 62, 64; 63, identifier:listkw; 64, string:'truncate'; 65, call; 65, 66; 65, 67; 66, identifier:_rectify_countdown_or_bool; 67, argument_list; 67, 68; 68, identifier:truncate; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 74; 71, subscript; 71, 72; 71, 73; 72, identifier:listkw; 73, string:'packed'; 74, call; 74, 75; 74, 76; 75, identifier:_rectify_countdown_or_bool; 76, argument_list; 76, 77; 77, identifier:packed; 78, expression_statement; 78, 79; 79, assignment; 79, 80; 79, 81; 80, identifier:nobraces; 81, call; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:listkw; 84, identifier:pop; 85, argument_list; 85, 86; 85, 87; 86, string:'nobr'; 87, call; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:listkw; 90, identifier:pop; 91, argument_list; 91, 92; 91, 93; 92, string:'nobraces'; 93, False; 94, expression_statement; 94, 95; 95, assignment; 95, 96; 95, 97; 96, identifier:itemsep; 97, call; 97, 98; 97, 101; 98, attribute; 98, 99; 98, 100; 99, identifier:listkw; 100, identifier:get; 101, argument_list; 101, 102; 101, 103; 102, string:'itemsep'; 103, string:' '; 104, comment; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 108; 107, identifier:trailing_sep; 108, call; 108, 109; 108, 112; 109, attribute; 109, 110; 109, 111; 110, identifier:listkw; 111, identifier:get; 112, argument_list; 112, 113; 112, 114; 113, string:'trailing_sep'; 114, True; 115, expression_statement; 115, 116; 116, assignment; 116, 117; 116, 118; 117, identifier:with_comma; 118, True; 119, expression_statement; 119, 120; 120, assignment; 120, 121; 120, 122; 121, identifier:itemstr_list; 122, call; 122, 123; 122, 124; 123, identifier:get_itemstr_list; 124, argument_list; 124, 125; 124, 126; 125, identifier:list_; 126, dictionary_splat; 126, 127; 127, identifier:listkw; 128, expression_statement; 128, 129; 129, assignment; 129, 130; 129, 131; 130, identifier:is_tuple; 131, call; 131, 132; 131, 133; 132, identifier:isinstance; 133, argument_list; 133, 134; 133, 135; 134, identifier:list_; 135, identifier:tuple; 136, expression_statement; 136, 137; 137, assignment; 137, 138; 137, 139; 138, identifier:is_set; 139, call; 139, 140; 139, 141; 140, identifier:isinstance; 141, argument_list; 141, 142; 141, 143; 142, identifier:list_; 143, tuple; 143, 144; 143, 145; 143, 146; 144, identifier:set; 145, identifier:frozenset; 146, attribute; 146, 147; 146, 148; 147, identifier:ut; 148, identifier:oset; 149, expression_statement; 149, 150; 150, assignment; 150, 151; 150, 152; 151, identifier:is_onetup; 152, boolean_operator:and; 152, 153; 152, 159; 153, call; 153, 154; 153, 155; 154, identifier:isinstance; 155, argument_list; 155, 156; 155, 157; 156, identifier:list_; 157, parenthesized_expression; 157, 158; 158, identifier:tuple; 159, comparison_operator:<=; 159, 160; 159, 164; 160, call; 160, 161; 160, 162; 161, identifier:len; 162, argument_list; 162, 163; 163, identifier:list_; 164, integer:1; 165, if_statement; 165, 166; 165, 167; 165, 176; 165, 187; 165, 198; 166, identifier:nobraces; 167, block; 167, 168; 168, expression_statement; 168, 169; 169, assignment; 169, 170; 169, 173; 170, pattern_list; 170, 171; 170, 172; 171, identifier:lbr; 172, identifier:rbr; 173, expression_list; 173, 174; 173, 175; 174, string:''; 175, string:''; 176, elif_clause; 176, 177; 176, 178; 177, identifier:is_tuple; 178, block; 178, 179; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 184; 181, pattern_list; 181, 182; 181, 183; 182, identifier:lbr; 183, identifier:rbr; 184, expression_list; 184, 185; 184, 186; 185, string:'('; 186, string:')'; 187, elif_clause; 187, 188; 187, 189; 188, identifier:is_set; 189, block; 189, 190; 190, expression_statement; 190, 191; 191, assignment; 191, 192; 191, 195; 192, pattern_list; 192, 193; 192, 194; 193, identifier:lbr; 194, identifier:rbr; 195, expression_list; 195, 196; 195, 197; 196, string:'{'; 197, string:'}'; 198, else_clause; 198, 199; 199, block; 199, 200; 200, expression_statement; 200, 201; 201, assignment; 201, 202; 201, 205; 202, pattern_list; 202, 203; 202, 204; 203, identifier:lbr; 204, identifier:rbr; 205, expression_list; 205, 206; 205, 207; 206, string:'['; 207, string:']'; 208, if_statement; 208, 209; 208, 215; 209, comparison_operator:==; 209, 210; 209, 214; 210, call; 210, 211; 210, 212; 211, identifier:len; 212, argument_list; 212, 213; 213, identifier:itemstr_list; 214, integer:0; 215, block; 215, 216; 216, expression_statement; 216, 217; 217, assignment; 217, 218; 217, 219; 218, identifier:newlines; 219, False; 220, if_statement; 220, 221; 220, 233; 220, 358; 221, boolean_operator:and; 221, 222; 221, 225; 222, comparison_operator:is; 222, 223; 222, 224; 223, identifier:newlines; 224, False; 225, parenthesized_expression; 225, 226; 226, boolean_operator:or; 226, 227; 226, 230; 227, comparison_operator:is; 227, 228; 227, 229; 228, identifier:newlines; 229, True; 230, comparison_operator:>; 230, 231; 230, 232; 231, identifier:newlines; 232, integer:0; 233, block; 233, 234; 233, 241; 234, expression_statement; 234, 235; 235, assignment; 235, 236; 235, 237; 236, identifier:sep; 237, conditional_expression:if; 237, 238; 237, 239; 237, 240; 238, string:',\n'; 239, identifier:with_comma; 240, string:'\n'; 241, if_statement; 241, 242; 241, 243; 241, 264; 242, identifier:nobraces; 243, block; 243, 244; 243, 253; 243, 260; 244, expression_statement; 244, 245; 245, assignment; 245, 246; 245, 247; 246, identifier:body_str; 247, call; 247, 248; 247, 251; 248, attribute; 248, 249; 248, 250; 249, identifier:sep; 250, identifier:join; 251, argument_list; 251, 252; 252, identifier:itemstr_list; 253, if_statement; 253, 254; 253, 255; 254, identifier:trailing_sep; 255, block; 255, 256; 256, expression_statement; 256, 257; 257, augmented_assignment:+=; 257, 258; 257, 259; 258, identifier:body_str; 259, string:','; 260, expression_statement; 260, 261; 261, assignment; 261, 262; 261, 263; 262, identifier:retstr; 263, identifier:body_str; 264, else_clause; 264, 265; 265, block; 265, 266; 265, 354; 266, if_statement; 266, 267; 266, 268; 266, 269; 266, 314; 267, identifier:packed; 268, comment; 269, block; 269, 270; 269, 281; 269, 294; 269, 301; 270, expression_statement; 270, 271; 271, assignment; 271, 272; 271, 273; 272, identifier:joinstr; 273, binary_operator:+; 273, 274; 273, 275; 274, identifier:sep; 275, binary_operator:*; 275, 276; 275, 277; 276, identifier:itemsep; 277, call; 277, 278; 277, 279; 278, identifier:len; 279, argument_list; 279, 280; 280, identifier:lbr; 281, expression_statement; 281, 282; 282, assignment; 282, 283; 282, 284; 283, identifier:body_str; 284, call; 284, 285; 284, 288; 285, attribute; 285, 286; 285, 287; 286, identifier:joinstr; 287, identifier:join; 288, argument_list; 288, 289; 289, list_comprehension; 289, 290; 289, 291; 290, identifier:itemstr; 291, for_in_clause; 291, 292; 291, 293; 292, identifier:itemstr; 293, identifier:itemstr_list; 294, if_statement; 294, 295; 294, 296; 295, identifier:trailing_sep; 296, block; 296, 297; 297, expression_statement; 297, 298; 298, augmented_assignment:+=; 298, 299; 298, 300; 299, identifier:body_str; 300, string:','; 301, expression_statement; 301, 302; 302, assignment; 302, 303; 302, 304; 303, identifier:braced_body_str; 304, parenthesized_expression; 304, 305; 305, binary_operator:+; 305, 306; 305, 313; 306, binary_operator:+; 306, 307; 306, 312; 307, binary_operator:+; 307, 308; 307, 311; 308, binary_operator:+; 308, 309; 308, 310; 309, identifier:lbr; 310, string:''; 311, identifier:body_str; 312, string:''; 313, identifier:rbr; 314, else_clause; 314, 315; 315, block; 315, 316; 315, 334; 315, 341; 316, expression_statement; 316, 317; 317, assignment; 317, 318; 317, 319; 318, identifier:body_str; 319, call; 319, 320; 319, 323; 320, attribute; 320, 321; 320, 322; 321, identifier:sep; 322, identifier:join; 323, argument_list; 323, 324; 324, list_comprehension; 324, 325; 324, 331; 325, call; 325, 326; 325, 329; 326, attribute; 326, 327; 326, 328; 327, identifier:ut; 328, identifier:indent; 329, argument_list; 329, 330; 330, identifier:itemstr; 331, for_in_clause; 331, 332; 331, 333; 332, identifier:itemstr; 333, identifier:itemstr_list; 334, if_statement; 334, 335; 334, 336; 335, identifier:trailing_sep; 336, block; 336, 337; 337, expression_statement; 337, 338; 338, augmented_assignment:+=; 338, 339; 338, 340; 339, identifier:body_str; 340, string:','; 341, expression_statement; 341, 342; 342, assignment; 342, 343; 342, 344; 343, identifier:braced_body_str; 344, parenthesized_expression; 344, 345; 345, binary_operator:+; 345, 346; 345, 353; 346, binary_operator:+; 346, 347; 346, 352; 347, binary_operator:+; 347, 348; 347, 351; 348, binary_operator:+; 348, 349; 348, 350; 349, identifier:lbr; 350, string:'\n'; 351, identifier:body_str; 352, string:'\n'; 353, identifier:rbr; 354, expression_statement; 354, 355; 355, assignment; 355, 356; 355, 357; 356, identifier:retstr; 357, identifier:braced_body_str; 358, else_clause; 358, 359; 359, block; 359, 360; 359, 369; 359, 378; 359, 385; 360, expression_statement; 360, 361; 361, assignment; 361, 362; 361, 363; 362, identifier:sep; 363, conditional_expression:if; 363, 364; 363, 367; 363, 368; 364, binary_operator:+; 364, 365; 364, 366; 365, string:','; 366, identifier:itemsep; 367, identifier:with_comma; 368, identifier:itemsep; 369, expression_statement; 369, 370; 370, assignment; 370, 371; 370, 372; 371, identifier:body_str; 372, call; 372, 373; 372, 376; 373, attribute; 373, 374; 373, 375; 374, identifier:sep; 375, identifier:join; 376, argument_list; 376, 377; 377, identifier:itemstr_list; 378, if_statement; 378, 379; 378, 380; 379, identifier:is_onetup; 380, block; 380, 381; 381, expression_statement; 381, 382; 382, augmented_assignment:+=; 382, 383; 382, 384; 383, identifier:body_str; 384, string:','; 385, expression_statement; 385, 386; 386, assignment; 386, 387; 386, 388; 387, identifier:retstr; 388, parenthesized_expression; 388, 389; 389, binary_operator:+; 389, 390; 389, 393; 390, binary_operator:+; 390, 391; 390, 392; 391, identifier:lbr; 392, identifier:body_str; 393, identifier:rbr; 394, comment; 395, expression_statement; 395, 396; 396, assignment; 396, 397; 396, 398; 397, identifier:do_truncate; 398, boolean_operator:and; 398, 399; 398, 402; 399, comparison_operator:is; 399, 400; 399, 401; 400, identifier:truncate; 401, False; 402, parenthesized_expression; 402, 403; 403, boolean_operator:or; 403, 404; 403, 407; 404, comparison_operator:is; 404, 405; 404, 406; 405, identifier:truncate; 406, True; 407, comparison_operator:==; 407, 408; 407, 409; 408, identifier:truncate; 409, integer:0; 410, if_statement; 410, 411; 410, 412; 411, identifier:do_truncate; 412, block; 412, 413; 412, 423; 413, expression_statement; 413, 414; 414, assignment; 414, 415; 414, 416; 415, identifier:truncatekw; 416, call; 416, 417; 416, 420; 417, attribute; 417, 418; 417, 419; 418, identifier:listkw; 419, identifier:get; 420, argument_list; 420, 421; 420, 422; 421, string:'truncatekw'; 422, dictionary; 423, expression_statement; 423, 424; 424, assignment; 424, 425; 424, 426; 425, identifier:retstr; 426, call; 426, 427; 426, 428; 427, identifier:truncate_str; 428, argument_list; 428, 429; 428, 430; 429, identifier:retstr; 430, dictionary_splat; 430, 431; 431, identifier:truncatekw; 432, return_statement; 432, 433; 433, identifier:retstr | def list_str(list_, **listkw):
r"""
Makes a pretty list string
Args:
list_ (list): input list
**listkw: nl, newlines, packed, truncate, nobr, nobraces, itemsep,
trailing_sep, truncatekw, strvals, recursive,
indent_, precision, use_numpy, with_dtype, force_dtype,
stritems, strkeys, align, explicit, sorted_, key_order,
key_order_metric, maxlen
Returns:
str: retstr
CommandLine:
python -m utool.util_str --test-list_str
python -m utool.util_str --exec-list_str --truncate=True
python -m utool.util_str --exec-list_str --truncate=0
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> import utool as ut
>>> list_ = [[(('--verbose-qt', '--verbqt'), 1, False, ''),
>>> (('--verbose-qt', '--verbqt'), 1, False, ''),
>>> (('--verbose-qt', '--verbqt'), 1, False, ''),
>>> (('--verbose-qt', '--verbqt'), 1, False, '')],
>>> [(['--nodyn'], 1, False, ''), (['--nodyn'], 1, False, '')]]
>>> listkw = {'nl': 2}
>>> result = list_str(list_, **listkw)
>>> print(result)
[
[
(('--verbose-qt', '--verbqt'), 1, False, ''),
(('--verbose-qt', '--verbqt'), 1, False, ''),
(('--verbose-qt', '--verbqt'), 1, False, ''),
(('--verbose-qt', '--verbqt'), 1, False, ''),
],
[
(['--nodyn'], 1, False, ''),
(['--nodyn'], 1, False, ''),
],
]
"""
import utool as ut
newlines = listkw.pop('nl', listkw.pop('newlines', 1))
packed = listkw.pop('packed', False)
truncate = listkw.pop('truncate', False)
listkw['nl'] = _rectify_countdown_or_bool(newlines)
listkw['truncate'] = _rectify_countdown_or_bool(truncate)
listkw['packed'] = _rectify_countdown_or_bool(packed)
nobraces = listkw.pop('nobr', listkw.pop('nobraces', False))
itemsep = listkw.get('itemsep', ' ')
# Doesn't actually put in trailing comma if on same line
trailing_sep = listkw.get('trailing_sep', True)
with_comma = True
itemstr_list = get_itemstr_list(list_, **listkw)
is_tuple = isinstance(list_, tuple)
is_set = isinstance(list_, (set, frozenset, ut.oset))
is_onetup = isinstance(list_, (tuple)) and len(list_) <= 1
if nobraces:
lbr, rbr = '', ''
elif is_tuple:
lbr, rbr = '(', ')'
elif is_set:
lbr, rbr = '{', '}'
else:
lbr, rbr = '[', ']'
if len(itemstr_list) == 0:
newlines = False
if newlines is not False and (newlines is True or newlines > 0):
sep = ',\n' if with_comma else '\n'
if nobraces:
body_str = sep.join(itemstr_list)
if trailing_sep:
body_str += ','
retstr = body_str
else:
if packed:
# DEPRICATE?
joinstr = sep + itemsep * len(lbr)
body_str = joinstr.join([itemstr for itemstr in itemstr_list])
if trailing_sep:
body_str += ','
braced_body_str = (lbr + '' + body_str + '' + rbr)
else:
body_str = sep.join([
ut.indent(itemstr) for itemstr in itemstr_list])
if trailing_sep:
body_str += ','
braced_body_str = (lbr + '\n' + body_str + '\n' + rbr)
retstr = braced_body_str
else:
sep = ',' + itemsep if with_comma else itemsep
body_str = sep.join(itemstr_list)
if is_onetup:
body_str += ','
retstr = (lbr + body_str + rbr)
# TODO: rectify with dict_truncate
do_truncate = truncate is not False and (truncate is True or truncate == 0)
if do_truncate:
truncatekw = listkw.get('truncatekw', {})
retstr = truncate_str(retstr, **truncatekw)
return retstr |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:horiz_string; 3, parameters; 3, 4; 3, 6; 4, list_splat_pattern; 4, 5; 5, identifier:args; 6, dictionary_splat_pattern; 6, 7; 7, identifier:kwargs; 8, block; 8, 9; 8, 11; 8, 14; 8, 24; 8, 34; 8, 65; 8, 82; 8, 86; 8, 90; 8, 91; 8, 267; 8, 280; 8, 289; 9, expression_statement; 9, 10; 10, comment; 11, import_statement; 11, 12; 12, dotted_name; 12, 13; 13, identifier:unicodedata; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:precision; 17, call; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:kwargs; 20, identifier:get; 21, argument_list; 21, 22; 21, 23; 22, string:'precision'; 23, None; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:sep; 27, call; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:kwargs; 30, identifier:get; 31, argument_list; 31, 32; 31, 33; 32, string:'sep'; 33, string:''; 34, if_statement; 34, 35; 34, 52; 34, 59; 35, boolean_operator:and; 35, 36; 35, 42; 36, comparison_operator:==; 36, 37; 36, 41; 37, call; 37, 38; 37, 39; 38, identifier:len; 39, argument_list; 39, 40; 40, identifier:args; 41, integer:1; 42, not_operator; 42, 43; 43, call; 43, 44; 43, 45; 44, identifier:isinstance; 45, argument_list; 45, 46; 45, 49; 46, subscript; 46, 47; 46, 48; 47, identifier:args; 48, integer:0; 49, attribute; 49, 50; 49, 51; 50, identifier:six; 51, identifier:string_types; 52, block; 52, 53; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:val_list; 56, subscript; 56, 57; 56, 58; 57, identifier:args; 58, integer:0; 59, else_clause; 59, 60; 60, block; 60, 61; 61, expression_statement; 61, 62; 62, assignment; 62, 63; 62, 64; 63, identifier:val_list; 64, identifier:args; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:val_list; 68, list_comprehension; 68, 69; 68, 79; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:unicodedata; 72, identifier:normalize; 73, argument_list; 73, 74; 73, 75; 74, string:'NFC'; 75, call; 75, 76; 75, 77; 76, identifier:ensure_unicode; 77, argument_list; 77, 78; 78, identifier:val; 79, for_in_clause; 79, 80; 79, 81; 80, identifier:val; 81, identifier:val_list; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 85; 84, identifier:all_lines; 85, list:[]; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:hpos; 89, integer:0; 90, comment; 91, for_statement; 91, 92; 91, 93; 91, 100; 91, 101; 92, identifier:sx; 93, call; 93, 94; 93, 95; 94, identifier:range; 95, argument_list; 95, 96; 96, call; 96, 97; 96, 98; 97, identifier:len; 98, argument_list; 98, 99; 99, identifier:val_list; 100, comment; 101, block; 101, 102; 101, 108; 101, 112; 101, 153; 101, 169; 101, 170; 101, 179; 101, 191; 101, 192; 101, 206; 101, 207; 101, 235; 101, 236; 102, expression_statement; 102, 103; 103, assignment; 103, 104; 103, 105; 104, identifier:val; 105, subscript; 105, 106; 105, 107; 106, identifier:val_list; 107, identifier:sx; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:str_; 111, None; 112, if_statement; 112, 113; 112, 116; 112, 117; 113, comparison_operator:is; 113, 114; 113, 115; 114, identifier:precision; 115, None; 116, comment; 117, block; 117, 118; 118, if_statement; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:util_type; 121, identifier:HAVE_NUMPY; 122, block; 122, 123; 123, try_statement; 123, 124; 123, 149; 124, block; 124, 125; 125, if_statement; 125, 126; 125, 133; 126, call; 126, 127; 126, 128; 127, identifier:isinstance; 128, argument_list; 128, 129; 128, 130; 129, identifier:val; 130, attribute; 130, 131; 130, 132; 131, identifier:np; 132, identifier:ndarray; 133, block; 133, 134; 134, expression_statement; 134, 135; 135, assignment; 135, 136; 135, 137; 136, identifier:str_; 137, call; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:np; 140, identifier:array_str; 141, argument_list; 141, 142; 141, 143; 141, 146; 142, identifier:val; 143, keyword_argument; 143, 144; 143, 145; 144, identifier:precision; 145, identifier:precision; 146, keyword_argument; 146, 147; 146, 148; 147, identifier:suppress_small; 148, True; 149, except_clause; 149, 150; 149, 151; 150, identifier:ImportError; 151, block; 151, 152; 152, pass_statement; 153, if_statement; 153, 154; 153, 157; 154, comparison_operator:is; 154, 155; 154, 156; 155, identifier:str_; 156, None; 157, block; 157, 158; 158, expression_statement; 158, 159; 159, assignment; 159, 160; 159, 161; 160, identifier:str_; 161, call; 161, 162; 161, 165; 162, attribute; 162, 163; 162, 164; 163, identifier:six; 164, identifier:text_type; 165, argument_list; 165, 166; 166, subscript; 166, 167; 166, 168; 167, identifier:val_list; 168, identifier:sx; 169, comment; 170, expression_statement; 170, 171; 171, assignment; 171, 172; 171, 173; 172, identifier:lines; 173, call; 173, 174; 173, 177; 174, attribute; 174, 175; 174, 176; 175, identifier:str_; 176, identifier:split; 177, argument_list; 177, 178; 178, string:'\n'; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 182; 181, identifier:line_diff; 182, binary_operator:-; 182, 183; 182, 187; 183, call; 183, 184; 183, 185; 184, identifier:len; 185, argument_list; 185, 186; 186, identifier:lines; 187, call; 187, 188; 187, 189; 188, identifier:len; 189, argument_list; 189, 190; 190, identifier:all_lines; 191, comment; 192, if_statement; 192, 193; 192, 196; 193, comparison_operator:>; 193, 194; 193, 195; 194, identifier:line_diff; 195, integer:0; 196, block; 196, 197; 197, expression_statement; 197, 198; 198, augmented_assignment:+=; 198, 199; 198, 200; 199, identifier:all_lines; 200, binary_operator:*; 200, 201; 200, 205; 201, list:[' ' * hpos]; 201, 202; 202, binary_operator:*; 202, 203; 202, 204; 203, string:' '; 204, identifier:hpos; 205, identifier:line_diff; 206, comment; 207, for_statement; 207, 208; 207, 211; 207, 215; 208, pattern_list; 208, 209; 208, 210; 209, identifier:lx; 210, identifier:line; 211, call; 211, 212; 211, 213; 212, identifier:enumerate; 213, argument_list; 213, 214; 214, identifier:lines; 215, block; 215, 216; 215, 222; 216, expression_statement; 216, 217; 217, augmented_assignment:+=; 217, 218; 217, 221; 218, subscript; 218, 219; 218, 220; 219, identifier:all_lines; 220, identifier:lx; 221, identifier:line; 222, expression_statement; 222, 223; 223, assignment; 223, 224; 223, 225; 224, identifier:hpos; 225, call; 225, 226; 225, 227; 226, identifier:max; 227, argument_list; 227, 228; 227, 229; 228, identifier:hpos; 229, call; 229, 230; 229, 231; 230, identifier:len; 231, argument_list; 231, 232; 232, subscript; 232, 233; 232, 234; 233, identifier:all_lines; 234, identifier:lx; 235, comment; 236, for_statement; 236, 237; 236, 238; 236, 245; 237, identifier:lx; 238, call; 238, 239; 238, 240; 239, identifier:range; 240, argument_list; 240, 241; 241, call; 241, 242; 241, 243; 242, identifier:len; 243, argument_list; 243, 244; 244, identifier:all_lines; 245, block; 245, 246; 245, 257; 246, expression_statement; 246, 247; 247, assignment; 247, 248; 247, 249; 248, identifier:hpos_diff; 249, binary_operator:-; 249, 250; 249, 251; 250, identifier:hpos; 251, call; 251, 252; 251, 253; 252, identifier:len; 253, argument_list; 253, 254; 254, subscript; 254, 255; 254, 256; 255, identifier:all_lines; 256, identifier:lx; 257, expression_statement; 257, 258; 258, augmented_assignment:+=; 258, 259; 258, 262; 259, subscript; 259, 260; 259, 261; 260, identifier:all_lines; 261, identifier:lx; 262, binary_operator:+; 262, 263; 262, 266; 263, binary_operator:*; 263, 264; 263, 265; 264, string:' '; 265, identifier:hpos_diff; 266, identifier:sep; 267, expression_statement; 267, 268; 268, assignment; 268, 269; 268, 270; 269, identifier:all_lines; 270, list_comprehension; 270, 271; 270, 277; 271, call; 271, 272; 271, 275; 272, attribute; 272, 273; 272, 274; 273, identifier:line; 274, identifier:rstrip; 275, argument_list; 275, 276; 276, string:' '; 277, for_in_clause; 277, 278; 277, 279; 278, identifier:line; 279, identifier:all_lines; 280, expression_statement; 280, 281; 281, assignment; 281, 282; 281, 283; 282, identifier:ret; 283, call; 283, 284; 283, 287; 284, attribute; 284, 285; 284, 286; 285, string:'\n'; 286, identifier:join; 287, argument_list; 287, 288; 288, identifier:all_lines; 289, return_statement; 289, 290; 290, identifier:ret | def horiz_string(*args, **kwargs):
"""
Horizontally concatenates strings reprs preserving indentation
Concats a list of objects ensuring that the next item in the list
is all the way to the right of any previous items.
Args:
*args: list of strings to concat
**kwargs: precision, sep
CommandLine:
python -m utool.util_str --test-horiz_string
Example1:
>>> # ENABLE_DOCTEST
>>> # Pretty printing of matrices demo / test
>>> import utool
>>> import numpy as np
>>> # Wouldn't it be nice if we could print this operation easily?
>>> B = np.array(((1, 2), (3, 4)))
>>> C = np.array(((5, 6), (7, 8)))
>>> A = B.dot(C)
>>> # Eg 1:
>>> result = (utool.hz_str('A = ', A, ' = ', B, ' * ', C))
>>> print(result)
A = [[19 22] = [[1 2] * [[5 6]
[43 50]] [3 4]] [7 8]]
Exam2:
>>> # Eg 2:
>>> str_list = ['A = ', str(B), ' * ', str(C)]
>>> horizstr = (utool.horiz_string(*str_list))
>>> result = (horizstr)
>>> print(result)
A = [[1 2] * [[5 6]
[3 4]] [7 8]]
"""
import unicodedata
precision = kwargs.get('precision', None)
sep = kwargs.get('sep', '')
if len(args) == 1 and not isinstance(args[0], six.string_types):
val_list = args[0]
else:
val_list = args
val_list = [unicodedata.normalize('NFC', ensure_unicode(val))
for val in val_list]
all_lines = []
hpos = 0
# for each value in the list or args
for sx in range(len(val_list)):
# Ensure value is a string
val = val_list[sx]
str_ = None
if precision is not None:
# Hack in numpy precision
if util_type.HAVE_NUMPY:
try:
if isinstance(val, np.ndarray):
str_ = np.array_str(val, precision=precision,
suppress_small=True)
except ImportError:
pass
if str_ is None:
str_ = six.text_type(val_list[sx])
# continue with formating
lines = str_.split('\n')
line_diff = len(lines) - len(all_lines)
# Vertical padding
if line_diff > 0:
all_lines += [' ' * hpos] * line_diff
# Add strings
for lx, line in enumerate(lines):
all_lines[lx] += line
hpos = max(hpos, len(all_lines[lx]))
# Horizontal padding
for lx in range(len(all_lines)):
hpos_diff = hpos - len(all_lines[lx])
all_lines[lx] += ' ' * hpos_diff + sep
all_lines = [line.rstrip(' ') for line in all_lines]
ret = '\n'.join(all_lines)
return ret |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 12; 2, function_name:get_textdiff; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 4, identifier:text1; 5, identifier:text2; 6, default_parameter; 6, 7; 6, 8; 7, identifier:num_context_lines; 8, integer:0; 9, default_parameter; 9, 10; 9, 11; 10, identifier:ignore_whitespace; 11, False; 12, block; 12, 13; 12, 15; 12, 18; 12, 25; 12, 32; 12, 40; 12, 48; 12, 97; 12, 112; 12, 283; 13, expression_statement; 13, 14; 14, comment; 15, import_statement; 15, 16; 16, dotted_name; 16, 17; 17, identifier:difflib; 18, expression_statement; 18, 19; 19, assignment; 19, 20; 19, 21; 20, identifier:text1; 21, call; 21, 22; 21, 23; 22, identifier:ensure_unicode; 23, argument_list; 23, 24; 24, identifier:text1; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:text2; 28, call; 28, 29; 28, 30; 29, identifier:ensure_unicode; 30, argument_list; 30, 31; 31, identifier:text2; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:text1_lines; 35, call; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:text1; 38, identifier:splitlines; 39, argument_list; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:text2_lines; 43, call; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:text2; 46, identifier:splitlines; 47, argument_list; 48, if_statement; 48, 49; 48, 50; 48, 91; 49, identifier:ignore_whitespace; 50, block; 50, 51; 50, 63; 50, 75; 51, expression_statement; 51, 52; 52, assignment; 52, 53; 52, 54; 53, identifier:text1_lines; 54, list_comprehension; 54, 55; 54, 60; 55, call; 55, 56; 55, 59; 56, attribute; 56, 57; 56, 58; 57, identifier:t; 58, identifier:rstrip; 59, argument_list; 60, for_in_clause; 60, 61; 60, 62; 61, identifier:t; 62, identifier:text1_lines; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:text2_lines; 66, list_comprehension; 66, 67; 66, 72; 67, call; 67, 68; 67, 71; 68, attribute; 68, 69; 68, 70; 69, identifier:t; 70, identifier:rstrip; 71, argument_list; 72, for_in_clause; 72, 73; 72, 74; 73, identifier:t; 74, identifier:text2_lines; 75, expression_statement; 75, 76; 76, assignment; 76, 77; 76, 78; 77, identifier:ndiff_kw; 78, call; 78, 79; 78, 80; 79, identifier:dict; 80, argument_list; 80, 81; 80, 86; 81, keyword_argument; 81, 82; 81, 83; 82, identifier:linejunk; 83, attribute; 83, 84; 83, 85; 84, identifier:difflib; 85, identifier:IS_LINE_JUNK; 86, keyword_argument; 86, 87; 86, 88; 87, identifier:charjunk; 88, attribute; 88, 89; 88, 90; 89, identifier:difflib; 90, identifier:IS_CHARACTER_JUNK; 91, else_clause; 91, 92; 92, block; 92, 93; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:ndiff_kw; 96, dictionary; 97, expression_statement; 97, 98; 98, assignment; 98, 99; 98, 100; 99, identifier:all_diff_lines; 100, call; 100, 101; 100, 102; 101, identifier:list; 102, argument_list; 102, 103; 103, call; 103, 104; 103, 107; 104, attribute; 104, 105; 104, 106; 105, identifier:difflib; 106, identifier:ndiff; 107, argument_list; 107, 108; 107, 109; 107, 110; 108, identifier:text1_lines; 109, identifier:text2_lines; 110, dictionary_splat; 110, 111; 111, identifier:ndiff_kw; 112, if_statement; 112, 113; 112, 116; 112, 121; 113, comparison_operator:is; 113, 114; 113, 115; 114, identifier:num_context_lines; 115, None; 116, block; 116, 117; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 120; 119, identifier:diff_lines; 120, identifier:all_diff_lines; 121, else_clause; 121, 122; 122, block; 122, 123; 122, 128; 122, 129; 122, 148; 122, 149; 122, 156; 122, 213; 122, 217; 123, import_from_statement; 123, 124; 123, 126; 124, dotted_name; 124, 125; 125, identifier:utool; 126, dotted_name; 126, 127; 127, identifier:util_list; 128, comment; 129, expression_statement; 129, 130; 130, assignment; 130, 131; 130, 132; 131, identifier:ismarked_list; 132, list_comprehension; 132, 133; 132, 145; 133, boolean_operator:and; 133, 134; 133, 140; 134, comparison_operator:>; 134, 135; 134, 139; 135, call; 135, 136; 135, 137; 136, identifier:len; 137, argument_list; 137, 138; 138, identifier:line; 139, integer:0; 140, comparison_operator:in; 140, 141; 140, 144; 141, subscript; 141, 142; 141, 143; 142, identifier:line; 143, integer:0; 144, string:'+-?'; 145, for_in_clause; 145, 146; 145, 147; 146, identifier:line; 147, identifier:all_diff_lines; 148, comment; 149, expression_statement; 149, 150; 150, assignment; 150, 151; 150, 152; 151, identifier:isvalid_list; 152, subscript; 152, 153; 152, 154; 153, identifier:ismarked_list; 154, slice; 154, 155; 155, colon; 156, for_statement; 156, 157; 156, 158; 156, 165; 157, identifier:i; 158, call; 158, 159; 158, 160; 159, identifier:range; 160, argument_list; 160, 161; 160, 162; 161, integer:1; 162, binary_operator:+; 162, 163; 162, 164; 163, identifier:num_context_lines; 164, integer:1; 165, block; 165, 166; 165, 190; 166, expression_statement; 166, 167; 167, assignment; 167, 168; 167, 174; 168, subscript; 168, 169; 168, 170; 169, identifier:isvalid_list; 170, slice; 170, 171; 170, 172; 171, colon; 172, unary_operator:-; 172, 173; 173, identifier:i; 174, call; 174, 175; 174, 178; 175, attribute; 175, 176; 175, 177; 176, identifier:util_list; 177, identifier:or_lists; 178, argument_list; 178, 179; 178, 185; 179, subscript; 179, 180; 179, 181; 180, identifier:isvalid_list; 181, slice; 181, 182; 181, 183; 182, colon; 183, unary_operator:-; 183, 184; 184, identifier:i; 185, subscript; 185, 186; 185, 187; 186, identifier:ismarked_list; 187, slice; 187, 188; 187, 189; 188, identifier:i; 189, colon; 190, expression_statement; 190, 191; 191, assignment; 191, 192; 191, 197; 192, subscript; 192, 193; 192, 194; 193, identifier:isvalid_list; 194, slice; 194, 195; 194, 196; 195, identifier:i; 196, colon; 197, call; 197, 198; 197, 201; 198, attribute; 198, 199; 198, 200; 199, identifier:util_list; 200, identifier:or_lists; 201, argument_list; 201, 202; 201, 207; 202, subscript; 202, 203; 202, 204; 203, identifier:isvalid_list; 204, slice; 204, 205; 204, 206; 205, identifier:i; 206, colon; 207, subscript; 207, 208; 207, 209; 208, identifier:ismarked_list; 209, slice; 209, 210; 209, 211; 210, colon; 211, unary_operator:-; 211, 212; 212, identifier:i; 213, expression_statement; 213, 214; 214, assignment; 214, 215; 214, 216; 215, identifier:USE_BREAK_LINE; 216, True; 217, if_statement; 217, 218; 217, 219; 217, 220; 217, 271; 218, identifier:USE_BREAK_LINE; 219, comment; 220, block; 220, 221; 220, 225; 220, 229; 220, 233; 220, 234; 221, expression_statement; 221, 222; 222, assignment; 222, 223; 222, 224; 223, identifier:diff_lines; 224, list:[]; 225, expression_statement; 225, 226; 226, assignment; 226, 227; 226, 228; 227, identifier:prev; 228, False; 229, expression_statement; 229, 230; 230, assignment; 230, 231; 230, 232; 231, identifier:visual_break; 232, string:'\n <... FILTERED CONTEXT ...> \n'; 233, comment; 234, for_statement; 234, 235; 234, 238; 234, 243; 235, pattern_list; 235, 236; 235, 237; 236, identifier:line; 237, identifier:valid; 238, call; 238, 239; 238, 240; 239, identifier:zip; 240, argument_list; 240, 241; 240, 242; 241, identifier:all_diff_lines; 242, identifier:isvalid_list; 243, block; 243, 244; 243, 267; 244, if_statement; 244, 245; 244, 246; 244, 254; 245, identifier:valid; 246, block; 246, 247; 247, expression_statement; 247, 248; 248, call; 248, 249; 248, 252; 249, attribute; 249, 250; 249, 251; 250, identifier:diff_lines; 251, identifier:append; 252, argument_list; 252, 253; 253, identifier:line; 254, elif_clause; 254, 255; 254, 256; 255, identifier:prev; 256, block; 256, 257; 257, if_statement; 257, 258; 257, 259; 258, False; 259, block; 259, 260; 260, expression_statement; 260, 261; 261, call; 261, 262; 261, 265; 262, attribute; 262, 263; 262, 264; 263, identifier:diff_lines; 264, identifier:append; 265, argument_list; 265, 266; 266, identifier:visual_break; 267, expression_statement; 267, 268; 268, assignment; 268, 269; 268, 270; 269, identifier:prev; 270, identifier:valid; 271, else_clause; 271, 272; 272, block; 272, 273; 273, expression_statement; 273, 274; 274, assignment; 274, 275; 274, 276; 275, identifier:diff_lines; 276, call; 276, 277; 276, 280; 277, attribute; 277, 278; 277, 279; 278, identifier:util_list; 279, identifier:compress; 280, argument_list; 280, 281; 280, 282; 281, identifier:all_diff_lines; 282, identifier:isvalid_list; 283, return_statement; 283, 284; 284, call; 284, 285; 284, 288; 285, attribute; 285, 286; 285, 287; 286, string:'\n'; 287, identifier:join; 288, argument_list; 288, 289; 289, identifier:diff_lines | def get_textdiff(text1, text2, num_context_lines=0, ignore_whitespace=False):
r"""
Uses difflib to return a difference string between two similar texts
Args:
text1 (str):
text2 (str):
Returns:
str: formatted difference text message
SeeAlso:
ut.color_diff_text
References:
http://www.java2s.com/Code/Python/Utility/IntelligentdiffbetweentextfilesTimPeters.htm
CommandLine:
python -m utool.util_str --test-get_textdiff:1
python -m utool.util_str --test-get_textdiff:0
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> # build test data
>>> text1 = 'one\ntwo\nthree'
>>> text2 = 'one\ntwo\nfive'
>>> # execute function
>>> result = get_textdiff(text1, text2)
>>> # verify results
>>> print(result)
- three
+ five
Example2:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> # build test data
>>> text1 = 'one\ntwo\nthree\n3.1\n3.14\n3.1415\npi\n3.4\n3.5\n4'
>>> text2 = 'one\ntwo\nfive\n3.1\n3.14\n3.1415\npi\n3.4\n4'
>>> # execute function
>>> num_context_lines = 1
>>> result = get_textdiff(text1, text2, num_context_lines)
>>> # verify results
>>> print(result)
"""
import difflib
text1 = ensure_unicode(text1)
text2 = ensure_unicode(text2)
text1_lines = text1.splitlines()
text2_lines = text2.splitlines()
if ignore_whitespace:
text1_lines = [t.rstrip() for t in text1_lines]
text2_lines = [t.rstrip() for t in text2_lines]
ndiff_kw = dict(linejunk=difflib.IS_LINE_JUNK,
charjunk=difflib.IS_CHARACTER_JUNK)
else:
ndiff_kw = {}
all_diff_lines = list(difflib.ndiff(text1_lines, text2_lines, **ndiff_kw))
if num_context_lines is None:
diff_lines = all_diff_lines
else:
from utool import util_list
# boolean for every line if it is marked or not
ismarked_list = [len(line) > 0 and line[0] in '+-?'
for line in all_diff_lines]
# flag lines that are within num_context_lines away from a diff line
isvalid_list = ismarked_list[:]
for i in range(1, num_context_lines + 1):
isvalid_list[:-i] = util_list.or_lists(isvalid_list[:-i],
ismarked_list[i:])
isvalid_list[i:] = util_list.or_lists(isvalid_list[i:],
ismarked_list[:-i])
USE_BREAK_LINE = True
if USE_BREAK_LINE:
# insert a visual break when there is a break in context
diff_lines = []
prev = False
visual_break = '\n <... FILTERED CONTEXT ...> \n'
#print(isvalid_list)
for line, valid in zip(all_diff_lines, isvalid_list):
if valid:
diff_lines.append(line)
elif prev:
if False:
diff_lines.append(visual_break)
prev = valid
else:
diff_lines = util_list.compress(all_diff_lines, isvalid_list)
return '\n'.join(diff_lines) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 18; 2, function_name:add; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 4, identifier:self; 5, identifier:data; 6, default_parameter; 6, 7; 6, 8; 7, identifier:value; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:timestamp; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:namespace; 14, None; 15, default_parameter; 15, 16; 15, 17; 16, identifier:debug; 17, False; 18, block; 18, 19; 18, 21; 18, 45; 18, 51; 18, 58; 18, 74; 18, 80; 18, 86; 18, 92; 18, 103; 18, 114; 18, 177; 18, 193; 18, 205; 18, 257; 18, 261; 18, 269; 18, 275; 18, 285; 18, 295; 18, 488; 18, 494; 19, expression_statement; 19, 20; 20, comment; 21, if_statement; 21, 22; 21, 25; 22, comparison_operator:is; 22, 23; 22, 24; 23, identifier:value; 24, None; 25, block; 25, 26; 26, return_statement; 26, 27; 27, call; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:self; 30, identifier:add; 31, argument_list; 31, 32; 31, 36; 31, 39; 31, 42; 32, tuple; 32, 33; 33, tuple; 33, 34; 33, 35; 34, identifier:data; 35, identifier:value; 36, keyword_argument; 36, 37; 36, 38; 37, identifier:timestamp; 38, identifier:timestamp; 39, keyword_argument; 39, 40; 39, 41; 40, identifier:namespace; 41, identifier:namespace; 42, keyword_argument; 42, 43; 42, 44; 43, identifier:debug; 44, identifier:debug; 45, expression_statement; 45, 46; 46, assignment; 46, 47; 46, 48; 47, identifier:writer; 48, attribute; 48, 49; 48, 50; 49, identifier:self; 50, identifier:writer; 51, if_statement; 51, 52; 51, 55; 52, comparison_operator:is; 52, 53; 52, 54; 53, identifier:writer; 54, None; 55, block; 55, 56; 56, raise_statement; 56, 57; 57, identifier:GaugedUseAfterFreeError; 58, if_statement; 58, 59; 58, 62; 59, comparison_operator:is; 59, 60; 59, 61; 60, identifier:timestamp; 61, None; 62, block; 62, 63; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:timestamp; 66, call; 66, 67; 66, 68; 67, identifier:long; 68, argument_list; 68, 69; 69, binary_operator:*; 69, 70; 69, 73; 70, call; 70, 71; 70, 72; 71, identifier:time; 72, argument_list; 73, integer:1000; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 77; 76, identifier:config; 77, attribute; 77, 78; 77, 79; 78, identifier:self; 79, identifier:config; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:block_size; 83, attribute; 83, 84; 83, 85; 84, identifier:config; 85, identifier:block_size; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:this_block; 89, binary_operator://; 89, 90; 89, 91; 90, identifier:timestamp; 91, identifier:block_size; 92, expression_statement; 92, 93; 93, assignment; 93, 94; 93, 95; 94, identifier:this_array; 95, binary_operator://; 95, 96; 95, 100; 96, parenthesized_expression; 96, 97; 97, binary_operator:%; 97, 98; 97, 99; 98, identifier:timestamp; 99, identifier:block_size; 100, attribute; 100, 101; 100, 102; 101, identifier:config; 102, identifier:resolution; 103, if_statement; 103, 104; 103, 107; 104, comparison_operator:is; 104, 105; 104, 106; 105, identifier:namespace; 106, None; 107, block; 107, 108; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:namespace; 111, attribute; 111, 112; 111, 113; 112, identifier:config; 113, identifier:namespace; 114, if_statement; 114, 115; 114, 134; 115, boolean_operator:or; 115, 116; 115, 121; 115, 122; 116, comparison_operator:<; 116, 117; 116, 118; 117, identifier:this_block; 118, attribute; 118, 119; 118, 120; 119, identifier:self; 120, identifier:current_block; 121, line_continuation:\; 122, parenthesized_expression; 122, 123; 123, boolean_operator:and; 123, 124; 123, 129; 124, comparison_operator:==; 124, 125; 124, 126; 125, identifier:this_block; 126, attribute; 126, 127; 126, 128; 127, identifier:self; 128, identifier:current_block; 129, comparison_operator:<; 129, 130; 129, 131; 130, identifier:this_array; 131, attribute; 131, 132; 131, 133; 132, identifier:self; 133, identifier:current_array; 134, block; 134, 135; 135, if_statement; 135, 136; 135, 143; 135, 153; 135, 174; 136, comparison_operator:==; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:config; 139, identifier:append_only_violation; 140, attribute; 140, 141; 140, 142; 141, identifier:Writer; 142, identifier:ERROR; 143, block; 143, 144; 143, 148; 144, expression_statement; 144, 145; 145, assignment; 145, 146; 145, 147; 146, identifier:msg; 147, string:'Gauged is append-only; timestamps must be increasing'; 148, raise_statement; 148, 149; 149, call; 149, 150; 149, 151; 150, identifier:GaugedAppendOnlyError; 151, argument_list; 151, 152; 152, identifier:msg; 153, elif_clause; 153, 154; 153, 161; 154, comparison_operator:==; 154, 155; 154, 158; 155, attribute; 155, 156; 155, 157; 156, identifier:config; 157, identifier:append_only_violation; 158, attribute; 158, 159; 158, 160; 159, identifier:Writer; 160, identifier:REWRITE; 161, block; 161, 162; 161, 168; 162, expression_statement; 162, 163; 163, assignment; 163, 164; 163, 165; 164, identifier:this_block; 165, attribute; 165, 166; 165, 167; 166, identifier:self; 167, identifier:current_block; 168, expression_statement; 168, 169; 169, assignment; 169, 170; 169, 171; 170, identifier:this_array; 171, attribute; 171, 172; 171, 173; 172, identifier:self; 173, identifier:current_array; 174, else_clause; 174, 175; 175, block; 175, 176; 176, return_statement; 177, if_statement; 177, 178; 177, 183; 178, call; 178, 179; 178, 180; 179, identifier:isinstance; 180, argument_list; 180, 181; 180, 182; 181, identifier:data; 182, identifier:unicode; 183, block; 183, 184; 184, expression_statement; 184, 185; 185, assignment; 185, 186; 185, 187; 186, identifier:data; 187, call; 187, 188; 187, 191; 188, attribute; 188, 189; 188, 190; 189, identifier:data; 190, identifier:encode; 191, argument_list; 191, 192; 192, string:'utf8'; 193, if_statement; 193, 194; 193, 195; 194, identifier:debug; 195, block; 195, 196; 196, return_statement; 196, 197; 197, call; 197, 198; 197, 201; 198, attribute; 198, 199; 198, 200; 199, identifier:self; 200, identifier:debug; 201, argument_list; 201, 202; 201, 203; 201, 204; 202, identifier:timestamp; 203, identifier:namespace; 204, identifier:data; 205, if_statement; 205, 206; 205, 211; 205, 230; 206, comparison_operator:>; 206, 207; 206, 208; 207, identifier:this_block; 208, attribute; 208, 209; 208, 210; 209, identifier:self; 210, identifier:current_block; 211, block; 211, 212; 211, 218; 211, 224; 212, expression_statement; 212, 213; 213, call; 213, 214; 213, 217; 214, attribute; 214, 215; 214, 216; 215, identifier:self; 216, identifier:flush_blocks; 217, argument_list; 218, expression_statement; 218, 219; 219, assignment; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:self; 222, identifier:current_block; 223, identifier:this_block; 224, expression_statement; 224, 225; 225, assignment; 225, 226; 225, 229; 226, attribute; 226, 227; 226, 228; 227, identifier:self; 228, identifier:current_array; 229, identifier:this_array; 230, elif_clause; 230, 231; 230, 236; 231, comparison_operator:>; 231, 232; 231, 233; 232, identifier:this_array; 233, attribute; 233, 234; 233, 235; 234, identifier:self; 235, identifier:current_array; 236, block; 236, 237; 236, 251; 237, if_statement; 237, 238; 237, 248; 238, not_operator; 238, 239; 239, call; 239, 240; 239, 243; 240, attribute; 240, 241; 240, 242; 241, identifier:Gauged; 242, identifier:writer_flush_arrays; 243, argument_list; 243, 244; 243, 245; 244, identifier:writer; 245, attribute; 245, 246; 245, 247; 246, identifier:self; 247, identifier:current_array; 248, block; 248, 249; 249, raise_statement; 249, 250; 250, identifier:MemoryError; 251, expression_statement; 251, 252; 252, assignment; 252, 253; 252, 256; 253, attribute; 253, 254; 253, 255; 254, identifier:self; 255, identifier:current_array; 256, identifier:this_array; 257, expression_statement; 257, 258; 258, assignment; 258, 259; 258, 260; 259, identifier:data_points; 260, integer:0; 261, expression_statement; 261, 262; 262, assignment; 262, 263; 262, 264; 263, identifier:namespace_statistics; 264, subscript; 264, 265; 264, 268; 265, attribute; 265, 266; 265, 267; 266, identifier:self; 267, identifier:statistics; 268, identifier:namespace; 269, expression_statement; 269, 270; 270, assignment; 270, 271; 270, 272; 271, identifier:whitelist; 272, attribute; 272, 273; 272, 274; 273, identifier:config; 274, identifier:key_whitelist; 275, expression_statement; 275, 276; 276, assignment; 276, 277; 276, 278; 277, identifier:skip_long_keys; 278, comparison_operator:==; 278, 279; 278, 282; 279, attribute; 279, 280; 279, 281; 280, identifier:config; 281, identifier:key_overflow; 282, attribute; 282, 283; 282, 284; 283, identifier:Writer; 284, identifier:IGNORE; 285, expression_statement; 285, 286; 286, assignment; 286, 287; 286, 288; 287, identifier:skip_gauge_nan; 288, comparison_operator:==; 288, 289; 288, 292; 289, attribute; 289, 290; 289, 291; 290, identifier:config; 291, identifier:gauge_nan; 292, attribute; 292, 293; 292, 294; 293, identifier:Writer; 294, identifier:IGNORE; 295, if_statement; 295, 296; 295, 310; 295, 311; 295, 342; 296, boolean_operator:and; 296, 297; 296, 307; 297, boolean_operator:and; 297, 298; 297, 305; 297, 306; 298, boolean_operator:and; 298, 299; 298, 304; 299, call; 299, 300; 299, 301; 300, identifier:isinstance; 301, argument_list; 301, 302; 301, 303; 302, identifier:data; 303, identifier:str; 304, identifier:skip_gauge_nan; 305, line_continuation:\; 306, identifier:skip_long_keys; 307, comparison_operator:is; 307, 308; 307, 309; 308, identifier:whitelist; 309, None; 310, comment; 311, block; 311, 312; 311, 319; 311, 336; 312, expression_statement; 312, 313; 313, assignment; 313, 314; 313, 315; 314, identifier:data_points; 315, call; 315, 316; 315, 317; 316, identifier:c_uint32; 317, argument_list; 317, 318; 318, integer:0; 319, if_statement; 319, 320; 319, 333; 320, not_operator; 320, 321; 321, call; 321, 322; 321, 325; 322, attribute; 322, 323; 322, 324; 323, identifier:Gauged; 324, identifier:writer_emit_pairs; 325, argument_list; 325, 326; 325, 327; 325, 328; 325, 329; 326, identifier:writer; 327, identifier:namespace; 328, identifier:data; 329, call; 329, 330; 329, 331; 330, identifier:byref; 331, argument_list; 331, 332; 332, identifier:data_points; 333, block; 333, 334; 334, raise_statement; 334, 335; 335, identifier:MemoryError; 336, expression_statement; 336, 337; 337, assignment; 337, 338; 337, 339; 338, identifier:data_points; 339, attribute; 339, 340; 339, 341; 340, identifier:data_points; 341, identifier:value; 342, else_clause; 342, 343; 343, block; 343, 344; 343, 375; 343, 381; 344, if_statement; 344, 345; 344, 350; 344, 359; 345, call; 345, 346; 345, 347; 346, identifier:isinstance; 347, argument_list; 347, 348; 347, 349; 348, identifier:data; 349, identifier:dict; 350, block; 350, 351; 351, expression_statement; 351, 352; 352, assignment; 352, 353; 352, 354; 353, identifier:data; 354, call; 354, 355; 354, 358; 355, attribute; 355, 356; 355, 357; 356, identifier:data; 357, identifier:iteritems; 358, argument_list; 359, elif_clause; 359, 360; 359, 365; 360, call; 360, 361; 360, 362; 361, identifier:isinstance; 362, argument_list; 362, 363; 362, 364; 363, identifier:data; 364, identifier:str; 365, block; 365, 366; 366, expression_statement; 366, 367; 367, assignment; 367, 368; 367, 369; 368, identifier:data; 369, call; 369, 370; 369, 373; 370, attribute; 370, 371; 370, 372; 371, identifier:self; 372, identifier:parse_query; 373, argument_list; 373, 374; 374, identifier:data; 375, expression_statement; 375, 376; 376, assignment; 376, 377; 376, 378; 377, identifier:emit; 378, attribute; 378, 379; 378, 380; 379, identifier:Gauged; 380, identifier:writer_emit; 381, for_statement; 381, 382; 381, 385; 381, 386; 382, pattern_list; 382, 383; 382, 384; 383, identifier:key; 384, identifier:value; 385, identifier:data; 386, block; 386, 387; 386, 394; 386, 404; 386, 423; 386, 435; 386, 448; 386, 484; 387, expression_statement; 387, 388; 388, assignment; 388, 389; 388, 390; 389, identifier:key; 390, call; 390, 391; 390, 392; 391, identifier:to_bytes; 392, argument_list; 392, 393; 393, identifier:key; 394, if_statement; 394, 395; 394, 402; 395, boolean_operator:and; 395, 396; 395, 399; 396, comparison_operator:is; 396, 397; 396, 398; 397, identifier:whitelist; 398, None; 399, comparison_operator:not; 399, 400; 399, 401; 400, identifier:key; 401, identifier:whitelist; 402, block; 402, 403; 403, continue_statement; 404, try_statement; 404, 405; 404, 413; 405, block; 405, 406; 406, expression_statement; 406, 407; 407, assignment; 407, 408; 407, 409; 408, identifier:value; 409, call; 409, 410; 409, 411; 410, identifier:float; 411, argument_list; 411, 412; 412, identifier:value; 413, except_clause; 413, 414; 413, 415; 414, identifier:ValueError; 415, block; 415, 416; 416, expression_statement; 416, 417; 417, assignment; 417, 418; 417, 419; 418, identifier:value; 419, call; 419, 420; 419, 421; 420, identifier:float; 421, argument_list; 421, 422; 422, string:'nan'; 423, if_statement; 423, 424; 423, 427; 423, 428; 424, comparison_operator:!=; 424, 425; 424, 426; 425, identifier:value; 426, identifier:value; 427, comment; 428, block; 428, 429; 428, 433; 429, if_statement; 429, 430; 429, 431; 430, identifier:skip_gauge_nan; 431, block; 431, 432; 432, continue_statement; 433, raise_statement; 433, 434; 434, identifier:GaugedNaNError; 435, expression_statement; 435, 436; 436, assignment; 436, 437; 436, 438; 437, identifier:success; 438, call; 438, 439; 438, 440; 439, identifier:emit; 440, argument_list; 440, 441; 440, 442; 440, 443; 440, 444; 441, identifier:writer; 442, identifier:namespace; 443, identifier:key; 444, call; 444, 445; 444, 446; 445, identifier:c_float; 446, argument_list; 446, 447; 447, identifier:value; 448, if_statement; 448, 449; 448, 452; 449, comparison_operator:!=; 449, 450; 449, 451; 450, identifier:success; 451, integer:1; 452, block; 452, 453; 453, if_statement; 453, 454; 453, 456; 453, 459; 454, not_operator; 454, 455; 455, identifier:success; 456, block; 456, 457; 457, raise_statement; 457, 458; 458, identifier:MemoryError; 459, elif_clause; 459, 460; 459, 468; 460, boolean_operator:and; 460, 461; 460, 466; 461, comparison_operator:==; 461, 462; 461, 463; 462, identifier:success; 463, attribute; 463, 464; 463, 465; 464, identifier:Writer; 465, identifier:KEY_OVERFLOW; 466, not_operator; 466, 467; 467, identifier:skip_long_keys; 468, block; 468, 469; 468, 473; 468, 479; 469, expression_statement; 469, 470; 470, assignment; 470, 471; 470, 472; 471, identifier:msg; 472, string:'Key is larger than the driver allows '; 473, expression_statement; 473, 474; 474, augmented_assignment:+=; 474, 475; 474, 476; 475, identifier:msg; 476, binary_operator:%; 476, 477; 476, 478; 477, string:'(%s)'; 478, identifier:key; 479, raise_statement; 479, 480; 480, call; 480, 481; 480, 482; 481, identifier:GaugedKeyOverflowError; 482, argument_list; 482, 483; 483, identifier:msg; 484, expression_statement; 484, 485; 485, augmented_assignment:+=; 485, 486; 485, 487; 486, identifier:data_points; 487, integer:1; 488, expression_statement; 488, 489; 489, augmented_assignment:+=; 489, 490; 489, 493; 490, attribute; 490, 491; 490, 492; 491, identifier:namespace_statistics; 492, identifier:data_points; 493, identifier:data_points; 494, if_statement; 494, 495; 494, 498; 495, attribute; 495, 496; 495, 497; 496, identifier:self; 497, identifier:flush_now; 498, block; 498, 499; 499, expression_statement; 499, 500; 500, call; 500, 501; 500, 504; 501, attribute; 501, 502; 501, 503; 502, identifier:self; 503, identifier:flush; 504, argument_list | def add(self, data, value=None, timestamp=None, namespace=None,
debug=False):
"""Queue a gauge or gauges to be written"""
if value is not None:
return self.add(((data, value),), timestamp=timestamp,
namespace=namespace, debug=debug)
writer = self.writer
if writer is None:
raise GaugedUseAfterFreeError
if timestamp is None:
timestamp = long(time() * 1000)
config = self.config
block_size = config.block_size
this_block = timestamp // block_size
this_array = (timestamp % block_size) // config.resolution
if namespace is None:
namespace = config.namespace
if this_block < self.current_block or \
(this_block == self.current_block and
this_array < self.current_array):
if config.append_only_violation == Writer.ERROR:
msg = 'Gauged is append-only; timestamps must be increasing'
raise GaugedAppendOnlyError(msg)
elif config.append_only_violation == Writer.REWRITE:
this_block = self.current_block
this_array = self.current_array
else:
return
if isinstance(data, unicode):
data = data.encode('utf8')
if debug:
return self.debug(timestamp, namespace, data)
if this_block > self.current_block:
self.flush_blocks()
self.current_block = this_block
self.current_array = this_array
elif this_array > self.current_array:
if not Gauged.writer_flush_arrays(writer, self.current_array):
raise MemoryError
self.current_array = this_array
data_points = 0
namespace_statistics = self.statistics[namespace]
whitelist = config.key_whitelist
skip_long_keys = config.key_overflow == Writer.IGNORE
skip_gauge_nan = config.gauge_nan == Writer.IGNORE
if isinstance(data, str) and skip_gauge_nan \
and skip_long_keys and whitelist is None: # fast path
data_points = c_uint32(0)
if not Gauged.writer_emit_pairs(writer, namespace, data,
byref(data_points)):
raise MemoryError
data_points = data_points.value
else:
if isinstance(data, dict):
data = data.iteritems()
elif isinstance(data, str):
data = self.parse_query(data)
emit = Gauged.writer_emit
for key, value in data:
key = to_bytes(key)
if whitelist is not None and key not in whitelist:
continue
try:
value = float(value)
except ValueError:
value = float('nan')
if value != value: # => NaN?
if skip_gauge_nan:
continue
raise GaugedNaNError
success = emit(writer, namespace, key, c_float(value))
if success != 1:
if not success:
raise MemoryError
elif success == Writer.KEY_OVERFLOW and not skip_long_keys:
msg = 'Key is larger than the driver allows '
msg += '(%s)' % key
raise GaugedKeyOverflowError(msg)
data_points += 1
namespace_statistics.data_points += data_points
if self.flush_now:
self.flush() |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 14; 2, function_name:generate_psms_quanted; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 11; 4, identifier:quantdb; 5, identifier:tsvfn; 6, identifier:isob_header; 7, identifier:oldheader; 8, default_parameter; 8, 9; 8, 10; 9, identifier:isobaric; 10, False; 11, default_parameter; 11, 12; 11, 13; 12, identifier:precursor; 13, False; 14, block; 14, 15; 14, 17; 14, 29; 14, 36; 15, expression_statement; 15, 16; 16, comment; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 22; 19, pattern_list; 19, 20; 19, 21; 20, identifier:allquants; 21, identifier:sqlfields; 22, call; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:quantdb; 25, identifier:select_all_psm_quants; 26, argument_list; 26, 27; 26, 28; 27, identifier:isobaric; 28, identifier:precursor; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:quant; 32, call; 32, 33; 32, 34; 33, identifier:next; 34, argument_list; 34, 35; 35, identifier:allquants; 36, for_statement; 36, 37; 36, 40; 36, 50; 37, pattern_list; 37, 38; 37, 39; 38, identifier:rownr; 39, identifier:psm; 40, call; 40, 41; 40, 42; 41, identifier:enumerate; 42, argument_list; 42, 43; 43, call; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:readers; 46, identifier:generate_tsv_psms; 47, argument_list; 47, 48; 47, 49; 48, identifier:tsvfn; 49, identifier:oldheader; 50, block; 50, 51; 50, 67; 50, 102; 50, 181; 51, expression_statement; 51, 52; 52, assignment; 52, 53; 52, 54; 53, identifier:outpsm; 54, dictionary_comprehension; 54, 55; 54, 58; 55, pair; 55, 56; 55, 57; 56, identifier:x; 57, identifier:y; 58, for_in_clause; 58, 59; 58, 62; 59, pattern_list; 59, 60; 59, 61; 60, identifier:x; 61, identifier:y; 62, call; 62, 63; 62, 66; 63, attribute; 63, 64; 63, 65; 64, identifier:psm; 65, identifier:items; 66, argument_list; 67, if_statement; 67, 68; 67, 69; 68, identifier:precursor; 69, block; 69, 70; 69, 78; 69, 87; 70, expression_statement; 70, 71; 71, assignment; 71, 72; 71, 73; 72, identifier:pquant; 73, subscript; 73, 74; 73, 75; 74, identifier:quant; 75, subscript; 75, 76; 75, 77; 76, identifier:sqlfields; 77, string:'precursor'; 78, if_statement; 78, 79; 78, 82; 79, comparison_operator:is; 79, 80; 79, 81; 80, identifier:pquant; 81, None; 82, block; 82, 83; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:pquant; 86, string:'NA'; 87, expression_statement; 87, 88; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:outpsm; 91, identifier:update; 92, argument_list; 92, 93; 93, dictionary; 93, 94; 94, pair; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:mzidtsvdata; 97, identifier:HEADER_PRECURSOR_QUANT; 98, call; 98, 99; 98, 100; 99, identifier:str; 100, argument_list; 100, 101; 101, identifier:pquant; 102, if_statement; 102, 103; 102, 104; 102, 162; 103, identifier:isobaric; 104, block; 104, 105; 104, 109; 104, 151; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 108; 107, identifier:isoquants; 108, dictionary; 109, while_statement; 109, 110; 109, 115; 110, comparison_operator:==; 110, 111; 110, 114; 111, subscript; 111, 112; 111, 113; 112, identifier:quant; 113, integer:0; 114, identifier:rownr; 115, block; 115, 116; 115, 137; 116, expression_statement; 116, 117; 117, call; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, identifier:isoquants; 120, identifier:update; 121, argument_list; 121, 122; 122, dictionary; 122, 123; 123, pair; 123, 124; 123, 129; 124, subscript; 124, 125; 124, 126; 125, identifier:quant; 126, subscript; 126, 127; 126, 128; 127, identifier:sqlfields; 128, string:'isochan'; 129, call; 129, 130; 129, 131; 130, identifier:str; 131, argument_list; 131, 132; 132, subscript; 132, 133; 132, 134; 133, identifier:quant; 134, subscript; 134, 135; 134, 136; 135, identifier:sqlfields; 136, string:'isoquant'; 137, try_statement; 137, 138; 137, 146; 138, block; 138, 139; 139, expression_statement; 139, 140; 140, assignment; 140, 141; 140, 142; 141, identifier:quant; 142, call; 142, 143; 142, 144; 143, identifier:next; 144, argument_list; 144, 145; 145, identifier:allquants; 146, except_clause; 146, 147; 146, 148; 146, 149; 147, identifier:StopIteration; 148, comment; 149, block; 149, 150; 150, break_statement; 151, expression_statement; 151, 152; 152, call; 152, 153; 152, 156; 153, attribute; 153, 154; 153, 155; 154, identifier:outpsm; 155, identifier:update; 156, argument_list; 156, 157; 157, call; 157, 158; 157, 159; 158, identifier:get_quant_NAs; 159, argument_list; 159, 160; 159, 161; 160, identifier:isoquants; 161, identifier:isob_header; 162, else_clause; 162, 163; 163, block; 163, 164; 164, try_statement; 164, 165; 164, 173; 165, block; 165, 166; 166, expression_statement; 166, 167; 167, assignment; 167, 168; 167, 169; 168, identifier:quant; 169, call; 169, 170; 169, 171; 170, identifier:next; 171, argument_list; 171, 172; 172, identifier:allquants; 173, except_clause; 173, 174; 173, 175; 173, 176; 174, identifier:StopIteration; 175, comment; 176, block; 176, 177; 176, 180; 177, expression_statement; 177, 178; 178, yield; 178, 179; 179, identifier:outpsm; 180, break_statement; 181, expression_statement; 181, 182; 182, yield; 182, 183; 183, identifier:outpsm | def generate_psms_quanted(quantdb, tsvfn, isob_header, oldheader,
isobaric=False, precursor=False):
"""Takes dbfn and connects, gets quants for each line in tsvfn, sorts
them in line by using keys in quantheader list."""
allquants, sqlfields = quantdb.select_all_psm_quants(isobaric, precursor)
quant = next(allquants)
for rownr, psm in enumerate(readers.generate_tsv_psms(tsvfn, oldheader)):
outpsm = {x: y for x, y in psm.items()}
if precursor:
pquant = quant[sqlfields['precursor']]
if pquant is None:
pquant = 'NA'
outpsm.update({mzidtsvdata.HEADER_PRECURSOR_QUANT: str(pquant)})
if isobaric:
isoquants = {}
while quant[0] == rownr:
isoquants.update({quant[sqlfields['isochan']]:
str(quant[sqlfields['isoquant']])})
try:
quant = next(allquants)
except StopIteration:
# last PSM, break from while loop or it is not yielded at all
break
outpsm.update(get_quant_NAs(isoquants, isob_header))
else:
try:
quant = next(allquants)
except StopIteration:
# last PSM, needs explicit yield/break or it will not be yielded
yield outpsm
break
yield outpsm |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:total_purge_developed_repo; 3, parameters; 3, 4; 4, identifier:repodir; 5, block; 5, 6; 5, 8; 5, 12; 5, 17; 5, 20; 5, 33; 5, 41; 5, 86; 5, 107; 5, 112; 5, 122; 5, 141; 5, 149; 5, 157; 5, 162; 5, 211; 5, 216; 5, 233; 5, 355; 5, 370; 5, 373; 5, 381; 5, 386; 6, expression_statement; 6, 7; 7, comment; 8, assert_statement; 8, 9; 9, comparison_operator:is; 9, 10; 9, 11; 10, identifier:repodir; 11, None; 12, import_statement; 12, 13; 13, aliased_import; 13, 14; 13, 16; 14, dotted_name; 14, 15; 15, identifier:utool; 16, identifier:ut; 17, import_statement; 17, 18; 18, dotted_name; 18, 19; 19, identifier:os; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:repo; 23, call; 23, 24; 23, 29; 24, attribute; 24, 25; 24, 28; 25, attribute; 25, 26; 25, 27; 26, identifier:ut; 27, identifier:util_git; 28, identifier:Repo; 29, argument_list; 29, 30; 30, keyword_argument; 30, 31; 30, 32; 31, identifier:dpath; 32, identifier:repodir; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:user; 36, subscript; 36, 37; 36, 40; 37, attribute; 37, 38; 37, 39; 38, identifier:os; 39, identifier:environ; 40, string:'USER'; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:fmtdict; 44, call; 44, 45; 44, 46; 45, identifier:dict; 46, argument_list; 46, 47; 46, 50; 46, 55; 46, 60; 46, 65; 46, 72; 46, 79; 47, keyword_argument; 47, 48; 47, 49; 48, identifier:user; 49, identifier:user; 50, keyword_argument; 50, 51; 50, 52; 51, identifier:modname; 52, attribute; 52, 53; 52, 54; 53, identifier:repo; 54, identifier:modname; 55, keyword_argument; 55, 56; 55, 57; 56, identifier:reponame; 57, attribute; 57, 58; 57, 59; 58, identifier:repo; 59, identifier:reponame; 60, keyword_argument; 60, 61; 60, 62; 61, identifier:dpath; 62, attribute; 62, 63; 62, 64; 63, identifier:repo; 64, identifier:dpath; 65, keyword_argument; 65, 66; 65, 67; 66, identifier:global_site_pkgs; 67, call; 67, 68; 67, 71; 68, attribute; 68, 69; 68, 70; 69, identifier:ut; 70, identifier:get_global_dist_packages_dir; 71, argument_list; 72, keyword_argument; 72, 73; 72, 74; 73, identifier:local_site_pkgs; 74, call; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, identifier:ut; 77, identifier:get_local_dist_packages_dir; 78, argument_list; 79, keyword_argument; 79, 80; 79, 81; 80, identifier:venv_site_pkgs; 81, call; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:ut; 84, identifier:get_site_packages_dir; 85, argument_list; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:commands; 89, list_comprehension; 89, 90; 89, 97; 90, call; 90, 91; 90, 94; 91, attribute; 91, 92; 91, 93; 92, identifier:_; 93, identifier:format; 94, argument_list; 94, 95; 95, dictionary_splat; 95, 96; 96, identifier:fmtdict; 97, for_in_clause; 97, 98; 97, 99; 98, identifier:_; 99, list:[
'pip uninstall {modname}',
'sudo -H pip uninstall {modname}',
'sudo pip uninstall {modname}',
'easy_install -m {modname}',
'cd {dpath} && python setup.py develop --uninstall',
# If they still exist try chowning to current user
'sudo chown -R {user}:{user} {dpath}',
]; 99, 100; 99, 101; 99, 102; 99, 103; 99, 104; 99, 105; 99, 106; 100, string:'pip uninstall {modname}'; 101, string:'sudo -H pip uninstall {modname}'; 102, string:'sudo pip uninstall {modname}'; 103, string:'easy_install -m {modname}'; 104, string:'cd {dpath} && python setup.py develop --uninstall'; 105, comment; 106, string:'sudo chown -R {user}:{user} {dpath}'; 107, expression_statement; 107, 108; 108, call; 108, 109; 108, 110; 109, identifier:print; 110, argument_list; 110, 111; 111, string:'Normal uninstall commands'; 112, expression_statement; 112, 113; 113, call; 113, 114; 113, 115; 114, identifier:print; 115, argument_list; 115, 116; 116, call; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, string:'\n'; 119, identifier:join; 120, argument_list; 120, 121; 121, identifier:commands; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:possible_link_paths; 125, list_comprehension; 125, 126; 125, 133; 126, call; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:_; 129, identifier:format; 130, argument_list; 130, 131; 131, dictionary_splat; 131, 132; 132, identifier:fmtdict; 133, for_in_clause; 133, 134; 133, 135; 134, identifier:_; 135, list:[
'{dpath}/{modname}.egg-info',
'{dpath}/build',
'{venv_site_pkgs}/{reponame}.egg-info',
'{local_site_pkgs}/{reponame}.egg-info',
'{venv_site_pkgs}/{reponame}.egg-info',
]; 135, 136; 135, 137; 135, 138; 135, 139; 135, 140; 136, string:'{dpath}/{modname}.egg-info'; 137, string:'{dpath}/build'; 138, string:'{venv_site_pkgs}/{reponame}.egg-info'; 139, string:'{local_site_pkgs}/{reponame}.egg-info'; 140, string:'{venv_site_pkgs}/{reponame}.egg-info'; 141, import_from_statement; 141, 142; 141, 145; 141, 147; 142, dotted_name; 142, 143; 142, 144; 143, identifier:os; 144, identifier:path; 145, dotted_name; 145, 146; 146, identifier:exists; 147, dotted_name; 147, 148; 148, identifier:basename; 149, expression_statement; 149, 150; 150, assignment; 150, 151; 150, 152; 151, identifier:existing_link_paths; 152, list_comprehension; 152, 153; 152, 154; 153, identifier:path; 154, for_in_clause; 154, 155; 154, 156; 155, identifier:path; 156, identifier:possible_link_paths; 157, expression_statement; 157, 158; 158, call; 158, 159; 158, 160; 159, identifier:print; 160, argument_list; 160, 161; 161, string:'# Delete paths and eggs'; 162, for_statement; 162, 163; 162, 164; 162, 165; 163, identifier:path; 164, identifier:existing_link_paths; 165, block; 165, 166; 165, 210; 166, if_statement; 166, 167; 166, 171; 167, call; 167, 168; 167, 169; 168, identifier:exists; 169, argument_list; 169, 170; 170, identifier:path; 171, block; 171, 172; 172, if_statement; 172, 173; 172, 183; 172, 196; 173, comparison_operator:!=; 173, 174; 173, 182; 174, subscript; 174, 175; 174, 181; 175, call; 175, 176; 175, 179; 176, attribute; 176, 177; 176, 178; 177, identifier:ut; 178, identifier:get_file_info; 179, argument_list; 179, 180; 180, identifier:path; 181, string:'owner'; 182, identifier:user; 183, block; 183, 184; 184, expression_statement; 184, 185; 185, call; 185, 186; 185, 187; 186, identifier:print; 187, argument_list; 187, 188; 188, call; 188, 189; 188, 192; 189, attribute; 189, 190; 189, 191; 190, string:'sudo /bin/rm -rf {path}'; 191, identifier:format; 192, argument_list; 192, 193; 193, keyword_argument; 193, 194; 193, 195; 194, identifier:path; 195, identifier:path; 196, else_clause; 196, 197; 197, block; 197, 198; 198, expression_statement; 198, 199; 199, call; 199, 200; 199, 201; 200, identifier:print; 201, argument_list; 201, 202; 202, call; 202, 203; 202, 206; 203, attribute; 203, 204; 203, 205; 204, string:'/bin/rm -rf {path}'; 205, identifier:format; 206, argument_list; 206, 207; 207, keyword_argument; 207, 208; 207, 209; 208, identifier:path; 209, identifier:path; 210, comment; 211, expression_statement; 211, 212; 212, call; 212, 213; 212, 214; 213, identifier:print; 214, argument_list; 214, 215; 215, string:'# Make sure nothing is in the easy install paths'; 216, expression_statement; 216, 217; 217, assignment; 217, 218; 217, 219; 218, identifier:easyinstall_paths; 219, list_comprehension; 219, 220; 219, 227; 220, call; 220, 221; 220, 224; 221, attribute; 221, 222; 221, 223; 222, identifier:_; 223, identifier:format; 224, argument_list; 224, 225; 225, dictionary_splat; 225, 226; 226, identifier:fmtdict; 227, for_in_clause; 227, 228; 227, 229; 228, identifier:_; 229, list:[
'{venv_site_pkgs}/easy-install.pth',
'{local_site_pkgs}/easy-install.pth',
'{venv_site_pkgs}/easy-install.pth',
]; 229, 230; 229, 231; 229, 232; 230, string:'{venv_site_pkgs}/easy-install.pth'; 231, string:'{local_site_pkgs}/easy-install.pth'; 232, string:'{venv_site_pkgs}/easy-install.pth'; 233, for_statement; 233, 234; 233, 235; 233, 236; 234, identifier:path; 235, identifier:easyinstall_paths; 236, block; 236, 237; 237, if_statement; 237, 238; 237, 242; 238, call; 238, 239; 238, 240; 239, identifier:exists; 240, argument_list; 240, 241; 241, identifier:path; 242, block; 242, 243; 242, 264; 242, 275; 242, 287; 242, 299; 243, expression_statement; 243, 244; 244, assignment; 244, 245; 244, 246; 245, identifier:easy_install_list; 246, call; 246, 247; 246, 262; 247, attribute; 247, 248; 247, 261; 248, call; 248, 249; 248, 260; 249, attribute; 249, 250; 249, 259; 250, call; 250, 251; 250, 254; 251, attribute; 251, 252; 251, 253; 252, identifier:ut; 253, identifier:readfrom; 254, argument_list; 254, 255; 254, 256; 255, identifier:path; 256, keyword_argument; 256, 257; 256, 258; 257, identifier:verbose; 258, False; 259, identifier:strip; 260, argument_list; 261, identifier:split; 262, argument_list; 262, 263; 263, string:'\n'; 264, expression_statement; 264, 265; 265, assignment; 265, 266; 265, 267; 266, identifier:easy_install_list_; 267, list_comprehension; 267, 268; 267, 272; 268, call; 268, 269; 268, 270; 269, identifier:basename; 270, argument_list; 270, 271; 271, identifier:p; 272, for_in_clause; 272, 273; 272, 274; 273, identifier:p; 274, identifier:easy_install_list; 275, expression_statement; 275, 276; 276, assignment; 276, 277; 276, 278; 277, identifier:index1; 278, call; 278, 279; 278, 282; 279, attribute; 279, 280; 279, 281; 280, identifier:ut; 281, identifier:listfind; 282, argument_list; 282, 283; 282, 284; 283, identifier:easy_install_list_; 284, attribute; 284, 285; 284, 286; 285, identifier:repo; 286, identifier:reponame; 287, expression_statement; 287, 288; 288, assignment; 288, 289; 288, 290; 289, identifier:index2; 290, call; 290, 291; 290, 294; 291, attribute; 291, 292; 291, 293; 292, identifier:ut; 293, identifier:listfind; 294, argument_list; 294, 295; 294, 296; 295, identifier:easy_install_list_; 296, attribute; 296, 297; 296, 298; 297, identifier:repo; 298, identifier:modname; 299, if_statement; 299, 300; 299, 307; 300, boolean_operator:or; 300, 301; 300, 304; 301, comparison_operator:is; 301, 302; 301, 303; 302, identifier:index1; 303, None; 304, comparison_operator:is; 304, 305; 304, 306; 305, identifier:index2; 306, None; 307, block; 307, 308; 307, 317; 308, expression_statement; 308, 309; 309, call; 309, 310; 309, 311; 310, identifier:print; 311, argument_list; 311, 312; 312, binary_operator:%; 312, 313; 312, 314; 313, string:'Found at index1=%r, index=%r'; 314, tuple; 314, 315; 314, 316; 315, identifier:index1; 316, identifier:index2; 317, if_statement; 317, 318; 317, 328; 317, 341; 318, comparison_operator:!=; 318, 319; 318, 327; 319, subscript; 319, 320; 319, 326; 320, call; 320, 321; 320, 324; 321, attribute; 321, 322; 321, 323; 322, identifier:ut; 323, identifier:get_file_info; 324, argument_list; 324, 325; 325, identifier:path; 326, string:'owner'; 327, identifier:user; 328, block; 328, 329; 329, expression_statement; 329, 330; 330, call; 330, 331; 330, 332; 331, identifier:print; 332, argument_list; 332, 333; 333, call; 333, 334; 333, 337; 334, attribute; 334, 335; 334, 336; 335, string:'sudo gvim {path}'; 336, identifier:format; 337, argument_list; 337, 338; 338, keyword_argument; 338, 339; 338, 340; 339, identifier:path; 340, identifier:path; 341, else_clause; 341, 342; 342, block; 342, 343; 343, expression_statement; 343, 344; 344, call; 344, 345; 344, 346; 345, identifier:print; 346, argument_list; 346, 347; 347, call; 347, 348; 347, 351; 348, attribute; 348, 349; 348, 350; 349, string:'gvim {path}'; 350, identifier:format; 351, argument_list; 351, 352; 352, keyword_argument; 352, 353; 352, 354; 353, identifier:path; 354, identifier:path; 355, expression_statement; 355, 356; 356, assignment; 356, 357; 356, 358; 357, identifier:checkcmds; 358, list_comprehension; 358, 359; 358, 366; 359, call; 359, 360; 359, 363; 360, attribute; 360, 361; 360, 362; 361, identifier:_; 362, identifier:format; 363, argument_list; 363, 364; 364, dictionary_splat; 364, 365; 365, identifier:fmtdict; 366, for_in_clause; 366, 367; 366, 368; 367, identifier:_; 368, list:[
'python -c "import {modname}; print({modname}.__file__)"'
]; 368, 369; 369, string:'python -c "import {modname}; print({modname}.__file__)"'; 370, import_statement; 370, 371; 371, dotted_name; 371, 372; 372, identifier:sys; 373, assert_statement; 373, 374; 374, comparison_operator:not; 374, 375; 374, 378; 375, attribute; 375, 376; 375, 377; 376, identifier:repo; 377, identifier:modname; 378, attribute; 378, 379; 378, 380; 379, identifier:sys; 380, identifier:modules; 381, expression_statement; 381, 382; 382, call; 382, 383; 382, 384; 383, identifier:print; 384, argument_list; 384, 385; 385, string:"# CHECK STATUS"; 386, for_statement; 386, 387; 386, 388; 386, 389; 387, identifier:cmd; 388, identifier:checkcmds; 389, block; 389, 390; 390, expression_statement; 390, 391; 391, call; 391, 392; 391, 393; 392, identifier:print; 393, argument_list; 393, 394; 394, identifier:cmd | def total_purge_developed_repo(repodir):
r"""
Outputs commands to help purge a repo
Args:
repodir (str): path to developed repository
CommandLine:
python -m utool.util_sysreq total_purge_installed_repo --show
Ignore:
repodir = ut.truepath('~/code/Lasagne')
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_sysreq import * # NOQA
>>> import utool as ut
>>> repodir = ut.get_argval('--repodir', default=None)
>>> result = total_purge_installed_repo(repodir)
"""
assert repodir is not None
import utool as ut
import os
repo = ut.util_git.Repo(dpath=repodir)
user = os.environ['USER']
fmtdict = dict(
user=user,
modname=repo.modname,
reponame=repo.reponame,
dpath=repo.dpath,
global_site_pkgs=ut.get_global_dist_packages_dir(),
local_site_pkgs=ut.get_local_dist_packages_dir(),
venv_site_pkgs=ut.get_site_packages_dir(),
)
commands = [_.format(**fmtdict) for _ in [
'pip uninstall {modname}',
'sudo -H pip uninstall {modname}',
'sudo pip uninstall {modname}',
'easy_install -m {modname}',
'cd {dpath} && python setup.py develop --uninstall',
# If they still exist try chowning to current user
'sudo chown -R {user}:{user} {dpath}',
]]
print('Normal uninstall commands')
print('\n'.join(commands))
possible_link_paths = [_.format(**fmtdict) for _ in [
'{dpath}/{modname}.egg-info',
'{dpath}/build',
'{venv_site_pkgs}/{reponame}.egg-info',
'{local_site_pkgs}/{reponame}.egg-info',
'{venv_site_pkgs}/{reponame}.egg-info',
]]
from os.path import exists, basename
existing_link_paths = [path for path in possible_link_paths]
print('# Delete paths and eggs')
for path in existing_link_paths:
if exists(path):
if ut.get_file_info(path)['owner'] != user:
print('sudo /bin/rm -rf {path}'.format(path=path))
else:
print('/bin/rm -rf {path}'.format(path=path))
#ut.delete(path)
print('# Make sure nothing is in the easy install paths')
easyinstall_paths = [_.format(**fmtdict) for _ in [
'{venv_site_pkgs}/easy-install.pth',
'{local_site_pkgs}/easy-install.pth',
'{venv_site_pkgs}/easy-install.pth',
]]
for path in easyinstall_paths:
if exists(path):
easy_install_list = ut.readfrom(path, verbose=False).strip().split('\n')
easy_install_list_ = [basename(p) for p in easy_install_list]
index1 = ut.listfind(easy_install_list_, repo.reponame)
index2 = ut.listfind(easy_install_list_, repo.modname)
if index1 is not None or index2 is not None:
print('Found at index1=%r, index=%r' % (index1, index2))
if ut.get_file_info(path)['owner'] != user:
print('sudo gvim {path}'.format(path=path))
else:
print('gvim {path}'.format(path=path))
checkcmds = [_.format(**fmtdict) for _ in [
'python -c "import {modname}; print({modname}.__file__)"'
]]
import sys
assert repo.modname not in sys.modules
print("# CHECK STATUS")
for cmd in checkcmds:
print(cmd) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:nx_dag_node_rank; 3, parameters; 3, 4; 3, 5; 4, identifier:graph; 5, default_parameter; 5, 6; 5, 7; 6, identifier:nodes; 7, None; 8, block; 8, 9; 8, 11; 8, 16; 8, 30; 8, 52; 8, 62; 9, expression_statement; 9, 10; 10, comment; 11, import_statement; 11, 12; 12, aliased_import; 12, 13; 12, 15; 13, dotted_name; 13, 14; 14, identifier:utool; 15, identifier:ut; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:source; 19, subscript; 19, 20; 19, 29; 20, call; 20, 21; 20, 22; 21, identifier:list; 22, argument_list; 22, 23; 23, call; 23, 24; 23, 27; 24, attribute; 24, 25; 24, 26; 25, identifier:ut; 26, identifier:nx_source_nodes; 27, argument_list; 27, 28; 28, identifier:graph; 29, integer:0; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:longest_paths; 33, call; 33, 34; 33, 35; 34, identifier:dict; 35, argument_list; 35, 36; 36, list_comprehension; 36, 37; 36, 45; 37, tuple; 37, 38; 37, 39; 38, identifier:target; 39, call; 39, 40; 39, 41; 40, identifier:dag_longest_path; 41, argument_list; 41, 42; 41, 43; 41, 44; 42, identifier:graph; 43, identifier:source; 44, identifier:target; 45, for_in_clause; 45, 46; 45, 47; 46, identifier:target; 47, call; 47, 48; 47, 51; 48, attribute; 48, 49; 48, 50; 49, identifier:graph; 50, identifier:nodes; 51, argument_list; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:node_to_rank; 55, call; 55, 56; 55, 59; 56, attribute; 56, 57; 56, 58; 57, identifier:ut; 58, identifier:map_dict_vals; 59, argument_list; 59, 60; 59, 61; 60, identifier:len; 61, identifier:longest_paths; 62, if_statement; 62, 63; 62, 66; 62, 69; 63, comparison_operator:is; 63, 64; 63, 65; 64, identifier:nodes; 65, None; 66, block; 66, 67; 67, return_statement; 67, 68; 68, identifier:node_to_rank; 69, else_clause; 69, 70; 70, block; 70, 71; 70, 81; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:ranks; 74, call; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, identifier:ut; 77, identifier:dict_take; 78, argument_list; 78, 79; 78, 80; 79, identifier:node_to_rank; 80, identifier:nodes; 81, return_statement; 81, 82; 82, identifier:ranks | def nx_dag_node_rank(graph, nodes=None):
"""
Returns rank of nodes that define the "level" each node is on in a
topological sort. This is the same as the Graphviz dot rank.
Ignore:
simple_graph = ut.simplify_graph(exi_graph)
adj_dict = ut.nx_to_adj_dict(simple_graph)
import plottool as pt
pt.qt4ensure()
pt.show_nx(graph)
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> adj_dict = {0: [5], 1: [5], 2: [1], 3: [4], 4: [0], 5: [], 6: [4], 7: [9], 8: [6], 9: [1]}
>>> nodes = [2, 1, 5]
>>> f_graph = ut.nx_from_adj_dict(adj_dict, nx.DiGraph)
>>> graph = f_graph.reverse()
>>> #ranks = ut.nx_dag_node_rank(graph, nodes)
>>> ranks = ut.nx_dag_node_rank(graph, nodes)
>>> result = ('ranks = %r' % (ranks,))
>>> print(result)
ranks = [3, 2, 1]
"""
import utool as ut
source = list(ut.nx_source_nodes(graph))[0]
longest_paths = dict([(target, dag_longest_path(graph, source, target))
for target in graph.nodes()])
node_to_rank = ut.map_dict_vals(len, longest_paths)
if nodes is None:
return node_to_rank
else:
ranks = ut.dict_take(node_to_rank, nodes)
return ranks |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 16; 2, function_name:nx_all_simple_edge_paths; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 10; 3, 13; 4, identifier:G; 5, identifier:source; 6, identifier:target; 7, default_parameter; 7, 8; 7, 9; 8, identifier:cutoff; 9, None; 10, default_parameter; 10, 11; 10, 12; 11, identifier:keys; 12, False; 13, default_parameter; 13, 14; 13, 15; 14, identifier:data; 15, False; 16, block; 16, 17; 16, 19; 16, 33; 16, 39; 16, 44; 16, 47; 16, 52; 16, 56; 16, 96; 16, 107; 17, expression_statement; 17, 18; 18, comment; 19, if_statement; 19, 20; 19, 23; 20, comparison_operator:is; 20, 21; 20, 22; 21, identifier:cutoff; 22, None; 23, block; 23, 24; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:cutoff; 27, binary_operator:-; 27, 28; 27, 32; 28, call; 28, 29; 28, 30; 29, identifier:len; 30, argument_list; 30, 31; 31, identifier:G; 32, integer:1; 33, if_statement; 33, 34; 33, 37; 34, comparison_operator:<; 34, 35; 34, 36; 35, identifier:cutoff; 36, integer:1; 37, block; 37, 38; 38, return_statement; 39, import_statement; 39, 40; 40, aliased_import; 40, 41; 40, 43; 41, dotted_name; 41, 42; 42, identifier:utool; 43, identifier:ut; 44, import_statement; 44, 45; 45, dotted_name; 45, 46; 46, identifier:six; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:visited_nodes; 50, list:[source]; 50, 51; 51, identifier:source; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:visited_edges; 55, list:[]; 56, if_statement; 56, 57; 56, 62; 56, 80; 57, call; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:G; 60, identifier:is_multigraph; 61, argument_list; 62, block; 62, 63; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:get_neighbs; 66, call; 66, 67; 66, 70; 67, attribute; 67, 68; 67, 69; 68, identifier:ut; 69, identifier:partial; 70, argument_list; 70, 71; 70, 74; 70, 77; 71, attribute; 71, 72; 71, 73; 72, identifier:G; 73, identifier:edges; 74, keyword_argument; 74, 75; 74, 76; 75, identifier:keys; 76, identifier:keys; 77, keyword_argument; 77, 78; 77, 79; 78, identifier:data; 79, identifier:data; 80, else_clause; 80, 81; 81, block; 81, 82; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 85; 84, identifier:get_neighbs; 85, call; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, identifier:ut; 88, identifier:partial; 89, argument_list; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:G; 92, identifier:edges; 93, keyword_argument; 93, 94; 93, 95; 94, identifier:data; 95, identifier:data; 96, expression_statement; 96, 97; 97, assignment; 97, 98; 97, 99; 98, identifier:edge_stack; 99, list:[iter(get_neighbs(source))]; 99, 100; 100, call; 100, 101; 100, 102; 101, identifier:iter; 102, argument_list; 102, 103; 103, call; 103, 104; 103, 105; 104, identifier:get_neighbs; 105, argument_list; 105, 106; 106, identifier:source; 107, while_statement; 107, 108; 107, 109; 108, identifier:edge_stack; 109, block; 109, 110; 109, 117; 109, 127; 110, expression_statement; 110, 111; 111, assignment; 111, 112; 111, 113; 112, identifier:children_edges; 113, subscript; 113, 114; 113, 115; 114, identifier:edge_stack; 115, unary_operator:-; 115, 116; 116, integer:1; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 120; 119, identifier:child_edge; 120, call; 120, 121; 120, 124; 121, attribute; 121, 122; 121, 123; 122, identifier:six; 123, identifier:next; 124, argument_list; 124, 125; 124, 126; 125, identifier:children_edges; 126, None; 127, if_statement; 127, 128; 127, 131; 127, 158; 127, 215; 128, comparison_operator:is; 128, 129; 128, 130; 129, identifier:child_edge; 130, None; 131, block; 131, 132; 131, 138; 131, 144; 132, expression_statement; 132, 133; 133, call; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, identifier:edge_stack; 136, identifier:pop; 137, argument_list; 138, expression_statement; 138, 139; 139, call; 139, 140; 139, 143; 140, attribute; 140, 141; 140, 142; 141, identifier:visited_nodes; 142, identifier:pop; 143, argument_list; 144, if_statement; 144, 145; 144, 151; 145, comparison_operator:>; 145, 146; 145, 150; 146, call; 146, 147; 146, 148; 147, identifier:len; 148, argument_list; 148, 149; 149, identifier:visited_edges; 150, integer:0; 151, block; 151, 152; 152, expression_statement; 152, 153; 153, call; 153, 154; 153, 157; 154, attribute; 154, 155; 154, 156; 155, identifier:visited_edges; 156, identifier:pop; 157, argument_list; 158, elif_clause; 158, 159; 158, 165; 159, comparison_operator:<; 159, 160; 159, 164; 160, call; 160, 161; 160, 162; 161, identifier:len; 162, argument_list; 162, 163; 163, identifier:visited_nodes; 164, identifier:cutoff; 165, block; 165, 166; 165, 172; 166, expression_statement; 166, 167; 167, assignment; 167, 168; 167, 169; 168, identifier:child_node; 169, subscript; 169, 170; 169, 171; 170, identifier:child_edge; 171, integer:1; 172, if_statement; 172, 173; 172, 176; 172, 183; 173, comparison_operator:==; 173, 174; 173, 175; 174, identifier:child_node; 175, identifier:target; 176, block; 176, 177; 177, expression_statement; 177, 178; 178, yield; 178, 179; 179, binary_operator:+; 179, 180; 179, 181; 180, identifier:visited_edges; 181, list:[child_edge]; 181, 182; 182, identifier:child_edge; 183, elif_clause; 183, 184; 183, 187; 184, comparison_operator:not; 184, 185; 184, 186; 185, identifier:child_node; 186, identifier:visited_nodes; 187, block; 187, 188; 187, 195; 187, 202; 188, expression_statement; 188, 189; 189, call; 189, 190; 189, 193; 190, attribute; 190, 191; 190, 192; 191, identifier:visited_nodes; 192, identifier:append; 193, argument_list; 193, 194; 194, identifier:child_node; 195, expression_statement; 195, 196; 196, call; 196, 197; 196, 200; 197, attribute; 197, 198; 197, 199; 198, identifier:visited_edges; 199, identifier:append; 200, argument_list; 200, 201; 201, identifier:child_edge; 202, expression_statement; 202, 203; 203, call; 203, 204; 203, 207; 204, attribute; 204, 205; 204, 206; 205, identifier:edge_stack; 206, identifier:append; 207, argument_list; 207, 208; 208, call; 208, 209; 208, 210; 209, identifier:iter; 210, argument_list; 210, 211; 211, call; 211, 212; 211, 213; 212, identifier:get_neighbs; 213, argument_list; 213, 214; 214, identifier:child_node; 215, else_clause; 215, 216; 216, block; 216, 217; 216, 240; 216, 246; 216, 252; 217, for_statement; 217, 218; 217, 219; 217, 226; 218, identifier:edge; 219, binary_operator:+; 219, 220; 219, 222; 220, list:[child_edge]; 220, 221; 221, identifier:child_edge; 222, call; 222, 223; 222, 224; 223, identifier:list; 224, argument_list; 224, 225; 225, identifier:children_edges; 226, block; 226, 227; 227, if_statement; 227, 228; 227, 233; 228, comparison_operator:==; 228, 229; 228, 232; 229, subscript; 229, 230; 229, 231; 230, identifier:edge; 231, integer:1; 232, identifier:target; 233, block; 233, 234; 234, expression_statement; 234, 235; 235, yield; 235, 236; 236, binary_operator:+; 236, 237; 236, 238; 237, identifier:visited_edges; 238, list:[edge]; 238, 239; 239, identifier:edge; 240, expression_statement; 240, 241; 241, call; 241, 242; 241, 245; 242, attribute; 242, 243; 242, 244; 243, identifier:edge_stack; 244, identifier:pop; 245, argument_list; 246, expression_statement; 246, 247; 247, call; 247, 248; 247, 251; 248, attribute; 248, 249; 248, 250; 249, identifier:visited_nodes; 250, identifier:pop; 251, argument_list; 252, if_statement; 252, 253; 252, 259; 253, comparison_operator:>; 253, 254; 253, 258; 254, call; 254, 255; 254, 256; 255, identifier:len; 256, argument_list; 256, 257; 257, identifier:visited_edges; 258, integer:0; 259, block; 259, 260; 260, expression_statement; 260, 261; 261, call; 261, 262; 261, 265; 262, attribute; 262, 263; 262, 264; 263, identifier:visited_edges; 264, identifier:pop; 265, argument_list | def nx_all_simple_edge_paths(G, source, target, cutoff=None, keys=False,
data=False):
"""
Returns each path from source to target as a list of edges.
This function is meant to be used with MultiGraphs or MultiDiGraphs.
When ``keys`` is True each edge in the path is returned with its unique key
identifier. In this case it is possible to distinguish between different
paths along different edges between the same two nodes.
Derived from simple_paths.py in networkx
"""
if cutoff is None:
cutoff = len(G) - 1
if cutoff < 1:
return
import utool as ut
import six
visited_nodes = [source]
visited_edges = []
if G.is_multigraph():
get_neighbs = ut.partial(G.edges, keys=keys, data=data)
else:
get_neighbs = ut.partial(G.edges, data=data)
edge_stack = [iter(get_neighbs(source))]
while edge_stack:
children_edges = edge_stack[-1]
child_edge = six.next(children_edges, None)
if child_edge is None:
edge_stack.pop()
visited_nodes.pop()
if len(visited_edges) > 0:
visited_edges.pop()
elif len(visited_nodes) < cutoff:
child_node = child_edge[1]
if child_node == target:
yield visited_edges + [child_edge]
elif child_node not in visited_nodes:
visited_nodes.append(child_node)
visited_edges.append(child_edge)
edge_stack.append(iter(get_neighbs(child_node)))
else:
for edge in [child_edge] + list(children_edges):
if edge[1] == target:
yield visited_edges + [edge]
edge_stack.pop()
visited_nodes.pop()
if len(visited_edges) > 0:
visited_edges.pop() |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 20; 2, function_name:nx_gen_node_attrs; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 14; 3, 17; 4, identifier:G; 5, identifier:key; 6, default_parameter; 6, 7; 6, 8; 7, identifier:nodes; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:default; 11, attribute; 11, 12; 11, 13; 12, identifier:util_const; 13, identifier:NoParam; 14, default_parameter; 14, 15; 14, 16; 15, identifier:on_missing; 16, string:'error'; 17, default_parameter; 17, 18; 17, 19; 18, identifier:on_keyerr; 19, string:'default'; 20, block; 20, 21; 20, 23; 20, 32; 20, 47; 20, 60; 20, 61; 20, 68; 20, 139; 20, 140; 20, 217; 21, expression_statement; 21, 22; 22, comment; 23, if_statement; 23, 24; 23, 27; 24, comparison_operator:is; 24, 25; 24, 26; 25, identifier:on_missing; 26, None; 27, block; 27, 28; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:on_missing; 31, string:'error'; 32, if_statement; 32, 33; 32, 42; 33, boolean_operator:and; 33, 34; 33, 39; 34, comparison_operator:is; 34, 35; 34, 36; 35, identifier:default; 36, attribute; 36, 37; 36, 38; 37, identifier:util_const; 38, identifier:NoParam; 39, comparison_operator:==; 39, 40; 39, 41; 40, identifier:on_keyerr; 41, string:'default'; 42, block; 42, 43; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 46; 45, identifier:on_keyerr; 46, string:'error'; 47, if_statement; 47, 48; 47, 51; 48, comparison_operator:is; 48, 49; 48, 50; 49, identifier:nodes; 50, None; 51, block; 51, 52; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:nodes; 55, call; 55, 56; 55, 59; 56, attribute; 56, 57; 56, 58; 57, identifier:G; 58, identifier:nodes; 59, argument_list; 60, comment; 61, expression_statement; 61, 62; 62, assignment; 62, 63; 62, 64; 63, identifier:node_dict; 64, call; 64, 65; 64, 66; 65, identifier:nx_node_dict; 66, argument_list; 66, 67; 67, identifier:G; 68, if_statement; 68, 69; 68, 72; 68, 85; 68, 106; 68, 127; 69, comparison_operator:==; 69, 70; 69, 71; 70, identifier:on_missing; 71, string:'error'; 72, block; 72, 73; 73, expression_statement; 73, 74; 74, assignment; 74, 75; 74, 76; 75, identifier:node_data; 76, generator_expression; 76, 77; 76, 82; 77, tuple; 77, 78; 77, 79; 78, identifier:n; 79, subscript; 79, 80; 79, 81; 80, identifier:node_dict; 81, identifier:n; 82, for_in_clause; 82, 83; 82, 84; 83, identifier:n; 84, identifier:nodes; 85, elif_clause; 85, 86; 85, 89; 86, comparison_operator:==; 86, 87; 86, 88; 87, identifier:on_missing; 88, string:'filter'; 89, block; 89, 90; 90, expression_statement; 90, 91; 91, assignment; 91, 92; 91, 93; 92, identifier:node_data; 93, generator_expression; 93, 94; 93, 99; 93, 102; 94, tuple; 94, 95; 94, 96; 95, identifier:n; 96, subscript; 96, 97; 96, 98; 97, identifier:node_dict; 98, identifier:n; 99, for_in_clause; 99, 100; 99, 101; 100, identifier:n; 101, identifier:nodes; 102, if_clause; 102, 103; 103, comparison_operator:in; 103, 104; 103, 105; 104, identifier:n; 105, identifier:G; 106, elif_clause; 106, 107; 106, 110; 107, comparison_operator:==; 107, 108; 107, 109; 108, identifier:on_missing; 109, string:'default'; 110, block; 110, 111; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:node_data; 114, generator_expression; 114, 115; 114, 124; 115, tuple; 115, 116; 115, 117; 116, identifier:n; 117, call; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, identifier:node_dict; 120, identifier:get; 121, argument_list; 121, 122; 121, 123; 122, identifier:n; 123, dictionary; 124, for_in_clause; 124, 125; 124, 126; 125, identifier:n; 126, identifier:nodes; 127, else_clause; 127, 128; 128, block; 128, 129; 129, raise_statement; 129, 130; 130, call; 130, 131; 130, 132; 131, identifier:KeyError; 132, argument_list; 132, 133; 133, call; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, string:'on_missing={} must be error, filter or default'; 136, identifier:format; 137, argument_list; 137, 138; 138, identifier:on_missing; 139, comment; 140, if_statement; 140, 141; 140, 144; 140, 159; 140, 182; 140, 205; 141, comparison_operator:==; 141, 142; 141, 143; 142, identifier:on_keyerr; 143, string:'error'; 144, block; 144, 145; 145, expression_statement; 145, 146; 146, assignment; 146, 147; 146, 148; 147, identifier:node_attrs; 148, generator_expression; 148, 149; 148, 154; 149, tuple; 149, 150; 149, 151; 150, identifier:n; 151, subscript; 151, 152; 151, 153; 152, identifier:d; 153, identifier:key; 154, for_in_clause; 154, 155; 154, 158; 155, pattern_list; 155, 156; 155, 157; 156, identifier:n; 157, identifier:d; 158, identifier:node_data; 159, elif_clause; 159, 160; 159, 163; 160, comparison_operator:==; 160, 161; 160, 162; 161, identifier:on_keyerr; 162, string:'filter'; 163, block; 163, 164; 164, expression_statement; 164, 165; 165, assignment; 165, 166; 165, 167; 166, identifier:node_attrs; 167, generator_expression; 167, 168; 167, 173; 167, 178; 168, tuple; 168, 169; 168, 170; 169, identifier:n; 170, subscript; 170, 171; 170, 172; 171, identifier:d; 172, identifier:key; 173, for_in_clause; 173, 174; 173, 177; 174, pattern_list; 174, 175; 174, 176; 175, identifier:n; 176, identifier:d; 177, identifier:node_data; 178, if_clause; 178, 179; 179, comparison_operator:in; 179, 180; 179, 181; 180, identifier:key; 181, identifier:d; 182, elif_clause; 182, 183; 182, 186; 183, comparison_operator:==; 183, 184; 183, 185; 184, identifier:on_keyerr; 185, string:'default'; 186, block; 186, 187; 187, expression_statement; 187, 188; 188, assignment; 188, 189; 188, 190; 189, identifier:node_attrs; 190, generator_expression; 190, 191; 190, 200; 191, tuple; 191, 192; 191, 193; 192, identifier:n; 193, call; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:d; 196, identifier:get; 197, argument_list; 197, 198; 197, 199; 198, identifier:key; 199, identifier:default; 200, for_in_clause; 200, 201; 200, 204; 201, pattern_list; 201, 202; 201, 203; 202, identifier:n; 203, identifier:d; 204, identifier:node_data; 205, else_clause; 205, 206; 206, block; 206, 207; 207, raise_statement; 207, 208; 208, call; 208, 209; 208, 210; 209, identifier:KeyError; 210, argument_list; 210, 211; 211, call; 211, 212; 211, 215; 212, attribute; 212, 213; 212, 214; 213, string:'on_keyerr={} must be error filter or default'; 214, identifier:format; 215, argument_list; 215, 216; 216, identifier:on_keyerr; 217, return_statement; 217, 218; 218, identifier:node_attrs | def nx_gen_node_attrs(G, key, nodes=None, default=util_const.NoParam,
on_missing='error', on_keyerr='default'):
"""
Improved generator version of nx.get_node_attributes
Args:
on_missing (str): Strategy for handling nodes missing from G.
Can be {'error', 'default', 'filter'}. defaults to 'error'.
on_keyerr (str): Strategy for handling keys missing from node dicts.
Can be {'error', 'default', 'filter'}. defaults to 'default'
if default is specified, otherwise defaults to 'error'.
Notes:
strategies are:
error - raises an error if key or node does not exist
default - returns node, but uses value specified by default
filter - skips the node
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> G = nx.Graph([(1, 2), (2, 3)])
>>> nx.set_node_attributes(G, name='part', values={1: 'bar', 3: 'baz'})
>>> nodes = [1, 2, 3, 4]
>>> #
>>> assert len(list(ut.nx_gen_node_attrs(G, 'part', default=None, on_missing='error', on_keyerr='default'))) == 3
>>> assert len(list(ut.nx_gen_node_attrs(G, 'part', default=None, on_missing='error', on_keyerr='filter'))) == 2
>>> ut.assert_raises(KeyError, list, ut.nx_gen_node_attrs(G, 'part', on_missing='error', on_keyerr='error'))
>>> #
>>> assert len(list(ut.nx_gen_node_attrs(G, 'part', nodes, default=None, on_missing='filter', on_keyerr='default'))) == 3
>>> assert len(list(ut.nx_gen_node_attrs(G, 'part', nodes, default=None, on_missing='filter', on_keyerr='filter'))) == 2
>>> ut.assert_raises(KeyError, list, ut.nx_gen_node_attrs(G, 'part', nodes, on_missing='filter', on_keyerr='error'))
>>> #
>>> assert len(list(ut.nx_gen_node_attrs(G, 'part', nodes, default=None, on_missing='default', on_keyerr='default'))) == 4
>>> assert len(list(ut.nx_gen_node_attrs(G, 'part', nodes, default=None, on_missing='default', on_keyerr='filter'))) == 2
>>> ut.assert_raises(KeyError, list, ut.nx_gen_node_attrs(G, 'part', nodes, on_missing='default', on_keyerr='error'))
Example:
>>> # DISABLE_DOCTEST
>>> # ALL CASES
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> G = nx.Graph([(1, 2), (2, 3)])
>>> nx.set_node_attributes(G, name='full', values={1: 'A', 2: 'B', 3: 'C'})
>>> nx.set_node_attributes(G, name='part', values={1: 'bar', 3: 'baz'})
>>> nodes = [1, 2, 3, 4]
>>> attrs = dict(ut.nx_gen_node_attrs(G, 'full'))
>>> input_grid = {
>>> 'nodes': [None, (1, 2, 3, 4)],
>>> 'key': ['part', 'full'],
>>> 'default': [util_const.NoParam, None],
>>> }
>>> inputs = ut.all_dict_combinations(input_grid)
>>> kw_grid = {
>>> 'on_missing': ['error', 'default', 'filter'],
>>> 'on_keyerr': ['error', 'default', 'filter'],
>>> }
>>> kws = ut.all_dict_combinations(kw_grid)
>>> for in_ in inputs:
>>> for kw in kws:
>>> kw2 = ut.dict_union(kw, in_)
>>> #print(kw2)
>>> on_missing = kw['on_missing']
>>> on_keyerr = kw['on_keyerr']
>>> if on_keyerr == 'default' and in_['default'] is util_const.NoParam:
>>> on_keyerr = 'error'
>>> will_miss = False
>>> will_keyerr = False
>>> if on_missing == 'error':
>>> if in_['key'] == 'part' and in_['nodes'] is not None:
>>> will_miss = True
>>> if in_['key'] == 'full' and in_['nodes'] is not None:
>>> will_miss = True
>>> if on_keyerr == 'error':
>>> if in_['key'] == 'part':
>>> will_keyerr = True
>>> if on_missing == 'default':
>>> if in_['key'] == 'full' and in_['nodes'] is not None:
>>> will_keyerr = True
>>> want_error = will_miss or will_keyerr
>>> gen = ut.nx_gen_node_attrs(G, **kw2)
>>> try:
>>> attrs = list(gen)
>>> except KeyError:
>>> if not want_error:
>>> raise AssertionError('should not have errored')
>>> else:
>>> if want_error:
>>> raise AssertionError('should have errored')
"""
if on_missing is None:
on_missing = 'error'
if default is util_const.NoParam and on_keyerr == 'default':
on_keyerr = 'error'
if nodes is None:
nodes = G.nodes()
# Generate `node_data` nodes and data dictionary
node_dict = nx_node_dict(G)
if on_missing == 'error':
node_data = ((n, node_dict[n]) for n in nodes)
elif on_missing == 'filter':
node_data = ((n, node_dict[n]) for n in nodes if n in G)
elif on_missing == 'default':
node_data = ((n, node_dict.get(n, {})) for n in nodes)
else:
raise KeyError('on_missing={} must be error, filter or default'.format(
on_missing))
# Get `node_attrs` desired value out of dictionary
if on_keyerr == 'error':
node_attrs = ((n, d[key]) for n, d in node_data)
elif on_keyerr == 'filter':
node_attrs = ((n, d[key]) for n, d in node_data if key in d)
elif on_keyerr == 'default':
node_attrs = ((n, d.get(key, default)) for n, d in node_data)
else:
raise KeyError('on_keyerr={} must be error filter or default'.format(on_keyerr))
return node_attrs |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 20; 2, function_name:nx_gen_edge_values; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 14; 3, 17; 4, identifier:G; 5, identifier:key; 6, default_parameter; 6, 7; 6, 8; 7, identifier:edges; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:default; 11, attribute; 11, 12; 11, 13; 12, identifier:util_const; 13, identifier:NoParam; 14, default_parameter; 14, 15; 14, 16; 15, identifier:on_missing; 16, string:'error'; 17, default_parameter; 17, 18; 17, 19; 18, identifier:on_keyerr; 19, string:'default'; 20, block; 20, 21; 20, 23; 20, 36; 20, 45; 20, 54; 20, 69; 20, 70; 20, 133; 20, 134; 20, 180; 21, expression_statement; 21, 22; 22, comment; 23, if_statement; 23, 24; 23, 27; 24, comparison_operator:is; 24, 25; 24, 26; 25, identifier:edges; 26, None; 27, block; 27, 28; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:edges; 31, call; 31, 32; 31, 35; 32, attribute; 32, 33; 32, 34; 33, identifier:G; 34, identifier:edges; 35, argument_list; 36, if_statement; 36, 37; 36, 40; 37, comparison_operator:is; 37, 38; 37, 39; 38, identifier:on_missing; 39, None; 40, block; 40, 41; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:on_missing; 44, string:'error'; 45, if_statement; 45, 46; 45, 49; 46, comparison_operator:is; 46, 47; 46, 48; 47, identifier:on_keyerr; 48, None; 49, block; 49, 50; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:on_keyerr; 53, string:'default'; 54, if_statement; 54, 55; 54, 64; 55, boolean_operator:and; 55, 56; 55, 61; 56, comparison_operator:is; 56, 57; 56, 58; 57, identifier:default; 58, attribute; 58, 59; 58, 60; 59, identifier:util_const; 60, identifier:NoParam; 61, comparison_operator:==; 61, 62; 61, 63; 62, identifier:on_keyerr; 63, string:'default'; 64, block; 64, 65; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:on_keyerr; 68, string:'error'; 69, comment; 70, if_statement; 70, 71; 70, 74; 70, 91; 70, 121; 71, comparison_operator:==; 71, 72; 71, 73; 72, identifier:on_missing; 73, string:'error'; 74, block; 74, 75; 75, expression_statement; 75, 76; 76, assignment; 76, 77; 76, 78; 77, identifier:data_iter; 78, generator_expression; 78, 79; 78, 86; 79, subscript; 79, 80; 79, 85; 80, subscript; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:G; 83, identifier:adj; 84, identifier:u; 85, identifier:v; 86, for_in_clause; 86, 87; 86, 90; 87, pattern_list; 87, 88; 87, 89; 88, identifier:u; 89, identifier:v; 90, identifier:edges; 91, elif_clause; 91, 92; 91, 95; 92, comparison_operator:==; 92, 93; 92, 94; 93, identifier:on_missing; 94, string:'default'; 95, block; 95, 96; 96, expression_statement; 96, 97; 97, assignment; 97, 98; 97, 99; 98, identifier:data_iter; 99, generator_expression; 99, 100; 99, 116; 100, conditional_expression:if; 100, 101; 100, 108; 100, 115; 101, subscript; 101, 102; 101, 107; 102, subscript; 102, 103; 102, 106; 103, attribute; 103, 104; 103, 105; 104, identifier:G; 105, identifier:adj; 106, identifier:u; 107, identifier:v; 108, call; 108, 109; 108, 112; 109, attribute; 109, 110; 109, 111; 110, identifier:G; 111, identifier:has_edge; 112, argument_list; 112, 113; 112, 114; 113, identifier:u; 114, identifier:v; 115, dictionary; 116, for_in_clause; 116, 117; 116, 120; 117, pattern_list; 117, 118; 117, 119; 118, identifier:u; 119, identifier:v; 120, identifier:edges; 121, else_clause; 121, 122; 122, block; 122, 123; 123, raise_statement; 123, 124; 124, call; 124, 125; 124, 126; 125, identifier:KeyError; 126, argument_list; 126, 127; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, string:'on_missing={} must be error, filter or default'; 130, identifier:format; 131, argument_list; 131, 132; 132, identifier:on_missing; 133, comment; 134, if_statement; 134, 135; 134, 138; 134, 149; 134, 168; 135, comparison_operator:==; 135, 136; 135, 137; 136, identifier:on_keyerr; 137, string:'error'; 138, block; 138, 139; 139, expression_statement; 139, 140; 140, assignment; 140, 141; 140, 142; 141, identifier:value_iter; 142, generator_expression; 142, 143; 142, 146; 143, subscript; 143, 144; 143, 145; 144, identifier:d; 145, identifier:key; 146, for_in_clause; 146, 147; 146, 148; 147, identifier:d; 148, identifier:data_iter; 149, elif_clause; 149, 150; 149, 153; 150, comparison_operator:==; 150, 151; 150, 152; 151, identifier:on_keyerr; 152, string:'default'; 153, block; 153, 154; 154, expression_statement; 154, 155; 155, assignment; 155, 156; 155, 157; 156, identifier:value_iter; 157, generator_expression; 157, 158; 157, 165; 158, call; 158, 159; 158, 162; 159, attribute; 159, 160; 159, 161; 160, identifier:d; 161, identifier:get; 162, argument_list; 162, 163; 162, 164; 163, identifier:key; 164, identifier:default; 165, for_in_clause; 165, 166; 165, 167; 166, identifier:d; 167, identifier:data_iter; 168, else_clause; 168, 169; 169, block; 169, 170; 170, raise_statement; 170, 171; 171, call; 171, 172; 171, 173; 172, identifier:KeyError; 173, argument_list; 173, 174; 174, call; 174, 175; 174, 178; 175, attribute; 175, 176; 175, 177; 176, string:'on_keyerr={} must be error or default'; 177, identifier:format; 178, argument_list; 178, 179; 179, identifier:on_keyerr; 180, return_statement; 180, 181; 181, identifier:value_iter | def nx_gen_edge_values(G, key, edges=None, default=util_const.NoParam,
on_missing='error', on_keyerr='default'):
"""
Generates attributes values of specific edges
Args:
on_missing (str): Strategy for handling nodes missing from G.
Can be {'error', 'default'}. defaults to 'error'.
on_keyerr (str): Strategy for handling keys missing from node dicts.
Can be {'error', 'default'}. defaults to 'default'
if default is specified, otherwise defaults to 'error'.
"""
if edges is None:
edges = G.edges()
if on_missing is None:
on_missing = 'error'
if on_keyerr is None:
on_keyerr = 'default'
if default is util_const.NoParam and on_keyerr == 'default':
on_keyerr = 'error'
# Generate `data_iter` edges and data dictionary
if on_missing == 'error':
data_iter = (G.adj[u][v] for u, v in edges)
elif on_missing == 'default':
data_iter = (G.adj[u][v] if G.has_edge(u, v) else {}
for u, v in edges)
else:
raise KeyError('on_missing={} must be error, filter or default'.format(
on_missing))
# Get `value_iter` desired value out of dictionary
if on_keyerr == 'error':
value_iter = (d[key] for d in data_iter)
elif on_keyerr == 'default':
value_iter = (d.get(key, default) for d in data_iter)
else:
raise KeyError('on_keyerr={} must be error or default'.format(on_keyerr))
return value_iter |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 20; 2, function_name:nx_gen_edge_attrs; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 14; 3, 17; 4, identifier:G; 5, identifier:key; 6, default_parameter; 6, 7; 6, 8; 7, identifier:edges; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:default; 11, attribute; 11, 12; 11, 13; 12, identifier:util_const; 13, identifier:NoParam; 14, default_parameter; 14, 15; 14, 16; 15, identifier:on_missing; 16, string:'error'; 17, default_parameter; 17, 18; 17, 19; 18, identifier:on_keyerr; 19, string:'default'; 20, block; 20, 21; 20, 23; 20, 32; 20, 47; 20, 75; 20, 76; 20, 184; 20, 185; 20, 262; 21, expression_statement; 21, 22; 22, comment; 23, if_statement; 23, 24; 23, 27; 24, comparison_operator:is; 24, 25; 24, 26; 25, identifier:on_missing; 26, None; 27, block; 27, 28; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:on_missing; 31, string:'error'; 32, if_statement; 32, 33; 32, 42; 33, boolean_operator:and; 33, 34; 33, 39; 34, comparison_operator:is; 34, 35; 34, 36; 35, identifier:default; 36, attribute; 36, 37; 36, 38; 37, identifier:util_const; 38, identifier:NoParam; 39, comparison_operator:==; 39, 40; 39, 41; 40, identifier:on_keyerr; 41, string:'default'; 42, block; 42, 43; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 46; 45, identifier:on_keyerr; 46, string:'error'; 47, if_statement; 47, 48; 47, 51; 48, comparison_operator:is; 48, 49; 48, 50; 49, identifier:edges; 50, None; 51, block; 51, 52; 52, if_statement; 52, 53; 52, 58; 52, 65; 53, call; 53, 54; 53, 57; 54, attribute; 54, 55; 54, 56; 55, identifier:G; 56, identifier:is_multigraph; 57, argument_list; 58, block; 58, 59; 58, 64; 59, raise_statement; 59, 60; 60, call; 60, 61; 60, 62; 61, identifier:NotImplementedError; 62, argument_list; 62, 63; 63, string:''; 64, comment; 65, else_clause; 65, 66; 66, block; 66, 67; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:edges; 70, call; 70, 71; 70, 74; 71, attribute; 71, 72; 71, 73; 72, identifier:G; 73, identifier:edges; 74, argument_list; 75, comment; 76, if_statement; 76, 77; 76, 80; 76, 101; 76, 134; 76, 172; 77, comparison_operator:==; 77, 78; 77, 79; 78, identifier:on_missing; 79, string:'error'; 80, block; 80, 81; 81, expression_statement; 81, 82; 82, assignment; 82, 83; 82, 84; 83, identifier:edge_data; 84, generator_expression; 84, 85; 84, 96; 85, tuple; 85, 86; 85, 89; 86, tuple; 86, 87; 86, 88; 87, identifier:u; 88, identifier:v; 89, subscript; 89, 90; 89, 95; 90, subscript; 90, 91; 90, 94; 91, attribute; 91, 92; 91, 93; 92, identifier:G; 93, identifier:adj; 94, identifier:u; 95, identifier:v; 96, for_in_clause; 96, 97; 96, 100; 97, pattern_list; 97, 98; 97, 99; 98, identifier:u; 99, identifier:v; 100, identifier:edges; 101, elif_clause; 101, 102; 101, 105; 102, comparison_operator:==; 102, 103; 102, 104; 103, identifier:on_missing; 104, string:'filter'; 105, block; 105, 106; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:edge_data; 109, generator_expression; 109, 110; 109, 121; 109, 126; 110, tuple; 110, 111; 110, 114; 111, tuple; 111, 112; 111, 113; 112, identifier:u; 113, identifier:v; 114, subscript; 114, 115; 114, 120; 115, subscript; 115, 116; 115, 119; 116, attribute; 116, 117; 116, 118; 117, identifier:G; 118, identifier:adj; 119, identifier:u; 120, identifier:v; 121, for_in_clause; 121, 122; 121, 125; 122, pattern_list; 122, 123; 122, 124; 123, identifier:u; 124, identifier:v; 125, identifier:edges; 126, if_clause; 126, 127; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:G; 130, identifier:has_edge; 131, argument_list; 131, 132; 131, 133; 132, identifier:u; 133, identifier:v; 134, elif_clause; 134, 135; 134, 138; 135, comparison_operator:==; 135, 136; 135, 137; 136, identifier:on_missing; 137, string:'default'; 138, block; 138, 139; 139, expression_statement; 139, 140; 140, assignment; 140, 141; 140, 142; 141, identifier:edge_data; 142, generator_expression; 142, 143; 142, 167; 143, conditional_expression:if; 143, 144; 143, 155; 143, 162; 144, tuple; 144, 145; 144, 148; 145, tuple; 145, 146; 145, 147; 146, identifier:u; 147, identifier:v; 148, subscript; 148, 149; 148, 154; 149, subscript; 149, 150; 149, 153; 150, attribute; 150, 151; 150, 152; 151, identifier:G; 152, identifier:adj; 153, identifier:u; 154, identifier:v; 155, call; 155, 156; 155, 159; 156, attribute; 156, 157; 156, 158; 157, identifier:G; 158, identifier:has_edge; 159, argument_list; 159, 160; 159, 161; 160, identifier:u; 161, identifier:v; 162, tuple; 162, 163; 162, 166; 163, tuple; 163, 164; 163, 165; 164, identifier:u; 165, identifier:v; 166, dictionary; 167, for_in_clause; 167, 168; 167, 171; 168, pattern_list; 168, 169; 168, 170; 169, identifier:u; 170, identifier:v; 171, identifier:edges; 172, else_clause; 172, 173; 173, block; 173, 174; 174, raise_statement; 174, 175; 175, call; 175, 176; 175, 177; 176, identifier:KeyError; 177, argument_list; 177, 178; 178, call; 178, 179; 178, 182; 179, attribute; 179, 180; 179, 181; 180, string:'on_missing={}'; 181, identifier:format; 182, argument_list; 182, 183; 183, identifier:on_missing; 184, comment; 185, if_statement; 185, 186; 185, 189; 185, 204; 185, 227; 185, 250; 186, comparison_operator:==; 186, 187; 186, 188; 187, identifier:on_keyerr; 188, string:'error'; 189, block; 189, 190; 190, expression_statement; 190, 191; 191, assignment; 191, 192; 191, 193; 192, identifier:edge_attrs; 193, generator_expression; 193, 194; 193, 199; 194, tuple; 194, 195; 194, 196; 195, identifier:e; 196, subscript; 196, 197; 196, 198; 197, identifier:d; 198, identifier:key; 199, for_in_clause; 199, 200; 199, 203; 200, pattern_list; 200, 201; 200, 202; 201, identifier:e; 202, identifier:d; 203, identifier:edge_data; 204, elif_clause; 204, 205; 204, 208; 205, comparison_operator:==; 205, 206; 205, 207; 206, identifier:on_keyerr; 207, string:'filter'; 208, block; 208, 209; 209, expression_statement; 209, 210; 210, assignment; 210, 211; 210, 212; 211, identifier:edge_attrs; 212, generator_expression; 212, 213; 212, 218; 212, 223; 213, tuple; 213, 214; 213, 215; 214, identifier:e; 215, subscript; 215, 216; 215, 217; 216, identifier:d; 217, identifier:key; 218, for_in_clause; 218, 219; 218, 222; 219, pattern_list; 219, 220; 219, 221; 220, identifier:e; 221, identifier:d; 222, identifier:edge_data; 223, if_clause; 223, 224; 224, comparison_operator:in; 224, 225; 224, 226; 225, identifier:key; 226, identifier:d; 227, elif_clause; 227, 228; 227, 231; 228, comparison_operator:==; 228, 229; 228, 230; 229, identifier:on_keyerr; 230, string:'default'; 231, block; 231, 232; 232, expression_statement; 232, 233; 233, assignment; 233, 234; 233, 235; 234, identifier:edge_attrs; 235, generator_expression; 235, 236; 235, 245; 236, tuple; 236, 237; 236, 238; 237, identifier:e; 238, call; 238, 239; 238, 242; 239, attribute; 239, 240; 239, 241; 240, identifier:d; 241, identifier:get; 242, argument_list; 242, 243; 242, 244; 243, identifier:key; 244, identifier:default; 245, for_in_clause; 245, 246; 245, 249; 246, pattern_list; 246, 247; 246, 248; 247, identifier:e; 248, identifier:d; 249, identifier:edge_data; 250, else_clause; 250, 251; 251, block; 251, 252; 252, raise_statement; 252, 253; 253, call; 253, 254; 253, 255; 254, identifier:KeyError; 255, argument_list; 255, 256; 256, call; 256, 257; 256, 260; 257, attribute; 257, 258; 257, 259; 258, string:'on_keyerr={}'; 259, identifier:format; 260, argument_list; 260, 261; 261, identifier:on_keyerr; 262, return_statement; 262, 263; 263, identifier:edge_attrs | def nx_gen_edge_attrs(G, key, edges=None, default=util_const.NoParam,
on_missing='error', on_keyerr='default'):
"""
Improved generator version of nx.get_edge_attributes
Args:
on_missing (str): Strategy for handling nodes missing from G.
Can be {'error', 'default', 'filter'}. defaults to 'error'.
is on_missing is not error, then we allow any edge even if the
endpoints are not in the graph.
on_keyerr (str): Strategy for handling keys missing from node dicts.
Can be {'error', 'default', 'filter'}. defaults to 'default'
if default is specified, otherwise defaults to 'error'.
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
>>> nx.set_edge_attributes(G, name='part', values={(1, 2): 'bar', (2, 3): 'baz'})
>>> edges = [(1, 2), (2, 3), (3, 4), (4, 5)]
>>> func = ut.partial(ut.nx_gen_edge_attrs, G, 'part', default=None)
>>> #
>>> assert len(list(func(on_missing='error', on_keyerr='default'))) == 3
>>> assert len(list(func(on_missing='error', on_keyerr='filter'))) == 2
>>> ut.assert_raises(KeyError, list, func(on_missing='error', on_keyerr='error'))
>>> #
>>> assert len(list(func(edges, on_missing='filter', on_keyerr='default'))) == 3
>>> assert len(list(func(edges, on_missing='filter', on_keyerr='filter'))) == 2
>>> ut.assert_raises(KeyError, list, func(edges, on_missing='filter', on_keyerr='error'))
>>> #
>>> assert len(list(func(edges, on_missing='default', on_keyerr='default'))) == 4
>>> assert len(list(func(edges, on_missing='default', on_keyerr='filter'))) == 2
>>> ut.assert_raises(KeyError, list, func(edges, on_missing='default', on_keyerr='error'))
"""
if on_missing is None:
on_missing = 'error'
if default is util_const.NoParam and on_keyerr == 'default':
on_keyerr = 'error'
if edges is None:
if G.is_multigraph():
raise NotImplementedError('')
# uvk_iter = G.edges(keys=True)
else:
edges = G.edges()
# Generate `edge_data` edges and data dictionary
if on_missing == 'error':
edge_data = (((u, v), G.adj[u][v]) for u, v in edges)
elif on_missing == 'filter':
edge_data = (((u, v), G.adj[u][v]) for u, v in edges if G.has_edge(u, v))
elif on_missing == 'default':
edge_data = (((u, v), G.adj[u][v])
if G.has_edge(u, v) else ((u, v), {})
for u, v in edges)
else:
raise KeyError('on_missing={}'.format(on_missing))
# Get `edge_attrs` desired value out of dictionary
if on_keyerr == 'error':
edge_attrs = ((e, d[key]) for e, d in edge_data)
elif on_keyerr == 'filter':
edge_attrs = ((e, d[key]) for e, d in edge_data if key in d)
elif on_keyerr == 'default':
edge_attrs = ((e, d.get(key, default)) for e, d in edge_data)
else:
raise KeyError('on_keyerr={}'.format(on_keyerr))
return edge_attrs |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:nx_ensure_agraph_color; 3, parameters; 3, 4; 4, identifier:graph; 5, block; 5, 6; 5, 8; 5, 13; 5, 18; 5, 19; 5, 188; 5, 210; 6, expression_statement; 6, 7; 7, comment; 8, import_from_statement; 8, 9; 8, 11; 9, dotted_name; 9, 10; 10, identifier:plottool; 11, dotted_name; 11, 12; 12, identifier:color_funcs; 13, import_statement; 13, 14; 14, aliased_import; 14, 15; 14, 17; 15, dotted_name; 15, 16; 16, identifier:plottool; 17, identifier:pt; 18, comment; 19, function_definition; 19, 20; 19, 21; 19, 23; 20, function_name:_fix_agraph_color; 21, parameters; 21, 22; 22, identifier:data; 23, block; 23, 24; 24, try_statement; 24, 25; 24, 163; 25, block; 25, 26; 25, 36; 25, 46; 25, 50; 25, 66; 26, expression_statement; 26, 27; 27, assignment; 27, 28; 27, 29; 28, identifier:orig_color; 29, call; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:data; 32, identifier:get; 33, argument_list; 33, 34; 33, 35; 34, string:'color'; 35, None; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:alpha; 39, call; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:data; 42, identifier:get; 43, argument_list; 43, 44; 43, 45; 44, string:'alpha'; 45, None; 46, expression_statement; 46, 47; 47, assignment; 47, 48; 47, 49; 48, identifier:color; 49, identifier:orig_color; 50, if_statement; 50, 51; 50, 58; 51, boolean_operator:and; 51, 52; 51, 55; 52, comparison_operator:is; 52, 53; 52, 54; 53, identifier:color; 54, None; 55, comparison_operator:is; 55, 56; 55, 57; 56, identifier:alpha; 57, None; 58, block; 58, 59; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:color; 62, list:[0, 0, 0]; 62, 63; 62, 64; 62, 65; 63, integer:0; 64, integer:0; 65, integer:0; 66, if_statement; 66, 67; 66, 70; 67, comparison_operator:is; 67, 68; 67, 69; 68, identifier:color; 69, None; 70, block; 70, 71; 70, 80; 70, 81; 70, 82; 70, 94; 70, 130; 70, 137; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:color; 74, call; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, identifier:pt; 77, identifier:ensure_nonhex_color; 78, argument_list; 78, 79; 79, identifier:color; 80, comment; 81, comment; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 85; 84, identifier:color; 85, call; 85, 86; 85, 87; 86, identifier:list; 87, argument_list; 87, 88; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:color_funcs; 91, identifier:ensure_base255; 92, argument_list; 92, 93; 93, identifier:color; 94, if_statement; 94, 95; 94, 98; 95, comparison_operator:is; 95, 96; 95, 97; 96, identifier:alpha; 97, None; 98, block; 98, 99; 99, if_statement; 99, 100; 99, 106; 99, 117; 100, comparison_operator:==; 100, 101; 100, 105; 101, call; 101, 102; 101, 103; 102, identifier:len; 103, argument_list; 103, 104; 104, identifier:color; 105, integer:3; 106, block; 106, 107; 107, expression_statement; 107, 108; 108, augmented_assignment:+=; 108, 109; 108, 110; 109, identifier:color; 110, list:[int(alpha * 255)]; 110, 111; 111, call; 111, 112; 111, 113; 112, identifier:int; 113, argument_list; 113, 114; 114, binary_operator:*; 114, 115; 114, 116; 115, identifier:alpha; 116, integer:255; 117, else_clause; 117, 118; 118, block; 118, 119; 119, expression_statement; 119, 120; 120, assignment; 120, 121; 120, 124; 121, subscript; 121, 122; 121, 123; 122, identifier:color; 123, integer:3; 124, call; 124, 125; 124, 126; 125, identifier:int; 126, argument_list; 126, 127; 127, binary_operator:*; 127, 128; 127, 129; 128, identifier:alpha; 129, integer:255; 130, expression_statement; 130, 131; 131, assignment; 131, 132; 131, 133; 132, identifier:color; 133, call; 133, 134; 133, 135; 134, identifier:tuple; 135, argument_list; 135, 136; 136, identifier:color; 137, if_statement; 137, 138; 137, 144; 137, 153; 138, comparison_operator:==; 138, 139; 138, 143; 139, call; 139, 140; 139, 141; 140, identifier:len; 141, argument_list; 141, 142; 142, identifier:color; 143, integer:3; 144, block; 144, 145; 145, expression_statement; 145, 146; 146, assignment; 146, 147; 146, 150; 147, subscript; 147, 148; 147, 149; 148, identifier:data; 149, string:'color'; 150, binary_operator:%; 150, 151; 150, 152; 151, string:'#%02x%02x%02x'; 152, identifier:color; 153, else_clause; 153, 154; 154, block; 154, 155; 155, expression_statement; 155, 156; 156, assignment; 156, 157; 156, 160; 157, subscript; 157, 158; 157, 159; 158, identifier:data; 159, string:'color'; 160, binary_operator:%; 160, 161; 160, 162; 161, string:'#%02x%02x%02x%02x'; 162, identifier:color; 163, except_clause; 163, 164; 163, 168; 164, as_pattern; 164, 165; 164, 166; 165, identifier:Exception; 166, as_pattern_target; 166, 167; 167, identifier:ex; 168, block; 168, 169; 168, 174; 168, 187; 169, import_statement; 169, 170; 170, aliased_import; 170, 171; 170, 173; 171, dotted_name; 171, 172; 172, identifier:utool; 173, identifier:ut; 174, expression_statement; 174, 175; 175, call; 175, 176; 175, 179; 176, attribute; 176, 177; 176, 178; 177, identifier:ut; 178, identifier:printex; 179, argument_list; 179, 180; 179, 181; 180, identifier:ex; 181, keyword_argument; 181, 182; 181, 183; 182, identifier:keys; 183, list:['color', 'orig_color', 'data']; 183, 184; 183, 185; 183, 186; 184, string:'color'; 185, string:'orig_color'; 186, string:'data'; 187, raise_statement; 188, for_statement; 188, 189; 188, 192; 188, 200; 189, pattern_list; 189, 190; 189, 191; 190, identifier:node; 191, identifier:node_data; 192, call; 192, 193; 192, 196; 193, attribute; 193, 194; 193, 195; 194, identifier:graph; 195, identifier:nodes; 196, argument_list; 196, 197; 197, keyword_argument; 197, 198; 197, 199; 198, identifier:data; 199, True; 200, block; 200, 201; 200, 205; 201, expression_statement; 201, 202; 202, assignment; 202, 203; 202, 204; 203, identifier:data; 204, identifier:node_data; 205, expression_statement; 205, 206; 206, call; 206, 207; 206, 208; 207, identifier:_fix_agraph_color; 208, argument_list; 208, 209; 209, identifier:data; 210, for_statement; 210, 211; 210, 215; 210, 223; 211, pattern_list; 211, 212; 211, 213; 211, 214; 212, identifier:u; 213, identifier:v; 214, identifier:edge_data; 215, call; 215, 216; 215, 219; 216, attribute; 216, 217; 216, 218; 217, identifier:graph; 218, identifier:edges; 219, argument_list; 219, 220; 220, keyword_argument; 220, 221; 220, 222; 221, identifier:data; 222, True; 223, block; 223, 224; 223, 228; 224, expression_statement; 224, 225; 225, assignment; 225, 226; 225, 227; 226, identifier:data; 227, identifier:edge_data; 228, expression_statement; 228, 229; 229, call; 229, 230; 229, 231; 230, identifier:_fix_agraph_color; 231, argument_list; 231, 232; 232, identifier:data | def nx_ensure_agraph_color(graph):
""" changes colors to hex strings on graph attrs """
from plottool import color_funcs
import plottool as pt
#import six
def _fix_agraph_color(data):
try:
orig_color = data.get('color', None)
alpha = data.get('alpha', None)
color = orig_color
if color is None and alpha is not None:
color = [0, 0, 0]
if color is not None:
color = pt.ensure_nonhex_color(color)
#if isinstance(color, np.ndarray):
# color = color.tolist()
color = list(color_funcs.ensure_base255(color))
if alpha is not None:
if len(color) == 3:
color += [int(alpha * 255)]
else:
color[3] = int(alpha * 255)
color = tuple(color)
if len(color) == 3:
data['color'] = '#%02x%02x%02x' % color
else:
data['color'] = '#%02x%02x%02x%02x' % color
except Exception as ex:
import utool as ut
ut.printex(ex, keys=['color', 'orig_color', 'data'])
raise
for node, node_data in graph.nodes(data=True):
data = node_data
_fix_agraph_color(data)
for u, v, edge_data in graph.edges(data=True):
data = edge_data
_fix_agraph_color(data) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:simplify_graph; 3, parameters; 3, 4; 4, identifier:graph; 5, block; 5, 6; 5, 8; 5, 13; 5, 27; 5, 36; 5, 70; 5, 80; 5, 129; 5, 135; 5, 141; 5, 148; 5, 155; 6, expression_statement; 6, 7; 7, comment; 8, import_statement; 8, 9; 9, aliased_import; 9, 10; 9, 12; 10, dotted_name; 10, 11; 11, identifier:utool; 12, identifier:ut; 13, expression_statement; 13, 14; 14, assignment; 14, 15; 14, 16; 15, identifier:nodes; 16, call; 16, 17; 16, 18; 17, identifier:sorted; 18, argument_list; 18, 19; 19, call; 19, 20; 19, 21; 20, identifier:list; 21, argument_list; 21, 22; 22, call; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:graph; 25, identifier:nodes; 26, argument_list; 27, expression_statement; 27, 28; 28, assignment; 28, 29; 28, 30; 29, identifier:node_lookup; 30, call; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:ut; 33, identifier:make_index_lookup; 34, argument_list; 34, 35; 35, identifier:nodes; 36, if_statement; 36, 37; 36, 42; 36, 57; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:graph; 40, identifier:is_multigraph; 41, argument_list; 42, block; 42, 43; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 46; 45, identifier:edges; 46, call; 46, 47; 46, 48; 47, identifier:list; 48, argument_list; 48, 49; 49, call; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:graph; 52, identifier:edges; 53, argument_list; 53, 54; 54, keyword_argument; 54, 55; 54, 56; 55, identifier:keys; 56, True; 57, else_clause; 57, 58; 58, block; 58, 59; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:edges; 62, call; 62, 63; 62, 64; 63, identifier:list; 64, argument_list; 64, 65; 65, call; 65, 66; 65, 69; 66, attribute; 66, 67; 66, 68; 67, identifier:graph; 68, identifier:edges; 69, argument_list; 70, expression_statement; 70, 71; 71, assignment; 71, 72; 71, 73; 72, identifier:new_nodes; 73, call; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:ut; 76, identifier:take; 77, argument_list; 77, 78; 77, 79; 78, identifier:node_lookup; 79, identifier:nodes; 80, if_statement; 80, 81; 80, 86; 80, 109; 81, call; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:graph; 84, identifier:is_multigraph; 85, argument_list; 86, block; 86, 87; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:new_edges; 90, list_comprehension; 90, 91; 90, 106; 91, tuple; 91, 92; 91, 97; 91, 102; 91, 105; 92, subscript; 92, 93; 92, 94; 93, identifier:node_lookup; 94, subscript; 94, 95; 94, 96; 95, identifier:e; 96, integer:0; 97, subscript; 97, 98; 97, 99; 98, identifier:node_lookup; 99, subscript; 99, 100; 99, 101; 100, identifier:e; 101, integer:1; 102, subscript; 102, 103; 102, 104; 103, identifier:e; 104, integer:2; 105, dictionary; 106, for_in_clause; 106, 107; 106, 108; 107, identifier:e; 108, identifier:edges; 109, else_clause; 109, 110; 110, block; 110, 111; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:new_edges; 114, list_comprehension; 114, 115; 114, 126; 115, tuple; 115, 116; 115, 121; 116, subscript; 116, 117; 116, 118; 117, identifier:node_lookup; 118, subscript; 118, 119; 118, 120; 119, identifier:e; 120, integer:0; 121, subscript; 121, 122; 121, 123; 122, identifier:node_lookup; 123, subscript; 123, 124; 123, 125; 124, identifier:e; 125, integer:1; 126, for_in_clause; 126, 127; 126, 128; 127, identifier:e; 128, identifier:edges; 129, expression_statement; 129, 130; 130, assignment; 130, 131; 130, 132; 131, identifier:cls; 132, attribute; 132, 133; 132, 134; 133, identifier:graph; 134, identifier:__class__; 135, expression_statement; 135, 136; 136, assignment; 136, 137; 136, 138; 137, identifier:new_graph; 138, call; 138, 139; 138, 140; 139, identifier:cls; 140, argument_list; 141, expression_statement; 141, 142; 142, call; 142, 143; 142, 146; 143, attribute; 143, 144; 143, 145; 144, identifier:new_graph; 145, identifier:add_nodes_from; 146, argument_list; 146, 147; 147, identifier:new_nodes; 148, expression_statement; 148, 149; 149, call; 149, 150; 149, 153; 150, attribute; 150, 151; 150, 152; 151, identifier:new_graph; 152, identifier:add_edges_from; 153, argument_list; 153, 154; 154, identifier:new_edges; 155, return_statement; 155, 156; 156, identifier:new_graph | def simplify_graph(graph):
"""
strips out everything but connectivity
Args:
graph (nx.Graph):
Returns:
nx.Graph: new_graph
CommandLine:
python3 -m utool.util_graph simplify_graph --show
python2 -m utool.util_graph simplify_graph --show
python2 -c "import networkx as nx; print(nx.__version__)"
python3 -c "import networkx as nx; print(nx.__version__)"
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> graph = nx.DiGraph([('a', 'b'), ('a', 'c'), ('a', 'e'),
>>> ('a', 'd'), ('b', 'd'), ('c', 'e'),
>>> ('d', 'e'), ('c', 'e'), ('c', 'd')])
>>> new_graph = simplify_graph(graph)
>>> result = ut.repr2(list(new_graph.edges()))
>>> #adj_list = sorted(list(nx.generate_adjlist(new_graph)))
>>> #result = ut.repr2(adj_list)
>>> print(result)
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 3), (2, 3), (2, 4), (3, 4)]
['0 1 2 3 4', '1 3 4', '2 4', '3', '4 3']
"""
import utool as ut
nodes = sorted(list(graph.nodes()))
node_lookup = ut.make_index_lookup(nodes)
if graph.is_multigraph():
edges = list(graph.edges(keys=True))
else:
edges = list(graph.edges())
new_nodes = ut.take(node_lookup, nodes)
if graph.is_multigraph():
new_edges = [(node_lookup[e[0]], node_lookup[e[1]], e[2], {}) for e in edges]
else:
new_edges = [(node_lookup[e[0]], node_lookup[e[1]]) for e in edges]
cls = graph.__class__
new_graph = cls()
new_graph.add_nodes_from(new_nodes)
new_graph.add_edges_from(new_edges)
return new_graph |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:subgraph_from_edges; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:G; 5, identifier:edge_list; 6, default_parameter; 6, 7; 6, 8; 7, identifier:ref_back; 8, True; 9, block; 9, 10; 9, 12; 9, 13; 9, 32; 9, 33; 9, 46; 9, 121; 10, expression_statement; 10, 11; 11, comment; 12, comment; 13, expression_statement; 13, 14; 14, assignment; 14, 15; 14, 16; 15, identifier:sub_nodes; 16, call; 16, 17; 16, 18; 17, identifier:list; 18, argument_list; 18, 19; 19, set_comprehension; 19, 20; 19, 21; 19, 24; 20, identifier:y; 21, for_in_clause; 21, 22; 21, 23; 22, identifier:x; 23, identifier:edge_list; 24, for_in_clause; 24, 25; 24, 26; 25, identifier:y; 26, subscript; 26, 27; 26, 28; 27, identifier:x; 28, slice; 28, 29; 28, 30; 28, 31; 29, integer:0; 30, colon; 31, integer:2; 32, comment; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:multi_edge_list; 36, list_comprehension; 36, 37; 36, 43; 37, subscript; 37, 38; 37, 39; 38, identifier:edge; 39, slice; 39, 40; 39, 41; 39, 42; 40, integer:0; 41, colon; 42, integer:3; 43, for_in_clause; 43, 44; 43, 45; 44, identifier:edge; 45, identifier:edge_list; 46, if_statement; 46, 47; 46, 48; 46, 82; 47, identifier:ref_back; 48, block; 48, 49; 48, 58; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:G_sub; 52, call; 52, 53; 52, 56; 53, attribute; 53, 54; 53, 55; 54, identifier:G; 55, identifier:subgraph; 56, argument_list; 56, 57; 57, identifier:sub_nodes; 58, for_statement; 58, 59; 58, 60; 58, 68; 59, identifier:edge; 60, call; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:G_sub; 63, identifier:edges; 64, argument_list; 64, 65; 65, keyword_argument; 65, 66; 65, 67; 66, identifier:keys; 67, True; 68, block; 68, 69; 69, if_statement; 69, 70; 69, 73; 70, comparison_operator:not; 70, 71; 70, 72; 71, identifier:edge; 72, identifier:multi_edge_list; 73, block; 73, 74; 74, expression_statement; 74, 75; 75, call; 75, 76; 75, 79; 76, attribute; 76, 77; 76, 78; 77, identifier:G_sub; 78, identifier:remove_edge; 79, argument_list; 79, 80; 80, list_splat; 80, 81; 81, identifier:edge; 82, else_clause; 82, 83; 83, block; 83, 84; 83, 97; 84, expression_statement; 84, 85; 85, assignment; 85, 86; 85, 87; 86, identifier:G_sub; 87, call; 87, 88; 87, 96; 88, attribute; 88, 89; 88, 95; 89, call; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:G; 92, identifier:subgraph; 93, argument_list; 93, 94; 94, identifier:sub_nodes; 95, identifier:copy; 96, argument_list; 97, for_statement; 97, 98; 97, 99; 97, 107; 98, identifier:edge; 99, call; 99, 100; 99, 103; 100, attribute; 100, 101; 100, 102; 101, identifier:G_sub; 102, identifier:edges; 103, argument_list; 103, 104; 104, keyword_argument; 104, 105; 104, 106; 105, identifier:keys; 106, True; 107, block; 107, 108; 108, if_statement; 108, 109; 108, 112; 109, comparison_operator:not; 109, 110; 109, 111; 110, identifier:edge; 111, identifier:multi_edge_list; 112, block; 112, 113; 113, expression_statement; 113, 114; 114, call; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, identifier:G_sub; 117, identifier:remove_edge; 118, argument_list; 118, 119; 119, list_splat; 119, 120; 120, identifier:edge; 121, return_statement; 121, 122; 122, identifier:G_sub | def subgraph_from_edges(G, edge_list, ref_back=True):
"""
Creates a networkx graph that is a subgraph of G
defined by the list of edges in edge_list.
Requires G to be a networkx MultiGraph or MultiDiGraph
edge_list is a list of edges in either (u,v) or (u,v,d) form
where u and v are nodes comprising an edge,
and d would be a dictionary of edge attributes
ref_back determines whether the created subgraph refers to back
to the original graph and therefore changes to the subgraph's
attributes also affect the original graph, or if it is to create a
new copy of the original graph.
References:
http://stackoverflow.com/questions/16150557/nx-subgraph-from-edges
"""
# TODO: support multi-di-graph
sub_nodes = list({y for x in edge_list for y in x[0:2]})
#edge_list_no_data = [edge[0:2] for edge in edge_list]
multi_edge_list = [edge[0:3] for edge in edge_list]
if ref_back:
G_sub = G.subgraph(sub_nodes)
for edge in G_sub.edges(keys=True):
if edge not in multi_edge_list:
G_sub.remove_edge(*edge)
else:
G_sub = G.subgraph(sub_nodes).copy()
for edge in G_sub.edges(keys=True):
if edge not in multi_edge_list:
G_sub.remove_edge(*edge)
return G_sub |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 30; 2, function_name:bfs_conditional; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 3, 18; 3, 21; 3, 24; 3, 27; 4, identifier:G; 5, identifier:source; 6, default_parameter; 6, 7; 6, 8; 7, identifier:reverse; 8, False; 9, default_parameter; 9, 10; 9, 11; 10, identifier:keys; 11, True; 12, default_parameter; 12, 13; 12, 14; 13, identifier:data; 14, False; 15, default_parameter; 15, 16; 15, 17; 16, identifier:yield_nodes; 17, True; 18, default_parameter; 18, 19; 18, 20; 19, identifier:yield_if; 20, None; 21, default_parameter; 21, 22; 21, 23; 22, identifier:continue_if; 23, None; 24, default_parameter; 24, 25; 24, 26; 25, identifier:visited_nodes; 26, None; 27, default_parameter; 27, 28; 27, 29; 28, identifier:yield_source; 29, False; 30, block; 30, 31; 30, 33; 30, 50; 30, 92; 30, 101; 30, 122; 30, 172; 31, expression_statement; 31, 32; 32, comment; 33, if_statement; 33, 34; 33, 41; 34, boolean_operator:and; 34, 35; 34, 36; 35, identifier:reverse; 36, call; 36, 37; 36, 38; 37, identifier:hasattr; 38, argument_list; 38, 39; 38, 40; 39, identifier:G; 40, string:'reverse'; 41, block; 41, 42; 42, expression_statement; 42, 43; 43, assignment; 43, 44; 43, 45; 44, identifier:G; 45, call; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:G; 48, identifier:reverse; 49, argument_list; 50, if_statement; 50, 51; 50, 58; 50, 73; 51, call; 51, 52; 51, 53; 52, identifier:isinstance; 53, argument_list; 53, 54; 53, 55; 54, identifier:G; 55, attribute; 55, 56; 55, 57; 56, identifier:nx; 57, identifier:Graph; 58, block; 58, 59; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:neighbors; 62, call; 62, 63; 62, 66; 63, attribute; 63, 64; 63, 65; 64, identifier:functools; 65, identifier:partial; 66, argument_list; 66, 67; 66, 70; 67, attribute; 67, 68; 67, 69; 68, identifier:G; 69, identifier:edges; 70, keyword_argument; 70, 71; 70, 72; 71, identifier:data; 72, identifier:data; 73, else_clause; 73, 74; 74, block; 74, 75; 75, expression_statement; 75, 76; 76, assignment; 76, 77; 76, 78; 77, identifier:neighbors; 78, call; 78, 79; 78, 82; 79, attribute; 79, 80; 79, 81; 80, identifier:functools; 81, identifier:partial; 82, argument_list; 82, 83; 82, 86; 82, 89; 83, attribute; 83, 84; 83, 85; 84, identifier:G; 85, identifier:edges; 86, keyword_argument; 86, 87; 86, 88; 87, identifier:keys; 88, identifier:keys; 89, keyword_argument; 89, 90; 89, 91; 90, identifier:data; 91, identifier:data; 92, expression_statement; 92, 93; 93, assignment; 93, 94; 93, 95; 94, identifier:queue; 95, call; 95, 96; 95, 99; 96, attribute; 96, 97; 96, 98; 97, identifier:collections; 98, identifier:deque; 99, argument_list; 99, 100; 100, list:[]; 101, if_statement; 101, 102; 101, 105; 101, 113; 102, comparison_operator:is; 102, 103; 102, 104; 103, identifier:visited_nodes; 104, None; 105, block; 105, 106; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:visited_nodes; 109, call; 109, 110; 109, 111; 110, identifier:set; 111, argument_list; 111, 112; 112, list:[]; 113, else_clause; 113, 114; 114, block; 114, 115; 115, expression_statement; 115, 116; 116, assignment; 116, 117; 116, 118; 117, identifier:visited_nodes; 118, call; 118, 119; 118, 120; 119, identifier:set; 120, argument_list; 120, 121; 121, identifier:visited_nodes; 122, if_statement; 122, 123; 122, 126; 123, comparison_operator:not; 123, 124; 123, 125; 124, identifier:source; 125, identifier:visited_nodes; 126, block; 126, 127; 126, 135; 126, 142; 126, 149; 126, 163; 127, if_statement; 127, 128; 127, 131; 128, boolean_operator:and; 128, 129; 128, 130; 129, identifier:yield_nodes; 130, identifier:yield_source; 131, block; 131, 132; 132, expression_statement; 132, 133; 133, yield; 133, 134; 134, identifier:source; 135, expression_statement; 135, 136; 136, call; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:visited_nodes; 139, identifier:add; 140, argument_list; 140, 141; 141, identifier:source; 142, expression_statement; 142, 143; 143, assignment; 143, 144; 143, 145; 144, identifier:new_edges; 145, call; 145, 146; 145, 147; 146, identifier:neighbors; 147, argument_list; 147, 148; 148, identifier:source; 149, if_statement; 149, 150; 149, 155; 150, call; 150, 151; 150, 152; 151, identifier:isinstance; 152, argument_list; 152, 153; 152, 154; 153, identifier:new_edges; 154, identifier:list; 155, block; 155, 156; 156, expression_statement; 156, 157; 157, assignment; 157, 158; 157, 159; 158, identifier:new_edges; 159, call; 159, 160; 159, 161; 160, identifier:iter; 161, argument_list; 161, 162; 162, identifier:new_edges; 163, expression_statement; 163, 164; 164, call; 164, 165; 164, 168; 165, attribute; 165, 166; 165, 167; 166, identifier:queue; 167, identifier:append; 168, argument_list; 168, 169; 169, tuple; 169, 170; 169, 171; 170, identifier:source; 171, identifier:new_edges; 172, while_statement; 172, 173; 172, 174; 173, identifier:queue; 174, block; 174, 175; 174, 183; 174, 288; 175, expression_statement; 175, 176; 176, assignment; 176, 177; 176, 180; 177, pattern_list; 177, 178; 177, 179; 178, identifier:parent; 179, identifier:edges; 180, subscript; 180, 181; 180, 182; 181, identifier:queue; 182, integer:0; 183, for_statement; 183, 184; 183, 185; 183, 186; 184, identifier:edge; 185, identifier:edges; 186, block; 186, 187; 186, 193; 186, 233; 187, expression_statement; 187, 188; 188, assignment; 188, 189; 188, 190; 189, identifier:child; 190, subscript; 190, 191; 190, 192; 191, identifier:edge; 192, integer:1; 193, if_statement; 193, 194; 193, 195; 193, 216; 194, identifier:yield_nodes; 195, block; 195, 196; 196, if_statement; 196, 197; 196, 200; 197, comparison_operator:not; 197, 198; 197, 199; 198, identifier:child; 199, identifier:visited_nodes; 200, block; 200, 201; 201, if_statement; 201, 202; 201, 212; 202, boolean_operator:or; 202, 203; 202, 206; 203, comparison_operator:is; 203, 204; 203, 205; 204, identifier:yield_if; 205, None; 206, call; 206, 207; 206, 208; 207, identifier:yield_if; 208, argument_list; 208, 209; 208, 210; 208, 211; 209, identifier:G; 210, identifier:child; 211, identifier:edge; 212, block; 212, 213; 213, expression_statement; 213, 214; 214, yield; 214, 215; 215, identifier:child; 216, else_clause; 216, 217; 217, block; 217, 218; 218, if_statement; 218, 219; 218, 229; 219, boolean_operator:or; 219, 220; 219, 223; 220, comparison_operator:is; 220, 221; 220, 222; 221, identifier:yield_if; 222, None; 223, call; 223, 224; 223, 225; 224, identifier:yield_if; 225, argument_list; 225, 226; 225, 227; 225, 228; 226, identifier:G; 227, identifier:child; 228, identifier:edge; 229, block; 229, 230; 230, expression_statement; 230, 231; 231, yield; 231, 232; 232, identifier:edge; 233, if_statement; 233, 234; 233, 237; 234, comparison_operator:not; 234, 235; 234, 236; 235, identifier:child; 236, identifier:visited_nodes; 237, block; 237, 238; 237, 245; 237, 246; 238, expression_statement; 238, 239; 239, call; 239, 240; 239, 243; 240, attribute; 240, 241; 240, 242; 241, identifier:visited_nodes; 242, identifier:add; 243, argument_list; 243, 244; 244, identifier:child; 245, comment; 246, if_statement; 246, 247; 246, 257; 247, boolean_operator:or; 247, 248; 247, 251; 248, comparison_operator:is; 248, 249; 248, 250; 249, identifier:continue_if; 250, None; 251, call; 251, 252; 251, 253; 252, identifier:continue_if; 253, argument_list; 253, 254; 253, 255; 253, 256; 254, identifier:G; 255, identifier:child; 256, identifier:edge; 257, block; 257, 258; 257, 265; 257, 279; 258, expression_statement; 258, 259; 259, assignment; 259, 260; 259, 261; 260, identifier:new_edges; 261, call; 261, 262; 261, 263; 262, identifier:neighbors; 263, argument_list; 263, 264; 264, identifier:child; 265, if_statement; 265, 266; 265, 271; 266, call; 266, 267; 266, 268; 267, identifier:isinstance; 268, argument_list; 268, 269; 268, 270; 269, identifier:new_edges; 270, identifier:list; 271, block; 271, 272; 272, expression_statement; 272, 273; 273, assignment; 273, 274; 273, 275; 274, identifier:new_edges; 275, call; 275, 276; 275, 277; 276, identifier:iter; 277, argument_list; 277, 278; 278, identifier:new_edges; 279, expression_statement; 279, 280; 280, call; 280, 281; 280, 284; 281, attribute; 281, 282; 281, 283; 282, identifier:queue; 283, identifier:append; 284, argument_list; 284, 285; 285, tuple; 285, 286; 285, 287; 286, identifier:child; 287, identifier:new_edges; 288, expression_statement; 288, 289; 289, call; 289, 290; 289, 293; 290, attribute; 290, 291; 290, 292; 291, identifier:queue; 292, identifier:popleft; 293, argument_list | def bfs_conditional(G, source, reverse=False, keys=True, data=False,
yield_nodes=True, yield_if=None,
continue_if=None, visited_nodes=None,
yield_source=False):
"""
Produce edges in a breadth-first-search starting at source, but only return
nodes that satisfiy a condition, and only iterate past a node if it
satisfies a different condition.
conditions are callables that take (G, child, edge) and return true or false
CommandLine:
python -m utool.util_graph bfs_conditional
Example:
>>> # DISABLE_DOCTEST
>>> import networkx as nx
>>> import utool as ut
>>> G = nx.Graph()
>>> G.add_edges_from([(1, 2), (1, 3), (2, 3), (2, 4)])
>>> continue_if = lambda G, child, edge: True
>>> result = list(ut.bfs_conditional(G, 1, yield_nodes=False))
>>> print(result)
[(1, 2), (1, 3), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (4, 2)]
Example:
>>> # ENABLE_DOCTEST
>>> import networkx as nx
>>> import utool as ut
>>> G = nx.Graph()
>>> continue_if = lambda G, child, edge: (child % 2 == 0)
>>> yield_if = lambda G, child, edge: (child % 2 == 1)
>>> G.add_edges_from([(0, 1), (1, 3), (3, 5), (5, 10),
>>> (4, 3), (3, 6),
>>> (0, 2), (2, 4), (4, 6), (6, 10)])
>>> result = list(ut.bfs_conditional(G, 0, continue_if=continue_if,
>>> yield_if=yield_if))
>>> print(result)
[1, 3, 5]
"""
if reverse and hasattr(G, 'reverse'):
G = G.reverse()
if isinstance(G, nx.Graph):
neighbors = functools.partial(G.edges, data=data)
else:
neighbors = functools.partial(G.edges, keys=keys, data=data)
queue = collections.deque([])
if visited_nodes is None:
visited_nodes = set([])
else:
visited_nodes = set(visited_nodes)
if source not in visited_nodes:
if yield_nodes and yield_source:
yield source
visited_nodes.add(source)
new_edges = neighbors(source)
if isinstance(new_edges, list):
new_edges = iter(new_edges)
queue.append((source, new_edges))
while queue:
parent, edges = queue[0]
for edge in edges:
child = edge[1]
if yield_nodes:
if child not in visited_nodes:
if yield_if is None or yield_if(G, child, edge):
yield child
else:
if yield_if is None or yield_if(G, child, edge):
yield edge
if child not in visited_nodes:
visited_nodes.add(child)
# Add new children to queue if the condition is satisfied
if continue_if is None or continue_if(G, child, edge):
new_edges = neighbors(child)
if isinstance(new_edges, list):
new_edges = iter(new_edges)
queue.append((child, new_edges))
queue.popleft() |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:approx_min_num_components; 3, parameters; 3, 4; 3, 5; 4, identifier:nodes; 5, identifier:negative_edges; 6, block; 6, 7; 6, 9; 6, 14; 6, 18; 6, 26; 6, 33; 6, 40; 6, 41; 6, 89; 6, 111; 6, 112; 6, 123; 6, 124; 6, 133; 6, 163; 6, 164; 6, 290; 6, 298; 7, expression_statement; 7, 8; 8, comment; 9, import_statement; 9, 10; 10, aliased_import; 10, 11; 10, 13; 11, dotted_name; 11, 12; 12, identifier:utool; 13, identifier:ut; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:num; 17, integer:0; 18, expression_statement; 18, 19; 19, assignment; 19, 20; 19, 21; 20, identifier:g_neg; 21, call; 21, 22; 21, 25; 22, attribute; 22, 23; 22, 24; 23, identifier:nx; 24, identifier:Graph; 25, argument_list; 26, expression_statement; 26, 27; 27, call; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:g_neg; 30, identifier:add_nodes_from; 31, argument_list; 31, 32; 32, identifier:nodes; 33, expression_statement; 33, 34; 34, call; 34, 35; 34, 38; 35, attribute; 35, 36; 35, 37; 36, identifier:g_neg; 37, identifier:add_edges_from; 38, argument_list; 38, 39; 39, identifier:negative_edges; 40, comment; 41, if_statement; 41, 42; 41, 50; 41, 69; 42, call; 42, 43; 42, 48; 43, attribute; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:nx; 46, identifier:__version__; 47, identifier:startswith; 48, argument_list; 48, 49; 49, string:'2'; 50, block; 50, 51; 51, expression_statement; 51, 52; 52, assignment; 52, 53; 52, 54; 53, identifier:deg0_nodes; 54, list_comprehension; 54, 55; 54, 56; 54, 65; 55, identifier:n; 56, for_in_clause; 56, 57; 56, 60; 57, pattern_list; 57, 58; 57, 59; 58, identifier:n; 59, identifier:d; 60, call; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:g_neg; 63, identifier:degree; 64, argument_list; 65, if_clause; 65, 66; 66, comparison_operator:==; 66, 67; 66, 68; 67, identifier:d; 68, integer:0; 69, else_clause; 69, 70; 70, block; 70, 71; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:deg0_nodes; 74, list_comprehension; 74, 75; 74, 76; 74, 85; 75, identifier:n; 76, for_in_clause; 76, 77; 76, 80; 77, pattern_list; 77, 78; 77, 79; 78, identifier:n; 79, identifier:d; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:g_neg; 83, identifier:degree_iter; 84, argument_list; 85, if_clause; 85, 86; 86, comparison_operator:==; 86, 87; 86, 88; 87, identifier:d; 88, integer:0; 89, for_statement; 89, 90; 89, 93; 89, 99; 90, pattern_list; 90, 91; 90, 92; 91, identifier:u; 92, identifier:v; 93, call; 93, 94; 93, 97; 94, attribute; 94, 95; 94, 96; 95, identifier:ut; 96, identifier:itertwo; 97, argument_list; 97, 98; 98, identifier:deg0_nodes; 99, block; 99, 100; 99, 110; 100, expression_statement; 100, 101; 101, call; 101, 102; 101, 103; 102, identifier:nx_contracted_nodes; 103, argument_list; 103, 104; 103, 105; 103, 106; 103, 107; 104, identifier:g_neg; 105, identifier:v; 106, identifier:u; 107, keyword_argument; 107, 108; 107, 109; 108, identifier:inplace; 109, True; 110, comment; 111, comment; 112, expression_statement; 112, 113; 113, assignment; 113, 114; 113, 115; 114, identifier:unused; 115, call; 115, 116; 115, 117; 116, identifier:list; 117, argument_list; 117, 118; 118, call; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:g_neg; 121, identifier:nodes; 122, argument_list; 123, comment; 124, expression_statement; 124, 125; 125, assignment; 125, 126; 125, 127; 126, identifier:g_pos; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:nx; 130, identifier:complement; 131, argument_list; 131, 132; 132, identifier:g_neg; 133, if_statement; 133, 134; 133, 135; 134, False; 135, block; 135, 136; 135, 143; 135, 154; 135, 161; 136, import_from_statement; 136, 137; 136, 141; 137, dotted_name; 137, 138; 137, 139; 137, 140; 138, identifier:networkx; 139, identifier:algorithms; 140, identifier:approximation; 141, dotted_name; 141, 142; 142, identifier:clique; 143, expression_statement; 143, 144; 144, assignment; 144, 145; 144, 148; 145, pattern_list; 145, 146; 145, 147; 146, identifier:maxiset; 147, identifier:cliques; 148, call; 148, 149; 148, 152; 149, attribute; 149, 150; 149, 151; 150, identifier:clique; 151, identifier:clique_removal; 152, argument_list; 152, 153; 153, identifier:g_pos; 154, expression_statement; 154, 155; 155, assignment; 155, 156; 155, 157; 156, identifier:num; 157, call; 157, 158; 157, 159; 158, identifier:len; 159, argument_list; 159, 160; 160, identifier:cliques; 161, return_statement; 161, 162; 162, identifier:num; 163, comment; 164, while_statement; 164, 165; 164, 171; 164, 172; 165, comparison_operator:>; 165, 166; 165, 170; 166, call; 166, 167; 166, 168; 167, identifier:len; 168, argument_list; 168, 169; 169, identifier:unused; 170, integer:0; 171, comment; 172, block; 172, 173; 172, 177; 172, 178; 172, 179; 172, 183; 172, 189; 172, 196; 172, 208; 172, 218; 173, expression_statement; 173, 174; 174, augmented_assignment:+=; 174, 175; 174, 176; 175, identifier:num; 176, integer:1; 177, comment; 178, comment; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 182; 181, identifier:idx1; 182, integer:0; 183, expression_statement; 183, 184; 184, assignment; 184, 185; 184, 186; 185, identifier:n1; 186, subscript; 186, 187; 186, 188; 187, identifier:unused; 188, identifier:idx1; 189, expression_statement; 189, 190; 190, call; 190, 191; 190, 194; 191, attribute; 191, 192; 191, 193; 192, identifier:unused; 193, identifier:remove; 194, argument_list; 194, 195; 195, identifier:n1; 196, expression_statement; 196, 197; 197, assignment; 197, 198; 197, 199; 198, identifier:neigbs; 199, call; 199, 200; 199, 201; 200, identifier:list; 201, argument_list; 201, 202; 202, call; 202, 203; 202, 206; 203, attribute; 203, 204; 203, 205; 204, identifier:g_pos; 205, identifier:neighbors; 206, argument_list; 206, 207; 207, identifier:n1; 208, expression_statement; 208, 209; 209, assignment; 209, 210; 209, 211; 210, identifier:neigbs; 211, call; 211, 212; 211, 215; 212, attribute; 212, 213; 212, 214; 213, identifier:ut; 214, identifier:isect; 215, argument_list; 215, 216; 215, 217; 216, identifier:neigbs; 217, identifier:unused; 218, while_statement; 218, 219; 218, 225; 218, 226; 218, 227; 219, comparison_operator:>; 219, 220; 219, 224; 220, call; 220, 221; 220, 222; 221, identifier:len; 222, argument_list; 222, 223; 223, identifier:neigbs; 224, integer:0; 225, comment; 226, comment; 227, block; 227, 228; 227, 232; 227, 238; 227, 245; 227, 246; 227, 257; 227, 258; 227, 267; 227, 268; 227, 280; 228, expression_statement; 228, 229; 229, assignment; 229, 230; 229, 231; 230, identifier:idx2; 231, integer:0; 232, expression_statement; 232, 233; 233, assignment; 233, 234; 233, 235; 234, identifier:n2; 235, subscript; 235, 236; 235, 237; 236, identifier:neigbs; 237, identifier:idx2; 238, expression_statement; 238, 239; 239, call; 239, 240; 239, 243; 240, attribute; 240, 241; 240, 242; 241, identifier:unused; 242, identifier:remove; 243, argument_list; 243, 244; 244, identifier:n2; 245, comment; 246, expression_statement; 246, 247; 247, assignment; 247, 248; 247, 249; 248, identifier:g_neg; 249, call; 249, 250; 249, 253; 250, attribute; 250, 251; 250, 252; 251, identifier:nx; 252, identifier:contracted_nodes; 253, argument_list; 253, 254; 253, 255; 253, 256; 254, identifier:g_neg; 255, identifier:n1; 256, identifier:n2; 257, comment; 258, expression_statement; 258, 259; 259, assignment; 259, 260; 259, 261; 260, identifier:g_pos; 261, call; 261, 262; 261, 265; 262, attribute; 262, 263; 262, 264; 263, identifier:nx; 264, identifier:complement; 265, argument_list; 265, 266; 266, identifier:g_neg; 267, comment; 268, expression_statement; 268, 269; 269, assignment; 269, 270; 269, 271; 270, identifier:neigbs; 271, call; 271, 272; 271, 273; 272, identifier:list; 273, argument_list; 273, 274; 274, call; 274, 275; 274, 278; 275, attribute; 275, 276; 275, 277; 276, identifier:g_pos; 277, identifier:neighbors; 278, argument_list; 278, 279; 279, identifier:n1; 280, expression_statement; 280, 281; 281, assignment; 281, 282; 281, 283; 282, identifier:neigbs; 283, call; 283, 284; 283, 287; 284, attribute; 284, 285; 284, 286; 285, identifier:ut; 286, identifier:isect; 287, argument_list; 287, 288; 287, 289; 288, identifier:neigbs; 289, identifier:unused; 290, expression_statement; 290, 291; 291, call; 291, 292; 291, 293; 292, identifier:print; 293, argument_list; 293, 294; 294, binary_operator:%; 294, 295; 294, 296; 295, string:'num = %r'; 296, tuple; 296, 297; 297, identifier:num; 298, return_statement; 298, 299; 299, identifier:num | def approx_min_num_components(nodes, negative_edges):
"""
Find approximate minimum number of connected components possible
Each edge represents that two nodes must be separated
This code doesn't solve the problem. The problem is NP-complete and
reduces to minimum clique cover (MCC). This is only an approximate
solution. Not sure what the approximation ratio is.
CommandLine:
python -m utool.util_graph approx_min_num_components
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> nodes = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> edges = [(1, 2), (2, 3), (3, 1),
>>> (4, 5), (5, 6), (6, 4),
>>> (7, 8), (8, 9), (9, 7),
>>> (1, 4), (4, 7), (7, 1),
>>> ]
>>> g_pos = nx.Graph()
>>> g_pos.add_edges_from(edges)
>>> g_neg = nx.complement(g_pos)
>>> #import plottool as pt
>>> #pt.qt4ensure()
>>> #pt.show_nx(g_pos)
>>> #pt.show_nx(g_neg)
>>> negative_edges = g_neg.edges()
>>> nodes = [1, 2, 3, 4, 5, 6, 7]
>>> negative_edges = [(1, 2), (2, 3), (4, 5)]
>>> result = approx_min_num_components(nodes, negative_edges)
>>> print(result)
2
"""
import utool as ut
num = 0
g_neg = nx.Graph()
g_neg.add_nodes_from(nodes)
g_neg.add_edges_from(negative_edges)
# Collapse all nodes with degree 0
if nx.__version__.startswith('2'):
deg0_nodes = [n for n, d in g_neg.degree() if d == 0]
else:
deg0_nodes = [n for n, d in g_neg.degree_iter() if d == 0]
for u, v in ut.itertwo(deg0_nodes):
nx_contracted_nodes(g_neg, v, u, inplace=True)
# g_neg = nx.contracted_nodes(g_neg, v, u, self_loops=False)
# Initialize unused nodes to be everything
unused = list(g_neg.nodes())
# complement of the graph contains all possible positive edges
g_pos = nx.complement(g_neg)
if False:
from networkx.algorithms.approximation import clique
maxiset, cliques = clique.clique_removal(g_pos)
num = len(cliques)
return num
# Iterate until we have used all nodes
while len(unused) > 0:
# Seed a new "minimum component"
num += 1
# Grab a random unused node n1
#idx1 = np.random.randint(0, len(unused))
idx1 = 0
n1 = unused[idx1]
unused.remove(n1)
neigbs = list(g_pos.neighbors(n1))
neigbs = ut.isect(neigbs, unused)
while len(neigbs) > 0:
# Find node n2, that n1 could be connected to
#idx2 = np.random.randint(0, len(neigbs))
idx2 = 0
n2 = neigbs[idx2]
unused.remove(n2)
# Collapse negative information of n1 and n2
g_neg = nx.contracted_nodes(g_neg, n1, n2)
# Compute new possible positive edges
g_pos = nx.complement(g_neg)
# Iterate until n1 has no more possible connections
neigbs = list(g_pos.neighbors(n1))
neigbs = ut.isect(neigbs, unused)
print('num = %r' % (num,))
return num |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 15; 2, function_name:generate_proteins; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 12; 4, identifier:pepfn; 5, identifier:proteins; 6, identifier:pepheader; 7, identifier:scorecol; 8, identifier:minlog; 9, default_parameter; 9, 10; 9, 11; 10, identifier:higherbetter; 11, True; 12, default_parameter; 12, 13; 12, 14; 13, identifier:protcol; 14, False; 15, block; 15, 16; 15, 18; 15, 22; 15, 29; 15, 39; 15, 75; 15, 142; 16, expression_statement; 16, 17; 17, comment; 18, expression_statement; 18, 19; 19, assignment; 19, 20; 19, 21; 20, identifier:protein_peptides; 21, dictionary; 22, if_statement; 22, 23; 22, 24; 23, identifier:minlog; 24, block; 24, 25; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:higherbetter; 28, False; 29, if_statement; 29, 30; 29, 32; 30, not_operator; 30, 31; 31, identifier:protcol; 32, block; 32, 33; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:protcol; 36, attribute; 36, 37; 36, 38; 37, identifier:peptabledata; 38, identifier:HEADER_MASTERPROTEINS; 39, for_statement; 39, 40; 39, 41; 39, 48; 40, identifier:psm; 41, call; 41, 42; 41, 45; 42, attribute; 42, 43; 42, 44; 43, identifier:reader; 44, identifier:generate_tsv_psms; 45, argument_list; 45, 46; 45, 47; 46, identifier:pepfn; 47, identifier:pepheader; 48, block; 48, 49; 48, 55; 48, 61; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:p_acc; 52, subscript; 52, 53; 52, 54; 53, identifier:psm; 54, identifier:protcol; 55, if_statement; 55, 56; 55, 59; 56, comparison_operator:in; 56, 57; 56, 58; 57, string:';'; 58, identifier:p_acc; 59, block; 59, 60; 60, continue_statement; 61, expression_statement; 61, 62; 62, assignment; 62, 63; 62, 64; 63, identifier:protein_peptides; 64, call; 64, 65; 64, 66; 65, identifier:evaluate_peptide; 66, argument_list; 66, 67; 66, 68; 66, 69; 66, 70; 66, 71; 66, 72; 67, identifier:protein_peptides; 68, identifier:psm; 69, identifier:p_acc; 70, identifier:higherbetter; 71, identifier:scorecol; 72, keyword_argument; 72, 73; 72, 74; 73, identifier:fncol; 74, False; 75, if_statement; 75, 76; 75, 77; 76, identifier:minlog; 77, block; 77, 78; 77, 133; 78, try_statement; 78, 79; 78, 103; 79, block; 79, 80; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:nextbestscore; 83, call; 83, 84; 83, 85; 84, identifier:min; 85, argument_list; 85, 86; 86, list_comprehension; 86, 87; 86, 90; 86, 97; 87, subscript; 87, 88; 87, 89; 88, identifier:pep; 89, string:'score'; 90, for_in_clause; 90, 91; 90, 92; 91, identifier:pep; 92, call; 92, 93; 92, 96; 93, attribute; 93, 94; 93, 95; 94, identifier:protein_peptides; 95, identifier:values; 96, argument_list; 97, if_clause; 97, 98; 98, comparison_operator:>; 98, 99; 98, 102; 99, subscript; 99, 100; 99, 101; 100, identifier:pep; 101, string:'score'; 102, integer:0; 103, except_clause; 103, 104; 103, 105; 104, identifier:ValueError; 105, block; 105, 106; 105, 109; 105, 126; 106, import_statement; 106, 107; 107, dotted_name; 107, 108; 108, identifier:sys; 109, expression_statement; 109, 110; 110, call; 110, 111; 110, 116; 111, attribute; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:sys; 114, identifier:stderr; 115, identifier:write; 116, argument_list; 116, 117; 117, call; 117, 118; 117, 124; 118, attribute; 118, 119; 118, 123; 119, concatenated_string; 119, 120; 119, 121; 119, 122; 120, string:'Cannot find score of type {} which is above 0. '; 121, string:'Only scores above zero can have a -log value. '; 122, string:'Exiting.'; 123, identifier:format; 124, argument_list; 124, 125; 125, identifier:scorecol; 126, expression_statement; 126, 127; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:sys; 130, identifier:exit; 131, argument_list; 131, 132; 132, integer:1; 133, expression_statement; 133, 134; 134, assignment; 134, 135; 134, 136; 135, identifier:nextbestscore; 136, unary_operator:-; 136, 137; 137, call; 137, 138; 137, 139; 138, identifier:log; 139, argument_list; 139, 140; 139, 141; 140, identifier:nextbestscore; 141, integer:10; 142, for_statement; 142, 143; 142, 144; 142, 145; 143, identifier:protein; 144, identifier:proteins; 145, block; 145, 146; 145, 184; 145, 205; 145, 218; 146, try_statement; 146, 147; 146, 158; 147, block; 147, 148; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 151; 150, identifier:peptide; 151, subscript; 151, 152; 151, 153; 152, identifier:protein_peptides; 153, subscript; 153, 154; 153, 155; 154, identifier:protein; 155, attribute; 155, 156; 155, 157; 156, identifier:prottabledata; 157, identifier:HEADER_PROTEIN; 158, except_clause; 158, 159; 158, 160; 159, identifier:KeyError; 160, block; 160, 161; 160, 177; 161, expression_statement; 161, 162; 162, call; 162, 163; 162, 164; 163, identifier:print; 164, argument_list; 164, 165; 165, call; 165, 166; 165, 171; 166, attribute; 166, 167; 166, 170; 167, concatenated_string; 167, 168; 167, 169; 168, string:'WARNING - protein {} not found in peptide '; 169, string:'table'; 170, identifier:format; 171, argument_list; 171, 172; 172, subscript; 172, 173; 172, 174; 173, identifier:protein; 174, attribute; 174, 175; 174, 176; 175, identifier:prottabledata; 176, identifier:HEADER_PROTEIN; 177, expression_statement; 177, 178; 178, assignment; 178, 179; 178, 180; 179, identifier:peptide; 180, dictionary; 180, 181; 181, pair; 181, 182; 181, 183; 182, string:'score'; 183, string:'NA'; 184, if_statement; 184, 185; 184, 192; 185, boolean_operator:and; 185, 186; 185, 187; 186, identifier:minlog; 187, comparison_operator:!=; 187, 188; 187, 191; 188, subscript; 188, 189; 188, 190; 189, identifier:peptide; 190, string:'score'; 191, string:'NA'; 192, block; 192, 193; 193, expression_statement; 193, 194; 194, assignment; 194, 195; 194, 198; 195, subscript; 195, 196; 195, 197; 196, identifier:peptide; 197, string:'score'; 198, call; 198, 199; 198, 200; 199, identifier:log_score; 200, argument_list; 200, 201; 200, 204; 201, subscript; 201, 202; 201, 203; 202, identifier:peptide; 203, string:'score'; 204, identifier:nextbestscore; 205, expression_statement; 205, 206; 206, assignment; 206, 207; 206, 212; 207, subscript; 207, 208; 207, 209; 208, identifier:protein; 209, attribute; 209, 210; 209, 211; 210, identifier:prottabledata; 211, identifier:HEADER_QSCORE; 212, call; 212, 213; 212, 214; 213, identifier:str; 214, argument_list; 214, 215; 215, subscript; 215, 216; 215, 217; 216, identifier:peptide; 217, string:'score'; 218, expression_statement; 218, 219; 219, yield; 219, 220; 220, identifier:protein | def generate_proteins(pepfn, proteins, pepheader, scorecol, minlog,
higherbetter=True, protcol=False):
"""Best peptide for each protein in a table"""
protein_peptides = {}
if minlog:
higherbetter = False
if not protcol:
protcol = peptabledata.HEADER_MASTERPROTEINS
for psm in reader.generate_tsv_psms(pepfn, pepheader):
p_acc = psm[protcol]
if ';' in p_acc:
continue
protein_peptides = evaluate_peptide(protein_peptides, psm, p_acc,
higherbetter, scorecol,
fncol=False)
if minlog:
try:
nextbestscore = min([pep['score'] for pep in
protein_peptides.values()
if pep['score'] > 0])
except ValueError:
import sys
sys.stderr.write('Cannot find score of type {} which is above 0. '
'Only scores above zero can have a -log value. '
'Exiting.'.format(scorecol))
sys.exit(1)
nextbestscore = -log(nextbestscore, 10)
for protein in proteins:
try:
peptide = protein_peptides[protein[prottabledata.HEADER_PROTEIN]]
except KeyError:
print('WARNING - protein {} not found in peptide '
'table'.format(protein[prottabledata.HEADER_PROTEIN]))
peptide = {'score': 'NA'}
if minlog and peptide['score'] != 'NA':
peptide['score'] = log_score(peptide['score'], nextbestscore)
protein[prottabledata.HEADER_QSCORE] = str(
peptide['score'])
yield protein |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 29; 2, function_name:grab_file_url; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 3, 23; 3, 26; 4, identifier:file_url; 5, default_parameter; 5, 6; 5, 7; 6, identifier:appname; 7, string:'utool'; 8, default_parameter; 8, 9; 8, 10; 9, identifier:download_dir; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:delay; 13, None; 14, default_parameter; 14, 15; 14, 16; 15, identifier:spoof; 16, False; 17, default_parameter; 17, 18; 17, 19; 18, identifier:fname; 19, None; 20, default_parameter; 20, 21; 20, 22; 21, identifier:verbose; 22, True; 23, default_parameter; 23, 24; 23, 25; 24, identifier:redownload; 25, False; 26, default_parameter; 26, 27; 26, 28; 27, identifier:check_hash; 28, False; 29, block; 29, 30; 29, 32; 29, 39; 29, 51; 29, 52; 29, 66; 29, 67; 29, 75; 29, 76; 29, 205; 29, 206; 29, 213; 29, 274; 29, 281; 29, 282; 29, 348; 30, expression_statement; 30, 31; 31, comment; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:file_url; 35, call; 35, 36; 35, 37; 36, identifier:clean_dropbox_link; 37, argument_list; 37, 38; 38, identifier:file_url; 39, if_statement; 39, 40; 39, 43; 40, comparison_operator:is; 40, 41; 40, 42; 41, identifier:fname; 42, None; 43, block; 43, 44; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:fname; 47, call; 47, 48; 47, 49; 48, identifier:basename; 49, argument_list; 49, 50; 50, identifier:file_url; 51, comment; 52, if_statement; 52, 53; 52, 56; 53, comparison_operator:is; 53, 54; 53, 55; 54, identifier:download_dir; 55, None; 56, block; 56, 57; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 60; 59, identifier:download_dir; 60, call; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:util_cplat; 63, identifier:get_app_cache_dir; 64, argument_list; 64, 65; 65, identifier:appname; 66, comment; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:fpath; 70, call; 70, 71; 70, 72; 71, identifier:join; 72, argument_list; 72, 73; 72, 74; 73, identifier:download_dir; 74, identifier:fname; 75, comment; 76, if_statement; 76, 77; 76, 78; 77, identifier:check_hash; 78, block; 78, 79; 78, 100; 78, 101; 78, 114; 78, 119; 78, 120; 78, 133; 78, 152; 78, 153; 79, if_statement; 79, 80; 79, 87; 79, 92; 80, call; 80, 81; 80, 82; 81, identifier:isinstance; 82, argument_list; 82, 83; 82, 84; 83, identifier:check_hash; 84, tuple; 84, 85; 84, 86; 85, identifier:list; 86, identifier:tuple; 87, block; 87, 88; 88, expression_statement; 88, 89; 89, assignment; 89, 90; 89, 91; 90, identifier:hash_list; 91, identifier:check_hash; 92, else_clause; 92, 93; 93, block; 93, 94; 93, 99; 94, expression_statement; 94, 95; 95, assignment; 95, 96; 95, 97; 96, identifier:hash_list; 97, list:['md5']; 97, 98; 98, string:'md5'; 99, comment; 100, comment; 101, expression_statement; 101, 102; 102, assignment; 102, 103; 102, 106; 103, pattern_list; 103, 104; 103, 105; 104, identifier:hash_remote; 105, identifier:hash_tag_remote; 106, call; 106, 107; 106, 108; 107, identifier:grab_file_remote_hash; 108, argument_list; 108, 109; 108, 110; 108, 111; 109, identifier:file_url; 110, identifier:hash_list; 111, keyword_argument; 111, 112; 111, 113; 112, identifier:verbose; 113, identifier:verbose; 114, expression_statement; 114, 115; 115, assignment; 115, 116; 115, 117; 116, identifier:hash_list; 117, list:[hash_tag_remote]; 117, 118; 118, identifier:hash_tag_remote; 119, comment; 120, expression_statement; 120, 121; 121, assignment; 121, 122; 121, 125; 122, pattern_list; 122, 123; 122, 124; 123, identifier:hash_local; 124, identifier:hash_tag_local; 125, call; 125, 126; 125, 127; 126, identifier:get_file_local_hash; 127, argument_list; 127, 128; 127, 129; 127, 130; 128, identifier:fpath; 129, identifier:hash_list; 130, keyword_argument; 130, 131; 130, 132; 131, identifier:verbose; 132, identifier:verbose; 133, if_statement; 133, 134; 133, 135; 134, identifier:verbose; 135, block; 135, 136; 135, 144; 136, expression_statement; 136, 137; 137, call; 137, 138; 137, 139; 138, identifier:print; 139, argument_list; 139, 140; 140, binary_operator:%; 140, 141; 140, 142; 141, string:'[utool] Pre Local Hash: %r'; 142, tuple; 142, 143; 143, identifier:hash_local; 144, expression_statement; 144, 145; 145, call; 145, 146; 145, 147; 146, identifier:print; 147, argument_list; 147, 148; 148, binary_operator:%; 148, 149; 148, 150; 149, string:'[utool] Pre Remote Hash: %r'; 150, tuple; 150, 151; 151, identifier:hash_remote; 152, comment; 153, if_statement; 153, 154; 153, 157; 153, 158; 153, 163; 153, 180; 153, 191; 154, comparison_operator:is; 154, 155; 154, 156; 155, identifier:hash_remote; 156, None; 157, comment; 158, block; 158, 159; 159, expression_statement; 159, 160; 160, assignment; 160, 161; 160, 162; 161, identifier:check_hash; 162, False; 163, elif_clause; 163, 164; 163, 167; 164, comparison_operator:is; 164, 165; 164, 166; 165, identifier:hash_local; 166, None; 167, block; 167, 168; 167, 176; 168, if_statement; 168, 169; 168, 170; 169, identifier:verbose; 170, block; 170, 171; 171, expression_statement; 171, 172; 172, call; 172, 173; 172, 174; 173, identifier:print; 174, argument_list; 174, 175; 175, string:'[utool] Remote hash provided but local hash missing, redownloading.'; 176, expression_statement; 176, 177; 177, assignment; 177, 178; 177, 179; 178, identifier:redownload; 179, True; 180, elif_clause; 180, 181; 180, 184; 181, comparison_operator:==; 181, 182; 181, 183; 182, identifier:hash_local; 183, identifier:hash_remote; 184, block; 184, 185; 185, assert_statement; 185, 186; 185, 189; 186, comparison_operator:==; 186, 187; 186, 188; 187, identifier:hash_tag_local; 188, identifier:hash_tag_remote; 189, parenthesized_expression; 189, 190; 190, string:'hash tag disagreement'; 191, else_clause; 191, 192; 192, block; 192, 193; 192, 201; 193, if_statement; 193, 194; 193, 195; 194, identifier:verbose; 195, block; 195, 196; 196, expression_statement; 196, 197; 197, call; 197, 198; 197, 199; 198, identifier:print; 199, argument_list; 199, 200; 200, string:'[utool] Both hashes provided, but they disagree, redownloading.'; 201, expression_statement; 201, 202; 202, assignment; 202, 203; 202, 204; 203, identifier:redownload; 204, True; 205, comment; 206, expression_statement; 206, 207; 207, call; 207, 208; 207, 211; 208, attribute; 208, 209; 208, 210; 209, identifier:util_path; 210, identifier:ensurepath; 211, argument_list; 211, 212; 212, identifier:download_dir; 213, if_statement; 213, 214; 213, 221; 213, 222; 213, 262; 214, boolean_operator:or; 214, 215; 214, 216; 215, identifier:redownload; 216, not_operator; 216, 217; 217, call; 217, 218; 217, 219; 218, identifier:exists; 219, argument_list; 219, 220; 220, identifier:fpath; 221, comment; 222, block; 222, 223; 222, 233; 222, 253; 223, if_statement; 223, 224; 223, 225; 224, identifier:verbose; 225, block; 225, 226; 226, expression_statement; 226, 227; 227, call; 227, 228; 227, 229; 228, identifier:print; 229, argument_list; 229, 230; 230, binary_operator:%; 230, 231; 230, 232; 231, string:'[utool] Downloading file %s'; 232, identifier:fpath; 233, if_statement; 233, 234; 233, 237; 234, comparison_operator:is; 234, 235; 234, 236; 235, identifier:delay; 236, None; 237, block; 237, 238; 237, 246; 238, expression_statement; 238, 239; 239, call; 239, 240; 239, 241; 240, identifier:print; 241, argument_list; 241, 242; 242, binary_operator:%; 242, 243; 242, 244; 243, string:'[utool] delay download by %r seconds'; 244, tuple; 244, 245; 245, identifier:delay; 246, expression_statement; 246, 247; 247, call; 247, 248; 247, 251; 248, attribute; 248, 249; 248, 250; 249, identifier:time; 250, identifier:sleep; 251, argument_list; 251, 252; 252, identifier:delay; 253, expression_statement; 253, 254; 254, call; 254, 255; 254, 256; 255, identifier:download_url; 256, argument_list; 256, 257; 256, 258; 256, 259; 257, identifier:file_url; 258, identifier:fpath; 259, keyword_argument; 259, 260; 259, 261; 260, identifier:spoof; 261, identifier:spoof; 262, else_clause; 262, 263; 263, block; 263, 264; 264, if_statement; 264, 265; 264, 266; 265, identifier:verbose; 266, block; 266, 267; 267, expression_statement; 267, 268; 268, call; 268, 269; 268, 270; 269, identifier:print; 270, argument_list; 270, 271; 271, binary_operator:%; 271, 272; 271, 273; 272, string:'[utool] Already have file %s'; 273, identifier:fpath; 274, expression_statement; 274, 275; 275, call; 275, 276; 275, 279; 276, attribute; 276, 277; 276, 278; 277, identifier:util_path; 278, identifier:assert_exists; 279, argument_list; 279, 280; 280, identifier:fpath; 281, comment; 282, if_statement; 282, 283; 282, 284; 282, 285; 283, identifier:check_hash; 284, comment; 285, block; 285, 286; 285, 294; 285, 313; 285, 314; 285, 327; 285, 338; 285, 343; 286, expression_statement; 286, 287; 287, assignment; 287, 288; 287, 289; 288, identifier:hash_fpath; 289, binary_operator:%; 289, 290; 289, 291; 290, string:'%s.%s'; 291, tuple; 291, 292; 291, 293; 292, identifier:fpath; 293, identifier:hash_tag_remote; 294, with_statement; 294, 295; 294, 305; 295, with_clause; 295, 296; 296, with_item; 296, 297; 297, as_pattern; 297, 298; 297, 303; 298, call; 298, 299; 298, 300; 299, identifier:open; 300, argument_list; 300, 301; 300, 302; 301, identifier:hash_fpath; 302, string:'w'; 303, as_pattern_target; 303, 304; 304, identifier:hash_file; 305, block; 305, 306; 306, expression_statement; 306, 307; 307, call; 307, 308; 307, 311; 308, attribute; 308, 309; 308, 310; 309, identifier:hash_file; 310, identifier:write; 311, argument_list; 311, 312; 312, identifier:hash_remote; 313, comment; 314, expression_statement; 314, 315; 315, assignment; 315, 316; 315, 319; 316, pattern_list; 316, 317; 316, 318; 317, identifier:hash_local; 318, identifier:hash_tag_local; 319, call; 319, 320; 319, 321; 320, identifier:get_file_local_hash; 321, argument_list; 321, 322; 321, 323; 321, 324; 322, identifier:fpath; 323, identifier:hash_list; 324, keyword_argument; 324, 325; 324, 326; 325, identifier:verbose; 326, identifier:verbose; 327, if_statement; 327, 328; 327, 329; 328, identifier:verbose; 329, block; 329, 330; 330, expression_statement; 330, 331; 331, call; 331, 332; 331, 333; 332, identifier:print; 333, argument_list; 333, 334; 334, binary_operator:%; 334, 335; 334, 336; 335, string:'[utool] Post Local Hash: %r'; 336, tuple; 336, 337; 337, identifier:hash_local; 338, assert_statement; 338, 339; 338, 342; 339, comparison_operator:==; 339, 340; 339, 341; 340, identifier:hash_local; 341, identifier:hash_remote; 342, string:'Post-download hash disagreement'; 343, assert_statement; 343, 344; 343, 347; 344, comparison_operator:==; 344, 345; 344, 346; 345, identifier:hash_tag_local; 346, identifier:hash_tag_remote; 347, string:'Post-download hash tag disagreement'; 348, return_statement; 348, 349; 349, identifier:fpath | def grab_file_url(file_url, appname='utool', download_dir=None, delay=None,
spoof=False, fname=None, verbose=True, redownload=False,
check_hash=False):
r"""
Downloads a file and returns the local path of the file.
The resulting file is cached, so multiple calls to this function do not
result in multiple dowloads.
Args:
file_url (str): url to the file
appname (str): (default = 'utool')
download_dir custom directory (None): (default = None)
delay (None): delay time before download (default = None)
spoof (bool): (default = False)
fname (str): custom file name (default = None)
verbose (bool): verbosity flag (default = True)
redownload (bool): if True forces redownload of the file
(default = False)
check_hash (bool or iterable): if True, defaults to checking 4 hashes
(in order): custom, md5, sha1, sha256. These hashes are checked
for remote copies and, if found, will check the local file. You may
also specify a list of hashes to check, for example ['md5', 'sha256']
in the specified order. The first verified hash to be found is used
(default = False)
Returns:
str: fpath - file path string
CommandLine:
python -m utool.util_grabdata --test-grab_file_url:0
python -m utool.util_grabdata --test-grab_file_url:1
Example0:
>>> # ENABLE_DOCTEST
>>> from utool.util_grabdata import * # NOQA
>>> import utool as ut # NOQA
>>> from os.path import basename
>>> ut.exec_funckw(ut.grab_file_url, locals())
>>> file_url = 'http://i.imgur.com/JGrqMnV.png'
>>> redownload = True
>>> fname = 'lena.png'
>>> lena_fpath = ut.grab_file_url(file_url, fname=fname,
>>> redownload=redownload)
>>> result = basename(lena_fpath)
>>> print(result)
lena.png
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_grabdata import * # NOQA
>>> import utool as ut # NOQA
>>> ut.exec_funckw(ut.grab_file_url, locals())
>>> file_url = 'https://lev.cs.rpi.edu/public/models/detect.yolo.12.classes'
>>> fname = 'detect.yolo.12.classes'
>>> check_hash = True
>>> fpath = ut.grab_file_url(file_url, fname=fname, check_hash=check_hash)
"""
file_url = clean_dropbox_link(file_url)
if fname is None:
fname = basename(file_url)
# Download zipfile to
if download_dir is None:
download_dir = util_cplat.get_app_cache_dir(appname)
# Zipfile should unzip to:
fpath = join(download_dir, fname)
# If check hash, get remote hash and assert local copy is the same
if check_hash:
if isinstance(check_hash, (list, tuple)):
hash_list = check_hash
else:
hash_list = ['md5']
# hash_list = ['sha1.custom', 'md5', 'sha1', 'sha256']
# Get expected remote file
hash_remote, hash_tag_remote = grab_file_remote_hash(file_url, hash_list, verbose=verbose)
hash_list = [hash_tag_remote]
# We have a valid candidate hash from remote, check for same hash locally
hash_local, hash_tag_local = get_file_local_hash(fpath, hash_list, verbose=verbose)
if verbose:
print('[utool] Pre Local Hash: %r' % (hash_local, ))
print('[utool] Pre Remote Hash: %r' % (hash_remote, ))
# Check all 4 hash conditions
if hash_remote is None:
# No remote hash provided, turn off post-download hash check
check_hash = False
elif hash_local is None:
if verbose:
print('[utool] Remote hash provided but local hash missing, redownloading.')
redownload = True
elif hash_local == hash_remote:
assert hash_tag_local == hash_tag_remote, ('hash tag disagreement')
else:
if verbose:
print('[utool] Both hashes provided, but they disagree, redownloading.')
redownload = True
# Download
util_path.ensurepath(download_dir)
if redownload or not exists(fpath):
# Download testdata
if verbose:
print('[utool] Downloading file %s' % fpath)
if delay is not None:
print('[utool] delay download by %r seconds' % (delay,))
time.sleep(delay)
download_url(file_url, fpath, spoof=spoof)
else:
if verbose:
print('[utool] Already have file %s' % fpath)
util_path.assert_exists(fpath)
# Post-download local hash verification
if check_hash:
# File has been successfuly downloaded, write remote hash to local hash file
hash_fpath = '%s.%s' % (fpath, hash_tag_remote, )
with open(hash_fpath, 'w') as hash_file:
hash_file.write(hash_remote)
# For sanity check (custom) and file verification (hashing), get local hash again
hash_local, hash_tag_local = get_file_local_hash(fpath, hash_list, verbose=verbose)
if verbose:
print('[utool] Post Local Hash: %r' % (hash_local, ))
assert hash_local == hash_remote, 'Post-download hash disagreement'
assert hash_tag_local == hash_tag_remote, 'Post-download hash tag disagreement'
return fpath |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:get_uniprot_evidence_level; 3, parameters; 3, 4; 4, identifier:header; 5, block; 5, 6; 5, 8; 5, 16; 5, 51; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:header; 11, call; 11, 12; 11, 15; 12, attribute; 12, 13; 12, 14; 13, identifier:header; 14, identifier:split; 15, argument_list; 16, for_statement; 16, 17; 16, 18; 16, 19; 17, identifier:item; 18, identifier:header; 19, block; 19, 20; 19, 29; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:item; 23, call; 23, 24; 23, 27; 24, attribute; 24, 25; 24, 26; 25, identifier:item; 26, identifier:split; 27, argument_list; 27, 28; 28, string:'='; 29, try_statement; 29, 30; 29, 47; 30, block; 30, 31; 31, if_statement; 31, 32; 31, 37; 32, comparison_operator:==; 32, 33; 32, 36; 33, subscript; 33, 34; 33, 35; 34, identifier:item; 35, integer:0; 36, string:'PE'; 37, block; 37, 38; 38, return_statement; 38, 39; 39, binary_operator:-; 39, 40; 39, 41; 40, integer:5; 41, call; 41, 42; 41, 43; 42, identifier:int; 43, argument_list; 43, 44; 44, subscript; 44, 45; 44, 46; 45, identifier:item; 46, integer:1; 47, except_clause; 47, 48; 47, 49; 48, identifier:IndexError; 49, block; 49, 50; 50, continue_statement; 51, return_statement; 51, 52; 52, unary_operator:-; 52, 53; 53, integer:1 | def get_uniprot_evidence_level(header):
"""Returns uniprot protein existence evidence level for a fasta header.
Evidence levels are 1-5, but we return 5 - x since sorting still demands
that higher is better."""
header = header.split()
for item in header:
item = item.split('=')
try:
if item[0] == 'PE':
return 5 - int(item[1])
except IndexError:
continue
return -1 |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:_drain; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:cycles; 7, None; 8, block; 8, 9; 8, 11; 8, 18; 8, 29; 8, 59; 8, 418; 9, expression_statement; 9, 10; 10, comment; 11, expression_statement; 11, 12; 12, call; 12, 13; 12, 16; 13, attribute; 13, 14; 13, 15; 14, identifier:log; 15, identifier:info; 16, argument_list; 16, 17; 17, string:"Now draining..."; 18, if_statement; 18, 19; 18, 21; 19, not_operator; 19, 20; 20, identifier:cycles; 21, block; 21, 22; 22, expression_statement; 22, 23; 23, call; 23, 24; 23, 27; 24, attribute; 24, 25; 24, 26; 25, identifier:log; 26, identifier:info; 27, argument_list; 27, 28; 28, string:"No cycle count, the pipeline may be drained forever."; 29, if_statement; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:self; 32, identifier:calibration; 33, block; 33, 34; 33, 41; 34, expression_statement; 34, 35; 35, call; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:log; 38, identifier:info; 39, argument_list; 39, 40; 40, string:"Setting up the detector calibration."; 41, for_statement; 41, 42; 41, 43; 41, 46; 42, identifier:module; 43, attribute; 43, 44; 43, 45; 44, identifier:self; 45, identifier:modules; 46, block; 46, 47; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:module; 51, identifier:detector; 52, call; 52, 53; 52, 58; 53, attribute; 53, 54; 53, 57; 54, attribute; 54, 55; 54, 56; 55, identifier:self; 56, identifier:calibration; 57, identifier:get_detector; 58, argument_list; 59, try_statement; 59, 60; 59, 408; 60, block; 60, 61; 61, while_statement; 61, 62; 61, 66; 62, not_operator; 62, 63; 63, attribute; 63, 64; 63, 65; 64, identifier:self; 65, identifier:_stop; 66, block; 66, 67; 66, 73; 66, 79; 66, 93; 66, 101; 66, 361; 66, 376; 66, 391; 66, 397; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:cycle_start; 70, call; 70, 71; 70, 72; 71, identifier:timer; 72, argument_list; 73, expression_statement; 73, 74; 74, assignment; 74, 75; 74, 76; 75, identifier:cycle_start_cpu; 76, call; 76, 77; 76, 78; 77, identifier:process_time; 78, argument_list; 79, expression_statement; 79, 80; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:log; 83, identifier:debug; 84, argument_list; 84, 85; 85, call; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, string:"Pumping blob #{0}"; 88, identifier:format; 89, argument_list; 89, 90; 90, attribute; 90, 91; 90, 92; 91, identifier:self; 92, identifier:_cycle_count; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:self; 97, identifier:blob; 98, call; 98, 99; 98, 100; 99, identifier:Blob; 100, argument_list; 101, for_statement; 101, 102; 101, 103; 101, 106; 102, identifier:module; 103, attribute; 103, 104; 103, 105; 104, identifier:self; 105, identifier:modules; 106, block; 106, 107; 106, 129; 106, 173; 106, 205; 106, 245; 106, 259; 106, 265; 106, 271; 106, 278; 106, 323; 107, if_statement; 107, 108; 107, 113; 108, comparison_operator:is; 108, 109; 108, 112; 109, attribute; 109, 110; 109, 111; 110, identifier:self; 111, identifier:blob; 112, None; 113, block; 113, 114; 113, 128; 114, expression_statement; 114, 115; 115, call; 115, 116; 115, 119; 116, attribute; 116, 117; 116, 118; 117, identifier:log; 118, identifier:debug; 119, argument_list; 119, 120; 120, call; 120, 121; 120, 124; 121, attribute; 121, 122; 121, 123; 122, string:"Skipping {0}, due to empty blob."; 123, identifier:format; 124, argument_list; 124, 125; 125, attribute; 125, 126; 125, 127; 126, identifier:module; 127, identifier:name; 128, continue_statement; 129, if_statement; 129, 130; 129, 152; 130, boolean_operator:and; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:module; 133, identifier:only_if; 134, not_operator; 134, 135; 135, call; 135, 136; 135, 141; 136, attribute; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:module; 139, identifier:only_if; 140, identifier:issubset; 141, argument_list; 141, 142; 142, call; 142, 143; 142, 144; 143, identifier:set; 144, argument_list; 144, 145; 145, call; 145, 146; 145, 151; 146, attribute; 146, 147; 146, 150; 147, attribute; 147, 148; 147, 149; 148, identifier:self; 149, identifier:blob; 150, identifier:keys; 151, argument_list; 152, block; 152, 153; 152, 172; 153, expression_statement; 153, 154; 154, call; 154, 155; 154, 158; 155, attribute; 155, 156; 155, 157; 156, identifier:log; 157, identifier:debug; 158, argument_list; 158, 159; 159, call; 159, 160; 159, 165; 160, attribute; 160, 161; 160, 164; 161, concatenated_string; 161, 162; 161, 163; 162, string:"Skipping {0}, due to missing required key"; 163, string:"'{1}'."; 164, identifier:format; 165, argument_list; 165, 166; 165, 169; 166, attribute; 166, 167; 166, 168; 167, identifier:module; 168, identifier:name; 169, attribute; 169, 170; 169, 171; 170, identifier:module; 171, identifier:only_if; 172, continue_statement; 173, if_statement; 173, 174; 173, 186; 174, comparison_operator:!=; 174, 175; 174, 185; 175, binary_operator:%; 175, 176; 175, 182; 176, parenthesized_expression; 176, 177; 177, binary_operator:+; 177, 178; 177, 181; 178, attribute; 178, 179; 178, 180; 179, identifier:self; 180, identifier:_cycle_count; 181, integer:1; 182, attribute; 182, 183; 182, 184; 183, identifier:module; 184, identifier:every; 185, integer:0; 186, block; 186, 187; 186, 204; 187, expression_statement; 187, 188; 188, call; 188, 189; 188, 192; 189, attribute; 189, 190; 189, 191; 190, identifier:log; 191, identifier:debug; 192, argument_list; 192, 193; 193, call; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, string:"Skipping {0} (every {1} iterations)."; 196, identifier:format; 197, argument_list; 197, 198; 197, 201; 198, attribute; 198, 199; 198, 200; 199, identifier:module; 200, identifier:name; 201, attribute; 201, 202; 201, 203; 202, identifier:module; 203, identifier:every; 204, continue_statement; 205, if_statement; 205, 206; 205, 211; 205, 237; 206, comparison_operator:is; 206, 207; 206, 210; 207, attribute; 207, 208; 207, 209; 208, identifier:module; 209, identifier:blob_keys; 210, None; 211, block; 211, 212; 212, expression_statement; 212, 213; 213, assignment; 213, 214; 213, 215; 214, identifier:blob_to_send; 215, call; 215, 216; 215, 217; 216, identifier:Blob; 217, argument_list; 217, 218; 218, dictionary_comprehension; 218, 219; 218, 226; 218, 231; 219, pair; 219, 220; 219, 221; 220, identifier:k; 221, subscript; 221, 222; 221, 225; 222, attribute; 222, 223; 222, 224; 223, identifier:self; 224, identifier:blob; 225, identifier:k; 226, for_in_clause; 226, 227; 226, 228; 227, identifier:k; 228, attribute; 228, 229; 228, 230; 229, identifier:module; 230, identifier:blob_keys; 231, if_clause; 231, 232; 232, comparison_operator:in; 232, 233; 232, 234; 233, identifier:k; 234, attribute; 234, 235; 234, 236; 235, identifier:self; 236, identifier:blob; 237, else_clause; 237, 238; 238, block; 238, 239; 239, expression_statement; 239, 240; 240, assignment; 240, 241; 240, 242; 241, identifier:blob_to_send; 242, attribute; 242, 243; 242, 244; 243, identifier:self; 244, identifier:blob; 245, expression_statement; 245, 246; 246, call; 246, 247; 246, 250; 247, attribute; 247, 248; 247, 249; 248, identifier:log; 249, identifier:debug; 250, argument_list; 250, 251; 251, call; 251, 252; 251, 255; 252, attribute; 252, 253; 252, 254; 253, string:"Processing {0} "; 254, identifier:format; 255, argument_list; 255, 256; 256, attribute; 256, 257; 256, 258; 257, identifier:module; 258, identifier:name; 259, expression_statement; 259, 260; 260, assignment; 260, 261; 260, 262; 261, identifier:start; 262, call; 262, 263; 262, 264; 263, identifier:timer; 264, argument_list; 265, expression_statement; 265, 266; 266, assignment; 266, 267; 266, 268; 267, identifier:start_cpu; 268, call; 268, 269; 268, 270; 269, identifier:process_time; 270, argument_list; 271, expression_statement; 271, 272; 272, assignment; 272, 273; 272, 274; 273, identifier:new_blob; 274, call; 274, 275; 274, 276; 275, identifier:module; 276, argument_list; 276, 277; 277, identifier:blob_to_send; 278, if_statement; 278, 279; 278, 286; 279, boolean_operator:or; 279, 280; 279, 283; 280, attribute; 280, 281; 280, 282; 281, identifier:self; 282, identifier:timeit; 283, attribute; 283, 284; 283, 285; 284, identifier:module; 285, identifier:timeit; 286, block; 286, 287; 286, 305; 287, expression_statement; 287, 288; 288, call; 288, 289; 288, 299; 289, attribute; 289, 290; 289, 297; 289, 298; 290, subscript; 290, 291; 290, 296; 291, subscript; 291, 292; 291, 295; 292, attribute; 292, 293; 292, 294; 293, identifier:self; 294, identifier:_timeit; 295, identifier:module; 296, string:'process'; 297, line_continuation:\; 298, identifier:append; 299, argument_list; 299, 300; 300, binary_operator:-; 300, 301; 300, 304; 301, call; 301, 302; 301, 303; 302, identifier:timer; 303, argument_list; 304, identifier:start; 305, expression_statement; 305, 306; 306, call; 306, 307; 306, 317; 307, attribute; 307, 308; 307, 315; 307, 316; 308, subscript; 308, 309; 308, 314; 309, subscript; 309, 310; 309, 313; 310, attribute; 310, 311; 310, 312; 311, identifier:self; 312, identifier:_timeit; 313, identifier:module; 314, string:'process_cpu'; 315, line_continuation:\; 316, identifier:append; 317, argument_list; 317, 318; 318, binary_operator:-; 318, 319; 318, 322; 319, call; 319, 320; 319, 321; 320, identifier:process_time; 321, argument_list; 322, identifier:start_cpu; 323, if_statement; 323, 324; 323, 329; 323, 353; 324, comparison_operator:is; 324, 325; 324, 328; 325, attribute; 325, 326; 325, 327; 326, identifier:module; 327, identifier:blob_keys; 328, None; 329, block; 329, 330; 330, if_statement; 330, 331; 330, 334; 331, comparison_operator:is; 331, 332; 331, 333; 332, identifier:new_blob; 333, None; 334, block; 334, 335; 335, for_statement; 335, 336; 335, 337; 335, 342; 336, identifier:key; 337, call; 337, 338; 337, 341; 338, attribute; 338, 339; 338, 340; 339, identifier:new_blob; 340, identifier:keys; 341, argument_list; 342, block; 342, 343; 343, expression_statement; 343, 344; 344, assignment; 344, 345; 344, 350; 345, subscript; 345, 346; 345, 349; 346, attribute; 346, 347; 346, 348; 347, identifier:self; 348, identifier:blob; 349, identifier:key; 350, subscript; 350, 351; 350, 352; 351, identifier:new_blob; 352, identifier:key; 353, else_clause; 353, 354; 354, block; 354, 355; 355, expression_statement; 355, 356; 356, assignment; 356, 357; 356, 360; 357, attribute; 357, 358; 357, 359; 358, identifier:self; 359, identifier:blob; 360, identifier:new_blob; 361, expression_statement; 361, 362; 362, call; 362, 363; 362, 370; 363, attribute; 363, 364; 363, 369; 364, subscript; 364, 365; 364, 368; 365, attribute; 365, 366; 365, 367; 366, identifier:self; 367, identifier:_timeit; 368, string:'cycles'; 369, identifier:append; 370, argument_list; 370, 371; 371, binary_operator:-; 371, 372; 371, 375; 372, call; 372, 373; 372, 374; 373, identifier:timer; 374, argument_list; 375, identifier:cycle_start; 376, expression_statement; 376, 377; 377, call; 377, 378; 377, 385; 378, attribute; 378, 379; 378, 384; 379, subscript; 379, 380; 379, 383; 380, attribute; 380, 381; 380, 382; 381, identifier:self; 382, identifier:_timeit; 383, string:'cycles_cpu'; 384, identifier:append; 385, argument_list; 385, 386; 386, binary_operator:-; 386, 387; 386, 390; 387, call; 387, 388; 387, 389; 388, identifier:process_time; 389, argument_list; 390, identifier:cycle_start_cpu; 391, expression_statement; 391, 392; 392, augmented_assignment:+=; 392, 393; 392, 396; 393, attribute; 393, 394; 393, 395; 394, identifier:self; 395, identifier:_cycle_count; 396, integer:1; 397, if_statement; 397, 398; 397, 405; 398, boolean_operator:and; 398, 399; 398, 400; 399, identifier:cycles; 400, comparison_operator:>=; 400, 401; 400, 404; 401, attribute; 401, 402; 401, 403; 402, identifier:self; 403, identifier:_cycle_count; 404, identifier:cycles; 405, block; 405, 406; 406, raise_statement; 406, 407; 407, identifier:StopIteration; 408, except_clause; 408, 409; 408, 410; 409, identifier:StopIteration; 410, block; 410, 411; 411, expression_statement; 411, 412; 412, call; 412, 413; 412, 416; 413, attribute; 413, 414; 413, 415; 414, identifier:log; 415, identifier:info; 416, argument_list; 416, 417; 417, string:"Nothing left to pump through."; 418, return_statement; 418, 419; 419, call; 419, 420; 419, 423; 420, attribute; 420, 421; 420, 422; 421, identifier:self; 422, identifier:finish; 423, argument_list | def _drain(self, cycles=None):
"""Activate the pump and let the flow go.
This will call the process() method on each attached module until
a StopIteration is raised, usually by a pump when it reached the EOF.
A StopIteration is also raised when self.cycles was set and the
number of cycles has reached that limit.
"""
log.info("Now draining...")
if not cycles:
log.info("No cycle count, the pipeline may be drained forever.")
if self.calibration:
log.info("Setting up the detector calibration.")
for module in self.modules:
module.detector = self.calibration.get_detector()
try:
while not self._stop:
cycle_start = timer()
cycle_start_cpu = process_time()
log.debug("Pumping blob #{0}".format(self._cycle_count))
self.blob = Blob()
for module in self.modules:
if self.blob is None:
log.debug(
"Skipping {0}, due to empty blob.".format(
module.name
)
)
continue
if module.only_if and not module.only_if.issubset(set(
self.blob.keys())):
log.debug(
"Skipping {0}, due to missing required key"
"'{1}'.".format(module.name, module.only_if)
)
continue
if (self._cycle_count + 1) % module.every != 0:
log.debug(
"Skipping {0} (every {1} iterations).".format(
module.name, module.every
)
)
continue
if module.blob_keys is not None:
blob_to_send = Blob({
k: self.blob[k]
for k in module.blob_keys
if k in self.blob
})
else:
blob_to_send = self.blob
log.debug("Processing {0} ".format(module.name))
start = timer()
start_cpu = process_time()
new_blob = module(blob_to_send)
if self.timeit or module.timeit:
self._timeit[module]['process'] \
.append(timer() - start)
self._timeit[module]['process_cpu'] \
.append(process_time() - start_cpu)
if module.blob_keys is not None:
if new_blob is not None:
for key in new_blob.keys():
self.blob[key] = new_blob[key]
else:
self.blob = new_blob
self._timeit['cycles'].append(timer() - cycle_start)
self._timeit['cycles_cpu'].append(
process_time() - cycle_start_cpu
)
self._cycle_count += 1
if cycles and self._cycle_count >= cycles:
raise StopIteration
except StopIteration:
log.info("Nothing left to pump through.")
return self.finish() |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:start; 3, parameters; 3, 4; 4, default_parameter; 4, 5; 4, 6; 5, identifier:backdate; 6, None; 7, block; 7, 8; 7, 10; 7, 22; 7, 40; 7, 52; 7, 58; 7, 124; 7, 132; 7, 140; 7, 141; 7, 149; 7, 157; 8, expression_statement; 8, 9; 9, comment; 10, if_statement; 10, 11; 10, 16; 11, attribute; 11, 12; 11, 15; 12, attribute; 12, 13; 12, 14; 13, identifier:f; 14, identifier:s; 15, identifier:cum; 16, block; 16, 17; 17, raise_statement; 17, 18; 18, call; 18, 19; 18, 20; 19, identifier:StartError; 20, argument_list; 20, 21; 21, string:"Already have stamps, can't start again (must reset)."; 22, if_statement; 22, 23; 22, 34; 23, boolean_operator:or; 23, 24; 23, 29; 24, attribute; 24, 25; 24, 28; 25, attribute; 25, 26; 25, 27; 26, identifier:f; 27, identifier:t; 28, identifier:subdvsn_awaiting; 29, attribute; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:f; 32, identifier:t; 33, identifier:par_subdvsn_awaiting; 34, block; 34, 35; 35, raise_statement; 35, 36; 36, call; 36, 37; 36, 38; 37, identifier:StartError; 38, argument_list; 38, 39; 39, string:"Already have subdivisions, can't start again (must reset)."; 40, if_statement; 40, 41; 40, 46; 41, attribute; 41, 42; 41, 45; 42, attribute; 42, 43; 42, 44; 43, identifier:f; 44, identifier:t; 45, identifier:stopped; 46, block; 46, 47; 47, raise_statement; 47, 48; 48, call; 48, 49; 48, 50; 49, identifier:StoppedError; 50, argument_list; 50, 51; 51, string:"Timer already stopped (must open new or reset)."; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:t; 55, call; 55, 56; 55, 57; 56, identifier:timer; 57, argument_list; 58, if_statement; 58, 59; 58, 62; 58, 67; 59, comparison_operator:is; 59, 60; 59, 61; 60, identifier:backdate; 61, None; 62, block; 62, 63; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:t_start; 66, identifier:t; 67, else_clause; 67, 68; 68, block; 68, 69; 68, 83; 68, 96; 68, 106; 68, 120; 69, if_statement; 69, 70; 69, 77; 70, comparison_operator:is; 70, 71; 70, 74; 71, attribute; 71, 72; 71, 73; 72, identifier:f; 73, identifier:t; 74, attribute; 74, 75; 74, 76; 75, identifier:f; 76, identifier:root; 77, block; 77, 78; 78, raise_statement; 78, 79; 79, call; 79, 80; 79, 81; 80, identifier:BackdateError; 81, argument_list; 81, 82; 82, string:"Cannot backdate start of root timer."; 83, if_statement; 83, 84; 83, 90; 84, not_operator; 84, 85; 85, call; 85, 86; 85, 87; 86, identifier:isinstance; 87, argument_list; 87, 88; 87, 89; 88, identifier:backdate; 89, identifier:float; 90, block; 90, 91; 91, raise_statement; 91, 92; 92, call; 92, 93; 92, 94; 93, identifier:TypeError; 94, argument_list; 94, 95; 95, string:"Backdate must be type float."; 96, if_statement; 96, 97; 96, 100; 97, comparison_operator:>; 97, 98; 97, 99; 98, identifier:backdate; 99, identifier:t; 100, block; 100, 101; 101, raise_statement; 101, 102; 102, call; 102, 103; 102, 104; 103, identifier:BackdateError; 104, argument_list; 104, 105; 105, string:"Cannot backdate to future time."; 106, if_statement; 106, 107; 106, 114; 107, comparison_operator:<; 107, 108; 107, 109; 108, identifier:backdate; 109, attribute; 109, 110; 109, 113; 110, attribute; 110, 111; 110, 112; 111, identifier:f; 112, identifier:tm1; 113, identifier:last_t; 114, block; 114, 115; 115, raise_statement; 115, 116; 116, call; 116, 117; 116, 118; 117, identifier:BackdateError; 118, argument_list; 118, 119; 119, string:"Cannot backdate start to time previous to latest stamp in parent timer."; 120, expression_statement; 120, 121; 121, assignment; 121, 122; 121, 123; 122, identifier:t_start; 123, identifier:backdate; 124, expression_statement; 124, 125; 125, assignment; 125, 126; 125, 131; 126, attribute; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:f; 129, identifier:t; 130, identifier:paused; 131, False; 132, expression_statement; 132, 133; 133, assignment; 133, 134; 133, 139; 134, attribute; 134, 135; 134, 138; 135, attribute; 135, 136; 135, 137; 136, identifier:f; 137, identifier:t; 138, identifier:tmp_total; 139, float:0.; 140, comment; 141, expression_statement; 141, 142; 142, assignment; 142, 143; 142, 148; 143, attribute; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:f; 146, identifier:t; 147, identifier:start_t; 148, identifier:t_start; 149, expression_statement; 149, 150; 150, assignment; 150, 151; 150, 156; 151, attribute; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:f; 154, identifier:t; 155, identifier:last_t; 156, identifier:t_start; 157, return_statement; 157, 158; 158, identifier:t | def start(backdate=None):
"""
Mark the start of timing, overwriting the automatic start data written on
import, or the automatic start at the beginning of a subdivision.
Notes:
Backdating: For subdivisions only. Backdate time must be in the past
but more recent than the latest stamp in the parent timer.
Args:
backdate (float, optional): time to use for start instead of current.
Returns:
float: The current time.
Raises:
BackdateError: If given backdate time is out of range or used in root timer.
StartError: If the timer is not in a pristine state (if any stamps or
subdivisions, must reset instead).
StoppedError: If the timer is already stopped (must reset instead).
TypeError: If given backdate value is not type float.
"""
if f.s.cum:
raise StartError("Already have stamps, can't start again (must reset).")
if f.t.subdvsn_awaiting or f.t.par_subdvsn_awaiting:
raise StartError("Already have subdivisions, can't start again (must reset).")
if f.t.stopped:
raise StoppedError("Timer already stopped (must open new or reset).")
t = timer()
if backdate is None:
t_start = t
else:
if f.t is f.root:
raise BackdateError("Cannot backdate start of root timer.")
if not isinstance(backdate, float):
raise TypeError("Backdate must be type float.")
if backdate > t:
raise BackdateError("Cannot backdate to future time.")
if backdate < f.tm1.last_t:
raise BackdateError("Cannot backdate start to time previous to latest stamp in parent timer.")
t_start = backdate
f.t.paused = False
f.t.tmp_total = 0. # (In case previously paused.)
f.t.start_t = t_start
f.t.last_t = t_start
return t |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 26; 2, function_name:stamp; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 3, 23; 4, identifier:name; 5, default_parameter; 5, 6; 5, 7; 6, identifier:backdate; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:unique; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:keep_subdivisions; 13, None; 14, default_parameter; 14, 15; 14, 16; 15, identifier:quick_print; 16, None; 17, default_parameter; 17, 18; 17, 19; 18, identifier:un; 19, None; 20, default_parameter; 20, 21; 20, 22; 21, identifier:ks; 22, None; 23, default_parameter; 23, 24; 23, 25; 24, identifier:qp; 25, None; 26, block; 26, 27; 26, 29; 26, 35; 26, 47; 26, 59; 26, 111; 26, 121; 26, 122; 26, 143; 26, 144; 26, 165; 26, 186; 26, 195; 26, 203; 26, 211; 26, 221; 27, expression_statement; 27, 28; 28, comment; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:t; 32, call; 32, 33; 32, 34; 33, identifier:timer; 34, argument_list; 35, if_statement; 35, 36; 35, 41; 36, attribute; 36, 37; 36, 40; 37, attribute; 37, 38; 37, 39; 38, identifier:f; 39, identifier:t; 40, identifier:stopped; 41, block; 41, 42; 42, raise_statement; 42, 43; 43, call; 43, 44; 43, 45; 44, identifier:StoppedError; 45, argument_list; 45, 46; 46, string:"Cannot stamp stopped timer."; 47, if_statement; 47, 48; 47, 53; 48, attribute; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:f; 51, identifier:t; 52, identifier:paused; 53, block; 53, 54; 54, raise_statement; 54, 55; 55, call; 55, 56; 55, 57; 56, identifier:PausedError; 57, argument_list; 57, 58; 58, string:"Cannot stamp paused timer."; 59, if_statement; 59, 60; 59, 63; 59, 68; 60, comparison_operator:is; 60, 61; 60, 62; 61, identifier:backdate; 62, None; 63, block; 63, 64; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:t_stamp; 67, identifier:t; 68, else_clause; 68, 69; 69, block; 69, 70; 69, 83; 69, 93; 69, 107; 70, if_statement; 70, 71; 70, 77; 71, not_operator; 71, 72; 72, call; 72, 73; 72, 74; 73, identifier:isinstance; 74, argument_list; 74, 75; 74, 76; 75, identifier:backdate; 76, identifier:float; 77, block; 77, 78; 78, raise_statement; 78, 79; 79, call; 79, 80; 79, 81; 80, identifier:TypeError; 81, argument_list; 81, 82; 82, string:"Backdate must be type float."; 83, if_statement; 83, 84; 83, 87; 84, comparison_operator:>; 84, 85; 84, 86; 85, identifier:backdate; 86, identifier:t; 87, block; 87, 88; 88, raise_statement; 88, 89; 89, call; 89, 90; 89, 91; 90, identifier:BackdateError; 91, argument_list; 91, 92; 92, string:"Cannot backdate to future time."; 93, if_statement; 93, 94; 93, 101; 94, comparison_operator:<; 94, 95; 94, 96; 95, identifier:backdate; 96, attribute; 96, 97; 96, 100; 97, attribute; 97, 98; 97, 99; 98, identifier:f; 99, identifier:t; 100, identifier:last_t; 101, block; 101, 102; 102, raise_statement; 102, 103; 103, call; 103, 104; 103, 105; 104, identifier:BackdateError; 105, argument_list; 105, 106; 106, string:"Cannot backdate to time earlier than last stamp."; 107, expression_statement; 107, 108; 108, assignment; 108, 109; 108, 110; 109, identifier:t_stamp; 110, identifier:backdate; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:elapsed; 114, binary_operator:-; 114, 115; 114, 116; 115, identifier:t_stamp; 116, attribute; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:f; 119, identifier:t; 120, identifier:last_t; 121, comment; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:unique; 125, conditional_expression:if; 125, 126; 125, 129; 125, 137; 126, subscript; 126, 127; 126, 128; 127, identifier:SET; 128, string:'UN'; 129, parenthesized_expression; 129, 130; 130, boolean_operator:and; 130, 131; 130, 134; 131, comparison_operator:is; 131, 132; 131, 133; 132, identifier:unique; 133, None; 134, comparison_operator:is; 134, 135; 134, 136; 135, identifier:un; 136, None; 137, call; 137, 138; 137, 139; 138, identifier:bool; 139, argument_list; 139, 140; 140, boolean_operator:or; 140, 141; 140, 142; 141, identifier:unique; 142, identifier:un; 143, comment; 144, expression_statement; 144, 145; 145, assignment; 145, 146; 145, 147; 146, identifier:keep_subdivisions; 147, conditional_expression:if; 147, 148; 147, 151; 147, 159; 148, subscript; 148, 149; 148, 150; 149, identifier:SET; 150, string:'KS'; 151, parenthesized_expression; 151, 152; 152, boolean_operator:and; 152, 153; 152, 156; 153, comparison_operator:is; 153, 154; 153, 155; 154, identifier:keep_subdivisions; 155, None; 156, comparison_operator:is; 156, 157; 156, 158; 157, identifier:ks; 158, None; 159, call; 159, 160; 159, 161; 160, identifier:bool; 161, argument_list; 161, 162; 162, boolean_operator:or; 162, 163; 162, 164; 163, identifier:keep_subdivisions; 164, identifier:ks; 165, expression_statement; 165, 166; 166, assignment; 166, 167; 166, 168; 167, identifier:quick_print; 168, conditional_expression:if; 168, 169; 168, 172; 168, 180; 169, subscript; 169, 170; 169, 171; 170, identifier:SET; 171, string:'QP'; 172, parenthesized_expression; 172, 173; 173, boolean_operator:and; 173, 174; 173, 177; 174, comparison_operator:is; 174, 175; 174, 176; 175, identifier:quick_print; 176, None; 177, comparison_operator:is; 177, 178; 177, 179; 178, identifier:qp; 179, None; 180, call; 180, 181; 180, 182; 181, identifier:bool; 182, argument_list; 182, 183; 183, boolean_operator:or; 183, 184; 183, 185; 184, identifier:quick_print; 185, identifier:qp; 186, expression_statement; 186, 187; 187, call; 187, 188; 187, 189; 188, identifier:_stamp; 189, argument_list; 189, 190; 189, 191; 189, 192; 189, 193; 189, 194; 190, identifier:name; 191, identifier:elapsed; 192, identifier:unique; 193, identifier:keep_subdivisions; 194, identifier:quick_print; 195, expression_statement; 195, 196; 196, assignment; 196, 197; 196, 198; 197, identifier:tmp_self; 198, binary_operator:-; 198, 199; 198, 202; 199, call; 199, 200; 199, 201; 200, identifier:timer; 201, argument_list; 202, identifier:t; 203, expression_statement; 203, 204; 204, augmented_assignment:+=; 204, 205; 204, 210; 205, attribute; 205, 206; 205, 209; 206, attribute; 206, 207; 206, 208; 207, identifier:f; 208, identifier:t; 209, identifier:self_cut; 210, identifier:tmp_self; 211, expression_statement; 211, 212; 212, assignment; 212, 213; 212, 218; 213, attribute; 213, 214; 213, 217; 214, attribute; 214, 215; 214, 216; 215, identifier:f; 216, identifier:t; 217, identifier:last_t; 218, binary_operator:+; 218, 219; 218, 220; 219, identifier:t_stamp; 220, identifier:tmp_self; 221, return_statement; 221, 222; 222, identifier:t | def stamp(name, backdate=None,
unique=None, keep_subdivisions=None, quick_print=None,
un=None, ks=None, qp=None):
"""
Mark the end of a timing interval.
Notes:
If keeping subdivisions, each subdivision currently awaiting
assignment to a stamp (i.e. ended since the last stamp in this level)
will be assigned to this one. Otherwise, all awaiting ones will be
discarded after aggregating their self times into the current timer.
If both long- and short-form are present, they are OR'ed together. If
neither are present, the current global default is used.
Backdating: record a stamp as if it happened at an earlier time.
Backdate time must be in the past but more recent than the latest stamp.
(This can be useful for parallel applications, wherein a sub- process
can return times of interest to the master process.)
Warning:
When backdating, awaiting subdivisions will be assigned as normal, with
no additional checks for validity.
Args:
name (any): The identifier for this interval, processed through str()
backdate (float, optional): time to use for stamp instead of current
unique (bool, optional): enforce uniqueness
keep_subdivisions (bool, optional): keep awaiting subdivisions
quick_print (bool, optional): print elapsed interval time
un (bool, optional): short-form for unique
ks (bool, optional): short-form for keep_subdivisions
qp (bool, optional): short-form for quick_print
Returns:
float: The current time.
Raises:
BackdateError: If the given backdate time is out of range.
PausedError: If the timer is paused.
StoppedError: If the timer is stopped.
TypeError: If the given backdate value is not type float.
"""
t = timer()
if f.t.stopped:
raise StoppedError("Cannot stamp stopped timer.")
if f.t.paused:
raise PausedError("Cannot stamp paused timer.")
if backdate is None:
t_stamp = t
else:
if not isinstance(backdate, float):
raise TypeError("Backdate must be type float.")
if backdate > t:
raise BackdateError("Cannot backdate to future time.")
if backdate < f.t.last_t:
raise BackdateError("Cannot backdate to time earlier than last stamp.")
t_stamp = backdate
elapsed = t_stamp - f.t.last_t
# Logic: default unless either arg used. if both args used, 'or' them.
unique = SET['UN'] if (unique is None and un is None) else bool(unique or un) # bool(None) becomes False
keep_subdivisions = SET['KS'] if (keep_subdivisions is None and ks is None) else bool(keep_subdivisions or ks)
quick_print = SET['QP'] if (quick_print is None and qp is None) else bool(quick_print or qp)
_stamp(name, elapsed, unique, keep_subdivisions, quick_print)
tmp_self = timer() - t
f.t.self_cut += tmp_self
f.t.last_t = t_stamp + tmp_self
return t |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 28; 2, function_name:stop; 3, parameters; 3, 4; 3, 7; 3, 10; 3, 13; 3, 16; 3, 19; 3, 22; 3, 25; 4, default_parameter; 4, 5; 4, 6; 5, identifier:name; 6, None; 7, default_parameter; 7, 8; 7, 9; 8, identifier:backdate; 9, None; 10, default_parameter; 10, 11; 10, 12; 11, identifier:unique; 12, None; 13, default_parameter; 13, 14; 13, 15; 14, identifier:keep_subdivisions; 15, None; 16, default_parameter; 16, 17; 16, 18; 17, identifier:quick_print; 18, None; 19, default_parameter; 19, 20; 19, 21; 20, identifier:un; 21, None; 22, default_parameter; 22, 23; 22, 24; 23, identifier:ks; 24, None; 25, default_parameter; 25, 26; 25, 27; 26, identifier:qp; 27, None; 28, block; 28, 29; 28, 31; 28, 37; 28, 49; 28, 115; 28, 136; 28, 137; 28, 158; 28, 179; 28, 225; 28, 263; 28, 285; 28, 297; 28, 309; 28, 310; 28, 316; 28, 324; 28, 346; 29, expression_statement; 29, 30; 30, comment; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:t; 34, call; 34, 35; 34, 36; 35, identifier:timer; 36, argument_list; 37, if_statement; 37, 38; 37, 43; 38, attribute; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:f; 41, identifier:t; 42, identifier:stopped; 43, block; 43, 44; 44, raise_statement; 44, 45; 45, call; 45, 46; 45, 47; 46, identifier:StoppedError; 47, argument_list; 47, 48; 48, string:"Timer already stopped."; 49, if_statement; 49, 50; 49, 53; 49, 58; 50, comparison_operator:is; 50, 51; 50, 52; 51, identifier:backdate; 52, None; 53, block; 53, 54; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 57; 56, identifier:t_stop; 57, identifier:t; 58, else_clause; 58, 59; 59, block; 59, 60; 59, 74; 59, 87; 59, 97; 59, 111; 60, if_statement; 60, 61; 60, 68; 61, comparison_operator:is; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:f; 64, identifier:t; 65, attribute; 65, 66; 65, 67; 66, identifier:f; 67, identifier:root; 68, block; 68, 69; 69, raise_statement; 69, 70; 70, call; 70, 71; 70, 72; 71, identifier:BackdateError; 72, argument_list; 72, 73; 73, string:"Cannot backdate stop of root timer."; 74, if_statement; 74, 75; 74, 81; 75, not_operator; 75, 76; 76, call; 76, 77; 76, 78; 77, identifier:isinstance; 78, argument_list; 78, 79; 78, 80; 79, identifier:backdate; 80, identifier:float; 81, block; 81, 82; 82, raise_statement; 82, 83; 83, call; 83, 84; 83, 85; 84, identifier:TypeError; 85, argument_list; 85, 86; 86, string:"Backdate must be type float."; 87, if_statement; 87, 88; 87, 91; 88, comparison_operator:>; 88, 89; 88, 90; 89, identifier:backdate; 90, identifier:t; 91, block; 91, 92; 92, raise_statement; 92, 93; 93, call; 93, 94; 93, 95; 94, identifier:BackdateError; 95, argument_list; 95, 96; 96, string:"Cannot backdate to future time."; 97, if_statement; 97, 98; 97, 105; 98, comparison_operator:<; 98, 99; 98, 100; 99, identifier:backdate; 100, attribute; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:f; 103, identifier:t; 104, identifier:last_t; 105, block; 105, 106; 106, raise_statement; 106, 107; 107, call; 107, 108; 107, 109; 108, identifier:BackdateError; 109, argument_list; 109, 110; 110, string:"Cannot backdate to time earlier than last stamp."; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:t_stop; 114, identifier:backdate; 115, expression_statement; 115, 116; 116, assignment; 116, 117; 116, 118; 117, identifier:unique; 118, conditional_expression:if; 118, 119; 118, 122; 118, 130; 119, subscript; 119, 120; 119, 121; 120, identifier:SET; 121, string:'UN'; 122, parenthesized_expression; 122, 123; 123, boolean_operator:and; 123, 124; 123, 127; 124, comparison_operator:is; 124, 125; 124, 126; 125, identifier:unique; 126, None; 127, comparison_operator:is; 127, 128; 127, 129; 128, identifier:un; 129, None; 130, call; 130, 131; 130, 132; 131, identifier:bool; 132, argument_list; 132, 133; 133, boolean_operator:or; 133, 134; 133, 135; 134, identifier:unique; 135, identifier:un; 136, comment; 137, expression_statement; 137, 138; 138, assignment; 138, 139; 138, 140; 139, identifier:keep_subdivisions; 140, conditional_expression:if; 140, 141; 140, 144; 140, 152; 141, subscript; 141, 142; 141, 143; 142, identifier:SET; 143, string:'KS'; 144, parenthesized_expression; 144, 145; 145, boolean_operator:and; 145, 146; 145, 149; 146, comparison_operator:is; 146, 147; 146, 148; 147, identifier:keep_subdivisions; 148, None; 149, comparison_operator:is; 149, 150; 149, 151; 150, identifier:ks; 151, None; 152, call; 152, 153; 152, 154; 153, identifier:bool; 154, argument_list; 154, 155; 155, boolean_operator:or; 155, 156; 155, 157; 156, identifier:keep_subdivisions; 157, identifier:ks; 158, expression_statement; 158, 159; 159, assignment; 159, 160; 159, 161; 160, identifier:quick_print; 161, conditional_expression:if; 161, 162; 161, 165; 161, 173; 162, subscript; 162, 163; 162, 164; 163, identifier:SET; 164, string:'QP'; 165, parenthesized_expression; 165, 166; 166, boolean_operator:and; 166, 167; 166, 170; 167, comparison_operator:is; 167, 168; 167, 169; 168, identifier:quick_print; 169, None; 170, comparison_operator:is; 170, 171; 170, 172; 171, identifier:qp; 172, None; 173, call; 173, 174; 173, 175; 174, identifier:bool; 175, argument_list; 175, 176; 176, boolean_operator:or; 176, 177; 176, 178; 177, identifier:quick_print; 178, identifier:qp; 179, if_statement; 179, 180; 179, 183; 179, 215; 180, comparison_operator:is; 180, 181; 180, 182; 181, identifier:name; 182, None; 183, block; 183, 184; 183, 196; 183, 206; 184, if_statement; 184, 185; 184, 190; 185, attribute; 185, 186; 185, 189; 186, attribute; 186, 187; 186, 188; 187, identifier:f; 188, identifier:t; 189, identifier:paused; 190, block; 190, 191; 191, raise_statement; 191, 192; 192, call; 192, 193; 192, 194; 193, identifier:PausedError; 194, argument_list; 194, 195; 195, string:"Cannot stamp paused timer."; 196, expression_statement; 196, 197; 197, assignment; 197, 198; 197, 199; 198, identifier:elapsed; 199, binary_operator:-; 199, 200; 199, 201; 200, identifier:t_stop; 201, attribute; 201, 202; 201, 205; 202, attribute; 202, 203; 202, 204; 203, identifier:f; 204, identifier:t; 205, identifier:last_t; 206, expression_statement; 206, 207; 207, call; 207, 208; 207, 209; 208, identifier:_stamp; 209, argument_list; 209, 210; 209, 211; 209, 212; 209, 213; 209, 214; 210, identifier:name; 211, identifier:elapsed; 212, identifier:unique; 213, identifier:keep_subdivisions; 214, identifier:quick_print; 215, else_clause; 215, 216; 216, block; 216, 217; 217, expression_statement; 217, 218; 218, call; 218, 219; 218, 222; 219, attribute; 219, 220; 219, 221; 220, identifier:times_priv; 221, identifier:assign_subdivisions; 222, argument_list; 222, 223; 222, 224; 223, identifier:UNASGN; 224, identifier:keep_subdivisions; 225, for_statement; 225, 226; 225, 227; 225, 232; 226, identifier:s; 227, attribute; 227, 228; 227, 231; 228, attribute; 228, 229; 228, 230; 229, identifier:f; 230, identifier:t; 231, identifier:rgstr_stamps; 232, block; 232, 233; 233, if_statement; 233, 234; 233, 241; 234, comparison_operator:not; 234, 235; 234, 236; 235, identifier:s; 236, attribute; 236, 237; 236, 240; 237, attribute; 237, 238; 237, 239; 238, identifier:f; 239, identifier:s; 240, identifier:cum; 241, block; 241, 242; 241, 252; 242, expression_statement; 242, 243; 243, assignment; 243, 244; 243, 251; 244, subscript; 244, 245; 244, 250; 245, attribute; 245, 246; 245, 249; 246, attribute; 246, 247; 246, 248; 247, identifier:f; 248, identifier:s; 249, identifier:cum; 250, identifier:s; 251, float:0.; 252, expression_statement; 252, 253; 253, call; 253, 254; 253, 261; 254, attribute; 254, 255; 254, 260; 255, attribute; 255, 256; 255, 259; 256, attribute; 256, 257; 256, 258; 257, identifier:f; 258, identifier:s; 259, identifier:order; 260, identifier:append; 261, argument_list; 261, 262; 262, identifier:s; 263, if_statement; 263, 264; 263, 270; 264, not_operator; 264, 265; 265, attribute; 265, 266; 265, 269; 266, attribute; 266, 267; 266, 268; 267, identifier:f; 268, identifier:t; 269, identifier:paused; 270, block; 270, 271; 271, expression_statement; 271, 272; 272, augmented_assignment:+=; 272, 273; 272, 278; 273, attribute; 273, 274; 273, 277; 274, attribute; 274, 275; 274, 276; 275, identifier:f; 276, identifier:t; 277, identifier:tmp_total; 278, binary_operator:-; 278, 279; 278, 280; 279, identifier:t_stop; 280, attribute; 280, 281; 280, 284; 281, attribute; 281, 282; 281, 283; 282, identifier:f; 283, identifier:t; 284, identifier:start_t; 285, expression_statement; 285, 286; 286, augmented_assignment:-=; 286, 287; 286, 292; 287, attribute; 287, 288; 287, 291; 288, attribute; 288, 289; 288, 290; 289, identifier:f; 290, identifier:t; 291, identifier:tmp_total; 292, attribute; 292, 293; 292, 296; 293, attribute; 293, 294; 293, 295; 294, identifier:f; 295, identifier:t; 296, identifier:self_cut; 297, expression_statement; 297, 298; 298, augmented_assignment:+=; 298, 299; 298, 304; 299, attribute; 299, 300; 299, 303; 300, attribute; 300, 301; 300, 302; 301, identifier:f; 302, identifier:t; 303, identifier:self_cut; 304, binary_operator:-; 304, 305; 304, 308; 305, call; 305, 306; 305, 307; 306, identifier:timer; 307, argument_list; 308, identifier:t; 309, comment; 310, expression_statement; 310, 311; 311, call; 311, 312; 311, 315; 312, attribute; 312, 313; 312, 314; 313, identifier:times_priv; 314, identifier:dump_times; 315, argument_list; 316, expression_statement; 316, 317; 317, assignment; 317, 318; 317, 323; 318, attribute; 318, 319; 318, 322; 319, attribute; 319, 320; 319, 321; 320, identifier:f; 321, identifier:t; 322, identifier:stopped; 323, True; 324, if_statement; 324, 325; 324, 326; 325, identifier:quick_print; 326, block; 326, 327; 327, expression_statement; 327, 328; 328, call; 328, 329; 328, 330; 329, identifier:print; 330, argument_list; 330, 331; 331, call; 331, 332; 331, 335; 332, attribute; 332, 333; 332, 334; 333, string:"({}) Total: {:.4f}"; 334, identifier:format; 335, argument_list; 335, 336; 335, 341; 336, attribute; 336, 337; 336, 340; 337, attribute; 337, 338; 337, 339; 338, identifier:f; 339, identifier:t; 340, identifier:name; 341, attribute; 341, 342; 341, 345; 342, attribute; 342, 343; 342, 344; 343, identifier:f; 344, identifier:r; 345, identifier:total; 346, return_statement; 346, 347; 347, identifier:t | def stop(name=None, backdate=None,
unique=None, keep_subdivisions=None, quick_print=None,
un=None, ks=None, qp=None):
"""
Mark the end of timing. Optionally performs a stamp, hence accepts the
same arguments.
Notes:
If keeping subdivisions and not calling a stamp, any awaiting subdivisions
will be assigned to a special 'UNASSIGNED' position to indicate that they
are not properly accounted for in the hierarchy (these can happen at
different places and may be combined inadvertently).
Backdating: For subdivisions only. Backdate time must be in the past
but more recent than the latest stamp.
Args:
name (any, optional): If used, passed to a call to stamp()
backdate (float, optional): time to use for stop instead of current
unique (bool, optional): see stamp()
keep_subdivisions (bool, optional): keep awaiting subdivisions
quick_print (bool, optional): boolean, print total time
un (bool, optional): see stamp()
ks (bool, optional): see stamp()
qp (bool, optional): see stamp()
Returns:
float: The current time.
Raises:
BackdateError: If given backdate is out of range, or if used in root timer.
PausedError: If attempting stamp in paused timer.
StoppedError: If timer already stopped.
TypeError: If given backdate value is not type float.
"""
t = timer()
if f.t.stopped:
raise StoppedError("Timer already stopped.")
if backdate is None:
t_stop = t
else:
if f.t is f.root:
raise BackdateError("Cannot backdate stop of root timer.")
if not isinstance(backdate, float):
raise TypeError("Backdate must be type float.")
if backdate > t:
raise BackdateError("Cannot backdate to future time.")
if backdate < f.t.last_t:
raise BackdateError("Cannot backdate to time earlier than last stamp.")
t_stop = backdate
unique = SET['UN'] if (unique is None and un is None) else bool(unique or un) # bool(None) becomes False
keep_subdivisions = SET['KS'] if (keep_subdivisions is None and ks is None) else bool(keep_subdivisions or ks)
quick_print = SET['QP'] if (quick_print is None and qp is None) else bool(quick_print or qp)
if name is not None:
if f.t.paused:
raise PausedError("Cannot stamp paused timer.")
elapsed = t_stop - f.t.last_t
_stamp(name, elapsed, unique, keep_subdivisions, quick_print)
else:
times_priv.assign_subdivisions(UNASGN, keep_subdivisions)
for s in f.t.rgstr_stamps:
if s not in f.s.cum:
f.s.cum[s] = 0.
f.s.order.append(s)
if not f.t.paused:
f.t.tmp_total += t_stop - f.t.start_t
f.t.tmp_total -= f.t.self_cut
f.t.self_cut += timer() - t # AFTER subtraction from tmp_total, before dump
times_priv.dump_times()
f.t.stopped = True
if quick_print:
print("({}) Total: {:.4f}".format(f.t.name, f.r.total))
return t |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 38; 2, function_name:timed_loop; 3, parameters; 3, 4; 3, 7; 3, 10; 3, 15; 3, 18; 3, 23; 3, 28; 3, 33; 4, default_parameter; 4, 5; 4, 6; 5, identifier:name; 6, None; 7, default_parameter; 7, 8; 7, 9; 8, identifier:rgstr_stamps; 9, None; 10, default_parameter; 10, 11; 10, 12; 11, identifier:save_itrs; 12, subscript; 12, 13; 12, 14; 13, identifier:SET; 14, string:'SI'; 15, default_parameter; 15, 16; 15, 17; 16, identifier:loop_end_stamp; 17, None; 18, default_parameter; 18, 19; 18, 20; 19, identifier:end_stamp_unique; 20, subscript; 20, 21; 20, 22; 21, identifier:SET; 22, string:'UN'; 23, default_parameter; 23, 24; 23, 25; 24, identifier:keep_prev_subdivisions; 25, subscript; 25, 26; 25, 27; 26, identifier:SET; 27, string:'KS'; 28, default_parameter; 28, 29; 28, 30; 29, identifier:keep_end_subdivisions; 30, subscript; 30, 31; 30, 32; 31, identifier:SET; 32, string:'KS'; 33, default_parameter; 33, 34; 33, 35; 34, identifier:quick_print; 35, subscript; 35, 36; 35, 37; 36, identifier:SET; 37, string:'QP'; 38, block; 38, 39; 38, 41; 39, expression_statement; 39, 40; 40, comment; 41, return_statement; 41, 42; 42, call; 42, 43; 42, 44; 43, identifier:TimedLoop; 44, argument_list; 44, 45; 44, 48; 44, 51; 44, 54; 44, 57; 44, 60; 44, 63; 45, keyword_argument; 45, 46; 45, 47; 46, identifier:name; 47, identifier:name; 48, keyword_argument; 48, 49; 48, 50; 49, identifier:rgstr_stamps; 50, identifier:rgstr_stamps; 51, keyword_argument; 51, 52; 51, 53; 52, identifier:save_itrs; 53, identifier:save_itrs; 54, keyword_argument; 54, 55; 54, 56; 55, identifier:loop_end_stamp; 56, identifier:loop_end_stamp; 57, keyword_argument; 57, 58; 57, 59; 58, identifier:end_stamp_unique; 59, identifier:end_stamp_unique; 60, keyword_argument; 60, 61; 60, 62; 61, identifier:keep_prev_subdivisions; 62, identifier:keep_prev_subdivisions; 63, keyword_argument; 63, 64; 63, 65; 64, identifier:keep_end_subdivisions; 65, identifier:keep_end_subdivisions | def timed_loop(name=None,
rgstr_stamps=None,
save_itrs=SET['SI'],
loop_end_stamp=None,
end_stamp_unique=SET['UN'],
keep_prev_subdivisions=SET['KS'],
keep_end_subdivisions=SET['KS'],
quick_print=SET['QP']):
"""
Instantiate a TimedLoop object for measuring loop iteration timing data.
Can be used with either for or while loops.
Example::
loop = timed_loop()
while x > 0: # or for x in <iterable>:
next(loop) # or loop.next()
<body of loop, with gtimer stamps>
loop.exit()
Notes:
Can be used as a context manager around the loop, without requiring
separate call to exit(). Redundant calls to exit() do no harm. Loop
functionality is implemented in the next() or __next__() methods.
Each instance can only be used once, so for an inner loop, this function
must be called within the outer loop.
Any awaiting subdivisions kept at entrance to a loop section will go to
the 'UNASSIGNED' position to indicate that they are not properly accounted
for in the hierarchy. Likewise for any awaiting subdivisions kept at the
end of loop iterations without a named stamp.
Args:
name (any, optional): Identifier (makes the loop a subdivision), passed
through str().
rgstr_stamps (list, tuple, optional): Identifiers, see subdivision().
save_itrs (bool, optional): see subdivision().
loop_end_stamp (any, optional): Identifier, automatic stamp at end of
every iteration.
end_stamp_unique (bool, optional): see stamp().
keep_prev_subdivisions (bool, optional): Keep awaiting subdivisions on
entering loop.
keep_end_subdivisions (bool, optional): Keep awaiting subdivisions at
end of iterations.
quick_print (bool, optional): Named loop only, print at end of each iteration.
Returns:
TimedLoop: Custom gtimer object for measuring loops.
"""
return TimedLoop(name=name,
rgstr_stamps=rgstr_stamps,
save_itrs=save_itrs,
loop_end_stamp=loop_end_stamp,
end_stamp_unique=end_stamp_unique,
keep_prev_subdivisions=keep_prev_subdivisions,
keep_end_subdivisions=keep_end_subdivisions) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 39; 2, function_name:timed_for; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 16; 3, 19; 3, 24; 3, 29; 3, 34; 4, identifier:iterable; 5, default_parameter; 5, 6; 5, 7; 6, identifier:name; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:rgstr_stamps; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:save_itrs; 13, subscript; 13, 14; 13, 15; 14, identifier:SET; 15, string:'SI'; 16, default_parameter; 16, 17; 16, 18; 17, identifier:loop_end_stamp; 18, None; 19, default_parameter; 19, 20; 19, 21; 20, identifier:end_stamp_unique; 21, subscript; 21, 22; 21, 23; 22, identifier:SET; 23, string:'UN'; 24, default_parameter; 24, 25; 24, 26; 25, identifier:keep_prev_subdivisions; 26, subscript; 26, 27; 26, 28; 27, identifier:SET; 28, string:'KS'; 29, default_parameter; 29, 30; 29, 31; 30, identifier:keep_end_subdivisions; 31, subscript; 31, 32; 31, 33; 32, identifier:SET; 33, string:'KS'; 34, default_parameter; 34, 35; 34, 36; 35, identifier:quick_print; 36, subscript; 36, 37; 36, 38; 37, identifier:SET; 38, string:'QP'; 39, block; 39, 40; 39, 42; 40, expression_statement; 40, 41; 41, comment; 42, return_statement; 42, 43; 43, call; 43, 44; 43, 45; 44, identifier:TimedFor; 45, argument_list; 45, 46; 45, 47; 45, 50; 45, 53; 45, 56; 45, 59; 45, 62; 45, 65; 46, identifier:iterable; 47, keyword_argument; 47, 48; 47, 49; 48, identifier:name; 49, identifier:name; 50, keyword_argument; 50, 51; 50, 52; 51, identifier:rgstr_stamps; 52, identifier:rgstr_stamps; 53, keyword_argument; 53, 54; 53, 55; 54, identifier:save_itrs; 55, identifier:save_itrs; 56, keyword_argument; 56, 57; 56, 58; 57, identifier:loop_end_stamp; 58, identifier:loop_end_stamp; 59, keyword_argument; 59, 60; 59, 61; 60, identifier:end_stamp_unique; 61, identifier:end_stamp_unique; 62, keyword_argument; 62, 63; 62, 64; 63, identifier:keep_prev_subdivisions; 64, identifier:keep_prev_subdivisions; 65, keyword_argument; 65, 66; 65, 67; 66, identifier:keep_end_subdivisions; 67, identifier:keep_end_subdivisions | def timed_for(iterable,
name=None,
rgstr_stamps=None,
save_itrs=SET['SI'],
loop_end_stamp=None,
end_stamp_unique=SET['UN'],
keep_prev_subdivisions=SET['KS'],
keep_end_subdivisions=SET['KS'],
quick_print=SET['QP']):
"""
Instantiate a TimedLoop object for measuring for loop iteration timing data.
Can be used only on for loops.
Example::
for i in gtimer.timed_for(iterable, ..):
<body of loop with gtimer stamps>
Notes:
Can be used as a context manager around the loop. When breaking out of
the loop, requires usage either as a context manager or with a reference
to the object on which to call the exit() method after leaving the loop
body. Redundant calls to exit() do no harm. Loop functionality is
implemented in the __iter__() method.
Each instance can only be used once, so for an inner loop, this function
must be called within the outer loop.
Any awaiting subdivisions kept at entrance to a loop section will go to
the 'UNASSIGNED' position to indicate that they are not properly accounted
for in the hierarchy. Likewise for any awaiting subdivisions kept at the
end of loop iterations without a named stamp.
Args:
iterable: Same as provided to regular 'for' command.
name (any, optional): Identifier (makes the loop a subdivision), passed
through str().
rgstr_stamps (list,tuple, optional): Identifiers, see subdivision().
save_itrs (bool, optional): see subdivision().
loop_end_stamp (any, optional): Identifier, automatic stamp at end of
every iteration, passed through str().
end_stamp_unique (bool, optional): see stamp().
keep_prev_subdivisions (bool, optional): Keep awaiting subdivisions on
entering loop.
keep_end_subdivisions (bool, optional): Keep awaiting subdivisions at
end of iterations.
quick_print (bool, optional): Named loop only, print at end of each iteration.
Returns:
TimedFor: Custom gtimer object for measuring for loops.
"""
return TimedFor(iterable,
name=name,
rgstr_stamps=rgstr_stamps,
save_itrs=save_itrs,
loop_end_stamp=loop_end_stamp,
end_stamp_unique=end_stamp_unique,
keep_prev_subdivisions=keep_prev_subdivisions,
keep_end_subdivisions=keep_end_subdivisions) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:format_gmeta; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:data; 5, default_parameter; 5, 6; 5, 7; 6, identifier:acl; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:identifier; 10, None; 11, block; 11, 12; 11, 14; 12, expression_statement; 12, 13; 13, comment; 14, if_statement; 14, 15; 14, 20; 14, 129; 14, 159; 15, call; 15, 16; 15, 17; 16, identifier:isinstance; 17, argument_list; 17, 18; 17, 19; 18, identifier:data; 19, identifier:dict; 20, block; 20, 21; 20, 35; 20, 47; 20, 48; 20, 52; 20, 112; 21, if_statement; 21, 22; 21, 29; 22, boolean_operator:or; 22, 23; 22, 26; 23, comparison_operator:is; 23, 24; 23, 25; 24, identifier:acl; 25, None; 26, comparison_operator:is; 26, 27; 26, 28; 27, identifier:identifier; 28, None; 29, block; 29, 30; 30, raise_statement; 30, 31; 31, call; 31, 32; 31, 33; 32, identifier:ValueError; 33, argument_list; 33, 34; 34, string:"acl and identifier are required when formatting a GMetaEntry."; 35, if_statement; 35, 36; 35, 41; 36, call; 36, 37; 36, 38; 37, identifier:isinstance; 38, argument_list; 38, 39; 38, 40; 39, identifier:acl; 40, identifier:str; 41, block; 41, 42; 42, expression_statement; 42, 43; 43, assignment; 43, 44; 43, 45; 44, identifier:acl; 45, list:[acl]; 45, 46; 46, identifier:acl; 47, comment; 48, expression_statement; 48, 49; 49, assignment; 49, 50; 49, 51; 50, identifier:prefixed_acl; 51, list:[]; 52, for_statement; 52, 53; 52, 54; 52, 55; 52, 56; 52, 57; 52, 58; 53, identifier:uuid; 54, identifier:acl; 55, comment; 56, comment; 57, comment; 58, block; 58, 59; 59, if_statement; 59, 60; 59, 75; 59, 102; 59, 103; 60, boolean_operator:and; 60, 61; 60, 64; 61, comparison_operator:!=; 61, 62; 61, 63; 62, identifier:uuid; 63, string:"public"; 64, not_operator; 64, 65; 65, call; 65, 66; 65, 73; 66, attribute; 66, 67; 66, 72; 67, call; 67, 68; 67, 71; 68, attribute; 68, 69; 68, 70; 69, identifier:uuid; 70, identifier:lower; 71, argument_list; 72, identifier:startswith; 73, argument_list; 73, 74; 74, string:"urn:"; 75, block; 75, 76; 75, 89; 76, expression_statement; 76, 77; 77, call; 77, 78; 77, 81; 78, attribute; 78, 79; 78, 80; 79, identifier:prefixed_acl; 80, identifier:append; 81, argument_list; 81, 82; 82, binary_operator:+; 82, 83; 82, 84; 83, string:"urn:globus:auth:identity:"; 84, call; 84, 85; 84, 88; 85, attribute; 85, 86; 85, 87; 86, identifier:uuid; 87, identifier:lower; 88, argument_list; 89, expression_statement; 89, 90; 90, call; 90, 91; 90, 94; 91, attribute; 91, 92; 91, 93; 92, identifier:prefixed_acl; 93, identifier:append; 94, argument_list; 94, 95; 95, binary_operator:+; 95, 96; 95, 97; 96, string:"urn:globus:groups:id:"; 97, call; 97, 98; 97, 101; 98, attribute; 98, 99; 98, 100; 99, identifier:uuid; 100, identifier:lower; 101, argument_list; 102, comment; 103, else_clause; 103, 104; 104, block; 104, 105; 105, expression_statement; 105, 106; 106, call; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, identifier:prefixed_acl; 109, identifier:append; 110, argument_list; 110, 111; 111, identifier:uuid; 112, return_statement; 112, 113; 113, dictionary; 113, 114; 113, 117; 113, 120; 113, 123; 113, 126; 114, pair; 114, 115; 114, 116; 115, string:"@datatype"; 116, string:"GMetaEntry"; 117, pair; 117, 118; 117, 119; 118, string:"@version"; 119, string:"2016-11-09"; 120, pair; 120, 121; 120, 122; 121, string:"subject"; 122, identifier:identifier; 123, pair; 123, 124; 123, 125; 124, string:"visible_to"; 125, identifier:prefixed_acl; 126, pair; 126, 127; 126, 128; 127, string:"content"; 128, identifier:data; 129, elif_clause; 129, 130; 129, 135; 130, call; 130, 131; 130, 132; 131, identifier:isinstance; 132, argument_list; 132, 133; 132, 134; 133, identifier:data; 134, identifier:list; 135, block; 135, 136; 136, return_statement; 136, 137; 137, dictionary; 137, 138; 137, 141; 137, 144; 137, 147; 138, pair; 138, 139; 138, 140; 139, string:"@datatype"; 140, string:"GIngest"; 141, pair; 141, 142; 141, 143; 142, string:"@version"; 143, string:"2016-11-09"; 144, pair; 144, 145; 144, 146; 145, string:"ingest_type"; 146, string:"GMetaList"; 147, pair; 147, 148; 147, 149; 148, string:"ingest_data"; 149, dictionary; 149, 150; 149, 153; 149, 156; 150, pair; 150, 151; 150, 152; 151, string:"@datatype"; 152, string:"GMetaList"; 153, pair; 153, 154; 153, 155; 154, string:"@version"; 155, string:"2016-11-09"; 156, pair; 156, 157; 156, 158; 157, string:"gmeta"; 158, identifier:data; 159, else_clause; 159, 160; 160, block; 160, 161; 161, raise_statement; 161, 162; 162, call; 162, 163; 162, 164; 163, identifier:TypeError; 164, argument_list; 164, 165; 165, binary_operator:+; 165, 166; 165, 175; 166, binary_operator:+; 166, 167; 166, 168; 167, string:"Cannot format '"; 168, call; 168, 169; 168, 170; 169, identifier:str; 170, argument_list; 170, 171; 171, call; 171, 172; 171, 173; 172, identifier:type; 173, argument_list; 173, 174; 174, identifier:data; 175, string:"' into GMeta." | def format_gmeta(data, acl=None, identifier=None):
"""Format input into GMeta format, suitable for ingesting into Globus Search.
Formats a dictionary into a GMetaEntry.
Formats a list of GMetaEntry into a GMetaList inside a GMetaIngest.
**Example usage**::
glist = []
for document in all_my_documents:
gmeta_entry = format_gmeta(document, ["public"], document["id"])
glist.append(gmeta_entry)
ingest_ready_document = format_gmeta(glist)
Arguments:
data (dict or list): The data to be formatted.
If data is a dict, arguments ``acl`` and ``identifier`` are required.
If data is a list, it must consist of GMetaEntry documents.
acl (list of str): The list of Globus UUIDs allowed to view the document,
or the special value ``["public"]`` to allow anyone access.
Required if data is a dict. Ignored if data is a list.
Will be formatted into URNs if required.
identifier (str): A unique identifier for this document. If this value is not unique,
ingests into Globus Search may merge entries.
Required is data is a dict. Ignored if data is a list.
Returns:
dict (if ``data`` is ``dict``): The data as a GMetaEntry.
dict (if ``data`` is ``list``): The data as a GMetaIngest.
"""
if isinstance(data, dict):
if acl is None or identifier is None:
raise ValueError("acl and identifier are required when formatting a GMetaEntry.")
if isinstance(acl, str):
acl = [acl]
# "Correctly" format ACL entries into URNs
prefixed_acl = []
for uuid in acl:
# If entry is not special value "public" and is not a URN, make URN
# It is not known what the type of UUID is, so use both
# This solution is known to be hacky
if uuid != "public" and not uuid.lower().startswith("urn:"):
prefixed_acl.append("urn:globus:auth:identity:"+uuid.lower())
prefixed_acl.append("urn:globus:groups:id:"+uuid.lower())
# Otherwise, no modification
else:
prefixed_acl.append(uuid)
return {
"@datatype": "GMetaEntry",
"@version": "2016-11-09",
"subject": identifier,
"visible_to": prefixed_acl,
"content": data
}
elif isinstance(data, list):
return {
"@datatype": "GIngest",
"@version": "2016-11-09",
"ingest_type": "GMetaList",
"ingest_data": {
"@datatype": "GMetaList",
"@version": "2016-11-09",
"gmeta": data
}
}
else:
raise TypeError("Cannot format '" + str(type(data)) + "' into GMeta.") |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 12; 2, function_name:insensitive_comparison; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 4, identifier:item1; 5, identifier:item2; 6, default_parameter; 6, 7; 6, 8; 7, identifier:type_insensitive; 8, False; 9, default_parameter; 9, 10; 9, 11; 10, identifier:string_insensitive; 11, False; 12, block; 12, 13; 12, 15; 12, 16; 12, 32; 12, 33; 13, expression_statement; 13, 14; 14, comment; 15, comment; 16, if_statement; 16, 17; 16, 29; 17, boolean_operator:and; 17, 18; 17, 20; 18, not_operator; 18, 19; 19, identifier:type_insensitive; 20, comparison_operator:!=; 20, 21; 20, 25; 21, call; 21, 22; 21, 23; 22, identifier:type; 23, argument_list; 23, 24; 24, identifier:item1; 25, call; 25, 26; 25, 27; 26, identifier:type; 27, argument_list; 27, 28; 28, identifier:item2; 29, block; 29, 30; 30, return_statement; 30, 31; 31, False; 32, comment; 33, if_statement; 33, 34; 33, 39; 33, 40; 33, 129; 33, 130; 33, 250; 33, 251; 33, 432; 33, 433; 34, call; 34, 35; 34, 36; 35, identifier:isinstance; 36, argument_list; 36, 37; 36, 38; 37, identifier:item1; 38, identifier:Mapping; 39, comment; 40, block; 40, 41; 40, 51; 40, 52; 40, 66; 40, 67; 40, 94; 40, 95; 40, 96; 40, 126; 40, 127; 41, if_statement; 41, 42; 41, 48; 42, not_operator; 42, 43; 43, call; 43, 44; 43, 45; 44, identifier:isinstance; 45, argument_list; 45, 46; 45, 47; 46, identifier:item2; 47, identifier:Mapping; 48, block; 48, 49; 49, return_statement; 49, 50; 50, False; 51, comment; 52, if_statement; 52, 53; 52, 63; 53, not_operator; 53, 54; 54, comparison_operator:==; 54, 55; 54, 59; 55, call; 55, 56; 55, 57; 56, identifier:len; 57, argument_list; 57, 58; 58, identifier:item1; 59, call; 59, 60; 59, 61; 60, identifier:len; 61, argument_list; 61, 62; 62, identifier:item2; 63, block; 63, 64; 64, return_statement; 64, 65; 65, False; 66, comment; 67, if_statement; 67, 68; 67, 91; 68, not_operator; 68, 69; 69, call; 69, 70; 69, 71; 70, identifier:insensitive_comparison; 71, argument_list; 71, 72; 71, 80; 71, 88; 72, call; 72, 73; 72, 74; 73, identifier:list; 74, argument_list; 74, 75; 75, call; 75, 76; 75, 79; 76, attribute; 76, 77; 76, 78; 77, identifier:item1; 78, identifier:keys; 79, argument_list; 80, call; 80, 81; 80, 82; 81, identifier:list; 82, argument_list; 82, 83; 83, call; 83, 84; 83, 87; 84, attribute; 84, 85; 84, 86; 85, identifier:item2; 86, identifier:keys; 87, argument_list; 88, keyword_argument; 88, 89; 88, 90; 89, identifier:type_insensitive; 90, True; 91, block; 91, 92; 92, return_statement; 92, 93; 93, False; 94, comment; 95, comment; 96, for_statement; 96, 97; 96, 100; 96, 105; 97, pattern_list; 97, 98; 97, 99; 98, identifier:key; 99, identifier:val; 100, call; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:item1; 103, identifier:items; 104, argument_list; 105, block; 105, 106; 106, if_statement; 106, 107; 106, 123; 107, not_operator; 107, 108; 108, call; 108, 109; 108, 110; 109, identifier:insensitive_comparison; 110, argument_list; 110, 111; 110, 114; 110, 117; 110, 120; 111, subscript; 111, 112; 111, 113; 112, identifier:item1; 113, identifier:key; 114, subscript; 114, 115; 114, 116; 115, identifier:item2; 116, identifier:key; 117, keyword_argument; 117, 118; 117, 119; 118, identifier:type_insensitive; 119, identifier:type_insensitive; 120, keyword_argument; 120, 121; 120, 122; 121, identifier:string_insensitive; 122, identifier:string_insensitive; 123, block; 123, 124; 124, return_statement; 124, 125; 125, False; 126, comment; 127, return_statement; 127, 128; 128, True; 129, comment; 130, elif_clause; 130, 131; 130, 136; 130, 137; 131, call; 131, 132; 131, 133; 132, identifier:isinstance; 133, argument_list; 133, 134; 133, 135; 134, identifier:item1; 135, identifier:str; 136, comment; 137, block; 137, 138; 137, 148; 137, 149; 137, 166; 137, 167; 138, if_statement; 138, 139; 138, 145; 139, not_operator; 139, 140; 140, call; 140, 141; 140, 142; 141, identifier:isinstance; 142, argument_list; 142, 143; 142, 144; 143, identifier:item2; 144, identifier:str; 145, block; 145, 146; 146, return_statement; 146, 147; 147, False; 148, comment; 149, if_statement; 149, 150; 149, 163; 150, boolean_operator:and; 150, 151; 150, 161; 151, not_operator; 151, 152; 152, comparison_operator:==; 152, 153; 152, 157; 153, call; 153, 154; 153, 155; 154, identifier:len; 155, argument_list; 155, 156; 156, identifier:item1; 157, call; 157, 158; 157, 159; 158, identifier:len; 159, argument_list; 159, 160; 160, identifier:item2; 161, not_operator; 161, 162; 162, identifier:string_insensitive; 163, block; 163, 164; 164, return_statement; 164, 165; 165, False; 166, comment; 167, if_statement; 167, 168; 167, 169; 167, 170; 167, 243; 167, 244; 168, identifier:string_insensitive; 169, comment; 170, block; 170, 171; 170, 191; 170, 192; 170, 211; 170, 230; 170, 231; 171, if_statement; 171, 172; 171, 178; 172, comparison_operator:<=; 172, 173; 172, 177; 173, call; 173, 174; 173, 175; 174, identifier:len; 175, argument_list; 175, 176; 176, identifier:item1; 177, integer:1; 178, block; 178, 179; 179, return_statement; 179, 180; 180, comparison_operator:==; 180, 181; 180, 186; 181, call; 181, 182; 181, 185; 182, attribute; 182, 183; 182, 184; 183, identifier:item1; 184, identifier:lower; 185, argument_list; 186, call; 186, 187; 186, 190; 187, attribute; 187, 188; 187, 189; 188, identifier:item2; 189, identifier:lower; 190, argument_list; 191, comment; 192, expression_statement; 192, 193; 193, assignment; 193, 194; 193, 195; 194, identifier:item1_list; 195, list_comprehension; 195, 196; 195, 197; 195, 204; 196, identifier:c; 197, for_in_clause; 197, 198; 197, 199; 198, identifier:c; 199, call; 199, 200; 199, 203; 200, attribute; 200, 201; 200, 202; 201, identifier:item1; 202, identifier:lower; 203, argument_list; 204, if_clause; 204, 205; 205, not_operator; 205, 206; 206, call; 206, 207; 206, 210; 207, attribute; 207, 208; 207, 209; 208, identifier:c; 209, identifier:isspace; 210, argument_list; 211, expression_statement; 211, 212; 212, assignment; 212, 213; 212, 214; 213, identifier:item2_list; 214, list_comprehension; 214, 215; 214, 216; 214, 223; 215, identifier:c; 216, for_in_clause; 216, 217; 216, 218; 217, identifier:c; 218, call; 218, 219; 218, 222; 219, attribute; 219, 220; 219, 221; 220, identifier:item2; 221, identifier:lower; 222, argument_list; 223, if_clause; 223, 224; 224, not_operator; 224, 225; 225, call; 225, 226; 225, 229; 226, attribute; 226, 227; 226, 228; 227, identifier:c; 228, identifier:isspace; 229, argument_list; 230, comment; 231, return_statement; 231, 232; 232, call; 232, 233; 232, 234; 233, identifier:insensitive_comparison; 234, argument_list; 234, 235; 234, 236; 234, 237; 234, 240; 235, identifier:item1_list; 236, identifier:item2_list; 237, keyword_argument; 237, 238; 237, 239; 238, identifier:type_insensitive; 239, identifier:type_insensitive; 240, keyword_argument; 240, 241; 240, 242; 241, identifier:string_insensitive; 242, identifier:string_insensitive; 243, comment; 244, else_clause; 244, 245; 245, block; 245, 246; 246, return_statement; 246, 247; 247, comparison_operator:==; 247, 248; 247, 249; 248, identifier:item1; 249, identifier:item2; 250, comment; 251, elif_clause; 251, 252; 251, 263; 251, 264; 252, boolean_operator:and; 252, 253; 252, 258; 253, call; 253, 254; 253, 255; 254, identifier:isinstance; 255, argument_list; 255, 256; 255, 257; 256, identifier:item1; 257, identifier:Container; 258, call; 258, 259; 258, 260; 259, identifier:isinstance; 260, argument_list; 260, 261; 260, 262; 261, identifier:item1; 262, identifier:Iterable; 263, comment; 264, block; 264, 265; 264, 282; 264, 283; 264, 297; 264, 298; 264, 299; 264, 300; 264, 301; 264, 302; 264, 312; 264, 316; 264, 372; 264, 373; 265, if_statement; 265, 266; 265, 279; 266, boolean_operator:or; 266, 267; 266, 273; 267, not_operator; 267, 268; 268, call; 268, 269; 268, 270; 269, identifier:isinstance; 270, argument_list; 270, 271; 270, 272; 271, identifier:item2; 272, identifier:Container; 273, not_operator; 273, 274; 274, call; 274, 275; 274, 276; 275, identifier:isinstance; 276, argument_list; 276, 277; 276, 278; 277, identifier:item2; 278, identifier:Iterable; 279, block; 279, 280; 280, return_statement; 280, 281; 281, False; 282, comment; 283, if_statement; 283, 284; 283, 294; 284, not_operator; 284, 285; 285, comparison_operator:==; 285, 286; 285, 290; 286, call; 286, 287; 286, 288; 287, identifier:len; 288, argument_list; 288, 289; 289, identifier:item1; 290, call; 290, 291; 290, 292; 291, identifier:len; 292, argument_list; 292, 293; 293, identifier:item2; 294, block; 294, 295; 295, return_statement; 295, 296; 296, False; 297, comment; 298, comment; 299, comment; 300, comment; 301, comment; 302, expression_statement; 302, 303; 303, assignment; 303, 304; 303, 305; 304, identifier:item2_copy; 305, call; 305, 306; 305, 307; 306, identifier:list; 307, argument_list; 307, 308; 308, call; 308, 309; 308, 310; 309, identifier:deepcopy; 310, argument_list; 310, 311; 311, identifier:item2; 312, expression_statement; 312, 313; 313, assignment; 313, 314; 313, 315; 314, identifier:remove_failed; 315, False; 316, for_statement; 316, 317; 316, 318; 316, 319; 317, identifier:elem; 318, identifier:item1; 319, block; 319, 320; 319, 324; 319, 325; 319, 365; 319, 366; 320, expression_statement; 320, 321; 321, assignment; 321, 322; 321, 323; 322, identifier:matched; 323, False; 324, comment; 325, for_statement; 325, 326; 325, 327; 325, 328; 325, 329; 326, identifier:candidate; 327, identifier:item2; 328, comment; 329, block; 329, 330; 330, if_statement; 330, 331; 330, 342; 331, call; 331, 332; 331, 333; 332, identifier:insensitive_comparison; 333, argument_list; 333, 334; 333, 335; 333, 336; 333, 339; 334, identifier:elem; 335, identifier:candidate; 336, keyword_argument; 336, 337; 336, 338; 337, identifier:type_insensitive; 338, identifier:type_insensitive; 339, keyword_argument; 339, 340; 339, 341; 340, identifier:string_insensitive; 341, identifier:string_insensitive; 342, block; 342, 343; 342, 347; 342, 364; 343, expression_statement; 343, 344; 344, assignment; 344, 345; 344, 346; 345, identifier:matched; 346, True; 347, try_statement; 347, 348; 347, 356; 348, block; 348, 349; 349, expression_statement; 349, 350; 350, call; 350, 351; 350, 354; 351, attribute; 351, 352; 351, 353; 352, identifier:item2_copy; 353, identifier:remove; 354, argument_list; 354, 355; 355, identifier:candidate; 356, except_clause; 356, 357; 356, 358; 356, 359; 357, identifier:ValueError; 358, comment; 359, block; 359, 360; 360, expression_statement; 360, 361; 361, assignment; 361, 362; 361, 363; 362, identifier:remove_failed; 363, True; 364, break_statement; 365, comment; 366, if_statement; 366, 367; 366, 369; 367, not_operator; 367, 368; 368, identifier:matched; 369, block; 369, 370; 370, return_statement; 370, 371; 371, False; 372, comment; 373, if_statement; 373, 374; 373, 376; 373, 377; 373, 378; 373, 386; 373, 387; 373, 388; 374, not_operator; 374, 375; 375, identifier:remove_failed; 376, comment; 377, comment; 378, block; 378, 379; 379, return_statement; 379, 380; 380, comparison_operator:==; 380, 381; 380, 385; 381, call; 381, 382; 381, 383; 382, identifier:len; 383, argument_list; 383, 384; 384, identifier:item2_copy; 385, integer:0; 386, comment; 387, comment; 388, else_clause; 388, 389; 389, block; 389, 390; 389, 429; 389, 430; 390, for_statement; 390, 391; 390, 392; 390, 393; 391, identifier:elem; 392, identifier:item2; 393, block; 393, 394; 393, 398; 393, 399; 393, 422; 393, 423; 394, expression_statement; 394, 395; 395, assignment; 395, 396; 395, 397; 396, identifier:matched; 397, False; 398, comment; 399, for_statement; 399, 400; 399, 401; 399, 402; 399, 403; 400, identifier:candidate; 401, identifier:item1; 402, comment; 403, block; 403, 404; 404, if_statement; 404, 405; 404, 416; 405, call; 405, 406; 405, 407; 406, identifier:insensitive_comparison; 407, argument_list; 407, 408; 407, 409; 407, 410; 407, 413; 408, identifier:elem; 409, identifier:candidate; 410, keyword_argument; 410, 411; 410, 412; 411, identifier:type_insensitive; 412, identifier:type_insensitive; 413, keyword_argument; 413, 414; 413, 415; 414, identifier:string_insensitive; 415, identifier:string_insensitive; 416, block; 416, 417; 416, 421; 417, expression_statement; 417, 418; 418, assignment; 418, 419; 418, 420; 419, identifier:matched; 420, True; 421, break_statement; 422, comment; 423, if_statement; 423, 424; 423, 426; 424, not_operator; 424, 425; 425, identifier:matched; 426, block; 426, 427; 427, return_statement; 427, 428; 428, False; 429, comment; 430, return_statement; 430, 431; 431, True; 432, comment; 433, else_clause; 433, 434; 434, block; 434, 435; 435, return_statement; 435, 436; 436, comparison_operator:==; 436, 437; 436, 438; 437, identifier:item1; 438, identifier:item2 | def insensitive_comparison(item1, item2, type_insensitive=False, string_insensitive=False):
"""Compare two items without regard to order.
The following rules are used to determine equivalence:
* Items that are not of the same type can be equivalent only when ``type_insensitive=True``.
* Mapping objects are equal iff the keys in each item exist in both items and have
the same value (with the same ``insensitive_comparison``).
* Other containers except for strings are equal iff every element in each item exists
in both items (duplicate items must be present the same number of times).
* Containers must be ``Iterable`` to be compared in this way.
* Non-containers are equivalent if the equality operator returns ``True``.
* Strings are treated as non-containers when ``string_insensitive=False``,
and are treated as containers when ``string_insensitive=True``. When treated as
containers, each (case-insensitive) character is treated as an element and
whitespace is ignored.
* If the items are in different categories above, they are never equivalent,
even when ``type_insensitive=True``.
Arguments:
item1 (any): The first item to compare.
item2 (any): The second item to compare.
type_insensitive (bool): When ``True``, items of a different type are not automatically
unequivalent. When ``False``, items must be the same type to be equivalent.
**Default**: ``False``.
string_insensitive (bool): When ``True``, strings are treated as containers, with each
character being one element in the container.
When ``False``, strings are treated as non-containers and compared directly.
**Default**: ``False``.
Returns:
bool: ``True`` iff the two items are equivalent (see above).
``False`` otherwise.
"""
# If type-sensitive, check types
if not type_insensitive and type(item1) != type(item2):
return False
# Handle Mapping objects (dict)
if isinstance(item1, Mapping):
# Second item must be Mapping
if not isinstance(item2, Mapping):
return False
# Items must have the same number of elements
if not len(item1) == len(item2):
return False
# Keys must be the same
if not insensitive_comparison(list(item1.keys()), list(item2.keys()),
type_insensitive=True):
return False
# Each key's value must be the same
# We can just check item1.items because the keys are the same
for key, val in item1.items():
if not insensitive_comparison(item1[key], item2[key],
type_insensitive=type_insensitive,
string_insensitive=string_insensitive):
return False
# Keys and values are the same
return True
# Handle strings
elif isinstance(item1, str):
# Second item must be string
if not isinstance(item2, str):
return False
# Items must have the same number of elements (except string_insensitive)
if not len(item1) == len(item2) and not string_insensitive:
return False
# If we're insensitive to case, spaces, and order, compare characters
if string_insensitive:
# If the string is one character long, skip additional comparison
if len(item1) <= 1:
return item1.lower() == item2.lower()
# Make strings into containers (lists) and discard whitespace
item1_list = [c for c in item1.lower() if not c.isspace()]
item2_list = [c for c in item2.lower() if not c.isspace()]
# The insensitive args shouldn't matter, but they're here just in case
return insensitive_comparison(item1_list, item2_list,
type_insensitive=type_insensitive,
string_insensitive=string_insensitive)
# Otherwise, case and order matter
else:
return item1 == item2
# Handle other Iterable Containers
elif isinstance(item1, Container) and isinstance(item1, Iterable):
# Second item must be an Iterable Container
if not isinstance(item2, Container) or not isinstance(item2, Iterable):
return False
# Items must have the same number of elements
if not len(item1) == len(item2):
return False
# Every element in item1 must be in item2, and vice-versa
# Painfully slow, but unavoidable for deep comparison
# Each match in item1 removes the corresponding element from item2_copy
# If they're the same, item2_copy should be empty at the end,
# unless a .remove() failed, in which case we have to re-match using item2
item2_copy = list(deepcopy(item2))
remove_failed = False
for elem in item1:
matched = False
# Try every element
for candidate in item2:
# If comparison succeeds, flag a match, remove match from copy, and dump out
if insensitive_comparison(elem, candidate,
type_insensitive=type_insensitive,
string_insensitive=string_insensitive):
matched = True
try:
item2_copy.remove(candidate)
except ValueError: # list.remove(x): x not in list
remove_failed = True
break
# One failure indicates unequivalence
if not matched:
return False
# If all removes succeeded, we can shortcut checking all item2 elements in item1
if not remove_failed:
# If the Containers are equivalent, all elements in item2_copy should be removed
# Otherwise
return len(item2_copy) == 0
# If something failed, we have to verify all of item2
# We can't assume item2 != item1, because removal is comparative
else:
for elem in item2:
matched = False
# Try every element
for candidate in item1:
# If comparison succeeds, flag a match, remove match from copy, and dump out
if insensitive_comparison(elem, candidate,
type_insensitive=type_insensitive,
string_insensitive=string_insensitive):
matched = True
break
# One failure indicates unequivalence
if not matched:
return False
# All elements have a match
return True
# Handle otherwise unhandled type (catchall)
else:
return item1 == item2 |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:template_to_filepath; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:template; 5, identifier:metadata; 6, default_parameter; 6, 7; 6, 8; 7, identifier:template_patterns; 8, None; 9, block; 9, 10; 9, 12; 9, 19; 9, 28; 9, 35; 9, 292; 10, expression_statement; 10, 11; 11, comment; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:path; 15, call; 15, 16; 15, 17; 16, identifier:Path; 17, argument_list; 17, 18; 18, identifier:template; 19, if_statement; 19, 20; 19, 23; 20, comparison_operator:is; 20, 21; 20, 22; 21, identifier:template_patterns; 22, None; 23, block; 23, 24; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:template_patterns; 27, identifier:TEMPLATE_PATTERNS; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:suggested_filename; 31, call; 31, 32; 31, 33; 32, identifier:suggest_filename; 33, argument_list; 33, 34; 34, identifier:metadata; 35, if_statement; 35, 36; 35, 51; 35, 59; 35, 252; 35, 270; 35, 286; 36, parenthesized_expression; 36, 37; 37, boolean_operator:or; 37, 38; 37, 45; 38, comparison_operator:==; 38, 39; 38, 40; 39, identifier:path; 40, call; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:Path; 43, identifier:cwd; 44, argument_list; 45, comparison_operator:==; 45, 46; 45, 47; 46, identifier:path; 47, call; 47, 48; 47, 49; 48, identifier:Path; 49, argument_list; 49, 50; 50, string:'%suggested%'; 51, block; 51, 52; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:filepath; 55, call; 55, 56; 55, 57; 56, identifier:Path; 57, argument_list; 57, 58; 58, identifier:suggested_filename; 59, elif_clause; 59, 60; 59, 71; 60, call; 60, 61; 60, 62; 61, identifier:any; 62, generator_expression; 62, 63; 62, 68; 63, comparison_operator:in; 63, 64; 63, 65; 64, identifier:template_pattern; 65, attribute; 65, 66; 65, 67; 66, identifier:path; 67, identifier:parts; 68, for_in_clause; 68, 69; 68, 70; 69, identifier:template_pattern; 70, identifier:template_patterns; 71, block; 71, 72; 71, 86; 71, 99; 71, 103; 71, 244; 72, if_statement; 72, 73; 72, 81; 73, call; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:template; 76, identifier:endswith; 77, argument_list; 77, 78; 78, tuple; 78, 79; 78, 80; 79, string:'/'; 80, string:'\\'; 81, block; 81, 82; 82, expression_statement; 82, 83; 83, augmented_assignment:+=; 83, 84; 83, 85; 84, identifier:template; 85, identifier:suggested_filename; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:path; 89, call; 89, 90; 89, 91; 90, identifier:Path; 91, argument_list; 91, 92; 92, call; 92, 93; 92, 96; 93, attribute; 93, 94; 93, 95; 94, identifier:template; 95, identifier:replace; 96, argument_list; 96, 97; 96, 98; 97, string:'%suggested%'; 98, identifier:suggested_filename; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:parts; 102, list:[]; 103, for_statement; 103, 104; 103, 105; 103, 108; 104, identifier:part; 105, attribute; 105, 106; 105, 107; 106, identifier:path; 107, identifier:parts; 108, block; 108, 109; 109, if_statement; 109, 110; 109, 115; 109, 123; 110, comparison_operator:==; 110, 111; 110, 112; 111, identifier:part; 112, attribute; 112, 113; 112, 114; 113, identifier:path; 114, identifier:anchor; 115, block; 115, 116; 116, expression_statement; 116, 117; 117, call; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, identifier:parts; 120, identifier:append; 121, argument_list; 121, 122; 122, identifier:part; 123, else_clause; 123, 124; 124, block; 124, 125; 124, 234; 125, for_statement; 125, 126; 125, 127; 125, 128; 126, identifier:key; 127, identifier:template_patterns; 128, block; 128, 129; 129, if_statement; 129, 130; 129, 147; 130, parenthesized_expression; 130, 131; 130, 132; 131, comment; 132, boolean_operator:and; 132, 133; 132, 136; 133, comparison_operator:in; 133, 134; 133, 135; 134, identifier:key; 135, identifier:part; 136, call; 136, 137; 136, 138; 137, identifier:any; 138, generator_expression; 138, 139; 138, 142; 139, comparison_operator:in; 139, 140; 139, 141; 140, identifier:field; 141, identifier:metadata; 142, for_in_clause; 142, 143; 142, 144; 143, identifier:field; 144, subscript; 144, 145; 144, 146; 145, identifier:template_patterns; 146, identifier:key; 147, block; 147, 148; 147, 167; 147, 219; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 151; 150, identifier:field; 151, call; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:more_itertools; 154, identifier:first_true; 155, argument_list; 155, 156; 155, 159; 156, subscript; 156, 157; 156, 158; 157, identifier:template_patterns; 158, identifier:key; 159, keyword_argument; 159, 160; 159, 161; 160, identifier:pred; 161, lambda; 161, 162; 161, 164; 162, lambda_parameters; 162, 163; 163, identifier:k; 164, comparison_operator:in; 164, 165; 164, 166; 165, identifier:k; 166, identifier:metadata; 167, if_statement; 167, 168; 167, 176; 168, call; 168, 169; 168, 172; 169, attribute; 169, 170; 169, 171; 170, identifier:key; 171, identifier:startswith; 172, argument_list; 172, 173; 173, tuple; 173, 174; 173, 175; 174, string:'%disc'; 175, string:'%track'; 176, block; 176, 177; 176, 192; 177, expression_statement; 177, 178; 178, assignment; 178, 179; 178, 180; 179, identifier:number; 180, call; 180, 181; 180, 182; 181, identifier:_split_number_field; 182, argument_list; 182, 183; 183, call; 183, 184; 183, 185; 184, identifier:str; 185, argument_list; 185, 186; 186, call; 186, 187; 186, 188; 187, identifier:list_to_single_value; 188, argument_list; 188, 189; 189, subscript; 189, 190; 189, 191; 190, identifier:metadata; 191, identifier:field; 192, if_statement; 192, 193; 192, 199; 192, 211; 193, call; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:key; 196, identifier:endswith; 197, argument_list; 197, 198; 198, string:'2%'; 199, block; 199, 200; 200, expression_statement; 200, 201; 201, assignment; 201, 202; 201, 205; 202, subscript; 202, 203; 202, 204; 203, identifier:metadata; 204, identifier:field; 205, call; 205, 206; 205, 209; 206, attribute; 206, 207; 206, 208; 207, identifier:number; 208, identifier:zfill; 209, argument_list; 209, 210; 210, integer:2; 211, else_clause; 211, 212; 212, block; 212, 213; 213, expression_statement; 213, 214; 214, assignment; 214, 215; 214, 218; 215, subscript; 215, 216; 215, 217; 216, identifier:metadata; 217, identifier:field; 218, identifier:number; 219, expression_statement; 219, 220; 220, assignment; 220, 221; 220, 222; 221, identifier:part; 222, call; 222, 223; 222, 226; 223, attribute; 223, 224; 223, 225; 224, identifier:part; 225, identifier:replace; 226, argument_list; 226, 227; 226, 228; 227, identifier:key; 228, call; 228, 229; 228, 230; 229, identifier:list_to_single_value; 230, argument_list; 230, 231; 231, subscript; 231, 232; 231, 233; 232, identifier:metadata; 233, identifier:field; 234, expression_statement; 234, 235; 235, call; 235, 236; 235, 239; 236, attribute; 236, 237; 236, 238; 237, identifier:parts; 238, identifier:append; 239, argument_list; 239, 240; 240, call; 240, 241; 240, 242; 241, identifier:_replace_invalid_characters; 242, argument_list; 242, 243; 243, identifier:part; 244, expression_statement; 244, 245; 245, assignment; 245, 246; 245, 247; 246, identifier:filepath; 247, call; 247, 248; 247, 249; 248, identifier:Path; 249, argument_list; 249, 250; 250, list_splat; 250, 251; 251, identifier:parts; 252, elif_clause; 252, 253; 252, 256; 253, comparison_operator:in; 253, 254; 253, 255; 254, string:'%suggested%'; 255, identifier:template; 256, block; 256, 257; 257, expression_statement; 257, 258; 258, assignment; 258, 259; 258, 260; 259, identifier:filepath; 260, call; 260, 261; 260, 262; 261, identifier:Path; 262, argument_list; 262, 263; 263, call; 263, 264; 263, 267; 264, attribute; 264, 265; 264, 266; 265, identifier:template; 266, identifier:replace; 267, argument_list; 267, 268; 267, 269; 268, string:'%suggested%'; 269, identifier:suggested_filename; 270, elif_clause; 270, 271; 270, 279; 271, call; 271, 272; 271, 275; 272, attribute; 272, 273; 272, 274; 273, identifier:template; 274, identifier:endswith; 275, argument_list; 275, 276; 276, tuple; 276, 277; 276, 278; 277, string:'/'; 278, string:'\\'; 279, block; 279, 280; 280, expression_statement; 280, 281; 281, assignment; 281, 282; 281, 283; 282, identifier:filepath; 283, binary_operator:/; 283, 284; 283, 285; 284, identifier:path; 285, identifier:suggested_filename; 286, else_clause; 286, 287; 287, block; 287, 288; 288, expression_statement; 288, 289; 289, assignment; 289, 290; 289, 291; 290, identifier:filepath; 291, identifier:path; 292, return_statement; 292, 293; 293, identifier:filepath | def template_to_filepath(template, metadata, template_patterns=None):
"""Create directory structure and file name based on metadata template.
Note:
A template meant to be a base directory for suggested
names should have a trailing slash or backslash.
Parameters:
template (str or ~os.PathLike): A filepath which can include template patterns as defined by :param template_patterns:.
metadata (~collections.abc.Mapping): A metadata dict.
template_patterns (~collections.abc.Mapping): A dict of ``pattern: field`` pairs used to replace patterns with metadata field values.
Default: :const:`~google_music_utils.constants.TEMPLATE_PATTERNS`
Returns:
~pathlib.Path: A filepath.
"""
path = Path(template)
if template_patterns is None:
template_patterns = TEMPLATE_PATTERNS
suggested_filename = suggest_filename(metadata)
if (
path == Path.cwd()
or path == Path('%suggested%')
):
filepath = Path(suggested_filename)
elif any(template_pattern in path.parts for template_pattern in template_patterns):
if template.endswith(('/', '\\')):
template += suggested_filename
path = Path(template.replace('%suggested%', suggested_filename))
parts = []
for part in path.parts:
if part == path.anchor:
parts.append(part)
else:
for key in template_patterns:
if ( # pragma: no branch
key in part
and any(field in metadata for field in template_patterns[key])
):
field = more_itertools.first_true(
template_patterns[key],
pred=lambda k: k in metadata
)
if key.startswith(('%disc', '%track')):
number = _split_number_field(
str(
list_to_single_value(
metadata[field]
)
)
)
if key.endswith('2%'):
metadata[field] = number.zfill(2)
else:
metadata[field] = number
part = part.replace(
key,
list_to_single_value(
metadata[field]
)
)
parts.append(_replace_invalid_characters(part))
filepath = Path(*parts)
elif '%suggested%' in template:
filepath = Path(template.replace('%suggested%', suggested_filename))
elif template.endswith(('/', '\\')):
filepath = path / suggested_filename
else:
filepath = path
return filepath |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:_get_station_codes; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:force; 7, False; 8, block; 8, 9; 8, 11; 8, 25; 8, 33; 8, 34; 8, 38; 8, 99; 8, 105; 8, 153; 8, 250; 9, expression_statement; 9, 10; 10, comment; 11, if_statement; 11, 12; 11, 20; 12, boolean_operator:and; 12, 13; 12, 15; 13, not_operator; 13, 14; 14, identifier:force; 15, comparison_operator:is; 15, 16; 15, 19; 16, attribute; 16, 17; 16, 18; 17, identifier:self; 18, identifier:station_codes; 19, None; 20, block; 20, 21; 21, return_statement; 21, 22; 22, attribute; 22, 23; 22, 24; 23, identifier:self; 24, identifier:station_codes; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:state_urls; 28, call; 28, 29; 28, 32; 29, attribute; 29, 30; 29, 31; 30, identifier:self; 31, identifier:_get_state_urls; 32, argument_list; 33, comment; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:state_matches; 37, None; 38, if_statement; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:self; 41, identifier:bbox; 42, block; 42, 43; 43, with_statement; 43, 44; 43, 62; 44, with_clause; 44, 45; 45, with_item; 45, 46; 46, as_pattern; 46, 47; 46, 60; 47, call; 47, 48; 47, 49; 48, identifier:collection; 49, argument_list; 49, 50; 49, 59; 50, call; 50, 51; 50, 56; 51, attribute; 51, 52; 51, 55; 52, attribute; 52, 53; 52, 54; 53, identifier:os; 54, identifier:path; 55, identifier:join; 56, argument_list; 56, 57; 56, 58; 57, string:"resources"; 58, string:"ne_50m_admin_1_states_provinces_lakes_shp.shp"; 59, string:"r"; 60, as_pattern_target; 60, 61; 61, identifier:c; 62, block; 62, 63; 62, 82; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:geom_matches; 66, list_comprehension; 66, 67; 66, 70; 67, subscript; 67, 68; 67, 69; 68, identifier:x; 69, string:"properties"; 70, for_in_clause; 70, 71; 70, 72; 71, identifier:x; 72, call; 72, 73; 72, 76; 73, attribute; 73, 74; 73, 75; 74, identifier:c; 75, identifier:filter; 76, argument_list; 76, 77; 77, keyword_argument; 77, 78; 77, 79; 78, identifier:bbox; 79, attribute; 79, 80; 79, 81; 80, identifier:self; 81, identifier:bbox; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 85; 84, identifier:state_matches; 85, list_comprehension; 85, 86; 85, 96; 86, conditional_expression:if; 86, 87; 86, 90; 86, 95; 87, subscript; 87, 88; 87, 89; 88, identifier:x; 89, string:"postal"; 90, comparison_operator:!=; 90, 91; 90, 94; 91, subscript; 91, 92; 91, 93; 92, identifier:x; 93, string:"admin"; 94, string:"Canada"; 95, string:"CN"; 96, for_in_clause; 96, 97; 96, 98; 97, identifier:x; 98, identifier:geom_matches; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:self; 103, identifier:station_codes; 104, list:[]; 105, for_statement; 105, 106; 105, 107; 105, 108; 106, identifier:state_url; 107, identifier:state_urls; 108, block; 108, 109; 108, 139; 109, if_statement; 109, 110; 109, 113; 110, comparison_operator:is; 110, 111; 110, 112; 111, identifier:state_matches; 112, None; 113, block; 113, 114; 113, 133; 114, expression_statement; 114, 115; 115, assignment; 115, 116; 115, 117; 116, identifier:state_abbr; 117, subscript; 117, 118; 117, 132; 118, call; 118, 119; 118, 130; 119, attribute; 119, 120; 119, 129; 120, subscript; 120, 121; 120, 127; 121, call; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:state_url; 124, identifier:split; 125, argument_list; 125, 126; 126, string:"/"; 127, unary_operator:-; 127, 128; 128, integer:1; 129, identifier:split; 130, argument_list; 130, 131; 131, string:"."; 132, integer:0; 133, if_statement; 133, 134; 133, 137; 134, comparison_operator:not; 134, 135; 134, 136; 135, identifier:state_abbr; 136, identifier:state_matches; 137, block; 137, 138; 138, continue_statement; 139, expression_statement; 139, 140; 140, call; 140, 141; 140, 146; 141, attribute; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, identifier:self; 144, identifier:station_codes; 145, identifier:extend; 146, argument_list; 146, 147; 147, call; 147, 148; 147, 151; 148, attribute; 148, 149; 148, 150; 149, identifier:self; 150, identifier:_get_stations_for_state; 151, argument_list; 151, 152; 152, identifier:state_url; 153, if_statement; 153, 154; 153, 157; 153, 158; 154, attribute; 154, 155; 154, 156; 155, identifier:self; 156, identifier:bbox; 157, comment; 158, block; 158, 159; 158, 170; 158, 181; 158, 235; 159, expression_statement; 159, 160; 160, assignment; 160, 161; 160, 162; 161, identifier:metadata; 162, call; 162, 163; 162, 166; 163, attribute; 163, 164; 163, 165; 164, identifier:self; 165, identifier:_get_metadata; 166, argument_list; 166, 167; 167, attribute; 167, 168; 167, 169; 168, identifier:self; 169, identifier:station_codes; 170, expression_statement; 170, 171; 171, assignment; 171, 172; 171, 173; 172, identifier:parsed_metadata; 173, call; 173, 174; 173, 179; 174, attribute; 174, 175; 174, 178; 175, attribute; 175, 176; 175, 177; 176, identifier:self; 177, identifier:parser; 178, identifier:_parse_metadata; 179, argument_list; 179, 180; 180, identifier:metadata; 181, function_definition; 181, 182; 181, 183; 181, 185; 182, function_name:in_bbox; 183, parameters; 183, 184; 184, identifier:code; 185, block; 185, 186; 185, 194; 185, 202; 186, expression_statement; 186, 187; 187, assignment; 187, 188; 187, 189; 188, identifier:lat; 189, subscript; 189, 190; 189, 193; 190, subscript; 190, 191; 190, 192; 191, identifier:parsed_metadata; 192, identifier:code; 193, string:"latitude"; 194, expression_statement; 194, 195; 195, assignment; 195, 196; 195, 197; 196, identifier:lon; 197, subscript; 197, 198; 197, 201; 198, subscript; 198, 199; 198, 200; 199, identifier:parsed_metadata; 200, identifier:code; 201, string:"longitude"; 202, return_statement; 202, 203; 203, parenthesized_expression; 203, 204; 204, boolean_operator:and; 204, 205; 204, 228; 205, boolean_operator:and; 205, 206; 205, 221; 206, boolean_operator:and; 206, 207; 206, 214; 207, comparison_operator:>=; 207, 208; 207, 209; 208, identifier:lon; 209, subscript; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, identifier:self; 212, identifier:bbox; 213, integer:0; 214, comparison_operator:<=; 214, 215; 214, 216; 215, identifier:lon; 216, subscript; 216, 217; 216, 220; 217, attribute; 217, 218; 217, 219; 218, identifier:self; 219, identifier:bbox; 220, integer:2; 221, comparison_operator:>=; 221, 222; 221, 223; 222, identifier:lat; 223, subscript; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:self; 226, identifier:bbox; 227, integer:1; 228, comparison_operator:<=; 228, 229; 228, 230; 229, identifier:lat; 230, subscript; 230, 231; 230, 234; 231, attribute; 231, 232; 231, 233; 232, identifier:self; 233, identifier:bbox; 234, integer:3; 235, expression_statement; 235, 236; 236, assignment; 236, 237; 236, 240; 237, attribute; 237, 238; 237, 239; 238, identifier:self; 239, identifier:station_codes; 240, call; 240, 241; 240, 242; 241, identifier:list; 242, argument_list; 242, 243; 243, call; 243, 244; 243, 245; 244, identifier:filter; 245, argument_list; 245, 246; 245, 247; 246, identifier:in_bbox; 247, attribute; 247, 248; 247, 249; 248, identifier:self; 249, identifier:station_codes; 250, return_statement; 250, 251; 251, attribute; 251, 252; 251, 253; 252, identifier:self; 253, identifier:station_codes | def _get_station_codes(self, force=False):
"""
Gets and caches a list of station codes optionally within a bbox.
Will return the cached version if it exists unless force is True.
"""
if not force and self.station_codes is not None:
return self.station_codes
state_urls = self._get_state_urls()
# filter by bounding box against a shapefile
state_matches = None
if self.bbox:
with collection(
os.path.join(
"resources",
"ne_50m_admin_1_states_provinces_lakes_shp.shp",
),
"r",
) as c:
geom_matches = [
x["properties"] for x in c.filter(bbox=self.bbox)
]
state_matches = [
x["postal"] if x["admin"] != "Canada" else "CN"
for x in geom_matches
]
self.station_codes = []
for state_url in state_urls:
if state_matches is not None:
state_abbr = state_url.split("/")[-1].split(".")[0]
if state_abbr not in state_matches:
continue
self.station_codes.extend(self._get_stations_for_state(state_url))
if self.bbox:
# retrieve metadata for all stations to properly filter them
metadata = self._get_metadata(self.station_codes)
parsed_metadata = self.parser._parse_metadata(metadata)
def in_bbox(code):
lat = parsed_metadata[code]["latitude"]
lon = parsed_metadata[code]["longitude"]
return (
lon >= self.bbox[0]
and lon <= self.bbox[2]
and lat >= self.bbox[1]
and lat <= self.bbox[3]
)
self.station_codes = list(filter(in_bbox, self.station_codes))
return self.station_codes |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:_validate_query; 3, parameters; 3, 4; 4, identifier:query; 5, block; 5, 6; 5, 8; 5, 15; 5, 16; 5, 30; 5, 41; 5, 42; 5, 90; 5, 91; 5, 123; 5, 124; 5, 144; 5, 155; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:query; 11, call; 11, 12; 11, 13; 12, identifier:deepcopy; 13, argument_list; 13, 14; 14, identifier:query; 15, comment; 16, if_statement; 16, 17; 16, 24; 17, comparison_operator:==; 17, 18; 17, 21; 18, subscript; 18, 19; 18, 20; 19, identifier:query; 20, string:"q"; 21, subscript; 21, 22; 21, 23; 22, identifier:BLANK_QUERY; 23, string:"q"; 24, block; 24, 25; 25, raise_statement; 25, 26; 26, call; 26, 27; 26, 28; 27, identifier:ValueError; 28, argument_list; 28, 29; 29, string:"No query specified."; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 35; 32, subscript; 32, 33; 32, 34; 33, identifier:query; 34, string:"q"; 35, call; 35, 36; 35, 37; 36, identifier:_clean_query_string; 37, argument_list; 37, 38; 38, subscript; 38, 39; 38, 40; 39, identifier:query; 40, string:"q"; 41, comment; 42, if_statement; 42, 43; 42, 48; 42, 60; 42, 61; 43, comparison_operator:is; 43, 44; 43, 47; 44, subscript; 44, 45; 44, 46; 45, identifier:query; 46, string:"limit"; 47, None; 48, block; 48, 49; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 54; 51, subscript; 51, 52; 51, 53; 52, identifier:query; 53, string:"limit"; 54, conditional_expression:if; 54, 55; 54, 56; 54, 59; 55, identifier:SEARCH_LIMIT; 56, subscript; 56, 57; 56, 58; 57, identifier:query; 58, string:"advanced"; 59, identifier:NONADVANCED_LIMIT; 60, comment; 61, elif_clause; 61, 62; 61, 67; 62, comparison_operator:>; 62, 63; 62, 66; 63, subscript; 63, 64; 63, 65; 64, identifier:query; 65, string:"limit"; 66, identifier:SEARCH_LIMIT; 67, block; 67, 68; 67, 84; 68, expression_statement; 68, 69; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:warnings; 72, identifier:warn; 73, argument_list; 73, 74; 73, 83; 74, call; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, string:'Reduced result limit from {} to the Search maximum: {}'; 77, identifier:format; 78, argument_list; 78, 79; 78, 82; 79, subscript; 79, 80; 79, 81; 80, identifier:query; 81, string:"limit"; 82, identifier:SEARCH_LIMIT; 83, identifier:RuntimeWarning; 84, expression_statement; 84, 85; 85, assignment; 85, 86; 85, 89; 86, subscript; 86, 87; 86, 88; 87, identifier:query; 88, string:"limit"; 89, identifier:SEARCH_LIMIT; 90, comment; 91, for_statement; 91, 92; 91, 95; 91, 100; 91, 101; 92, pattern_list; 92, 93; 92, 94; 93, identifier:key; 94, identifier:val; 95, call; 95, 96; 95, 99; 96, attribute; 96, 97; 96, 98; 97, identifier:BLANK_QUERY; 98, identifier:items; 99, argument_list; 100, comment; 101, block; 101, 102; 102, if_statement; 102, 103; 102, 115; 103, comparison_operator:==; 103, 104; 103, 114; 104, call; 104, 105; 104, 108; 105, attribute; 105, 106; 105, 107; 106, identifier:query; 107, identifier:get; 108, argument_list; 108, 109; 108, 110; 109, identifier:key; 110, call; 110, 111; 110, 112; 111, identifier:float; 112, argument_list; 112, 113; 113, string:'nan'; 114, identifier:val; 115, block; 115, 116; 116, expression_statement; 116, 117; 117, call; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, identifier:query; 120, identifier:pop; 121, argument_list; 121, 122; 122, identifier:key; 123, comment; 124, expression_statement; 124, 125; 125, assignment; 125, 126; 125, 127; 126, identifier:to_remove; 127, list_comprehension; 127, 128; 127, 129; 127, 136; 128, identifier:field; 129, for_in_clause; 129, 130; 129, 131; 130, identifier:field; 131, call; 131, 132; 131, 135; 132, attribute; 132, 133; 132, 134; 133, identifier:query; 134, identifier:keys; 135, argument_list; 136, if_clause; 136, 137; 137, comparison_operator:not; 137, 138; 137, 139; 138, identifier:field; 139, call; 139, 140; 139, 143; 140, attribute; 140, 141; 140, 142; 141, identifier:BLANK_QUERY; 142, identifier:keys; 143, argument_list; 144, expression_statement; 144, 145; 145, list_comprehension; 145, 146; 145, 152; 146, call; 146, 147; 146, 150; 147, attribute; 147, 148; 147, 149; 148, identifier:query; 149, identifier:pop; 150, argument_list; 150, 151; 151, identifier:field; 152, for_in_clause; 152, 153; 152, 154; 153, identifier:field; 154, identifier:to_remove; 155, return_statement; 155, 156; 156, identifier:query | def _validate_query(query):
"""Validate and clean up a query to be sent to Search.
Cleans the query string, removes unneeded parameters, and validates for correctness.
Does not modify the original argument.
Raises an Exception on invalid input.
Arguments:
query (dict): The query to validate.
Returns:
dict: The validated query.
"""
query = deepcopy(query)
# q is always required
if query["q"] == BLANK_QUERY["q"]:
raise ValueError("No query specified.")
query["q"] = _clean_query_string(query["q"])
# limit should be set to appropriate default if not specified
if query["limit"] is None:
query["limit"] = SEARCH_LIMIT if query["advanced"] else NONADVANCED_LIMIT
# If specified, the limit should not be greater than the Search maximum
elif query["limit"] > SEARCH_LIMIT:
warnings.warn('Reduced result limit from {} to the Search maximum: {}'
.format(query["limit"], SEARCH_LIMIT), RuntimeWarning)
query["limit"] = SEARCH_LIMIT
# Remove all blank/default values
for key, val in BLANK_QUERY.items():
# Default for get is NaN so comparison is always False
if query.get(key, float('nan')) == val:
query.pop(key)
# Remove unsupported fields
to_remove = [field for field in query.keys() if field not in BLANK_QUERY.keys()]
[query.pop(field) for field in to_remove]
return query |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:show_fields; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:block; 7, None; 8, block; 8, 9; 8, 11; 8, 19; 8, 103; 9, expression_statement; 9, 10; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:mapping; 14, call; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:self; 17, identifier:_mapping; 18, argument_list; 19, if_statement; 19, 20; 19, 23; 19, 26; 19, 73; 20, comparison_operator:is; 20, 21; 20, 22; 21, identifier:block; 22, None; 23, block; 23, 24; 24, return_statement; 24, 25; 25, identifier:mapping; 26, elif_clause; 26, 27; 26, 30; 27, comparison_operator:==; 27, 28; 27, 29; 28, identifier:block; 29, string:"top"; 30, block; 30, 31; 30, 37; 30, 59; 30, 63; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:blocks; 34, call; 34, 35; 34, 36; 35, identifier:set; 36, argument_list; 37, for_statement; 37, 38; 37, 39; 37, 44; 38, identifier:key; 39, call; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:mapping; 42, identifier:keys; 43, argument_list; 44, block; 44, 45; 45, expression_statement; 45, 46; 46, call; 46, 47; 46, 50; 47, attribute; 47, 48; 47, 49; 48, identifier:blocks; 49, identifier:add; 50, argument_list; 50, 51; 51, subscript; 51, 52; 51, 58; 52, call; 52, 53; 52, 56; 53, attribute; 53, 54; 53, 55; 54, identifier:key; 55, identifier:split; 56, argument_list; 56, 57; 57, string:"."; 58, integer:0; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:block_map; 62, dictionary; 63, for_statement; 63, 64; 63, 65; 63, 66; 64, identifier:b; 65, identifier:blocks; 66, block; 66, 67; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 72; 69, subscript; 69, 70; 69, 71; 70, identifier:block_map; 71, identifier:b; 72, string:"object"; 73, else_clause; 73, 74; 74, block; 74, 75; 74, 79; 75, expression_statement; 75, 76; 76, assignment; 76, 77; 76, 78; 77, identifier:block_map; 78, dictionary; 79, for_statement; 79, 80; 79, 83; 79, 88; 80, pattern_list; 80, 81; 80, 82; 81, identifier:key; 82, identifier:value; 83, call; 83, 84; 83, 87; 84, attribute; 84, 85; 84, 86; 85, identifier:mapping; 86, identifier:items; 87, argument_list; 88, block; 88, 89; 89, if_statement; 89, 90; 89, 96; 90, call; 90, 91; 90, 94; 91, attribute; 91, 92; 91, 93; 92, identifier:key; 93, identifier:startswith; 94, argument_list; 94, 95; 95, identifier:block; 96, block; 96, 97; 97, expression_statement; 97, 98; 98, assignment; 98, 99; 98, 102; 99, subscript; 99, 100; 99, 101; 100, identifier:block_map; 101, identifier:key; 102, identifier:value; 103, return_statement; 103, 104; 104, identifier:block_map | def show_fields(self, block=None):
"""Retrieve and return the mapping for the given metadata block.
Arguments:
block (str): The top-level field to fetch the mapping for (for example, ``"mdf"``),
or the special values ``None`` for everything or ``"top"`` for just the
top-level fields.
**Default:** ``None``.
index (str): The Search index to map. **Default:** The current index.
Returns:
dict: ``field:datatype`` pairs.
"""
mapping = self._mapping()
if block is None:
return mapping
elif block == "top":
blocks = set()
for key in mapping.keys():
blocks.add(key.split(".")[0])
block_map = {}
for b in blocks:
block_map[b] = "object"
else:
block_map = {}
for key, value in mapping.items():
if key.startswith(block):
block_map[key] = value
return block_map |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:sorted; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:by; 6, dictionary_splat_pattern; 6, 7; 7, identifier:kwargs; 8, block; 8, 9; 8, 11; 8, 24; 9, expression_statement; 9, 10; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:sort_idc; 14, call; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:np; 17, identifier:argsort; 18, argument_list; 18, 19; 18, 22; 19, subscript; 19, 20; 19, 21; 20, identifier:self; 21, identifier:by; 22, dictionary_splat; 22, 23; 23, identifier:kwargs; 24, return_statement; 24, 25; 25, call; 25, 26; 25, 29; 26, attribute; 26, 27; 26, 28; 27, identifier:self; 28, identifier:__class__; 29, argument_list; 29, 30; 29, 33; 29, 38; 29, 43; 30, subscript; 30, 31; 30, 32; 31, identifier:self; 32, identifier:sort_idc; 33, keyword_argument; 33, 34; 33, 35; 34, identifier:h5loc; 35, attribute; 35, 36; 35, 37; 36, identifier:self; 37, identifier:h5loc; 38, keyword_argument; 38, 39; 38, 40; 39, identifier:split_h5; 40, attribute; 40, 41; 40, 42; 41, identifier:self; 42, identifier:split_h5; 43, keyword_argument; 43, 44; 43, 45; 44, identifier:name; 45, attribute; 45, 46; 45, 47; 46, identifier:self; 47, identifier:name | def sorted(self, by, **kwargs):
"""Sort array by a column.
Parameters
==========
by: str
Name of the columns to sort by(e.g. 'time').
"""
sort_idc = np.argsort(self[by], **kwargs)
return self.__class__(
self[sort_idc],
h5loc=self.h5loc,
split_h5=self.split_h5,
name=self.name
) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:create_multi_output_factor; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, identifier:self; 5, identifier:tool; 6, identifier:source; 7, identifier:splitting_node; 8, identifier:sink; 9, block; 9, 10; 9, 12; 9, 35; 9, 56; 9, 57; 9, 58; 9, 79; 9, 80; 9, 89; 9, 95; 9, 105; 9, 118; 9, 345; 9, 352; 10, expression_statement; 10, 11; 11, comment; 12, if_statement; 12, 13; 12, 21; 13, boolean_operator:and; 13, 14; 13, 15; 14, identifier:source; 15, not_operator; 15, 16; 16, call; 16, 17; 16, 18; 17, identifier:isinstance; 18, argument_list; 18, 19; 18, 20; 19, identifier:source; 20, identifier:Node; 21, block; 21, 22; 22, raise_statement; 22, 23; 23, call; 23, 24; 23, 25; 24, identifier:ValueError; 25, argument_list; 25, 26; 26, call; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, string:"Expected Node, got {}"; 29, identifier:format; 30, argument_list; 30, 31; 31, call; 31, 32; 31, 33; 32, identifier:type; 33, argument_list; 33, 34; 34, identifier:source; 35, if_statement; 35, 36; 35, 42; 36, not_operator; 36, 37; 37, call; 37, 38; 37, 39; 38, identifier:isinstance; 39, argument_list; 39, 40; 39, 41; 40, identifier:sink; 41, identifier:Node; 42, block; 42, 43; 43, raise_statement; 43, 44; 44, call; 44, 45; 44, 46; 45, identifier:ValueError; 46, argument_list; 46, 47; 47, call; 47, 48; 47, 51; 48, attribute; 48, 49; 48, 50; 49, string:"Expected Node, got {}"; 50, identifier:format; 51, argument_list; 51, 52; 52, call; 52, 53; 52, 54; 53, identifier:type; 54, argument_list; 54, 55; 55, identifier:sink; 56, comment; 57, comment; 58, if_statement; 58, 59; 58, 65; 59, not_operator; 59, 60; 60, call; 60, 61; 60, 62; 61, identifier:isinstance; 62, argument_list; 62, 63; 62, 64; 63, identifier:tool; 64, identifier:MultiOutputTool; 65, block; 65, 66; 66, raise_statement; 66, 67; 67, call; 67, 68; 67, 69; 68, identifier:ValueError; 69, argument_list; 69, 70; 70, call; 70, 71; 70, 74; 71, attribute; 71, 72; 71, 73; 72, string:"Expected MultiOutputTool, got {}"; 73, identifier:format; 74, argument_list; 74, 75; 75, call; 75, 76; 75, 77; 76, identifier:type; 77, argument_list; 77, 78; 78, identifier:tool; 79, comment; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:input_plates; 83, conditional_expression:if; 83, 84; 83, 87; 83, 88; 84, attribute; 84, 85; 84, 86; 85, identifier:source; 86, identifier:plates; 87, identifier:source; 88, list:[]; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:output_plates; 92, attribute; 92, 93; 92, 94; 93, identifier:sink; 94, identifier:plates; 95, if_statement; 95, 96; 95, 102; 96, comparison_operator:>; 96, 97; 96, 101; 97, call; 97, 98; 97, 99; 98, identifier:len; 99, argument_list; 99, 100; 100, identifier:input_plates; 101, integer:1; 102, block; 102, 103; 103, raise_statement; 103, 104; 104, identifier:NotImplementedError; 105, if_statement; 105, 106; 105, 112; 106, comparison_operator:==; 106, 107; 106, 111; 107, call; 107, 108; 107, 109; 108, identifier:len; 109, argument_list; 109, 110; 110, identifier:output_plates; 111, integer:0; 112, block; 112, 113; 113, raise_statement; 113, 114; 114, call; 114, 115; 114, 116; 115, identifier:ValueError; 116, argument_list; 116, 117; 117, string:"No output plate found"; 118, if_statement; 118, 119; 118, 125; 118, 174; 119, comparison_operator:==; 119, 120; 119, 124; 120, call; 120, 121; 120, 122; 121, identifier:len; 122, argument_list; 122, 123; 123, identifier:output_plates; 124, integer:1; 125, block; 125, 126; 125, 143; 126, if_statement; 126, 127; 126, 137; 127, not_operator; 127, 128; 128, call; 128, 129; 128, 132; 129, attribute; 129, 130; 129, 131; 130, identifier:self; 131, identifier:check_multi_output_plate_compatibility; 132, argument_list; 132, 133; 132, 134; 133, identifier:input_plates; 134, subscript; 134, 135; 134, 136; 135, identifier:output_plates; 136, integer:0; 137, block; 137, 138; 138, raise_statement; 138, 139; 139, call; 139, 140; 139, 141; 140, identifier:IncompatiblePlatesError; 141, argument_list; 141, 142; 142, string:"Parent plate does not match input plate"; 143, expression_statement; 143, 144; 144, assignment; 144, 145; 144, 146; 145, identifier:factor; 146, call; 146, 147; 146, 148; 147, identifier:MultiOutputFactor; 148, argument_list; 148, 149; 148, 152; 148, 155; 148, 158; 148, 161; 148, 169; 149, keyword_argument; 149, 150; 149, 151; 150, identifier:tool; 151, identifier:tool; 152, keyword_argument; 152, 153; 152, 154; 153, identifier:source_node; 154, identifier:source; 155, keyword_argument; 155, 156; 155, 157; 156, identifier:splitting_node; 157, identifier:splitting_node; 158, keyword_argument; 158, 159; 158, 160; 159, identifier:sink_node; 160, identifier:sink; 161, keyword_argument; 161, 162; 161, 163; 162, identifier:input_plate; 163, conditional_expression:if; 163, 164; 163, 167; 163, 168; 164, subscript; 164, 165; 164, 166; 165, identifier:input_plates; 166, integer:0; 167, identifier:input_plates; 168, None; 169, keyword_argument; 169, 170; 169, 171; 170, identifier:output_plates; 171, subscript; 171, 172; 171, 173; 172, identifier:output_plates; 173, integer:0; 174, else_clause; 174, 175; 174, 176; 174, 177; 174, 178; 174, 179; 174, 180; 174, 181; 175, comment; 176, comment; 177, comment; 178, comment; 179, comment; 180, comment; 181, block; 181, 182; 181, 192; 181, 205; 181, 264; 181, 319; 182, if_statement; 182, 183; 182, 189; 183, comparison_operator:>; 183, 184; 183, 188; 184, call; 184, 185; 184, 186; 185, identifier:len; 186, argument_list; 186, 187; 187, identifier:output_plates; 188, integer:2; 189, block; 189, 190; 190, raise_statement; 190, 191; 191, identifier:NotImplementedError; 192, if_statement; 192, 193; 192, 199; 193, comparison_operator:!=; 193, 194; 193, 198; 194, call; 194, 195; 194, 196; 195, identifier:len; 196, argument_list; 196, 197; 197, identifier:input_plates; 198, integer:1; 199, block; 199, 200; 200, raise_statement; 200, 201; 201, call; 201, 202; 201, 203; 202, identifier:IncompatiblePlatesError; 203, argument_list; 203, 204; 204, string:"Require an input plate to match all but one of the output plates"; 205, if_statement; 205, 206; 205, 213; 205, 214; 205, 221; 206, comparison_operator:==; 206, 207; 206, 210; 207, subscript; 207, 208; 207, 209; 208, identifier:output_plates; 209, integer:0; 210, subscript; 210, 211; 210, 212; 211, identifier:input_plates; 212, integer:0; 213, comment; 214, block; 214, 215; 215, expression_statement; 215, 216; 216, assignment; 216, 217; 216, 218; 217, identifier:output_plate; 218, subscript; 218, 219; 218, 220; 219, identifier:output_plates; 220, integer:1; 221, else_clause; 221, 222; 222, block; 222, 223; 222, 241; 222, 247; 222, 248; 223, if_statement; 223, 224; 223, 235; 224, comparison_operator:!=; 224, 225; 224, 230; 225, attribute; 225, 226; 225, 229; 226, subscript; 226, 227; 226, 228; 227, identifier:output_plates; 228, integer:1; 229, identifier:plate_id; 230, attribute; 230, 231; 230, 234; 231, subscript; 231, 232; 231, 233; 232, identifier:input_plates; 233, integer:0; 234, identifier:plate_id; 235, block; 235, 236; 236, raise_statement; 236, 237; 237, call; 237, 238; 237, 239; 238, identifier:IncompatiblePlatesError; 239, argument_list; 239, 240; 240, string:"Require an input plate to match all but one of the output plates"; 241, expression_statement; 241, 242; 242, assignment; 242, 243; 242, 244; 243, identifier:output_plate; 244, subscript; 244, 245; 244, 246; 245, identifier:output_plates; 246, integer:0; 247, comment; 248, expression_statement; 248, 249; 249, assignment; 249, 250; 249, 257; 250, pattern_list; 250, 251; 250, 254; 251, subscript; 251, 252; 251, 253; 252, identifier:output_plates; 253, integer:1; 254, subscript; 254, 255; 254, 256; 255, identifier:output_plates; 256, integer:0; 257, expression_list; 257, 258; 257, 261; 258, subscript; 258, 259; 258, 260; 259, identifier:output_plates; 260, integer:0; 261, subscript; 261, 262; 261, 263; 262, identifier:output_plates; 263, integer:1; 264, if_statement; 264, 265; 264, 269; 264, 270; 265, not_operator; 265, 266; 266, attribute; 266, 267; 266, 268; 267, identifier:output_plate; 268, identifier:is_root; 269, comment; 270, block; 270, 271; 270, 275; 270, 283; 270, 310; 271, expression_statement; 271, 272; 272, assignment; 272, 273; 272, 274; 273, identifier:match; 274, False; 275, expression_statement; 275, 276; 276, assignment; 276, 277; 276, 278; 277, identifier:parent; 278, attribute; 278, 279; 278, 282; 279, subscript; 279, 280; 279, 281; 280, identifier:input_plates; 281, integer:0; 282, identifier:parent; 283, while_statement; 283, 284; 283, 287; 284, comparison_operator:is; 284, 285; 284, 286; 285, identifier:parent; 286, None; 287, block; 287, 288; 287, 304; 288, if_statement; 288, 289; 288, 298; 289, comparison_operator:==; 289, 290; 289, 293; 290, attribute; 290, 291; 290, 292; 291, identifier:parent; 292, identifier:plate_id; 293, attribute; 293, 294; 293, 297; 294, attribute; 294, 295; 294, 296; 295, identifier:output_plate; 296, identifier:parent; 297, identifier:plate_id; 298, block; 298, 299; 298, 303; 299, expression_statement; 299, 300; 300, assignment; 300, 301; 300, 302; 301, identifier:match; 302, True; 303, break_statement; 304, expression_statement; 304, 305; 305, assignment; 305, 306; 305, 307; 306, identifier:parent; 307, attribute; 307, 308; 307, 309; 308, identifier:parent; 309, identifier:parent; 310, if_statement; 310, 311; 310, 313; 311, not_operator; 311, 312; 312, identifier:match; 313, block; 313, 314; 314, raise_statement; 314, 315; 315, call; 315, 316; 315, 317; 316, identifier:IncompatiblePlatesError; 317, argument_list; 317, 318; 318, string:"Require an input plate to match all but one of the output plates"; 319, expression_statement; 319, 320; 320, assignment; 320, 321; 320, 322; 321, identifier:factor; 322, call; 322, 323; 322, 324; 323, identifier:MultiOutputFactor; 324, argument_list; 324, 325; 324, 328; 324, 331; 324, 334; 324, 337; 324, 342; 325, keyword_argument; 325, 326; 325, 327; 326, identifier:tool; 327, identifier:tool; 328, keyword_argument; 328, 329; 328, 330; 329, identifier:source_node; 330, identifier:source; 331, keyword_argument; 331, 332; 331, 333; 332, identifier:sink_node; 333, identifier:sink; 334, keyword_argument; 334, 335; 334, 336; 335, identifier:splitting_node; 336, identifier:splitting_node; 337, keyword_argument; 337, 338; 337, 339; 338, identifier:input_plate; 339, subscript; 339, 340; 339, 341; 340, identifier:input_plates; 341, integer:0; 342, keyword_argument; 342, 343; 342, 344; 343, identifier:output_plates; 344, identifier:output_plates; 345, expression_statement; 345, 346; 346, call; 346, 347; 346, 350; 347, attribute; 347, 348; 347, 349; 348, identifier:self; 349, identifier:_add_factor; 350, argument_list; 350, 351; 351, identifier:factor; 352, return_statement; 352, 353; 353, identifier:factor | def create_multi_output_factor(self, tool, source, splitting_node, sink):
"""
Creates a multi-output factor.
This takes a single node, applies a MultiOutputTool to create multiple nodes on a new plate
Instantiates a single tool for all of the input plate values,
and connects the source and sink nodes with that tool.
Note that the tool parameters these are currently fixed over a plate. For parameters that vary over a plate,
an extra input stream should be used
:param tool: The tool to use. This is either an instantiated Tool object or a dict with "name" and "parameters"
:param source: The source node
:param splitting_node: The node over which to split
:param sink: The sink node
:return: The factor object
:type tool: MultiOutputTool | dict
:type source: Node | None
:type sink: Node
:rtype: Factor
"""
if source and not isinstance(source, Node):
raise ValueError("Expected Node, got {}".format(type(source)))
if not isinstance(sink, Node):
raise ValueError("Expected Node, got {}".format(type(sink)))
# if isinstance(tool, dict):
# tool = self.channels.get_tool(**tool)
if not isinstance(tool, MultiOutputTool):
raise ValueError("Expected MultiOutputTool, got {}".format(type(tool)))
# Check that the input_plate are compatible - note this is the opposite way round to a normal factor
input_plates = source.plates if source else []
output_plates = sink.plates
if len(input_plates) > 1:
raise NotImplementedError
if len(output_plates) == 0:
raise ValueError("No output plate found")
if len(output_plates) == 1:
if not self.check_multi_output_plate_compatibility(input_plates, output_plates[0]):
raise IncompatiblePlatesError("Parent plate does not match input plate")
factor = MultiOutputFactor(tool=tool, source_node=source, splitting_node=splitting_node, sink_node=sink,
input_plate=input_plates[0] if input_plates else None,
output_plates=output_plates[0])
else:
# The output plates should be the same as the input plates, except for one
# additional plate. Since we're currently only supporting one input plate,
# we can safely assume that there is a single matching plate.
# Finally, note that the output plate must either have no parents
# (i.e. it is at the root of the tree), or the parent plate is somewhere
# in the input plate's ancestry
if len(output_plates) > 2:
raise NotImplementedError
if len(input_plates) != 1:
raise IncompatiblePlatesError("Require an input plate to match all but one of the output plates")
if output_plates[0] == input_plates[0]:
# Found a match, so the output plate should be the other plate
output_plate = output_plates[1]
else:
if output_plates[1].plate_id != input_plates[0].plate_id:
raise IncompatiblePlatesError("Require an input plate to match all but one of the output plates")
output_plate = output_plates[0]
# Swap them round so the new plate is the last plate - this is required by the factor
output_plates[1], output_plates[0] = output_plates[0], output_plates[1]
if not output_plate.is_root:
# We need to walk up the input plate's parent tree
match = False
parent = input_plates[0].parent
while parent is not None:
if parent.plate_id == output_plate.parent.plate_id:
match = True
break
parent = parent.parent
if not match:
raise IncompatiblePlatesError("Require an input plate to match all but one of the output plates")
factor = MultiOutputFactor(
tool=tool, source_node=source, sink_node=sink,
splitting_node=splitting_node, input_plate=input_plates[0], output_plates=output_plates)
self._add_factor(factor)
return factor |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:to_dict; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:tool_long_names; 7, True; 8, block; 8, 9; 8, 11; 8, 29; 8, 84; 8, 220; 8, 231; 9, expression_statement; 9, 10; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:d; 14, call; 14, 15; 14, 16; 15, identifier:dict; 16, argument_list; 16, 17; 16, 20; 16, 23; 17, keyword_argument; 17, 18; 17, 19; 18, identifier:nodes; 19, list:[]; 20, keyword_argument; 20, 21; 20, 22; 21, identifier:factors; 22, list:[]; 23, keyword_argument; 23, 24; 23, 25; 24, identifier:plates; 25, call; 25, 26; 25, 27; 26, identifier:defaultdict; 27, argument_list; 27, 28; 28, identifier:list; 29, for_statement; 29, 30; 29, 31; 29, 34; 30, identifier:node; 31, attribute; 31, 32; 31, 33; 32, identifier:self; 33, identifier:nodes; 34, block; 34, 35; 34, 45; 34, 57; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:node_id; 38, attribute; 38, 39; 38, 44; 39, subscript; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:self; 42, identifier:nodes; 43, identifier:node; 44, identifier:node_id; 45, expression_statement; 45, 46; 46, call; 46, 47; 46, 52; 47, attribute; 47, 48; 47, 51; 48, subscript; 48, 49; 48, 50; 49, identifier:d; 50, string:'nodes'; 51, identifier:append; 52, argument_list; 52, 53; 53, dictionary; 53, 54; 54, pair; 54, 55; 54, 56; 55, string:'id'; 56, identifier:node_id; 57, for_statement; 57, 58; 57, 59; 57, 66; 58, identifier:plate_id; 59, attribute; 59, 60; 59, 65; 60, subscript; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:self; 63, identifier:nodes; 64, identifier:node; 65, identifier:plate_ids; 66, block; 66, 67; 67, expression_statement; 67, 68; 68, call; 68, 69; 68, 76; 69, attribute; 69, 70; 69, 75; 70, subscript; 70, 71; 70, 74; 71, subscript; 71, 72; 71, 73; 72, identifier:d; 73, string:'plates'; 74, identifier:plate_id; 75, identifier:append; 76, argument_list; 76, 77; 77, dictionary; 77, 78; 77, 81; 78, pair; 78, 79; 78, 80; 79, string:'id'; 80, identifier:node_id; 81, pair; 81, 82; 81, 83; 82, string:'type'; 83, string:'node'; 84, for_statement; 84, 85; 84, 86; 84, 89; 85, identifier:factor; 86, attribute; 86, 87; 86, 88; 87, identifier:self; 88, identifier:factors; 89, block; 89, 90; 89, 106; 89, 143; 89, 165; 90, expression_statement; 90, 91; 91, assignment; 91, 92; 91, 93; 92, identifier:tool; 93, conditional_expression:if; 93, 94; 93, 100; 93, 101; 94, call; 94, 95; 94, 96; 95, identifier:str; 96, argument_list; 96, 97; 97, attribute; 97, 98; 97, 99; 98, identifier:factor; 99, identifier:tool; 100, identifier:tool_long_names; 101, attribute; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:factor; 104, identifier:tool; 105, identifier:name; 106, try_statement; 106, 107; 106, 120; 107, block; 107, 108; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:sources; 111, list_comprehension; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:s; 114, identifier:node_id; 115, for_in_clause; 115, 116; 115, 117; 116, identifier:s; 117, attribute; 117, 118; 117, 119; 118, identifier:factor; 119, identifier:sources; 120, except_clause; 120, 121; 120, 122; 121, identifier:AttributeError; 122, block; 122, 123; 123, if_statement; 123, 124; 123, 127; 123, 137; 124, attribute; 124, 125; 124, 126; 125, identifier:factor; 126, identifier:source; 127, block; 127, 128; 128, expression_statement; 128, 129; 129, assignment; 129, 130; 129, 131; 130, identifier:sources; 131, list:[factor.source.node_id]; 131, 132; 132, attribute; 132, 133; 132, 136; 133, attribute; 133, 134; 133, 135; 134, identifier:factor; 135, identifier:source; 136, identifier:node_id; 137, else_clause; 137, 138; 138, block; 138, 139; 139, expression_statement; 139, 140; 140, assignment; 140, 141; 140, 142; 141, identifier:sources; 142, list:[]; 143, expression_statement; 143, 144; 144, call; 144, 145; 144, 150; 145, attribute; 145, 146; 145, 149; 146, subscript; 146, 147; 146, 148; 147, identifier:d; 148, string:'factors'; 149, identifier:append; 150, argument_list; 150, 151; 151, dictionary; 151, 152; 151, 155; 151, 158; 152, pair; 152, 153; 152, 154; 153, string:'id'; 154, identifier:tool; 155, pair; 155, 156; 155, 157; 156, string:'sources'; 157, identifier:sources; 158, pair; 158, 159; 158, 160; 159, string:'sink'; 160, attribute; 160, 161; 160, 164; 161, attribute; 161, 162; 161, 163; 162, identifier:factor; 163, identifier:sink; 164, identifier:node_id; 165, try_statement; 165, 166; 165, 216; 166, block; 166, 167; 167, if_statement; 167, 168; 167, 171; 167, 197; 168, attribute; 168, 169; 168, 170; 169, identifier:factor; 170, identifier:plates; 171, block; 171, 172; 172, for_statement; 172, 173; 172, 174; 172, 177; 173, identifier:plate; 174, attribute; 174, 175; 174, 176; 175, identifier:factor; 176, identifier:plates; 177, block; 177, 178; 178, expression_statement; 178, 179; 179, call; 179, 180; 179, 189; 180, attribute; 180, 181; 180, 188; 181, subscript; 181, 182; 181, 185; 182, subscript; 182, 183; 182, 184; 183, identifier:d; 184, string:'plates'; 185, attribute; 185, 186; 185, 187; 186, identifier:plate; 187, identifier:plate_id; 188, identifier:append; 189, argument_list; 189, 190; 190, dictionary; 190, 191; 190, 194; 191, pair; 191, 192; 191, 193; 192, string:'id'; 193, identifier:tool; 194, pair; 194, 195; 194, 196; 195, string:'type'; 196, string:'factor'; 197, else_clause; 197, 198; 198, block; 198, 199; 199, expression_statement; 199, 200; 200, call; 200, 201; 200, 208; 201, attribute; 201, 202; 201, 207; 202, subscript; 202, 203; 202, 206; 203, subscript; 203, 204; 203, 205; 204, identifier:d; 205, string:'plates'; 206, string:'root'; 207, identifier:append; 208, argument_list; 208, 209; 209, dictionary; 209, 210; 209, 213; 210, pair; 210, 211; 210, 212; 211, string:'id'; 212, identifier:tool; 213, pair; 213, 214; 213, 215; 214, string:'type'; 215, string:'factor'; 216, except_clause; 216, 217; 216, 218; 217, identifier:AttributeError; 218, block; 218, 219; 219, pass_statement; 220, expression_statement; 220, 221; 221, assignment; 221, 222; 221, 225; 222, subscript; 222, 223; 222, 224; 223, identifier:d; 224, string:'plates'; 225, call; 225, 226; 225, 227; 226, identifier:dict; 227, argument_list; 227, 228; 228, subscript; 228, 229; 228, 230; 229, identifier:d; 230, string:'plates'; 231, return_statement; 231, 232; 232, identifier:d | def to_dict(self, tool_long_names=True):
"""
Get a representation of the workflow as a dictionary for display purposes
:param tool_long_names: Indicates whether to use long names, such as
SplitterFromStream(element=None, use_mapping_keys_only=True)
or short names, such as
splitter_from_stream
:type tool_long_names: bool
:return: The dictionary of nodes, factors and plates
"""
d = dict(nodes=[], factors=[], plates=defaultdict(list))
for node in self.nodes:
node_id = self.nodes[node].node_id
d['nodes'].append({'id': node_id})
for plate_id in self.nodes[node].plate_ids:
d['plates'][plate_id].append({'id': node_id, 'type': 'node'})
for factor in self.factors:
tool = str(factor.tool) if tool_long_names else factor.tool.name
try:
sources = [s.node_id for s in factor.sources]
except AttributeError:
if factor.source:
sources = [factor.source.node_id]
else:
sources = []
d['factors'].append({
'id': tool,
'sources': sources,
'sink': factor.sink.node_id})
try:
if factor.plates:
for plate in factor.plates:
d['plates'][plate.plate_id].append({'id': tool, 'type': 'factor'})
else:
d['plates']['root'].append({'id': tool, 'type': 'factor'})
except AttributeError:
pass
d['plates'] = dict(d['plates'])
return d |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 13; 2, function_name:GenericPump; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 4, identifier:filenames; 5, default_parameter; 5, 6; 5, 7; 6, identifier:use_jppy; 7, False; 8, default_parameter; 8, 9; 8, 10; 9, identifier:name; 10, string:"GenericPump"; 11, dictionary_splat_pattern; 11, 12; 12, identifier:kwargs; 13, block; 13, 14; 13, 16; 13, 28; 13, 50; 13, 69; 13, 89; 13, 98; 13, 120; 13, 142; 13, 160; 13, 209; 13, 221; 14, expression_statement; 14, 15; 15, comment; 16, if_statement; 16, 17; 16, 22; 17, call; 17, 18; 17, 19; 18, identifier:isinstance; 19, argument_list; 19, 20; 19, 21; 20, identifier:filenames; 21, identifier:str; 22, block; 22, 23; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:filenames; 26, list:[filenames]; 26, 27; 27, identifier:filenames; 28, try_statement; 28, 29; 28, 35; 29, block; 29, 30; 30, expression_statement; 30, 31; 31, call; 31, 32; 31, 33; 32, identifier:iter; 33, argument_list; 33, 34; 34, identifier:filenames; 35, except_clause; 35, 36; 35, 37; 36, identifier:TypeError; 37, block; 37, 38; 37, 45; 38, expression_statement; 38, 39; 39, call; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:log; 42, identifier:critical; 43, argument_list; 43, 44; 44, string:"Don't know how to iterate through filenames."; 45, raise_statement; 45, 46; 46, call; 46, 47; 46, 48; 47, identifier:TypeError; 48, argument_list; 48, 49; 49, string:"Invalid filenames."; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:extensions; 53, call; 53, 54; 53, 55; 54, identifier:set; 55, generator_expression; 55, 56; 55, 66; 56, subscript; 56, 57; 56, 65; 57, call; 57, 58; 57, 63; 58, attribute; 58, 59; 58, 62; 59, attribute; 59, 60; 59, 61; 60, identifier:os; 61, identifier:path; 62, identifier:splitext; 63, argument_list; 63, 64; 64, identifier:fn; 65, integer:1; 66, for_in_clause; 66, 67; 66, 68; 67, identifier:fn; 68, identifier:filenames; 69, if_statement; 69, 70; 69, 76; 70, comparison_operator:>; 70, 71; 70, 75; 71, call; 71, 72; 71, 73; 72, identifier:len; 73, argument_list; 73, 74; 74, identifier:extensions; 75, integer:1; 76, block; 76, 77; 76, 84; 77, expression_statement; 77, 78; 78, call; 78, 79; 78, 82; 79, attribute; 79, 80; 79, 81; 80, identifier:log; 81, identifier:critical; 82, argument_list; 82, 83; 83, string:"Mixed filetypes, please use only files of the same type"; 84, raise_statement; 84, 85; 85, call; 85, 86; 85, 87; 86, identifier:IOError; 87, argument_list; 87, 88; 88, string:"Mixed filetypes."; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:extension; 92, subscript; 92, 93; 92, 97; 93, call; 93, 94; 93, 95; 94, identifier:list; 95, argument_list; 95, 96; 96, identifier:extensions; 97, integer:0; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:io; 101, dictionary; 101, 102; 101, 105; 101, 108; 101, 114; 101, 117; 102, pair; 102, 103; 102, 104; 103, string:'.evt'; 104, identifier:EvtPump; 105, pair; 105, 106; 105, 107; 106, string:'.h5'; 107, identifier:HDF5Pump; 108, pair; 108, 109; 108, 110; 109, string:'.root'; 110, conditional_expression:if; 110, 111; 110, 112; 110, 113; 111, identifier:EventPump; 112, identifier:use_jppy; 113, identifier:AanetPump; 114, pair; 114, 115; 114, 116; 115, string:'.dat'; 116, identifier:DAQPump; 117, pair; 117, 118; 117, 119; 118, string:'.dqd'; 119, identifier:CLBPump; 120, if_statement; 120, 121; 120, 124; 121, comparison_operator:not; 121, 122; 121, 123; 122, identifier:extension; 123, identifier:io; 124, block; 124, 125; 124, 137; 125, expression_statement; 125, 126; 126, call; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:log; 129, identifier:critical; 130, argument_list; 130, 131; 131, call; 131, 132; 131, 135; 132, attribute; 132, 133; 132, 134; 133, string:"No pump found for file extension '{0}'"; 134, identifier:format; 135, argument_list; 135, 136; 136, identifier:extension; 137, raise_statement; 137, 138; 138, call; 138, 139; 138, 140; 139, identifier:ValueError; 140, argument_list; 140, 141; 141, string:"Unknown filetype"; 142, expression_statement; 142, 143; 143, assignment; 143, 144; 143, 145; 144, identifier:missing_files; 145, list_comprehension; 145, 146; 145, 147; 145, 150; 146, identifier:fn; 147, for_in_clause; 147, 148; 147, 149; 148, identifier:fn; 149, identifier:filenames; 150, if_clause; 150, 151; 151, not_operator; 151, 152; 152, call; 152, 153; 152, 158; 153, attribute; 153, 154; 153, 157; 154, attribute; 154, 155; 154, 156; 155, identifier:os; 156, identifier:path; 157, identifier:exists; 158, argument_list; 158, 159; 159, identifier:fn; 160, if_statement; 160, 161; 160, 162; 161, identifier:missing_files; 162, block; 162, 163; 163, if_statement; 163, 164; 163, 173; 163, 190; 164, comparison_operator:==; 164, 165; 164, 169; 165, call; 165, 166; 165, 167; 166, identifier:len; 167, argument_list; 167, 168; 168, identifier:missing_files; 169, call; 169, 170; 169, 171; 170, identifier:len; 171, argument_list; 171, 172; 172, identifier:filenames; 173, block; 173, 174; 173, 178; 173, 185; 174, expression_statement; 174, 175; 175, assignment; 175, 176; 175, 177; 176, identifier:message; 177, string:"None of the given files could be found."; 178, expression_statement; 178, 179; 179, call; 179, 180; 179, 183; 180, attribute; 180, 181; 180, 182; 181, identifier:log; 182, identifier:critical; 183, argument_list; 183, 184; 184, identifier:message; 185, raise_statement; 185, 186; 186, call; 186, 187; 186, 188; 187, identifier:SystemExit; 188, argument_list; 188, 189; 189, identifier:message; 190, else_clause; 190, 191; 191, block; 191, 192; 192, expression_statement; 192, 193; 193, call; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:log; 196, identifier:warning; 197, argument_list; 197, 198; 198, call; 198, 199; 198, 202; 199, attribute; 199, 200; 199, 201; 200, string:"The following files are missing and ignored: {}"; 201, identifier:format; 202, argument_list; 202, 203; 203, call; 203, 204; 203, 207; 204, attribute; 204, 205; 204, 206; 205, string:', '; 206, identifier:join; 207, argument_list; 207, 208; 208, identifier:missing_files; 209, expression_statement; 209, 210; 210, assignment; 210, 211; 210, 212; 211, identifier:input_files; 212, binary_operator:-; 212, 213; 212, 217; 213, call; 213, 214; 213, 215; 214, identifier:set; 215, argument_list; 215, 216; 216, identifier:filenames; 217, call; 217, 218; 217, 219; 218, identifier:set; 219, argument_list; 219, 220; 220, identifier:missing_files; 221, if_statement; 221, 222; 221, 228; 221, 245; 222, comparison_operator:==; 222, 223; 222, 227; 223, call; 223, 224; 223, 225; 224, identifier:len; 225, argument_list; 225, 226; 226, identifier:input_files; 227, integer:1; 228, block; 228, 229; 229, return_statement; 229, 230; 230, call; 230, 231; 230, 234; 231, subscript; 231, 232; 231, 233; 232, identifier:io; 233, identifier:extension; 234, argument_list; 234, 235; 234, 240; 234, 243; 235, keyword_argument; 235, 236; 235, 237; 236, identifier:filename; 237, subscript; 237, 238; 237, 239; 238, identifier:filenames; 239, integer:0; 240, keyword_argument; 240, 241; 240, 242; 241, identifier:name; 242, identifier:name; 243, dictionary_splat; 243, 244; 244, identifier:kwargs; 245, else_clause; 245, 246; 246, block; 246, 247; 247, return_statement; 247, 248; 248, call; 248, 249; 248, 252; 249, subscript; 249, 250; 249, 251; 250, identifier:io; 251, identifier:extension; 252, argument_list; 252, 253; 252, 256; 252, 259; 253, keyword_argument; 253, 254; 253, 255; 254, identifier:filenames; 255, identifier:filenames; 256, keyword_argument; 256, 257; 256, 258; 257, identifier:name; 258, identifier:name; 259, dictionary_splat; 259, 260; 260, identifier:kwargs | def GenericPump(filenames, use_jppy=False, name="GenericPump", **kwargs):
"""A generic pump which utilises the appropriate pump."""
if isinstance(filenames, str):
filenames = [filenames]
try:
iter(filenames)
except TypeError:
log.critical("Don't know how to iterate through filenames.")
raise TypeError("Invalid filenames.")
extensions = set(os.path.splitext(fn)[1] for fn in filenames)
if len(extensions) > 1:
log.critical("Mixed filetypes, please use only files of the same type")
raise IOError("Mixed filetypes.")
extension = list(extensions)[0]
io = {
'.evt': EvtPump,
'.h5': HDF5Pump,
'.root': EventPump if use_jppy else AanetPump,
'.dat': DAQPump,
'.dqd': CLBPump,
}
if extension not in io:
log.critical(
"No pump found for file extension '{0}'".format(extension)
)
raise ValueError("Unknown filetype")
missing_files = [fn for fn in filenames if not os.path.exists(fn)]
if missing_files:
if len(missing_files) == len(filenames):
message = "None of the given files could be found."
log.critical(message)
raise SystemExit(message)
else:
log.warning(
"The following files are missing and ignored: {}".format(
', '.join(missing_files)
)
)
input_files = set(filenames) - set(missing_files)
if len(input_files) == 1:
return io[extension](filename=filenames[0], name=name, **kwargs)
else:
return io[extension](filenames=filenames, name=name, **kwargs) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 10; 2, function_name:get_sources; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 4, identifier:self; 5, identifier:plate; 6, identifier:plate_value; 7, default_parameter; 7, 8; 7, 9; 8, identifier:sources; 9, None; 10, block; 10, 11; 10, 13; 10, 22; 10, 89; 10, 127; 10, 128; 11, expression_statement; 11, 12; 12, comment; 13, if_statement; 13, 14; 13, 17; 14, comparison_operator:is; 14, 15; 14, 16; 15, identifier:sources; 16, None; 17, block; 17, 18; 18, expression_statement; 18, 19; 19, assignment; 19, 20; 19, 21; 20, identifier:sources; 21, list:[]; 22, if_statement; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:self; 25, identifier:sources; 26, block; 26, 27; 27, for_statement; 27, 28; 27, 31; 27, 37; 28, pattern_list; 28, 29; 28, 30; 29, identifier:si; 30, identifier:source; 31, call; 31, 32; 31, 33; 32, identifier:enumerate; 33, argument_list; 33, 34; 34, attribute; 34, 35; 34, 36; 35, identifier:self; 36, identifier:sources; 37, block; 37, 38; 38, if_statement; 38, 39; 38, 53; 38, 65; 38, 83; 39, boolean_operator:and; 39, 40; 39, 48; 40, comparison_operator:==; 40, 41; 40, 47; 41, call; 41, 42; 41, 43; 42, identifier:len; 43, argument_list; 43, 44; 44, attribute; 44, 45; 44, 46; 45, identifier:source; 46, identifier:streams; 47, integer:1; 48, comparison_operator:in; 48, 49; 48, 50; 49, None; 50, attribute; 50, 51; 50, 52; 51, identifier:source; 52, identifier:streams; 53, block; 53, 54; 54, expression_statement; 54, 55; 55, call; 55, 56; 55, 59; 56, attribute; 56, 57; 56, 58; 57, identifier:sources; 58, identifier:append; 59, argument_list; 59, 60; 60, subscript; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:source; 63, identifier:streams; 64, None; 65, elif_clause; 65, 66; 65, 71; 66, comparison_operator:in; 66, 67; 66, 68; 67, identifier:plate_value; 68, attribute; 68, 69; 68, 70; 69, identifier:source; 70, identifier:streams; 71, block; 71, 72; 72, expression_statement; 72, 73; 73, call; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:sources; 76, identifier:append; 77, argument_list; 77, 78; 78, subscript; 78, 79; 78, 82; 79, attribute; 79, 80; 79, 81; 80, identifier:source; 81, identifier:streams; 82, identifier:plate_value; 83, else_clause; 83, 84; 83, 85; 83, 86; 83, 87; 84, comment; 85, comment; 86, comment; 87, block; 87, 88; 88, pass_statement; 89, if_statement; 89, 90; 89, 94; 89, 95; 90, not_operator; 90, 91; 91, attribute; 91, 92; 91, 93; 92, identifier:plate; 93, identifier:is_root; 94, comment; 95, block; 95, 96; 95, 114; 96, expression_statement; 96, 97; 97, assignment; 97, 98; 97, 99; 98, identifier:parent_plate_value; 99, call; 99, 100; 99, 101; 100, identifier:tuple; 101, generator_expression; 101, 102; 101, 103; 101, 106; 102, identifier:pv; 103, for_in_clause; 103, 104; 103, 105; 104, identifier:pv; 105, identifier:plate_value; 106, if_clause; 106, 107; 107, comparison_operator:!=; 107, 108; 107, 111; 108, subscript; 108, 109; 108, 110; 109, identifier:pv; 110, integer:0; 111, attribute; 111, 112; 111, 113; 112, identifier:plate; 113, identifier:meta_data_id; 114, expression_statement; 114, 115; 115, assignment; 115, 116; 115, 117; 116, identifier:sources; 117, call; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, identifier:self; 120, identifier:get_sources; 121, argument_list; 121, 122; 121, 125; 121, 126; 122, attribute; 122, 123; 122, 124; 123, identifier:plate; 124, identifier:parent; 125, identifier:parent_plate_value; 126, identifier:sources; 127, comment; 128, return_statement; 128, 129; 129, identifier:sources | def get_sources(self, plate, plate_value, sources=None):
"""
Gets the source streams for a given plate value on a plate.
Also populates with source streams that are valid for the parent plates of this plate,
with the appropriate meta-data for the parent plate.
:param plate: The plate being operated on
:param plate_value: The specific plate value of interest
:param sources: The currently found sources (for recursion)
:return: The appropriate source streams
:type plate: Plate
:type plate_value: tuple
:type sources: list[Stream] | None
"""
if sources is None:
sources = []
if self.sources:
for si, source in enumerate(self.sources):
if len(source.streams) == 1 and None in source.streams:
sources.append(source.streams[None])
elif plate_value in source.streams:
sources.append(source.streams[plate_value])
else:
# # TODO - determine whether this should raise an exception or not, or even log a warning
# logging.warn("{} with value {} not valid for source {}"
# .format(plate, plate_value, source))
pass
if not plate.is_root:
# Populate with sources defined on parent plate
parent_plate_value = tuple(pv for pv in plate_value if pv[0] != plate.meta_data_id)
sources = self.get_sources(plate.parent, parent_plate_value, sources)
# sources.extend(self.get_global_sources())
return sources |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:get_splitting_stream; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:input_plate_value; 6, block; 6, 7; 6, 9; 6, 17; 6, 38; 6, 62; 6, 63; 6, 85; 6, 95; 6, 262; 7, expression_statement; 7, 8; 8, comment; 9, if_statement; 9, 10; 9, 14; 10, not_operator; 10, 11; 11, attribute; 11, 12; 11, 13; 12, identifier:self; 13, identifier:splitting_node; 14, block; 14, 15; 15, return_statement; 15, 16; 16, None; 17, if_statement; 17, 18; 17, 28; 17, 29; 18, comparison_operator:==; 18, 19; 18, 27; 19, call; 19, 20; 19, 21; 20, identifier:len; 21, argument_list; 21, 22; 22, attribute; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:self; 25, identifier:splitting_node; 26, identifier:plates; 27, integer:0; 28, comment; 29, block; 29, 30; 30, return_statement; 30, 31; 31, subscript; 31, 32; 31, 37; 32, attribute; 32, 33; 32, 36; 33, attribute; 33, 34; 33, 35; 34, identifier:self; 35, identifier:splitting_node; 36, identifier:streams; 37, None; 38, if_statement; 38, 39; 38, 49; 39, comparison_operator:>; 39, 40; 39, 48; 40, call; 40, 41; 40, 42; 41, identifier:len; 42, argument_list; 42, 43; 43, attribute; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:self; 46, identifier:splitting_node; 47, identifier:plates; 48, integer:1; 49, block; 49, 50; 50, raise_statement; 50, 51; 51, call; 51, 52; 51, 53; 52, identifier:ValueError; 53, argument_list; 53, 54; 54, call; 54, 55; 54, 58; 55, attribute; 55, 56; 55, 57; 56, string:"Splitting node cannot live on multiple plates for factor {}"; 57, identifier:format; 58, argument_list; 58, 59; 59, attribute; 59, 60; 59, 61; 60, identifier:self; 61, identifier:factor_id; 62, comment; 63, if_statement; 63, 64; 63, 79; 64, boolean_operator:and; 64, 65; 64, 69; 65, not_operator; 65, 66; 66, attribute; 66, 67; 66, 68; 67, identifier:self; 68, identifier:input_plate; 69, comparison_operator:>; 69, 70; 69, 78; 70, call; 70, 71; 70, 72; 71, identifier:len; 72, argument_list; 72, 73; 73, attribute; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:self; 76, identifier:splitting_node; 77, identifier:plates; 78, integer:0; 79, block; 79, 80; 80, raise_statement; 80, 81; 81, call; 81, 82; 81, 83; 82, identifier:ValueError; 83, argument_list; 83, 84; 84, string:"Splitting node cannot live on a plate if there is no input plate"; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 88; 87, identifier:splitting_plate; 88, subscript; 88, 89; 88, 94; 89, attribute; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:self; 92, identifier:splitting_node; 93, identifier:plates; 94, integer:0; 95, if_statement; 95, 96; 95, 101; 95, 102; 95, 113; 96, comparison_operator:==; 96, 97; 96, 100; 97, attribute; 97, 98; 97, 99; 98, identifier:self; 99, identifier:input_plate; 100, identifier:splitting_plate; 101, comment; 102, block; 102, 103; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:splitting_stream; 106, subscript; 106, 107; 106, 112; 107, attribute; 107, 108; 107, 111; 108, attribute; 108, 109; 108, 110; 109, identifier:self; 110, identifier:splitting_node; 111, identifier:streams; 112, identifier:input_plate_value; 113, else_clause; 113, 114; 113, 115; 114, comment; 115, block; 115, 116; 116, if_statement; 116, 117; 116, 125; 116, 176; 116, 177; 116, 238; 117, call; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, identifier:splitting_plate; 120, identifier:is_child; 121, argument_list; 121, 122; 122, attribute; 122, 123; 122, 124; 123, identifier:self; 124, identifier:input_plate; 125, block; 125, 126; 125, 151; 125, 164; 126, expression_statement; 126, 127; 127, assignment; 127, 128; 127, 129; 128, identifier:ppv; 129, call; 129, 130; 129, 131; 130, identifier:filter; 131, argument_list; 131, 132; 131, 144; 132, lambda; 132, 133; 132, 135; 133, lambda_parameters; 133, 134; 134, identifier:x; 135, call; 135, 136; 135, 137; 136, identifier:all; 137, generator_expression; 137, 138; 137, 141; 138, comparison_operator:in; 138, 139; 138, 140; 139, identifier:p; 140, identifier:input_plate_value; 141, for_in_clause; 141, 142; 141, 143; 142, identifier:p; 143, identifier:x; 144, attribute; 144, 145; 144, 150; 145, attribute; 145, 146; 145, 149; 146, attribute; 146, 147; 146, 148; 147, identifier:self; 148, identifier:input_plate; 149, identifier:parent; 150, identifier:values; 151, if_statement; 151, 152; 151, 158; 152, comparison_operator:!=; 152, 153; 152, 157; 153, call; 153, 154; 153, 155; 154, identifier:len; 155, argument_list; 155, 156; 156, identifier:ppv; 157, integer:1; 158, block; 158, 159; 159, raise_statement; 159, 160; 160, call; 160, 161; 160, 162; 161, identifier:ValueError; 162, argument_list; 162, 163; 163, string:"Parent plate value not found"; 164, expression_statement; 164, 165; 165, assignment; 165, 166; 165, 167; 166, identifier:splitting_stream; 167, subscript; 167, 168; 167, 173; 168, attribute; 168, 169; 168, 172; 169, attribute; 169, 170; 169, 171; 170, identifier:self; 171, identifier:splitting_node; 172, identifier:streams; 173, subscript; 173, 174; 173, 175; 174, identifier:ppv; 175, integer:0; 176, comment; 177, elif_clause; 177, 178; 177, 186; 177, 187; 177, 188; 177, 189; 178, call; 178, 179; 178, 182; 179, attribute; 179, 180; 179, 181; 180, identifier:splitting_plate; 181, identifier:is_descendant; 182, argument_list; 182, 183; 183, attribute; 183, 184; 183, 185; 184, identifier:self; 185, identifier:input_plate; 186, comment; 187, comment; 188, comment; 189, block; 189, 190; 189, 215; 189, 228; 190, expression_statement; 190, 191; 191, assignment; 191, 192; 191, 193; 192, identifier:ppv; 193, call; 193, 194; 193, 195; 194, identifier:filter; 195, argument_list; 195, 196; 195, 208; 196, lambda; 196, 197; 196, 199; 197, lambda_parameters; 197, 198; 198, identifier:x; 199, call; 199, 200; 199, 201; 200, identifier:all; 201, generator_expression; 201, 202; 201, 205; 202, comparison_operator:in; 202, 203; 202, 204; 203, identifier:p; 204, identifier:input_plate_value; 205, for_in_clause; 205, 206; 205, 207; 206, identifier:p; 207, identifier:x; 208, attribute; 208, 209; 208, 214; 209, attribute; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, identifier:self; 212, identifier:input_plate; 213, identifier:parent; 214, identifier:values; 215, if_statement; 215, 216; 215, 222; 216, comparison_operator:!=; 216, 217; 216, 221; 217, call; 217, 218; 217, 219; 218, identifier:len; 219, argument_list; 219, 220; 220, identifier:ppv; 221, integer:1; 222, block; 222, 223; 223, raise_statement; 223, 224; 224, call; 224, 225; 224, 226; 225, identifier:ValueError; 226, argument_list; 226, 227; 227, string:"Parent plate value not found"; 228, expression_statement; 228, 229; 229, assignment; 229, 230; 229, 231; 230, identifier:splitting_stream; 231, subscript; 231, 232; 231, 237; 232, attribute; 232, 233; 232, 236; 233, attribute; 233, 234; 233, 235; 234, identifier:self; 235, identifier:splitting_node; 236, identifier:streams; 237, identifier:ppv; 238, else_clause; 238, 239; 239, block; 239, 240; 240, raise_statement; 240, 241; 241, call; 241, 242; 241, 243; 242, identifier:IncompatiblePlatesError; 243, argument_list; 243, 244; 244, call; 244, 245; 244, 248; 245, attribute; 245, 246; 245, 247; 246, string:"Splitting node plate {} does not match input plate {} for factor {}"; 247, identifier:format; 248, argument_list; 248, 249; 248, 252; 248, 259; 249, attribute; 249, 250; 249, 251; 250, identifier:self; 251, identifier:input_plate; 252, subscript; 252, 253; 252, 258; 253, attribute; 253, 254; 253, 257; 254, attribute; 254, 255; 254, 256; 255, identifier:self; 256, identifier:splitting_node; 257, identifier:plates; 258, integer:0; 259, attribute; 259, 260; 259, 261; 260, identifier:self; 261, identifier:factor_id; 262, return_statement; 262, 263; 263, identifier:splitting_stream | def get_splitting_stream(self, input_plate_value):
"""
Get the splitting stream
:param input_plate_value: The input plate value
:return: The splitting stream
"""
if not self.splitting_node:
return None
if len(self.splitting_node.plates) == 0:
# Use global plate value
return self.splitting_node.streams[None]
if len(self.splitting_node.plates) > 1:
raise ValueError("Splitting node cannot live on multiple plates for factor {}"
.format(self.factor_id))
# now len(self.splitting_node.plates) == 1:
if not self.input_plate and len(self.splitting_node.plates) > 0:
raise ValueError("Splitting node cannot live on a plate if there is no input plate")
splitting_plate = self.splitting_node.plates[0]
if self.input_plate == splitting_plate:
# Use matching plate value
splitting_stream = self.splitting_node.streams[input_plate_value]
else:
# First check if it's a direct child
if splitting_plate.is_child(self.input_plate):
ppv = filter(lambda x: all(p in input_plate_value for p in x), self.input_plate.parent.values)
if len(ppv) != 1:
raise ValueError("Parent plate value not found")
splitting_stream = self.splitting_node.streams[ppv[0]]
# Then more generally if it's a descendant
elif splitting_plate.is_descendant(self.input_plate):
# Here we need to find the splitting plate value that is valid for the
# current input plate value
# TODO: This needs checking - is the logic still the same as for the case above?
ppv = filter(lambda x: all(p in input_plate_value for p in x), self.input_plate.parent.values)
if len(ppv) != 1:
raise ValueError("Parent plate value not found")
splitting_stream = self.splitting_node.streams[ppv]
else:
raise IncompatiblePlatesError(
"Splitting node plate {} does not match input plate {} for factor {}"
.format(self.input_plate, self.splitting_node.plates[0], self.factor_id))
return splitting_stream |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 16; 2, function_name:iter_cognates; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 4, identifier:dataset; 5, default_parameter; 5, 6; 5, 7; 6, identifier:column; 7, string:'Segments'; 8, default_parameter; 8, 9; 8, 10; 9, identifier:method; 10, string:'turchin'; 11, default_parameter; 11, 12; 11, 13; 12, identifier:threshold; 13, float:0.5; 14, dictionary_splat_pattern; 14, 15; 15, identifier:kw; 16, block; 16, 17; 16, 19; 16, 123; 17, expression_statement; 17, 18; 18, comment; 19, if_statement; 19, 20; 19, 23; 20, comparison_operator:==; 20, 21; 20, 22; 21, identifier:method; 22, string:'turchin'; 23, block; 23, 24; 24, for_statement; 24, 25; 24, 26; 24, 31; 25, identifier:row; 26, subscript; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, identifier:dataset; 29, identifier:objects; 30, string:'FormTable'; 31, block; 31, 32; 31, 49; 31, 63; 31, 84; 31, 97; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:sounds; 35, call; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, string:''; 38, identifier:join; 39, argument_list; 39, 40; 40, call; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:lingpy; 43, identifier:tokens2class; 44, argument_list; 44, 45; 44, 48; 45, subscript; 45, 46; 45, 47; 46, identifier:row; 47, identifier:column; 48, string:'dolgo'; 49, if_statement; 49, 50; 49, 56; 50, call; 50, 51; 50, 54; 51, attribute; 51, 52; 51, 53; 52, identifier:sounds; 53, identifier:startswith; 54, argument_list; 54, 55; 55, string:'V'; 56, block; 56, 57; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 60; 59, identifier:sounds; 60, binary_operator:+; 60, 61; 60, 62; 61, string:'H'; 62, identifier:sounds; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:sounds; 66, call; 66, 67; 66, 70; 67, attribute; 67, 68; 67, 69; 68, string:'-'; 69, identifier:join; 70, argument_list; 70, 71; 71, subscript; 71, 72; 71, 81; 72, list_comprehension; 72, 73; 72, 74; 72, 77; 73, identifier:s; 74, for_in_clause; 74, 75; 74, 76; 75, identifier:s; 76, identifier:sounds; 77, if_clause; 77, 78; 78, comparison_operator:!=; 78, 79; 78, 80; 79, identifier:s; 80, string:'V'; 81, slice; 81, 82; 81, 83; 82, colon; 83, integer:2; 84, expression_statement; 84, 85; 85, assignment; 85, 86; 85, 87; 86, identifier:cogid; 87, binary_operator:+; 87, 88; 87, 96; 88, binary_operator:+; 88, 89; 88, 95; 89, call; 89, 90; 89, 91; 90, identifier:slug; 91, argument_list; 91, 92; 92, subscript; 92, 93; 92, 94; 93, identifier:row; 94, string:'Parameter_ID'; 95, string:'-'; 96, identifier:sounds; 97, if_statement; 97, 98; 97, 101; 98, comparison_operator:not; 98, 99; 98, 100; 99, string:'0'; 100, identifier:sounds; 101, block; 101, 102; 102, expression_statement; 102, 103; 103, yield; 103, 104; 104, call; 104, 105; 104, 106; 105, identifier:dict; 106, argument_list; 106, 107; 106, 112; 106, 117; 106, 120; 107, keyword_argument; 107, 108; 107, 109; 108, identifier:Form_ID; 109, subscript; 109, 110; 109, 111; 110, identifier:row; 111, string:'ID'; 112, keyword_argument; 112, 113; 112, 114; 113, identifier:Form; 114, subscript; 114, 115; 114, 116; 115, identifier:row; 116, string:'Value'; 117, keyword_argument; 117, 118; 117, 119; 118, identifier:Cognateset_ID; 119, identifier:cogid; 120, keyword_argument; 120, 121; 120, 122; 121, identifier:Cognate_Detection_Method; 122, string:'CMM'; 123, if_statement; 123, 124; 123, 129; 124, comparison_operator:in; 124, 125; 124, 126; 125, identifier:method; 126, list:['sca', 'lexstat']; 126, 127; 126, 128; 127, string:'sca'; 128, string:'lexstat'; 129, block; 129, 130; 129, 137; 129, 150; 129, 165; 130, expression_statement; 130, 131; 131, assignment; 131, 132; 131, 133; 132, identifier:lex; 133, call; 133, 134; 133, 135; 134, identifier:_cldf2lexstat; 135, argument_list; 135, 136; 136, identifier:dataset; 137, if_statement; 137, 138; 137, 141; 138, comparison_operator:==; 138, 139; 138, 140; 139, identifier:method; 140, string:'lexstat'; 141, block; 141, 142; 142, expression_statement; 142, 143; 143, call; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:lex; 146, identifier:get_scorer; 147, argument_list; 147, 148; 148, dictionary_splat; 148, 149; 149, identifier:kw; 150, expression_statement; 150, 151; 151, call; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:lex; 154, identifier:cluster; 155, argument_list; 155, 156; 155, 159; 155, 162; 156, keyword_argument; 156, 157; 156, 158; 157, identifier:method; 158, identifier:method; 159, keyword_argument; 159, 160; 159, 161; 160, identifier:threshold; 161, identifier:threshold; 162, keyword_argument; 162, 163; 162, 164; 163, identifier:ref; 164, string:'cogid'; 165, for_statement; 165, 166; 165, 167; 165, 168; 166, identifier:k; 167, identifier:lex; 168, block; 168, 169; 169, expression_statement; 169, 170; 170, yield; 170, 171; 171, call; 171, 172; 171, 173; 172, identifier:Cognate; 173, argument_list; 173, 174; 173, 180; 173, 186; 173, 192; 174, keyword_argument; 174, 175; 174, 176; 175, identifier:Form_ID; 176, subscript; 176, 177; 176, 178; 176, 179; 177, identifier:lex; 178, identifier:k; 179, string:'lid'; 180, keyword_argument; 180, 181; 180, 182; 181, identifier:Form; 182, subscript; 182, 183; 182, 184; 182, 185; 183, identifier:lex; 184, identifier:k; 185, string:'value'; 186, keyword_argument; 186, 187; 186, 188; 187, identifier:Cognateset_ID; 188, subscript; 188, 189; 188, 190; 188, 191; 189, identifier:lex; 190, identifier:k; 191, string:'cogid'; 192, keyword_argument; 192, 193; 192, 194; 193, identifier:Cognate_Detection_Method; 194, binary_operator:+; 194, 195; 194, 196; 195, identifier:method; 196, call; 196, 197; 196, 200; 197, attribute; 197, 198; 197, 199; 198, string:'-t{0:.2f}'; 199, identifier:format; 200, argument_list; 200, 201; 201, identifier:threshold | def iter_cognates(dataset, column='Segments', method='turchin', threshold=0.5, **kw):
"""
Compute cognates automatically for a given dataset.
"""
if method == 'turchin':
for row in dataset.objects['FormTable']:
sounds = ''.join(lingpy.tokens2class(row[column], 'dolgo'))
if sounds.startswith('V'):
sounds = 'H' + sounds
sounds = '-'.join([s for s in sounds if s != 'V'][:2])
cogid = slug(row['Parameter_ID']) + '-' + sounds
if '0' not in sounds:
yield dict(
Form_ID=row['ID'],
Form=row['Value'],
Cognateset_ID=cogid,
Cognate_Detection_Method='CMM')
if method in ['sca', 'lexstat']:
lex = _cldf2lexstat(dataset)
if method == 'lexstat':
lex.get_scorer(**kw)
lex.cluster(method=method, threshold=threshold, ref='cogid')
for k in lex:
yield Cognate(
Form_ID=lex[k, 'lid'],
Form=lex[k, 'value'],
Cognateset_ID=lex[k, 'cogid'],
Cognate_Detection_Method=method + '-t{0:.2f}'.format(threshold)) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:get_tool_class; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:tool; 6, block; 6, 7; 6, 9; 6, 41; 6, 45; 6, 46; 6, 110; 6, 120; 6, 121; 6, 129; 6, 139; 7, expression_statement; 7, 8; 8, comment; 9, if_statement; 9, 10; 9, 15; 9, 23; 9, 34; 10, call; 10, 11; 10, 12; 11, identifier:isinstance; 12, argument_list; 12, 13; 12, 14; 13, identifier:tool; 14, identifier:string_types; 15, block; 15, 16; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:tool_id; 19, call; 19, 20; 19, 21; 20, identifier:StreamId; 21, argument_list; 21, 22; 22, identifier:tool; 23, elif_clause; 23, 24; 23, 29; 24, call; 24, 25; 24, 26; 25, identifier:isinstance; 26, argument_list; 26, 27; 26, 28; 27, identifier:tool; 28, identifier:StreamId; 29, block; 29, 30; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:tool_id; 33, identifier:tool; 34, else_clause; 34, 35; 35, block; 35, 36; 36, raise_statement; 36, 37; 37, call; 37, 38; 37, 39; 38, identifier:TypeError; 39, argument_list; 39, 40; 40, identifier:tool; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:tool_stream_view; 44, None; 45, comment; 46, if_statement; 46, 47; 46, 52; 46, 72; 47, comparison_operator:in; 47, 48; 47, 49; 48, identifier:tool_id; 49, attribute; 49, 50; 49, 51; 50, identifier:self; 51, identifier:tools; 52, block; 52, 53; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:tool_stream_view; 56, call; 56, 57; 56, 64; 57, attribute; 57, 58; 57, 63; 58, subscript; 58, 59; 58, 62; 59, attribute; 59, 60; 59, 61; 60, identifier:self; 61, identifier:tools; 62, identifier:tool_id; 63, identifier:window; 64, argument_list; 64, 65; 65, tuple; 65, 66; 65, 67; 66, identifier:MIN_DATE; 67, attribute; 67, 68; 67, 71; 68, attribute; 68, 69; 68, 70; 69, identifier:self; 70, identifier:tools; 71, identifier:up_to_timestamp; 72, else_clause; 72, 73; 72, 74; 73, comment; 74, block; 74, 75; 75, for_statement; 75, 76; 75, 77; 75, 80; 76, identifier:tool_channel; 77, attribute; 77, 78; 77, 79; 78, identifier:self; 79, identifier:tool_channels; 80, block; 80, 81; 80, 89; 81, if_statement; 81, 82; 81, 87; 82, comparison_operator:==; 82, 83; 82, 84; 83, identifier:tool_channel; 84, attribute; 84, 85; 84, 86; 85, identifier:self; 86, identifier:tools; 87, block; 87, 88; 88, continue_statement; 89, if_statement; 89, 90; 89, 93; 89, 94; 90, comparison_operator:in; 90, 91; 90, 92; 91, identifier:tool_id; 92, identifier:tool_channel; 93, comment; 94, block; 94, 95; 95, expression_statement; 95, 96; 96, assignment; 96, 97; 96, 98; 97, identifier:tool_stream_view; 98, call; 98, 99; 98, 104; 99, attribute; 99, 100; 99, 103; 100, subscript; 100, 101; 100, 102; 101, identifier:tool_channel; 102, identifier:tool_id; 103, identifier:window; 104, argument_list; 104, 105; 105, tuple; 105, 106; 105, 107; 106, identifier:MIN_DATE; 107, attribute; 107, 108; 107, 109; 108, identifier:tool_channel; 109, identifier:up_to_timestamp; 110, if_statement; 110, 111; 110, 114; 111, comparison_operator:is; 111, 112; 111, 113; 112, identifier:tool_stream_view; 113, None; 114, block; 114, 115; 115, raise_statement; 115, 116; 116, call; 116, 117; 116, 118; 117, identifier:ToolNotFoundError; 118, argument_list; 118, 119; 119, identifier:tool; 120, comment; 121, expression_statement; 121, 122; 122, assignment; 122, 123; 122, 124; 123, identifier:last; 124, call; 124, 125; 124, 128; 125, attribute; 125, 126; 125, 127; 126, identifier:tool_stream_view; 127, identifier:last; 128, argument_list; 129, if_statement; 129, 130; 129, 133; 130, comparison_operator:is; 130, 131; 130, 132; 131, identifier:last; 132, None; 133, block; 133, 134; 134, raise_statement; 134, 135; 135, call; 135, 136; 135, 137; 136, identifier:ToolNotFoundError; 137, argument_list; 137, 138; 138, identifier:tool; 139, return_statement; 139, 140; 140, attribute; 140, 141; 140, 146; 141, call; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, identifier:tool_stream_view; 144, identifier:last; 145, argument_list; 146, identifier:value | def get_tool_class(self, tool):
"""
Gets the actual class which can then be instantiated with its parameters
:param tool: The tool name or id
:type tool: str | unicode | StreamId
:rtype: Tool | MultiOutputTool
:return: The tool class
"""
if isinstance(tool, string_types):
tool_id = StreamId(tool)
elif isinstance(tool, StreamId):
tool_id = tool
else:
raise TypeError(tool)
tool_stream_view = None
# Look in the main tool channel first
if tool_id in self.tools:
tool_stream_view = self.tools[tool_id].window((MIN_DATE, self.tools.up_to_timestamp))
else:
# Otherwise look through all the channels in the order they were defined
for tool_channel in self.tool_channels:
if tool_channel == self.tools:
continue
if tool_id in tool_channel:
# noinspection PyTypeChecker
tool_stream_view = tool_channel[tool_id].window((MIN_DATE, tool_channel.up_to_timestamp))
if tool_stream_view is None:
raise ToolNotFoundError(tool)
# TODO: Use tool versions - here we just take the latest one
last = tool_stream_view.last()
if last is None:
raise ToolNotFoundError(tool)
return tool_stream_view.last().value |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:pmt_angles; 3, parameters; 3, 4; 4, identifier:self; 5, block; 5, 6; 5, 8; 5, 47; 6, expression_statement; 6, 7; 7, comment; 8, if_statement; 8, 9; 8, 14; 9, comparison_operator:==; 9, 10; 9, 13; 10, attribute; 10, 11; 10, 12; 11, identifier:self; 12, identifier:_pmt_angles; 13, list:[]; 14, block; 14, 15; 14, 35; 15, expression_statement; 15, 16; 16, assignment; 16, 17; 16, 18; 17, identifier:mask; 18, binary_operator:&; 18, 19; 18, 27; 19, parenthesized_expression; 19, 20; 20, comparison_operator:==; 20, 21; 20, 26; 21, attribute; 21, 22; 21, 25; 22, attribute; 22, 23; 22, 24; 23, identifier:self; 24, identifier:pmts; 25, identifier:du; 26, integer:1; 27, parenthesized_expression; 27, 28; 28, comparison_operator:==; 28, 29; 28, 34; 29, attribute; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:self; 32, identifier:pmts; 33, identifier:floor; 34, integer:1; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 40; 37, attribute; 37, 38; 37, 39; 38, identifier:self; 39, identifier:_pmt_angles; 40, subscript; 40, 41; 40, 46; 41, attribute; 41, 42; 41, 45; 42, attribute; 42, 43; 42, 44; 43, identifier:self; 44, identifier:pmts; 45, identifier:dir; 46, identifier:mask; 47, return_statement; 47, 48; 48, attribute; 48, 49; 48, 50; 49, identifier:self; 50, identifier:_pmt_angles | def pmt_angles(self):
"""A list of PMT directions sorted by PMT channel, on DU-1, floor-1"""
if self._pmt_angles == []:
mask = (self.pmts.du == 1) & (self.pmts.floor == 1)
self._pmt_angles = self.pmts.dir[mask]
return self._pmt_angles |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:_get_point; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:profile; 6, identifier:point; 7, block; 7, 8; 7, 10; 7, 24; 8, expression_statement; 8, 9; 9, comment; 10, expression_statement; 10, 11; 11, assignment; 11, 12; 11, 13; 12, identifier:cur_points_z; 13, list_comprehension; 13, 14; 13, 19; 14, attribute; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:p; 17, identifier:location; 18, identifier:z; 19, for_in_clause; 19, 20; 19, 21; 20, identifier:p; 21, attribute; 21, 22; 21, 23; 22, identifier:profile; 23, identifier:elements; 24, try_statement; 24, 25; 24, 43; 25, block; 25, 26; 25, 37; 26, expression_statement; 26, 27; 27, assignment; 27, 28; 27, 29; 28, identifier:cur_idx; 29, call; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:cur_points_z; 32, identifier:index; 33, argument_list; 33, 34; 34, attribute; 34, 35; 34, 36; 35, identifier:point; 36, identifier:z; 37, return_statement; 37, 38; 38, subscript; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:profile; 41, identifier:elements; 42, identifier:cur_idx; 43, except_clause; 43, 44; 43, 45; 44, identifier:ValueError; 45, block; 45, 46; 45, 56; 45, 62; 45, 71; 45, 79; 45, 89; 46, expression_statement; 46, 47; 47, assignment; 47, 48; 47, 49; 48, identifier:new_idx; 49, call; 49, 50; 49, 51; 50, identifier:bisect_left; 51, argument_list; 51, 52; 51, 53; 52, identifier:cur_points_z; 53, attribute; 53, 54; 53, 55; 54, identifier:point; 55, identifier:z; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:new_point; 59, call; 59, 60; 59, 61; 60, identifier:Point; 61, argument_list; 62, expression_statement; 62, 63; 63, assignment; 63, 64; 63, 67; 64, attribute; 64, 65; 64, 66; 65, identifier:new_point; 66, identifier:location; 67, call; 67, 68; 67, 69; 68, identifier:sPoint; 69, argument_list; 69, 70; 70, identifier:point; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 76; 73, attribute; 73, 74; 73, 75; 74, identifier:new_point; 75, identifier:time; 76, attribute; 76, 77; 76, 78; 77, identifier:profile; 78, identifier:time; 79, expression_statement; 79, 80; 80, call; 80, 81; 80, 86; 81, attribute; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:profile; 84, identifier:elements; 85, identifier:insert; 86, argument_list; 86, 87; 86, 88; 87, identifier:new_idx; 88, identifier:new_point; 89, return_statement; 89, 90; 90, identifier:new_point | def _get_point(self, profile, point):
"""
Finds the given point in the profile, or adds it in sorted z order.
"""
cur_points_z = [p.location.z for p in profile.elements]
try:
cur_idx = cur_points_z.index(point.z)
return profile.elements[cur_idx]
except ValueError:
new_idx = bisect_left(cur_points_z, point.z)
new_point = Point()
new_point.location = sPoint(point)
new_point.time = profile.time
profile.elements.insert(new_idx, new_point)
return new_point |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:metadata_sorter; 3, parameters; 3, 4; 3, 5; 4, identifier:x; 5, identifier:y; 6, block; 6, 7; 6, 9; 6, 16; 7, expression_statement; 7, 8; 8, comment; 9, if_statement; 9, 10; 9, 13; 10, comparison_operator:==; 10, 11; 10, 12; 11, identifier:x; 12, identifier:y; 13, block; 13, 14; 14, return_statement; 14, 15; 15, integer:0; 16, if_statement; 16, 17; 16, 24; 16, 43; 16, 51; 16, 58; 17, boolean_operator:and; 17, 18; 17, 21; 18, comparison_operator:in; 18, 19; 18, 20; 19, identifier:x; 20, identifier:METADATA_SORTER_FIRST; 21, comparison_operator:in; 21, 22; 21, 23; 22, identifier:y; 23, identifier:METADATA_SORTER_FIRST; 24, block; 24, 25; 25, return_statement; 25, 26; 26, conditional_expression:if; 26, 27; 26, 29; 26, 42; 27, unary_operator:-; 27, 28; 28, integer:1; 29, comparison_operator:<; 29, 30; 29, 36; 30, call; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:METADATA_SORTER_FIRST; 33, identifier:index; 34, argument_list; 34, 35; 35, identifier:x; 36, call; 36, 37; 36, 40; 37, attribute; 37, 38; 37, 39; 38, identifier:METADATA_SORTER_FIRST; 39, identifier:index; 40, argument_list; 40, 41; 41, identifier:y; 42, integer:1; 43, elif_clause; 43, 44; 43, 47; 44, comparison_operator:in; 44, 45; 44, 46; 45, identifier:x; 46, identifier:METADATA_SORTER_FIRST; 47, block; 47, 48; 48, return_statement; 48, 49; 49, unary_operator:-; 49, 50; 50, integer:1; 51, elif_clause; 51, 52; 51, 55; 52, comparison_operator:in; 52, 53; 52, 54; 53, identifier:y; 54, identifier:METADATA_SORTER_FIRST; 55, block; 55, 56; 56, return_statement; 56, 57; 57, integer:1; 58, else_clause; 58, 59; 59, block; 59, 60; 60, if_statement; 60, 61; 60, 74; 60, 89; 60, 99; 60, 110; 61, boolean_operator:and; 61, 62; 61, 68; 62, call; 62, 63; 62, 66; 63, attribute; 63, 64; 63, 65; 64, identifier:x; 65, identifier:startswith; 66, argument_list; 66, 67; 67, string:'_'; 68, call; 68, 69; 68, 72; 69, attribute; 69, 70; 69, 71; 70, identifier:y; 71, identifier:startswith; 72, argument_list; 72, 73; 73, string:'_'; 74, block; 74, 75; 75, return_statement; 75, 76; 76, call; 76, 77; 76, 78; 77, identifier:cmp; 78, argument_list; 78, 79; 78, 84; 79, subscript; 79, 80; 79, 81; 80, identifier:x; 81, slice; 81, 82; 81, 83; 82, integer:1; 83, colon; 84, subscript; 84, 85; 84, 86; 85, identifier:y; 86, slice; 86, 87; 86, 88; 87, integer:1; 88, colon; 89, elif_clause; 89, 90; 89, 96; 90, call; 90, 91; 90, 94; 91, attribute; 91, 92; 91, 93; 92, identifier:x; 93, identifier:startswith; 94, argument_list; 94, 95; 95, string:'_'; 96, block; 96, 97; 97, return_statement; 97, 98; 98, integer:1; 99, elif_clause; 99, 100; 99, 106; 100, call; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:y; 103, identifier:startswith; 104, argument_list; 104, 105; 105, string:'_'; 106, block; 106, 107; 107, return_statement; 107, 108; 108, unary_operator:-; 108, 109; 109, integer:1; 110, else_clause; 110, 111; 111, block; 111, 112; 112, return_statement; 112, 113; 113, call; 113, 114; 113, 115; 114, identifier:cmp; 115, argument_list; 115, 116; 115, 117; 116, identifier:x; 117, identifier:y | def metadata_sorter(x, y):
""" Sort metadata keys by priority.
"""
if x == y:
return 0
if x in METADATA_SORTER_FIRST and y in METADATA_SORTER_FIRST:
return -1 if METADATA_SORTER_FIRST.index(x) < METADATA_SORTER_FIRST.index(y) else 1
elif x in METADATA_SORTER_FIRST:
return -1
elif y in METADATA_SORTER_FIRST:
return 1
else:
if x.startswith('_') and y.startswith('_'):
return cmp(x[1:], y[1:])
elif x.startswith('_'):
return 1
elif y.startswith('_'):
return -1
else:
return cmp(x, y) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:computeStrongestPaths; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:profile; 6, identifier:pairwisePreferences; 7, block; 7, 8; 7, 10; 7, 20; 7, 27; 7, 28; 7, 34; 7, 46; 7, 108; 7, 184; 8, expression_statement; 8, 9; 9, comment; 10, expression_statement; 10, 11; 11, assignment; 11, 12; 11, 13; 12, identifier:cands; 13, call; 13, 14; 13, 19; 14, attribute; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:profile; 17, identifier:candMap; 18, identifier:keys; 19, argument_list; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:numCands; 23, call; 23, 24; 23, 25; 24, identifier:len; 25, argument_list; 25, 26; 26, identifier:cands; 27, comment; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:strongestPaths; 31, call; 31, 32; 31, 33; 32, identifier:dict; 33, argument_list; 34, for_statement; 34, 35; 34, 36; 34, 37; 35, identifier:cand; 36, identifier:cands; 37, block; 37, 38; 38, expression_statement; 38, 39; 39, assignment; 39, 40; 39, 43; 40, subscript; 40, 41; 40, 42; 41, identifier:strongestPaths; 42, identifier:cand; 43, call; 43, 44; 43, 45; 44, identifier:dict; 45, argument_list; 46, for_statement; 46, 47; 46, 48; 46, 55; 47, identifier:i; 48, call; 48, 49; 48, 50; 49, identifier:range; 50, argument_list; 50, 51; 50, 52; 51, integer:1; 52, binary_operator:+; 52, 53; 52, 54; 53, identifier:numCands; 54, integer:1; 55, block; 55, 56; 56, for_statement; 56, 57; 56, 58; 56, 65; 57, identifier:j; 58, call; 58, 59; 58, 60; 59, identifier:range; 60, argument_list; 60, 61; 60, 62; 61, integer:1; 62, binary_operator:+; 62, 63; 62, 64; 63, identifier:numCands; 64, integer:1; 65, block; 65, 66; 65, 73; 66, if_statement; 66, 67; 66, 71; 67, parenthesized_expression; 67, 68; 68, comparison_operator:==; 68, 69; 68, 70; 69, identifier:i; 70, identifier:j; 71, block; 71, 72; 72, continue_statement; 73, if_statement; 73, 74; 73, 85; 73, 98; 74, comparison_operator:>; 74, 75; 74, 80; 75, subscript; 75, 76; 75, 79; 76, subscript; 76, 77; 76, 78; 77, identifier:pairwisePreferences; 78, identifier:i; 79, identifier:j; 80, subscript; 80, 81; 80, 84; 81, subscript; 81, 82; 81, 83; 82, identifier:pairwisePreferences; 83, identifier:j; 84, identifier:i; 85, block; 85, 86; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 93; 88, subscript; 88, 89; 88, 92; 89, subscript; 89, 90; 89, 91; 90, identifier:strongestPaths; 91, identifier:i; 92, identifier:j; 93, subscript; 93, 94; 93, 97; 94, subscript; 94, 95; 94, 96; 95, identifier:pairwisePreferences; 96, identifier:i; 97, identifier:j; 98, else_clause; 98, 99; 99, block; 99, 100; 100, expression_statement; 100, 101; 101, assignment; 101, 102; 101, 107; 102, subscript; 102, 103; 102, 106; 103, subscript; 103, 104; 103, 105; 104, identifier:strongestPaths; 105, identifier:i; 106, identifier:j; 107, integer:0; 108, for_statement; 108, 109; 108, 110; 108, 117; 109, identifier:i; 110, call; 110, 111; 110, 112; 111, identifier:range; 112, argument_list; 112, 113; 112, 114; 113, integer:1; 114, binary_operator:+; 114, 115; 114, 116; 115, identifier:numCands; 116, integer:1; 117, block; 117, 118; 118, for_statement; 118, 119; 118, 120; 118, 127; 119, identifier:j; 120, call; 120, 121; 120, 122; 121, identifier:range; 122, argument_list; 122, 123; 122, 124; 123, integer:1; 124, binary_operator:+; 124, 125; 124, 126; 125, identifier:numCands; 126, integer:1; 127, block; 127, 128; 127, 135; 128, if_statement; 128, 129; 128, 133; 129, parenthesized_expression; 129, 130; 130, comparison_operator:==; 130, 131; 130, 132; 131, identifier:i; 132, identifier:j; 133, block; 133, 134; 134, continue_statement; 135, for_statement; 135, 136; 135, 137; 135, 144; 136, identifier:k; 137, call; 137, 138; 137, 139; 138, identifier:range; 139, argument_list; 139, 140; 139, 141; 140, integer:1; 141, binary_operator:+; 141, 142; 141, 143; 142, identifier:numCands; 143, integer:1; 144, block; 144, 145; 144, 156; 145, if_statement; 145, 146; 145, 154; 146, parenthesized_expression; 146, 147; 147, boolean_operator:or; 147, 148; 147, 151; 148, comparison_operator:==; 148, 149; 148, 150; 149, identifier:i; 150, identifier:k; 151, comparison_operator:==; 151, 152; 151, 153; 152, identifier:j; 153, identifier:k; 154, block; 154, 155; 155, continue_statement; 156, expression_statement; 156, 157; 157, assignment; 157, 158; 157, 163; 158, subscript; 158, 159; 158, 162; 159, subscript; 159, 160; 159, 161; 160, identifier:strongestPaths; 161, identifier:j; 162, identifier:k; 163, call; 163, 164; 163, 165; 164, identifier:max; 165, argument_list; 165, 166; 165, 171; 166, subscript; 166, 167; 166, 170; 167, subscript; 167, 168; 167, 169; 168, identifier:strongestPaths; 169, identifier:j; 170, identifier:k; 171, call; 171, 172; 171, 173; 172, identifier:min; 173, argument_list; 173, 174; 173, 179; 174, subscript; 174, 175; 174, 178; 175, subscript; 175, 176; 175, 177; 176, identifier:strongestPaths; 177, identifier:j; 178, identifier:i; 179, subscript; 179, 180; 179, 183; 180, subscript; 180, 181; 180, 182; 181, identifier:strongestPaths; 182, identifier:i; 183, identifier:k; 184, return_statement; 184, 185; 185, identifier:strongestPaths | def computeStrongestPaths(self, profile, pairwisePreferences):
"""
Returns a two-dimensional dictionary that associates every pair of candidates, cand1 and
cand2, with the strongest path from cand1 to cand2.
:ivar Profile profile: A Profile object that represents an election profile.
:ivar dict<int,dict<int,int>> pairwisePreferences: A two-dimensional dictionary that
associates every pair of candidates, cand1 and cand2, with number of voters who prefer
cand1 to cand2.
"""
cands = profile.candMap.keys()
numCands = len(cands)
# Initialize the two-dimensional dictionary that will hold our strongest paths.
strongestPaths = dict()
for cand in cands:
strongestPaths[cand] = dict()
for i in range(1, numCands + 1):
for j in range(1, numCands + 1):
if (i == j):
continue
if pairwisePreferences[i][j] > pairwisePreferences[j][i]:
strongestPaths[i][j] = pairwisePreferences[i][j]
else:
strongestPaths[i][j] = 0
for i in range(1, numCands + 1):
for j in range(1, numCands + 1):
if (i == j):
continue
for k in range(1, numCands + 1):
if (i == k or j == k):
continue
strongestPaths[j][k] = max(strongestPaths[j][k], min(strongestPaths[j][i], strongestPaths[i][k]))
return strongestPaths |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:computePairwisePreferences; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:profile; 6, block; 6, 7; 6, 9; 6, 19; 6, 20; 6, 26; 6, 38; 6, 59; 6, 188; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:cands; 12, call; 12, 13; 12, 18; 13, attribute; 13, 14; 13, 17; 14, attribute; 14, 15; 14, 16; 15, identifier:profile; 16, identifier:candMap; 17, identifier:keys; 18, argument_list; 19, comment; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:pairwisePreferences; 23, call; 23, 24; 23, 25; 24, identifier:dict; 25, argument_list; 26, for_statement; 26, 27; 26, 28; 26, 29; 27, identifier:cand; 28, identifier:cands; 29, block; 29, 30; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 35; 32, subscript; 32, 33; 32, 34; 33, identifier:pairwisePreferences; 34, identifier:cand; 35, call; 35, 36; 35, 37; 36, identifier:dict; 37, argument_list; 38, for_statement; 38, 39; 38, 40; 38, 41; 39, identifier:cand1; 40, identifier:cands; 41, block; 41, 42; 42, for_statement; 42, 43; 42, 44; 42, 45; 43, identifier:cand2; 44, identifier:cands; 45, block; 45, 46; 46, if_statement; 46, 47; 46, 50; 47, comparison_operator:!=; 47, 48; 47, 49; 48, identifier:cand1; 49, identifier:cand2; 50, block; 50, 51; 51, expression_statement; 51, 52; 52, assignment; 52, 53; 52, 58; 53, subscript; 53, 54; 53, 57; 54, subscript; 54, 55; 54, 56; 55, identifier:pairwisePreferences; 56, identifier:cand1; 57, identifier:cand2; 58, integer:0; 59, for_statement; 59, 60; 59, 61; 59, 64; 60, identifier:preference; 61, attribute; 61, 62; 61, 63; 62, identifier:profile; 63, identifier:preferences; 64, block; 64, 65; 64, 71; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:wmgMap; 68, attribute; 68, 69; 68, 70; 69, identifier:preference; 70, identifier:wmgMap; 71, for_statement; 71, 72; 71, 75; 71, 82; 71, 83; 71, 84; 72, pattern_list; 72, 73; 72, 74; 73, identifier:cand1; 74, identifier:cand2; 75, call; 75, 76; 75, 79; 76, attribute; 76, 77; 76, 78; 77, identifier:itertools; 78, identifier:combinations; 79, argument_list; 79, 80; 79, 81; 80, identifier:cands; 81, integer:2; 82, comment; 83, comment; 84, block; 84, 85; 85, if_statement; 85, 86; 85, 93; 85, 115; 85, 145; 85, 166; 86, comparison_operator:not; 86, 87; 86, 88; 87, identifier:cand1; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:wmgMap; 91, identifier:keys; 92, argument_list; 93, block; 93, 94; 94, if_statement; 94, 95; 94, 102; 95, comparison_operator:in; 95, 96; 95, 97; 96, identifier:cand2; 97, call; 97, 98; 97, 101; 98, attribute; 98, 99; 98, 100; 99, identifier:wmgMap; 100, identifier:keys; 101, argument_list; 102, block; 102, 103; 103, expression_statement; 103, 104; 104, augmented_assignment:+=; 104, 105; 104, 110; 105, subscript; 105, 106; 105, 109; 106, subscript; 106, 107; 106, 108; 107, identifier:pairwisePreferences; 108, identifier:cand2; 109, identifier:cand1; 110, binary_operator:*; 110, 111; 110, 112; 111, integer:1; 112, attribute; 112, 113; 112, 114; 113, identifier:preference; 114, identifier:count; 115, elif_clause; 115, 116; 115, 123; 116, comparison_operator:not; 116, 117; 116, 118; 117, identifier:cand2; 118, call; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:wmgMap; 121, identifier:keys; 122, argument_list; 123, block; 123, 124; 124, if_statement; 124, 125; 124, 132; 125, comparison_operator:in; 125, 126; 125, 127; 126, identifier:cand1; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:wmgMap; 130, identifier:keys; 131, argument_list; 132, block; 132, 133; 133, expression_statement; 133, 134; 134, augmented_assignment:+=; 134, 135; 134, 140; 135, subscript; 135, 136; 135, 139; 136, subscript; 136, 137; 136, 138; 137, identifier:pairwisePreferences; 138, identifier:cand1; 139, identifier:cand2; 140, binary_operator:*; 140, 141; 140, 142; 141, integer:1; 142, attribute; 142, 143; 142, 144; 143, identifier:preference; 144, identifier:count; 145, elif_clause; 145, 146; 145, 153; 146, comparison_operator:==; 146, 147; 146, 152; 147, subscript; 147, 148; 147, 151; 148, subscript; 148, 149; 148, 150; 149, identifier:wmgMap; 150, identifier:cand1; 151, identifier:cand2; 152, integer:1; 153, block; 153, 154; 154, expression_statement; 154, 155; 155, augmented_assignment:+=; 155, 156; 155, 161; 156, subscript; 156, 157; 156, 160; 157, subscript; 157, 158; 157, 159; 158, identifier:pairwisePreferences; 159, identifier:cand1; 160, identifier:cand2; 161, binary_operator:*; 161, 162; 161, 163; 162, integer:1; 163, attribute; 163, 164; 163, 165; 164, identifier:preference; 165, identifier:count; 166, elif_clause; 166, 167; 166, 175; 167, comparison_operator:==; 167, 168; 167, 173; 168, subscript; 168, 169; 168, 172; 169, subscript; 169, 170; 169, 171; 170, identifier:wmgMap; 171, identifier:cand1; 172, identifier:cand2; 173, unary_operator:-; 173, 174; 174, integer:1; 175, block; 175, 176; 176, expression_statement; 176, 177; 177, augmented_assignment:+=; 177, 178; 177, 183; 178, subscript; 178, 179; 178, 182; 179, subscript; 179, 180; 179, 181; 180, identifier:pairwisePreferences; 181, identifier:cand2; 182, identifier:cand1; 183, binary_operator:*; 183, 184; 183, 185; 184, integer:1; 185, attribute; 185, 186; 185, 187; 186, identifier:preference; 187, identifier:count; 188, return_statement; 188, 189; 189, identifier:pairwisePreferences | def computePairwisePreferences(self, profile):
"""
Returns a two-dimensional dictionary that associates every pair of candidates, cand1 and
cand2, with number of voters who prefer cand1 to cand2.
:ivar Profile profile: A Profile object that represents an election profile.
"""
cands = profile.candMap.keys()
# Initialize the two-dimensional dictionary that will hold our pairwise preferences.
pairwisePreferences = dict()
for cand in cands:
pairwisePreferences[cand] = dict()
for cand1 in cands:
for cand2 in cands:
if cand1 != cand2:
pairwisePreferences[cand1][cand2] = 0
for preference in profile.preferences:
wmgMap = preference.wmgMap
for cand1, cand2 in itertools.combinations(cands, 2):
# If either candidate was unranked, we assume that they are lower ranked than all
# ranked candidates.
if cand1 not in wmgMap.keys():
if cand2 in wmgMap.keys():
pairwisePreferences[cand2][cand1] += 1 * preference.count
elif cand2 not in wmgMap.keys():
if cand1 in wmgMap.keys():
pairwisePreferences[cand1][cand2] += 1 * preference.count
elif wmgMap[cand1][cand2] == 1:
pairwisePreferences[cand1][cand2] += 1 * preference.count
elif wmgMap[cand1][cand2] == -1:
pairwisePreferences[cand2][cand1] += 1 * preference.count
return pairwisePreferences |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:STVsocwinners; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:profile; 6, block; 6, 7; 6, 9; 6, 17; 6, 25; 6, 31; 6, 66; 6, 80; 6, 87; 6, 93; 6, 94; 6, 100; 6, 101; 6, 110; 6, 114; 6, 121; 6, 274; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:ordering; 12, call; 12, 13; 12, 16; 13, attribute; 13, 14; 13, 15; 14, identifier:profile; 15, identifier:getOrderVectors; 16, argument_list; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:prefcounts; 20, call; 20, 21; 20, 24; 21, attribute; 21, 22; 21, 23; 22, identifier:profile; 23, identifier:getPreferenceCounts; 24, argument_list; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:m; 28, attribute; 28, 29; 28, 30; 29, identifier:profile; 30, identifier:numCands; 31, if_statement; 31, 32; 31, 40; 31, 51; 32, comparison_operator:==; 32, 33; 32, 39; 33, call; 33, 34; 33, 35; 34, identifier:min; 35, argument_list; 35, 36; 36, subscript; 36, 37; 36, 38; 37, identifier:ordering; 38, integer:0; 39, integer:0; 40, block; 40, 41; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:startstate; 44, call; 44, 45; 44, 46; 45, identifier:set; 46, argument_list; 46, 47; 47, call; 47, 48; 47, 49; 48, identifier:range; 49, argument_list; 49, 50; 50, identifier:m; 51, else_clause; 51, 52; 52, block; 52, 53; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:startstate; 56, call; 56, 57; 56, 58; 57, identifier:set; 58, argument_list; 58, 59; 59, call; 59, 60; 59, 61; 60, identifier:range; 61, argument_list; 61, 62; 61, 63; 62, integer:1; 63, binary_operator:+; 63, 64; 63, 65; 64, identifier:m; 65, integer:1; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 71; 68, pattern_list; 68, 69; 68, 70; 69, identifier:ordering; 70, identifier:startstate; 71, call; 71, 72; 71, 75; 72, attribute; 72, 73; 72, 74; 73, identifier:self; 74, identifier:preprocessing; 75, argument_list; 75, 76; 75, 77; 75, 78; 75, 79; 76, identifier:ordering; 77, identifier:prefcounts; 78, identifier:m; 79, identifier:startstate; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:m_star; 83, call; 83, 84; 83, 85; 84, identifier:len; 85, argument_list; 85, 86; 86, identifier:startstate; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:known_winners; 90, call; 90, 91; 90, 92; 91, identifier:set; 92, argument_list; 93, comment; 94, expression_statement; 94, 95; 95, assignment; 95, 96; 95, 97; 96, identifier:hashtable2; 97, call; 97, 98; 97, 99; 98, identifier:set; 99, argument_list; 100, comment; 101, expression_statement; 101, 102; 102, assignment; 102, 103; 102, 104; 103, identifier:root; 104, call; 104, 105; 104, 106; 105, identifier:Node; 106, argument_list; 106, 107; 107, keyword_argument; 107, 108; 107, 109; 108, identifier:value; 109, identifier:startstate; 110, expression_statement; 110, 111; 111, assignment; 111, 112; 111, 113; 112, identifier:stackNode; 113, list:[]; 114, expression_statement; 114, 115; 115, call; 115, 116; 115, 119; 116, attribute; 116, 117; 116, 118; 117, identifier:stackNode; 118, identifier:append; 119, argument_list; 119, 120; 120, identifier:root; 121, while_statement; 121, 122; 121, 123; 121, 124; 122, identifier:stackNode; 123, comment; 124, block; 124, 125; 124, 133; 124, 134; 124, 144; 124, 145; 124, 146; 124, 176; 124, 177; 124, 183; 124, 184; 124, 196; 124, 207; 125, expression_statement; 125, 126; 126, assignment; 126, 127; 126, 128; 127, identifier:node; 128, call; 128, 129; 128, 132; 129, attribute; 129, 130; 129, 131; 130, identifier:stackNode; 131, identifier:pop; 132, argument_list; 133, comment; 134, expression_statement; 134, 135; 135, assignment; 135, 136; 135, 137; 136, identifier:state; 137, call; 137, 138; 137, 143; 138, attribute; 138, 139; 138, 142; 139, attribute; 139, 140; 139, 141; 140, identifier:node; 141, identifier:value; 142, identifier:copy; 143, argument_list; 144, comment; 145, comment; 146, if_statement; 146, 147; 146, 162; 147, boolean_operator:and; 147, 148; 147, 154; 148, comparison_operator:==; 148, 149; 148, 153; 149, call; 149, 150; 149, 151; 150, identifier:len; 151, argument_list; 151, 152; 152, identifier:state; 153, integer:1; 154, comparison_operator:not; 154, 155; 154, 161; 155, subscript; 155, 156; 155, 160; 156, call; 156, 157; 156, 158; 157, identifier:list; 158, argument_list; 158, 159; 159, identifier:state; 160, integer:0; 161, identifier:known_winners; 162, block; 162, 163; 162, 175; 163, expression_statement; 163, 164; 164, call; 164, 165; 164, 168; 165, attribute; 165, 166; 165, 167; 166, identifier:known_winners; 167, identifier:add; 168, argument_list; 168, 169; 169, subscript; 169, 170; 169, 174; 170, call; 170, 171; 170, 172; 171, identifier:list; 172, argument_list; 172, 173; 173, identifier:state; 174, integer:0; 175, continue_statement; 176, comment; 177, if_statement; 177, 178; 177, 181; 178, comparison_operator:<=; 178, 179; 178, 180; 179, identifier:state; 180, identifier:known_winners; 181, block; 181, 182; 182, continue_statement; 183, comment; 184, expression_statement; 184, 185; 185, assignment; 185, 186; 185, 187; 186, identifier:plural_score; 187, call; 187, 188; 187, 191; 188, attribute; 188, 189; 188, 190; 189, identifier:self; 190, identifier:get_plurality_scores3; 191, argument_list; 191, 192; 191, 193; 191, 194; 191, 195; 192, identifier:prefcounts; 193, identifier:ordering; 194, identifier:state; 195, identifier:m_star; 196, expression_statement; 196, 197; 197, assignment; 197, 198; 197, 199; 198, identifier:minscore; 199, call; 199, 200; 199, 201; 200, identifier:min; 201, argument_list; 201, 202; 202, call; 202, 203; 202, 206; 203, attribute; 203, 204; 203, 205; 204, identifier:plural_score; 205, identifier:values; 206, argument_list; 207, for_statement; 207, 208; 207, 209; 207, 210; 208, identifier:to_be_deleted; 209, identifier:state; 210, block; 210, 211; 211, if_statement; 211, 212; 211, 217; 212, comparison_operator:==; 212, 213; 212, 216; 213, subscript; 213, 214; 213, 215; 214, identifier:plural_score; 215, identifier:to_be_deleted; 216, identifier:minscore; 217, block; 217, 218; 217, 226; 217, 233; 217, 243; 218, expression_statement; 218, 219; 219, assignment; 219, 220; 219, 221; 220, identifier:child_state; 221, call; 221, 222; 221, 225; 222, attribute; 222, 223; 222, 224; 223, identifier:state; 224, identifier:copy; 225, argument_list; 226, expression_statement; 226, 227; 227, call; 227, 228; 227, 231; 228, attribute; 228, 229; 228, 230; 229, identifier:child_state; 230, identifier:remove; 231, argument_list; 231, 232; 232, identifier:to_be_deleted; 233, expression_statement; 233, 234; 234, assignment; 234, 235; 234, 236; 235, identifier:tpc; 236, call; 236, 237; 236, 238; 237, identifier:tuple; 238, argument_list; 238, 239; 239, call; 239, 240; 239, 241; 240, identifier:sorted; 241, argument_list; 241, 242; 242, identifier:child_state; 243, if_statement; 243, 244; 243, 247; 243, 249; 244, comparison_operator:in; 244, 245; 244, 246; 245, identifier:tpc; 246, identifier:hashtable2; 247, block; 247, 248; 248, continue_statement; 249, else_clause; 249, 250; 250, block; 250, 251; 250, 258; 250, 267; 251, expression_statement; 251, 252; 252, call; 252, 253; 252, 256; 253, attribute; 253, 254; 253, 255; 254, identifier:hashtable2; 255, identifier:add; 256, argument_list; 256, 257; 257, identifier:tpc; 258, expression_statement; 258, 259; 259, assignment; 259, 260; 259, 261; 260, identifier:child_node; 261, call; 261, 262; 261, 263; 262, identifier:Node; 263, argument_list; 263, 264; 264, keyword_argument; 264, 265; 264, 266; 265, identifier:value; 266, identifier:child_state; 267, expression_statement; 267, 268; 268, call; 268, 269; 268, 272; 269, attribute; 269, 270; 269, 271; 270, identifier:stackNode; 271, identifier:append; 272, argument_list; 272, 273; 273, identifier:child_node; 274, return_statement; 274, 275; 275, call; 275, 276; 275, 277; 276, identifier:sorted; 277, argument_list; 277, 278; 278, identifier:known_winners | def STVsocwinners(self, profile):
"""
Returns an integer list that represents all possible winners of a profile under STV rule.
:ivar Profile profile: A Profile object that represents an election profile.
"""
ordering = profile.getOrderVectors()
prefcounts = profile.getPreferenceCounts()
m = profile.numCands
if min(ordering[0]) == 0:
startstate = set(range(m))
else:
startstate = set(range(1, m + 1))
ordering, startstate = self.preprocessing(ordering, prefcounts, m, startstate)
m_star = len(startstate)
known_winners = set()
# ----------Some statistics--------------
hashtable2 = set()
# push the node of start state into the priority queue
root = Node(value=startstate)
stackNode = []
stackNode.append(root)
while stackNode:
# ------------pop the current node-----------------
node = stackNode.pop()
# -------------------------------------------------
state = node.value.copy()
# use heuristic to delete all the candidates which satisfy the following condition
# goal state 1: if the state set contains only 1 candidate, then stop
if len(state) == 1 and list(state)[0] not in known_winners:
known_winners.add(list(state)[0])
continue
# goal state 2 (pruning): if the state set is subset of the known_winners set, then stop
if state <= known_winners:
continue
# ----------Compute plurality score for the current remaining candidates--------------
plural_score = self.get_plurality_scores3(prefcounts, ordering, state, m_star)
minscore = min(plural_score.values())
for to_be_deleted in state:
if plural_score[to_be_deleted] == minscore:
child_state = state.copy()
child_state.remove(to_be_deleted)
tpc = tuple(sorted(child_state))
if tpc in hashtable2:
continue
else:
hashtable2.add(tpc)
child_node = Node(value=child_state)
stackNode.append(child_node)
return sorted(known_winners) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:baldwinsoc_winners; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:profile; 6, block; 6, 7; 6, 9; 6, 17; 6, 23; 6, 31; 6, 66; 6, 80; 6, 86; 6, 87; 6, 93; 6, 94; 6, 103; 6, 107; 6, 114; 6, 295; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:ordering; 12, call; 12, 13; 12, 16; 13, attribute; 13, 14; 13, 15; 14, identifier:profile; 15, identifier:getOrderVectors; 16, argument_list; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:m; 20, attribute; 20, 21; 20, 22; 21, identifier:profile; 22, identifier:numCands; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:prefcounts; 26, call; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, identifier:profile; 29, identifier:getPreferenceCounts; 30, argument_list; 31, if_statement; 31, 32; 31, 40; 31, 51; 32, comparison_operator:==; 32, 33; 32, 39; 33, call; 33, 34; 33, 35; 34, identifier:min; 35, argument_list; 35, 36; 36, subscript; 36, 37; 36, 38; 37, identifier:ordering; 38, integer:0; 39, integer:0; 40, block; 40, 41; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:startstate; 44, call; 44, 45; 44, 46; 45, identifier:set; 46, argument_list; 46, 47; 47, call; 47, 48; 47, 49; 48, identifier:range; 49, argument_list; 49, 50; 50, identifier:m; 51, else_clause; 51, 52; 52, block; 52, 53; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:startstate; 56, call; 56, 57; 56, 58; 57, identifier:set; 58, argument_list; 58, 59; 59, call; 59, 60; 59, 61; 60, identifier:range; 61, argument_list; 61, 62; 61, 63; 62, integer:1; 63, binary_operator:+; 63, 64; 63, 65; 64, identifier:m; 65, integer:1; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:wmg; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:self; 72, identifier:getWmg2; 73, argument_list; 73, 74; 73, 75; 73, 76; 73, 77; 74, identifier:prefcounts; 75, identifier:ordering; 76, identifier:startstate; 77, keyword_argument; 77, 78; 77, 79; 78, identifier:normalize; 79, False; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:known_winners; 83, call; 83, 84; 83, 85; 84, identifier:set; 85, argument_list; 86, comment; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:hashtable2; 90, call; 90, 91; 90, 92; 91, identifier:set; 92, argument_list; 93, comment; 94, expression_statement; 94, 95; 95, assignment; 95, 96; 95, 97; 96, identifier:root; 97, call; 97, 98; 97, 99; 98, identifier:Node; 99, argument_list; 99, 100; 100, keyword_argument; 100, 101; 100, 102; 101, identifier:value; 102, identifier:startstate; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:stackNode; 106, list:[]; 107, expression_statement; 107, 108; 108, call; 108, 109; 108, 112; 109, attribute; 109, 110; 109, 111; 110, identifier:stackNode; 111, identifier:append; 112, argument_list; 112, 113; 113, identifier:root; 114, while_statement; 114, 115; 114, 116; 114, 117; 115, identifier:stackNode; 116, comment; 117, block; 117, 118; 117, 126; 117, 127; 117, 137; 117, 138; 117, 168; 117, 169; 117, 175; 117, 176; 117, 182; 117, 192; 117, 214; 117, 215; 117, 216; 117, 217; 117, 228; 118, expression_statement; 118, 119; 119, assignment; 119, 120; 119, 121; 120, identifier:node; 121, call; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:stackNode; 124, identifier:pop; 125, argument_list; 126, comment; 127, expression_statement; 127, 128; 128, assignment; 128, 129; 128, 130; 129, identifier:state; 130, call; 130, 131; 130, 136; 131, attribute; 131, 132; 131, 135; 132, attribute; 132, 133; 132, 134; 133, identifier:node; 134, identifier:value; 135, identifier:copy; 136, argument_list; 137, comment; 138, if_statement; 138, 139; 138, 154; 139, boolean_operator:and; 139, 140; 139, 146; 140, comparison_operator:==; 140, 141; 140, 145; 141, call; 141, 142; 141, 143; 142, identifier:len; 143, argument_list; 143, 144; 144, identifier:state; 145, integer:1; 146, comparison_operator:not; 146, 147; 146, 153; 147, subscript; 147, 148; 147, 152; 148, call; 148, 149; 148, 150; 149, identifier:list; 150, argument_list; 150, 151; 151, identifier:state; 152, integer:0; 153, identifier:known_winners; 154, block; 154, 155; 154, 167; 155, expression_statement; 155, 156; 156, call; 156, 157; 156, 160; 157, attribute; 157, 158; 157, 159; 158, identifier:known_winners; 159, identifier:add; 160, argument_list; 160, 161; 161, subscript; 161, 162; 161, 166; 162, call; 162, 163; 162, 164; 163, identifier:list; 164, argument_list; 164, 165; 165, identifier:state; 166, integer:0; 167, continue_statement; 168, comment; 169, if_statement; 169, 170; 169, 173; 170, comparison_operator:<=; 170, 171; 170, 172; 171, identifier:state; 172, identifier:known_winners; 173, block; 173, 174; 174, continue_statement; 175, comment; 176, expression_statement; 176, 177; 177, assignment; 177, 178; 177, 179; 178, identifier:plural_score; 179, call; 179, 180; 179, 181; 180, identifier:dict; 181, argument_list; 182, for_statement; 182, 183; 182, 184; 182, 185; 183, identifier:cand; 184, identifier:state; 185, block; 185, 186; 186, expression_statement; 186, 187; 187, assignment; 187, 188; 187, 191; 188, subscript; 188, 189; 188, 190; 189, identifier:plural_score; 190, identifier:cand; 191, integer:0; 192, for_statement; 192, 193; 192, 196; 192, 203; 193, pattern_list; 193, 194; 193, 195; 194, identifier:cand1; 195, identifier:cand2; 196, call; 196, 197; 196, 200; 197, attribute; 197, 198; 197, 199; 198, identifier:itertools; 199, identifier:permutations; 200, argument_list; 200, 201; 200, 202; 201, identifier:state; 202, integer:2; 203, block; 203, 204; 204, expression_statement; 204, 205; 205, augmented_assignment:+=; 205, 206; 205, 209; 206, subscript; 206, 207; 206, 208; 207, identifier:plural_score; 208, identifier:cand1; 209, subscript; 209, 210; 209, 213; 210, subscript; 210, 211; 210, 212; 211, identifier:wmg; 212, identifier:cand1; 213, identifier:cand2; 214, comment; 215, comment; 216, comment; 217, expression_statement; 217, 218; 218, assignment; 218, 219; 218, 220; 219, identifier:minscore; 220, call; 220, 221; 220, 222; 221, identifier:min; 222, argument_list; 222, 223; 223, call; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:plural_score; 226, identifier:values; 227, argument_list; 228, for_statement; 228, 229; 228, 230; 228, 231; 229, identifier:to_be_deleted; 230, identifier:state; 231, block; 231, 232; 232, if_statement; 232, 233; 232, 238; 233, comparison_operator:==; 233, 234; 233, 237; 234, subscript; 234, 235; 234, 236; 235, identifier:plural_score; 236, identifier:to_be_deleted; 237, identifier:minscore; 238, block; 238, 239; 238, 247; 238, 254; 238, 264; 239, expression_statement; 239, 240; 240, assignment; 240, 241; 240, 242; 241, identifier:child_state; 242, call; 242, 243; 242, 246; 243, attribute; 243, 244; 243, 245; 244, identifier:state; 245, identifier:copy; 246, argument_list; 247, expression_statement; 247, 248; 248, call; 248, 249; 248, 252; 249, attribute; 249, 250; 249, 251; 250, identifier:child_state; 251, identifier:remove; 252, argument_list; 252, 253; 253, identifier:to_be_deleted; 254, expression_statement; 254, 255; 255, assignment; 255, 256; 255, 257; 256, identifier:tpc; 257, call; 257, 258; 257, 259; 258, identifier:tuple; 259, argument_list; 259, 260; 260, call; 260, 261; 260, 262; 261, identifier:sorted; 262, argument_list; 262, 263; 263, identifier:child_state; 264, if_statement; 264, 265; 264, 268; 264, 270; 265, comparison_operator:in; 265, 266; 265, 267; 266, identifier:tpc; 267, identifier:hashtable2; 268, block; 268, 269; 269, continue_statement; 270, else_clause; 270, 271; 271, block; 271, 272; 271, 279; 271, 288; 272, expression_statement; 272, 273; 273, call; 273, 274; 273, 277; 274, attribute; 274, 275; 274, 276; 275, identifier:hashtable2; 276, identifier:add; 277, argument_list; 277, 278; 278, identifier:tpc; 279, expression_statement; 279, 280; 280, assignment; 280, 281; 280, 282; 281, identifier:child_node; 282, call; 282, 283; 282, 284; 283, identifier:Node; 284, argument_list; 284, 285; 285, keyword_argument; 285, 286; 285, 287; 286, identifier:value; 287, identifier:child_state; 288, expression_statement; 288, 289; 289, call; 289, 290; 289, 293; 290, attribute; 290, 291; 290, 292; 291, identifier:stackNode; 292, identifier:append; 293, argument_list; 293, 294; 294, identifier:child_node; 295, return_statement; 295, 296; 296, call; 296, 297; 296, 298; 297, identifier:sorted; 298, argument_list; 298, 299; 299, identifier:known_winners | def baldwinsoc_winners(self, profile):
"""
Returns an integer list that represents all possible winners of a profile under baldwin rule.
:ivar Profile profile: A Profile object that represents an election profile.
"""
ordering = profile.getOrderVectors()
m = profile.numCands
prefcounts = profile.getPreferenceCounts()
if min(ordering[0]) == 0:
startstate = set(range(m))
else:
startstate = set(range(1, m + 1))
wmg = self.getWmg2(prefcounts, ordering, startstate, normalize=False)
known_winners = set()
# ----------Some statistics--------------
hashtable2 = set()
# push the node of start state into the priority queue
root = Node(value=startstate)
stackNode = []
stackNode.append(root)
while stackNode:
# ------------pop the current node-----------------
node = stackNode.pop()
# -------------------------------------------------
state = node.value.copy()
# goal state 1: if the state set contains only 1 candidate, then stop
if len(state) == 1 and list(state)[0] not in known_winners:
known_winners.add(list(state)[0])
continue
# goal state 2 (pruning): if the state set is subset of the known_winners set, then stop
if state <= known_winners:
continue
# ----------Compute plurality score for the current remaining candidates--------------
plural_score = dict()
for cand in state:
plural_score[cand] = 0
for cand1, cand2 in itertools.permutations(state, 2):
plural_score[cand1] += wmg[cand1][cand2]
# if current state satisfies one of the 3 goal state, continue to the next loop
# After using heuristics, generate children and push them into priority queue
# frontier = [val for val in known_winners if val in state] + list(set(state) - set(known_winners))
minscore = min(plural_score.values())
for to_be_deleted in state:
if plural_score[to_be_deleted] == minscore:
child_state = state.copy()
child_state.remove(to_be_deleted)
tpc = tuple(sorted(child_state))
if tpc in hashtable2:
continue
else:
hashtable2.add(tpc)
child_node = Node(value=child_state)
stackNode.append(child_node)
return sorted(known_winners) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:getWmg2; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, identifier:self; 5, identifier:prefcounts; 6, identifier:ordering; 7, identifier:state; 8, default_parameter; 8, 9; 8, 10; 9, identifier:normalize; 10, False; 11, block; 11, 12; 11, 14; 11, 15; 11, 21; 11, 33; 11, 61; 11, 62; 11, 63; 11, 64; 11, 100; 11, 101; 11, 102; 11, 174; 12, expression_statement; 12, 13; 13, comment; 14, comment; 15, expression_statement; 15, 16; 16, assignment; 16, 17; 16, 18; 17, identifier:wmgMap; 18, call; 18, 19; 18, 20; 19, identifier:dict; 20, argument_list; 21, for_statement; 21, 22; 21, 23; 21, 24; 22, identifier:cand; 23, identifier:state; 24, block; 24, 25; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 30; 27, subscript; 27, 28; 27, 29; 28, identifier:wmgMap; 29, identifier:cand; 30, call; 30, 31; 30, 32; 31, identifier:dict; 32, argument_list; 33, for_statement; 33, 34; 33, 37; 33, 44; 34, pattern_list; 34, 35; 34, 36; 35, identifier:cand1; 36, identifier:cand2; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:itertools; 40, identifier:combinations; 41, argument_list; 41, 42; 41, 43; 42, identifier:state; 43, integer:2; 44, block; 44, 45; 44, 53; 45, expression_statement; 45, 46; 46, assignment; 46, 47; 46, 52; 47, subscript; 47, 48; 47, 51; 48, subscript; 48, 49; 48, 50; 49, identifier:wmgMap; 50, identifier:cand1; 51, identifier:cand2; 52, integer:0; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 60; 55, subscript; 55, 56; 55, 59; 56, subscript; 56, 57; 56, 58; 57, identifier:wmgMap; 58, identifier:cand2; 59, identifier:cand1; 60, integer:0; 61, comment; 62, comment; 63, comment; 64, for_statement; 64, 65; 64, 66; 64, 74; 65, identifier:i; 66, call; 66, 67; 66, 68; 67, identifier:range; 68, argument_list; 68, 69; 68, 70; 69, integer:0; 70, call; 70, 71; 70, 72; 71, identifier:len; 72, argument_list; 72, 73; 73, identifier:prefcounts; 74, block; 74, 75; 75, for_statement; 75, 76; 75, 79; 75, 88; 75, 89; 76, pattern_list; 76, 77; 76, 78; 77, identifier:cand1; 78, identifier:cand2; 79, call; 79, 80; 79, 83; 80, attribute; 80, 81; 80, 82; 81, identifier:itertools; 82, identifier:combinations; 83, argument_list; 83, 84; 83, 87; 84, subscript; 84, 85; 84, 86; 85, identifier:ordering; 86, identifier:i; 87, integer:2; 88, comment; 89, block; 89, 90; 90, expression_statement; 90, 91; 91, augmented_assignment:+=; 91, 92; 91, 97; 92, subscript; 92, 93; 92, 96; 93, subscript; 93, 94; 93, 95; 94, identifier:wmgMap; 95, identifier:cand1; 96, identifier:cand2; 97, subscript; 97, 98; 97, 99; 98, identifier:prefcounts; 99, identifier:i; 100, comment; 101, comment; 102, if_statement; 102, 103; 102, 106; 103, comparison_operator:==; 103, 104; 103, 105; 104, identifier:normalize; 105, True; 106, block; 106, 107; 106, 114; 106, 139; 107, expression_statement; 107, 108; 108, assignment; 108, 109; 108, 110; 109, identifier:maxEdge; 110, call; 110, 111; 110, 112; 111, identifier:float; 112, argument_list; 112, 113; 113, string:'-inf'; 114, for_statement; 114, 115; 114, 116; 114, 121; 115, identifier:cand; 116, call; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:wmgMap; 119, identifier:keys; 120, argument_list; 121, block; 121, 122; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:maxEdge; 125, call; 125, 126; 125, 127; 126, identifier:max; 127, argument_list; 127, 128; 127, 129; 128, identifier:maxEdge; 129, call; 129, 130; 129, 131; 130, identifier:max; 131, argument_list; 131, 132; 132, call; 132, 133; 132, 138; 133, attribute; 133, 134; 133, 137; 134, subscript; 134, 135; 134, 136; 135, identifier:wmgMap; 136, identifier:cand; 137, identifier:values; 138, argument_list; 139, for_statement; 139, 140; 139, 141; 139, 146; 140, identifier:cand1; 141, call; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, identifier:wmgMap; 144, identifier:keys; 145, argument_list; 146, block; 146, 147; 147, for_statement; 147, 148; 147, 149; 147, 156; 148, identifier:cand2; 149, call; 149, 150; 149, 155; 150, attribute; 150, 151; 150, 154; 151, subscript; 151, 152; 151, 153; 152, identifier:wmgMap; 153, identifier:cand1; 154, identifier:keys; 155, argument_list; 156, block; 156, 157; 157, expression_statement; 157, 158; 158, assignment; 158, 159; 158, 164; 159, subscript; 159, 160; 159, 163; 160, subscript; 160, 161; 160, 162; 161, identifier:wmgMap; 162, identifier:cand1; 163, identifier:cand2; 164, binary_operator:/; 164, 165; 164, 173; 165, call; 165, 166; 165, 167; 166, identifier:float; 167, argument_list; 167, 168; 168, subscript; 168, 169; 168, 172; 169, subscript; 169, 170; 169, 171; 170, identifier:wmgMap; 171, identifier:cand1; 172, identifier:cand2; 173, identifier:maxEdge; 174, return_statement; 174, 175; 175, identifier:wmgMap | def getWmg2(self, prefcounts, ordering, state, normalize=False):
"""
Generate a weighted majority graph that represents the whole profile. The function will
return a two-dimensional dictionary that associates integer representations of each pair of
candidates, cand1 and cand2, with the number of times cand1 is ranked above cand2 minus the
number of times cand2 is ranked above cand1.
:ivar bool normalize: If normalize is True, the function will return a normalized graph
where each edge has been divided by the value of the largest edge.
"""
# Initialize a new dictionary for our final weighted majority graph.
wmgMap = dict()
for cand in state:
wmgMap[cand] = dict()
for cand1, cand2 in itertools.combinations(state, 2):
wmgMap[cand1][cand2] = 0
wmgMap[cand2][cand1] = 0
# Go through the wmgMaps and increment the value of each edge in our final graph with the
# edges in each of the wmgMaps. We take into account the number of times that the vote
# occured.
for i in range(0, len(prefcounts)):
for cand1, cand2 in itertools.combinations(ordering[i], 2): # --------------------------
wmgMap[cand1][cand2] += prefcounts[i]
# By default, we assume that the weighted majority graph should not be normalized. If
# desired, we normalize by dividing each edge by the value of the largest edge.
if normalize == True:
maxEdge = float('-inf')
for cand in wmgMap.keys():
maxEdge = max(maxEdge, max(wmgMap[cand].values()))
for cand1 in wmgMap.keys():
for cand2 in wmgMap[cand1].keys():
wmgMap[cand1][cand2] = float(wmgMap[cand1][cand2]) / maxEdge
return wmgMap |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:PluRunOff_cowinners; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:profile; 6, block; 6, 7; 6, 9; 6, 10; 6, 11; 6, 19; 6, 41; 6, 42; 6, 50; 6, 57; 6, 65; 6, 76; 6, 82; 6, 83; 6, 87; 6, 186; 6, 187; 6, 313; 7, expression_statement; 7, 8; 8, comment; 9, comment; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:elecType; 14, call; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:profile; 17, identifier:getElecType; 18, argument_list; 19, if_statement; 19, 20; 19, 31; 20, boolean_operator:and; 20, 21; 20, 28; 21, boolean_operator:and; 21, 22; 21, 25; 22, comparison_operator:!=; 22, 23; 22, 24; 23, identifier:elecType; 24, string:"soc"; 25, comparison_operator:!=; 25, 26; 25, 27; 26, identifier:elecType; 27, string:"toc"; 28, comparison_operator:!=; 28, 29; 28, 30; 29, identifier:elecType; 30, string:"csv"; 31, block; 31, 32; 31, 37; 32, expression_statement; 32, 33; 33, call; 33, 34; 33, 35; 34, identifier:print; 35, argument_list; 35, 36; 36, string:"ERROR: unsupported election type"; 37, expression_statement; 37, 38; 38, call; 38, 39; 38, 40; 39, identifier:exit; 40, argument_list; 41, comment; 42, expression_statement; 42, 43; 43, assignment; 43, 44; 43, 45; 44, identifier:prefcounts; 45, call; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:profile; 48, identifier:getPreferenceCounts; 49, argument_list; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:len_prefcounts; 53, call; 53, 54; 53, 55; 54, identifier:len; 55, argument_list; 55, 56; 56, identifier:prefcounts; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 60; 59, identifier:rankmaps; 60, call; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:profile; 63, identifier:getRankMaps; 64, argument_list; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:ranking; 68, call; 68, 69; 68, 74; 69, attribute; 69, 70; 69, 73; 70, call; 70, 71; 70, 72; 71, identifier:MechanismPlurality; 72, argument_list; 73, identifier:getRanking; 74, argument_list; 74, 75; 75, identifier:profile; 76, expression_statement; 76, 77; 77, assignment; 77, 78; 77, 79; 78, identifier:known_winners; 79, call; 79, 80; 79, 81; 80, identifier:set; 81, argument_list; 82, comment; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:top_2_combinations; 86, list:[]; 87, if_statement; 87, 88; 87, 98; 87, 124; 88, comparison_operator:>; 88, 89; 88, 97; 89, call; 89, 90; 89, 91; 90, identifier:len; 91, argument_list; 91, 92; 92, subscript; 92, 93; 92, 96; 93, subscript; 93, 94; 93, 95; 94, identifier:ranking; 95, integer:0; 96, integer:0; 97, integer:1; 98, block; 98, 99; 99, for_statement; 99, 100; 99, 103; 99, 114; 100, pattern_list; 100, 101; 100, 102; 101, identifier:cand1; 102, identifier:cand2; 103, call; 103, 104; 103, 107; 104, attribute; 104, 105; 104, 106; 105, identifier:itertools; 106, identifier:combinations; 107, argument_list; 107, 108; 107, 113; 108, subscript; 108, 109; 108, 112; 109, subscript; 109, 110; 109, 111; 110, identifier:ranking; 111, integer:0; 112, integer:0; 113, integer:2; 114, block; 114, 115; 115, expression_statement; 115, 116; 116, call; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:top_2_combinations; 119, identifier:append; 120, argument_list; 120, 121; 121, list:[cand1, cand2]; 121, 122; 121, 123; 122, identifier:cand1; 123, identifier:cand2; 124, else_clause; 124, 125; 125, block; 125, 126; 125, 136; 126, expression_statement; 126, 127; 127, assignment; 127, 128; 127, 129; 128, identifier:max_cand; 129, subscript; 129, 130; 129, 135; 130, subscript; 130, 131; 130, 134; 131, subscript; 131, 132; 131, 133; 132, identifier:ranking; 133, integer:0; 134, integer:0; 135, integer:0; 136, if_statement; 136, 137; 136, 147; 136, 165; 137, comparison_operator:>; 137, 138; 137, 146; 138, call; 138, 139; 138, 140; 139, identifier:len; 140, argument_list; 140, 141; 141, subscript; 141, 142; 141, 145; 142, subscript; 142, 143; 142, 144; 143, identifier:ranking; 144, integer:0; 145, integer:1; 146, integer:1; 147, block; 147, 148; 148, for_statement; 148, 149; 148, 150; 148, 155; 149, identifier:second_max_cand; 150, subscript; 150, 151; 150, 154; 151, subscript; 151, 152; 151, 153; 152, identifier:ranking; 153, integer:0; 154, integer:1; 155, block; 155, 156; 156, expression_statement; 156, 157; 157, call; 157, 158; 157, 161; 158, attribute; 158, 159; 158, 160; 159, identifier:top_2_combinations; 160, identifier:append; 161, argument_list; 161, 162; 162, list:[max_cand, second_max_cand]; 162, 163; 162, 164; 163, identifier:max_cand; 164, identifier:second_max_cand; 165, else_clause; 165, 166; 166, block; 166, 167; 166, 177; 167, expression_statement; 167, 168; 168, assignment; 168, 169; 168, 170; 169, identifier:second_max_cand; 170, subscript; 170, 171; 170, 176; 171, subscript; 171, 172; 171, 175; 172, subscript; 172, 173; 172, 174; 173, identifier:ranking; 174, integer:0; 175, integer:1; 176, integer:0; 177, expression_statement; 177, 178; 178, call; 178, 179; 178, 182; 179, attribute; 179, 180; 179, 181; 180, identifier:top_2_combinations; 181, identifier:append; 182, argument_list; 182, 183; 183, list:[max_cand, second_max_cand]; 183, 184; 183, 185; 184, identifier:max_cand; 185, identifier:second_max_cand; 186, comment; 187, for_statement; 187, 188; 187, 189; 187, 190; 188, identifier:top_2; 189, identifier:top_2_combinations; 190, block; 190, 191; 190, 205; 190, 275; 190, 286; 190, 304; 191, expression_statement; 191, 192; 192, assignment; 192, 193; 192, 194; 193, identifier:dict_top2; 194, dictionary; 194, 195; 194, 200; 195, pair; 195, 196; 195, 199; 196, subscript; 196, 197; 196, 198; 197, identifier:top_2; 198, integer:0; 199, integer:0; 200, pair; 200, 201; 200, 204; 201, subscript; 201, 202; 201, 203; 202, identifier:top_2; 203, integer:1; 204, integer:0; 205, for_statement; 205, 206; 205, 207; 205, 211; 206, identifier:i; 207, call; 207, 208; 207, 209; 208, identifier:range; 209, argument_list; 209, 210; 210, identifier:len_prefcounts; 211, block; 211, 212; 211, 234; 211, 245; 211, 263; 212, expression_statement; 212, 213; 213, assignment; 213, 214; 213, 215; 214, identifier:vote_top2; 215, dictionary_comprehension; 215, 216; 215, 219; 215, 230; 216, pair; 216, 217; 216, 218; 217, identifier:key; 218, identifier:value; 219, for_in_clause; 219, 220; 219, 223; 220, pattern_list; 220, 221; 220, 222; 221, identifier:key; 222, identifier:value; 223, call; 223, 224; 223, 229; 224, attribute; 224, 225; 224, 228; 225, subscript; 225, 226; 225, 227; 226, identifier:rankmaps; 227, identifier:i; 228, identifier:items; 229, argument_list; 230, if_clause; 230, 231; 231, comparison_operator:in; 231, 232; 231, 233; 232, identifier:key; 233, identifier:top_2; 234, expression_statement; 234, 235; 235, assignment; 235, 236; 235, 237; 236, identifier:top_position; 237, call; 237, 238; 237, 239; 238, identifier:min; 239, argument_list; 239, 240; 240, call; 240, 241; 240, 244; 241, attribute; 241, 242; 241, 243; 242, identifier:vote_top2; 243, identifier:values; 244, argument_list; 245, expression_statement; 245, 246; 246, assignment; 246, 247; 246, 248; 247, identifier:keys; 248, list_comprehension; 248, 249; 248, 250; 248, 257; 249, identifier:x; 250, for_in_clause; 250, 251; 250, 252; 251, identifier:x; 252, call; 252, 253; 252, 256; 253, attribute; 253, 254; 253, 255; 254, identifier:vote_top2; 255, identifier:keys; 256, argument_list; 257, if_clause; 257, 258; 258, comparison_operator:==; 258, 259; 258, 262; 259, subscript; 259, 260; 259, 261; 260, identifier:vote_top2; 261, identifier:x; 262, identifier:top_position; 263, for_statement; 263, 264; 263, 265; 263, 266; 264, identifier:key; 265, identifier:keys; 266, block; 266, 267; 267, expression_statement; 267, 268; 268, augmented_assignment:+=; 268, 269; 268, 272; 269, subscript; 269, 270; 269, 271; 270, identifier:dict_top2; 271, identifier:key; 272, subscript; 272, 273; 272, 274; 273, identifier:prefcounts; 274, identifier:i; 275, expression_statement; 275, 276; 276, assignment; 276, 277; 276, 278; 277, identifier:max_value; 278, call; 278, 279; 278, 280; 279, identifier:max; 280, argument_list; 280, 281; 281, call; 281, 282; 281, 285; 282, attribute; 282, 283; 282, 284; 283, identifier:dict_top2; 284, identifier:values; 285, argument_list; 286, expression_statement; 286, 287; 287, assignment; 287, 288; 287, 289; 288, identifier:winners; 289, list_comprehension; 289, 290; 289, 291; 289, 298; 290, identifier:y; 291, for_in_clause; 291, 292; 291, 293; 292, identifier:y; 293, call; 293, 294; 293, 297; 294, attribute; 294, 295; 294, 296; 295, identifier:dict_top2; 296, identifier:keys; 297, argument_list; 298, if_clause; 298, 299; 299, comparison_operator:==; 299, 300; 299, 303; 300, subscript; 300, 301; 300, 302; 301, identifier:dict_top2; 302, identifier:y; 303, identifier:max_value; 304, expression_statement; 304, 305; 305, assignment; 305, 306; 305, 307; 306, identifier:known_winners; 307, binary_operator:|; 307, 308; 307, 309; 308, identifier:known_winners; 309, call; 309, 310; 309, 311; 310, identifier:set; 311, argument_list; 311, 312; 312, identifier:winners; 313, return_statement; 313, 314; 314, call; 314, 315; 314, 316; 315, identifier:sorted; 316, argument_list; 316, 317; 317, identifier:known_winners | def PluRunOff_cowinners(self, profile):
"""
Returns a list that associates all the winners of a profile under Plurality with Runoff rule.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Currently, we expect the profile to contain complete ordering over candidates. Ties are
# allowed however.
elecType = profile.getElecType()
if elecType != "soc" and elecType != "toc" and elecType != "csv":
print("ERROR: unsupported election type")
exit()
# Initialization
prefcounts = profile.getPreferenceCounts()
len_prefcounts = len(prefcounts)
rankmaps = profile.getRankMaps()
ranking = MechanismPlurality().getRanking(profile)
known_winners = set()
# 1st round: find the top 2 candidates in plurality scores
top_2_combinations = []
if len(ranking[0][0]) > 1:
for cand1, cand2 in itertools.combinations(ranking[0][0], 2):
top_2_combinations.append([cand1, cand2])
else:
max_cand = ranking[0][0][0]
if len(ranking[0][1]) > 1:
for second_max_cand in ranking[0][1]:
top_2_combinations.append([max_cand, second_max_cand])
else:
second_max_cand = ranking[0][1][0]
top_2_combinations.append([max_cand, second_max_cand])
# 2nd round: find the candidate with maximum plurality score
for top_2 in top_2_combinations:
dict_top2 = {top_2[0]: 0, top_2[1]: 0}
for i in range(len_prefcounts):
vote_top2 = {key: value for key, value in rankmaps[i].items() if key in top_2}
top_position = min(vote_top2.values())
keys = [x for x in vote_top2.keys() if vote_top2[x] == top_position]
for key in keys:
dict_top2[key] += prefcounts[i]
max_value = max(dict_top2.values())
winners = [y for y in dict_top2.keys() if dict_top2[y] == max_value]
known_winners = known_winners | set(winners)
return sorted(known_winners) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:_cache_offsets; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:up_to_index; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:verbose; 10, True; 11, block; 11, 12; 11, 14; 11, 76; 11, 155; 11, 163; 11, 164; 11, 174; 12, expression_statement; 12, 13; 13, comment; 14, if_statement; 14, 15; 14, 17; 14, 59; 15, not_operator; 15, 16; 16, identifier:up_to_index; 17, block; 17, 18; 17, 28; 17, 38; 17, 44; 18, if_statement; 18, 19; 18, 20; 19, identifier:verbose; 20, block; 20, 21; 21, expression_statement; 21, 22; 22, call; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:self; 25, identifier:print; 26, argument_list; 26, 27; 27, string:"Caching event file offsets, this may take a bit."; 28, expression_statement; 28, 29; 29, call; 29, 30; 29, 35; 30, attribute; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:self; 33, identifier:blob_file; 34, identifier:seek; 35, argument_list; 35, 36; 35, 37; 36, integer:0; 37, integer:0; 38, expression_statement; 38, 39; 39, assignment; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:self; 42, identifier:event_offsets; 43, list:[]; 44, if_statement; 44, 45; 44, 49; 45, not_operator; 45, 46; 46, attribute; 46, 47; 46, 48; 47, identifier:self; 48, identifier:raw_header; 49, block; 49, 50; 50, expression_statement; 50, 51; 51, call; 51, 52; 51, 57; 52, attribute; 52, 53; 52, 56; 53, attribute; 53, 54; 53, 55; 54, identifier:self; 55, identifier:event_offsets; 56, identifier:append; 57, argument_list; 57, 58; 58, integer:0; 59, else_clause; 59, 60; 60, block; 60, 61; 61, expression_statement; 61, 62; 62, call; 62, 63; 62, 68; 63, attribute; 63, 64; 63, 67; 64, attribute; 64, 65; 64, 66; 65, identifier:self; 66, identifier:blob_file; 67, identifier:seek; 68, argument_list; 68, 69; 68, 75; 69, subscript; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:self; 72, identifier:event_offsets; 73, unary_operator:-; 73, 74; 74, integer:1; 75, integer:0; 76, for_statement; 76, 77; 76, 78; 76, 87; 77, identifier:line; 78, call; 78, 79; 78, 80; 79, identifier:iter; 80, argument_list; 80, 81; 80, 86; 81, attribute; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:self; 84, identifier:blob_file; 85, identifier:readline; 86, string:''; 87, block; 87, 88; 87, 95; 87, 140; 88, expression_statement; 88, 89; 89, assignment; 89, 90; 89, 91; 90, identifier:line; 91, call; 91, 92; 91, 93; 92, identifier:try_decode_string; 93, argument_list; 93, 94; 94, identifier:line; 95, if_statement; 95, 96; 95, 102; 96, call; 96, 97; 96, 100; 97, attribute; 97, 98; 97, 99; 98, identifier:line; 99, identifier:startswith; 100, argument_list; 100, 101; 101, string:'end_event:'; 102, block; 102, 103; 102, 109; 103, expression_statement; 103, 104; 104, call; 104, 105; 104, 108; 105, attribute; 105, 106; 105, 107; 106, identifier:self; 107, identifier:_record_offset; 108, argument_list; 109, if_statement; 109, 110; 109, 120; 110, comparison_operator:==; 110, 111; 110, 119; 111, binary_operator:%; 111, 112; 111, 118; 112, call; 112, 113; 112, 114; 113, identifier:len; 114, argument_list; 114, 115; 115, attribute; 115, 116; 115, 117; 116, identifier:self; 117, identifier:event_offsets; 118, integer:100; 119, integer:0; 120, block; 120, 121; 120, 132; 121, if_statement; 121, 122; 121, 123; 122, identifier:verbose; 123, block; 123, 124; 124, expression_statement; 124, 125; 125, call; 125, 126; 125, 127; 126, identifier:print; 127, argument_list; 127, 128; 127, 129; 128, string:'.'; 129, keyword_argument; 129, 130; 129, 131; 130, identifier:end; 131, string:''; 132, expression_statement; 132, 133; 133, call; 133, 134; 133, 139; 134, attribute; 134, 135; 134, 138; 135, attribute; 135, 136; 135, 137; 136, identifier:sys; 137, identifier:stdout; 138, identifier:flush; 139, argument_list; 140, if_statement; 140, 141; 140, 153; 141, boolean_operator:and; 141, 142; 141, 143; 142, identifier:up_to_index; 143, comparison_operator:>=; 143, 144; 143, 150; 144, call; 144, 145; 144, 146; 145, identifier:len; 146, argument_list; 146, 147; 147, attribute; 147, 148; 147, 149; 148, identifier:self; 149, identifier:event_offsets; 150, binary_operator:+; 150, 151; 150, 152; 151, identifier:up_to_index; 152, integer:1; 153, block; 153, 154; 154, return_statement; 155, expression_statement; 155, 156; 156, call; 156, 157; 156, 162; 157, attribute; 157, 158; 157, 161; 158, attribute; 158, 159; 158, 160; 159, identifier:self; 160, identifier:event_offsets; 161, identifier:pop; 162, argument_list; 163, comment; 164, if_statement; 164, 165; 164, 167; 165, not_operator; 165, 166; 166, identifier:up_to_index; 167, block; 167, 168; 168, expression_statement; 168, 169; 169, assignment; 169, 170; 169, 173; 170, attribute; 170, 171; 170, 172; 171, identifier:self; 172, identifier:whole_file_cached; 173, True; 174, expression_statement; 174, 175; 175, call; 175, 176; 175, 179; 176, attribute; 176, 177; 176, 178; 177, identifier:self; 178, identifier:print; 179, argument_list; 179, 180; 180, call; 180, 181; 180, 184; 181, attribute; 181, 182; 181, 183; 182, string:"\n{0} events indexed."; 183, identifier:format; 184, argument_list; 184, 185; 185, call; 185, 186; 185, 187; 186, identifier:len; 187, argument_list; 187, 188; 188, attribute; 188, 189; 188, 190; 189, identifier:self; 190, identifier:event_offsets | def _cache_offsets(self, up_to_index=None, verbose=True):
"""Cache all event offsets."""
if not up_to_index:
if verbose:
self.print("Caching event file offsets, this may take a bit.")
self.blob_file.seek(0, 0)
self.event_offsets = []
if not self.raw_header:
self.event_offsets.append(0)
else:
self.blob_file.seek(self.event_offsets[-1], 0)
for line in iter(self.blob_file.readline, ''):
line = try_decode_string(line)
if line.startswith('end_event:'):
self._record_offset()
if len(self.event_offsets) % 100 == 0:
if verbose:
print('.', end='')
sys.stdout.flush()
if up_to_index and len(self.event_offsets) >= up_to_index + 1:
return
self.event_offsets.pop() # get rid of the last entry
if not up_to_index:
self.whole_file_cached = True
self.print("\n{0} events indexed.".format(len(self.event_offsets))) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:getUtilities; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:decision; 6, identifier:binaryRelations; 7, block; 7, 8; 7, 10; 7, 17; 7, 21; 7, 136; 8, expression_statement; 8, 9; 9, comment; 10, expression_statement; 10, 11; 11, assignment; 11, 12; 11, 13; 12, identifier:m; 13, call; 13, 14; 13, 15; 14, identifier:len; 15, argument_list; 15, 16; 16, identifier:binaryRelations; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:utilities; 20, list:[]; 21, for_statement; 21, 22; 21, 23; 21, 24; 22, identifier:cand; 23, identifier:decision; 24, block; 24, 25; 24, 32; 24, 36; 24, 88; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:tops; 28, list:[cand-1]; 28, 29; 29, binary_operator:-; 29, 30; 29, 31; 30, identifier:cand; 31, integer:1; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:index; 35, integer:0; 36, while_statement; 36, 37; 36, 43; 37, comparison_operator:<; 37, 38; 37, 39; 38, identifier:index; 39, call; 39, 40; 39, 41; 40, identifier:len; 41, argument_list; 41, 42; 42, identifier:tops; 43, block; 43, 44; 43, 50; 43, 84; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:s; 47, subscript; 47, 48; 47, 49; 48, identifier:tops; 49, identifier:index; 50, for_statement; 50, 51; 50, 52; 50, 56; 51, identifier:j; 52, call; 52, 53; 52, 54; 53, identifier:range; 54, argument_list; 54, 55; 55, identifier:m; 56, block; 56, 57; 56, 63; 57, if_statement; 57, 58; 57, 61; 58, comparison_operator:==; 58, 59; 58, 60; 59, identifier:j; 60, identifier:s; 61, block; 61, 62; 62, continue_statement; 63, if_statement; 63, 64; 63, 71; 64, comparison_operator:>; 64, 65; 64, 70; 65, subscript; 65, 66; 65, 69; 66, subscript; 66, 67; 66, 68; 67, identifier:binaryRelations; 68, identifier:j; 69, identifier:s; 70, integer:0; 71, block; 71, 72; 72, if_statement; 72, 73; 72, 76; 73, comparison_operator:not; 73, 74; 73, 75; 74, identifier:j; 75, identifier:tops; 76, block; 76, 77; 77, expression_statement; 77, 78; 78, call; 78, 79; 78, 82; 79, attribute; 79, 80; 79, 81; 80, identifier:tops; 81, identifier:append; 82, argument_list; 82, 83; 83, identifier:j; 84, expression_statement; 84, 85; 85, augmented_assignment:+=; 85, 86; 85, 87; 86, identifier:index; 87, integer:1; 88, if_statement; 88, 89; 88, 97; 88, 127; 89, comparison_operator:<=; 89, 90; 89, 94; 90, call; 90, 91; 90, 92; 91, identifier:len; 92, argument_list; 92, 93; 93, identifier:tops; 94, attribute; 94, 95; 94, 96; 95, identifier:self; 96, identifier:k; 97, block; 97, 98; 98, if_statement; 98, 99; 98, 104; 98, 112; 99, comparison_operator:==; 99, 100; 99, 103; 100, attribute; 100, 101; 100, 102; 101, identifier:self; 102, identifier:isLoss; 103, False; 104, block; 104, 105; 105, expression_statement; 105, 106; 106, call; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, identifier:utilities; 109, identifier:append; 110, argument_list; 110, 111; 111, float:1.0; 112, elif_clause; 112, 113; 112, 118; 113, comparison_operator:==; 113, 114; 113, 117; 114, attribute; 114, 115; 114, 116; 115, identifier:self; 116, identifier:isLoss; 117, True; 118, block; 118, 119; 119, expression_statement; 119, 120; 120, call; 120, 121; 120, 124; 121, attribute; 121, 122; 121, 123; 122, identifier:utilities; 123, identifier:append; 124, argument_list; 124, 125; 125, unary_operator:-; 125, 126; 126, float:1.0; 127, else_clause; 127, 128; 128, block; 128, 129; 129, expression_statement; 129, 130; 130, call; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:utilities; 133, identifier:append; 134, argument_list; 134, 135; 135, float:0.0; 136, return_statement; 136, 137; 137, identifier:utilities | def getUtilities(self, decision, binaryRelations):
"""
Returns a floats that contains the utilities of every candidate in the decision. This was
adapted from code written by Lirong Xia.
:ivar list<int> decision: Contains a list of integer representations of candidates in the
current decision.
:ivar list<list,int> binaryRelations: A two-dimensional array whose number of rows and
colums is equal to the number of candidates. For each pair of candidates, cand1 and
cand2, binaryRelations[cand1-1][cand2-1] contains 1 if cand1 is ranked above cand2
and 0 otherwise.
"""
m = len(binaryRelations)
utilities = []
for cand in decision:
tops = [cand-1]
index = 0
while index < len(tops):
s = tops[index]
for j in range(m):
if j == s:
continue
if binaryRelations[j][s] > 0:
if j not in tops:
tops.append(j)
index += 1
if len(tops) <= self.k:
if self.isLoss == False:
utilities.append(1.0)
elif self.isLoss == True:
utilities.append(-1.0)
else:
utilities.append(0.0)
return utilities |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:execute; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, identifier:self; 5, identifier:sources; 6, identifier:sink; 7, identifier:interval; 8, default_parameter; 8, 9; 8, 10; 9, identifier:alignment_stream; 10, None; 11, block; 11, 12; 11, 14; 11, 35; 11, 36; 11, 56; 11, 68; 12, expression_statement; 12, 13; 13, comment; 14, if_statement; 14, 15; 14, 21; 15, not_operator; 15, 16; 16, call; 16, 17; 16, 18; 17, identifier:isinstance; 18, argument_list; 18, 19; 18, 20; 19, identifier:interval; 20, identifier:TimeInterval; 21, block; 21, 22; 22, raise_statement; 22, 23; 23, call; 23, 24; 23, 25; 24, identifier:TypeError; 25, argument_list; 25, 26; 26, call; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, string:'Expected TimeInterval, got {}'; 29, identifier:format; 30, argument_list; 30, 31; 31, call; 31, 32; 31, 33; 32, identifier:type; 33, argument_list; 33, 34; 34, identifier:interval; 35, comment; 36, if_statement; 36, 37; 36, 46; 37, comparison_operator:>; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:interval; 40, identifier:end; 41, attribute; 41, 42; 41, 45; 42, attribute; 42, 43; 42, 44; 43, identifier:sink; 44, identifier:channel; 45, identifier:up_to_timestamp; 46, block; 46, 47; 47, raise_statement; 47, 48; 48, call; 48, 49; 48, 50; 49, identifier:StreamNotAvailableError; 50, argument_list; 50, 51; 51, attribute; 51, 52; 51, 55; 52, attribute; 52, 53; 52, 54; 53, identifier:sink; 54, identifier:channel; 55, identifier:up_to_timestamp; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:required_intervals; 59, binary_operator:-; 59, 60; 59, 65; 60, call; 60, 61; 60, 62; 61, identifier:TimeIntervals; 62, argument_list; 62, 63; 63, list:[interval]; 63, 64; 64, identifier:interval; 65, attribute; 65, 66; 65, 67; 66, identifier:sink; 67, identifier:calculated_intervals; 68, if_statement; 68, 69; 68, 73; 69, not_operator; 69, 70; 70, attribute; 70, 71; 70, 72; 71, identifier:required_intervals; 72, identifier:is_empty; 73, block; 73, 74; 73, 78; 73, 116; 73, 128; 73, 151; 73, 171; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 77; 76, identifier:document_count; 77, integer:0; 78, for_statement; 78, 79; 78, 80; 78, 81; 79, identifier:interval; 80, identifier:required_intervals; 81, block; 81, 82; 81, 110; 82, for_statement; 82, 83; 82, 84; 82, 98; 83, identifier:stream_instance; 84, call; 84, 85; 84, 88; 85, attribute; 85, 86; 85, 87; 86, identifier:self; 87, identifier:_execute; 88, argument_list; 88, 89; 88, 92; 88, 95; 89, keyword_argument; 89, 90; 89, 91; 90, identifier:sources; 91, identifier:sources; 92, keyword_argument; 92, 93; 92, 94; 93, identifier:alignment_stream; 94, identifier:alignment_stream; 95, keyword_argument; 95, 96; 95, 97; 96, identifier:interval; 97, identifier:interval; 98, block; 98, 99; 98, 106; 99, expression_statement; 99, 100; 100, call; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:sink; 103, identifier:writer; 104, argument_list; 104, 105; 105, identifier:stream_instance; 106, expression_statement; 106, 107; 107, augmented_assignment:+=; 107, 108; 107, 109; 108, identifier:document_count; 109, integer:1; 110, expression_statement; 110, 111; 111, augmented_assignment:+=; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:sink; 114, identifier:calculated_intervals; 115, identifier:interval; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 119; 118, identifier:required_intervals; 119, binary_operator:-; 119, 120; 119, 125; 120, call; 120, 121; 120, 122; 121, identifier:TimeIntervals; 122, argument_list; 122, 123; 123, list:[interval]; 123, 124; 124, identifier:interval; 125, attribute; 125, 126; 125, 127; 126, identifier:sink; 127, identifier:calculated_intervals; 128, if_statement; 128, 129; 128, 133; 128, 134; 129, not_operator; 129, 130; 130, attribute; 130, 131; 130, 132; 131, identifier:required_intervals; 132, identifier:is_empty; 133, comment; 134, block; 134, 135; 135, expression_statement; 135, 136; 136, call; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:logging; 139, identifier:error; 140, argument_list; 140, 141; 141, call; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, string:"{} execution error for time interval {} on stream {}"; 144, identifier:format; 145, argument_list; 145, 146; 145, 149; 145, 150; 146, attribute; 146, 147; 146, 148; 147, identifier:self; 148, identifier:name; 149, identifier:interval; 150, identifier:sink; 151, if_statement; 151, 152; 151, 154; 152, not_operator; 152, 153; 153, identifier:document_count; 154, block; 154, 155; 155, expression_statement; 155, 156; 156, call; 156, 157; 156, 160; 157, attribute; 157, 158; 157, 159; 158, identifier:logging; 159, identifier:debug; 160, argument_list; 160, 161; 161, call; 161, 162; 161, 165; 162, attribute; 162, 163; 162, 164; 163, string:"{} did not produce any data for time interval {} on stream {}"; 164, identifier:format; 165, argument_list; 165, 166; 165, 169; 165, 170; 166, attribute; 166, 167; 166, 168; 167, identifier:self; 168, identifier:name; 169, identifier:interval; 170, identifier:sink; 171, expression_statement; 171, 172; 172, call; 172, 173; 172, 176; 173, attribute; 173, 174; 173, 175; 174, identifier:self; 175, identifier:write_to_history; 176, argument_list; 176, 177; 176, 180; 176, 185; 177, keyword_argument; 177, 178; 177, 179; 178, identifier:interval; 179, identifier:interval; 180, keyword_argument; 180, 181; 180, 182; 181, identifier:tool; 182, attribute; 182, 183; 182, 184; 183, identifier:self; 184, identifier:name; 185, keyword_argument; 185, 186; 185, 187; 186, identifier:document_count; 187, identifier:document_count | def execute(self, sources, sink, interval, alignment_stream=None):
"""
Execute the tool over the given time interval.
If an alignment stream is given, the output instances will be aligned to this stream
:param sources: The source streams (possibly None)
:param sink: The sink stream
:param alignment_stream: The alignment stream
:param interval: The time interval
:type sources: list[Stream] | tuple[Stream] | None
:type sink: Stream
:type alignment_stream: Stream | None
:type interval: TimeInterval
:return: None
"""
if not isinstance(interval, TimeInterval):
raise TypeError('Expected TimeInterval, got {}'.format(type(interval)))
# logging.info(self.message(interval))
if interval.end > sink.channel.up_to_timestamp:
raise StreamNotAvailableError(sink.channel.up_to_timestamp)
required_intervals = TimeIntervals([interval]) - sink.calculated_intervals
if not required_intervals.is_empty:
document_count = 0
for interval in required_intervals:
for stream_instance in self._execute(
sources=sources, alignment_stream=alignment_stream, interval=interval):
sink.writer(stream_instance)
document_count += 1
sink.calculated_intervals += interval
required_intervals = TimeIntervals([interval]) - sink.calculated_intervals
if not required_intervals.is_empty:
# raise ToolExecutionError(required_intervals)
logging.error("{} execution error for time interval {} on stream {}".format(
self.name, interval, sink))
if not document_count:
logging.debug("{} did not produce any data for time interval {} on stream {}".format(
self.name, interval, sink))
self.write_to_history(
interval=interval,
tool=self.name,
document_count=document_count
) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:upload_runsummary; 3, parameters; 3, 4; 3, 5; 4, identifier:csv_filename; 5, default_parameter; 5, 6; 5, 7; 6, identifier:dryrun; 7, False; 8, block; 8, 9; 8, 11; 8, 21; 8, 45; 8, 77; 8, 86; 8, 121; 8, 127; 8, 143; 8, 159; 8, 180; 8, 185; 8, 205; 8, 215; 8, 232; 8, 237; 8, 247; 8, 248; 8, 290; 8, 302; 8, 313; 8, 318; 8, 339; 9, expression_statement; 9, 10; 10, comment; 11, expression_statement; 11, 12; 12, call; 12, 13; 12, 14; 13, identifier:print; 14, argument_list; 14, 15; 15, call; 15, 16; 15, 19; 16, attribute; 16, 17; 16, 18; 17, string:"Checking '{}' for consistency."; 18, identifier:format; 19, argument_list; 19, 20; 20, identifier:csv_filename; 21, if_statement; 21, 22; 21, 31; 22, not_operator; 22, 23; 23, call; 23, 24; 23, 29; 24, attribute; 24, 25; 24, 28; 25, attribute; 25, 26; 25, 27; 26, identifier:os; 27, identifier:path; 28, identifier:exists; 29, argument_list; 29, 30; 30, identifier:csv_filename; 31, block; 31, 32; 31, 44; 32, expression_statement; 32, 33; 33, call; 33, 34; 33, 37; 34, attribute; 34, 35; 34, 36; 35, identifier:log; 36, identifier:critical; 37, argument_list; 37, 38; 38, call; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, string:"{} -> file not found."; 41, identifier:format; 42, argument_list; 42, 43; 43, identifier:csv_filename; 44, return_statement; 45, try_statement; 45, 46; 45, 59; 46, block; 46, 47; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:df; 50, call; 50, 51; 50, 54; 51, attribute; 51, 52; 51, 53; 52, identifier:pd; 53, identifier:read_csv; 54, argument_list; 54, 55; 54, 56; 55, identifier:csv_filename; 56, keyword_argument; 56, 57; 56, 58; 57, identifier:sep; 58, string:'\t'; 59, except_clause; 59, 60; 59, 68; 60, as_pattern; 60, 61; 60, 66; 61, attribute; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:pd; 64, identifier:errors; 65, identifier:EmptyDataError; 66, as_pattern_target; 66, 67; 67, identifier:e; 68, block; 68, 69; 68, 76; 69, expression_statement; 69, 70; 70, call; 70, 71; 70, 74; 71, attribute; 71, 72; 71, 73; 72, identifier:log; 73, identifier:error; 74, argument_list; 74, 75; 75, identifier:e; 76, return_statement; 77, expression_statement; 77, 78; 78, assignment; 78, 79; 78, 80; 79, identifier:cols; 80, call; 80, 81; 80, 82; 81, identifier:set; 82, argument_list; 82, 83; 83, attribute; 83, 84; 83, 85; 84, identifier:df; 85, identifier:columns; 86, if_statement; 86, 87; 86, 94; 87, not_operator; 87, 88; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:REQUIRED_COLUMNS; 91, identifier:issubset; 92, argument_list; 92, 93; 93, identifier:cols; 94, block; 94, 95; 94, 120; 95, expression_statement; 95, 96; 96, call; 96, 97; 96, 100; 97, attribute; 97, 98; 97, 99; 98, identifier:log; 99, identifier:error; 100, argument_list; 100, 101; 101, call; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, string:"Missing columns: {}."; 104, identifier:format; 105, argument_list; 105, 106; 106, call; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, string:', '; 109, identifier:join; 110, generator_expression; 110, 111; 110, 115; 111, call; 111, 112; 111, 113; 112, identifier:str; 113, argument_list; 113, 114; 114, identifier:c; 115, for_in_clause; 115, 116; 115, 117; 116, identifier:c; 117, binary_operator:-; 117, 118; 117, 119; 118, identifier:REQUIRED_COLUMNS; 119, identifier:cols; 120, return_statement; 121, expression_statement; 121, 122; 122, assignment; 122, 123; 122, 124; 123, identifier:parameters; 124, binary_operator:-; 124, 125; 124, 126; 125, identifier:cols; 126, identifier:REQUIRED_COLUMNS; 127, if_statement; 127, 128; 127, 134; 128, comparison_operator:<; 128, 129; 128, 133; 129, call; 129, 130; 129, 131; 130, identifier:len; 131, argument_list; 131, 132; 132, identifier:parameters; 133, integer:1; 134, block; 134, 135; 134, 142; 135, expression_statement; 135, 136; 136, call; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:log; 139, identifier:error; 140, argument_list; 140, 141; 141, string:"No parameter columns found."; 142, return_statement; 143, if_statement; 143, 144; 143, 150; 144, comparison_operator:==; 144, 145; 144, 149; 145, call; 145, 146; 145, 147; 146, identifier:len; 147, argument_list; 147, 148; 148, identifier:df; 149, integer:0; 150, block; 150, 151; 150, 158; 151, expression_statement; 151, 152; 152, call; 152, 153; 152, 156; 153, attribute; 153, 154; 153, 155; 154, identifier:log; 155, identifier:critical; 156, argument_list; 156, 157; 157, string:"Empty dataset."; 158, return_statement; 159, expression_statement; 159, 160; 160, call; 160, 161; 160, 162; 161, identifier:print; 162, argument_list; 162, 163; 163, call; 163, 164; 163, 167; 164, attribute; 164, 165; 164, 166; 165, string:"Found data for parameters: {}."; 166, identifier:format; 167, argument_list; 167, 168; 168, call; 168, 169; 168, 172; 169, attribute; 169, 170; 169, 171; 170, string:', '; 171, identifier:join; 172, generator_expression; 172, 173; 172, 177; 173, call; 173, 174; 173, 175; 174, identifier:str; 175, argument_list; 175, 176; 176, identifier:c; 177, for_in_clause; 177, 178; 177, 179; 178, identifier:c; 179, identifier:parameters; 180, expression_statement; 180, 181; 181, call; 181, 182; 181, 183; 182, identifier:print; 183, argument_list; 183, 184; 184, string:"Converting CSV data into JSON"; 185, if_statement; 185, 186; 185, 187; 185, 199; 186, identifier:dryrun; 187, block; 187, 188; 187, 195; 188, expression_statement; 188, 189; 189, call; 189, 190; 189, 193; 190, attribute; 190, 191; 190, 192; 191, identifier:log; 192, identifier:warn; 193, argument_list; 193, 194; 194, string:"Dryrun: adding 'TEST_' prefix to parameter names"; 195, expression_statement; 195, 196; 196, assignment; 196, 197; 196, 198; 197, identifier:prefix; 198, string:"TEST_"; 199, else_clause; 199, 200; 200, block; 200, 201; 201, expression_statement; 201, 202; 202, assignment; 202, 203; 202, 204; 203, identifier:prefix; 204, string:""; 205, expression_statement; 205, 206; 206, assignment; 206, 207; 206, 208; 207, identifier:data; 208, call; 208, 209; 208, 210; 209, identifier:convert_runsummary_to_json; 210, argument_list; 210, 211; 210, 212; 211, identifier:df; 212, keyword_argument; 212, 213; 212, 214; 213, identifier:prefix; 214, identifier:prefix; 215, expression_statement; 215, 216; 216, call; 216, 217; 216, 218; 217, identifier:print; 218, argument_list; 218, 219; 219, call; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, string:"We have {:.3f} MB to upload."; 222, identifier:format; 223, argument_list; 223, 224; 224, binary_operator:/; 224, 225; 224, 229; 225, call; 225, 226; 225, 227; 226, identifier:len; 227, argument_list; 227, 228; 228, identifier:data; 229, binary_operator:**; 229, 230; 229, 231; 230, integer:1024; 231, integer:2; 232, expression_statement; 232, 233; 233, call; 233, 234; 233, 235; 234, identifier:print; 235, argument_list; 235, 236; 236, string:"Requesting database session."; 237, expression_statement; 237, 238; 238, assignment; 238, 239; 238, 240; 239, identifier:db; 240, call; 240, 241; 240, 246; 241, attribute; 241, 242; 241, 245; 242, attribute; 242, 243; 242, 244; 243, identifier:kp; 244, identifier:db; 245, identifier:DBManager; 246, argument_list; 247, comment; 248, if_statement; 248, 249; 248, 256; 248, 262; 249, call; 249, 250; 249, 255; 250, attribute; 250, 251; 250, 254; 251, attribute; 251, 252; 251, 253; 252, identifier:kp; 253, identifier:db; 254, identifier:we_are_in_lyon; 255, argument_list; 256, block; 256, 257; 256, 261; 257, expression_statement; 257, 258; 258, assignment; 258, 259; 258, 260; 259, identifier:session_cookie; 260, string:"sid=_kmcprod_134.158_lyo7783844001343100343mcprod1223user"; 261, comment; 262, else_clause; 262, 263; 263, block; 263, 264; 263, 280; 264, expression_statement; 264, 265; 265, assignment; 265, 266; 265, 267; 266, identifier:session_cookie; 267, call; 267, 268; 267, 277; 268, attribute; 268, 269; 268, 276; 269, call; 269, 270; 269, 275; 270, attribute; 270, 271; 270, 274; 271, attribute; 271, 272; 271, 273; 272, identifier:kp; 273, identifier:config; 274, identifier:Config; 275, argument_list; 276, identifier:get; 277, argument_list; 277, 278; 277, 279; 278, string:'DB'; 279, string:'session_cookie'; 280, if_statement; 280, 281; 280, 284; 281, comparison_operator:is; 281, 282; 281, 283; 282, identifier:session_cookie; 283, None; 284, block; 284, 285; 285, raise_statement; 285, 286; 286, call; 286, 287; 286, 288; 287, identifier:SystemExit; 288, argument_list; 288, 289; 289, string:"Could not restore DB session."; 290, expression_statement; 290, 291; 291, call; 291, 292; 291, 295; 292, attribute; 292, 293; 292, 294; 293, identifier:log; 294, identifier:debug; 295, argument_list; 295, 296; 296, call; 296, 297; 296, 300; 297, attribute; 297, 298; 297, 299; 298, string:"Using the session cookie: {}"; 299, identifier:format; 300, argument_list; 300, 301; 301, identifier:session_cookie; 302, expression_statement; 302, 303; 303, assignment; 303, 304; 303, 307; 304, pattern_list; 304, 305; 304, 306; 305, identifier:cookie_key; 306, identifier:sid; 307, call; 307, 308; 307, 311; 308, attribute; 308, 309; 308, 310; 309, identifier:session_cookie; 310, identifier:split; 311, argument_list; 311, 312; 312, string:'='; 313, expression_statement; 313, 314; 314, call; 314, 315; 314, 316; 315, identifier:print; 316, argument_list; 316, 317; 317, string:"Uploading the data to the database."; 318, expression_statement; 318, 319; 319, assignment; 319, 320; 319, 321; 320, identifier:r; 321, call; 321, 322; 321, 325; 322, attribute; 322, 323; 322, 324; 323, identifier:requests; 324, identifier:post; 325, argument_list; 325, 326; 325, 327; 325, 333; 326, identifier:RUNSUMMARY_URL; 327, keyword_argument; 327, 328; 327, 329; 328, identifier:cookies; 329, dictionary; 329, 330; 330, pair; 330, 331; 330, 332; 331, identifier:cookie_key; 332, identifier:sid; 333, keyword_argument; 333, 334; 333, 335; 334, identifier:files; 335, dictionary; 335, 336; 336, pair; 336, 337; 336, 338; 337, string:'datafile'; 338, identifier:data; 339, if_statement; 339, 340; 339, 345; 339, 418; 340, comparison_operator:==; 340, 341; 340, 344; 341, attribute; 341, 342; 341, 343; 342, identifier:r; 343, identifier:status_code; 344, integer:200; 345, block; 345, 346; 345, 360; 345, 365; 345, 376; 345, 397; 346, expression_statement; 346, 347; 347, call; 347, 348; 347, 351; 348, attribute; 348, 349; 348, 350; 349, identifier:log; 350, identifier:debug; 351, argument_list; 351, 352; 352, call; 352, 353; 352, 356; 353, attribute; 353, 354; 353, 355; 354, string:"POST request status code: {}"; 355, identifier:format; 356, argument_list; 356, 357; 357, attribute; 357, 358; 357, 359; 358, identifier:r; 359, identifier:status_code; 360, expression_statement; 360, 361; 361, call; 361, 362; 361, 363; 362, identifier:print; 363, argument_list; 363, 364; 364, string:"Database response:"; 365, expression_statement; 365, 366; 366, assignment; 366, 367; 366, 368; 367, identifier:db_answer; 368, call; 368, 369; 368, 372; 369, attribute; 369, 370; 369, 371; 370, identifier:json; 371, identifier:loads; 372, argument_list; 372, 373; 373, attribute; 373, 374; 373, 375; 374, identifier:r; 375, identifier:text; 376, for_statement; 376, 377; 376, 380; 376, 385; 377, pattern_list; 377, 378; 377, 379; 378, identifier:key; 379, identifier:value; 380, call; 380, 381; 380, 384; 381, attribute; 381, 382; 381, 383; 382, identifier:db_answer; 383, identifier:items; 384, argument_list; 385, block; 385, 386; 386, expression_statement; 386, 387; 387, call; 387, 388; 387, 389; 388, identifier:print; 389, argument_list; 389, 390; 390, call; 390, 391; 390, 394; 391, attribute; 391, 392; 391, 393; 392, string:" -> {}: {}"; 393, identifier:format; 394, argument_list; 394, 395; 394, 396; 395, identifier:key; 396, identifier:value; 397, if_statement; 397, 398; 397, 403; 397, 409; 398, comparison_operator:==; 398, 399; 398, 402; 399, subscript; 399, 400; 399, 401; 400, identifier:db_answer; 401, string:'Result'; 402, string:'OK'; 403, block; 403, 404; 404, expression_statement; 404, 405; 405, call; 405, 406; 405, 407; 406, identifier:print; 407, argument_list; 407, 408; 408, string:"Upload successful."; 409, else_clause; 409, 410; 410, block; 410, 411; 411, expression_statement; 411, 412; 412, call; 412, 413; 412, 416; 413, attribute; 413, 414; 413, 415; 414, identifier:log; 415, identifier:critical; 416, argument_list; 416, 417; 417, string:"Something went wrong."; 418, else_clause; 418, 419; 419, block; 419, 420; 419, 434; 419, 441; 420, expression_statement; 420, 421; 421, call; 421, 422; 421, 425; 422, attribute; 422, 423; 422, 424; 423, identifier:log; 424, identifier:error; 425, argument_list; 425, 426; 426, call; 426, 427; 426, 430; 427, attribute; 427, 428; 427, 429; 428, string:"POST request status code: {}"; 429, identifier:format; 430, argument_list; 430, 431; 431, attribute; 431, 432; 431, 433; 432, identifier:r; 433, identifier:status_code; 434, expression_statement; 434, 435; 435, call; 435, 436; 435, 439; 436, attribute; 436, 437; 436, 438; 437, identifier:log; 438, identifier:critical; 439, argument_list; 439, 440; 440, string:"Something went wrong..."; 441, return_statement | def upload_runsummary(csv_filename, dryrun=False):
"""Reads the CSV file and uploads its contents to the runsummary table"""
print("Checking '{}' for consistency.".format(csv_filename))
if not os.path.exists(csv_filename):
log.critical("{} -> file not found.".format(csv_filename))
return
try:
df = pd.read_csv(csv_filename, sep='\t')
except pd.errors.EmptyDataError as e:
log.error(e)
return
cols = set(df.columns)
if not REQUIRED_COLUMNS.issubset(cols):
log.error(
"Missing columns: {}.".format(
', '.join(str(c) for c in REQUIRED_COLUMNS - cols)
)
)
return
parameters = cols - REQUIRED_COLUMNS
if len(parameters) < 1:
log.error("No parameter columns found.")
return
if len(df) == 0:
log.critical("Empty dataset.")
return
print(
"Found data for parameters: {}.".format(
', '.join(str(c) for c in parameters)
)
)
print("Converting CSV data into JSON")
if dryrun:
log.warn("Dryrun: adding 'TEST_' prefix to parameter names")
prefix = "TEST_"
else:
prefix = ""
data = convert_runsummary_to_json(df, prefix=prefix)
print("We have {:.3f} MB to upload.".format(len(data) / 1024**2))
print("Requesting database session.")
db = kp.db.DBManager() # noqa
if kp.db.we_are_in_lyon():
session_cookie = "sid=_kmcprod_134.158_lyo7783844001343100343mcprod1223user" # noqa
else:
session_cookie = kp.config.Config().get('DB', 'session_cookie')
if session_cookie is None:
raise SystemExit("Could not restore DB session.")
log.debug("Using the session cookie: {}".format(session_cookie))
cookie_key, sid = session_cookie.split('=')
print("Uploading the data to the database.")
r = requests.post(
RUNSUMMARY_URL, cookies={cookie_key: sid}, files={'datafile': data}
)
if r.status_code == 200:
log.debug("POST request status code: {}".format(r.status_code))
print("Database response:")
db_answer = json.loads(r.text)
for key, value in db_answer.items():
print(" -> {}: {}".format(key, value))
if db_answer['Result'] == 'OK':
print("Upload successful.")
else:
log.critical("Something went wrong.")
else:
log.error("POST request status code: {}".format(r.status_code))
log.critical("Something went wrong...")
return |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:get_movie; 3, parameters; 3, 4; 4, identifier:tmdb_id; 5, block; 5, 6; 5, 8; 5, 14; 5, 23; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:redis_key; 11, binary_operator:%; 11, 12; 11, 13; 12, string:'m_%s'; 13, identifier:tmdb_id; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:cached; 17, call; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:redis_ro_conn; 20, identifier:get; 21, argument_list; 21, 22; 22, identifier:redis_key; 23, if_statement; 23, 24; 23, 25; 23, 31; 24, identifier:cached; 25, block; 25, 26; 26, return_statement; 26, 27; 27, call; 27, 28; 27, 29; 28, identifier:Response; 29, argument_list; 29, 30; 30, identifier:cached; 31, else_clause; 31, 32; 32, block; 32, 33; 32, 87; 32, 194; 32, 218; 32, 236; 32, 258; 32, 270; 32, 283; 33, try_statement; 33, 34; 33, 62; 34, block; 34, 35; 34, 44; 34, 53; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:details; 38, call; 38, 39; 38, 40; 39, identifier:get_on_tmdb; 40, argument_list; 40, 41; 41, binary_operator:%; 41, 42; 41, 43; 42, string:u'/movie/%d'; 43, identifier:tmdb_id; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:cast; 47, call; 47, 48; 47, 49; 48, identifier:get_on_tmdb; 49, argument_list; 49, 50; 50, binary_operator:%; 50, 51; 50, 52; 51, string:u'/movie/%d/casts'; 52, identifier:tmdb_id; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:alternative; 56, call; 56, 57; 56, 58; 57, identifier:get_on_tmdb; 58, argument_list; 58, 59; 59, binary_operator:%; 59, 60; 59, 61; 60, string:u'/movie/%d/alternative_titles'; 61, identifier:tmdb_id; 62, except_clause; 62, 63; 62, 69; 63, as_pattern; 63, 64; 63, 67; 64, attribute; 64, 65; 64, 66; 65, identifier:requests; 66, identifier:HTTPError; 67, as_pattern_target; 67, 68; 68, identifier:err; 69, block; 69, 70; 70, return_statement; 70, 71; 71, call; 71, 72; 71, 73; 72, identifier:Response; 73, argument_list; 73, 74; 73, 80; 74, binary_operator:%; 74, 75; 74, 76; 75, string:'TMDB API error: %s'; 76, call; 76, 77; 76, 78; 77, identifier:str; 78, argument_list; 78, 79; 79, identifier:err; 80, keyword_argument; 80, 81; 80, 82; 81, identifier:status; 82, attribute; 82, 83; 82, 86; 83, attribute; 83, 84; 83, 85; 84, identifier:err; 85, identifier:response; 86, identifier:status_code; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:movie; 90, dictionary; 90, 91; 90, 96; 90, 101; 90, 124; 90, 141; 90, 152; 90, 163; 90, 174; 90, 191; 91, pair; 91, 92; 91, 93; 92, string:'title'; 93, subscript; 93, 94; 93, 95; 94, identifier:details; 95, string:'original_title'; 96, pair; 96, 97; 96, 98; 97, string:'score'; 98, subscript; 98, 99; 98, 100; 99, identifier:details; 100, string:'popularity'; 101, pair; 101, 102; 101, 103; 102, string:'directors'; 103, list_comprehension; 103, 104; 103, 107; 103, 112; 104, subscript; 104, 105; 104, 106; 105, identifier:x; 106, string:'name'; 107, for_in_clause; 107, 108; 107, 109; 108, identifier:x; 109, subscript; 109, 110; 109, 111; 110, identifier:cast; 111, string:'crew'; 112, if_clause; 112, 113; 113, boolean_operator:and; 113, 114; 113, 119; 114, comparison_operator:==; 114, 115; 114, 118; 115, subscript; 115, 116; 115, 117; 116, identifier:x; 117, string:'department'; 118, string:'Directing'; 119, comparison_operator:==; 119, 120; 119, 123; 120, subscript; 120, 121; 120, 122; 121, identifier:x; 122, string:'job'; 123, string:'Director'; 124, pair; 124, 125; 124, 126; 125, string:'writers'; 126, list_comprehension; 126, 127; 126, 130; 126, 135; 127, subscript; 127, 128; 127, 129; 128, identifier:x; 129, string:'name'; 130, for_in_clause; 130, 131; 130, 132; 131, identifier:x; 132, subscript; 132, 133; 132, 134; 133, identifier:cast; 134, string:'crew'; 135, if_clause; 135, 136; 136, comparison_operator:==; 136, 137; 136, 140; 137, subscript; 137, 138; 137, 139; 138, identifier:x; 139, string:'department'; 140, string:'Writing'; 141, pair; 141, 142; 141, 143; 142, string:'cast'; 143, list_comprehension; 143, 144; 143, 147; 144, subscript; 144, 145; 144, 146; 145, identifier:x; 146, string:'name'; 147, for_in_clause; 147, 148; 147, 149; 148, identifier:x; 149, subscript; 149, 150; 149, 151; 150, identifier:cast; 151, string:'cast'; 152, pair; 152, 153; 152, 154; 153, string:'genres'; 154, list_comprehension; 154, 155; 154, 158; 155, subscript; 155, 156; 155, 157; 156, identifier:x; 157, string:'name'; 158, for_in_clause; 158, 159; 158, 160; 159, identifier:x; 160, subscript; 160, 161; 160, 162; 161, identifier:details; 162, string:'genres'; 163, pair; 163, 164; 163, 165; 164, string:'countries'; 165, list_comprehension; 165, 166; 165, 169; 166, subscript; 166, 167; 166, 168; 167, identifier:x; 168, string:'name'; 169, for_in_clause; 169, 170; 169, 171; 170, identifier:x; 171, subscript; 171, 172; 171, 173; 172, identifier:details; 173, string:'production_countries'; 174, pair; 174, 175; 174, 176; 175, string:'tmdb_votes'; 176, call; 176, 177; 176, 178; 177, identifier:int; 178, argument_list; 178, 179; 179, call; 179, 180; 179, 181; 180, identifier:round; 181, argument_list; 181, 182; 182, binary_operator:*; 182, 183; 182, 190; 183, call; 183, 184; 183, 187; 184, attribute; 184, 185; 184, 186; 185, identifier:details; 186, identifier:get; 187, argument_list; 187, 188; 187, 189; 188, string:'vote_average'; 189, integer:0; 190, float:0.5; 191, pair; 191, 192; 191, 193; 192, string:'_tmdb_id'; 193, identifier:tmdb_id; 194, if_statement; 194, 195; 194, 201; 195, call; 195, 196; 195, 199; 196, attribute; 196, 197; 196, 198; 197, identifier:details; 198, identifier:get; 199, argument_list; 199, 200; 200, string:'release_date'; 201, block; 201, 202; 202, expression_statement; 202, 203; 203, assignment; 203, 204; 203, 207; 204, subscript; 204, 205; 204, 206; 205, identifier:movie; 206, string:'year'; 207, attribute; 207, 208; 207, 217; 208, call; 208, 209; 208, 212; 209, attribute; 209, 210; 209, 211; 210, identifier:datetime; 211, identifier:strptime; 212, argument_list; 212, 213; 212, 216; 213, subscript; 213, 214; 213, 215; 214, identifier:details; 215, string:'release_date'; 216, string:'%Y-%m-%d'; 217, identifier:year; 218, if_statement; 218, 219; 218, 225; 219, call; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:details; 222, identifier:get; 223, argument_list; 223, 224; 224, string:'belongs_to_collection'; 225, block; 225, 226; 226, expression_statement; 226, 227; 227, assignment; 227, 228; 227, 231; 228, subscript; 228, 229; 228, 230; 229, identifier:movie; 230, string:'collection'; 231, subscript; 231, 232; 231, 235; 232, subscript; 232, 233; 232, 234; 233, identifier:details; 234, string:'belongs_to_collection'; 235, string:'name'; 236, for_statement; 236, 237; 236, 238; 236, 241; 237, identifier:alt; 238, subscript; 238, 239; 238, 240; 239, identifier:alternative; 240, string:'titles'; 241, block; 241, 242; 242, expression_statement; 242, 243; 243, assignment; 243, 244; 243, 255; 244, subscript; 244, 245; 244, 246; 245, identifier:movie; 246, binary_operator:%; 246, 247; 246, 248; 247, string:'title_%s'; 248, call; 248, 249; 248, 254; 249, attribute; 249, 250; 249, 253; 250, subscript; 250, 251; 250, 252; 251, identifier:alt; 252, string:'iso_3166_1'; 253, identifier:lower; 254, argument_list; 255, subscript; 255, 256; 255, 257; 256, identifier:alt; 257, string:'title'; 258, expression_statement; 258, 259; 259, assignment; 259, 260; 259, 261; 260, identifier:json_response; 261, call; 261, 262; 261, 265; 262, attribute; 262, 263; 262, 264; 263, identifier:json; 264, identifier:dumps; 265, argument_list; 265, 266; 266, dictionary; 266, 267; 267, pair; 267, 268; 267, 269; 268, string:'movie'; 269, identifier:movie; 270, expression_statement; 270, 271; 271, call; 271, 272; 271, 275; 272, attribute; 272, 273; 272, 274; 273, identifier:redis_conn; 274, identifier:setex; 275, argument_list; 275, 276; 275, 277; 275, 282; 276, identifier:redis_key; 277, subscript; 277, 278; 277, 281; 278, attribute; 278, 279; 278, 280; 279, identifier:app; 280, identifier:config; 281, string:'CACHE_TTL'; 282, identifier:json_response; 283, return_statement; 283, 284; 284, call; 284, 285; 284, 286; 285, identifier:Response; 286, argument_list; 286, 287; 287, identifier:json_response | def get_movie(tmdb_id):
""" Get informations about a movie using its tmdb id.
"""
redis_key = 'm_%s' % tmdb_id
cached = redis_ro_conn.get(redis_key)
if cached:
return Response(cached)
else:
try:
details = get_on_tmdb(u'/movie/%d' % tmdb_id)
cast = get_on_tmdb(u'/movie/%d/casts' % tmdb_id)
alternative = get_on_tmdb(u'/movie/%d/alternative_titles' % tmdb_id)
except requests.HTTPError as err:
return Response('TMDB API error: %s' % str(err), status=err.response.status_code)
movie = {'title': details['original_title'],
'score': details['popularity'],
'directors': [x['name'] for x in cast['crew'] if x['department'] == 'Directing' and x['job'] == 'Director'],
'writers': [x['name'] for x in cast['crew'] if x['department'] == 'Writing'],
'cast': [x['name'] for x in cast['cast']],
'genres': [x['name'] for x in details['genres']],
'countries': [x['name'] for x in details['production_countries']],
'tmdb_votes': int(round(details.get('vote_average', 0) * 0.5)),
'_tmdb_id': tmdb_id}
if details.get('release_date'):
movie['year'] = datetime.strptime(details['release_date'], '%Y-%m-%d').year
if details.get('belongs_to_collection'):
movie['collection'] = details['belongs_to_collection']['name']
for alt in alternative['titles']:
movie['title_%s' % alt['iso_3166_1'].lower()] = alt['title']
json_response = json.dumps({'movie': movie})
redis_conn.setex(redis_key, app.config['CACHE_TTL'], json_response)
return Response(json_response) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 13; 2, function_name:parse_pattern; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:format_string; 5, identifier:env; 6, default_parameter; 6, 7; 6, 8; 7, identifier:wrapper; 8, lambda; 8, 9; 8, 12; 9, lambda_parameters; 9, 10; 9, 11; 10, identifier:x; 11, identifier:y; 12, identifier:y; 13, block; 13, 14; 13, 16; 13, 22; 13, 43; 13, 47; 13, 48; 13, 142; 14, expression_statement; 14, 15; 15, comment; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:formatter; 19, call; 19, 20; 19, 21; 20, identifier:Formatter; 21, argument_list; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:fields; 25, list_comprehension; 25, 26; 25, 29; 25, 37; 26, subscript; 26, 27; 26, 28; 27, identifier:x; 28, integer:1; 29, for_in_clause; 29, 30; 29, 31; 30, identifier:x; 31, call; 31, 32; 31, 35; 32, attribute; 32, 33; 32, 34; 33, identifier:formatter; 34, identifier:parse; 35, argument_list; 35, 36; 36, identifier:format_string; 37, if_clause; 37, 38; 38, comparison_operator:is; 38, 39; 38, 42; 39, subscript; 39, 40; 39, 41; 40, identifier:x; 41, integer:1; 42, None; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 46; 45, identifier:prepared_env; 46, dictionary; 47, comment; 48, for_statement; 48, 49; 48, 50; 48, 51; 48, 52; 48, 53; 49, identifier:field; 50, identifier:fields; 51, comment; 52, comment; 53, block; 53, 54; 53, 119; 53, 132; 54, for_statement; 54, 55; 54, 56; 54, 70; 54, 71; 54, 113; 55, identifier:field_alt; 56, generator_expression; 56, 57; 56, 62; 57, call; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:x; 60, identifier:strip; 61, argument_list; 62, for_in_clause; 62, 63; 62, 64; 63, identifier:x; 64, call; 64, 65; 64, 68; 65, attribute; 65, 66; 65, 67; 66, identifier:field; 67, identifier:split; 68, argument_list; 68, 69; 69, string:'|'; 70, comment; 71, block; 71, 72; 71, 107; 72, if_statement; 72, 73; 72, 85; 72, 96; 73, boolean_operator:and; 73, 74; 73, 79; 74, comparison_operator:in; 74, 75; 74, 78; 75, subscript; 75, 76; 75, 77; 76, identifier:field_alt; 77, integer:0; 78, string:'\'"'; 79, comparison_operator:in; 79, 80; 79, 84; 80, subscript; 80, 81; 80, 82; 81, identifier:field_alt; 82, unary_operator:-; 82, 83; 83, integer:1; 84, string:'\'"'; 85, block; 85, 86; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:field_values; 89, subscript; 89, 90; 89, 91; 90, identifier:field_alt; 91, slice; 91, 92; 91, 93; 91, 94; 92, integer:1; 93, colon; 94, unary_operator:-; 94, 95; 95, integer:1; 96, else_clause; 96, 97; 97, block; 97, 98; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:field_values; 101, call; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:env; 104, identifier:get; 105, argument_list; 105, 106; 106, identifier:field_alt; 107, if_statement; 107, 108; 107, 111; 108, comparison_operator:is; 108, 109; 108, 110; 109, identifier:field_values; 110, None; 111, block; 111, 112; 112, break_statement; 113, else_clause; 113, 114; 114, block; 114, 115; 115, expression_statement; 115, 116; 116, assignment; 116, 117; 116, 118; 117, identifier:field_values; 118, list:[]; 119, if_statement; 119, 120; 119, 126; 120, not_operator; 120, 121; 121, call; 121, 122; 121, 123; 122, identifier:isinstance; 123, argument_list; 123, 124; 123, 125; 124, identifier:field_values; 125, identifier:list; 126, block; 126, 127; 127, expression_statement; 127, 128; 128, assignment; 128, 129; 128, 130; 129, identifier:field_values; 130, list:[field_values]; 130, 131; 131, identifier:field_values; 132, expression_statement; 132, 133; 133, assignment; 133, 134; 133, 137; 134, subscript; 134, 135; 134, 136; 135, identifier:prepared_env; 136, identifier:field; 137, call; 137, 138; 137, 139; 138, identifier:wrapper; 139, argument_list; 139, 140; 139, 141; 140, identifier:field_alt; 141, identifier:field_values; 142, return_statement; 142, 143; 143, identifier:prepared_env | def parse_pattern(format_string, env, wrapper=lambda x, y: y):
""" Parse the format_string and return prepared data according to the env.
Pick each field found in the format_string from the env(ironment), apply
the wrapper on each data and return a mapping between field-to-replace and
values for each.
"""
formatter = Formatter()
fields = [x[1] for x in formatter.parse(format_string) if x[1] is not None]
prepared_env = {}
# Create a prepared environment with only used fields, all as list:
for field in fields:
# Search for a movie attribute for each alternative field separated
# by a pipe sign:
for field_alt in (x.strip() for x in field.split('|')):
# Handle default values (enclosed by quotes):
if field_alt[0] in '\'"' and field_alt[-1] in '\'"':
field_values = field_alt[1:-1]
else:
field_values = env.get(field_alt)
if field_values is not None:
break
else:
field_values = []
if not isinstance(field_values, list):
field_values = [field_values]
prepared_env[field] = wrapper(field_alt, field_values)
return prepared_env |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 26; 2, function_name:calibrate_dom; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 10; 3, 13; 3, 16; 3, 19; 3, 22; 4, identifier:dom_id; 5, identifier:data; 6, identifier:detector; 7, default_parameter; 7, 8; 7, 9; 8, identifier:livetime; 9, None; 10, default_parameter; 10, 11; 10, 12; 11, identifier:fit_ang_dist; 12, False; 13, default_parameter; 13, 14; 13, 15; 14, identifier:scale_mc_to_data; 15, True; 16, default_parameter; 16, 17; 16, 18; 17, identifier:ad_fit_shape; 18, string:'pexp'; 19, default_parameter; 19, 20; 19, 21; 20, identifier:fit_background; 21, True; 22, default_parameter; 22, 23; 22, 24; 23, identifier:ctmin; 24, unary_operator:-; 24, 25; 25, float:1.; 26, block; 26, 27; 26, 29; 26, 91; 26, 110; 26, 118; 26, 127; 26, 135; 26, 143; 26, 151; 26, 177; 26, 197; 26, 198; 26, 202; 26, 293; 26, 294; 26, 312; 26, 321; 26, 330; 26, 340; 26, 351; 26, 362; 26, 372; 26, 383; 26, 392; 26, 459; 27, expression_statement; 27, 28; 28, comment; 29, if_statement; 29, 30; 29, 35; 30, call; 30, 31; 30, 32; 31, identifier:isinstance; 32, argument_list; 32, 33; 32, 34; 33, identifier:data; 34, identifier:str; 35, block; 35, 36; 35, 40; 35, 50; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:filename; 39, identifier:data; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:loaders; 43, dictionary; 43, 44; 43, 47; 44, pair; 44, 45; 44, 46; 45, string:'.h5'; 46, identifier:load_k40_coincidences_from_hdf5; 47, pair; 47, 48; 47, 49; 48, string:'.root'; 49, identifier:load_k40_coincidences_from_rootfile; 50, try_statement; 50, 51; 50, 67; 50, 79; 51, block; 51, 52; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:loader; 55, subscript; 55, 56; 55, 57; 56, identifier:loaders; 57, subscript; 57, 58; 57, 66; 58, call; 58, 59; 58, 64; 59, attribute; 59, 60; 59, 63; 60, attribute; 60, 61; 60, 62; 61, identifier:os; 62, identifier:path; 63, identifier:splitext; 64, argument_list; 64, 65; 65, identifier:filename; 66, integer:1; 67, except_clause; 67, 68; 67, 69; 68, identifier:KeyError; 69, block; 69, 70; 69, 77; 70, expression_statement; 70, 71; 71, call; 71, 72; 71, 75; 72, attribute; 72, 73; 72, 74; 73, identifier:log; 74, identifier:critical; 75, argument_list; 75, 76; 76, string:'File format not supported.'; 77, raise_statement; 77, 78; 78, identifier:IOError; 79, else_clause; 79, 80; 80, block; 80, 81; 81, expression_statement; 81, 82; 82, assignment; 82, 83; 82, 86; 83, pattern_list; 83, 84; 83, 85; 84, identifier:data; 85, identifier:livetime; 86, call; 86, 87; 86, 88; 87, identifier:loader; 88, argument_list; 88, 89; 88, 90; 89, identifier:filename; 90, identifier:dom_id; 91, expression_statement; 91, 92; 92, assignment; 92, 93; 92, 94; 93, identifier:combs; 94, call; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:np; 97, identifier:array; 98, argument_list; 98, 99; 99, call; 99, 100; 99, 101; 100, identifier:list; 101, argument_list; 101, 102; 102, call; 102, 103; 102, 104; 103, identifier:combinations; 104, argument_list; 104, 105; 104, 109; 105, call; 105, 106; 105, 107; 106, identifier:range; 107, argument_list; 107, 108; 108, integer:31; 109, integer:2; 110, expression_statement; 110, 111; 111, assignment; 111, 112; 111, 113; 112, identifier:angles; 113, call; 113, 114; 113, 115; 114, identifier:calculate_angles; 115, argument_list; 115, 116; 115, 117; 116, identifier:detector; 117, identifier:combs; 118, expression_statement; 118, 119; 119, assignment; 119, 120; 119, 121; 120, identifier:cos_angles; 121, call; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:np; 124, identifier:cos; 125, argument_list; 125, 126; 126, identifier:angles; 127, expression_statement; 127, 128; 128, assignment; 128, 129; 128, 130; 129, identifier:angles; 130, subscript; 130, 131; 130, 132; 131, identifier:angles; 132, comparison_operator:>=; 132, 133; 132, 134; 133, identifier:cos_angles; 134, identifier:ctmin; 135, expression_statement; 135, 136; 136, assignment; 136, 137; 136, 138; 137, identifier:data; 138, subscript; 138, 139; 138, 140; 139, identifier:data; 140, comparison_operator:>=; 140, 141; 140, 142; 141, identifier:cos_angles; 142, identifier:ctmin; 143, expression_statement; 143, 144; 144, assignment; 144, 145; 144, 146; 145, identifier:combs; 146, subscript; 146, 147; 146, 148; 147, identifier:combs; 148, comparison_operator:>=; 148, 149; 148, 150; 149, identifier:cos_angles; 150, identifier:ctmin; 151, try_statement; 151, 152; 151, 173; 152, block; 152, 153; 152, 164; 153, expression_statement; 153, 154; 154, assignment; 154, 155; 154, 156; 155, identifier:fit_res; 156, call; 156, 157; 156, 158; 157, identifier:fit_delta_ts; 158, argument_list; 158, 159; 158, 160; 158, 161; 159, identifier:data; 160, identifier:livetime; 161, keyword_argument; 161, 162; 161, 163; 162, identifier:fit_background; 163, identifier:fit_background; 164, expression_statement; 164, 165; 165, assignment; 165, 166; 165, 172; 166, pattern_list; 166, 167; 166, 168; 166, 169; 166, 170; 166, 171; 167, identifier:rates; 168, identifier:means; 169, identifier:sigmas; 170, identifier:popts; 171, identifier:pcovs; 172, identifier:fit_res; 173, except_clause; 173, 174; 174, block; 174, 175; 175, return_statement; 175, 176; 176, integer:0; 177, expression_statement; 177, 178; 178, assignment; 178, 179; 178, 180; 179, identifier:rate_errors; 180, call; 180, 181; 180, 184; 181, attribute; 181, 182; 181, 183; 182, identifier:np; 183, identifier:array; 184, argument_list; 184, 185; 185, list_comprehension; 185, 186; 185, 194; 186, subscript; 186, 187; 186, 193; 187, call; 187, 188; 187, 191; 188, attribute; 188, 189; 188, 190; 189, identifier:np; 190, identifier:diag; 191, argument_list; 191, 192; 192, identifier:pc; 193, integer:2; 194, for_in_clause; 194, 195; 194, 196; 195, identifier:pc; 196, identifier:pcovs; 197, comment; 198, expression_statement; 198, 199; 199, assignment; 199, 200; 199, 201; 200, identifier:scale_factor; 201, None; 202, if_statement; 202, 203; 202, 204; 202, 224; 203, identifier:fit_ang_dist; 204, block; 204, 205; 204, 217; 205, expression_statement; 205, 206; 206, assignment; 206, 207; 206, 208; 207, identifier:fit_res; 208, call; 208, 209; 208, 210; 209, identifier:fit_angular_distribution; 210, argument_list; 210, 211; 210, 212; 210, 213; 210, 214; 211, identifier:angles; 212, identifier:rates; 213, identifier:rate_errors; 214, keyword_argument; 214, 215; 214, 216; 215, identifier:shape; 216, identifier:ad_fit_shape; 217, expression_statement; 217, 218; 218, assignment; 218, 219; 218, 223; 219, pattern_list; 219, 220; 219, 221; 219, 222; 220, identifier:fitted_rates; 221, identifier:exp_popts; 222, identifier:exp_pcov; 223, identifier:fit_res; 224, else_clause; 224, 225; 225, block; 225, 226; 225, 240; 225, 274; 225, 280; 225, 284; 225, 288; 226, expression_statement; 226, 227; 227, assignment; 227, 228; 227, 229; 228, identifier:mc_fitted_rates; 229, call; 229, 230; 229, 231; 230, identifier:exponential_polinomial; 231, argument_list; 231, 232; 231, 238; 232, call; 232, 233; 232, 236; 233, attribute; 233, 234; 233, 235; 234, identifier:np; 235, identifier:cos; 236, argument_list; 236, 237; 237, identifier:angles; 238, list_splat; 238, 239; 239, identifier:MC_ANG_DIST; 240, if_statement; 240, 241; 240, 242; 240, 268; 241, identifier:scale_mc_to_data; 242, block; 242, 243; 243, expression_statement; 243, 244; 244, assignment; 244, 245; 244, 246; 245, identifier:scale_factor; 246, binary_operator:/; 246, 247; 246, 257; 246, 258; 247, call; 247, 248; 247, 251; 248, attribute; 248, 249; 248, 250; 249, identifier:np; 250, identifier:mean; 251, argument_list; 251, 252; 252, subscript; 252, 253; 252, 254; 253, identifier:rates; 254, comparison_operator:<; 254, 255; 254, 256; 255, identifier:angles; 256, float:1.5; 257, line_continuation:\; 258, call; 258, 259; 258, 262; 259, attribute; 259, 260; 259, 261; 260, identifier:np; 261, identifier:mean; 262, argument_list; 262, 263; 263, subscript; 263, 264; 263, 265; 264, identifier:mc_fitted_rates; 265, comparison_operator:<; 265, 266; 265, 267; 266, identifier:angles; 267, float:1.5; 268, else_clause; 268, 269; 269, block; 269, 270; 270, expression_statement; 270, 271; 271, assignment; 271, 272; 271, 273; 272, identifier:scale_factor; 273, float:1.; 274, expression_statement; 274, 275; 275, assignment; 275, 276; 275, 277; 276, identifier:fitted_rates; 277, binary_operator:*; 277, 278; 277, 279; 278, identifier:mc_fitted_rates; 279, identifier:scale_factor; 280, expression_statement; 280, 281; 281, assignment; 281, 282; 281, 283; 282, identifier:exp_popts; 283, list:[]; 284, expression_statement; 284, 285; 285, assignment; 285, 286; 285, 287; 286, identifier:exp_pcov; 287, list:[]; 288, expression_statement; 288, 289; 289, call; 289, 290; 289, 291; 290, identifier:print; 291, argument_list; 291, 292; 292, string:'Using angular distribution from Monte Carlo'; 293, comment; 294, if_statement; 294, 295; 294, 297; 294, 306; 295, not_operator; 295, 296; 296, identifier:fit_background; 297, block; 297, 298; 298, expression_statement; 298, 299; 299, assignment; 299, 300; 299, 301; 300, identifier:minimize_weights; 301, call; 301, 302; 301, 303; 302, identifier:calculate_weights; 303, argument_list; 303, 304; 303, 305; 304, identifier:fitted_rates; 305, identifier:data; 306, else_clause; 306, 307; 307, block; 307, 308; 308, expression_statement; 308, 309; 309, assignment; 309, 310; 309, 311; 310, identifier:minimize_weights; 311, identifier:fitted_rates; 312, expression_statement; 312, 313; 313, assignment; 313, 314; 313, 315; 314, identifier:opt_t0s; 315, call; 315, 316; 315, 317; 316, identifier:minimize_t0s; 317, argument_list; 317, 318; 317, 319; 317, 320; 318, identifier:means; 319, identifier:minimize_weights; 320, identifier:combs; 321, expression_statement; 321, 322; 322, assignment; 322, 323; 322, 324; 323, identifier:opt_sigmas; 324, call; 324, 325; 324, 326; 325, identifier:minimize_sigmas; 326, argument_list; 326, 327; 326, 328; 326, 329; 327, identifier:sigmas; 328, identifier:minimize_weights; 329, identifier:combs; 330, expression_statement; 330, 331; 331, assignment; 331, 332; 331, 333; 332, identifier:opt_qes; 333, call; 333, 334; 333, 335; 334, identifier:minimize_qes; 335, argument_list; 335, 336; 335, 337; 335, 338; 335, 339; 336, identifier:fitted_rates; 337, identifier:rates; 338, identifier:minimize_weights; 339, identifier:combs; 340, expression_statement; 340, 341; 341, assignment; 341, 342; 341, 343; 342, identifier:corrected_means; 343, call; 343, 344; 343, 345; 344, identifier:correct_means; 345, argument_list; 345, 346; 345, 347; 345, 350; 346, identifier:means; 347, attribute; 347, 348; 347, 349; 348, identifier:opt_t0s; 349, identifier:x; 350, identifier:combs; 351, expression_statement; 351, 352; 352, assignment; 352, 353; 352, 354; 353, identifier:corrected_rates; 354, call; 354, 355; 354, 356; 355, identifier:correct_rates; 356, argument_list; 356, 357; 356, 358; 356, 361; 357, identifier:rates; 358, attribute; 358, 359; 358, 360; 359, identifier:opt_qes; 360, identifier:x; 361, identifier:combs; 362, expression_statement; 362, 363; 363, assignment; 363, 364; 363, 367; 364, pattern_list; 364, 365; 364, 366; 365, identifier:rms_means; 366, identifier:rms_corrected_means; 367, call; 367, 368; 367, 369; 368, identifier:calculate_rms_means; 369, argument_list; 369, 370; 369, 371; 370, identifier:means; 371, identifier:corrected_means; 372, expression_statement; 372, 373; 373, assignment; 373, 374; 373, 377; 374, pattern_list; 374, 375; 374, 376; 375, identifier:rms_rates; 376, identifier:rms_corrected_rates; 377, call; 377, 378; 377, 379; 378, identifier:calculate_rms_rates; 379, argument_list; 379, 380; 379, 381; 379, 382; 380, identifier:rates; 381, identifier:fitted_rates; 382, identifier:corrected_rates; 383, expression_statement; 383, 384; 384, assignment; 384, 385; 384, 386; 385, identifier:cos_angles; 386, call; 386, 387; 386, 390; 387, attribute; 387, 388; 387, 389; 388, identifier:np; 389, identifier:cos; 390, argument_list; 390, 391; 391, identifier:angles; 392, expression_statement; 392, 393; 393, assignment; 393, 394; 393, 395; 394, identifier:return_data; 395, dictionary; 395, 396; 395, 399; 395, 402; 395, 405; 395, 408; 395, 411; 395, 414; 395, 417; 395, 420; 395, 423; 395, 426; 395, 429; 395, 432; 395, 435; 395, 438; 395, 441; 395, 444; 395, 447; 395, 450; 395, 453; 395, 456; 396, pair; 396, 397; 396, 398; 397, string:'opt_t0s'; 398, identifier:opt_t0s; 399, pair; 399, 400; 399, 401; 400, string:'opt_qes'; 401, identifier:opt_qes; 402, pair; 402, 403; 402, 404; 403, string:'data'; 404, identifier:data; 405, pair; 405, 406; 405, 407; 406, string:'means'; 407, identifier:means; 408, pair; 408, 409; 408, 410; 409, string:'rates'; 410, identifier:rates; 411, pair; 411, 412; 411, 413; 412, string:'fitted_rates'; 413, identifier:fitted_rates; 414, pair; 414, 415; 414, 416; 415, string:'angles'; 416, identifier:angles; 417, pair; 417, 418; 417, 419; 418, string:'corrected_means'; 419, identifier:corrected_means; 420, pair; 420, 421; 420, 422; 421, string:'corrected_rates'; 422, identifier:corrected_rates; 423, pair; 423, 424; 423, 425; 424, string:'rms_means'; 425, identifier:rms_means; 426, pair; 426, 427; 426, 428; 427, string:'rms_corrected_means'; 428, identifier:rms_corrected_means; 429, pair; 429, 430; 429, 431; 430, string:'rms_rates'; 431, identifier:rms_rates; 432, pair; 432, 433; 432, 434; 433, string:'rms_corrected_rates'; 434, identifier:rms_corrected_rates; 435, pair; 435, 436; 435, 437; 436, string:'gaussian_popts'; 437, identifier:popts; 438, pair; 438, 439; 438, 440; 439, string:'livetime'; 440, identifier:livetime; 441, pair; 441, 442; 441, 443; 442, string:'exp_popts'; 443, identifier:exp_popts; 444, pair; 444, 445; 444, 446; 445, string:'exp_pcov'; 446, identifier:exp_pcov; 447, pair; 447, 448; 447, 449; 448, string:'scale_factor'; 449, identifier:scale_factor; 450, pair; 450, 451; 450, 452; 451, string:'opt_sigmas'; 452, identifier:opt_sigmas; 453, pair; 453, 454; 453, 455; 454, string:'sigmas'; 455, identifier:sigmas; 456, pair; 456, 457; 456, 458; 457, string:'combs'; 458, identifier:combs; 459, return_statement; 459, 460; 460, identifier:return_data | def calibrate_dom(
dom_id,
data,
detector,
livetime=None,
fit_ang_dist=False,
scale_mc_to_data=True,
ad_fit_shape='pexp',
fit_background=True,
ctmin=-1.
):
"""Calibrate intra DOM PMT time offsets, efficiencies and sigmas
Parameters
----------
dom_id: DOM ID
data: dict of coincidences or root or hdf5 file
detector: instance of detector class
livetime: data-taking duration [s]
fixed_ang_dist: fixing angular distribution e.g. for data mc comparison
auto_scale: auto scales the fixed angular distribution to the data
Returns
-------
return_data: dictionary with fit results
"""
if isinstance(data, str):
filename = data
loaders = {
'.h5': load_k40_coincidences_from_hdf5,
'.root': load_k40_coincidences_from_rootfile
}
try:
loader = loaders[os.path.splitext(filename)[1]]
except KeyError:
log.critical('File format not supported.')
raise IOError
else:
data, livetime = loader(filename, dom_id)
combs = np.array(list(combinations(range(31), 2)))
angles = calculate_angles(detector, combs)
cos_angles = np.cos(angles)
angles = angles[cos_angles >= ctmin]
data = data[cos_angles >= ctmin]
combs = combs[cos_angles >= ctmin]
try:
fit_res = fit_delta_ts(data, livetime, fit_background=fit_background)
rates, means, sigmas, popts, pcovs = fit_res
except:
return 0
rate_errors = np.array([np.diag(pc)[2] for pc in pcovs])
# mean_errors = np.array([np.diag(pc)[0] for pc in pcovs])
scale_factor = None
if fit_ang_dist:
fit_res = fit_angular_distribution(
angles, rates, rate_errors, shape=ad_fit_shape
)
fitted_rates, exp_popts, exp_pcov = fit_res
else:
mc_fitted_rates = exponential_polinomial(np.cos(angles), *MC_ANG_DIST)
if scale_mc_to_data:
scale_factor = np.mean(rates[angles < 1.5]) / \
np.mean(mc_fitted_rates[angles < 1.5])
else:
scale_factor = 1.
fitted_rates = mc_fitted_rates * scale_factor
exp_popts = []
exp_pcov = []
print('Using angular distribution from Monte Carlo')
# t0_weights = np.array([0. if a>1. else 1. for a in angles])
if not fit_background:
minimize_weights = calculate_weights(fitted_rates, data)
else:
minimize_weights = fitted_rates
opt_t0s = minimize_t0s(means, minimize_weights, combs)
opt_sigmas = minimize_sigmas(sigmas, minimize_weights, combs)
opt_qes = minimize_qes(fitted_rates, rates, minimize_weights, combs)
corrected_means = correct_means(means, opt_t0s.x, combs)
corrected_rates = correct_rates(rates, opt_qes.x, combs)
rms_means, rms_corrected_means = calculate_rms_means(
means, corrected_means
)
rms_rates, rms_corrected_rates = calculate_rms_rates(
rates, fitted_rates, corrected_rates
)
cos_angles = np.cos(angles)
return_data = {
'opt_t0s': opt_t0s,
'opt_qes': opt_qes,
'data': data,
'means': means,
'rates': rates,
'fitted_rates': fitted_rates,
'angles': angles,
'corrected_means': corrected_means,
'corrected_rates': corrected_rates,
'rms_means': rms_means,
'rms_corrected_means': rms_corrected_means,
'rms_rates': rms_rates,
'rms_corrected_rates': rms_corrected_rates,
'gaussian_popts': popts,
'livetime': livetime,
'exp_popts': exp_popts,
'exp_pcov': exp_pcov,
'scale_factor': scale_factor,
'opt_sigmas': opt_sigmas,
'sigmas': sigmas,
'combs': combs
}
return return_data |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 17; 2, function_name:analyze; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:segments; 5, identifier:analysis; 6, default_parameter; 6, 7; 6, 8; 7, identifier:lookup; 8, call; 8, 9; 8, 10; 9, identifier:dict; 10, argument_list; 10, 11; 10, 14; 11, keyword_argument; 11, 12; 11, 13; 12, identifier:bipa; 13, dictionary; 14, keyword_argument; 14, 15; 14, 16; 15, identifier:dolgo; 16, dictionary; 17, block; 17, 18; 17, 20; 17, 21; 17, 30; 17, 31; 17, 32; 17, 51; 17, 52; 17, 153; 17, 154; 17, 155; 17, 156; 17, 157; 17, 188; 17, 189; 17, 190; 17, 269; 18, expression_statement; 18, 19; 19, comment; 20, comment; 21, if_statement; 21, 22; 21, 24; 22, not_operator; 22, 23; 23, identifier:segments; 24, block; 24, 25; 25, raise_statement; 25, 26; 26, call; 26, 27; 26, 28; 27, identifier:ValueError; 28, argument_list; 28, 29; 29, string:'Empty sequence.'; 30, comment; 31, comment; 32, if_statement; 32, 33; 32, 45; 33, not_operator; 33, 34; 34, list_comprehension; 34, 35; 34, 36; 34, 39; 35, identifier:segment; 36, for_in_clause; 36, 37; 36, 38; 37, identifier:segment; 38, identifier:segments; 39, if_clause; 39, 40; 40, call; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:segment; 43, identifier:strip; 44, argument_list; 45, block; 45, 46; 46, raise_statement; 46, 47; 47, call; 47, 48; 47, 49; 48, identifier:ValueError; 49, argument_list; 49, 50; 50, string:'No information in the sequence.'; 51, comment; 52, try_statement; 52, 53; 52, 144; 53, block; 53, 54; 53, 62; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 59; 56, pattern_list; 56, 57; 56, 58; 57, identifier:bipa_analysis; 58, identifier:sc_analysis; 59, expression_list; 59, 60; 59, 61; 60, list:[]; 61, list:[]; 62, for_statement; 62, 63; 62, 64; 62, 65; 63, identifier:s; 64, identifier:segments; 65, block; 65, 66; 65, 77; 65, 96; 65, 103; 65, 114; 65, 137; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:a; 69, call; 69, 70; 69, 75; 70, attribute; 70, 71; 70, 74; 71, subscript; 71, 72; 71, 73; 72, identifier:lookup; 73, string:'bipa'; 74, identifier:get; 75, argument_list; 75, 76; 76, identifier:s; 77, if_statement; 77, 78; 77, 81; 78, comparison_operator:is; 78, 79; 78, 80; 79, identifier:a; 80, None; 81, block; 81, 82; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 85; 84, identifier:a; 85, call; 85, 86; 85, 91; 86, attribute; 86, 87; 86, 90; 87, subscript; 87, 88; 87, 89; 88, identifier:lookup; 89, string:'bipa'; 90, identifier:setdefault; 91, argument_list; 91, 92; 91, 93; 92, identifier:s; 93, subscript; 93, 94; 93, 95; 94, identifier:BIPA; 95, identifier:s; 96, expression_statement; 96, 97; 97, call; 97, 98; 97, 101; 98, attribute; 98, 99; 98, 100; 99, identifier:bipa_analysis; 100, identifier:append; 101, argument_list; 101, 102; 102, identifier:a; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:sc; 106, call; 106, 107; 106, 112; 107, attribute; 107, 108; 107, 111; 108, subscript; 108, 109; 108, 110; 109, identifier:lookup; 110, string:'dolgo'; 111, identifier:get; 112, argument_list; 112, 113; 113, identifier:s; 114, if_statement; 114, 115; 114, 118; 115, comparison_operator:is; 115, 116; 115, 117; 116, identifier:sc; 117, None; 118, block; 118, 119; 119, expression_statement; 119, 120; 120, assignment; 120, 121; 120, 122; 121, identifier:sc; 122, call; 122, 123; 122, 128; 123, attribute; 123, 124; 123, 127; 124, subscript; 124, 125; 124, 126; 125, identifier:lookup; 126, string:'dolgo'; 127, identifier:setdefault; 128, argument_list; 128, 129; 128, 130; 129, identifier:s; 130, call; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:BIPA; 133, identifier:translate; 134, argument_list; 134, 135; 134, 136; 135, identifier:s; 136, identifier:DOLGO; 137, expression_statement; 137, 138; 138, call; 138, 139; 138, 142; 139, attribute; 139, 140; 139, 141; 140, identifier:sc_analysis; 141, identifier:append; 142, argument_list; 142, 143; 143, identifier:sc; 144, except_clause; 144, 145; 144, 146; 145, comment; 146, block; 146, 147; 146, 152; 147, expression_statement; 147, 148; 148, call; 148, 149; 148, 150; 149, identifier:print; 150, argument_list; 150, 151; 151, identifier:segments; 152, raise_statement; 153, comment; 154, comment; 155, comment; 156, comment; 157, for_statement; 157, 158; 157, 161; 157, 166; 158, pattern_list; 158, 159; 158, 160; 159, identifier:sound_bipa; 160, identifier:sound_class; 161, call; 161, 162; 161, 163; 162, identifier:zip; 163, argument_list; 163, 164; 163, 165; 164, identifier:bipa_analysis; 165, identifier:sc_analysis; 166, block; 166, 167; 167, if_statement; 167, 168; 167, 181; 168, boolean_operator:or; 168, 169; 168, 178; 169, call; 169, 170; 169, 171; 170, identifier:isinstance; 171, argument_list; 171, 172; 171, 173; 172, identifier:sound_bipa; 173, attribute; 173, 174; 173, 177; 174, attribute; 174, 175; 174, 176; 175, identifier:pyclts; 176, identifier:models; 177, identifier:UnknownSound; 178, comparison_operator:==; 178, 179; 178, 180; 179, identifier:sound_class; 180, string:'?'; 181, block; 181, 182; 182, expression_statement; 182, 183; 183, augmented_assignment:+=; 183, 184; 183, 187; 184, attribute; 184, 185; 184, 186; 185, identifier:analysis; 186, identifier:general_errors; 187, integer:1; 188, comment; 189, comment; 190, for_statement; 190, 191; 190, 195; 190, 201; 190, 202; 191, pattern_list; 191, 192; 191, 193; 191, 194; 192, identifier:segment; 193, identifier:sound_bipa; 194, identifier:sound_class; 195, call; 195, 196; 195, 197; 196, identifier:zip; 197, argument_list; 197, 198; 197, 199; 197, 200; 198, identifier:segments; 199, identifier:bipa_analysis; 200, identifier:sc_analysis; 201, comment; 202, block; 202, 203; 202, 213; 202, 214; 202, 215; 202, 254; 202, 255; 203, expression_statement; 203, 204; 204, call; 204, 205; 204, 210; 205, attribute; 205, 206; 205, 209; 206, attribute; 206, 207; 206, 208; 207, identifier:analysis; 208, identifier:segments; 209, identifier:update; 210, argument_list; 210, 211; 211, list:[segment]; 211, 212; 212, identifier:segment; 213, comment; 214, comment; 215, if_statement; 215, 216; 215, 225; 215, 235; 216, call; 216, 217; 216, 218; 217, identifier:isinstance; 218, argument_list; 218, 219; 218, 220; 219, identifier:sound_bipa; 220, attribute; 220, 221; 220, 224; 221, attribute; 221, 222; 221, 223; 222, identifier:pyclts; 223, identifier:models; 224, identifier:UnknownSound; 225, block; 225, 226; 226, expression_statement; 226, 227; 227, call; 227, 228; 227, 233; 228, attribute; 228, 229; 228, 232; 229, attribute; 229, 230; 229, 231; 230, identifier:analysis; 231, identifier:bipa_errors; 232, identifier:add; 233, argument_list; 233, 234; 234, identifier:segment; 235, else_clause; 235, 236; 236, block; 236, 237; 237, expression_statement; 237, 238; 238, call; 238, 239; 238, 248; 239, attribute; 239, 240; 239, 247; 240, subscript; 240, 241; 240, 244; 241, attribute; 241, 242; 241, 243; 242, identifier:analysis; 243, identifier:replacements; 244, attribute; 244, 245; 244, 246; 245, identifier:sound_bipa; 246, identifier:source; 247, identifier:add; 248, argument_list; 248, 249; 249, call; 249, 250; 249, 253; 250, attribute; 250, 251; 250, 252; 251, identifier:sound_bipa; 252, identifier:__unicode__; 253, argument_list; 254, comment; 255, if_statement; 255, 256; 255, 259; 256, comparison_operator:==; 256, 257; 256, 258; 257, identifier:sound_class; 258, string:'?'; 259, block; 259, 260; 260, expression_statement; 260, 261; 261, call; 261, 262; 261, 267; 262, attribute; 262, 263; 262, 266; 263, attribute; 263, 264; 263, 265; 264, identifier:analysis; 265, identifier:sclass_errors; 266, identifier:add; 267, argument_list; 267, 268; 268, identifier:segment; 269, return_statement; 269, 270; 270, expression_list; 270, 271; 270, 272; 270, 273; 270, 274; 271, identifier:segments; 272, identifier:bipa_analysis; 273, identifier:sc_analysis; 274, identifier:analysis | def analyze(segments, analysis, lookup=dict(bipa={}, dolgo={})):
"""
Test a sequence for compatibility with CLPA and LingPy.
:param analysis: Pass a `TranscriptionAnalysis` instance for cumulative reporting.
"""
# raise a ValueError in case of empty segments/strings
if not segments:
raise ValueError('Empty sequence.')
# test if at least one element in `segments` has information
# (helps to catch really badly formed input, such as ['\n']
if not [segment for segment in segments if segment.strip()]:
raise ValueError('No information in the sequence.')
# build the phonologic and sound class analyses
try:
bipa_analysis, sc_analysis = [], []
for s in segments:
a = lookup['bipa'].get(s)
if a is None:
a = lookup['bipa'].setdefault(s, BIPA[s])
bipa_analysis.append(a)
sc = lookup['dolgo'].get(s)
if sc is None:
sc = lookup['dolgo'].setdefault(s, BIPA.translate(s, DOLGO))
sc_analysis.append(sc)
except: # noqa
print(segments)
raise
# compute general errors; this loop must take place outside the
# following one because the code for computing single errors (either
# in `bipa_analysis` or in `soundclass_analysis`) is unnecessary
# complicated
for sound_bipa, sound_class in zip(bipa_analysis, sc_analysis):
if isinstance(sound_bipa, pyclts.models.UnknownSound) or sound_class == '?':
analysis.general_errors += 1
# iterate over the segments and analyses, updating counts of occurrences
# and specific errors
for segment, sound_bipa, sound_class in zip(segments, bipa_analysis, sc_analysis):
# update the segment count
analysis.segments.update([segment])
# add an error if we got an unknown sound, otherwise just append
# the `replacements` dictionary
if isinstance(sound_bipa, pyclts.models.UnknownSound):
analysis.bipa_errors.add(segment)
else:
analysis.replacements[sound_bipa.source].add(sound_bipa.__unicode__())
# update sound class errors, if any
if sound_class == '?':
analysis.sclass_errors.add(segment)
return segments, bipa_analysis, sc_analysis, analysis |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 15; 2, function_name:setup_limits; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 4, identifier:conf_file; 5, identifier:limits_file; 6, default_parameter; 6, 7; 6, 8; 7, identifier:do_reload; 8, True; 9, default_parameter; 9, 10; 9, 11; 10, identifier:dry_run; 11, False; 12, default_parameter; 12, 13; 12, 14; 13, identifier:debug; 14, False; 15, block; 15, 16; 15, 18; 15, 19; 15, 26; 15, 27; 15, 38; 15, 46; 15, 58; 15, 70; 15, 71; 15, 80; 15, 81; 15, 85; 15, 153; 15, 154; 15, 175; 15, 188; 15, 189; 15, 195; 15, 196; 15, 200; 15, 247; 15, 248; 15, 283; 16, expression_statement; 16, 17; 17, comment; 18, comment; 19, if_statement; 19, 20; 19, 21; 20, identifier:dry_run; 21, block; 21, 22; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:debug; 25, True; 26, comment; 27, expression_statement; 27, 28; 28, assignment; 28, 29; 28, 30; 29, identifier:conf; 30, call; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:config; 33, identifier:Config; 34, argument_list; 34, 35; 35, keyword_argument; 35, 36; 35, 37; 36, identifier:conf_file; 37, identifier:conf_file; 38, expression_statement; 38, 39; 39, assignment; 39, 40; 39, 41; 40, identifier:db; 41, call; 41, 42; 41, 45; 42, attribute; 42, 43; 42, 44; 43, identifier:conf; 44, identifier:get_database; 45, argument_list; 46, expression_statement; 46, 47; 47, assignment; 47, 48; 47, 49; 48, identifier:limits_key; 49, call; 49, 50; 49, 55; 50, attribute; 50, 51; 50, 54; 51, subscript; 51, 52; 51, 53; 52, identifier:conf; 53, string:'control'; 54, identifier:get; 55, argument_list; 55, 56; 55, 57; 56, string:'limits_key'; 57, string:'limits'; 58, expression_statement; 58, 59; 59, assignment; 59, 60; 59, 61; 60, identifier:control_channel; 61, call; 61, 62; 61, 67; 62, attribute; 62, 63; 62, 66; 63, subscript; 63, 64; 63, 65; 64, identifier:conf; 65, string:'control'; 66, identifier:get; 67, argument_list; 67, 68; 67, 69; 68, string:'channel'; 69, string:'control'; 70, comment; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:limits_tree; 74, call; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, identifier:etree; 77, identifier:parse; 78, argument_list; 78, 79; 79, identifier:limits_file; 80, comment; 81, expression_statement; 81, 82; 82, assignment; 82, 83; 82, 84; 83, identifier:lims; 84, list:[]; 85, for_statement; 85, 86; 85, 89; 85, 97; 85, 98; 86, pattern_list; 86, 87; 86, 88; 87, identifier:idx; 88, identifier:lim; 89, call; 89, 90; 89, 91; 90, identifier:enumerate; 91, argument_list; 91, 92; 92, call; 92, 93; 92, 96; 93, attribute; 93, 94; 93, 95; 94, identifier:limits_tree; 95, identifier:getroot; 96, argument_list; 97, comment; 98, block; 98, 99; 98, 120; 98, 121; 99, if_statement; 99, 100; 99, 105; 100, comparison_operator:!=; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:lim; 103, identifier:tag; 104, string:'limit'; 105, block; 105, 106; 105, 119; 106, expression_statement; 106, 107; 107, call; 107, 108; 107, 111; 108, attribute; 108, 109; 108, 110; 109, identifier:warnings; 110, identifier:warn; 111, argument_list; 111, 112; 112, binary_operator:%; 112, 113; 112, 114; 113, string:"Unrecognized tag %r in limits file at index %d"; 114, tuple; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, identifier:lim; 117, identifier:tag; 118, identifier:idx; 119, continue_statement; 120, comment; 121, try_statement; 121, 122; 121, 135; 122, block; 122, 123; 123, expression_statement; 123, 124; 124, call; 124, 125; 124, 128; 125, attribute; 125, 126; 125, 127; 126, identifier:lims; 127, identifier:append; 128, argument_list; 128, 129; 129, call; 129, 130; 129, 131; 130, identifier:parse_limit_node; 131, argument_list; 131, 132; 131, 133; 131, 134; 132, identifier:db; 133, identifier:idx; 134, identifier:lim; 135, except_clause; 135, 136; 135, 140; 136, as_pattern; 136, 137; 136, 138; 137, identifier:Exception; 138, as_pattern_target; 138, 139; 139, identifier:exc; 140, block; 140, 141; 140, 152; 141, expression_statement; 141, 142; 142, call; 142, 143; 142, 146; 143, attribute; 143, 144; 143, 145; 144, identifier:warnings; 145, identifier:warn; 146, argument_list; 146, 147; 147, binary_operator:%; 147, 148; 147, 149; 148, string:"Couldn't understand limit at index %d: %s"; 149, tuple; 149, 150; 149, 151; 150, identifier:idx; 151, identifier:exc; 152, continue_statement; 153, comment; 154, if_statement; 154, 155; 154, 156; 155, identifier:debug; 156, block; 156, 157; 156, 163; 157, print_statement; 157, 158; 157, 162; 158, chevron; 158, 159; 159, attribute; 159, 160; 159, 161; 160, identifier:sys; 161, identifier:stderr; 162, string:"Installing the following limits:"; 163, for_statement; 163, 164; 163, 165; 163, 166; 164, identifier:lim; 165, identifier:lims; 166, block; 166, 167; 167, print_statement; 167, 168; 167, 172; 168, chevron; 168, 169; 169, attribute; 169, 170; 169, 171; 170, identifier:sys; 171, identifier:stderr; 172, binary_operator:%; 172, 173; 172, 174; 173, string:" %r"; 174, identifier:lim; 175, if_statement; 175, 176; 175, 178; 176, not_operator; 176, 177; 177, identifier:dry_run; 178, block; 178, 179; 179, expression_statement; 179, 180; 180, call; 180, 181; 180, 184; 181, attribute; 181, 182; 181, 183; 182, identifier:database; 183, identifier:limit_update; 184, argument_list; 184, 185; 184, 186; 184, 187; 185, identifier:db; 186, identifier:limits_key; 187, identifier:lims; 188, comment; 189, if_statement; 189, 190; 189, 193; 190, comparison_operator:is; 190, 191; 190, 192; 191, identifier:do_reload; 192, False; 193, block; 193, 194; 194, return_statement; 195, comment; 196, expression_statement; 196, 197; 197, assignment; 197, 198; 197, 199; 198, identifier:params; 199, list:[]; 200, if_statement; 200, 201; 200, 204; 200, 205; 200, 207; 200, 237; 201, comparison_operator:is; 201, 202; 201, 203; 202, identifier:do_reload; 203, True; 204, comment; 205, block; 205, 206; 206, pass_statement; 207, elif_clause; 207, 208; 207, 230; 208, parenthesized_expression; 208, 209; 209, boolean_operator:or; 209, 210; 209, 218; 210, call; 210, 211; 210, 212; 211, identifier:isinstance; 212, argument_list; 212, 213; 212, 214; 213, identifier:do_reload; 214, tuple; 214, 215; 214, 216; 214, 217; 215, identifier:int; 216, identifier:long; 217, identifier:float; 218, parenthesized_expression; 218, 219; 219, boolean_operator:and; 219, 220; 219, 225; 220, call; 220, 221; 220, 222; 221, identifier:isinstance; 222, argument_list; 222, 223; 222, 224; 223, identifier:do_reload; 224, identifier:basestring; 225, call; 225, 226; 225, 229; 226, attribute; 226, 227; 226, 228; 227, identifier:do_reload; 228, identifier:isdigit; 229, argument_list; 230, block; 230, 231; 231, expression_statement; 231, 232; 232, assignment; 232, 233; 232, 234; 233, identifier:params; 234, list:['spread', do_reload]; 234, 235; 234, 236; 235, string:'spread'; 236, identifier:do_reload; 237, else_clause; 237, 238; 238, block; 238, 239; 239, expression_statement; 239, 240; 240, assignment; 240, 241; 240, 242; 241, identifier:params; 242, list:[str(do_reload)]; 242, 243; 243, call; 243, 244; 243, 245; 244, identifier:str; 245, argument_list; 245, 246; 246, identifier:do_reload; 247, comment; 248, if_statement; 248, 249; 248, 250; 249, identifier:debug; 250, block; 250, 251; 250, 256; 250, 263; 251, expression_statement; 251, 252; 252, assignment; 252, 253; 252, 254; 253, identifier:cmd; 254, list:['reload']; 254, 255; 255, string:'reload'; 256, expression_statement; 256, 257; 257, call; 257, 258; 257, 261; 258, attribute; 258, 259; 258, 260; 259, identifier:cmd; 260, identifier:extend; 261, argument_list; 261, 262; 262, identifier:params; 263, print_statement; 263, 264; 263, 268; 264, chevron; 264, 265; 265, attribute; 265, 266; 265, 267; 266, identifier:sys; 267, identifier:stderr; 268, parenthesized_expression; 268, 269; 269, binary_operator:%; 269, 270; 269, 271; 270, string:"Issuing command: %s"; 271, call; 271, 272; 271, 275; 272, attribute; 272, 273; 272, 274; 273, string:' '; 274, identifier:join; 275, generator_expression; 275, 276; 275, 280; 276, call; 276, 277; 276, 278; 277, identifier:str; 278, argument_list; 278, 279; 279, identifier:c; 280, for_in_clause; 280, 281; 280, 282; 281, identifier:c; 282, identifier:cmd; 283, if_statement; 283, 284; 283, 286; 284, not_operator; 284, 285; 285, identifier:dry_run; 286, block; 286, 287; 287, expression_statement; 287, 288; 288, call; 288, 289; 288, 292; 289, attribute; 289, 290; 289, 291; 290, identifier:database; 291, identifier:command; 292, argument_list; 292, 293; 292, 294; 292, 295; 292, 296; 293, identifier:db; 294, identifier:control_channel; 295, string:'reload'; 296, list_splat; 296, 297; 297, identifier:params | def setup_limits(conf_file, limits_file, do_reload=True,
dry_run=False, debug=False):
"""
Set up or update limits in the Redis database.
:param conf_file: Name of the configuration file, for connecting
to the Redis database.
:param limits_file: Name of the XML file describing the limits to
configure.
:param do_reload: Controls reloading behavior. If True (the
default), a reload command is issued. If False,
no reload command is issued. String values
result in a reload command of the given load
type, and integer or float values result in a
reload command of type 'spread' with the given
spread interval.
:param dry_run: If True, no changes are made to the database.
Implies debug=True.
:param debug: If True, debugging messages are emitted while
loading the limits and updating the database.
"""
# If dry_run is set, default debug to True
if dry_run:
debug = True
# Connect to the database...
conf = config.Config(conf_file=conf_file)
db = conf.get_database()
limits_key = conf['control'].get('limits_key', 'limits')
control_channel = conf['control'].get('channel', 'control')
# Parse the limits file
limits_tree = etree.parse(limits_file)
# Now, we parse the limits XML file
lims = []
for idx, lim in enumerate(limits_tree.getroot()):
# Skip tags we don't recognize
if lim.tag != 'limit':
warnings.warn("Unrecognized tag %r in limits file at index %d" %
(lim.tag, idx))
continue
# Construct the limit and add it to the list of limits
try:
lims.append(parse_limit_node(db, idx, lim))
except Exception as exc:
warnings.warn("Couldn't understand limit at index %d: %s" %
(idx, exc))
continue
# Now that we have the limits, let's install them
if debug:
print >>sys.stderr, "Installing the following limits:"
for lim in lims:
print >>sys.stderr, " %r" % lim
if not dry_run:
database.limit_update(db, limits_key, lims)
# Were we requested to reload the limits?
if do_reload is False:
return
# OK, figure out what kind of reload to do
params = []
if do_reload is True:
# Nothing to do; use default semantics
pass
elif (isinstance(do_reload, (int, long, float)) or
(isinstance(do_reload, basestring) and do_reload.isdigit())):
params = ['spread', do_reload]
else:
params = [str(do_reload)]
# Issue the reload command
if debug:
cmd = ['reload']
cmd.extend(params)
print >>sys.stderr, ("Issuing command: %s" %
' '.join(str(c) for c in cmd))
if not dry_run:
database.command(db, control_channel, 'reload', *params) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:make_limit_node; 3, parameters; 3, 4; 3, 5; 4, identifier:root; 5, identifier:limit; 6, block; 6, 7; 6, 9; 6, 10; 6, 26; 6, 27; 7, expression_statement; 7, 8; 8, comment; 9, comment; 10, expression_statement; 10, 11; 11, assignment; 11, 12; 11, 13; 12, identifier:limit_node; 13, call; 13, 14; 13, 17; 14, attribute; 14, 15; 14, 16; 15, identifier:etree; 16, identifier:SubElement; 17, argument_list; 17, 18; 17, 19; 17, 20; 18, identifier:root; 19, string:'limit'; 20, dictionary; 20, 21; 21, pair; 21, 22; 21, 23; 22, string:'class'; 23, attribute; 23, 24; 23, 25; 24, identifier:limit; 25, identifier:_limit_full_name; 26, comment; 27, for_statement; 27, 28; 27, 29; 27, 35; 28, identifier:attr; 29, call; 29, 30; 29, 31; 30, identifier:sorted; 31, argument_list; 31, 32; 32, attribute; 32, 33; 32, 34; 33, identifier:limit; 34, identifier:attrs; 35, block; 35, 36; 35, 44; 35, 54; 35, 62; 35, 63; 35, 94; 35, 95; 35, 108; 35, 109; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:desc; 39, subscript; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:limit; 42, identifier:attrs; 43, identifier:attr; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:attr_type; 47, call; 47, 48; 47, 51; 48, attribute; 48, 49; 48, 50; 49, identifier:desc; 50, identifier:get; 51, argument_list; 51, 52; 51, 53; 52, string:'type'; 53, identifier:str; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 57; 56, identifier:value; 57, call; 57, 58; 57, 59; 58, identifier:getattr; 59, argument_list; 59, 60; 59, 61; 60, identifier:limit; 61, identifier:attr; 62, comment; 63, if_statement; 63, 64; 63, 67; 64, comparison_operator:in; 64, 65; 64, 66; 65, string:'default'; 66, identifier:desc; 67, block; 67, 68; 67, 87; 67, 88; 68, expression_statement; 68, 69; 69, assignment; 69, 70; 69, 71; 70, identifier:default; 71, parenthesized_expression; 71, 72; 72, conditional_expression:if; 72, 73; 72, 78; 72, 84; 73, call; 73, 74; 73, 77; 74, subscript; 74, 75; 74, 76; 75, identifier:desc; 76, string:'default'; 77, argument_list; 78, call; 78, 79; 78, 80; 79, identifier:callable; 80, argument_list; 80, 81; 81, subscript; 81, 82; 81, 83; 82, identifier:desc; 83, string:'default'; 84, subscript; 84, 85; 84, 86; 85, identifier:desc; 86, string:'default'; 87, comment; 88, if_statement; 88, 89; 88, 92; 89, comparison_operator:==; 89, 90; 89, 91; 90, identifier:value; 91, identifier:default; 92, block; 92, 93; 93, continue_statement; 94, comment; 95, expression_statement; 95, 96; 96, assignment; 96, 97; 96, 98; 97, identifier:attr_node; 98, call; 98, 99; 98, 102; 99, attribute; 99, 100; 99, 101; 100, identifier:etree; 101, identifier:SubElement; 102, argument_list; 102, 103; 102, 104; 102, 105; 103, identifier:limit_node; 104, string:'attr'; 105, keyword_argument; 105, 106; 105, 107; 106, identifier:name; 107, identifier:attr; 108, comment; 109, if_statement; 109, 110; 109, 113; 109, 137; 109, 185; 110, comparison_operator:==; 110, 111; 110, 112; 111, identifier:attr_type; 112, identifier:list; 113, block; 113, 114; 114, for_statement; 114, 115; 114, 116; 114, 117; 115, identifier:val; 116, identifier:value; 117, block; 117, 118; 117, 128; 118, expression_statement; 118, 119; 119, assignment; 119, 120; 119, 121; 120, identifier:val_node; 121, call; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:etree; 124, identifier:SubElement; 125, argument_list; 125, 126; 125, 127; 126, identifier:attr_node; 127, string:'value'; 128, expression_statement; 128, 129; 129, assignment; 129, 130; 129, 133; 130, attribute; 130, 131; 130, 132; 131, identifier:val_node; 132, identifier:text; 133, call; 133, 134; 133, 135; 134, identifier:str; 135, argument_list; 135, 136; 136, identifier:val; 137, elif_clause; 137, 138; 137, 141; 138, comparison_operator:==; 138, 139; 138, 140; 139, identifier:attr_type; 140, identifier:dict; 141, block; 141, 142; 142, for_statement; 142, 143; 142, 146; 142, 162; 143, pattern_list; 143, 144; 143, 145; 144, identifier:key; 145, identifier:val; 146, call; 146, 147; 146, 148; 147, identifier:sorted; 148, argument_list; 148, 149; 148, 154; 149, call; 149, 150; 149, 153; 150, attribute; 150, 151; 150, 152; 151, identifier:value; 152, identifier:items; 153, argument_list; 154, keyword_argument; 154, 155; 154, 156; 155, identifier:key; 156, lambda; 156, 157; 156, 159; 157, lambda_parameters; 157, 158; 158, identifier:x; 159, subscript; 159, 160; 159, 161; 160, identifier:x; 161, integer:0; 162, block; 162, 163; 162, 176; 163, expression_statement; 163, 164; 164, assignment; 164, 165; 164, 166; 165, identifier:val_node; 166, call; 166, 167; 166, 170; 167, attribute; 167, 168; 167, 169; 168, identifier:etree; 169, identifier:SubElement; 170, argument_list; 170, 171; 170, 172; 170, 173; 171, identifier:attr_node; 172, string:'value'; 173, keyword_argument; 173, 174; 173, 175; 174, identifier:key; 175, identifier:key; 176, expression_statement; 176, 177; 177, assignment; 177, 178; 177, 181; 178, attribute; 178, 179; 178, 180; 179, identifier:val_node; 180, identifier:text; 181, call; 181, 182; 181, 183; 182, identifier:str; 183, argument_list; 183, 184; 184, identifier:val; 185, else_clause; 185, 186; 186, block; 186, 187; 187, expression_statement; 187, 188; 188, assignment; 188, 189; 188, 192; 189, attribute; 189, 190; 189, 191; 190, identifier:attr_node; 191, identifier:text; 192, call; 192, 193; 192, 194; 193, identifier:str; 194, argument_list; 194, 195; 195, identifier:value | def make_limit_node(root, limit):
"""
Given a Limit object, generate an XML node.
:param root: The root node of the XML tree being built.
:param limit: The Limit object to serialize to XML.
"""
# Build the base limit node
limit_node = etree.SubElement(root, 'limit',
{'class': limit._limit_full_name})
# Walk through all the recognized attributes
for attr in sorted(limit.attrs):
desc = limit.attrs[attr]
attr_type = desc.get('type', str)
value = getattr(limit, attr)
# Determine the default value, if we have one...
if 'default' in desc:
default = (desc['default']() if callable(desc['default']) else
desc['default'])
# Skip attributes that have their default settings
if value == default:
continue
# Set up the attr node
attr_node = etree.SubElement(limit_node, 'attr', name=attr)
# Treat lists and dicts specially
if attr_type == list:
for val in value:
val_node = etree.SubElement(attr_node, 'value')
val_node.text = str(val)
elif attr_type == dict:
for key, val in sorted(value.items(), key=lambda x: x[0]):
val_node = etree.SubElement(attr_node, 'value', key=key)
val_node.text = str(val)
else:
attr_node.text = str(value) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 15; 2, function_name:turnstile_command; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 4, identifier:conf_file; 5, identifier:command; 6, default_parameter; 6, 7; 6, 8; 7, identifier:arguments; 8, list:[]; 9, default_parameter; 9, 10; 9, 11; 10, identifier:channel; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:debug; 14, False; 15, block; 15, 16; 15, 18; 15, 19; 15, 30; 15, 38; 15, 50; 15, 51; 15, 59; 15, 63; 15, 129; 15, 130; 15, 154; 15, 165; 15, 166; 15, 171; 15, 172; 15, 180; 15, 187; 15, 188; 16, expression_statement; 16, 17; 17, comment; 18, comment; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:conf; 22, call; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:config; 25, identifier:Config; 26, argument_list; 26, 27; 27, keyword_argument; 27, 28; 27, 29; 28, identifier:conf_file; 29, identifier:conf_file; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:db; 33, call; 33, 34; 33, 37; 34, attribute; 34, 35; 34, 36; 35, identifier:conf; 36, identifier:get_database; 37, argument_list; 38, expression_statement; 38, 39; 39, assignment; 39, 40; 39, 41; 40, identifier:control_channel; 41, call; 41, 42; 41, 47; 42, attribute; 42, 43; 42, 46; 43, subscript; 43, 44; 43, 45; 44, identifier:conf; 45, string:'control'; 46, identifier:get; 47, argument_list; 47, 48; 47, 49; 48, string:'channel'; 49, string:'control'; 50, comment; 51, expression_statement; 51, 52; 52, assignment; 52, 53; 52, 54; 53, identifier:command; 54, call; 54, 55; 54, 58; 55, attribute; 55, 56; 55, 57; 56, identifier:command; 57, identifier:lower; 58, argument_list; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:ts_conv; 62, False; 63, if_statement; 63, 64; 63, 67; 63, 68; 64, comparison_operator:==; 64, 65; 64, 66; 65, identifier:command; 66, string:'ping'; 67, comment; 68, block; 68, 69; 68, 96; 68, 97; 68, 120; 68, 121; 69, if_statement; 69, 70; 69, 71; 69, 78; 70, identifier:arguments; 71, block; 71, 72; 72, expression_statement; 72, 73; 73, assignment; 73, 74; 73, 75; 74, identifier:channel; 75, subscript; 75, 76; 75, 77; 76, identifier:arguments; 77, integer:0; 78, else_clause; 78, 79; 79, block; 79, 80; 79, 91; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:channel; 83, call; 83, 84; 83, 85; 84, identifier:str; 85, argument_list; 85, 86; 86, call; 86, 87; 86, 90; 87, attribute; 87, 88; 87, 89; 88, identifier:uuid; 89, identifier:uuid4; 90, argument_list; 91, expression_statement; 91, 92; 92, assignment; 92, 93; 92, 94; 93, identifier:arguments; 94, list:[channel]; 94, 95; 95, identifier:channel; 96, comment; 97, if_statement; 97, 98; 97, 104; 98, comparison_operator:<; 98, 99; 98, 103; 99, call; 99, 100; 99, 101; 100, identifier:len; 101, argument_list; 101, 102; 102, identifier:arguments; 103, integer:2; 104, block; 104, 105; 104, 116; 105, expression_statement; 105, 106; 106, call; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, identifier:arguments; 109, identifier:append; 110, argument_list; 110, 111; 111, call; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:time; 114, identifier:time; 115, argument_list; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 119; 118, identifier:ts_conv; 119, True; 120, comment; 121, expression_statement; 121, 122; 122, assignment; 122, 123; 122, 124; 123, identifier:arguments; 124, subscript; 124, 125; 124, 126; 125, identifier:arguments; 126, slice; 126, 127; 126, 128; 127, colon; 128, integer:2; 129, comment; 130, if_statement; 130, 131; 130, 132; 131, identifier:debug; 132, block; 132, 133; 132, 140; 133, expression_statement; 133, 134; 134, assignment; 134, 135; 134, 136; 135, identifier:cmd; 136, binary_operator:+; 136, 137; 136, 139; 137, list:[command]; 137, 138; 138, identifier:command; 139, identifier:arguments; 140, print_statement; 140, 141; 140, 145; 141, chevron; 141, 142; 142, attribute; 142, 143; 142, 144; 143, identifier:sys; 144, identifier:stderr; 145, parenthesized_expression; 145, 146; 146, binary_operator:%; 146, 147; 146, 148; 147, string:"Issuing command: %s"; 148, call; 148, 149; 148, 152; 149, attribute; 149, 150; 149, 151; 150, string:' '; 151, identifier:join; 152, argument_list; 152, 153; 153, identifier:cmd; 154, expression_statement; 154, 155; 155, call; 155, 156; 155, 159; 156, attribute; 156, 157; 156, 158; 157, identifier:database; 158, identifier:command; 159, argument_list; 159, 160; 159, 161; 159, 162; 159, 163; 160, identifier:db; 161, identifier:control_channel; 162, identifier:command; 163, list_splat; 163, 164; 164, identifier:arguments; 165, comment; 166, if_statement; 166, 167; 166, 169; 167, not_operator; 167, 168; 168, identifier:channel; 169, block; 169, 170; 170, return_statement; 171, comment; 172, expression_statement; 172, 173; 173, assignment; 173, 174; 173, 175; 174, identifier:pubsub; 175, call; 175, 176; 175, 179; 176, attribute; 176, 177; 176, 178; 177, identifier:db; 178, identifier:pubsub; 179, argument_list; 180, expression_statement; 180, 181; 181, call; 181, 182; 181, 185; 182, attribute; 182, 183; 182, 184; 183, identifier:pubsub; 184, identifier:subscribe; 185, argument_list; 185, 186; 186, identifier:channel; 187, comment; 188, try_statement; 188, 189; 188, 313; 189, block; 189, 190; 189, 194; 190, expression_statement; 190, 191; 191, assignment; 191, 192; 191, 193; 192, identifier:count; 193, integer:0; 194, for_statement; 194, 195; 194, 196; 194, 201; 194, 202; 195, identifier:msg; 196, call; 196, 197; 196, 200; 197, attribute; 197, 198; 197, 199; 198, identifier:pubsub; 199, identifier:listen; 200, argument_list; 201, comment; 202, block; 202, 203; 202, 223; 202, 240; 202, 244; 202, 245; 202, 256; 202, 257; 202, 258; 202, 301; 202, 302; 203, if_statement; 203, 204; 203, 205; 204, identifier:debug; 205, block; 205, 206; 205, 215; 206, expression_statement; 206, 207; 207, assignment; 207, 208; 207, 209; 208, identifier:formatted; 209, call; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, identifier:pprint; 212, identifier:pformat; 213, argument_list; 213, 214; 214, identifier:msg; 215, print_statement; 215, 216; 215, 220; 216, chevron; 216, 217; 217, attribute; 217, 218; 217, 219; 218, identifier:sys; 219, identifier:stderr; 220, binary_operator:%; 220, 221; 220, 222; 221, string:"Received message: %s"; 222, identifier:formatted; 223, if_statement; 223, 224; 223, 238; 224, parenthesized_expression; 224, 225; 225, boolean_operator:or; 225, 226; 225, 233; 226, comparison_operator:not; 226, 227; 226, 230; 227, subscript; 227, 228; 227, 229; 228, identifier:msg; 229, string:'type'; 230, tuple; 230, 231; 230, 232; 231, string:'pmessage'; 232, string:'message'; 233, comparison_operator:!=; 233, 234; 233, 237; 234, subscript; 234, 235; 234, 236; 235, identifier:msg; 236, string:'channel'; 237, identifier:channel; 238, block; 238, 239; 239, continue_statement; 240, expression_statement; 240, 241; 241, augmented_assignment:+=; 241, 242; 241, 243; 242, identifier:count; 243, integer:1; 244, comment; 245, expression_statement; 245, 246; 246, assignment; 246, 247; 246, 248; 247, identifier:response; 248, call; 248, 249; 248, 254; 249, attribute; 249, 250; 249, 253; 250, subscript; 250, 251; 250, 252; 251, identifier:msg; 252, string:'data'; 253, identifier:split; 254, argument_list; 254, 255; 255, string:':'; 256, comment; 257, comment; 258, if_statement; 258, 259; 258, 266; 259, boolean_operator:and; 259, 260; 259, 261; 260, identifier:ts_conv; 261, comparison_operator:==; 261, 262; 261, 265; 262, subscript; 262, 263; 262, 264; 263, identifier:response; 264, integer:0; 265, string:'pong'; 266, block; 266, 267; 267, try_statement; 267, 268; 267, 296; 268, block; 268, 269; 268, 287; 269, expression_statement; 269, 270; 270, assignment; 270, 271; 270, 272; 271, identifier:rtt; 272, binary_operator:*; 272, 273; 272, 286; 273, parenthesized_expression; 273, 274; 274, binary_operator:-; 274, 275; 274, 280; 275, call; 275, 276; 275, 279; 276, attribute; 276, 277; 276, 278; 277, identifier:time; 278, identifier:time; 279, argument_list; 280, call; 280, 281; 280, 282; 281, identifier:float; 282, argument_list; 282, 283; 283, subscript; 283, 284; 283, 285; 284, identifier:response; 285, integer:2; 286, integer:100; 287, expression_statement; 287, 288; 288, call; 288, 289; 288, 292; 289, attribute; 289, 290; 289, 291; 290, identifier:response; 291, identifier:append; 292, argument_list; 292, 293; 293, binary_operator:%; 293, 294; 293, 295; 294, string:'(RTT %.2fms)'; 295, identifier:rtt; 296, except_clause; 296, 297; 296, 298; 296, 299; 297, identifier:Exception; 298, comment; 299, block; 299, 300; 300, pass_statement; 301, comment; 302, print_statement; 302, 303; 303, binary_operator:%; 303, 304; 303, 305; 304, string:"Response % 5d: %s"; 305, tuple; 305, 306; 305, 307; 306, identifier:count; 307, call; 307, 308; 307, 311; 308, attribute; 308, 309; 308, 310; 309, string:' '; 310, identifier:join; 311, argument_list; 311, 312; 312, identifier:response; 313, except_clause; 313, 314; 313, 315; 313, 316; 313, 317; 314, identifier:KeyboardInterrupt; 315, comment; 316, comment; 317, block; 317, 318; 318, pass_statement | def turnstile_command(conf_file, command, arguments=[], channel=None,
debug=False):
"""
Issue a command to all running control daemons.
:param conf_file: Name of the configuration file.
:param command: The command to execute. Note that 'ping' is
handled specially; in particular, the "channel"
parameter is implied. (A random value will be
used for the channel to listen on.)
:param arguments: A list of arguments for the command. Note that
the colon character (':') cannot be used.
:param channel: If not None, specifies the name of a message
channel to listen for responses on. Will wait
indefinitely; to terminate the listening loop, use
the keyboard interrupt sequence.
:param debug: If True, debugging messages are emitted while
sending the command.
"""
# Connect to the database...
conf = config.Config(conf_file=conf_file)
db = conf.get_database()
control_channel = conf['control'].get('channel', 'control')
# Now, set up the command
command = command.lower()
ts_conv = False
if command == 'ping':
# We handle 'ping' specially; first, figure out the channel
if arguments:
channel = arguments[0]
else:
channel = str(uuid.uuid4())
arguments = [channel]
# Next, add on a timestamp
if len(arguments) < 2:
arguments.append(time.time())
ts_conv = True
# Limit the argument list length
arguments = arguments[:2]
# OK, the command is all set up. Let us now send the command...
if debug:
cmd = [command] + arguments
print >>sys.stderr, ("Issuing command: %s" %
' '.join(cmd))
database.command(db, control_channel, command, *arguments)
# Were we asked to listen on a channel?
if not channel:
return
# OK, let's subscribe to the channel...
pubsub = db.pubsub()
pubsub.subscribe(channel)
# Now we listen...
try:
count = 0
for msg in pubsub.listen():
# Make sure the message is one we're interested in
if debug:
formatted = pprint.pformat(msg)
print >>sys.stderr, "Received message: %s" % formatted
if (msg['type'] not in ('pmessage', 'message') or
msg['channel'] != channel):
continue
count += 1
# Figure out the response
response = msg['data'].split(':')
# If this is a 'pong' and ts_conv is true, add an RTT to
# the response
if ts_conv and response[0] == 'pong':
try:
rtt = (time.time() - float(response[2])) * 100
response.append('(RTT %.2fms)' % rtt)
except Exception:
# IndexError or ValueError, probably; ignore it
pass
# Print out the response
print "Response % 5d: %s" % (count, ' '.join(response))
except KeyboardInterrupt:
# We want to break out of the loop, but not return any error
# to the caller...
pass |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 1, 6; 2, function_name:humanize_timesince; 3, parameters; 3, 4; 4, identifier:start_time; 5, comment; 6, block; 6, 7; 6, 9; 6, 15; 6, 23; 6, 24; 6, 25; 6, 36; 6, 44; 6, 67; 6, 75; 6, 98; 6, 104; 6, 127; 6, 135; 6, 158; 6, 166; 6, 189; 7, expression_statement; 7, 8; 8, comment; 9, if_statement; 9, 10; 9, 12; 10, not_operator; 10, 11; 11, identifier:start_time; 12, block; 12, 13; 13, return_statement; 13, 14; 14, identifier:start_time; 15, expression_statement; 15, 16; 16, assignment; 16, 17; 16, 18; 17, identifier:delta; 18, binary_operator:-; 18, 19; 18, 22; 19, call; 19, 20; 19, 21; 20, identifier:local_now; 21, argument_list; 22, identifier:start_time; 23, comment; 24, comment; 25, if_statement; 25, 26; 25, 33; 26, comparison_operator:<; 26, 27; 26, 32; 27, call; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:delta; 30, identifier:total_seconds; 31, argument_list; 32, integer:0; 33, block; 33, 34; 34, return_statement; 34, 35; 35, string:'a few seconds ago'; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:num_years; 39, binary_operator://; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:delta; 42, identifier:days; 43, integer:365; 44, if_statement; 44, 45; 44, 48; 45, comparison_operator:>; 45, 46; 45, 47; 46, identifier:num_years; 47, integer:0; 48, block; 48, 49; 49, return_statement; 49, 50; 50, call; 50, 51; 50, 54; 51, attribute; 51, 52; 51, 53; 52, string:'{} year{} ago'; 53, identifier:format; 54, argument_list; 54, 55; 55, list_splat; 55, 56; 56, parenthesized_expression; 56, 57; 57, conditional_expression:if; 57, 58; 57, 61; 57, 64; 58, tuple; 58, 59; 58, 60; 59, identifier:num_years; 60, string:'s'; 61, comparison_operator:>; 61, 62; 61, 63; 62, identifier:num_years; 63, integer:1; 64, tuple; 64, 65; 64, 66; 65, identifier:num_years; 66, string:''; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:num_weeks; 70, binary_operator://; 70, 71; 70, 74; 71, attribute; 71, 72; 71, 73; 72, identifier:delta; 73, identifier:days; 74, integer:7; 75, if_statement; 75, 76; 75, 79; 76, comparison_operator:>; 76, 77; 76, 78; 77, identifier:num_weeks; 78, integer:0; 79, block; 79, 80; 80, return_statement; 80, 81; 81, call; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, string:'{} week{} ago'; 84, identifier:format; 85, argument_list; 85, 86; 86, list_splat; 86, 87; 87, parenthesized_expression; 87, 88; 88, conditional_expression:if; 88, 89; 88, 92; 88, 95; 89, tuple; 89, 90; 89, 91; 90, identifier:num_weeks; 91, string:'s'; 92, comparison_operator:>; 92, 93; 92, 94; 93, identifier:num_weeks; 94, integer:1; 95, tuple; 95, 96; 95, 97; 96, identifier:num_weeks; 97, string:''; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:num_days; 101, attribute; 101, 102; 101, 103; 102, identifier:delta; 103, identifier:days; 104, if_statement; 104, 105; 104, 108; 105, comparison_operator:>; 105, 106; 105, 107; 106, identifier:num_days; 107, integer:0; 108, block; 108, 109; 109, return_statement; 109, 110; 110, call; 110, 111; 110, 114; 111, attribute; 111, 112; 111, 113; 112, string:'{} day{} ago'; 113, identifier:format; 114, argument_list; 114, 115; 115, list_splat; 115, 116; 116, parenthesized_expression; 116, 117; 117, conditional_expression:if; 117, 118; 117, 121; 117, 124; 118, tuple; 118, 119; 118, 120; 119, identifier:num_days; 120, string:'s'; 121, comparison_operator:>; 121, 122; 121, 123; 122, identifier:num_days; 123, integer:1; 124, tuple; 124, 125; 124, 126; 125, identifier:num_days; 126, string:''; 127, expression_statement; 127, 128; 128, assignment; 128, 129; 128, 130; 129, identifier:num_hours; 130, binary_operator://; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:delta; 133, identifier:seconds; 134, integer:3600; 135, if_statement; 135, 136; 135, 139; 136, comparison_operator:>; 136, 137; 136, 138; 137, identifier:num_hours; 138, integer:0; 139, block; 139, 140; 140, return_statement; 140, 141; 141, call; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, string:'{} hour{} ago'; 144, identifier:format; 145, argument_list; 145, 146; 146, list_splat; 146, 147; 147, parenthesized_expression; 147, 148; 148, conditional_expression:if; 148, 149; 148, 152; 148, 155; 149, tuple; 149, 150; 149, 151; 150, identifier:num_hours; 151, string:'s'; 152, comparison_operator:>; 152, 153; 152, 154; 153, identifier:num_hours; 154, integer:1; 155, tuple; 155, 156; 155, 157; 156, identifier:num_hours; 157, string:''; 158, expression_statement; 158, 159; 159, assignment; 159, 160; 159, 161; 160, identifier:num_minutes; 161, binary_operator://; 161, 162; 161, 165; 162, attribute; 162, 163; 162, 164; 163, identifier:delta; 164, identifier:seconds; 165, integer:60; 166, if_statement; 166, 167; 166, 170; 167, comparison_operator:>; 167, 168; 167, 169; 168, identifier:num_minutes; 169, integer:0; 170, block; 170, 171; 171, return_statement; 171, 172; 172, call; 172, 173; 172, 176; 173, attribute; 173, 174; 173, 175; 174, string:'{} minute{} ago'; 175, identifier:format; 176, argument_list; 176, 177; 177, list_splat; 177, 178; 178, parenthesized_expression; 178, 179; 179, conditional_expression:if; 179, 180; 179, 183; 179, 186; 180, tuple; 180, 181; 180, 182; 181, identifier:num_minutes; 182, string:'s'; 183, comparison_operator:>; 183, 184; 183, 185; 184, identifier:num_minutes; 185, integer:1; 186, tuple; 186, 187; 186, 188; 187, identifier:num_minutes; 188, string:''; 189, return_statement; 189, 190; 190, string:'a few seconds ago' | def humanize_timesince(start_time): # pylint:disable=too-many-return-statements
"""Creates a string representation of time since the given `start_time`."""
if not start_time:
return start_time
delta = local_now() - start_time
# assumption: negative delta values originate from clock
# differences on different app server machines
if delta.total_seconds() < 0:
return 'a few seconds ago'
num_years = delta.days // 365
if num_years > 0:
return '{} year{} ago'.format(
*((num_years, 's') if num_years > 1 else (num_years, '')))
num_weeks = delta.days // 7
if num_weeks > 0:
return '{} week{} ago'.format(
*((num_weeks, 's') if num_weeks > 1 else (num_weeks, '')))
num_days = delta.days
if num_days > 0:
return '{} day{} ago'.format(
*((num_days, 's') if num_days > 1 else (num_days, '')))
num_hours = delta.seconds // 3600
if num_hours > 0:
return '{} hour{} ago'.format(*((num_hours, 's') if num_hours > 1 else (num_hours, '')))
num_minutes = delta.seconds // 60
if num_minutes > 0:
return '{} minute{} ago'.format(
*((num_minutes, 's') if num_minutes > 1 else (num_minutes, '')))
return 'a few seconds ago' |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:fire; 3, parameters; 3, 4; 3, 5; 3, 7; 4, identifier:self; 5, list_splat_pattern; 5, 6; 6, identifier:args; 7, dictionary_splat_pattern; 7, 8; 8, identifier:kw; 9, block; 9, 10; 9, 12; 9, 16; 9, 29; 9, 359; 10, expression_statement; 10, 11; 11, comment; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:result; 15, list:[]; 16, with_statement; 16, 17; 16, 22; 17, with_clause; 17, 18; 18, with_item; 18, 19; 19, attribute; 19, 20; 19, 21; 20, identifier:self; 21, identifier:_hlock; 22, block; 22, 23; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:handlers; 26, attribute; 26, 27; 26, 28; 27, identifier:self; 28, identifier:handlers; 29, if_statement; 29, 30; 29, 35; 29, 36; 29, 99; 30, comparison_operator:==; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:self; 33, identifier:threads; 34, integer:0; 35, comment; 36, block; 36, 37; 37, for_statement; 37, 38; 37, 39; 37, 40; 37, 41; 38, identifier:k; 39, identifier:handlers; 40, comment; 41, block; 41, 42; 41, 51; 42, expression_statement; 42, 43; 43, assignment; 43, 44; 43, 48; 44, pattern_list; 44, 45; 44, 46; 44, 47; 45, identifier:h; 46, identifier:m; 47, identifier:t; 48, subscript; 48, 49; 48, 50; 49, identifier:handlers; 50, identifier:k; 51, try_statement; 51, 52; 51, 78; 52, block; 52, 53; 52, 68; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:r; 56, call; 56, 57; 56, 60; 57, attribute; 57, 58; 57, 59; 58, identifier:self; 59, identifier:_memoize; 60, argument_list; 60, 61; 60, 62; 60, 63; 60, 64; 60, 66; 61, identifier:h; 62, identifier:m; 63, identifier:t; 64, list_splat; 64, 65; 65, identifier:args; 66, dictionary_splat; 66, 67; 67, identifier:kw; 68, expression_statement; 68, 69; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:result; 72, identifier:append; 73, argument_list; 73, 74; 74, call; 74, 75; 74, 76; 75, identifier:tuple; 76, argument_list; 76, 77; 77, identifier:r; 78, except_clause; 78, 79; 79, block; 79, 80; 80, expression_statement; 80, 81; 81, call; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:result; 84, identifier:append; 85, argument_list; 85, 86; 86, tuple; 86, 87; 86, 88; 86, 98; 87, False; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:self; 91, identifier:_error; 92, argument_list; 92, 93; 93, call; 93, 94; 93, 97; 94, attribute; 94, 95; 94, 96; 95, identifier:sys; 96, identifier:exc_info; 97, argument_list; 98, identifier:h; 99, elif_clause; 99, 100; 99, 105; 99, 106; 100, comparison_operator:>; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:self; 103, identifier:threads; 104, integer:0; 105, comment; 106, block; 106, 107; 106, 113; 106, 114; 106, 115; 106, 121; 106, 248; 107, expression_statement; 107, 108; 108, assignment; 108, 109; 108, 110; 109, identifier:queue; 110, call; 110, 111; 110, 112; 111, identifier:Queue; 112, argument_list; 113, comment; 114, comment; 115, expression_statement; 115, 116; 116, assignment; 116, 117; 116, 118; 117, identifier:rlock; 118, call; 118, 119; 118, 120; 119, identifier:RLock; 120, argument_list; 121, function_definition; 121, 122; 121, 123; 121, 128; 122, function_name:_execute; 123, parameters; 123, 124; 123, 126; 124, list_splat_pattern; 124, 125; 125, identifier:args; 126, dictionary_splat_pattern; 126, 127; 127, identifier:kw; 128, block; 128, 129; 128, 131; 129, expression_statement; 129, 130; 130, comment; 131, while_statement; 131, 132; 131, 133; 132, True; 133, block; 133, 134; 134, try_statement; 134, 135; 134, 243; 135, block; 135, 136; 135, 144; 135, 156; 135, 157; 135, 166; 135, 167; 135, 237; 136, expression_statement; 136, 137; 137, assignment; 137, 138; 137, 139; 138, identifier:item; 139, call; 139, 140; 139, 143; 140, attribute; 140, 141; 140, 142; 141, identifier:queue; 142, identifier:get; 143, argument_list; 144, if_statement; 144, 145; 144, 148; 145, comparison_operator:is; 145, 146; 145, 147; 146, identifier:item; 147, None; 148, block; 148, 149; 148, 155; 149, expression_statement; 149, 150; 150, call; 150, 151; 150, 154; 151, attribute; 151, 152; 151, 153; 152, identifier:queue; 153, identifier:task_done; 154, argument_list; 155, break_statement; 156, comment; 157, expression_statement; 157, 158; 158, assignment; 158, 159; 158, 163; 159, pattern_list; 159, 160; 159, 161; 159, 162; 160, identifier:h; 161, identifier:m; 162, identifier:t; 163, subscript; 163, 164; 163, 165; 164, identifier:handlers; 165, identifier:item; 166, comment; 167, try_statement; 167, 168; 167, 205; 168, block; 168, 169; 168, 184; 169, expression_statement; 169, 170; 170, assignment; 170, 171; 170, 172; 171, identifier:r; 172, call; 172, 173; 172, 176; 173, attribute; 173, 174; 173, 175; 174, identifier:self; 175, identifier:_memoize; 176, argument_list; 176, 177; 176, 178; 176, 179; 176, 180; 176, 182; 177, identifier:h; 178, identifier:m; 179, identifier:t; 180, list_splat; 180, 181; 181, identifier:args; 182, dictionary_splat; 182, 183; 183, identifier:kw; 184, if_statement; 184, 185; 184, 189; 185, not_operator; 185, 186; 186, attribute; 186, 187; 186, 188; 187, identifier:self; 188, identifier:asynch; 189, block; 189, 190; 190, with_statement; 190, 191; 190, 194; 191, with_clause; 191, 192; 192, with_item; 192, 193; 193, identifier:rlock; 194, block; 194, 195; 195, expression_statement; 195, 196; 196, call; 196, 197; 196, 200; 197, attribute; 197, 198; 197, 199; 198, identifier:result; 199, identifier:append; 200, argument_list; 200, 201; 201, call; 201, 202; 201, 203; 202, identifier:tuple; 203, argument_list; 203, 204; 204, identifier:r; 205, except_clause; 205, 206; 206, block; 206, 207; 207, if_statement; 207, 208; 207, 212; 208, not_operator; 208, 209; 209, attribute; 209, 210; 209, 211; 210, identifier:self; 211, identifier:asynch; 212, block; 212, 213; 213, with_statement; 213, 214; 213, 217; 214, with_clause; 214, 215; 215, with_item; 215, 216; 216, identifier:rlock; 217, block; 217, 218; 218, expression_statement; 218, 219; 219, call; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:result; 222, identifier:append; 223, argument_list; 223, 224; 224, tuple; 224, 225; 224, 226; 224, 236; 225, False; 226, call; 226, 227; 226, 230; 227, attribute; 227, 228; 227, 229; 228, identifier:self; 229, identifier:_error; 230, argument_list; 230, 231; 231, call; 231, 232; 231, 235; 232, attribute; 232, 233; 232, 234; 233, identifier:sys; 234, identifier:exc_info; 235, argument_list; 236, identifier:h; 237, expression_statement; 237, 238; 238, call; 238, 239; 238, 242; 239, attribute; 239, 240; 239, 241; 240, identifier:queue; 241, identifier:task_done; 242, argument_list; 243, except_clause; 243, 244; 243, 245; 243, 246; 244, identifier:Empty; 245, comment; 246, block; 246, 247; 247, break_statement; 248, if_statement; 248, 249; 248, 250; 249, identifier:handlers; 250, block; 250, 251; 250, 262; 250, 296; 250, 332; 250, 347; 251, expression_statement; 251, 252; 252, assignment; 252, 253; 252, 254; 253, identifier:threads; 254, call; 254, 255; 254, 258; 255, attribute; 255, 256; 255, 257; 256, identifier:self; 257, identifier:_threads; 258, argument_list; 258, 259; 259, keyword_argument; 259, 260; 259, 261; 260, identifier:handlers; 261, identifier:handlers; 262, for_statement; 262, 263; 262, 264; 262, 268; 263, identifier:_; 264, call; 264, 265; 264, 266; 265, identifier:range; 266, argument_list; 266, 267; 267, identifier:threads; 268, block; 268, 269; 268, 284; 268, 290; 269, expression_statement; 269, 270; 270, assignment; 270, 271; 270, 272; 271, identifier:t; 272, call; 272, 273; 272, 274; 273, identifier:Thread; 274, argument_list; 274, 275; 274, 278; 274, 281; 275, keyword_argument; 275, 276; 275, 277; 276, identifier:target; 277, identifier:_execute; 278, keyword_argument; 278, 279; 278, 280; 279, identifier:args; 280, identifier:args; 281, keyword_argument; 281, 282; 281, 283; 282, identifier:kwargs; 283, identifier:kw; 284, expression_statement; 284, 285; 285, assignment; 285, 286; 285, 289; 286, attribute; 286, 287; 286, 288; 287, identifier:t; 288, identifier:daemon; 289, True; 290, expression_statement; 290, 291; 291, call; 291, 292; 291, 295; 292, attribute; 292, 293; 292, 294; 293, identifier:t; 294, identifier:start; 295, argument_list; 296, for_statement; 296, 297; 296, 298; 296, 299; 297, identifier:k; 298, identifier:handlers; 299, block; 299, 300; 299, 307; 300, expression_statement; 300, 301; 301, call; 301, 302; 301, 305; 302, attribute; 302, 303; 302, 304; 303, identifier:queue; 304, identifier:put; 305, argument_list; 305, 306; 306, identifier:k; 307, if_statement; 307, 308; 307, 311; 307, 312; 308, attribute; 308, 309; 308, 310; 309, identifier:self; 310, identifier:asynch; 311, comment; 312, block; 312, 313; 312, 322; 313, expression_statement; 313, 314; 314, assignment; 314, 315; 314, 319; 315, pattern_list; 315, 316; 315, 317; 315, 318; 316, identifier:h; 317, identifier:_; 318, identifier:_; 319, subscript; 319, 320; 319, 321; 320, identifier:handlers; 321, identifier:k; 322, expression_statement; 322, 323; 323, call; 323, 324; 323, 327; 324, attribute; 324, 325; 324, 326; 325, identifier:result; 326, identifier:append; 327, argument_list; 327, 328; 328, tuple; 328, 329; 328, 330; 328, 331; 329, None; 330, None; 331, identifier:h; 332, for_statement; 332, 333; 332, 334; 332, 338; 333, identifier:_; 334, call; 334, 335; 334, 336; 335, identifier:range; 336, argument_list; 336, 337; 337, identifier:threads; 338, block; 338, 339; 338, 346; 339, expression_statement; 339, 340; 340, call; 340, 341; 340, 344; 341, attribute; 341, 342; 341, 343; 342, identifier:queue; 343, identifier:put; 344, argument_list; 344, 345; 345, None; 346, comment; 347, if_statement; 347, 348; 347, 352; 348, not_operator; 348, 349; 349, attribute; 349, 350; 349, 351; 350, identifier:self; 351, identifier:asynch; 352, block; 352, 353; 353, expression_statement; 353, 354; 354, call; 354, 355; 354, 358; 355, attribute; 355, 356; 355, 357; 356, identifier:queue; 357, identifier:join; 358, argument_list; 359, return_statement; 359, 360; 360, boolean_operator:or; 360, 361; 360, 365; 361, call; 361, 362; 361, 363; 362, identifier:tuple; 363, argument_list; 363, 364; 364, identifier:result; 365, None | def fire(self, *args, **kw):
""" Stores all registered handlers in a queue for processing """
result = []
with self._hlock:
handlers = self.handlers
if self.threads == 0: # same-thread execution - synchronized
for k in handlers:
# handler, memoize, timeout
h, m, t = handlers[k]
try:
r = self._memoize(h, m, t, *args, **kw)
result.append(tuple(r))
except:
result.append((False, self._error(sys.exc_info()), h))
elif self.threads > 0: # multi-thread execution - desynchronized if self.threads > 1
queue = Queue()
# result lock just in case [].append() is not
# thread-safe in other Python implementations
rlock = RLock()
def _execute(*args, **kw):
""" Executes all handlers stored in the queue """
while True:
try:
item = queue.get()
if item is None:
queue.task_done()
break
# handler, memoize, timeout
h, m, t = handlers[item] # call under active lock
try:
r = self._memoize(h, m, t, *args, **kw)
if not self.asynch:
with rlock:
result.append(tuple(r))
except:
if not self.asynch:
with rlock:
result.append((False, self._error(sys.exc_info()), h))
queue.task_done()
except Empty: # never triggered, just to be safe
break
if handlers:
threads = self._threads(handlers=handlers)
for _ in range(threads):
t = Thread(target=_execute, args=args, kwargs=kw)
t.daemon = True
t.start()
for k in handlers:
queue.put(k)
if self.asynch: # main thread, no locking required
h, _, _ = handlers[k]
result.append((None, None, h))
for _ in range(threads):
queue.put(None) # stop each worker
if not self.asynch:
queue.join()
return tuple(result) or None |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 18; 2, function_name:runGetResults; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 4, identifier:cmd; 5, default_parameter; 5, 6; 5, 7; 6, identifier:stdout; 7, True; 8, default_parameter; 8, 9; 8, 10; 9, identifier:stderr; 10, True; 11, default_parameter; 11, 12; 11, 13; 12, identifier:encoding; 13, call; 13, 14; 13, 17; 14, attribute; 14, 15; 14, 16; 15, identifier:sys; 16, identifier:getdefaultencoding; 17, argument_list; 18, block; 18, 19; 18, 21; 18, 59; 18, 94; 18, 115; 18, 187; 18, 191; 18, 195; 18, 199; 18, 233; 18, 267; 18, 271; 18, 278; 18, 370; 18, 410; 18, 416; 19, expression_statement; 19, 20; 20, string:'''
runGetResults - Simple method to run a command and return the results of the execution as a dict.
@param cmd <str/list> - String of command and arguments, or list of command and arguments
If cmd is a string, the command will be executed as if ran exactly as written in a shell. This mode supports shell-isms like '&&' and '|'
If cmd is a list, the first element will be the executable, and further elements are arguments that will be passed to that executable.
@param stdout <True/False> - Default True, Whether to gather and include program's stdout data in results.
If False, that data the program prints to stdout will just be output to the current tty and not recorded.
If True, it will NOT be output to the tty, and will be recorded under the key "stdout" in the return dict.
@param stderr <True/False or "stdout"/subprocess.STDOUT> - Default True, Whether to gather and include program's stderr data in results, or to combine with "stdout" data.
If False, the data the program prints to stderr will just be output to the current tty and not recorded
If True, it will NOT be output to the tty, and will be recorded under the key "stderr" in the return dict.
If "stdout" or subprocess.STDOUT - stderr data will be blended with stdout data. This requires that stdout=True.
@param encoding <None/str> - Default sys.getdefaultencoding(), the program's output will automatically be decoded using the provided codec (e.x. "utf-8" or "ascii").
If None or False-ish, data will not be decoded (i.e. in python3 will be "bytes" type)
If unsure, leave this as it's default value, or provide "utf-8"
@return <dict> - Dict of results. Has following keys:
'returnCode' - <int> - Always present, included the integer return-code from the command.
'stdout' <unciode/str/bytes (depending on #encoding)> - Present if stdout=True, contains data output by program to stdout, or stdout+stderr if stderr param is "stdout"/subprocess.STDOUT
'stderr' <unicode/str/bytes (depending on #encoding)> - Present if stderr=True, contains data output by program to stderr.
@raises - SimpleCommandFailure if it cannot launch the given command, for reasons such as: cannot find the executable, or no permission to execute, etc
'''; 21, if_statement; 21, 22; 21, 29; 21, 36; 21, 53; 22, comparison_operator:in; 22, 23; 22, 24; 23, identifier:stderr; 24, tuple; 24, 25; 24, 26; 25, string:'stdout'; 26, attribute; 26, 27; 26, 28; 27, identifier:subprocess; 28, identifier:STDOUT; 29, block; 29, 30; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:stderr; 33, attribute; 33, 34; 33, 35; 34, identifier:subprocess; 35, identifier:STDOUT; 36, elif_clause; 36, 37; 36, 46; 37, boolean_operator:or; 37, 38; 37, 41; 38, comparison_operator:==; 38, 39; 38, 40; 39, identifier:stderr; 40, True; 41, comparison_operator:==; 41, 42; 41, 43; 42, identifier:stderr; 43, attribute; 43, 44; 43, 45; 44, identifier:subprocess; 45, identifier:PIPE; 46, block; 46, 47; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:stderr; 50, attribute; 50, 51; 50, 52; 51, identifier:subprocess; 52, identifier:PIPE; 53, else_clause; 53, 54; 54, block; 54, 55; 55, expression_statement; 55, 56; 56, assignment; 56, 57; 56, 58; 57, identifier:stderr; 58, None; 59, if_statement; 59, 60; 59, 69; 59, 76; 60, boolean_operator:or; 60, 61; 60, 64; 61, comparison_operator:==; 61, 62; 61, 63; 62, identifier:stdout; 63, True; 64, comparison_operator:==; 64, 65; 64, 66; 65, identifier:stdout; 66, attribute; 66, 67; 66, 68; 67, identifier:subprocess; 68, identifier:STDOUT; 69, block; 69, 70; 70, expression_statement; 70, 71; 71, assignment; 71, 72; 71, 73; 72, identifier:stdout; 73, attribute; 73, 74; 73, 75; 74, identifier:subprocess; 75, identifier:PIPE; 76, else_clause; 76, 77; 77, block; 77, 78; 77, 82; 78, expression_statement; 78, 79; 79, assignment; 79, 80; 79, 81; 80, identifier:stdout; 81, None; 82, if_statement; 82, 83; 82, 88; 83, comparison_operator:==; 83, 84; 83, 85; 84, identifier:stderr; 85, attribute; 85, 86; 85, 87; 86, identifier:subprocess; 87, identifier:PIPE; 88, block; 88, 89; 89, raise_statement; 89, 90; 90, call; 90, 91; 90, 92; 91, identifier:ValueError; 92, argument_list; 92, 93; 93, string:'Cannot redirect stderr to stdout if stdout is not captured.'; 94, if_statement; 94, 95; 94, 104; 94, 109; 95, call; 95, 96; 95, 97; 96, identifier:issubclass; 97, argument_list; 97, 98; 97, 101; 98, attribute; 98, 99; 98, 100; 99, identifier:cmd; 100, identifier:__class__; 101, tuple; 101, 102; 101, 103; 102, identifier:list; 103, identifier:tuple; 104, block; 104, 105; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 108; 107, identifier:shell; 108, False; 109, else_clause; 109, 110; 110, block; 110, 111; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:shell; 114, True; 115, try_statement; 115, 116; 115, 135; 116, block; 116, 117; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 120; 119, identifier:pipe; 120, call; 120, 121; 120, 124; 121, attribute; 121, 122; 121, 123; 122, identifier:subprocess; 123, identifier:Popen; 124, argument_list; 124, 125; 124, 126; 124, 129; 124, 132; 125, identifier:cmd; 126, keyword_argument; 126, 127; 126, 128; 127, identifier:stdout; 128, identifier:stdout; 129, keyword_argument; 129, 130; 129, 131; 130, identifier:stderr; 131, identifier:stderr; 132, keyword_argument; 132, 133; 132, 134; 133, identifier:shell; 134, identifier:shell; 135, except_clause; 135, 136; 135, 140; 136, as_pattern; 136, 137; 136, 138; 137, identifier:Exception; 138, as_pattern_target; 138, 139; 139, identifier:e; 140, block; 140, 141; 140, 172; 141, try_statement; 141, 142; 141, 163; 142, block; 142, 143; 143, if_statement; 143, 144; 143, 147; 143, 157; 144, comparison_operator:is; 144, 145; 144, 146; 145, identifier:shell; 146, True; 147, block; 147, 148; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 151; 150, identifier:cmdStr; 151, call; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, string:' '; 154, identifier:join; 155, argument_list; 155, 156; 156, identifier:cmd; 157, else_clause; 157, 158; 158, block; 158, 159; 159, expression_statement; 159, 160; 160, assignment; 160, 161; 160, 162; 161, identifier:cmdStr; 162, identifier:cmd; 163, except_clause; 163, 164; 164, block; 164, 165; 165, expression_statement; 165, 166; 166, assignment; 166, 167; 166, 168; 167, identifier:cmdStr; 168, call; 168, 169; 168, 170; 169, identifier:repr; 170, argument_list; 170, 171; 171, identifier:cmd; 172, raise_statement; 172, 173; 173, call; 173, 174; 173, 175; 174, identifier:SimpleCommandFailure; 175, argument_list; 175, 176; 175, 184; 176, binary_operator:%; 176, 177; 176, 178; 177, string:'Failed to execute "%s": %s'; 178, tuple; 178, 179; 178, 180; 179, identifier:cmdStr; 180, call; 180, 181; 180, 182; 181, identifier:str; 182, argument_list; 182, 183; 183, identifier:e; 184, keyword_argument; 184, 185; 184, 186; 185, identifier:returnCode; 186, integer:255; 187, expression_statement; 187, 188; 188, assignment; 188, 189; 188, 190; 189, identifier:streams; 190, list:[]; 191, expression_statement; 191, 192; 192, assignment; 192, 193; 192, 194; 193, identifier:fileNoToKey; 194, dictionary; 195, expression_statement; 195, 196; 196, assignment; 196, 197; 196, 198; 197, identifier:ret; 198, dictionary; 199, if_statement; 199, 200; 199, 205; 200, comparison_operator:==; 200, 201; 200, 202; 201, identifier:stdout; 202, attribute; 202, 203; 202, 204; 203, identifier:subprocess; 204, identifier:PIPE; 205, block; 205, 206; 205, 215; 205, 227; 206, expression_statement; 206, 207; 207, call; 207, 208; 207, 211; 208, attribute; 208, 209; 208, 210; 209, identifier:streams; 210, identifier:append; 211, argument_list; 211, 212; 212, attribute; 212, 213; 212, 214; 213, identifier:pipe; 214, identifier:stdout; 215, expression_statement; 215, 216; 216, assignment; 216, 217; 216, 226; 217, subscript; 217, 218; 217, 219; 218, identifier:fileNoToKey; 219, call; 219, 220; 219, 225; 220, attribute; 220, 221; 220, 224; 221, attribute; 221, 222; 221, 223; 222, identifier:pipe; 223, identifier:stdout; 224, identifier:fileno; 225, argument_list; 226, string:'stdout'; 227, expression_statement; 227, 228; 228, assignment; 228, 229; 228, 232; 229, subscript; 229, 230; 229, 231; 230, identifier:ret; 231, string:'stdout'; 232, list:[]; 233, if_statement; 233, 234; 233, 239; 234, comparison_operator:==; 234, 235; 234, 236; 235, identifier:stderr; 236, attribute; 236, 237; 236, 238; 237, identifier:subprocess; 238, identifier:PIPE; 239, block; 239, 240; 239, 249; 239, 261; 240, expression_statement; 240, 241; 241, call; 241, 242; 241, 245; 242, attribute; 242, 243; 242, 244; 243, identifier:streams; 244, identifier:append; 245, argument_list; 245, 246; 246, attribute; 246, 247; 246, 248; 247, identifier:pipe; 248, identifier:stderr; 249, expression_statement; 249, 250; 250, assignment; 250, 251; 250, 260; 251, subscript; 251, 252; 251, 253; 252, identifier:fileNoToKey; 253, call; 253, 254; 253, 259; 254, attribute; 254, 255; 254, 258; 255, attribute; 255, 256; 255, 257; 256, identifier:pipe; 257, identifier:stderr; 258, identifier:fileno; 259, argument_list; 260, string:'stderr'; 261, expression_statement; 261, 262; 262, assignment; 262, 263; 262, 266; 263, subscript; 263, 264; 263, 265; 264, identifier:ret; 265, string:'stderr'; 266, list:[]; 267, expression_statement; 267, 268; 268, assignment; 268, 269; 268, 270; 269, identifier:returnCode; 270, None; 271, expression_statement; 271, 272; 272, call; 272, 273; 272, 276; 273, attribute; 273, 274; 273, 275; 274, identifier:time; 275, identifier:sleep; 276, argument_list; 276, 277; 277, float:.02; 278, while_statement; 278, 279; 278, 284; 279, boolean_operator:or; 279, 280; 279, 283; 280, comparison_operator:is; 280, 281; 280, 282; 281, identifier:returnCode; 282, None; 283, identifier:streams; 284, block; 284, 285; 284, 293; 285, expression_statement; 285, 286; 286, assignment; 286, 287; 286, 288; 287, identifier:returnCode; 288, call; 288, 289; 288, 292; 289, attribute; 289, 290; 289, 291; 290, identifier:pipe; 291, identifier:poll; 292, argument_list; 293, while_statement; 293, 294; 293, 295; 294, True; 295, block; 295, 296; 295, 311; 295, 324; 296, expression_statement; 296, 297; 297, assignment; 297, 298; 297, 302; 298, tuple_pattern; 298, 299; 298, 300; 298, 301; 299, identifier:readyToRead; 300, identifier:junk1; 301, identifier:junk2; 302, call; 302, 303; 302, 306; 303, attribute; 303, 304; 303, 305; 304, identifier:select; 305, identifier:select; 306, argument_list; 306, 307; 306, 308; 306, 309; 306, 310; 307, identifier:streams; 308, list:[]; 309, list:[]; 310, float:.005; 311, if_statement; 311, 312; 311, 314; 311, 315; 312, not_operator; 312, 313; 313, identifier:readyToRead; 314, comment; 315, block; 315, 316; 315, 323; 316, expression_statement; 316, 317; 317, call; 317, 318; 317, 321; 318, attribute; 318, 319; 318, 320; 319, identifier:time; 320, identifier:sleep; 321, argument_list; 321, 322; 322, float:.01; 323, break_statement; 324, for_statement; 324, 325; 324, 326; 324, 327; 325, identifier:readyStream; 326, identifier:readyToRead; 327, block; 327, 328; 327, 338; 327, 346; 327, 361; 328, expression_statement; 328, 329; 329, assignment; 329, 330; 329, 331; 330, identifier:retKey; 331, subscript; 331, 332; 331, 333; 332, identifier:fileNoToKey; 333, call; 333, 334; 333, 337; 334, attribute; 334, 335; 334, 336; 335, identifier:readyStream; 336, identifier:fileno; 337, argument_list; 338, expression_statement; 338, 339; 339, assignment; 339, 340; 339, 341; 340, identifier:curRead; 341, call; 341, 342; 341, 345; 342, attribute; 342, 343; 342, 344; 343, identifier:readyStream; 344, identifier:read; 345, argument_list; 346, if_statement; 346, 347; 346, 352; 347, comparison_operator:in; 347, 348; 347, 349; 348, identifier:curRead; 349, tuple; 349, 350; 349, 351; 350, string:b''; 351, string:''; 352, block; 352, 353; 352, 360; 353, expression_statement; 353, 354; 354, call; 354, 355; 354, 358; 355, attribute; 355, 356; 355, 357; 356, identifier:streams; 357, identifier:remove; 358, argument_list; 358, 359; 359, identifier:readyStream; 360, continue_statement; 361, expression_statement; 361, 362; 362, call; 362, 363; 362, 368; 363, attribute; 363, 364; 363, 367; 364, subscript; 364, 365; 364, 366; 365, identifier:ret; 366, identifier:retKey; 367, identifier:append; 368, argument_list; 368, 369; 369, identifier:curRead; 370, for_statement; 370, 371; 370, 372; 370, 380; 371, identifier:key; 372, call; 372, 373; 372, 374; 373, identifier:list; 374, argument_list; 374, 375; 375, call; 375, 376; 375, 379; 376, attribute; 376, 377; 376, 378; 377, identifier:ret; 378, identifier:keys; 379, argument_list; 380, block; 380, 381; 380, 394; 381, expression_statement; 381, 382; 382, assignment; 382, 383; 382, 386; 383, subscript; 383, 384; 383, 385; 384, identifier:ret; 385, identifier:key; 386, call; 386, 387; 386, 390; 387, attribute; 387, 388; 387, 389; 388, string:b''; 389, identifier:join; 390, argument_list; 390, 391; 391, subscript; 391, 392; 391, 393; 392, identifier:ret; 393, identifier:key; 394, if_statement; 394, 395; 394, 396; 395, identifier:encoding; 396, block; 396, 397; 397, expression_statement; 397, 398; 398, assignment; 398, 399; 398, 402; 399, subscript; 399, 400; 399, 401; 400, identifier:ret; 401, identifier:key; 402, call; 402, 403; 402, 408; 403, attribute; 403, 404; 403, 407; 404, subscript; 404, 405; 404, 406; 405, identifier:ret; 406, identifier:key; 407, identifier:decode; 408, argument_list; 408, 409; 409, identifier:encoding; 410, expression_statement; 410, 411; 411, assignment; 411, 412; 411, 415; 412, subscript; 412, 413; 412, 414; 413, identifier:ret; 414, string:'returnCode'; 415, identifier:returnCode; 416, return_statement; 416, 417; 417, identifier:ret | def runGetResults(cmd, stdout=True, stderr=True, encoding=sys.getdefaultencoding()):
'''
runGetResults - Simple method to run a command and return the results of the execution as a dict.
@param cmd <str/list> - String of command and arguments, or list of command and arguments
If cmd is a string, the command will be executed as if ran exactly as written in a shell. This mode supports shell-isms like '&&' and '|'
If cmd is a list, the first element will be the executable, and further elements are arguments that will be passed to that executable.
@param stdout <True/False> - Default True, Whether to gather and include program's stdout data in results.
If False, that data the program prints to stdout will just be output to the current tty and not recorded.
If True, it will NOT be output to the tty, and will be recorded under the key "stdout" in the return dict.
@param stderr <True/False or "stdout"/subprocess.STDOUT> - Default True, Whether to gather and include program's stderr data in results, or to combine with "stdout" data.
If False, the data the program prints to stderr will just be output to the current tty and not recorded
If True, it will NOT be output to the tty, and will be recorded under the key "stderr" in the return dict.
If "stdout" or subprocess.STDOUT - stderr data will be blended with stdout data. This requires that stdout=True.
@param encoding <None/str> - Default sys.getdefaultencoding(), the program's output will automatically be decoded using the provided codec (e.x. "utf-8" or "ascii").
If None or False-ish, data will not be decoded (i.e. in python3 will be "bytes" type)
If unsure, leave this as it's default value, or provide "utf-8"
@return <dict> - Dict of results. Has following keys:
'returnCode' - <int> - Always present, included the integer return-code from the command.
'stdout' <unciode/str/bytes (depending on #encoding)> - Present if stdout=True, contains data output by program to stdout, or stdout+stderr if stderr param is "stdout"/subprocess.STDOUT
'stderr' <unicode/str/bytes (depending on #encoding)> - Present if stderr=True, contains data output by program to stderr.
@raises - SimpleCommandFailure if it cannot launch the given command, for reasons such as: cannot find the executable, or no permission to execute, etc
'''
if stderr in ('stdout', subprocess.STDOUT):
stderr = subprocess.STDOUT
elif stderr == True or stderr == subprocess.PIPE:
stderr = subprocess.PIPE
else:
stderr = None
if stdout == True or stdout == subprocess.STDOUT:
stdout = subprocess.PIPE
else:
stdout = None
if stderr == subprocess.PIPE:
raise ValueError('Cannot redirect stderr to stdout if stdout is not captured.')
if issubclass(cmd.__class__, (list, tuple)):
shell = False
else:
shell = True
try:
pipe = subprocess.Popen(cmd, stdout=stdout, stderr=stderr, shell=shell)
except Exception as e:
try:
if shell is True:
cmdStr = ' '.join(cmd)
else:
cmdStr = cmd
except:
cmdStr = repr(cmd)
raise SimpleCommandFailure('Failed to execute "%s": %s' %(cmdStr, str(e)), returnCode=255)
streams = []
fileNoToKey = {}
ret = {}
if stdout == subprocess.PIPE:
streams.append(pipe.stdout)
fileNoToKey[pipe.stdout.fileno()] = 'stdout'
ret['stdout'] = []
if stderr == subprocess.PIPE:
streams.append(pipe.stderr)
fileNoToKey[pipe.stderr.fileno()] = 'stderr'
ret['stderr'] = []
returnCode = None
time.sleep(.02)
while returnCode is None or streams:
returnCode = pipe.poll()
while True:
(readyToRead, junk1, junk2) = select.select(streams, [], [], .005)
if not readyToRead:
# Don't strangle CPU
time.sleep(.01)
break
for readyStream in readyToRead:
retKey = fileNoToKey[readyStream.fileno()]
curRead = readyStream.read()
if curRead in (b'', ''):
streams.remove(readyStream)
continue
ret[retKey].append(curRead)
for key in list(ret.keys()):
ret[key] = b''.join(ret[key])
if encoding:
ret[key] = ret[key].decode(encoding)
ret['returnCode'] = returnCode
return ret |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:_pathway_feature_permutation; 3, parameters; 3, 4; 3, 5; 4, identifier:pathway_feature_tuples; 5, identifier:permutation_max_iters; 6, block; 6, 7; 6, 9; 6, 26; 6, 33; 6, 40; 6, 44; 6, 48; 6, 262; 6, 269; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 14; 11, pattern_list; 11, 12; 11, 13; 12, identifier:pathways; 13, identifier:features; 14, list_comprehension; 14, 15; 14, 19; 15, call; 15, 16; 15, 17; 16, identifier:list; 17, argument_list; 17, 18; 18, identifier:elements_at_position; 19, for_in_clause; 19, 20; 19, 21; 20, identifier:elements_at_position; 21, call; 21, 22; 21, 23; 22, identifier:zip; 23, argument_list; 23, 24; 24, list_splat; 24, 25; 25, identifier:pathway_feature_tuples; 26, expression_statement; 26, 27; 27, assignment; 27, 28; 27, 29; 28, identifier:original_pathways; 29, subscript; 29, 30; 29, 31; 30, identifier:pathways; 31, slice; 31, 32; 32, colon; 33, expression_statement; 33, 34; 34, call; 34, 35; 34, 38; 35, attribute; 35, 36; 35, 37; 36, identifier:random; 37, identifier:shuffle; 38, argument_list; 38, 39; 39, identifier:pathways; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:feature_block_locations; 43, dictionary; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:i; 47, integer:0; 48, while_statement; 48, 49; 48, 55; 49, comparison_operator:<; 49, 50; 49, 51; 50, identifier:i; 51, call; 51, 52; 51, 53; 52, identifier:len; 53, argument_list; 53, 54; 54, identifier:pathways; 55, block; 55, 56; 55, 60; 55, 66; 55, 72; 55, 73; 55, 74; 55, 75; 55, 250; 55, 254; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:starting_index; 59, identifier:i; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:current_feature; 63, subscript; 63, 64; 63, 65; 64, identifier:features; 65, identifier:i; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:pathway_set; 69, call; 69, 70; 69, 71; 70, identifier:set; 71, argument_list; 72, comment; 73, comment; 74, comment; 75, while_statement; 75, 76; 75, 88; 75, 89; 75, 90; 75, 91; 76, boolean_operator:and; 76, 77; 76, 83; 77, comparison_operator:<; 77, 78; 77, 79; 78, identifier:i; 79, call; 79, 80; 79, 81; 80, identifier:len; 81, argument_list; 81, 82; 82, identifier:pathways; 83, comparison_operator:==; 83, 84; 83, 87; 84, subscript; 84, 85; 84, 86; 85, identifier:features; 86, identifier:i; 87, identifier:current_feature; 88, comment; 89, comment; 90, comment; 91, block; 91, 92; 91, 246; 92, if_statement; 92, 93; 92, 98; 92, 108; 93, comparison_operator:not; 93, 94; 93, 97; 94, subscript; 94, 95; 94, 96; 95, identifier:pathways; 96, identifier:i; 97, identifier:pathway_set; 98, block; 98, 99; 99, expression_statement; 99, 100; 100, call; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:pathway_set; 103, identifier:add; 104, argument_list; 104, 105; 105, subscript; 105, 106; 105, 107; 106, identifier:pathways; 107, identifier:i; 108, else_clause; 108, 109; 109, block; 109, 110; 109, 114; 109, 118; 109, 225; 109, 232; 109, 240; 110, expression_statement; 110, 111; 111, assignment; 111, 112; 111, 113; 112, identifier:k; 113, integer:0; 114, expression_statement; 114, 115; 115, assignment; 115, 116; 115, 117; 116, identifier:random_pathway; 117, None; 118, while_statement; 118, 119; 118, 120; 118, 121; 118, 122; 119, True; 120, comment; 121, comment; 122, block; 122, 123; 122, 139; 122, 145; 122, 151; 122, 202; 122, 206; 123, expression_statement; 123, 124; 124, assignment; 124, 125; 124, 126; 125, identifier:j; 126, call; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:random; 129, identifier:choice; 130, argument_list; 130, 131; 131, call; 131, 132; 131, 133; 132, identifier:range; 133, argument_list; 133, 134; 133, 135; 134, integer:0; 135, call; 135, 136; 135, 137; 136, identifier:len; 137, argument_list; 137, 138; 138, identifier:pathways; 139, expression_statement; 139, 140; 140, assignment; 140, 141; 140, 142; 141, identifier:random_pathway; 142, subscript; 142, 143; 142, 144; 143, identifier:pathways; 144, identifier:j; 145, expression_statement; 145, 146; 146, assignment; 146, 147; 146, 148; 147, identifier:random_feature; 148, subscript; 148, 149; 148, 150; 149, identifier:features; 150, identifier:j; 151, if_statement; 151, 152; 151, 162; 151, 163; 151, 164; 152, parenthesized_expression; 152, 153; 153, boolean_operator:and; 153, 154; 153, 159; 154, comparison_operator:!=; 154, 155; 154, 156; 155, identifier:random_pathway; 156, subscript; 156, 157; 156, 158; 157, identifier:pathways; 158, identifier:i; 159, comparison_operator:not; 159, 160; 159, 161; 160, identifier:random_pathway; 161, identifier:pathway_set; 162, comment; 163, comment; 164, block; 164, 165; 164, 171; 164, 172; 164, 173; 164, 182; 164, 191; 164, 192; 164, 193; 164, 194; 165, if_statement; 165, 166; 165, 169; 166, comparison_operator:not; 166, 167; 166, 168; 167, identifier:random_feature; 168, identifier:feature_block_locations; 169, block; 169, 170; 170, break_statement; 171, comment; 172, comment; 173, expression_statement; 173, 174; 174, assignment; 174, 175; 174, 178; 174, 179; 175, pattern_list; 175, 176; 175, 177; 176, identifier:feature_block_start; 177, identifier:feature_block_end; 178, line_continuation:\; 179, subscript; 179, 180; 179, 181; 180, identifier:feature_block_locations; 181, identifier:random_feature; 182, expression_statement; 182, 183; 183, assignment; 183, 184; 183, 185; 184, identifier:pathway_block; 185, subscript; 185, 186; 185, 187; 186, identifier:pathways; 187, slice; 187, 188; 187, 189; 187, 190; 188, identifier:feature_block_start; 189, colon; 190, identifier:feature_block_end; 191, comment; 192, comment; 193, comment; 194, if_statement; 194, 195; 194, 200; 195, comparison_operator:not; 195, 196; 195, 199; 196, subscript; 196, 197; 196, 198; 197, identifier:pathways; 198, identifier:i; 199, identifier:pathway_block; 200, block; 200, 201; 201, break_statement; 202, expression_statement; 202, 203; 203, augmented_assignment:+=; 203, 204; 203, 205; 204, identifier:k; 205, integer:1; 206, if_statement; 206, 207; 206, 210; 207, comparison_operator:>; 207, 208; 207, 209; 208, identifier:k; 209, identifier:permutation_max_iters; 210, block; 210, 211; 210, 223; 211, expression_statement; 211, 212; 212, call; 212, 213; 212, 214; 213, identifier:print; 214, argument_list; 214, 215; 215, call; 215, 216; 215, 221; 216, attribute; 216, 217; 216, 220; 217, concatenated_string; 217, 218; 217, 219; 218, string:"Permutation step: reached the maximum "; 219, string:"number of iterations {0}."; 220, identifier:format; 221, argument_list; 221, 222; 222, identifier:permutation_max_iters; 223, return_statement; 223, 224; 224, None; 225, expression_statement; 225, 226; 226, call; 226, 227; 226, 230; 227, attribute; 227, 228; 227, 229; 228, identifier:pathway_set; 229, identifier:add; 230, argument_list; 230, 231; 231, identifier:random_pathway; 232, expression_statement; 232, 233; 233, assignment; 233, 234; 233, 237; 234, subscript; 234, 235; 234, 236; 235, identifier:pathways; 236, identifier:j; 237, subscript; 237, 238; 237, 239; 238, identifier:pathways; 239, identifier:i; 240, expression_statement; 240, 241; 241, assignment; 241, 242; 241, 245; 242, subscript; 242, 243; 242, 244; 243, identifier:pathways; 244, identifier:i; 245, identifier:random_pathway; 246, expression_statement; 246, 247; 247, augmented_assignment:+=; 247, 248; 247, 249; 248, identifier:i; 249, integer:1; 250, expression_statement; 250, 251; 251, assignment; 251, 252; 251, 253; 252, identifier:ending_index; 253, identifier:i; 254, expression_statement; 254, 255; 255, assignment; 255, 256; 255, 259; 256, subscript; 256, 257; 256, 258; 257, identifier:feature_block_locations; 258, identifier:current_feature; 259, tuple; 259, 260; 259, 261; 260, identifier:starting_index; 261, identifier:ending_index; 262, if_statement; 262, 263; 262, 266; 263, comparison_operator:==; 263, 264; 263, 265; 264, identifier:original_pathways; 265, identifier:pathways; 266, block; 266, 267; 267, return_statement; 267, 268; 268, None; 269, return_statement; 269, 270; 270, call; 270, 271; 270, 272; 271, identifier:list; 272, argument_list; 272, 273; 273, call; 273, 274; 273, 275; 274, identifier:zip; 275, argument_list; 275, 276; 275, 277; 276, identifier:pathways; 277, identifier:features | def _pathway_feature_permutation(pathway_feature_tuples,
permutation_max_iters):
"""Permute the pathways across features for one side in the
network. Used in `permute_pathways_across_features`
Parameters
-----------
pathway_feature_tuples : list(tup(str, int))
a tuple list [(pathway, feature)] where the pathway, feature pairing
indicates that a pathway was overrepresented in that feature
permutation_max_iters : int
specify the maximum number of iterations, limit the number of attempts
we have to generate a permutation
Returns
-----------
list(tup(str, int)), the list of pathway, feature pairings after the
permutation
"""
pathways, features = [list(elements_at_position)
for elements_at_position in
zip(*pathway_feature_tuples)]
original_pathways = pathways[:]
random.shuffle(pathways)
feature_block_locations = {}
i = 0
while i < len(pathways):
starting_index = i
current_feature = features[i]
pathway_set = set()
# input is grouped by feature, so we want to keep track of the start
# and end of a given "block" of the same feature--this corresponds
# to all the pathways overrepresented in that feature.
while i < len(pathways) and features[i] == current_feature:
# check the results of the permutation. if `pathway_set` does
# not contain the current pathway, we are maintaining the
# necessary invariants in our permutation thus far.
if pathways[i] not in pathway_set:
pathway_set.add(pathways[i])
else:
k = 0
random_pathway = None
while True:
# select another random pathway from the list
# and get the feature to which it belongs
j = random.choice(range(0, len(pathways)))
random_pathway = pathways[j]
random_feature = features[j]
if (random_pathway != pathways[i] and
random_pathway not in pathway_set):
# if this is a feature we have not already seen,
# we are done.
if random_feature not in feature_block_locations:
break
# otherwise, look at the indices that correspond
# to that feature's block of pathways
feature_block_start, feature_block_end = \
feature_block_locations[random_feature]
pathway_block = pathways[feature_block_start:
feature_block_end]
# make sure that the current pathway is not in
# that block--ensures that we maintain the invariant
# after the swap
if pathways[i] not in pathway_block:
break
k += 1
if k > permutation_max_iters:
print("Permutation step: reached the maximum "
"number of iterations {0}.".format(
permutation_max_iters))
return None
pathway_set.add(random_pathway)
pathways[j] = pathways[i]
pathways[i] = random_pathway
i += 1
ending_index = i
feature_block_locations[current_feature] = (
starting_index, ending_index)
if original_pathways == pathways:
return None
return list(zip(pathways, features)) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:get_field_infos; 3, parameters; 3, 4; 3, 5; 4, identifier:code; 5, identifier:free_format; 6, block; 6, 7; 6, 9; 6, 13; 6, 17; 6, 24; 6, 28; 6, 199; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:offset; 12, integer:0; 13, expression_statement; 13, 14; 14, assignment; 14, 15; 14, 16; 15, identifier:field_infos; 16, list:[]; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:lines; 20, call; 20, 21; 20, 22; 21, identifier:_clean_code; 22, argument_list; 22, 23; 23, identifier:code; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:previous_offset; 27, integer:0; 28, for_statement; 28, 29; 28, 30; 28, 35; 29, identifier:row; 30, call; 30, 31; 30, 32; 31, identifier:process_cobol; 32, argument_list; 32, 33; 32, 34; 33, identifier:lines; 34, identifier:free_format; 35, block; 35, 36; 35, 42; 35, 50; 35, 58; 35, 66; 35, 74; 35, 82; 35, 90; 35, 91; 35, 115; 35, 116; 35, 127; 35, 128; 35, 139; 35, 140; 35, 151; 35, 152; 35, 158; 35, 159; 35, 178; 35, 185; 35, 186; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:fi; 39, call; 39, 40; 39, 41; 40, identifier:PicFieldInfo; 41, argument_list; 42, expression_statement; 42, 43; 43, assignment; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:fi; 46, identifier:name; 47, subscript; 47, 48; 47, 49; 48, identifier:row; 49, string:"name"; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 55; 52, attribute; 52, 53; 52, 54; 53, identifier:fi; 54, identifier:level; 55, subscript; 55, 56; 55, 57; 56, identifier:row; 57, string:"level"; 58, expression_statement; 58, 59; 59, assignment; 59, 60; 59, 63; 60, attribute; 60, 61; 60, 62; 61, identifier:fi; 62, identifier:pic; 63, subscript; 63, 64; 63, 65; 64, identifier:row; 65, string:"pic"; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 71; 68, attribute; 68, 69; 68, 70; 69, identifier:fi; 70, identifier:occurs; 71, subscript; 71, 72; 71, 73; 72, identifier:row; 73, string:"occurs"; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 79; 76, attribute; 76, 77; 76, 78; 77, identifier:fi; 78, identifier:redefines; 79, subscript; 79, 80; 79, 81; 80, identifier:row; 81, string:"redefines"; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 87; 84, attribute; 84, 85; 84, 86; 85, identifier:fi; 86, identifier:indexed_by; 87, subscript; 87, 88; 87, 89; 88, identifier:row; 89, string:"indexed_by"; 90, comment; 91, if_statement; 91, 92; 91, 95; 92, attribute; 92, 93; 92, 94; 93, identifier:fi; 94, identifier:redefines; 95, block; 95, 96; 96, for_statement; 96, 97; 96, 98; 96, 99; 97, identifier:fib; 98, identifier:field_infos; 99, block; 99, 100; 100, if_statement; 100, 101; 100, 108; 101, comparison_operator:==; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:fib; 104, identifier:name; 105, attribute; 105, 106; 105, 107; 106, identifier:fi; 107, identifier:redefines; 108, block; 108, 109; 109, expression_statement; 109, 110; 110, assignment; 110, 111; 110, 112; 111, identifier:offset; 112, attribute; 112, 113; 112, 114; 113, identifier:fib; 114, identifier:offset; 115, comment; 116, if_statement; 116, 117; 116, 122; 117, comparison_operator:==; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, identifier:fi; 120, identifier:level; 121, integer:1; 122, block; 122, 123; 123, expression_statement; 123, 124; 124, assignment; 124, 125; 124, 126; 125, identifier:offset; 126, integer:1; 127, comment; 128, if_statement; 128, 129; 128, 134; 129, comparison_operator:==; 129, 130; 129, 133; 130, attribute; 130, 131; 130, 132; 131, identifier:fi; 132, identifier:level; 133, integer:78; 134, block; 134, 135; 135, expression_statement; 135, 136; 136, assignment; 136, 137; 136, 138; 137, identifier:offset; 138, integer:0; 139, comment; 140, if_statement; 140, 141; 140, 146; 141, comparison_operator:==; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, identifier:fi; 144, identifier:level; 145, integer:77; 146, block; 146, 147; 147, expression_statement; 147, 148; 148, assignment; 148, 149; 148, 150; 149, identifier:offset; 150, integer:1; 151, comment; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 157; 154, attribute; 154, 155; 154, 156; 155, identifier:fi; 156, identifier:offset; 157, identifier:offset; 158, comment; 159, if_statement; 159, 160; 159, 165; 159, 172; 160, comparison_operator:==; 160, 161; 160, 164; 161, attribute; 161, 162; 161, 163; 162, identifier:fi; 163, identifier:level; 164, integer:88; 165, block; 165, 166; 166, expression_statement; 166, 167; 167, assignment; 167, 168; 167, 171; 168, attribute; 168, 169; 168, 170; 169, identifier:fi; 170, identifier:offset; 171, identifier:previous_offset; 172, else_clause; 172, 173; 173, block; 173, 174; 174, expression_statement; 174, 175; 175, assignment; 175, 176; 175, 177; 176, identifier:previous_offset; 177, identifier:offset; 178, expression_statement; 178, 179; 179, call; 179, 180; 179, 183; 180, attribute; 180, 181; 180, 182; 181, identifier:field_infos; 182, identifier:append; 183, argument_list; 183, 184; 184, identifier:fi; 185, comment; 186, if_statement; 186, 187; 186, 190; 187, subscript; 187, 188; 187, 189; 188, identifier:row; 189, string:'pic'; 190, block; 190, 191; 191, expression_statement; 191, 192; 192, augmented_assignment:+=; 192, 193; 192, 194; 193, identifier:offset; 194, subscript; 194, 195; 194, 198; 195, subscript; 195, 196; 195, 197; 196, identifier:row; 197, string:'pic_info'; 198, string:'length'; 199, return_statement; 199, 200; 200, identifier:field_infos | def get_field_infos(code, free_format):
"""
Gets the list of pic fields information from line |start| to line |end|.
:param code: code to parse
:returns: the list of pic fields info found in the specified text.
"""
offset = 0
field_infos = []
lines = _clean_code(code)
previous_offset = 0
for row in process_cobol(lines, free_format):
fi = PicFieldInfo()
fi.name = row["name"]
fi.level = row["level"]
fi.pic = row["pic"]
fi.occurs = row["occurs"]
fi.redefines = row["redefines"]
fi.indexed_by = row["indexed_by"]
# find item that was redefined and use its offset
if fi.redefines:
for fib in field_infos:
if fib.name == fi.redefines:
offset = fib.offset
# level 1 should have their offset set to 1
if fi.level == 1:
offset = 1
# level 78 have no offset
if fi.level == 78:
offset = 0
# level 77 have offset always to 1
if fi.level == 77:
offset = 1
# set item offset
fi.offset = offset
# special case: level 88 have the same level as its parent
if fi.level == 88:
fi.offset = previous_offset
else:
previous_offset = offset
field_infos.append(fi)
# compute offset of next PIC field.
if row['pic']:
offset += row['pic_info']['length']
return field_infos |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:_advanced_acronym_detection; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 4, identifier:s; 5, identifier:i; 6, identifier:words; 7, identifier:acronyms; 8, block; 8, 9; 8, 11; 8, 12; 8, 26; 8, 27; 8, 31; 8, 32; 8, 45; 8, 46; 8, 161; 8, 162; 8, 177; 8, 178; 8, 179; 8, 185; 8, 186; 8, 198; 8, 199; 8, 234; 9, expression_statement; 9, 10; 10, comment; 11, comment; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:acstr; 15, call; 15, 16; 15, 19; 16, attribute; 16, 17; 16, 18; 17, string:''; 18, identifier:join; 19, argument_list; 19, 20; 20, subscript; 20, 21; 20, 22; 21, identifier:words; 22, slice; 22, 23; 22, 24; 22, 25; 23, identifier:s; 24, colon; 25, identifier:i; 26, comment; 27, expression_statement; 27, 28; 28, assignment; 28, 29; 28, 30; 29, identifier:range_list; 30, list:[]; 31, comment; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:not_range; 35, call; 35, 36; 35, 37; 36, identifier:set; 37, argument_list; 37, 38; 38, call; 38, 39; 38, 40; 39, identifier:range; 40, argument_list; 40, 41; 41, call; 41, 42; 41, 43; 42, identifier:len; 43, argument_list; 43, 44; 44, identifier:acstr; 45, comment; 46, for_statement; 46, 47; 46, 48; 46, 49; 46, 50; 47, identifier:acronym; 48, identifier:acronyms; 49, comment; 50, block; 50, 51; 50, 63; 50, 64; 50, 65; 50, 69; 51, expression_statement; 51, 52; 52, assignment; 52, 53; 52, 54; 53, identifier:rac; 54, call; 54, 55; 54, 58; 55, attribute; 55, 56; 55, 57; 56, identifier:regex; 57, identifier:compile; 58, argument_list; 58, 59; 59, call; 59, 60; 59, 61; 60, identifier:unicode; 61, argument_list; 61, 62; 62, identifier:acronym; 63, comment; 64, comment; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:n; 68, integer:0; 69, while_statement; 69, 70; 69, 71; 70, True; 71, block; 71, 72; 71, 82; 71, 87; 71, 103; 71, 107; 71, 108; 71, 112; 71, 134; 72, expression_statement; 72, 73; 73, assignment; 73, 74; 73, 75; 74, identifier:m; 75, call; 75, 76; 75, 79; 76, attribute; 76, 77; 76, 78; 77, identifier:rac; 78, identifier:search; 79, argument_list; 79, 80; 79, 81; 80, identifier:acstr; 81, identifier:n; 82, if_statement; 82, 83; 82, 85; 83, not_operator; 83, 84; 84, identifier:m; 85, block; 85, 86; 86, break_statement; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 92; 89, pattern_list; 89, 90; 89, 91; 90, identifier:a; 91, identifier:b; 92, expression_list; 92, 93; 92, 98; 93, call; 93, 94; 93, 97; 94, attribute; 94, 95; 94, 96; 95, identifier:m; 96, identifier:start; 97, argument_list; 98, call; 98, 99; 98, 102; 99, attribute; 99, 100; 99, 101; 100, identifier:m; 101, identifier:end; 102, argument_list; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:n; 106, identifier:b; 107, comment; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:ok; 111, True; 112, for_statement; 112, 113; 112, 114; 112, 115; 113, identifier:r; 114, identifier:range_list; 115, block; 115, 116; 116, if_statement; 116, 117; 116, 128; 117, boolean_operator:and; 117, 118; 117, 123; 118, comparison_operator:<; 118, 119; 118, 120; 119, identifier:a; 120, subscript; 120, 121; 120, 122; 121, identifier:r; 122, integer:1; 123, comparison_operator:>; 123, 124; 123, 125; 124, identifier:b; 125, subscript; 125, 126; 125, 127; 126, identifier:r; 127, integer:0; 128, block; 128, 129; 128, 133; 129, expression_statement; 129, 130; 130, assignment; 130, 131; 130, 132; 131, identifier:ok; 132, False; 133, break_statement; 134, if_statement; 134, 135; 134, 136; 135, identifier:ok; 136, block; 136, 137; 136, 146; 137, expression_statement; 137, 138; 138, call; 138, 139; 138, 142; 139, attribute; 139, 140; 139, 141; 140, identifier:range_list; 141, identifier:append; 142, argument_list; 142, 143; 143, tuple; 143, 144; 143, 145; 144, identifier:a; 145, identifier:b; 146, for_statement; 146, 147; 146, 148; 146, 153; 147, identifier:j; 148, call; 148, 149; 148, 150; 149, identifier:xrange; 150, argument_list; 150, 151; 150, 152; 151, identifier:a; 152, identifier:b; 153, block; 153, 154; 154, expression_statement; 154, 155; 155, call; 155, 156; 155, 159; 156, attribute; 156, 157; 156, 158; 157, identifier:not_range; 158, identifier:remove; 159, argument_list; 159, 160; 160, identifier:j; 161, comment; 162, for_statement; 162, 163; 162, 164; 162, 165; 163, identifier:nr; 164, identifier:not_range; 165, block; 165, 166; 166, expression_statement; 166, 167; 167, call; 167, 168; 167, 171; 168, attribute; 168, 169; 168, 170; 169, identifier:range_list; 170, identifier:append; 171, argument_list; 171, 172; 172, tuple; 172, 173; 172, 174; 173, identifier:nr; 174, binary_operator:+; 174, 175; 174, 176; 175, identifier:nr; 176, integer:1; 177, comment; 178, comment; 179, expression_statement; 179, 180; 180, call; 180, 181; 180, 184; 181, attribute; 181, 182; 181, 183; 182, identifier:range_list; 183, identifier:sort; 184, argument_list; 185, comment; 186, for_statement; 186, 187; 186, 188; 186, 193; 187, identifier:_; 188, call; 188, 189; 188, 190; 189, identifier:xrange; 190, argument_list; 190, 191; 190, 192; 191, identifier:s; 192, identifier:i; 193, block; 193, 194; 194, delete_statement; 194, 195; 195, subscript; 195, 196; 195, 197; 196, identifier:words; 197, identifier:s; 198, comment; 199, for_statement; 199, 200; 199, 201; 199, 208; 200, identifier:j; 201, call; 201, 202; 201, 203; 202, identifier:xrange; 203, argument_list; 203, 204; 204, call; 204, 205; 204, 206; 205, identifier:len; 206, argument_list; 206, 207; 207, identifier:range_list; 208, block; 208, 209; 208, 215; 209, expression_statement; 209, 210; 210, assignment; 210, 211; 210, 212; 211, identifier:r; 212, subscript; 212, 213; 212, 214; 213, identifier:range_list; 214, identifier:j; 215, expression_statement; 215, 216; 216, call; 216, 217; 216, 220; 217, attribute; 217, 218; 217, 219; 218, identifier:words; 219, identifier:insert; 220, argument_list; 220, 221; 220, 224; 221, binary_operator:+; 221, 222; 221, 223; 222, identifier:s; 223, identifier:j; 224, subscript; 224, 225; 224, 226; 225, identifier:acstr; 226, slice; 226, 227; 226, 230; 226, 231; 227, subscript; 227, 228; 227, 229; 228, identifier:r; 229, integer:0; 230, colon; 231, subscript; 231, 232; 231, 233; 232, identifier:r; 233, integer:1; 234, return_statement; 234, 235; 235, binary_operator:-; 235, 236; 235, 242; 236, binary_operator:+; 236, 237; 236, 238; 237, identifier:s; 238, call; 238, 239; 238, 240; 239, identifier:len; 240, argument_list; 240, 241; 241, identifier:range_list; 242, integer:1 | def _advanced_acronym_detection(s, i, words, acronyms):
"""
Detect acronyms by checking against a list of acronyms.
Check a run of words represented by the range [s, i].
Return last index of new word groups.
"""
# Combine each letter into single string.
acstr = ''.join(words[s:i])
# List of ranges representing found acronyms.
range_list = []
# Set of remaining letters.
not_range = set(range(len(acstr)))
# Search for each acronym in acstr.
for acronym in acronyms:
# TODO: Sanitize acronyms to include only letters.
rac = regex.compile(unicode(acronym))
# Loop until all instances of the acronym are found,
# instead of just the first.
n = 0
while True:
m = rac.search(acstr, n)
if not m:
break
a, b = m.start(), m.end()
n = b
# Make sure found acronym doesn't overlap with others.
ok = True
for r in range_list:
if a < r[1] and b > r[0]:
ok = False
break
if ok:
range_list.append((a, b))
for j in xrange(a, b):
not_range.remove(j)
# Add remaining letters as ranges.
for nr in not_range:
range_list.append((nr, nr + 1))
# No ranges will overlap, so it's safe to sort by lower bound,
# which sort() will do by default.
range_list.sort()
# Remove original letters in word list.
for _ in xrange(s, i):
del words[s]
# Replace them with new word grouping.
for j in xrange(len(range_list)):
r = range_list[j]
words.insert(s + j, acstr[r[0]:r[1]])
return s + len(range_list) - 1 |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:_separate_words; 3, parameters; 3, 4; 4, identifier:string; 5, block; 5, 6; 5, 8; 5, 12; 5, 16; 5, 17; 5, 18; 5, 22; 5, 23; 5, 27; 5, 28; 5, 37; 5, 38; 5, 39; 5, 43; 5, 62; 5, 63; 5, 64; 5, 222; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:words; 11, list:[]; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:separator; 15, string:""; 16, comment; 17, comment; 18, expression_statement; 18, 19; 19, assignment; 19, 20; 19, 21; 20, identifier:i; 21, integer:1; 22, comment; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:s; 26, integer:0; 27, comment; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:p; 31, subscript; 31, 32; 31, 33; 32, identifier:string; 33, slice; 33, 34; 33, 35; 33, 36; 34, integer:0; 35, colon; 36, integer:1; 37, comment; 38, comment; 39, expression_statement; 39, 40; 40, assignment; 40, 41; 40, 42; 41, identifier:was_upper; 42, False; 43, if_statement; 43, 44; 43, 49; 44, call; 44, 45; 44, 48; 45, attribute; 45, 46; 45, 47; 46, identifier:string; 47, identifier:isupper; 48, argument_list; 49, block; 49, 50; 49, 58; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:string; 53, call; 53, 54; 53, 57; 54, attribute; 54, 55; 54, 56; 55, identifier:string; 56, identifier:lower; 57, argument_list; 58, expression_statement; 58, 59; 59, assignment; 59, 60; 59, 61; 60, identifier:was_upper; 61, True; 62, comment; 63, comment; 64, while_statement; 64, 65; 64, 71; 65, comparison_operator:<=; 65, 66; 65, 67; 66, identifier:i; 67, call; 67, 68; 67, 69; 68, identifier:len; 69, argument_list; 69, 70; 70, identifier:string; 71, block; 71, 72; 71, 83; 71, 87; 71, 156; 71, 214; 71, 218; 72, expression_statement; 72, 73; 73, assignment; 73, 74; 73, 75; 74, identifier:c; 75, subscript; 75, 76; 75, 77; 76, identifier:string; 77, slice; 77, 78; 77, 79; 77, 80; 78, identifier:i; 79, colon; 80, binary_operator:+; 80, 81; 80, 82; 81, identifier:i; 82, integer:1; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:split; 86, False; 87, if_statement; 87, 88; 87, 94; 87, 95; 87, 148; 88, comparison_operator:<; 88, 89; 88, 90; 89, identifier:i; 90, call; 90, 91; 90, 92; 91, identifier:len; 92, argument_list; 92, 93; 93, identifier:string; 94, comment; 95, block; 95, 96; 96, if_statement; 96, 97; 96, 103; 96, 108; 96, 109; 96, 128; 96, 129; 97, call; 97, 98; 97, 101; 98, attribute; 98, 99; 98, 100; 99, identifier:UPPER; 100, identifier:match; 101, argument_list; 101, 102; 102, identifier:c; 103, block; 103, 104; 104, expression_statement; 104, 105; 105, assignment; 105, 106; 105, 107; 106, identifier:split; 107, True; 108, comment; 109, elif_clause; 109, 110; 109, 123; 110, boolean_operator:and; 110, 111; 110, 117; 111, call; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:NOTSEP; 114, identifier:match; 115, argument_list; 115, 116; 116, identifier:c; 117, call; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, identifier:SEP; 120, identifier:match; 121, argument_list; 121, 122; 122, identifier:p; 123, block; 123, 124; 124, expression_statement; 124, 125; 125, assignment; 125, 126; 125, 127; 126, identifier:split; 127, True; 128, comment; 129, elif_clause; 129, 130; 129, 143; 130, boolean_operator:and; 130, 131; 130, 137; 131, call; 131, 132; 131, 135; 132, attribute; 132, 133; 132, 134; 133, identifier:SEP; 134, identifier:match; 135, argument_list; 135, 136; 136, identifier:c; 137, call; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:NOTSEP; 140, identifier:match; 141, argument_list; 141, 142; 142, identifier:p; 143, block; 143, 144; 144, expression_statement; 144, 145; 145, assignment; 145, 146; 145, 147; 146, identifier:split; 147, True; 148, else_clause; 148, 149; 148, 150; 148, 151; 149, comment; 150, comment; 151, block; 151, 152; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:split; 155, True; 156, if_statement; 156, 157; 156, 158; 157, identifier:split; 158, block; 158, 159; 158, 210; 159, if_statement; 159, 160; 159, 166; 159, 179; 160, call; 160, 161; 160, 164; 161, attribute; 161, 162; 161, 163; 162, identifier:NOTSEP; 163, identifier:match; 164, argument_list; 164, 165; 165, identifier:p; 166, block; 166, 167; 167, expression_statement; 167, 168; 168, call; 168, 169; 168, 172; 169, attribute; 169, 170; 169, 171; 170, identifier:words; 171, identifier:append; 172, argument_list; 172, 173; 173, subscript; 173, 174; 173, 175; 174, identifier:string; 175, slice; 175, 176; 175, 177; 175, 178; 176, identifier:s; 177, colon; 178, identifier:i; 179, else_clause; 179, 180; 179, 181; 179, 182; 180, comment; 181, comment; 182, block; 182, 183; 182, 198; 182, 199; 182, 206; 182, 207; 182, 208; 182, 209; 183, if_statement; 183, 184; 183, 186; 184, not_operator; 184, 185; 185, identifier:separator; 186, block; 186, 187; 187, expression_statement; 187, 188; 188, assignment; 188, 189; 188, 190; 189, identifier:separator; 190, subscript; 190, 191; 190, 192; 191, identifier:string; 192, slice; 192, 193; 192, 194; 192, 195; 193, identifier:s; 194, colon; 195, binary_operator:+; 195, 196; 195, 197; 196, identifier:s; 197, integer:1; 198, comment; 199, expression_statement; 199, 200; 200, call; 200, 201; 200, 204; 201, attribute; 201, 202; 201, 203; 202, identifier:words; 203, identifier:append; 204, argument_list; 204, 205; 205, None; 206, comment; 207, comment; 208, comment; 209, comment; 210, expression_statement; 210, 211; 211, assignment; 211, 212; 211, 213; 212, identifier:s; 213, identifier:i; 214, expression_statement; 214, 215; 215, augmented_assignment:+=; 215, 216; 215, 217; 216, identifier:i; 217, integer:1; 218, expression_statement; 218, 219; 219, assignment; 219, 220; 219, 221; 220, identifier:p; 221, identifier:c; 222, return_statement; 222, 223; 223, expression_list; 223, 224; 223, 225; 223, 226; 224, identifier:words; 225, identifier:separator; 226, identifier:was_upper | def _separate_words(string):
"""
Segment string on separator into list of words.
Arguments:
string -- the string we want to process
Returns:
words -- list of words the string got minced to
separator -- the separator char intersecting words
was_upper -- whether string happened to be upper-case
"""
words = []
separator = ""
# Index of current character. Initially 1 because we don't want to check
# if the 0th character is a boundary.
i = 1
# Index of first character in a sequence
s = 0
# Previous character.
p = string[0:1]
# Treat an all-caps stringiable as lower-case, so that every letter isn't
# counted as a boundary.
was_upper = False
if string.isupper():
string = string.lower()
was_upper = True
# Iterate over each character, checking for boundaries, or places where
# the stringiable should divided.
while i <= len(string):
c = string[i:i + 1]
split = False
if i < len(string):
# Detect upper-case letter as boundary.
if UPPER.match(c):
split = True
# Detect transition from separator to not separator.
elif NOTSEP.match(c) and SEP.match(p):
split = True
# Detect transition not separator to separator.
elif SEP.match(c) and NOTSEP.match(p):
split = True
else:
# The loop goes one extra iteration so that it can handle the
# remaining text after the last boundary.
split = True
if split:
if NOTSEP.match(p):
words.append(string[s:i])
else:
# stringiable contains at least one separator.
# Use the first one as the stringiable's primary separator.
if not separator:
separator = string[s:s + 1]
# Use None to indicate a separator in the word list.
words.append(None)
# If separators weren't included in the list, then breaks
# between upper-case sequences ("AAA_BBB") would be
# disregarded; the letter-run detector would count them as one
# sequence ("AAABBB").
s = i
i += 1
p = c
return words, separator, was_upper |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:parse_case; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:string; 5, default_parameter; 5, 6; 5, 7; 6, identifier:acronyms; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:preserve_case; 10, False; 11, block; 11, 12; 11, 14; 11, 24; 11, 50; 11, 51; 11, 52; 11, 56; 11, 57; 11, 61; 11, 62; 11, 122; 11, 135; 11, 136; 11, 137; 11, 149; 11, 150; 11, 159; 11, 187; 12, expression_statement; 12, 13; 13, comment; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 20; 16, pattern_list; 16, 17; 16, 18; 16, 19; 17, identifier:words; 18, identifier:separator; 19, identifier:was_upper; 20, call; 20, 21; 20, 22; 21, identifier:_separate_words; 22, argument_list; 22, 23; 23, identifier:string; 24, if_statement; 24, 25; 24, 26; 24, 27; 24, 39; 25, identifier:acronyms; 26, comment; 27, block; 27, 28; 27, 35; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:acronyms; 31, call; 31, 32; 31, 33; 32, identifier:_sanitize_acronyms; 33, argument_list; 33, 34; 34, identifier:acronyms; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:check_acronym; 38, identifier:_advanced_acronym_detection; 39, else_clause; 39, 40; 40, block; 40, 41; 40, 45; 40, 46; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:acronyms; 44, list:[]; 45, comment; 46, expression_statement; 46, 47; 47, assignment; 47, 48; 47, 49; 48, identifier:check_acronym; 49, identifier:_simple_acronym_detection; 50, comment; 51, comment; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:i; 55, integer:0; 56, comment; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 60; 59, identifier:s; 60, None; 61, comment; 62, while_statement; 62, 63; 62, 69; 63, comparison_operator:<; 63, 64; 63, 65; 64, identifier:i; 65, call; 65, 66; 65, 67; 66, identifier:len; 67, argument_list; 67, 68; 68, identifier:words; 69, block; 69, 70; 69, 76; 69, 118; 70, expression_statement; 70, 71; 71, assignment; 71, 72; 71, 73; 72, identifier:word; 73, subscript; 73, 74; 73, 75; 74, identifier:words; 75, identifier:i; 76, if_statement; 76, 77; 76, 87; 76, 97; 77, boolean_operator:and; 77, 78; 77, 81; 78, comparison_operator:is; 78, 79; 78, 80; 79, identifier:word; 80, None; 81, call; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:UPPER; 84, identifier:match; 85, argument_list; 85, 86; 86, identifier:word; 87, block; 87, 88; 88, if_statement; 88, 89; 88, 92; 89, comparison_operator:is; 89, 90; 89, 91; 90, identifier:s; 91, None; 92, block; 92, 93; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:s; 96, identifier:i; 97, elif_clause; 97, 98; 97, 101; 98, comparison_operator:is; 98, 99; 98, 100; 99, identifier:s; 100, None; 101, block; 101, 102; 101, 114; 102, expression_statement; 102, 103; 103, assignment; 103, 104; 103, 105; 104, identifier:i; 105, binary_operator:+; 105, 106; 105, 113; 106, call; 106, 107; 106, 108; 107, identifier:check_acronym; 108, argument_list; 108, 109; 108, 110; 108, 111; 108, 112; 109, identifier:s; 110, identifier:i; 111, identifier:words; 112, identifier:acronyms; 113, integer:1; 114, expression_statement; 114, 115; 115, assignment; 115, 116; 115, 117; 116, identifier:s; 117, None; 118, expression_statement; 118, 119; 119, augmented_assignment:+=; 119, 120; 119, 121; 120, identifier:i; 121, integer:1; 122, if_statement; 122, 123; 122, 126; 123, comparison_operator:is; 123, 124; 123, 125; 124, identifier:s; 125, None; 126, block; 126, 127; 127, expression_statement; 127, 128; 128, call; 128, 129; 128, 130; 129, identifier:check_acronym; 130, argument_list; 130, 131; 130, 132; 130, 133; 130, 134; 131, identifier:s; 132, identifier:i; 133, identifier:words; 134, identifier:acronyms; 135, comment; 136, comment; 137, expression_statement; 137, 138; 138, assignment; 138, 139; 138, 140; 139, identifier:words; 140, list_comprehension; 140, 141; 140, 142; 140, 145; 141, identifier:w; 142, for_in_clause; 142, 143; 142, 144; 143, identifier:w; 144, identifier:words; 145, if_clause; 145, 146; 146, comparison_operator:is; 146, 147; 146, 148; 147, identifier:w; 148, None; 149, comment; 150, expression_statement; 150, 151; 151, assignment; 151, 152; 151, 153; 152, identifier:case_type; 153, call; 153, 154; 153, 155; 154, identifier:_determine_case; 155, argument_list; 155, 156; 155, 157; 155, 158; 156, identifier:was_upper; 157, identifier:words; 158, identifier:string; 159, if_statement; 159, 160; 159, 161; 159, 177; 160, identifier:preserve_case; 161, block; 161, 162; 162, if_statement; 162, 163; 162, 164; 163, identifier:was_upper; 164, block; 164, 165; 165, expression_statement; 165, 166; 166, assignment; 166, 167; 166, 168; 167, identifier:words; 168, list_comprehension; 168, 169; 168, 174; 169, call; 169, 170; 169, 173; 170, attribute; 170, 171; 170, 172; 171, identifier:w; 172, identifier:upper; 173, argument_list; 174, for_in_clause; 174, 175; 174, 176; 175, identifier:w; 176, identifier:words; 177, else_clause; 177, 178; 178, block; 178, 179; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 182; 181, identifier:words; 182, call; 182, 183; 182, 184; 183, identifier:_normalize_words; 184, argument_list; 184, 185; 184, 186; 185, identifier:words; 186, identifier:acronyms; 187, return_statement; 187, 188; 188, expression_list; 188, 189; 188, 190; 188, 191; 189, identifier:words; 190, identifier:case_type; 191, identifier:separator | def parse_case(string, acronyms=None, preserve_case=False):
"""
Parse a stringiable into a list of words.
Also returns the case type, which can be one of the following:
- upper: All words are upper-case.
- lower: All words are lower-case.
- pascal: All words are title-case or upper-case. Note that the
stringiable may still have separators.
- camel: First word is lower-case, the rest are title-case or
upper-case. stringiable may still have separators.
- mixed: Any other mixing of word casing. Never occurs if there are
no separators.
- unknown: stringiable contains no words.
Also returns the first separator character, or False if there isn't one.
"""
words, separator, was_upper = _separate_words(string)
if acronyms:
# Use advanced acronym detection with list
acronyms = _sanitize_acronyms(acronyms)
check_acronym = _advanced_acronym_detection
else:
acronyms = []
# Fallback to simple acronym detection.
check_acronym = _simple_acronym_detection
# Letter-run detector
# Index of current word.
i = 0
# Index of first letter in run.
s = None
# Find runs of single upper-case letters.
while i < len(words):
word = words[i]
if word is not None and UPPER.match(word):
if s is None:
s = i
elif s is not None:
i = check_acronym(s, i, words, acronyms) + 1
s = None
i += 1
if s is not None:
check_acronym(s, i, words, acronyms)
# Separators are no longer needed, so they can be removed. They *should*
# be removed, since it's supposed to be a *word* list.
words = [w for w in words if w is not None]
# Determine case type.
case_type = _determine_case(was_upper, words, string)
if preserve_case:
if was_upper:
words = [w.upper() for w in words]
else:
words = _normalize_words(words, acronyms)
return words, case_type, separator |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:listen; 3, parameters; 3, 4; 4, identifier:self; 5, block; 5, 6; 5, 8; 5, 9; 5, 10; 5, 11; 5, 22; 5, 23; 5, 27; 5, 48; 5, 58; 5, 59; 5, 73; 5, 80; 5, 81; 6, expression_statement; 6, 7; 7, comment; 8, comment; 9, comment; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:db; 14, call; 14, 15; 14, 20; 15, attribute; 15, 16; 15, 19; 16, attribute; 16, 17; 16, 18; 17, identifier:self; 18, identifier:config; 19, identifier:get_database; 20, argument_list; 20, 21; 21, string:'control'; 22, comment; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:kwargs; 26, dictionary; 27, if_statement; 27, 28; 27, 35; 28, comparison_operator:in; 28, 29; 28, 30; 29, string:'shard_hint'; 30, subscript; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:self; 33, identifier:config; 34, string:'control'; 35, block; 35, 36; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 41; 38, subscript; 38, 39; 38, 40; 39, identifier:kwargs; 40, string:'shard_hint'; 41, subscript; 41, 42; 41, 47; 42, subscript; 42, 43; 42, 46; 43, attribute; 43, 44; 43, 45; 44, identifier:self; 45, identifier:config; 46, string:'control'; 47, string:'shard_hint'; 48, expression_statement; 48, 49; 49, assignment; 49, 50; 49, 51; 50, identifier:pubsub; 51, call; 51, 52; 51, 55; 52, attribute; 52, 53; 52, 54; 53, identifier:db; 54, identifier:pubsub; 55, argument_list; 55, 56; 56, dictionary_splat; 56, 57; 57, identifier:kwargs; 58, comment; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:channel; 62, call; 62, 63; 62, 70; 63, attribute; 63, 64; 63, 69; 64, subscript; 64, 65; 64, 68; 65, attribute; 65, 66; 65, 67; 66, identifier:self; 67, identifier:config; 68, string:'control'; 69, identifier:get; 70, argument_list; 70, 71; 70, 72; 71, string:'channel'; 72, string:'control'; 73, expression_statement; 73, 74; 74, call; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, identifier:pubsub; 77, identifier:subscribe; 78, argument_list; 78, 79; 79, identifier:channel; 80, comment; 81, for_statement; 81, 82; 81, 83; 81, 88; 81, 89; 82, identifier:msg; 83, call; 83, 84; 83, 87; 84, attribute; 84, 85; 84, 86; 85, identifier:pubsub; 86, identifier:listen; 87, argument_list; 88, comment; 89, block; 89, 90; 90, if_statement; 90, 91; 90, 105; 90, 106; 91, parenthesized_expression; 91, 92; 92, boolean_operator:and; 92, 93; 92, 100; 93, comparison_operator:in; 93, 94; 93, 97; 94, subscript; 94, 95; 94, 96; 95, identifier:msg; 96, string:'type'; 97, tuple; 97, 98; 97, 99; 98, string:'pmessage'; 99, string:'message'; 100, comparison_operator:==; 100, 101; 100, 104; 101, subscript; 101, 102; 101, 103; 102, identifier:msg; 103, string:'channel'; 104, identifier:channel; 105, comment; 106, block; 106, 107; 106, 121; 106, 122; 106, 127; 106, 128; 106, 145; 106, 146; 106, 185; 106, 186; 106, 200; 106, 201; 106, 213; 107, expression_statement; 107, 108; 108, assignment; 108, 109; 108, 113; 109, pattern_list; 109, 110; 109, 111; 109, 112; 110, identifier:command; 111, identifier:_sep; 112, identifier:args; 113, call; 113, 114; 113, 119; 114, attribute; 114, 115; 114, 118; 115, subscript; 115, 116; 115, 117; 116, identifier:msg; 117, string:'data'; 118, identifier:partition; 119, argument_list; 119, 120; 120, string:':'; 121, comment; 122, if_statement; 122, 123; 122, 125; 123, not_operator; 123, 124; 124, identifier:command; 125, block; 125, 126; 126, continue_statement; 127, comment; 128, if_statement; 128, 129; 128, 134; 129, comparison_operator:==; 129, 130; 129, 133; 130, subscript; 130, 131; 130, 132; 131, identifier:command; 132, integer:0; 133, string:'_'; 134, block; 134, 135; 134, 144; 135, expression_statement; 135, 136; 136, call; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:LOG; 139, identifier:error; 140, argument_list; 140, 141; 141, binary_operator:%; 141, 142; 141, 143; 142, string:"Cannot call internal command %r"; 143, identifier:command; 144, continue_statement; 145, comment; 146, if_statement; 146, 147; 146, 152; 146, 161; 147, comparison_operator:in; 147, 148; 147, 149; 148, identifier:command; 149, attribute; 149, 150; 149, 151; 150, identifier:self; 151, identifier:_commands; 152, block; 152, 153; 153, expression_statement; 153, 154; 154, assignment; 154, 155; 154, 156; 155, identifier:func; 156, subscript; 156, 157; 156, 160; 157, attribute; 157, 158; 157, 159; 158, identifier:self; 159, identifier:_commands; 160, identifier:command; 161, else_clause; 161, 162; 161, 163; 162, comment; 163, block; 163, 164; 163, 177; 164, expression_statement; 164, 165; 165, assignment; 165, 166; 165, 167; 166, identifier:func; 167, call; 167, 168; 167, 171; 168, attribute; 168, 169; 168, 170; 169, identifier:utils; 170, identifier:find_entrypoint; 171, argument_list; 171, 172; 171, 173; 171, 174; 172, string:'turnstile.command'; 173, identifier:command; 174, keyword_argument; 174, 175; 174, 176; 175, identifier:compat; 176, False; 177, expression_statement; 177, 178; 178, assignment; 178, 179; 178, 184; 179, subscript; 179, 180; 179, 183; 180, attribute; 180, 181; 180, 182; 181, identifier:self; 182, identifier:_commands; 183, identifier:command; 184, identifier:func; 185, comment; 186, if_statement; 186, 187; 186, 189; 187, not_operator; 187, 188; 188, identifier:func; 189, block; 189, 190; 189, 199; 190, expression_statement; 190, 191; 191, call; 191, 192; 191, 195; 192, attribute; 192, 193; 192, 194; 193, identifier:LOG; 194, identifier:error; 195, argument_list; 195, 196; 196, binary_operator:%; 196, 197; 196, 198; 197, string:"No such command %r"; 198, identifier:command; 199, continue_statement; 200, comment; 201, expression_statement; 201, 202; 202, assignment; 202, 203; 202, 204; 203, identifier:arglist; 204, conditional_expression:if; 204, 205; 204, 211; 204, 212; 205, call; 205, 206; 205, 209; 206, attribute; 206, 207; 206, 208; 207, identifier:args; 208, identifier:split; 209, argument_list; 209, 210; 210, string:':'; 211, identifier:args; 212, list:[]; 213, try_statement; 213, 214; 213, 222; 214, block; 214, 215; 215, expression_statement; 215, 216; 216, call; 216, 217; 216, 218; 217, identifier:func; 218, argument_list; 218, 219; 218, 220; 219, identifier:self; 220, list_splat; 220, 221; 221, identifier:arglist; 222, except_clause; 222, 223; 222, 224; 223, identifier:Exception; 224, block; 224, 225; 224, 236; 225, expression_statement; 225, 226; 226, call; 226, 227; 226, 230; 227, attribute; 227, 228; 227, 229; 228, identifier:LOG; 229, identifier:exception; 230, argument_list; 230, 231; 231, binary_operator:%; 231, 232; 231, 233; 232, string:"Failed to execute command %r arguments %r"; 233, tuple; 233, 234; 233, 235; 234, identifier:command; 235, identifier:arglist; 236, continue_statement | def listen(self):
"""
Listen for incoming control messages.
If the 'redis.shard_hint' configuration is set, its value will
be passed to the pubsub() method when setting up the
subscription. The control channel to subscribe to is
specified by the 'redis.control_channel' configuration
('control' by default).
"""
# Use a specific database handle, with override. This allows
# the long-lived listen thread to be configured to use a
# different database or different database options.
db = self.config.get_database('control')
# Need a pub-sub object
kwargs = {}
if 'shard_hint' in self.config['control']:
kwargs['shard_hint'] = self.config['control']['shard_hint']
pubsub = db.pubsub(**kwargs)
# Subscribe to the right channel(s)...
channel = self.config['control'].get('channel', 'control')
pubsub.subscribe(channel)
# Now we listen...
for msg in pubsub.listen():
# Only interested in messages to our reload channel
if (msg['type'] in ('pmessage', 'message') and
msg['channel'] == channel):
# Figure out what kind of message this is
command, _sep, args = msg['data'].partition(':')
# We must have some command...
if not command:
continue
# Don't do anything with internal commands
if command[0] == '_':
LOG.error("Cannot call internal command %r" % command)
continue
# Look up the command
if command in self._commands:
func = self._commands[command]
else:
# Try an entrypoint
func = utils.find_entrypoint('turnstile.command', command,
compat=False)
self._commands[command] = func
# Don't do anything with missing commands
if not func:
LOG.error("No such command %r" % command)
continue
# Execute the desired command
arglist = args.split(':') if args else []
try:
func(self, *arglist)
except Exception:
LOG.exception("Failed to execute command %r arguments %r" %
(command, arglist))
continue |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:initialize; 3, parameters; 3, 4; 4, identifier:config; 5, block; 5, 6; 5, 8; 5, 9; 5, 37; 5, 38; 5, 42; 5, 68; 5, 69; 5, 85; 5, 86; 5, 90; 5, 94; 5, 98; 5, 205; 5, 214; 5, 215; 5, 235; 5, 236; 5, 237; 5, 321; 5, 322; 5, 329; 6, expression_statement; 6, 7; 7, comment; 8, comment; 9, if_statement; 9, 10; 9, 13; 9, 29; 10, comparison_operator:in; 10, 11; 10, 12; 11, string:'redis_client'; 12, identifier:config; 13, block; 13, 14; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:client; 17, call; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:utils; 20, identifier:find_entrypoint; 21, argument_list; 21, 22; 21, 23; 21, 26; 22, string:'turnstile.redis_client'; 23, subscript; 23, 24; 23, 25; 24, identifier:config; 25, string:'redis_client'; 26, keyword_argument; 26, 27; 26, 28; 27, identifier:required; 28, True; 29, else_clause; 29, 30; 30, block; 30, 31; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:client; 34, attribute; 34, 35; 34, 36; 35, identifier:redis; 36, identifier:StrictRedis; 37, comment; 38, expression_statement; 38, 39; 39, assignment; 39, 40; 39, 41; 40, identifier:kwargs; 41, dictionary; 42, for_statement; 42, 43; 42, 46; 42, 51; 43, pattern_list; 43, 44; 43, 45; 44, identifier:cfg_var; 45, identifier:type_; 46, call; 46, 47; 46, 50; 47, attribute; 47, 48; 47, 49; 48, identifier:REDIS_CONFIGS; 49, identifier:items; 50, argument_list; 51, block; 51, 52; 52, if_statement; 52, 53; 52, 56; 53, comparison_operator:in; 53, 54; 53, 55; 54, identifier:cfg_var; 55, identifier:config; 56, block; 56, 57; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 62; 59, subscript; 59, 60; 59, 61; 60, identifier:kwargs; 61, identifier:cfg_var; 62, call; 62, 63; 62, 64; 63, identifier:type_; 64, argument_list; 64, 65; 65, subscript; 65, 66; 65, 67; 66, identifier:config; 67, identifier:cfg_var; 68, comment; 69, if_statement; 69, 70; 69, 77; 70, boolean_operator:and; 70, 71; 70, 74; 71, comparison_operator:not; 71, 72; 71, 73; 72, string:'host'; 73, identifier:kwargs; 74, comparison_operator:not; 74, 75; 74, 76; 75, string:'unix_socket_path'; 76, identifier:kwargs; 77, block; 77, 78; 78, raise_statement; 78, 79; 79, call; 79, 80; 79, 83; 80, attribute; 80, 81; 80, 82; 81, identifier:redis; 82, identifier:ConnectionError; 83, argument_list; 83, 84; 84, string:"No host specified for redis database"; 85, comment; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:cpool_class; 89, None; 90, expression_statement; 90, 91; 91, assignment; 91, 92; 91, 93; 92, identifier:cpool; 93, dictionary; 94, expression_statement; 94, 95; 95, assignment; 95, 96; 95, 97; 96, identifier:extra_kwargs; 97, dictionary; 98, for_statement; 98, 99; 98, 102; 98, 107; 99, pattern_list; 99, 100; 99, 101; 100, identifier:key; 101, identifier:value; 102, call; 102, 103; 102, 106; 103, attribute; 103, 104; 103, 105; 104, identifier:config; 105, identifier:items; 106, argument_list; 107, block; 107, 108; 108, if_statement; 108, 109; 108, 115; 108, 190; 109, call; 109, 110; 109, 113; 110, attribute; 110, 111; 110, 112; 111, identifier:key; 112, identifier:startswith; 113, argument_list; 113, 114; 114, string:'connection_pool.'; 115, block; 115, 116; 115, 128; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 122; 118, pattern_list; 118, 119; 118, 120; 118, 121; 119, identifier:_dummy; 120, identifier:_sep; 121, identifier:varname; 122, call; 122, 123; 122, 126; 123, attribute; 123, 124; 123, 125; 124, identifier:key; 125, identifier:partition; 126, argument_list; 126, 127; 127, string:'.'; 128, if_statement; 128, 129; 128, 132; 128, 148; 128, 162; 128, 182; 129, comparison_operator:==; 129, 130; 129, 131; 130, identifier:varname; 131, string:'connection_class'; 132, block; 132, 133; 133, expression_statement; 133, 134; 134, assignment; 134, 135; 134, 138; 135, subscript; 135, 136; 135, 137; 136, identifier:cpool; 137, identifier:varname; 138, call; 138, 139; 138, 142; 139, attribute; 139, 140; 139, 141; 140, identifier:utils; 141, identifier:find_entrypoint; 142, argument_list; 142, 143; 142, 144; 142, 145; 143, string:'turnstile.connection_class'; 144, identifier:value; 145, keyword_argument; 145, 146; 145, 147; 146, identifier:required; 147, True; 148, elif_clause; 148, 149; 148, 152; 149, comparison_operator:==; 149, 150; 149, 151; 150, identifier:varname; 151, string:'max_connections'; 152, block; 152, 153; 153, expression_statement; 153, 154; 154, assignment; 154, 155; 154, 158; 155, subscript; 155, 156; 155, 157; 156, identifier:cpool; 157, identifier:varname; 158, call; 158, 159; 158, 160; 159, identifier:int; 160, argument_list; 160, 161; 161, identifier:value; 162, elif_clause; 162, 163; 162, 166; 163, comparison_operator:==; 163, 164; 163, 165; 164, identifier:varname; 165, string:'parser_class'; 166, block; 166, 167; 167, expression_statement; 167, 168; 168, assignment; 168, 169; 168, 172; 169, subscript; 169, 170; 169, 171; 170, identifier:cpool; 171, identifier:varname; 172, call; 172, 173; 172, 176; 173, attribute; 173, 174; 173, 175; 174, identifier:utils; 175, identifier:find_entrypoint; 176, argument_list; 176, 177; 176, 178; 176, 179; 177, string:'turnstile.parser_class'; 178, identifier:value; 179, keyword_argument; 179, 180; 179, 181; 180, identifier:required; 181, True; 182, else_clause; 182, 183; 183, block; 183, 184; 184, expression_statement; 184, 185; 185, assignment; 185, 186; 185, 189; 186, subscript; 186, 187; 186, 188; 187, identifier:cpool; 188, identifier:varname; 189, identifier:value; 190, elif_clause; 190, 191; 190, 198; 191, boolean_operator:and; 191, 192; 191, 195; 192, comparison_operator:not; 192, 193; 192, 194; 193, identifier:key; 194, identifier:REDIS_CONFIGS; 195, comparison_operator:not; 195, 196; 195, 197; 196, identifier:key; 197, identifier:REDIS_EXCLUDES; 198, block; 198, 199; 199, expression_statement; 199, 200; 200, assignment; 200, 201; 200, 204; 201, subscript; 201, 202; 201, 203; 202, identifier:extra_kwargs; 203, identifier:key; 204, identifier:value; 205, if_statement; 205, 206; 205, 207; 206, identifier:cpool; 207, block; 207, 208; 208, expression_statement; 208, 209; 209, assignment; 209, 210; 209, 211; 210, identifier:cpool_class; 211, attribute; 211, 212; 211, 213; 212, identifier:redis; 213, identifier:ConnectionPool; 214, comment; 215, if_statement; 215, 216; 215, 219; 216, comparison_operator:in; 216, 217; 216, 218; 217, string:'connection_pool'; 218, identifier:config; 219, block; 219, 220; 220, expression_statement; 220, 221; 221, assignment; 221, 222; 221, 223; 222, identifier:cpool_class; 223, call; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:utils; 226, identifier:find_entrypoint; 227, argument_list; 227, 228; 227, 229; 227, 232; 228, string:'turnstile.connection_pool'; 229, subscript; 229, 230; 229, 231; 230, identifier:config; 231, string:'connection_pool'; 232, keyword_argument; 232, 233; 232, 234; 233, identifier:required; 234, True; 235, comment; 236, comment; 237, if_statement; 237, 238; 237, 239; 238, identifier:cpool_class; 239, block; 239, 240; 239, 247; 239, 248; 239, 306; 239, 307; 239, 308; 240, expression_statement; 240, 241; 241, call; 241, 242; 241, 245; 242, attribute; 242, 243; 242, 244; 243, identifier:cpool; 244, identifier:update; 245, argument_list; 245, 246; 246, identifier:kwargs; 247, comment; 248, if_statement; 248, 249; 248, 252; 249, comparison_operator:not; 249, 250; 249, 251; 250, string:'connection_class'; 251, identifier:cpool; 252, block; 252, 253; 253, if_statement; 253, 254; 253, 257; 253, 296; 254, comparison_operator:in; 254, 255; 254, 256; 255, string:'unix_socket_path'; 256, identifier:cpool; 257, block; 257, 258; 257, 267; 257, 276; 257, 284; 257, 288; 258, if_statement; 258, 259; 258, 262; 259, comparison_operator:in; 259, 260; 259, 261; 260, string:'host'; 261, identifier:cpool; 262, block; 262, 263; 263, delete_statement; 263, 264; 264, subscript; 264, 265; 264, 266; 265, identifier:cpool; 266, string:'host'; 267, if_statement; 267, 268; 267, 271; 268, comparison_operator:in; 268, 269; 268, 270; 269, string:'port'; 270, identifier:cpool; 271, block; 271, 272; 272, delete_statement; 272, 273; 273, subscript; 273, 274; 273, 275; 274, identifier:cpool; 275, string:'port'; 276, expression_statement; 276, 277; 277, assignment; 277, 278; 277, 281; 278, subscript; 278, 279; 278, 280; 279, identifier:cpool; 280, string:'path'; 281, subscript; 281, 282; 281, 283; 282, identifier:cpool; 283, string:'unix_socket_path'; 284, delete_statement; 284, 285; 285, subscript; 285, 286; 285, 287; 286, identifier:cpool; 287, string:'unix_socket_path'; 288, expression_statement; 288, 289; 289, assignment; 289, 290; 289, 293; 290, subscript; 290, 291; 290, 292; 291, identifier:cpool; 292, string:'connection_class'; 293, attribute; 293, 294; 293, 295; 294, identifier:redis; 295, identifier:UnixDomainSocketConnection; 296, else_clause; 296, 297; 297, block; 297, 298; 298, expression_statement; 298, 299; 299, assignment; 299, 300; 299, 303; 300, subscript; 300, 301; 300, 302; 301, identifier:cpool; 302, string:'connection_class'; 303, attribute; 303, 304; 303, 305; 304, identifier:redis; 305, identifier:Connection; 306, comment; 307, comment; 308, expression_statement; 308, 309; 309, assignment; 309, 310; 309, 311; 310, identifier:kwargs; 311, call; 311, 312; 311, 313; 312, identifier:dict; 313, argument_list; 313, 314; 314, keyword_argument; 314, 315; 314, 316; 315, identifier:connection_pool; 316, call; 316, 317; 316, 318; 317, identifier:cpool_class; 318, argument_list; 318, 319; 319, dictionary_splat; 319, 320; 320, identifier:cpool; 321, comment; 322, expression_statement; 322, 323; 323, call; 323, 324; 323, 327; 324, attribute; 324, 325; 324, 326; 325, identifier:kwargs; 326, identifier:update; 327, argument_list; 327, 328; 328, identifier:extra_kwargs; 329, return_statement; 329, 330; 330, call; 330, 331; 330, 332; 331, identifier:client; 332, argument_list; 332, 333; 333, dictionary_splat; 333, 334; 334, identifier:kwargs | def initialize(config):
"""
Initialize a connection to the Redis database.
"""
# Determine the client class to use
if 'redis_client' in config:
client = utils.find_entrypoint('turnstile.redis_client',
config['redis_client'], required=True)
else:
client = redis.StrictRedis
# Extract relevant connection information from the configuration
kwargs = {}
for cfg_var, type_ in REDIS_CONFIGS.items():
if cfg_var in config:
kwargs[cfg_var] = type_(config[cfg_var])
# Make sure we have at a minimum the hostname
if 'host' not in kwargs and 'unix_socket_path' not in kwargs:
raise redis.ConnectionError("No host specified for redis database")
# Look up the connection pool configuration
cpool_class = None
cpool = {}
extra_kwargs = {}
for key, value in config.items():
if key.startswith('connection_pool.'):
_dummy, _sep, varname = key.partition('.')
if varname == 'connection_class':
cpool[varname] = utils.find_entrypoint(
'turnstile.connection_class', value, required=True)
elif varname == 'max_connections':
cpool[varname] = int(value)
elif varname == 'parser_class':
cpool[varname] = utils.find_entrypoint(
'turnstile.parser_class', value, required=True)
else:
cpool[varname] = value
elif key not in REDIS_CONFIGS and key not in REDIS_EXCLUDES:
extra_kwargs[key] = value
if cpool:
cpool_class = redis.ConnectionPool
# Use custom connection pool class if requested...
if 'connection_pool' in config:
cpool_class = utils.find_entrypoint('turnstile.connection_pool',
config['connection_pool'],
required=True)
# If we're using a connection pool, we'll need to pass the keyword
# arguments to that instead of to redis
if cpool_class:
cpool.update(kwargs)
# Use a custom connection class?
if 'connection_class' not in cpool:
if 'unix_socket_path' in cpool:
if 'host' in cpool:
del cpool['host']
if 'port' in cpool:
del cpool['port']
cpool['path'] = cpool['unix_socket_path']
del cpool['unix_socket_path']
cpool['connection_class'] = redis.UnixDomainSocketConnection
else:
cpool['connection_class'] = redis.Connection
# Build the connection pool to use and set up to pass it into
# the redis constructor...
kwargs = dict(connection_pool=cpool_class(**cpool))
# Build and return the database
kwargs.update(extra_kwargs)
return client(**kwargs) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:read_attributes; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:attributes; 7, None; 8, block; 8, 9; 8, 11; 8, 24; 8, 32; 8, 41; 8, 68; 8, 69; 8, 149; 8, 150; 8, 157; 8, 169; 8, 170; 8, 208; 9, expression_statement; 9, 10; 10, string:'''
Collect read attributes across reads in this PileupCollection into a
pandas.DataFrame.
Valid attributes are the following properties of a pysam.AlignedSegment
instance. See:
http://pysam.readthedocs.org/en/latest/api.html#pysam.AlignedSegment
for the meaning of these attributes.
* cigarstring
* flag
* inferred_length
* is_duplicate
* is_paired
* is_proper_pair
* is_qcfail
* is_read1
* is_read2
* is_reverse
* is_secondary
* is_unmapped
* mapping_quality
* mate_is_reverse
* mate_is_unmapped
* next_reference_id
* next_reference_start
* query_alignment_end
* query_alignment_length
* query_alignment_qualities
* query_alignment_sequence
* query_alignment_start
* query_length
* query_name
* reference_end
* reference_id
* reference_length
* reference_start
* template_length
(Note: the above list is parsed into the _READ_ATTRIBUTE_NAMES class
variable, so be careful when modifying it.)
Additionally, for alignment "tags" (arbitrary key values associated
with an alignment), a column of the form "TAG_{tag name}" is
included.
Finally, the column "pysam_alignment_record" gives the underlying
`pysam.AlignedSegment` instances.
Parameters
----------
attributes (optional): list of strings
List of columns to include. If unspecified, all columns are
included in the result.
Returns
----------
pandas.DataFrame of read attributes.
'''; 11, function_definition; 11, 12; 11, 13; 11, 15; 12, function_name:include; 13, parameters; 13, 14; 14, identifier:attribute; 15, block; 15, 16; 16, return_statement; 16, 17; 17, boolean_operator:or; 17, 18; 17, 21; 18, comparison_operator:is; 18, 19; 18, 20; 19, identifier:attributes; 20, None; 21, comparison_operator:in; 21, 22; 21, 23; 22, identifier:attribute; 23, identifier:attributes; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:reads; 27, call; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:self; 30, identifier:reads; 31, argument_list; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:possible_column_names; 35, call; 35, 36; 35, 37; 36, identifier:list; 37, argument_list; 37, 38; 38, attribute; 38, 39; 38, 40; 39, identifier:PileupCollection; 40, identifier:_READ_ATTRIBUTE_NAMES; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:result; 44, call; 44, 45; 44, 46; 45, identifier:OrderedDict; 46, generator_expression; 46, 47; 46, 58; 46, 63; 47, tuple; 47, 48; 47, 49; 48, identifier:name; 49, list_comprehension; 49, 50; 49, 55; 50, call; 50, 51; 50, 52; 51, identifier:getattr; 52, argument_list; 52, 53; 52, 54; 53, identifier:read; 54, identifier:name; 55, for_in_clause; 55, 56; 55, 57; 56, identifier:read; 57, identifier:reads; 58, for_in_clause; 58, 59; 58, 60; 59, identifier:name; 60, attribute; 60, 61; 60, 62; 61, identifier:PileupCollection; 62, identifier:_READ_ATTRIBUTE_NAMES; 63, if_clause; 63, 64; 64, call; 64, 65; 64, 66; 65, identifier:include; 66, argument_list; 66, 67; 67, identifier:name; 68, comment; 69, if_statement; 69, 70; 69, 71; 70, identifier:reads; 71, block; 71, 72; 71, 87; 71, 108; 72, expression_statement; 72, 73; 73, assignment; 73, 74; 73, 75; 74, identifier:tag_dicts; 75, list_comprehension; 75, 76; 75, 84; 76, call; 76, 77; 76, 78; 77, identifier:dict; 78, argument_list; 78, 79; 79, call; 79, 80; 79, 83; 80, attribute; 80, 81; 80, 82; 81, identifier:x; 82, identifier:get_tags; 83, argument_list; 84, for_in_clause; 84, 85; 84, 86; 85, identifier:x; 86, identifier:reads; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:tag_keys; 90, call; 90, 91; 90, 94; 91, attribute; 91, 92; 91, 93; 92, identifier:set; 93, identifier:union; 94, argument_list; 94, 95; 95, list_splat; 95, 96; 96, list_comprehension; 96, 97; 96, 105; 97, call; 97, 98; 97, 99; 98, identifier:set; 99, argument_list; 99, 100; 100, call; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:item; 103, identifier:keys; 104, argument_list; 105, for_in_clause; 105, 106; 105, 107; 106, identifier:item; 107, identifier:tag_dicts; 108, for_statement; 108, 109; 108, 110; 108, 114; 109, identifier:tag_key; 110, call; 110, 111; 110, 112; 111, identifier:sorted; 112, argument_list; 112, 113; 113, identifier:tag_keys; 114, block; 114, 115; 114, 121; 114, 128; 115, expression_statement; 115, 116; 116, assignment; 116, 117; 116, 118; 117, identifier:column_name; 118, binary_operator:%; 118, 119; 118, 120; 119, string:"TAG_%s"; 120, identifier:tag_key; 121, expression_statement; 121, 122; 122, call; 122, 123; 122, 126; 123, attribute; 123, 124; 123, 125; 124, identifier:possible_column_names; 125, identifier:append; 126, argument_list; 126, 127; 127, identifier:column_name; 128, if_statement; 128, 129; 128, 133; 129, call; 129, 130; 129, 131; 130, identifier:include; 131, argument_list; 131, 132; 132, identifier:column_name; 133, block; 133, 134; 134, expression_statement; 134, 135; 135, assignment; 135, 136; 135, 139; 136, subscript; 136, 137; 136, 138; 137, identifier:result; 138, identifier:column_name; 139, list_comprehension; 139, 140; 139, 146; 140, call; 140, 141; 140, 144; 141, attribute; 141, 142; 141, 143; 142, identifier:d; 143, identifier:get; 144, argument_list; 144, 145; 145, identifier:tag_key; 146, for_in_clause; 146, 147; 146, 148; 147, identifier:d; 148, identifier:tag_dicts; 149, comment; 150, expression_statement; 150, 151; 151, call; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:possible_column_names; 154, identifier:append; 155, argument_list; 155, 156; 156, string:"pysam_alignment_record"; 157, if_statement; 157, 158; 157, 162; 158, call; 158, 159; 158, 160; 159, identifier:include; 160, argument_list; 160, 161; 161, string:"pysam_alignment_record"; 162, block; 162, 163; 163, expression_statement; 163, 164; 164, assignment; 164, 165; 164, 168; 165, subscript; 165, 166; 165, 167; 166, identifier:result; 167, string:"pysam_alignment_record"; 168, identifier:reads; 169, comment; 170, if_statement; 170, 171; 170, 174; 171, comparison_operator:is; 171, 172; 171, 173; 172, identifier:attributes; 173, None; 174, block; 174, 175; 174, 198; 175, for_statement; 175, 176; 175, 177; 175, 178; 176, identifier:attribute; 177, identifier:attributes; 178, block; 178, 179; 179, if_statement; 179, 180; 179, 183; 180, comparison_operator:not; 180, 181; 180, 182; 181, identifier:attribute; 182, identifier:result; 183, block; 183, 184; 184, raise_statement; 184, 185; 185, call; 185, 186; 185, 187; 186, identifier:ValueError; 187, argument_list; 187, 188; 188, binary_operator:%; 188, 189; 188, 190; 189, string:"No such attribute: %s. Valid attributes are: %s"; 190, tuple; 190, 191; 190, 192; 191, identifier:attribute; 192, call; 192, 193; 192, 196; 193, attribute; 193, 194; 193, 195; 194, string:" "; 195, identifier:join; 196, argument_list; 196, 197; 197, identifier:possible_column_names; 198, assert_statement; 198, 199; 199, comparison_operator:==; 199, 200; 199, 204; 200, call; 200, 201; 200, 202; 201, identifier:set; 202, argument_list; 202, 203; 203, identifier:attributes; 204, call; 204, 205; 204, 206; 205, identifier:set; 206, argument_list; 206, 207; 207, identifier:result; 208, return_statement; 208, 209; 209, call; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, identifier:pandas; 212, identifier:DataFrame; 213, argument_list; 213, 214; 214, identifier:result | def read_attributes(self, attributes=None):
'''
Collect read attributes across reads in this PileupCollection into a
pandas.DataFrame.
Valid attributes are the following properties of a pysam.AlignedSegment
instance. See:
http://pysam.readthedocs.org/en/latest/api.html#pysam.AlignedSegment
for the meaning of these attributes.
* cigarstring
* flag
* inferred_length
* is_duplicate
* is_paired
* is_proper_pair
* is_qcfail
* is_read1
* is_read2
* is_reverse
* is_secondary
* is_unmapped
* mapping_quality
* mate_is_reverse
* mate_is_unmapped
* next_reference_id
* next_reference_start
* query_alignment_end
* query_alignment_length
* query_alignment_qualities
* query_alignment_sequence
* query_alignment_start
* query_length
* query_name
* reference_end
* reference_id
* reference_length
* reference_start
* template_length
(Note: the above list is parsed into the _READ_ATTRIBUTE_NAMES class
variable, so be careful when modifying it.)
Additionally, for alignment "tags" (arbitrary key values associated
with an alignment), a column of the form "TAG_{tag name}" is
included.
Finally, the column "pysam_alignment_record" gives the underlying
`pysam.AlignedSegment` instances.
Parameters
----------
attributes (optional): list of strings
List of columns to include. If unspecified, all columns are
included in the result.
Returns
----------
pandas.DataFrame of read attributes.
'''
def include(attribute):
return attributes is None or attribute in attributes
reads = self.reads()
possible_column_names = list(PileupCollection._READ_ATTRIBUTE_NAMES)
result = OrderedDict(
(name, [getattr(read, name) for read in reads])
for name in PileupCollection._READ_ATTRIBUTE_NAMES
if include(name))
# Add tag columns.
if reads:
tag_dicts = [dict(x.get_tags()) for x in reads]
tag_keys = set.union(
*[set(item.keys()) for item in tag_dicts])
for tag_key in sorted(tag_keys):
column_name = "TAG_%s" % tag_key
possible_column_names.append(column_name)
if include(column_name):
result[column_name] = [d.get(tag_key) for d in tag_dicts]
# Lastly, we include the underlying pysam alignment record.
possible_column_names.append("pysam_alignment_record")
if include("pysam_alignment_record"):
result["pysam_alignment_record"] = reads
# If particular attributes were requested, check that they're here.
if attributes is not None:
for attribute in attributes:
if attribute not in result:
raise ValueError(
"No such attribute: %s. Valid attributes are: %s"
% (attribute, " ".join(possible_column_names)))
assert set(attributes) == set(result)
return pandas.DataFrame(result) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:group_by_allele; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:locus; 6, block; 6, 7; 6, 9; 6, 16; 6, 20; 6, 24; 6, 172; 6, 188; 6, 264; 6, 265; 6, 266; 6, 288; 7, expression_statement; 7, 8; 8, string:'''
Split the PileupCollection by the alleles suggested by the reads at the
specified locus.
If a read has an insertion immediately following the locus, then the
insertion is included in the allele. For example, if locus is the
1-base range [5,6), one allele might be "AGA", indicating that at
locus 5 some read has an "A" followed by a 2-base insertion ("GA"). If
a read has a deletion at the specified locus, the allele is the empty
string.
The given locus may include any number of bases. If the locus includes
multiple bases, then the alleles consist of all bases aligning to that
range in any read. Note that only sequences actually sequenced in a
particular read are included. For example, if one read has "ATT" at a
locus and another read has "GCC", then the alleles are "ATT" and
"GCC", but not "GTT". That is, the bases in each allele are phased. For
this reason, only reads that overlap the entire locus are included.
If the locus is an empty interval (e.g. [5,5) ), then the alleles
consist only of inserted bases. In this example, only bases inserted
immediately after locus 5 would be included (but *not* the base
actually at locus 5). In the previous insertion example, the allele
would be "GA", indicating a 2-base insertion. Reads that have no
insertion at that position (matches or deletions) would have the empty
string as their allele.
Parameters
----------
locus : Locus
The reference locus, encompassing 0 or more bases.
Returns
----------
A dict of string -> PileupCollection. The keys are nucleotide strings
giving the bases sequenced at the locus, and the values are
PileupCollection instances of the alignments that support that allele.
'''; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:locus; 12, call; 12, 13; 12, 14; 13, identifier:to_locus; 14, argument_list; 14, 15; 15, identifier:locus; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:read_to_allele; 19, None; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:loci; 23, list:[]; 24, if_statement; 24, 25; 24, 28; 24, 29; 24, 115; 25, attribute; 25, 26; 25, 27; 26, identifier:locus; 27, identifier:positions; 28, comment; 29, block; 29, 30; 30, for_statement; 30, 31; 30, 32; 30, 35; 31, identifier:position; 32, attribute; 32, 33; 32, 34; 33, identifier:locus; 34, identifier:positions; 35, block; 35, 36; 35, 48; 35, 55; 35, 59; 35, 111; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:base_position; 39, call; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:Locus; 42, identifier:from_interbase_coordinates; 43, argument_list; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:locus; 46, identifier:contig; 47, identifier:position; 48, expression_statement; 48, 49; 49, call; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:loci; 52, identifier:append; 53, argument_list; 53, 54; 54, identifier:base_position; 55, expression_statement; 55, 56; 56, assignment; 56, 57; 56, 58; 57, identifier:new_read_to_allele; 58, dictionary; 59, for_statement; 59, 60; 59, 61; 59, 66; 60, identifier:element; 61, subscript; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:self; 64, identifier:pileups; 65, identifier:base_position; 66, block; 66, 67; 66, 71; 66, 80; 66, 97; 66, 105; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:allele_prefix; 70, string:""; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:key; 74, call; 74, 75; 74, 76; 75, identifier:alignment_key; 76, argument_list; 76, 77; 77, attribute; 77, 78; 77, 79; 78, identifier:element; 79, identifier:alignment; 80, if_statement; 80, 81; 80, 84; 81, comparison_operator:is; 81, 82; 81, 83; 82, identifier:read_to_allele; 83, None; 84, block; 84, 85; 85, try_statement; 85, 86; 85, 93; 86, block; 86, 87; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:allele_prefix; 90, subscript; 90, 91; 90, 92; 91, identifier:read_to_allele; 92, identifier:key; 93, except_clause; 93, 94; 93, 95; 94, identifier:KeyError; 95, block; 95, 96; 96, continue_statement; 97, expression_statement; 97, 98; 98, assignment; 98, 99; 98, 100; 99, identifier:allele; 100, binary_operator:+; 100, 101; 100, 102; 101, identifier:allele_prefix; 102, attribute; 102, 103; 102, 104; 103, identifier:element; 104, identifier:bases; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 110; 107, subscript; 107, 108; 107, 109; 108, identifier:new_read_to_allele; 109, identifier:key; 110, identifier:allele; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:read_to_allele; 114, identifier:new_read_to_allele; 115, else_clause; 115, 116; 115, 117; 116, comment; 117, block; 117, 118; 117, 132; 117, 139; 117, 143; 118, expression_statement; 118, 119; 119, assignment; 119, 120; 119, 121; 120, identifier:position_before; 121, call; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:Locus; 124, identifier:from_interbase_coordinates; 125, argument_list; 125, 126; 125, 129; 126, attribute; 126, 127; 126, 128; 127, identifier:locus; 128, identifier:contig; 129, attribute; 129, 130; 129, 131; 130, identifier:locus; 131, identifier:start; 132, expression_statement; 132, 133; 133, call; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, identifier:loci; 136, identifier:append; 137, argument_list; 137, 138; 138, identifier:position_before; 139, expression_statement; 139, 140; 140, assignment; 140, 141; 140, 142; 141, identifier:read_to_allele; 142, dictionary; 143, for_statement; 143, 144; 143, 145; 143, 150; 144, identifier:element; 145, subscript; 145, 146; 145, 149; 146, attribute; 146, 147; 146, 148; 147, identifier:self; 148, identifier:pileups; 149, identifier:position_before; 150, block; 150, 151; 150, 161; 151, expression_statement; 151, 152; 152, assignment; 152, 153; 152, 154; 153, identifier:allele; 154, subscript; 154, 155; 154, 158; 155, attribute; 155, 156; 155, 157; 156, identifier:element; 157, identifier:bases; 158, slice; 158, 159; 158, 160; 159, integer:1; 160, colon; 161, expression_statement; 161, 162; 162, assignment; 162, 163; 162, 171; 163, subscript; 163, 164; 163, 165; 164, identifier:read_to_allele; 165, call; 165, 166; 165, 167; 166, identifier:alignment_key; 167, argument_list; 167, 168; 168, attribute; 168, 169; 168, 170; 169, identifier:element; 170, identifier:alignment; 171, identifier:allele; 172, expression_statement; 172, 173; 173, assignment; 173, 174; 173, 175; 174, identifier:split; 175, call; 175, 176; 175, 177; 176, identifier:defaultdict; 177, argument_list; 177, 178; 178, lambda; 178, 179; 179, call; 179, 180; 179, 181; 180, identifier:PileupCollection; 181, argument_list; 181, 182; 181, 185; 182, keyword_argument; 182, 183; 182, 184; 183, identifier:pileups; 184, dictionary; 185, keyword_argument; 185, 186; 185, 187; 186, identifier:parent; 187, identifier:self; 188, for_statement; 188, 189; 188, 190; 188, 191; 189, identifier:locus; 190, identifier:loci; 191, block; 191, 192; 191, 200; 192, expression_statement; 192, 193; 193, assignment; 193, 194; 193, 195; 194, identifier:pileup; 195, subscript; 195, 196; 195, 199; 196, attribute; 196, 197; 196, 198; 197, identifier:self; 198, identifier:pileups; 199, identifier:locus; 200, for_statement; 200, 201; 200, 202; 200, 205; 201, identifier:e; 202, attribute; 202, 203; 202, 204; 203, identifier:pileup; 204, identifier:elements; 205, block; 205, 206; 205, 220; 206, expression_statement; 206, 207; 207, assignment; 207, 208; 207, 209; 208, identifier:key; 209, call; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, identifier:read_to_allele; 212, identifier:get; 213, argument_list; 213, 214; 214, call; 214, 215; 214, 216; 215, identifier:alignment_key; 216, argument_list; 216, 217; 217, attribute; 217, 218; 217, 219; 218, identifier:e; 219, identifier:alignment; 220, if_statement; 220, 221; 220, 224; 221, comparison_operator:is; 221, 222; 221, 223; 222, identifier:key; 223, None; 224, block; 224, 225; 225, if_statement; 225, 226; 225, 233; 225, 247; 226, comparison_operator:in; 226, 227; 226, 228; 227, identifier:locus; 228, attribute; 228, 229; 228, 232; 229, subscript; 229, 230; 229, 231; 230, identifier:split; 231, identifier:key; 232, identifier:pileups; 233, block; 233, 234; 234, expression_statement; 234, 235; 235, call; 235, 236; 235, 245; 236, attribute; 236, 237; 236, 244; 237, subscript; 237, 238; 237, 243; 238, attribute; 238, 239; 238, 242; 239, subscript; 239, 240; 239, 241; 240, identifier:split; 241, identifier:key; 242, identifier:pileups; 243, identifier:locus; 244, identifier:append; 245, argument_list; 245, 246; 246, identifier:e; 247, else_clause; 247, 248; 248, block; 248, 249; 249, expression_statement; 249, 250; 250, assignment; 250, 251; 250, 258; 251, subscript; 251, 252; 251, 257; 252, attribute; 252, 253; 252, 256; 253, subscript; 253, 254; 253, 255; 254, identifier:split; 255, identifier:key; 256, identifier:pileups; 257, identifier:locus; 258, call; 258, 259; 258, 260; 259, identifier:Pileup; 260, argument_list; 260, 261; 260, 262; 261, identifier:locus; 262, list:[e]; 262, 263; 263, identifier:e; 264, comment; 265, comment; 266, function_definition; 266, 267; 266, 268; 266, 270; 267, function_name:sorter; 268, parameters; 268, 269; 269, identifier:pair; 270, block; 270, 271; 270, 277; 271, expression_statement; 271, 272; 272, assignment; 272, 273; 272, 276; 273, tuple_pattern; 273, 274; 273, 275; 274, identifier:allele; 275, identifier:pileup_collection; 276, identifier:pair; 277, return_statement; 277, 278; 278, tuple; 278, 279; 278, 287; 279, binary_operator:*; 279, 280; 279, 282; 280, unary_operator:-; 280, 281; 281, integer:1; 282, call; 282, 283; 282, 286; 283, attribute; 283, 284; 283, 285; 284, identifier:pileup_collection; 285, identifier:num_reads; 286, argument_list; 287, identifier:allele; 288, return_statement; 288, 289; 289, call; 289, 290; 289, 291; 290, identifier:OrderedDict; 291, argument_list; 291, 292; 292, call; 292, 293; 292, 294; 293, identifier:sorted; 294, argument_list; 294, 295; 294, 300; 295, call; 295, 296; 295, 299; 296, attribute; 296, 297; 296, 298; 297, identifier:split; 298, identifier:items; 299, argument_list; 300, keyword_argument; 300, 301; 300, 302; 301, identifier:key; 302, identifier:sorter | def group_by_allele(self, locus):
'''
Split the PileupCollection by the alleles suggested by the reads at the
specified locus.
If a read has an insertion immediately following the locus, then the
insertion is included in the allele. For example, if locus is the
1-base range [5,6), one allele might be "AGA", indicating that at
locus 5 some read has an "A" followed by a 2-base insertion ("GA"). If
a read has a deletion at the specified locus, the allele is the empty
string.
The given locus may include any number of bases. If the locus includes
multiple bases, then the alleles consist of all bases aligning to that
range in any read. Note that only sequences actually sequenced in a
particular read are included. For example, if one read has "ATT" at a
locus and another read has "GCC", then the alleles are "ATT" and
"GCC", but not "GTT". That is, the bases in each allele are phased. For
this reason, only reads that overlap the entire locus are included.
If the locus is an empty interval (e.g. [5,5) ), then the alleles
consist only of inserted bases. In this example, only bases inserted
immediately after locus 5 would be included (but *not* the base
actually at locus 5). In the previous insertion example, the allele
would be "GA", indicating a 2-base insertion. Reads that have no
insertion at that position (matches or deletions) would have the empty
string as their allele.
Parameters
----------
locus : Locus
The reference locus, encompassing 0 or more bases.
Returns
----------
A dict of string -> PileupCollection. The keys are nucleotide strings
giving the bases sequenced at the locus, and the values are
PileupCollection instances of the alignments that support that allele.
'''
locus = to_locus(locus)
read_to_allele = None
loci = []
if locus.positions:
# Our locus includes at least one reference base.
for position in locus.positions:
base_position = Locus.from_interbase_coordinates(
locus.contig, position)
loci.append(base_position)
new_read_to_allele = {}
for element in self.pileups[base_position]:
allele_prefix = ""
key = alignment_key(element.alignment)
if read_to_allele is not None:
try:
allele_prefix = read_to_allele[key]
except KeyError:
continue
allele = allele_prefix + element.bases
new_read_to_allele[key] = allele
read_to_allele = new_read_to_allele
else:
# Our locus is between reference bases.
position_before = Locus.from_interbase_coordinates(
locus.contig, locus.start)
loci.append(position_before)
read_to_allele = {}
for element in self.pileups[position_before]:
allele = element.bases[1:]
read_to_allele[alignment_key(element.alignment)] = allele
split = defaultdict(lambda: PileupCollection(pileups={}, parent=self))
for locus in loci:
pileup = self.pileups[locus]
for e in pileup.elements:
key = read_to_allele.get(alignment_key(e.alignment))
if key is not None:
if locus in split[key].pileups:
split[key].pileups[locus].append(e)
else:
split[key].pileups[locus] = Pileup(locus, [e])
# Sort by number of reads (descending). Break ties with the
# lexicographic ordering of the allele string.
def sorter(pair):
(allele, pileup_collection) = pair
return (-1 * pileup_collection.num_reads(), allele)
return OrderedDict(sorted(split.items(), key=sorter)) |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:from_bam; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:pysam_samfile; 5, identifier:loci; 6, default_parameter; 6, 7; 6, 8; 7, identifier:normalized_contig_names; 8, True; 9, block; 9, 10; 9, 12; 9, 23; 9, 27; 9, 46; 10, expression_statement; 10, 11; 11, string:'''
Create a PileupCollection for a set of loci from a BAM file.
Parameters
----------
pysam_samfile : `pysam.Samfile` instance, or filename string
to a BAM file. The BAM file must be indexed.
loci : list of Locus instances
Loci to collect pileups for.
normalized_contig_names : whether the contig names have been normalized
(e.g. pyensembl removes the 'chr' prefix). Set to true to
de-normalize the names when querying the BAM file.
Returns
----------
PileupCollection instance containing pileups for the specified loci.
All alignments in the BAM file are included (e.g. duplicate reads,
secondary alignments, etc.). See `PileupCollection.filter` if these
need to be removed.
'''; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:loci; 15, list_comprehension; 15, 16; 15, 20; 16, call; 16, 17; 16, 18; 17, identifier:to_locus; 18, argument_list; 18, 19; 19, identifier:obj; 20, for_in_clause; 20, 21; 20, 22; 21, identifier:obj; 22, identifier:loci; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:close_on_completion; 26, False; 27, if_statement; 27, 28; 27, 34; 28, call; 28, 29; 28, 32; 29, attribute; 29, 30; 29, 31; 30, identifier:typechecks; 31, identifier:is_string; 32, argument_list; 32, 33; 33, identifier:pysam_samfile; 34, block; 34, 35; 34, 42; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:pysam_samfile; 38, call; 38, 39; 38, 40; 39, identifier:Samfile; 40, argument_list; 40, 41; 41, identifier:pysam_samfile; 42, expression_statement; 42, 43; 43, assignment; 43, 44; 43, 45; 44, identifier:close_on_completion; 45, True; 46, try_statement; 46, 47; 46, 48; 46, 49; 46, 270; 47, comment; 48, comment; 49, block; 49, 50; 49, 92; 49, 99; 49, 100; 49, 131; 49, 268; 50, if_statement; 50, 51; 50, 52; 50, 86; 51, identifier:normalized_contig_names; 52, block; 52, 53; 52, 57; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:chromosome_name_map; 56, dictionary; 57, for_statement; 57, 58; 57, 59; 57, 62; 58, identifier:name; 59, attribute; 59, 60; 59, 61; 60, identifier:pysam_samfile; 61, identifier:references; 62, block; 62, 63; 62, 74; 62, 80; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:normalized; 66, call; 66, 67; 66, 72; 67, attribute; 67, 68; 67, 71; 68, attribute; 68, 69; 68, 70; 69, identifier:pyensembl; 70, identifier:locus; 71, identifier:normalize_chromosome; 72, argument_list; 72, 73; 73, identifier:name; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 79; 76, subscript; 76, 77; 76, 78; 77, identifier:chromosome_name_map; 78, identifier:normalized; 79, identifier:name; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 85; 82, subscript; 82, 83; 82, 84; 83, identifier:chromosome_name_map; 84, identifier:name; 85, identifier:name; 86, else_clause; 86, 87; 87, block; 87, 88; 88, expression_statement; 88, 89; 89, assignment; 89, 90; 89, 91; 90, identifier:chromosome_name_map; 91, None; 92, expression_statement; 92, 93; 93, assignment; 93, 94; 93, 95; 94, identifier:result; 95, call; 95, 96; 95, 97; 96, identifier:PileupCollection; 97, argument_list; 97, 98; 98, dictionary; 99, comment; 100, expression_statement; 100, 101; 101, assignment; 101, 102; 101, 103; 102, identifier:locus_iterator; 103, call; 103, 104; 103, 109; 104, attribute; 104, 105; 104, 108; 105, attribute; 105, 106; 105, 107; 106, identifier:itertools; 107, identifier:chain; 108, identifier:from_iterable; 109, generator_expression; 109, 110; 109, 125; 110, generator_expression; 110, 111; 110, 120; 111, call; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:Locus; 114, identifier:from_interbase_coordinates; 115, argument_list; 115, 116; 115, 119; 116, attribute; 116, 117; 116, 118; 117, identifier:locus_interval; 118, identifier:contig; 119, identifier:pos; 120, for_in_clause; 120, 121; 120, 122; 121, identifier:pos; 122, attribute; 122, 123; 122, 124; 123, identifier:locus_interval; 124, identifier:positions; 125, for_in_clause; 125, 126; 125, 127; 126, identifier:locus_interval; 127, call; 127, 128; 127, 129; 128, identifier:sorted; 129, argument_list; 129, 130; 130, identifier:loci; 131, for_statement; 131, 132; 131, 133; 131, 134; 132, identifier:locus; 133, identifier:locus_iterator; 134, block; 134, 135; 134, 147; 134, 183; 134, 207; 134, 221; 134, 222; 134, 223; 134, 229; 134, 236; 134, 237; 135, expression_statement; 135, 136; 136, assignment; 136, 137; 136, 142; 137, subscript; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:result; 140, identifier:pileups; 141, identifier:locus; 142, call; 142, 143; 142, 144; 143, identifier:Pileup; 144, argument_list; 144, 145; 144, 146; 145, identifier:locus; 146, list:[]; 147, if_statement; 147, 148; 147, 149; 147, 175; 148, identifier:normalized_contig_names; 149, block; 149, 150; 150, try_statement; 150, 151; 150, 160; 151, block; 151, 152; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:chromosome; 155, subscript; 155, 156; 155, 157; 156, identifier:chromosome_name_map; 157, attribute; 157, 158; 157, 159; 158, identifier:locus; 159, identifier:contig; 160, except_clause; 160, 161; 160, 162; 161, identifier:KeyError; 162, block; 162, 163; 162, 174; 163, expression_statement; 163, 164; 164, call; 164, 165; 164, 168; 165, attribute; 165, 166; 165, 167; 166, identifier:logging; 167, identifier:warn; 168, argument_list; 168, 169; 169, binary_operator:%; 169, 170; 169, 171; 170, string:"No such contig in bam: %s"; 171, attribute; 171, 172; 171, 173; 172, identifier:locus; 173, identifier:contig; 174, continue_statement; 175, else_clause; 175, 176; 176, block; 176, 177; 177, expression_statement; 177, 178; 178, assignment; 178, 179; 178, 180; 179, identifier:chromosome; 180, attribute; 180, 181; 180, 182; 181, identifier:locus; 182, identifier:contig; 183, expression_statement; 183, 184; 184, assignment; 184, 185; 184, 186; 185, identifier:columns; 186, call; 186, 187; 186, 190; 187, attribute; 187, 188; 187, 189; 188, identifier:pysam_samfile; 189, identifier:pileup; 190, argument_list; 190, 191; 190, 192; 190, 195; 190, 200; 190, 201; 190, 204; 191, identifier:chromosome; 192, attribute; 192, 193; 192, 194; 193, identifier:locus; 194, identifier:position; 195, binary_operator:+; 195, 196; 195, 199; 196, attribute; 196, 197; 196, 198; 197, identifier:locus; 198, identifier:position; 199, integer:1; 200, comment; 201, keyword_argument; 201, 202; 201, 203; 202, identifier:truncate; 203, True; 204, keyword_argument; 204, 205; 204, 206; 205, identifier:stepper; 206, string:"nofilter"; 207, try_statement; 207, 208; 207, 216; 208, block; 208, 209; 209, expression_statement; 209, 210; 210, assignment; 210, 211; 210, 212; 211, identifier:column; 212, call; 212, 213; 212, 214; 213, identifier:next; 214, argument_list; 214, 215; 215, identifier:columns; 216, except_clause; 216, 217; 216, 218; 216, 219; 217, identifier:StopIteration; 218, comment; 219, block; 219, 220; 220, continue_statement; 221, comment; 222, comment; 223, expression_statement; 223, 224; 224, assignment; 224, 225; 224, 226; 225, identifier:pileups; 226, attribute; 226, 227; 226, 228; 227, identifier:column; 228, identifier:pileups; 229, assert_statement; 229, 230; 230, comparison_operator:==; 230, 231; 230, 235; 231, call; 231, 232; 231, 233; 232, identifier:list; 233, argument_list; 233, 234; 234, identifier:columns; 235, list:[]; 236, comment; 237, for_statement; 237, 238; 237, 239; 237, 240; 238, identifier:pileup_read; 239, identifier:pileups; 240, block; 240, 241; 241, if_statement; 241, 242; 241, 246; 242, not_operator; 242, 243; 243, attribute; 243, 244; 243, 245; 244, identifier:pileup_read; 245, identifier:is_refskip; 246, block; 246, 247; 246, 257; 247, expression_statement; 247, 248; 248, assignment; 248, 249; 248, 250; 249, identifier:element; 250, call; 250, 251; 250, 254; 251, attribute; 251, 252; 251, 253; 252, identifier:PileupElement; 253, identifier:from_pysam_alignment; 254, argument_list; 254, 255; 254, 256; 255, identifier:locus; 256, identifier:pileup_read; 257, expression_statement; 257, 258; 258, call; 258, 259; 258, 266; 259, attribute; 259, 260; 259, 265; 260, subscript; 260, 261; 260, 264; 261, attribute; 261, 262; 261, 263; 262, identifier:result; 263, identifier:pileups; 264, identifier:locus; 265, identifier:append; 266, argument_list; 266, 267; 267, identifier:element; 268, return_statement; 268, 269; 269, identifier:result; 270, finally_clause; 270, 271; 271, block; 271, 272; 272, if_statement; 272, 273; 272, 274; 273, identifier:close_on_completion; 274, block; 274, 275; 275, expression_statement; 275, 276; 276, call; 276, 277; 276, 280; 277, attribute; 277, 278; 277, 279; 278, identifier:pysam_samfile; 279, identifier:close; 280, argument_list | def from_bam(pysam_samfile, loci, normalized_contig_names=True):
'''
Create a PileupCollection for a set of loci from a BAM file.
Parameters
----------
pysam_samfile : `pysam.Samfile` instance, or filename string
to a BAM file. The BAM file must be indexed.
loci : list of Locus instances
Loci to collect pileups for.
normalized_contig_names : whether the contig names have been normalized
(e.g. pyensembl removes the 'chr' prefix). Set to true to
de-normalize the names when querying the BAM file.
Returns
----------
PileupCollection instance containing pileups for the specified loci.
All alignments in the BAM file are included (e.g. duplicate reads,
secondary alignments, etc.). See `PileupCollection.filter` if these
need to be removed.
'''
loci = [to_locus(obj) for obj in loci]
close_on_completion = False
if typechecks.is_string(pysam_samfile):
pysam_samfile = Samfile(pysam_samfile)
close_on_completion = True
try:
# Map from pyensembl normalized chromosome names used in Variant to
# the names used in the BAM file.
if normalized_contig_names:
chromosome_name_map = {}
for name in pysam_samfile.references:
normalized = pyensembl.locus.normalize_chromosome(name)
chromosome_name_map[normalized] = name
chromosome_name_map[name] = name
else:
chromosome_name_map = None
result = PileupCollection({})
# Optimization: we sort variants so our BAM reads are localized.
locus_iterator = itertools.chain.from_iterable(
(Locus.from_interbase_coordinates(locus_interval.contig, pos)
for pos
in locus_interval.positions)
for locus_interval in sorted(loci))
for locus in locus_iterator:
result.pileups[locus] = Pileup(locus, [])
if normalized_contig_names:
try:
chromosome = chromosome_name_map[locus.contig]
except KeyError:
logging.warn("No such contig in bam: %s" % locus.contig)
continue
else:
chromosome = locus.contig
columns = pysam_samfile.pileup(
chromosome,
locus.position,
locus.position + 1, # exclusive, 0-indexed
truncate=True,
stepper="nofilter")
try:
column = next(columns)
except StopIteration:
# No reads align to this locus.
continue
# Note that storing the pileups here is necessary, since the
# subsequent assertion will invalidate our column.
pileups = column.pileups
assert list(columns) == [] # column is invalid after this.
for pileup_read in pileups:
if not pileup_read.is_refskip:
element = PileupElement.from_pysam_alignment(
locus, pileup_read)
result.pileups[locus].append(element)
return result
finally:
if close_on_completion:
pysam_samfile.close() |
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:check_recommended_global_attributes; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:dataset; 6, block; 6, 7; 6, 9; 6, 19; 6, 35; 6, 44; 6, 54; 6, 66; 6, 89; 6, 90; 6, 140; 6, 149; 6, 170; 6, 171; 6, 191; 6, 199; 6, 208; 6, 217; 6, 235; 6, 257; 7, expression_statement; 7, 8; 8, string:'''
Check the global recommended attributes for 2.0 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
:id = "" ; //.................................................. RECOMMENDED - Should be a human readable unique identifier for data set. (ACDD)
:naming_authority = "" ; //.................................... RECOMMENDED - Backward URL of institution (for example, gov.noaa.ncei). (ACDD)
:history = "" ; //............................................. RECOMMENDED - Provides an audit trail for modifications to the original data. (ACDD)
:source = "" ; //.............................................. RECOMMENDED - The method of production of the original data. (CF)
:processing_level = "" ; //.................................... RECOMMENDED - Provide a description of the processing or quality control level of the data. (ACDD)
:comment = "" ; //............................................. RECOMMENDED - Provide useful additional information here. (CF)
:acknowledgment = "" ; //...................................... RECOMMENDED - A place to acknowledge various types of support for the project that produced this data. (ACDD)
:license = "" ; //............................................. RECOMMENDED - Describe the restrictions to data access and distribution. (ACDD)
:standard_name_vocabulary = "CF Standard Name Table vNN" ; //.. RECOMMENDED - If using CF standard name attribute for variables. Replace NN with the CF standard name table number (CF)
:date_created = "" ; //........................................ RECOMMENDED - Creation date of this version of the data(netCDF). Use ISO 8601:2004 for date and time. (ACDD)
:creator_name = "" ; //........................................ RECOMMENDED - The name of the person (or other creator type specified by the creator_type attribute) principally responsible for creating this data. (ACDD)
:creator_email = "" ; //....................................... RECOMMENDED - The email address of the person (or other creator type specified by the creator_type attribute) principally responsible for creating this data. (ACDD)
:creator_url = "" ; //......................................... RECOMMENDED - The URL of the person (or other creator type specified by the creator_type attribute) principally responsible for creating this data. (ACDD)
:institution = "" ; //......................................... RECOMMENDED -The name of the institution principally responsible for originating this data.. An institution attribute can be used for each variable if variables come from more than one institution. (CF/ACDD)
:project = "" ; //............................................. RECOMMENDED - The name of the project(s) principally responsible for originating this data. Multiple projects can be separated by commas. (ACDD)
:publisher_name = "" ; //...................................... RECOMMENDED - The name of the person (or other entity specified by the publisher_type attribute) responsible for publishing the data file or product to users, with its current metadata and format. (ACDD)
:publisher_email = "" ; //..................................... RECOMMENDED - The email address of the person (or other entity specified by the publisher_type attribute) responsible for publishing the data file or product to users, with its current metadata and format. (ACDD)
:publisher_url = "" ; //....................................... RECOMMENDED - The URL of the person (or other entity specified by the publisher_type attribute) responsible for publishing the data file or product to users, with its current metadata and format. (ACDD)
:geospatial_bounds = "" ; //................................... RECOMMENDED - Describes the data's 2D or 3D geospatial extent in OGC's Well-Known Text (WKT) Geometry format. (ACDD)
:geospatial_bounds_crs = "" ; //............................... RECOMMENDED - The coordinate reference system (CRS) of the point coordinates in the geospatial_bounds attribute. (ACDD)
:geospatial_bounds_vertical_crs = "" ; //...................... RECOMMENDED - The vertical coordinate reference system (CRS) for the Z axis of the point coordinates in the geospatial_bounds attribute. (ACDD)
:geospatial_lat_min = 0.0d ; //................................ RECOMMENDED - Describes a simple lower latitude limit. (ACDD)
:geospatial_lat_max = 0.0d ; //................................ RECOMMENDED - Describes a simple upper latitude limit. (ACDD)
:geospatial_lon_min = 0.0d ; //................................ RECOMMENDED - Describes a simple lower longitude limit. (ACDD)
:geospatial_lon_max = 0.0d ; //................................ RECOMMENDED - Describes a simple upper longitude limit. (ACDD)
:geospatial_vertical_min = 0.0d ; //........................... RECOMMENDED - Describes the numerically smaller vertical limit. (ACDD)
:geospatial_vertical_max = 0.0d ; //........................... RECOMMENDED - Describes the numerically larger vertical limit. (ACDD)
:geospatial_vertical_positive = "" ; //........................ RECOMMENDED - Use "up" or "down". (ACDD)
:time_coverage_start = "" ; //................................. RECOMMENDED - Describes the time of the first data point in the data set. Use ISO 8601:2004 for date and time. (ACDD)
:time_coverage_end = "" ; //................................... RECOMMENDED - Describes the time of the last data point in the data set. Use ISO 8601:2004 for date and time.(ACDD)
:time_coverage_duration = "" ; //.............................. RECOMMENDED - Describes the duration of the data set. Use ISO 8601:2004 for date and time. (ACDD)
:time_coverage_resolution = "" ; //............................ RECOMMENDED - Describes the targeted time period between each value in the data set. Use ISO 8601:2004 for date and time. (ACDD)
:uuid = "" ; //................................................ RECOMMENDED - Machine readable unique identifier for each file. A new uuid is created whenever the file is changed. (NCEI)
:sea_name = "" ; //............................................ RECOMMENDED - The names of the sea in which the data were collected. Use NCEI sea names table. (NCEI)
'''; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:recommended_ctx; 12, call; 12, 13; 12, 14; 13, identifier:TestCtx; 14, argument_list; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:BaseCheck; 17, identifier:MEDIUM; 18, string:'Recommended global attributes'; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:sea_names; 22, list_comprehension; 22, 23; 22, 28; 23, call; 23, 24; 23, 27; 24, attribute; 24, 25; 24, 26; 25, identifier:sn; 26, identifier:lower; 27, argument_list; 28, for_in_clause; 28, 29; 28, 30; 29, identifier:sn; 30, call; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:util; 33, identifier:get_sea_names; 34, argument_list; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:sea_name; 38, call; 38, 39; 38, 40; 39, identifier:getattr; 40, argument_list; 40, 41; 40, 42; 40, 43; 41, identifier:dataset; 42, string:'sea_name'; 43, string:''; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:sea_name; 47, call; 47, 48; 47, 51; 48, attribute; 48, 49; 48, 50; 49, identifier:sea_name; 50, identifier:replace; 51, argument_list; 51, 52; 51, 53; 52, string:', '; 53, string:','; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 57; 56, identifier:sea_name; 57, conditional_expression:if; 57, 58; 57, 64; 57, 65; 58, call; 58, 59; 58, 62; 59, attribute; 59, 60; 59, 61; 60, identifier:sea_name; 61, identifier:split; 62, argument_list; 62, 63; 63, string:','; 64, identifier:sea_name; 65, list:[]; 66, for_statement; 66, 67; 66, 68; 66, 69; 67, identifier:sea; 68, identifier:sea_name; 69, block; 69, 70; 70, expression_statement; 70, 71; 71, call; 71, 72; 71, 75; 72, attribute; 72, 73; 72, 74; 73, identifier:recommended_ctx; 74, identifier:assert_true; 75, argument_list; 75, 76; 75, 83; 76, comparison_operator:in; 76, 77; 76, 82; 77, call; 77, 78; 77, 81; 78, attribute; 78, 79; 78, 80; 79, identifier:sea; 80, identifier:lower; 81, argument_list; 82, identifier:sea_names; 83, call; 83, 84; 83, 87; 84, attribute; 84, 85; 84, 86; 85, string:'sea_name attribute should exist and should be from the NODC sea names list: {} is not a valid sea name'; 86, identifier:format; 87, argument_list; 87, 88; 88, identifier:sea; 89, comment; 90, for_statement; 90, 91; 90, 92; 90, 97; 91, identifier:attr; 92, list:['time_coverage_start', 'time_coverage_end', 'date_created', 'date_modified']; 92, 93; 92, 94; 92, 95; 92, 96; 93, string:'time_coverage_start'; 94, string:'time_coverage_end'; 95, string:'date_created'; 96, string:'date_modified'; 97, block; 97, 98; 97, 107; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:attr_value; 101, call; 101, 102; 101, 103; 102, identifier:getattr; 103, argument_list; 103, 104; 103, 105; 103, 106; 104, identifier:dataset; 105, identifier:attr; 106, string:''; 107, try_statement; 107, 108; 107, 123; 108, block; 108, 109; 108, 114; 108, 122; 109, expression_statement; 109, 110; 110, call; 110, 111; 110, 112; 111, identifier:parse_datetime; 112, argument_list; 112, 113; 113, identifier:attr_value; 114, expression_statement; 114, 115; 115, call; 115, 116; 115, 119; 116, attribute; 116, 117; 116, 118; 117, identifier:recommended_ctx; 118, identifier:assert_true; 119, argument_list; 119, 120; 119, 121; 120, True; 121, string:''; 122, comment; 123, except_clause; 123, 124; 123, 125; 124, identifier:ISO8601Error; 125, block; 125, 126; 126, expression_statement; 126, 127; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:recommended_ctx; 130, identifier:assert_true; 131, argument_list; 131, 132; 131, 133; 132, False; 133, call; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, string:'{} should exist and be ISO-8601 format (example: PT1M30S), currently: {}'; 136, identifier:format; 137, argument_list; 137, 138; 137, 139; 138, identifier:attr; 139, identifier:attr_value; 140, expression_statement; 140, 141; 141, assignment; 141, 142; 141, 143; 142, identifier:value; 143, call; 143, 144; 143, 145; 144, identifier:getattr; 145, argument_list; 145, 146; 145, 147; 145, 148; 146, identifier:dataset; 147, string:'geospatial_vertical_positive'; 148, string:''; 149, expression_statement; 149, 150; 150, call; 150, 151; 150, 154; 151, attribute; 151, 152; 151, 153; 152, identifier:recommended_ctx; 153, identifier:assert_true; 154, argument_list; 154, 155; 154, 164; 155, comparison_operator:in; 155, 156; 155, 161; 156, call; 156, 157; 156, 160; 157, attribute; 157, 158; 157, 159; 158, identifier:value; 159, identifier:lower; 160, argument_list; 161, list:['up', 'down']; 161, 162; 161, 163; 162, string:'up'; 163, string:'down'; 164, call; 164, 165; 164, 168; 165, attribute; 165, 166; 165, 167; 166, string:'geospatial_vertical_positive attribute should be up or down: {}'; 167, identifier:format; 168, argument_list; 168, 169; 169, identifier:value; 170, comment; 171, expression_statement; 171, 172; 172, assignment; 172, 173; 172, 174; 173, identifier:ack_exists; 174, call; 174, 175; 174, 176; 175, identifier:any; 176, argument_list; 176, 177; 177, generator_expression; 177, 178; 177, 186; 178, comparison_operator:!=; 178, 179; 178, 185; 179, call; 179, 180; 179, 181; 180, identifier:getattr; 181, argument_list; 181, 182; 181, 183; 181, 184; 182, identifier:dataset; 183, identifier:attr; 184, string:''; 185, string:''; 186, for_in_clause; 186, 187; 186, 188; 187, identifier:attr; 188, list:['acknowledgment', 'acknowledgement']; 188, 189; 188, 190; 189, string:'acknowledgment'; 190, string:'acknowledgement'; 191, expression_statement; 191, 192; 192, call; 192, 193; 192, 196; 193, attribute; 193, 194; 193, 195; 194, identifier:recommended_ctx; 195, identifier:assert_true; 196, argument_list; 196, 197; 196, 198; 197, identifier:ack_exists; 198, string:'acknowledgement attribute should exist and not be empty'; 199, expression_statement; 199, 200; 200, assignment; 200, 201; 200, 202; 201, identifier:standard_name_vocab; 202, call; 202, 203; 202, 204; 203, identifier:getattr; 204, argument_list; 204, 205; 204, 206; 204, 207; 205, identifier:dataset; 206, string:'standard_name_vocabulary'; 207, string:''; 208, expression_statement; 208, 209; 209, assignment; 209, 210; 209, 211; 210, identifier:regex; 211, call; 211, 212; 211, 215; 212, attribute; 212, 213; 212, 214; 213, identifier:re; 214, identifier:compile; 215, argument_list; 215, 216; 216, string:r'[sS]tandard [nN]ame [tT]able'; 217, expression_statement; 217, 218; 218, call; 218, 219; 218, 222; 219, attribute; 219, 220; 219, 221; 220, identifier:recommended_ctx; 221, identifier:assert_true; 222, argument_list; 222, 223; 222, 229; 223, call; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:regex; 226, identifier:search; 227, argument_list; 227, 228; 228, identifier:standard_name_vocab; 229, call; 229, 230; 229, 233; 230, attribute; 230, 231; 230, 232; 231, string:"standard_name_vocabulary doesn't contain 'Standard Name Table': {}"; 232, identifier:format; 233, argument_list; 233, 234; 234, identifier:standard_name_vocab; 235, if_statement; 235, 236; 235, 241; 236, call; 236, 237; 236, 238; 237, identifier:hasattr; 238, argument_list; 238, 239; 238, 240; 239, identifier:dataset; 240, string:'comment'; 241, block; 241, 242; 242, expression_statement; 242, 243; 243, call; 243, 244; 243, 247; 244, attribute; 244, 245; 244, 246; 245, identifier:recommended_ctx; 246, identifier:assert_true; 247, argument_list; 247, 248; 247, 256; 248, comparison_operator:!=; 248, 249; 248, 255; 249, call; 249, 250; 249, 251; 250, identifier:getattr; 251, argument_list; 251, 252; 251, 253; 251, 254; 252, identifier:dataset; 253, string:'comment'; 254, string:''; 255, string:''; 256, string:'comment attribute should not be empty if specified'; 257, return_statement; 257, 258; 258, call; 258, 259; 258, 262; 259, attribute; 259, 260; 259, 261; 260, identifier:recommended_ctx; 261, identifier:to_result; 262, argument_list | def check_recommended_global_attributes(self, dataset):
'''
Check the global recommended attributes for 2.0 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
:id = "" ; //.................................................. RECOMMENDED - Should be a human readable unique identifier for data set. (ACDD)
:naming_authority = "" ; //.................................... RECOMMENDED - Backward URL of institution (for example, gov.noaa.ncei). (ACDD)
:history = "" ; //............................................. RECOMMENDED - Provides an audit trail for modifications to the original data. (ACDD)
:source = "" ; //.............................................. RECOMMENDED - The method of production of the original data. (CF)
:processing_level = "" ; //.................................... RECOMMENDED - Provide a description of the processing or quality control level of the data. (ACDD)
:comment = "" ; //............................................. RECOMMENDED - Provide useful additional information here. (CF)
:acknowledgment = "" ; //...................................... RECOMMENDED - A place to acknowledge various types of support for the project that produced this data. (ACDD)
:license = "" ; //............................................. RECOMMENDED - Describe the restrictions to data access and distribution. (ACDD)
:standard_name_vocabulary = "CF Standard Name Table vNN" ; //.. RECOMMENDED - If using CF standard name attribute for variables. Replace NN with the CF standard name table number (CF)
:date_created = "" ; //........................................ RECOMMENDED - Creation date of this version of the data(netCDF). Use ISO 8601:2004 for date and time. (ACDD)
:creator_name = "" ; //........................................ RECOMMENDED - The name of the person (or other creator type specified by the creator_type attribute) principally responsible for creating this data. (ACDD)
:creator_email = "" ; //....................................... RECOMMENDED - The email address of the person (or other creator type specified by the creator_type attribute) principally responsible for creating this data. (ACDD)
:creator_url = "" ; //......................................... RECOMMENDED - The URL of the person (or other creator type specified by the creator_type attribute) principally responsible for creating this data. (ACDD)
:institution = "" ; //......................................... RECOMMENDED -The name of the institution principally responsible for originating this data.. An institution attribute can be used for each variable if variables come from more than one institution. (CF/ACDD)
:project = "" ; //............................................. RECOMMENDED - The name of the project(s) principally responsible for originating this data. Multiple projects can be separated by commas. (ACDD)
:publisher_name = "" ; //...................................... RECOMMENDED - The name of the person (or other entity specified by the publisher_type attribute) responsible for publishing the data file or product to users, with its current metadata and format. (ACDD)
:publisher_email = "" ; //..................................... RECOMMENDED - The email address of the person (or other entity specified by the publisher_type attribute) responsible for publishing the data file or product to users, with its current metadata and format. (ACDD)
:publisher_url = "" ; //....................................... RECOMMENDED - The URL of the person (or other entity specified by the publisher_type attribute) responsible for publishing the data file or product to users, with its current metadata and format. (ACDD)
:geospatial_bounds = "" ; //................................... RECOMMENDED - Describes the data's 2D or 3D geospatial extent in OGC's Well-Known Text (WKT) Geometry format. (ACDD)
:geospatial_bounds_crs = "" ; //............................... RECOMMENDED - The coordinate reference system (CRS) of the point coordinates in the geospatial_bounds attribute. (ACDD)
:geospatial_bounds_vertical_crs = "" ; //...................... RECOMMENDED - The vertical coordinate reference system (CRS) for the Z axis of the point coordinates in the geospatial_bounds attribute. (ACDD)
:geospatial_lat_min = 0.0d ; //................................ RECOMMENDED - Describes a simple lower latitude limit. (ACDD)
:geospatial_lat_max = 0.0d ; //................................ RECOMMENDED - Describes a simple upper latitude limit. (ACDD)
:geospatial_lon_min = 0.0d ; //................................ RECOMMENDED - Describes a simple lower longitude limit. (ACDD)
:geospatial_lon_max = 0.0d ; //................................ RECOMMENDED - Describes a simple upper longitude limit. (ACDD)
:geospatial_vertical_min = 0.0d ; //........................... RECOMMENDED - Describes the numerically smaller vertical limit. (ACDD)
:geospatial_vertical_max = 0.0d ; //........................... RECOMMENDED - Describes the numerically larger vertical limit. (ACDD)
:geospatial_vertical_positive = "" ; //........................ RECOMMENDED - Use "up" or "down". (ACDD)
:time_coverage_start = "" ; //................................. RECOMMENDED - Describes the time of the first data point in the data set. Use ISO 8601:2004 for date and time. (ACDD)
:time_coverage_end = "" ; //................................... RECOMMENDED - Describes the time of the last data point in the data set. Use ISO 8601:2004 for date and time.(ACDD)
:time_coverage_duration = "" ; //.............................. RECOMMENDED - Describes the duration of the data set. Use ISO 8601:2004 for date and time. (ACDD)
:time_coverage_resolution = "" ; //............................ RECOMMENDED - Describes the targeted time period between each value in the data set. Use ISO 8601:2004 for date and time. (ACDD)
:uuid = "" ; //................................................ RECOMMENDED - Machine readable unique identifier for each file. A new uuid is created whenever the file is changed. (NCEI)
:sea_name = "" ; //............................................ RECOMMENDED - The names of the sea in which the data were collected. Use NCEI sea names table. (NCEI)
'''
recommended_ctx = TestCtx(BaseCheck.MEDIUM, 'Recommended global attributes')
sea_names = [sn.lower() for sn in util.get_sea_names()]
sea_name = getattr(dataset, 'sea_name', '')
sea_name = sea_name.replace(', ', ',')
sea_name = sea_name.split(',') if sea_name else []
for sea in sea_name:
recommended_ctx.assert_true(
sea.lower() in sea_names,
'sea_name attribute should exist and should be from the NODC sea names list: {} is not a valid sea name'.format(sea)
)
# Parse dates, check for ISO 8601
for attr in ['time_coverage_start', 'time_coverage_end', 'date_created', 'date_modified']:
attr_value = getattr(dataset, attr, '')
try:
parse_datetime(attr_value)
recommended_ctx.assert_true(True, '') # Score it True!
except ISO8601Error:
recommended_ctx.assert_true(False, '{} should exist and be ISO-8601 format (example: PT1M30S), currently: {}'.format(attr, attr_value))
value = getattr(dataset, 'geospatial_vertical_positive', '')
recommended_ctx.assert_true(value.lower() in ['up', 'down'], 'geospatial_vertical_positive attribute should be up or down: {}'.format(value))
# I hate english.
ack_exists = any((getattr(dataset, attr, '') != '' for attr in ['acknowledgment', 'acknowledgement']))
recommended_ctx.assert_true(ack_exists, 'acknowledgement attribute should exist and not be empty')
standard_name_vocab = getattr(dataset, 'standard_name_vocabulary', '')
regex = re.compile(r'[sS]tandard [nN]ame [tT]able')
recommended_ctx.assert_true(regex.search(standard_name_vocab),
"standard_name_vocabulary doesn't contain 'Standard Name Table': {}".format(standard_name_vocab))
if hasattr(dataset, 'comment'):
recommended_ctx.assert_true(getattr(dataset, 'comment', '') != '', 'comment attribute should not be empty if specified')
return recommended_ctx.to_result() |
Subsets and Splits